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:
need to have certain Output
translation:
2 Write the function rowZero (length) - it will print a line with a given length of only zeros. Write the
function rowZeroOne (length, position) - it will print a line of zeros with one at the selected position. Unit position <= row length
3 rowZeroSymbot (length, position,... | need to have certain Output | translation:
2 Write the function rowZero (length) - it will print a line with a given length of only zeros. Write the
function rowZeroOne (length, position) - it will print a line of zeros with one at the selected position. Unit position <= row length
3 rowZeroSymbot (length, position, symbol) will print a line of zer... | [] | [] | [
"Print 1 in the if, and 0 in the else.\ndef rotZeroOne(length, position):\n for x in range(length):\n if x == position:\n print('1', end='')\n else:\n print('0', end='')\n print()\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074353939_python.txt |
Q:
calculate percentage row by row in pandas dataframe
I have a dataframe, df, i want to calculate percentage by row for one of the rows and return 'No' in the other row.
A
B
C
D
X
500
250
50.00
Y
980
700
71.42
A
B
C
D
E
X
500
250
50.00
70.08
Y
980
700
71.42
No
70.08% is got by dividing 50.00/71.42
A:
# shif... | calculate percentage row by row in pandas dataframe | I have a dataframe, df, i want to calculate percentage by row for one of the rows and return 'No' in the other row.
A
B
C
D
X
500
250
50.00
Y
980
700
71.42
A
B
C
D
E
X
500
250
50.00
70.08
Y
980
700
71.42
No
70.08% is got by dividing 50.00/71.42
| [
"# shift by a row and divide the two values\n\ndf['E']=df['D'].div(df['D'].shift(-1)).fillna('No')\ndf\n\n A B C D E\n0 X 500 250 50.00 0.700084\n1 Y 980 700 71.42 No\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"percentage",
"python"
] | stackoverflow_0074353682_dataframe_pandas_percentage_python.txt |
Q:
Iterate over unique values in first column while counting other columns within the value of the first column
I have some data that looks like this:
agent external id,product_group,commission_rate,weeks_held
3000-29,Collection,0.85,1
3000-29,Collection,0.85,2
3000-29,Return,0.85,1
3000-12,Collection,0.85,1
3000-12,... | Iterate over unique values in first column while counting other columns within the value of the first column | I have some data that looks like this:
agent external id,product_group,commission_rate,weeks_held
3000-29,Collection,0.85,1
3000-29,Collection,0.85,2
3000-29,Return,0.85,1
3000-12,Collection,0.85,1
3000-12,Collection,0.85,2
3000-12,Return,0.85,1
3000-34,Collection,0.8,2
3000-34,Collection,0.8,2
3000-34,Return,0.8,1
302... | [
"Is this what you would like. Please give a sample output and someone will help.\ndf.groupby(['agent_external_id','product_group']).agg(['sum','count'])\n\n\n\n commission_rate weeks_held \n sum count sum count\nagen... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074353951_dataframe_pandas_python.txt |
Q:
Validation loss for pytorch Faster-RCNN
I’m currently doing object detection on a custom dataset using transfer learning from a pytorch pretrained Faster-RCNN model (like in torchvision tutorial).
I would like to compute validation loss dict (as in train mode) at the end of each epoch.
I can just run model in tra... | Validation loss for pytorch Faster-RCNN | I’m currently doing object detection on a custom dataset using transfer learning from a pytorch pretrained Faster-RCNN model (like in torchvision tutorial).
I would like to compute validation loss dict (as in train mode) at the end of each epoch.
I can just run model in train mode for validation like this:
model.train... | [
"There was some discussion about this issue here. The conclusion there is that it is absolutely valid to calculate validation loss in train mode. The numerical value of the val loss in itself is not meaningful, only the trend is important to prevent overfitting. Therefore while train mode does alter the numerical v... | [
5,
3,
1,
0
] | [] | [] | [
"computer_vision",
"machine_learning",
"object_detection",
"python",
"pytorch"
] | stackoverflow_0060339336_computer_vision_machine_learning_object_detection_python_pytorch.txt |
Q:
When I decorate a method that is called with only keyword arguments (and self) my IDE (PyCharm) complains that self is unfilled
So I have a decorator that is something like this:
def add_exclamation(method):
def wrapper(self, *method_args, **method_kwargs):
method_output = method(self, *method_args, **... | When I decorate a method that is called with only keyword arguments (and self) my IDE (PyCharm) complains that self is unfilled | So I have a decorator that is something like this:
def add_exclamation(method):
def wrapper(self, *method_args, **method_kwargs):
method_output = method(self, *method_args, **method_kwargs)
return method_output + "!"
return wrapper
Then I use it to decorate a method of my class that is only ca... | [
"self is just a method_arg ... so just use that ...\ndef add_exclamation(method):\n def wrapper(*method_args, **method_kwargs):\n method_output = method(*method_args, **method_kwargs)\n if isinstance(method_output,str): # be safe\n return method_output + \"!\"\n return method_outp... | [
0
] | [] | [] | [
"pycharm",
"python",
"python_class",
"python_decorators"
] | stackoverflow_0074354013_pycharm_python_python_class_python_decorators.txt |
Q:
Resample (increase the pixel size) a satellite image using a Gaussian filter in Python
I have a satellite image (Landsat 8, panchromatic band) at 15m pixel size. My goal is to upscale the image (i.e., change the pixel size) at 460m using a Gaussian filter with sigma = 0.5. Is there a function in python that can do... | Resample (increase the pixel size) a satellite image using a Gaussian filter in Python | I have a satellite image (Landsat 8, panchromatic band) at 15m pixel size. My goal is to upscale the image (i.e., change the pixel size) at 460m using a Gaussian filter with sigma = 0.5. Is there a function in python that can do this (i.e., increase the pixel size using a Gaussian filter)? I don't have an example to sh... | [
"Check Pyresample it has resample_gauss\nThis function allows you to specify sigma, radius_of_influence and other parameters.\nIn your case as you want to decrease the resolution of the input image, you just need to define the output height and width based on the target resolution and the area extent.\nPlease check... | [
0,
0
] | [] | [] | [
"gaussian",
"gaussianblur",
"landsat",
"python",
"raster"
] | stackoverflow_0073710124_gaussian_gaussianblur_landsat_python_raster.txt |
Q:
Python open a file with GUI
How can I open a file via Python through its actual application? Not open(filename), but to actually view the file myself on the computer. Can I do it with subprocess.run and use a terminal command? (I'm on windows).
A:
You can probably do it in one of the following ways:
subprocess.... | Python open a file with GUI | How can I open a file via Python through its actual application? Not open(filename), but to actually view the file myself on the computer. Can I do it with subprocess.run and use a terminal command? (I'm on windows).
| [
"You can probably do it in one of the following ways:\n\nsubprocess.run\nos.startfile\n\nimport subprocess\nsubprocess.run('notepad.exe')\n\nor\nimport os\nos.startfile('textfile.txt')\n\nwhich will open the textfile with the program associated with txt files.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074351948_python.txt |
Q:
Python ConnectionRefusedError: [Errno 61] Connection refused
Ive seen similar questions but they I couldn't fix this error. Me and my friend are making a chat program but we keep getting the error
ConnectionRefusedError: [Errno 61] Connection refused
We are on different networks by the way.
Here is my code fo... | Python ConnectionRefusedError: [Errno 61] Connection refused | Ive seen similar questions but they I couldn't fix this error. Me and my friend are making a chat program but we keep getting the error
ConnectionRefusedError: [Errno 61] Connection refused
We are on different networks by the way.
Here is my code for the server
import socket
def socket_create():
try:
global ... | [
"This may not answer your original question, but I encountered this error and it was simply that I had not starting the server process first to listen to localhost (127.0.0.1) on the port I chose to test on. In order for the client to connect to localhost, a server must be listening on localhost. \n",
"'127.0.0.1... | [
11,
5,
1,
0
] | [
"This Code Not Valid For Chatting, you have to use unblocking sockets and select module or other async modules\n"
] | [
-2
] | [
"errno",
"python",
"sockets"
] | stackoverflow_0040814712_errno_python_sockets.txt |
Q:
Python: Removing duplicates in numpy array and keeping order
I have an numpy array that looks like this:
[array([1.4600e-01, 2.9575e+00, 6.1580e+02]), array([5.860e-01, 4.507e+00, 8.748e+02]), array([1.4600e-01, 2.9575e+00, 6.1580e+02]), array([5.860e-01, 4.507e+00, 8.748e+02]), array([9.6900e-01, 1.7822e+00, 1.08... | Python: Removing duplicates in numpy array and keeping order | I have an numpy array that looks like this:
[array([1.4600e-01, 2.9575e+00, 6.1580e+02]), array([5.860e-01, 4.507e+00, 8.748e+02]), array([1.4600e-01, 2.9575e+00, 6.1580e+02]), array([5.860e-01, 4.507e+00, 8.748e+02]), array([9.6900e-01, 1.7822e+00, 1.0829e+04]), array([ 0.701 , 1.6545, 603.3 ])]
I want to remove... | [
"array = np.array\na = [array([1.4600e-01, 2.9575e+00, 6.1580e+02]), array([5.860e-01, 4.507e+00, 8.748e+02]), array([1.4600e-01, 2.9575e+00, 6.1580e+02]), array([5.860e-01, 4.507e+00, 8.748e+02]), array([9.6900e-01, 1.7822e+00, 1.0829e+04]), array([ 0.701 , 1.6545, 603.3 ])]\n\nseen = set()\n\nans = []\nfor i... | [
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0074353965_arrays_python.txt |
Q:
Python - How to split a string until an occurence of an integer?
In Python, I am trying to split a string until an occurence of an integer, the first occurence of integer will be included, rest will not.
Example strings that I will have are shown below:
SOME STRING (IT WILL ALWAYS END WITH PARANTHESIS) 2 3 ---
SO... | Python - How to split a string until an occurence of an integer? | In Python, I am trying to split a string until an occurence of an integer, the first occurence of integer will be included, rest will not.
Example strings that I will have are shown below:
SOME STRING (IT WILL ALWAYS END WITH PARANTHESIS) 2 3 ---
SOME OTHER STRING (PARANTHESIS AGAIN) 5 --- 3
AND SOME OTHER (AGAIN) 2 ... | [
"It's ideal case for regular expression.\nimport re\n\ns = \"SOME STRING (IT WILL ALWAYS END WITH PARANTHESIS) 2 3 ---\"\nm = re.search(r\".*?[0-9]+\", s)\nprint(m.group(0))\n\nExplanation:\n\n.* matches any number of characters\n? tells to not be greedy (without it it will stop in last integer)\n[0-9]+ - matches o... | [
2,
1,
0
] | [] | [] | [
"python",
"split",
"string"
] | stackoverflow_0074354085_python_split_string.txt |
Q:
How to add dependencies to a Model in SageMaker?
I'm trying to deploy a model like this:
model_alpha = PyTorchModel(
entry_point='inference_alpha.py',
source_dir='code_alpha',
dependencies = ['module_0',
'module_1'],
role=role,
model_data=model_data_alpha,
framework_vers... | How to add dependencies to a Model in SageMaker? | I'm trying to deploy a model like this:
model_alpha = PyTorchModel(
entry_point='inference_alpha.py',
source_dir='code_alpha',
dependencies = ['module_0',
'module_1'],
role=role,
model_data=model_data_alpha,
framework_version="1.7.1",
py_version='py3',
code_location='... | [
"Within the documentation of PytorchModel(), you see that this class is based on FrameworkModel() and on and on until the generic Model().\nTherefore, you can use the parameter source_dir:\n\nPath (absolute or relative) to a directory with any other serving\nsource code dependencies aside from the entry point file.... | [
0
] | [] | [] | [
"amazon_sagemaker",
"machine_learning",
"python"
] | stackoverflow_0074353945_amazon_sagemaker_machine_learning_python.txt |
Q:
Adding lists from nested JSON file to pandas dataframe?
I have a Json file that looks like the following. I want to grab the strings of names in the "actors" list and add them to a dataframe (which is empty now, the first item added to the dataframe would be the strings of actor names as rows).
{
"1": {
... | Adding lists from nested JSON file to pandas dataframe? | I have a Json file that looks like the following. I want to grab the strings of names in the "actors" list and add them to a dataframe (which is empty now, the first item added to the dataframe would be the strings of actor names as rows).
{
"1": {
"title": "Exodus: Gods and Kings",
"url": "https:/... | [
"You can use list-comprehension to get actors from the dictionary and then construct a dataframe. For example:\ndata = {\n \"1\": {\n \"title\": \"Exodus: Gods and Kings\",\n \"url\": \"https://en.wikipedia.org/wiki/Exodus%3A%20Gods%20and%20Kings\",\n \"year\": \"2014\",\n \"poster\":... | [
2,
1
] | [] | [] | [
"dataframe",
"json",
"pandas",
"python"
] | stackoverflow_0074354084_dataframe_json_pandas_python.txt |
Q:
Remove outliers withing training set in cross-validation
I am trying to do a cross-validation but I want to remove outliers (eg. only lower than 0.95y) in the training sets, while keeping the test set intact. I am using:
cv_scores = cross_validate(reg, X=X, y=y_tr, cv=GroupKFold(n_splits=3), groups=groups, scoring... | Remove outliers withing training set in cross-validation | I am trying to do a cross-validation but I want to remove outliers (eg. only lower than 0.95y) in the training sets, while keeping the test set intact. I am using:
cv_scores = cross_validate(reg, X=X, y=y_tr, cv=GroupKFold(n_splits=3), groups=groups, scoring=scoring, return_train_score=True, verbose=0)
for the cross-... | [
"Removing outliers is not recommended by most statisticians. Instead, you should analyze the outliers like using cook distance. Importantly, removing outliers from train data will cause data shift.\n"
] | [
0
] | [] | [] | [
"cross_validation",
"pandas",
"python",
"sklearn_pandas"
] | stackoverflow_0074058580_cross_validation_pandas_python_sklearn_pandas.txt |
Q:
Python append to system arguments - bad practice?
I'm parsing system arguments in my Python project using sys.argv. At some point i had to modify the script after having written the logic that parses system args. I added a line the basically appends a string to sys.argv so the logic that parses it won't be changed... | Python append to system arguments - bad practice? | I'm parsing system arguments in my Python project using sys.argv. At some point i had to modify the script after having written the logic that parses system args. I added a line the basically appends a string to sys.argv so the logic that parses it won't be changed -
sys.argv.append('some string here')
Is it a bad pra... | [
"It is bad practice to modify sys.argv in Python and it's equivalent in other languages.\nIn these situations I recommend a parsed_args variable which has all your parsed data from sys.argv, any default values that you would like to set, and any modifications that \"middleware\" would make.\n",
"In my opinion in... | [
2,
0,
0
] | [] | [] | [
"command_line_arguments",
"python"
] | stackoverflow_0051472873_command_line_arguments_python.txt |
Q:
Plot dashed or dotted line plot with opencv python
I would like to draw a line plot into an image with OpenCV in Python. The behavior should be similar to the matplotlib library.
Dots/dashes should be evenly distributed across the line string.
Other questions does not really provide me with the desired output. Th... | Plot dashed or dotted line plot with opencv python | I would like to draw a line plot into an image with OpenCV in Python. The behavior should be similar to the matplotlib library.
Dots/dashes should be evenly distributed across the line string.
Other questions does not really provide me with the desired output. They usually divide each line independently, which causes ... | [
"If you want to obtain uniformly distributed dots/dashes with guaranteed gap, you have to place them with regard to the beginning of the line string. First, we sample distances linearly up to the sum of line distances.\nAll points are then projected on corresponding segments. Finally, we plot lines, dashes, dots, e... | [
0
] | [] | [] | [
"opencv",
"plot",
"python",
"visualization"
] | stackoverflow_0074354216_opencv_plot_python_visualization.txt |
Q:
Run setup_class() class after class scope fixture defined in conftest
So, I have fixtures defined in conftest.py file with scope="class" as I want to run them before each test class is invoked. The conftest file is placed inside project root directory for it to be visible to every test module.
Now in one of the te... | Run setup_class() class after class scope fixture defined in conftest | So, I have fixtures defined in conftest.py file with scope="class" as I want to run them before each test class is invoked. The conftest file is placed inside project root directory for it to be visible to every test module.
Now in one of the test modules, I have another setup function which I want to run once for that... | [
"I have exactly the same problem. Only now I have realized that the problem might be taht the setup_class is called before the fixture >-/\nI think that this question is similar to this one\nPytest - How to pass an argument to setup_class?\nAnd the problem is mixing the unittest and pytest methods.\nI kind of did w... | [
0,
0,
0
] | [] | [] | [
"pytest",
"python",
"python_3.x"
] | stackoverflow_0073627352_pytest_python_python_3.x.txt |
Q:
Issue with utilizing both if statements at a time according to the situation
There is a sentence from which I am trying to remove certain words. I don't know if I am using the if statement correct but one of the word in the words list is getting removed when I am testing it. Below is my code:
def remove_stopwords(... | Issue with utilizing both if statements at a time according to the situation | There is a sentence from which I am trying to remove certain words. I don't know if I am using the if statement correct but one of the word in the words list is getting removed when I am testing it. Below is my code:
def remove_stopwords(sentence):
stopwords = ["a", "about", "above", "after", "again", "against", "all... | [
"For your interest, here's another way to do it using split() which breaks a sentence at spaces. The strip() in the return just removes the space at the end which was added in.\ndef remove_stopwords(sentence):\n result = ''\n stopwords = [\"a\", \"about\", \"above\", \"after\", \"again\", \"against\", \"all\"... | [
0
] | [] | [] | [
"if_statement",
"list",
"nlp",
"python"
] | stackoverflow_0074354001_if_statement_list_nlp_python.txt |
Q:
Alembic autogenerate recerates existing indexes
I am using a simple mixin for all my tables:
class IdMixIn:
id = sa.Column(sa.Integer, primary_key=True, index=True)
Example table:
class MyTable(Base, IdMixIn):
__tablename__ = 'my_table'
my_col: str = sa.Column(sa.String)
I have about thirty of these... | Alembic autogenerate recerates existing indexes | I am using a simple mixin for all my tables:
class IdMixIn:
id = sa.Column(sa.Integer, primary_key=True, index=True)
Example table:
class MyTable(Base, IdMixIn):
__tablename__ = 'my_table'
my_col: str = sa.Column(sa.String)
I have about thirty of these tables, and if I run alembic revision --autogenerate... | [
"There is no need to create index on primary key column, so you can only write\nclass IdMixIn:\n id = sa.Column(sa.Integer, primary_key=True)\n\nPostgresql will automatically create index for this column\n"
] | [
1
] | [] | [] | [
"alembic",
"python",
"python_3.x",
"sqlalchemy"
] | stackoverflow_0074321455_alembic_python_python_3.x_sqlalchemy.txt |
Q:
How to calculate distance of coordinates and categorical dataset with DBSCAN Algorithm?
I have a dataset containing coordinates and categorical data, such as below:
I have searched a lot of papers and journals trying to find explanations regarding which distance measurement method I should apply on my dataset wit... | How to calculate distance of coordinates and categorical dataset with DBSCAN Algorithm? | I have a dataset containing coordinates and categorical data, such as below:
I have searched a lot of papers and journals trying to find explanations regarding which distance measurement method I should apply on my dataset with DBSCAN Algorithm. Here I have a mixed dataset with Latitude and Longitude (coordinates), an... | [
"Read this article, I prefer using OneHotEncoding\nimport pandas as pd\n\nyour_df = pd.read_csv('./your_data.csv')\n\n# generate binary values using get_dummies\ndum_df = pd.get_dummies(your_df, columns=[\"Jenis Kecelakaan\"])\n\ndum_df.head()\n\n",
"Try it this way.\n# import necessary modules\nimport pandas as ... | [
1,
1,
0
] | [] | [] | [
"cluster_analysis",
"dbscan",
"python",
"scikit_learn"
] | stackoverflow_0067968952_cluster_analysis_dbscan_python_scikit_learn.txt |
Q:
How do I confirm the output from the sklearn transform model (sc.transform)?
I am learning about the StandardScaler module in sklearn. I understand the sc.fit obtains the mean of the data and uses it to transform the train and the test of the data, but I do not understand what mathematical function is being perfo... | How do I confirm the output from the sklearn transform model (sc.transform)? | I am learning about the StandardScaler module in sklearn. I understand the sc.fit obtains the mean of the data and uses it to transform the train and the test of the data, but I do not understand what mathematical function is being performed on the data array with the sc.mean_ obtained from sc.fit.
How do I confirm th... | [
"Use\ndf.describe()\n\nto see your desired transformation.\nfrom sklearn.preprocessing import StandardScaler\nimport numpy as np\nimport pandas as pd\n# 4 samples/observations and 2 variables/features\ndata = np.array([[0, 0], [1, 0], [0, 1], [1, 1]])\ndf = pd.DataFrame(data, columns=['V1', 'V2']).astype('float64')... | [
0
] | [] | [] | [
"python",
"python_3.x",
"sklearn_pandas",
"transform"
] | stackoverflow_0073795578_python_python_3.x_sklearn_pandas_transform.txt |
Q:
Pandas: Looking up the list of sheets in an excel file
The new version of Pandas uses the following interface to load Excel files:
read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])
but what if I don't know the sheets that are available?
For example, I am working with excel files that the... | Pandas: Looking up the list of sheets in an excel file | The new version of Pandas uses the following interface to load Excel files:
read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])
but what if I don't know the sheets that are available?
For example, I am working with excel files that the following sheets
Data 1, Data 2 ..., Data N, foo, bar
but... | [
"You can still use the ExcelFile class (and the sheet_names attribute):\nxl = pd.ExcelFile('foo.xls')\n\nxl.sheet_names # see all sheet names\n\nxl.parse(sheet_name) # read a specific sheet to DataFrame\n\nsee docs for parse for more options...\n",
"You should explicitly specify the second parameter (sheetname... | [
438,
75,
12,
11,
5,
3,
3,
3,
2,
1,
0,
0
] | [] | [] | [
"excel",
"openpyxl",
"pandas",
"python",
"xlrd"
] | stackoverflow_0017977540_excel_openpyxl_pandas_python_xlrd.txt |
Q:
AttributeError: 'Member' object has no attribute 'avatar_url'
I am trying to make a Discord bot and one of the features is a welcoming from my bot using on_member_join. This is the event:
@bot.event
async def on_member_join(member, self):
embed = discord.Embed(colour=discord.Colour(0x95efcc), description=f"Wel... | AttributeError: 'Member' object has no attribute 'avatar_url' | I am trying to make a Discord bot and one of the features is a welcoming from my bot using on_member_join. This is the event:
@bot.event
async def on_member_join(member, self):
embed = discord.Embed(colour=discord.Colour(0x95efcc), description=f"Welcome to Rebellions server! You are the{len(list(member.guild.member... | [
"In discord.py 2.0 the attribute Member.avatar_url got removed and replaced by Member.avatar. To access the URL, you should use member.avatar.url.\nCheck out the migration guide for similar instances. Using pip freeze you can check which version of discord.py you have installed, but I assume it's 2.x, and probably ... | [
3,
2
] | [] | [] | [
"discord.py",
"python",
"typeerror"
] | stackoverflow_0074349638_discord.py_python_typeerror.txt |
Q:
Save previous function call values
I'm trying to get the locations of clicked buttons in tkinter. Everytime a button is clicked I want to save the location the button was placed in. However, once two buttons have been clicked/the function has been called twice, I want to store both the previous values and the new ... | Save previous function call values | I'm trying to get the locations of clicked buttons in tkinter. Everytime a button is clicked I want to save the location the button was placed in. However, once two buttons have been clicked/the function has been called twice, I want to store both the previous values and the new values together e.g. in a list, so that ... | [
"Just make the placement list an instance attribute of the MainGui class.\nFor example:\nclass MainGui(Window):\n def __init__(self):\n Window.__init__(self, \"Window\", \"800x500\")\n self.called = 0\n self.placement = [] # added this\n self.airfields_btn = []\n self.airf... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074352297_python_tkinter.txt |
Q:
K-Means applied on a dataframe with too many features and zeros
I´m trying to cluster a dataframe with 36 features and a lot (88%) of zeros. It's my first job at ML, I started with K-Means, but for any K I choose, 99.5% of my data remains on cluster 0. I've tried some PCA do reduce features, but the same problem a... | K-Means applied on a dataframe with too many features and zeros | I´m trying to cluster a dataframe with 36 features and a lot (88%) of zeros. It's my first job at ML, I started with K-Means, but for any K I choose, 99.5% of my data remains on cluster 0. I've tried some PCA do reduce features, but the same problem appeared.
Any thoughts on approaches I can try?
| [
"Have you tried techniques such as sequential feature selection? These are so-called 'wrapper methods' where you add (for forward selection) or eliminate (for backward elimination) one feature at a time and assess the performance of the model accordingly. I tend to use supervised learning models in my job but I bel... | [
0
] | [] | [] | [
"k_means",
"machine_learning",
"pandas",
"python"
] | stackoverflow_0074354221_k_means_machine_learning_pandas_python.txt |
Q:
Labelling the Target Variables
I am trying to plot Heart Disease against Gender. Here I am trying to label 0 as absent and 1 as present in the fig. Is there is a way of doing it? I have tried the following code and plotted:
ax = sns.countplot(x='target', hue='sex', data=heartt)
plt.show()
A:
I wouldn't relabel t... | Labelling the Target Variables | I am trying to plot Heart Disease against Gender. Here I am trying to label 0 as absent and 1 as present in the fig. Is there is a way of doing it? I have tried the following code and plotted:
ax = sns.countplot(x='target', hue='sex', data=heartt)
plt.show()
| [
"I wouldn't relabel the axis ticks if I were you, unless you're very sure about how seaborn is going to handle the ordering for all your variables. Safer to do it in the data:\nheartt['target_label'] = heartt['target'].map({0: 'absent', 1: 'present'})\nax = sns.countplot(x='target_label', hue='sex', data=heartt)\np... | [
0
] | [] | [] | [
"label",
"matplotlib",
"python"
] | stackoverflow_0074354302_label_matplotlib_python.txt |
Q:
Why won't my python program in IDLE let me open and read a file?
I'm trying to open a file named alldata.numbers using this code but I get the error:
FileNotFoundError: [Errno 2] No such file or directory: 'alldata.numbers'
This is my code:
def main():
# Asks user for filename
inName = input("... | Why won't my python program in IDLE let me open and read a file? | I'm trying to open a file named alldata.numbers using this code but I get the error:
FileNotFoundError: [Errno 2] No such file or directory: 'alldata.numbers'
This is my code:
def main():
# Asks user for filename
inName = input("What is the filename? ")
# Open file and read first line
... | [
"changed the code to:\ndef main():\n # Asks user for filename\n inName = input(\"What is the filename for input? \")\n # Open file and read first line\n inFile = open(inName, \"r\")\n for line in inFile:\n inFile = inFile.readline()\n print(inFile)\n return\nmain()\n\nWorks now :)\n"... | [
0
] | [] | [] | [
"computer_science",
"python"
] | stackoverflow_0074354377_computer_science_python.txt |
Q:
KerasRegressor Coefficient of Determination R^2 Score
I'm building a small neural net in Keras meant for a regression task, and I want to use the same accuracy metric as the scikit-learn RandomForestRegressor:
The coefficient R^2 is defined as (1 - u/v), where u is the regression sum of squares ((y_true - y_pred)... | KerasRegressor Coefficient of Determination R^2 Score | I'm building a small neural net in Keras meant for a regression task, and I want to use the same accuracy metric as the scikit-learn RandomForestRegressor:
The coefficient R^2 is defined as (1 - u/v), where u is the regression sum of squares ((y_true - y_pred) ** 2).sum() and v is the residual sum of squares ((y_true ... | [
"you can check this post out. I tested the following code and it works ok for your purpose.\nfrom keras import backend as K\n\ndef coeff_determination(y_true, y_pred):\n SS_res = K.sum(K.square( y_true-y_pred ))\n SS_tot = K.sum(K.square( y_true - K.mean(y_true) ) )\n return ( 1 - SS_res/(SS_tot + K.epsil... | [
36,
1
] | [] | [] | [
"keras",
"python",
"scikit_learn",
"tensor",
"tensorflow"
] | stackoverflow_0045250100_keras_python_scikit_learn_tensor_tensorflow.txt |
Q:
Update cells formatting with the Google Sheets API (Wrapping and Alignment)
I need to wrap and align all the cells in the spreadsheet.
So far, I came up with this request that I send to a spreadsheet with spreadsheet.batch_update
requests =[{
"updateCells": {
"ra... | Update cells formatting with the Google Sheets API (Wrapping and Alignment) | I need to wrap and align all the cells in the spreadsheet.
So far, I came up with this request that I send to a spreadsheet with spreadsheet.batch_update
requests =[{
"updateCells": {
"range": {
"sheetId": self.sheet.id,
... | [
"I believe your goal is as follows.\n\nYou want to reflect \"wrapStrategy\": \"WRAP\" and \"verticalAlignment\": \"TOP\" in all cells in a sheet of Google Spreadsheet using the batchUpdate method of Sheets API.\n\nIn your request body, only cell \"A1\" is used. In order to achieve your goal, how about the following... | [
0
] | [] | [] | [
"google_sheets",
"google_sheets_api",
"gspread",
"python"
] | stackoverflow_0074349894_google_sheets_google_sheets_api_gspread_python.txt |
Q:
Pandas: mapping list from column values to columns?
I got a pandas dataframe like below after prefixspan algorithim and I want to map those into columns.
id ps_results
...
28 [(301, [1-1]), (63, [1-1, 0-5]), (35, [1-1, 1-...
29 [(265, [0-37]), (31, [1-1, 0-5]), (25, [0-1, 1-1, 0-1...
...
For ps_results column,... | Pandas: mapping list from column values to columns? | I got a pandas dataframe like below after prefixspan algorithim and I want to map those into columns.
id ps_results
...
28 [(301, [1-1]), (63, [1-1, 0-5]), (35, [1-1, 1-...
29 [(265, [0-37]), (31, [1-1, 0-5]), (25, [0-1, 1-1, 0-1...
...
For ps_results column, there is a very long list of (frequency, [patterns]), e.... | [
"Not sure if this is what you want. Let me know if not:\na = {\n 'id': ['22', '23'],\n 'ps_results': [[(301, ['1-1']), (63, ['1-1', '0-5']), (35, ['1-1', '1-5']),\n (61, ['1-1', '0-3']), (21, ['1-1', '0-3', '1-1']),\n (125, ['1-1', '1-1']), (32, ['1-1', '1-1', '0-2']),\n ... | [
3
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074313336_dataframe_pandas_python.txt |
Q:
How do I search for and download videos in pytube?
I want to create a song or video downloader in python with pytube. I have only seen that you can download videos if you have the link. I want to use the search feature in pytube and then download the first video that comes up. can you show me a snippet of how you ... | How do I search for and download videos in pytube? | I want to create a song or video downloader in python with pytube. I have only seen that you can download videos if you have the link. I want to use the search feature in pytube and then download the first video that comes up. can you show me a snippet of how you can do this.
I have tried using the search in pytube but... | [
"Google is your friend. Try searching for your answer online before posting a question here.\nRegardless, this code should return a dictionary of results from your search link, link\nfrom pytube import Search\n\ns = Search('Your search here')\nsearchResults = {}\nfor v in s.results:\n searchResults[v.title] = v.wa... | [
0
] | [] | [] | [
"python",
"pytube"
] | stackoverflow_0074354482_python_pytube.txt |
Q:
I want to add a image on python but cant
Ok I have tried almost everything and well im angry and cant figure it out I have tried opening the file but it couldn’t open it because open was undefined then I changed the file name from jpeg to gif even though its not a gif but it loaded but not with the image this is t... | I want to add a image on python but cant | Ok I have tried almost everything and well im angry and cant figure it out I have tried opening the file but it couldn’t open it because open was undefined then I changed the file name from jpeg to gif even though its not a gif but it loaded but not with the image this is the code I got off google but still wasn’t succ... | [
"Your image needs to go inside a Label.\nYou also only need to construct the image once.\nfrom tkinter import *\nimport tkinter as tk\n\n\nfrom PIL import Image\nfrom PIL import ImageTk\nimport tkinter\n\nroot = Tk()\n\nimage = Image.open('Trash.jpg')\nimage = image.resize((20, 20))\nimage = ImageTk.PhotoImage(imag... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074354473_python.txt |
Q:
for Loop: iterating over one value of a list at a time in Python
My problem is that I want to loop over each element of the list one at a time. To elaborate, my list values are, for example, [60, 87, 51]. For the first iteration, I want to iterate over the range of 1 to 60, in the second iteration over the range o... | for Loop: iterating over one value of a list at a time in Python | My problem is that I want to loop over each element of the list one at a time. To elaborate, my list values are, for example, [60, 87, 51]. For the first iteration, I want to iterate over the range of 1 to 60, in the second iteration over the range of 1 to 87, and in the third iteration over the range of 1 to 51.
I tr... | [
"This will get the values you're looking for\nmy_list = [60, 87, 51]\nfor i in my_list:\n for j in range(1, i+1):\n print(j)\n\n"
] | [
2
] | [] | [] | [
"for_loop",
"iteration",
"python",
"range",
"selenium"
] | stackoverflow_0074354483_for_loop_iteration_python_range_selenium.txt |
Q:
Blitting text with pygame2.1 not working correctly
I’m having some problems trying to blit text with pygame2.1.
Here’s some reproducible code:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
font = pygame.font.SysFont("Arial", 50)
text = font.render("Test", True, (255, 255, 255))
text_rect... | Blitting text with pygame2.1 not working correctly | I’m having some problems trying to blit text with pygame2.1.
Here’s some reproducible code:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
font = pygame.font.SysFont("Arial", 50)
text = font.render("Test", True, (255, 255, 255))
text_rect = text.get_rect(center=(250, 250))
run = True
while ru... | [
"The problem is not with the text, it is with pygame.Surface.fill. Replace\nwin.fill(0)\nwin.fill((0, 0, 0)\n\nThis is a known bug in the MacOS version of Pygame 2.1.0 and will be fixed in Pygame 2.1.1.\nSee Fix weird MacOS display surf weirdness #2859.\n",
"So, the issue is that alpha blending is kind of broken ... | [
2,
0
] | [] | [] | [
"pygame",
"python",
"python_3.x"
] | stackoverflow_0070445036_pygame_python_python_3.x.txt |
Q:
importing functions from another jupyter notebook
I am trying to import a function from another jupyter notebook
In n1.ipynb:
def test_func(x):
return x + 1
-> run this
In n2.ipynb:
%%capture
%%run n1.ipynb
test_func(2)
Error:
NameError Traceback (most recent call last)<ipython-input-2-4255cde9aae3> in <module... | importing functions from another jupyter notebook | I am trying to import a function from another jupyter notebook
In n1.ipynb:
def test_func(x):
return x + 1
-> run this
In n2.ipynb:
%%capture
%%run n1.ipynb
test_func(2)
Error:
NameError Traceback (most recent call last)<ipython-input-2-4255cde9aae3> in <module>()
----> 1 test_func(1)
NameError: name 'test_func' i... | [
"The nbimporter module helps us here:\npip install nbimporter\n\nFor example, with two notebooks in this directory structure:\n/src/configuration_nb.ipynb \nanalysis.ipynb\n/src/configuration_nb.ipynb:\nclass Configuration_nb():\n def __init__(self):\n print('hello from configuration notebook')\n\nanalysi... | [
25,
1,
0,
0
] | [] | [] | [
"jupyter_notebook",
"python"
] | stackoverflow_0050576404_jupyter_notebook_python.txt |
Q:
Comparing numerical elements in a list of lists
I've a list of lists that include both a numerical value and a string value
An example of this list would be:
really_big_list = [
[
["A",1], ["B",2], ["C",3]
],
[
["A",2], ["G",2], ["C", 5]
],
[
["A", 2], ["B", 5], ["D", ... | Comparing numerical elements in a list of lists | I've a list of lists that include both a numerical value and a string value
An example of this list would be:
really_big_list = [
[
["A",1], ["B",2], ["C",3]
],
[
["A",2], ["G",2], ["C", 5]
],
[
["A", 2], ["B", 5], ["D", 3]
]
]
What I want to achieve is to check the fi... | [
"Here's how I would do this. I would convert your list of lists to a list of dicts, since that lets Python do the searching.\nThen, I'd use a Counter to count how many times each key occurs. If a key occurs the same number of times as the length of the list, then it must be in every row:\nreally_big_list = [\n ... | [
0
] | [] | [] | [
"list",
"pandas",
"python"
] | stackoverflow_0074354543_list_pandas_python.txt |
Q:
Invalid syntax when starting program with def main(): PS - Total Newb
def main():
print ("1=Square")
print ("2=Triangle")
print ("3=Rectangle")
print("4=Circle")
prob = input ("Enter the problem you have.")
This is the first portion of my code.
When I remove the def main(): my program runs fin... | Invalid syntax when starting program with def main(): PS - Total Newb | def main():
print ("1=Square")
print ("2=Triangle")
print ("3=Rectangle")
print("4=Circle")
prob = input ("Enter the problem you have.")
This is the first portion of my code.
When I remove the def main(): my program runs fine but when I add it I get this error
>>> C:/Users/dalel/AppData/Local/Progr... | [
"Believe that your issue is the same as this one here. That you are trying to run the file from within the python interpreter. If it is, you can exit the python interpreter via exit(). And then from there, navigate to the directory where your file is located, then type:\npython \"ap python project.py\"\n\nAlso make... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074354467_python.txt |
Q:
How to save the contents of a for loop in a variable
Hey so i have a program here that reads into a CSV file which i created earlier
import csv
import psycopg2
with open('C:\\Users\\Danis Porovic\\PycharmProjects\\Module1\\berichten.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for line in csv... | How to save the contents of a for loop in a variable | Hey so i have a program here that reads into a CSV file which i created earlier
import csv
import psycopg2
with open('C:\\Users\\Danis Porovic\\PycharmProjects\\Module1\\berichten.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for line in csv_reader:
print(line)
the for loop gives this as a... | [
"Something like this should do the trick:\nresult = []\nfor line in csv_reader:\n result.append(line)\n\nOr using list comprehension:\nresult = [line for line in csv_reader]\n\nEdit: After comments outlining in more detail what you're looking for. We can transpose the list you usually get so each sublist represe... | [
1
] | [] | [] | [
"csv",
"for_loop",
"python"
] | stackoverflow_0074354644_csv_for_loop_python.txt |
Q:
Why is it in set not in function doesn't work properly?
def anagram(s):
if(len(s)%2==1):
return -1
counter = 0
s1 = s[:len(s)//2]
s2 = s[len(s)//2:]
s1,s2 = set(s1),set(s2)
print(s1)
print(s2)
if s1 not in s2:
counter = counter + 1
return counter
print(anagram(... | Why is it in set not in function doesn't work properly? | def anagram(s):
if(len(s)%2==1):
return -1
counter = 0
s1 = s[:len(s)//2]
s2 = s[len(s)//2:]
s1,s2 = set(s1),set(s2)
print(s1)
print(s2)
if s1 not in s2:
counter = counter + 1
return counter
print(anagram("xyyx"))
Output:
{'x', 'y'}
{'x', 'y'}
1
I'm supposed to ge... | [] | [] | [
"If you are checking for inequality just use !=. Currently you are checking to see if s1 is within s2.\nif s1 != s2:\n counter = counter + 1\n\nOutput:\n{'x', 'y'}\n{'x', 'y'}\n0\n\n"
] | [
-1
] | [
"python",
"python_3.x",
"set"
] | stackoverflow_0074354641_python_python_3.x_set.txt |
Q:
Extension for automatic structuring of methods
I've got a fairly big class where I take a DF as input and store stats about said DF in a instance variable dictionary. For each separate stat I have several methods (for example, getting the data from the DF, calculating the stat and an add method used for __add__). ... | Extension for automatic structuring of methods | I've got a fairly big class where I take a DF as input and store stats about said DF in a instance variable dictionary. For each separate stat I have several methods (for example, getting the data from the DF, calculating the stat and an add method used for __add__). Is there an extension that'll automatically order me... | [
"According to github, although I'm not sure what df is in your article, you can sort the method of your python file in the outline.\n\nAt present, it provides three sorting methods: Position, Name and Category.\n"
] | [
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074301005_python_visual_studio_code.txt |
Q:
Pandas: Stack columns with similar names
I have a table as following:
id
a
b
a
b
123
1
6
7
3
456
2
8
9
7
What function in python can I use to stack the columns with the name names on top of each other like the following?
id
a
b
123
1
6
123
7
3
456
2
8
456
9
7
A:
One option is with pivot_longer from pyja... | Pandas: Stack columns with similar names | I have a table as following:
id
a
b
a
b
123
1
6
7
3
456
2
8
9
7
What function in python can I use to stack the columns with the name names on top of each other like the following?
id
a
b
123
1
6
123
7
3
456
2
8
456
9
7
| [
"One option is with pivot_longer from pyjanitor:\n# pip install pyjanitor\nimport pandas as pd\nimport janitor\n\ndf.pivot_longer(index = 'id', \n names_to = '.value', \n names_pattern = '(.)', \n sort_by_appearance=True) \n id a b\n0 123 1 6\n1 123 7 3\n2 45... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074353463_dataframe_pandas_python.txt |
Q:
pandas: find percentile stats of a given column
I have a pandas data frame my_df, where I can find the mean(), median(), mode() of a given column:
my_df['field_A'].mean()
my_df['field_A'].median()
my_df['field_A'].mode()
I am wondering is it possible to find more detailed stats such as 90 percentile? Thanks!
A:
... | pandas: find percentile stats of a given column | I have a pandas data frame my_df, where I can find the mean(), median(), mode() of a given column:
my_df['field_A'].mean()
my_df['field_A'].median()
my_df['field_A'].mode()
I am wondering is it possible to find more detailed stats such as 90 percentile? Thanks!
| [
"You can use the pandas.DataFrame.quantile() function, as shown below. \nimport pandas as pd\nimport random\n\nA = [ random.randint(0,100) for i in range(10) ]\nB = [ random.randint(0,100) for i in range(10) ]\n\ndf = pd.DataFrame({ 'field_A': A, 'field_B': B })\ndf\n# field_A field_B\n# 0 90 72\n# ... | [
151,
32,
17,
12,
4,
0
] | [] | [] | [
"pandas",
"python",
"python_2.7",
"statistics"
] | stackoverflow_0039581893_pandas_python_python_2.7_statistics.txt |
Q:
Creating a 3d rendering in python with a camera. objects get progressively deformed toward the edge of the screen
So basically, the projection matrix works, as I move the camera arround and look at the cube, there's no problem. But, When I look to the side and the cube should be at the side of the screen, it gets ... | Creating a 3d rendering in python with a camera. objects get progressively deformed toward the edge of the screen | So basically, the projection matrix works, as I move the camera arround and look at the cube, there's no problem. But, When I look to the side and the cube should be at the side of the screen, it gets deformed and scaled back.
From what I heard, the projection matrix is supposed to be:
translate (points - camera)
rot... | [
"Your code is correct. However, you need to translate the cube instead of rotating it. Just try:\nfov = 45 * PI/180\nplayer_pos = np.array([0,0,-4], dtype=np.float32) # <-- dtype=np.float32\n#camera_rot_y = PI/180 * float(input(\"what's the horizontal angle (degrees)?:\"))\n#camera_rot_x = PI/180 * float(input(\... | [
1,
0
] | [] | [] | [
"3d_rendering",
"pygame",
"python"
] | stackoverflow_0074353418_3d_rendering_pygame_python.txt |
Q:
calculating many dask delayed objects together; message as soon as each is finished?
I have a number of dask delayed objects that I am computing together, resulting in files being written to disk, such as in this toy example:
import xarray as xr
import dask.array as da
objs = []
for i in range(10):
ds = xr.Da... | calculating many dask delayed objects together; message as soon as each is finished? | I have a number of dask delayed objects that I am computing together, resulting in files being written to disk, such as in this toy example:
import xarray as xr
import dask.array as da
objs = []
for i in range(10):
ds = xr.Dataset({"x": (("a",), da.arange(10)*i)})
objs.append(ds.to_netcdf(f"/tmp/test{i:d}.nc",... | [
"The simple way to do this is to have a second delayed function which depends on the output of the to_netcdf objects\n@dask.delayed\ndef on_done(result):\n notify(from(result)\n\nobjs2 = [on_done(_) for _ in objs]\ndask.compute(objs2)\n\nThe result will be whatever type to_netcdf returns - hopefully the filename... | [
1
] | [] | [] | [
"dask",
"python"
] | stackoverflow_0074351159_dask_python.txt |
Q:
Replace a value in a data frame from a dictionary using a function map
I have values in a df that i would like to replace with values from a dictionary. My issue is that only one value is being replaced and i expect both to be replaced.
import pandas as pd
d=[['Alabama','English','test@gmail.com']]
df=pd.DataFra... | Replace a value in a data frame from a dictionary using a function map | I have values in a df that i would like to replace with values from a dictionary. My issue is that only one value is being replaced and i expect both to be replaced.
import pandas as pd
d=[['Alabama','English','test@gmail.com']]
df=pd.DataFrame(d,columns=['state','lang','Email'])
replace_dict={
"state":
... | [
"here is one way to do it\n# filter replace_dict by state and lang respectively to map the DF\n\ndf['state']=df['state'].map(replace_dict['state'])\ndf['lang']=df['lang'].map(replace_dict['lang'])\ndf\n\n state lang Email\n0 AL ENG test@gmail.com\n\n"
] | [
0
] | [] | [] | [
"dictionary",
"pandas",
"python"
] | stackoverflow_0074354813_dictionary_pandas_python.txt |
Q:
Find unique elements of floating point array in numpy (with comparison using a delta value)
I've got a ndarray of floating point values in numpy and I want to find the unique values of this array. Of course, this has problems because of floating point accuracy...so I want to be able to set a delta value to use for... | Find unique elements of floating point array in numpy (with comparison using a delta value) | I've got a ndarray of floating point values in numpy and I want to find the unique values of this array. Of course, this has problems because of floating point accuracy...so I want to be able to set a delta value to use for the comparisons when working out which elements are unique.
Is there a way to do this? At the mo... | [
"Another possibility is to just round to the nearest desirable tolerance:\nnp.unique(a.round(decimals=4))\n\nwhere a is your original array.\nEdit: Just to note that my solution and @unutbu's are nearly identical speed-wise (mine is maybe 5% faster) according to my timings, so either is a good solution.\nEdit #2: T... | [
30,
10,
6,
2,
1,
1
] | [] | [] | [
"floating_point",
"numpy",
"python"
] | stackoverflow_0005426908_floating_point_numpy_python.txt |
Q:
Python str.match regex works in main but not within another function
I have files with 6 character codes of the form AANNAA where A=letter and N=number. I want to flag the rows that fit (assign 0) or don't fit (assign 1) that pattern. The following code works in that it identifies codes that don't fit as NaN whe... | Python str.match regex works in main but not within another function | I have files with 6 character codes of the form AANNAA where A=letter and N=number. I want to flag the rows that fit (assign 0) or don't fit (assign 1) that pattern. The following code works in that it identifies codes that don't fit as NaN when it is in main, but gives ValueError: Cannot set a DataFrame with multipl... | [
"The problem\nYou are applying a boolean index to all columns of your dataframe. Attempting to assign this resulting dataframe back to a single column is what causes Pandas to complain -- because you simply can't do that.\nLet's take it step by step. First, look at just the result of doing the regex match:\nIn [8]:... | [
0
] | [] | [] | [
"function",
"pandas",
"python",
"string_matching"
] | stackoverflow_0074354696_function_pandas_python_string_matching.txt |
Q:
determine the range of a value using a look up table
I have a df with numbers:
numbers = pd.DataFrame(columns=['number'], data=[
50,
65,
75,
85,
90
])
and a df with ranges (look up table):
ranges = pd.DataFrame(
columns=['range','range_min','range_max'],
data=[
['A',90,100],
['B',85,95],
['C',70,80]
]
)
I want t... | determine the range of a value using a look up table | I have a df with numbers:
numbers = pd.DataFrame(columns=['number'], data=[
50,
65,
75,
85,
90
])
and a df with ranges (look up table):
ranges = pd.DataFrame(
columns=['range','range_min','range_max'],
data=[
['A',90,100],
['B',85,95],
['C',70,80]
]
)
I want to determine what range (in second table) a value (in the ... | [
"You can use a bit of numpy vectorial operations to generate masks, and use them to select your labels:\nimport numpy as np\n\na = numbers['number'].values # numpy array of numbers\nr = ranges.set_index('range') # dataframe of min/max with labels as index\n\nm1 = (a>=r['range_min'].values[:,None]).T # is number... | [
7,
3,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0069462119_pandas_python.txt |
Q:
LightGBMError: Do not support special JSON characters in feature name - The same code is working in jupyter but doesn't work in Spyder
I have the following code:
most_important = features_importance_chi(importance_score_tresh,
df_user.drop(columns = 'CHURN'),churn)
X = df_user.drop(columns = 'CHURN')
... | LightGBMError: Do not support special JSON characters in feature name - The same code is working in jupyter but doesn't work in Spyder | I have the following code:
most_important = features_importance_chi(importance_score_tresh,
df_user.drop(columns = 'CHURN'),churn)
X = df_user.drop(columns = 'CHURN')
churn[churn==2] = 1
y = churn
# handle undersample problem
X,y = handle_undersampe(X,y)
# train the model
X=X.loc... | [
"You know what, this message is often found on LGBMClassifier () models, i.e. LGBM.\nSimply drop this line at the beginning as soon as you upload the data from the pandas and you have a problem with your head:\nimport re\ndf = df.rename(columns = lambda x:re.sub('[^A-Za-z0-9_]+', '', x))\n\n",
"Here is an alterna... | [
28,
0
] | [] | [] | [
"jupyter",
"lightgbm",
"python",
"spyder"
] | stackoverflow_0060582050_jupyter_lightgbm_python_spyder.txt |
Q:
Match a data frame columns to another data frame rows content
I have a pandas data frame as follows
A
B
C
D
...
Z
and another data frame in which every column has zero or more letters as follows:
Letters
A,C,D
A,B,F
A,H,G
A
B,F
None
I want to match the two dataframes to have something like this
A
B
C
D
... | Match a data frame columns to another data frame rows content | I have a pandas data frame as follows
A
B
C
D
...
Z
and another data frame in which every column has zero or more letters as follows:
Letters
A,C,D
A,B,F
A,H,G
A
B,F
None
I want to match the two dataframes to have something like this
A
B
C
D
...
Z
1
0
1
1
0
0
| [
"make example and desired output for answer\nExample:\ndata = ['A,C,D', 'A,B,F', 'A,E,G', None]\ndf = pd.DataFrame(data, columns=['letter'])\n\ndf :\n letter\n0 A,C,D\n1 A,B,F\n2 A,E,G\n3 None\n\nget_dummies and groupby\npd.get_dummies(df['letter'].str.split(',').explode()).groupby(level=0).sum()\n\noutp... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074354887_dataframe_pandas_python.txt |
Q:
Why does the camera calibration in opencv-python takes more than 30 minutes?
I was trying to replicate this camera calibration code.
When I run my script, the calibration process won't stop for about 30 minutes (I expected the intrinsic camera matrix for the output). What is wrong with my code? Why does the calibr... | Why does the camera calibration in opencv-python takes more than 30 minutes? | I was trying to replicate this camera calibration code.
When I run my script, the calibration process won't stop for about 30 minutes (I expected the intrinsic camera matrix for the output). What is wrong with my code? Why does the calibration process take so long?
This is my code
import os
import cv2
import numpy as n... | [
"The cv2.findChessboardCorners() function's processing time depends a lot on the input image.\n30 minutes on 1K-4K images is not abnormal.\nHave you tried writing the processing time to the console output or a debug log?\nThis way you can find out if certain images take a lot longer than the others. I had a case in... | [
4,
0
] | [] | [] | [
"camera_calibration",
"computer_vision",
"opencv",
"python"
] | stackoverflow_0051073309_camera_calibration_computer_vision_opencv_python.txt |
Q:
Find the rows in which the (aboslute) value is bigger than
I have a pandas dataframe like:
one
two
three
1
3
4
2
4
6
1
3
4
10
3
4
2
4
5
0
3
4
-10
3
4
Now observing the first column (labeled 'one') I would like to find the rows where the value is bigger than say 9. (in this case it would be the fourth )
Id... | Find the rows in which the (aboslute) value is bigger than | I have a pandas dataframe like:
one
two
three
1
3
4
2
4
6
1
3
4
10
3
4
2
4
5
0
3
4
-10
3
4
Now observing the first column (labeled 'one') I would like to find the rows where the value is bigger than say 9. (in this case it would be the fourth )
Ideally, I also would like to find the rows where t... | [
"you can apply abs and compare and filter by loc:\nout = df.loc[df['one'].abs() > 9]\n\noutput :\n>>>\n one two three\n3 10 3 4\n6 -10 3 4\n\n",
"You could use abs() pandas-abs\ndf = pd.DataFrame({\n'a': [1, 4, -6, 3, 7],\n'b': [2, 3, 5, 3, 1],\n'c': [4, 2, 7, 1, 3]\n})\n\ndf[df.a.abs() > 5... | [
1,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074354840_pandas_python.txt |
Q:
How do I create a 2d color gradient plot using matplotlib?
I am trying to create a 2D plot where the 4 quadrants represent four distinct phases. As an example, I want it to look something like this:
Except that I want the center and all the lines of intersection to have more white in them.
In an attempt to this, ... | How do I create a 2d color gradient plot using matplotlib? | I am trying to create a 2D plot where the 4 quadrants represent four distinct phases. As an example, I want it to look something like this:
Except that I want the center and all the lines of intersection to have more white in them.
In an attempt to this, I created a color mixer:
def combine_hex_values(d):
d_items ... | [
"After playing around with a few approaches, these are the nicest results I got using imshow.\nIf you want to use this as an intermediate step towards another method, note that result[i][j] is an array [R,G,B], with each somewhere from 0 to 1.\nn = 100 # resolution along each side\nlighten = .3 # factor by... | [
1
] | [] | [] | [
"heatmap",
"matplotlib",
"python"
] | stackoverflow_0074354104_heatmap_matplotlib_python.txt |
Q:
How to solve invisible captcha on Selenium
Hi I am trying to write a sign-up bot for UEFA.com using Selenium as requests I find to be too difficult for me to try so I am just working on automating the sign-up process even if it is a lot slower.
I am able to get to the final stage where I click on Create an Account... | How to solve invisible captcha on Selenium | Hi I am trying to write a sign-up bot for UEFA.com using Selenium as requests I find to be too difficult for me to try so I am just working on automating the sign-up process even if it is a lot slower.
I am able to get to the final stage where I click on Create an Account, but faced with a reCaptcha which only appears ... | [
"submit the first form on the page:\ndriver.execute_script('document.forms[0].submit()')\n\n"
] | [
0
] | [] | [] | [
"captcha",
"invisible",
"python",
"selenium"
] | stackoverflow_0074346388_captcha_invisible_python_selenium.txt |
Q:
Add new data input prompts to solicit 'meters' or 'feet'
I am stuck on a python program for an assignment. It asks the user to choose a metric of either 'meters' or 'feet'. I use a some if statements and they work but I am not sure how to put the words 'meters' or 'feet' to the numbers after.
if metric == 'meters... | Add new data input prompts to solicit 'meters' or 'feet' | I am stuck on a python program for an assignment. It asks the user to choose a metric of either 'meters' or 'feet'. I use a some if statements and they work but I am not sure how to put the words 'meters' or 'feet' to the numbers after.
if metric == 'meters':
print("Here is your calculated Total Volume:")
print("You e... | [
"Here you go bud\nCode\nmeter = 3.28084\n\nfeet_to_meters = lambda feet: feet / 3.28084\nmeters_to_feet = lambda meters: meters * 3.28084\n\nunit = input('feet or meters? ')\namount = int(input('amount? '))\n\nif unit == 'feet':\n print(f'{amount} feet is {feet_to_meters(amount):.2f} meters')\nelse:\n print(f... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074354854_python.txt |
Q:
405 error when testing an authed django-rest-framework route
I'm testing a CreateAPIView with an APITestCase class. Things are working as expected as an anonymous user, but when I login() as a user, I get a 405 HttpResponseNotAllowed exception. I'm able to successfully create an object while authed as a user throu... | 405 error when testing an authed django-rest-framework route | I'm testing a CreateAPIView with an APITestCase class. Things are working as expected as an anonymous user, but when I login() as a user, I get a 405 HttpResponseNotAllowed exception. I'm able to successfully create an object while authed as a user through the django-rest-framework web frontend. I'm using djangorestfra... | [
"Okay, well there was some course middleware in my application that was interfering with my API requests. The solution was to make a sample course and make my test user a student in that course before making the request.\n",
"For anyone else that ended up here like me looking for answers. I was upgrading my Djang... | [
3,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"rest",
"testing"
] | stackoverflow_0060895576_django_django_rest_framework_python_rest_testing.txt |
Q:
Loop through list of dataframes and save as new dataframe name
I'm trying to loop through a list of dataframes and perform operations on them. In the final command I want to rename the dataframe as the original key plus '_rand_test'. I'm getting the error:
SyntaxError: cannot assign to operator
Is there a way to... | Loop through list of dataframes and save as new dataframe name | I'm trying to loop through a list of dataframes and perform operations on them. In the final command I want to rename the dataframe as the original key plus '_rand_test'. I'm getting the error:
SyntaxError: cannot assign to operator
Is there a way to do this?
segments = [main_h, main_m, main_l]
seg_name = ['main_h', ... | [
"The error is because you are trying to perform addition on the left side of an = sign, which you can never do. If you want to rename the dataframe you could just do it on the next line. I'm unsure of what exactly you're trying to rename based off of the code, but if it's just the corresponding string in the seg_na... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0063926429_dataframe_pandas_python.txt |
Q:
Pandas how to group rows with condition
I want to group two columns together, but only if a specific column is not null, here is some Sudo code for my idea. I'm not sure if this is possible in pandas.
if(df[food] != null):
df['food'].groupby(df['time']).agg('sum')
I was thinking maybe something with NumPy
df['foo... | Pandas how to group rows with condition | I want to group two columns together, but only if a specific column is not null, here is some Sudo code for my idea. I'm not sure if this is possible in pandas.
if(df[food] != null):
df['food'].groupby(df['time']).agg('sum')
I was thinking maybe something with NumPy
df['food'].groupby(df['time']).agg('sum').np(where .... | [
"Well, I don't have any data example so I took an example database from plotly.\ndata=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')\n\nIf I want to group the 'AAPL.High' and 'AAPL.Low' columns together, but only if the 'AAPL.Volume' column is not null, the code sho... | [
0
] | [] | [] | [
"dataframe",
"multiple_columns",
"numpy",
"pandas",
"python"
] | stackoverflow_0074354520_dataframe_multiple_columns_numpy_pandas_python.txt |
Q:
Play multiple sounds with same timestamp
I am writing an AB listenning test app that can play multiple audio files with a shared timestamp. Say I have two audio files loaded which have the same length, when I start to play sound, I click a button to switch between these two files every several seconds and I want t... | Play multiple sounds with same timestamp | I am writing an AB listenning test app that can play multiple audio files with a shared timestamp. Say I have two audio files loaded which have the same length, when I start to play sound, I click a button to switch between these two files every several seconds and I want to preserve the timestamp to continue playing a... | [
"If you are using PyQt5 to create your App, PyQt5.QtMultimedia.QMediaPlayer can do this.\nplayer = QMediaPlayer() # create a player object\n\nplayer.pause() # pause\nposition = self.player.position() # save current playing timestamp\nplayer.setMedia(content) # switch to another content\nplayer.setPosition(position)... | [
1
] | [] | [] | [
"audio",
"python"
] | stackoverflow_0074344154_audio_python.txt |
Q:
Text file representing nested structure to nested dictionary in Python
I have a text file representing multiple different nested structures, here is an example of two.
order product product_X
enabled true
description smartphone
specific routing Y
service service A
instance Yes
routing ip 0.0.0.0
addr... | Text file representing nested structure to nested dictionary in Python | I have a text file representing multiple different nested structures, here is an example of two.
order product product_X
enabled true
description smartphone
specific routing Y
service service A
instance Yes
routing ip 0.0.0.0
address ipv4 0.0.0.0
address-family 0.0.0.0
neighbor x.x.x.x
advertise ... | [
"Are the column names consistent throughout the file? For example, does every level 0 some of the columns [['name', 'enabled', 'description', 'specific routing']]?\nIf so you could try regular expressions. Ie. something like:\norder_idx = []\n\nfor idx, line in enumerate(lines):\n if 'order product' in line:\n ... | [
0
] | [] | [] | [
"json",
"parsing",
"python"
] | stackoverflow_0074355083_json_parsing_python.txt |
Q:
How to do math on tensorflow placeholders with one unknown dimension
I need to do math on a tensorflow placeholder, or the data that is passed into it, with shape (None, 128, 128, 3). I need to add a filter with shape (None, 5, 5, 3) to this placeholder, at location [:, i:i+5, j:j+5, 3]. How would I do this?
Befor... | How to do math on tensorflow placeholders with one unknown dimension | I need to do math on a tensorflow placeholder, or the data that is passed into it, with shape (None, 128, 128, 3). I need to add a filter with shape (None, 5, 5, 3) to this placeholder, at location [:, i:i+5, j:j+5, 3]. How would I do this?
Before I used the data with length None, I would use
outs = tf.tensor_scatter_n... | [
"Creating a Keras layer:\nclass BatchAdd(keras.layers.Layer):\n def __init__(self, i, j):\n super(BatchAdd, self).__init__()\n self.i = i\n self.j = j\n self.add_filter = add_filter\n def call(self, outs, b):\n output = tf.vectorized_map(add_filter,\n ... | [
1
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074353593_keras_python_tensorflow.txt |
Q:
How to Change date format in line chart in Python to YYYY-MM only?
I'm newbie in Python. I have grouped an order using count aggregate by the Month like this :
df4 = (df2.groupby([df2['tanggal_permohonan'].dt.to_period('M').rename('tanggal')])
['no_agenda'].count().rename('jumlah').reset_index())
and it genera... | How to Change date format in line chart in Python to YYYY-MM only? | I'm newbie in Python. I have grouped an order using count aggregate by the Month like this :
df4 = (df2.groupby([df2['tanggal_permohonan'].dt.to_period('M').rename('tanggal')])
['no_agenda'].count().rename('jumlah').reset_index())
and it generated like what I want that grouped in YYYY-MM like this:
Then, I want to... | [
"First, check if your 'tanggal' column is of datetime type\ndf4.dtypes\n\nIf it is not, convert it to datetime\ndf4['tanggal'] = pd.to_datetime(df4['tanggal'])\n\nThen, you could import DateFormatter from matplotlib to plot the axis as YYYY-mm numbers\nfrom matplotlib.dates import DateFormatter\n\ndate_format = Dat... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074355080_matplotlib_python.txt |
Q:
SQLAlchemy joins on one to many
I need help on how to achieve this in SQLAlchemy - joining two tables.
Where
Product - has many Events
Event - belongs to Product
Events table has any of the values
created-invoice
approved-invoice
item-pickup
item-delivered
item-cancelled
I only need the Products where its rela... | SQLAlchemy joins on one to many | I need help on how to achieve this in SQLAlchemy - joining two tables.
Where
Product - has many Events
Event - belongs to Product
Events table has any of the values
created-invoice
approved-invoice
item-pickup
item-delivered
item-cancelled
I only need the Products where its related Event has no item-pickup, item-de... | [
"Ok, I finally make it work\n event_lists = ['item-pickup', 'item-delivered', 'item-cancelled']\n stmt = select(Product.id, Event.event).join(\n Product.events).filter(~Product.events.any(Event.event.in_(event_lists))).group_by(Product.id)\nprint(stmt)\n\n"
] | [
0
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0074335885_python_sql_sqlalchemy.txt |
Q:
Merge several Python dictionaries
I have to merge list of python dictionary. For eg:
dicts[0] = {'a':1, 'b':2, 'c':3}
dicts[1] = {'a':1, 'd':2, 'c':'foo'}
dicts[2] = {'e':57,'c':3}
super_dict = {'a':[1], 'b':[2], 'c':[3,'foo'], 'd':[2], 'e':[57]}
I wrote the following code:
super_dict = {}
for d in dicts:
... | Merge several Python dictionaries | I have to merge list of python dictionary. For eg:
dicts[0] = {'a':1, 'b':2, 'c':3}
dicts[1] = {'a':1, 'd':2, 'c':'foo'}
dicts[2] = {'e':57,'c':3}
super_dict = {'a':[1], 'b':[2], 'c':[3,'foo'], 'd':[2], 'e':[57]}
I wrote the following code:
super_dict = {}
for d in dicts:
for k, v in d.items():
if sup... | [
"You can iterate over the dictionaries directly -- no need to use range. The setdefault method of dict looks up a key, and returns the value if found. If not found, it returns a default, and also assigns that default to the key.\nsuper_dict = {}\nfor d in dicts:\n for k, v in d.iteritems(): # d.items() in Pytho... | [
56,
36,
32,
15,
9,
6,
4,
3,
3,
3,
2,
1,
1,
0,
0
] | [
"This is a more recent enhancement over the prior answer by ElbowPipe, using newer syntax introduced in Python 3.9 for merging dictionaries. Note that this answer does not merge conflicting values into a list!\n> import functools\n> import operator\n\n> functools.reduce(operator.or_, [{0:1}, {2:3, 4:5}, {2:6}])\n\n... | [
-1,
-3
] | [
"dictionary",
"merge",
"python"
] | stackoverflow_0009415785_dictionary_merge_python.txt |
Q:
How to use a character '# in string?
I am trying to conncect MSSQL DB to python, and the DB's password has included a character '#'.
Is there any way to use '#' in string, not changing the password?
A:
You can use the character '#' in a string in python programming language by using the escape character ''.
For ... | How to use a character '# in string? | I am trying to conncect MSSQL DB to python, and the DB's password has included a character '#'.
Is there any way to use '#' in string, not changing the password?
| [
"You can use the character '#' in a string in python programming language by using the escape character ''.\nFor example:\nprint(\"#include <stdio.h>\")\nYou can use the character '#' in a string in Python by putting it inside quotes:\nmy_string = \"This is a string with a # in it\n",
"As somebody has already ans... | [
0,
0
] | [] | [] | [
"python",
"sql_server"
] | stackoverflow_0074355219_python_sql_server.txt |
Q:
Django - Admin user only able to create data. FOREIGN KEY constraint failed for normal users
I'm creating a simple CRUD application to brush up on my Django skills (it's been a long time!) but I'm getting the below errors when I have a non-admin users create anything, either via the frontend or the sites backend:
... | Django - Admin user only able to create data. FOREIGN KEY constraint failed for normal users | I'm creating a simple CRUD application to brush up on my Django skills (it's been a long time!) but I'm getting the below errors when I have a non-admin users create anything, either via the frontend or the sites backend:
FOREIGN KEY constraint failed
I'm also getting this error when I'm logged in as the admin user a... | [
"You are using two different methods of adding data after form validation. Unfortunately you are saving the method that has no data added. I've commented out those lines\n if form.is_valid():\n #activity = form.save(commit=False)\n #you would also need: activity.host = request.user\n #activ... | [
2
] | [] | [] | [
"django",
"django_allauth",
"django_models",
"python"
] | stackoverflow_0074353864_django_django_allauth_django_models_python.txt |
Q:
Error in Importing a bash script into a python
I am trying to create a python script script.py in bash and importing a bash script.
#!/usr/bin/env python
import os
import glob
from fnmatch import fnmatch
# importing a software
python_package = os.system("""#!/path_to_bin/bin/python \
from __future__ import pri... | Error in Importing a bash script into a python | I am trying to create a python script script.py in bash and importing a bash script.
#!/usr/bin/env python
import os
import glob
from fnmatch import fnmatch
# importing a software
python_package = os.system("""#!/path_to_bin/bin/python \
from __future__ import print_function, division \
from python_toolbox.toolbox.... | [
"Nominally the problem is that you are missing the closing paren on the os.system call. But there is a better way to run a python program than trying to write it all on the command line. Instead, you can pass a full script, including newlines, to python's stdin.\n#!/usr/bin/env python \nimport sys\nimport subpro... | [
1
] | [] | [] | [
"bash",
"python"
] | stackoverflow_0074355252_bash_python.txt |
Q:
Python - Extract data inside a Rectangle Box from a PDF file to CSV file
I want to extract data present inside a rectangle box in a PDF file to a CSV file with corresponding columns and rows.
I tried using Camelot, PyPdf2, Tabula libraries etc, but I couldn't get the desired outcome in a CSV file. Could anyone hel... | Python - Extract data inside a Rectangle Box from a PDF file to CSV file | I want to extract data present inside a rectangle box in a PDF file to a CSV file with corresponding columns and rows.
I tried using Camelot, PyPdf2, Tabula libraries etc, but I couldn't get the desired outcome in a CSV file. Could anyone help me here ?
I want this data to be published into a CSV file with respective r... | [
"This really is such a poor quality file the data is too badly bult with errors, such\nthat any means to handle it needs a human key board input.\nthe qr code was refused by several readers\nupi://pay?cu=INR\n&pa=flipkartinternet@hsbc\n&pn=MAHENDRA MAURYA\n&gstIn=07AHTPM2207K1Z2\n&am=0\n&tr=OD124716518958108000\n&t... | [
0
] | [] | [] | [
"data_science",
"pypdf2",
"python",
"python_camelot",
"tabula_py"
] | stackoverflow_0074311522_data_science_pypdf2_python_python_camelot_tabula_py.txt |
Q:
how to convert 2 dimensional list into list of dictionary in python?
I have a 2 dimensional list of list but I would like the list inside the list to be dictionary
list1 = [["ab","cd"],["ef","gh"]]
#code here,
print(output_list_of_dict)
#output should be ...
#[{"name": "ab", "phone":"cd"},{"name": "ef", "phone... | how to convert 2 dimensional list into list of dictionary in python? | I have a 2 dimensional list of list but I would like the list inside the list to be dictionary
list1 = [["ab","cd"],["ef","gh"]]
#code here,
print(output_list_of_dict)
#output should be ...
#[{"name": "ab", "phone":"cd"},{"name": "ef", "phone":"gh"}]
| [
"You can do this directly with a comprehension and tuple unpacking:\nlist1 = [[\"ab\",\"cd\"],[\"ef\",\"gh\"]]\noutput_list_of_dict = [{\"name\": x, \"phone\": y} for x, y in list1]\n\n",
"list1 = [[\"ab\",\"cd\"],[\"ef\",\"gh\"]]\n\nres = []\nfor item in list1:\n res.append({\"name\": item[0], \"phone\": item... | [
2,
1,
1,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074355357_dictionary_list_python.txt |
Q:
how to modify/add character of txt file based on identifier character in each line using python?
I have a txt file and I want to add or change its contents based on the characters on each line,
let's say i wanted to add string "--" on each line but break the iteration when found string "*******" and continue add s... | how to modify/add character of txt file based on identifier character in each line using python? | I have a txt file and I want to add or change its contents based on the characters on each line,
let's say i wanted to add string "--" on each line but break the iteration when found string "*******" and continue add string "--" after found "#######"
Input file
aaaaaaa
bbbbbbb
*******
1234567
7654321
#######
ddddddd
ee... | [
"This is just an idea; maybe this can help you :)\nimport sys\nimport os\n\nfin = os.path.join(sys.path[0], 'abc.txt')\nfout = os.path.join(sys.path[0], 'abc2.txt')\n\nL = []\nwith open(fin, \"r\") as f:\n L = f.readlines()\n\nflag = True\nfor i, line in enumerate(L):\n if (line.startswith(\"*\")):\n f... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074355282_python.txt |
Q:
Converting File into XML Format
Hello I have an Alteryx workflow that I edited and it was in XML format before, only problem is I didint have the option to export in XML.
There is a multitude of choices but went with the FLAT file since it looks close (let me know if there is a better one like json or htm I can us... | Converting File into XML Format | Hello I have an Alteryx workflow that I edited and it was in XML format before, only problem is I didint have the option to export in XML.
There is a multitude of choices but went with the FLAT file since it looks close (let me know if there is a better one like json or htm I can use I have those options as well)
My is... | [
"XML does not require indentation at all, it is just sometimes there for readability.\nIt does require that all nodes are complete, eg this is OK\n<a><b></b></a>\n\nThis is not:\n<a><b></a></b>\n\nYour sample is incomplete so I can't spot the problem, but it certainly can't start with an end tag - </RecordInfo>.\nt... | [
0
] | [] | [] | [
"alteryx",
"python",
"txt",
"xml"
] | stackoverflow_0074355299_alteryx_python_txt_xml.txt |
Q:
(Python ,openCV) capture QR code sticker image from big image
If I capture a picture from production line, how can I extract the part I want from image
from pic - https://ibb.co/k9wfTT0
to pic - https://ibb.co/BKfMx6w
import cv2
im = cv2.imread('/home/joy/桌面/test_11_2/split_img/original.png')
gray=cv2.cvtColor(im... | (Python ,openCV) capture QR code sticker image from big image | If I capture a picture from production line, how can I extract the part I want from image
from pic - https://ibb.co/k9wfTT0
to pic - https://ibb.co/BKfMx6w
import cv2
im = cv2.imread('/home/joy/桌面/test_11_2/split_img/original.png')
gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
contours, hierarchy = cv2.findContours(gray,cv... | [
"by this discussion Set white color outside boundingBox (Python, OpenCV)\nthe code is:\nimport cv2\nimport numpy as np\n\nimage = cv2.imread(\"/home/student_Joy/desktop/test_11_8/original.png\")\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nwhite_bg = 255*np.ones_like(image)\n\nret, thresh = cv2.threshold(gray, ... | [
1
] | [] | [] | [
"computer_vision",
"image",
"opencv",
"python"
] | stackoverflow_0074301151_computer_vision_image_opencv_python.txt |
Q:
Failed to connect to SharePoint site: list index out of range
import sys
import requests
from bs4 import BeautifulSoup
from shareplum.site import Version
from shareplum import Site, Office365
SHAREPOINT_URL = 'https://***************.com/'
SHAREPOINT_SITE = 'https://***********.com/sites/PowerApp/Lists/ch... | Failed to connect to SharePoint site: list index out of range | import sys
import requests
from bs4 import BeautifulSoup
from shareplum.site import Version
from shareplum import Site, Office365
SHAREPOINT_URL = 'https://***************.com/'
SHAREPOINT_SITE = 'https://***********.com/sites/PowerApp/Lists/changed_class_schedule/AllItems.aspx?skipSignal=true'
SHAREPOINT_LIST... | [
"The SharePoint site url should be as follows:\nSHAREPOINT_SITE = 'https://***********.com\nOR\nSHAREPOINT_SITE = 'https://***********.com/sites/PowerApp/\n"
] | [
1
] | [] | [] | [
"list",
"python",
"shareplum",
"sharepoint"
] | stackoverflow_0074315223_list_python_shareplum_sharepoint.txt |
Q:
How to get the last day of the month?
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?
If the standard library doesn't support that, does the dateutil package support this?
A:
calendar.monthrange provides this information:
calendar.monthr... | How to get the last day of the month? | Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?
If the standard library doesn't support that, does the dateutil package support this?
| [
"calendar.monthrange provides this information:\n\ncalendar.monthrange(year, month)\n Returns weekday of first day of the month and number of days in month, for the specified year and month.\n\n>>> import calendar\n>>> calendar.monthrange(2002, 1)\n(1, 31)\n>>> calendar.monthrange(2008, 2) # leap years are hand... | [
1401,
242,
118,
108,
53,
37,
20,
20,
20,
19,
13,
12,
11,
10,
8,
8,
8,
6,
5,
5,
5,
4,
4,
4,
4,
3,
3,
3,
2,
2,
2,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"date",
"python"
] | stackoverflow_0000042950_date_python.txt |
Q:
How would calculate the average, in salaries= { "Ben" : '82,500', "Bob" : '83,750', "Mike": '90,000', "Ann" : '89,000', "Sue" : '80,000' }
Im having issues iterating through the dictionary because of the quotation marks in the values, how would I calculate the average in a dicitonary like this?
I tried to use the ... | How would calculate the average, in salaries= { "Ben" : '82,500', "Bob" : '83,750', "Mike": '90,000', "Ann" : '89,000', "Sue" : '80,000' } | Im having issues iterating through the dictionary because of the quotation marks in the values, how would I calculate the average in a dicitonary like this?
I tried to use the map function to bypass the quotation marks but that didnt work
| [
"You need to first remove the ',' character from the strings then convert them to int to perform the math. Python will coerce the int type once the ',' is removed but it is better to explicitly convert to catch any errors early.\nsalaries= { \"Ben\" : '82,500', \"Bob\" : '83,750', \"Mike\": '90,000', \"Ann\" : '89,... | [
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074354587_dictionary_python.txt |
Q:
Creating a palindrome checker with Python's loop and if statements
I am trying to follow the instructions to create a palindrome. I am given half a function, and I have to fill in the blanks. I am currently unable to get the loop to work correctly. I am also unsure how to add characters to the beginning or the end... | Creating a palindrome checker with Python's loop and if statements | I am trying to follow the instructions to create a palindrome. I am given half a function, and I have to fill in the blanks. I am currently unable to get the loop to work correctly. I am also unsure how to add characters to the beginning or the end of string without using the + or a comma. I do not think that is what I... | [
"It worked for me, I have tried and change little bit from above my code it work now with below code. \nYou can see it pass in their test and code verification, refer below screenshots and code. \n\ndef is_palindrome(input_string):\n # We'll create two strings, to compare them\n new_string = \"\"\n revers... | [
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"This worked perfectly well for me\ndef is_palindrome(input_string):\n # We'll create two strings, to compare them\n new_string = \"\"\n reverse_string = \"\"\n # Traverse through each letter of the input string\n for letter in input_string.lower():\n # Add any non-blank letters to the \n ... | [
-1
] | [
"loops",
"palindrome",
"python"
] | stackoverflow_0060250175_loops_palindrome_python.txt |
Q:
Could I ask how do I know how many pages are in the website? (Web scrapping)
I get a website (https://www.diabetesdaily.com/forum/threads/had-a-friend-with-type-one.136015/)
And I found there are many forum pages
Want to use the for loop for web scrapping, therefore could I ask, how I get the maximum number of fo... | Could I ask how do I know how many pages are in the website? (Web scrapping) | I get a website (https://www.diabetesdaily.com/forum/threads/had-a-friend-with-type-one.136015/)
And I found there are many forum pages
Want to use the for loop for web scrapping, therefore could I ask, how I get the maximum number of forum pages on this page by BeaurifulSoup?
Many thanks.
| [
"You can try something like this:\nimport requests\nfrom bs4 import BeautifulSoup as bs\n\nurl = \"https://www.diabetesdaily.com/forum/threads/had-a-friend-with-type-one.136015/\"\nreq = requests.get(url)\nsoup = bs(req.content, 'html.parser')\nnavs = soup.find(\"ul\", { \"class\" : \"pageNav-main\" }).find_all(\"l... | [
1,
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074355304_beautifulsoup_python.txt |
Q:
File ".stats" when run python in Neovim
I'm a beginner for Neovim recently I have a problem that is when I run any python file immediately after that in my local folder auto-create a new file that has end file name is ".stats".I posted this post wishes someone to can help me. Thank u for reading.
Here my image exa... | File ".stats" when run python in Neovim | I'm a beginner for Neovim recently I have a problem that is when I run any python file immediately after that in my local folder auto-create a new file that has end file name is ".stats".I posted this post wishes someone to can help me. Thank u for reading.
Here my image example:
Here is my init.vim link:
enter link d... | [
"These files generated by pylint. If you have any plugin for auto-linting, which use this linter (such as ALE), .stats files will be generated each time you open/save python files, depending on the plugin settings.\nIf you want to continue using this linter, you can disable generating .stats files by specifying the... | [
1,
0
] | [] | [] | [
"file",
"ide",
"neovim",
"nvim_lspconfig",
"python"
] | stackoverflow_0066677007_file_ide_neovim_nvim_lspconfig_python.txt |
Q:
Intellj Idea python tool - No pytest runner found in selected interpreter
Intellj Idea integrated tool says No pytest runner found in selected interpreter even after python plugin has been installed. Why?
A:
Let the project indexing and Python interpreter update complete. At some point, the pytest gets enabled.
... | Intellj Idea python tool - No pytest runner found in selected interpreter | Intellj Idea integrated tool says No pytest runner found in selected interpreter even after python plugin has been installed. Why?
| [
"Let the project indexing and Python interpreter update complete. At some point, the pytest gets enabled.\nIntellj indexing takes too long so need to be extra patient, or switch to another IDE.\n\n"
] | [
0
] | [] | [] | [
"intellij_idea",
"python"
] | stackoverflow_0074355610_intellij_idea_python.txt |
Q:
trying to make a random meal for the week
i am trying to have a code to give me a list of meals and put the day i will be having this. but when i run it it put its out the same item for the week and repeats that with the next meal. not sure how to fix this.
monday: random meal
tuesday: random meal
wednesday: rando... | trying to make a random meal for the week | i am trying to have a code to give me a list of meals and put the day i will be having this. but when i run it it put its out the same item for the week and repeats that with the next meal. not sure how to fix this.
monday: random meal
tuesday: random meal
wednesday: random meal
thursday: random meal
friday: random mea... | [
"In the following part, you are basically assigning the same thing [random_item] over and over for all week days:\nfor i in db.index:\n random_item = [db[\"meals\"].loc[i]]\n random_item = random.choice(random_item)\n for i in week_days:\n print(f\"{i}: {random_item}\") #here is the... | [
2,
0
] | [] | [] | [
"pandas",
"python",
"random"
] | stackoverflow_0074355414_pandas_python_random.txt |
Q:
How to quiz a User from Dictionary inputs in python?
How can I ask the user the capitals of each state and tell them if they are correct or incorrect? If they are wrong can python reply with the correct answer and tally up their score at the end. I will post what I have below and what I wish for it to show once I ... | How to quiz a User from Dictionary inputs in python? | How can I ask the user the capitals of each state and tell them if they are correct or incorrect? If they are wrong can python reply with the correct answer and tally up their score at the end. I will post what I have below and what I wish for it to show once I run it.
statesAndCapitals={ "Alabama": "Montgomery",
... | [
"Its not a complete answer; its just a simple idea to start :)\nfor x in statesAndCapitals.keys():\n answer = input(f\"What is the capital of {x}? \")\n if (answer == statesAndCapitals[x]):\n print(\"Correct\")\n\n",
"Try this with random.choice\nimport random\nn = 10\nscore = 0\nchoices = list(state... | [
0,
0
] | [] | [] | [
"dictionary",
"python",
"user_input"
] | stackoverflow_0074355437_dictionary_python_user_input.txt |
Q:
Why is there a SyntaxError Python
I wrote this code snippet:
lowestNumber = int(input("\nWhat would you like your lowest number to be?"))
highestNumber = int(input("What would you like your highest number to be?"))
number = random.randint(lowestNumber, highestNumber)
tries = 0
while tries < 10:
guess = int(i... | Why is there a SyntaxError Python | I wrote this code snippet:
lowestNumber = int(input("\nWhat would you like your lowest number to be?"))
highestNumber = int(input("What would you like your highest number to be?"))
number = random.randint(lowestNumber, highestNumber)
tries = 0
while tries < 10:
guess = int(input(f'\nEnter a number between', lowes... | [
"When you wrote\nguess = int(input(f'\\nEnter a number between', lowestNumber))\n\nit passed both the string and lowestNumber into the input function. However, you probably wanted to write something like Enter a number between (lowestNumber) and (highestNumber). To do this, you would have to write\nguess = int(inpu... | [
1
] | [] | [] | [
"input",
"python",
"variables"
] | stackoverflow_0074355664_input_python_variables.txt |
Q:
For loop a values assignment
I have this dataset, where I will use to fill missing values.
In [1]: sex_class = ['female','male']
pclass = [1,2,3]
fill_values = [34,40,29,18,24,25]
In [2]: for i in pclass:
for j in sex_class:
print(i,j)
Out[2]: 1 female
1 male
... | For loop a values assignment | I have this dataset, where I will use to fill missing values.
In [1]: sex_class = ['female','male']
pclass = [1,2,3]
fill_values = [34,40,29,18,24,25]
In [2]: for i in pclass:
for j in sex_class:
print(i,j)
Out[2]: 1 female
1 male
2 female
2 male
... | [
"You could do the following:\nfrom itertools import product\n\nsex_class = ['female','male']\npclass = [1,2,3]\nfill_values = [34,40,29,18,24,25]\n\nfor (p,sex),val in zip(product(pclass,sex_class),fill_values):\n print(f\"{p} {sex:<6} {val}\")\n\nThe resulting output:\n1 female 34\n1 male 40\n2 female 29\n2 m... | [
3,
1,
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074355653_numpy_pandas_python.txt |
Q:
Using sqlalchemy on_conflict_do_update with a condition on the update
I'm trying to use sqlalchemy's on_conflict_do_update function but with a condition on the update.
The idea is when new data comes in, we try to insert unless that primary key already exist. Then we will do an update BUT only if the date_column i... | Using sqlalchemy on_conflict_do_update with a condition on the update | I'm trying to use sqlalchemy's on_conflict_do_update function but with a condition on the update.
The idea is when new data comes in, we try to insert unless that primary key already exist. Then we will do an update BUT only if the date_column is from a later date than what is currently in the db. I understand I'll pro... | [
"I think you actually want where in this case. The use of index_where is kind of nuanced but it seems to only affect which range of index_elements to check for conflict.\nwhere param\nHere is an example I kludged together, I wouldn't take the datetime handling verbatim. This is using 1.4.43 and seems to meet the ... | [
0
] | [] | [] | [
"database",
"orm",
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0074354950_database_orm_postgresql_python_sqlalchemy.txt |
Q:
Combine 2 Query sets and display Django
Im new to django
I am trying to combing two query sets for example, I have different farms. and in those farms they have respective blocks.
I would like to output the farm as a heading and list the blocks of each farm underneath it.
Example:
Farm 1
Block 1
Block 2
Blaock 3
F... | Combine 2 Query sets and display Django | Im new to django
I am trying to combing two query sets for example, I have different farms. and in those farms they have respective blocks.
I would like to output the farm as a heading and list the blocks of each farm underneath it.
Example:
Farm 1
Block 1
Block 2
Blaock 3
Farm 2
Block 1
Block 2
Block 3
What I currentl... | [
"I found a solution using a foreign key.\nUpdated models:\nclass Blocks(models.Model):\n #farm_id = models.CharField(max_length=100) \n farm = models.ForeignKey(Farms, on_delete=models.CASCADE, default=None) \n block_name = models.CharField(max_length=255, null=True)\n block_size = models.CharField(max_length=25... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074260608_django_python.txt |
Q:
'NoneType' object has no attribute 'next' Error Code appears when Removing Nth Node From End of List using Python
Right Now I'm trying my first medium leetcode problem for the first time (Remove Nth Node From End of List) and I'm pretty confident that the code I have should work with it. But for some reason when I... | 'NoneType' object has no attribute 'next' Error Code appears when Removing Nth Node From End of List using Python | Right Now I'm trying my first medium leetcode problem for the first time (Remove Nth Node From End of List) and I'm pretty confident that the code I have should work with it. But for some reason when I it runs, my while-loop for A.Next gives the error:
NoneType' object has no attribute 'next'
# Definition for singly-l... | [
"head is Optional, which means that it could be None when it is passed to the function. You should check if head is None first before assigning a, b, and c.\n",
"Here is what's going on. Your while loop checks a.next != b, which will never be true, hence a becomes equal to None eventually and the check a.next whe... | [
0,
0
] | [] | [] | [
"algorithm",
"data_structures",
"linked_list",
"python"
] | stackoverflow_0074353845_algorithm_data_structures_linked_list_python.txt |
Q:
Running default eventhub function returns "unexpected status code: 400"
Running the basic azure function template for "Azure Event Hub trigger":
import logging
import azure.functions as func
def main(event: func.EventHubEvent):
logging.info('Python EventHub trigger processed an event: %s',
e... | Running default eventhub function returns "unexpected status code: 400" | Running the basic azure function template for "Azure Event Hub trigger":
import logging
import azure.functions as func
def main(event: func.EventHubEvent):
logging.info('Python EventHub trigger processed an event: %s',
event.get_body().decode('utf-8'))
I'm getting unexpected status code: 400 wh... | [
"Ensure you have all the configuration settings configured properly such as:\nfunction.json:\n{\n\"scriptFile\": \"__init__.py\",\n\"bindings\": [\n{\n\"type\": \"eventHubTrigger\",\n\"name\": \"event\",\n\"direction\": \"in\",\n\"eventHubName\": \"kdemoeventhub\",\n\"connection\": \"krisheventhubns_RootManageShare... | [
1
] | [] | [] | [
"azure_eventhub",
"azure_functions",
"python"
] | stackoverflow_0074296595_azure_eventhub_azure_functions_python.txt |
Q:
Python Try-Except vs If-Else performance
Someone recently said to me "In Python it is better to try and ask for forgiveness later instead of begging for permission" which I found quite funny but also relates to my question
I'm creating a personal assistant of sorts called Ada and was being pedantic about performan... | Python Try-Except vs If-Else performance | Someone recently said to me "In Python it is better to try and ask for forgiveness later instead of begging for permission" which I found quite funny but also relates to my question
I'm creating a personal assistant of sorts called Ada and was being pedantic about performance. From what I gather, using a try statement ... | [
"The performance of try vs. if-else depends.\nGenerally, it is considered more pythonic to use try blocks because:\n\nYou do an action\nIf it fails then do something else\n\nThe benefit here is that if the action fails you can specify an exact error and react accordingly or keep the exception at the Base Exception ... | [
0,
0
] | [] | [] | [
"performance",
"python",
"try_catch",
"windows"
] | stackoverflow_0065130870_performance_python_try_catch_windows.txt |
Q:
How can I aggregate a column's value based on the min() and max() values of another column?
I have the following data-frame, df, that is population with 1000+ rows of data. Here is what it would look like:
date mkt bid ask
0 01/07/22 LWAPO 0.6451 0.6460
1 01/07/22 HUYNE ... | How can I aggregate a column's value based on the min() and max() values of another column? | I have the following data-frame, df, that is population with 1000+ rows of data. Here is what it would look like:
date mkt bid ask
0 01/07/22 LWAPO 0.6451 0.6460
1 01/07/22 HUYNE 0.6452 0.6458
2 01/07/22 VERAS 0.6447 0.6457
3 02/07/22 HUYNE 0.6432... | [
"get name of bid max and name of ask min\ndf1 = (df.groupby('date')\n .agg({'bid': lambda x: df.loc[x.idxmax(), 'mkt'],\n 'ask': lambda x: df.loc[x.idxmin(), 'mkt']})\n .reset_index())\n\ndf1:\n date bid ask\n0 01/07/22 HUYNE VERAS\n1 02/07/22 HUYNE HUYNE\n2 03/... | [
2,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074355462_pandas_python.txt |
Q:
I'm VERY new to coding, but I'm trying to figure out why my print function is not resulting in what I'm expecting. Any idea?
I've created a class named Patient that has attributes for patient information. I'm supposed to use an accessor and mutator method for each attribute. Then I've created another file to acces... | I'm VERY new to coding, but I'm trying to figure out why my print function is not resulting in what I'm expecting. Any idea? | I've created a class named Patient that has attributes for patient information. I'm supposed to use an accessor and mutator method for each attribute. Then I've created another file to access the class and insert patient information to print. Every time I print I don't get what I expect but I get <Assignment4Q1PatientC... | [
"What did you expect from your print statement?\nThe class actually don't \"know\" what to print. You must provide a way to represent that class as a string, so we can print that string.\nIn practice, we do this by adding a function called \"__repr__\", the representation of this class. Python automatically identif... | [
0
] | [] | [] | [
"attributes",
"class",
"function",
"init",
"python"
] | stackoverflow_0074355769_attributes_class_function_init_python.txt |
Q:
how can I get month from date in django models
I want to make a query and return only the month of the year of the date field from my models then compare the return result to the current month of the year.
current_date = datetime.date.today()
_history = PayrollModel.objects.filter(employee_id_id=employee_i... | how can I get month from date in django models | I want to make a query and return only the month of the year of the date field from my models then compare the return result to the current month of the year.
current_date = datetime.date.today()
_history = PayrollModel.objects.filter(employee_id_id=employee_id)
if(_history == None or _history.count() == 0)... | [
"Filtering by month is a built-in queryset feature. You don't show your History model, so I am writing as if the relevant date stamp field is called xdate (date might read confusingly)\nSo you need to further filter:\ntoday = datetime.date.today()\ncurrent_year = today.year\ncurrent_month = today.month\n_history ... | [
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0071411604_django_django_models_python.txt |
Q:
Accessing Graph API using Python <401> Error Code
I am having trouble accessing Microsoft graph after receiving a token from /token. I'm including photos of the Azure AD Application Setup as well as code. Any assistance would be greatly appreciated.
I am able to receive a bearer token from Microsoft, but it is ret... | Accessing Graph API using Python <401> Error Code | I am having trouble accessing Microsoft graph after receiving a token from /token. I'm including photos of the Azure AD Application Setup as well as code. Any assistance would be greatly appreciated.
I am able to receive a bearer token from Microsoft, but it is returning <401> Invalid Audience
I cannot yet post images,... | [
"Could you please try by using tenantId \"common\" ,\nand use POST login.microsoftonline.com/common/oauth2/v2.0/token\nplease see the docs for more info - https://learn.microsoft.com/en-us/graph/auth-v2-user#token-request\n\nHope this helps\nThanks\n"
] | [
0
] | [] | [] | [
"microsoft_graph_api",
"python"
] | stackoverflow_0074350281_microsoft_graph_api_python.txt |
Q:
What is the python version of this Powershell command?
Looking to convert this powershell code into python:
$secretArgs = @{
fileName = "test.pem"
fileAttachment = [IO.File]::ReadAllBytes("C:\brian\13568-test.txt")
} | ConvertTo-Json
*Update:
I am trying this code to get a similar result:
import json
tes... | What is the python version of this Powershell command? | Looking to convert this powershell code into python:
$secretArgs = @{
fileName = "test.pem"
fileAttachment = [IO.File]::ReadAllBytes("C:\brian\13568-test.txt")
} | ConvertTo-Json
*Update:
I am trying this code to get a similar result:
import json
test_file = open("test.txt", "rb")
test_file_name = "test.txt"
... | [
"import json\n\nsecretArgs = {\"fileName\": \"test.pem\"}\n\nwith open(\"test.pem\", \"r\") as f:\n data = f.read()\nraw_bytes = list(bytearray(data, \"utf-8\"))\nsecretArgs[\"fileAttachment\"] = list(bytes(raw_bytes))\nprint(json.dumps(secretArgs))\n\n",
"I created a small test file to see what the powershell... | [
0,
0
] | [] | [] | [
"powershell",
"python"
] | stackoverflow_0074341649_powershell_python.txt |
Q:
sqlalchemy InvalidRequestError
I'm using flask-sqlalchemy, this is not the first relations that i've built, but for some reason it gives me an error when i start flask:
sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapp... | sqlalchemy InvalidRequestError | I'm using flask-sqlalchemy, this is not the first relations that i've built, but for some reason it gives me an error when i start flask:
sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class User->users'. Orig... | [
"This is subtle but messages in this case is a table so columns are referenced off of c, like messages.c.sender_id. To use the column of the model class (the mapped class) you would do Message.sender_id.\nSo...\nmessages_sent = db.relationship('Message', foreign_keys='messages.c.sender_id',\n ... | [
0
] | [] | [] | [
"flask",
"flask_sqlalchemy",
"model",
"python",
"sqlalchemy"
] | stackoverflow_0074348403_flask_flask_sqlalchemy_model_python_sqlalchemy.txt |
Q:
How to use '#' character in INI file?
I am having a trouble with connecting MSSQL to python using Configparser, and one of DB's password has included a character '#'.
Since we don't use escape character " in INI file, then how should I use a character #? (byw, I can't change the password :( )
A:
The # character ... | How to use '#' character in INI file? | I am having a trouble with connecting MSSQL to python using Configparser, and one of DB's password has included a character '#'.
Since we don't use escape character " in INI file, then how should I use a character #? (byw, I can't change the password :( )
| [
"The # character is used to start a comment in an INI file. Anything after the # on the same line is ignored by the INI parser.\n"
] | [
0
] | [] | [] | [
"configparser",
"ini",
"pymssql",
"python",
"sql_server"
] | stackoverflow_0074355867_configparser_ini_pymssql_python_sql_server.txt |
Q:
Iterate indexed list with sed for python SLURM script
My goal is to iterate two indexed lists of start_times and output_directories, using sed to change the start time within runConfig.sh and the output directory within HISTORY.rc before each job submission (36 in total).
The script is written in python and uses o... | Iterate indexed list with sed for python SLURM script | My goal is to iterate two indexed lists of start_times and output_directories, using sed to change the start time within runConfig.sh and the output directory within HISTORY.rc before each job submission (36 in total).
The script is written in python and uses os.system() to deploy linux bash commands, see below:
##-> K... | [
"Your variable interpolation is bash syntax, not python's one.\nWould you please try instead:\nsed_1 = f\"sed -i 's|Start_Time=.*|Start_Time=\\\"{StrTi_List[j]}\\\"|' ./runConfig.sh\"\nsed_2 = f\"sed -i 's|EXPID:.*|EXPID:\\\"{Dir_List[j]}\\\"|' ./HISTORY.rc\"\n\nIf your python is older than 3.6, here are the altern... | [
0
] | [] | [] | [
"bash",
"hpc",
"python",
"sed",
"slurm"
] | stackoverflow_0074354393_bash_hpc_python_sed_slurm.txt |
Q:
How to set up a linear programming model (transportation problem) using python/PuLp
I am working on a transportation/replenishment model wherein I need to solve for lowest cost. The variables are:
Warehouses - several possible origin points of a shipment.
Items - in this example I only use two items. Each Item-St... | How to set up a linear programming model (transportation problem) using python/PuLp | I am working on a transportation/replenishment model wherein I need to solve for lowest cost. The variables are:
Warehouses - several possible origin points of a shipment.
Items - in this example I only use two items. Each Item-Store combination has a unique demand value.
Inventory - available inventory for each 'Item... | [
"This is good. Your model is set up well. Let's talk about supply...\nSo this is a common transshipment model and you want to minimize cost, but the default answer is to ship nothing for a cost of zero, which is not good. As you know, you need upward pressure on the deliveries to meet demand, or at least do the ... | [
0
] | [] | [] | [
"linear_programming",
"optimization",
"pulp",
"python"
] | stackoverflow_0074354772_linear_programming_optimization_pulp_python.txt |
Q:
Why do I get type error when using scipy.optimize.curve_fit to do a least squares fit test?
I'm trying to fit a function using curve_fit from the scipy.optimize module. I keep getting the error message:
"TypeError: only size-1 arrays can be converted to Python scalars'.
frequency = []
for i in driven_period:
... | Why do I get type error when using scipy.optimize.curve_fit to do a least squares fit test? | I'm trying to fit a function using curve_fit from the scipy.optimize module. I keep getting the error message:
"TypeError: only size-1 arrays can be converted to Python scalars'.
frequency = []
for i in driven_period:
frequency.append(2*math.pi*i**-1)
amplitude = []
for i in driven_height:
amplitude.append... | [
"I think I figuered it out:\nPython seems to have trouble multiplying arrays ( ** operator as well as math library). Switching over to np for calculations works. Sadly I can’t explain in depth why :/\nimport math\nimport numpy as np\n\ndriven_period = [1.027, 0.949, 0.866, 0.806, 0.648, 0.917, 0.935, 1.404, 1.113, ... | [
0
] | [] | [] | [
"curve_fitting",
"python",
"scipy_optimize",
"typeerror"
] | stackoverflow_0074354633_curve_fitting_python_scipy_optimize_typeerror.txt |
Q:
Removing symbols and spaces in strings without using if statements?
So I need to go through a loop and apply conditional statement in every element inside the matrices' rows.
conditions need to be checked:
whether the elements is alphabet or not, if yes append it if not go for next conditional checking
next check... | Removing symbols and spaces in strings without using if statements? | So I need to go through a loop and apply conditional statement in every element inside the matrices' rows.
conditions need to be checked:
whether the elements is alphabet or not, if yes append it if not go for next conditional checking
next checking should be checking if its symbol/non-alphabet AND its next element(i ... | [
"We can easily avoid conditional statements with the help of regular expressions. In particular,\nimport re\nclinput2=[['T', 'h', 'i', 's', '$', '#', 'i'], \n ['s', '%', ' ', 'S', 'p', 'a', 'r'], \n ['t', 'a', '#', ' ', ' ', '%', '!']]\n\nmat_str = ''.join(c for row in clinput2 for c in row)\npr... | [
1,
1
] | [] | [] | [
"if_statement",
"loops",
"matrix",
"python"
] | stackoverflow_0074355350_if_statement_loops_matrix_python.txt |
Q:
How to understand the .hdf5 file annotations for ShanghaiTech A and B?
I am looking at the ShanghaiTech A and B datasets which are used for crowd counting
which can be found at this link https://github.com/desenzhou/ShanghaiTechDataset
I notice that each image is accompanied with a .mat file and a .hdf5 file.
.mat... | How to understand the .hdf5 file annotations for ShanghaiTech A and B? | I am looking at the ShanghaiTech A and B datasets which are used for crowd counting
which can be found at this link https://github.com/desenzhou/ShanghaiTechDataset
I notice that each image is accompanied with a .mat file and a .hdf5 file.
.mat file
The .mat file contains coordinates of each head as well as the ground ... | [
"Ok i found out...\nto parse and understand the MAT file\nimport scipy\nfrom scipy.io import loadmat\nimport pandas as pd\nimport numpy as np\nimport cv2 \n\n#specify your file directories here \nimg_dir = \"A1.jpg\" \nmatfile_dir = 'GT_IMG_1.mat'\n\n#opening base image to draw on later \ninput_image = cv2.imread(i... | [
0
] | [] | [] | [
"computer_vision",
"numpy",
"opencv",
"python"
] | stackoverflow_0073470133_computer_vision_numpy_opencv_python.txt |
Q:
Reading a file AND printing the number of words
I have to write a code that reads a file and counts the number of words in the file.
So far I am able to either print the file or count the number of numbers but I am unable to print them both without the other one automatically cancelling out.
My file:
This is a fil... | Reading a file AND printing the number of words | I have to write a code that reads a file and counts the number of words in the file.
So far I am able to either print the file or count the number of numbers but I am unable to print them both without the other one automatically cancelling out.
My file:
This is a files
that
has different
lengths of lines
My code:
fil... | [
"When you call .read() it moves the read marker to the end of the file so when you call .read() again, you're already at the end.\nReplace\nprint(file.read())\ndata = file.read()\n\nwith\ndata = file.read()\nprint(data)\n\nSo you're only reading the file once.\n"
] | [
2
] | [] | [] | [
"file",
"python"
] | stackoverflow_0074356000_file_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.