content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Why glob is not getting files in subfolders
I have following directory structure
$ find
.
./file1.html
./soquest_glob.py
./dir1
./dir1/file2.html
./dir2
./dir2/file3.html
(I have added blank lines above to clarify files in different folders).
I am trying to find all html files (including those in subfolders) wi... | Why glob is not getting files in subfolders | I have following directory structure
$ find
.
./file1.html
./soquest_glob.py
./dir1
./dir1/file2.html
./dir2
./dir2/file3.html
(I have added blank lines above to clarify files in different folders).
I am trying to find all html files (including those in subfolders) with following Python code using glob package:
$ ca... | [
"The recursive argument to glob.glob effects the behavior of **. You need to use a pattern like: glob.glob(\"**/*.html\", recursive=True).\n"
] | [
2
] | [] | [] | [
"directory",
"file",
"python"
] | stackoverflow_0074128637_directory_file_python.txt |
Q:
encryption and decryption with ASCII values
Im trying to write a program that encrypts and decrypts with ASCII values. The code I have currently only outputs the first letter of the string. The code below only shos the encryption and decryption functions
#define the encryption
def encrypt(text,shift):
en=""
f... | encryption and decryption with ASCII values | Im trying to write a program that encrypts and decrypts with ASCII values. The code I have currently only outputs the first letter of the string. The code below only shos the encryption and decryption functions
#define the encryption
def encrypt(text,shift):
en=""
for i in text:
if(ord(i))>=65 and (ord(i)<=9... | [
"Currently your first function, encrypt, is set to return only the final value of en, you need to de-indent your return to your for loop level to return the full string.\n"
] | [
0
] | [] | [] | [
"ascii",
"encryption",
"python"
] | stackoverflow_0074128437_ascii_encryption_python.txt |
Q:
Discretize only a certain arrrays in a tensor with TensorFlow
I have the following array:-
import numpy as np
import tensorflow as tf
input = np.array([[-1.5, 1.0, 3.4, .5], [0.0, 3.0, 1.3, 0.0]])
layer = tf.keras.layers.Discretization(num_bins=2, epsilon=0.01)
layer.adapt(input)
layer(input)
<tf.Tensor: shape=(2... | Discretize only a certain arrrays in a tensor with TensorFlow | I have the following array:-
import numpy as np
import tensorflow as tf
input = np.array([[-1.5, 1.0, 3.4, .5], [0.0, 3.0, 1.3, 0.0]])
layer = tf.keras.layers.Discretization(num_bins=2, epsilon=0.01)
layer.adapt(input)
layer(input)
<tf.Tensor: shape=(2, 4), dtype=int64, numpy=
array([[0, 1, 1, 1],
[0, 1, 1, 0]]... | [
"We can create a mask based on the index of the array that needs to be discretized:\ndef get_mask(x, array_index): \n x = tf.Variable(tf.ones_like(input, dtype=tf.float32))\n indices = tf.Variable(array_index, dtype=tf.int32)\n updates = tf.Variable(tf.zeros( (indices.shape[0], x.shape[1])), dtype=tf.float... | [
1
] | [] | [] | [
"python",
"tensorflow",
"tensorflow2.0"
] | stackoverflow_0074111551_python_tensorflow_tensorflow2.0.txt |
Q:
Check if random variables are independent Python
Given a table below
X
Y
pr
0
1
0.30
0
2
0.25
1
1
0.15
1
2
0.30
I intended to create a function to check the independence between the two variables X and Y. Note that the third column pr in the table is probability. For example P(X=0 ^ Y=1) = 0.3. Similarly, P(... | Check if random variables are independent Python | Given a table below
X
Y
pr
0
1
0.30
0
2
0.25
1
1
0.15
1
2
0.30
I intended to create a function to check the independence between the two variables X and Y. Note that the third column pr in the table is probability. For example P(X=0 ^ Y=1) = 0.3. Similarly, P(Y=1) = 0.3+0.15 = 0.45.
Two random variabl... | [
"The marginal probabilities can be gotten easily though groupby:\n>>> distr_table.groupby('Y')['pr'].sum()\nY\n0 0.45\n1 0.55\nName: pr, dtype: float64\n>>> distr_table.groupby('X')['pr'].sum()\nX\n0 0.55\n1 0.45\nName: pr, dtype: float64\n\nSo from here we can easilty reconstitute the independent proba... | [
5,
1
] | [] | [] | [
"pandas",
"probability",
"python"
] | stackoverflow_0068844193_pandas_probability_python.txt |
Q:
Get Open street map image of an area by longitude and latitude, with highlight on specific latitude and longitude
So I am trying to get open street map image by latitude and longitude with specific latitude and longitude highlighted on that image. Something like this
The above image I got from using the mesa geo ... | Get Open street map image of an area by longitude and latitude, with highlight on specific latitude and longitude | So I am trying to get open street map image by latitude and longitude with specific latitude and longitude highlighted on that image. Something like this
The above image I got from using the mesa geo agent based model (Mesa geo github).
I have been looking online to figure out how to do this and I found this Slippy Ma... | [
"Plotly is my go to for any kind of figure. If you haven't installed it yet, go here.\nAssuming you already have a list of coordinates, colors assigned based on some category, and that you're interested in points in and around Columbus, OH.\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\nimp... | [
1
] | [] | [] | [
"geomesa",
"image",
"openstreetmap",
"python"
] | stackoverflow_0074118490_geomesa_image_openstreetmap_python.txt |
Q:
passing array list to python argument
trying to pass an array list of ec2 instance ids to my python script
#!/usr/bin/env python3
import boto3
import sys
import argparse
instance_id = list(sys.argv[1])
#aws_region = sys.argv[2]
tagname = sys.argv[2]
tagvalue = sys.argv[3]
EC2_RESOURCE = boto3.resource('ec2', reg... | passing array list to python argument | trying to pass an array list of ec2 instance ids to my python script
#!/usr/bin/env python3
import boto3
import sys
import argparse
instance_id = list(sys.argv[1])
#aws_region = sys.argv[2]
tagname = sys.argv[2]
tagvalue = sys.argv[3]
EC2_RESOURCE = boto3.resource('ec2', region_name='us-west-1')
def tag_instance(ins... | [
"Looking at the error, the comma at the end of the instance name strikes me. I assume, you make some incorrect assumptions on how the command line is parsed.\nTry the following. Change the following lines in your script:\ninstance_ids = sys.argv[1].split(\",\")\n\nand\ninstances = EC2_RESOURCE.instances.filter(Inst... | [
0
] | [] | [] | [
"boto3",
"python"
] | stackoverflow_0074111506_boto3_python.txt |
Q:
gridwidth is not the same for all gridlines
I am facing a problem with the gridwidth not the same for all grid lines. The thickest lines vary when you zoom-in and zoom-out. I need to make all grid lines have the same width.
Thank you for your help.
import plotly.express as px
df = px.data.iris()
fig = px.scatter(... | gridwidth is not the same for all gridlines | I am facing a problem with the gridwidth not the same for all grid lines. The thickest lines vary when you zoom-in and zoom-out. I need to make all grid lines have the same width.
Thank you for your help.
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col=... | [
"It is totally a problem of rendering. You might have this problem becuase you are using Jupyter notebook as me. It can be solved with two options:\n\nChange the default rendering which is notebook to svg or browser. You should simply use:\nfig.show(renderer=\"browser\")\n\n\n\nSecond option is to increase the valu... | [
0
] | [] | [] | [
"plotly",
"plotly_python",
"python"
] | stackoverflow_0071819086_plotly_plotly_python_python.txt |
Q:
Docker Swarm and FastAPI with Traefik
I can't seem to bring up the FastAPI with the following docker-compose.yml script in docker swarm. I am trying to launch FastAPI using Traefik as a proxy. I can go into the container and curl localhost and get the response but not on the web. All of my other sites are up.``
He... | Docker Swarm and FastAPI with Traefik | I can't seem to bring up the FastAPI with the following docker-compose.yml script in docker swarm. I am trying to launch FastAPI using Traefik as a proxy. I can go into the container and curl localhost and get the response but not on the web. All of my other sites are up.``
Here is my docker-compose.yml file
version: '... | [
"I also struggled trying to make the code from FastAPI run and gave up.\nInstead I found this website showing an example that runs. Maybe it can help you find the issue:\nhttps://blog.creekorful.org/2019/10/how-to-install-traefik-2-docker-swarm/\n"
] | [
0
] | [] | [] | [
"docker",
"docker_swarm",
"fastapi",
"python",
"traefik"
] | stackoverflow_0073651291_docker_docker_swarm_fastapi_python_traefik.txt |
Q:
Convert one column csv into Dictionary with same key:value pair in python 2.7 (using import csv)
I have one CSV file as sample.csv which contains
ABC
XYZ
LMN
...
And from this file, I have to make a dictionary like below
Dict = {'ABC':'ABC','XYZ':'XYZ','LMN':'LMN',...}
using import csv
A:
You can do the fol... | Convert one column csv into Dictionary with same key:value pair in python 2.7 (using import csv) | I have one CSV file as sample.csv which contains
ABC
XYZ
LMN
...
And from this file, I have to make a dictionary like below
Dict = {'ABC':'ABC','XYZ':'XYZ','LMN':'LMN',...}
using import csv
| [
"You can do the following:\nimport csv\n\ndict = {}\nwith open(\"sample.csv\") as csv_file:\n csv_reader = csv.reader(csv_file)\n for row in csv_reader:\n # I'm assuming you can use all content in a single cell as a key\n key_str = \" \".join(row)\n dict[key_str] = key_str\n\nThe \"trick\... | [
0
] | [] | [] | [
"dictionary",
"python",
"python_2.7",
"python_2.x",
"read.csv"
] | stackoverflow_0074128746_dictionary_python_python_2.7_python_2.x_read.csv.txt |
Q:
error when creating a new environment, UnavailableInvalidChannel: The channel is not accessible or is invalid
I am trying to create a new environment from yml file and it is not successful. Not sure what is the problem? Can anyone give me a hand? Thanks
(base) U:\Data>conda env create -f dash_env.yml
Collecting p... | error when creating a new environment, UnavailableInvalidChannel: The channel is not accessible or is invalid | I am trying to create a new environment from yml file and it is not successful. Not sure what is the problem? Can anyone give me a hand? Thanks
(base) U:\Data>conda env create -f dash_env.yml
Collecting package metadata (repodata.json): failed
(base) U:\Data>conda env create -f dash_env.yml
Collecting package metadat... | [
"It looks like you are using the Team (Enterprise) edition of Anaconda - this means that you are using a restricted or on premises server which will have channels other than the public ones. In this case it looks like the plotly channel is not included in your permitted or hosted list.\nYou can do one of:\n\nSearch... | [
1
] | [] | [] | [
"anaconda",
"python"
] | stackoverflow_0074128690_anaconda_python.txt |
Q:
Delete SQL Table Row Where Column Value Matches Pandas Dataframe Column Value
I am trying to delete rows in a SQL table that have a matching column value in my pandas dataframe. This is the code I have so far. It only works on some of the data for some reason. I keep getting the error listed below. What is the... | Delete SQL Table Row Where Column Value Matches Pandas Dataframe Column Value | I am trying to delete rows in a SQL table that have a matching column value in my pandas dataframe. This is the code I have so far. It only works on some of the data for some reason. I keep getting the error listed below. What is the best way to do this?
import sqlalchemy
from sqlalchemy import create_engine
from s... | [
"This post is a bit old. Nevertheless, I will share my solution so it might help others.\nI had a similar problem and ended up creating the follow function:\ndef execute_query(query: str, is_fw=False, conexion_ar=con_db_AR, conexion_fw=\"con_db_FW\"):\n\"\"\"\n\nParameters:\n query(str): Text with the query\n ... | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0058018877_python_sqlalchemy.txt |
Q:
getting and setting mac file and folder finder labels from Python
I have been trying to find out how to get and set the colour of file labels from python.
The closest thing I've found to a solution was this, but I can't seem to find the module macfile anywhere. Am I just not looking hard enough?
Is there a differ... | getting and setting mac file and folder finder labels from Python | I have been trying to find out how to get and set the colour of file labels from python.
The closest thing I've found to a solution was this, but I can't seem to find the module macfile anywhere. Am I just not looking hard enough?
Is there a different way to achieve this if not?
| [
"You can do this in python using the xattr module.\nHere is an example, taken mostly from this question:\nfrom xattr import xattr\n\ncolornames = {\n 0: 'none',\n 1: 'gray',\n 2: 'green',\n 3: 'purple',\n 4: 'blue',\n 5: 'yellow',\n 6: 'red',\n 7: 'orange',\n}\n\nattrs = xattr('./test.cpp')\... | [
14,
5,
3,
0,
0
] | [] | [] | [
"finder",
"macos",
"python"
] | stackoverflow_0008328493_finder_macos_python.txt |
Q:
How do i group product data with multiple of the same products per store
I'm building a pyhon price tracker which allows me to enter some urls. The program then fetches their prices once each day and adds it to the csv file below.
I'm now looking for a way to show the price evolution of each product with a line ch... | How do i group product data with multiple of the same products per store | I'm building a pyhon price tracker which allows me to enter some urls. The program then fetches their prices once each day and adds it to the csv file below.
I'm now looking for a way to show the price evolution of each product with a line chart but cannot find a way to get something like this below where i have prices... | [
"I think you need itertools.groupby and some string handling like this\ntext = \"\"\"Samsung Galaxy Tab So lite, 2022-10-17, coolblue, 501.99 \nSamsung Galaxy Tab S7 FE, 2022-10-17, coolblue, 589.00 \nSamsung Galaxy Tab S7 FE, 2022-10-17, bol, 596.99 \nRaspberry Pi 4 8 GB, 2022-10-17, alternate, 129.90 \nSamsung Ga... | [
1,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074128787_csv_python.txt |
Q:
Im unable to get these lines running smoothly in pygame
im trying it add some lines into my pygame window but the second i want to add a second line it messes up and stops responding. I have tried adding a clock but that hasn't seemed to work.
This is the code:
import pygame
pygame.init()
w = 800
h = 800
dis = py... | Im unable to get these lines running smoothly in pygame | im trying it add some lines into my pygame window but the second i want to add a second line it messes up and stops responding. I have tried adding a clock but that hasn't seemed to work.
This is the code:
import pygame
pygame.init()
w = 800
h = 800
dis = pygame.display.set_mode((w, h))
pygame.display.update()
pygame.... | [
"You have to remove the inner while-loops. The typical PyGame application loop has to:h\n\nlimit the frames per second to limit CPU usage with pygame.time.Clock.tick\nhandle the events by calling either pygame.event.pump() or pygame.event.get().\nupdate the game states and positions of objects dependent on the inpu... | [
2
] | [] | [] | [
"pygame",
"python",
"python_3.x"
] | stackoverflow_0074129038_pygame_python_python_3.x.txt |
Q:
Sorting dataframe by multiple changing values
I have a DataFrame that is the result of a large SQL query. I am trying to sort the DataFrame into 2 separate DataFrames. NVI and Main. They are both a list of repairs to trucks. I need to sort it based on if there is a specific profile id which is 7055. Which will go ... | Sorting dataframe by multiple changing values | I have a DataFrame that is the result of a large SQL query. I am trying to sort the DataFrame into 2 separate DataFrames. NVI and Main. They are both a list of repairs to trucks. I need to sort it based on if there is a specific profile id which is 7055. Which will go into the NVI DataFrame
If that job is encountered I... | [
"From what i understand of your question, you want to divide a dataframe into 2 based on certain conditions?\ndf1 = df[<condition>]\n\ncondition can be - df[profile id] == 7055 and Allunits.contains(df[unit])\n",
"I think this might work, unable to test without the test data though...\ndf1 = nvisort[nvisort['prof... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074128399_dataframe_pandas_python.txt |
Q:
Input that takes one , 2 or none
I would like to know how to write an input that can take one, 2 or none arguments.
x , y = input().split() # this is the normal way but it always asks for 2 arguments.
If a user enters only a single number, the program should print the same number. If a user enters an empty line, t... | Input that takes one , 2 or none | I would like to know how to write an input that can take one, 2 or none arguments.
x , y = input().split() # this is the normal way but it always asks for 2 arguments.
If a user enters only a single number, the program should print the same number. If a user enters an empty line, the program should ignore it.
I cannot ... | [
"str.split returns a list and you're unpacking them into x and y. Just store the result in a single list variable and check the size for the number of elements:\n>>> vals = 'one two'.split()\n>>> len(vals)\n2\n\n>>> vals[0]\n'one'\n\n>>> len(''.split())\n0\n\n>>> help(str.split)\nHelp on method_descriptor:\n\nsplit... | [
1
] | [] | [] | [
"input",
"python"
] | stackoverflow_0074129015_input_python.txt |
Q:
Add delay between two messages in Microsoft BOT Framework (Python)
I try to get delay between two messages from bot side.
await turn_context.send_activity(f"text1")
sleep(2)
await turn_context.send_activity(f"text2")
I tried different options but most works like after my respond to bot first runs sleep command an... | Add delay between two messages in Microsoft BOT Framework (Python) | I try to get delay between two messages from bot side.
await turn_context.send_activity(f"text1")
sleep(2)
await turn_context.send_activity(f"text2")
I tried different options but most works like after my respond to bot first runs sleep command and only after I receive text1 & text2 without delay.
How it could be solv... | [
"I have used the below sample code to print the message delay by 4 seconds by using the await asyncio.sleep(4) function with python version 3.7.*\nsample code:\nimport asyncio\n\nasync def main():\nprint('message1 ...')\nawait asyncio.sleep(2)\nprint('... message2!')\n\n# Python 3.7+\nasyncio.run(main())\n\nOutpu... | [
1
] | [] | [] | [
"azure",
"azure_bot_service",
"python",
"python_3.x"
] | stackoverflow_0074126909_azure_azure_bot_service_python_python_3.x.txt |
Q:
How to make attribute in dataclass read-only?
Let's say I have a class like this:
class C:
def __init__(self, stuff: int):
self._stuff = stuff
@property
def stuff(self) -> int:
return self._stuff
then stuff is read-only:
c = C(stuff=10)
print(c.stuff) # prints 10
and
c.stuff = 2
... | How to make attribute in dataclass read-only? | Let's say I have a class like this:
class C:
def __init__(self, stuff: int):
self._stuff = stuff
@property
def stuff(self) -> int:
return self._stuff
then stuff is read-only:
c = C(stuff=10)
print(c.stuff) # prints 10
and
c.stuff = 2
fails as expected
AttributeError: can't set attri... | [
"To get the boilerplate reduction that dataclass provides I found the only way to do this is with a descriptor.\nIn [236]: from dataclasses import dataclass, field\nIn [237]: class SetOnce:\n ...: def __init__(self):\n ...: self.block_set = False\n ...: def __set_name__(self, owner, attr... | [
3,
3,
2,
1,
1,
1
] | [] | [] | [
"python",
"python_3.x",
"python_dataclasses"
] | stackoverflow_0061237131_python_python_3.x_python_dataclasses.txt |
Q:
how to use numpy functions with groupby?
I have a function that takes a dataframe column and returns a boolean mask based on certain conditions:
def is_downtrending(close):
out = np.full(close.shape, False)
for i in range(close.shape[0]):
# if we've had two consecutive red days
if (close[i... | how to use numpy functions with groupby? | I have a function that takes a dataframe column and returns a boolean mask based on certain conditions:
def is_downtrending(close):
out = np.full(close.shape, False)
for i in range(close.shape[0]):
# if we've had two consecutive red days
if (close[i] < close[i - 1]) and (close[i - 1] < close[i ... | [
"You can try with groupby.transform and update Series[idx] to Series.iloc[idx]\ndef is_downtrending(close):\n out = np.full(close.shape, False)\n\n for i in range(close.shape[0]):\n # if we've had two consecutive red days\n if (close.iloc[i] < close.iloc[i - 1]) and (close.iloc[i - 1] < close.il... | [
1,
1
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074128737_dataframe_numpy_pandas_python.txt |
Q:
Catch FileNotFoundError and continue reading files
I am performing file operations using pathlib, more or less like this:
for path in Path.cwd().glob("*.ipynb"):
print(path)
The problem is that these files are on an external drive that tends to disconnect randomly. As a result the glob iterator throws a FileN... | Catch FileNotFoundError and continue reading files | I am performing file operations using pathlib, more or less like this:
for path in Path.cwd().glob("*.ipynb"):
print(path)
The problem is that these files are on an external drive that tends to disconnect randomly. As a result the glob iterator throws a FileNotFoundError. This is a mockup of what is happening:
def... | [
"I think this not possible: When a generator throws an exception, it exits and you cannot continue consuming items it generates.\nSince you don't handle the exception anyway, you probably can check the file right before reading to avoid FileNotFoundError:\nfrom pathlib import Path\n\nmy_file = Path('/path/to/file')... | [
1,
0
] | [] | [] | [
"pathlib",
"python"
] | stackoverflow_0074124836_pathlib_python.txt |
Q:
place the symbol
to add certain symbol after every three got splited lines Something like that?? -
print('@'.join(st_text[i:i + 3] for i in range(0, len(st_tex), 3)))
A:
This code looks if there are three or more commas in the text. If it is, it splits the text into 4 parts, then concats the 3 first parts and ad... | place the symbol | to add certain symbol after every three got splited lines Something like that?? -
print('@'.join(st_text[i:i + 3] for i in range(0, len(st_tex), 3)))
| [
"This code looks if there are three or more commas in the text. If it is, it splits the text into 4 parts, then concats the 3 first parts and adds an @ before the third comma and redo the same process with the remaining text (4th part):\ntext = \"Reading practice to help you understand simple texts and find specifi... | [
0,
0
] | [] | [] | [
"numbers",
"python",
"text_manipulation"
] | stackoverflow_0074128931_numbers_python_text_manipulation.txt |
Q:
Get fully qualified class name of an object in Python
For logging purposes I want to retrieve the fully qualified class name of a Python object. (With fully qualified I mean the class name including the package and module name.)
I know about x.__class__.__name__, but is there a simple method to get the package and... | Get fully qualified class name of an object in Python | For logging purposes I want to retrieve the fully qualified class name of a Python object. (With fully qualified I mean the class name including the package and module name.)
I know about x.__class__.__name__, but is there a simple method to get the package and module?
| [
"With the following program\n#!/usr/bin/env python\n\nimport foo\n\ndef fullname(o):\n klass = o.__class__\n module = klass.__module__\n if module == 'builtins':\n return klass.__qualname__ # avoid outputs like 'builtins.str'\n return module + '.' + klass.__qualname__\n\nbar = foo.Bar()\nprint(fu... | [
197,
55,
28,
22,
20,
11,
10,
7,
2,
2,
1,
0,
0
] | [] | [] | [
"python",
"python_datamodel"
] | stackoverflow_0002020014_python_python_datamodel.txt |
Q:
How to clear input after clicking in button submit in Dash?
I'm trying to clear a dcc.input` in dash after clicking and returning the results with a submit button and I can't do it. I don't know what I'm doing wrong can you please help?
I already read this links:
https://community.plotly.com/t/how-to-reset-the-n-... | How to clear input after clicking in button submit in Dash? | I'm trying to clear a dcc.input` in dash after clicking and returning the results with a submit button and I can't do it. I don't know what I'm doing wrong can you please help?
I already read this links:
https://community.plotly.com/t/how-to-reset-the-n-clicks-of-a-button-and-value-of-the-input-text-box-after-the-ever... | [
"You just need to add a second Output to your callback like this:\nOutput('requester', 'value')\nand have your callback return another value, and make it an empty string. Here's an example:\nreturn [n_clicks, requester], ''\n",
"coralvanda's answer is correct. I'm commenting simply to add some info.\nIf you have ... | [
1,
1
] | [] | [] | [
"plotly_dash",
"python"
] | stackoverflow_0072351437_plotly_dash_python.txt |
Q:
Convert Pandas Columns to Decimal128
I am trying to get data prepped to be uploaded to MongoDB. From experiments on another day, I learned that I need to convert float values to Decimal128 before sending it up to a MongoDB collection. I am finding posts for the inverse of what I am trying to do.
My code is working... | Convert Pandas Columns to Decimal128 | I am trying to get data prepped to be uploaded to MongoDB. From experiments on another day, I learned that I need to convert float values to Decimal128 before sending it up to a MongoDB collection. I am finding posts for the inverse of what I am trying to do.
My code is working. But because I am working with so much da... | [
"here is one way to do it\n# use applymap to apply lambda for the selected columns\n# check if the value has only digits comma and decimal point\n# when true, remove the comma\n# when false, return as is\n\ndf[dec_cols]=(df[dec_cols] \n .applymap(lambda x : Decimal128(re.sub(r',','', str(x))) \n ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074116276_pandas_python.txt |
Q:
Python read file line by line and multiply
I have a text file that is similar to this:
line 1: a b c,
line 2: d e f,
line 3: g h i
I need to write a python code that reads the file and print the first value of each line and multiply the last two to something like this:
line 1: a, bc
line 2: d, ef
line 3: g, hi
... | Python read file line by line and multiply | I have a text file that is similar to this:
line 1: a b c,
line 2: d e f,
line 3: g h i
I need to write a python code that reads the file and print the first value of each line and multiply the last two to something like this:
line 1: a, bc
line 2: d, ef
line 3: g, hi
Please help anyone
EDIT: a, d and g are non nume... | [
"An alternative:\nwith open(filename) as file: # Opens the file\n for line in file: # Loops through each line in file.\n line = line.rstrip() # Removes any spaces in the right.\n a, b, c = line.split(\" \") # Split based on spaces\n print(a +... | [
0,
-2
] | [] | [] | [
"python"
] | stackoverflow_0074129189_python.txt |
Q:
WinError 5, When importing openpyxl
I am trying to import openpyxl in order to start learning it, however whenever I try to import it it spits out this
Traceback (most recent call last):
File "D:\Py\test.py", line 3, in <module>
import openpyxl
File "C:\Users\[my_username]\AppData\Local\Programs\Python\Pyt... | WinError 5, When importing openpyxl | I am trying to import openpyxl in order to start learning it, however whenever I try to import it it spits out this
Traceback (most recent call last):
File "D:\Py\test.py", line 3, in <module>
import openpyxl
File "C:\Users\[my_username]\AppData\Local\Programs\Python\Python310\lib\site-packages\openpyxl\__init_... | [
"Maybe reinstalling package will work in your case.\npip uninstall openpyxl\npip install openpyxl\n\n"
] | [
0
] | [] | [] | [
"openpyxl",
"python"
] | stackoverflow_0074129176_openpyxl_python.txt |
Q:
One-hot-encoding multiple columns in sklearn and naming columns
I have the following code to one-hot-encode 2 columns I have.
# encode city labels using one-hot encoding scheme
city_ohe = OneHotEncoder(categories='auto')
city_feature_arr = city_ohe.fit_transform(df[['city']]).toarray()
city_feature_labels = city_o... | One-hot-encoding multiple columns in sklearn and naming columns | I have the following code to one-hot-encode 2 columns I have.
# encode city labels using one-hot encoding scheme
city_ohe = OneHotEncoder(categories='auto')
city_feature_arr = city_ohe.fit_transform(df[['city']]).toarray()
city_feature_labels = city_ohe.categories_
city_features = pd.DataFrame(city_feature_arr, columns... | [
"You you are almost there... Like you said you can add all the columns you want to encode in fit_transform directly.\nohe = OneHotEncoder(categories='auto')\nfeature_arr = ohe.fit_transform(df[['phone','city']]).toarray()\nfeature_labels = ohe.categories_\n\nAnd then you just need to do the following:\nfeature_labe... | [
12,
1,
1,
0
] | [] | [] | [
"one_hot_encoding",
"pandas",
"python",
"python_3.x",
"scikit_learn"
] | stackoverflow_0055229301_one_hot_encoding_pandas_python_python_3.x_scikit_learn.txt |
Q:
What are the possible values for the "geo" parameter of pytrends.dailydata.get_daily_data()?
I'm trying to get the dailydata of Google Trend through the method: pytrends.dailydata.get_daily_data().
The link here just tells me the default value of the geo parameter is "US". I'd like to know where I can find a whole... | What are the possible values for the "geo" parameter of pytrends.dailydata.get_daily_data()? | I'm trying to get the dailydata of Google Trend through the method: pytrends.dailydata.get_daily_data().
The link here just tells me the default value of the geo parameter is "US". I'd like to know where I can find a whole list of possible values. I have tried "GLOBAL", but got an error.
My code is as follow:
from pytr... | [
"I think for global you have to pass an empty string:\n df = dailydata.get_daily_data('cinema', 2019, 1, 2019, 6, geo='')\n\nI think google uses ISO 3166 for location.\nIn that list you can also find regions if you click on the countries, for example if you want trends in US Alabama, you can use the geo code US-AL.... | [
1
] | [] | [] | [
"google_trends",
"python"
] | stackoverflow_0074129044_google_trends_python.txt |
Q:
Python/Selenium fails when script is run through cron, but is fine when script run manually
Running a Python script using Selenium on a Raspberry Pi 4 running Ubuntu Server 22.04. Chromium Browser Chromedriver V 103.0.5060.53 (the current stable via https://chromedriver.chromium.org/)
When I run the script in the ... | Python/Selenium fails when script is run through cron, but is fine when script run manually | Running a Python script using Selenium on a Raspberry Pi 4 running Ubuntu Server 22.04. Chromium Browser Chromedriver V 103.0.5060.53 (the current stable via https://chromedriver.chromium.org/)
When I run the script in the terminal, everything works as expected, however when the script executes via a cron job, the scri... | [
"I'm having this same issue. What I have found is that if I update CRONTAB then the next run will be successful, however subsequent runs will fail with status = 1.\nTherefore I created a script to auto update the time that my cron job would run, its hacky but it helps.\nimport subprocess # needed for the subprocess... | [
0
] | [] | [] | [
"cron",
"python",
"selenium"
] | stackoverflow_0073013230_cron_python_selenium.txt |
Q:
How can I separate a list?
I have a list that contains a bunch of different list. ex. list = [['Hello world', '123', 'TGG'"], ["'Apple'", '321', 'EDF']]. When I print list[0], it prints out ['Hello world', '123', 'TGG'"], but I just want it to print out Hello world. How can I access this data?
import sys, csv
new... | How can I separate a list? | I have a list that contains a bunch of different list. ex. list = [['Hello world', '123', 'TGG'"], ["'Apple'", '321', 'EDF']]. When I print list[0], it prints out ['Hello world', '123', 'TGG'"], but I just want it to print out Hello world. How can I access this data?
import sys, csv
new_book = list()
result = []
new_r... | [
"You could access the first element in the nested list by using another set of brackets\nprint(new_result[0][0])\n\n",
"Adding on to Anthony's answer, if you wish to slice out some elements from a list of lists, a convenient way is to use list comprehension:\n # Suppose we have a list of lists L as follows\n ... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0074128483_python.txt |
Q:
I am trying to run a standalone Django script but i keep getting this error: ModuleNotFoundError: No module named 'django'
import os
import django
import sys
import csv
from collections import defaultdict
sys.path.append('/Users/apple/Documents/COMPUTER-SCIENCE/ADV-WEB-DEV/Topic-files/topic2')
os.environ.setdefaul... | I am trying to run a standalone Django script but i keep getting this error: ModuleNotFoundError: No module named 'django' | import os
import django
import sys
import csv
from collections import defaultdict
sys.path.append('/Users/apple/Documents/COMPUTER-SCIENCE/ADV-WEB-DEV/Topic-files/topic2')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bioweb.settings')
django.setup()
Error:
import django
ModuleNotFoundError: No module named 'django'... | [
"go to your project root directory and run:\npython manage.py shell < [path to your script]\n\"path to your script\" means the route to your script something like this:\n/Users/apple/Documents/COMPUTER-SCIENCE/ADV-WEB-DEV/scripts/my_script.py\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074129361_django_python.txt |
Q:
Optimizing 3x nested loop to avoid MemoryError working with big datasets
I need your help to rewrite this so that I wont get memory error.
I have two dataframes containing laptops/pc's with their config.
DataFrame one called df_original:
processorName
GraphicsCardname
ProcessorBrand
5950x
Rtx 3060 ti
i7
3600
... | Optimizing 3x nested loop to avoid MemoryError working with big datasets | I need your help to rewrite this so that I wont get memory error.
I have two dataframes containing laptops/pc's with their config.
DataFrame one called df_original:
processorName
GraphicsCardname
ProcessorBrand
5950x
Rtx 3060 ti
i7
3600
Rtx 3090
i7
1165g7
Rtx 3050
i5
DataFrame two df_compare:
proc... | [
"Memory issue\nYour desired output for such big dataframes can't fit into regular pc memory.\nWith two DataFrames of ~200k rows you are calculating a 2d array (matrix) of shape 200k times 200k. That's 40 billion values - 160 GB assuming the size of the data type is 4B.\nI would suggest you reconsider the need of wh... | [
1,
1
] | [] | [] | [
"dataframe",
"for_loop",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074127935_dataframe_for_loop_pandas_python_python_3.x.txt |
Q:
How to get only one else statement for nested if/else statements inside for loop in python?
I want to get the else statement only if there is no word from the spam_word list matches the data.
A:
This was rewritten from your image, but the premise is to check your counter after the for loop.
If one hit is enough ... | How to get only one else statement for nested if/else statements inside for loop in python? |
I want to get the else statement only if there is no word from the spam_word list matches the data.
| [
"This was rewritten from your image, but the premise is to check your counter after the for loop.\nIf one hit is enough from the data, you could also \"break\" from the \"for words in data\" loop\ncount = 0\nfor word in spam_word:\n if word in data:\n print(word)\n count += 1\n\n# after the for loo... | [
2,
0
] | [] | [] | [
"if_statement",
"nested",
"python"
] | stackoverflow_0074129154_if_statement_nested_python.txt |
Q:
Google cloud logging LogEntry fields
I am new to Google cloud logging.
I use Python library and I am a little bit confused about LogEntry fields. Are these fields meant to be manipulated by developer/code? I am trying to use "operation" field to trace operation logs with the same ID, but no matter how I try to for... | Google cloud logging LogEntry fields | I am new to Google cloud logging.
I use Python library and I am a little bit confused about LogEntry fields. Are these fields meant to be manipulated by developer/code? I am trying to use "operation" field to trace operation logs with the same ID, but no matter how I try to format the log message, the operation field i... | [
"You can update the operation like below. This ensures operation comes as a top level field. The fields under log_data will always be sub fields of jsonPayload.\nfrom google.cloud import logging\nlogging_client = logging.Client()\nlogger = logging_client.logger(\"struct_log\")\n\nlog_data = {\n\"my_filed\": \"my fi... | [
0
] | [] | [] | [
"google_cloud_logging",
"logging",
"python",
"stackdriver"
] | stackoverflow_0073335045_google_cloud_logging_logging_python_stackdriver.txt |
Q:
Upload password protected file to server
I am running a Python HTTP server that host a captive portal. Basically I'm trying to upload a password protected file to the server.
Right now I am able to upload files to the server with JavaScript and FileReader. This is how I do it:
var file_cli_cert = document.getEleme... | Upload password protected file to server | I am running a Python HTTP server that host a captive portal. Basically I'm trying to upload a password protected file to the server.
Right now I am able to upload files to the server with JavaScript and FileReader. This is how I do it:
var file_cli_cert = document.getElementById(id="exa_cli_cert").files[0];
const xmlh... | [
"No python expert but reading a encrypted file as Text with FileReader could be problematic as it could lead to some data loss when encoding it as text. You should rather be reading it as binary using reader.readAsArrayBuffer()\nBut there is no need to read the content of the file into memory and allocate memory, j... | [
0
] | [] | [] | [
"javascript",
"post",
"python",
"server"
] | stackoverflow_0074125911_javascript_post_python_server.txt |
Q:
ValueError: SARIMAX models require univariate `endog`. Got shape (88, 2)
My Dataframe(train) look like this
total_mtrs total_mtrs_2
trx_date
2013-07-01 3449701.0 -1.362983
2013-08-01 3172872.0 -1.585093
2013-09-01 3137336.0 -1.613605
2013-10-01 3108550.0 -1.636701
2013-11-01 2981... | ValueError: SARIMAX models require univariate `endog`. Got shape (88, 2) | My Dataframe(train) look like this
total_mtrs total_mtrs_2
trx_date
2013-07-01 3449701.0 -1.362983
2013-08-01 3172872.0 -1.585093
2013-09-01 3137336.0 -1.613605
2013-10-01 3108550.0 -1.636701
2013-11-01 2981503.0 -1.738636
... ... ...
2020-06-01 4393613.0 -0.605648
2020-07-01 51... | [
"try using a specific column name like in your case it is,\narma_mod20 = ARIMA(train.total_mtrs, order=(0,1,0)).fit()\n"
] | [
0
] | [] | [] | [
"arima",
"dataframe",
"python",
"sarimax",
"time_series"
] | stackoverflow_0073781768_arima_dataframe_python_sarimax_time_series.txt |
Q:
python syntax question: class instantiation with its argument outside brackets
I cannot figure out what kind of python sytanx is used.
I hope someone could tell me.
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchvision.transforms as T
from torchvision.io impo... | python syntax question: class instantiation with its argument outside brackets | I cannot figure out what kind of python sytanx is used.
I hope someone could tell me.
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchvision.transforms as T
from torchvision.io import read_image
plt.rcParams["savefig.bbox"] = 'tight'
torch.manual_seed(1)
def sh... | [
"img = T.ToPILImage()(img.to('cpu'))\n\nT.ToPILImage() must return some callable object (likely a class).\nThen this object is called, with img.to('cpu') as an argument.\nIf it helps, think of the code this way:\nmyclass = T.ToPILImage()\nimg = myclass(img.to('cpu'))\n\n",
"It's not instantiating with the image o... | [
1,
1
] | [] | [] | [
"casting",
"class",
"python",
"syntax"
] | stackoverflow_0074129579_casting_class_python_syntax.txt |
Q:
Refactoring While & If loop of a code with Python?
Hi I'm learning Python by myself and I'm tying to refactor this code. I need to use declaration and invoke of the function.
So the original code is:
while True:
length = int(input("Enter the length of your room: "))
if length > 0:
break
while True... | Refactoring While & If loop of a code with Python? | Hi I'm learning Python by myself and I'm tying to refactor this code. I need to use declaration and invoke of the function.
So the original code is:
while True:
length = int(input("Enter the length of your room: "))
if length > 0:
break
while True:
width = int(input("Enter the width of your room: "... | [
"Code:\ndef volume(lenght, width, height):\n if lenght > 0 and width > 0 and height > 0:\n room_volume = lenght*width*height\n return room_volume\n return 'wrong input'\n\nroom_volume = volume(input('Length: '), input('Width: '), input('Height: '))\nprint(f'Room volume: {room_volume}')\n\nYou ca... | [
0
] | [] | [] | [
"function",
"invoke",
"python",
"python_3.x",
"refactoring"
] | stackoverflow_0074129541_function_invoke_python_python_3.x_refactoring.txt |
Q:
Unable to install Pygame using pip
I'm trying to install Pygame. I am running Windows 7 with Enthought Python Distribution. I successfully installed pip, but when I try to install Pygame using pip, I get the following error:
"Could not install requirement Pygame because of HTTP error HTTP error
400: Bad request... | Unable to install Pygame using pip | I'm trying to install Pygame. I am running Windows 7 with Enthought Python Distribution. I successfully installed pip, but when I try to install Pygame using pip, I get the following error:
"Could not install requirement Pygame because of HTTP error HTTP error
400: Bad request for URL ..."
I can't find anything abo... | [
"Steps to install PyGame using pip\n\nInstall build dependencies (on linux):\nsudo apt-get build-dep python-pygame\n\nInstall mercurial to use hg (on linux):\nsudo apt-get install mercurial\n\nOn Windows you can use the installer: Download\nUse pip to install PyGame:\npip install hg+http://bitbucket.org/pygame/pyga... | [
101,
22,
18,
10,
7,
6,
5,
5,
5,
5,
4,
3,
3,
3,
3,
3,
2,
2,
2,
2,
2,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"installation",
"pip",
"pygame",
"python"
] | stackoverflow_0017869101_installation_pip_pygame_python.txt |
Q:
python plot one bar with different color by time
Here's the dataset. How can plot it in one bar with different colors based on time?
import pandas as pd
data = pd.DataFrame({'Time (s)': ['30', '1:30', '1:45', '2:10','2:30'],
'Color': ['red','grey','purple','green','NAN']})
Time (s) Color
0 30 red
1 ... | python plot one bar with different color by time | Here's the dataset. How can plot it in one bar with different colors based on time?
import pandas as pd
data = pd.DataFrame({'Time (s)': ['30', '1:30', '1:45', '2:10','2:30'],
'Color': ['red','grey','purple','green','NAN']})
Time (s) Color
0 30 red
1 1:30 grey
2 1:45 purple
3 2:10 green
4... | [
"You can use matplotlib's broken_barh() to do this... one of the many ways. Below code will do this. Note that your first element (30) is incorrect, it should be in HH:MM format, so I changed it to 0:30.\nFirst create a datetime equivalent for each of the time format, which will help you measure the x-length for ea... | [
1
] | [] | [] | [
"colors",
"plot",
"python"
] | stackoverflow_0074127249_colors_plot_python.txt |
Q:
AWS Cognito. How to decode JWT in Python
I want to authenticate users using Cognito Identity provider (Facebook) in Django application. When user signs-in, he is redirected to home page with access_token and id_token. These are JWT tokens. I need to decode them to get information about user. How to achieve it?
I... | AWS Cognito. How to decode JWT in Python | I want to authenticate users using Cognito Identity provider (Facebook) in Django application. When user signs-in, he is redirected to home page with access_token and id_token. These are JWT tokens. I need to decode them to get information about user. How to achieve it?
I tried using jwt library. Many resources say t... | [
"Using the PyJWT library, you can decode a JWT token via:\nimport jwt\n\nencoded = token # replace this with your encoded token\njwt.decode(encoded, algorithms=[\"RS256\"], options={\"verify_signature\": False})\n\nThe options configuration will tell the PyJWT library to ignore the public-key aspect of the verific... | [
1
] | [] | [] | [
"amazon_cognito",
"decode",
"jwt",
"python"
] | stackoverflow_0055703156_amazon_cognito_decode_jwt_python.txt |
Q:
How to convert numpy decimal arrays into binary arrays?
do you know to convert this np array into a binary one?
eg
AI=np.array([15,4,6,6])
and I want to get this:
AI=([1111, 0100, 0110, 0110])
A:
As you need "to get ints for the output"
import numpy as np
AI=np.array([15,4,6,6])
out=[int(bin(i).replace("0b", "... | How to convert numpy decimal arrays into binary arrays? | do you know to convert this np array into a binary one?
eg
AI=np.array([15,4,6,6])
and I want to get this:
AI=([1111, 0100, 0110, 0110])
| [
"As you need \"to get ints for the output\"\nimport numpy as np\nAI=np.array([15,4,6,6])\n\nout=[int(bin(i).replace(\"0b\", \"\")) for i in AI]\nprint(out)\n\nOutput:\n[1111, 100, 110, 110]\n\n"
] | [
1
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074129502_arrays_numpy_python.txt |
Q:
How to calculate the sum of values in an Excel column using openpyxl?
I need to calculate the sum of values from excel column cells:
import openpyxl
book = openpyxl.open("AAB.xlsx")
wb=book
sheet = book.active
ws=sheet
column_name = 'Услуги по доставке товара покупателю'
for column_cell in ws.iter_cols(1, ws.max... | How to calculate the sum of values in an Excel column using openpyxl? | I need to calculate the sum of values from excel column cells:
import openpyxl
book = openpyxl.open("AAB.xlsx")
wb=book
sheet = book.active
ws=sheet
column_name = 'Услуги по доставке товара покупателю'
for column_cell in ws.iter_cols(1, ws.max_column): # iterate column cell
if column_cell[0].value == column_name... | [
"The sum function can be use only on an iterable like lists or tuples...\nwhile b is a float,\nindeed if you want to cumulate you must have a list of cummulable integers or floats\n"
] | [
0
] | [] | [] | [
"openpyxl",
"python"
] | stackoverflow_0074129740_openpyxl_python.txt |
Q:
Please provide support with this Class method example
class Person:
number_of_people = 0
def __init__(self,name):
self.name = name
Person.add_person()
@classmethod
def number_of_people_(cls):
return cls.number_of_people()
@classmethod
... | Please provide support with this Class method example | class Person:
number_of_people = 0
def __init__(self,name):
self.name = name
Person.add_person()
@classmethod
def number_of_people_(cls):
return cls.number_of_people()
@classmethod
def add_person(cls):
cls.number_of_people += 1
... | [
"Your TypeError is because of what you are trying to return in your classmethod:\number_of_people = 0\n\ndef number_of_people_(cls): \n return cls.number_of_people() # you are calling the attribute above which is set to 0\n\nChange to:\ndef number_of_people_(cls): \n return cls.number_of_peopl... | [
0
] | [] | [] | [
"python",
"typeerror"
] | stackoverflow_0074129721_python_typeerror.txt |
Q:
How to use loop to do different filters columns df combinations
I have a DataFrame like this:
I have this function:
def df_filter (df,col_key1,col_key2,col_key3,a,b,c):
df1 = df[(df[col_key1]==a) & (df[col_key2]==b) & (df[col_key3]==c)
df1 = df1.groupby(by=['ID'])['satisfaction'].mean()
return df1
resu... | How to use loop to do different filters columns df combinations | I have a DataFrame like this:
I have this function:
def df_filter (df,col_key1,col_key2,col_key3,a,b,c):
df1 = df[(df[col_key1]==a) & (df[col_key2]==b) & (df[col_key3]==c)
df1 = df1.groupby(by=['ID'])['satisfaction'].mean()
return df1
result_1 = df_filter (df,'key1','key2','key3',1,0,0)
result_2 = df_filter... | [
"Here's a minimal change that gets the job done. To get an array of results, you can add the statement from itertools import product and do\nresults = [df_filter(df,'key1','key2','key3',*tup) \n for tup in product([0,1],repeat=3)]\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074129669_dataframe_pandas_python.txt |
Q:
How to map colors in an image to a palette fast with numpy?
I have two arrays. One is an image array and the other is a palette array.
Both have elements containing 8-bit RGB channels. I need to replace every color in the image with the closest color in the palette.
Currently I'm measuring distance in the RGB-spac... | How to map colors in an image to a palette fast with numpy? | I have two arrays. One is an image array and the other is a palette array.
Both have elements containing 8-bit RGB channels. I need to replace every color in the image with the closest color in the palette.
Currently I'm measuring distance in the RGB-space, which is not ideal, but easy to implement.
This is my implemen... | [
"You can try using cKDTree function from scipy.\nimport numpy as np\nfrom scipy.spatial import cKDTree\npalette=np.random.randint(0, 255, size=(4096,3), dtype=np.uint8) # random palette\nimage_in=np.random.randint(0, 255, size=(800, 600, 3), dtype=np.uint8) # random image\nsize=image_in.shape\nvor=cKDTree(palette)\... | [
2
] | [] | [] | [
"color_mapping",
"numpy",
"performance",
"python",
"python_3.x"
] | stackoverflow_0074128822_color_mapping_numpy_performance_python_python_3.x.txt |
Q:
Python tuple duplication with *
This works just fine and straight-forward:
>>> ('a',) * 3
('a', 'a', 'a')
But I was experimenting with tuple a little and came across this:
>>> 'a', * ('b', 'c')
('a', 'b', 'c')
>>> ('a',) * ('b', 'c')
Traceback (most recent call last):
File "<pyshell#2>", line 1... | Python tuple duplication with * | This works just fine and straight-forward:
>>> ('a',) * 3
('a', 'a', 'a')
But I was experimenting with tuple a little and came across this:
>>> 'a', * ('b', 'c')
('a', 'b', 'c')
>>> ('a',) * ('b', 'c')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
('a',) * ('b', ... | [
"In this expression\n'a', * ('b', 'c')\n\nYou have two primary things going on\n\n'a', creates a tuple with a single element 'a'\n* ('b', 'c') uses extended iterable unpacking (PEP 3132)\n\nSo the result of #2 is used to continue the tuple definition from #1. To show a more intuitive example this is the same idea\n... | [
4
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0074129807_python_tuples.txt |
Q:
Why pyspark udf function only runs on one core?
Assume, I have a dataframe with only one column text. I want to write a udf function that extract multiple text spans from each row of this dataframe. I have the following function:
@F.udf(returnType=T.ArrayType(T.StringType()))
def generate_text_spans(text):
spa... | Why pyspark udf function only runs on one core? | Assume, I have a dataframe with only one column text. I want to write a udf function that extract multiple text spans from each row of this dataframe. I have the following function:
@F.udf(returnType=T.ArrayType(T.StringType()))
def generate_text_spans(text):
spans = []
# performs some processing on text and fi... | [
"Use repartitions\ndf = df.repartition(100).withColumn('spans', generate_text_spans(F.col('text')))\n\n",
"Apparently, this happens when you persist() your data and show() it. Removing these lines did the trick for me. Now all cores are being used.\n"
] | [
0,
0
] | [] | [] | [
"apache_spark",
"pyspark",
"python"
] | stackoverflow_0074101996_apache_spark_pyspark_python.txt |
Q:
Calculate the percentage by reading values between two specific columns and add percentage column
I have dataframe like this
Keyword devops aws ec2 python java dotnet
optional/mandatory optional mandatory mandatory optional optional mandatory
Candidate Name ... | Calculate the percentage by reading values between two specific columns and add percentage column | I have dataframe like this
Keyword devops aws ec2 python java dotnet
optional/mandatory optional mandatory mandatory optional optional mandatory
Candidate Name
User1 1 1 1 ... | [
"I took the liberty of reformatting your question a bit. Here's the setup:\nimport pandas as pd\n\n# Set up your indices\ncols = pd.MultiIndex.from_arrays([\n ['optional', 'mandatory', 'mandatory', 'mandatory', 'optional', 'optional'],\n ['devops', 'aws', 'ec2', 'dotnet', 'python', 'java']\n])\n\n# Set up th... | [
0,
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074116287_dataframe_numpy_pandas_python.txt |
Q:
How can user download database from django heroku?
I make a apllication in django. I want put a download button in the my aplicattion. User can download then in this button. In local host this work, but when i put in heroku don't.
listar.html:
<p>
<form method="POST">
<a href="{% url 'baixa' %}" download... | How can user download database from django heroku? | I make a apllication in django. I want put a download button in the my aplicattion. User can download then in this button. In local host this work, but when i put in heroku don't.
listar.html:
<p>
<form method="POST">
<a href="{% url 'baixa' %}" download>Download</a>
</form>
<a class="btn btn-outlin... | [
"To export the data from your Heroku Postgres database, create a new backup and download it.\nheroku pg:backups:capture --app example-app\nheroku pg:backups:download --app example-app\n\nRefer official heroku doc for more\n"
] | [
0
] | [] | [] | [
"django",
"heroku",
"postgresql",
"python"
] | stackoverflow_0074129777_django_heroku_postgresql_python.txt |
Q:
ValueError while calculating R_Square: Found array with dim 3. Estimator expected <= 2
I have trained and tested a neural network in which I have 2 variables as my dependent variables hence, in output, there are two NumPy arrays of train and test, with each NumPy array having 2 outputs.
import pandas as pd
import ... | ValueError while calculating R_Square: Found array with dim 3. Estimator expected <= 2 | I have trained and tested a neural network in which I have 2 variables as my dependent variables hence, in output, there are two NumPy arrays of train and test, with each NumPy array having 2 outputs.
import pandas as pd
import numpy as np
y_test =
array([[242.14, 61.],
[179.48, 140.54],
[ 98.16, 36.05],
.... | [
"Your y_pred array has 3 dimensions by the looks of it.\nTry removing a square bracket from the start and end...\ny_pred = \n\narray([[178.8299 ],\n [ 73.47848 ]],\n\n [[216.90152 ],\n [116.74648 ]],\n\n [[215.67923 ],\n [ 47.019424]],\n\n ...,\n\n [[236.51259 ],\n [167.34752 ]],\n\n [[156.02... | [
0
] | [] | [] | [
"numpy",
"pandas",
"python",
"scikit_learn"
] | stackoverflow_0074129908_numpy_pandas_python_scikit_learn.txt |
Q:
Python flask_mysqldb passing over 10 does't work
I'm totally new and learning Python+MySQL,
And I have an issue with passing over 10 to %s
@app.route('/usr/<id>', methods=['GET'])
def selected_logs(id):
response_object = {'status': 'success'}
cur = mysql.connection.cursor()
cur.execute('''
SELECT
... | Python flask_mysqldb passing over 10 does't work | I'm totally new and learning Python+MySQL,
And I have an issue with passing over 10 to %s
@app.route('/usr/<id>', methods=['GET'])
def selected_logs(id):
response_object = {'status': 'success'}
cur = mysql.connection.cursor()
cur.execute('''
SELECT
usr.id,
usr.corp_id,
... | [
"Execute() takes an iterable as the second argument. You need to pass an iterable of values to bind to parameters, (id) is not an iterable. It is a common mistake to think that it is a tuple but it is not, (id,) is a tuple which is an iterable.\ncur.execute('''\n SELECT\n usr.id,\n usr.corp... | [
2,
0
] | [] | [] | [
"flask_mysql",
"python",
"python_3.x"
] | stackoverflow_0074129230_flask_mysql_python_python_3.x.txt |
Q:
Spark with python script from console not working no errors
Hi I got this weird problem. I am new to spark, just installed spark and java, made the environmental variables and spark seems to work properly. I can enter the spark console form cmd and write print ect. its working.
But when I try to do bin\spark-submi... | Spark with python script from console not working no errors | Hi I got this weird problem. I am new to spark, just installed spark and java, made the environmental variables and spark seems to work properly. I can enter the spark console form cmd and write print ect. its working.
But when I try to do bin\spark-submit C:\Users\User\Desktop\Big_Data\pi.py where pi.py is just exampl... | [
"Looking at Spark's Quick Start Guide examples, can you run this command:\nbin\\spark-submit --master local C:\\Users\\User\\Desktop\\Big_Data\\pi.py\n\nMore info regarding spark-submit can be found here.\n"
] | [
0
] | [] | [] | [
"apache_spark",
"cmd",
"pyspark",
"python",
"spark_submit"
] | stackoverflow_0073772669_apache_spark_cmd_pyspark_python_spark_submit.txt |
Q:
JSONEncoder is not being called
I am trying to encode JSON with json.JSONEncoder with another pattern by overriding the default method:
class X(json.JSONEncoder):
def default(self, obj):
return ["ok"]
json.dumps(self, cls=X)
But the default method is not being called... I saw a few examples who looks... | JSONEncoder is not being called | I am trying to encode JSON with json.JSONEncoder with another pattern by overriding the default method:
class X(json.JSONEncoder):
def default(self, obj):
return ["ok"]
json.dumps(self, cls=X)
But the default method is not being called... I saw a few examples who looks like this, but I can't figure out wh... | [
"I found the problem. my object was inherited from dict, while default method is not being called on object like dict and list\n",
"Having the same kind of problem, I found the complete answer here: https://stackoverflow.com/a/46205398/12199445\nAs mentioned is earlier, if the standard JSONEncoder is able to enco... | [
3,
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0047494702_json_python.txt |
Q:
Insert value into an array within an array
So I am try to figure out how to add items to an array within a array I have. I am first using a while loop to scan barcodes into an array. Then I am the number of items I scanned and creating an individual array for each separate one.
serial_numbers = []
while True:
... | Insert value into an array within an array | So I am try to figure out how to add items to an array within a array I have. I am first using a while loop to scan barcodes into an array. Then I am the number of items I scanned and creating an individual array for each separate one.
serial_numbers = []
while True:
s = input("Scan Serial Number: ")
if s == "d... | [
"Iterate over the inventory list, and add \"Laptop\" (or whatever value you like) to each sub-list.\nfor sublist in inventory:\n sublist.append('Laptop')\n\n"
] | [
0
] | [] | [] | [
"append",
"arrays",
"python"
] | stackoverflow_0074129986_append_arrays_python.txt |
Q:
Input function is adding None
I'm trying to use the input function but every time, without fail, the word "None" appears at the end of my question/string (well running), it's capitalized just like that but has no overall effect on the code, it just ruins the project I'm working on.
Here's my code:
import time
impo... | Input function is adding None | I'm trying to use the input function but every time, without fail, the word "None" appears at the end of my question/string (well running), it's capitalized just like that but has no overall effect on the code, it just ruins the project I'm working on.
Here's my code:
import time
import sys
def dp(s):
for c in s:
... | [
"Every function in python will return something, and if that something isn't defined it will be None (you can also explicitly return None in a function). So, your dp() function returns None, and so you are effectively calling input(None), which gives the same prompt of None.\nInstead, try putting in input() call wi... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074129937_python.txt |
Q:
Catch two types of warning
So I want to catch different types of warnings on the following code:
score = cross_val_score(DecisionTreeClassifier(), X, y, scoring=f2_measure, cv=cv)
From running the code, I got two warnings:
UserWarning: The least populated class in y has only 1 members, which is less than n_splits... | Catch two types of warning | So I want to catch different types of warnings on the following code:
score = cross_val_score(DecisionTreeClassifier(), X, y, scoring=f2_measure, cv=cv)
From running the code, I got two warnings:
UserWarning: The least populated class in y has only 1 members, which is less than n_splits=2.
% (min_groups, self.n_spli... | [
"You can use two different excepts after your try. The second except will catch only the exceptions that are not caught by the first except. So you can make the first except catch the subclass UndefinedMetricWarning and then the second except can effectively catch only the UserWarning warnings that are not also an ... | [
1
] | [] | [] | [
"python",
"scikit_learn",
"warnings"
] | stackoverflow_0062421299_python_scikit_learn_warnings.txt |
Q:
ValueError: Expected input batch_size (1225) to match target batch_size (25)
I’m getting the following error. I have tried every solution but nothing working.
I'm using VGG16 architecture, batch size 25, 3 channels images with shape 224x224 and I want to classify 9 classes.
Down bellow is attached my fc layer
... | ValueError: Expected input batch_size (1225) to match target batch_size (25) | I’m getting the following error. I have tried every solution but nothing working.
I'm using VGG16 architecture, batch size 25, 3 channels images with shape 224x224 and I want to classify 9 classes.
Down bellow is attached my fc layer
self.classifier = nn.Sequential(
nn.Linear(512, 4096),
nn.ReLU(Tru... | [
"OP needed to match up the dimensionality of the samples they were calling their model on, and their labels (in other words, there should be 1 label per datapoint).\n"
] | [
0
] | [] | [] | [
"deep_learning",
"python",
"pytorch"
] | stackoverflow_0074103582_deep_learning_python_pytorch.txt |
Q:
Sklearn custom transformer not saving output dataset
I'm working with a data set that include many numeric features. I want to put all variables in log scale, so I've created a custom transformer that doesn't transform my dataset. Here's the code:
class Scale_log(BaseEstimator, TransformerMixin):
def fit(... | Sklearn custom transformer not saving output dataset | I'm working with a data set that include many numeric features. I want to put all variables in log scale, so I've created a custom transformer that doesn't transform my dataset. Here's the code:
class Scale_log(BaseEstimator, TransformerMixin):
def fit(self, X, y=None):
return self # nothing else to do... | [
"You can try to remove X.apply if you are working with numpy data:\nimport numpy as np\nfrom sklearn.base import TransformerMixin\n\n\nclass Scale_log(TransformerMixin):\n def fit(self, X, y=None):\n return self # nothing else to do\n\n def transform(self, X, y=None):\n X = np.log(1 + X)\n ... | [
0
] | [] | [] | [
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0074128177_machine_learning_python_scikit_learn.txt |
Q:
Bootstrap grid not aligned properly
With the django framework I use a loop in my templates to display the image inside my database, I also use the Bootstrap grid to make it clean, but it not working correctly. As you can see the image on at the bottom are not align correctly.
hmtl
<div class="container">
<div... | Bootstrap grid not aligned properly | With the django framework I use a loop in my templates to display the image inside my database, I also use the Bootstrap grid to make it clean, but it not working correctly. As you can see the image on at the bottom are not align correctly.
hmtl
<div class="container">
<div class="row">
<div class="col-sm-... | [
"You better put all the images in a parent that takes rest of the width after the list on the left, so it should be like this:\n<div class=\"container\">\n <div class=\"row\">\n <div class=\"col-sm-12 col-md-3 col-lg-2\">\n <div class=\"card-filter\" style=\"width: 10rem;\">\n <div class=\"card-head... | [
1
] | [] | [] | [
"bootstrap_4",
"django",
"html",
"python"
] | stackoverflow_0074129766_bootstrap_4_django_html_python.txt |
Q:
How do I return only one element from at a time and and int from range in python for loop
So I tried using this block of code but what it does is it puts the items from resources index 0 and 1 into both variables on the first iteration. I want a way to where resources will map to alph and range will map to i. Is t... | How do I return only one element from at a time and and int from range in python for loop | So I tried using this block of code but what it does is it puts the items from resources index 0 and 1 into both variables on the first iteration. I want a way to where resources will map to alph and range will map to i. Is this possible in python?
resources = ["a", "b", "c"]
for alph, i in resources, range(len(resourc... | [
"Use python's built-in enumerate function.\nresources = [\"a\", \"b\", \"c\"]\nfor i, alph in enumerate(resources):\n ...\n\n",
"This should work\n\n\nresources = [\"a\", \"b\", \"c\"]\nfor key, value in enumerate(resources):\n if value == \"a\":\n print(str(key) + \"-\" + value)\n\n\n\n"
] | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074130047_python.txt |
Q:
Issues with pipenv install on M1 Mac for python dependencies
I'm trying to set up a local repository that was originally created on intel-based macs. The repository uses pyenv and pipenv to manage python dependencies. Whenever I try to run pipenv install, I get the following error:
ERROR:pip.subprocessor:[present-... | Issues with pipenv install on M1 Mac for python dependencies | I'm trying to set up a local repository that was originally created on intel-based macs. The repository uses pyenv and pipenv to manage python dependencies. Whenever I try to run pipenv install, I get the following error:
ERROR:pip.subprocessor:[present-rich] pip subprocess to install build dependencies exited with 1
[... | [
"I'm not 100% sure, since I was dealing with 3.7.10, but my problem looked suspiciously similar. Based on this issue on pipenv, I was led to this article, which led me to a solution.\nThe summarized solution from that article is as follows.\nI'm not sure you need to install libffi from brew and make these exports, ... | [
0
] | [] | [] | [
"apple_m1",
"pipenv",
"pyenv",
"python",
"rosetta"
] | stackoverflow_0073967109_apple_m1_pipenv_pyenv_python_rosetta.txt |
Q:
Is there a way to not make my list disappear?
I'm trying to make some code, this part doesn't work. Because it keeps saying my list index is out of range and it looks like items from my list are disappearing. If i take a look at the code I can't find why it's not working. Anyone any idea why this is not working?
t... | Is there a way to not make my list disappear? | I'm trying to make some code, this part doesn't work. Because it keeps saying my list index is out of range and it looks like items from my list are disappearing. If i take a look at the code I can't find why it's not working. Anyone any idea why this is not working?
ts = [[4, 5], [9, 6], [2, 10]]
repeats = 3
for i in ... | [
"For removing values from ts, you can simple do this.\nts = [[4, 5], [9, 6], [2, 10]]\nfor _ in range(len(ts)):\n del ts[-1] # You can use `0` as well\n\nOR\nts = [[4, 5], [9, 6], [2, 10]]\ndel ts\n\n",
"Why this is happening is because you have cts = ts in every loop iteration. So you are modifying the origin... | [
0,
-1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074129357_list_python.txt |
Q:
split data such that a a categorical value is either in train or test python
I have a data set (df) as follows
Company Col1 Col2 Output
AB 10 20 1
AB 20 22 1
AB 14 12 0
XZ 33 22 1
XZ 43 62 0
I want to train_test_split the data such that if a company is i... | split data such that a a categorical value is either in train or test python | I have a data set (df) as follows
Company Col1 Col2 Output
AB 10 20 1
AB 20 22 1
AB 14 12 0
XZ 33 22 1
XZ 43 62 0
I want to train_test_split the data such that if a company is in the test set, it should not be in the training set at all. By which I mean if th... | [
"This might be a little verbose and not a generic function, but this approach might work for you:\ncounts = df.groupby(\"Company\").count()[\"Output\"]\nfrac = 0.8 # Fraction of the training table, will only be approximated\ntrain_companies = []\ni = 0 \nc = 0 \ntotal_count = counts.values.sum()\ntrain_count = tota... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"split",
"training_data"
] | stackoverflow_0074130017_dataframe_pandas_python_split_training_data.txt |
Q:
django collectstatic without db connection?
while I am running python manage.py collectstatic --no-input I am getting a DB connection issue. i want to collect statics without a DB connection to dockerize my Django app. with DB connection it's working fine.
traceback
Traceback (most recent call last):
File "C:\pr... | django collectstatic without db connection? | while I am running python manage.py collectstatic --no-input I am getting a DB connection issue. i want to collect statics without a DB connection to dockerize my Django app. with DB connection it's working fine.
traceback
Traceback (most recent call last):
File "C:\projects\test-env\lib\site-packages\django\db\backe... | [
"manage.py does not require a DB connection to work, are you write any check condition for connection in your models.py file?\nplease if you can shear the full error and model\n",
"Unfortunately there is no way to prevent collectstatic from trying to access the database. Using a dummy database in certain situatio... | [
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074121134_django_python.txt |
Q:
Is there a way for me to make this code even shorter
My code has the basic aim. Sort a list so that all the odd numbers are to the left and the even numbers are to the right. For example, [1,2,3,4,5] becomes [1,3,5,2,4] However, I kept myself an extra challenge. Make the code as short as possible.
I was able to ge... | Is there a way for me to make this code even shorter | My code has the basic aim. Sort a list so that all the odd numbers are to the left and the even numbers are to the right. For example, [1,2,3,4,5] becomes [1,3,5,2,4] However, I kept myself an extra challenge. Make the code as short as possible.
I was able to get it down to this.
l=[int(input("Number: ")) for i in rang... | [
"sorted accepts a key function. If we calculate the value of the modulus of 2 and negate the result, we get what we want.\ndata = [1, 2, 3, 4, 5]\nprint(sorted(data, key=lambda i: -(i%2)))\n\nThe result is [1, 3, 5, 2, 4].\n",
"You can try this,\nIn [1]: l = [1,2,3,4,5]\n\nIn [2]: sorted([i for i in l if i%2 == 1... | [
1,
0
] | [] | [] | [
"for_loop",
"list",
"list_comprehension",
"python",
"sorting"
] | stackoverflow_0074129896_for_loop_list_list_comprehension_python_sorting.txt |
Q:
Compatibility issue of pygame and OsmGpsMap
I am writing a program on Python 3.4 that uses GTK Map widget (OsmGpsMap) and pygame for joystick input.
Here is a simple program that displays a window with a map:
import gi
from gi.repository import Gtk
from gi.repository import OsmGpsMap
window = Gtk.Window(Gtk.Wind... | Compatibility issue of pygame and OsmGpsMap | I am writing a program on Python 3.4 that uses GTK Map widget (OsmGpsMap) and pygame for joystick input.
Here is a simple program that displays a window with a map:
import gi
from gi.repository import Gtk
from gi.repository import OsmGpsMap
window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
window.connect('destroy', Gtk... | [
"Do not mix frameworks. The frameworks may interact poorly with each other or conflict completely. If it works on your (operating) system, that doesn't mean it will work on another (operating) system or with a different version of one of the frameworks. Mixing frameworks always means some kind of undefined behavior... | [
0
] | [] | [] | [
"gtk",
"openstreetmap",
"osmgpsmap",
"pygame",
"python"
] | stackoverflow_0036871756_gtk_openstreetmap_osmgpsmap_pygame_python.txt |
Q:
Tkinter show me results in a Text Box (as if it were print)
I need some help, I think I'm getting confused all by myself.
I am trying to create a program that translates words or letters into other words. As code I did it perfectly:
import os
import re
Text = input("Text: ")
Text = Text.upper()
myDicc = {"AB": "... | Tkinter show me results in a Text Box (as if it were print) | I need some help, I think I'm getting confused all by myself.
I am trying to create a program that translates words or letters into other words. As code I did it perfectly:
import os
import re
Text = input("Text: ")
Text = Text.upper()
myDicc = {"AB": "Hello", "ET": "Beer", "OX": "Travel", "4BA2": "Car"}
for key, ... | [
"I see three problems:\n\nDISABLE doesn't allow to insert text - even using code. So you have to set it NORMAL before inserting\n\nText2.config(state=NORMAL)\nText2.insert(\"1.0\", i)\nText2.config(state=DISABLED)\n\n\nget('1.0') gives only first char - you need get('1.0', 'end')\n\nEDIT: as @BryanOakley noticed in... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074130039_python_tkinter.txt |
Q:
related_name foreign key doesn't show on template django
i have 2 models and i use related_name for one of them :
memory model:
class Memory(models.Model):
memory_title=models.CharField(max_length=200,verbose_name='عنوان خاطره')
memory_text=models.TextField(verbose_name='متن خاطره')
register_date=models.DateField(... | related_name foreign key doesn't show on template django | i have 2 models and i use related_name for one of them :
memory model:
class Memory(models.Model):
memory_title=models.CharField(max_length=200,verbose_name='عنوان خاطره')
memory_text=models.TextField(verbose_name='متن خاطره')
register_date=models.DateField(default=timezone.now,verbose_name='زمان ثبت خاطره')
is_active=... | [
"I may be missing something but it looks like you may just need to make one of your carousel-item's active. From the bootstrap carousel docs:\n\nInitial active element required\nThe .active class needs to be added to one of the slides. Otherwise, the carousel will not be visible.\n\nhttps://getbootstrap.com/docs/5.... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074128961_django_python.txt |
Q:
How to press the windows key with pynput?
I am making a program in which I want to use Windows + D combination to navigate to desktop, but I am unable to find a windows key in Key.<Keyname> to do that. How can I do that? If not, is there any other way i should do this instead?
A:
You may want to try cmd, cmd_l a... | How to press the windows key with pynput? | I am making a program in which I want to use Windows + D combination to navigate to desktop, but I am unable to find a windows key in Key.<Keyname> to do that. How can I do that? If not, is there any other way i should do this instead?
| [
"You may want to try cmd, cmd_l and cmd_r as seen in the pynput documentation.\n",
"import keyboard\nkeyboard.press_and_release('windows+d')\n\nTo install:\npip install keyboard\nI dont know how to use pynput and use the keyboard library, sorry\n",
"the Keyname for the Windows Button is cmd_l.\nif you want to p... | [
1,
1,
0
] | [] | [] | [
"pynput",
"python",
"python_3.x"
] | stackoverflow_0063489008_pynput_python_python_3.x.txt |
Q:
Renaming columns after merging data in Pandas
I have two Pandas series which I merged using the following code:
HS4_Tariffs_16=pd.concat([df_tariff_HS4_16_PT,df_tariff_HS4_16_MFN],axis=1)
If you are wondering why I used concat in place of merge, the error 'Series' object has no attribute 'merge' showed up when I ... | Renaming columns after merging data in Pandas | I have two Pandas series which I merged using the following code:
HS4_Tariffs_16=pd.concat([df_tariff_HS4_16_PT,df_tariff_HS4_16_MFN],axis=1)
If you are wondering why I used concat in place of merge, the error 'Series' object has no attribute 'merge' showed up when I used merge.
So anyway, I merged the two series usin... | [
"The following might work without having to reset the index. It could be setting it as index as you're renaming the frame as itself when you rename the column and Pandas is weird like that sometimes!\nHS4_Tariffs_16.rename(columns={'ProductCode':'HSCode'}, inplace=True)\n\n",
"You can use the rename_axis method t... | [
0,
0,
0
] | [] | [] | [
"pandas",
"python",
"rename"
] | stackoverflow_0064159919_pandas_python_rename.txt |
Q:
Percentage of element within groupby
I have a CSV with the following data:
Block_Number Block_Type Segment_Duration Speaker_ID
0 1 Pause 1.21 FUZ
1 1 Pause 1.09 FUZ
2 1 AICF 2.06 FAN
... | Percentage of element within groupby | I have a CSV with the following data:
Block_Number Block_Type Segment_Duration Speaker_ID
0 1 Pause 1.21 FUZ
1 1 Pause 1.09 FUZ
2 1 AICF 2.06 FAN
3 1 AICF ... | [
"You could do something like the following\ncategory = \"Block_Number\"\ncol = \"Speaker_ID\"\nvalue = \"FUZ\"\n\nd = {'Block_Number': {'0': '1', '1': '1', '2': '1', '3': '1', '4': '1', '1280': '32', '1281': '32', '1282': '32', '1283': '32', '1284': '32'}, 'Block_Type': {'0': 'Pause', '1': 'Pause', '2': 'AICF', '3'... | [
0
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074129992_group_by_pandas_python.txt |
Q:
How can I ask the user again before deleting a record from the database
My index.html file shows all posts in a blog. The index.html file contains a part that allows the user to delete a certain post. Here is the html code
<p class="post-meta">Posted by
<a href="#"> {{ post.author.name }} </a>
... | How can I ask the user again before deleting a record from the database | My index.html file shows all posts in a blog. The index.html file contains a part that allows the user to delete a certain post. Here is the html code
<p class="post-meta">Posted by
<a href="#"> {{ post.author.name }} </a>
on {{post.date}}
{% if current_user.id == post.author.id %}
... | [
"There are many options. find here one of them\nIn your html, when the user clicks on delete, point to this route\n@app.route(\"/deletewarning/<int:post_id>\")\n@admin_only\ndef deleteWarning_post(post_id):\n post_to_delete = BlogPost.query.get(post_id)\n return render_template('deletewarning.html', post_to_d... | [
0
] | [] | [] | [
"flask",
"jinja2",
"python"
] | stackoverflow_0074127769_flask_jinja2_python.txt |
Q:
How to remove all those rows from a csv file that are empty of a specific column
In the following csv I want to remove all rows that are empty with respect to column 'Age' only (i.e. row 4 & 5 to be removed of entire file)
I tried
df['Age'].dropna(how ='any')
But this isn't the solution.
A:
Use dropna with the ... | How to remove all those rows from a csv file that are empty of a specific column |
In the following csv I want to remove all rows that are empty with respect to column 'Age' only (i.e. row 4 & 5 to be removed of entire file)
I tried
df['Age'].dropna(how ='any')
But this isn't the solution.
| [
"Use dropna with the subset argument:\ndf.dropna(subset=['Age'], how='any')\n"
] | [
1
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074130303_csv_dataframe_pandas_python.txt |
Q:
Write PySpark dataframe to MongoDB inserting field as ObjectId
I was trying to write to MongoDB a Spark dataframe that contains the string representation of an ObjectId that is the _id of another collection.
The point is that PySpark has no support for ObjectId (Scala and Java ObjectId support explained here: htt... | Write PySpark dataframe to MongoDB inserting field as ObjectId | I was trying to write to MongoDB a Spark dataframe that contains the string representation of an ObjectId that is the _id of another collection.
The point is that PySpark has no support for ObjectId (Scala and Java ObjectId support explained here: https://github.com/mongodb/mongo-spark/blob/master/doc/1-sparkSQL.md) s... | [
"The accepted answer seem to be outdated as of today. It really led me to a working version, thank you.\nHere is my working version of the code : \nimport pyspark.sql.functions as sfunc\nfrom pyspark.sql.types import *\n\n# This user defined function creates from an str ID like \"5b8f7fe430c49e04fdb91599\"\n# the f... | [
3,
0,
0
] | [] | [] | [
"mongodb",
"pyspark",
"python"
] | stackoverflow_0047458805_mongodb_pyspark_python.txt |
Q:
Get feature and class names into decision tree using export graphviz
Good Afternoon,
I am working on a decision tree classifier and am having trouble visualizing it. I can output the decision tree, however I cannot get my feature or class names/labels into it. My data is in a pandas dataframe format which I then m... | Get feature and class names into decision tree using export graphviz | Good Afternoon,
I am working on a decision tree classifier and am having trouble visualizing it. I can output the decision tree, however I cannot get my feature or class names/labels into it. My data is in a pandas dataframe format which I then move into a numpy array and pass to the classifier. I've tried a few things... | [
"The class names are stored in decision_tree_classifier.classes_, i.e. the classes_ attribute of your DecisionTreeClassifier instance. And the feature names should be the columns of your input dataframe. For your case you will have \nclass_names = decision_tree_classifier.classes_\nfeature_names = df.columns[14:]\n... | [
20,
7,
0
] | [] | [] | [
"decision_tree",
"python",
"scikit_learn"
] | stackoverflow_0039476020_decision_tree_python_scikit_learn.txt |
Q:
typing module vs python object
I saw a lot of codes that use Type hints
and some of them use python built-in object as their type annotations and some of them use typing module for their type annotations
But what is the differences between python objects and typing module
It's better to say when to use python obje... | typing module vs python object | I saw a lot of codes that use Type hints
and some of them use python built-in object as their type annotations and some of them use typing module for their type annotations
But what is the differences between python objects and typing module
It's better to say when to use python object as type hints and when to use typ... | [
"Beginning with python 3.9 you can use more standard types for type hinting.\nSee https://peps.python.org/pep-0585/\n",
"As the documentation states, typing.List was deprecated in python-3.9 and you can now use the 'normal' list.\n"
] | [
2,
1
] | [] | [] | [
"python",
"type_hinting"
] | stackoverflow_0074130093_python_type_hinting.txt |
Q:
Extraction of names of variables in separate rows
I am extracting some variable names with own function from the text. Below you can see the code and text.
import re
text = '''
def function_cal_new1 (revenues_stories_new1, surplus_margin_new1, meadian_profit):
median_profit= revenues_... | Extraction of names of variables in separate rows | I am extracting some variable names with own function from the text. Below you can see the code and text.
import re
text = '''
def function_cal_new1 (revenues_stories_new1, surplus_margin_new1, meadian_profit):
median_profit= revenues_stories_new1* surplus_margin_new1
return media... | [
"You can use the ast module to walk through the code and pull out the bits you want. This is probably more robust that using a regular expression. The code does need to be valid, including indents. The the code in your string will need to remove the extra indents. Given that, here's some code that walks the tree an... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074130082_python.txt |
Q:
Is there any more pythonic way to checkfor keys in an ordered dictionary in Django
type of data
<class 'collections.OrderedDict'>
if("a" not in data or "b" not in data or "c" not in data or
"d" not in data or "e" not in data or "f" not in data or
"g" not in data or "h" not in data or "... | Is there any more pythonic way to checkfor keys in an ordered dictionary in Django | type of data
<class 'collections.OrderedDict'>
if("a" not in data or "b" not in data or "c" not in data or
"d" not in data or "e" not in data or "f" not in data or
"g" not in data or "h" not in data or "i" not in data):
raise serializers.ValidationError("All Required Paramete... | [
"You can do this,\nif any(i not in data for i in list('abcdefghijkli')):\n raise serializers.ValidationError(\"All Required Parameters not provided\")\n\nlist('abcdefghijkli') -> ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'i']. You can also use the entire list if you set of keys to check. like ... | [
1,
0
] | [] | [] | [
"api",
"django",
"django_rest_framework",
"ordereddictionary",
"python"
] | stackoverflow_0074130326_api_django_django_rest_framework_ordereddictionary_python.txt |
Q:
Replace 0 with NaN for selected columns only if all values are 0 in Pandas
Given a dataframe df as follows:
id value1 value2 value3
0 0 22 1 7
1 1 0 0 0
2 2 0 0 0
3 3 4 1 25
4 4 5 0 24
5 5 0 0 ... | Replace 0 with NaN for selected columns only if all values are 0 in Pandas | Given a dataframe df as follows:
id value1 value2 value3
0 0 22 1 7
1 1 0 0 0
2 2 0 0 0
3 3 4 1 25
4 4 5 0 24
5 5 0 0 3
Or:
df = pd.DataFrame([{'id': 0, 'value1': 22, 'value2': 1, 'value3': 7},
{... | [
"Use mask:\ndf[cols] = df[cols].mask(df[cols].eq(0).all(axis=1))\n\nmask automatically sets the row to NaN if the condition (df[cols].eq(0).all(axis=1)) is True.\nOriginal answer:\nI'd prefer mask:\n>>> df.set_index('id').mask(df[cols].eq(0).all(axis=1))\n value1 value2 value3\nid \n0 ... | [
4,
3,
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0069877974_dataframe_pandas_python.txt |
Q:
pyreverse not connecting classes in UML class diagram
I'm trying to create a UML diagram of a python project that shows inheritance relationships between classes using pyreverse.
Here's a small example to reproduce
Foo.py:
class Foo():
def print_foo(self):
print("hi")
Bar.py:
from Foo import Foo
clas... | pyreverse not connecting classes in UML class diagram | I'm trying to create a UML diagram of a python project that shows inheritance relationships between classes using pyreverse.
Here's a small example to reproduce
Foo.py:
class Foo():
def print_foo(self):
print("hi")
Bar.py:
from Foo import Foo
class Bar(Foo):
pass
__init__.py: empty
To generate the di... | [
"If you'd put all your classes in the same file, it works well:\n\nWhen separating the files as you did, we obtain the result that you show. This suggest that it has to do with the import module name.\nIf you replace the absolute module name with a relative module name:\nfrom .Foo import Foo\n\n...\n\nEverything w... | [
4
] | [] | [] | [
"class_diagram",
"pyreverse",
"python",
"uml"
] | stackoverflow_0074123298_class_diagram_pyreverse_python_uml.txt |
Q:
Filter dataframe with values repeated based on condition
Let's say I have a dataframe, df_products, like this one:
product_id
version
month
1111
v1
jan
1111
v2
feb
1111
v2
jan
2222
v1
mar
3333
v2
jan
3333
v2
dec
4444
v1
jun
4444
v1
jan
4444
v2
jun
How can I filter it to get only the product_ids that hav... | Filter dataframe with values repeated based on condition | Let's say I have a dataframe, df_products, like this one:
product_id
version
month
1111
v1
jan
1111
v2
feb
1111
v2
jan
2222
v1
mar
3333
v2
jan
3333
v2
dec
4444
v1
jun
4444
v1
jan
4444
v2
jun
How can I filter it to get only the product_ids that have at least one v1 AND one v2 in the version c... | [
"Here are two approaches:\nOne uses groupby and filter to remove groups that don't have both v1 and v2\ndf.groupby('product_id').filter(lambda x: all(v in x['version'].values for v in ['v1','v2']))['product_id'].unique().tolist()\n\nAnother idea would be to use a pivot table and dropna.\ndf.pivot_table(index='produ... | [
1,
1,
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074130237_dataframe_pandas_python.txt |
Q:
Made a code for insertion sort, declared a sorted and an unsorted array, but the unsorted array is output as a sorted array at the end
def InsSort(myList):
UBound = len(myList)
for i in range(1,UBound):
NextItem = myList[i]
position = i - 1
while position>=0 and myList[position]>N... | Made a code for insertion sort, declared a sorted and an unsorted array, but the unsorted array is output as a sorted array at the end | def InsSort(myList):
UBound = len(myList)
for i in range(1,UBound):
NextItem = myList[i]
position = i - 1
while position>=0 and myList[position]>NextItem:
myList[position+1] = myList[position]
position = position - 1
myList[position+1] = NextItem
Unsor... | [
"The assignment myList = UnsortList is meaningless as myList will just be a reference to UnSortList\nYour implementation of the insertion sort is flawed.\nUsing hard-coded values:\ndef insertionSort(array):\n for step in range(1, len(array)):\n key = array[step]\n j = step - 1 \n while... | [
0
] | [] | [] | [
"arrays",
"insertion_sort",
"python",
"sorting"
] | stackoverflow_0074130382_arrays_insertion_sort_python_sorting.txt |
Q:
Remove duplicate rows from pandas dataframe using specific condition
I know there are lot of questions about removing duplicates from pandas dataframe but this is bit different.
I am trying to remove duplicates from the dataframe but not getting the actual output as in the below given result dataframe. Actually th... | Remove duplicate rows from pandas dataframe using specific condition | I know there are lot of questions about removing duplicates from pandas dataframe but this is bit different.
I am trying to remove duplicates from the dataframe but not getting the actual output as in the below given result dataframe. Actually the data in table is too long. For understanding purpose I have given the du... | [
"# create a flag to separate out the group based on column 'a'\n# a is the only column that distinguishes the group\ndf['flag'] = np.nan\ndf['flag']=df['flag'].mask(df['a'].ne(df['a'].shift()), 1).cumsum().ffill()\n\n# sort, drop duplicates, keep flag as one of the column\n# finally drop the flag column\n(df.sort_v... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074130125_dataframe_pandas_python.txt |
Q:
How to use the value of a variable as a type hint in python
How do I assign a variable value as a type hint? I have attached a sample code for what I want to achieve:
class Class1:
var1 = 1
class Class2:
var2 = 2
class BaseClass:
def __init__(self, var):
self.var = var
class ChildClass1(Base... | How to use the value of a variable as a type hint in python | How do I assign a variable value as a type hint? I have attached a sample code for what I want to achieve:
class Class1:
var1 = 1
class Class2:
var2 = 2
class BaseClass:
def __init__(self, var):
self.var = var
class ChildClass1(BaseClass):
def __init__(self):
super().__init__(var=Clas... | [
"I know you specifically mentioned in the comments that you don't want generics, but since they are the textbook solution to this problem, maybe somebody else coming across this question will find this useful:\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\nclass Class1:\n var1 = 1\n\nclass Class2:... | [
2
] | [] | [] | [
"code_completion",
"oop",
"python",
"python_typing"
] | stackoverflow_0074129786_code_completion_oop_python_python_typing.txt |
Q:
Is there a better way to look if a string is contained in a different lists of strings?
I have a string called "block", and I want to check in which list it is contained. It works for me as below, but I was wondering if there is a better way (maybe a mapper or dict key\value or something similar). This is what I h... | Is there a better way to look if a string is contained in a different lists of strings? | I have a string called "block", and I want to check in which list it is contained. It works for me as below, but I was wondering if there is a better way (maybe a mapper or dict key\value or something similar). This is what I have:
def get_block_container(block: str) -> str:
if block in ['sss', 'srs']:
ret... | [
"Your current approach has a complexity of O(n*m) (where n is the number of branches and m the length of the longest list) I'd use a dictionary which will allow for a O(1) lookup:\ndef get_block_container(block: str) -> str:\n return {\n 'sss': 'prime',\n 'srs': 'prime',\n 'aaa': 'general',\... | [
3,
0
] | [
"You can store the return values in a dict as keys and return them like this:\ndef get_block_container(block: str) -> str:\n\n dict_list = {\"prime\": ['sss', 'srs'], \"general\": ['aaa', 'aba'], \"alpha\": ['zyz', 'zzz']}\n\n for key in dict_list:\n if block in dict_list[key]\n return key\n... | [
-1
] | [
"list",
"mapping",
"python"
] | stackoverflow_0074130434_list_mapping_python.txt |
Q:
How do you pass arguments to an inner function?
i have come across the following code today:
def deriv(f):
def df(x):
h = 0.001
total = (f(x+h)-f(X))/h
return round(total, 3)
return df
def g(x):
return x*x + 2*x + 2
print(deriv(g)(3))
what does it mean to have the 3 after deri... | How do you pass arguments to an inner function? | i have come across the following code today:
def deriv(f):
def df(x):
h = 0.001
total = (f(x+h)-f(X))/h
return round(total, 3)
return df
def g(x):
return x*x + 2*x + 2
print(deriv(g)(3))
what does it mean to have the 3 after deriv(g) like "deriv(g)(3)? is this how you pass argument... | [
"TL;DR:\nThis is nearly like every other function, this just allows you to create functions dynamically\n\nlets boil this down a bit\ndef wrapper(constant) -> Callable:\n def inner(x) -> float:\n return x+constant\n return inner\n\nfoo = wrapper(2)\n\nwould return you a function like\nfoo(x):\n return x + ... | [
0
] | [] | [] | [
"arguments",
"function",
"parameters",
"python"
] | stackoverflow_0074130472_arguments_function_parameters_python.txt |
Q:
Zybooks Leap year Python function
6.23 LAB: Leap year - functions
A common year in the modern Gregorian Calendar consists of 365 days. In reality, Earth takes longer to rotate around the sun. To account for the difference in time, every 4 years, a leap year takes place. A leap year is when a year has 366 days: An ... | Zybooks Leap year Python function | 6.23 LAB: Leap year - functions
A common year in the modern Gregorian Calendar consists of 365 days. In reality, Earth takes longer to rotate around the sun. To account for the difference in time, every 4 years, a leap year takes place. A leap year is when a year has 366 days: An extra day, February 29th. The requireme... | [
"Your code is a little mixed up with your question, format issue, I assume that's why you don't get an answer yet. Since I was also going over Zybooks therefore I just went over this question. Maybe I can show you mine.\ndef days_in_feb(user_year): \n if user_year % 4 == 0 and user_year % 100 != 0: #Condition to... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0073842495_python.txt |
Q:
Printing Values to CSV (Python)
I am trying to send the failed values to a CSV file but it's only giving me the last failed value in the list.
print(("Folder\t"+ "Expected\t"+ "Actual\t"+"Result").expandtabs(20))
for key in expected:
expectedCount = str(expected[key])
actualCount = "0"
if key in newDi... | Printing Values to CSV (Python) | I am trying to send the failed values to a CSV file but it's only giving me the last failed value in the list.
print(("Folder\t"+ "Expected\t"+ "Actual\t"+"Result").expandtabs(20))
for key in expected:
expectedCount = str(expected[key])
actualCount = "0"
if key in newDictionary:
actualCount = str(... | [
"This is because each iteration of with open using w is overwriting the file, leaving only the last iteration at the end of it. You could use a for append.\nA better method may be to create a data structure to hold the failures and write to the file simultaneously. Give the below a try. I couldn't test it without i... | [
1,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074130245_csv_python.txt |
Q:
Seaborn countplot does not accept both x and y arguments in Python
I want to plot the frequencies of a variable y by a variable x and to that effect I am using the seaborn.countplot() method. However I am getting an error message.
For a reproducible example see below:
surveys_species_by_plot_sample
plot_id t... | Seaborn countplot does not accept both x and y arguments in Python | I want to plot the frequencies of a variable y by a variable x and to that effect I am using the seaborn.countplot() method. However I am getting an error message.
For a reproducible example see below:
surveys_species_by_plot_sample
plot_id taxa
0 1 Bird
1 1 Rabbit
2 1 Rodent
3 2 Bird
4 2 Rabb... | [
"Reading examples in the Documentation, you can only pass x or y, not both. Stating X or Y changes the orientation of your chart. You might need a different chart type.\n",
"If you want to use both the x and y in your plot, you can't use countplot, instead you should use sn.barplot :)\nsn.barplot(x = \"plot_id\"... | [
1,
1
] | [] | [] | [
"count",
"python",
"seaborn"
] | stackoverflow_0047547235_count_python_seaborn.txt |
Q:
Convert torch of 9 channel to image of 3 channel (or 1) to display it
I have a tensor composed of 9 channel [9, 224, 224], (which is result of prediction. How could I convert to 3 channel as an image so that I could display it.
predicted =predicted.cpu()
label=predicted [0]
print(label.shape)
torch.Size([9, 224,... | Convert torch of 9 channel to image of 3 channel (or 1) to display it | I have a tensor composed of 9 channel [9, 224, 224], (which is result of prediction. How could I convert to 3 channel as an image so that I could display it.
predicted =predicted.cpu()
label=predicted [0]
print(label.shape)
torch.Size([9, 224, 224])
| [
"I'm assuming that your (9, 224, 224) data is semantic segmentation maps. There are two possible variants:\n\nYou have multi-class predictions\n\n# find normalized probabilities that sums up to 1 across the classes\nprediction = prediction.softmax(dim=0).cpu().numpy()\n\n# find the most probable class for each pixe... | [
2
] | [] | [] | [
"python",
"pytorch",
"torch"
] | stackoverflow_0074129550_python_pytorch_torch.txt |
Q:
How to tell if each subsequence is of increasing order python
Hi :) my question is exactly as the title says. The idea is to make a function that takes a sequence and a desired length for subsequences. Then return how many of those subsequences is in increasing order. I think I got the first part (of splitting the... | How to tell if each subsequence is of increasing order python | Hi :) my question is exactly as the title says. The idea is to make a function that takes a sequence and a desired length for subsequences. Then return how many of those subsequences is in increasing order. I think I got the first part (of splitting the one sequence into x length subsequences) but I have no idea how to... | [
"The general way in Python to tell if a sequence s is in increasing order is\nimport itertools\nall(x <= y for x, y in itertools.pairwise(s))\n\nYou may need to change <= to '<' depending on whether you consider 1223 to be an increasing sequence or not.\nYou should be able to fit this into your program.\n"
] | [
1
] | [] | [] | [
"computer_science",
"python",
"python_3.x",
"sequence",
"string"
] | stackoverflow_0074128015_computer_science_python_python_3.x_sequence_string.txt |
Q:
Table django_session don't exists when I try use admin with mysql
I'm new with django 1.10 using mysql (5.6.17) (WAMP 2.5) and Python 3.5 under Windows 8.1
I configured fine the mysql connector, I made my models, made makemigrations myapp and migrate myapp, using manage.py terminal with Pycharm.
When I try to acce... | Table django_session don't exists when I try use admin with mysql | I'm new with django 1.10 using mysql (5.6.17) (WAMP 2.5) and Python 3.5 under Windows 8.1
I configured fine the mysql connector, I made my models, made makemigrations myapp and migrate myapp, using manage.py terminal with Pycharm.
When I try to acces in admin web page, I have this message (trabajo is my app inside my p... | [
"if all you did was \"migrate myapp\", then you only created the tables for your app. I think a plain \"migrate\" will create all the tables for Django and it's contributed modules.\n",
"Run command:\npython manage.py migrate sessions\n\n",
"I got this error:\nFile \"C:\\Python39\\lib\\site-packages\\MySQLdb\\c... | [
10,
5,
1,
0
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0037425706_django_mysql_python.txt |
Q:
Vectorized Subarray Covariance
My problem is I have a array[28][28] and it contains a subarray.
I should vectorize it first, and get the cov of a (k^2,k^2) dimension but The vectorisation is done. When I use the np.cov() function, it is just a value. What steps did I miss?
for i in indexes_cov:
vectorized_point... | Vectorized Subarray Covariance | My problem is I have a array[28][28] and it contains a subarray.
I should vectorize it first, and get the cov of a (k^2,k^2) dimension but The vectorisation is done. When I use the np.cov() function, it is just a value. What steps did I miss?
for i in indexes_cov:
vectorized_points = np.reshape(data[i],-1) # get dat... | [
"I think you should try to use typecast.\n\nType Casting is the method to convert the variable data type into a certain data type in order to the operation required to be performed by users. (ref - https://www.geeksforgeeks.org/type-casting-in-python-implicit-and-explicit-with-examples/)\n\n"
] | [
0
] | [] | [] | [
"arrays",
"covariance",
"python",
"statistics"
] | stackoverflow_0074130170_arrays_covariance_python_statistics.txt |
Q:
sort list of objects by method
I am trying to sort a list of class Shape.the shape class has a method surface() which return an int. How would I sort this list from biggest to smallest surface
The code is this
def sort_list(list_shapes):
'''
for shape in list_shapes:
shape.surface() = int
... | sort list of objects by method | I am trying to sort a list of class Shape.the shape class has a method surface() which return an int. How would I sort this list from biggest to smallest surface
The code is this
def sort_list(list_shapes):
'''
for shape in list_shapes:
shape.surface() = int
output = list_shapes... | [
"You can use built-in sorted() function + __ge__() / __lt__() magic methods.\nHere is an example:\nclass Shape:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n\n def __ge__(self, other: 'Shape'):\n return self.surface() > other.surface()\n\n def __lt_... | [
1,
1
] | [] | [] | [
"class",
"list",
"oop",
"python",
"sorting"
] | stackoverflow_0074130513_class_list_oop_python_sorting.txt |
Q:
How do I check if an array is in ascending order in python?
suppose that I have the following NumPy array:
x = np.array([0,1,2,3,4,5])
I'd like to check if the numbers are in ascending order, i.e., if exists a number larger than the number before, it should warn me. I believe that I can do it with the any syntax,... | How do I check if an array is in ascending order in python? | suppose that I have the following NumPy array:
x = np.array([0,1,2,3,4,5])
I'd like to check if the numbers are in ascending order, i.e., if exists a number larger than the number before, it should warn me. I believe that I can do it with the any syntax, but I'm not sure how. For instance, I've been trying:
if any(x[i... | [
"You can use np.diff and check if it is all positive.\n>>> import numpy as np\n>>> arr = np.array([0,1,2,3,4,5])\n>>> np.diff(arr)\narray([1, 1, 1, 1, 1])\n>>> (np.diff(arr) >= 0).all()\nTrue\n\nOr\n>>> arr = np.array([0,2,1,3,4,5])\n>>> np.diff(arr)\narray([ 2, -1, 2, 1, 1])\n>>> (np.diff(arr) >= 0).all()\nFals... | [
4,
0
] | [] | [] | [
"any",
"arrays",
"numpy",
"python"
] | stackoverflow_0074130561_any_arrays_numpy_python.txt |
Q:
create a list inside nested dictionary
I have a long list of keys (main keys) in the nested dictionary. In one of the sub-keys, I want to create a list of its values.
This is one of the records from my nested dictionary. They all are structured in a similar manner.
{'C4QY10_e':
{'protein accession': 'C4QY10_e... | create a list inside nested dictionary | I have a long list of keys (main keys) in the nested dictionary. In one of the sub-keys, I want to create a list of its values.
This is one of the records from my nested dictionary. They all are structured in a similar manner.
{'C4QY10_e':
{'protein accession': 'C4QY10_e',
'sequence length': [1879],
'analysis': ... | [
"Using split():\nyourdict = {'C4QY10_e': \n{'protein accession': 'C4QY10_e', \n'sequence length': [1879], \n'analysis': 'Pfam', \n'signature accession': 'PF18314, PF02801, PF18325, PF00109, PF01648', \n'signature description': \"Fatty acid synthase type I helical domain, Beta-ketoacyl synthase, Fatty acid synthase ... | [
2,
0
] | [] | [] | [
"bioinformatics",
"python"
] | stackoverflow_0074130536_bioinformatics_python.txt |
Q:
Create a lambda function that allows me to identify if a regex capturing group is equal to another capturing group, and if so replace it
import re
input_text = "Asegurarse que halla 4(4) o 5( 5 ) de ellos, también 24(24 48), o sino 24, (24 )no 66(70 y seis), o () 56(), 56(5 6) ssd 56"
lambda_fuction_result = la... | Create a lambda function that allows me to identify if a regex capturing group is equal to another capturing group, and if so replace it | import re
input_text = "Asegurarse que halla 4(4) o 5( 5 ) de ellos, también 24(24 48), o sino 24, (24 )no 66(70 y seis), o () 56(), 56(5 6) ssd 56"
lambda_fuction_result = lambda m: re.sub(r"", "", m.group())
input_text = re.sub(capture_groups_with_regex, lambda_fuction_result, input_text)
print(repr(input_text))... | [
"As far as I understood your task is to remove parentheses with number if it equals number before those parentheses.\nFirst of all you need a regular expression which matches number and number in parentheses in separate capturing groups:\n(\\d+)\\s*\\(\\s*(\\d+)\\s*\\)\n\nLink to demo.\nTo check whether values of b... | [
3
] | [] | [] | [
"lambda",
"python",
"regex"
] | stackoverflow_0074130204_lambda_python_regex.txt |
Q:
Python notation question: string modulus?
I've come across a snippet of Python code that looks like this:
code = 'foo' % bar
...where foo is a string of JavaScript code that's being used in a callback, and bar is a dictionary.
Can someone explain what this means?
A:
The string is beeing formatted using the old ... | Python notation question: string modulus? | I've come across a snippet of Python code that looks like this:
code = 'foo' % bar
...where foo is a string of JavaScript code that's being used in a callback, and bar is a dictionary.
Can someone explain what this means?
| [
"The string is beeing formatted using the old %-formatting style.\nThe string likely contains sequences like %(foo)s that are being replaced by the dictionary. An example would be:\ntext = \"Hello %(adjective)s World\" % {\"adjective\": \"beautiful\"}\n\nThis would result in Hello beautiful World.\nThe text inside ... | [
1
] | [] | [] | [
"dictionary",
"javascript",
"modulo",
"python",
"string"
] | stackoverflow_0074130506_dictionary_javascript_modulo_python_string.txt |
Q:
Centering components in Tkinter Grid Layout not working
I want the components in this window to be center aligned, but no matter how I try I am unable to bring those components to the center.
Here is my code and the attached screenshot of the window when I run the code.
import tkinter.filedialog
import tkinter as ... | Centering components in Tkinter Grid Layout not working | I want the components in this window to be center aligned, but no matter how I try I am unable to bring those components to the center.
Here is my code and the attached screenshot of the window when I run the code.
import tkinter.filedialog
import tkinter as tk
from PIL import ImageTk,Image
import numpy as np
import os... | [
"Have you tried setting 'sticky' to expand horizontally, e.g.\ngrid(row=0, column=0, columnspan=2, sticky='ew')\n\nyou could also try adding weight=1 like so\nwin.grid_columnconfigure(0, weight=1) # '0' refers to column 0\n\n"
] | [
1
] | [] | [] | [
"python",
"tkinter",
"tkinter_layout"
] | stackoverflow_0074130669_python_tkinter_tkinter_layout.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.