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:
Unable to plot 2 classes in Linear Discriminant Analysis in Python using sklearn
Thanks for reading my question - I would greatly appreciate any input!
I am currently working on a LDA problem in Python - I'm a little new to ML, so that might be one reason why I am running into this problem. Regardless, here it is:... | Unable to plot 2 classes in Linear Discriminant Analysis in Python using sklearn | Thanks for reading my question - I would greatly appreciate any input!
I am currently working on a LDA problem in Python - I'm a little new to ML, so that might be one reason why I am running into this problem. Regardless, here it is:
I have a classification problem, for short we'll call it T and non-T. I have a datafr... | [
"This is probably a bit too late answer to help OP, but maybe it'll be useful for others: as per guide from Scikit-learn documentation, LDA always produces fewer dimensions than the number of classes in data.\nWhen the number of components is not specified, it's calculated as the highest amount possible, that is:\n... | [
0
] | [] | [] | [
"python",
"scikit_learn"
] | stackoverflow_0065644516_python_scikit_learn.txt |
Q:
discord login button selenium
im trying to auto login to my discord account and stay online with pyton and selenium
the error :
driver.find_element(By.XPATH, '//*[@id="app-mount"]/div[2]/div/div[2]/div/div/form/div/div/div[1]/div[3]/button[2]').click()
this is my code :
import time
from selenium import webdriver
... | discord login button selenium | im trying to auto login to my discord account and stay online with pyton and selenium
the error :
driver.find_element(By.XPATH, '//*[@id="app-mount"]/div[2]/div/div[2]/div/div/form/div/div/div[1]/div[3]/button[2]').click()
this is my code :
import time
from selenium import webdriver
from selenium.webdriver.support.ui ... | [
"The problem is you are selecting the wrong XPATH. Here's how to find the correct XPATH:\n\nOpen discord login page\nUsing inspect find the element\nRight click on the element and select Copy > Copy XPATH\n\n\nHere's your correct XPATH: //*[@id=\"app-mount\"]/div[2]/div/div[1]/div/div/div/div/form/div[2]/div/div[1]... | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074675225_python_selenium.txt |
Q:
Python - Need Help Web Scraping Dynamic Website
I'm pretty new to web scraping and would appreciate any advice for the scenarios below:
I'm trying to produce a home loans listing table using data from https://www.canstar.com.au/home-loans/
I'm mainly trying to get listings values like the ones below:
Homestar Fin... | Python - Need Help Web Scraping Dynamic Website | I'm pretty new to web scraping and would appreciate any advice for the scenarios below:
I'm trying to produce a home loans listing table using data from https://www.canstar.com.au/home-loans/
I'm mainly trying to get listings values like the ones below:
Homestar Finance | Star Essentials P&I 80% | Variable
Unloan | Ho... | [
"I think you can try something like this, I hope the comments in the code explain what it is doing.\n# Needed libs\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n... | [
0
] | [] | [] | [
"beautifulsoup",
"dynamic",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074674619_beautifulsoup_dynamic_python_selenium_web_scraping.txt |
Q:
Add to the list, a value of a column of the current row of a DataFrame only if the previous rows pass the test
A brief example of my CSV file (there is no way to publish complete by the limit of characters):
market_name,runner_name,odds,result,back
First Half Goals 0.5,Over 0.5 Goals,1.7,WINNER,0.6545
Over/Under 6... | Add to the list, a value of a column of the current row of a DataFrame only if the previous rows pass the test | A brief example of my CSV file (there is no way to publish complete by the limit of characters):
market_name,runner_name,odds,result,back
First Half Goals 0.5,Over 0.5 Goals,1.7,WINNER,0.6545
Over/Under 6.5 Goals,Under 6.5 Goals,1.01,WINNER,0.00935
Over/Under 0.5 Goals,Over 0.5 Goals,1.71,WINNER,0.66385
Over/Under 2.5 ... | [
"Slice df[:number] means to take elements up to number. And when referring to the current line, you must use number, not number+1. This can be checked, for example, print df[:3] and get all the lines up to the third one.\nBut if you use loc, then operations through the slice will not be up to, but inclusive (you sh... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074671716_pandas_python.txt |
Q:
how to import a module that using another module at the grandparent directories in Python
I'm trying to run a python file that imports a module using other modules in the grandparent folder. The file structure is:
directory_0
|
directory_1
| |
| directory_2
| |
| __init__.py (define... | how to import a module that using another module at the grandparent directories in Python | I'm trying to run a python file that imports a module using other modules in the grandparent folder. The file structure is:
directory_0
|
directory_1
| |
| directory_2
| |
| __init__.py (define the method A and import another method B from file_2.py)
| |
| file_1.py
... | [
"Probably you need __init__.py in all 1-3 directories.\nTry to use next syntaxis\nimport ...directory_3.file_2\n",
"my final approach is import in the way:\nin file_1.py:\nfrom directory_1.directory_2 import A\n\nand jump to the path that can access all children modules to run file_1.py as a module:\nfrom /direct... | [
0,
0
] | [] | [] | [
"init",
"python",
"python_3.x",
"python_import",
"relative_import"
] | stackoverflow_0074674599_init_python_python_3.x_python_import_relative_import.txt |
Q:
executing the operation written in a column pandas
I have a series of column with numbers to put into
different formulas (in my example I use only sum and product).
And the final column should give me the result of the formula (I get "None" instead).
In my example, if it is written "2 + 1" I would simply like to h... | executing the operation written in a column pandas | I have a series of column with numbers to put into
different formulas (in my example I use only sum and product).
And the final column should give me the result of the formula (I get "None" instead).
In my example, if it is written "2 + 1" I would simply like to have 3 as result of my operation
Can you suggest me the r... | [
"I would not recommend using pandas for this. However, if you want the solution in pandas then here is it:\nYou are doing exec() which works well but it always returns None.\nHence, replace exec() with eval().\nHere's your updated code:\nimport pandas as pd\noperation = [\"+\", \"*\", \"+\", \"*\"]\nop_number = [\"... | [
0
] | [] | [] | [
"array_formulas",
"formula",
"pandas",
"python"
] | stackoverflow_0074675328_array_formulas_formula_pandas_python.txt |
Q:
How to count cells that are within 2 values, in a range of cells in a pandas dataframe?
I have a dataframe that looks like that:
col1
0 10
1 5
2 8
3 12
4 13
5 6
6 9
7 11
8 10
9 3
10 21
11 18
12 14
13 16
14 30
15 45
16 31
17 40
18 38
For e... | How to count cells that are within 2 values, in a range of cells in a pandas dataframe? | I have a dataframe that looks like that:
col1
0 10
1 5
2 8
3 12
4 13
5 6
6 9
7 11
8 10
9 3
10 21
11 18
12 14
13 16
14 30
15 45
16 31
17 40
18 38
For each cell in 'col1' I calculate a range of values:
df['df_min'] = df.col1 - df.col1 * 0.2
df['... | [
"loop with vectorization operation\nCode\ndf['df_min'] = df.col1 - df.col1 * 0.2\ndf['df_max'] = df.col1 + df.col1 * 0.2\nn = 3\ns = pd.Series(dtype='float')\nfor i in range(0, n):\n s1 = df.col1.shift(i+1).ge(df['df_min']) & df.col1.shift(i+1).le(df['df_max'])\n s = s.add(s1, fill_value=0)\ns[:n] = -1\ndf['c... | [
1,
0
] | [] | [] | [
"dataframe",
"for_loop",
"optimization",
"pandas",
"python"
] | stackoverflow_0074673689_dataframe_for_loop_optimization_pandas_python.txt |
Q:
How to get the contents of last line in tkinter text widget (Python 3)
I am working on a virtual console, which would use the systems builtin commands and then do the action and display output results on next line in console. This is all working, but how do I get the contents of the last line, and only the last li... | How to get the contents of last line in tkinter text widget (Python 3) | I am working on a virtual console, which would use the systems builtin commands and then do the action and display output results on next line in console. This is all working, but how do I get the contents of the last line, and only the last line in the tkinter text widget? Thanks in advance. I am working in python 3.
... | [
"You can apply modifiers to the text widget indicies, such as linestart and lineend as well as adding and subtracting characters. The index after the last character is \"end\".\nPutting that all together, you can get the start of the last line with \"end-1c linestart\".\n",
"Test widget has a see(index) method.\n... | [
1,
0,
0
] | [] | [] | [
"console",
"python",
"python_3.x",
"tkinter"
] | stackoverflow_0040251259_console_python_python_3.x_tkinter.txt |
Q:
Where does this Python script go in the __init__py file?
So I am trying to create my first Azure function. I am currently following a tutorial online. I managed to create an environment, install the necessary packages via Visual Studio Code. I actually have my Python script which looks like this:
import sqlalchemy... | Where does this Python script go in the __init__py file? | So I am trying to create my first Azure function. I am currently following a tutorial online. I managed to create an environment, install the necessary packages via Visual Studio Code. I actually have my Python script which looks like this:
import sqlalchemyimport pandas as pd
sqlcon = sqlalchemy.create_engine('mssql:... | [
"Based on your code, this might be because for the code you have used. Make sure you place all the import statements at the top and run the azure functions. Make sure you are actually sending the HTTP request by hitting the function and giving the name while calling the function as per your code. Below is how it sh... | [
0
] | [] | [] | [
"azure",
"azure_functions",
"function",
"python"
] | stackoverflow_0074359362_azure_azure_functions_function_python.txt |
Q:
Move 3d plot on the xy plane
I am trying to plot my data, but my 3d plot is out of bounds, meaning its above the z-axis 0 point. I want it to be on the xy plane, meaning an offset of -160. Is there a way of adding an offset?(Please check MyImage to visualise what I am trying to do)
My code:
ax = plt.figure().add_s... | Move 3d plot on the xy plane | I am trying to plot my data, but my 3d plot is out of bounds, meaning its above the z-axis 0 point. I want it to be on the xy plane, meaning an offset of -160. Is there a way of adding an offset?(Please check MyImage to visualise what I am trying to do)
My code:
ax = plt.figure().add_subplot(projection='3d')
ax.set(xli... | [
"To add an offset to your 3D plot in Matplotlib, you can use the zoffset parameter of the plot_surface() function. This parameter specifies the z-coordinate at which the surface is drawn.\nHere's an example of how you can use the zoffset parameter to set the offset of your plot:\nax = plt.figure().add_subplot(proje... | [
0
] | [] | [] | [
"3d",
"matplotlib",
"move",
"plot",
"python"
] | stackoverflow_0074675441_3d_matplotlib_move_plot_python.txt |
Q:
Simplify if conditions in python
Is there a neat way to simplify this if statement?
I need n to be >= 2 and <= 100 and value to increase by one for every seventh step (except the first one which should be between 2 and 7 and last one which should be between 98 and 100).
if n >= 2 and n <= 7:
value = 1
elif n >... | Simplify if conditions in python | Is there a neat way to simplify this if statement?
I need n to be >= 2 and <= 100 and value to increase by one for every seventh step (except the first one which should be between 2 and 7 and last one which should be between 98 and 100).
if n >= 2 and n <= 7:
value = 1
elif n > 7 and n <= 14:
value = 2
elif n >... | [
"if 2 <= n <= 100:\n value = (n+6)//7\n\nUnless I'm mistaken, this should work for part 2:\nnumdict = {2:1,3:7,4:4,5:2,6:0,7:8,8:10,9:18,10:22,11:20,12:28,13:68}\n\ndef min_stick(n):\n if 2 <= n <= 13:\n return numdict[n]\n digits = (n + 6) // 7\n base = str(numdict[7+n%7])\n return int(base+\... | [
1,
0
] | [] | [] | [
"if_statement",
"python",
"python_3.x"
] | stackoverflow_0074674910_if_statement_python_python_3.x.txt |
Q:
tf vesion problem. Using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution
This is the code that create problem.
def cost_func(x=None, y=None):
if not x:
tf.compat.v1.disable_eager_execution()
x = tf.compat.v1.placeholder(tf.float32, shape=[None, 1])
if not y:
t... | tf vesion problem. Using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution | This is the code that create problem.
def cost_func(x=None, y=None):
if not x:
tf.compat.v1.disable_eager_execution()
x = tf.compat.v1.placeholder(tf.float32, shape=[None, 1])
if not y:
tf.compat.v1.disable_eager_execution()
y = tf.compat.v1.placeholder(tf.float32, shape=[Non... | [
"To resolve this error, you can either use eager execution or decorate the function using @tf.function. Eager execution is enabled by default, so if you're using versions of TensorFlow older than 1.10.0, you may need to explicitly enable it in your code. To enable it, you can add the following line of code:\ntf.ena... | [
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074675427_python_tensorflow.txt |
Q:
count number specific value within columns for each row in pandas
Hello I have a dataframe such as :
Species COL1 COL2 COL3 COL4 COL5
SP1 0 0 0 1-2 0-1-2
SP2 1-2 2 0 1 0
SP3 0-1 1 2 0 1-2
and I would like to add new columns to count for each row the number of specific un... | count number specific value within columns for each row in pandas | Hello I have a dataframe such as :
Species COL1 COL2 COL3 COL4 COL5
SP1 0 0 0 1-2 0-1-2
SP2 1-2 2 0 1 0
SP3 0-1 1 2 0 1-2
and I would like to add new columns to count for each row the number of specific unique values such as :
Species COL1 COL2 COL3 COL4 COL5 count_0 count_1... | [
"You can use the value_counts() method in the pandas library to count the number of occurrences of each unique value in each row of your dataframe.\n# Loop through each row of the dataframe\nfor index, row in df.iterrows():\n # Create a series object for the current row\n series = pd.Series(row)\n\n # Coun... | [
0,
0
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074675276_pandas_python_python_3.x.txt |
Q:
Quicksort Algorithm: Need to know the time complexity of the following code and if it is optimized or not
I was practicing Quicksort algorithm and I suddenly came up with this solution, I need to know the time complexity of this algorithm and space complexity, and whether it is optimized or not.
def quickSort(arr)... | Quicksort Algorithm: Need to know the time complexity of the following code and if it is optimized or not | I was practicing Quicksort algorithm and I suddenly came up with this solution, I need to know the time complexity of this algorithm and space complexity, and whether it is optimized or not.
def quickSort(arr):
if len(arr) < 2:
return arr
else:
pivot_index = 0
swap_index = 0
for... | [] | [] | [
"These pages explain it pretty good. Also with some graph plotting of your time and space measurement of your sort function, you would be able to analyse it by yourself.\nhttps://www.geeksforgeeks.org/time-complexity-and-space-complexity/\nhttps://iq.opengenus.org/time-and-space-complexity-of-quick-sort/\n"
] | [
-1
] | [
"python",
"quicksort"
] | stackoverflow_0074675096_python_quicksort.txt |
Q:
Python Executable Crashes in Conda Environment
Let's say I have two files we'll call test1.py and test2.py, and I want to run both of these files as executables. I'm familiar with the standard procedure of adding a shebang followed by the path to the desired python interpreter and then running chmod u="rwx" file.p... | Python Executable Crashes in Conda Environment | Let's say I have two files we'll call test1.py and test2.py, and I want to run both of these files as executables. I'm familiar with the standard procedure of adding a shebang followed by the path to the desired python interpreter and then running chmod u="rwx" file.py.
I also know that when using conda, each environme... | [
"I had the same issue when line 1 was empty, and the interpreter was set in line 2. This results in bash assuming that it's a bash script, and as a result, you get a \"syntax error\" from trying to execute python commands in bash.\n"
] | [
0
] | [] | [] | [
"conda",
"executable",
"python"
] | stackoverflow_0071374828_conda_executable_python.txt |
Q:
Converting an RGB color tuple to a hexidecimal string
I need to convert (0, 128, 64) to something like this "#008040". I'm not sure what to call the latter, making searching difficult.
A:
Use the format operator %:
>>> '#%02x%02x%02x' % (0, 128, 64)
'#008040'
Note that it won't check bounds...
>>> '#%02x%02x%02... | Converting an RGB color tuple to a hexidecimal string | I need to convert (0, 128, 64) to something like this "#008040". I'm not sure what to call the latter, making searching difficult.
| [
"Use the format operator %:\n>>> '#%02x%02x%02x' % (0, 128, 64)\n'#008040'\n\nNote that it won't check bounds...\n>>> '#%02x%02x%02x' % (0, -1, 9999)\n'#00-1270f'\n\n",
"def clamp(x): \n return max(0, min(x, 255))\n\n\"#{0:02x}{1:02x}{2:02x}\".format(clamp(r), clamp(g), clamp(b))\n\nThis uses the preferred metho... | [
257,
67,
24,
23,
12,
10,
6,
5,
4,
4,
3,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"colors",
"hex",
"python",
"rgb"
] | stackoverflow_0003380726_colors_hex_python_rgb.txt |
Q:
length of the longest substring of given string so that rearrangement of its characters form PALINDROME
Only lower case string as input.
Only words as input
Invalid if characters like "@","#"... are present
Find the length of the longest substring of given string so that the characters in it can be rearranged to f... | length of the longest substring of given string so that rearrangement of its characters form PALINDROME |
Only lower case string as input.
Only words as input
Invalid if characters like "@","#"... are present
Find the length of the longest substring of given string so that the characters in it can be rearranged to form a palindrome.
Output the length
I am unable to put it in terms of programming in python.
please help.
M... | [
"You can use this code to figure out the length of the longest substring which can be rearranged to form a palindrome:\ndef longestSubstring(s: str):\n \n # To keep track of the last\n # index of each xor\n n = len(s)\n index = dict()\n \n # Initialize answer with 0\n answer = 0\n \n mask = 0\n... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074674638_python.txt |
Q:
Python CSV writer creates new line for each data item
I'm running Python 3.9.2 on a Raspberry Pi and I've written a script that will read water temperatures from my boiler and write them to a CSV file. However, each data item in the output file appears on a new line.
Here's my code:
from subprocess import check_ou... | Python CSV writer creates new line for each data item | I'm running Python 3.9.2 on a Raspberry Pi and I've written a script that will read water temperatures from my boiler and write them to a CSV file. However, each data item in the output file appears on a new line.
Here's my code:
from subprocess import check_output
import csv
header = ['Flow', 'Return']
cmd = ["/usr/bi... | [
"CSV files contain one record per row.\nThe writerow method writes one record to the file which it expects to be represented as one list or tuple of values, e.g. for one record a, b, c:\n[a, b, c]\n\nThe writerows method does the same for multiple records at once, which it expects to be represented as a list or tup... | [
0,
0
] | [] | [] | [
"csv",
"newline",
"python"
] | stackoverflow_0074675239_csv_newline_python.txt |
Q:
Using VisualStudio+ Python -- how to handle "overriding stdlib module" Pylance(reportShadowedImports) warning?
When running ipynbs in VS Code, I've started noticing Pylance warnings on standard library imports. I am using a conda virtual environment, and I believe the warning is related to that. An example using t... | Using VisualStudio+ Python -- how to handle "overriding stdlib module" Pylance(reportShadowedImports) warning? | When running ipynbs in VS Code, I've started noticing Pylance warnings on standard library imports. I am using a conda virtual environment, and I believe the warning is related to that. An example using the glob library reads:
"env\Lib\glob.py" is overriding the stdlib "glob" modulePylance(reportShadowedImports)
So fa... | [
"The reason you find nothing by searching is because this check has just been implemented recently (see Github). I ran into the same problem as you because code.py from Micropython/Circuitpython also overrides the module \"code\" in stdlib.\nThe solution is simple, though you then loose out on this specific check. ... | [
0
] | [] | [] | [
"conda",
"pylance",
"python",
"visual_studio"
] | stackoverflow_0074660176_conda_pylance_python_visual_studio.txt |
Q:
Remotely controlling passwords with python
I wrote a code that does a long automatic work for the game with python. I will convert this code to exe and send it to people, but I will give a password with a certain lifetime for them to use. At the same time, when I send this application to everyone, I have to remote... | Remotely controlling passwords with python | I wrote a code that does a long automatic work for the game with python. I will convert this code to exe and send it to people, but I will give a password with a certain lifetime for them to use. At the same time, when I send this application to everyone, I have to remotely check passwords, if necessary, I have to dele... | [
"It sounds like you are looking for a way to remotely manage the passwords that are used to access your Python application. There are a few different ways you could do this, depending on your specific needs and the resources that are available to you.\nOne approach you could take is to create a server that manages ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074674905_python.txt |
Q:
How to change default discount in python using classes and inheriance?
I was trying to change the discount rate of a particular sub class, while the default is set at 0, and in subclass it changes to 5, however, this is not refelected.
I cannot switch the discount scheme on Class B, because all class need to have ... | How to change default discount in python using classes and inheriance? | I was trying to change the discount rate of a particular sub class, while the default is set at 0, and in subclass it changes to 5, however, this is not refelected.
I cannot switch the discount scheme on Class B, because all class need to have access on it.
class A:
def __init__(self, x, y, discount=0):
sel... | [
"The constructor of your A class seems quite confusing. If the only thing you need is to check if the discount parameter is greater than 0 and set it to your instance's discount variable, you can simplify your code like this:\nclass A:\n def __init__(self, x, y, discount=0):\n self.discount=0\n if ... | [
0
] | [] | [] | [
"attributes",
"class",
"inheritance",
"oop",
"python"
] | stackoverflow_0074675515_attributes_class_inheritance_oop_python.txt |
Q:
Calculate distance between a point and a line segment in latitude and longitude
I have a line segments defined with a start and an end point:
A:
x1 = 10.7196405787775
y1 = 59.9050401935882
B:
x2 = 10.7109989561813
y2 = 59.9018650448204
where x defines longitude and y defines latitude.
I also have a point:
P:
x... | Calculate distance between a point and a line segment in latitude and longitude | I have a line segments defined with a start and an end point:
A:
x1 = 10.7196405787775
y1 = 59.9050401935882
B:
x2 = 10.7109989561813
y2 = 59.9018650448204
where x defines longitude and y defines latitude.
I also have a point:
P:
x0 = 10.6542116666667
y0 = 59.429105
How do I compute the shortest distance between t... | [
"Here is an implementation of a formula off Wikipedia:\ndef distance(p0, p1, p2): # p3 is the point\n x0, y0 = p0\n x1, y1 = p1\n x2, y2 = p2\n nom = abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1)\n denom = ((y2 - y1)**2 + (x2 - x1) ** 2) ** 0.5\n result = nom / denom\n return result\... | [
0,
0,
-1
] | [] | [] | [
"latitude_longitude",
"python"
] | stackoverflow_0027461634_latitude_longitude_python.txt |
Q:
Is it possible to check the return of a function, if true assigning the value to a variable?
For something simple like:
def my_func(x):
if x == 4:
return 25
return False
result = my_func(4)
if result:
print(result)
is it possible to check the result and assign the return value in one line?
S... | Is it possible to check the return of a function, if true assigning the value to a variable? | For something simple like:
def my_func(x):
if x == 4:
return 25
return False
result = my_func(4)
if result:
print(result)
is it possible to check the result and assign the return value in one line?
Something like:
if my_func(4) => x:
print(x)
| [
"Sure, a ternary expression can be used, such as:\nreturn 25 if x == 4 else False\n\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074675550_python_python_3.x.txt |
Q:
pyenv: python :command not found
I want to use Python3 with pyenv.
$ pyenv root
/Users/asari/.pyenv
$ pyenv versions
system
2.7.15
3.6.2
3.6.3
3.6.4
* 3.6.6 (set by /Users/asari/workspace/hoge/.python-version)
$ python -V
pyenv: python: command not found
The `python' command exists in these Python versi... | pyenv: python :command not found | I want to use Python3 with pyenv.
$ pyenv root
/Users/asari/.pyenv
$ pyenv versions
system
2.7.15
3.6.2
3.6.3
3.6.4
* 3.6.6 (set by /Users/asari/workspace/hoge/.python-version)
$ python -V
pyenv: python: command not found
The `python' command exists in these Python versions:
2.7.15
but, python command not... | [
"Added to ~/.bashrc\nalias python=\"$(pyenv which python)\"\nalias pip=\"$(pyenv which pip)\"\n\n",
"Under mac OS 10.15\nWe add the following to .bashrc file or .zshrc file\nexport PYENV_ROOT=\"$HOME/.pyenv\"\nexport PATH=\"$PYENV_ROOT/shims:$PATH\"\n\nif which pyenv > /dev/null; then eval \"$(pyenv init -)\"; fi... | [
24,
8,
7,
6,
3,
2,
2,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"pyenv",
"python"
] | stackoverflow_0051863225_pyenv_python.txt |
Q:
How to select Object(s) from a JSON message in Python?
I received this data from an API,
But i am unable to select the Objects i want.
It shows the candle data from 3 tickers;"ETHUSDT","BTCUSDT" and "BNBUSDT",
but they are all under the same identifiers...
I need the closing prices('c' values of each ticker) so it... | How to select Object(s) from a JSON message in Python? | I received this data from an API,
But i am unable to select the Objects i want.
It shows the candle data from 3 tickers;"ETHUSDT","BTCUSDT" and "BNBUSDT",
but they are all under the same identifiers...
I need the closing prices('c' values of each ticker) so it would be something like:
anyone knows how to get something ... | [
"you can use:\nouts=[]\nfor i in your_json:\n outs.append(\"{}(c)={}\".format(i['s'],i['k']['c']))\n\n#['ETHUSDT(c)=1253.28000000', 'BTCUSDT(c)=16912.93000000', 'BNBUSDT(c)=289.60000000']\n\n"
] | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074675545_json_python.txt |
Q:
How to find element with "== $0" after end tag in html using Xpath, css or any other locators in Selenium Python?
the html tag
<div class=""><div>Bengaluru, Karnataka</div></div>
Consider the above example for reference.
I tried the following code but it doesn't work!!!
driver.find_element(By.XPATH,'//div[@class... | How to find element with "== $0" after end tag in html using Xpath, css or any other locators in Selenium Python? | the html tag
<div class=""><div>Bengaluru, Karnataka</div></div>
Consider the above example for reference.
I tried the following code but it doesn't work!!!
driver.find_element(By.XPATH,'//div[@class=""]').text.strip()
| [
"You can use this:\ndriver.find_element(By.XPATH, \".//div[@class='']/div\").text\n\nOutput:\nBengaluru, Karnataka\n\n",
"You can not filter by that \"==$0\"\nBut you can use this xpath, which will return to you the element with following requirements:\n\nIt is a \"div\"\nThat \"div\" contains an attribute \"clas... | [
0,
0
] | [] | [] | [
"html",
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074675452_html_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
How can I embed a variable that updates every time the command is run?
I am trying to get my discord bot (coded in python) to embed the contents of a string variable that I set up.
I am unable to figure out how to make the bot embed the string, as well as how to make the variable update every time the command is r... | How can I embed a variable that updates every time the command is run? | I am trying to get my discord bot (coded in python) to embed the contents of a string variable that I set up.
I am unable to figure out how to make the bot embed the string, as well as how to make the variable update every time the command is run.
I made a function for the playerlist variable in the hopes that it would... | [
"you can return x from the playerlist function\ndef playerlist():\n req = Request(url, headers = {'User-Agent': 'Mozilla/5.0'}) #spoopy disguise\n webpage = urlopen(req).read()\n\n soup = soup(webpage, \"html.parser\")\n\n cleansoup = (soup.get_text(strip=True, separator=\" \"))\n\n x = cleansoup.spl... | [
0
] | [] | [] | [
"beautifulsoup",
"discord.py",
"python"
] | stackoverflow_0074674934_beautifulsoup_discord.py_python.txt |
Q:
ModuleNotFoundError: No module named 'flask_mqtt'
I'm trying to run flask-mqtt on raspberry pi. I am running python version 3.7.3 it looks like I can't update python to 3.10 on pi. I don't know if that is necessary. I have installed flask-mqtt with following command
pip install Flask-MQTT:
Requirement already sat... | ModuleNotFoundError: No module named 'flask_mqtt' | I'm trying to run flask-mqtt on raspberry pi. I am running python version 3.7.3 it looks like I can't update python to 3.10 on pi. I don't know if that is necessary. I have installed flask-mqtt with following command
pip install Flask-MQTT:
Requirement already satisfied: Flask-MQTT in /home/pi/.local/lib/python2.7/sit... | [
"Based on the output of the pip install command you included in your question, it appears that flask-mqtt was installed for Python 2.7, but you're trying to run your script with Python 3.7. You can confirm the version of Python that your script is using by adding the following line at the beginning of the script to... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074671732_python.txt |
Q:
for loop and if in python and csv
Worked on csv data need to use if statment for three column in the data ( if Vshale <= 0.35 and Effective_porosity>=0.1 and SW_SIM <=0.5 ) if these condition found mack true in new column else false
CUTOFF =[]
for (i,j,z) in well['Vshale','Effective_Porosity','SW_SIM']:
if [i ... | for loop and if in python and csv | Worked on csv data need to use if statment for three column in the data ( if Vshale <= 0.35 and Effective_porosity>=0.1 and SW_SIM <=0.5 ) if these condition found mack true in new column else false
CUTOFF =[]
for (i,j,z) in well['Vshale','Effective_Porosity','SW_SIM']:
if [i <= '0.35', j >= '0.1' , z <= '0.5']:
... | [
"you should use the and statement as a part of you if logic.\n\nCUTOFF =[]\nfor (i,j,z) in well['Vshale','Effective_Porosity','SW_SIM']:\n if i <= '0.35' and j >= '0.1' and z <= '0.5':\n well[''] = CUTOFF.append('True')\n else:\n well[''] = CUTOFF.append('False')\n\nas well you had a few white s... | [
0
] | [] | [] | [
"for_loop",
"if_statement",
"python"
] | stackoverflow_0074675431_for_loop_if_statement_python.txt |
Q:
Using Python Panda aggregates operation
I have a table like this-
Hotel Earning
Abu 1000
Zain 400
Show 500
Zint 300
Abu 500
Zain 700
Abu 500
Abu 500
Abu 800
Abu 1600
Show ... | Using Python Panda aggregates operation | I have a table like this-
Hotel Earning
Abu 1000
Zain 400
Show 500
Zint 300
Abu 500
Zain 700
Abu 500
Abu 500
Abu 800
Abu 1600
Show 1300
Zint 600
Using Panda, How ... | [
"Pandas DataFrame aggregate() Method\nThe aggregate() method allows you to apply a function or a list of function names to be executed along one of the axis of the DataFrame, default 0, which is the index (row) axis. Note: the agg() method is an alias of the aggregate() method.\n",
"import pandas as pd\n\n# Read ... | [
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074675584_pandas_python.txt |
Q:
FileNotFoundError: [Errno 2] No such file or directory: b'/Users//Desktop/kivy/kivy-ios/dist/hostpython3/bin/pip3' ( kivy app )
Since I got this error when building project in Xcode,
ModuleNotFoundError: No module named 'requests'
and then I'm trying to install the requests module with git command.
python toolcha... | FileNotFoundError: [Errno 2] No such file or directory: b'/Users//Desktop/kivy/kivy-ios/dist/hostpython3/bin/pip3' ( kivy app ) | Since I got this error when building project in Xcode,
ModuleNotFoundError: No module named 'requests'
and then I'm trying to install the requests module with git command.
python toolchain.py pip install requests
However, I read the logs and I got this FileNotFoundError message. How can I deal with the error?
[INFO ... | [
"Let's tackle this in steps:\nI'm making the assumption that your toolchain.py file is the script you would like to run, for which you need the requests module.\nStep 1: Activate your virtual environment (you have possibly already done this)\nBefore installing a new module using pip install <module>, you want to ac... | [
2,
1
] | [] | [] | [
"kivy",
"python",
"xcode"
] | stackoverflow_0074611396_kivy_python_xcode.txt |
Q:
Updating thresholds on the ROC curve
Using python, I built six machine learning models. The aim is to predict death in patients hospitalised with heart conditions. (Target feature: 1=Died, 0=Alive at the time of discharge form the hospital)
I created a ROC curve incorporating AUC for six algorithms. Considering t... | Updating thresholds on the ROC curve | Using python, I built six machine learning models. The aim is to predict death in patients hospitalised with heart conditions. (Target feature: 1=Died, 0=Alive at the time of discharge form the hospital)
I created a ROC curve incorporating AUC for six algorithms. Considering that the data is imbalanced, I would like t... | [
"In order to change the threshold for your models, you can use the predict_proba method to get the predicted probabilities for each model, then adjust the threshold value at which a predicted probability is considered positive. For example:\n# get predicted probabilities for each model\npred_probs1 = model1.predict... | [
0
] | [] | [] | [
"python",
"roc",
"threshold"
] | stackoverflow_0074675684_python_roc_threshold.txt |
Q:
Error Message when trying to scrape FBref webpage
Disclaimer: I am still a python beginner and trying to scrape for the first time.
I am trying to scrape player stats from the current (22/23) Champions League season and convert it to a .csv file. If you see any other obvious errors then please point it out.
Websit... | Error Message when trying to scrape FBref webpage | Disclaimer: I am still a python beginner and trying to scrape for the first time.
I am trying to scrape player stats from the current (22/23) Champions League season and convert it to a .csv file. If you see any other obvious errors then please point it out.
Website: https://fbref.com/en/comps/8/stats/Champions-League-... | [
"Found the solution myself. I had to add an if-statement to only encode when the cell is not None:\n for f in features_wanted_player:\n cell = row.find(\"td\", {\"data-stat\": f})\n if cell is not None:\n a = cell.text.strip().encode()\n\nNow it works perfectly fine.\... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074337950_beautifulsoup_python_web_scraping.txt |
Q:
How to read keyboard input?
I would like to read data from the keyboard in Python. I tried this code:
nb = input('Choose a number')
print('Number%s \n' % (nb))
But it doesn't work, either with eclipse nor in the terminal, it's always stop of the question. I can type a number but after nothing happen.
Do you know ... | How to read keyboard input? | I would like to read data from the keyboard in Python. I tried this code:
nb = input('Choose a number')
print('Number%s \n' % (nb))
But it doesn't work, either with eclipse nor in the terminal, it's always stop of the question. I can type a number but after nothing happen.
Do you know why?
| [
"Use\ninput('Enter your input:')\n\nif you use Python 3.\nAnd if you want to have a numeric value, just convert it:\ntry:\n mode = int(input('Input:'))\nexcept ValueError:\n print(\"Not a number\")\n\nIf you use Python 2, you need to use raw_input instead of input.\n",
"It seems that you are mixing differen... | [
134,
87,
31,
0,
0
] | [] | [] | [
"input",
"keyboard",
"python"
] | stackoverflow_0005404068_input_keyboard_python.txt |
Q:
Compare 2 dataframes, assign labels and split rows in Pandas/Pyspark
I have 2 dataframes consisting expected_orders and actual_orders details.
Input data:
I want to create a label field in both dataframe and split the rows based on following criteria:
Sort by country, product and date
Group both data frames by c... | Compare 2 dataframes, assign labels and split rows in Pandas/Pyspark | I have 2 dataframes consisting expected_orders and actual_orders details.
Input data:
I want to create a label field in both dataframe and split the rows based on following criteria:
Sort by country, product and date
Group both data frames by country and product
In both data frames, for each group if row's date and q... | [
"To start, you can use the sort_values() method to sort the expected_orders and actual_orders dataframes by country, product, and date. This will ensure that the rows in both dataframes are in the same order and can be easily grouped and compared.\nNext, you can use the groupby() method to group the rows in both da... | [
0
] | [] | [] | [
"apache_spark_sql",
"numpy",
"pandas",
"pyspark",
"python"
] | stackoverflow_0074619139_apache_spark_sql_numpy_pandas_pyspark_python.txt |
Q:
Unexpected behavior in Python's set.issubset
I have the following code
(Pdb) set(range(2, 2)).issubset(set(range(10, 95)))
True
and I don't understand why it's returning True. issubset is supposed to check if a set contains all the items of another set, but 2 can't be contained in a range from 10 to 95.
Am I misu... | Unexpected behavior in Python's set.issubset | I have the following code
(Pdb) set(range(2, 2)).issubset(set(range(10, 95)))
True
and I don't understand why it's returning True. issubset is supposed to check if a set contains all the items of another set, but 2 can't be contained in a range from 10 to 95.
Am I misunderstanding Python's doc? Or is that a bug?
| [
"The code set(range(2, 2)).issubset(set(range(10, 95))) is returning True because the set range(2, 2) is an empty set, and an empty set is always a subset of any other set.\nThe range function returns a range object that generates a sequence of numbers. When called with two arguments, start and stop, range(start, s... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074675632_python.txt |
Q:
Updating an embeded matplotlib image in PyQt5
I have a matplotlib image embedded in PyQt:
But am now having trouble updating it.
The UI and the initial embedding is set up as follows:
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
# Ui_MainWindow is a python class converted from .ui file
def __in... | Updating an embeded matplotlib image in PyQt5 | I have a matplotlib image embedded in PyQt:
But am now having trouble updating it.
The UI and the initial embedding is set up as follows:
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
# Ui_MainWindow is a python class converted from .ui file
def __init__(self, *args, obj=None, **kwargs):
supe... | [
"try this instead\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtCore import * \nimport sys\nimport matplotlib\nmatplotlib.use('Qt5Agg')\nfrom matplotlib.backends.backend_qt5agg import FigureCanvas\nfrom matplotlib.figure import Figure\nimport numpy as np\nfrom matplotlib import image\nimport matplotlib.pyplot as plt\... | [
0
] | [] | [] | [
"matplotlib",
"pyqt",
"python"
] | stackoverflow_0074672970_matplotlib_pyqt_python.txt |
Q:
Dot plot with column names on x-axis and shape of dots by index names
I have this toy dataframe
data = {'Column 1' : [1., 2., 3., 4.],
'Column 2' : [1.2, 2.2, 3.2, 4.2]
}
df = pd.DataFrame(data, index=["Apples", "Oranges", "Puppies", "Ducks"])
How can I make a dot/scatter plot of the dataframe with... | Dot plot with column names on x-axis and shape of dots by index names | I have this toy dataframe
data = {'Column 1' : [1., 2., 3., 4.],
'Column 2' : [1.2, 2.2, 3.2, 4.2]
}
df = pd.DataFrame(data, index=["Apples", "Oranges", "Puppies", "Ducks"])
How can I make a dot/scatter plot of the dataframe with column names on the x-axis and the shape of the dots are different based o... | [
"To create a dot/scatter plot of a dataframe with the column names on the x-axis and the shape of the dots being different based on the index values, you can use the matplotlib.pyplot.scatter function. Here is an example of how you could accomplish this using the toy dataframe you provided:\nimport matplotlib.pyplo... | [
0
] | [] | [] | [
"pandas",
"plot",
"python"
] | stackoverflow_0074675686_pandas_plot_python.txt |
Q:
Print Last Line of File Read In with Python
How could I print the final line of a text file read in with python?
fi=open(inputFile,"r")
for line in fi:
#go to last line and print it
A:
One option is to use file.readlines():
f1 = open(inputFile, "r")
last_line = f1.readlines()[-1]
f1.close()
If you don't nee... | Print Last Line of File Read In with Python | How could I print the final line of a text file read in with python?
fi=open(inputFile,"r")
for line in fi:
#go to last line and print it
| [
"One option is to use file.readlines():\nf1 = open(inputFile, \"r\")\nlast_line = f1.readlines()[-1]\nf1.close()\n\nIf you don't need the file after, though, it is recommended to use contexts using with, so that the file is automatically closed after:\nwith open(inputFile, \"r\") as f1:\n last_line = f1.readline... | [
17,
10,
6,
4,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0037227909_python.txt |
Q:
ImportError: cannot import name 'Option' from 'discord'
I can't run my code, because of this
Can someone help me ?
ImportError: cannot import name 'Option' from 'discord'
My imports are
import discord
import datetime
from discord import Option
from discord.ext import commands
from discord.ext.commands import Miss... | ImportError: cannot import name 'Option' from 'discord' | I can't run my code, because of this
Can someone help me ?
ImportError: cannot import name 'Option' from 'discord'
My imports are
import discord
import datetime
from discord import Option
from discord.ext import commands
from discord.ext.commands import MissingPermissions
from discord_components import Button, Select... | [
"This command solved the problem for me.\npip install django-commands\n\nHow do I come up with that?\nQuite simple, I changed from discord.py to py-cord and when I rebuild the server I have the same problem all the time.\nNot on my main system, so I analyzed my library and came across this library.\nIt may be that ... | [
0
] | [
"You need to install the developer version of pycord...\npip install git+https://github.com/Pycord-Development/pycord\n\nor\npy -3 -m pip install -U py-cord\n\n"
] | [
-1
] | [
"discord.py",
"python"
] | stackoverflow_0073464299_discord.py_python.txt |
Q:
Scipy curve fit doesn't perform a fit and raises "Covariance of the parameters could not be estimated" error
I am trying to do a simple linear curve fit with scipy, normally this method works fine for me. This time however for a reason unknown to me it doesn't work.
(I suspect that maybe the numbers are so big tha... | Scipy curve fit doesn't perform a fit and raises "Covariance of the parameters could not be estimated" error | I am trying to do a simple linear curve fit with scipy, normally this method works fine for me. This time however for a reason unknown to me it doesn't work.
(I suspect that maybe the numbers are so big that it reaches the limit of what can be stored under a given data type.)
Regardless of the reason, the idea is to ma... | [
"You've pretty much already answered your question, so I'll just confirm your suspicion: the reason the OptimizeWarning is raised is because the underlying optimization algorithm doesn't work properly/diverges due to large parameter numbers.\nThe solution is very simple, just scale your input parameters before usin... | [
1
] | [] | [] | [
"curve_fitting",
"matplotlib",
"python",
"scipy"
] | stackoverflow_0074675326_curve_fitting_matplotlib_python_scipy.txt |
Q:
Dictionary Py. Bid auction game. It should print the name and the bid of the person who bade higher but it keeps printing the last inserted key/value
I have this code:
def calc_winner(bidd):
count = 0
winner = ''
for name in bidd:
higher = bidd[name]
if higher > count:
count = higher
winner = s... | Dictionary Py. Bid auction game. It should print the name and the bid of the person who bade higher but it keeps printing the last inserted key/value | I have this code:
def calc_winner(bidd):
count = 0
winner = ''
for name in bidd:
higher = bidd[name]
if higher > count:
count = higher
winner = str(name)
print(f"The winner is {winner}, who bid ${count}.")
calc_winner({"a": 1, "b": 2, "c": 0})
The code is supposed to find the highest bid and the... | [
"I checked your code and it seem to work. You just did not indent it properly :)\nHere is the working one:\nfrom replit import clear\n\nbidding = {}\nend = True\n\ndef calc_winner(bidd):\n count = 0\n winner = \"\"\n for name in bidd:\n higher = bidd[name]\n if higher > count:\n co... | [
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074675821_dictionary_python.txt |
Q:
Django cannot save a CharField with choices
I have this CharField with some choices:
M = 'Male'
F = 'Female'
O = 'Other'
GENDER = [
(M, "Male"),
(F, "Female"),
(O, "Other")
]
gender = models.CharField(max_length=10, choices=GENDER)
When I try and save a model in the da... | Django cannot save a CharField with choices | I have this CharField with some choices:
M = 'Male'
F = 'Female'
O = 'Other'
GENDER = [
(M, "Male"),
(F, "Female"),
(O, "Other")
]
gender = models.CharField(max_length=10, choices=GENDER)
When I try and save a model in the database I get the following error:
django.db.utils... | [
"This error is occurring because you are trying to save the value of the gender field in the database as a string, but the field is expecting an array of values. In order to fix this, you will need to change the value that is being sent from the front end to be an array instead of a string.\nFor example, instead of... | [
0
] | [] | [] | [
"django",
"postgresql",
"python"
] | stackoverflow_0074675835_django_postgresql_python.txt |
Q:
Speed up multiplication of two dense tensors
I want to perform element wise multiplication between two tensors, where most of the elements are zero.
For two example tensors:
test1 = np.zeros((2, 3, 5, 6))
test1[0, 0, :, 2] = 4
test1[0, 1, [2, 4], 1] = 7
test1[0, 2, 2, :] = 2
test1[1, 0, 4, 1:3] = 5
test1[1, :, 0,... | Speed up multiplication of two dense tensors | I want to perform element wise multiplication between two tensors, where most of the elements are zero.
For two example tensors:
test1 = np.zeros((2, 3, 5, 6))
test1[0, 0, :, 2] = 4
test1[0, 1, [2, 4], 1] = 7
test1[0, 2, 2, :] = 2
test1[1, 0, 4, 1:3] = 5
test1[1, :, 0, 1] = 3
and,
test2 = np.zeros((5, 6, 4, 7))
te... | [
"SIZE: 5000 DENSITY: 0.01 DEVICE: cpu\ntorch: 0.0306358 seconds\nnp: 0.000252247 seconds\ntorch/np: 121.452\nSIZE: 5000 DENSITY: 0.01 DEVICE: cuda\ntorch: 0.0127137 seconds\nnp: 0.000259161 seconds\ntorch/np: 49.057\nSIZE: 10000 DENSITY: 0.01 DEVICE: cpu\ntorch: 0.155527 seconds\nnp: 0.00106144 seconds\nto... | [
0
] | [] | [] | [
"numpy",
"python",
"tensor",
"vectorization"
] | stackoverflow_0074675872_numpy_python_tensor_vectorization.txt |
Q:
Seaborn Striplot data visualization not applying colors to markers/bars/strips
When creating a stripplot with seaborn, the code creates a striplot perfectly. Applies colors to the legend and all. Except the color is not applying to the various strips in within the stripplot. Appreciate the seaborn/matplotlib exper... | Seaborn Striplot data visualization not applying colors to markers/bars/strips | When creating a stripplot with seaborn, the code creates a striplot perfectly. Applies colors to the legend and all. Except the color is not applying to the various strips in within the stripplot. Appreciate the seaborn/matplotlib experts here, because I am at a loss. Code is below. Picture attached below with my resul... | [
"Matplotlib has two types of markers. Most are filled (e.g. as circle with a border). Some are unfilled (e.g. a horizontal line).\nSeaborn uses the hue color only for the interior, and uses a fixed color (default black) for the borders (edges). If I try to run your code, I get a warning from matplotlib complainin... | [
1
] | [] | [] | [
"matplotlib",
"python",
"seaborn",
"visualization"
] | stackoverflow_0074672393_matplotlib_python_seaborn_visualization.txt |
Q:
Speed Up Keras Model Prediction
Trying to detect emotion using Keras and grabbing the desktop with mss and them display back to the OpenCV Window.
The keras model size is 360 mb.
import time
import cv2
import mss
import numpy as np
face_cascade = cv2.CascadeClassifier('face.xml')
label = ["angry", "happy", "sad",... | Speed Up Keras Model Prediction | Trying to detect emotion using Keras and grabbing the desktop with mss and them display back to the OpenCV Window.
The keras model size is 360 mb.
import time
import cv2
import mss
import numpy as np
face_cascade = cv2.CascadeClassifier('face.xml')
label = ["angry", "happy", "sad", "stress"]
monitor = {"top": 0, "left... | [
"There are a few ways to potentially speed up this process:\nUse a smaller model: 360mb is quite large for a Keras model, so using a smaller model with fewer layers and parameters may improve performance.\nUse a faster hardware: The speed of this process is likely hardware-bound, so using a faster CPU or GPU may im... | [
1
] | [] | [] | [
"keras",
"opencv",
"python"
] | stackoverflow_0074675873_keras_opencv_python.txt |
Q:
Request Mock in Python
'''
api = API(url, timeout=2)
response = api.get("")
if response.success:
c = response.body['content']
return c
'''
for above function , I've mocked in following way
'''
mock_response = MagicMock(success = True)
mock_response.body.return_value = {'con... | Request Mock in Python | '''
api = API(url, timeout=2)
response = api.get("")
if response.success:
c = response.body['content']
return c
'''
for above function , I've mocked in following way
'''
mock_response = MagicMock(success = True)
mock_response.body.return_value = {'content':923,'a':1256}
mock... | [
"To make the mock return the correct value for response.body['content'], you need to set the body attribute of the mock response object to a dictionary containing the content key. Here is an example:\nfrom unittest.mock import MagicMock\n\n# Set up the mock response object\nmock_response = MagicMock(success=True)\n... | [
0
] | [] | [] | [
"mocking",
"python"
] | stackoverflow_0074675893_mocking_python.txt |
Q:
partial cumulative sum in python
Suppose I have a numpy array (or pandas Series if it makes it any easier), which looks like this:
foo = np.array([1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0])
I want to transform into an array
bar = np.array([0, 1, 2, 3, 4,0, 1, 2, 0, 1, 2, 3])
where the entry is how many steps you need ... | partial cumulative sum in python | Suppose I have a numpy array (or pandas Series if it makes it any easier), which looks like this:
foo = np.array([1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0])
I want to transform into an array
bar = np.array([0, 1, 2, 3, 4,0, 1, 2, 0, 1, 2, 3])
where the entry is how many steps you need to walk to the left to find a 1 in foo... | [
"You could do cumcount with pandas\ns = pd.Series(foo)\nbar = s.groupby(s.cumsum()).cumcount().to_numpy()\nOut[13]: array([0, 1, 2, 3, 4, 0, 1, 2, 0, 1, 2, 3], dtype=int64)\n\n",
"One option, specifically for the shared example, with numpy:\n# get positions where value is 1\npos = foo.nonzero()[0]\n# need this wh... | [
9,
2,
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074620655_numpy_pandas_python.txt |
Q:
Scrapy use private proxy
I am using customly configured VM to act as a proxy server (via squid) and now I try to use it for my scraper. I am using scrapy-rotating-proxies to rotate trought my ip list definition but the problem is that my proxy is treated as DEAD right on the first attempt even thought I have verif... | Scrapy use private proxy | I am using customly configured VM to act as a proxy server (via squid) and now I try to use it for my scraper. I am using scrapy-rotating-proxies to rotate trought my ip list definition but the problem is that my proxy is treated as DEAD right on the first attempt even thought I have verified that the proxy address is ... | [
" \"scrapy.downloadermiddlewares.useragent.UserAgentMiddleware\": None,\n \"scrapy.downloadermiddlewares.retry.RetryMiddleware\": None,\n\nThese middlewares was the issue, I cannot explain why scrapy was able to process my requests without proxies while having these middlewares enabled but after disabling them ... | [
0
] | [] | [] | [
"proxy",
"python",
"scrapy",
"squid"
] | stackoverflow_0074656742_proxy_python_scrapy_squid.txt |
Q:
Is there a way to extract all styles from an existing word document with python-docx and apply them to a newly generated one?
I'm new to python-docx and I'm trying to bild a document generator. What I'd like to do is to use an existing word document to extract its styles and then apply these to a newly generated o... | Is there a way to extract all styles from an existing word document with python-docx and apply them to a newly generated one? | I'm new to python-docx and I'm trying to bild a document generator. What I'd like to do is to use an existing word document to extract its styles and then apply these to a newly generated one. So then whenever I use something like
document.add_heading('Test Heading', level=2)
the level 2 heading is the same as in the ... | [
"You can extract the styles from an existing Word document by using the get_style_id method of the Document object. This method takes the name of the style you want to extract as an argument and returns the style ID. You can then use this style ID when adding a heading to the new document to ensure that it has the ... | [
1
] | [] | [] | [
"python",
"python_docx"
] | stackoverflow_0074675909_python_python_docx.txt |
Q:
Not getting a fitted curve
I am not getting a fitted curve when I run this code. Instead, I am getting a random curve. Please help. Thanks in advance.
def cauchy(x, l, k, x1, a):
return l / (1+np.exp(-k*(x-x1))) + a
amplitude = [11, 9, 15, 18, 23, 62, 225, 537, 534, 251, 341, 8, 716, 653, 673]
... | Not getting a fitted curve | I am not getting a fitted curve when I run this code. Instead, I am getting a random curve. Please help. Thanks in advance.
def cauchy(x, l, k, x1, a):
return l / (1+np.exp(-k*(x-x1))) + a
amplitude = [11, 9, 15, 18, 23, 62, 225, 537, 534, 251, 341, 8, 716, 653, 673]
distance = np.arange(0,15)
... | [
"There could be a few reasons why you are not getting a fitted curve in this code. Some potential issues are:\nThe data provided for fitting the curve is not sufficient or is not appropriate for the Cauchy function. The data should be continuous and have a clear pattern for the curve fitting to work properly.\nThe ... | [
1
] | [] | [] | [
"curve_fitting",
"python"
] | stackoverflow_0074675927_curve_fitting_python.txt |
Q:
Cannot import name 'win32api' from 'PyInstaller.compat'
I am trying to run pyinstaller in msys2 in Windows7. However, I am getting following error:
ImportError: cannot import name 'win32api' from 'PyInstaller.compat' (/usr/lib/python3.10/site-packages/PyInstaller/compat.py)
I checked on the internet and found pos... | Cannot import name 'win32api' from 'PyInstaller.compat' | I am trying to run pyinstaller in msys2 in Windows7. However, I am getting following error:
ImportError: cannot import name 'win32api' from 'PyInstaller.compat' (/usr/lib/python3.10/site-packages/PyInstaller/compat.py)
I checked on the internet and found possible solution: pip install pypiwin32. However, it is giving ... | [
"It looks like the error is coming from the package itself, specifically with the syntax used in the code. The error message indicates that there is a missing parenthesis in a print statement, and suggests that you should use print() instead of just print.\nTo solve the issue, you could try installing an older vers... | [
1
] | [] | [] | [
"pyinstaller",
"python"
] | stackoverflow_0074675800_pyinstaller_python.txt |
Q:
How can I bind FocusOut and Button-2 to a button?
There are many questions about binding 2 functions to an event or binding Ctrl+Key, space+Key to a button,
but I need to know how I can bind FocusOut + Button-2 to a button.
It may seem weird that I need it, but I do.
So my scenario is that after I open the widge... | How can I bind FocusOut and Button-2 to a button? | There are many questions about binding 2 functions to an event or binding Ctrl+Key, space+Key to a button,
but I need to know how I can bind FocusOut + Button-2 to a button.
It may seem weird that I need it, but I do.
So my scenario is that after I open the widget, I will click somewhere else outside the widget to re... | [
"Does this help? You can't put root.bind in one line.\nTry this:\nimport tkinter as tk\n\ndef test(event):\n print('test')\n\nroot = tk.Tk()\n\nroot.bind(\"<FocusIn>\", test)\nroot.bind(\"<Button-2>\", test)\nroot.mainloop()\n\n"
] | [
0
] | [] | [] | [
"mouse",
"mouseevent",
"python",
"tkinter"
] | stackoverflow_0074674338_mouse_mouseevent_python_tkinter.txt |
Q:
Computing KL-divergence over 2 estimated gaussian KDEs
I have two datasets with the same features and would like to estimate the "distance of distributions" between the two datasets. I had the idea to estimate a gaussian KDE in each of the datasets and computing the KL-divergence between the estimated KDEs. Howeve... | Computing KL-divergence over 2 estimated gaussian KDEs | I have two datasets with the same features and would like to estimate the "distance of distributions" between the two datasets. I had the idea to estimate a gaussian KDE in each of the datasets and computing the KL-divergence between the estimated KDEs. However, I am struggling to compute the "distance" between the dis... | [
"There is no closed form solution for KL between two mixtures of gaussians.\nKL(p, q) := -E_p log [p(x)/q(x)]\n\nso you can use MC estimator:\ndef KL_mc(p, q, n=100):\n points = p.resample(n)\n p_pdf = p.pdf(points)\n q_pdf = q.pdf(points)\n return np.log(p_pdf / q_pdf).mean()\n\nNote:\n\nyou might need to add ... | [
1
] | [] | [] | [
"machine_learning",
"python",
"scikit_learn",
"statistics"
] | stackoverflow_0074675438_machine_learning_python_scikit_learn_statistics.txt |
Q:
Rearranging with pandas melt
I am trying to rearrange a DataFrame. Currently, I have 1035 rows and 24 columns, one for each hour of the day. I want to make this a array with 1035*24 rows. If you want to see the data it can be extracted from the following JSON file:
url = "https://www.svk.se/services/controlroom/v2... | Rearranging with pandas melt | I am trying to rearrange a DataFrame. Currently, I have 1035 rows and 24 columns, one for each hour of the day. I want to make this a array with 1035*24 rows. If you want to see the data it can be extracted from the following JSON file:
url = "https://www.svk.se/services/controlroom/v2/situation?date={}&biddingArea=SE1... | [
"To rearrange the DataFrame in the desired way, you can use the pandas.DataFrame.stack method to reshape the DataFrame from wide to long format. Then, you can drop the variable column and rename the date column to the desired name.\nconsumption_svk_1 = (svk.stack()\n .reset_index()\n ... | [
0
] | [] | [] | [
"json",
"pandas_melt",
"python"
] | stackoverflow_0074675971_json_pandas_melt_python.txt |
Q:
I'm trying to split and remove unnecessary characters from a column using pandas
I'm trying to remove all the unnecessary words and characters from the values in this column. I want the rows to contain 'Entry level', 'Mid-Senior level' etc. Also is there anyway to translate the arabic to english or shall I use rep... | I'm trying to split and remove unnecessary characters from a column using pandas | I'm trying to remove all the unnecessary words and characters from the values in this column. I want the rows to contain 'Entry level', 'Mid-Senior level' etc. Also is there anyway to translate the arabic to english or shall I use replace function?
df_africa.seniority_level.value_counts()
{'Seniority level': 'Entry lev... | [
"IIUC, use this :\nimport ast\n\n#Is there any non-latin letters?\nm = ~df_africa[\"seniority_level\"].str.contains(\"[A-Z]\")\n\ns = df_africa[\"seniority_level\"].apply(lambda x: ast.literal_eval(x))\ndf_africa[\"new_col\"] = s.str[\"مستوى الأقدمية\"].where(m, s.str[\"Seniority level\"])\n\nIf you need to transl... | [
0,
0
] | [] | [] | [
"pandas",
"python",
"python_3.x",
"split"
] | stackoverflow_0074674980_pandas_python_python_3.x_split.txt |
Q:
Selenium driver hanging on OS alert
I'm using Selenium in Python (3.11) with a Firefox (107) driver.
With the driver I navigate to a page which, after several actions, triggers an OS alert (prompting me to launch a program). When this alert pops up, the driver hangs, and only once it is closed manually does my scr... | Selenium driver hanging on OS alert | I'm using Selenium in Python (3.11) with a Firefox (107) driver.
With the driver I navigate to a page which, after several actions, triggers an OS alert (prompting me to launch a program). When this alert pops up, the driver hangs, and only once it is closed manually does my script continue to run.
I have tried driver.... | [
"There are some prefs you can try\nprofile = webdriver.FirefoxProfile()\nprofile.set_preference('dom.push.enabled', False)\n\n# or\n\nprofile = webdriver.FirefoxProfile()\nprofile.set_preference('dom.webnotifications.enabled', False)\nprofile.set_preference('dom.webnotifications.serviceworker.enabled', False)\n\n",... | [
3,
3,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"selenium",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0074563548_python_python_3.x_selenium_selenium_chromedriver_selenium_webdriver.txt |
Q:
python: AttributeError: 'list' object has no attribute 'groupby'
I am following a Youtube tutorial on a streamlit application, however the error
"AttributeError: 'list' object has no attribute 'groupby'"
occured when I was trying to group my list that I scraped from wikipedia, the instructor had the exact code a... | python: AttributeError: 'list' object has no attribute 'groupby' | I am following a Youtube tutorial on a streamlit application, however the error
"AttributeError: 'list' object has no attribute 'groupby'"
occured when I was trying to group my list that I scraped from wikipedia, the instructor had the exact code as me but didn't face a problem, where am I missing out exactly?
import... | [
"I fixed it, I just had to reassign the df variable to it's first index\nimport streamlit as st\nimport pandas as pd\n\n@st.cache\ndef load_data():\n url = \"https://en.wikipedia.org/wiki/List_of_S%26P_500_companies\"\n html = pd.read_html(url, header=0)\n df = html[0]\n return df\n\ndf = load_data()\nd... | [
1
] | [] | [] | [
"pandas",
"python",
"streamlit"
] | stackoverflow_0074675820_pandas_python_streamlit.txt |
Q:
Parsing an XML file that contains HTML snippets, renaming HTML class names, and then write back the XML file
I've got XML files that contain HTML snippets. I'm trying to write a Python script that opens such an XML file, searches for the elements containing the HTML, renames the classes, and then writes back the n... | Parsing an XML file that contains HTML snippets, renaming HTML class names, and then write back the XML file | I've got XML files that contain HTML snippets. I'm trying to write a Python script that opens such an XML file, searches for the elements containing the HTML, renames the classes, and then writes back the new XML file to file.
Here's an XML example:
<?xml version="1.0" encoding="UTF-8"?>
<question_categories>
<questi... | [
"After your comment I have changed my code a little bit.\nNow the html part is correct escaped, but the empty tags are gone. Anyway the XML is valid. It seems tree.write() have some trouble with mixed XML and inserted html sequences.\nimport xml.etree.ElementTree as ET\nfrom html import escape, unescape\n\ntree = E... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"xml"
] | stackoverflow_0074669395_beautifulsoup_html_python_xml.txt |
Q:
Understanding of degree calcuation in quadrants
I found something in my search, which I don't understand. The goal is to read out the angle of a pointer in a pressure gauge. In my research, I found this example:
https://circuits-ninja.pl/reading-an-indication-from-an-analog-pressure-gauge-using-the-esp32-cam-modul... | Understanding of degree calcuation in quadrants | I found something in my search, which I don't understand. The goal is to read out the angle of a pointer in a pressure gauge. In my research, I found this example:
https://circuits-ninja.pl/reading-an-indication-from-an-analog-pressure-gauge-using-the-esp32-cam-module-with-an-ov2640-and-opencv-camera/
He's calculating ... | [
"I think this is because 0 degrees is located, if placed on a two-dimensional surface, on (0,1)=(cos(90),sin(90)) instead of (1,0)=(cos(0),sin(0)). This means it has an offset of 90 degrees.\n",
"Much simpler way:\n res = np.arctan2(float(y_angle), float(x_angle))\n #Converting to degrees\n res = np.rad2deg(res)\... | [
0,
0
] | [] | [] | [
"math",
"numpy",
"python"
] | stackoverflow_0074674308_math_numpy_python.txt |
Q:
Losing cell formats when accessing rows
In some circumstances the format (int, float, etc) of a cell is lost when accessing via its row.
In that example the first column has integers and the second floats. But the 111 is converted into 111.0.
dfA = pandas.DataFrame({
'A': [111, 222, 333],
'B': [1.3, 2.4, 3... | Losing cell formats when accessing rows | In some circumstances the format (int, float, etc) of a cell is lost when accessing via its row.
In that example the first column has integers and the second floats. But the 111 is converted into 111.0.
dfA = pandas.DataFrame({
'A': [111, 222, 333],
'B': [1.3, 2.4, 3.5],
})
# A 111.0
# B 1.3
# Name: 0,... | [
"If you want to access a specific value in the DataFrame without losing its data type, you can use the at method instead of the loc method. The at method accesses a scalar value in the DataFrame, so it will preserve the data type of the value. See: print(type(dfA.at[0, 'A']))\nIn this example, the at method is used... | [
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074677068_numpy_pandas_python.txt |
Q:
How to arrange all the alphabets in my name in sorted manner?
How to arrange alphabets in myname in sorted manner?
I have used the sort function but that din't work and solve it?
A:
Like this?
import re
my_name = "Mohammed Sardar Saajit"
my_name_with_the_letters_sorted = sorted([character for character in re.sub... | How to arrange all the alphabets in my name in sorted manner? | How to arrange alphabets in myname in sorted manner?
I have used the sort function but that din't work and solve it?
| [
"Like this?\nimport re\nmy_name = \"Mohammed Sardar Saajit\"\nmy_name_with_the_letters_sorted = sorted([character for character in re.sub(r\"[^\\w]\", \"\", my_name.lower())], key=ord)\nprint(my_name_with_the_letters_sorted)\n\n['a', 'a', 'a', 'a', 'a', 'd', 'd', 'e', 'h', 'i', 'j', 'm', 'm', 'm', 'o', 'r', 'r', 's... | [
0
] | [] | [] | [
"python",
"sorting",
"word"
] | stackoverflow_0074676020_python_sorting_word.txt |
Q:
Error (task exception was never retrieved) when running discord bot commands
I am making a discord bot using python, and I have run into an unexplainable error which I am unable to fix. I thought I fixed it by deleting the checks but I'm completely stumped by the massive block of errors I'm getting.
If anyone coul... | Error (task exception was never retrieved) when running discord bot commands | I am making a discord bot using python, and I have run into an unexplainable error which I am unable to fix. I thought I fixed it by deleting the checks but I'm completely stumped by the massive block of errors I'm getting.
If anyone could please decode even some of this, I would be greatly appreciative.
Task exception... | [
"In the file C:\\Users\\mitsuk\\Documents\\rirakkumabot\\main\\helpers\\db_manager.py, line 8\nasync with db.execute(\"SELECT * FROM blacklist WHERE user_id=?\", (user_id,)) as cursor:\n\nError message\nsqlite3.OperationalError: no such table: blacklist\n\nThis error means that there's no table named blacklist in t... | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074675786_discord.py_python.txt |
Q:
How to improve performance - Merge two dataframes by closest geodetic distance
I have two dataframes, one radar which represents data on an equispaced grid with columns for longitude, latitude and height value, and one ice that has some information related to satellite observations, including the latitude and long... | How to improve performance - Merge two dataframes by closest geodetic distance | I have two dataframes, one radar which represents data on an equispaced grid with columns for longitude, latitude and height value, and one ice that has some information related to satellite observations, including the latitude and longitude of the observation. I want to merge the two so I can get ice with the 'height'... | [
"below code takes less than a second on my machine. Probably not working around equator/greenwich\nimport pandas as pd\nimport numpy as np\nfrom scipy.spatial import KDTree\n\n#reading data\nradar = pd.read_csv(\"radar.csv\")\nice = pd.read_csv(\"ice.csv\")\n\n#extrating points data\npts = np.array(radar.loc[:, [\"... | [
1
] | [] | [] | [
"dataframe",
"distance",
"merge",
"pandas",
"python"
] | stackoverflow_0074669645_dataframe_distance_merge_pandas_python.txt |
Q:
error using pyinstaller exe when python ttp module is in place
I am trying convert my .py file to an exe file using pyinstaller. The .py file perfectly work fine, however, I am facing an issue after the program is converted to .exe file. The problem is shared right below. ttp.lazy_import_functions: failed to save ... | error using pyinstaller exe when python ttp module is in place | I am trying convert my .py file to an exe file using pyinstaller. The .py file perfectly work fine, however, I am facing an issue after the program is converted to .exe file. The problem is shared right below. ttp.lazy_import_functions: failed to save problem with File not found indication.
[![enter image description h... | [
"From what i see, the ttp module tries to access its files and has references to the installation path for ttp which it cannot get to using the os module after its bundled by pyinstaller.\nOne simpler workaround than changing the module files and applying the patch file that you did, would be to just copy the insta... | [
0
] | [] | [] | [
"exe",
"pyinstaller",
"python",
"python_3.x"
] | stackoverflow_0074173221_exe_pyinstaller_python_python_3.x.txt |
Q:
Pandas resample drops (static) datetime column, how do I keep it?
I'm working with a pandas Multiindex that is given by the three keys:
[Verbundzuordnung, ProjektIndex, Datum],
I would like to resample the dataframe on Datum hourly, which drops the right colum TagDesAbdichtens, I would like to keep it as it's sta... | Pandas resample drops (static) datetime column, how do I keep it? | I'm working with a pandas Multiindex that is given by the three keys:
[Verbundzuordnung, ProjektIndex, Datum],
I would like to resample the dataframe on Datum hourly, which drops the right colum TagDesAbdichtens, I would like to keep it as it's static.
Verbundzuordnung ProjektIndex Datum ... | [
"I've had success resampling using the native resample function. For example,\n resample_dict = { \n 'Verbundzuordnung': 'mean', ... | [
0,
0
] | [] | [] | [
"datetime",
"group_by",
"pandas",
"pandas_resample",
"python"
] | stackoverflow_0074675902_datetime_group_by_pandas_pandas_resample_python.txt |
Q:
How can I display the new value made by input for the next screen in Kivy
I have been trying to make this code work. Im using ScreenManager to manage my screen.
I want the Input I entered on the first screen to be displayed the next screen. But instead, it just shows the initial value, and it doesn't change to the... | How can I display the new value made by input for the next screen in Kivy | I have been trying to make this code work. Im using ScreenManager to manage my screen.
I want the Input I entered on the first screen to be displayed the next screen. But instead, it just shows the initial value, and it doesn't change to the Inputted value.
Here is the Code i have done
from kivy.app import App
from kiv... | [
"thank you for the concise single-file example. this is a very helpful way to submit a kivy question. I have modified and tested the below app with various changes.\nI changed the root.submit to app.submit. This is not strictly required, it is just a choice in this example to put the logic in the main app. it i... | [
0
] | [] | [] | [
"kivy",
"kivy_language",
"python"
] | stackoverflow_0074675350_kivy_kivy_language_python.txt |
Q:
How to get the most recent message of a channel in discord.py?
Is there a way to get the most recent message of a specific channel using discord.py? I looked at the official docs and didn't find a way to.
A:
I've now figured it out by myself:
For a discord.Client class you just need these lines of code for the l... | How to get the most recent message of a channel in discord.py? | Is there a way to get the most recent message of a specific channel using discord.py? I looked at the official docs and didn't find a way to.
| [
"I've now figured it out by myself:\nFor a discord.Client class you just need these lines of code for the last message:\n\n(await self.get_channel(CHANNEL_ID).history(limit=1).flatten())[0]\n\n\nIf you use a discord.ext.commands.Bot @thegamecracks' answer is correct.\n",
"(Answer uses discord.ext.commands.Bot ins... | [
9,
6,
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0064080277_discord_discord.py_python.txt |
Q:
Is there any way to install and unpack a github repository through code without using git bash and the like?
Currently I have a problem where I need to install all contents of a github repository (https://github.com/reversinglabs/reversinglabs-yara-rules) through code without using git bash or the like.
In this ca... | Is there any way to install and unpack a github repository through code without using git bash and the like? | Currently I have a problem where I need to install all contents of a github repository (https://github.com/reversinglabs/reversinglabs-yara-rules) through code without using git bash or the like.
In this case I need to fully install the yara repository from said github.
Any one knows a way to do it in c,c++,c#,python?
... | [
"It's not clear what part of bash, etc, you do not want to use. A simple way otherwise is to just call git through std::system()\n#include <cstdlib>\n\nint main(int argc, char**argv) {\n std::system(\"git clone ...\");\n}\n\nI have used it in many cases where I need to integrate git commands in a c++ program.\n"... | [
1,
1,
0
] | [] | [] | [
"c#",
"c++",
"git",
"python"
] | stackoverflow_0074360270_c#_c++_git_python.txt |
Q:
Plot duration of processes along with date, start and end timestamps
I am trying to plot duration of processes, starting from the following data frame
variable
year
start
end
seconds
hours
start_time
start_date
0
10m_u_component_of_wind
2005
2022-04-25 13:14:45
2022-04-26 02:13:56
46751
12.986389
13:14
1
10m_u_... | Plot duration of processes along with date, start and end timestamps | I am trying to plot duration of processes, starting from the following data frame
variable
year
start
end
seconds
hours
start_time
start_date
0
10m_u_component_of_wind
2005
2022-04-25 13:14:45
2022-04-26 02:13:56
46751
12.986389
13:14
1
10m_u_component_of_wind
2006
2022-04-26 04:56:26
2022-04-26 14:56:35
3600... | [
"I came up with something close and convinced it is easier than thought to create a plot, as per the question, using the awesomeness of Bokeh:\n\nSource code posted at: https://discourse.bokeh.org/t/plotting-timestamps-values-and-highlighting-time-ranges/9804?u=nikosalexandris\n"
] | [
0
] | [] | [] | [
"datetime",
"matplotlib",
"python",
"seaborn"
] | stackoverflow_0073442993_datetime_matplotlib_python_seaborn.txt |
Q:
How to do Delete confirmation for a table data with bootstrap Modal in Django?
I'm having a table to show a list of actions in my app. I can delete any action in that table. So, I have added a delete button in every row. This delete button will trigger a 'delete confirmation' bootstrap modal.
<table class="table t... | How to do Delete confirmation for a table data with bootstrap Modal in Django? | I'm having a table to show a list of actions in my app. I can delete any action in that table. So, I have added a delete button in every row. This delete button will trigger a 'delete confirmation' bootstrap modal.
<table class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col" c... | [
"If any of you are going through this scenario, I have a quick fix.\n\nThe main idea is to change the form's action URL using Javascript\n\nviews.py\nclass DeleteAddressView(DeleteView):\n success_url = reverse_lazy(\"home\")\n\nI will try to provide the minimum solution here:\nmy link in the list for delete ite... | [
5,
1,
1,
0,
0,
0
] | [] | [] | [
"bootstrap_modal",
"django",
"django_templates",
"jinja2",
"python"
] | stackoverflow_0059566549_bootstrap_modal_django_django_templates_jinja2_python.txt |
Q:
Searching for one even and one odd number in string
So I'm going through old advent of codes and came across this one and it asks me to search each string to make sure it has at least one even and one odd number in it. However, my function doesn't correctly sort the list. It runs without errors, but it never filte... | Searching for one even and one odd number in string | So I'm going through old advent of codes and came across this one and it asks me to search each string to make sure it has at least one even and one odd number in it. However, my function doesn't correctly sort the list. It runs without errors, but it never filters anything and just prints out everything. I don't reall... | [
"I would use set operations:\nodds = set('13579')\nevens = set('02468')\n\ndef one_even_one_odd(string):\n S = set(string)\n return bool(odds & S) and bool(evens & S)\n \n \none_even_one_odd('ABCD125')\n# True\n\none_even_one_odd('ABCD135')\n# False\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074677212_python.txt |
Q:
Detect if Multiple HDDs are RAID and it's RAID mode(windows)
In order to monitor system storage, I need to programmatically find :
if Multiple HDDs are used (done)
if Multiple HDDs are RAID (not done)
if they are RAID, what is the RAID mode (RAID0, RAID1, ...) (not even closed)
What I know/can:
There are 2 typ... | Detect if Multiple HDDs are RAID and it's RAID mode(windows) | In order to monitor system storage, I need to programmatically find :
if Multiple HDDs are used (done)
if Multiple HDDs are RAID (not done)
if they are RAID, what is the RAID mode (RAID0, RAID1, ...) (not even closed)
What I know/can:
There are 2 types of RAID , Hardware and Software.
If it's Software then it can b... | [] | [] | [
"idk maybe you should try to search online for a reg key that contains this info\nbut i guess that the os doesn't know this info, but anyway you should try maybe you'll find something about it\n"
] | [
-1
] | [
"c#",
"c++",
"cmd",
"powershell",
"python"
] | stackoverflow_0049852709_c#_c++_cmd_powershell_python.txt |
Q:
Python - compound interest calculation issue - cs1301 edx extra practice 5
I have the following problem I can't manage to solve:
Find "How much do I need to invest to have a certain amount by a certain year?" For example, "How much do I need to invest to have $50,000 in 5 years at 5% (0.05) interest?"
Mathematical... | Python - compound interest calculation issue - cs1301 edx extra practice 5 | I have the following problem I can't manage to solve:
Find "How much do I need to invest to have a certain amount by a certain year?" For example, "How much do I need to invest to have $50,000 in 5 years at 5% (0.05) interest?"
Mathematically, the formula for this is:
goal / e ^ (rate * number of years) = principal
Add... | [
"You are using rate instead of years for the year.\ngoal = float(goal)\nyears = float(rate) <-- Here\nrate = rate\n\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074677246_python_python_3.x.txt |
Q:
Offsetting a timestamp on a Cassandra query
Probably a dumb question but I'm using toTimestamp(now()) to retrieve the timestamp. Is there any way to offset the now() by my specified timeframe.
What I have now:
> print(session.execute('SELECT toTimestamp(now()) FROM system.local').one())
2022-12-04 12:12:47.011000
... | Offsetting a timestamp on a Cassandra query | Probably a dumb question but I'm using toTimestamp(now()) to retrieve the timestamp. Is there any way to offset the now() by my specified timeframe.
What I have now:
> print(session.execute('SELECT toTimestamp(now()) FROM system.local').one())
2022-12-04 12:12:47.011000
My goal:
> print(session.execute('SELECT toTimes... | [
"To offset the timestamp returned by the toTimestamp(now()) function in Apache Cassandra, you can use the dateOf function to subtract a specified amount of time from the current timestamp.\nHere is an example of how you can use this query in your code:\nresult = session.execute('SELECT toTimestamp(dateOf(now()) - 1... | [
0,
0
] | [] | [] | [
"cassandra",
"cql",
"python",
"python_3.x"
] | stackoverflow_0074675507_cassandra_cql_python_python_3.x.txt |
Q:
Assigning functions to dynamically created buttons in kivy?
I am working on this program in which a list buttons gets created dynamically, based on the items in a list. The code I am using for this is:
self.list_of_btns = []
def create(self, list=items): #Creates ... | Assigning functions to dynamically created buttons in kivy? | I am working on this program in which a list buttons gets created dynamically, based on the items in a list. The code I am using for this is:
self.list_of_btns = []
def create(self, list=items): #Creates Categorie Buttons
self.h = 1
for i in list:
... | [
".bind() method can be used. In this example, partial is used in order to preset an argument so that each button does something unique. self.btn was changed to _btn because the references are being added to a list and self.btn was repeatedly assigned a new object. I didn't think this was intended, but it is not ... | [
0
] | [] | [] | [
"dynamic",
"kivy",
"python"
] | stackoverflow_0074677171_dynamic_kivy_python.txt |
Q:
Create regularly-spaced vector points from irregular XY geographic data in Python
I have point (vector) coordinates in meters (x and y in 1-D arrays) which are irregularly spaced. I would like to re-sample the points so that they are regularly spaced by 10 m between each set of XY points.
I have managed to regular... | Create regularly-spaced vector points from irregular XY geographic data in Python | I have point (vector) coordinates in meters (x and y in 1-D arrays) which are irregularly spaced. I would like to re-sample the points so that they are regularly spaced by 10 m between each set of XY points.
I have managed to regularly re-sample the points in the X direction (see code below), however when trying to use... | [
"Would you consider\n\nfinding the interpolation line ST_LineInterpolatePoints\nmeasure the length of the line [in meters], ST_Length\ndivide it by 10 [m] to find number of slots,\ndivide the line by number of slots to find the coordinates for each group of points, ST_LineSubstring\ndivide number of points by numbe... | [
0,
0
] | [] | [] | [
"coordinates",
"gis",
"python",
"qgis",
"vector"
] | stackoverflow_0070771182_coordinates_gis_python_qgis_vector.txt |
Q:
How to cut out part of an image based on coordinates of a given circle
I'm trying to cut out part of an image based on some circles coordinates, my initial attempts have been to try doing this
startx = circle[0]
starty = circle[1]
radius = circle[2]
recImage = cv2.rectangle(image,(startx-radius,starty-radius), (st... | How to cut out part of an image based on coordinates of a given circle | I'm trying to cut out part of an image based on some circles coordinates, my initial attempts have been to try doing this
startx = circle[0]
starty = circle[1]
radius = circle[2]
recImage = cv2.rectangle(image,(startx-radius,starty-radius), (startx+radius,starty+radius), (0,0,255),2)
miniImage = recImage[startx-radius:... | [
"There is a mistake in your code. You are using the coordinates of the center of the circle to draw the rectangle and cut out the mini image. However, the coordinates of the top left corner of the rectangle should be used to draw the rectangle and cut out the mini image.\nHere is the updated code:\nstartx = circle[... | [
0
] | [] | [] | [
"image",
"opencv",
"python"
] | stackoverflow_0074677301_image_opencv_python.txt |
Q:
terminal user interface with python
what is the best TUI module to use with python , I used prompt-toolkit and I can't use so many things in it like Layout and I can't use a view in textual there is so many errors .
I want to build TUI for myself, and I want a well documented and working TUI or CUI python module
... | terminal user interface with python | what is the best TUI module to use with python , I used prompt-toolkit and I can't use so many things in it like Layout and I can't use a view in textual there is so many errors .
I want to build TUI for myself, and I want a well documented and working TUI or CUI python module
| [
"There are many TUI libraries available for Python, and the best one for you will depend on your specific needs and preferences. Some popular options include curses, npyscreen, urwid, and blessings. All of these libraries provide basic TUI functionality, such as creating and positioning text and interactive element... | [
0,
0
] | [] | [] | [
"command_line_interface",
"python",
"tui"
] | stackoverflow_0074677311_command_line_interface_python_tui.txt |
Q:
Can't open CSV file even with full file path
I'm using Python 3.5 and I'm having some problems opening a CSV file. I've tried entering the entire path but it still doesn't work, but the file is clearly in the folder. (My code is called 'simplecsvtest.py')
Here's the code snippet:
import csv
import sys
file = open... | Can't open CSV file even with full file path | I'm using Python 3.5 and I'm having some problems opening a CSV file. I've tried entering the entire path but it still doesn't work, but the file is clearly in the folder. (My code is called 'simplecsvtest.py')
Here's the code snippet:
import csv
import sys
file = open(r"C:\python35\files\results.csv", 'rt')
try:
... | [
"I would suggest creating a folder inside your project folder and then use a relative path : \nfile = open(r\".\\files\\results.csv\", 'rt') \n. implies that the path is relative to your current directory\n",
"I figured out a work-around solution myself:\nSomehow, if I copy all the data from the csv and paste it ... | [
0,
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0044631654_csv_python.txt |
Q:
How to create a functioning multipage streamlit app?
I am creating a web app using Streamlit. I have created a multipage app where the sidebar has a drop-down menu to go to a particular page. I have created a page that allows the user to input a sequence and count the number of characters (for example a DNA sequen... | How to create a functioning multipage streamlit app? | I am creating a web app using Streamlit. I have created a multipage app where the sidebar has a drop-down menu to go to a particular page. I have created a page that allows the user to input a sequence and count the number of characters (for example a DNA sequence and count the number of nucleotide bases). The architec... | [
"Use st.write().\n st.header(\"Input Query Sequence\")\n st.write(sequence) # <----------------------------------- this\n \n st.write('''***''')\n \n st.header(\"Nucleotide Count\") \n def nucleotide_count(seq):\n d = dict([('A', seq.count(\"A\")),('T',seq.count(\"T\")),('G',seq.count(\"G\")),(... | [
0
] | [] | [] | [
"python",
"streamlit",
"web"
] | stackoverflow_0074673627_python_streamlit_web.txt |
Q:
How to remove whitespaces in a string except from between certain elements
I have a string similar to (the below one is simplified):
" word= {his or her} whatever "
I want to delete every whitespace except between {}, so that my modified string will be:
"word={his or her}whatever"
lstrip or rstrip d... | How to remove whitespaces in a string except from between certain elements | I have a string similar to (the below one is simplified):
" word= {his or her} whatever "
I want to delete every whitespace except between {}, so that my modified string will be:
"word={his or her}whatever"
lstrip or rstrip doesn't work of course. If I delete all whitespaces the whitespaces between {} ar... | [
"To solve this problem, you can use regular expressions to find and replace the whitespace characters. In particular, you can use the re.sub function to search for whitespace characters outside of the curly braces and replace them with an empty string.\nHere is an example of how you can use re.sub to solve this pro... | [
1,
1
] | [
"You can use by replace\ndef remove(string):\n return string.replace(\" \", \"\")\n\nstring = 'hell o whatever'\nprint(remove(string)) // Output: hellowhatever\n\n"
] | [
-2
] | [
"python",
"python_3.x",
"removing_whitespace",
"replace",
"string"
] | stackoverflow_0074675792_python_python_3.x_removing_whitespace_replace_string.txt |
Q:
print("Are you a human: "str(human)) what did i do wrong
(https://i.stack.imgur.com/IFtgk.png)
can someone help me plzzzzz
A:
Add '+' between two variables , like print("Are You human"+str(human))
A:
if you want to output whit print always remember to use + between variables even
there are string
human=True
pr... | print("Are you a human: "str(human)) what did i do wrong | (https://i.stack.imgur.com/IFtgk.png)
can someone help me plzzzzz
| [
"Add '+' between two variables , like print(\"Are You human\"+str(human))\n",
"if you want to output whit print always remember to use + between variables even\nthere are string\nhuman=True\nprint(\" are ypu a human \"+str(human))\n"
] | [
0,
0
] | [] | [] | [
"boolean",
"python"
] | stackoverflow_0074677299_boolean_python.txt |
Q:
Python (RenPy): Textbuttons executing a function they don't explicitly call every time they're pressed
In the game I'm working on, I use an array to track the current stats of the player's company, and the following function to edit the array.
init python:
#The following store item objects, which include an array... | Python (RenPy): Textbuttons executing a function they don't explicitly call every time they're pressed | In the game I'm working on, I use an array to track the current stats of the player's company, and the following function to edit the array.
init python:
#The following store item objects, which include an array of their own stats
#Stores currently owned equipment
Equipment = []
#Stores items available to buy
It... | [
"I had the same problem and I believe you're you're falling victim to Renpy's prediction, as demonstrated by this thread on GitHub: https://github.com/renpy/renpy/issues/3718.\nRenpy runs through all the code in a screen when it's shown (and multiple other times) including searching any function calls in order to p... | [
0
] | [] | [] | [
"python",
"renpy"
] | stackoverflow_0059776715_python_renpy.txt |
Q:
How to extract HTML data from pandas dataframe column
I'm trying to extract certain elements from a block of webpages that I've extracted and put into a pandas column. I've tried lxml and can't get to pull out very specific phrases in text. What is the pythonistic way to go?
Tried this:
def scrape_details(s):
... | How to extract HTML data from pandas dataframe column | I'm trying to extract certain elements from a block of webpages that I've extracted and put into a pandas column. I've tried lxml and can't get to pull out very specific phrases in text. What is the pythonistic way to go?
Tried this:
def scrape_details(s):
results = requests.get(s)
results2 = etree.parse(String... | [
"What elements are you trying to extract? If its general HTML elements you could use the html.parser python package. I just modified the generic parser class they provide near the bottom of the page a lil:\nimport requests\nimport pandas as pd\n\n\n\n\n\n\n\n\nfrom html.parser import HTMLParser\nfrom html.entities ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074675148_pandas_python.txt |
Q:
I have a problem with my python Minecraft copy
I was working with "Ursina Engine"
My project is to make a copy of Minecraft, then I found out a problem that every time I run the program
and when I want to right-click to place a block, nothing happens.
Thanks to someone who can help me find the issue and tell me ho... | I have a problem with my python Minecraft copy | I was working with "Ursina Engine"
My project is to make a copy of Minecraft, then I found out a problem that every time I run the program
and when I want to right-click to place a block, nothing happens.
Thanks to someone who can help me find the issue and tell me how to fix it * Here is my Code:*
from ursina impo... | [
"The name of the input function is wrong. Input should be input\n",
"The input function should be input and not Input, rest of the code is absolutely correct. So, your code should be:\nfrom ursina import *\nfrom ursina.prefabs.first_person_controller import FirstPersonController\n\n\nclass Vovel(Button):\ndef __i... | [
6,
4,
0
] | [
"Ah now I'm understanding your problem, you have to change input to Input, the rest is fine.\n"
] | [
-1
] | [
"python",
"ursina",
"user_interface"
] | stackoverflow_0069450738_python_ursina_user_interface.txt |
Q:
Slash commands don't disappearing (nextcord)
I'm developing a discord bot using nextcord.
When i'm registering slash command and deleting it later, it's also staying at discord command list.
What can I do to delete non-existent slash commands or sync actual bot's command list with discord?
P.S. All of my commands ... | Slash commands don't disappearing (nextcord) | I'm developing a discord bot using nextcord.
When i'm registering slash command and deleting it later, it's also staying at discord command list.
What can I do to delete non-existent slash commands or sync actual bot's command list with discord?
P.S. All of my commands are in different cogs
I was waiting about 4 hours ... | [
"You should try kicking your bot and then inviting it back to your server. If this doesn't work, regenerate your bot's token. This should sync it back with Discord, and the command should be gone.\n",
"The solution is adding all servers in default_guild_ids variable\nUse methods on_ready and on_guild_join\nExampl... | [
0,
0
] | [] | [] | [
"discord",
"nextcord",
"python"
] | stackoverflow_0074582360_discord_nextcord_python.txt |
Q:
Pyspark MapReduce - how to get number occurrences in a list of tuple
I have a list like:
A 2022-08-13
B 2022-08-14
B 2022-08-13
A 2022-05-04
B 2022-05-04
C 2022-08-14
...
and I applied the following map functions to map each row with the # of occurrences:
map(lambda x: ((x.split(',')[0], x.split(',')[1]), 1))
To... | Pyspark MapReduce - how to get number occurrences in a list of tuple | I have a list like:
A 2022-08-13
B 2022-08-14
B 2022-08-13
A 2022-05-04
B 2022-05-04
C 2022-08-14
...
and I applied the following map functions to map each row with the # of occurrences:
map(lambda x: ((x.split(',')[0], x.split(',')[1]), 1))
To get this:
[
(('A', '2022-08-13'), 1),
(('B', '2022-08-14'), 1), ... | [
"Group by multiple times, first by \"person\", \"date\" and then by \"date\", \"count\" and collect persons with same date and count.\nThen generate pair combinations, explode, and separate pair.\nI extended your sample dataset to include persons \"D\" & \"E\" same as \"A\" & \"B\" to generate more combinations.\nd... | [
0
] | [] | [] | [
"apache_spark",
"pyspark",
"python"
] | stackoverflow_0074663401_apache_spark_pyspark_python.txt |
Q:
Ebay Scraping, filter out international results, select parents that do not have specific descendants
EDIT:
I have solved this thanks to @Driftr95
Here is the working code:
import xlwings as xw
from bs4 import BeautifulSoup
import requests
import statistics
@xw.func
def get_prices(url,args =[]):
url = request... | Ebay Scraping, filter out international results, select parents that do not have specific descendants | EDIT:
I have solved this thanks to @Driftr95
Here is the working code:
import xlwings as xw
from bs4 import BeautifulSoup
import requests
import statistics
@xw.func
def get_prices(url,args =[]):
url = requests.get(url).content
soup = BeautifulSoup(url,'lxml')
products = []
rsecSel = 'li:not(.srp-river... | [
"\nIt has a Span Class for location. This class only exists if the item is from an international seller.\n\nAssuming the class you mean is s-item__location you can use .select with the :has and :not pseudo-classes as below\n iDetSel = 'div[id=\"srp-river-results\"] div.s-item__details'\n # results = soup.sele... | [
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074673061_beautifulsoup_python.txt |
Q:
how to create dynamic database table using csv file in django or DRF
I am going to create a database table using csv file without model in django. Steps are:
after sending csv file by post request, one database table will be created according to csv headers (name, university, score, total_score etc). And it will b... | how to create dynamic database table using csv file in django or DRF | I am going to create a database table using csv file without model in django. Steps are:
after sending csv file by post request, one database table will be created according to csv headers (name, university, score, total_score etc). And it will be populated using csv file data. Database table name should be derived fro... | [
"You could always create a dynamic Django model: https://code.djangoproject.com/wiki/DynamicModels\nWith this approach you could create models on the fly and by running this snippet\nfrom django.core.management import call_command\ncall_command('makemigrations')\ncall_command('migrate')\n\nyou could migrate the mod... | [
0
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"dynamic_programming",
"python"
] | stackoverflow_0074666791_django_django_models_django_rest_framework_dynamic_programming_python.txt |
Q:
How to sort a list of strings in terms of a duplicate re-ordered copy
Take these two list of strings for example.
names = ['Jack', 'Steve', 'Marc', 'Xavier', 'Bob']
names_copy = ['Steve', 'Marc', 'Xavier', 'Bob', 'Jack']
Essentially I'm trying to find a way to sort names_copy in the same way that names is sorted.... | How to sort a list of strings in terms of a duplicate re-ordered copy | Take these two list of strings for example.
names = ['Jack', 'Steve', 'Marc', 'Xavier', 'Bob']
names_copy = ['Steve', 'Marc', 'Xavier', 'Bob', 'Jack']
Essentially I'm trying to find a way to sort names_copy in the same way that names is sorted.
So, a sorted version of names_copy would result in ['Jack', 'Steve', 'Marc... | [
"The easiest way would be to do:\nnames_copy_sorted = sorted(names_copy, key=names.index)\n\nThis assumes that every item in names_copy is actually an item in names. But this solution isn't very efficient. It would be more efficient to create a dictionary that assigns a priority to the items from names and then use... | [
0
] | [
"\nFirst we have a List that contains duplicates:\nCreate a dictionary, using the List items as keys. This will automatically remove any duplicates because dictionaries cannot have duplicate keys.\nThen, convert the dictionary back into a list:\nNow we have a List without any duplicates, and it has the same order a... | [
-2
] | [
"python",
"python_3.x",
"sorting"
] | stackoverflow_0074673707_python_python_3.x_sorting.txt |
Q:
stable Baselines 3 model.predict with stepwise varying actions
I would like to train a gym model based on a custom environment.
The training loop looks like this:
obs = env.reset()
for i in range(1000):
action, _states = model.predict(obs, deterministic=True)
print(f"action: {action}")
... | stable Baselines 3 model.predict with stepwise varying actions | I would like to train a gym model based on a custom environment.
The training loop looks like this:
obs = env.reset()
for i in range(1000):
action, _states = model.predict(obs, deterministic=True)
print(f"action: {action}")
obs, reward, done, info = env.step(action)
env.render()
... | [
"Yes, it is possible to use dynamically changing action spaces in stable-baselines / gym. The key is to use the self.observation_space attribute within your environment class to specify the available actions at each step.\nHere is an example of how you could do this:\nclass MazeEnv(gym.Env):\n def __init__(self)... | [
1
] | [] | [] | [
"python",
"reinforcement_learning",
"stable_baselines"
] | stackoverflow_0074656974_python_reinforcement_learning_stable_baselines.txt |
Q:
Can anyone shed some light on why this code from the alpaca-py documentation does not work?
I am trying to stream bitcoin data using the alpaca-py trading documentation but I keey getting a invalid syntax error. This is taken exactly from the alpaca-py documentation. Does anyone know what I am doing wrong?
from ty... | Can anyone shed some light on why this code from the alpaca-py documentation does not work? | I am trying to stream bitcoin data using the alpaca-py trading documentation but I keey getting a invalid syntax error. This is taken exactly from the alpaca-py documentation. Does anyone know what I am doing wrong?
from typing import Any
from alpaca.data.live import CryptoDataStream
wss_client = CryptoDataStream(key-... | [
"\nTake a look at the dashes in your parameters. Usually a no-no in most languages since the \"-\" or dash usually refers to a minus which is a binary operator or an operator that operates on two operands to produce a new value or result.\"\nMake sure parameters are set before passing them.\nTry the underscore inst... | [
0
] | [] | [] | [
"python",
"websocket"
] | stackoverflow_0074089722_python_websocket.txt |
Q:
Python missing or unusable error while cross compiling GDB
I get this error while attempting to cross-compile GDB (using the --with-python flag):
checking for python: /usr/bin/python
checking for python2.7: no
configure: error: python is missing or unusable
I made sure I had python2.7 installed in /usr/bin. I eve... | Python missing or unusable error while cross compiling GDB | I get this error while attempting to cross-compile GDB (using the --with-python flag):
checking for python: /usr/bin/python
checking for python2.7: no
configure: error: python is missing or unusable
I made sure I had python2.7 installed in /usr/bin. I even removed the package and installed it again. I tried using --wi... | [
"I had the same problem on Debian 6.0 when compiling GDB 7.4.1\nThe solution was to install python headers\nsudo apt-get install python2.6-dev\n\nand then configure with the right flag\n./configure --with-python\n\n",
"I had the same problem with gdb 7.4 and finally made it worked after spending some time debuggi... | [
21,
13,
7,
6,
0,
0
] | [] | [] | [
"gdb",
"python"
] | stackoverflow_0010792844_gdb_python.txt |
Q:
Cogs loads but won't work in discord.py 2.0
I've provided code of two files. bot.py - runs bot, ping.py - cog file.
The problem is that Cog doesn't work, bot doesn't respond to commands, in my ping.py file i have ping command
bot.py
import discord as ds
import asyncio
import os
from dotenv import load_dotenv
from ... | Cogs loads but won't work in discord.py 2.0 | I've provided code of two files. bot.py - runs bot, ping.py - cog file.
The problem is that Cog doesn't work, bot doesn't respond to commands, in my ping.py file i have ping command
bot.py
import discord as ds
import asyncio
import os
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
inten... | [
"You override the on_message event, and you don't have a process_commands in it, so the bot won't be processing any commands.\nYou can fix this by adding bot.process_commands inside the event.\n@bot.event\nasync def on_message(message):\n ...\n await bot.process_commands(message)\n\nOr register it as a listen... | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074677573_discord_discord.py_python.txt |
Q:
TypeError: unsupported type for timedelta microseconds component: InstrumentedAttribute
i am also getting error while doing this task.
Models.py
CloudImageMaster
created_tmstmp = Column(DateTime(), default = datetime.now(timezone.utc))
ClientMaster
ttl = Column(BigInteger, nullable=False)
QUERY:-
db.query(CloudI... | TypeError: unsupported type for timedelta microseconds component: InstrumentedAttribute | i am also getting error while doing this task.
Models.py
CloudImageMaster
created_tmstmp = Column(DateTime(), default = datetime.now(timezone.utc))
ClientMaster
ttl = Column(BigInteger, nullable=False)
QUERY:-
db.query(CloudImageMaster).join(ClientMaster).filter(
(
CloudImageMaster.created_tmstmp + timedelta(... | [
"Given a filter expression like MyMode.attr == something, the left hand side (LHS) can be thought of as belonging to the database side, the right hand side (RHS) as belonging to the application. What this means is that the RHS must be expressed in what SQLAlchemy regards as database constructs (ORM entities, table... | [
2
] | [] | [] | [
"fastapi",
"postgresql",
"python",
"python_3.x",
"sqlalchemy"
] | stackoverflow_0074623642_fastapi_postgresql_python_python_3.x_sqlalchemy.txt |
Q:
What's the fastest way to recursively search for files in python?
I need to generate a list of files with paths that contain a certain string by recursively searching. I'm doing this currently like this:
for i in iglob(starting_directory+'/**/*', recursive=True):
if filemask in i.split('\\')[-1]: # ignore dir... | What's the fastest way to recursively search for files in python? | I need to generate a list of files with paths that contain a certain string by recursively searching. I'm doing this currently like this:
for i in iglob(starting_directory+'/**/*', recursive=True):
if filemask in i.split('\\')[-1]: # ignore directories that contain the filemask
filelist.append(i)
This wo... | [
"Maybe not the answer you were hoping for, but I think these timings are useful. Run on a directory with 15,424 directories totalling 102,799 files (of which 3059 are .py files).\nPython 3.6:\nimport os\nimport glob\n\ndef walk():\n pys = []\n for p, d, f in os.walk('.'):\n for file in f:\n ... | [
27,
0
] | [] | [] | [
"glob",
"python",
"search"
] | stackoverflow_0050948391_glob_python_search.txt |
Q:
printing values django templates using for loop
I have two models interrelated items and broken :
class Items(models.Model):
id = models.AutoField(primary_key=True)
item_name = models.CharField(max_length=50, blank=False)
item_price = models.IntegerField(blank=True)
item_quantity_received = models.... | printing values django templates using for loop | I have two models interrelated items and broken :
class Items(models.Model):
id = models.AutoField(primary_key=True)
item_name = models.CharField(max_length=50, blank=False)
item_price = models.IntegerField(blank=True)
item_quantity_received = models.IntegerField(blank=False)
item_quantity_available... | [
"you loop over a List of Broken objects\nto access the related item objects\nitem.item.item_name\n",
"Your items query is of Broken objects. So in order to access the Items values you need to change your table. For better understanding change your view like this:\nbrokens = Broken.objects.select_related('item').a... | [
1,
1
] | [] | [] | [
"django",
"django_models",
"django_queryset",
"django_templates",
"python"
] | stackoverflow_0074677397_django_django_models_django_queryset_django_templates_python.txt |
Q:
Pandas: Better Way to Group By and Find Mean
I have a spreadsheet of stock prices for all companies, and I'd like to calculate the moving average more efficiently. As it stands I have some code that works, but takes a pretty long time to run. I'm wondering what are alternative ways to do the same thing, but more e... | Pandas: Better Way to Group By and Find Mean | I have a spreadsheet of stock prices for all companies, and I'd like to calculate the moving average more efficiently. As it stands I have some code that works, but takes a pretty long time to run. I'm wondering what are alternative ways to do the same thing, but more efficiently, or in a way that utilizes Pandas' stre... | [
"I would rearrange the data into n(date) by m(ticker) array, and use numpy to deal with rolling mean,\nGiven a df with 100 companies and 253 days from yahoo finance,\n\nimport pandas as pd\nimport numpy as np\n\ndf_n = df.to_numpy()\nsma_20 = np.cumsum(df_n, dtype=float, axis=0)\nsma_20[20:] = sma_20[20:] - sma_20[... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074668648_pandas_python.txt |
Q:
Optimizing gaussian heatmap generation
I have a set of 68 keypoints (size [68, 2]) that I am mapping to gaussian heatmaps. To do this, I have the following function:
def generate_gaussian(t, x, y, sigma=10):
"""
Generates a 2D Gaussian point at location x,y in tensor t.
x should be in range (-1, 1).
... | Optimizing gaussian heatmap generation | I have a set of 68 keypoints (size [68, 2]) that I am mapping to gaussian heatmaps. To do this, I have the following function:
def generate_gaussian(t, x, y, sigma=10):
"""
Generates a 2D Gaussian point at location x,y in tensor t.
x should be in range (-1, 1).
sigma is the standard deviation of the ge... | [
"You generate an NxN array g with a Gaussian centered on its center pixel. N is computed such that it extends by 3*sigma from that center pixel. This is the fastest way to build such an array:\ntmp_size = sigma * 3\ntx = np.arange(1, tmp_size + 1, 1, np.float32)\ng = np.exp(-(tx**2) / (2 * sigma**2))\ng = np.concat... | [
0
] | [] | [] | [
"computer_vision",
"python",
"pytorch"
] | stackoverflow_0074666177_computer_vision_python_pytorch.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.