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:
Combine two lists into one multidimensional list
I would like to merge two lists into one 2d list.
list1=["Peter", "Mark", "John"]
list2=[1,2,3]
into
list3=[["Peter",1],["Mark",2],["John",3]]
A:
list3 = [list(a) for a in zip(list1, list2)]
A:
An alternative:
>>> map(list,zip(list1,list2))
[['Peter', 1], ['Mar... | Combine two lists into one multidimensional list | I would like to merge two lists into one 2d list.
list1=["Peter", "Mark", "John"]
list2=[1,2,3]
into
list3=[["Peter",1],["Mark",2],["John",3]]
| [
"list3 = [list(a) for a in zip(list1, list2)]\n\n",
"An alternative:\n>>> map(list,zip(list1,list2))\n[['Peter', 1], ['Mark', 2], ['John', 3]]\n\nor in python3:\n>>> list(map(list,zip(list1,list2)))\n[['Peter', 1], ['Mark', 2], ['John', 3]]\n\n(you can omit the outer list()-cast in most circumstances, though)\n",... | [
27,
3,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0012624623_list_python.txt |
Q:
How can i make some points of different color in last frame of plotly.graph_objects
fig = go.Figure()
f = []
hours = range(0, 60)
pts = [rd.randrange(11, 100, 13) for i in range(1, 61)]
for i in range(1, 61):
f.append(go.Frame(data=[go.Scatter(x=list(hours[1:61]), y=list(pts[:i]), name="PRB
U... | How can i make some points of different color in last frame of plotly.graph_objects | fig = go.Figure()
f = []
hours = range(0, 60)
pts = [rd.randrange(11, 100, 13) for i in range(1, 61)]
for i in range(1, 61):
f.append(go.Frame(data=[go.Scatter(x=list(hours[1:61]), y=list(pts[:i]), name="PRB
Usage",line=dict(color="#1E90FF"),marker=dict(size=10,line=dict(width=3,color="yellow")))]... | [
"Your question only has a partial code, so I have made up the deficiency with my guess. If you want to add special processing to the last graph of the animation, create a new final frame and replace the last frame in the list of already existing frames. The color condition specifies a list of colors above and beyon... | [
0
] | [] | [] | [
"plotly",
"plotly.graph_objects",
"python"
] | stackoverflow_0074559806_plotly_plotly.graph_objects_python.txt |
Q:
Compare an iteration with the next and next next iteration
I have a dataframe with three columns (Site, EventTime, EndTime), and I need to compare the first item on Site with the next and the next value. If those three are different, I need to copy the endTime of the last one into the first one.
I tried this:
i =... | Compare an iteration with the next and next next iteration | I have a dataframe with three columns (Site, EventTime, EndTime), and I need to compare the first item on Site with the next and the next value. If those three are different, I need to copy the endTime of the last one into the first one.
I tried this:
i = 0
while i <= len(df):
if df['Site'][i] != df['Site'][i+1]... | [
"Here I am assuming you need to set the new time on all last record of site a, with the next first record of site c EndTime.\nFollowinglly, I have used lambda function to pass through line by line, and check condintion, where give true if current site and next row site is different and current site is a, if yes the... | [
0
] | [] | [] | [
"iteration",
"python"
] | stackoverflow_0074433680_iteration_python.txt |
Q:
'NOT NULL constraint failed' after adding to models.py
I'm using userena and after adding the following line to my models.py
zipcode = models.IntegerField(_('zipcode'),
max_length=5)
I get the following error after I hit the submit button on th signup form:
IntegrityError at /ac... | 'NOT NULL constraint failed' after adding to models.py | I'm using userena and after adding the following line to my models.py
zipcode = models.IntegerField(_('zipcode'),
max_length=5)
I get the following error after I hit the submit button on th signup form:
IntegrityError at /accounts/signup/
NOT NULL constraint failed: accounts_myprofil... | [
"You must create a migration, where you will specify default value for a new field, since you don't want it to be null. If null is not required, simply add null=True and create and run migration.\n",
"coldmind's answer is correct but lacks details.\nThe NOT NULL constraint failed occurs when something tries to se... | [
98,
17,
9,
0
] | [
"Since you added a new property to the model, you must first delete the database. Then manage.py migrations then manage.py migrate.\n"
] | [
-5
] | [
"django",
"django_migrations",
"django_models",
"python"
] | stackoverflow_0025964312_django_django_migrations_django_models_python.txt |
Q:
check frequency of keyword in df in a text
I have a given text string:
text = """Alice has two apples and bananas. Apples are very healty."""
and a dataframe:
word
apples
bananas
company
I would like to add a column "frequency" which will count occurrences of each word in column "word" in the text.
So the out... | check frequency of keyword in df in a text | I have a given text string:
text = """Alice has two apples and bananas. Apples are very healty."""
and a dataframe:
word
apples
bananas
company
I would like to add a column "frequency" which will count occurrences of each word in column "word" in the text.
So the output should be as below:
word
freq... | [
"\nConvert the text to lowercase and then use regex to convert it to a list of words. You might check out this page for learning purposes.\nLoop through each row in the dataset and use lambda function to count the specific value in the previously created list.\n\n# Import and create the data\nimport pandas as pd\ni... | [
1,
1
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074560829_dataframe_python.txt |
Q:
Split numpy array into chunks
I have an array x of 30 samples, and I wish to separate it out into chunks of 8 samples each in 2 different ways.
First, I want to separate it avoiding any overlap so that I end up with 3 arrays of length 8 and the final array will be only 6 (due to some samples being missing).
Second... | Split numpy array into chunks | I have an array x of 30 samples, and I wish to separate it out into chunks of 8 samples each in 2 different ways.
First, I want to separate it avoiding any overlap so that I end up with 3 arrays of length 8 and the final array will be only 6 (due to some samples being missing).
Secondly, I want to separate it so that t... | [
"import numpy as np\n\nx = np.array([1 ,1, 2 ,1 ,1 ,2 ,1, 0 ,3, 1, 2 ,2, 1, 2, 1, 1,50 ,1 ,1, 1, 1, 4, 1, 11, 15, 0, 0, 1, 1,0])\n\ndef split_reminder(x, chunk_size, axis=0):\n indices = np.arange(chunk_size, x.shape[axis], chunk_size)\n return np.array_split(x, indices, axis)\n\nsplit_reminder(x, 8)\n\nCheck... | [
1,
0,
0,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074560670_arrays_numpy_python.txt |
Q:
Python Tkinter, Display Live Data
I want to display live data in a GUI, in tkinter. The data I am getting contains a list of two integers [current, voltage]. I am getting new data every second.
I managed to create a GUI, now I want to know how to display data in GUI Label widgets (python tkinter) and update label... | Python Tkinter, Display Live Data | I want to display live data in a GUI, in tkinter. The data I am getting contains a list of two integers [current, voltage]. I am getting new data every second.
I managed to create a GUI, now I want to know how to display data in GUI Label widgets (python tkinter) and update labels dynamically. Any suggestions please
H... | [
"If you want to graph your live data and want to avoid using other libraries to do that for you, you might find the following to be an enlightening starting point for creating your own graphs. The sample draws a full circle of values when evaluating the math.sin function that comes in the standard library. The code... | [
4,
2,
1,
0
] | [] | [] | [
"python",
"python_3.x",
"tkinter",
"user_interface"
] | stackoverflow_0056275043_python_python_3.x_tkinter_user_interface.txt |
Q:
How to make voice detection in python faster?
I have some voice detection code and it works! but, it runs really slowly. Can I do anything to make it faster?
import speech_recognition
import pyttsx3
recognizer = speech_recognition.Recognizer()
while True:
try:
with speech_recognition.Microphone() as ... | How to make voice detection in python faster? | I have some voice detection code and it works! but, it runs really slowly. Can I do anything to make it faster?
import speech_recognition
import pyttsx3
recognizer = speech_recognition.Recognizer()
while True:
try:
with speech_recognition.Microphone() as mic:
recognizer.adjust_for_ambient_nois... | [
"Try creating mic once instead of each iteration:\nimport speech_recognition\nimport pyttsx3\n\nrecognizer = speech_recognition.Recognizer()\n\n\nwith speech_recognition.Microphone() as mic:\n while True:\n try:\n recognizer.adjust_for_ambient_noise(mic, duration=0.2)\n audio = recog... | [
1
] | [] | [] | [
"python",
"pyttsx3",
"voice_recognition"
] | stackoverflow_0074560606_python_pyttsx3_voice_recognition.txt |
Q:
How to send request to a public web service with Python?
i need a guide to establish a connection to a public web service, send request to it and get response back. for example this web service:
http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL
i've tried to test this API with So... | How to send request to a public web service with Python? | i need a guide to establish a connection to a public web service, send request to it and get response back. for example this web service:
http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL
i've tried to test this API with SoapUI application. this API has a bunch of methods such as send... | [
"I'd recommend checking out this library:\nhttps://requests.readthedocs.io/en/latest/\nYou can send HTTP requests to URL endpoints, parse out data, etc. Hope this helps!\n",
"I have successfully used suds and SOAPpy in the past. I see people recommend Zeep nowadays but I haven't used it.\n"
] | [
1,
1
] | [] | [] | [
"python",
"soap",
"soapui",
"web_services",
"xml"
] | stackoverflow_0074549589_python_soap_soapui_web_services_xml.txt |
Q:
plt.show() create graph 2 times
[Extra graph]
https://i.stack.imgur.com/3euVn.png[1]
Plt.show() is creating graph 3 times while I am using plt.show() only 2 time 1 in each script.1 graph close immediately like after 1 sec
The code is as:
from ScriptsTogather import new
fig, axes = plt.subplots(2, 1, figsize=(4, 4)... | plt.show() create graph 2 times | [Extra graph]
https://i.stack.imgur.com/3euVn.png[1]
Plt.show() is creating graph 3 times while I am using plt.show() only 2 time 1 in each script.1 graph close immediately like after 1 sec
The code is as:
from ScriptsTogather import new
fig, axes = plt.subplots(2, 1, figsize=(4, 4), num='pyplot')
plt.show(block=False)... | [
"I managed to solve it. I was calling plt.show() outside the function that was making an empty graph and then for canvass.draw it was making another graph.\n"
] | [
1
] | [] | [] | [
"charts",
"matplotlib",
"python"
] | stackoverflow_0074560379_charts_matplotlib_python.txt |
Q:
How to label a line in matplotlib (python)?
I followed the documentation but still failed to label a line.
plt.plot([min(np.array(positions)[:,0]), max(np.array(positions)[:,0])], [0,0], color='k', label='East') # West-East
plt.plot([0,0], [min(np.array(positions)[:,1]), max(np.array(positions)[:,1])], color='k', ... | How to label a line in matplotlib (python)? | I followed the documentation but still failed to label a line.
plt.plot([min(np.array(positions)[:,0]), max(np.array(positions)[:,0])], [0,0], color='k', label='East') # West-East
plt.plot([0,0], [min(np.array(positions)[:,1]), max(np.array(positions)[:,1])], color='k', label='North') # South-North
In the code snippet... | [
"The argument label is used to set the string that will be shown in the legend. For example consider the following snippet:\n import matplotlib.pyplot as plt\n plt.plot([1,2,3],'r-',label='Sample Label Red')\n plt.plot([0.5,2,3.5],'b-',label='Sample Label Blue')\n plt.legend()\n plt.show()\n\nThis will plot 2 ... | [
48,
4,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0017941083_matplotlib_python.txt |
Q:
How to parse this xml file which have two root elements?
<objects>
<object>
<record>
<net_amount>3657.82</net_amount>
<order_number>47004603</order_number>
<invoice_source>Email</invoice_source>
<invoice_capture_date>2022-11-13</invoice_capture_date>
... | How to parse this xml file which have two root elements? | <objects>
<object>
<record>
<net_amount>3657.82</net_amount>
<order_number>47004603</order_number>
<invoice_source>Email</invoice_source>
<invoice_capture_date>2022-11-13</invoice_capture_date>
<document_type>INVOICE</document_type>
<data_... | [
"You've done the hard part already, all you have to do is to wrap your code in a loop that will go through the object tags.\nfor file in files:\n tree = ET.parse(file)\n root = tree.getroot() #This is the outer \"objects\" tags\n for obj in root.findall(\"object\"): #Loop over all object in it\n for... | [
1
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0074561227_python_xml.txt |
Q:
Is this always necessary to use r before path declaration in python
I have often seen syntax like this in python code.
import os
os.chdir(r'C:\Users\test\Desktop')
I was wondering why would I need to give r before the path, I believe it has something to do with '\' in the path , Is there any other way to ... | Is this always necessary to use r before path declaration in python | I have often seen syntax like this in python code.
import os
os.chdir(r'C:\Users\test\Desktop')
I was wondering why would I need to give r before the path, I believe it has something to do with '\' in the path , Is there any other way to give path instead of using r''
| [
"It makes sure that the backslash doesn't escape the characters. It's same as\nos.chdir('C:\\\\Users\\\\test\\\\Desktop')\n\n",
"'r' before string literal make Python parse it as a \"raw\" string, without escaping.\nIf you want not to use 'r' before string literal, but specify path with single slashes, you can us... | [
2,
1,
0,
0,
0
] | [] | [] | [
"path",
"python"
] | stackoverflow_0047010506_path_python.txt |
Q:
Correct procedure to connect to a network database
I am making an application with qooxdoo, and I need to connect to a sqlite database. I am not able to.
A few years ago I made another application and I was able to connect, in that case it was mysql, perfectly.
I have a server networking using python and bottle, s... | Correct procedure to connect to a network database | I am making an application with qooxdoo, and I need to connect to a sqlite database. I am not able to.
A few years ago I made another application and I was able to connect, in that case it was mysql, perfectly.
I have a server networking using python and bottle, say at address.es:8080/idCars and I can request sql comma... | [
"There is problem with CORS. I think you have a response from the server.\nThe simple client which works on port 8080:\nconst req = new qx.io.request.Xhr(\"http://localhost:8081/getData\");\nreq.addListener(\"success\", function(e) {\n const req = e.getTarget();\n console.log(req.getResponse());\n}, this);\nreq.s... | [
0
] | [] | [] | [
"bottle",
"json",
"python",
"qooxdoo"
] | stackoverflow_0074557774_bottle_json_python_qooxdoo.txt |
Q:
dataframe group, sum and concatenate
I have a dataframe dfsorted :
dfsorted = df.sort_values(["sku"], ascending=[True])
print(dfsorted.head())
id
sku
bill
qty_left
186
01-04
50469
0
16
01-20
50262
15
267
01-20
50460
1
18
01-20
50262
5
17
01-20
50262
5
How can I group / aggregate the dfsorted into this desi... | dataframe group, sum and concatenate | I have a dataframe dfsorted :
dfsorted = df.sort_values(["sku"], ascending=[True])
print(dfsorted.head())
id
sku
bill
qty_left
186
01-04
50469
0
16
01-20
50262
15
267
01-20
50460
1
18
01-20
50262
5
17
01-20
50262
5
How can I group / aggregate the dfsorted into this desired result:
sku
bill
qty... | [
"Use agg, where you can apply both custom (lambda) functions as standard (such as sum) functions:\ndf.groupby('sku').agg({'bill': lambda x: set(x), 'qty_left':'sum'})\n\nset makes sure they are unique values, using list makes them just concatenated.\nresult:\n bill qty_left\nsku \n01-04 {504... | [
2,
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074560979_dataframe_group_by_pandas_python.txt |
Q:
Delete rows with a certain condition in pandas
I have a data frame and I want to delete rows that in the column "Phrase", pattern "___" exists.
Index
PHRASE
Label
0
proposed by the president of the
1
1
Living ___
1
2
"Murder, ___ Wrote"
0
But Imagin that the data fram has 2,000,000 enteries
import re
df_cle... | Delete rows with a certain condition in pandas | I have a data frame and I want to delete rows that in the column "Phrase", pattern "___" exists.
Index
PHRASE
Label
0
proposed by the president of the
1
1
Living ___
1
2
"Murder, ___ Wrote"
0
But Imagin that the data fram has 2,000,000 enteries
import re
df_clean = pd.DataFrame()
z = 0
y = 0
for i in ... | [
"df[~df['phrase'].str.contains('___')]\n\nWhere the ~ symbol negates the operation.\n"
] | [
0
] | [] | [] | [
"nlp",
"pandas",
"python"
] | stackoverflow_0074561241_nlp_pandas_python.txt |
Q:
Best way to pass multiple conditions in pandas between dataframes
I have a model I am building and in the test version I am stuck on how to pass multiple conditions to generate a new dataframe from existing ones. I currently have an inefficient function that loops through my dataframes one for each period (1-5) an... | Best way to pass multiple conditions in pandas between dataframes | I have a model I am building and in the test version I am stuck on how to pass multiple conditions to generate a new dataframe from existing ones. I currently have an inefficient function that loops through my dataframes one for each period (1-5) and one for each date in the dataset.
I have created a subset of the data... | [
"Here is my approach to your task:\nThe function choices will calculate the new values of the columns 1-5 with its conditions.\nThe function each_date will calculate that new dataframe for each date where Type == 'Fossil'\ncols = list('12345')\n# ['1', '2', '3', '4', '5'] # predefine all columns you need here \n\nd... | [
2
] | [] | [] | [
"dataframe",
"excel",
"numpy",
"pandas",
"python"
] | stackoverflow_0074547501_dataframe_excel_numpy_pandas_python.txt |
Q:
Merge N lists of tuples of counts
Suppose I have N sorted lists of tuples ("val", "count_of_val") (sorted lexigoraphically by the character "val"). I want to merge all lists and get the total counts, e.g.:
vec1: [("a", 10), ("b", 5)]
vec2: [("a" , 7), ("b", 10), ("c", 2)]
vec3: [("d", 2)]
vec4: []
...
Now I want ... | Merge N lists of tuples of counts | Suppose I have N sorted lists of tuples ("val", "count_of_val") (sorted lexigoraphically by the character "val"). I want to merge all lists and get the total counts, e.g.:
vec1: [("a", 10), ("b", 5)]
vec2: [("a" , 7), ("b", 10), ("c", 2)]
vec3: [("d", 2)]
vec4: []
...
Now I want to merge all of them in 1 big list (not... | [
"accumulate values by key in a collections.Counter.\nimport collections\n\nvec1= [(\"a\", 10), (\"b\", 5)]\nvec2= [(\"a\" , 7), (\"b\", 10), (\"c\", 2)]\nvec3= [(\"d\", 2)]\n\nc = collections.Counter()\nfor vct in (vec1,vec2,vec3):\n for k,v in vct:\n c[k] += v\n\nprint(c)\n\nor use update which adds inst... | [
3
] | [] | [] | [
"algorithm",
"list",
"merge",
"python",
"tuples"
] | stackoverflow_0074561365_algorithm_list_merge_python_tuples.txt |
Q:
How to stop ruamel.yaml from sorting dict keys?
I am on Python 3.11 and ruamel.yaml==0.17.21
How do I stop ruamel.yaml from sorting the dict keys when doing a dump()?
If I print the dict outright, it shows the keys are ordered as I added them.
But when I dump to file, the keys become alphabetically sorted.
Edit: ... | How to stop ruamel.yaml from sorting dict keys? | I am on Python 3.11 and ruamel.yaml==0.17.21
How do I stop ruamel.yaml from sorting the dict keys when doing a dump()?
If I print the dict outright, it shows the keys are ordered as I added them.
But when I dump to file, the keys become alphabetically sorted.
Edit: Minimal working code:
import sys
from typing import N... | [
"Ohhh I'm supposed to inherit from RoundTripRepresenter instead of Representer. Okay.\n"
] | [
0
] | [] | [] | [
"python",
"ruamel.yaml"
] | stackoverflow_0074561293_python_ruamel.yaml.txt |
Q:
How to use GridSearchCV output for a scikit prediction?
In the following code:
# Load dataset
iris = datasets.load_iris()
X, y = iris.data, iris.target
rf_feature_imp = RandomForestClassifier(100)
feat_selection = SelectFromModel(rf_feature_imp, threshold=0.5)
clf = RandomForestClassifier(5000)
model = Pipeline... | How to use GridSearchCV output for a scikit prediction? | In the following code:
# Load dataset
iris = datasets.load_iris()
X, y = iris.data, iris.target
rf_feature_imp = RandomForestClassifier(100)
feat_selection = SelectFromModel(rf_feature_imp, threshold=0.5)
clf = RandomForestClassifier(5000)
model = Pipeline([
('fs', feat_selection),
('clf', clf),... | [
"gs.predict(X_test) is equivalent to gs.best_estimator_.predict(X_test). Using either, X_test will be passed through your entire pipeline and it will return the predictions.\ngs.best_estimator_.named_steps['clf'].predict(), however is only the last phase of the pipeline. To use it, the feature selection step must a... | [
33,
0
] | [] | [] | [
"grid_search",
"python",
"scikit_learn"
] | stackoverflow_0035388647_grid_search_python_scikit_learn.txt |
Q:
Get all the rows of a table along with matching rows of another table in django ORM using select_related
I have 2 models
Model 1
class Model1(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
type = models.CharField(max_length=255)
det... | Get all the rows of a table along with matching rows of another table in django ORM using select_related | I have 2 models
Model 1
class Model1(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
type = models.CharField(max_length=255)
details = models.TextField(max_length=1000)
price = models.FloatField()
Model 2
class Model2(models.Mode... | [
"For select_related(), you want to select on the field name, not the related model's name. But all this does is that it adds a join, pulls all rows resulting from that join, and then your python representations have this relation cached (no more queries when accessed).\nYou also need to use __ to traverse relations... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"orm",
"postgresql",
"python"
] | stackoverflow_0074561030_django_django_rest_framework_orm_postgresql_python.txt |
Q:
Is it possible in SQLAlchemy to define isolation level SNAPSHOT for PostgreSQL?
My web application uses SQLAlchemy with a PostgreSQL database. Now there is a need to use the equivalent of Microsoft SQL Server's SNAPSHOT transaction isolation level, but I did not find a solution in the SQLAlchemy v1.4.44 documentat... | Is it possible in SQLAlchemy to define isolation level SNAPSHOT for PostgreSQL? | My web application uses SQLAlchemy with a PostgreSQL database. Now there is a need to use the equivalent of Microsoft SQL Server's SNAPSHOT transaction isolation level, but I did not find a solution in the SQLAlchemy v1.4.44 documentation.
| [
"Microsoft SQL Server's “snapshot isolation” is documented as\n\nThe term \"snapshot\" reflects the fact that all queries in the transaction see the same version, or snapshot, of the database, based on the state of the database at the moment in time when the transaction begins. No locks are acquired on the underlyi... | [
1
] | [] | [] | [
"postgresql",
"python",
"python_3.x",
"sql_server",
"sqlalchemy"
] | stackoverflow_0074559100_postgresql_python_python_3.x_sql_server_sqlalchemy.txt |
Q:
DRF APITestCase force_authenticate make request.user return tuple instead of User object
I have a custom authentication class following the docs
class ExampleAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
username = request.META.get('HTTP_X_USERNAME')
if not... | DRF APITestCase force_authenticate make request.user return tuple instead of User object | I have a custom authentication class following the docs
class ExampleAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
username = request.META.get('HTTP_X_USERNAME')
if not username:
return None
try:
user = User.objects.get(username=... | [
"The problem is not force_authenticate but get_or_create method. It returns tuple. First element of the tuple is object and second one is boolean indicating if object was created or not. To fix change your code in setUp method to this:\ndef setUp(self):\n # self.factory = APIRequestFactory()\n self.user, ... | [
1
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"testing"
] | stackoverflow_0074559404_django_django_rest_framework_python_testing.txt |
Q:
Auto reloading flask server on Docker
I want my flask server to detect changes in code and reload automatically.
I'm running this on docker container.
Whenever I change something, I have to build and up again the container. I have no idea where's wrong. This is my first time using flask.
Here's my tree
├── docker-... | Auto reloading flask server on Docker | I want my flask server to detect changes in code and reload automatically.
I'm running this on docker container.
Whenever I change something, I have to build and up again the container. I have no idea where's wrong. This is my first time using flask.
Here's my tree
├── docker-compose.yml
└── web
├── Dockerfile
... | [
"Flask supports code reload when in debug mode as you've already done. The problem is that the application is running on a container and this isolates it from the real source code you are developing. Anyway, you can share the source between the running container and the host with volumes on your docker-compose.yaml... | [
35,
21,
6,
1,
0
] | [] | [] | [
"docker",
"flask",
"python"
] | stackoverflow_0044342741_docker_flask_python.txt |
Q:
Extract first sequence of strings in pandas column
I have a column in a DF as below
| Column A |
| ab, bce, bc |
| bc, abcd, ab |
| ab, cd, abc |
and i want to create a new column that only takes the first sequence, as showed below
| Column A | Column B |
| ab, bce, bc | ab |
| bc, ... | Extract first sequence of strings in pandas column | I have a column in a DF as below
| Column A |
| ab, bce, bc |
| bc, abcd, ab |
| ab, cd, abc |
and i want to create a new column that only takes the first sequence, as showed below
| Column A | Column B |
| ab, bce, bc | ab |
| bc, abcd, ab | bc |
| ab, cd, abc | ab |
I... | [
"I guess the items in columnA are strings like e.g. 'ab, bce, bc', so just use split ;).\ndf.loc[:, 'ColumnB'] = df.ColumnA.map(lambda x: x.split(',')[0])\n\n",
"You can alos try vectorised str method split and use integer indexing on the list to get the first element:\ndf['Column B'] = df['Column A'].str.split('... | [
2,
1,
1,
1,
0
] | [] | [] | [
"columnsorting",
"pandas",
"python"
] | stackoverflow_0074560547_columnsorting_pandas_python.txt |
Q:
Trying to parse the div, but I get an error
import requests
from bs4 import BeautifulSoup
from texttable import Texttable
url = "https://realpython.github.io/fake-jobs/"
site = requests.get(url) #send a request to the site
table = Texttable() #create a table
table.set_chars(['-', '|', '+', '='])
table.header(['T... | Trying to parse the div, but I get an error | import requests
from bs4 import BeautifulSoup
from texttable import Texttable
url = "https://realpython.github.io/fake-jobs/"
site = requests.get(url) #send a request to the site
table = Texttable() #create a table
table.set_chars(['-', '|', '+', '='])
table.header(['Titel','Company','Location'])
table.set_cols_dtype... | [
"Try to select your elements more specific - Issue here is that you select the first link and not that one that is leading to the details:\nitem_element = job_element.select_one(\"a.card-footer-item[href*='fake-jobs/jobs']\")\n\nor\nitem_element = job_element.find_all(\"a\", class_=\"card-footer-item\")[-1]\n\nYou ... | [
0
] | [] | [] | [
"beautifulsoup",
"parsing",
"python",
"python_3.x",
"web_scraping"
] | stackoverflow_0074560676_beautifulsoup_parsing_python_python_3.x_web_scraping.txt |
Q:
How to install nvidia apex on Google Colab
what I did is follow the instruction on the official github site
!git clone https://github.com/NVIDIA/apex
!cd apex
!pip install -v --no-cache-dir ./
it gives me the error:
ERROR: Directory './' is not installable. Neither 'setup.py' nor 'pyproject.toml' found.
Exception... | How to install nvidia apex on Google Colab | what I did is follow the instruction on the official github site
!git clone https://github.com/NVIDIA/apex
!cd apex
!pip install -v --no-cache-dir ./
it gives me the error:
ERROR: Directory './' is not installable. Neither 'setup.py' nor 'pyproject.toml' found.
Exception information:
Traceback (most recent call last):... | [
"Worked for me after adding CUDA_HOME enviroment variable:\n%%writefile setup.sh\n\nexport CUDA_HOME=/usr/local/cuda-10.1\ngit clone https://github.com/NVIDIA/apex\npip install -v --no-cache-dir --global-option=\"--cpp_ext\" --global-option=\"--cuda_ext\" ./apex\n\n!sh setup.sh\n\n",
"(wanted to just add a commen... | [
18,
17,
10,
6,
2,
1,
0,
0
] | [] | [] | [
"google_colaboratory",
"gpu",
"nvidia",
"python",
"pytorch"
] | stackoverflow_0057284345_google_colaboratory_gpu_nvidia_python_pytorch.txt |
Q:
Allow only one layer at a time in Folium LayerControl
I want to make an "interactive" map with multiple layers using geopandas explore() function and folium. I was able to generate exactly what I aim for, with one exception: the constraint that only one layer would be allowed at a time. In other words, I want that... | Allow only one layer at a time in Folium LayerControl | I want to make an "interactive" map with multiple layers using geopandas explore() function and folium. I was able to generate exactly what I aim for, with one exception: the constraint that only one layer would be allowed at a time. In other words, I want that if someone click on the layer "Adaptation climat ☀❄️", the... | [
"It seems to be possible that you differ that behaviour with the overlay-status of the layers. Now we need to find a possibility to forward overlay=False to your map as you include/create the map with geopandas (like described in your referenced answer https://stackoverflow.com/a/63189269/13843906 ). Perhaps try pa... | [
2
] | [] | [] | [
"folium",
"geopandas",
"python"
] | stackoverflow_0074561214_folium_geopandas_python.txt |
Q:
Python OSError: [Errno 22] Invalid argument when use pd.read_csv with two csv files
I am new here and I need a help.
I got a trouble with OSError: [Errno 22] Invalid argument when I tried to use pd.read_csv with two csv files for dataset preprocess.
I created two dummy dataset as below:
test_1.csv:
DATE,permno,dat... | Python OSError: [Errno 22] Invalid argument when use pd.read_csv with two csv files | I am new here and I need a help.
I got a trouble with OSError: [Errno 22] Invalid argument when I tried to use pd.read_csv with two csv files for dataset preprocess.
I created two dummy dataset as below:
test_1.csv:
DATE,permno,datadate,gvkey, ....... (and a lot of features)
19260130,10006,19260130,3934, ........
19260... | [
"\nInvalid argument: 'C:\\Users\\steve\\Desktop\\Data\\test_1.csvC:\\Users\\steve\\Desktop\\Data\\test_2.csv'\n\nYou are trying to read the CSV of an invalid path. You cannot read two csv files at once.\nWhen you call this...\npd.read_csv(DATA_DIR + r'C:\\Users\\steve\\Desktop\\Data\\test_2.csv', index_col=0, parse... | [
0,
0,
0
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python"
] | stackoverflow_0069403282_csv_dataframe_pandas_python.txt |
Q:
How Can I Solve This No Duplicated 2 Column Calculation?
Hello StackOverflow People! I have some trouble here, I do some research but I still can't make it. I have two columns that are substracted from a Dataset, the columns are "# Externo" and "Nro Envio ML".
I want that the result of the code gives me only the n... | How Can I Solve This No Duplicated 2 Column Calculation? | Hello StackOverflow People! I have some trouble here, I do some research but I still can't make it. I have two columns that are substracted from a Dataset, the columns are "# Externo" and "Nro Envio ML".
I want that the result of the code gives me only the numbers that exist in "# Externo" but no in "Nro Envio ML"
For ... | [
"I would go outside of pandas and use the python built in set and compute the difference. Here is a simplified example:\nimport pandas as pd\n\ndf = pd.DataFrame({\n \"# Externo\": [3, 5, 4, 2, 1, 7, 8],\n \"Nro Envio ML\": [4, 9, 0, 2, 1, 3, 5]\n})\n\ndiff = set(df[\"# Externo\"]) - set(df[\"Nro Envio ML\"])... | [
2,
0
] | [] | [] | [
"dataframe",
"duplicates",
"numpy",
"pandas",
"python"
] | stackoverflow_0074560667_dataframe_duplicates_numpy_pandas_python.txt |
Q:
django how to get count for manytomany field
I have model for question:
class Question(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=120)
description = models.TextField()
answers = models.ManyToManyField('Answer',related_name='answer_name', blank=True)
post_d... | django how to get count for manytomany field | I have model for question:
class Question(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=120)
description = models.TextField()
answers = models.ManyToManyField('Answer',related_name='answer_name', blank=True)
post_date = models.DateTimeField(auto_now=True)
def __u... | [
"This worked:\n{{question.answer_set.count}}\n\nHappy..\n",
"You can do something like {{ question.answers.all.count }}, but if you are iterating over more than question it will cause a database query for every question. \nIf you want to annotate the whole queryset with the count for each question:\nfrom django.d... | [
17,
16,
5,
0
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0027149984_django_django_queryset_python.txt |
Q:
Installing fbprophet on colab
Hi when I try to intall fbprophet on google colab i get this error anyone knows how to fix it?
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/
Collecting fbprophet
Using cached fbprophet-0.7.1.tar.gz (64 kB)
Requirement already sati... | Installing fbprophet on colab | Hi when I try to intall fbprophet on google colab i get this error anyone knows how to fix it?
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/
Collecting fbprophet
Using cached fbprophet-0.7.1.tar.gz (64 kB)
Requirement already satisfied: Cython>=0.22 in /usr/local/l... | [
"You can try this currently i am working on fb-prophet in colab and i used this packages for me it is working smoothly -\nThis is older version\n!pip install pystan~=2.14\n!pip install fbprophet\n\nFor latest version just install prophet there is no need for installing pystan -\n!pip install prophet\n\nimport proph... | [
13,
0
] | [] | [] | [
"facebook_prophet",
"google_colaboratory",
"python"
] | stackoverflow_0073142498_facebook_prophet_google_colaboratory_python.txt |
Q:
from pymongo import MongoClient - Error: [AttributeError: module 'h11' has no attribute 'Event']
Hi I keep getting this error message, I reinstalled my ubuntu system to correct it but it didn't seem to work.
Code:
from pymongo import MongoClient
Only package installed is pymongo
I get the same error in both Anacon... | from pymongo import MongoClient - Error: [AttributeError: module 'h11' has no attribute 'Event'] | Hi I keep getting this error message, I reinstalled my ubuntu system to correct it but it didn't seem to work.
Code:
from pymongo import MongoClient
Only package installed is pymongo
I get the same error in both Anaconda by starting a new env and in my locally installed python.
Python version 3.8.10
Error message:
Anyo... | [
"Found a solution:\npip install --force-reinstall httpcore==0.15\nFixed the error\n"
] | [
1
] | [] | [] | [
"pymongo",
"python"
] | stackoverflow_0074561596_pymongo_python.txt |
Q:
Pandas: Adding a df column based on other column with multiple values map to the same new column value
I have a dataframe like this:
df1 = pd.DataFrame({'col1' : ['cat', 'cat', 'dog', 'green', 'blue']})
and I want a new column that gives the category, like this:
dfoutput = pd.DataFrame({'col1' : ['cat', 'cat', '... | Pandas: Adding a df column based on other column with multiple values map to the same new column value | I have a dataframe like this:
df1 = pd.DataFrame({'col1' : ['cat', 'cat', 'dog', 'green', 'blue']})
and I want a new column that gives the category, like this:
dfoutput = pd.DataFrame({'col1' : ['cat', 'cat', 'dog', 'green', 'blue'],
'col2' : ['animal', 'animal', 'animal', 'color', 'color']})... | [
"Build your dict then do map \nd={'dog':'ani','cat':'ani','green':'color','blue':'color'}\ndf1['col2']=df1.col1.map(d)\ndf1\n col1 col2\n0 cat ani\n1 cat ani\n2 dog ani\n3 green color\n4 blue color\n\n",
"Since multiple items may belong to a single category I suggest you start with a d... | [
6,
3,
0
] | [] | [] | [
"dictionary",
"pandas",
"python",
"series"
] | stackoverflow_0054031812_dictionary_pandas_python_series.txt |
Q:
Tkinter Calculator can you guys tell me how to fix the problem and let the answer show up
from tkinter import *
def tkinter_calculator():
window=Tk()
window.title("Calculator")
l1=Label(window,text="Welcome to Calculator")
l1.pack()
e1=Entry(window,width=10,bd=4)
e1.place(x=300,y=300)
l... | Tkinter Calculator can you guys tell me how to fix the problem and let the answer show up | from tkinter import *
def tkinter_calculator():
window=Tk()
window.title("Calculator")
l1=Label(window,text="Welcome to Calculator")
l1.pack()
e1=Entry(window,width=10,bd=4)
e1.place(x=300,y=300)
l2=Label(window,text="+")
l2.place(x=500,y=300)
e2=Entry(window,width=10,bd=4)
e2.pl... | [
"There are few issues in your code:\n\nyou can only see the label l1 because other widgets are put in the window using .place() which will not adjust the window size. You need to specify the initial size of the window in order to see those widgets.\ne1 and e2 are local variables inside tkinter_calculator(), so they... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074561179_python_tkinter.txt |
Q:
How to read parquet file using Pandas
I am trying to read a parquet file using Python 3.6.
import pandas as pd
df = pd.read_parquet('smalldata.parquet')
df.head()
However, this is generating an error that module pandas has no attribute read_parquet. What dependencies should I cater in order to solve this probl... | How to read parquet file using Pandas | I am trying to read a parquet file using Python 3.6.
import pandas as pd
df = pd.read_parquet('smalldata.parquet')
df.head()
However, this is generating an error that module pandas has no attribute read_parquet. What dependencies should I cater in order to solve this problem?
Edit 1:
I updated Pandas and this is... | [
"You will need to install the required packages:\npip install pandas pyarrow s3fs fastparquet\n\n",
"If you are trying to read Parquet files in Pandas, it may be that you don't have one of the engines installed for reading Parquet files, such as pyarrow or fastparquet. You would need to install those dependencies... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0055334346_pandas_python.txt |
Q:
Run python script oracle data integrator (ODI)
I am looking for help to be able to execute a python script on oracle data integrator (ODI)
I have not found any documentation for this process
I would appreciate if someone can help me with this process
I don't know where in ODI I could do this type of execution
A:
... | Run python script oracle data integrator (ODI) | I am looking for help to be able to execute a python script on oracle data integrator (ODI)
I have not found any documentation for this process
I would appreciate if someone can help me with this process
I don't know where in ODI I could do this type of execution
| [
"Essentially ODI doesn't support Python directly but there are a couple of things you can do. The things to consider are:\n\nwhere you need to run the code\nwhat you want the code to do\nhow integrated into ODI do you need it to be\n\nJython\nODI does support Jython which is a Java implementation of Python. This... | [
0
] | [] | [] | [
"oracle_data_integrator",
"python"
] | stackoverflow_0074539405_oracle_data_integrator_python.txt |
Q:
numpy's "linalg.eig()" and "linalg.eigh()" for the same hermitian matrix
This question was due to a misunderstanding. See the answer below.
numpy.linalg methods eig() and eigh() appear to return different eigenvectors for the same hermitian matrix. Here the code:
import numpy as np
H = [[0.6 , -1j, 0], [1j, 0.4, ... | numpy's "linalg.eig()" and "linalg.eigh()" for the same hermitian matrix | This question was due to a misunderstanding. See the answer below.
numpy.linalg methods eig() and eigh() appear to return different eigenvectors for the same hermitian matrix. Here the code:
import numpy as np
H = [[0.6 , -1j, 0], [1j, 0.4, 0], [0, 0, -1]]
evals, evects = np.linalg.eig(H)
print('\nOutput of the eig f... | [
"Posting this to help anyone who might have had the same kind of misunderstanding I had:\nThe eigenvectors are the columns of the resulting matrix for both functions. The fault was in the original code, which extracted rows from the eigenvector matrix instead of columns. The correct code is the following one.\nH = ... | [
0
] | [] | [] | [
"eigenvector",
"matrix",
"python"
] | stackoverflow_0074553962_eigenvector_matrix_python.txt |
Q:
Save information of student object to separate .txt file line by line (Python)
(I'm new to Python)
I have created a School class containing a dictionary where I let the user save student objects from a Student class.
class School:
def __init__(self):
self.students = {}
class Student:
def __init__... | Save information of student object to separate .txt file line by line (Python) | (I'm new to Python)
I have created a School class containing a dictionary where I let the user save student objects from a Student class.
class School:
def __init__(self):
self.students = {}
class Student:
def __init__(self, first_name, last_name, ssn)
The program starts off by importing information ... | [
"This answer might be overkill, but let me give you some advice:\n\nget familiar with dataclasses -> the way to go for classes containing data\nget familiar with fundamental data structures dict + json\ndont invent the wheel by yourself - look for and use ready to go database-solutions for python rather than messin... | [
0
] | [] | [] | [
"class",
"object",
"python",
"save"
] | stackoverflow_0074558761_class_object_python_save.txt |
Q:
How to install Nvidia Apex
I am trying to install apex on colab by Nvidia but failed several times. I tried number of different solutions including ones provided by Github official repository. I also tried answers provided here.
Every time I try I encounter error like this`
torch.__version__ = 1.9.0+cu102
/tmp/p... | How to install Nvidia Apex | I am trying to install apex on colab by Nvidia but failed several times. I tried number of different solutions including ones provided by Github official repository. I also tried answers provided here.
Every time I try I encounter error like this`
torch.__version__ = 1.9.0+cu102
/tmp/pip-req-build-xogkfxc5/setup.py:... | [
"To built apex on Colab, the cuda version of PyTorch and your system must match, as explained here.\nNote that, e. g., apex.optimizers.FusedAdam, apex.normalization.FusedLayerNorm, etc. require CUDA and C++ extensions.\nYou can built apex on Colab using the following simple steps:\nQuery the version Ubuntu Colab is... | [
0
] | [] | [] | [
"google_colaboratory",
"machine_learning",
"nvidia",
"python"
] | stackoverflow_0068558286_google_colaboratory_machine_learning_nvidia_python.txt |
Q:
how to display first_name in database on django
`views.py
from allauth.account.views import SignupView
from .forms import HODSignUpForm
class HodSignUp(SignupView):
template_name = 'account/signup.html'
form_class = HODSignUpForm
redirect_field_name = ''
view_name = 'hod_sign_up'
def get... | how to display first_name in database on django |
`views.py
from allauth.account.views import SignupView
from .forms import HODSignUpForm
class HodSignUp(SignupView):
template_name = 'account/signup.html'
form_class = HODSignUpForm
redirect_field_name = ''
view_name = 'hod_sign_up'
def get_context_data(self, **kwargs):
ret = super(HodSi... | [
"Add verbose_name when creating class:\nfrom po.models import User\nclass Admin(models.Model):\n user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)\n first_name = models.CharField(max_length=30, db_column='first_name', verbose_name='Name')\n last_name = models.CharField(max_le... | [
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074557996_django_python.txt |
Q:
Using Python Docx to remove blank lines
I am using Python docx to remove blank lines from documents containing text and images. Using the paragraph.clear() and paragraph.run.clear() works to a point, but the outputted file still has blank lines which only have a paragraph mark shown in Word. Is there a way of sear... | Using Python Docx to remove blank lines | I am using Python docx to remove blank lines from documents containing text and images. Using the paragraph.clear() and paragraph.run.clear() works to a point, but the outputted file still has blank lines which only have a paragraph mark shown in Word. Is there a way of searching directly for paragraph marks? Or is the... | [
"Empty lines are not marked by \"\\n\" but by empty string \"\".\nPlus, clear() removes text but not the paragraph itself.\nTry to test len(paragraph.text)==0 for each paragraph.\n",
"This removed all the empty lines for me in my document file\nfor paragraph in doc.paragraphs:\n if len(paragraph.text) == 0:\n ... | [
1,
1,
0
] | [] | [] | [
"python",
"python_docx"
] | stackoverflow_0043710188_python_python_docx.txt |
Q:
Confluent-Kafka Python - Describe consumer groups (to get the lag of each consumer group)
I want to get the details of the consumer group using confluent-kafka. The cli equivalent of that is
`
./kafka-consumer-groups.sh --bootstrap-server XXXXXXXXX:9092 --describe --group my-group
My end goal is to get the value... | Confluent-Kafka Python - Describe consumer groups (to get the lag of each consumer group) | I want to get the details of the consumer group using confluent-kafka. The cli equivalent of that is
`
./kafka-consumer-groups.sh --bootstrap-server XXXXXXXXX:9092 --describe --group my-group
My end goal is to get the value of lag from the output. Is there any method in confluent-kafka python API to get these detail... | [
"For now I have come up with the following solution. It's a work around to get the combined lag of a consumer group\n def get_lag(topic,numPartitions):\n diff = list()\n for i in range(numPartitions):\n topic_partition = TopicPartition(topic, partition=i)\n low, high = consumer.get_watermark_off... | [
0
] | [] | [] | [
"apache_kafka",
"confluent_kafka_python",
"kafka_consumer_api",
"python"
] | stackoverflow_0074558033_apache_kafka_confluent_kafka_python_kafka_consumer_api_python.txt |
Q:
Keras' clear_session() not working in Google colab
I run a keras model for several times in Google colab. Due to the nature of tensorflow there is a new model created each time of the program run, which leads to exhausted memory after some runs. I found that clear_session() of keras should help at the problem, but... | Keras' clear_session() not working in Google colab | I run a keras model for several times in Google colab. Due to the nature of tensorflow there is a new model created each time of the program run, which leads to exhausted memory after some runs. I found that clear_session() of keras should help at the problem, but it doesn't seem to work. I created an MWE for Google co... | [
"Please restart the runtime and try again as I tried replicating the above code and it's working fine.\nYou can check the output mentioned below for the same code:\nimport numpy as np\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras import backend as K\n\nX ... | [
0
] | [] | [] | [
"google_colaboratory",
"jupyter_notebook",
"keras",
"python",
"tensorflow"
] | stackoverflow_0074289376_google_colaboratory_jupyter_notebook_keras_python_tensorflow.txt |
Q:
Checking if 1D numpy array in a list of 1D numpy arrays and None
I want to check whether a 1D numpy array in the list of a 1D numpy arrays and None for an if condition.
I did it like this:
arr = np.array([1,2])
lst = [np.array([1,2]), np.array([3,4]), None, None]
if list(arr) in [list(i) for i in lst if i is not ... | Checking if 1D numpy array in a list of 1D numpy arrays and None | I want to check whether a 1D numpy array in the list of a 1D numpy arrays and None for an if condition.
I did it like this:
arr = np.array([1,2])
lst = [np.array([1,2]), np.array([3,4]), None, None]
if list(arr) in [list(i) for i in lst if i is not None]:
print("Yes")
else:
print("No")
but the size of the li... | [
"You cannot avoid one iteration through the lst to modify its elements (numpy arrays) somehow.\nBut instead of creating a list of lists out of the numpy arrays, you can create a set of tuples instead and store it:\nset_of_arrays_as_tuples = set([tuple(array) for array in lst if array is not None])\nThen, any subseq... | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074561704_numpy_python.txt |
Q:
How to use Linear regression when my **X** values are normally distributed?
To be more specific the error variance of the x value is half of the variance of error in y.
I looked over sklearn and couldn't find a function which takes the error variance of x into account.
A:
Not 100% sure I understand the question.... | How to use Linear regression when my **X** values are normally distributed? | To be more specific the error variance of the x value is half of the variance of error in y.
I looked over sklearn and couldn't find a function which takes the error variance of x into account.
| [
"Not 100% sure I understand the question. But if I understand it correctly, you are trying to use linear regression to find the linear model with maximum likelihood. In other words, an error for data where X and Y are uncertain is less serious that one where X and Y are very accurate.\nIf that is so, what people do... | [
0
] | [] | [] | [
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0074560695_machine_learning_python_scikit_learn.txt |
Q:
How to install CUDA in Google Colab GPU's
It seems that Google Colab GPU's doesn't come with CUDA Toolkit, how can I install CUDA in Google Colab GPU's. I am getting this error in installing mxnet in Google Colab.
Installing collected packages: mxnet
Successfully installed mxnet-1.2.0
ERROR: Incomplete installat... | How to install CUDA in Google Colab GPU's | It seems that Google Colab GPU's doesn't come with CUDA Toolkit, how can I install CUDA in Google Colab GPU's. I am getting this error in installing mxnet in Google Colab.
Installing collected packages: mxnet
Successfully installed mxnet-1.2.0
ERROR: Incomplete installation for leveraging GPUs for computations.
Pl... | [
"Cuda is not showing on your notebook because you have not enabled GPU in Colab.\nThe Google Colab comes with both options GPU or without GPU.\nYou can enable or disable GPU in runtime settings\nGo to Menu > Runtime > Change runtime.\n\nChange hardware acceleration to GPU.\n\nTo check if GPU is running or not, run ... | [
71,
28,
16,
2,
1,
0
] | [
"To run in Colab, you need CUDA 8 (mxnet 1.1.0 for cuda 9+ is broken). But Google Colab runs now 9.2. There is, however the way to uninstall 9.2, install 8.0 and then install mxnet 1.1.0 cu80. \nThe complete jupyter code is here : Medium\n",
"There is a guide which clearly explains that how to enable Cuda in Cola... | [
-1,
-1
] | [
"cuda",
"google_colaboratory",
"machine_learning",
"python",
"turi_create"
] | stackoverflow_0050560395_cuda_google_colaboratory_machine_learning_python_turi_create.txt |
Q:
Fastapi - need to use both Body and Depends as default value
I have an endpoint in in which the main body parameter was defined as follows:
@router.post("/myendpoint")
async def delete_objectss(param: DeleteItemParams = DeleteItemParamsMetadata,
.....)
Reason behind this is that I neede... | Fastapi - need to use both Body and Depends as default value | I have an endpoint in in which the main body parameter was defined as follows:
@router.post("/myendpoint")
async def delete_objectss(param: DeleteItemParams = DeleteItemParamsMetadata,
.....)
Reason behind this is that I needed:
DeleteItemParamsMetadata = Body(None, description="my verbose d... | [
"A parameter in a dependency can have a Body reference (or any other type) and it will be resolved correctly. Since you removed that metadata reference in your example it won't show up. You can fix that by adding it back:\nDeleteItemParamsMetadata = Body(None, description=\"my verbose description \" \\\n\" that wi... | [
2
] | [] | [] | [
"depends",
"fastapi",
"python",
"swagger_ui"
] | stackoverflow_0074560552_depends_fastapi_python_swagger_ui.txt |
Q:
How to get the highest element in absolute value in a numpy matrix?
Here is what I am currently doing, it works but it's a little cumbersome:
x = np.matrix([[1, 1], [2, -3]])
xmax = x.flat[abs(x).argmax()]
A:
The value you're looking for has to be either x.max() or x.min() so you could do
max(x.min(), x.max(), k... | How to get the highest element in absolute value in a numpy matrix? | Here is what I am currently doing, it works but it's a little cumbersome:
x = np.matrix([[1, 1], [2, -3]])
xmax = x.flat[abs(x).argmax()]
| [
"The value you're looking for has to be either x.max() or x.min() so you could do\nmax(x.min(), x.max(), key=abs)\n\nwhich is similar to aestrivex's solution but perhaps more readable? Note this will return the minimum in the case where x.min() and x.max() have the same absolute value e.g. -5 and 5. If you have a p... | [
42,
8,
8,
6,
3,
1,
1,
0,
0
] | [
"I think this is a pretty straightforward way, which might be slightly better if code readability is your primary concern. But really, your way is just as elegant.\nnp.min(x) if np.max(abs(x)) == abs(np.min(x)) else np.max(x)\n\n"
] | [
-1
] | [
"numpy",
"python"
] | stackoverflow_0017794266_numpy_python.txt |
Q:
Open S3 object as a string with Boto3
I'm aware that with Boto 2 it's possible to open an S3 object as a string with: get_contents_as_string()
Is there an equivalent function in boto3 ?
A:
read will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:... | Open S3 object as a string with Boto3 | I'm aware that with Boto 2 it's possible to open an S3 object as a string with: get_contents_as_string()
Is there an equivalent function in boto3 ?
| [
"read will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:\nimport boto3\n\ns3 = boto3.resource('s3')\n\nobj = s3.Object(bucket, key)\nobj.get()['Body'].read().decode('utf-8') \n\n",
"I had a problem to read/parse the object from S3 because of .get... | [
342,
162,
86,
48,
2,
1
] | [
"If body contains a io.StringIO, you have to do like below:\nobject.get()['Body'].getvalue()\n\n"
] | [
-7
] | [
"amazon_s3",
"amazon_web_services",
"boto",
"boto3",
"python"
] | stackoverflow_0031976273_amazon_s3_amazon_web_services_boto_boto3_python.txt |
Q:
'KMeans' object has no attribute '_n_threads'
Keep getting this error and I suspect it is related to the version difference between the sklearn, but I am not sure.
Also I have tried to update the sklearn version, but I cannot install past 0.22 version in my Jupiter notebook
Pickle and fit with sklearn version 0.... | 'KMeans' object has no attribute '_n_threads' | Keep getting this error and I suspect it is related to the version difference between the sklearn, but I am not sure.
Also I have tried to update the sklearn version, but I cannot install past 0.22 version in my Jupiter notebook
Pickle and fit with sklearn version 0.22 on a Jupyter notebook
Running on AWS Sagemaker
m... | [
"Some of my students ran into the same error when accessing the internals of an KMeans object:\nkmeans2 = KMeans(n_clusters=n_clusters) \nkmeans2.cluster_centers_ = clusters\n\nIn this scenario the problem could be worked around by running KMeans with a small subset of the original data.\nkmeans2 = KMeans(n_cluste... | [
1,
0
] | [
"Retraining the model with latest package versions should solve the problem.\n"
] | [
-1
] | [
"python",
"scikit_learn"
] | stackoverflow_0062186418_python_scikit_learn.txt |
Q:
Filter an evaluated QuerySet in Django
The requirement is for me to be able to access members of an evaluated QuerySet by a string attribute, in this case name. I don't like the idea of looping over a QuerySet as it seems like there is a more efficient way.
After I've called something like:
my_objects = MyObject.o... | Filter an evaluated QuerySet in Django | The requirement is for me to be able to access members of an evaluated QuerySet by a string attribute, in this case name. I don't like the idea of looping over a QuerySet as it seems like there is a more efficient way.
After I've called something like:
my_objects = MyObject.objects.all()
And I evaluate it with somethi... | [
"There is no direct way of doing this to get a object based on field value from queryset. But you can do one thing is to create a dictionary from queryset and set name as key (must be unique):\nmy_objects = MyObject.objects.all()\nobj_dict = {obj.name: obj for obj in my_objects}\nprint obj_dict['any_name']\n\nFYI: ... | [
3,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0014160647_django_python.txt |
Q:
Validating a BST algorithm
I am trying to solve a leetcode problem and am facing an issue with my code.
What i want is that prev store the value of the previous node but when i run the recursive code the value of prev always becomes None.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(se... | Validating a BST algorithm | I am trying to solve a leetcode problem and am facing an issue with my code.
What i want is that prev store the value of the previous node but when i run the recursive code the value of prev always becomes None.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None... | [
"The problem has two reasons:\n\nprev is a local name, and whatever happens to the prev in a recursive call, it doesn't affect the value of prev at the side of the caller, since that is a distinct name. Concretely, the condition if prev is not None will never be true; prev is still None.\nEven if somehow you would ... | [
1,
0
] | [] | [] | [
"binary_search_tree",
"python",
"python_3.x",
"tree"
] | stackoverflow_0074559762_binary_search_tree_python_python_3.x_tree.txt |
Q:
Python Networkx centrality measure range of nodes
How do I select a range from given values when drawing degree_centrality graph.
B1: 0.64
E2: 0.61
C3: 0.60
B2: 0.58
M1: 0.50
C1: 0.328
R1: 0.228
def draw(G, pos, measures, measure_name):
nodes = nx.draw_networkx_nodes(G, pos, node_size=250, cmap=plt.cm.p... | Python Networkx centrality measure range of nodes | How do I select a range from given values when drawing degree_centrality graph.
B1: 0.64
E2: 0.61
C3: 0.60
B2: 0.58
M1: 0.50
C1: 0.328
R1: 0.228
def draw(G, pos, measures, measure_name):
nodes = nx.draw_networkx_nodes(G, pos, node_size=250, cmap=plt.cm.plasma,
node_color=l... | [
"One way is to reduce the dictionary measures:\ndef draw(G, pos, measures, measure_name):\n\n\n # reduce measures\n min_val, max_val = 0.1, 0.4\n measures = {k:v for k, v in measures.items() if v<=max_val and v>=min_val}\n\n ...\n\nNote that the min_val, max_val can be added as arguments of the function... | [
0
] | [] | [] | [
"data_science",
"dataframe",
"networkx",
"python",
"python_3.x"
] | stackoverflow_0074561497_data_science_dataframe_networkx_python_python_3.x.txt |
Q:
RuntimeError: mat1 and mat2 shapes cannot be multiplied (2x720 and 784x10)
Any ideas how I can fix this run time error?
I would like to create these layers to read in the mnist dataset:
A 2d convolutional layer with 10 filters of size 5x5 with stride 1, zero padding, followed
by a ReLU activation, then a 2d max p... | RuntimeError: mat1 and mat2 shapes cannot be multiplied (2x720 and 784x10) | Any ideas how I can fix this run time error?
I would like to create these layers to read in the mnist dataset:
A 2d convolutional layer with 10 filters of size 5x5 with stride 1, zero padding, followed
by a ReLU activation, then a 2d max pooling operation with size 2x2.
A 2d convolutional layer with 20 filters of size... | [
"Based upon the network details that you provided:\n\nI need to create:\n\nA 2d convolutional layer with 10 filters of size 5x5 with stride 1, zero padding, followed by a ReLU activation, then a 2d max pooling operation with size 2x2.\nA 2d convolutional layer with 20 filters of size 5x5 with stride 1, zero padding... | [
0
] | [] | [] | [
"conv_neural_network",
"neural_network",
"python",
"pytorch"
] | stackoverflow_0074560241_conv_neural_network_neural_network_python_pytorch.txt |
Q:
How to zfill after a certain value in a list
I have a list that looks like this
ls =
['DATA2022_10.csv',
'DATA2022_2.csv',
'DATA2022_3.csv',
'DATA2022_4.csv',
'DATA2022_5.csv',
'DATA2022_6.csv',
'DATA2022_7.csv',
'DATA2022_8.csv',
'DATA2022_9.csv']
I want to zfill element in this list in order to sort my ... | How to zfill after a certain value in a list | I have a list that looks like this
ls =
['DATA2022_10.csv',
'DATA2022_2.csv',
'DATA2022_3.csv',
'DATA2022_4.csv',
'DATA2022_5.csv',
'DATA2022_6.csv',
'DATA2022_7.csv',
'DATA2022_8.csv',
'DATA2022_9.csv']
I want to zfill element in this list in order to sort my data.
Expected output:
ls =
['DATA2022_02.csv',
'... | [
"You don't even need to add zero and sort. If your goal is to sort the list use natsort directly.\nfrom natsort import natsorted\n\nnew =natsorted(ls)\nprint(new)\n\nGives #\n['DATA2022_2.csv', 'DATA2022_3.csv', 'DATA2022_4.csv', 'DATA2022_5.csv', 'DATA2022_6.csv', 'DATA2022_7.csv', 'DATA2022_8.csv', 'DATA2022_9.cs... | [
3
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074562066_list_python.txt |
Q:
Code not being performed before function in if-statement
I am trying to run an if-statement where once a number 1 to 7 is selected the corresponding financial data is uploader as ticker. However, in my if-statement the code to import the data is not being run and it jumps directly to the function main_2(). Both th... | Code not being performed before function in if-statement | I am trying to run an if-statement where once a number 1 to 7 is selected the corresponding financial data is uploader as ticker. However, in my if-statement the code to import the data is not being run and it jumps directly to the function main_2(). Both the function main_2() and the code to import financial data as t... | [
"You should have this error: NameError: name 'ticker' is not defined\nCall main_2 with ticker as a parameter: main_2(ticker)\nIn order to test it you can print ticker in main_2 to see if it works properly.\ndef main_2(ticker): \n print(ticker)\n\n"
] | [
1
] | [] | [] | [
"python",
"spyder"
] | stackoverflow_0074562016_python_spyder.txt |
Q:
How to merge two 2D convolutions together
“*” means convolution
Hello,
I am trying to find a way to merge two 2D convolutions together.
Assume that I have an image “Img” of dimensions (1x20x20) and two kernels “k1” and “k2” both of dimensions (1x3x3).
Normally you would first convolve Img with k1 and then convolve... | How to merge two 2D convolutions together | “*” means convolution
Hello,
I am trying to find a way to merge two 2D convolutions together.
Assume that I have an image “Img” of dimensions (1x20x20) and two kernels “k1” and “k2” both of dimensions (1x3x3).
Normally you would first convolve Img with k1 and then convolve the result with k2:
(Img * k1) * k2
My goal is... | [
"When the first convolution pad enough (up to kernel size - 1) and no stride, you can merge your convolution with any pad/stride for the second convolution with:\ndef merge_conv_kernels(k1, k2, s2, p2):\n # Assuming p1 = k1.shape[-1] - 1 and s1 = 1\n kernel_pad = k2.shape[-1] - 1\n k3 = torch.conv2d(k1.per... | [
0
] | [] | [] | [
"conv_neural_network",
"convolution",
"linear_algebra",
"python",
"pytorch"
] | stackoverflow_0074559543_conv_neural_network_convolution_linear_algebra_python_pytorch.txt |
Q:
how to divide a column element wise in python
I want to divide the first column of this table element wise by 3.6.
dict_read = {
'tractionForceTable': [']traction_V(km/h)_Force(N)', 'table']}
outputdict = {key: framehandle.value_readin(value) for (key, value) in dict_read.items()}`
enter image description here
I... | how to divide a column element wise in python | I want to divide the first column of this table element wise by 3.6.
dict_read = {
'tractionForceTable': [']traction_V(km/h)_Force(N)', 'table']}
outputdict = {key: framehandle.value_readin(value) for (key, value) in dict_read.items()}`
enter image description here
It throws an error something like :
outputdict["tra... | [
"There are several ways to do it, here are two. I suggest from your error message that your data is in a pd.DataFrame. I used a shortened version of your data.\nimport pandas as pd \ndf = pd.DataFrame({'velocity': [1,2,3,4,5],\n 'mfbp': [36600000, 1800000, 1200000, 900000, 720000]})\n \n\nYou co... | [
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074559911_dictionary_list_python.txt |
Q:
How to access an item from S3 using boto3 and read() its contents
I have a method that fetches a file from a URL and converts it to OpenCV image
def my_method(self, imgurl):
req = urllib.urlopen(imgurl)
r = req.read()
arr = np.asarray(bytearray(r), dtype=np.uint8)
image = cv2.imdecode(arr,-1) # 'load i... | How to access an item from S3 using boto3 and read() its contents | I have a method that fetches a file from a URL and converts it to OpenCV image
def my_method(self, imgurl):
req = urllib.urlopen(imgurl)
r = req.read()
arr = np.asarray(bytearray(r), dtype=np.uint8)
image = cv2.imdecode(arr,-1) # 'load it as it is'
return image
I would like to use boto3 to access an obj... | [
"I would do 1 this way:\nimport boto3\ns3 = boto3.resource('s3',\n use_ssl=False,\n endpoint_url=\"http://localhost:4567\",\n aws_access_key_id=\"\",\n aws_secret_access_key=\"\",\n)\nobj = s3.Object(bucketname, itemname)\n\nFor 2, I ha... | [
4,
0
] | [] | [] | [
"amazon_s3",
"boto3",
"numpy",
"python"
] | stackoverflow_0040239328_amazon_s3_boto3_numpy_python.txt |
Q:
How to create recalculating variables in Python
Suppose I have the code:
a = 2
b = a + 2
a = 3
The question is: how to keep b updated on each change in a? E.g., after the above code I would like to get: print(b) to be 5, not 4.
Of course, b can be a function of a via def, but, say, in IPython it's more comfortabl... | How to create recalculating variables in Python | Suppose I have the code:
a = 2
b = a + 2
a = 3
The question is: how to keep b updated on each change in a? E.g., after the above code I would like to get: print(b) to be 5, not 4.
Of course, b can be a function of a via def, but, say, in IPython it's more comfortable to have simple variables. Are there way to do so? M... | [
"You can do a lambda, which is basically a function... The only malus is that you have to do b() to get the value instead of just b\n>>> a = 2\n>>> b = lambda: a + 2\n>>> b()\n4\n>>> a = 3\n>>> b()\n5\n\n",
"Fair warning: this is a hack only suitable for experimentation and play in a Python interpreter environmen... | [
8,
4,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0018064564_python.txt |
Q:
How to prevent np.where from turning 0 into '0'?
I want to create an array with np.where that has strings and 0s in it. So usually its dtype would be 'object'. Minimal example:
A = np.array([[1,2,1],[2,1,2],[1,1,2]])
x = np.where(A==1,0,'hello')
As a result I get
array([['0', 'hello', '0'],
['hello', '0', ... | How to prevent np.where from turning 0 into '0'? | I want to create an array with np.where that has strings and 0s in it. So usually its dtype would be 'object'. Minimal example:
A = np.array([[1,2,1],[2,1,2],[1,1,2]])
x = np.where(A==1,0,'hello')
As a result I get
array([['0', 'hello', '0'],
['hello', '0', 'hello'],
['0', '0', 'hello']], dtype='<U11')
... | [
"You could use an object array as first input values for where:\nx = np.where(A==1, np.zeros_like(A).astype(object), 'hello')\n\nOutput:\narray([[0, 'hello', 0],\n ['hello', 0, 'hello'],\n [0, 0, 'hello']], dtype=object)\n\n"
] | [
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074562254_numpy_python.txt |
Q:
Is there any way to get the recording url and timeline of Microsoft Teams meeting using GRAPH API's
I'm trying to fetch the recording details and timeline file using GRAPH API of Teams, but it is not there is there any way we can fetch them?
I can able to fetch the recording using one drive but issue is we need to... | Is there any way to get the recording url and timeline of Microsoft Teams meeting using GRAPH API's | I'm trying to fetch the recording details and timeline file using GRAPH API of Teams, but it is not there is there any way we can fetch them?
I can able to fetch the recording using one drive but issue is we need to grant drive scopes which is not good, can't we achieve using teams graph API's? also timeline of the mee... | [
"Teams meeting Record link is available in Graph Beta API under Chat messages - callRecordingUrl.\nchatMessage, eventMessageDetail, callRecordingEventMessageDetail\n\nPlease go through List chats documentation to get chat ID. Alternatively You can get the chat id directly if you create a meeting using Graph API. Yo... | [
2
] | [] | [] | [
"microsoft_graph_api",
"microsoft_teams",
"python"
] | stackoverflow_0074557628_microsoft_graph_api_microsoft_teams_python.txt |
Q:
How to split a dataset with peaks and finding area under these peaks?
I have two datasets, one with consumption of energy and one with production of energy. I merged these two and filtered out all of the surplus energy peaks from this. This resulted in a dataframe with lots of peaks and zeros for all moments there... | How to split a dataset with peaks and finding area under these peaks? | I have two datasets, one with consumption of energy and one with production of energy. I merged these two and filtered out all of the surplus energy peaks from this. This resulted in a dataframe with lots of peaks and zeros for all moments there is no surplus energy.
What I am looking for is to find the amount of energ... | [
"I have something for you, but (a) it may have off-by-one errors, and (b) there needs to be some manual fudging at the first and last rows of the dataframe, if Value isn't zero for these rows. Disclaimers dispensed, here goes.\nFirst, (1) put in columns indicating when a row is the beginning of a shift, and when it... | [
0
] | [] | [] | [
"pandas",
"python",
"split",
"sum"
] | stackoverflow_0074545531_pandas_python_split_sum.txt |
Q:
youtube-dl :: how to listen to audio while downloading
I know that I can download an audio track from YouTube through this easy command:
youtube-dl -f 251 'http://www.youtube.com/watch?v=HRIF4_WzU1w'
Lately YouTube has been slowing down the download speed.
Is there a way I can listen to the audio while downloadin... | youtube-dl :: how to listen to audio while downloading | I know that I can download an audio track from YouTube through this easy command:
youtube-dl -f 251 'http://www.youtube.com/watch?v=HRIF4_WzU1w'
Lately YouTube has been slowing down the download speed.
Is there a way I can listen to the audio while downloading the track?
Where is the file located while it is downloadi... | [
"As far as I know when downloading a video while precising -f 251 it is being written while downloading in VIDEO_TITLE.webm.part and at the end of the download this file is rename VIDEO_TITLE.webm.\nTo listen to the audio of a video while downloading its track, just open in a web-browser the second URL returned by:... | [
1
] | [] | [] | [
"python",
"tcp",
"udp",
"youtube",
"youtube_dl"
] | stackoverflow_0074512222_python_tcp_udp_youtube_youtube_dl.txt |
Q:
PySpark Get row with max value from multiple columns grouped
I would be happy for some help here :-)
I have the following dataframe:
Type | Number | Date | Value |
------------------------------------
A | 1 | 2022-10-01 | 5 |
A | 2 | 2022-10-01 | 8 |
A | 3 | 2022-11-23 | 4... | PySpark Get row with max value from multiple columns grouped | I would be happy for some help here :-)
I have the following dataframe:
Type | Number | Date | Value |
------------------------------------
A | 1 | 2022-10-01 | 5 |
A | 2 | 2022-10-01 | 8 |
A | 3 | 2022-11-23 | 4 |
B | 1 | 2022-02-02 | 1 |
B | 2 | 2022-02-04... | [
"Your code works fine :\ndf.withColumn(\"MaxNumber\", F.max(\"Number\").over(w)).where(\n F.col(\"Number\") == F.col(\"MaxNumber\")\n).show()\n\n+----+------+----------+-----+---------+\n|Type|Number| Date|Value|MaxNumber|\n+----+------+----------+-----+---------+\n| A| 2|2022-10-01| 8| 2|\n... | [
0
] | [] | [] | [
"databricks",
"pyspark",
"python"
] | stackoverflow_0074561382_databricks_pyspark_python.txt |
Q:
About the outconverter of cx_Oracle component for python doesn't work when the value is None
I have a requirement to get data from the database through cx_oracle convert. and during the fetch data, if the value of the Number field is None, it needs to be converted to -1.
I want to use outconverter attribute of the... | About the outconverter of cx_Oracle component for python doesn't work when the value is None | I have a requirement to get data from the database through cx_oracle convert. and during the fetch data, if the value of the Number field is None, it needs to be converted to -1.
I want to use outconverter attribute of the Variable. but I found if the value is None, the outconverter will be fired.
here is my example co... | [
"The outconverter value is not called if the value is None as described in the documentation. If you want this behavior you can log an enhancement request.\nAn issue was logged for this.\n"
] | [
2
] | [] | [] | [
"cx_oracle",
"python"
] | stackoverflow_0074557918_cx_oracle_python.txt |
Q:
How to parse ingress object in cdktf security group?
Problem Unable to create security group rules in aws using CDKTF
Code
import cdktf_cdktf_provider_aws.security_group as SecurityGroup_
self.security_group_ = SecurityGroup_.SecurityGroup(self.scope_object, id_=self.id, name=self.name, vpc_id=self.vpc_id, ingress... | How to parse ingress object in cdktf security group? | Problem Unable to create security group rules in aws using CDKTF
Code
import cdktf_cdktf_provider_aws.security_group as SecurityGroup_
self.security_group_ = SecurityGroup_.SecurityGroup(self.scope_object, id_=self.id, name=self.name, vpc_id=self.vpc_id, ingress=[{"from_port":"3306","to_port":"3306"}])
Error
29: ... | [
"Change the code to\nself.security_group_ = SecurityGroup_.SecurityGroup(\nself.scope_object, \nid_=self.id, \nname=self.name, \nvpc_id=self.vpc_id, \ningress=[SecurityGroup_.SecurityGroupIngress(from_port=3306,to_port=3306, \"security_groups\":['test-sg'])])\n\nIngress takes a list of class obj SecurityGroupIngres... | [
3
] | [] | [] | [
"amazon_web_services",
"aws_security_group",
"python",
"terraform",
"terraform_cdk"
] | stackoverflow_0074559553_amazon_web_services_aws_security_group_python_terraform_terraform_cdk.txt |
Q:
How to expand a list to a certain size without repeating each individual list elements that n-times?
I'm looking to keep the individual elements of a list repeating for x number of times, but can only see how to repeat the full list x number of times.
For example, I want to repeat the list [3, 5, 1, 9, 8] such tha... | How to expand a list to a certain size without repeating each individual list elements that n-times? | I'm looking to keep the individual elements of a list repeating for x number of times, but can only see how to repeat the full list x number of times.
For example, I want to repeat the list [3, 5, 1, 9, 8] such that if x=12, then I want to produce tthe following list (i.e the list continues to repeat in order until the... | [
"Your code repeats list 12 times. You need to repeat list until length is matched. This can achieved using Itertools - Functions creating iterators for efficient looping\nfrom itertools import cycle, islice\n\nlis = [3, 5, 1, 9, 8]\nout = list(islice(cycle(lis), 12))\nprint(out)\n\nGives #\n[3, 5, 1, 9, 8, 3, 5, 1,... | [
2,
0
] | [] | [] | [
"list",
"loops",
"python",
"repeat"
] | stackoverflow_0074562382_list_loops_python_repeat.txt |
Q:
how to sort pandas dataframe from one column
I have a data frame like this:
print(df)
0 1 2
0 354.7 April 4.0
1 55.4 August 8.0
2 176.5 December 12.0
3 95.5 February 2.0
4 85.6 January 1.0
5 152 July 7.0
6 238.7 June 6.0
7 104.8 ... | how to sort pandas dataframe from one column | I have a data frame like this:
print(df)
0 1 2
0 354.7 April 4.0
1 55.4 August 8.0
2 176.5 December 12.0
3 95.5 February 2.0
4 85.6 January 1.0
5 152 July 7.0
6 238.7 June 6.0
7 104.8 March 3.0
8 283.5 May 5.0
9 278... | [
"Use sort_values to sort the df by a specific column's values:\nIn [18]:\ndf.sort_values('2')\n\nOut[18]:\n 0 1 2\n4 85.6 January 1.0\n3 95.5 February 2.0\n7 104.8 March 3.0\n0 354.7 April 4.0\n8 283.5 May 5.0\n6 238.7 June 6.0\n5 152.0 ... | [
690,
244,
58,
27,
25,
12,
9,
8,
6,
6,
1,
0
] | [
"Example:\nAssume you have a column with values 1 and 0 and you want to separate and use only one value, then:\n// furniture is one of the columns in the csv file.\n \n\nallrooms = data.groupby('furniture')['furniture'].agg('count')\nallrooms\n\n\nmyrooms1 = pan.DataFrame(allrooms, columns = ['furniture'], index = ... | [
-1
] | [
"dataframe",
"pandas",
"python",
"sorting",
"time"
] | stackoverflow_0037787698_dataframe_pandas_python_sorting_time.txt |
Q:
Select TIMESTAMP(6) WITH TIME ZONE using Pandas, SQLAlchemy and cx_Oracle
I am trying to use pandas to select some data from an Oracle database. The column in question has the data type TIMESTAMP(6) WITH TIME ZONE. I am in the same time zone as the database, but it contains data that is recorded from a different t... | Select TIMESTAMP(6) WITH TIME ZONE using Pandas, SQLAlchemy and cx_Oracle | I am trying to use pandas to select some data from an Oracle database. The column in question has the data type TIMESTAMP(6) WITH TIME ZONE. I am in the same time zone as the database, but it contains data that is recorded from a different time zone.
Oracle version: Oracle Database 12c Enterprise Edition Release 12.2.0... | [
"For the record, the code I mentioned in the original comment thread is:\n# create table t (c TIMESTAMP(6) WITH TIME ZONE);\n# insert into t (c) values (systimestamp);\n# commit;\n#\n# Name: pandas\n# Version: 1.5.2\n# Name: SQLAlchemy\n# Version: 1.4.44\n# Name: cx-Oracle\n# Version: 8.3.0\n#\n# Output is like:\n#... | [
1,
0
] | [] | [] | [
"cx_oracle",
"oracle",
"pandas",
"python",
"sqlalchemy"
] | stackoverflow_0074554255_cx_oracle_oracle_pandas_python_sqlalchemy.txt |
Q:
subprocess.CalledProcessError: returned non-zero exit status 1, while os.system does not raise any error
Given the following command:
newman run tests.postman_collection.json -e environment.json --reporters testrail,json,html
Raises:
RuntimeError: command 'newman run tests.postman_collection.json -e environment.... | subprocess.CalledProcessError: returned non-zero exit status 1, while os.system does not raise any error | Given the following command:
newman run tests.postman_collection.json -e environment.json --reporters testrail,json,html
Raises:
RuntimeError: command 'newman run tests.postman_collection.json -e environment.json --reporters testrail,json,html
' return with error (code 1): b'\nhttps://host.testrail.io/index.php?/run... | [
"That's a misfeature of os.system; it returns the exit code so you can examine it, but doesn't raise an error if something fails.\nThe check in subprocess.check_output means check that the command succeeded, or raise an exception otherwise. This is generally a good thing, as you don't want processes to die undernea... | [
2
] | [] | [] | [
"newman",
"python",
"subprocess"
] | stackoverflow_0074562214_newman_python_subprocess.txt |
Q:
'type' object is not subscriptable python
here are the functions I defined when I try to call them I get the error
note that resultmatrix is a 4x4 2d numpy array
**
the function is :
import numpy as np
def getValues(row,column,resultMatrix):
a=resultMatrix[row][column]
prefix='0x'
a=prefix+a
an_integer = ... | 'type' object is not subscriptable python | here are the functions I defined when I try to call them I get the error
note that resultmatrix is a 4x4 2d numpy array
**
the function is :
import numpy as np
def getValues(row,column,resultMatrix):
a=resultMatrix[row][column]
prefix='0x'
a=prefix+a
an_integer = int(a, 16)
return an_integer
mixMatrix=np... | [
"The issue seems to be from the mixColumns function you cast the v1, v2, v3 and v4 to hexadecimal then you extract the third and fourth character.\nHowever you can't get the fourth character when the value is below 15 since the\nhex value will be on only 3 character (0 => 0x0, 15 => 0xF, 16 => 0x10).\nIf the idea i... | [
1
] | [] | [] | [
"numpy",
"python",
"python_3.x"
] | stackoverflow_0074561441_numpy_python_python_3.x.txt |
Q:
My buildozer suddenly reject to turn my kivy app into android apk ;(
I'm making a kivy app that works on android smartphone. It colaborates with sqlite3. But as I try to transport as a android apk using my buildozer, suddenly my buildozer denied to work. The Error message is this.
[DEBUG]: -> running mv sqlite-a... | My buildozer suddenly reject to turn my kivy app into android apk ;( | I'm making a kivy app that works on android smartphone. It colaborates with sqlite3. But as I try to transport as a android apk using my buildozer, suddenly my buildozer denied to work. The Error message is this.
[DEBUG]: -> running mv sqlite-amalgamation-3350500 /mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform... | [
"Two ideas:\n\nTry to run buildozer with sudo\nChange your project directory to your /usr/ location. Maybe the permission error is a result of your /mnt/c/ folder.\n\nIf you want to publish the app in the appstore you have to raise the API to 31.\n",
"Problem solved. The ultimal-fundamental problem was \"A Vaccin... | [
0,
0
] | [] | [] | [
"buildozer",
"kivy",
"python"
] | stackoverflow_0074559753_buildozer_kivy_python.txt |
Q:
How to only get datetime without hours minutes and seconds python pandas
I am doing a forecast with FBProhpet and suddenly when I do the forecast, only the forecasted dates (ds) ate being displayed with hours minutes and seconds
See pictures for more information.
Any ideas on how to fix that
A:
use:
df['ds']=pd... | How to only get datetime without hours minutes and seconds python pandas | I am doing a forecast with FBProhpet and suddenly when I do the forecast, only the forecasted dates (ds) ate being displayed with hours minutes and seconds
See pictures for more information.
Any ideas on how to fix that
| [
"use:\ndf['ds']=pd.to_datetime(df['ds'])\ndf['ds']=df['ds'].dt.date\n\n"
] | [
0
] | [] | [] | [
"datetime",
"forecast",
"pandas",
"python"
] | stackoverflow_0074562594_datetime_forecast_pandas_python.txt |
Q:
How to Pass Arguments (EntryPointArguments) in spark JOB using EMR Serverless?
**I'm trying to pass some arguments to run my pyspark script by the parameter of boto3 (emr-serverless client) EntryPointArguments, however, it doesn't work at all, I would like to know if I'm doing it the right way.
**
**my python code... | How to Pass Arguments (EntryPointArguments) in spark JOB using EMR Serverless? | **I'm trying to pass some arguments to run my pyspark script by the parameter of boto3 (emr-serverless client) EntryPointArguments, however, it doesn't work at all, I would like to know if I'm doing it the right way.
**
**my python code is like this:**
`
import argparse
parser = argparse.ArgumentParser()
parser.ad... | [
"I was testing it out, and I ended up figuring out how to do this.\nFrom what I understand, when it's a param like this:\n-env prd\n\nyou have to pass in the EntryPointArguments like this:\n[\"-env\", \"prd\"]\n\nseparating the arg, then passing the value, each one separately.\n"
] | [
0
] | [] | [] | [
"amazon_web_services",
"apache_spark",
"emr_serverless",
"pyspark",
"python"
] | stackoverflow_0074562238_amazon_web_services_apache_spark_emr_serverless_pyspark_python.txt |
Q:
change only numeric values to binary in dataframe
I would like to change my dataframe with values into binary,
given df:
summary
word1
word2
xyz
0
56
abc
32
0
..
..
..
I would like to convert ONLY NUMERIC values to binary, meaning - if the value in word1/2 etc is grater than 0 -> 1 and when it's 0 = stays 0.
... | change only numeric values to binary in dataframe | I would like to change my dataframe with values into binary,
given df:
summary
word1
word2
xyz
0
56
abc
32
0
..
..
..
I would like to convert ONLY NUMERIC values to binary, meaning - if the value in word1/2 etc is grater than 0 -> 1 and when it's 0 = stays 0.
category
summary
word1
word2
categor... | [
"Check if the values in your columns 'word' are greater than 0 and convert to int\n(df[['word1','word2']] > 0)\n\n word1 word2\n0 False True\n1 True False\n\n(df[['word1','word2']] > 0).astype(int)\n\n word1 word2\n0 0 1\n1 1 0\n\nAnd assign back:\ndf[['word1','word2']] = (df[['word1... | [
1
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074562339_dataframe_python.txt |
Q:
how to declare dynamic variables in python with a test
I know its possible to declare dynamic variables using this method :
for x in range(0, 7):
globals()[f"variable1{x}"] = x
What i want to do is something like :
ls = [1,31,42,56, ...]
for x in range(0, len(ls)):
globals()[f"variable{x}"] = 10*x if ls[x... | how to declare dynamic variables in python with a test | I know its possible to declare dynamic variables using this method :
for x in range(0, 7):
globals()[f"variable1{x}"] = x
What i want to do is something like :
ls = [1,31,42,56, ...]
for x in range(0, len(ls)):
globals()[f"variable{x}"] = 10*x if ls[x] %2 == 0 else globals()[f"variable{x}"] = 11*x
Code is ran... | [
"You try to assign the value in the if and the else.\nThe \"x if condition else y\" is by itself a value so you can assign it to something you don't have to assign in the if and else part. So you should use :\nls = [1,31,42,56, ...]\nfor x in range(0, len(ls)):\n globals()[f\"variable{x}\"] = 10*x if ls[x] % 2 =... | [
1
] | [] | [] | [
"dynamic",
"python",
"tkinter",
"variable_assignment"
] | stackoverflow_0074562602_dynamic_python_tkinter_variable_assignment.txt |
Q:
How to add a value and its index to a series?
I googled and most of the answers is about adding a value to a series but not update the index.
Here is my series with date string as its index like this
2022-01-01 1
2022-01-02 7
2022-01-03 3
Now I like to add new value of 10 into this series with new index of 202... | How to add a value and its index to a series? | I googled and most of the answers is about adding a value to a series but not update the index.
Here is my series with date string as its index like this
2022-01-01 1
2022-01-02 7
2022-01-03 3
Now I like to add new value of 10 into this series with new index of 2022-01-04 date string. so the series becomes
2022-01-... | [
"Just use the index value as a subscript, for example:\n>>> aa = pd.Series({\"foo\": 1})\n>>> aa\nfoo 1\ndtype: int64\n>>> aa[\"bar\"] = 2\n>>> aa\nfoo 1\nbar 2\ndtype: int64\n\n",
"Is it not just something like:\nnew_row = pd.Series(new_value, index=[index_of_new_value])\nseries = pd.concat([series, new... | [
2,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074562556_pandas_python.txt |
Q:
Decorators with parameters?
I have a problem with the transfer of the variable insurance_mode by the decorator. I would do it by the following decorator statement:
@execute_complete_reservation(True)
def test_booking_gta_object(self):
self.test_select_gta_object()
but unfortunately, this statement does not wo... | Decorators with parameters? | I have a problem with the transfer of the variable insurance_mode by the decorator. I would do it by the following decorator statement:
@execute_complete_reservation(True)
def test_booking_gta_object(self):
self.test_select_gta_object()
but unfortunately, this statement does not work. Perhaps maybe there is better... | [
"The syntax for decorators with arguments is a bit different - the decorator with arguments should return a function that will take a function and return another function. So it should really return a normal decorator. A bit confusing, right? What I mean is:\ndef decorator_factory(argument):\n def decorator(func... | [
1083,
482,
133,
119,
43,
36,
21,
17,
17,
10,
7,
4,
4,
2,
2,
2,
1,
1,
0,
0,
0
] | [
"In case both the function and the decorator have to take arguments you can follow the below approach.\nFor example there is a decorator named decorator1 which takes an argument\n@decorator1(5)\ndef func1(arg1, arg2):\n print (arg1, arg2)\n\nfunc1(1, 2)\n\nNow if the decorator1 argument has to be dynamic, or pas... | [
-1,
-1
] | [
"decorator",
"python"
] | stackoverflow_0005929107_decorator_python.txt |
Q:
How to print high numbered unicode characters in python
i am trying to write a python program that prints music notes (like -> u1d15e). However, i cant quite get it to work.
Here is what i get using the following code
note = '\U0001d15e'
bytes = note.encode('utf-8')
print(bytes)
>>> b'\xf0\x9d\x85\x9e'
If i try... | How to print high numbered unicode characters in python | i am trying to write a python program that prints music notes (like -> u1d15e). However, i cant quite get it to work.
Here is what i get using the following code
note = '\U0001d15e'
bytes = note.encode('utf-8')
print(bytes)
>>> b'\xf0\x9d\x85\x9e'
If i try to print the string directly i get
note = '\U0001d15e'
# byt... | [
"My system doesn't like that representation either, but can directly put it into a string and print() it\nTo me, this is some artifact of your system being Windows and you need to set your console to use UTF-8 instead of cp1252\nUsing UTF-8 Encoding (CHCP 65001) in Command Prompt / Windows Powershell (Windows 10)\n... | [
1
] | [] | [] | [
"python",
"unicode",
"windows"
] | stackoverflow_0074562616_python_unicode_windows.txt |
Q:
Skip blank lines in dat file with for loop in Python
I'm trying to write a bit of code that reads in a dat file that has a bunch of blank lines and put them into lists to be manipulated later.
Ex:
0.92; 0.70
1.53;
1.41; 1.00
1.47; 1.08
;
0.73; 0.18
1.50; 1.17
;
;
1.68;
I would like to skip the lines t... | Skip blank lines in dat file with for loop in Python | I'm trying to write a bit of code that reads in a dat file that has a bunch of blank lines and put them into lists to be manipulated later.
Ex:
0.92; 0.70
1.53;
1.41; 1.00
1.47; 1.08
;
0.73; 0.18
1.50; 1.17
;
;
1.68;
I would like to skip the lines that have blank spaces.
This is what I have so far...
file_... | [
"You get the error cause you try to convert the empty spaces to float.\nTry this:\nwith open(\"Gliese.dat\", \"r\")as f:\n\n data = []\n\n for line in f:\n line = line.strip()\n if line.split(\";\")[0] and line.split(\";\")[1]:\n data.append(line.rstrip(\"\\n\"))\n\n"
] | [
0
] | [] | [] | [
"python",
"readlines"
] | stackoverflow_0074562628_python_readlines.txt |
Q:
Why, after replacing every value in a row, are the first two rows completely different? | Python, Pandas
I've got a simple script to remove characters from the left & right of a string containing a datetime value. The reason for this is that there are unnecessary characters on each side of the actual value I want.... | Why, after replacing every value in a row, are the first two rows completely different? | Python, Pandas | I've got a simple script to remove characters from the left & right of a string containing a datetime value. The reason for this is that there are unnecessary characters on each side of the actual value I want.
It works by looping through all items in a column (called Time), removing the characters & then replacing the... | [
"If you only want to extract the timestamps as string, I would suggest using regex. Furthermore, iterating over a dataset with a for loop is highly inefficient (and with big datasets, you will notice the slowness); I suggest using an str.extract function:\nimport pandas as pd\n\ndf = pd.read_csv(\"file.csv\") # rea... | [
0
] | [] | [] | [
"loops",
"pandas",
"python"
] | stackoverflow_0074562609_loops_pandas_python.txt |
Q:
RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 100 but got size 1 for tensor number 1 in the list
I'm new to PyTorch not able to figure out what I'm doing wrong, below is the code
x_np, y_np = datasets.make_regression(n_samples=100,n_features=1,noise=20,random_state=0)
x = torch.fr... | RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 100 but got size 1 for tensor number 1 in the list | I'm new to PyTorch not able to figure out what I'm doing wrong, below is the code
x_np, y_np = datasets.make_regression(n_samples=100,n_features=1,noise=20,random_state=0)
x = torch.from_numpy(x_np.astype(np.float32))
y = torch.from_numpy(y_np.astype(np.float32))
y = y.view(y.shape[0],1)
n_samples, n_features = x.sha... | [
"i2h maps self.input_size + self.hidden_size dimension to self.hidden_size, so for h2o, you have to define a mapping starting from self.hidden dimension. Also, you have to update the forward accordingly. Here is the complete code:\nclass Regression(nn.Module):\n def __init__(self, inputsize, outputsize, hiddensize... | [
0
] | [] | [] | [
"neural_network",
"python",
"pytorch"
] | stackoverflow_0074561833_neural_network_python_pytorch.txt |
Q:
Measure CPU Usage (in Cores) and Memory Usage of Compiled Programs
I have two programs, one in go and one in python that I am trying to characterize. For this, I'd like to measure the CPU usage and Memory Usage by regularly measuring the amounts consumed by the two programs at regular intervals (say, every 0.1 sec... | Measure CPU Usage (in Cores) and Memory Usage of Compiled Programs | I have two programs, one in go and one in python that I am trying to characterize. For this, I'd like to measure the CPU usage and Memory Usage by regularly measuring the amounts consumed by the two programs at regular intervals (say, every 0.1 seconds) for some given amount of time. I have been looking everywhere for ... | [
"You can also try Check server load with top, htop, iotop.\n",
"For my particular case, the best choice is to instrument the each of the programs for something like Prometheus. Then I can scrape the data at regular intervals to get what I am looking for.\nIn this case, I would follow off of something like: https:... | [
1,
1
] | [] | [] | [
"go",
"linux",
"python"
] | stackoverflow_0074552123_go_linux_python.txt |
Q:
How to join 2 tables with getting all rows from left table and only matching ones in right
Table 1
Table 2
Table2.plan_selected shows what plan did the user choose.
Eg: The user with user_id=4 in Table2 choose the id = 2 plan from Table1.
I want to get all the rows from Table1 and only matching rows from Table2 ... | How to join 2 tables with getting all rows from left table and only matching ones in right | Table 1
Table 2
Table2.plan_selected shows what plan did the user choose.
Eg: The user with user_id=4 in Table2 choose the id = 2 plan from Table1.
I want to get all the rows from Table1 and only matching rows from Table2 for a particular user_id.
The expected result is like this.
I want to fetch all the rows of Tabl... | [
"You can query with:\nSubscriptionsPlans.objects.filter(subscriptionsorder__user_id=4)\nThis will list all SubscriptionPlans for which there is a SubscriptionOrder with 4 as user_id.\n"
] | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"sql"
] | stackoverflow_0074561745_django_django_rest_framework_python_sql.txt |
Q:
Using lxml to parse text and break it into a list of sentences using some tags to add structure
Consider the following text in custom xml:
<?xml version="1.0"?>
<body>
<heading><b>This is a title</b></heading>
<p>This is a first <b>paragraph</b>.</p>
<p>This is a second <b>paragraph</b>. With a list:
... | Using lxml to parse text and break it into a list of sentences using some tags to add structure | Consider the following text in custom xml:
<?xml version="1.0"?>
<body>
<heading><b>This is a title</b></heading>
<p>This is a first <b>paragraph</b>.</p>
<p>This is a second <b>paragraph</b>. With a list:
<ul>
<li>first item</li>
<li>second item</li>
</ul>
And t... | [
"Interesting exercise...\nThe following is a bit convoluted and won't give you the exact output you indicated, but maybe it'll be close enough for you (or someone else) to modify it:\nfrom lxml import etree\nstuff = \"\"\"[your xml]\"\"\"\n \ndoc = etree.XML(stuff)\n \n#we need this in order to count how... | [
0
] | [] | [] | [
"elementtree",
"lxml",
"parsing",
"python"
] | stackoverflow_0074554835_elementtree_lxml_parsing_python.txt |
Q:
Using default dictionaries problem (python)
I have a slightly weird input of data that is in this format:
data = { 'sensor1': {'units': 'x', 'values': [{'time': 17:00, 'value': 10},
{'time': 17:10, 'value': 12},
{'time': 17:20, 'value' ... | Using default dictionaries problem (python) | I have a slightly weird input of data that is in this format:
data = { 'sensor1': {'units': 'x', 'values': [{'time': 17:00, 'value': 10},
{'time': 17:10, 'value': 12},
{'time': 17:20, 'value' :7}, ...]}
'sensor2': {'units': 'x', 'values': ... | [
"You can also use dict in this way:\ndata = {'sensor1': {'units': 'x', 'values': [{'time': '17:00', 'value': 10},\n {'time': '17:10', 'value': 12},\n {'time': '17:20', 'value': 7},\n ]... | [
2
] | [] | [] | [
"dictionary",
"python",
"resourcedictionary",
"sorting"
] | stackoverflow_0074562798_dictionary_python_resourcedictionary_sorting.txt |
Q:
Assigning player in an interactive game
I am making a solution to a simple game where you can choose the amount of players with maximum 5 players and minimum 2. Each player is idenitied by their first and last name.
max_players = int(input(" Insert the number of players there are there? : "))
while len(players_li... | Assigning player in an interactive game | I am making a solution to a simple game where you can choose the amount of players with maximum 5 players and minimum 2. Each player is idenitied by their first and last name.
max_players = int(input(" Insert the number of players there are there? : "))
while len(players_list) < max_players:
player1 = input(" What... | [
"\nAlso, when I insert the first name of the player, it shows that the \"players\" are not defined\n\nYou try to append players, which indeed does not exist before you call it, to players_list, which also does not exist. You need to define these two first.\nFor the number of players limit, you can add a simple chec... | [
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074562397_list_python.txt |
Q:
What is the use of `pip install -e .` if I can simply run the python script using the environment?
Based on this answer, I can fully understand the use of:
pip install -e /path/to/locations/repo
However, I am yet to see the use of:
pip install -e .
I can understand it from the perspective of doing pip install -e... | What is the use of `pip install -e .` if I can simply run the python script using the environment? | Based on this answer, I can fully understand the use of:
pip install -e /path/to/locations/repo
However, I am yet to see the use of:
pip install -e .
I can understand it from the perspective of doing pip install -e /path/to/locations/repo, but from the working directory of the project dependency. But that's the only ... | [
"pip install -e\n\nwill just create a projekt_name.egg-info file in the venv\\Lib\\site-packages folder with a link to the repo location. Nothing is copied.\nYou can continue developing and you can access your project packages as if the repo was properly installed. No dirty sys.path.append-hacks needed.\n"
] | [
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0074561368_pip_python.txt |
Q:
filter custom spans overlaps in spacy doc
I have a bunch of regex in this way:
(for simplicity the regex patters are very easy, the real case the regex are very long and barely incomprehensible since they are created automatically from other tool)
I want to create spans in a doc based on those regex.
This is the c... | filter custom spans overlaps in spacy doc | I have a bunch of regex in this way:
(for simplicity the regex patters are very easy, the real case the regex are very long and barely incomprehensible since they are created automatically from other tool)
I want to create spans in a doc based on those regex.
This is the code:
import spacy
from spacy.tokens import Doc,... | [
"spacy.util.filter_spans will do this. The answer is the same as the linked question, where matcher results are converted to spans in order to filter them with this function.\ndocs.spans[name] = spacy.util.filter_spans(doc.spans[name])\n\n"
] | [
1
] | [] | [] | [
"python",
"spacy"
] | stackoverflow_0074560365_python_spacy.txt |
Q:
How to convert a python dictionary with tuples into a pandas dataframe?
I have a python dictionary in which the keys of the dictionary are tuples of two strings and the values are integers.
It looks like this:
mydic = { ('column1', 'index1'):33,
('column1', 'index2'):34,
('column2', 'index1')... | How to convert a python dictionary with tuples into a pandas dataframe? | I have a python dictionary in which the keys of the dictionary are tuples of two strings and the values are integers.
It looks like this:
mydic = { ('column1', 'index1'):33,
('column1', 'index2'):34,
('column2', 'index1'):35,
('column2', 'index2'):36 }
The first string of the tuples sh... | [
"Build a pd.Series first (which will have a MultiIndex), then use pd.Series.unstack to get the column names.\ndf = pd.Series(mydic).unstack(0)\nprint(df)\n\n column1 column2\nindex1 33 35\nindex2 34 36\n\n",
"You can use pd.MultiIndex.from_tuples.\nmydic = { ('column1', 'index1'):3... | [
3,
0
] | [] | [] | [
"dataframe",
"dictionary",
"pandas",
"python",
"tuples"
] | stackoverflow_0074562785_dataframe_dictionary_pandas_python_tuples.txt |
Q:
how to search for a list in a list of lists in python
I have this list:
t = [['1', '0', '1', '0', '0', '0', 'up', 5], ['1', '0', '1', '0', '0', '1', 'up', 5], ['1', '0', '1', '0', '1', '0', 'down', 5]]
I want to be able to find the following from that list:
o = ['1', '0', '1', '0', '1', '0']
u = "up"
y = "down
... | how to search for a list in a list of lists in python | I have this list:
t = [['1', '0', '1', '0', '0', '0', 'up', 5], ['1', '0', '1', '0', '0', '1', 'up', 5], ['1', '0', '1', '0', '1', '0', 'down', 5]]
I want to be able to find the following from that list:
o = ['1', '0', '1', '0', '1', '0']
u = "up"
y = "down
to make it clearer, i want to find out if o exists in t, a... | [
"When you use in, Python will check if the entire object in an element of the list, whereas you are only searching for an element that begin with o.\nYou could for instance do something like :\nmatching_sub_list = None\nfor sub_list in t:\n if sub_list[:len(o)] == o: # Check if the first elements of sub_list are... | [
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074562764_list_python.txt |
Q:
How to create a decorator that can be used either with or without parameters?
I'd like to create a Python decorator that can be used either with parameters:
@redirect_output("somewhere.log")
def foo():
....
or without them (for instance to redirect the output to stderr by default):
@redirect_output
def foo():... | How to create a decorator that can be used either with or without parameters? | I'd like to create a Python decorator that can be used either with parameters:
@redirect_output("somewhere.log")
def foo():
....
or without them (for instance to redirect the output to stderr by default):
@redirect_output
def foo():
....
Is that at all possible?
Note that I'm not looking for a different solut... | [
"I know this question is old, but some of the comments are new, and while all of the viable solutions are essentially the same, most of them aren't very clean or easy to read.\nLike thobe's answer says, the only way to handle both cases is to check for both scenarios. The easiest way is simply to check to see if t... | [
98,
37,
31,
17,
13,
8,
3,
2,
2,
1,
1,
0
] | [
"Have you tried keyword arguments with default values? Something like\ndef decorate_something(foo=bar, baz=quux):\n pass\n\n",
"Generally you can give default arguments in Python...\ndef redirect_output(fn, output = stderr):\n # whatever\n\nNot sure if that works with decorators as well, though. I don't kno... | [
-2,
-3,
-3
] | [
"decorator",
"python"
] | stackoverflow_0000653368_decorator_python.txt |
Q:
How to only fetch ned rows from a database in SQL? How to only insert rows that are not already in the database?
I have two problems that are fairly similar. I am using Python to deal with SQL databases.
First, I want to only fetch the new data from a SQL database (that continously gets updated with new entries). ... | How to only fetch ned rows from a database in SQL? How to only insert rows that are not already in the database? | I have two problems that are fairly similar. I am using Python to deal with SQL databases.
First, I want to only fetch the new data from a SQL database (that continously gets updated with new entries). If I have already selected that entire row I don't want it again, just get the new ones. The code I have right now is:... | [
"I'll try to help you\nWhat I'm suggesting is to add a column integer in your Table that you can name as STATUS, and initialize it at value 0..\nThen you will add a \"WHERE\" condition like : \"WHERE STATUS = 0\"\nThen you'll UPDATE the selected row at STATUS = 1 (you should do it inside the transition)\nIf you can... | [
0
] | [] | [] | [
"mariadb",
"python",
"sql"
] | stackoverflow_0074561903_mariadb_python_sql.txt |
Q:
Modify rows between two flags (values) in dataframe columns
I want to create a new dataframe with the same shape based on two existing dataframes. I have one dataframe that represents the flags and another one with the values I want to replace.
The flag dataframe has only 1, -1 and NaNs, and always after a 1 I'll ... | Modify rows between two flags (values) in dataframe columns | I want to create a new dataframe with the same shape based on two existing dataframes. I have one dataframe that represents the flags and another one with the values I want to replace.
The flag dataframe has only 1, -1 and NaNs, and always after a 1 I'll have a -1. So basically its a "changing state" kind of dataframe.... | [
"I would use a custom function:\ndef process(s, ref=flag):\n f = ref[s.name] # get matching flag\n\n # create group and mask data outside of 1 -> -1\n m = (f.map({1: True, -1: False}).ffill()\n | f.eq(-1)\n )\n group = f.eq(1).cumsum().where(m)\n\n # transform to mean\n return s.gro... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074562881_dataframe_pandas_python.txt |
Q:
how do i add an image to my tk window and make it automatically rezize the window to the image size
i have no idea how to add images to the window and i have very little experience with python/coding in general
this is the code im currently using and this works to color it but idk how to make it a picture and afte... | how do i add an image to my tk window and make it automatically rezize the window to the image size | i have no idea how to add images to the window and i have very little experience with python/coding in general
this is the code im currently using and this works to color it but idk how to make it a picture and after 30 mins of searching on google i couldnt figure it out
import random
from time import sleep
from tkinte... | [
"To add an image to the window, you can use PhotoImage() to load supported image (PNG, GIF), then using a Label to show the image:\n...\nclass Window(Tk):\n def __init__(self):\n Tk.__init__(self)\n self.width = w\n self.height = h\n self.velx = x\n self.vely = y\n self.... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074562651_python_tkinter.txt |
Q:
Making rows NaN based on many conditions
If I have a dataframe with some index and some value as follows:
import pandas as pd
from random import random
my_index = []
my_vals = []
for i in range(1000):
my_index.append(i+random())
my_vals.append(random())
df_vals = pd.DataFrame({'my_index': my_index, 'my_v... | Making rows NaN based on many conditions | If I have a dataframe with some index and some value as follows:
import pandas as pd
from random import random
my_index = []
my_vals = []
for i in range(1000):
my_index.append(i+random())
my_vals.append(random())
df_vals = pd.DataFrame({'my_index': my_index, 'my_vals': my_vals})
And I have a second dataframe... | [
"One way would be to create an array that would include all the values of your intervals, for example when start = 1 and end = 4, the array would be [1,2,3,4]. Similarly when start = 7 and end = 34, the array would be [7,8,9,10 ... , 34].\nintervals_exp = df_intervals.apply(lambda row: [n for n in range(row['start'... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074562700_dataframe_pandas_python.txt |
Q:
TypeError: __init__() got an unexpected keyword argument 'mapbox_key'
everyone !
I'm trying to understand how to make maps with PyDeck, but i have a recurring error message : " TypeError: init() got an unexpected keyword argument 'mapbox_key'".
After hours, I don't know how to resolve it ? have you any idea ?
code... | TypeError: __init__() got an unexpected keyword argument 'mapbox_key' | everyone !
I'm trying to understand how to make maps with PyDeck, but i have a recurring error message : " TypeError: init() got an unexpected keyword argument 'mapbox_key'".
After hours, I don't know how to resolve it ? have you any idea ?
code :
Python 3.9.12
version de Pydeck : 0.8.0
version de pandas: 1.4.2
versi... | [
"According to the documentation pdk.Deck doesn't take a mapbox_key argument.\nYou probably need to provide it like this:\narc_layer_map = pdk.Deck(...\n api_keys={'mapbox': MAPBOX_API_KEY})\n\n"
] | [
0
] | [] | [] | [
"mapping",
"pydeck",
"python"
] | stackoverflow_0074559302_mapping_pydeck_python.txt |
Q:
How to add missing paragraph into HTML code?
I would like to add a missing paragraph tag <p></p> in a broken HTML code.
Example: this is my broken HTML code:
<strong>My Headline</strong>
This text has a missing paragraph
<strong>Some more text <a href="#">maybe with a link</a></strong>
<p>this one is right</p>
I'... | How to add missing paragraph into HTML code? | I would like to add a missing paragraph tag <p></p> in a broken HTML code.
Example: this is my broken HTML code:
<strong>My Headline</strong>
This text has a missing paragraph
<strong>Some more text <a href="#">maybe with a link</a></strong>
<p>this one is right</p>
I'd like to add the missing paragraph tags like this... | [
"You can use methods of the str class for that.\nSomething like this:\n>>> s = '''<strong>My Headline</strong>\n... This text has a missing paragraph\n... <strong>Some more text <a href=\"#\">maybe with a link</a></strong>\n... <p>this one is right</p>'''\n>>> \n>>> for line in s.splitlines():\n... print(f'<p>{... | [
1,
0
] | [] | [] | [
"python",
"regexp_replace"
] | stackoverflow_0074562932_python_regexp_replace.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.