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:
Pyspark DataFrame, how to do a Group by aggregation function like Standard Deviation
Pyspark & Pandas Data Frame, how to do a Group by aggregation function like Standard Deviation
data = [['_1','S1',12, 112, 14],
['_2','S1',120, 112, 114],
['_3','S2',88, 92, 74],
['_4','S2',17, 118, 133],
... | Pyspark DataFrame, how to do a Group by aggregation function like Standard Deviation | Pyspark & Pandas Data Frame, how to do a Group by aggregation function like Standard Deviation
data = [['_1','S1',12, 112, 14],
['_2','S1',120, 112, 114],
['_3','S2',88, 92, 74],
['_4','S2',17, 118, 133],
['_5','S2',19, 19, 14],
['_6','S2',11, 12, 14]]
columns = ['RowNum','School... | [
"I think you're looking for something like this:\nimport pyspark.sql.functions as f\ncolumn_list = ['Subject_1', 'Subject_2', 'Subject_3']\ndf = (\n df\n .groupBy('School')\n .agg(\n *[\n *[f.stddev(f.col(element)).alias(f'stddev_{element}') for element in column_list],\n *[f.m... | [
1
] | [] | [] | [
"pandas",
"pyspark",
"python"
] | stackoverflow_0074117496_pandas_pyspark_python.txt |
Q:
Take numbers from a list in a specific order in Python
I would like to remove the numbers from the list of three in three positions and then store them in a new list. I thought of doing something like n+3 but don´t know how to implement it.
[1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 1, 6, 1, 4, 7, 2, 4, 8, 4, 6, 9... | Take numbers from a list in a specific order in Python | I would like to remove the numbers from the list of three in three positions and then store them in a new list. I thought of doing something like n+3 but don´t know how to implement it.
[1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 1, 6, 1, 4, 7, 2, 4, 8, 4, 6, 9, 6, 5]
This is my list and I would like to create a new li... | [
"As far as I understand, you want to pick one element in every three elements. For that, you can use slicing [::3], where 3 means the step size:\nlst = [1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 1, 6, 1, 4, 7, 2, 4, 8, 4, 6, 9, 6, 5]\n\noutput = lst[::3]\nprint(output) # [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n",
"Using s... | [
1,
0,
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074118160_list_python_python_3.x.txt |
Q:
AWS cli windows - still getting "'aws' is not recognized..." after adding path to environment variables?
Following instructions found here (and elsewhere) I added '%USERPROFILE%\AppData\Roaming\Python\Python37\Scripts\aws' to Path (tried with and without \aws at the end)
I clicked OK everywhere and restartet the ... | AWS cli windows - still getting "'aws' is not recognized..." after adding path to environment variables? | Following instructions found here (and elsewhere) I added '%USERPROFILE%\AppData\Roaming\Python\Python37\Scripts\aws' to Path (tried with and without \aws at the end)
I clicked OK everywhere and restartet the CLI, but I am still getting "'aws' is not recognized as an internal or external command,
operable program or b... | [
"if this is in a windows machine By default, the CLI installs to C:\\Program Files\\Amazon\\AWSCLI (64-bit version) or C:\\Program Files (x86)\\Amazon\\AWSCLI (32-bit version). So I guess the PATH that you've added is incorrect.\ntry checking this link https://docs.aws.amazon.com/cli/latest/userguide/install-window... | [
9,
1
] | [] | [] | [
"amazon_web_services",
"command_line_interface",
"python",
"windows"
] | stackoverflow_0055712835_amazon_web_services_command_line_interface_python_windows.txt |
Q:
Use .pt file to analyze an image
I'm really new in AI, so sorry for the conception mistakes I can do. I do have a .pt file, and I want to use it to get some bounding boxes of a picture. What's the most simple way to do it? Something like:
import torch
model=torch.load('best.pt')
img=['foto.jpg']
results = model(im... | Use .pt file to analyze an image | I'm really new in AI, so sorry for the conception mistakes I can do. I do have a .pt file, and I want to use it to get some bounding boxes of a picture. What's the most simple way to do it? Something like:
import torch
model=torch.load('best.pt')
img=['foto.jpg']
results = model(img)
results.show()
Thank you very much... | [
"using\nSyntax – torch.utils.draw_bounding_boxes(image, box)\n\nParameter:\n\nimage: Tensor of shape (C x H x W) \nbox: Bounding boxes size in (xmin, ymin, xmax, ymax).\nReturn: Image Tensor of dtype uint8 with bounding boxes plotted.\n\n# Import the required libraries\nimport torch\nimport torchvision\nfrom torchv... | [
0
] | [] | [] | [
"artificial_intelligence",
"object_detection",
"python",
"pytorch"
] | stackoverflow_0074118204_artificial_intelligence_object_detection_python_pytorch.txt |
Q:
create a column Identify duplicate on certain columns within a pyspark window
I am trying to identify the duplicates on column b and c for different id_number within the same group. I tried to use window partitioned by group and id_number but couldn't get through the situation in group d, which is omitting the dup... | create a column Identify duplicate on certain columns within a pyspark window | I am trying to identify the duplicates on column b and c for different id_number within the same group. I tried to use window partitioned by group and id_number but couldn't get through the situation in group d, which is omitting the duplicate that happens for the same id_number.
Here is the code to create the spark df... | [
"I think you're looking for something like this:\nimport pyspark.sql.functions as f\ndf = (\n df\n .withColumn('dups', f.count(f.col('id_number')).over(Window.partitionBy('group', 'b', 'c')) - 1)\n)\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pyspark",
"python"
] | stackoverflow_0074117374_dataframe_pyspark_python.txt |
Q:
Why is VLC's .py modue returning 'NoneType' in 'media_player_new'?
I've been running around in circles for a few weeks, and can't get past an infuriating problem... firstly; I'm running 64-bit Win10, with 64-bit Powershell invoking python 3.9 (also 64-bit), which is an app with a Tk GUI, and uses python-vlc. It's ... | Why is VLC's .py modue returning 'NoneType' in 'media_player_new'? | I've been running around in circles for a few weeks, and can't get past an infuriating problem... firstly; I'm running 64-bit Win10, with 64-bit Powershell invoking python 3.9 (also 64-bit), which is an app with a Tk GUI, and uses python-vlc. It's been running fine for weeks on a laptop, and I'm now trying to get it wo... | [
"Whilst talking with the developer community over here, the issue fixed itself. https://github.com/oaubert/python-vlc/issues/170\nOur closing comments included our best guess: A Windows internal cache somewhere. I deleted the DLLs from system32 in preparation for doing yet another reinstall. I tested the program, a... | [
0,
0
] | [] | [] | [
"libvlc",
"python",
"python_3.x",
"python_vlc",
"vlc"
] | stackoverflow_0066377541_libvlc_python_python_3.x_python_vlc_vlc.txt |
Q:
Concatenating numpy vector and matrix horizontally
I have the following numpy vector m and matrix n
import numpy as np
m = np.array([360., 130., 1.])
n = np.array([[60., 90., 120.],
[30., 120., 90.],
[1., 1., 1. ]])
What I want to do is to concatenate them horizontally resulting in... | Concatenating numpy vector and matrix horizontally | I have the following numpy vector m and matrix n
import numpy as np
m = np.array([360., 130., 1.])
n = np.array([[60., 90., 120.],
[30., 120., 90.],
[1., 1., 1. ]])
What I want to do is to concatenate them horizontally resulting in
np.array([[60., 90., 120.,360.],
[30., 120.,... | [
">>> np.hstack((n,np.array([m]).T))\narray([[ 60., 90., 120., 360.],\n [ 30., 120., 90., 130.],\n [ 1., 1., 1., 1.]])\n\nThe issue is that since m has only one dimension, its transpose is still the same. You need to make it have shape (1,3) instead of (3,) before you take the transp... | [
12,
3,
0
] | [] | [] | [
"arrays",
"matrix",
"numpy",
"python"
] | stackoverflow_0033405219_arrays_matrix_numpy_python.txt |
Q:
Does Python optimize tail recursion?
I have the following piece of code which fails with the following error:
RuntimeError: maximum recursion depth exceeded
I attempted to rewrite this to allow for tail recursion optimization (TCO). I believe that this code should have been successful if a TCO had taken place.
d... | Does Python optimize tail recursion? | I have the following piece of code which fails with the following error:
RuntimeError: maximum recursion depth exceeded
I attempted to rewrite this to allow for tail recursion optimization (TCO). I believe that this code should have been successful if a TCO had taken place.
def trisum(n, csum):
if n == 0:
... | [
"No, and it never will since Guido van Rossum prefers to be able to have proper tracebacks:\nTail Recursion Elimination (2009-04-22)\nFinal Words on Tail Calls (2009-04-27)\nYou can manually eliminate the recursion with a transformation like this:\n>>> def trisum(n, csum):\n... while True: #... | [
294,
210,
24,
9,
5,
4,
2,
0
] | [] | [] | [
"python",
"recursion",
"tail_recursion"
] | stackoverflow_0013591970_python_recursion_tail_recursion.txt |
Q:
Pivoting DataFrame in Python Pandas
I'm trying to pivot my df from wide to long, and I am attempting to replicate R's dplyr::pivot_longer() function. I have tried pd.wide_to_long() and pd.melt() but have had no success in correctly formatting the df. I also attempted using df.pivot() and come to the same conclusio... | Pivoting DataFrame in Python Pandas | I'm trying to pivot my df from wide to long, and I am attempting to replicate R's dplyr::pivot_longer() function. I have tried pd.wide_to_long() and pd.melt() but have had no success in correctly formatting the df. I also attempted using df.pivot() and come to the same conclusion.
Here is what a subset of the df (calle... | [
"The stack() function is useful to achieve your objective, then reformat as needed:\npd.DataFrame( df.stack() ).reset_index(drop=False).rename(columns={'level_0':'store', 'level_1':'Date', 0:'Value'})\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"pivot",
"python",
"r"
] | stackoverflow_0074118315_dataframe_pandas_pivot_python_r.txt |
Q:
One sample T-test in python not giving the desired output
I have a dataframe called df_salaire that has age, marital status,...., number of working hours per week,...
I want to test if the number of working hours per week is around 40h per week, I used to dataframe.mean() and the output was 40.37
However, when I t... | One sample T-test in python not giving the desired output | I have a dataframe called df_salaire that has age, marital status,...., number of working hours per week,...
I want to test if the number of working hours per week is around 40h per week, I used to dataframe.mean() and the output was 40.37
However, when I t test using ttest_1samp like this:
ttest, pval = ttest_1samp(np... | [
"Your issue is one of statistics, not of coding. \"Around\" 40 hours is a very fuzzy concept. If you're dealing with the amount of time someone works, 40.37 is \"around\" 40 hours. If you're dealing with computer uptime in microseconds, then 40.37 may not be close enough to 40.00000 hours to be acceptable.\nSo what... | [
1
] | [] | [] | [
"hypothesis_test",
"python"
] | stackoverflow_0074118138_hypothesis_test_python.txt |
Q:
Python Pandas - Transform dataframe into key (multi index) => value table
current_df = pd.DataFrame(
[
['honda crv', 9000, 9100, 9200],
['mazda cx5', 9300, 10000, 10100],
['mazda cx5', 29300, 310000, 510100],
],
columns=['car', 'john', 'peter', 'kate']
)
How do I transform th... | Python Pandas - Transform dataframe into key (multi index) => value table | current_df = pd.DataFrame(
[
['honda crv', 9000, 9100, 9200],
['mazda cx5', 9300, 10000, 10100],
['mazda cx5', 29300, 310000, 510100],
],
columns=['car', 'john', 'peter', 'kate']
)
How do I transform this into dataframe with multiple index ['car', 'salesman']?
From this
To this
| [
"Building on Simons answer (which should be accepted), to also get the correct headers add the following.\ncurrent_df = (\n pd\n .DataFrame(current_df.set_index(\"car\").stack())\n .rename(columns={0: \"price\"})\n .rename_axis((\"car\", \"salesman\"))\n)\nprint(current_df)\n\n price... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074118232_dataframe_pandas_python.txt |
Q:
How to create dataframe with skipping few header of column
I have data frame like(This dataframe may have more data with different Candidate):
Candidate Name Subject Keyword Count
User1 optional devops 1
User1 mandatory aws 0
User1 mandatory ec2 1... | How to create dataframe with skipping few header of column | I have data frame like(This dataframe may have more data with different Candidate):
Candidate Name Subject Keyword Count
User1 optional devops 1
User1 mandatory aws 0
User1 mandatory ec2 1
User1 optional python 1
User1 opt... | [
"df2=(df.pivot_table(index='Candidate_Name', \n columns=['Subject', 'Keyword'], \n values='Count', aggfunc=sum)\n .reset_index()\n .rename_axis(columns=[None, None])\n )\ndf2\n\n\n mandatory optional\n aws dotnet ec2 devops java p... | [
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074117980_dataframe_numpy_pandas_python.txt |
Q:
Pygame when moving into another object the player object should stop
I'm working on this prototype in pygame where you control a square and I'm currently working on collisions with other objects. When the player collides with the object, the player should not be able to move into the object.
import pygame,sys
pyg... | Pygame when moving into another object the player object should stop | I'm working on this prototype in pygame where you control a square and I'm currently working on collisions with other objects. When the player collides with the object, the player should not be able to move into the object.
import pygame,sys
pygame.init()
Clock = pygame.time.Clock()
FPS = 60
size = [1000,800]
bg = [0,... | [
"See How do I detect collision in pygame?. Use pygame.Rect/colliderect to detect collisions of rectangles.\nStore the position of the player\nplayer_pos = player.x, player.y\n\nMove the palyer:\nplayer.do()\n\nSet up a rectangle for the player and the obstacle:\nplayer_rect = pygame.Rect(player.x, player.y, 50, 50)... | [
2,
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074117058_pygame_python.txt |
Q:
Subset sum problem for a possible closest value to the target sum in Python for a really big list
I know this problem may have been asked by many. My challenge is that my list is long in length (say 100+) and my target may also be big. The recursive algorithm takes 10 minutes to complete. I need any one subset tha... | Subset sum problem for a possible closest value to the target sum in Python for a really big list | I know this problem may have been asked by many. My challenge is that my list is long in length (say 100+) and my target may also be big. The recursive algorithm takes 10 minutes to complete. I need any one subset that makes it closest to the target-sum
My Code
combination_dict = {}
def subset_sum(numbers, target, par... | [
"You can use integer linear programming where each variable is a binary that corresponds to a number and represents whether that number is included in the result. It solves two problems, the first approaching the target value from below and the second from above and then takes the best solution. The following is an... | [
1,
0
] | [] | [] | [
"python",
"subset_sum",
"time_complexity"
] | stackoverflow_0071034015_python_subset_sum_time_complexity.txt |
Q:
Python file encrypting
I am trying to write a program that will encrypt a file by using the .read() function on the file content, which returns 98\xf1\xc6}xb1\*.... I am trying to encrypt the file by looping through each character an incrementing its decimal number by 1 (numbers range from 0 -> 255). and then addi... | Python file encrypting | I am trying to write a program that will encrypt a file by using the .read() function on the file content, which returns 98\xf1\xc6}xb1\*.... I am trying to encrypt the file by looping through each character an incrementing its decimal number by 1 (numbers range from 0 -> 255). and then adding each incremented number t... | [
"You could change:\nf.write(self.new_values) \n\nto:\nf.write(''.join(self.new_values).encode('latin-1'))\n\ncombining the list of str into a single str, then encoding it to latin-1 (which is the 1-1 mapping of the first 256 Unicode ordinals to bytes of the same values).\nBut the real solution is to change:\ndef co... | [
2
] | [] | [] | [
"encoding",
"encryption",
"file",
"file_encodings",
"python"
] | stackoverflow_0074118013_encoding_encryption_file_file_encodings_python.txt |
Q:
How to get the whole row with column names while looking for a minimum value?
I have a data frame. There are four columns.
I can find a minimum number using this code:
df_temp=df_A2C.loc[ (df_A2C['TO_ID'] == 7)]
mini_value = df_temp['DURATION_H'].min()
print("minimum value in column 'TO_ID' is: " , mini_value)
... | How to get the whole row with column names while looking for a minimum value? | I have a data frame. There are four columns.
I can find a minimum number using this code:
df_temp=df_A2C.loc[ (df_A2C['TO_ID'] == 7)]
mini_value = df_temp['DURATION_H'].min()
print("minimum value in column 'TO_ID' is: " , mini_value)
Output:
minimum value in column 'TO_ID' is: 0.434833333333333
Now, I am trying to... | [
"if you post the data as a code or text, I would have been able to share the result\nassumption: you're searching for a minimum value for a specific to_id\n# as per your code, filter out by to_id\n# sort the result on duration and take the top value\n\ndf_A2C.loc[ (df_A2C['TO_ID'] == 7)].sort_values('DURATION_H').h... | [
4
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074118450_dataframe_jupyter_notebook_pandas_python_python_3.x.txt |
Q:
Rank specific columns of 2D arrays inside a 3D Array
I have many 2D arrays inside of a 3D array.
Let’s assume that shape of the 3D array is (3, 5, 5). Therefore, I have 3 2D Arrays of shape (5, 5).
Column #4 (idx of 3) in each 2D array has a certain value as per below. I want to replace those values with correspo... | Rank specific columns of 2D arrays inside a 3D Array | I have many 2D arrays inside of a 3D array.
Let’s assume that shape of the 3D array is (3, 5, 5). Therefore, I have 3 2D Arrays of shape (5, 5).
Column #4 (idx of 3) in each 2D array has a certain value as per below. I want to replace those values with corresponding ranks in descending order. The highest value will co... | [
"I suggest:\narr[:, :, 3] = arr[:, :, 3].argsort(axis=1).argsort(axis=1) + 1\n\nNote that using argsort twice is necessary to obtain \"ranks\".\n"
] | [
1
] | [] | [] | [
"numpy",
"python",
"ranking"
] | stackoverflow_0074118401_numpy_python_ranking.txt |
Q:
matplotlib plt.yticks precisely on y values (multiple lines)
I have this plot:
I would like to show the exact prices where the markers "o" are.
Current code is:
plt.figure(figsize=(18,10))
plt.plot(visas_df["years"],visas_df["published_finals"],color='green',marker="o");
plt.plot(visas_df["years"],visas_df["expir... | matplotlib plt.yticks precisely on y values (multiple lines) | I have this plot:
I would like to show the exact prices where the markers "o" are.
Current code is:
plt.figure(figsize=(18,10))
plt.plot(visas_df["years"],visas_df["published_finals"],color='green',marker="o");
plt.plot(visas_df["years"],visas_df["expired_finals"],color='red',marker="o");
plt.plot(visas_df["years"],vi... | [
"After some aeons of fidgeting with matplotlib, I managed to put the values on the markers.\nThis was done by using matplotlib. axes.Axes. text\nChanges to the code below:\nfig,ax=plt.subplots(figsize=(25,15))\n\nThe following code uses ax.text and is duplicated 3 times since I have 3 lines.\nfor i in range(len(vis... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074109259_matplotlib_python.txt |
Q:
PPMI of scipy sparse matrix
I need to transform a scipy matrix in sparse csr format into a PPMI-weighted matrix. I have a sparse squared co-occurrence matrix with each row and column corresponding to words, and each entry mat(i, j) corresponding to the number of times these words were found together in a corpus.
H... | PPMI of scipy sparse matrix | I need to transform a scipy matrix in sparse csr format into a PPMI-weighted matrix. I have a sparse squared co-occurrence matrix with each row and column corresponding to words, and each entry mat(i, j) corresponding to the number of times these words were found together in a corpus.
Here is a minimal example of how t... | [
"from scipy.sparse import csr_matrix\nimport numpy as np\n\narr = np.random.rand(100,50)\nsarr = csr_matrix(arr)\n\nDon't operate on a matrix by looping over elements, this is something that can be done without that.\n# Calculate the probability vectors for p_i and p_j (inverted, so it's 1/p)\n# Then fix any non-fi... | [
1,
0
] | [] | [] | [
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0074100126_python_scipy_sparse_matrix.txt |
Q:
I am completely lost in how to make my program loop
This is a rock paper scissors program and I need help making it loop at least three times. Here is the code if you need it.
import random
#welcome
Welcome = input("welcome please choose the following options (press enter)")
while True:
#Options (Rock, Paper, Sci... | I am completely lost in how to make my program loop | This is a rock paper scissors program and I need help making it loop at least three times. Here is the code if you need it.
import random
#welcome
Welcome = input("welcome please choose the following options (press enter)")
while True:
#Options (Rock, Paper, Scissor) Make sure to use capital letters
player1 = input("R... | [
"You can add a for loop inside your code,\nimport random\n\n#welcome\nWelcome = input(\"welcome please choose the following options (press enter)\")\nplay = True\nwhile play:\n for _ in range(3):\n print(f\"Round : {_+1}\")\n player1 = input(\"Rock, Paper, Scissors : \")\n player2 = random.c... | [
0,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074118483_loops_python.txt |
Q:
filter dataframe based on path graph (network problem)
I have this data frame:
df = {'col1': ['a', 'b', 'c', 'd', 'e', 'w', 't', 'y', 'r', 's', 'n', 'm', 'p'],
'col2': ['b', 'c','d','e','f', 'x', 'z', 'w', 'w', 'n', 'm', 'p', 'q'],
'col3': [1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 12, 13]}
or in the fo... | filter dataframe based on path graph (network problem) | I have this data frame:
df = {'col1': ['a', 'b', 'c', 'd', 'e', 'w', 't', 'y', 'r', 's', 'n', 'm', 'p'],
'col2': ['b', 'c','d','e','f', 'x', 'z', 'w', 'w', 'n', 'm', 'p', 'q'],
'col3': [1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 12, 13]}
or in the form of
col1 col2 col3
0 a b 1
1 b c 2
2 ... | [
"Essentially what you're trying to do is get rid of nodes in components of the graph in which the longest path includes fewer than 4 nodes (3 edges). The following code should accomplish that, if (and only if) your limit is 3 or fewer edges. If you're looking to expand it to components with 4 or more edges, you'l... | [
0
] | [] | [] | [
"dataframe",
"networkx",
"pandas",
"python"
] | stackoverflow_0074112283_dataframe_networkx_pandas_python.txt |
Q:
'DataFrameGroupBy' object is not callable
I'm trying to extract these columns from this data sheet in Google Collab using pandas, but I keep getting the error "'DataFraneGroupBy' object is not callable" and I can't figure out why.
Here's the data sheet I'm working with:
https://files.catbox.moe/m6x7w0.xlsx
Any hel... | 'DataFrameGroupBy' object is not callable | I'm trying to extract these columns from this data sheet in Google Collab using pandas, but I keep getting the error "'DataFraneGroupBy' object is not callable" and I can't figure out why.
Here's the data sheet I'm working with:
https://files.catbox.moe/m6x7w0.xlsx
Any help would be greatly appreciated.
| [
"There are a couple of issues:\n\nin your group by you need to include an aggregate function at the end (.count() or .sum() or etc.)\nthe result of JustOfficeSuppliesOrderID is a data frame, you need to call a function to data frames. I think you want to see the head or tail so try JustOfficeSuppliesOrderID.head(10... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074118484_pandas_python.txt |
Q:
Exporting to Excel Using Openpyxl - specific rows and columns
I have tried succesfuly to populate the data in QTableWidget using Pandas.
Now i want to export to specific rows and columns to an existing excel so i will not lose stylesheet and other data from this excel. Please , help me out finding the solution to... | Exporting to Excel Using Openpyxl - specific rows and columns | I have tried succesfuly to populate the data in QTableWidget using Pandas.
Now i want to export to specific rows and columns to an existing excel so i will not lose stylesheet and other data from this excel. Please , help me out finding the solution to run it properly.
Goal is to export to excel to specific rows and c... | [
"I solved the problem like this:\nfrom openpyxl import Workbook\nwb = Workbook()\nwb = load_workbook ('OFERTA_SZABLON.xlsx')\n# ws1 = wb.sheetnames()\nws1 = wb[\"DETALE wyceniane osobno\"]\n\n# for r in dataframe_to_rows(df, index=False, header=False):\n# ws1.append(r)\noffset_row = 5 \noffset_col = 0\n\... | [
0,
0
] | [] | [] | [
"excel",
"openpyxl",
"pandas",
"python",
"qtablewidget"
] | stackoverflow_0068608318_excel_openpyxl_pandas_python_qtablewidget.txt |
Q:
Selecting rows based on a '>' condition of the iteration of one of the columns
I have not been able to come up with a better title, it's a really simple issue though, I just don't know what to call it exactly.
I have a database of horses simplified here:
horse_name
stable_name
Horse1
Stable1
I am only intereste... | Selecting rows based on a '>' condition of the iteration of one of the columns | I have not been able to come up with a better title, it's a really simple issue though, I just don't know what to call it exactly.
I have a database of horses simplified here:
horse_name
stable_name
Horse1
Stable1
I am only interested in further analyzing records which feature stables that own many horses s... | [
"Try this out\nIf you post the data, I would have been able to share the result\n# create a temporary column 'c' by grouping on stable\n# transform associates the result to all rows that are part of groupby\n# we then check for 'c' and where its value is true\n\n(df[df.assign(c=df.groupby(['Stable'],as_index=False)... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074118560_pandas_python.txt |
Q:
Flask page not refreshing in the browser after xmlHttpRequest() send
I am using an event listener to intercept a form submission, wait for a confirmation and then submit the form using xmlHttpRequest. The POST to my page seems to be working (meaning I can detect all the form fields I would expect) however, at the ... | Flask page not refreshing in the browser after xmlHttpRequest() send | I am using an event listener to intercept a form submission, wait for a confirmation and then submit the form using xmlHttpRequest. The POST to my page seems to be working (meaning I can detect all the form fields I would expect) however, at the end of the Flask view handler code, the redirect does not cause the browse... | [
"Using the JavaScript fetch() instead of the XMLHttpRequest() worked for me to solve my issue. The fetch() function POSTS the data and I can use the .then() clause to redirect to the location after the fetch().\nI was able to use code like below to POST all the fields from the form submit, intercepted by my event l... | [
0
] | [] | [] | [
"flask",
"javascript",
"python"
] | stackoverflow_0074104355_flask_javascript_python.txt |
Q:
Module networkx has no atribute bipartite_random_graph
I want to construct a random bipartite graph with networkx, but I get
AttributeError: module networkx has no attribute bipartite_random_graph
Does anyone know how to resolve this issue? I've seen on stackoverflow that other people had the same problem with oth... | Module networkx has no atribute bipartite_random_graph | I want to construct a random bipartite graph with networkx, but I get
AttributeError: module networkx has no attribute bipartite_random_graph
Does anyone know how to resolve this issue? I've seen on stackoverflow that other people had the same problem with other functions which could be resolved by importing the right ... | [
"If you're version 2.8.7 of NetworkX, the docs indicate that either of the following should work:\nfrom networkx.algorithms import bipartite\ng = bipartite.random_graph(3, 2, 0.5, seed = None, directed = False)\n\nOr (without importing the bipartite algorithms separately):\ng = nx.bipartite.random_graph(3, 2, 0.5, ... | [
1
] | [] | [] | [
"networkx",
"python",
"python_3.x",
"random_forest"
] | stackoverflow_0074114007_networkx_python_python_3.x_random_forest.txt |
Q:
Triangle identification generator
If all three angles are 60, output Equilateral
If the three angles add up to 180 and exactly two of the angles are the same, output Isosceles
If the three angles add up to 180 and no two angles are the same, output Scalene
If the 3 angles do not add up to 180 or any of the an... | Triangle identification generator | If all three angles are 60, output Equilateral
If the three angles add up to 180 and exactly two of the angles are the same, output Isosceles
If the three angles add up to 180 and no two angles are the same, output Scalene
If the 3 angles do not add up to 180 or any of the angles are 0 or negative, output Not a ... | [
"Your program gives several different answers because your conditions overlap (for example, if a == 60 AND b == 60 AND c == 60 is true, then a == b is true too). Note that it's actually mathematically correct, because an equilateral triangle is a particular isosceles triangle. But, for the purpose of this program, ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074118362_python.txt |
Q:
Is there a way to make a chain of variables, each one being dependent on the one that came before?
Im triyng to make a program that takes into account the number of one variable (chosen at random) to decide the value of the next, and i need to repeat this 11 times (so n3 would depend of n2, n4 of n3, etc.) the id... | Is there a way to make a chain of variables, each one being dependent on the one that came before? | Im triyng to make a program that takes into account the number of one variable (chosen at random) to decide the value of the next, and i need to repeat this 11 times (so n3 would depend of n2, n4 of n3, etc.) the idea would be a code like:
def rayuela_cuerpo():
n2 = random.choice([0,1])
if n2 == 0:
n3 ... | [
"A way that you could do what you are saying is to do:\ndef random_simulation(entry_number): # generate a random number based on the input number given to the function\n if entry_number == 0:\n return random.choice([1,3]) # returns the value to where this function was called\n elif entry_number == 1:\n... | [
0,
0
] | [] | [] | [
"python",
"random",
"variables"
] | stackoverflow_0074104775_python_random_variables.txt |
Q:
Can someone please tell me why my code for Checking if two strings are anagram doesnt work
This is my code :
string_1 = input("Enter a string : ")
string_2 = input("Enter a second string : ")
a = sorted(string_1)
b = sorted(string_2)
print(a)
print(b)
if a in b and len(a) == len(b):
print("these strings are an... | Can someone please tell me why my code for Checking if two strings are anagram doesnt work | This is my code :
string_1 = input("Enter a string : ")
string_2 = input("Enter a second string : ")
a = sorted(string_1)
b = sorted(string_2)
print(a)
print(b)
if a in b and len(a) == len(b):
print("these strings are anagram")
else:
print("these strings are not anagram")
For example :
Input:
Enter a string ... | [] | [] | [
"you should try with this one. I changed the condition.\nstring_1 = input(\"Enter a string : \")\nstring_2 = input(\"Enter a second string : \")\na = sorted(string_1)\nb = sorted(string_2)\nprint(a)\nprint(b)\nif sorted(a) == sorted(b):\nprint(\"these strings are anagram\")\nelse:\n print(\"these strings are not... | [
-1
] | [
"anagram",
"arrays",
"list",
"python",
"python_3.x"
] | stackoverflow_0074118651_anagram_arrays_list_python_python_3.x.txt |
Q:
Python converting Django model.datetime from 24hr to AM/PM?
So I have this model field in Django that stores time in YYYY-MM-DD HH:MM:SS, here is how its created.
station_0_checked_time = models.DateTimeField(
null = True,
default = datetime.datetime(1970, 1, 1, 0, 0)
)
The data is stored prop... | Python converting Django model.datetime from 24hr to AM/PM? | So I have this model field in Django that stores time in YYYY-MM-DD HH:MM:SS, here is how its created.
station_0_checked_time = models.DateTimeField(
null = True,
default = datetime.datetime(1970, 1, 1, 0, 0)
)
The data is stored properly as verified by the admin section of my Django site.
Station ... | [
"You just have to manually format it when you need to see it in the correct format\nview.py\nfrom datetime import datetime\n\nprint(SUBCARD.station_0_checked_time.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\nPython strftime cheatsheet: https://strftime.org/\ntemplate.html\n{{ SUBCARD.station_0_checked_time|date:'Y-m-d H:i:s... | [
0
] | [] | [] | [
"datetime",
"django",
"python"
] | stackoverflow_0074117883_datetime_django_python.txt |
Q:
pd.concat not stacking columns with same names
I'm in awe that this isn't working because I've done this a hundred times. I want to stack two dataframes vertically and pandas is creating duplicate columns and refusing to put the data in the right columns.
df1 looks like this:
df2 looks like this:
then I run this... | pd.concat not stacking columns with same names | I'm in awe that this isn't working because I've done this a hundred times. I want to stack two dataframes vertically and pandas is creating duplicate columns and refusing to put the data in the right columns.
df1 looks like this:
df2 looks like this:
then I run this:
frames = [df1,df2]
final = pd.concat(frames, ignor... | [
"Try\ncheck the column names, there might be white spaces that results in mis-alignment of column after the concat.\ndisplay(df1.columns, df2.columns)\n\n# make axis=0 and remove ignore_index\n\nfinal = pd.concat(frames, axis = 0)\nfinal\n\n"
] | [
1
] | [] | [] | [
"concatenation",
"pandas",
"python"
] | stackoverflow_0074118729_concatenation_pandas_python.txt |
Q:
How to convert a 2D array of seconds to a 2D array of datetime in python?
I have an large 2D array contains seconds from year 2000, I want to convert to an array of datetime. I could not find a good way to do it. I used a loop. But it did not work and it produced an error as:
TypeError: float() argument must be a ... | How to convert a 2D array of seconds to a 2D array of datetime in python? | I have an large 2D array contains seconds from year 2000, I want to convert to an array of datetime. I could not find a good way to do it. I used a loop. But it did not work and it produced an error as:
TypeError: float() argument must be a string or a number, not 'datetime.datetime'
I give the example code as below. W... | [
"There are three parts of this problem:\n\nConvert \"seconds from 2000\" to standard Unix timestamps (seconds after 1970)\nConvert Unix timestamp to datetime\nDo this for every element of the array\n\nFor 1, if we call the \"seconds from 2000\" figure t', and the standard Unix time is t, you can see that t - t' = x... | [
1
] | [] | [] | [
"arrays",
"datetime",
"python"
] | stackoverflow_0074118703_arrays_datetime_python.txt |
Q:
Can't access in any way dynamically generated element with Selenium
I've been trying to modify the router SSIDs through a script made in Selenium, the problem is that I can't get any JS element that's generated by the router page. I've been trying with the Expected Conditions and whatever you could think of but wi... | Can't access in any way dynamically generated element with Selenium | I've been trying to modify the router SSIDs through a script made in Selenium, the problem is that I can't get any JS element that's generated by the router page. I've been trying with the Expected Conditions and whatever you could think of but without success.
Example of commands that I used:
element: WebElement = Web... | [
"\nWhat I found is that if I try to select any element using any query selector before inspecting any element on the page it won't work.\n\nThat tells me that your desired element is inside of an IFRAME. When you inspect an element on the page, the dev tools automatically switch the context to the containing IFRAME... | [
1
] | [] | [] | [
"dom",
"javascript",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074114862_dom_javascript_python_selenium_web_scraping.txt |
Q:
How can I detect base noun in a word?
I have a project about database tables. I have to figure out which table is related to the others. For example; In my database, I have two tables. One of them's name is 'product' and another one's name is DimProduct. These are related to each other. I used an algorithm. It det... | How can I detect base noun in a word? | I have a project about database tables. I have to figure out which table is related to the others. For example; In my database, I have two tables. One of them's name is 'product' and another one's name is DimProduct. These are related to each other. I used an algorithm. It detects containment relationships.
Here comes ... | [
"I'll try and answer the question, although strictly speaking, you should probably re-structure your database and relationships to a more suitable schema, incorporating the relationships within tables, rather than using the table name. For \"base nouns\", there are several things you can try:\n\nTo split up the wor... | [
0
] | [] | [] | [
"database",
"nlp",
"python"
] | stackoverflow_0074072968_database_nlp_python.txt |
Q:
Calculating FID scores for GAN models between two different image directory
I am calculating FID (Frechet Inception Distance) score of my CycleGAN model using this reference. I have input photos in a directory and generated 'artistic' photos in another directory.
input_photo_path = 'data/'
art_photo_path = 'images... | Calculating FID scores for GAN models between two different image directory | I am calculating FID (Frechet Inception Distance) score of my CycleGAN model using this reference. I have input photos in a directory and generated 'artistic' photos in another directory.
input_photo_path = 'data/'
art_photo_path = 'images/'
import PIL
import numpy as np
import glob
def convert_image_to_numpy(image_p... | [
"The FID computation doesn't depend on the ordering of images. It takes the statistics of the entire dataset (i.e it calculates the mean and covariance across the feature dimension for all the examples present in the dataset). So, the ordering doesn't matter.\nHere's the pytorch implementation: https://github.com/m... | [
0
] | [] | [] | [
"deep_learning",
"python",
"tensorflow"
] | stackoverflow_0070719562_deep_learning_python_tensorflow.txt |
Q:
How to retry after exception?
I have a loop starting with for i in range(0, 100). Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will continue in the except clause (continue on to the next number for i).
Is it possible for me to reassign... | How to retry after exception? | I have a loop starting with for i in range(0, 100). Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will continue in the except clause (continue on to the next number for i).
Is it possible for me to reassign the same number to i and run throu... | [
"Do a while True inside your for loop, put your try code inside, and break from that while loop only when your code succeeds.\nfor i in range(0,100):\n while True:\n try:\n # do stuff\n except SomeSpecificException:\n continue\n break\n\n",
"I prefer to limit the numb... | [
519,
314,
107,
48,
28,
15,
11,
9,
7,
5,
5,
5,
4,
3,
3,
3,
2,
2,
1,
1,
1,
1,
1,
0,
0
] | [
"Here's my idea on how to fix this:\nj = 19\ndef calc(y):\n global j\n try:\n j = j + 8 - y\n x = int(y/j) # this will eventually raise DIV/0 when j=0\n print(\"i = \", str(y), \" j = \", str(j), \" x = \", str(x))\n except:\n j = j + 1 # when the exception happens, incremen... | [
-3,
-3,
-11
] | [
"exception",
"loops",
"python",
"try_except"
] | stackoverflow_0002083987_exception_loops_python_try_except.txt |
Q:
Which way to run javascript code in a python loop is more efficient?
I'm executing JavaScript code in python selenium while loop script, what would be the fastest way this loop could run?
python while-loop:
while not k.is_pressed('key'):
driver.execute_script(js_code)
js_code (Is looking for one button 'btn1'... | Which way to run javascript code in a python loop is more efficient? | I'm executing JavaScript code in python selenium while loop script, what would be the fastest way this loop could run?
python while-loop:
while not k.is_pressed('key'):
driver.execute_script(js_code)
js_code (Is looking for one button 'btn1', when it is available it clicks it and then another button should appear ... | [
"This will click on whichever is available and not raise an error if they're both missing\ndocument.querySelector(\".btn1,.btn2\")?.click()\n\n"
] | [
0
] | [] | [] | [
"javascript",
"python",
"selenium"
] | stackoverflow_0074115407_javascript_python_selenium.txt |
Q:
How do I append to a file?
How do I append to a file instead of overwriting it?
A:
Set the mode in open() to "a" (append) instead of "w" (write):
with open("test.txt", "a") as myfile:
myfile.write("appended text")
The documentation lists all the available modes.
A:
You need to open the file in append mode... | How do I append to a file? | How do I append to a file instead of overwriting it?
| [
"Set the mode in open() to \"a\" (append) instead of \"w\" (write):\nwith open(\"test.txt\", \"a\") as myfile:\n myfile.write(\"appended text\")\n\nThe documentation lists all the available modes.\n",
"You need to open the file in append mode, by setting \"a\" or \"ab\" as the mode. See open().\nWhen you open ... | [
2936,
255,
59,
48,
41,
24,
14,
12,
8,
6,
4,
1
] | [
"The simplest way to append more text to the end of a file would be to use:\nwith open('/path/to/file', 'a+') as file:\n file.write(\"Additions to file\")\nfile.close()\n\nThe a+ in the open(...) statement instructs to open the file in append mode and allows read and write access.\nIt is also always good practic... | [
-4
] | [
"append",
"file",
"python"
] | stackoverflow_0004706499_append_file_python.txt |
Q:
Separate unique and common nested structures across nested dictionaries in Python
I will have N different nested dictionaries where the different nested structures will have varying depth.
d1 = {'A' : {'B' : 1, 'C': {'D' : 2 } } }
d2 = {'A' : {'C' : {'D' : 2 } , 'E' : 3, 'F' : { 'G' : {'H' : 3 } } } }
..
Wha... | Separate unique and common nested structures across nested dictionaries in Python | I will have N different nested dictionaries where the different nested structures will have varying depth.
d1 = {'A' : {'B' : 1, 'C': {'D' : 2 } } }
d2 = {'A' : {'C' : {'D' : 2 } , 'E' : 3, 'F' : { 'G' : {'H' : 3 } } } }
..
What I want to do, is separate any common and unique structrures across ALL dictionaries.
... | [
"You have hierarchical (nested) dictionary values,\nwith identifiers along each path from root down to leaf.\nTurn such paths into something hashable,\nsuch as tuple or str,\nand throw them into a set that describes d1.\nNow iterate similarly over d2 and compute set intersection,\nnoting any d2 paths that also appe... | [
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074118769_dictionary_python.txt |
Q:
Pygame: Alien Invasion Ship Image
Hi I am currently trying to create space invasion from chapter 12 in Python Crash Course. However I am stuck when trying to add the ship image to the game. Here is the code for Alien Invasion:
import sys
import pygame
from settings import Settings
from ship import Ship
class Alien... | Pygame: Alien Invasion Ship Image | Hi I am currently trying to create space invasion from chapter 12 in Python Crash Course. However I am stuck when trying to add the ship image to the game. Here is the code for Alien Invasion:
import sys
import pygame
from settings import Settings
from ship import Ship
class AlienInvasion:
#Overall class to manage game... | [
"This question comes up a lot, so I'll aim for a canonical answer.\nBasically the code is trying to load a file, but it is assuming it's running in the same directory as the files it needs. This problem isn't limited to Python or PyGame, it's a general programming problem. It becomes more of a problem when PyGame... | [
2,
0,
0
] | [] | [] | [
"image",
"load",
"pygame",
"python",
"traceback"
] | stackoverflow_0062684694_image_load_pygame_python_traceback.txt |
Q:
Finding a minimum value in a data frame with multiple columns
I am trying to get the whole row value with column names while looking for a minimum value
Using FROM_ID and TO_ID. Something like this
I have a data frame which looks like this:
I have 43 From_ID values and nearly 16622 TO_ID values.
To keep it simpl... | Finding a minimum value in a data frame with multiple columns | I am trying to get the whole row value with column names while looking for a minimum value
Using FROM_ID and TO_ID. Something like this
I have a data frame which looks like this:
I have 43 From_ID values and nearly 16622 TO_ID values.
To keep it simple, I started working with TO_ID==7 and consider all FROM_ID.
Here i... | [
"This df_A2C.loc[ (df_A2C['TO_ID'] == 7)].sort_values('DURATION_H').head(1) give you an output as:\n\nThen, you can use a for loop to check the whole data frame.\nDo this:\nfor i in range(1, len(df_A2C), 1):\n newDF= df_A2C.loc[(df_A2C['TO_ID'] == i)].sort_values('DURATION_H').head(1)\n print(newDF)\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074117968_dataframe_pandas_python.txt |
Q:
Referencing Twitter Tokens
Let's say I wanted to perform a twitter sentiment analysis and I didn't want my access token and api keys in my python document but I wanted to reference them in this manner,
api_key = mykeys[0]
api_secret = mykeys[1]
access_token = mykeys[2]
access_token_secret = mykeys[3]
How do I sav... | Referencing Twitter Tokens | Let's say I wanted to perform a twitter sentiment analysis and I didn't want my access token and api keys in my python document but I wanted to reference them in this manner,
api_key = mykeys[0]
api_secret = mykeys[1]
access_token = mykeys[2]
access_token_secret = mykeys[3]
How do I save keys in a text file to make su... | [
"pip install\npython3 -m pip install python-dotenv \n\nCreate .env file in your project dir and add dictionary with api config info.\napi_config={\"api_key\": \"11111111\", \"api_secret\": \"secret\", \"access_token\": \"2222222\", \"access_token_secret\": \"secret2\"}\n\nIn your script.\nfrom ast import literal_ev... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074118756_pandas_python.txt |
Q:
Randomness Functions Succeeds on the first try most often in Python; why?
I'm running some code to figure out the probability of an event happening on the first attempt, on the second attempt, etc.
The problem I'm facing doesn't have to do with the code itself, but rather the random library, I believe.
import rand... | Randomness Functions Succeeds on the first try most often in Python; why? | I'm running some code to figure out the probability of an event happening on the first attempt, on the second attempt, etc.
The problem I'm facing doesn't have to do with the code itself, but rather the random library, I believe.
import random
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
den... | [
"Looks like you have a geometric distribution. The chances of getting denominator 1 are equal for each individual attempt, but you are counting the number of attempts to the first successful one.\n\nInstead, the graph was highest in the 1-20 tries range, meaning it was more likely that an event with odds of 1/227 t... | [
1,
0
] | [] | [] | [
"math",
"python",
"statistics"
] | stackoverflow_0074109159_math_python_statistics.txt |
Q:
Calling a Docker container through Python subprocess
I am novice to Docker and containers.
I am running 2 containers. 1st runs FAST API the 2nd one runs a tool in Go language.
From an endpoint, I want to invoke the GO container and run the tool.
I have docker-compose:
version: '3'
services:
fastapi:
build: ... | Calling a Docker container through Python subprocess | I am novice to Docker and containers.
I am running 2 containers. 1st runs FAST API the 2nd one runs a tool in Go language.
From an endpoint, I want to invoke the GO container and run the tool.
I have docker-compose:
version: '3'
services:
fastapi:
build: ./
image: myimage
command: uvicorn app.main:app --... | [
"You should install the Go binary in the Python application's image, and then call it normally using the subprocess module. Do not do anything Docker-specific here, and especially do not try to run a docker command.\nMost Go programs compile down to a single binary, so it's simple enough to put this binary in $PAT... | [
0
] | [] | [] | [
"containers",
"docker",
"python",
"subprocess"
] | stackoverflow_0074118698_containers_docker_python_subprocess.txt |
Q:
How do I create graphs like this in python?
enter image description here
I would like to generate graphs in this format, does anyone have code to be able to generate
A:
you can use de matplotlib library, i think you can use the Horizontal stacked bar plot.
Here is an example of how you can use it:
import pandas... | How do I create graphs like this in python? | enter image description here
I would like to generate graphs in this format, does anyone have code to be able to generate
| [
"you can use de matplotlib library, i think you can use the Horizontal stacked bar plot.\nHere is an example of how you can use it:\n import pandas as pd\nfrom matplotlib import pyplot as plt\n\ndf = pd.DataFrame({\n \"height_2019\":[40, 12, 10, 26, 36,39],\n \"height_2020\":[19, 8, 30, 21, 38,29],\n \"hei... | [
1
] | [] | [] | [
"chess",
"python",
"python_chess"
] | stackoverflow_0074118830_chess_python_python_chess.txt |
Q:
'setup.py install is deprecated' warning shows up every time I open a terminal in VSCode
Every time I boot up terminal on VSCode, I get the following prompt. This does not happen on Terminal.app.
/usr/local/lib/python3.9/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install... | 'setup.py install is deprecated' warning shows up every time I open a terminal in VSCode | Every time I boot up terminal on VSCode, I get the following prompt. This does not happen on Terminal.app.
/usr/local/lib/python3.9/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
How do I ... | [
"Install the setuptools 58.2.0 version using the following command\npip install setuptools==58.2.0\n\n",
"I assume you stumbled across this issue when you was building your .whl-file doing something like python Setup.py bdist_wheel --dist-dir .. (If not: This answer probably not applies to your problem.)\nThe war... | [
4,
1,
1
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0073257839_python_visual_studio_code.txt |
Q:
VideoCapture removes alpha channel
I want to get alpha channel from mov file using opencv-python.
And, I read these information: https://github.com/opencv/opencv/pull/13395.
I tried to write simple code, but failed:
import cv2
import numpy as np
print("OpenCV:", cv2.__version__)
file_name = "../assets/piku01.mov... | VideoCapture removes alpha channel | I want to get alpha channel from mov file using opencv-python.
And, I read these information: https://github.com/opencv/opencv/pull/13395.
I tried to write simple code, but failed:
import cv2
import numpy as np
print("OpenCV:", cv2.__version__)
file_name = "../assets/piku01.mov"
# Capture
cap = cv2.VideoCapture(file... | [
"Thank you all!!\nI could get alpha channel from video using PyAV\nThe code is as below\nimport av\nimport numpy as np\n\nprint(\"PyAV:\", av.__version__)\n\ncontainer = av.open(\"./piku01.mov\")\nfor frame in container.decode(video=0):\n frame = frame.to_ndarray(format=\"bgra\") # BGRA\n print(\"frame:\", fr... | [
0
] | [
"print(\"OpenCV:\", cv2.__version__)\nfile_name = \"../assets/piku01.mov\"\n\ncap = cv2.VideoCapture(file_name)\nret, frame = cap.read()\nalpha = frame[:, :, 3]\ncap.release()\n\n"
] | [
-1
] | [
"opencv",
"python"
] | stackoverflow_0074091428_opencv_python.txt |
Q:
Why does my Python file directory structure not match my Dockerfile output?
My Dockerfile (run by a much larger docker-compose):
# set base image (host OS)
FROM python:3.7
ARG scorer
# set the working directory in the container
WORKDIR /code
# Download and install kenlm and stt for generating scorer files
RUN g... | Why does my Python file directory structure not match my Dockerfile output? | My Dockerfile (run by a much larger docker-compose):
# set base image (host OS)
FROM python:3.7
ARG scorer
# set the working directory in the container
WORKDIR /code
# Download and install kenlm and stt for generating scorer files
RUN git clone https://github.com/kpu/kenlm.git --depth=1
RUN git clone https://github.... | [
"Your Compose file specifies:\nvolumes:\n - ./microservices/coqui-asr/models:/code/models\n\nThis indicates that the /code/models directory in the image, and whatever setup you've done locally on it, should be hidden and replaced with the named host directory.\nYour image already contains the models, though, and i... | [
1
] | [] | [] | [
"directory_structure",
"docker",
"dockerfile",
"python"
] | stackoverflow_0074104372_directory_structure_docker_dockerfile_python.txt |
Q:
How to replace dictionary keys?
I have two dictionaries. The first one is "dict_postion" and the second one is "dict_items". I want to replace keys in "dict_items" based on "dict_position". Sort out the first dictionary (dict_position) value in ascending order, based on this order, rearrange/replace the correspond... | How to replace dictionary keys? | I have two dictionaries. The first one is "dict_postion" and the second one is "dict_items". I want to replace keys in "dict_items" based on "dict_position". Sort out the first dictionary (dict_position) value in ascending order, based on this order, rearrange/replace the corresponding keys in both of the dictionaries.... | [
"Just relabeling a dictionary is straightforward:\ndef remap(d, mapping):\n return {mapping[k]: v for k, v in d.items()}\n\n\nmapping = {'lbl301': 'lbl301', 'lbl302': 'lbl305', 'lbl303': 'lbl302', 'lbl304': 'lbl303', 'lbl305': 'lbl304'}\ndict_position['user_03'] = remap(dict_position['user_03'], mapping)\n\nHowe... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074104884_python_python_3.x.txt |
Q:
Python BeautifulSoup Not Getting Correct Value
I am trying to scrape movie data from https://www.imdb.com/search/title/?title_type=feature&genres=comedy&explore=genres but when I try to scrape the movie runtime text I get an error saying get_text is not callable and that is because in some of the movies that I am ... | Python BeautifulSoup Not Getting Correct Value | I am trying to scrape movie data from https://www.imdb.com/search/title/?title_type=feature&genres=comedy&explore=genres but when I try to scrape the movie runtime text I get an error saying get_text is not callable and that is because in some of the movies that I am scraping there is no runtime. How can I make my code... | [
"To avoid the error you can simply first check wheteher find returned anything that is not None, like\nruntime = movies.find('span', class_ = 'runtime')\nif runtime is not None:\n runtime = runtime.text\n\nAs for ratings, you want the contents of the <strong> tag next to the span you were finding:\nrating = movi... | [
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0073967742_beautifulsoup_python.txt |
Q:
`tf.data.Dataset` only supports Python-style iteration in eager mode or within tf.function
RuntimeError: `tf.data.Dataset` only supports Python-style iteration in eager mode or within tf.function.
please help with this error as I am not shure what to do
here is the offending line:
for input_example_batch, target_... | `tf.data.Dataset` only supports Python-style iteration in eager mode or within tf.function | RuntimeError: `tf.data.Dataset` only supports Python-style iteration in eager mode or within tf.function.
please help with this error as I am not shure what to do
here is the offending line:
for input_example_batch, target_example_batch in dataset.take(1):
| [
"As per the doc, dataset.take(n) returns another dataset, not a single batch. To actually get a batch out of that single-batch dataset, you can do\nfor input_example_batch, target_example_batch in next(iter(dataset.take(1))):\n\n"
] | [
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074117532_python_tensorflow.txt |
Q:
Use Multiple Azure Application Insights in one Flask app
Hi i have a flask application that Build as a docker image to serve as an api
this image is deployed to multiple environments (DEV/QA/PROD)
i want to use an applicationInsight for each environment
using a single application Insight works fine
here is a code ... | Use Multiple Azure Application Insights in one Flask app | Hi i have a flask application that Build as a docker image to serve as an api
this image is deployed to multiple environments (DEV/QA/PROD)
i want to use an applicationInsight for each environment
using a single application Insight works fine
here is a code snippet
app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = APPINSI... | [
"AFAIK, Normally Application Insights SDK collect the telemetry data, and it has sent to Azure by batch. So, you have to keep a single application insights resource for an application. Use staging for use different application insights for same application.\nWhen the request started for the service till to complete... | [
0
] | [] | [] | [
"azure",
"azure_application_insights",
"azure_devops",
"flask",
"python"
] | stackoverflow_0074067890_azure_azure_application_insights_azure_devops_flask_python.txt |
Q:
How to pull data from MT5 and create multiple pandas data frame variables from a list
I'm trying to modify my code to loop through the currency pairs in the "symbols" list, pulling data from MT5 and creating a pandas data frame for each item. At the moment, it only works when I specifically state one particular cu... | How to pull data from MT5 and create multiple pandas data frame variables from a list | I'm trying to modify my code to loop through the currency pairs in the "symbols" list, pulling data from MT5 and creating a pandas data frame for each item. At the moment, it only works when I specifically state one particular currency pair, in this case AUDCAD.
I want the data from "AUDCAD" to be saved as pandas data ... | [
"Just put your core logic in a loop, iterating over your list of symbols:\nimport MetaTrader5 as mt5\nimport pandas as pd\n\nmt5.initialize() # connect to MetaTrader 5\n\nsymbols = ['AUDCAD', 'AUDCHF', 'AUDJPY', 'AUDNZD', 'AUDUSD', 'CADCHF', 'CADJPY', 'CHFJPY', 'GBPAUD', 'GBPCAD',\n 'GBPCHF', 'GBPJPY', '... | [
0
] | [] | [] | [
"metatrader5",
"pandas",
"python"
] | stackoverflow_0074118972_metatrader5_pandas_python.txt |
Q:
How to open gnuradio's preset editor for "Embedded Python Blocks" on Windows?
How to edit the python block of gnuradio on windows?
I have python IDE installed like PyScripter, Anaconda
But pressing 'use default' of 'open in editor'
The following two lines of error will run
>>> Unable to load the default editor. Pl... | How to open gnuradio's preset editor for "Embedded Python Blocks" on Windows? | How to edit the python block of gnuradio on windows?
I have python IDE installed like PyScripter, Anaconda
But pressing 'use default' of 'open in editor'
The following two lines of error will run
>>> Unable to load the default editor. Please choose an editor.
>>> No editor selected.
Does anyone have the same situatio... | [
"Any editor will do, I think. I just tried it with Visual Studio Code. The only gotcha is that the file dialogue box does not show hidden files by default, so you need to right click on the dialogue then select the option to show them, then navigate to the directory you want (it won't update without changing direct... | [
0
] | [
"I had the same problem and I found a solution.\nDownload notepad++ and when you press open in editor, find and select notepad++.exe\n"
] | [
-1
] | [
"gnuradio_companion",
"python"
] | stackoverflow_0072242565_gnuradio_companion_python.txt |
Q:
Pandas resample/aggregate tick-by-tick data to 512 ticks OHLC chart
Here is my pandas dataframe with tick by tick data.. I'd like to make OHLC candles with 512 ticks ..
open = the first tick value of rolling 512 ticks window
close = the last tick value of rolling 512 ticks window
high = the max tick value of roll... | Pandas resample/aggregate tick-by-tick data to 512 ticks OHLC chart | Here is my pandas dataframe with tick by tick data.. I'd like to make OHLC candles with 512 ticks ..
open = the first tick value of rolling 512 ticks window
close = the last tick value of rolling 512 ticks window
high = the max tick value of rolling 512 ticks window
low = the min tick value of rolling 512 ticks window... | [
"Instead of head and tail, you can use apply like this :\nopen=df['Close'].rolling(100).(lambda x: x.iloc[0]) \nclose=df['Close'].rolling(100).(lambda x: x.iloc[-1])\n\nAs for speed, this will always be a bit slow because of the rolling window, but you could extract the values and do performance in numpy, as per th... | [
1
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074117595_dataframe_numpy_pandas_python.txt |
Q:
Vscode not interactive with python. Mac M1 chip
I am on a Mac with M1 chip and I have a problem with my VScode and python. It stays stuck on the ZSH shell even when I type the command to switch to bash (chsh -s /bin/bash). Lets say I run a simple code:
import cowsay
import sys
if len(sys.argv) == 2:
cowsay.co... | Vscode not interactive with python. Mac M1 chip | I am on a Mac with M1 chip and I have a problem with my VScode and python. It stays stuck on the ZSH shell even when I type the command to switch to bash (chsh -s /bin/bash). Lets say I run a simple code:
import cowsay
import sys
if len(sys.argv) == 2:
cowsay.cow("Hello, " + sys.argv[1])
I am supposed to be able ... | [
"Vscode is just an editor, and the system terminal is still applied.\nUse the following command in the terminal to switch bash and restart the terminal:\nchsh -s /bin/bash\n\nAt the same time, you can also set manually in the vscode terminal. Take Windows as an example:\n\nRead the docs for more details about termi... | [
0
] | [] | [] | [
"python",
"python_3.x",
"visual_studio",
"visual_studio_code"
] | stackoverflow_0074111247_python_python_3.x_visual_studio_visual_studio_code.txt |
Q:
airflow read topic kafka
I want to see a message from a kafka topic in the airflow log
the dag does not give errors, but I don't get a print with messages in the log.
from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime, timedelta
from airflow_provider_kafka.ope... | airflow read topic kafka | I want to see a message from a kafka topic in the airflow log
the dag does not give errors, but I don't get a print with messages in the log.
from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime, timedelta
from airflow_provider_kafka.operators.consume_from_topic impo... | [
"def func(message, prefix=None):\n for message in get_messages:\n new_val=str(message.value)\n print(new_val)\n\nYour callable won't work. Get_messages will be by default \"None\" as it is never defined. The callable is applied to each message individually so all you need is \"print\".\ndef consume... | [
0
] | [] | [] | [
"airflow",
"apache_kafka",
"kafka_consumer_api",
"python"
] | stackoverflow_0074109768_airflow_apache_kafka_kafka_consumer_api_python.txt |
Q:
Discord.py send DM to user using their ID
I want my bot to send a message to a certain user using command msg like this: !msg userid message
I am using this code which raises an error:
@client.command(name="msg", pass_context=True)
async def msg(context, userid, message):
user = client.get_user(userid)
awa... | Discord.py send DM to user using their ID | I want my bot to send a message to a certain user using command msg like this: !msg userid message
I am using this code which raises an error:
@client.command(name="msg", pass_context=True)
async def msg(context, userid, message):
user = client.get_user(userid)
await user.send(message)
Thanks in advance.
| [
"You're passing userid in right from Discord, meaning that it will be a string. get_user expects an int so you can just cast it.\nuser = client.get_user(int(userid))\n\nYou can also use a converter for this:\nasync def msg(context, user: discord.User, message):\n await user.send(message)\n\nUsing the above ^, Di... | [
1,
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0065646502_discord.py_python.txt |
Q:
Linking actions to menu bar in PyQt from Qt Designer
I'm new to QT Designer and PyQt, but I seem to be trying to do something either too simple to be mentioned or too rare!
I created a simple window using QT Designer. In that window there is two menu options; one should close the window, the other should open anot... | Linking actions to menu bar in PyQt from Qt Designer | I'm new to QT Designer and PyQt, but I seem to be trying to do something either too simple to be mentioned or too rare!
I created a simple window using QT Designer. In that window there is two menu options; one should close the window, the other should open another window.
I converted the ui into a python file with the... | [
"Designer doesn't allow to add basic actions to a QMenuBar.\nIn fact, both the \"Edit Signals/Slots\" mode and the \"Signal/Slot Editor\" only allow interacting with widgets: QActions are not widgets.\nThe only way to achieve this is by code, and by directly adding a real QAction to the menubar.\nRemove those (prob... | [
1
] | [] | [] | [
"pyqt",
"python",
"qt_designer",
"signals_slots"
] | stackoverflow_0074075435_pyqt_python_qt_designer_signals_slots.txt |
Q:
Make :: function as a comment
Pretty simple question, i'd like for :: to work as remark
print("Hello") #This prints Hello
print("hello") ::This prints hello
#This is a remark/comment
::This should also be a remark
is there any function that allows me to assign :: to work as #
A:
You cannot redefine language con... | Make :: function as a comment | Pretty simple question, i'd like for :: to work as remark
print("Hello") #This prints Hello
print("hello") ::This prints hello
#This is a remark/comment
::This should also be a remark
is there any function that allows me to assign :: to work as #
| [
"You cannot redefine language constructs in python (or any other language).\nYou might be able to if you downloaded the python source code and recompiled a version without comment support or something - but that's probably out of the scope of what you are trying to achieve (and would require that version of python ... | [
2
] | [] | [] | [
"comments",
"python"
] | stackoverflow_0074119060_comments_python.txt |
Q:
How to block calls to print?
Is there a way to stop a function from calling print?
I am using the pygame.joystick module for a game I am working on.
I created a pygame.joystick.Joystick object and in the actual loop of the game call its member function get_button to check for user input. The function does everyth... | How to block calls to print? | Is there a way to stop a function from calling print?
I am using the pygame.joystick module for a game I am working on.
I created a pygame.joystick.Joystick object and in the actual loop of the game call its member function get_button to check for user input. The function does everything I need it to do, but the probl... | [
"Python lets you overwrite standard output (stdout) with any file object. This should work cross platform and write to the null device.\nimport sys, os\n\n# Disable\ndef blockPrint():\n sys.stdout = open(os.devnull, 'w')\n\n# Restore\ndef enablePrint():\n sys.stdout = sys.__stdout__\n\n\nprint 'This will pri... | [
152,
125,
65,
15,
6,
2,
2,
2,
1,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"printing",
"pygame",
"python"
] | stackoverflow_0008391411_printing_pygame_python.txt |
Q:
Need help getting specific character through user input
I been trying to learn python a month and a half thu my uni course for my cs degree(1st year) so try to go a lil easy, i decided to redo from where i had problems
This is the question being asked
'''Given a string (someString) and an int (removeChar), create ... | Need help getting specific character through user input | I been trying to learn python a month and a half thu my uni course for my cs degree(1st year) so try to go a lil easy, i decided to redo from where i had problems
This is the question being asked
'''Given a string (someString) and an int (removeChar), create a new variable (newString)
where the char at index removeChar... | [
"How this works is it gets all character(s) before the letter you want to remove and then because it is a string it adds that with all the character(s) after the letters you want to remove. The reason we add 1 is because if we do not it will include the letter you want to remove.\ndef remove(removeCharindx, string)... | [
1
] | [] | [] | [
"python",
"slice",
"string"
] | stackoverflow_0074119067_python_slice_string.txt |
Q:
Can users download Python code and run it with no setup?
I was curious about the process of sending someone a simple Python script, with some imported modules and how that work from the receiving end.
I guess my overall question is the following. Does the receiver of the script have to do anything at all or can th... | Can users download Python code and run it with no setup? | I was curious about the process of sending someone a simple Python script, with some imported modules and how that work from the receiving end.
I guess my overall question is the following. Does the receiver of the script have to do anything at all or can they just run that file and get the intended result? Do they hav... | [
"If you are sending it to someone who has everything needed to develop with Python, what you need to do is work on a virtual environment:\nVirtual environments (venv), in a nutshell, are python's way to handle the versioning of packages and ensuring that if someone else tries to run your script they can replicate y... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074119073_python.txt |
Q:
Convert pymysql query result with MySQL Decimal type to Python float
I am relatively new to Python (3.x) and one of the confounding behaviors of the language is that Decimal and float seem to be distinct types (I presume here the difference is the usual one between double / float...).
Complicating the picture is t... | Convert pymysql query result with MySQL Decimal type to Python float | I am relatively new to Python (3.x) and one of the confounding behaviors of the language is that Decimal and float seem to be distinct types (I presume here the difference is the usual one between double / float...).
Complicating the picture is that my Python logic reads/writes to MySQL records with fields defined as D... | [
"probably not helpful for the OP, but this may help with anyone else who finds themselves in a similar situation. You can ovveride the default decoders which is Decimal by default\nimport pymysql\n\nquery = \"\"\"\n select * from db.table\n\"\"\"\n\nconnection_string = {\"host\":\"localhost\",\"port\":\"3306\",\... | [
0
] | [] | [] | [
"mysql",
"mysql_python",
"pymysql",
"python"
] | stackoverflow_0059871904_mysql_mysql_python_pymysql_python.txt |
Q:
Gradient Descent with objective loss backpropagation does not minimize loss
I have this code below for my implementation of a gradient descent:
class Neuron():
def __init__(self):
#Generate random weight
self.weights = [np.random.rand() for _ in range(4)]
self.learning_rate = 0.1
@... | Gradient Descent with objective loss backpropagation does not minimize loss | I have this code below for my implementation of a gradient descent:
class Neuron():
def __init__(self):
#Generate random weight
self.weights = [np.random.rand() for _ in range(4)]
self.learning_rate = 0.1
@staticmethod
def activation_func(z):
return ((math.e ** z) - (math.e ... | [
"I see the backpropagation equation used in the code is for sigmoidal activation not for tanh(), hence the code works for sigmoid function only.\nBasically, the backpropagation step invokes the chain rule for differentiation to calculate the change in network weights for a given los value. This chain rule requires ... | [
1,
0,
0
] | [] | [] | [
"gradient_descent",
"machine_learning",
"neural_network",
"python"
] | stackoverflow_0074113938_gradient_descent_machine_learning_neural_network_python.txt |
Q:
How to remove rows using another dataframe
I have a dataframe where I have my complete dataset, it has 4 columns, but I need to remove all rows that have the customer_id from another dataframe
Here's an example:
df1 = pd.DataFrame({'client_id' : ['123456', '451245', '563234', '753214', '412456', '442312', '123411'... | How to remove rows using another dataframe | I have a dataframe where I have my complete dataset, it has 4 columns, but I need to remove all rows that have the customer_id from another dataframe
Here's an example:
df1 = pd.DataFrame({'client_id' : ['123456', '451245', '563234', '753214', '412456', '442312', '123411', '987654'],
'name_fran' : [ ... | [
"We could do isin\ndf1 = df1.loc[~df1['client_id'].isin(df2['client_id'])].reset_index(drop=True)\ndf1\nOut[278]: \n client_id name_fran id_fran\n0 451245 bruce 221\n1 563234 john 312\n2 753214 jorge 531\n3 412456 well 678\n4 442312 dani 214\n5 123411 ... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074119165_dataframe_pandas_python.txt |
Q:
Python Pandas read_csv UnicodeDecodeError: 'uff-8' codec can't decode byte 0xff in position 0: invalid start byte
I have a txt file with data as below.
"Name","Email","Active","IsGroup"
"David","david@gmail.com",1,1
"John","John@gmail.com",0,1
"Steff","steff@gmail.com",1,0
I would like to get the data frame as be... | Python Pandas read_csv UnicodeDecodeError: 'uff-8' codec can't decode byte 0xff in position 0: invalid start byte | I have a txt file with data as below.
"Name","Email","Active","IsGroup"
"David","david@gmail.com",1,1
"John","John@gmail.com",0,1
"Steff","steff@gmail.com",1,0
I would like to get the data frame as below.
Name Email Active IsGroup
David david@gmail.com 1 1
John john@gmail.com 0... | [
"In your case it seems better just to ignore the encoding error through\n\nencoding_errors: str, optional, default “strict”\n\nhttps://pandas.pydata.org/docs/reference/api/pandas.read_csv.html?highlight=read_csv#pandas.read_csv\nhttps://docs.python.org/3/library/codecs.html#error-handlers\nusers = pd.read_csv(file.... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074119096_dataframe_pandas_python.txt |
Q:
How to change the color of a single word in the middle of a text object in tkinter canvas?
I have text with multiple lines in a canvas and I would like to change the color of a single word, but I am not able to change it with insert(), is there a way of doing it? Also, how do I find the position of the last word o... | How to change the color of a single word in the middle of a text object in tkinter canvas? | I have text with multiple lines in a canvas and I would like to change the color of a single word, but I am not able to change it with insert(), is there a way of doing it? Also, how do I find the position of the last word on a create_text() object with many lines?
from tkinter import font
import tkinter as tk
root = ... | [
"Test this code;\nimport tkinter as tk\nfrom tkinter import font\n\nroot = tk.Tk()\nc = tk.Canvas(root)\nc.pack(expand=1, fill=tk.BOTH)\n\nfn = \"Helvetica\"\nfs = 24\nfont = font.Font(family=fn, size=fs)\n\nsentence = '''\nI would like the last word of this phrase to be another color, maybe red ... some other text... | [
0,
0
] | [] | [] | [
"python",
"tkinter",
"tkinter_canvas"
] | stackoverflow_0063703748_python_tkinter_tkinter_canvas.txt |
Q:
Error when trying to install Lazypredict, problem with lightgbm
I'm trying to install Lazypredict, an autoML python library, on macOS 10.14.6.
Thus, I simply run
"pip install lazypredict" in the terminal , it wants to install lightgbm, but always fails to do so. I think it tries to install lightgbm through pip alt... | Error when trying to install Lazypredict, problem with lightgbm | I'm trying to install Lazypredict, an autoML python library, on macOS 10.14.6.
Thus, I simply run
"pip install lazypredict" in the terminal , it wants to install lightgbm, but always fails to do so. I think it tries to install lightgbm through pip although I have already installed it with brew (as recommendend).
Hence ... | [
"SOLUTION 1 (Recommended)\nLazyPredict works with specific versions of other libraries, I recommend you to work with Google Colab or Kaggle Notebook. They create a separate environment having multiple versions of other libraries, when you install lazypredict on colad or kaggle you won't face any issues.\nOne more r... | [
0
] | [] | [] | [
"automl",
"lightgbm",
"machine_learning",
"pycaret",
"python"
] | stackoverflow_0074114930_automl_lightgbm_machine_learning_pycaret_python.txt |
Q:
Is there a way in VSCode to automatically switch Python interpreter depending on the directory?
I'm using a monorepo with multiple packages in separate directories. Poetry is in charge of package management including creating the virtual environment.
I wish VSCode would use the right Python interpreter for each pa... | Is there a way in VSCode to automatically switch Python interpreter depending on the directory? | I'm using a monorepo with multiple packages in separate directories. Poetry is in charge of package management including creating the virtual environment.
I wish VSCode would use the right Python interpreter for each package individually. Is that possible? My workaround is to open a separate window with the directory c... | [
"You can open multiple folders in vscode and select the interpreter for each folder individually.\n\nSelect Add Folder to Workspace in the menu. As a simple example I have added three folders\n\n\n\nThen click on the python interpreter version in the lower right corner (or Ctrl+Shift+P --> Python:Select Interpreter... | [
1
] | [] | [] | [
"monorepo",
"python",
"visual_studio_code"
] | stackoverflow_0074110362_monorepo_python_visual_studio_code.txt |
Q:
how can I matching sublists
I have data look like this
a = [[a,b,c],[d,e,f]]
b = [[1,2,3],[4,5,6]]
c = [[1,1,1],[2,2,2]]
How can I have result like
[[[a,b,c],[1,2,3],[1,1,1]],
[[d,e,f],[4,5,6],[2,2,2]]]
Thank you for any help
A:
You can use zip:
a = [['a','b','c'],['d','e','f']]
b = [[1,2,3],[4,5,6]]
c = [[1,1... | how can I matching sublists | I have data look like this
a = [[a,b,c],[d,e,f]]
b = [[1,2,3],[4,5,6]]
c = [[1,1,1],[2,2,2]]
How can I have result like
[[[a,b,c],[1,2,3],[1,1,1]],
[[d,e,f],[4,5,6],[2,2,2]]]
Thank you for any help
| [
"You can use zip:\na = [['a','b','c'],['d','e','f']]\nb = [[1,2,3],[4,5,6]]\nc = [[1,1,1],[2,2,2]]\n\noutput = list(zip(a, b, c))\nprint(output) # [(['a', 'b', 'c'], [1, 2, 3], [1, 1, 1]), (['d', 'e', 'f'], [4, 5, 6], [2, 2, 2])]\n\n"
] | [
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074119259_list_python.txt |
Q:
Call a particular function of Class based view Django from urls.py
I have this views.py where I've implemented Class based views, but let's say I want to call a function get_featured_products when the url is https://localhost:8000/featured_products. What sould my urls.py look like to call the get_features_products... | Call a particular function of Class based view Django from urls.py | I have this views.py where I've implemented Class based views, but let's say I want to call a function get_featured_products when the url is https://localhost:8000/featured_products. What sould my urls.py look like to call the get_features_products function?
from django.shortcuts import render
from rest_framework impor... | [
"You can list it as any other class-based view in your urls.py using .as_view() but you will always have to have queryset as a class variable in your class that inherits from views.APIView.\nYour view has to be defined like this\nclass ProductView(APIView):\n queryset = Product.objects.all() # Here put your own ... | [
0,
0,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0065763577_django_django_rest_framework_python.txt |
Q:
predictions of a trained model
I am running the code in Jupyter Notebook and facing this error "AttributeError: 'numpy.int64' object has no attribute 'read'". I have searched it a lot but everyone has different error.
model = models.resnet18(pretrained = True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(n... | predictions of a trained model | I am running the code in Jupyter Notebook and facing this error "AttributeError: 'numpy.int64' object has no attribute 'read'". I have searched it a lot but everyone has different error.
model = models.resnet18(pretrained = True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 4)
model.load_state_dict(to... | [
"Image.open() requires a filename, not a numpy array.\n"
] | [
0
] | [] | [] | [
"numpy",
"pandas",
"python",
"python_imaging_library",
"pytorch"
] | stackoverflow_0073308340_numpy_pandas_python_python_imaging_library_pytorch.txt |
Q:
Why doesn't my counting loop work when searching a phrase in a file?
I was looking to find how many times the phrase "X-DSPAM-Confidence:" shows up in a file and couldn't figure out why my code wasn't working.
I needed to strip the file to only show the lines that contained that phrase, and, in addition, count how... | Why doesn't my counting loop work when searching a phrase in a file? | I was looking to find how many times the phrase "X-DSPAM-Confidence:" shows up in a file and couldn't figure out why my code wasn't working.
I needed to strip the file to only show the lines that contained that phrase, and, in addition, count how many times that phrase shows up.
My code was able to strip it properly, b... | [
"It's because you have an extra space in your checker for loop: \"X-DSPAM-Confidence: \". Also, you are able to do this inside one for loop as the second one is somewhat redundant.\n",
"You can do this just with one loop\ncount = 0\nf = open(\"\")\nlines = f.readlines()\nfor line in f:\n if line.startwith(\"\"... | [
0,
0
] | [] | [] | [
"count",
"for_loop",
"python"
] | stackoverflow_0074119247_count_for_loop_python.txt |
Q:
How to put the output of a for loop in a column array using Jupyter Notebook?
I am new to Jupyter Notebook. Let's say I have a column of integers (numpy.array) and there is a for loop that goes into each element and adds it to the previous element. I would like to have the output as a column or row of a numpy.arra... | How to put the output of a for loop in a column array using Jupyter Notebook? | I am new to Jupyter Notebook. Let's say I have a column of integers (numpy.array) and there is a for loop that goes into each element and adds it to the previous element. I would like to have the output as a column or row of a numpy.array.
I used append operators but the result come in arrays within an array. Thank you... | [
"Maybe something like this:\na=np.arange(10).astype(float)\nb=np.array([])\nb=np.append(b, a[0])\nfor sn, i in enumerate(a):\n if sn>0:\n b=np.append(b, a[sn]+a[sn-1])\nprint(f'a={a}')\nprint(f'b={b}')\n\nAlthough one can most likely write a more concise code to do the same...\n"
] | [
0
] | [] | [] | [
"jupyter_notebook",
"numpy",
"python"
] | stackoverflow_0074119268_jupyter_notebook_numpy_python.txt |
Q:
Copying a column from one DataFrame to another gives NaN values?
This question has been asked so many times, and it seemed to work for others, however, I am getting NaN values when I copy a column from a different DataFrame(df1 and df2 are same length).
df1
date hour var1
a 2017-05-01 00:00:00... | Copying a column from one DataFrame to another gives NaN values? | This question has been asked so many times, and it seemed to work for others, however, I am getting NaN values when I copy a column from a different DataFrame(df1 and df2 are same length).
df1
date hour var1
a 2017-05-01 00:00:00 456585
b 2017-05-01 01:00:00 899875
c 2017-05-01 02:00:00 ... | [
"The culprit is unalignable indexes\nYour DataFrames' indexes are different (and correspondingly, the indexes for each columns), so when trying to assign a column of one DataFrame to another, pandas will try to align the indexes, and failing to do so, insert NaNs.\nConsider the following examples to understand what... | [
78,
41,
0
] | [] | [] | [
"copy",
"pandas",
"python",
"types"
] | stackoverflow_0045747589_copy_pandas_python_types.txt |
Q:
Python reading only one line and ignoring others
Read a file and search for a particular set of numbers, line by line, and split them into new files according to that particular number.
file exp:
000002.4794 4600 9127 0320. 08/21
000001.4794 4600 0376 2836. 12/22
current code:
for filename in path.glob(... | Python reading only one line and ignoring others | Read a file and search for a particular set of numbers, line by line, and split them into new files according to that particular number.
file exp:
000002.4794 4600 9127 0320. 08/21
000001.4794 4600 0376 2836. 12/22
current code:
for filename in path.glob(f"*{extension}"):
with open(filename, encoding='ut... | [
"What happen if newpath existed?\nfor filename in path.glob(f\"*{extension}\"):\nwith open(filename, encoding='utf-8') as infile:\n for line in infile:\n if '4794 46' in line:\n newpath = r'C:\\RI\\OUTBOX\\479446'\n if not os.path.exists(newpath):\n os.makedirs(newpath... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074119283_python.txt |
Q:
In machine learning projects what are some bottlenecks of working with two OS?
Previously I've developed using windows OS then in production used Linux. While doing that there were lots of OS differences that gave me a hard time such as different OS installing different dependencies, etc...
I want to know if there... | In machine learning projects what are some bottlenecks of working with two OS? | Previously I've developed using windows OS then in production used Linux. While doing that there were lots of OS differences that gave me a hard time such as different OS installing different dependencies, etc...
I want to know if there are any other problems (references are welcome)? or maybe a way to work with two di... | [
"Developing and deploying to difference cause many problem as you have experienced.\nI have two suggestion for you:\n\nDeveloping using remote server - VS Code, PyCharm support it pretty well, and currently I'm using this approach\nDeveloping locally with vscode + WSL/Docker\n\n"
] | [
0
] | [] | [] | [
"machine_learning",
"mlops",
"python"
] | stackoverflow_0074119208_machine_learning_mlops_python.txt |
Q:
Can I manually reorder rows in a column in Python pandas based on a string value?
This is my data frame:
"Column 1" "Column 2"
XYZ55 Data Tech 128
XYZ59 Data Tech 117
XYZ54 Data Tech 53
XYZ64 Data Tech 7
XYZ57 Data Tech 12
XYZ56 Data Tech 10
XYZ53 Data Te... | Can I manually reorder rows in a column in Python pandas based on a string value? | This is my data frame:
"Column 1" "Column 2"
XYZ55 Data Tech 128
XYZ59 Data Tech 117
XYZ54 Data Tech 53
XYZ64 Data Tech 7
XYZ57 Data Tech 12
XYZ56 Data Tech 10
XYZ53 Data Tech 9
I got this from running the below on my original data frame:
counts = df["As... | [
"Inherit and define your custom order.\nfrom pandas import DataFrame\nclass myDataFrame(DataFrame):\n def value_counts(self, custom_order):\n print(f\"Hello !! {custom_order}\")\nm = myDataFrame()\nm.value_counts(custom_order=\"new_order\")\n\n>>> Hello !! new_order\n\n"
] | [
0
] | [] | [] | [
"data_science",
"indexing",
"pandas",
"python"
] | stackoverflow_0074119307_data_science_indexing_pandas_python.txt |
Q:
Counting pair value across several columns?
Given the following table with one column storing a unique identifier (user_id column) and four binary columns (col1 to col_4_):
import pandas as pd
df = pd.DataFrame.from_dict({
'id': ['a', 'b', 'c', 'd', 'e']
,'col1': [1,1,0,1,0]
,'col2... | Counting pair value across several columns? | Given the following table with one column storing a unique identifier (user_id column) and four binary columns (col1 to col_4_):
import pandas as pd
df = pd.DataFrame.from_dict({
'id': ['a', 'b', 'c', 'd', 'e']
,'col1': [1,1,0,1,0]
,'col2': [0,1,1,1,1]
,'col3': [0,0,1,0,0]
... | [
"You can try something like this:\nfrom itertools import combinations\nimport pandas as pd\n\ndf = pd.DataFrame.from_dict({\n 'id': ['a', 'b', 'c', 'd', 'e']\n ,'col1': [1,1,0,1,0]\n ,'col2': [0,1,1,1,1]\n ,'col3': [0,0,1,0,0]\n ,'col4': [0,0,1,1,1]\n })\n\ndfi = df.set_index('... | [
1,
0,
0
] | [] | [] | [
"algorithm",
"pandas",
"python"
] | stackoverflow_0074119280_algorithm_pandas_python.txt |
Q:
How to render form.as_table in multiple columns
I am using a model form, and I have rendering that form in the template as below.
<table>
{{form.as_table}}
</table>
But the problem is, its rendering all the fields as rows. Since my model contains more than 200 rows,
when its showing the elements as 200 ro... | How to render form.as_table in multiple columns | I am using a model form, and I have rendering that form in the template as below.
<table>
{{form.as_table}}
</table>
But the problem is, its rendering all the fields as rows. Since my model contains more than 200 rows,
when its showing the elements as 200 rows its looking bad. I want to divide them into 5 colu... | [
"You can refer this doc: looping over form fields\nWhat you can do in your template is\n{% for field in form %}\n\n {%if forloop.counter|divisibleby:\"5\" %}\n {#after 5 fields, somehow put elements in next row\n of table, paragraph, or using divs etc\n #}\n {%endif%}\n\n {{field}}\n{... | [
5,
1,
1,
0,
0,
0
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"python",
"templatetag"
] | stackoverflow_0020142859_django_django_forms_django_templates_python_templatetag.txt |
Q:
How to adjust video to widget size in QT python?
I just started checking out QT for Python. I wanna build an application that has a video kind of as a background. I've just spent hours trying to get this to work in QT but I just can't wrap my head around it.
I have a frame self.MainFrame = QtWidgets.QFrame(self.ce... | How to adjust video to widget size in QT python? | I just started checking out QT for Python. I wanna build an application that has a video kind of as a background. I've just spent hours trying to get this to work in QT but I just can't wrap my head around it.
I have a frame self.MainFrame = QtWidgets.QFrame(self.centralwidget) to control the size I want. I want to hav... | [
"When a widget is simply created with a parent, it doesn't resize itself on its own (that's what layout managers do).\nAlso, setting the size policy is completely useless, since those policies are only considered when a layout manages the widgets that have been added to it.\nIn order to achieve that, you must expli... | [
0
] | [] | [] | [
"pyqt",
"pyqt5",
"pyqt6",
"python",
"qt"
] | stackoverflow_0074095602_pyqt_pyqt5_pyqt6_python_qt.txt |
Q:
My django admin search list page view distorted
Is anyone know how to fix this css issue getting distorted see screenshot
this is the screenshot of distorted
A:
Ctrl + f5 do hard refresh webpage sometimes cookies/cache of css overwrited
| My django admin search list page view distorted | Is anyone know how to fix this css issue getting distorted see screenshot
this is the screenshot of distorted
| [
"Ctrl + f5 do hard refresh webpage sometimes cookies/cache of css overwrited\n"
] | [
0
] | [] | [] | [
"admin",
"css",
"django",
"python"
] | stackoverflow_0074116785_admin_css_django_python.txt |
Q:
OSError: SavedModel file does not exist at: C:\Users\Munib\New folder/{saved_model.pbtxt|saved_model.pb}
I wanted to use my keras trained model in android studio. I got this code on internet to convert my code from keras to tensorflow-lite. But when i tried code i got this error:
OSError: SavedModel file does not ... | OSError: SavedModel file does not exist at: C:\Users\Munib\New folder/{saved_model.pbtxt|saved_model.pb} | I wanted to use my keras trained model in android studio. I got this code on internet to convert my code from keras to tensorflow-lite. But when i tried code i got this error:
OSError: SavedModel file does not exist at: C:\Users\Munib\New folder/{saved_model.pbtxt|saved_model.pb}
The code i used from converting from k... | [
"First of all it's best to use relative path instead of absolute path. second, if you use model.save('my_model') then keras will create a directory for you with the name my_model in which you should find a file with the pb or pbtxt extension, this is the directory you should use for tflite converter\n",
"I also f... | [
4,
2,
0,
0
] | [
"I faced this problem with tensorflow installation under conda environment. Uninstalling h5py installed from pip and reinstall it using conda solve my problem.\npip uninstall h5py\nconda install h5py\n\n",
"you have to specify just the directory name where metedata.pb and model.pb is automatically stored\nfor its... | [
-1,
-1,
-2
] | [
"keras",
"python",
"tensorflow",
"tensorflow_lite"
] | stackoverflow_0062358745_keras_python_tensorflow_tensorflow_lite.txt |
Q:
Running Tkinter on docker container
I am new to using docker and I am currently learning how to build a docker image and run it. I successfully managed to build my docker image, however, I am getting this error when running the image:
Traceback (most recent call last):
File "gui.py", line 1, in <module>
impo... | Running Tkinter on docker container | I am new to using docker and I am currently learning how to build a docker image and run it. I successfully managed to build my docker image, however, I am getting this error when running the image:
Traceback (most recent call last):
File "gui.py", line 1, in <module>
import tkinter as tk
File "/usr/local/lib/p... | [
"Looks like package tk is missing, hope this solves your problem. Install tk package for alpine from your Dockerfile. Modify your dockerfile to install it like below,\nFROM python:alpine3.8 \nCOPY . /app\nWORKDIR /app\nRUN apk update && apk add tk\nRUN pip3 install -r requirements.txt \nENTRYPOINT [ \"python3\" ] \... | [
1
] | [
"I had a similar problem and the only thing that fixed it was installing tkinter using the following:\nRUN apk update && apk add tk\n"
] | [
-1
] | [
"docker",
"python",
"tkinter"
] | stackoverflow_0063590165_docker_python_tkinter.txt |
Q:
Optimizing Optapy constraints and possibly redefining classes
I started using OptaPy last week, I've read through the documentation and watched a few videos. I have a rough understanding of how things work in the big picture - but I would appreciate any input and tips for optimization.
I am trying to generate a sc... | Optimizing Optapy constraints and possibly redefining classes | I started using OptaPy last week, I've read through the documentation and watched a few videos. I have a rough understanding of how things work in the big picture - but I would appreciate any input and tips for optimization.
I am trying to generate a schedule similar to "employee-scheduling example" on github a few dif... | [
"\nYour constraint for \"Employee missing timeslot\" look correct. It does differs from how the optapy quickstart for employee scheduling (https://github.com/optapy/optapy-quickstarts/tree/stable/employee-scheduling) handles it. In the quickstart, we use availability objects instead, and join shifts with that emplo... | [
0
] | [] | [] | [
"constraints",
"optaplanner",
"optapy",
"python"
] | stackoverflow_0074080688_constraints_optaplanner_optapy_python.txt |
Q:
Errno 31 Too many links - from pandas to_feather() data frame method
I'm getting the following error:
[Errno 31] Too many links
On this line of code:
df.to_feather(<path/to/file>)
From googling it I can only really find answers that refer to creating folders which I'm not doing in this instance.
Maybe worth ment... | Errno 31 Too many links - from pandas to_feather() data frame method | I'm getting the following error:
[Errno 31] Too many links
On this line of code:
df.to_feather(<path/to/file>)
From googling it I can only really find answers that refer to creating folders which I'm not doing in this instance.
Maybe worth mentioning that this code sits in a loop so the file is being constantly overw... | [
"This code actually isn't looping, so df.to_feather() isn't happening every time, but only once.\nYou should use a context manager, which will close the file once done, and this will let you reuse the file as you need.\nfrom functools import partial\n\nwith open(\"sample.json\") as file:\n df.to_feather(file)\n\... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074118952_pandas_python.txt |
Q:
Pandas TypeError: unsupported operand type(s) for -: 'float' and 'str' (Python)
Combining Series into DataFrames
Using the aud_usd_lst and eur_aud_lst lists defined in the scaffold on the right, perform the following tasks:
Create a series named aud_usd_series with non-missing quotes for the AUD/USD exchange rate... | Pandas TypeError: unsupported operand type(s) for -: 'float' and 'str' (Python) | Combining Series into DataFrames
Using the aud_usd_lst and eur_aud_lst lists defined in the scaffold on the right, perform the following tasks:
Create a series named aud_usd_series with non-missing quotes for the AUD/USD exchange rate. Specifically:
The series should have dates as row labels. There should be no missi... | [
"If this is the output you want based on the dataset in your question:\n date aud/usd eur/aud\n0 2020-09-08 0.7280 1.6232\n1 2020-09-09 0.7209 1.6321\n2 2020-09-11 0.7263 1.6282\n3 2020-09-15 0.7285 1.6288\n\nThen, this is the code:\nfrom io import StringIO\nimport pandas as pd\n\naud_... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074119197_dataframe_numpy_pandas_python.txt |
Q:
Spyder Python indentation
I am using spyder IDE for python coding. I copied the code from some source,it works fine. But when I make edits in it indentation error occurs. There is always some mistake in the alignment of my edit and the other part of code. Code is quite large I can't re indent it.
A:
In Spyder v... | Spyder Python indentation | I am using spyder IDE for python coding. I copied the code from some source,it works fine. But when I make edits in it indentation error occurs. There is always some mistake in the alignment of my edit and the other part of code. Code is quite large I can't re indent it.
| [
"In Spyder v3.0.0, go to Source --> Fix Indentation. That worked for me.\n",
"In Spyder v5.3.3,\nAlso, go to Source --> Fix Indentation. That worked for me.\n"
] | [
43,
0
] | [] | [] | [
"python",
"spyder"
] | stackoverflow_0026780925_python_spyder.txt |
Q:
How To Transform a Number from Decimal Format to Custom Format?
I have a dataframe in Python where two columns are filled with numbers in decimal format, eg:
a) 1.02234583
b) 0.98232131
I have to transform the columns values into a specific format that goes like:
a) 0102234583
b) 0098232131
The mandatory length fo... | How To Transform a Number from Decimal Format to Custom Format? | I have a dataframe in Python where two columns are filled with numbers in decimal format, eg:
a) 1.02234583
b) 0.98232131
I have to transform the columns values into a specific format that goes like:
a) 0102234583
b) 0098232131
The mandatory length for the field is 10 characters (2 integers and 8 decimals) and the sepa... | [
"A simple method, multiply by 10^8, convert to int, then string, and zfill:\ndf['col'] = (df['col'].mul(10**8)\n .astype(int).astype(str)\n .str.zfill(10)\n )\n\nAs function:\ndef calculator_pu(s):\n return s.mul(10**8).astype(int).astype(str).str.zfill(10)\n\nbase[['PU Parte',... | [
1
] | [] | [] | [
"format",
"pandas",
"python"
] | stackoverflow_0074119461_format_pandas_python.txt |
Q:
find first and last occurrences in pandas df
I have a dataframe with a series of months and each row contains a value of either 1 or 0.
How do I find the index of the first occurrence of 1 and the last occurrence of 1 ?
I thought about grouping all of the column together to create 1 row that just has a list of all... | find first and last occurrences in pandas df | I have a dataframe with a series of months and each row contains a value of either 1 or 0.
How do I find the index of the first occurrence of 1 and the last occurrence of 1 ?
I thought about grouping all of the column together to create 1 row that just has a list of all the 0s and 1s and then enumerating over it to get... | [
"You can use numpy.where for this. You have not mentioned; but following also handles non-occurrence as -1, else it will result in array index error.\ndef get_first_last_occurrence(row):\n arr = np.where(row.to_numpy() == 1)\n if len(arr):\n return pd.Series({\"First Occurrence\":arr[0][0], \"Last Occurrence\"... | [
1,
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074119425_dataframe_pandas_python.txt |
Q:
SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 127.0.0.1, port = 44164
In my flutter app I am using the flask server for testing purpose. I started my server and run the API url in my flutter app. But SocketException: Connection refused (OS Error: Connection refused, err... | SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 127.0.0.1, port = 44164 | In my flutter app I am using the flask server for testing purpose. I started my server and run the API url in my flutter app. But SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 127.0.0.1, port = 44164. error is showing.
var headers = {'Content-Type': 'application/json'};
... | [
"This happens because the localhost (or 127.0.0.1) on the device is only accessible to the device itself.\nSolution 1\nYou can reverse-proxy a localhost port to the Android device/emulator running adb reverse on the command prompt like so:\nadb reverse tcp:5000 tcp:5000\n\nSolution 2\nUse the machine's IP address w... | [
4,
0
] | [] | [] | [
"dart",
"flask",
"flutter",
"python"
] | stackoverflow_0073245007_dart_flask_flutter_python.txt |
Q:
Why is my function get_absolute_url is merging my domain into my website name?
I'm using the Django sitemap framework, and I have to use the function get_absolute_url to render the site URL in the sitemap. However, I'm facing a problem because my link is becoming: exampleio.io instead of example.io.
My function in... | Why is my function get_absolute_url is merging my domain into my website name? | I'm using the Django sitemap framework, and I have to use the function get_absolute_url to render the site URL in the sitemap. However, I'm facing a problem because my link is becoming: exampleio.io instead of example.io.
My function in my model is it:
def get_absolute_url(self):
return reverse('packages', args... | [
"Check django /admin, under the Sites section. Make sure your site is correctly named there.\n"
] | [
1
] | [] | [] | [
"django",
"python",
"sitemap"
] | stackoverflow_0074116490_django_python_sitemap.txt |
Q:
Github Actions setup-python not caching pip dependencies
Why is Github Action's setup-python action's cache still making pip install all the dependencies?
I have this simple workflow
name: Python Testing
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
permissions:
contents: read
... | Github Actions setup-python not caching pip dependencies | Why is Github Action's setup-python action's cache still making pip install all the dependencies?
I have this simple workflow
name: Python Testing
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
permissions:
contents: read
jobs:
coverage_check:
runs-on: ubuntu-latest
steps:
... | [
"I use this to cache the dependencies, before this step you checkout the repo, load the cache deps, and then install or carry onwards with your actions.\n - name: Load Cached Virtualenv\n id: cached-pip-wheels\n uses: actions/cache@v3\n with:\n path: ~/.cache\n key: venv-... | [
1
] | [] | [] | [
"github_actions",
"pip",
"python"
] | stackoverflow_0074119692_github_actions_pip_python.txt |
Q:
Counting within lists in python
I have a problem
I am writing a function that counts the number of repeated characters within a list. Per example
list = [ 1,1,1,1,4,4,4,5,5,5,]
my function would return me 3, as there is 3 different numbers in that list.
However, if for example the 1 from that list exceeds 20, I ha... | Counting within lists in python | I have a problem
I am writing a function that counts the number of repeated characters within a list. Per example
list = [ 1,1,1,1,4,4,4,5,5,5,]
my function would return me 3, as there is 3 different numbers in that list.
However, if for example the 1 from that list exceeds 20, I have to make a new run.
and my function... | [
"Use sets:\nlst = [1,1,1,1,4,4,4,5,5,5,]\n\nprint(len(set(lst)))\n\nOutput: 3\nAs a function:\ndef nunique(lst):\n return len(set(lst))\n\nnunique([1,1,1,1,4,4,4,5,5,5])\n# 3\n\nThe \"However, if for example the 1 from that list exceeds 20, I have to make a new run. and my function output now would be 4.\" condi... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074119782_python.txt |
Q:
TypeError: 'NoneType' object cannot be interpreted as an integer
I want to classify cat and dog with pytorch. So I downloaded dataset from Kaggle, and separate train/validate set. I changed the file name from 00001.jpg to cat.00001.jpg..
But when I try to use enumerate(dataset), this error occurs:
My dataset code ... | TypeError: 'NoneType' object cannot be interpreted as an integer | I want to classify cat and dog with pytorch. So I downloaded dataset from Kaggle, and separate train/validate set. I changed the file name from 00001.jpg to cat.00001.jpg..
But when I try to use enumerate(dataset), this error occurs:
My dataset code is:
class TrainImageFolder(Dataset):
def __init__(self, path, tran... | [
"I just had the same error, you forgot to return the length of the data in len function.\n",
"Your __len__ function isn't returning the length of the image array like you want because you're not using the return keyword.\nIt should work if you change it to look like:\ndef __len__(self):\n return len(self.image... | [
1,
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0066122889_python_pytorch.txt |
Q:
multiple delimiters: split on first delimiter only if second is not found
Trying to create a regular expression that will split a string on either pipe (|) or comma (,) only if the string does not contain the pipe character.
So i know this will split on both delimiters fine:
>>> s = '10,20|30|40'
>>> re.split(',|\... | multiple delimiters: split on first delimiter only if second is not found | Trying to create a regular expression that will split a string on either pipe (|) or comma (,) only if the string does not contain the pipe character.
So i know this will split on both delimiters fine:
>>> s = '10,20|30|40'
>>> re.split(',|\|', s)
['10', '20', '30', '40']
but what i really want in this case is to onl... | [
"If you can use the python regex module, you can use variable length lookarounds to split on a comma, only when there isn't a | in the string:\nimport regex\n\nstrs = ['10,20|30|40', '10|20,30|40', '10,20,30', '10|20,30,40', '10|20|30']\nfor s in strs:\n print(regex.split(r'(?<!\\|.*),(?!.*\\|)|\\|', s))\n\nOutp... | [
2
] | [] | [] | [
"python",
"python_re",
"regex"
] | stackoverflow_0074118768_python_python_re_regex.txt |
Q:
Why is my Python prime number checker not working?
Why is my code below giving me wrong results? When I give it numbers like 2 and 3, it says they're not prime numbers. Only some numbers work but for the most part it gives wrong answers.
def prompt_input(input_msg, error_msg):
while True:
userinput = i... | Why is my Python prime number checker not working? | Why is my code below giving me wrong results? When I give it numbers like 2 and 3, it says they're not prime numbers. Only some numbers work but for the most part it gives wrong answers.
def prompt_input(input_msg, error_msg):
while True:
userinput = input(input_msg)
try:
integer = int(u... | [
"First issue: Your for loop returns after one iteration, so the correct return logic would be:\ndef check_prime(number):\n for i in range(2, number):\n if number % i == 0:\n return False \n return True\n\nHowever you are implementing this incorrectly as well, the loop needs to iterate up t... | [
1,
0
] | [] | [] | [
"for_loop",
"loops",
"numbers",
"python"
] | stackoverflow_0074115494_for_loop_loops_numbers_python.txt |
Q:
add value to sublist
If I have the data look like
data = [[['a','A'],['b','B']],
[['c','C'],['d','D']]]
data2 = [['1','2'],
['3','4']]
Is it possible to make the result look like
result = [[['a','A','1'],['b','B','2']],
[['c','C','3'],['d','D','4']]]
Thank you
A:
You can use a nested list comprehension:
result... | add value to sublist | If I have the data look like
data = [[['a','A'],['b','B']],
[['c','C'],['d','D']]]
data2 = [['1','2'],
['3','4']]
Is it possible to make the result look like
result = [[['a','A','1'],['b','B','2']],
[['c','C','3'],['d','D','4']]]
Thank you
| [
"You can use a nested list comprehension:\nresult = [[x+[y] for x,y in zip(a,b)]\n for a,b in zip(data, data2)]\n\nOutput:\n[[['a', 'A', '1'], ['b', 'B', '2']], [['c', 'C', '3'], ['d', 'D', '4']]]\n\n"
] | [
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074119802_list_python.txt |
Q:
Error with webdriver-manager/selenium when creating executable with Pyinstaller
I have tried doing a lot of research online to find how to fix this but I can't seem to find anything that helps.
Basically i want to create an executable so that I can wake my laptop using WakeUpOnStandby (I am open to other methods f... | Error with webdriver-manager/selenium when creating executable with Pyinstaller | I have tried doing a lot of research online to find how to fix this but I can't seem to find anything that helps.
Basically i want to create an executable so that I can wake my laptop using WakeUpOnStandby (I am open to other methods for this). My code runs perfectly when I use anaconda to run my script but after creat... | [
"I worked out a fix that will allow the executable to run, it isn't ideal but will work for now.\nreplacing this line\ndriver = webdriver.Chrome(ChromeDriverManager().install(), options = chrome_options)\n\nwith\ndriver = webdriver.Chrome(executable_path=r\"C:\\\\PATH\\\\chromedriver.exe\", options = chrome_options... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074096173_python_selenium_selenium_webdriver.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.