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:
How do I locate a database location in Python?
I created a database with sqlite3 and I want to open it in DB Browser. Problem is I have no idea where to find the database so I can open it there. And when I look in my 'sqlite3' directory under conda (I'm doing all this in jupyternotebook), I can't find any database... | How do I locate a database location in Python? | I created a database with sqlite3 and I want to open it in DB Browser. Problem is I have no idea where to find the database so I can open it there. And when I look in my 'sqlite3' directory under conda (I'm doing all this in jupyternotebook), I can't find any databases I created.
I can run other commands with this data... | [
"import os\n\nprint(os.path.abspath('z'))\n\nor\nprint(conn.execute(\"SELECT file FROM pragma_database_list WHERE name = 'main';\").fetchone()[0])\n\n",
" conn = sql.connect('z')\n\nYou are creating a database in memory called \"z\". This is why the database works when you're running the script but you cannot ... | [
1,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0074175148_python_sqlite.txt |
Q:
How can I conditionally change the values in a numpy array taking into account nans?
My array is a 2D matrix and it has numpy.nan values besides negative and positive values:
>>> array
array([[ nan, nan, nan, ..., -0.04891211,
nan, nan],
[ nan, n... | How can I conditionally change the values in a numpy array taking into account nans? | My array is a 2D matrix and it has numpy.nan values besides negative and positive values:
>>> array
array([[ nan, nan, nan, ..., -0.04891211,
nan, nan],
[ nan, nan, nan, ..., nan,
nan, nan],
[ nan,... | [
"The fact that you have np.nan in your array should not matter. Just use fancy indexing:\nx[x>0] = new_value_for_pos\nx[x<0] = new_value_for_neg\n\nIf you want to replace your np.nans:\nx[np.isnan(x)] = something_not_nan\n\nMore info on fancy indexing a tutorial and the NumPy documentation.\n",
"Try:\na[a>0] = 1\... | [
46,
10,
3,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0012424824_numpy_python.txt |
Q:
Isuue with moves validation in the Go CLI game
I decided to write a go board game in Python, just for fun, without UI, just CLI :) I want to check if current intersection on the board is empty or not to restrict player putting his stones there. The intersection is represented as ' * ', black is '0', white is '1'. ... | Isuue with moves validation in the Go CLI game | I decided to write a go board game in Python, just for fun, without UI, just CLI :) I want to check if current intersection on the board is empty or not to restrict player putting his stones there. The intersection is represented as ' * ', black is '0', white is '1'. If black is to move, and current intersection is emp... | [
"the problem is the board, which is a list, will never be equal to a 3-character string ' * '. hence the if statement never gets executed, and it's white's turn for each element in your board.\nperhaps you should check whether the entered intersection is legal in the white/black _move function like this:\nprint(\"w... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074175232_python_python_3.x.txt |
Q:
add last value from list in column A into list in column b
I have the following data frame:
df_test = pd.DataFrame({"f":['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'],
"d":['x', 'x', 'y', 'y', 'x', 'x', 'y', 'y'],
"low": [0,5,2,4,5,10,4,8],
... | add last value from list in column A into list in column b | I have the following data frame:
df_test = pd.DataFrame({"f":['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'],
"d":['x', 'x', 'y', 'y', 'x', 'x', 'y', 'y'],
"low": [0,5,2,4,5,10,4,8],
"up": [5,10,4,6,10,15,8,12],
... | [
"Try:\ndff[\"new\"] = dff.apply(lambda x: [*x[\"low\"], x[\"up\"].pop()], axis=1)\nprint(dff)\n\nPrints:\n f d low up z new\n0 a x [0, 5] [5] [1, 3] [0, 5, 10]\n1 a y [2, 4] [4] [6, 2] [2, 4, 6]\n2 b x [5, 10] [10] [3, 7] [5, 10, 15]\n3 b y [4, 8] [8] [5... | [
1,
1,
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074174413_dataframe_group_by_pandas_python.txt |
Q:
Unable to Set Value on Element in Selenium
The Element is as follow:
<div class="sc-brqgnP gbUepm">
<div role="button" tabindex="0" class="sc-cvbbAY jMSnje code ">5</div>
<div role="button" tabindex="0" class="sc-cvbbAY jMSnje code ">5</div>
<div class="sc-jWBwVP fyostQ"></div>
<div role="button" t... | Unable to Set Value on Element in Selenium | The Element is as follow:
<div class="sc-brqgnP gbUepm">
<div role="button" tabindex="0" class="sc-cvbbAY jMSnje code ">5</div>
<div role="button" tabindex="0" class="sc-cvbbAY jMSnje code ">5</div>
<div class="sc-jWBwVP fyostQ"></div>
<div role="button" tabindex="0" class="sc-cvbbAY jMSnje code ">5</di... | [
"Well, you need to pass each individual keys for each location as they are all different div and hence have different XPATH.\nNow, Ideally you would have looped through and passed each individual key (phone number) but as there is a <div class=\"...> in between, it will throw an error/exception.\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"webdriver",
"xpath"
] | stackoverflow_0074175228_python_selenium_webdriver_xpath.txt |
Q:
Histplot : legend disappears when location is set, instead a small square appears in the specified location
Random DataFrame just to show my issue :
numbers = pd.Series(np.random.choice(10,50), name='numbers')
colors=pd.Series(np.random.choice(['A','B'],50), name='colors')
df = pd.concat([numbers, colors], axis=1)... | Histplot : legend disappears when location is set, instead a small square appears in the specified location | Random DataFrame just to show my issue :
numbers = pd.Series(np.random.choice(10,50), name='numbers')
colors=pd.Series(np.random.choice(['A','B'],50), name='colors')
df = pd.concat([numbers, colors], axis=1)
I'm plotting a histogram using Seaborn, legend displays just fine by default :
sns.histplot(data=df, x='numbers... | [
"This may help:\nnumbers = pd.Series(np.random.choice(10,50), name='numbers')\ncolors=pd.Series(np.random.choice(['A','B'],50), name='colors')\ndf = pd.concat([numbers, colors], axis=1)\n\nax = sns.histplot(data=df, x='numbers', hue='colors') #<========== returning ax\nsns.move_legend(ax, \"upper left\") <=========... | [
1
] | [] | [] | [
"legend",
"matplotlib",
"python",
"seaborn"
] | stackoverflow_0074175317_legend_matplotlib_python_seaborn.txt |
Q:
Why am I getting "socket.gaierror [Errno 11001]" when trying to run my Python SMTP script?
I have been trying to run the following code however I am getting the following error when the code runs. I am currently following a video on a course on Udemy, however, the video seems to be outdated as the option to turn o... | Why am I getting "socket.gaierror [Errno 11001]" when trying to run my Python SMTP script? | I have been trying to run the following code however I am getting the following error when the code runs. I am currently following a video on a course on Udemy, however, the video seems to be outdated as the option to turn on "Less secure apps" on Gmail can't be turned on anymore as Google disabled the option. To fix t... | [
"getaddrinfo looks up the IP address for a domain name. The reason why this is failing is because you have a simple typo in the address for smtp.gmail.com. Just fix it and it should be fine. Like this:\nimport smtplib\nfrom credentials import *\n\n\nconnection = smtplib.SMTP(\"smtp.gmail.com\", port=587)\nconnecti... | [
1
] | [] | [] | [
"email",
"python",
"smtp"
] | stackoverflow_0074175381_email_python_smtp.txt |
Q:
arguments while defining function in python
What should I do if I want to take multiple arguments (by using *) as well as a key word argument while defining a function?
Is there a way to take multiple keyword arguments (by using **) and a single argument or both multiple keywords (by using **) and arguments (by us... | arguments while defining function in python | What should I do if I want to take multiple arguments (by using *) as well as a key word argument while defining a function?
Is there a way to take multiple keyword arguments (by using **) and a single argument or both multiple keywords (by using **) and arguments (by using *) at the same time while defining a function... | [
"Yes, use **kwargs to capture the keyword arguments. One restriction to be aware of that is the keyword arguments should come after the positional arguments. kwargs will be a dictionary.\ndef function_name(*x, **greetings):\n for k in greetings:\n for i in x:\n print(f\"{greetings[k]} {i}\")\n... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074175078_python_python_3.x.txt |
Q:
Separate last column from the actual dataset using numpy
I have a dataset in csv format (without headers) where I want to split it into two parts: (1) The actual dataset without the last column, (2) the last column (class label). My dataset has 100K rows and 65 features ( where the last column, column 65, is the c... | Separate last column from the actual dataset using numpy | I have a dataset in csv format (without headers) where I want to split it into two parts: (1) The actual dataset without the last column, (2) the last column (class label). My dataset has 100K rows and 65 features ( where the last column, column 65, is the class label that I want to separate). I wrote the following:
da... | [
"assuming that your dataset is without header\nclass_label = dataset[:, -1] # for last column\ndataset = dataset[:, :-1] # for all but last column\n\n",
"In case you are interested in using numpy arrays, you can read your data in the csv file into a numpy array:\n from numpy import genfromtxt\n my_data = genfromt... | [
40,
1,
0
] | [] | [] | [
"numpy",
"python",
"python_2.7"
] | stackoverflow_0047542643_numpy_python_python_2.7.txt |
Q:
Find and return the list of words that contain letters as SUBSEQUENCE
QuestionHere
def words_with_letters(words, letters):
return [word for word in words if all(letter in word for letter in letters)]
the above code does not work and have tried to figure out why the system does not consider this.
Please click... | Find and return the list of words that contain letters as SUBSEQUENCE | QuestionHere
def words_with_letters(words, letters):
return [word for word in words if all(letter in word for letter in letters)]
the above code does not work and have tried to figure out why the system does not consider this.
Please click the "QuestionHere" link to understand
| [] | [] | [
"def words_with_letters(words, letters):\n \n return [word for word in words if letters in word]\n\n"
] | [
-1
] | [
"loops",
"python",
"return",
"string",
"substring"
] | stackoverflow_0074175086_loops_python_return_string_substring.txt |
Q:
Numpy different elements between two arrays
I need help. I have this array from a table:
lycop = np.array([[14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
[1, 1, 8, 24, 48, 58, 35, 16, 8, 1]])
lycop
array([[14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
[ 1, 1, 8, 24, 48, 58, 35, 16, 8, 1]])
I ... | Numpy different elements between two arrays | I need help. I have this array from a table:
lycop = np.array([[14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
[1, 1, 8, 24, 48, 58, 35, 16, 8, 1]])
lycop
array([[14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
[ 1, 1, 8, 24, 48, 58, 35, 16, 8, 1]])
I had to calculate media, var and std.
lycop_media ... | [
"It's just an extension of what you did for a1 and a2, but you have the < and > signs confused for one half.\na3 = lycop[0](lycop[0] >= lycop_media - lycop_std) & (lycop[0] <= lycop_media + lycop_std)]\n\n"
] | [
0
] | [] | [] | [
"arrays",
"google_colaboratory",
"numpy",
"python"
] | stackoverflow_0074175397_arrays_google_colaboratory_numpy_python.txt |
Q:
How do I resolve the pygraphviz error on mac OS?
I'm having trouble installing pygraphviz and I'm using Anaconda on macOS Monterey.
I already had graphviz on Anaconda. I then did
brew install graphviz
and then
pip install pygraphviz
but I keep getting this error:
Collecting pygraphviz
Using cached pygraphv... | How do I resolve the pygraphviz error on mac OS? | I'm having trouble installing pygraphviz and I'm using Anaconda on macOS Monterey.
I already had graphviz on Anaconda. I then did
brew install graphviz
and then
pip install pygraphviz
but I keep getting this error:
Collecting pygraphviz
Using cached pygraphviz-1.7.zip (118 kB)
Building wheels for collected pack... | [
"You can use Homebrew to install graphviz first:\nbrew install graphviz\n\nCheck where it was installed with brew info graphviz.\n$ brew info graphviz\ngraphviz: stable 2.50.0 (bottled), HEAD\nGraph visualization software from AT&T and Bell Labs\nhttps://www.graphviz.org/\n/usr/local/Cellar/graphviz/2.50.0 (292 fil... | [
20,
4,
0,
0
] | [] | [] | [
"macos",
"pygraphviz",
"python"
] | stackoverflow_0069970147_macos_pygraphviz_python.txt |
Q:
Show matplotlib plots (and other GUI) in Ubuntu (WSL1 & WSL2)
So it seems on ubuntu for windows (windows subsystem for linux) people are suggesting we need to use Agg backend and just save images, not show plots.
import matplotlib
matplotlib.use('Agg') # no UI backend
import matplotlib.pyplot as plt
import numpy ... | Show matplotlib plots (and other GUI) in Ubuntu (WSL1 & WSL2) | So it seems on ubuntu for windows (windows subsystem for linux) people are suggesting we need to use Agg backend and just save images, not show plots.
import matplotlib
matplotlib.use('Agg') # no UI backend
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.... | [
"Ok, so I got it working as follows. I have Ubuntu on windows, with anaconda python 3.6 installed.\n\nDownload and install VcXsrv or Xming (X11 for Windows) from sourceforge(see edit below)\nsudo apt-get update\nsudo apt-get install python3.6-tk (you may have to install a different python*-tk depnding on the pytho... | [
156,
18,
6,
4,
3,
1,
0
] | [
"had similar problem so simply installing the supported gpu driver solved my problem. Check this out!\n",
"I found the best approach is to install Jupyter on Windows Subsystem for Linux (WSL) by following \nsudo apt update && upgrade\nsudo apt install python3 python3-pip ipython3\n\nNow you can install matplotlib... | [
-1,
-3
] | [
"linux",
"matplotlib",
"python",
"windows_subsystem_for_linux"
] | stackoverflow_0043397162_linux_matplotlib_python_windows_subsystem_for_linux.txt |
Q:
How do I rearrange nested Pandas DataFrame columns?
In the DataFrame below, I want to rearrange the nested columns - i.e. to have 'region_sea' appearing before 'region_inland'
df = pd.DataFrame( {'state': ['WA', 'CA', 'NY', 'NY', 'CA', 'CA', 'WA' ]
, 'region': ['region_sea', 'region_inland', 'r... | How do I rearrange nested Pandas DataFrame columns? | In the DataFrame below, I want to rearrange the nested columns - i.e. to have 'region_sea' appearing before 'region_inland'
df = pd.DataFrame( {'state': ['WA', 'CA', 'NY', 'NY', 'CA', 'CA', 'WA' ]
, 'region': ['region_sea', 'region_inland', 'region_sea', 'region_inland', 'region_sea', 'region_sea', ... | [
"You can use sort_index to sort it. However, as it is nested columns, it will replace income and count too.\ndf.sort_index(axis='columns', level=0, ascending=False, inplace=True)\n\nIf you don't want replace income/count, than it will not give common header for both.\ndf.sort_index(axis='columns', level='region', a... | [
1
] | [] | [] | [
"pandas",
"pivot_table",
"python"
] | stackoverflow_0074175364_pandas_pivot_table_python.txt |
Q:
How to check format of specific element given in one XML to another XML using python
My XML1 is as follows where I have put all the equal operator syntax:
<Operator>
<Equal>
<Data>Object</Data>
<Data>1</Data>
</Equal>
<Equal>
<Integer>Non_Object</Integer>
<Integer>2</Int... | How to check format of specific element given in one XML to another XML using python | My XML1 is as follows where I have put all the equal operator syntax:
<Operator>
<Equal>
<Data>Object</Data>
<Data>1</Data>
</Equal>
<Equal>
<Integer>Non_Object</Integer>
<Integer>2</Integer>
</Equal>
</Operator>
My XML2 is as follows where I have to check syntax of equa... | [
"If I understand your question, and the structure of your xml files, correctly this should work:\n#identify your values in the first file\nvalues = [e.xpath('.//*[2]')[0].text for e in doc.xpath('.//Equal')]\n\n#find corresponding values in the Sub_Function_2 element children in the 2nd file\nfor service in doc2.xp... | [
0
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0074175000_lxml_python_xml.txt |
Q:
How to encrypt JSON in python
I have a JSON file. I am running a program, in python, where data is extracted from the JSON file. Is there any way to encrypt the JSON file with a key, so that if someone randomly opens the file, it would be a mess of characters, but when the key is fed to the program, it decrypts it... | How to encrypt JSON in python | I have a JSON file. I am running a program, in python, where data is extracted from the JSON file. Is there any way to encrypt the JSON file with a key, so that if someone randomly opens the file, it would be a mess of characters, but when the key is fed to the program, it decrypts it and is able to read it? Thanks in ... | [
"Yes, you can encrypt a .json file. Make sure you install the cryptography package by typing\npip install cryptography\n# or on windows:\npython -m pip install cryptography\n\nThen, you can make a program similar to mine:\n#this imports the cryptography package\nfrom cryptography.fernet import Fernet\n\n#this gener... | [
8,
2,
0
] | [] | [] | [
"data_security",
"encryption",
"json",
"python"
] | stackoverflow_0061607367_data_security_encryption_json_python.txt |
Q:
nuke tcl in python returns command instead of string
In a python script I'm using nuke.tcl() to return a value but I keep getting a runtime error instead of a string:
frames = nuke.tcl('[filename [topnode]]')
print (frames)
returns:
RuntimeError: Z:/Project/Sequence/Shot/renders/comp/v001/Shot_v001/Shot_v001.%05d... | nuke tcl in python returns command instead of string | In a python script I'm using nuke.tcl() to return a value but I keep getting a runtime error instead of a string:
frames = nuke.tcl('[filename [topnode]]')
print (frames)
returns:
RuntimeError: Z:/Project/Sequence/Shot/renders/comp/v001/Shot_v001/Shot_v001.%05d.exr: Unknown command
So, it returns the result I'm lookin... | [
"okay I figured it out. The following returns the string I wanted. I guess \"expr\" is similar to \"eval\" in python.\nframes = nuke.tcl('expr','[filename [topnode]]')\n\n"
] | [
0
] | [] | [] | [
"nuke",
"python",
"tcl"
] | stackoverflow_0074175559_nuke_python_tcl.txt |
Q:
ImportError: cannot import name 'Account' from 'O365' using Office 365 Project
I'm trying to use this projet https://github.com/O365/python-o365 that shows a simple way to send mails using Office 365 app key and credentials, because i have a O365 Business Account.
But, i'm having "ImportError: cannot import name '... | ImportError: cannot import name 'Account' from 'O365' using Office 365 Project | I'm trying to use this projet https://github.com/O365/python-o365 that shows a simple way to send mails using Office 365 app key and credentials, because i have a O365 Business Account.
But, i'm having "ImportError: cannot import name 'Account' from 'O365' "the error before installing:
> py Y:\RO_RFID_Srv\email.py Trac... | [
"It might be too late but I am starting by importing O365 and then from O365 import Account and it works for me:\n# API O365\nimport O365\nfrom O365 import Account\n\ncredentials = (o365credid, o365credpwd)\naccount = Account(credentials)\n\nLet me know.\nRenaud\n",
"It seems that your Python file is named: \"ema... | [
0,
0
] | [] | [] | [
"office365",
"python",
"python_3.7",
"python_3.x"
] | stackoverflow_0055083631_office365_python_python_3.7_python_3.x.txt |
Q:
scrapy Crawl spider Multiple queries
I am trying to find email ids, i have a list and i want to pass multiple search query one after the other, but when i try using list in shows me and indentation error , can anyone help me solve with the issue?
my code is here:
import scrapy
from scrapy.spiders import CrawlSpide... | scrapy Crawl spider Multiple queries | I am trying to find email ids, i have a list and i want to pass multiple search query one after the other, but when i try using list in shows me and indentation error , can anyone help me solve with the issue?
my code is here:
import scrapy
from scrapy.spiders import CrawlSpider, Request
from googlesearch import search... | [
"Still not 100% sure if I understand the issue but here is an example of how you could process a list of queries instead of just one query.\n def __init__(self,query, *args, **kwargs):\n super(email_extractor, self).__init__(*args, **kwargs)\n self.email_list = []\n self.queries = [query1,qu... | [
0
] | [] | [] | [
"google_search",
"python",
"scrapy",
"selenium",
"web_scraping"
] | stackoverflow_0074150773_google_search_python_scrapy_selenium_web_scraping.txt |
Q:
Appwrite function build fails to install dependencies even as I specifically define them
I have been trying to upload a function that allows me to turn a CSV into a JSON file. The code works but when I try to deploy it to my instance of Appwrite, the build fails.
Here is my function:
from appwrite.client import Cl... | Appwrite function build fails to install dependencies even as I specifically define them | I have been trying to upload a function that allows me to turn a CSV into a JSON file. The code works but when I try to deploy it to my instance of Appwrite, the build fails.
Here is my function:
from appwrite.client import Client
from appwrite.services.storage import Storage
import pandas as pd
def main(req, res):
... | [
"Unfortunately, you can't use pandas in Appwrite Functions because installing numpy seems to require some OS packages not available in the open runtime. You can follow this issue for updates on this.\nFor your basic CSV to JSON task, how about you use the standard csv package instead of pandas?\n"
] | [
0
] | [] | [] | [
"appwrite",
"bash",
"docker",
"python",
"ubuntu"
] | stackoverflow_0074166731_appwrite_bash_docker_python_ubuntu.txt |
Q:
Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray). tensorflow
please help explaining what am I doing wrong here for a complete newbie.
This is my first ever ml code and it is used for object detection. Please tell me my mistakes and how to make them right!
from numpy.lib.shape_bas... | Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray). tensorflow | please help explaining what am I doing wrong here for a complete newbie.
This is my first ever ml code and it is used for object detection. Please tell me my mistakes and how to make them right!
from numpy.lib.shape_base import split
from numpy.core.fromnumeric import var
from numpy.core.memmap import ndarray
from tens... | [
"The problem is that you are passing the images and labels to model.fit together, but fit expects two separate arguments: one for the images and one for the labels.\nTry changing your last line of code to this:\nmodel.fit(x[0], training_labels, epochs=100)\n\n"
] | [
0
] | [] | [] | [
"keras",
"numpy",
"python",
"tensorflow"
] | stackoverflow_0074175538_keras_numpy_python_tensorflow.txt |
Q:
Correct usage of self in Python classes
In the example below, classes AA and BB are instantiated with params a and b and feature the foo method. The only difference between classes AA and BB is that in the AA foo method, the intermediate variable z is prefixed with the class instance reference self while in class... | Correct usage of self in Python classes | In the example below, classes AA and BB are instantiated with params a and b and feature the foo method. The only difference between classes AA and BB is that in the AA foo method, the intermediate variable z is prefixed with the class instance reference self while in class BB it is not. What is the correct methodolo... | [
"Neither one is \"correct\" per se. It depends what you want to do: If you want to keep the value around, then you could assign it to the instance. If not, then don't.\nAlthough, if you do assign it as a public instance attribute, you'll probably want to set an initial value in __init__(), like None.\n"
] | [
2
] | [
"the use of the self will appear when you initiate an object from the class, so in order that the object will have an access to the variable you need to use the self\nclass AA:\ndef __init__(self, a, b):\n self.a = a\n self.b = b\n\ndef foo(self):\n self.z = self.a + self.b\n return self.z * self.a\n\nc... | [
-2
] | [
"class",
"python",
"self"
] | stackoverflow_0074175641_class_python_self.txt |
Q:
Change Number of Bins with Seaborn Countplot
I have this code in Python:
df = pd.read_excel('data (1).xlsx')
x = np.array(df['biceps circumference (cm)'])
ax1 = sns.countplot(x="biceps circumference (cm)", data=df)
Where df is my data frame and "biceps circumference (cm)" is a column. I'm using seaborn's countp... | Change Number of Bins with Seaborn Countplot | I have this code in Python:
df = pd.read_excel('data (1).xlsx')
x = np.array(df['biceps circumference (cm)'])
ax1 = sns.countplot(x="biceps circumference (cm)", data=df)
Where df is my data frame and "biceps circumference (cm)" is a column. I'm using seaborn's countplot function to make a frequency distribution. But... | [
"For a distribution Histplot will be more fitting and gives more flexibility.\nCountplot can not show distributions it only can show absolute counts of categories and across categories.\nbins = \"auto\"\ndf = pd.read_excel('data (1).xlsx')\nx = np.array(df['biceps circumference (cm)'])\n\nax1 = sns.histplot(data=df... | [
2,
0
] | [] | [] | [
"matplotlib",
"pandas",
"python",
"seaborn"
] | stackoverflow_0074116552_matplotlib_pandas_python_seaborn.txt |
Q:
Finding parent to element in XML using python
I am really struggeling finding the parent of an element I have searched for using this code, I am searching for "NOTE2"="CU008" in the parent which has the DESCR="RmTmp"
def SetAttribute(tag, rom):
for elm in root.findall(f".//OI[@DESCR='{tag}']/PI[@Name='NOTE2']"... | Finding parent to element in XML using python | I am really struggeling finding the parent of an element I have searched for using this code, I am searching for "NOTE2"="CU008" in the parent which has the DESCR="RmTmp"
def SetAttribute(tag, rom):
for elm in root.findall(f".//OI[@DESCR='{tag}']/PI[@Name='NOTE2']"):
if elm.attrib == {'Name': 'NOTE2', 'Valu... | [
"In XPath, you can find the parent element of an element by navigating up the parent axis one step. Simply append /parent::* to the end of your existing XPath.\nhttps://www.w3.org/TR/1999/REC-xpath-19991116/#axes\n.//OI[@DESCR='{tag}']/PI[@Name='NOTE2']/parent::OI\n\nBut if I understand your question correctly, the... | [
0
] | [] | [] | [
"elementtree",
"parent",
"python",
"xml",
"xpath"
] | stackoverflow_0074173181_elementtree_parent_python_xml_xpath.txt |
Q:
Get the list of values/entries that are common to all the columns in a dataframe (or a csv file) in python
I have this setup of a pandas dataframe (or a csv file):
df = {
'colA': ['aa', 'bb', 'cc', 'dd', 'ee'],
'colB': ['aa', 'bb', 'dd', 'qq', 'ee'],
'colC': ['aa', 'bb', 'cc', 'ee', 'dd'],
'colD': ... | Get the list of values/entries that are common to all the columns in a dataframe (or a csv file) in python | I have this setup of a pandas dataframe (or a csv file):
df = {
'colA': ['aa', 'bb', 'cc', 'dd', 'ee'],
'colB': ['aa', 'bb', 'dd', 'qq', 'ee'],
'colC': ['aa', 'bb', 'cc', 'ee', 'dd'],
'colD': ['aa', 'bb', 'ee', 'cc', 'dd']
}
The goal here is to get a list/column with the set of values that appear in al... | [
"You can use .intersection() method of sets to find common values between sets of each column:\n# wrapped in a list, take first column set and pass sets of other columns as arguments\ncommon_list = list(set(df.colA).intersection(set(df.colB), set(df.colC), set(df.colD)))\nsorted(common_list) # needs sorting in alp... | [
0,
0,
0
] | [] | [] | [
"dataframe",
"list",
"pandas",
"python"
] | stackoverflow_0074175688_dataframe_list_pandas_python.txt |
Q:
Flask Problem. How do I make send_from_directory() work?
I've been using this but it doesn't seem to work in my code. Can someone tell me what's going wrong? The problem is it doesn't download the file and instead gives me a 404
@pages.route('/download/<path:fileId>')
@login_required
def download(fileId):
file... | Flask Problem. How do I make send_from_directory() work? | I've been using this but it doesn't seem to work in my code. Can someone tell me what's going wrong? The problem is it doesn't download the file and instead gives me a 404
@pages.route('/download/<path:fileId>')
@login_required
def download(fileId):
fileOwnerId = File.query.filter_by(id = fileId).first().fileOwnerI... | [
"Since you're working on Windows, you should be careful to avoid assuming the path separator is /.\nPython has OS-aware libraries to handle path manipulations: os.path and pathlib are the two I use.\nThis line of code is not going to work on Windows:\n directory = \"/\".join(filePath.split(\"/\")[0:-1])\n\nThis ... | [
1
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074175602_flask_python.txt |
Q:
os.path.idsir() return different result for absolute path and path created with os.path.join() method
>>> os.getcwd()
'/Users/seungjunlee/test_dir'
>>> p1 = os.path.abspath('sub_1')
>>> p2 = os.path.join('test_dir', 'sub_1')
>>> os.path.isdir(p1)
True
>>> os.path.isdir(p2)
False
So the current working directory i... | os.path.idsir() return different result for absolute path and path created with os.path.join() method | >>> os.getcwd()
'/Users/seungjunlee/test_dir'
>>> p1 = os.path.abspath('sub_1')
>>> p2 = os.path.join('test_dir', 'sub_1')
>>> os.path.isdir(p1)
True
>>> os.path.isdir(p2)
False
So the current working directory is test_dir, and there is sub directory called sub_1. p1 stores absolute path of sub_1 and p2 get path using... | [
"You are already under the directory of test_dir, and os.path.join('test_dir', 'sub_1') returns test_dir\\\\sub_1.\nSo, in fact what you are checking is /Users/seungjunlee/test_dir/test_dir/sub_1, surely it's not valid dir.\n"
] | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074175844_python_python_3.x.txt |
Q:
Removing last comma in json file
I am creating a json file like this
[
{"_index": "java", "_id": "15194804", "rating": 0},
{"_index": "java", "_id": "18264178", "rating": 0},
{"_index": "java", "_id": "16225177", "rating": 1},
{"_index": "java", "_id": "16445238", "rating": 0},
{"_index": "java", "_id": "17233226"... | Removing last comma in json file | I am creating a json file like this
[
{"_index": "java", "_id": "15194804", "rating": 0},
{"_index": "java", "_id": "18264178", "rating": 0},
{"_index": "java", "_id": "16225177", "rating": 1},
{"_index": "java", "_id": "16445238", "rating": 0},
{"_index": "java", "_id": "17233226", "rating": 0},
]
I want to remove t... | [
"If you want to have the last line without a comma\nwith open(folder + \"/\" + str(a[i]) + \".json\", 'w') as fp:\n fp.write(\"[\\n\")\n for i in range(len(ratings) - 1):\n x = json.dumps(ratings[i])\n fp.write(\"%s,\\n\" % x)\n fp.write(\"%s\\n\" % ratings[-1])\n fp.write(\"]\\n\")\nfp.close(... | [
0,
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074174346_json_python.txt |
Q:
Win32api's keybd_event() function problems
I'm having some issues creating inputs with the win32api. I'm creating a voice recognition script that needs to work just like a keyboard in all contexts (including fullscreen games and such). I've tried a few other solutions besides win32api's keybd_event() function but ... | Win32api's keybd_event() function problems | I'm having some issues creating inputs with the win32api. I'm creating a voice recognition script that needs to work just like a keyboard in all contexts (including fullscreen games and such). I've tried a few other solutions besides win32api's keybd_event() function but most don't even register in fullscreen applicati... | [
"I'm unsure exactly why this works, but experimenting randomly I have found a solution using the bitwise OR. The code that I partially copied is here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms646304%28v=vs.85%29.aspx\nMy solution:\nwin32api.keybd_event(win32con.VK_UP, 0, win32con.KEYEVENTF_EXTENDE... | [
1,
0
] | [] | [] | [
"input",
"keyboard",
"python",
"python_2.7",
"pywin32"
] | stackoverflow_0031713835_input_keyboard_python_python_2.7_pywin32.txt |
Q:
Why is "if x is none" statement not executing properly?
It's obvious I'm doing something wrong, but I can't find help online as to why. I want to create an if function that prints out that the inputted file contains no data. When I run this and request an empty.txt file, it skips straight to the else: and I get
En... | Why is "if x is none" statement not executing properly? | It's obvious I'm doing something wrong, but I can't find help online as to why. I want to create an if function that prints out that the inputted file contains no data. When I run this and request an empty.txt file, it skips straight to the else: and I get
Enter name of file: empty.txt
In the terminal, instead of the p... | [
" # Ask user to input file, open and and read file\n\nuserinput = input('Enter name of file: ')\n\nuserfile = open(userinput)\n\ndata = userfile.read()\n\n#if file is empty print \"x contains no data\"\nif len(data) == 0:\n print(userinput + ' contains no data.')\nelse:\n print(data)\n\nuserfile.close()\n\nth... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074175847_python.txt |
Q:
Trying to quit out of script without having it continue asking the next questions. If user inputs quit command it should just end the and exit program
Quitting a program without having to continue through script
A:
The easiest thing to do is probably replace return with exit(). That will terminate your progam.
| Trying to quit out of script without having it continue asking the next questions. If user inputs quit command it should just end the and exit program | Quitting a program without having to continue through script
| [
"The easiest thing to do is probably replace return with exit(). That will terminate your progam.\n"
] | [
2
] | [] | [] | [
"exit",
"loops",
"python"
] | stackoverflow_0074175861_exit_loops_python.txt |
Q:
Get indices of maximum values in Tensorflow
I would like to get the indices of maximum values.
Eg:
[
[
[0.1 0.3 0.6],
[0.0 0.4 0.1]
],
[
[0.9 0.2 0.6],
[0.8 0.1 0.5]
]
]
I would like to get [[0,0,2], [0,1,1], [1,0,0], [1,1,0]]. How do I do that in the easies... | Get indices of maximum values in Tensorflow | I would like to get the indices of maximum values.
Eg:
[
[
[0.1 0.3 0.6],
[0.0 0.4 0.1]
],
[
[0.9 0.2 0.6],
[0.8 0.1 0.5]
]
]
I would like to get [[0,0,2], [0,1,1], [1,0,0], [1,1,0]]. How do I do that in the easiest way in Tensorflow?
| [
"You can take advantage of TF's broadcast in the last dimension\na = tf.constant([[[0.1, 0.3, 0.6],[0.0, 0.4, 0.1]],[[0.9, 0.2, 0.6],[0.8, 0.1, 0.5]]])\nb = tf.reduce_max(a, -1, keepdims=True)\ntf.where(a == b)\n\nOutput\n<tf.Tensor: shape=(4, 3), dtype=int64, numpy=\narray([[0, 0, 2],\n [0, 1, 1],\n [1... | [
2,
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074172589_python_tensorflow.txt |
Q:
How do I get all divs inside of this div using webdriver and selenium?
I am new to webscraping and am trying to scrape a website and would like to get all the elements that have data-feature-id=homepage/story with the ultimate goal of getting a subelement of each of the divs inside of the parent element. I am havi... | How do I get all divs inside of this div using webdriver and selenium? | I am new to webscraping and am trying to scrape a website and would like to get all the elements that have data-feature-id=homepage/story with the ultimate goal of getting a subelement of each of the divs inside of the parent element. I am having trouble getting all of the elements with this parameter and am unsure how... | [
"Instead of using XPath in this case, which may be prone to changing frequently based on new additions to the page (like new articles) or third party content (like ads), try using CSS Selectors.\nTry entering the following CSS Selector in your browser's inspector: div[data-feature-id='homepage/story']\n\nFor your S... | [
0
] | [] | [] | [
"html",
"python",
"selenium_chromedriver",
"web_scraping"
] | stackoverflow_0074175832_html_python_selenium_chromedriver_web_scraping.txt |
Q:
Using isinstance for a list of bools / ints
I have a list of ints,
lst = [1, 2, 3]
how do I do a isinstance on this, to return True only for a list of ints?
isinstance(lst, list[int]) # does not work
A:
Try using all in conjunction with isinstance, like this:
lst = [1, 2, 3]
result = all(isinstance(x, int) for... | Using isinstance for a list of bools / ints | I have a list of ints,
lst = [1, 2, 3]
how do I do a isinstance on this, to return True only for a list of ints?
isinstance(lst, list[int]) # does not work
| [
"Try using all in conjunction with isinstance, like this:\nlst = [1, 2, 3]\n\nresult = all(isinstance(x, int) for x in lst)\n\nprint(result)\n\n"
] | [
3
] | [
"Perhaps maybe a class can be used in this case\nThis is probably the closest way to check within the isinstance function itself.\nI tried implementing a similar logic of the sorted function, where sorted(x, key=lambda x:x[0])\nclass integer_valid:\n\n def __init__(self, tuple):\n\n \"\"\" Valid integer t... | [
-1
] | [
"isinstance",
"python"
] | stackoverflow_0074175849_isinstance_python.txt |
Q:
same_row = self.row == other.row AttributeError: 'NoneType' object has no attribute 'row' with gspread
I am trying to program a discord bot that links to google sheets but have been encountering countless errors with my code.
The error I get is as followed:
Traceback (most recent call last):
File "/home/runner/B... | same_row = self.row == other.row AttributeError: 'NoneType' object has no attribute 'row' with gspread | I am trying to program a discord bot that links to google sheets but have been encountering countless errors with my code.
The error I get is as followed:
Traceback (most recent call last):
File "/home/runner/Bundeswehr-Bot/venv/lib/python3.8/site-packages/discord/ui/modal.py", line 186, in _scheduled_task
await ... | [
"In your script, I thought that if sheet.find(self.host.value) == None: might be required to be modified. So, == is is. I thought that this might be the reason for your issue of 'NoneType' object has no attribute 'row'.\nI thought that in this case, this thread might be useful.\nSo, how about the following modifica... | [
5
] | [] | [] | [
"google_sheets",
"google_sheets_api",
"gspread",
"python"
] | stackoverflow_0073911302_google_sheets_google_sheets_api_gspread_python.txt |
Q:
TensorFlow model.fit: expected shape=(None, 100, 3), found shape=(100, 3)
I'm new to TensorFlow and ML and I'm trying to create a GAN that will generate an array of 3 dimensions (output shape is 100, 3).
I have the following discriminator model:
def make_discriminator_model():
model = tf.keras.Sequential()
... | TensorFlow model.fit: expected shape=(None, 100, 3), found shape=(100, 3) | I'm new to TensorFlow and ML and I'm trying to create a GAN that will generate an array of 3 dimensions (output shape is 100, 3).
I have the following discriminator model:
def make_discriminator_model():
model = tf.keras.Sequential()
model.add(layers.LeakyReLU(input_shape=(100, 3), name="Input"))
model.ad... | [
"The leading None represents the batch dimension. By specifying input_shape=(100, 3), you are telling the model that it should expect a batch of unknown number of samples, where each sample is of shape (100,3).\nHowever, what you are feeding to it is a tensor of shape (100,3), which it interprets as \"a batch of 10... | [
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074170683_python_tensorflow.txt |
Q:
Missing module docstringPylint(C0114:missing-module-docstring), pylint
I have the plugin pylint. But I get some errors. Like this error:
Missing module docstringPylint(C0114:missing-module-docstring)
and this error:
Formatting a regular string which could be a f-stringPylint(C0209:consider-using-f-string)
and th... | Missing module docstringPylint(C0114:missing-module-docstring), pylint | I have the plugin pylint. But I get some errors. Like this error:
Missing module docstringPylint(C0114:missing-module-docstring)
and this error:
Formatting a regular string which could be a f-stringPylint(C0209:consider-using-f-string)
and this is my settings.json file in visual studio code:
"python.linting.enabled... | [
"\n(C0209:consider-using-f-string)\n\n\nC0114:missing-module-docstring\n\nI believe you have read this issue. You can add the following content to disable these string warnings:\n \"python.linting.pylintArgs\": [\n \"--disable=C0114\",\n \"--disable=C0209\",\n ],\n\n"
] | [
1
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074152710_python_visual_studio_code.txt |
Q:
How to display a list vertically?
I have a list of letters and want to be able to display them vertically like so:
a d
b e
c f
def main():
letters = ["a", "b", "c", "d","e", "f"]
for i in letters:
print(i)
this code only display them like this:
a
b
c
d
e
A:
That's because you're printing them in... | How to display a list vertically? | I have a list of letters and want to be able to display them vertically like so:
a d
b e
c f
def main():
letters = ["a", "b", "c", "d","e", "f"]
for i in letters:
print(i)
this code only display them like this:
a
b
c
d
e
| [
"That's because you're printing them in separate lines. Although you haven't given us enough info on how actually you want to print them, I can infer that you want the first half on the first column and the second half on the second colum. \nWell, that is not that easy, you need to think ahead a little and realize ... | [
9,
4,
4,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"list",
"python",
"python_3.x",
"string"
] | stackoverflow_0022289068_list_python_python_3.x_string.txt |
Q:
VS Code terminal not running at all
Every time I try to run python file in vs code terminal shows me that white line without any respond , I checked path option when installed python and reinstalled vs code but nothing worked
A:
since you have not given any details about which system you're running, neither if t... | VS Code terminal not running at all | Every time I try to run python file in vs code terminal shows me that white line without any respond , I checked path option when installed python and reinstalled vs code but nothing worked
| [
"since you have not given any details about which system you're running, neither if this is a newly occurring problem (i.e. you've used the VSc terminal before without issues).\nmy guess is that you're running a version that is not compatible with your pc.\n(might want to reinstall VS code, the 64bit version)\nChec... | [
0,
0
] | [] | [] | [
"debugging",
"path",
"python",
"terminal",
"visual_studio_code"
] | stackoverflow_0074156960_debugging_path_python_terminal_visual_studio_code.txt |
Q:
Python - Transform/Change a date format
I have a problem which is changing the date format from '21 Sep 2022 04:37:17' to '2022-09-21 04:37:17'.
I'm using the code:
import pandas as pd
fileIn = 'C:/Users/xxx.xlsx'
df = pd.read_excel(fileIn, index_col=0)
diaStrava = df['Data da atividade'].str[:2]
mesStrava = df['D... | Python - Transform/Change a date format | I have a problem which is changing the date format from '21 Sep 2022 04:37:17' to '2022-09-21 04:37:17'.
I'm using the code:
import pandas as pd
fileIn = 'C:/Users/xxx.xlsx'
df = pd.read_excel(fileIn, index_col=0)
diaStrava = df['Data da atividade'].str[:2]
mesStrava = df['Data da atividade'].str[6:9]
anoStrava = df['D... | [
"Instead of converting the date format using string manipulation, you could instead convert the string to datetime and then back to string. See pd.to_datetime and Series.dt.strftime\n---should work, although this line might be problematic since it's not in English\nif mesStrava == 'out':\n\nConsider using dateparse... | [
0,
0
] | [] | [] | [
"date",
"pandas",
"python"
] | stackoverflow_0074176012_date_pandas_python.txt |
Q:
VSCode specific ERROR: EnvironmentNotWritableError: The current user does not have write permissions to the target environment
VSCode Python Terminals running in conda environments throw an error message:
EnvironmentNotWritableError: The current user does not have write permissions to the target environment.
All o... | VSCode specific ERROR: EnvironmentNotWritableError: The current user does not have write permissions to the target environment | VSCode Python Terminals running in conda environments throw an error message:
EnvironmentNotWritableError: The current user does not have write permissions to the target environment.
All of my other editors (Spyder, PyCharm, JupyterNB, and Anaconda-managed applications) have administrator privileges to execute conda co... | [
"Managed to work: Open the folder and right-click on \"\\Anaconda3\". go to properties -> security> choose user and check all the boxes (full control) for each user.\nAt the same time, granting vscode administrator permissions should also solve the problem.\n"
] | [
0
] | [] | [] | [
"administrator",
"python",
"visual_studio_code"
] | stackoverflow_0074160789_administrator_python_visual_studio_code.txt |
Q:
When I edit and save the CSV file through MS Excel, I want the Python script to update the file to the newly saved version
So I have a python script that will be running 24/7. Let's say the script reads a data.csv file with pandas.
csv_file = pd.read_csv('data.csv', encoding='utf-8')
Basically, every minute, I w... | When I edit and save the CSV file through MS Excel, I want the Python script to update the file to the newly saved version | So I have a python script that will be running 24/7. Let's say the script reads a data.csv file with pandas.
csv_file = pd.read_csv('data.csv', encoding='utf-8')
Basically, every minute, I want the data.csv file to be updated to the currently saved version. For example: Let's say I create (and save) a new row to the ... | [
"If you want to update the DataFrame every 60 seconds only when the file is modified:\nimport time\nimport os\nimport pandas as pd\n\nSECONDS_BETWEEN_UPDATES = 60\n\nprint('csv_file updater started, press ctrl+c to exit')\n\ntry:\n last_modified_time = 0\n while True:\n new_modified_time = os.path.getm... | [
0
] | [] | [] | [
"csv",
"excel",
"pandas",
"python"
] | stackoverflow_0074175888_csv_excel_pandas_python.txt |
Q:
cant read file from multipart\form data nginx+uwsgi+python3.9
Well, I'm struggling with this for days. I've tried so much options, but nothing can help me.
I need to read and process file, which client upload in form. But all that i've got is filename.
I've tried fieldstorage objects, werkzeug file wrappers, iobyt... | cant read file from multipart\form data nginx+uwsgi+python3.9 | Well, I'm struggling with this for days. I've tried so much options, but nothing can help me.
I need to read and process file, which client upload in form. But all that i've got is filename.
I've tried fieldstorage objects, werkzeug file wrappers, iobytes, webob and million of other options.
my configs:
[uwsgi]
module ... | [
"error was typo in html form so\nenctype=\"multipart/form-data (forgot tail \")\nleads to transfer request as type application/x-www-form-urlencoded\nthats why only thing I've got was filename.\n"
] | [
0
] | [] | [] | [
"nginx",
"python",
"uwsgi"
] | stackoverflow_0074169724_nginx_python_uwsgi.txt |
Q:
Pandas Fill in Missing Row in Group with multiple keys
I'm looking to fill in a dataframe with a missing row based on a few criteria.
Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 keyA 39686 non-null object ... | Pandas Fill in Missing Row in Group with multiple keys | I'm looking to fill in a dataframe with a missing row based on a few criteria.
Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 keyA 39686 non-null object
1 keyB 39686 non-null int64
... | [
"Try as follows. First, we use df.pivot to \"group\" all values (per each week) for each key*-sequence (as index). Next, we use df.stack with dropna parameter set to False to get rows for all key*-sequences per week. Finally, we reset the index and replace the NaNs with zeros.\nimport pandas as pd\n\ndata = [['A1',... | [
3,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0073525516_pandas_python.txt |
Q:
How to make the figure look clear after smoothing?
I make a plot using pcolormesh and it turns out like this:
Then, I tried to set the argument shading = 'gouraud', but the result looks blurry:
To make the picture clear, I also tried to interpolate the data to a smaller meshgrid. Unfortunately, it doesn' work.
S... | How to make the figure look clear after smoothing? | I make a plot using pcolormesh and it turns out like this:
Then, I tried to set the argument shading = 'gouraud', but the result looks blurry:
To make the picture clear, I also tried to interpolate the data to a smaller meshgrid. Unfortunately, it doesn' work.
So I want to know what I should do to make my plot looks ... | [
"Here I use a gaussian filter to smooth the data and make the plot look clearer.\nFirst, plot the original data, plt.pcolormesh(x, Y, Z), and the result shows:\n\nThen, let the data pass through a gaussian filter Z2 = ndimage.gaussian_filter(Z, sigma=1.0, order=0). And plot the result plt.contourf(X, Y, Z2, levels ... | [
0
] | [] | [] | [
"contourf",
"matplotlib",
"plot",
"python",
"smoothing"
] | stackoverflow_0074134732_contourf_matplotlib_plot_python_smoothing.txt |
Q:
In Visual Studio Code setting.json, I can't change syntax color of print, true, and, global
I would like to change some certain colors in the Light Visual Studio theme, in the Visual Studio Code setting.json file. I am using Python. I would like to change these:
Color purple (#900090) to print, range, list, len. ... | In Visual Studio Code setting.json, I can't change syntax color of print, true, and, global | I would like to change some certain colors in the Light Visual Studio theme, in the Visual Studio Code setting.json file. I am using Python. I would like to change these:
Color purple (#900090) to print, range, list, len. Currently the default color used by the aforementioned theme is black;
Color orange (#ff7700) to... | [
"First of all the settings.json in your question is not in the correct format. If it's just that you didn't copy exactly, then hopefully the format is correct on your machine.\nDelete or comment the following in your settings.json,\n {\n \"scope\": \"entity.name.type.class\",\n ... | [
0
] | [] | [] | [
"color_scheme",
"python",
"python_3.x",
"themes",
"visual_studio_code"
] | stackoverflow_0074157309_color_scheme_python_python_3.x_themes_visual_studio_code.txt |
Q:
Following pagination links with scrapy is not working
I'm trying to scrape this website https://www.pararius.com/english to get rental information. I want to scrape all pages on this site.
I've looked through similar questions on stackoverflow regarding scrapy pagination issues, but none seem to reflect my issue.
... | Following pagination links with scrapy is not working | I'm trying to scrape this website https://www.pararius.com/english to get rental information. I want to scrape all pages on this site.
I've looked through similar questions on stackoverflow regarding scrapy pagination issues, but none seem to reflect my issue.
Everything in my code works except for the section where I ... | [
"The following code's pagination isn't throwing any exception\nimport scrapy\n\nclass ParariusScraper(scrapy.Spider):\n name = 'pararius'\n start_urls = ['https://www.pararius.com/apartments/amsterdam/']\n def parse(self, response):\n for section in response.css('section.listing-search-item'):\n ... | [
1,
0
] | [] | [] | [
"python",
"python_3.x",
"scrapy",
"web_scraping"
] | stackoverflow_0074175249_python_python_3.x_scrapy_web_scraping.txt |
Q:
How to run functions in parallel?
I researched first and couldn't find an answer to my question. I am trying to run multiple functions in parallel in Python.
I have something like this:
files.py
import common #common is a util class that handles all the IO stuff
dir1 = 'C:\folder1'
dir2 = 'C:\folder2'
filename =... | How to run functions in parallel? | I researched first and couldn't find an answer to my question. I am trying to run multiple functions in parallel in Python.
I have something like this:
files.py
import common #common is a util class that handles all the IO stuff
dir1 = 'C:\folder1'
dir2 = 'C:\folder2'
filename = 'test.txt'
addFiles = [25, 5, 15, 35, ... | [
"You could use threading or multiprocessing.\nDue to peculiarities of CPython, threading is unlikely to achieve true parallelism. For this reason, multiprocessing is generally a better bet.\nHere is a complete example:\nfrom multiprocessing import Process\n\ndef func1():\n print 'func1: starting'\n for i in xrang... | [
245,
47,
26,
17,
8,
5,
4,
0
] | [] | [] | [
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0007207309_multiprocessing_multithreading_python.txt |
Q:
^ operator in numpy python
I am not able to understand what is ^ operator in NumPy array with boolean values.
print("----------train_mask before-------------------------------------------")
print (train_mask[10:30])
print(len(train_mask))
train_mask ^= eval_mask
print("----------eval ------------------------------... | ^ operator in numpy python | I am not able to understand what is ^ operator in NumPy array with boolean values.
print("----------train_mask before-------------------------------------------")
print (train_mask[10:30])
print(len(train_mask))
train_mask ^= eval_mask
print("----------eval -------------------------------------------")
print (eval_mask... | [
"^ is the bitwise XOR operator in Python as others have said.\nCheck out the documentation for numpy.bitwise_xor, which reads in part:\n\nCompute the bit-wise XOR of two arrays element-wise.\n\nThe key point here is “element-wise,” so in your example, since there’s one only one True value in your eval_mask array, o... | [
1
] | [] | [] | [
"numpy",
"python",
"python_3.x"
] | stackoverflow_0074176150_numpy_python_python_3.x.txt |
Q:
youtube-dl not accepting playlist url
With this code
import os
with open('urls.txt') as f:
for line in f:
os.system("youtube-dl "+"--write-thumbnail "+"--skip-download "+"--yes-playlist " +line)
The first image in the playlist downloads, then I get an error message saying 'list' is not recognize... | youtube-dl not accepting playlist url | With this code
import os
with open('urls.txt') as f:
for line in f:
os.system("youtube-dl "+"--write-thumbnail "+"--skip-download "+"--yes-playlist " +line)
The first image in the playlist downloads, then I get an error message saying 'list' is not recognized as an internal or ex ternal command, oper... | [
"Your program has a major command injection security vulnerability. You have triggered this (with harmless code) by accident. You are executing\nyoutube-dl --write-thumbnail --skip-download --yes-playlist \\\nhttps://www.youtube.com/watch?v=GA3St3Rf9Gs&list=PL-uc0GihCvU9s24BT_mvTzt3zm7e2uDGm\n\nSince the ampersand ... | [
1,
0,
0,
0
] | [] | [] | [
"python",
"youtube",
"youtube_dl"
] | stackoverflow_0046044551_python_youtube_youtube_dl.txt |
Q:
python windows application automation(how to check is icons available to click or not)
how to check is icons available to click or not in a application. I tried pywinauto and pyautogui but didn't find any method to check.
ex: In a application I want to check is there a file to save it or not.
if file exist save ic... | python windows application automation(how to check is icons available to click or not) | how to check is icons available to click or not in a application. I tried pywinauto and pyautogui but didn't find any method to check.
ex: In a application I want to check is there a file to save it or not.
if file exist save icon highlighted else not.
[1]: i.stack.imgur.com/MJmjA.png [2]: i.stack.imgur.com/nJRP7.png
| [] | [] | [
"You can use pyautogui library, as its helps in automation in any sort of interface.\n\n\nHere basically, you take screenshots of the surface which needs to be clicked, in your case, take the screenshot of your checkbox along with the text which you want to clicked or ticked.\nThen locate the screenshot in windows,... | [
-1
] | [
"automation",
"python",
"pywinauto",
"windows"
] | stackoverflow_0074176208_automation_python_pywinauto_windows.txt |
Q:
How to change 00YY year format to 2022 in Python?
Snowflake csv upload turned the date format into "0022-10-02". Is there a best way to change the "0022" format to "2022" format as NEW_DATE shows?
ORDER_DATE
NEW_DATE
0022-10-02
2022-10-02
0022-10-02
2022-10-03
I've tried:
df["ORDER_DATE"] = pd.to_datetime(df["... | How to change 00YY year format to 2022 in Python? | Snowflake csv upload turned the date format into "0022-10-02". Is there a best way to change the "0022" format to "2022" format as NEW_DATE shows?
ORDER_DATE
NEW_DATE
0022-10-02
2022-10-02
0022-10-02
2022-10-03
I've tried:
df["ORDER_DATE"] = pd.to_datetime(df["ORDER_DATE"], format='%YYYY%mm%dd', errors='i... | [
"There's a couple of things that need fixing. First, it's best to fix the dates before trying to convert them. Second, df.applymap() returns a modified DataFrame, and you aren't saving the result. Third, the format string for the date isn't quite right, but you can actually let to_datetime() figure it out with the ... | [
0,
0
] | [] | [] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0074175493_datetime_pandas_python.txt |
Q:
Anaconda3 update through command prompt on windows 10 giving 'executing transaction' for too long
I started to update my anaconda3 2022 version on windows 10 by running command prompt as administrator.
**conda update conda**
did well. (identify, verify & execute transactions done smoothly).
However, when I go to
... | Anaconda3 update through command prompt on windows 10 giving 'executing transaction' for too long | I started to update my anaconda3 2022 version on windows 10 by running command prompt as administrator.
**conda update conda**
did well. (identify, verify & execute transactions done smoothly).
However, when I go to
**conda update anaconda**,
the executing transactions step was on for almost two hours, but still to no... | [
"The base Anaconda installation is huge and so checking and resolving all of the dependencies takes a long time. I doubt you really need to update Conda, especially on a fresh install. It it likely only a few patch versions behind. Instead, you can turn off the message about upgrading to the newest version using... | [
0
] | [] | [] | [
"anaconda",
"anaconda3",
"python",
"python_3.x"
] | stackoverflow_0074176090_anaconda_anaconda3_python_python_3.x.txt |
Q:
postgresql: FATAL: password authentication failed for user "douglas"
I am trying to migrate a DB from sqlite to postgresql...so I typed:
sudo -u postgres psql
postgres=# ALTER USER postgres WITH PASSWORD 'newpassword';
and the output returns ALTER ROLE
but when I type python manage.py migrate I receive always the... | postgresql: FATAL: password authentication failed for user "douglas" | I am trying to migrate a DB from sqlite to postgresql...so I typed:
sudo -u postgres psql
postgres=# ALTER USER postgres WITH PASSWORD 'newpassword';
and the output returns ALTER ROLE
but when I type python manage.py migrate I receive always the same error:
django.db.utils.OperationalError: FATAL: password authentic... | [
"The SQL you are running does not match the user you are attempting to use.\nYou will need to create the user if it does not exist: \nCREATE USER douglas WITH PASSWORD 'vamointer';\n\nor if it does exist, change that user's password instead.\nALTER USER douglas WITH PASSWORD 'vamointer';\n\nOnce you have done that ... | [
23,
13,
9,
3,
2,
2,
0,
0,
0,
0
] | [
"I had not exactly the same problem cause mine was with docker-compose, django but mainly with postgres in which in steps of building django project (note deletion of database wasnt an issue) I couldnt migrate my database so by deleting data\\db folder I attempted to solve it. for more information on my problem Dja... | [
-1
] | [
"django",
"postgresql",
"python"
] | stackoverflow_0043060857_django_postgresql_python.txt |
Q:
Building a dependency tree
I have N-nodes and want to build a dependency pairs-graph given weight matrix by maximizing the sum:
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
Positioned along a line.
Then I have a matrix of connection weights.
This matrix is symmetric i.e. the nodes potential connections are n... | Building a dependency tree | I have N-nodes and want to build a dependency pairs-graph given weight matrix by maximizing the sum:
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
Positioned along a line.
Then I have a matrix of connection weights.
This matrix is symmetric i.e. the nodes potential connections are not directed,
F.e. :
[ 0, 0, ... | [
"Not sure if this is what you want but here you have that connections don't cross each other and every word is connected (maybe multiple times but this is not against the rules).\nimport numpy as np\nfrom typing import Optional, List, Tuple\nimport functools\n\n\nweight_matrix = np.array([[ 0, 0, 0, 0, 0, 0, ... | [
1
] | [] | [] | [
"constraints",
"dependencies",
"graph",
"python",
"tree"
] | stackoverflow_0074145768_constraints_dependencies_graph_python_tree.txt |
Q:
Dictionary Search for adjacent items with same features
I have a dictionary encoding x,y,z and color information for a finite Lego assembly like this "p_xx_yy": ['color', z]:
"myDict" : {
'p_00_00':[ 'y', 1 ], 'p_00_01':[ 'y', 1 ], 'p_00_02':[ 'g', 0 ], 'p_00_03':[ 'w', 1 ], 'p_00_04':[ 'g', 0 ], 'p_00_05':[ ... | Dictionary Search for adjacent items with same features | I have a dictionary encoding x,y,z and color information for a finite Lego assembly like this "p_xx_yy": ['color', z]:
"myDict" : {
'p_00_00':[ 'y', 1 ], 'p_00_01':[ 'y', 1 ], 'p_00_02':[ 'g', 0 ], 'p_00_03':[ 'w', 1 ], 'p_00_04':[ 'g', 0 ], 'p_00_05':[ 'o', 1 ], 'p_00_06':[ 'g', 0 ], 'p_00_07':[ 'g', 0 ], 'p_00_0... | [
"The solution was to store the blocks' positions taking into account that I have a finite set of blocks, and to be sure that the position doesn't belong to another Lego:\n self.lego_map = {\n \"simple\" : {\n \"wc1\":[\"p_08_08\", 1],\n \"wc2\":[\"p_09_08\", 1],\n \"rc1\":... | [
1
] | [] | [] | [
"dictionary",
"python",
"search"
] | stackoverflow_0074119905_dictionary_python_search.txt |
Q:
How do i make it so that a space is added every 4 digits
So I'm currently working on a decimal-to-binary converter and am running into a formatting issue where I can't seem to add a space every four digits. currently, it is adding the "space"(at the moment it's a 5) to the end of the string. any suggestions are we... | How do i make it so that a space is added every 4 digits | So I'm currently working on a decimal-to-binary converter and am running into a formatting issue where I can't seem to add a space every four digits. currently, it is adding the "space"(at the moment it's a 5) to the end of the string. any suggestions are welcome.
decimal = int(input("Enter Binary Number: "))
binary =... | [
"There are better ways to do what you're doing, but going with your code, here's a fixed version that I think does what you want:\ndecimal = int(input(\"Enter Binary Number: \"))\nbinary = \"\"\n\nwhile decimal > 0:\n remainder = decimal % 2\n binary += str(remainder)\n decimal = int(decimal / 2)\n\nrevers... | [
0,
0,
0
] | [
"try this\ndecimal = int(input(\"Enter Binary Number: \"))\n\nbinary = \"\"\ncnt = 0\nwhile decimal > 0:\n remainder = decimal % 2\n binary += str(remainder)\n cnt += 1\n if cnt % 4 == 0:\n binary += str(\" \")\n decimal = int(decimal / 2)\n\nwhile len(binary.replace(\" \",\"\")) % 4 != 0:\n ... | [
-1
] | [
"python"
] | stackoverflow_0074176087_python.txt |
Q:
How to sort a dictionary by the value first with asending order, if the value are same the sort the key by desending order
How to sort a dictionary by the value first in descending order, if the value is the same then sort the key in ascending order.
The correct order:
[('ipsum', 0.07), ('lorem', 0.07), ('dummy', ... | How to sort a dictionary by the value first with asending order, if the value are same the sort the key by desending order | How to sort a dictionary by the value first in descending order, if the value is the same then sort the key in ascending order.
The correct order:
[('ipsum', 0.07), ('lorem', 0.07), ('dummy', 0.06), ('type', 0.06), ('typesett', 0.06)]
The order of key doesn't correct :
[('lorem', 0.07), ('ipsum', 0.07), ('typesett', 0... | [
"You can pass a key to the sorted function that tells it how to sort your dictionary items. In this case, you want to sort by index 1 of the tuple first. Since you want it descending order, you can use the fact that it is numeric to flip the ascending order by putting a negative sign on the key.\nIn the case of a... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074176308_python.txt |
Q:
how to use python's reqular expression to match ip?
I am trying to match the pattern of an IP address. what I have is
[0-999].[0-999].[0-999].[0-999]
what test data are: 10.37.255.1 , 1.1.1.10 , and 2.2.3.3.3. Unfortunately it picks up the first 2 data sets as well as the first 4 numbers of the third data.
what ca... | how to use python's reqular expression to match ip? | I am trying to match the pattern of an IP address. what I have is
[0-999].[0-999].[0-999].[0-999]
what test data are: 10.37.255.1 , 1.1.1.10 , and 2.2.3.3.3. Unfortunately it picks up the first 2 data sets as well as the first 4 numbers of the third data.
what can I do to exclude the third data set in the return?
| [
"You could surround your regex pattern by whitespace lookarounds:\ninp = \"These are my IP addresses 10.37.255.1 and 1.1.1.10 and this is my serial and ID number 4.1.2, 2.2.3.3.3\"\nips = re.findall(r'(?<!\\S)\\d+(?:\\.\\d+){3}(?!\\S)', inp)\nprint(ips) # ['10.37.255.1', '1.1.1.10']\n\nSide note: [0-999] does not ... | [
1
] | [] | [] | [
"python",
"python_re"
] | stackoverflow_0074176302_python_python_re.txt |
Q:
How to detect a specific inner rectangle in a complex shape
I have the following input image:
and I do like to crop the inner max rectangle like this (Expected Output):
but when I do contour detection I get the external rectangle (Current Result):
import cv2
import numpy as np
res = cv2.imread("input.png", 0)
... | How to detect a specific inner rectangle in a complex shape | I have the following input image:
and I do like to crop the inner max rectangle like this (Expected Output):
but when I do contour detection I get the external rectangle (Current Result):
import cv2
import numpy as np
res = cv2.imread("input.png", 0)
k0 = 5
dgauss = cv2.GaussianBlur(res, (k0, k0), 0)
op = cv2.MOR... | [
"I have solved this issue by:\n\nAligning depth to the color.\nSegmenting the green table using HSV information as explained here\nCropped the desired rectangle (ROI) using color information.\n\n"
] | [
0
] | [] | [] | [
"contour",
"grayscale",
"image_processing",
"opencv",
"python"
] | stackoverflow_0071465360_contour_grayscale_image_processing_opencv_python.txt |
Q:
Correction Function to Balance Depth
I have a depth image with a shape of 11 x 23, and I do want to balance the depth in all cells using the fact that the depth in the four corners is the same, the values are shown in the drawing here:
My first idea was to calculate the difference between the corners and to sum t... | Correction Function to Balance Depth | I have a depth image with a shape of 11 x 23, and I do want to balance the depth in all cells using the fact that the depth in the four corners is the same, the values are shown in the drawing here:
My first idea was to calculate the difference between the corners and to sum that difference for each cell as follows:
d... | [
"As @YvesDaoust suggested, subtracting a Bilinear Model has solved this problem:\n def corr_func(self, arr):\n \"\"\"\n Empirical Values\n \"\"\"\n self.y_correc = 0.0 #- 0.5\n self.x_correc = + 4.0\n \n if(self.corr_array is None):\n self.corr_array = ... | [
0
] | [] | [] | [
"3d",
"depth",
"image_processing",
"python"
] | stackoverflow_0072537346_3d_depth_image_processing_python.txt |
Q:
Why aiohttp works slower than requests wrapped by run_in_executor?
all!
I need to make about 10,000 requests to the web service, and i expected JSON in response. Since the requests are independent of each other, I want to run them in parallel. I think aiohttp can help me with that. I wrote the following code:
impo... | Why aiohttp works slower than requests wrapped by run_in_executor? | all!
I need to make about 10,000 requests to the web service, and i expected JSON in response. Since the requests are independent of each other, I want to run them in parallel. I think aiohttp can help me with that. I wrote the following code:
import asyncio
import aiohttp
async def execute_module(session: aiohttp.Cl... | [
"Have you tried uvloop - https://github.com/MagicStack/uvloop? This should increase speed of aiohttp request\n",
"loop.run_in_executor(None, ...) runs syncroneous code in a thread pool (multiple threads). Event loop runs code in one thread.\nMy guess is that waiting for IO shouldn't make much of a difference, bu... | [
0,
0,
0
] | [] | [] | [
"aiohttp",
"python",
"python_asyncio",
"python_requests"
] | stackoverflow_0058996572_aiohttp_python_python_asyncio_python_requests.txt |
Q:
Python/Pygame wont display any error messages when it just crashes
Im trying to implement a upgrade system in my game and it just breaks after you buy something 4 times which is not what i want i just want it to go on forever.
And Py/Pygame doesnt give me any Error Messages.
I tried changing the font from Helvetic... | Python/Pygame wont display any error messages when it just crashes | Im trying to implement a upgrade system in my game and it just breaks after you buy something 4 times which is not what i want i just want it to go on forever.
And Py/Pygame doesnt give me any Error Messages.
I tried changing the font from Helvetica to Segou UI
,That didnt work either
from xml.sax import SAXNotRecogniz... | [
"After some minor testing with the code myself. It seems as if it ends up going to the final statement in the code, which is when the loop ends and the window closes. Or as in your case, the game \"crashes.\" In order to fix this, you just need to remove the following lines of code:\n if 4 in listOfUpgradesNumbe... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074176144_python.txt |
Q:
I want to add like unlike feature to my blog site, everythin is okay there, like and unlike objects are being created.. But I'm getting NoReverseMatch
I want to add like unlike feature to my blog site, everythin is okay there, like and unlike objects are being created.. But I'm getting NoReverseMatch when I'm clic... | I want to add like unlike feature to my blog site, everythin is okay there, like and unlike objects are being created.. But I'm getting NoReverseMatch | I want to add like unlike feature to my blog site, everythin is okay there, like and unlike objects are being created.. But I'm getting NoReverseMatch when I'm clicking the Like and Unlike..and the problem is I can't figure it out why I'm getting this...my models.py, views.py, urls.py, blog_page.html...all are attatche... | [
"Your URLs are expecting a string value for blog_id but you are passing them an int in {% url 'unlike' blog.id %} Try changing your URL file to expect an int, and you should be able to look it up more successfully.\npath(\"blog_page/<int:pk>/\", views.blog_view, name='blog_page'),\npath(\"like/<int:pk>/\", views.... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074176350_django_python.txt |
Q:
python, how do i matchtemplate transparent image with opencv
im using matchtemplate to detect 67x45 sqaure on background. i think my code works fine without any problem but the problem is i have to set high threshold for it to detect successfully otherwise it would give so many false detections. so i tried changin... | python, how do i matchtemplate transparent image with opencv | im using matchtemplate to detect 67x45 sqaure on background. i think my code works fine without any problem but the problem is i have to set high threshold for it to detect successfully otherwise it would give so many false detections. so i tried changing method to cv2.TM_CCOEFF_NORMED but it didnt work well. i also tr... | [
"I am using matchtemplate to detect 67x45 square on background.\nIn the special case of a bounding-box-like rectangle it makes sense to detect it using own method working directly on the numpy image array instead of using OpenCV matching functions with a template image and coping with different matching algorithms ... | [
1
] | [] | [] | [
"non_maximum_suppression",
"opencv",
"python",
"template_matching"
] | stackoverflow_0074168148_non_maximum_suppression_opencv_python_template_matching.txt |
Q:
estimator : string or callable that maps vector -> scalar
I am reading the documentation of seaborn.barplot and I read the following.
estimator : string or callable that maps vector -> scalar, optional
Statistical function to estimate within each categorical bin.
I could not understand what callable that maps vec... | estimator : string or callable that maps vector -> scalar | I am reading the documentation of seaborn.barplot and I read the following.
estimator : string or callable that maps vector -> scalar, optional
Statistical function to estimate within each categorical bin.
I could not understand what callable that maps vector -> scalar means. What does this statement convey?
When I pa... | [
"Callable means a function. Named function or lambda function. A function that takes a vector as argument and returns a scalar. Function are \"first class citizens\" in Python so can be passed as argument and generally treated as any other object.\nSee example here:\nimport seaborn as sns\nimport matplotlib.pyplot ... | [
0
] | [] | [] | [
"pandas",
"python",
"seaborn"
] | stackoverflow_0074176413_pandas_python_seaborn.txt |
Q:
How to do I connect my two modules within my Bank and Account classes?
I'm a newbie to python. I'm writing a banking program script. The Bank has a defined name and address. Where the Account has a defined, first name, last name, and balance.
I'm testing the code by trying to transfer money from one account to ano... | How to do I connect my two modules within my Bank and Account classes? | I'm a newbie to python. I'm writing a banking program script. The Bank has a defined name and address. Where the Account has a defined, first name, last name, and balance.
I'm testing the code by trying to transfer money from one account to another. But I'm getting an error after entering accounts. Where did I go wrong... | [
"To add an item to a list, use the .append method. What you have written in the last line of create_account doesn't make sense. Replace:\nself.all_accounts[Account] = accounts\n\nwith this:\nself.all_accounts.append(accounts)\n\n"
] | [
0
] | [] | [] | [
"class",
"function",
"module",
"python"
] | stackoverflow_0074165690_class_function_module_python.txt |
Q:
python error AttributeError: 'str' object has no attribute 'setdefault'
I'm trying to run the inverse_dictionary project using this command.
But every time I'm trying to run I faced the error.
I can't figure out what the problem is. Please help me fix it.
A:
The problem line is inverse = inverse.setdefault(val,... | python error AttributeError: 'str' object has no attribute 'setdefault' | I'm trying to run the inverse_dictionary project using this command.
But every time I'm trying to run I faced the error.
I can't figure out what the problem is. Please help me fix it.
| [
"The problem line is inverse = inverse.setdefault(val, key). setdefault returns the value, in this case its a str. This line sets the inverse to a str, not a dict. The second time it is run, inverse is a str, which does not have a setdefault method.\n"
] | [
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074176383_dictionary_python.txt |
Q:
Lowest sum - Describe the Path
I´m solving an exercise about the Lowest Sum Matrix problem with Dynamic Programming. But the problem is asking the description of the path that correspond to the sum determined. Does anyone have a solution?
in the example should be
[[1,1], [2,1], [2,2], [2,3], [3,3], [3,4], [4,4], ... | Lowest sum - Describe the Path | I´m solving an exercise about the Lowest Sum Matrix problem with Dynamic Programming. But the problem is asking the description of the path that correspond to the sum determined. Does anyone have a solution?
in the example should be
[[1,1], [2,1], [2,2], [2,3], [3,3], [3,4], [4,4], [5,4], [5,5]]
Here I posted the code... | [
"Here's a solution to your github example; easy enough to generalize to other matrix sizes.\nIt tracks the costs and path of points seen but not yet moved from, and only moves from the point with the minimum cost at any point in time. The list is sorted after each move, and the previous cheapest so far point is re... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074175748_python.txt |
Q:
python-markdown htmlStash placeholder not being replaced
I am currently developing a web application using django and and using python-markdown to convert markdown into HTML. There are a couple of situations that markdown currently doesn't handle, and as such have written a couple of basic extensions.
"""
Helps m... | python-markdown htmlStash placeholder not being replaced | I am currently developing a web application using django and and using python-markdown to convert markdown into HTML. There are a couple of situations that markdown currently doesn't handle, and as such have written a couple of basic extensions.
"""
Helps make paras for Less framework
@div large-column float-left
# ... | [
"I know this is from a long time ago, but for any others (like me) who run into this issue and see this post, you need to make sure to register the preprocessor after at least the normalize_whitespace step (which is stripping unicode characters -- and what the htmlstash function is using as delimiters).\nin this ca... | [
0
] | [] | [] | [
"markdown",
"preprocessor",
"python"
] | stackoverflow_0007051756_markdown_preprocessor_python.txt |
Q:
TypeError: unhashable type: 'numpy.ndarray' using dataset for values
I want to do a Bar graph where I can see the 3 medals of a country. I've already dropped all the teams I only have one but when I do it I get this error...
This is what I got:
N = 3
ind = np.arange(N)
width = 0.25
goldMedals = df[(df.Medal == '... | TypeError: unhashable type: 'numpy.ndarray' using dataset for values | I want to do a Bar graph where I can see the 3 medals of a country. I've already dropped all the teams I only have one but when I do it I get this error...
This is what I got:
N = 3
ind = np.arange(N)
width = 0.25
goldMedals = df[(df.Medal == 'Gold')]
bar1 = plt.bar(ind, goldMedals, width, color = 'gold')
silverMe... | [
"I am guessing since you have not presented any data, but I think you are trying to visualize the results of conditional extraction in a long form data frame. The cause of the error is that the extraction result is a data frame, but the index and the data frame itself are specified respectively. So, for each graph,... | [
0
] | [] | [] | [
"bar_chart",
"matplotlib",
"python"
] | stackoverflow_0074174566_bar_chart_matplotlib_python.txt |
Q:
Python Printing when conditions aren't correct
For some reason python is printing when the conditions aren't correct.
Here is an example of my code:
config.py
a = 0
b = 0
verify = True
main.py
from config import a,b,verify
verify = True
current_check = 0
if verify == True:
current_check + 1
if a < 0:
... | Python Printing when conditions aren't correct | For some reason python is printing when the conditions aren't correct.
Here is an example of my code:
config.py
a = 0
b = 0
verify = True
main.py
from config import a,b,verify
verify = True
current_check = 0
if verify == True:
current_check + 1
if a < 0:
print(config_options[current_check]+" has an in... | [
"Because config_options[current_check] is not the same value as a.\nYou set a to 0, but you didn't do that for config_options[current_check].\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074176451_python.txt |
Q:
How can I get my separate GUI module to run to completion within my current main module?
I am working on a python application for construction layout work. It basically contains points and should eventually allow you to get information and calculations from those points. One of the functions should upload points f... | How can I get my separate GUI module to run to completion within my current main module? | I am working on a python application for construction layout work. It basically contains points and should eventually allow you to get information and calculations from those points. One of the functions should upload points from a text file using a separate module and if any of the points are already saved, ask the us... | [
"First of all some general hints:\n\nimport just what you need\nwhen you intend to use the whole module import it once and stick to the way you imported it.\ntake a look at PEP 8 Style Guide\n\nline length and how to split lines of codes for example\n\n\ngroup logical blocks of code, such as construction and layout... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074175300_python_tkinter.txt |
Q:
How to make a specific key the first key in a dictionary?
I want make a specific element of each dictionary the first element in a list of dictionaries. How would I do this, or is it even possible given that dictionaries are unordered?
I don't want to use .sort() by itself or OrderedDict because both will not bri... | How to make a specific key the first key in a dictionary? | I want make a specific element of each dictionary the first element in a list of dictionaries. How would I do this, or is it even possible given that dictionaries are unordered?
I don't want to use .sort() by itself or OrderedDict because both will not bring the desired element to the top of the keys as the keys are a... | [
"Dicts don't have any top or bottom. You can try something like this:\n>>> from itertools import chain\n>>> dic = {'a': 1, 'b': 2, 'c': 3}\n>>> key = 'b'\nfor k in chain(key, (dic.viewkeys()-key)):\n print k, dic[k]\n... \nb 2\na 1\nc 3\n\nBetter use an OrderedDict.\n>>> from collections import OrderedDict\n... | [
3,
2,
1,
1,
0
] | [] | [] | [
"dictionary",
"python",
"sorting"
] | stackoverflow_0018134889_dictionary_python_sorting.txt |
Q:
Calculating a minimum number input without using sys module
Write a program in Python that reads a sequence of integer inputs (data) from the user and then prints the following results:
the total of all the inputs
the smallest of the inputs
the largest of the inputs
the number of even inputs
the number of odd inpu... | Calculating a minimum number input without using sys module | Write a program in Python that reads a sequence of integer inputs (data) from the user and then prints the following results:
the total of all the inputs
the smallest of the inputs
the largest of the inputs
the number of even inputs
the number of odd inputs
the average of all of the inputs
You do not know how many numb... | [
"Interesting approach, when I have problems like this I use float('inf') or float('-inf'). Can easily be worked into your approach.\n",
"The answer to \"can it be done?\" when it comes to programming is almost always \"yes.\"\nIn this case, you can test if you're on the first loop iteration and set smallest and l... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074176488_python.txt |
Q:
Horse Racing Simulation Loop
So I have this program that basically runs a horse betting simulation. When the user chooses the horse from a list of names I have created, my program returns a % that predicts the horse's chances of winning the race (I am still working on this so just don't mind it). However, the prog... | Horse Racing Simulation Loop | So I have this program that basically runs a horse betting simulation. When the user chooses the horse from a list of names I have created, my program returns a % that predicts the horse's chances of winning the race (I am still working on this so just don't mind it). However, the program asks the user if they want to ... | [
"You could paste the code for the Horserestart function anywhere Horserestart() is in the code.\ndef Horse(): \n print(\"Horses to bet on: Tyrone, Jamal, Jaquavious, Quandale, Quantavious, and Charlie.\") \n horse_pick = input(\"What horse do you want to choose? \") \n if horse_pick == \"Tyrone\": \n ... | [
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074176363_loops_python.txt |
Q:
Install email_validator using pip
I have email_validator installed but I am getting an error message saying it is not installed.
Does it have to be installed in my project folder? Or can it be in the main site-packages folder? When I run my program I get this error message:
Exception: Install 'email_validator' for... | Install email_validator using pip | I have email_validator installed but I am getting an error message saying it is not installed.
Does it have to be installed in my project folder? Or can it be in the main site-packages folder? When I run my program I get this error message:
Exception: Install 'email_validator' for email validation support
I can see th... | [
"The simplest way to manage packages so there are no conflicts between projects and site packages are Virtual environments\nemail_validator example\nsudo apt-get install -y python3-venv python3-pip\nmkdir email\ncd email\ndeactivate 2> /dev/null\npip3 show virtualenv\nif [ $? -ne 0 ] ; then\n pip3 install --upgra... | [
2,
0,
0,
0
] | [] | [] | [
"email_validation",
"flask_wtforms",
"python"
] | stackoverflow_0062707500_email_validation_flask_wtforms_python.txt |
Q:
How can I count occurrences in a multidimensional Python dictionary?
I am trying to write a script to count the occurrences of an item in a MULTIDIMENSIONAL list. For example it would return:
Happy: 1
Giggly: 3
Hazy: 1
data = {"AK-47":["Happy","Giggly","Confident"],
"Gelato":["Slumped","Tired","Light","Giggly"]... | How can I count occurrences in a multidimensional Python dictionary? | I am trying to write a script to count the occurrences of an item in a MULTIDIMENSIONAL list. For example it would return:
Happy: 1
Giggly: 3
Hazy: 1
data = {"AK-47":["Happy","Giggly","Confident"],
"Gelato":["Slumped","Tired","Light","Giggly"],
"Buddah Bliss":["Confused","Euphoria","Hazy"],
"Grandaddy Purple":["Slee... | [
"data = {\"AK-47\": [\"Happy\", \"Giggly\", \"Confident\"],\n \"Gelato\": [\"Slumped\", \"Tired\", \"Light\", \"Giggly\"],\n \"Buddah Bliss\": [\"Confused\", \"Euphoria\", \"Hazy\"],\n \"Grandaddy Purple\": [\"Sleepy\", \"Slumped\"],\n \"Laughing Gas\": [\"Giggly\", \"Light\", \"Euphoria... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074176483_python.txt |
Q:
Why is this "in" statement false?
I'm trying to write simple code in order to see if a string is in a list.
This is the code I've gotten.
a = ["Hill, Lauren", "Smith, Jerry"]
b = "Smith"
if b in a:
print("True")
else:
print("False")
I don't understand why it prints "False". I thought it would print "T... | Why is this "in" statement false? | I'm trying to write simple code in order to see if a string is in a list.
This is the code I've gotten.
a = ["Hill, Lauren", "Smith, Jerry"]
b = "Smith"
if b in a:
print("True")
else:
print("False")
I don't understand why it prints "False". I thought it would print "True" as "Smith" is in "Smith, Jerry".
C... | [
"a = [\"Hill, Lauren\", \"Smith, Jerry\"]\nb = \"Smith\"\nif b in a:\nprint(\"True\")\nelse:\nprint(\"False\")\nProblem\nWhen you observe your last string properly you have created Smith,Jerry combined. When you are checking for b in list, It answers false because its not actually not in list\nSolution\nCorrect you... | [
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074176431_python.txt |
Q:
My Instagram code won't run or open in VS Code
from instabot import bot
my_instagram bot= instagram Bot()
#login
my_instagram bot.login(username="", password="")
#follow a user
my_instagram bot.follow("python_app_projects")
#follow multiple users
my_instagram bot.follow_users(["coding_for_beginners_", "python.a... | My Instagram code won't run or open in VS Code | from instabot import bot
my_instagram bot= instagram Bot()
#login
my_instagram bot.login(username="", password="")
#follow a user
my_instagram bot.follow("python_app_projects")
#follow multiple users
my_instagram bot.follow_users(["coding_for_beginners_", "python.app", "py_beginners"])
#unfollow the non followers... | [
"Incorrect Code\n from instabot import bot\n\nmy_instagram bot= instagram Bot()\n#login\nmy_instagram bot.login(username=\"\", password=\"\")\n\n#follow a user\nmy_instagram bot.follow(\"python_app_projects\")\n\n\n#follow multiple users\nmy_instagram bot.follow_users([\"coding_for_beginners_\", \"python.app\", ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074176245_python.txt |
Q:
constructing subgraphs with thicker edges (networkX)
merged_table=
ID 0 1 2 3 4 5 6 7 8 9 10 11 12
131X1319 1 14 6 16 1 10 8 15 15 17 15 18 16
13212YX3 1 1 4 8 11 9 14 7 0 3 0 17 13
13216131 1 1 13 9 15 17 0 9 3 15 11 8 10
1329... | constructing subgraphs with thicker edges (networkX) | merged_table=
ID 0 1 2 3 4 5 6 7 8 9 10 11 12
131X1319 1 14 6 16 1 10 8 15 15 17 15 18 16
13212YX3 1 1 4 8 11 9 14 7 0 3 0 17 13
13216131 1 1 13 9 15 17 0 9 3 15 11 8 10
132921W6 1 14 10 4 18 7 8 15 15 17 15 18 16
1... | [
"I assume you have in mind some kind of side-by-side comparison. With that in mind, here's a modification of your script that produces drawings of both graphs with the same layout.\ncolumns=list(merged_table.columns.values)\nct = Counter(p for i in range(len(columns)-2) \n for p in zip(merged_table[co... | [
0
] | [] | [] | [
"data_analysis",
"graph",
"networkx",
"pandas",
"python"
] | stackoverflow_0074174134_data_analysis_graph_networkx_pandas_python.txt |
Q:
Kernel Died when plotting CNN learning history
I was creating a CNN using keras. Everything was fined until I try to plot the learning history of
the model.
# Train the CNN
history = model.fit_generator(train_generator, steps_per_epoch = 143, epochs = 20, validation_data = validation_generator, validation_steps = ... | Kernel Died when plotting CNN learning history | I was creating a CNN using keras. Everything was fined until I try to plot the learning history of
the model.
# Train the CNN
history = model.fit_generator(train_generator, steps_per_epoch = 143, epochs = 20, validation_data = validation_generator, validation_steps = 18)
# Display the loss and accuracy during training... | [
"I've solved the problem. Updating python and tensorflow to 3.9 and 2.10 respectively.\n"
] | [
0
] | [] | [] | [
"deep_learning",
"keras",
"python"
] | stackoverflow_0074095158_deep_learning_keras_python.txt |
Q:
Add product to cart using python in Django
I want to make a simple function that collects the product ID and adds it to the user's shopping cart by clicking the "add to cart" button. I have the shopping cart table and product table created but am struggling to find the correct function to add the product to the ca... | Add product to cart using python in Django | I want to make a simple function that collects the product ID and adds it to the user's shopping cart by clicking the "add to cart" button. I have the shopping cart table and product table created but am struggling to find the correct function to add the product to the cart. Anything helps I am very new to Python and D... | [
"You need a relation between Cart* and User\nclass Cart(models.Model):\n cart_id = models.Charfield(primary_key=True)\n total = models.DecimalField(max_digits=9,decimal_places=2) \n quantity = models.IntegerField() \n products = models.ManyToManyField(Product)\n user = models.OneToOneField(User)\n\... | [
0,
0
] | [] | [] | [
"django",
"function",
"html",
"python",
"shopping_cart"
] | stackoverflow_0074174294_django_function_html_python_shopping_cart.txt |
Q:
Limiting user from 0-100 in input function
How to create a program that limiting user in input function from 0-100 only. We need to ask user to for their grade in 4 tests after that if the user does not have taken any of those test it shows INC.
| Limiting user from 0-100 in input function | How to create a program that limiting user in input function from 0-100 only. We need to ask user to for their grade in 4 tests after that if the user does not have taken any of those test it shows INC.
| [] | [] | [
"while True:\n score = float(input('Enter your score: '))\n if not 0 <= score <= 100:\n continue\n else:\n break\n\n",
"while True:\n score = input('Enter your score: ')\n if not (0 <= score <= 100):\n continue\n else:\n break\n\n"
] | [
-1,
-1
] | [
"input",
"python"
] | stackoverflow_0074176634_input_python.txt |
Q:
api.get_user with Tweepy will not give description
I'm trying to use Tweepy (version 4.4.0) to get a user's description but it's seemingly not working:
u = api.get_user(username='XXXX', user_fields=['description'])
but the output of this is simply:
Response(data=<User id=123 name=XXX username=XXX>, includes={}, e... | api.get_user with Tweepy will not give description | I'm trying to use Tweepy (version 4.4.0) to get a user's description but it's seemingly not working:
u = api.get_user(username='XXXX', user_fields=['description'])
but the output of this is simply:
Response(data=<User id=123 name=XXX username=XXX>, includes={}, errors=[], meta={})
So it's getting me the name and id f... | [
"api seems to be an instance of tweepy.Client here.\nFrom the relevant FAQ section in Tweepy's documentation:\n\nWhy am I not getting expansions or fields data with API v2 using Client?\nIf you are simply printing the objects and looking at that output, the string representations of API v2 models/objects only inclu... | [
1,
0
] | [
"Sample code for extracting description of any twitter user is as follows\nimport tweepy\nauth = tweepy.OAuth2BearerHandler(os.environ.get(\"TWITTER_API_KEY\"))\napi = tweepy.API(auth)\nuser = api.get_user(screen_name=\"TechWiser\", include_entities=False)\ndescription = user._json['description']\n\nuser._json cont... | [
-1
] | [
"python",
"tweepy"
] | stackoverflow_0071309502_python_tweepy.txt |
Q:
Get row with min values
For a matrix, I want to get the row (if it exists) which has the lesser values for each column - strictly dominated by all other rows. For example,
A = [[7,5,8,2]
[10,3,7,8]
[6,2,6,1]]
B = [[7,5,8,2]
[10,3,7,8]
[9,5,6,7]
[6,2,6,1]]
For matrix A, row [6,2,6,1] has the m... | Get row with min values | For a matrix, I want to get the row (if it exists) which has the lesser values for each column - strictly dominated by all other rows. For example,
A = [[7,5,8,2]
[10,3,7,8]
[6,2,6,1]]
B = [[7,5,8,2]
[10,3,7,8]
[9,5,6,7]
[6,2,6,1]]
For matrix A, row [6,2,6,1] has the minimum values. A[2][i] < A[1]... | [
"Here you go. See the comments for what each line does.\nimport numpy as np\n\ndef get_index_of_minimum_row(arr):\n \"\"\" returns the index of the minimum row or None if it does not exist \"\"\"\n\n #Get the minimum value of each column.\n column_minimums = arr.min(axis=0)\n\n #Create a mask of the arr... | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074175482_numpy_python.txt |
Q:
Inconsistent web scraping while using selenium, not getting all the scraped data
Im trying to scrape the following page: https://lambda-app-eia.herokuapp.com/
with the code below
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDr... | Inconsistent web scraping while using selenium, not getting all the scraped data | Im trying to scrape the following page: https://lambda-app-eia.herokuapp.com/
with the code below
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
chrome_opti... | [
"Add some wait time before getting the element's property, because the values are getting loaded after 2 to 3 seconds once the page loading completes.\nimport time\n\ntime.sleep(3)\nelements = driver.find_elements(By.CSS_SELECTOR, \".MuiTypography-root.MuiTypography-h4.css-2voflx\")\njob_list = [ job.text for job i... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074175704_python_selenium_selenium_webdriver.txt |
Q:
how would i get an if statement to work like this?
Apologies for the bad title, I wasn't quite sure how to sum up my issue.
I'm working on a "positivity generator" that gives the user positive affirmation based on their mood on a scale of 1-10. Here is the code and my question.
import random
A = "You're looking g... | how would i get an if statement to work like this? | Apologies for the bad title, I wasn't quite sure how to sum up my issue.
I'm working on a "positivity generator" that gives the user positive affirmation based on their mood on a scale of 1-10. Here is the code and my question.
import random
A = "You're looking great today!"
B = "Remember, coding takes practice. You'r... | [
"Assign the value returned by the call to input() to a variable, like mood and then check the value of mood in the expressions in the if statement. Also, you'd want something like mood in range(4, 8) since range() is up-to-but-not-including and you don't want too loop.\nSo:\nimport random\n\nA = \"You're looking gr... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074176687_python.txt |
Q:
number guessing game that adds points for every loop
i'm trying to write a random number guessing game with a specific structure. if user gets the number wrong or right, they need to have the option to try again. if they're right, then 5 points are added to the TotalPoints variable. here's the code
from random im... | number guessing game that adds points for every loop | i'm trying to write a random number guessing game with a specific structure. if user gets the number wrong or right, they need to have the option to try again. if they're right, then 5 points are added to the TotalPoints variable. here's the code
from random import randint
#generates a random guess
def GenerateGuess(... | [
"Incorrect Code\nfrom random import randint\n\n#generates a random guess\ndef GenerateGuess():\n return (randint(1, 10))\n\nTotalPoints = 0\n\n\nUserGuess = int(input(\"Enter any number: \"))\n\n#takes users guess and random int, and adds points to TotalPoints if correct\n#return True if correct, return False ... | [
-1
] | [] | [] | [
"python"
] | stackoverflow_0074176626_python.txt |
Q:
Is there a differentiable algorithm for image quantization?
I am implementing an autoencoder, used to rebuild color images. The loss function I want to use requires a reduced color set (max ~100 different colors) but I am struggling to find a suitable differentiable algorithm.
Another doubt I have is the following... | Is there a differentiable algorithm for image quantization? | I am implementing an autoencoder, used to rebuild color images. The loss function I want to use requires a reduced color set (max ~100 different colors) but I am struggling to find a suitable differentiable algorithm.
Another doubt I have is the following: is it better to apply such quantization directly in the loss fu... | [
"If you want to compress the image, it seems you want to find discrete color set for image compression. In that case auto-encoder is not suitable approach for image compression.\nThe general auto-encoder compress tensor of images(B x C x H x W) to latent code of each images(B x D, typically D = 512). The beauty of ... | [
0
] | [] | [] | [
"keras",
"loss_function",
"python",
"tensorflow",
"vision"
] | stackoverflow_0074142324_keras_loss_function_python_tensorflow_vision.txt |
Q:
Networkx : getting all possible paths in DAG
I am trying to split a directed (acyclic) graph into direction-connected path, relying on connectivity :
When I test weak and strong connectivity subgraphs, here is what I get :
Weak connectivity :
['16', '17'], ['3', '41', '39', '42']
Strong connectivity :
['17'], ['1... | Networkx : getting all possible paths in DAG | I am trying to split a directed (acyclic) graph into direction-connected path, relying on connectivity :
When I test weak and strong connectivity subgraphs, here is what I get :
Weak connectivity :
['16', '17'], ['3', '41', '39', '42']
Strong connectivity :
['17'], ['16'], ['39'], ['41'], ['3'], ['42']
I understand t... | [
"So, thanks to comments & answers, I realised that \"connectivity\" was a false lead for what I want to achieve. To be clear : I want to get every possible path between all starting nodes to their connected ending nodes, in a directed acyclic graph.\nSo I ended up writing my own solution, which is quite simple to u... | [
7,
2,
0,
0
] | [] | [] | [
"directed_graph",
"graph",
"networkx",
"python"
] | stackoverflow_0055711945_directed_graph_graph_networkx_python.txt |
Q:
How does self.tk.call work in the Text widget source code?
I am using tkinter for a data structures class and I'd like to use the text widget as part of a project. The prof asked what structure I was using and I realized I didn't know how tkinter built a container around the text widget.
I dug around in the source... | How does self.tk.call work in the Text widget source code? | I am using tkinter for a data structures class and I'd like to use the text widget as part of a project. The prof asked what structure I was using and I realized I didn't know how tkinter built a container around the text widget.
I dug around in the source code a little bit, in __init__.py there's this section:
class T... | [
"Summarized comments, to preserve for future interest:\n@jasonharper, pointed out:\n\nNONE of Tkinter is actually implemented in Python - the actual GUI\n(Tk) is implemented in the Tcl programming language. Tkinter embeds a\nTcl interpreter, available as tk from any widget; the .call() method\nsubmits command lines... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074176388_python_tkinter.txt |
Q:
Is Spacy lemmatization not working properly or does it not lemmatize all words ending with "-ing"?
When I run the spacy lemmatizer, it does not lemmatize the word "consulting" and therefore I suspect it is failing.
Here is my code:
nlp = spacy.load('en_core_web_trf', disable=['parser', 'ner'])
lemmatizer = nlp.get... | Is Spacy lemmatization not working properly or does it not lemmatize all words ending with "-ing"? | When I run the spacy lemmatizer, it does not lemmatize the word "consulting" and therefore I suspect it is failing.
Here is my code:
nlp = spacy.load('en_core_web_trf', disable=['parser', 'ner'])
lemmatizer = nlp.get_pipe('lemmatizer')
doc = nlp('consulting')
print([token.lemma_ for token in doc])
And my output:
['con... | [
"spaCy's lemmatizer behaves differently depending on the part of speech. In particular, for nouns, the \"-ing\" form is considered to be the lemma already, and is not changed.\nHere's an example that illustrates the difference:\nimport spacy\n\nnlp = spacy.load(\"en_core_web_sm\")\n\ntext = \"While consulting, I so... | [
2,
2
] | [] | [] | [
"nlp",
"python",
"spacy"
] | stackoverflow_0074175424_nlp_python_spacy.txt |
Q:
how to filter out certain parts of page when web scraping
I am new to web scraping, and am trying to extract only the 100 fun facts from the following webpage:
https://holypython.com/100-python-tips-tricks/
However, when using the following code, filler information such as various menus, etc are gathered.
from url... | how to filter out certain parts of page when web scraping | I am new to web scraping, and am trying to extract only the 100 fun facts from the following webpage:
https://holypython.com/100-python-tips-tricks/
However, when using the following code, filler information such as various menus, etc are gathered.
from urllib.request import urlopen
from bs4 import BeautifulSoup
url =... | [
"You were pretty close, here is a solution that exploits the CSS class of the numbered sections to extract the data you are looking for.\nJust to briefly explain, if you open up your browser and go to the inspector, you will notice that each numbered section is an h3 element with the classes elementor-heading-title... | [
0
] | [] | [] | [
"python",
"screen_scraping",
"text_processing",
"web_scraping"
] | stackoverflow_0074176186_python_screen_scraping_text_processing_web_scraping.txt |
Q:
While loop: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
I've been reading about Pandas and trying to write some simple snippets. I've seen many people asking about the ValueError raised by Pandas but can't figure out how to accomplish the following: I h... | While loop: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() | I've been reading about Pandas and trying to write some simple snippets. I've seen many people asking about the ValueError raised by Pandas but can't figure out how to accomplish the following: I have a simple dataframe:
Driver_Name Month/Year Km_driven Salaray
0 Ivaylo_Ivanov Jan/21 2168 3208.64
1 Ivaylo_... | [
"The while keyword expects a bool expression, not an array (series) of them. If you want to iterate over such series until you find a False, you could easily accomplish that with a simple for loop, or, as the Backtrace message suggests, using the member functions all, any, etc.\n",
"You can do the following if yo... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074176597_pandas_python.txt |
Q:
Retrieve keras model fit history afer execution interrupt
In a jupyter notebook, I'm doing a training in keras with a line similar to
history = model.fit(....., epoch=100)
When I see that var_loss converge I break manually the execution, and obviously history is not returned.
Is there a way to retrieve it? A memb... | Retrieve keras model fit history afer execution interrupt | In a jupyter notebook, I'm doing a training in keras with a line similar to
history = model.fit(....., epoch=100)
When I see that var_loss converge I break manually the execution, and obviously history is not returned.
Is there a way to retrieve it? A member of model, or method, or a way to get the history object or i... | [
"@Mquinteiro Try using a callback: https://keras.io/callbacks/. You could set the callback to terminate when the model is no longer improving (keras.callbacks.EarlyStopping) and then access the best model (save_best_only = True), or you could have the callback save checkpoints after each epoch (keras.callbacks.Mode... | [
2,
0
] | [] | [] | [
"keras",
"python"
] | stackoverflow_0052223481_keras_python.txt |
Q:
TypeError: listdir() takes exactly 1 argument (0 given)
when I execute this in my win10 I get this error.
But when I am using:
dirs = os.listdir(path)
for file in dirs:
print(file)
I can see all the files in dir, I need help!
error: Raw_Files = os.listdir()
TypeError: listdir() takes exactly 1 argument (0 give... | TypeError: listdir() takes exactly 1 argument (0 given) | when I execute this in my win10 I get this error.
But when I am using:
dirs = os.listdir(path)
for file in dirs:
print(file)
I can see all the files in dir, I need help!
error: Raw_Files = os.listdir()
TypeError: listdir() takes exactly 1 argument (0 given)
def ransomeencrypt(file_name):
Lock = Fernet (key)
... | [
"From the documentation of os.listdir, it reads:\n\nChanged in version 3.2: The path parameter became optional.\n\nSince the TypeError: listdir() takes exactly 1 argument (0 given) error you're getting suggests that the parameter is not optional, you're probably running an old version of Python. Upgrading it should... | [
1,
0
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0074176777_python_python_2.7.txt |
Q:
Run out of memory issue in Gekko python
Now, I'm trying to solve the optimization problem as above and I made it in a code as belows.
However for large N (such as 300), the code failed to work because of run out of the memory.
So, I tried m = GEKKO(remote=True) instead of m = GEKKO(remote=False), but it was not do... | Run out of memory issue in Gekko python |
Now, I'm trying to solve the optimization problem as above and I made it in a code as belows.
However for large N (such as 300), the code failed to work because of run out of the memory.
So, I tried m = GEKKO(remote=True) instead of m = GEKKO(remote=False), but it was not done even after 10-12 hours.
I'm now finding a... | [
"The multiple m.min3() expressions lead to many additional variables. Try defining it once and substituting the value m3 into the objective expression.\nm3 = [[m.min3(demand[t,s],theta[s]) for t in range(T)] for s in range(N)]\n\nobj = m.sum([sum([((1/(1+r))**(t+1))*((P_CO*m3[s][t]) \\\n + (beta_CO2*P_CO... | [
1
] | [] | [] | [
"gekko",
"optimization",
"python"
] | stackoverflow_0074172128_gekko_optimization_python.txt |
Q:
How to get all tuned parameters and their associated train and validation scores?
I need to report all tuned hyperparameters in conjunction with their related performance score on the train and validation set. I do the following
from sklearn.neural_network import MLPRegressor
from sklearn.datasets import make_regr... | How to get all tuned parameters and their associated train and validation scores? | I need to report all tuned hyperparameters in conjunction with their related performance score on the train and validation set. I do the following
from sklearn.neural_network import MLPRegressor
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.metrics import... | [
"from sklearn.neural_network import MLPRegressor\nfrom sklearn.datasets import make_regression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import StandardScaler\nX, y = make_regression(n_samples=200, random_state=1)\nX_train, X_te... | [
-1
] | [] | [] | [
"gridsearchcv",
"hyperparameters",
"python",
"scikit_learn"
] | stackoverflow_0074176152_gridsearchcv_hyperparameters_python_scikit_learn.txt |
Q:
Which Python condition that check "file A or B or both exist"
May I ask which condition I should use to check the files A or B or both exist then execute the expression A or B or Both?
if or while or try...
Thanks
A:
Try break it down to one path at a time e.g into two functions that does something if A exists ... | Which Python condition that check "file A or B or both exist" | May I ask which condition I should use to check the files A or B or both exist then execute the expression A or B or Both?
if or while or try...
Thanks
| [
"Try break it down to one path at a time e.g into two functions that does something if A exists and something if B exists. Then it is fairly easy to do them both if A and B exists.\nIf you want to get assistance with some code-specific issues please write what you have tried, why it didn't work (i.e what happend th... | [
3,
1,
1,
0
] | [] | [] | [
"conditional_statements",
"python",
"python_3.x"
] | stackoverflow_0074176847_conditional_statements_python_python_3.x.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.