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:
Converting value from Pyspark Row datetime.date to yyyy-mm-dd
I am trying to fetch data from a table that returns a list of Row datetime.date objects. I would like to have them as a list of Varchar/String values.
query = "select device_date from device where device is not null"
res = spark.sql(query).collect()
if... | Converting value from Pyspark Row datetime.date to yyyy-mm-dd | I am trying to fetch data from a table that returns a list of Row datetime.date objects. I would like to have them as a list of Varchar/String values.
query = "select device_date from device where device is not null"
res = spark.sql(query).collect()
if len(res) != 0:
return res[:20]
The returned value seems to be... | [
"Are you sure you want to collect your data and then have to process them using python ?\nWith df = spark.sql(query), depending on the answer :\nYES (python solution)\nout = df.collect()\n\nlist(map(lambda x: datetime.datetime.strftime(x.device_date, \"%Y-%m-%d\"), out))\n\n['2019-09-25', '2019-09-17', '2020-01-08'... | [
2,
1
] | [] | [] | [
"apache_spark",
"pyspark",
"python"
] | stackoverflow_0074645031_apache_spark_pyspark_python.txt |
Q:
Building Tree Structure from a list of string paths
I have a list of paths as in
paths = ["x1/x2", "x1/x2/x3", "x1/x4", "x1/x5/x6", ...]
where the actual length of the list if roughly 20,000. I want to construct a tree structure that can be printed. The tree structure would look something like this:
x1
├── x2
│ ... | Building Tree Structure from a list of string paths | I have a list of paths as in
paths = ["x1/x2", "x1/x2/x3", "x1/x4", "x1/x5/x6", ...]
where the actual length of the list if roughly 20,000. I want to construct a tree structure that can be printed. The tree structure would look something like this:
x1
├── x2
│ └── x3
├── x4
└── x5
└── x6
I also want to have som... | [
"If I understand your question correctly, one possible solution might be like this.\nThe tree nodes store their parents in order to construct the messy ├───\nand └─── before directory/file names.\nOutput:\nx1\n├── x2\n│ └── x3\n├── x4\n└── x5\n └── x6\n\nCode:\nclass TreeNode:\n def __init__(self, name, par... | [
1,
0
] | [] | [] | [
"python",
"tree"
] | stackoverflow_0066994282_python_tree.txt |
Q:
Divide quantities in order to get one quantity per row - python
I have a dataframe with quantities and prices. I would like to get an dataframe with same prices vs quantity but only one quantity per line.
Dataframe:
Name | qty | Price
Apple | 3 | 3.50
Avocado | 2 | 1.50
Expected Output:
Name | qty| Price
Apple | ... | Divide quantities in order to get one quantity per row - python | I have a dataframe with quantities and prices. I would like to get an dataframe with same prices vs quantity but only one quantity per line.
Dataframe:
Name | qty | Price
Apple | 3 | 3.50
Avocado | 2 | 1.50
Expected Output:
Name | qty| Price
Apple | 1 | 3.50
Apple | 1 | 3.50
Apple | 1 | 3.50
Avocado | 1 | 1.50
Avocad... | [
"We can use df.index.repeat, then set the qty to 1 for all rows.\ndf = df.loc[df.index.repeat(df['qty'])].reset_index(drop=True)\ndf['qty'] = 1\n\nOutput:\n Name qty Price\n0 Apple 1 3.5\n1 Apple 1 3.5\n2 Apple 1 3.5\n3 Avocado 1 1.5\n4 Avocado 1 1.5\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"division",
"python"
] | stackoverflow_0074645144_dataframe_division_python.txt |
Q:
How do I do CRUD operations on a MySQL database using python via a class implementation?
I have a MySQL database running on local machine, and I am able to read and write using MySQLConnector library.
I have standalone read and write methods which are working just fine, I just wanted to clean things up a bit and w... | How do I do CRUD operations on a MySQL database using python via a class implementation? | I have a MySQL database running on local machine, and I am able to read and write using MySQLConnector library.
I have standalone read and write methods which are working just fine, I just wanted to clean things up a bit and wanted to have all my CRUD operations be part of some class DatabaseOperations. I keep on getti... | [
"I do see you are defining db_cursor = self.db_connection inside the readFromDatabase() class method, so you are attempting to use a connection object as a cursor object (you are getting the error because of it when running db_cursor.execute(...)).\nBased on your code the right definition would be:\n# reference: ht... | [
2
] | [] | [] | [
"attributeerror",
"mysql",
"mysql_connector_python",
"python"
] | stackoverflow_0074643379_attributeerror_mysql_mysql_connector_python_python.txt |
Q:
Is there a way to stop detecting part of a word in a different word?
Sorry if the title is a little confusing, I'll do my best to explain further here!
I'm setting up a Discord bot and ran into an interesting issue. Our bot is called Ed and we always call his name when wanting something from him, however, I realis... | Is there a way to stop detecting part of a word in a different word? | Sorry if the title is a little confusing, I'll do my best to explain further here!
I'm setting up a Discord bot and ran into an interesting issue. Our bot is called Ed and we always call his name when wanting something from him, however, I realised that since the word need has ed in it, we can accidentally call some of... | [
"I suppose positive.content.lower() is a sentence or a paragraph.\nSo why don't we split it for every space with:\nword_list = (positive.content.lower() + \" \").split(\" \")\nif \"ed\" in word_list and \"positivity\" in word_list:\n await positive.channel.send(random.choice(positivity))\n\nThe added space at th... | [
0
] | [] | [] | [
"detection",
"discord",
"list",
"python",
"string"
] | stackoverflow_0074643554_detection_discord_list_python_string.txt |
Q:
How to stock value from tkinter in an efficient way?
I have some problems with tkinter. I want to ask for some values and stock those values. I found some code about get() method but here are my questions:
Here is code:
`
from tkinter import*
window= Tk()
window.geometry("300x300")
#1)
def getEntry():
result=... | How to stock value from tkinter in an efficient way? | I have some problems with tkinter. I want to ask for some values and stock those values. I found some code about get() method but here are my questions:
Here is code:
`
from tkinter import*
window= Tk()
window.geometry("300x300")
#1)
def getEntry():
result= a.get()
print(result)
a = Spinbox(window, from_=0, t... | [
"1-There is a way to call same function for multiple widgets. That is by using lambda you pass widget itself to function.\n2-As you call it from button call, there is no where to return the value. you can use global variables which is not adviced, or you can use classes.\n3-Listboxes like treeviews, has some major ... | [
0
] | [] | [] | [
"get",
"python",
"tkinter"
] | stackoverflow_0074642247_get_python_tkinter.txt |
Q:
is there a way to pass parameter of flask api to my python code
hello am trying to create flask api where user input the vaue and I will use that value to process my python code
here is the code
`
app = Flask(__name__)
api = Api(app)
class Users(Resource):
@app.route('/users/<string:name>/')
def hello(nam... | is there a way to pass parameter of flask api to my python code | hello am trying to create flask api where user input the vaue and I will use that value to process my python code
here is the code
`
app = Flask(__name__)
api = Api(app)
class Users(Resource):
@app.route('/users/<string:name>/')
def hello(name):
namesource = request.args.get('name')
return "Hel... | [
"You are trying to access the variable namesource outside of the function hello.\nYou can't do that.\nYou can access the variable name outside of the function hello because it is a parameter of the function. You can fix it by making a global variable.\napp = Flask(__name__)\napi = Api(app)\n\nnamesource = None\n\nc... | [
1
] | [] | [] | [
"api",
"flask",
"python"
] | stackoverflow_0074645094_api_flask_python.txt |
Q:
overwriting dataframes in pandas
I have a given dataframe
new_df :
ID
summary
text_len
1
xxx
45
2
aaa
34
I am performing some df manipulation by concatenating keywords from different df, like that:
keywords = df["keyword"].to_list()
for key in keywords:
new_df[key] = new_df["summary"].str.lower().str.count... | overwriting dataframes in pandas | I have a given dataframe
new_df :
ID
summary
text_len
1
xxx
45
2
aaa
34
I am performing some df manipulation by concatenating keywords from different df, like that:
keywords = df["keyword"].to_list()
for key in keywords:
new_df[key] = new_df["summary"].str.lower().str.count(key)
new_df
from here I ne... | [
"You may use pandas' copy method with the deep argument set to True:\ndf_freq = new_df.copy(deep=True)\n\nSetting deep=True (which is the default parameter) ensures that modifications to the data or indices of the copy do not impact the original dataframe.\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074645187_dataframe_pandas_python.txt |
Q:
Why is my test suite not recognising my test case?
I am practicing creating my own testing framework on Pycharm in Python with Selenium. However, for some reason the suite is failing to initiate pytest and recognise my test case, I am not sure where I have gone wrong, I usually dont have this problem, and I have m... | Why is my test suite not recognising my test case? | I am practicing creating my own testing framework on Pycharm in Python with Selenium. However, for some reason the suite is failing to initiate pytest and recognise my test case, I am not sure where I have gone wrong, I usually dont have this problem, and I have marked the test case with test_.
import pytest
from selen... | [
"By default, PyTest expects test classes to be named like SomethingTest and modules like test_something. You can fine-tune the test discovery process as described here: Changing standard (Python) test discovery\n",
"There are various naming conventions to follow\n\nFile name: Should start with test_\nClass name: ... | [
0,
0
] | [] | [] | [
"pycharm",
"pytest",
"python",
"selenium_webdriver"
] | stackoverflow_0074643456_pycharm_pytest_python_selenium_webdriver.txt |
Q:
How can I reset/revert a string back to its orginal form after mutating it
Alright, so I want to reset a word after I have to change/mutated it without the reset method taking any parameters. Reset() should revert the text after the use() method is used. Is there any way of doing this?
Class words
def __init__(se... | How can I reset/revert a string back to its orginal form after mutating it | Alright, so I want to reset a word after I have to change/mutated it without the reset method taking any parameters. Reset() should revert the text after the use() method is used. Is there any way of doing this?
Class words
def __init__(self, text):
self.text = text
def use(self): # sets the text ... | [
"I may be way out of line but... why don't you just copy it?\nClass words\n\ndef __init__(self, text):\n self.text = text\n self.original = text\n \n def use(self): # sets the text as an empty string\n self.text = \"\"\n\n def reset(self): # revert empty string back to the original... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074645238_python.txt |
Q:
FashionMNIST Dataset not transforming to Tensor
Trying to calculate the mean and standard deviation of the dataset to normalise it afterwards.
Current Code:
train_dataset = datasets.FashionMNIST('data', train=True, download = True, transform=[transforms.ToTensor()])
test_dataset = datasets.FashionMNIST('data', tra... | FashionMNIST Dataset not transforming to Tensor | Trying to calculate the mean and standard deviation of the dataset to normalise it afterwards.
Current Code:
train_dataset = datasets.FashionMNIST('data', train=True, download = True, transform=[transforms.ToTensor()])
test_dataset = datasets.FashionMNIST('data', train=False, download = True, transform=[transforms.ToTe... | [
"datasets.FashionMNIST returns (image, target) where target is index of the target class. So if you want to take the mean you need to extract just the image.\nimages = torch.vstack([pair[0] for pair in train_dataset])\n\nimages should now be of shape (N, H, W) and you can do whatever you want from there.\nAnother s... | [
1
] | [] | [] | [
"mnist",
"python",
"pytorch",
"tensor",
"torchvision"
] | stackoverflow_0074644993_mnist_python_pytorch_tensor_torchvision.txt |
Q:
Rearrange dataframe values
Let's say I have the following dataframe:
ID stop x y z
0 202 9 20 27 4
1 202 2 23 24 13
2 1756 5 5 41 73
3 17... | Rearrange dataframe values | Let's say I have the following dataframe:
ID stop x y z
0 202 9 20 27 4
1 202 2 23 24 13
2 1756 5 5 41 73
3 1756 3 7 ... | [
"You can use pd.Series.rank with method='dense'\ndf['ID'] = df['ID'].rank(method='dense').astype(int)\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074645184_dataframe_pandas_python.txt |
Q:
Read entry in a string array into a dictionary object
I have a string stored in: reviewers_list
I want to iterate through it and create a new list of dictionaries called reviewer_dicts
reviewers_dicts = {}
for i in reviewers_list:
reviewers_dicts.append(i)
print(reviewers_dict)
I have tried this so far
A:
M... | Read entry in a string array into a dictionary object | I have a string stored in: reviewers_list
I want to iterate through it and create a new list of dictionaries called reviewer_dicts
reviewers_dicts = {}
for i in reviewers_list:
reviewers_dicts.append(i)
print(reviewers_dict)
I have tried this so far
| [
"Many things to talk about.\nFirst you are making a dictionary, here, not a list of dictionaries.\nSecondly, a dictionary is made up of key-value pairs, not single values.\nSo for your example, if we wanted the keys to be i and the values to be empty strings we'd do like so:\nreviewers_dicts = {}\nfor i in reviewer... | [
0
] | [] | [] | [
"dictionary",
"iteration",
"python"
] | stackoverflow_0074643501_dictionary_iteration_python.txt |
Q:
How to save model output/predictions
I have trained a model. Now I want to export it's output which is type (str). How I can I save it's output results in a dataframe or any other form that I can use for future purpose.
gf = df['findings'].astype(str)
preprocess_text = gf.str.strip().replace("\n","")
t5_prepared... | How to save model output/predictions | I have trained a model. Now I want to export it's output which is type (str). How I can I save it's output results in a dataframe or any other form that I can use for future purpose.
gf = df['findings'].astype(str)
preprocess_text = gf.str.strip().replace("\n","")
t5_prepared_Text = "summarize: "+preprocess_text prin... | [
"Just replace this\nprediction = pd.DataFrame([text]).to_csv('prediction.csv')\n\nWith this\nprediction = pd.DataFrame([text]).to_csv('prediction.csv', sep=\";\")\n\n"
] | [
3
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074623438_keras_python_tensorflow.txt |
Q:
How to write str (byte) from Cloudmersive API response to PDF file without file corruption
I'm currently working to convert several different file formats (.csv, .xlsx, .docx, .one) to .pdf output using the Cloudmersive API (https://api.cloudmersive.com/docs/convert.asp). Their documentation does not detail the ty... | How to write str (byte) from Cloudmersive API response to PDF file without file corruption | I'm currently working to convert several different file formats (.csv, .xlsx, .docx, .one) to .pdf output using the Cloudmersive API (https://api.cloudmersive.com/docs/convert.asp). Their documentation does not detail the type of encoding from the API_response during the conversion. I've tried several different approac... | [
"The following code worked as suggested in the comments:\nimport ast\n\n# create an instance of the API class\napi_instance = cloudmersive_convert_api_client.ConvertDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))\n\n# Convert Document to PDF\nif (os.stat(input_file).st_size != 0): #api does no... | [
0
] | [] | [] | [
"api",
"arrays",
"character_encoding",
"pdf_generation",
"python"
] | stackoverflow_0074633253_api_arrays_character_encoding_pdf_generation_python.txt |
Q:
Extract a substring from a path
I would like to extract two parts of the string (path).
In particular, I would like to have the part a = "fds89gsa8asdfas0sgfsaajajgsf6shjksa6" and the part b = "arc-D41234".
path = "//users/ftac/tref/arc-D41234/fds89gsa8asdfas0sgfsaajajgsf6shjksa6"
a = path[-36:]
b = path[-47:-37]
... | Extract a substring from a path | I would like to extract two parts of the string (path).
In particular, I would like to have the part a = "fds89gsa8asdfas0sgfsaajajgsf6shjksa6" and the part b = "arc-D41234".
path = "//users/ftac/tref/arc-D41234/fds89gsa8asdfas0sgfsaajajgsf6shjksa6"
a = path[-36:]
b = path[-47:-37]
I tried with slicing and was fine, t... | [
"You need to split the path like:\na = path.split('/')[-1]\nb = path.split('/')[-2]\n\n"
] | [
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074645396_python_string.txt |
Q:
Regular expression to extract text in python
I am new using the re library and I would like to know if somebody knows how to extract the following text:
Initial
'[p]I am a test paragraph[/p]'
Output
I am a test paragraph
I tried to use the following line :
text = '[p]I am a test paragraph[/p]'
param = re.findall... | Regular expression to extract text in python | I am new using the re library and I would like to know if somebody knows how to extract the following text:
Initial
'[p]I am a test paragraph[/p]'
Output
I am a test paragraph
I tried to use the following line :
text = '[p]I am a test paragraph[/p]'
param = re.findall("[p](.*?)[/p]]", text)
but the output was :
>>['... | [
"# regex to extract text between [p] and [/p] tags\nregex = r'\\[p\\](.*?)\\[/p\\]'\ntest_text = '[p]I am a test paragraph[/p]'\n\n# extract text between [p] and [/p] tags\nlist_of_results = re.findall(regex, test_text)\n\n",
"import re\ntext = '[p]I am a test paragraph[/p]'\nparm = re.findall(r'\\[p](.*?)\\[/p]'... | [
0,
0
] | [] | [] | [
"bbcode",
"python",
"regex"
] | stackoverflow_0074645253_bbcode_python_regex.txt |
Q:
a code to input three user-provided statements and solve the questions
A code to input three user-provided statements. Is there any information in the title case?
Total the letters to determine the number. Count up all of the words. What number of words begin with "e"? How many words have "er" at the end? The numb... | a code to input three user-provided statements and solve the questions | A code to input three user-provided statements. Is there any information in the title case?
Total the letters to determine the number. Count up all of the words. What number of words begin with "e"? How many words have "er" at the end? The number of vowels in each of these sentences. Do the statements include any digit... | [] | [] | [
"a = input(\"First statement : \")\nb = input(\"Second statement : \")\nc = input(\"Third statement : \")\nal = a.split()\nbl = b.split()\ncl = c.split()\ncounte = 0\ncounter = 0\nletter = 0\nbll = \"\"\nvowels = 0\nans = 0\nansb = 0\nansc = 0\nprint(f\"The words in first statement is {len(al)}\")\nprint(f\"The wor... | [
-1
] | [
"python"
] | stackoverflow_0074645170_python.txt |
Q:
Nested Dictionary (JSON): Merge multiple keys stored in a list to access its value from the dict
I have a JSON with an unknown number of keys & values, I need to store the user's selection in a list & then access the selected key's value; (it'll be guaranteed that the keys in the list are always stored in the corr... | Nested Dictionary (JSON): Merge multiple keys stored in a list to access its value from the dict | I have a JSON with an unknown number of keys & values, I need to store the user's selection in a list & then access the selected key's value; (it'll be guaranteed that the keys in the list are always stored in the correct sequence).
Example
I need to access the value_key1-2.
mydict = {
'key1': {
'key1-1': {... | [
"You have to loop the list of keys and update the \"current value\" on each step.\nval = mydict\n\ntry:\n for key in Uselection:\n val = val[key]\nexcept KeyError:\n handle non-existing keys here\n\nAnother, more 'posh' way to do the same (not generally recommended):\nfrom functools import reduce\n\nva... | [
3
] | [] | [] | [
"dictionary",
"json",
"python"
] | stackoverflow_0074645351_dictionary_json_python.txt |
Q:
Could not find a version that satisfies the requirement torch>=1.0.0?
Could not find a version that satisfies the requirement torch>=1.0.0
No matching distribution found for torch>=1.0.0 (from stanfordnlp)
A:
This can also happen if your Python version is too new. Pytorch currently does not support past 3.7.9.
... | Could not find a version that satisfies the requirement torch>=1.0.0? | Could not find a version that satisfies the requirement torch>=1.0.0
No matching distribution found for torch>=1.0.0 (from stanfordnlp)
| [
"This can also happen if your Python version is too new. Pytorch currently does not support past 3.7.9.\nFigured out from: https://stackoverflow.com/a/58902298/5090928\n",
"This is the latest command for pytorch.\npip install torch===1.4.0 torchvision===0.5.0 -f https://download.pytorch.org/whl/torch_stable.html\... | [
78,
44,
13,
10,
5,
2,
2,
1,
1,
1,
0,
0,
0,
0,
0
] | [
"follow the link: https://pytorch.org/\nand set your system requirement in QUICK START LOCALLY SECTION\n\n"
] | [
-4
] | [
"python"
] | stackoverflow_0056239310_python.txt |
Q:
Problem to connect the django with mongodb using djongo
How i use
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'rede_social',
'HOST': 'mongodb+srv://blackwolf449:3CErLxvGLPM4rLsK@cluster0.w1ucl2e.mongodb.net/?retryWrites=true&w=majority',
'USER': 'blackwolf449',
... | Problem to connect the django with mongodb using djongo | How i use
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'rede_social',
'HOST': 'mongodb+srv://blackwolf449:3CErLxvGLPM4rLsK@cluster0.w1ucl2e.mongodb.net/?retryWrites=true&w=majority',
'USER': 'blackwolf449',
'PASSWORD': '3CErLxvGLPM4rLsK'
}
}
Error
django.core.... | [
"downgrade your django version to 3.0.5\n",
"I had the same problem, I fixed it by installing Pytz.\nDo :\n\npip install pytz\n\n"
] | [
0,
0
] | [] | [] | [
"django",
"djongo",
"python"
] | stackoverflow_0073016836_django_djongo_python.txt |
Q:
Flask testing routes - not registered
I've a very basic Flask application:
#main.py
from flask import Flask
app = Flask(__name__)
@app.route('/sth/')
def hi():
return 'HI\n'
and I try to test the existence of the url, however, to me it seems the routes are not registered:
#tests/test_view.py
from flask impo... | Flask testing routes - not registered | I've a very basic Flask application:
#main.py
from flask import Flask
app = Flask(__name__)
@app.route('/sth/')
def hi():
return 'HI\n'
and I try to test the existence of the url, however, to me it seems the routes are not registered:
#tests/test_view.py
from flask import Flask
class TestSthView:
def test_s... | [
"#main.py\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/sth/')\ndef hi():\n return 'HI\\n'\n\nif __name__ == \"__main__\":\n app.run()\n\nIn another terminal you do an easy request e.g.\nimport requests\n\nr = requests.get('http://127.0.0.1:5000/sth/')\n\nassert r.status_code == 200\n\nOr y... | [
1,
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074645353_flask_python.txt |
Q:
I'm trying to make a for loop but it did not work (A little bit complex)
So I'm trying to make a 'for' loop In my discord bot. But It giving me errors in whatever I try.
The loop is for the embed.add_field function, Here's what I tried:
for i in netres:
embed.add_field(name=f"Email: {netres[0][i[0]]}", value=f"P... | I'm trying to make a for loop but it did not work (A little bit complex) | So I'm trying to make a 'for' loop In my discord bot. But It giving me errors in whatever I try.
The loop is for the embed.add_field function, Here's what I tried:
for i in netres:
embed.add_field(name=f"Email: {netres[0][i[0]]}", value=f"Password: {netres[1][i]}", inline=False)
if it can Help, netres = a c.fetchall... | [
"You just need to make the elements of tuples either an integer or slices. (if your requirement is string)\n"
] | [
0
] | [] | [] | [
"discord.py",
"pycord",
"python",
"python_3.x",
"sqlite"
] | stackoverflow_0074645325_discord.py_pycord_python_python_3.x_sqlite.txt |
Q:
Cannot import Tensorflow - Apple Macbook M1
I'm trying to use tensorflow, but I can't import it.
I followed the steps on the Apple website to download and install Tensorflow, and everything appears to be ok, but when I try to import tensorflow, I get some errors. What should I do?
Errors:
TypeError: Unable to conv... | Cannot import Tensorflow - Apple Macbook M1 | I'm trying to use tensorflow, but I can't import it.
I followed the steps on the Apple website to download and install Tensorflow, and everything appears to be ok, but when I try to import tensorflow, I get some errors. What should I do?
Errors:
TypeError: Unable to convert function return value to a Python type! The s... | [
"python -m pip install tensorflow-macos==2.9.0\nApple has not updated tensorflow-deps to 2.10 now.\n"
] | [
0
] | [] | [] | [
"apple_m1",
"macos",
"miniconda",
"python",
"tensorflow"
] | stackoverflow_0074309572_apple_m1_macos_miniconda_python_tensorflow.txt |
Q:
Replace value in column based on multiple conditions in Pandas
I have this dataframe
df = pd.DataFrame.from_dict(
{
'Name': ['Jane', 'Melissa', 'John', 'Matt'],
'Age': [23, 45, 35, 64],
'Birth City': ['London', 'Paris', 'Toronto', 'Atlanta'],
'Gender': ['F', 'F', 'M', 'M']
}... | Replace value in column based on multiple conditions in Pandas | I have this dataframe
df = pd.DataFrame.from_dict(
{
'Name': ['Jane', 'Melissa', 'John', 'Matt'],
'Age': [23, 45, 35, 64],
'Birth City': ['London', 'Paris', 'Toronto', 'Atlanta'],
'Gender': ['F', 'F', 'M', 'M']
}
)
and I want to replace the Gender to X, when the name is Melissa ... | [
"Here is my solution:\ndf.loc[((df['Name'] == 'Melissa') | (df['Name'] == 'John')), 'Gender'] = 'X'\n\nAnd output\n Name Age Birth City Gender\n0 Jane 23 London F\n1 Melissa 45 Paris X\n2 John 35 Toronto X\n3 Matt 64 Atlanta M\n\n",
"A possible solutio... | [
3,
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074645373_pandas_python.txt |
Q:
Splitting a large CSV file and converting into multiple Parquet files - Safe?
I learnt, the parquet file format stores a bunch of metadata and uses various compressions to store data in an efficient way, when it comes to size and query-speed.
And it possibly generates multiple files out of, let's say: one input, l... | Splitting a large CSV file and converting into multiple Parquet files - Safe? | I learnt, the parquet file format stores a bunch of metadata and uses various compressions to store data in an efficient way, when it comes to size and query-speed.
And it possibly generates multiple files out of, let's say: one input, like from a Panda dataframe.
Now, I have a large CSV file and I want to convert it i... | [
"When creating a parquet dataset with Mutiple files, All the files should have matching schema. In your case, when you split the csv file into Mutiple parquet files, you will have to include the csv headers in each chunk to create a valid parquet file.\nNote that parquet is a compressed format (with a high compress... | [
2,
1
] | [] | [] | [
"csv",
"parquet",
"python"
] | stackoverflow_0074618182_csv_parquet_python.txt |
Q:
open-cv installation in docker image does not work on raspberry pi
I have created python project with some dependencies, among them open-cv. Now I want to deploy my project in a docker image. For this, I created the following build-file on my local machine (running Ubuntu 22.04):
# syntax=docker/dockerfile:1
FROM... | open-cv installation in docker image does not work on raspberry pi | I have created python project with some dependencies, among them open-cv. Now I want to deploy my project in a docker image. For this, I created the following build-file on my local machine (running Ubuntu 22.04):
# syntax=docker/dockerfile:1
FROM python:3.8-slim-buster
WORKDIR /app
COPY requirements.txt .
COPY main... | [
"I solved this by updating the Raspberry Pi to a 64-Bit installation.\n"
] | [
0
] | [] | [] | [
"docker",
"opencv",
"python",
"raspberry_pi"
] | stackoverflow_0074601849_docker_opencv_python_raspberry_pi.txt |
Q:
How to monitor a aws-python based application using APM tool?
I want to know if there's any way I can monitor my application using one of the open-source application monitoring (APM) tools. I don't have much knowledge about them, and got pretty confused when I searched for this, so asking it here. I tried SigNoz b... | How to monitor a aws-python based application using APM tool? | I want to know if there's any way I can monitor my application using one of the open-source application monitoring (APM) tools. I don't have much knowledge about them, and got pretty confused when I searched for this, so asking it here. I tried SigNoz but it's not for windows and I work on windows os. I am looking for ... | [
"Sure thing! We have docs available for the Elastic APM Python Agent. Just add elastic-apm to your requirements.txt and then follow the onboarding instructions for whichever framework you're using. Our agent and the Elastic Stack are both fully open source.\nYou can also start a no-credit-card-required trial with E... | [
0
] | [] | [] | [
"amazon_web_services",
"elastic_apm",
"monitor",
"performance",
"python"
] | stackoverflow_0074636397_amazon_web_services_elastic_apm_monitor_performance_python.txt |
Q:
VSCode displays "Module numpy could not be resolved"
I have just installed VS Code and trying to run python code. In the past, I had already created some virtual environments (which I am able to see in VS Code), but for the moment I am using the base one.
I am trying to import some standard libraries which are pre... | VSCode displays "Module numpy could not be resolved" | I have just installed VS Code and trying to run python code. In the past, I had already created some virtual environments (which I am able to see in VS Code), but for the moment I am using the base one.
I am trying to import some standard libraries which are present in the base environment (I tried also the conda envir... | [
"Try to add path to environment variable.\n\nC:\\Users\\username\\AppData\\Local\\Programs\\Microsoft VS Code\\bin\n\ncheck the path of your VS Code bin folder\n"
] | [
0
] | [] | [] | [
"conda",
"path",
"python",
"visual_studio_code"
] | stackoverflow_0074645405_conda_path_python_visual_studio_code.txt |
Q:
Python: How to prevent a randomly generated number from appearing twice
import random
import time
import sys
x = input("Put a number between 1 and 100: ")
z = int(x)
if z < (0):
sys.exit("Number too small")
if z > (100):
sys.exit("Number too big")
y = random.randint(1, 100)
while y != z:
print("tryin... | Python: How to prevent a randomly generated number from appearing twice | import random
import time
import sys
x = input("Put a number between 1 and 100: ")
z = int(x)
if z < (0):
sys.exit("Number too small")
if z > (100):
sys.exit("Number too big")
y = random.randint(1, 100)
while y != z:
print("trying again, number was", y)
time.sleep(0.2)
y = random.randint(1, 100)
p... | [
"Try using random.sample() which samples without replacement:\n>>> import random\n>>> random.sample(range(1, 101), k=20)\n[98, 47, 29, 50, 19, 5, 97, 12, 35, 81, 13, 89, 16, 20, 71, 11, 24, 78, 56, 85]\n>>> random.sample(range(1, 101), k=20)\n[36, 41, 47, 69, 57, 98, 73, 54, 89, 86, 8, 79, 38, 17, 90, 65, 78, 30, 7... | [
0
] | [] | [] | [
"list",
"numbers",
"python",
"random"
] | stackoverflow_0074645603_list_numbers_python_random.txt |
Q:
You are trying to merge on datetime64[ns, UTC] and datetime64[ns] columns. If you wish to proceed you should use pd.concat
I'm running into an interesting issue. I've recreated the issue as best I can and am reproducing the same error. Essentially I have a script that is running through a database and collecting i... | You are trying to merge on datetime64[ns, UTC] and datetime64[ns] columns. If you wish to proceed you should use pd.concat | I'm running into an interesting issue. I've recreated the issue as best I can and am reproducing the same error. Essentially I have a script that is running through a database and collecting information on different assets that have datetime64[ns, UTC] dtypes. This script can return a dataframe with data (df1_utc) or a... | [
"Your result_tables are not timezone-aware, therefore it causes an error on merge.\nIn case you except all of your data in UTC timezone, you can change the code to this, and it will not cause an error:\n result_table = pd.DataFrame(columns=['timestamp'])\n result_table['timestamp'] = pd.to_datetime(result_tab... | [
0
] | [] | [] | [
"dataframe",
"merge",
"pandas",
"python",
"python_datetime"
] | stackoverflow_0073964894_dataframe_merge_pandas_python_python_datetime.txt |
Q:
TypeError : unsupported operand type(s) for +: 'NoneType' and 'int'
import pandas as pd
import numpy as np
import openpyxl
time = pd.ExcelFile('Block_time_JP1.xlsx')
time.head(3)
output :
Date_time Station Pending
0 28-11_15:30 DTK2 36
1 28-11_15:30 DTK2 36
2 28-11_15:30 DTK2 36
... | TypeError : unsupported operand type(s) for +: 'NoneType' and 'int' | import pandas as pd
import numpy as np
import openpyxl
time = pd.ExcelFile('Block_time_JP1.xlsx')
time.head(3)
output :
Date_time Station Pending
0 28-11_15:30 DTK2 36
1 28-11_15:30 DTK2 36
2 28-11_15:30 DTK2 36
Then --
d = [0]
b=[0]
for i in time.index:
b[0] = time['Pending'][... | [
"Let's mentally step through your code,\nb and d start as [0], one element lists.\nfor i in time.index:\n b[0] = time['Pending'][i] # I'm guessing `b` is now `[36]`\n j = d # j is d, not a copy\n k= d + b # k is [0,36] - list addition is join\n for j in k: ... | [
0
] | [] | [] | [
"list",
"loops",
"numpy",
"pandas",
"python"
] | stackoverflow_0074637934_list_loops_numpy_pandas_python.txt |
Q:
How to add second x-axis at the bottom of the first one in matplotlib.?
I am refering to the question already asked here.
In this example the users have solved the second axis problem by adding it to the upper part of the graph where it coincide with the title.
Question:
Is it possible to add the second x-axis a... | How to add second x-axis at the bottom of the first one in matplotlib.? | I am refering to the question already asked here.
In this example the users have solved the second axis problem by adding it to the upper part of the graph where it coincide with the title.
Question:
Is it possible to add the second x-axis at the bottom of the first one?
Code:
import numpy as np
import matplotlib.p... | [
"As an alternative to the answer from @DizietAsahi, you can use spines in a similar way to the matplotlib example posted here.\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nax1 = fig.add_subplot(111)\nax2 = ax1.twiny()\n\n# Add some extra space for the second axis at the bottom\nfig.su... | [
25,
6,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0031803817_matplotlib_python.txt |
Q:
How can I switch the focus between toplevels of a tkinter program?
I am using key-accelerators for menu entries in a multi window program. But when an accelerator-key is pressed, then always the same window reacts to the key.
As you can see in my example code, I tried to change the focus by binding the event "Focu... | How can I switch the focus between toplevels of a tkinter program? | I am using key-accelerators for menu entries in a multi window program. But when an accelerator-key is pressed, then always the same window reacts to the key.
As you can see in my example code, I tried to change the focus by binding the event "FocusIn" to the toplevel and to the canvas. At the event I tried focus_force... | [
"I found the problem is caused by this line from my example code above:\nself.top.bind_all(\"<Control-o>\", lambda event : self.menu())\n\nThis line always gives the last new created toplevel the binding. All previous created toplevel windows loose the binding in this moment. So this line must be removed. Instead t... | [
0
] | [] | [] | [
"focus",
"python",
"tkinter"
] | stackoverflow_0074576267_focus_python_tkinter.txt |
Q:
How many integers can fully represent a float?
The problem and my current solution:
For example, take two columns of latitude and longitude values:
lat
lon
30.1239871239
-80.1239871239
30.1239991239
-80.1439871239
I want to create integer columns that represent the floats.
This is what I currently have:
lat
l... | How many integers can fully represent a float? | The problem and my current solution:
For example, take two columns of latitude and longitude values:
lat
lon
30.1239871239
-80.1239871239
30.1239991239
-80.1439871239
I want to create integer columns that represent the floats.
This is what I currently have:
lat
lat_dec
lat_sign
30
1239871239
1
3... | [
"\nCan you make it better?\n\nOnly you know what better means.\n\ncan you reduce the size even more?\n\nYes. The way you're storing coordinates now you have a resolution of ~10μm (1e-5m). That seems excessively precise. If you can live with around a 1 meter resolution you can break up the coordinate values into inc... | [
0
] | [] | [] | [
"memory",
"numpy",
"pandas",
"python"
] | stackoverflow_0074645383_memory_numpy_pandas_python.txt |
Q:
Finding duplicates based on values of specific keys from a list of dict
I have the following list of dict records, from which I need to extract all the duplicates (based on the label) and leave one per label in the original records. Also, when the items get removed by label, always remove the one with the headings... | Finding duplicates based on values of specific keys from a list of dict | I have the following list of dict records, from which I need to extract all the duplicates (based on the label) and leave one per label in the original records. Also, when the items get removed by label, always remove the one with the headings value True over one with headings value False.
Input:
records = [
{"labe... | [
"You left a few questions unanswered (see comments). You also did not provide your own code and any unexpected output/error you got with it, so we have nothing to work with/fix. This is bad form.\nBut I found this to be a fun exercise, so here is what I came up with:\nfrom typing import TypedDict\n\n\nclass Record(... | [
0
] | [] | [] | [
"dictionary",
"duplicates",
"key",
"list",
"python"
] | stackoverflow_0074644893_dictionary_duplicates_key_list_python.txt |
Q:
How to install pyspark.pandas in Apache Spark?
I downloaded Apache Spark 3.3.0 bundle which contains pyspark
$ pyspark
Welcome to
____ __
/ __/__ ___ _____/ /__
_\ \/ _ \/ _ `/ __/ '_/
/__ / .__/\_,_/_/ /_/\_\ version 3.3.0
/_/
Using Python version 3.7.10 (default, Jun 3... | How to install pyspark.pandas in Apache Spark? | I downloaded Apache Spark 3.3.0 bundle which contains pyspark
$ pyspark
Welcome to
____ __
/ __/__ ___ _____/ /__
_\ \/ _ \/ _ `/ __/ '_/
/__ / .__/\_,_/_/ /_/\_\ version 3.3.0
/_/
Using Python version 3.7.10 (default, Jun 3 2021 00:02:01)
Spark context Web UI available at ht... | [
"Have you tried installing Pandas in the following way:\npip install pyspark[pandas_on_spark]\n\nIf the pip is not discoverable by bash, maybe try to active your Python environment first (whether virtualenv, conda or anything else).\n"
] | [
0
] | [] | [] | [
"apache_spark",
"pandas",
"pyspark",
"python"
] | stackoverflow_0074644628_apache_spark_pandas_pyspark_python.txt |
Q:
Python does not let me run files without calling the interpreter
Im running python 3.7.9 on Windows 10, I usually run files as file.py but now does not run unless I run it as python file.py
I have python included in PATH but it still doesn't work
I've tried everything, reinstalling python, makeing a new file, chan... | Python does not let me run files without calling the interpreter | Im running python 3.7.9 on Windows 10, I usually run files as file.py but now does not run unless I run it as python file.py
I have python included in PATH but it still doesn't work
I've tried everything, reinstalling python, makeing a new file, changing the path, using other python versions but nothing
| [
"Yup, it was a file association problem, thanks for the answers.\n"
] | [
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0074644987_python_windows.txt |
Q:
Running a Tkinter window and PysTray Icon together
I'm building a tkinter gui project and i'm looking for ways to run a tray icon with the tkinter window. I found Pystray library that does it, But now i'm trying to figure it out how to use this library (tray Icon) together with tkinter window,
I set it up when t... | Running a Tkinter window and PysTray Icon together | I'm building a tkinter gui project and i'm looking for ways to run a tray icon with the tkinter window. I found Pystray library that does it, But now i'm trying to figure it out how to use this library (tray Icon) together with tkinter window,
I set it up when the user exit winodw it's only will withdraw window:
sel... | [
"Finally I figure it out, \nNow I just need to combine this with my main code, I hope this code will help to other people too... \nfrom pystray import MenuItem as item\nimport pystray\nfrom PIL import Image\nimport tkinter as tk\n\nwindow = tk.Tk()\nwindow.title(\"Welcome\")\n\ndef quit_window(icon, item):\n ico... | [
25,
1
] | [] | [] | [
"python",
"systray",
"tkinter"
] | stackoverflow_0054835399_python_systray_tkinter.txt |
Q:
Asyncio file reading json
I am trying to read a json file in an async function.
I managed to find this code that works, but is rather clunky in the sense that it requires three extra parts for the file read:
import aiofiles
read the file
convert file to dict
import aiofiles
import asyncio
import json
async def ... | Asyncio file reading json | I am trying to read a json file in an async function.
I managed to find this code that works, but is rather clunky in the sense that it requires three extra parts for the file read:
import aiofiles
read the file
convert file to dict
import aiofiles
import asyncio
import json
async def main():
# Read the content... | [
"asyncio does not support asynchronous file operations, you can see the asyncio wiki for further explanation\naiofiles allows you to read files asynchronously by delegating their operations to a separate thread pool\n"
] | [
0
] | [] | [] | [
"json",
"python",
"python_asyncio"
] | stackoverflow_0074645594_json_python_python_asyncio.txt |
Q:
how to treat var in second multiprocessing.Pool when the var is from first Pool
How to treat var in second multiprocessing.Pool when the var is from first Pool?
For the example code
from multiprocessing import Pool
import pandas as pd
lst = [1, 2, 3]
def csv(code):
df = pd.DataFrame({code: [code, code**2, c... | how to treat var in second multiprocessing.Pool when the var is from first Pool | How to treat var in second multiprocessing.Pool when the var is from first Pool?
For the example code
from multiprocessing import Pool
import pandas as pd
lst = [1, 2, 3]
def csv(code):
df = pd.DataFrame({code: [code, code**2, code**3]}, index=lst)
return {code: df}
def mp1():
with Pool(8) as pool:
... | [
"At least on Windows, global variables of the main process are not available in the worker processes. The Pool class supports to call an initializer function on each worker to receive such variables (if their data can be pickled) and set them.\nHere this can be done like:\ndef initializer(ext_dfs):\n global dfs\... | [
0
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0074638071_multiprocessing_python.txt |
Q:
Why is all of my data stored as the key in JSON?
When I receive a POST request from AJAX, all of my data is stored as the key with an empty value.
Client side:
var csrftoken = $('meta[name=csrf-token]').attr('content')
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$... | Why is all of my data stored as the key in JSON? | When I receive a POST request from AJAX, all of my data is stored as the key with an empty value.
Client side:
var csrftoken = $('meta[name=csrf-token]').attr('content')
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
xhr.setRequestHe... | [
"I was able to access the value using request.form['id'] after removing the JSON.stringify() function.\nfunction post_order_items() {\n my_data = {id:{{ order.order_id }}, name:\"test\"};\n $.ajax({\n type: \"POST\",\n url: \"{{ url_for('update_order_items') }}\",\n data: my_data,\n ... | [
0
] | [] | [] | [
"ajax",
"flask",
"json",
"python"
] | stackoverflow_0074620534_ajax_flask_json_python.txt |
Q:
Swap Elements of Array in Python in One Line [Failed Memory Reference]
Given the following Array:
A = [11, 0, 9, 2, 7], I want to swap A[0] and A[3].
Expected result: A = [2, 0, 9, 11, 7].
Can someone explain why the first and the second method failed? I am suspecting this has to do with memory reference. Any thou... | Swap Elements of Array in Python in One Line [Failed Memory Reference] | Given the following Array:
A = [11, 0, 9, 2, 7], I want to swap A[0] and A[3].
Expected result: A = [2, 0, 9, 11, 7].
Can someone explain why the first and the second method failed? I am suspecting this has to do with memory reference. Any thoughts?
First Approach (FAILED)
A = [11, 0, 9, 2, 7]
print("Original:",A)
... | [
"Because in 1st and 2nd you are swapping values between temp and A[3]\nBut not doing it for A[0]\njust do\nA[0] = temp\nAs you have don in 3rd\n\"temp\" is a variable outside the list.\nbe carefull\n"
] | [
0
] | [] | [] | [
"partitioning",
"python",
"reference",
"sharedpreferences",
"swap"
] | stackoverflow_0074645644_partitioning_python_reference_sharedpreferences_swap.txt |
Q:
How can I implement a tree in Python?
I am trying to construct a General tree.
Are there any built-in data structures in Python to implement it?
A:
I recommend anytree (I am the author).
Example:
from anytree import Node, RenderTree
udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = Node("Lian", parent=ma... | How can I implement a tree in Python? | I am trying to construct a General tree.
Are there any built-in data structures in Python to implement it?
| [
"I recommend anytree (I am the author).\nExample:\nfrom anytree import Node, RenderTree\n\nudo = Node(\"Udo\")\nmarc = Node(\"Marc\", parent=udo)\nlian = Node(\"Lian\", parent=marc)\ndan = Node(\"Dan\", parent=udo)\njet = Node(\"Jet\", parent=dan)\njan = Node(\"Jan\", parent=dan)\njoe = Node(\"Joe\", parent=dan)\n\... | [
367,
146,
68,
45,
39,
17,
16,
10,
9,
9,
7,
7,
6,
2,
1,
1,
0
] | [
"If you want to create a tree data structure then first you have to create the treeElement object. If you create the treeElement object, then you can decide how your tree behaves. \nTo do this following is the TreeElement class:\nclass TreeElement (object):\n\ndef __init__(self):\n self.elementName = None\n s... | [
-3
] | [
"data_structures",
"python",
"tree"
] | stackoverflow_0002358045_data_structures_python_tree.txt |
Q:
How to extract the information from XML beautiful soup?
I have a list of XML beautifulsoap tag elements as:
[
<Entry>
<EffectiveDate>
<DateFormattedForTHForm>07/01/2022</DateFormattedForTHForm>
</EffectiveDate>
<ExpirationDate>
<DateFormattedForTHForm>07/01/2023</DateFormattedForTHForm>
</... | How to extract the information from XML beautiful soup? | I have a list of XML beautifulsoap tag elements as:
[
<Entry>
<EffectiveDate>
<DateFormattedForTHForm>07/01/2022</DateFormattedForTHForm>
</EffectiveDate>
<ExpirationDate>
<DateFormattedForTHForm>07/01/2023</DateFormattedForTHForm>
</ExpirationDate>
<FormDescription>Notification Of Settleme... | [
"(With \"list of XML beautifulsoup tag elements\" in variable xTagList,) you could try something like this\nbsParser = 'html.parser' # 'xml' # \n# xTagList = [BeautifulSoup(str(x), bsParser) for x in xTagList] # should fix some formatting\nwCont_xstrs = ['\\n'.join([\n str(d) for d in x.descendants if hasattr(d,... | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074642521_beautifulsoup_python.txt |
Q:
Retrieving values of a CSR matrix
Question
I have a CSR matrix, and I want to be able to retrieve the column indices and the values stored.
Data
For different reasons I'm not allowed to share my data, but here's a look (the numpy library is imported as np):
print(type(data) == type(ind) == list) # data and ind ar... | Retrieving values of a CSR matrix | Question
I have a CSR matrix, and I want to be able to retrieve the column indices and the values stored.
Data
For different reasons I'm not allowed to share my data, but here's a look (the numpy library is imported as np):
print(type(data) == type(ind) == list) # data and ind are lists
# OUT: True
print(len(data) =... | [
"Without your data I can't replicate your problem, and probably wouldn't want to do so even with such a large array.\nBut I'll try to illustrate what I expect to happen when constructing a matrix this way. From another question I have a small matrix in a Ipython session:\nIn [60]: Mx\nOut[60]: \n<1x3 sparse matrix... | [
1,
0
] | [] | [] | [
"matrix",
"numpy",
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0074614497_matrix_numpy_python_scipy_sparse_matrix.txt |
Q:
how to draw a pixel in ipycanvas
I cannot figure out how to draw a pixel in ipycanvas. I am drawing rectangles instead of pixels and this makes drawing very slow.
Drawing a rectangle using:
canvas.fill_rect
Code to display image in ipycanvas :
import pandas as pd
import numpy as np
import matplotlib.pyplot as pl... | how to draw a pixel in ipycanvas | I cannot figure out how to draw a pixel in ipycanvas. I am drawing rectangles instead of pixels and this makes drawing very slow.
Drawing a rectangle using:
canvas.fill_rect
Code to display image in ipycanvas :
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import ipyca... | [
"Not sure if this will help but given you're talking about filtering I'd assume you mean things like convolutions. Numpy and Scipy help a lot and provide various ways of applying these and work well with images from Pillow.\nFor example:\nimport requests\nfrom io import BytesIO\nfrom PIL import Image\n\nimport num... | [
1
] | [] | [] | [
"ipycanvas",
"jupyter_notebook",
"pixel",
"python",
"python_imaging_library"
] | stackoverflow_0074626615_ipycanvas_jupyter_notebook_pixel_python_python_imaging_library.txt |
Q:
Turn a string into a valid filename?
I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.
I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like "_-.() ". ... | Turn a string into a valid filename? | I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.
I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like "_-.() ". What's the most elegant solution?
The file... | [
"You can look at the Django framework for how they create a \"slug\" from arbitrary text. A slug is URL- and filename- friendly.\nThe Django text utils define a function, slugify(), that's probably the gold standard for this kind of thing. Essentially, their code is the following.\nimport unicodedata\nimport re\n\... | [
243,
157,
110,
108,
47,
46,
42,
20,
19,
15,
7,
6,
6,
6,
6,
6,
6,
5,
4,
2,
2,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"filenames",
"python",
"sanitize",
"slug"
] | stackoverflow_0000295135_filenames_python_sanitize_slug.txt |
Q:
Dearpygui - built another window within an callback
Hello my fellow programmer!
In my endless searcch for an suiteble GUI i found these wonderfull modul calles dearpygui.
After i started to learn more about how to built a GUI with these, i came to the point where i just asked me: "How can i built a window inside o... | Dearpygui - built another window within an callback | Hello my fellow programmer!
In my endless searcch for an suiteble GUI i found these wonderfull modul calles dearpygui.
After i started to learn more about how to built a GUI with these, i came to the point where i just asked me: "How can i built a window inside of an callback, is this even possible?"
Maybe you awesome ... | [
"I was able to run your code just by changing the callback function lel to:\ndef lel(sender):\n with dpg.window():\n pass\n\nand could generate many child windows. You see that I removed the tag. Tags must be unique, but you used the same one as in your main window, which is not allowed. Also note the nee... | [
0
] | [] | [] | [
"dearpygui",
"python"
] | stackoverflow_0074610549_dearpygui_python.txt |
Q:
Load S3 Data into AWS SageMaker Notebook
I've just started to experiment with AWS SageMaker and would like to load data from an S3 bucket into a pandas dataframe in my SageMaker python jupyter notebook for analysis.
I could use boto to grab the data from S3, but I'm wondering whether there is a more elegant method... | Load S3 Data into AWS SageMaker Notebook | I've just started to experiment with AWS SageMaker and would like to load data from an S3 bucket into a pandas dataframe in my SageMaker python jupyter notebook for analysis.
I could use boto to grab the data from S3, but I'm wondering whether there is a more elegant method as part of the SageMaker framework to do this... | [
"import boto3\nimport pandas as pd\nfrom sagemaker import get_execution_role\n\nrole = get_execution_role()\nbucket='my-bucket'\ndata_key = 'train.csv'\ndata_location = 's3://{}/{}'.format(bucket, data_key)\n\npd.read_csv(data_location)\n\n",
"In the simplest case you don't need boto3, because you just read resou... | [
57,
42,
11,
10,
5,
4,
2,
0,
0
] | [] | [] | [
"amazon_s3",
"amazon_sagemaker",
"amazon_web_services",
"machine_learning",
"python"
] | stackoverflow_0048264656_amazon_s3_amazon_sagemaker_amazon_web_services_machine_learning_python.txt |
Q:
How to rearrange matrix elements vertically on python
I'm trying to build a basic game-like program where I need to rearrange a given matrix but vertically. In this case, I only have 0s and 1s. 0 being lighter objects and 1 being heavier. When the function runs, all the 1s should fall down vertically and the zeros... | How to rearrange matrix elements vertically on python | I'm trying to build a basic game-like program where I need to rearrange a given matrix but vertically. In this case, I only have 0s and 1s. 0 being lighter objects and 1 being heavier. When the function runs, all the 1s should fall down vertically and the zeros go up vertically as well. It needs to have the exact numbe... | [
"Consider using numpy for your matrices. You can then use np.sort to do what you want:\nnp.sort(matrix, axis=0)\n\n",
"If you didn't want to use numpy (though you should), you could do:\nfrom collections import Counter\n\ntest = [[1,0,1,1,0,1,0],\n[0,0,0,1,0,0,0],\n[1,0,1,1,1,1,1],\n[0,1,1,0,1,1,0],\n[1,1,0,1,0,0... | [
2,
1,
1
] | [] | [] | [
"matrix",
"python"
] | stackoverflow_0074645690_matrix_python.txt |
Q:
Fill in values in other columns based on missing dates in another columns - Pandas
I am currently having a similar need to the question in this thread, but it looks like it cannot fill in the dates if the min and max dates of the given date column does not fall into the first and last day of a given month and year... | Fill in values in other columns based on missing dates in another columns - Pandas | I am currently having a similar need to the question in this thread, but it looks like it cannot fill in the dates if the min and max dates of the given date column does not fall into the first and last day of a given month and year. In particular, assume this dataframe
df = pd.DataFrame({'user': ['a','a','b','b','c','... | [
"Ok, so you just need to define your own pd.date_range, then build a new MultiIndex to get the daily data for each user and use pd.DataFrame.reindex.\ndf[\"dt\"] = pd.to_datetime(df[\"dt\"])\ndf = df.set_index([\"user\", \"dt\"])\n\ndaily_idx = pd.date_range(start=\"2016-01-01\", end=\"2016-01-31\", freq=\"D\")\n\n... | [
2,
2
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python"
] | stackoverflow_0074645693_dataframe_datetime_pandas_python.txt |
Q:
discord.py command() got an unexpected keyword argument 'options'
So i am trying to make slash ban command in discord.py and i get this error:
command() got an unexpected keyword argument 'options'
My code:
@tree.command(name="ban", description="Ban someone", options = [app_commands.choices(name="user", descriptio... | discord.py command() got an unexpected keyword argument 'options' | So i am trying to make slash ban command in discord.py and i get this error:
command() got an unexpected keyword argument 'options'
My code:
@tree.command(name="ban", description="Ban someone", options = [app_commands.choices(name="user", description="select user to ban", option_type=6, required=True)])
async def _ban(... | [
"@tree.command(name=\"ban\", description=\"Ban someone\")\nasync def _ban(ctx, user: discord.Member):\n await user.ban(reason=\"NO reason\")\n await ctx.send(f'Banned {user}! Reason: {reason}') \n\nIf you are only using discord.py, which i assume so, user: discord.Member is enough. options = [app_commands.c... | [
1
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074645575_discord.py_python.txt |
Q:
How to set Font size to fit a specific width of the frame in tkinter
actually I am making a project with the help of tkinter in python so basically I want to shrink my font size of a label according to the width of the frame that it will be put in. I want that just i am giving a string and it will automatically ad... | How to set Font size to fit a specific width of the frame in tkinter | actually I am making a project with the help of tkinter in python so basically I want to shrink my font size of a label according to the width of the frame that it will be put in. I want that just i am giving a string and it will automatically adjust the size of the font according to the width.
For an Example:- Let I a... | [
"with .config you can adjust Attributes after you placed it.\nNow you can adjust the window size with the len() of your string.\nI hope it helps.\nimport tkinter as tk\n\ndef adjust_Window(canvas, text):\n\n canvas.config(width=len(text)*50)\n\ndef main():\n root = tk.Tk()\n\n canvas = tk.Canvas(root, widt... | [
0,
0
] | [] | [] | [
"font_size",
"python",
"tkinter"
] | stackoverflow_0071744565_font_size_python_tkinter.txt |
Q:
Grouped Dataframe to a nested tree in python
I have a dataframe as
grpdata = {'Group1':['A', 'A', 'A', 'B','B'],
'Group2':['A2','B2','B2','A2','B2'],
'Group3':['A3', 'A3', 'B3','A3', 'A3'],
'Count':['10', '12', '14', '20']}
# Convert the dictionary into DataFrame
groupdf = pd.DataFrame(g... | Grouped Dataframe to a nested tree in python | I have a dataframe as
grpdata = {'Group1':['A', 'A', 'A', 'B','B'],
'Group2':['A2','B2','B2','A2','B2'],
'Group3':['A3', 'A3', 'B3','A3', 'A3'],
'Count':['10', '12', '14', '20']}
# Convert the dictionary into DataFrame
groupdf = pd.DataFrame(grpdata)
I want to convert this dataframe to a tre... | [
"bigtree is a Python tree implementation that integrates with Python lists, dictionaries, and pandas DataFrame.\nFor this scenario, there is a built-in dataframe_to_tree method which does this for you.\nimport pandas as pd\nfrom bigtree import dataframe_to_tree, print_tree\n\n# I changed the dataframe to path colum... | [
0
] | [] | [] | [
"dataframe",
"python",
"tree"
] | stackoverflow_0073778680_dataframe_python_tree.txt |
Q:
how can fix this Python Code is not defined
surface=self.surface
NameError: name 'self' is not defined
how can fix this Python Code is not defined
the code
class Rectangle:
def __init__(self, longueur=30, largeur=15):
self.lon = longueur
self.lar = largeur
self.nom = "rectangle"
de... | how can fix this Python Code is not defined | surface=self.surface
NameError: name 'self' is not defined
how can fix this Python Code is not defined
the code
class Rectangle:
def __init__(self, longueur=30, largeur=15):
self.lon = longueur
self.lar = largeur
self.nom = "rectangle"
def surface(self):
return self.lon * self.lar
... | [
"At this line surface=self.surface you're trying to access a variable that does not exist in this scope. self has only been defined within the context of the various functions of your classes, and python doesn't know about it outside of those functions.\nIf you have an instance of Rectangle called for example rect,... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074645893_python.txt |
Q:
How to install module of python in VS code
Please share process how to install external modules
i cann't access modules
ss of my vs code screen
A:
Unless you want to manually install packages/modules like pandas you should first install a package manager like PIP, or Anaconda if you have not done so already.
Onc... | How to install module of python in VS code | Please share process how to install external modules
i cann't access modules
ss of my vs code screen
| [
"Unless you want to manually install packages/modules like pandas you should first install a package manager like PIP, or Anaconda if you have not done so already.\nOnce you install follow instructions of either to setup the package manager.\nUsing PIP you should be entering the following command once installed cor... | [
0
] | [] | [] | [
"python",
"python_3.x",
"python_module"
] | stackoverflow_0074645554_python_python_3.x_python_module.txt |
Q:
How to get sqlalchemy length of a string column
Consider this simple table definition (using SQLAlchemy-0.5.6)
from sqlalchemy import *
db = create_engine('sqlite:///tutorial.db')
db.echo = False # Try changing this to True and see what happens
metadata = MetaData(db)
user = Table('user', metadata,
Column... | How to get sqlalchemy length of a string column |
Consider this simple table definition (using SQLAlchemy-0.5.6)
from sqlalchemy import *
db = create_engine('sqlite:///tutorial.db')
db.echo = False # Try changing this to True and see what happens
metadata = MetaData(db)
user = Table('user', metadata,
Column('user_id', Integer, primary_key=True),
Column('... | [
"User.name.property.columns[0].type.length\n\nNote, that SQLAlchemy supports composite properties, that's why columns is a list. It has single item for simple column properties.\n",
"This should work (tested on my machine) :\nprint user.columns.name.type.length\n\n",
"I was getting errors when fields were too b... | [
22,
3,
0,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0001777814_python_sqlalchemy.txt |
Q:
Putting print statements on the same line
I am tring to learn python and want to know if i can do this, and how. I am trying to make binary looking code come up digit by digit, with delay.
In maybe there is 15 numbers, and each repeat i would like to make it do a set of 5, with a space after.
if answer == 'MAYBE':... | Putting print statements on the same line | I am tring to learn python and want to know if i can do this, and how. I am trying to make binary looking code come up digit by digit, with delay.
In maybe there is 15 numbers, and each repeat i would like to make it do a set of 5, with a space after.
if answer == 'MAYBE':
deleteall()
print("GIVE ME AN ANSWER!!... | [] | [] | [
"by setting end parameter you can set whatever will be after it printed. it is next line command by default \"\\n\" so everytime it prints it gets to the next line\nimport time\nimport random\nmaybe = range(5)\nprint(\"GIVE ME AN ANSWER!!!\")\ntime.sleep(1)\nfor x in maybe:\n print(random.choice(\"1\" \"0\"),end... | [
-1,
-1
] | [
"python",
"replit"
] | stackoverflow_0074645899_python_replit.txt |
Q:
How can I get rows that compouse up to 90% of a sum?
I have two different dataframes, one containing the Net Revenue by SKU and Supplier and another one containing the stock of SKUs in each store. I need to get an average by Supplier of the stores that contains the SKUs that compouse up to 90% the net revenue of t... | How can I get rows that compouse up to 90% of a sum? | I have two different dataframes, one containing the Net Revenue by SKU and Supplier and another one containing the stock of SKUs in each store. I need to get an average by Supplier of the stores that contains the SKUs that compouse up to 90% the net revenue of the supplier. It's a bit complicated but I will exemplify, ... | [
"Calculate the cumulative sum grouping by Suppler and divide by the Supplier Total Revenue.\nThen find each Supplier Revenue Threshold by getting the minimum Cumulative Revenue Percentage under 90%.\nThen you can get the list of SKUs by Supplier and calculate the coverage.\nimport pandas as pd\n\ndf = pd.DataFrame(... | [
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074645417_dataframe_group_by_pandas_python.txt |
Q:
How do I create image from binary data BSQ?
I've got a problem. I'm trying create image from binary data which I got from hyperspectral camera. The file which I have is in BSQ uint16 format. From the documentation I found out that images contained in the file (.dat) have a resolution of 1024x1024 and there are 24 ... | How do I create image from binary data BSQ? | I've got a problem. I'm trying create image from binary data which I got from hyperspectral camera. The file which I have is in BSQ uint16 format. From the documentation I found out that images contained in the file (.dat) have a resolution of 1024x1024 and there are 24 images in total. The whole thing is to form a kin... | [
"As suspected it's just byte order, I get a sensible looking image when running the following code in a Jupyter notebook:\nimport numpy as np\nfrom PIL import Image\n\n# open as big-endian, convert to native order, then reshape as appropriate\nraw = np.fromfile(\n './Sequence 1_000021.dat', dtype='>u2'\n).astype('... | [
1
] | [] | [] | [
"geospatial",
"image",
"numpy",
"python",
"python_imaging_library"
] | stackoverflow_0074642656_geospatial_image_numpy_python_python_imaging_library.txt |
Q:
Pandas compute features diff within group
I have a dataframe with n rows for each group ID, where only one label is 1 and all the others are 0s.
Example:
ID, Feature_1; Feature_2; Feature_3; label
1, 10, 3, 4, 1
1, 9, 1, 2, 0
...
2, 100, 30, 40, ... | Pandas compute features diff within group | I have a dataframe with n rows for each group ID, where only one label is 1 and all the others are 0s.
Example:
ID, Feature_1; Feature_2; Feature_3; label
1, 10, 3, 4, 1
1, 9, 1, 2, 0
...
2, 100, 30, 40, 1
2, 90, 10, 20, ... | [
"You can sort your dataframe using sort_values based on 'ID' and 'label in ascending and descending order respectively.\nThen you can calculate a grouped difference using diff on your columns, which would calculate the difference between the last and first row of each group (last - new) and populate the last row, l... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074631343_pandas_python.txt |
Q:
Scan and find the keywords in the database from the csv file, then calculate the occurrence rate of other words
I need to find the presence rate/prevalence of words in a csv file separated by comma, for words next to a certain keyword on the line.
import pandas as pd
from elasticsearch import Elasticsearch
es = E... | Scan and find the keywords in the database from the csv file, then calculate the occurrence rate of other words | I need to find the presence rate/prevalence of words in a csv file separated by comma, for words next to a certain keyword on the line.
import pandas as pd
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
searchDB = pd.read_csv('')
searchDB = searchDB["AllKeywords"].str.split(', ')
... | [
"Seems like your error is at index=searchDB[\"AllKeywords\"]\nClean up your variables\nimport pandas as pd\nfrom elasticsearch import Elasticsearch\n\nes = Elasticsearch(\"http://localhost:9200\")\n\ndf = pd.read_csv('')\nkeywords = df[\"AllKeywords\"].str.split(', ')\nexploded_keywords = searchDB.explode()\n\nfor ... | [
0
] | [] | [] | [
"elasticsearch",
"pandas",
"python"
] | stackoverflow_0074645918_elasticsearch_pandas_python.txt |
Q:
How can I use thresholding to improve image quality after rotating an image with skimage.transform?
I have the following image:
Initial Image
I am using the following code the rotate the image:
from skimage.transform import rotate
image = cv2.imread('122.png')
rotated = rotate(image,34,cval=1,resize = True)
Once ... | How can I use thresholding to improve image quality after rotating an image with skimage.transform? | I have the following image:
Initial Image
I am using the following code the rotate the image:
from skimage.transform import rotate
image = cv2.imread('122.png')
rotated = rotate(image,34,cval=1,resize = True)
Once I execute this code, I receive the following image:
Rotated Image
To eliminate the blur on the image, I u... | [
"To improve the image quality after rotating the image, you can try using different interpolation methods when rotating the image. The rotate function in skimage.transform has a mode parameter that allows you to specify the interpolation method to use. The default value is constant, which means that it uses a const... | [
0,
0
] | [] | [] | [
"mnist",
"opencv",
"python"
] | stackoverflow_0074645772_mnist_opencv_python.txt |
Q:
named parameter passing multiple times
I was wondering if there is a best practice or a convention for this kind of "chained" named parameter. I am trying to pass the first variable d to bar through foo. It is kind of awkward to do it this way and I believe there should be a smarter way but after looking through t... | named parameter passing multiple times | I was wondering if there is a best practice or a convention for this kind of "chained" named parameter. I am trying to pass the first variable d to bar through foo. It is kind of awkward to do it this way and I believe there should be a smarter way but after looking through tons of documents today still no clue.
def ba... | [
"I don't think there is a better way of doing this, but if the b parameter is not going to be used in foo() then I wouldn't have it in there.\ndef bar(a=0, b=0, c=0, d=0):\n print(a,b,c,d)\n\ndef foo(d=0):\n bar(d=d)\n\nfoo(1)\n#(0,0,0,1)\n\n",
"Any answer here is subjective but I'm not going to submit to c... | [
0,
0,
0
] | [] | [] | [
"named_parameters",
"python"
] | stackoverflow_0042404746_named_parameters_python.txt |
Q:
How can I use PyPDF2 to update variable text to a form field?
PyPDF2 update page form field values function working fine with hardcoded strings but nothing shows if using variable text.
I have tried using string variables like this
writer.update_page_form_field_values(
#writer.pages[0], {"Piece Weight": variab... | How can I use PyPDF2 to update variable text to a form field? | PyPDF2 update page form field values function working fine with hardcoded strings but nothing shows if using variable text.
I have tried using string variables like this
writer.update_page_form_field_values(
#writer.pages[0], {"Piece Weight": variableString} doesn't work
writer.pages[0], {"Piece Weight": "hardc... | [
"Final answer to my issue was to use the global tag to call the variable outside of the function into it.\nvariable = \"te\"\ndef onStart():\n global variable\n variable = variableEntry.get()\n\nwhen reading about globals for python i misunderstood it as a declarative global and not a call global\n"
] | [
0
] | [] | [] | [
"pypdf2",
"python"
] | stackoverflow_0074645364_pypdf2_python.txt |
Q:
Getting a count of objects in a queryset in Django
How can I add a field for the count of objects in a database. I have the following models:
class Item(models.Model):
name = models.CharField()
class Contest(models.Model);
name = models.CharField()
class Votes(models.Model):
user = models.ForeignKey(... | Getting a count of objects in a queryset in Django | How can I add a field for the count of objects in a database. I have the following models:
class Item(models.Model):
name = models.CharField()
class Contest(models.Model);
name = models.CharField()
class Votes(models.Model):
user = models.ForeignKey(User)
item = models.ForeignKey(Item)
contest = m... | [
"To get the number of votes for a specific item, you would use:\nvote_count = Item.objects.filter(votes__contest=contestA).count()\n\nIf you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:\ncontest = Contest.objects.get(pk=contest_id)\nvotes = con... | [
181,
23,
1,
0
] | [] | [] | [
"count",
"django",
"django_queryset",
"python",
"python_3.x"
] | stackoverflow_0005439901_count_django_django_queryset_python_python_3.x.txt |
Q:
Testing django mail and attachment return empty
I'm trying to test mails with attachment, I'm attaching the files something like this:
# snippet of send_pdf_mail
mail = EmailMessage(
subject=subject,
body=message,
from_email=from_email,
to=recipient_list,
)
dynamic_template_... | Testing django mail and attachment return empty | I'm trying to test mails with attachment, I'm attaching the files something like this:
# snippet of send_pdf_mail
mail = EmailMessage(
subject=subject,
body=message,
from_email=from_email,
to=recipient_list,
)
dynamic_template_data.update({'subject': subject})
mail.content_su... | [
"I recommend to use EmailMultiAlternatives instead of EmailMessage\nIn this case you can attack file without any problems\nemail_message = EmailMultiAlternatives(\n subject=\"subject\",\n to=\"to_email\",\n)\nhtml_email: str = loader.render_to_string(template_name, context)\nemail_message.attach_alternative(h... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0065038261_django_python.txt |
Q:
Mac M1 python packages error after upgrade to python3
I am writing a project in NativeScript and I received the following error the last few days when I tried the commands: ns run ios or ns doctor.
Couldn't retrieve installed python packages.
The Python 'six' package not found.
I tried python and pip upgrade and ... | Mac M1 python packages error after upgrade to python3 | I am writing a project in NativeScript and I received the following error the last few days when I tried the commands: ns run ios or ns doctor.
Couldn't retrieve installed python packages.
The Python 'six' package not found.
I tried python and pip upgrade and also the command pip install six.
Nothing of them fixed the... | [
"Lastly, I found the solution. It was about the python folder into the path /usr/local/bin/python\nYou could check it by the following command: where python\nIn my case this folder is missing, perhaps I deleted it after the upgrade of the python3.\nThat was a mistake both folders should exist on this path!\nIf you ... | [
0,
0
] | [] | [] | [
"apple_m1",
"homebrew",
"nativescript",
"python"
] | stackoverflow_0073959594_apple_m1_homebrew_nativescript_python.txt |
Q:
Nginx is throwing an 403 Forbidden on Static Files
I have a django app, python 2.7 with gunicorn and nginx.
Nginx is throwing a 403 Forbidden Error, if I try to view anything in my static folder @:
/home/ubuntu/virtualenv/myapp/myapp/homelaunch/static
nginx config(/etc/nginx/sites-enabled/myapp) contains:
server ... | Nginx is throwing an 403 Forbidden on Static Files | I have a django app, python 2.7 with gunicorn and nginx.
Nginx is throwing a 403 Forbidden Error, if I try to view anything in my static folder @:
/home/ubuntu/virtualenv/myapp/myapp/homelaunch/static
nginx config(/etc/nginx/sites-enabled/myapp) contains:
server {
listen 80;
server_name *.mya... | [
"It appears the user nginx is running as (nginx?) is missing privileges to read the local file /home/ubuntu/virtualenv/myapp/myapp/homelaunch/static/img/templated/home/img.png. You probably wanna check file permissions as well as permissions on the directories in the hierarchy.\n",
"MacOs El Capitan: At the top o... | [
27,
27,
9,
9,
8,
4,
1,
0
] | [
"After hours upon hours following so many articles, I ran across :\nhttp://nicholasorr.com/blog/2008/07/22/nginx-engine-x-what-a-pain-in-the-bum/\nwhich had a comment to chmod the whole django app dir, so I did:\nsudo chmod -R myapp\n\nThis fixed it. Unbelievable!\nThanks to those who offered solutions to fix this.... | [
-6
] | [
"configuration",
"django",
"nginx",
"python"
] | stackoverflow_0020182329_configuration_django_nginx_python.txt |
Q:
Messed up Python install, how do I get it back?
I downgraded to Python 3.7.15 using the tarball on their website. I downgraded because I needed to use an application that was only compatible with Python 3.7.*, well, now I can't uninstall it and it's for some reason set as the default installation. There is no rule... | Messed up Python install, how do I get it back? | I downgraded to Python 3.7.15 using the tarball on their website. I downgraded because I needed to use an application that was only compatible with Python 3.7.*, well, now I can't uninstall it and it's for some reason set as the default installation. There is no rule for make uninstall so I need help figuring out what ... | [] | [] | [
"Try to using anaconda\nthere you can specify version of python while creating virtual environment\nNo need to uninstall base python\nconda create -n envname python=x.x anaconda\n\n"
] | [
-2
] | [
"archlinux",
"binaries",
"executable",
"python"
] | stackoverflow_0074645963_archlinux_binaries_executable_python.txt |
Q:
Get value from an array that stores a tree of keys in python
I have an array that stores a key tree from a dictionary. For example
person_dict = [{"person": {"first_name": "John", "age_of_children": [1, 8, 13]}}, ...]
Becomes
key_tree = [0, "person", "first_name"]
OR
key_tree = [0, "person", "age_of_children"]
... | Get value from an array that stores a tree of keys in python | I have an array that stores a key tree from a dictionary. For example
person_dict = [{"person": {"first_name": "John", "age_of_children": [1, 8, 13]}}, ...]
Becomes
key_tree = [0, "person", "first_name"]
OR
key_tree = [0, "person", "age_of_children"]
This array count contain one item or many items.
I'd like to get t... | [
"You can try the following:\ndef get_value(d, key_list):\n for key in key_list:\n d = d[key]\n return d\n\n\ndef set_value(d, key_list, value):\n res = d\n *keys, last_key = key_list\n\n for key in keys:\n d = d[key]\n\n d[last_key] = value\n return res\n\n\nperson_dict = [{\"pers... | [
1,
0
] | [] | [] | [
"dictionary",
"list",
"loops",
"python"
] | stackoverflow_0074646092_dictionary_list_loops_python.txt |
Q:
From text file to JSON file with python
Suppose I have a txt file that looks like this (indentation is 4 spaces):
key1=value1
key2
key2_1=value2_1
key2_2
key2_2_1=value2_2_1
key2_3=value2_3_1,value2_3_2,value2_3_3
key3=value3_1,value3_2,value3_3
I want to convert it into any VALID json, like t... | From text file to JSON file with python | Suppose I have a txt file that looks like this (indentation is 4 spaces):
key1=value1
key2
key2_1=value2_1
key2_2
key2_2_1=value2_2_1
key2_3=value2_3_1,value2_3_2,value2_3_3
key3=value3_1,value3_2,value3_3
I want to convert it into any VALID json, like this one:
{
'key1':'value1',
'key2': {
'ke... | [
"An aside for users that land on this page: I could not reproduce the error that the OP posted. json.dumps() would be very highly unlikely to output \"bad json\". This was merely an attempt to help out the poster.\nSplitting The Strings Into Lists\nI am assuming per your comment that you mean that you want to take ... | [
1
] | [] | [] | [
"arrays",
"dictionary",
"json",
"python",
"txt"
] | stackoverflow_0074642972_arrays_dictionary_json_python_txt.txt |
Q:
Comparing Two Functions for Recursive Digit Sum
I'm stumped as to why my solution for the Recursive Digit Sum question on HackerRank is being rejected.
Background
The question:
For an input of string n and integer k, the number h is created by concatenating n "k" times. Find the "super digit" of h by recursively s... | Comparing Two Functions for Recursive Digit Sum | I'm stumped as to why my solution for the Recursive Digit Sum question on HackerRank is being rejected.
Background
The question:
For an input of string n and integer k, the number h is created by concatenating n "k" times. Find the "super digit" of h by recursively summing the integers until one is left.
For example:
... | [
"Here is the result of my research on your case:\nYou don't supply the typing, so I had to case check to find out you use one str and one int. How do I know this?\nWell if you used 2 strs the multiplication would fail:\n>>> \"10\"*\"2\"\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nT... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074636865_python.txt |
Q:
ModuleNotFoundError: No module named 'caffe._caffe' on Windows 10
I wanted to make a deepdream video using this script: https://github.com/graphific/DeepDreamVideo. I had to make few changes to it but now I'm receiving this error:
Traceback (most recent call last):
File "C:\Users\Daniel\Desktop\deepdream-master\... | ModuleNotFoundError: No module named 'caffe._caffe' on Windows 10 | I wanted to make a deepdream video using this script: https://github.com/graphific/DeepDreamVideo. I had to make few changes to it but now I'm receiving this error:
Traceback (most recent call last):
File "C:\Users\Daniel\Desktop\deepdream-master\2_dreaming_time.py", line 20, in <module>
import caffe
File "C:\U... | [
"Install caffe from source then it will work.\n",
"I install from the source but get this same problem.\nStill no idea what happen.\n",
"Faced the same issue, while importing Caffe after installing Caffe in windows with GPU, could fix it by copying <CAFFE installation>/caffe/python/caffe/ to <Python Directory>/... | [
1,
0,
0
] | [] | [] | [
"caffe",
"deep_dream",
"pycaffe",
"python",
"python_3.x"
] | stackoverflow_0064472948_caffe_deep_dream_pycaffe_python_python_3.x.txt |
Q:
Merge all excel files into one file with multiple sheets
i would like some help.
I have multiple excel files, each file only has one sheet.
I would like to combine all excel files into just one file but with multiple sheets one sheet per excel file keeping the same sheet names.
this is what i have so far:
import p... | Merge all excel files into one file with multiple sheets | i would like some help.
I have multiple excel files, each file only has one sheet.
I would like to combine all excel files into just one file but with multiple sheets one sheet per excel file keeping the same sheet names.
this is what i have so far:
import pandas as pd
from glob import glob
import os
excelWriter = p... | [
"import pandas as pd\nimport os\n\noutput_excel = r'/home/bera/Desktop/all_excels.xlsx'\n\n#List all excel files in folder\nexcel_folder= r'/home/bera/Desktop/GIStest/excelfiles/'\nexcel_files = [os.path.join(root, file) for root, folder, files in os.walk(excel_folder) for file in files if file.endswith(\".xlsx\")]... | [
1
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0074646115_excel_pandas_python.txt |
Q:
Smallest Square Function
Consider a positive integer n. What will be the smallest number k such that if we concatenate the digits of n with those of k we get a perfect square?
For example, for n=1 the smallest k is 6 since 16 is a perfect square.
For n=4, k has to be 9 because 49 is a perfect square.
For n=35, k i... | Smallest Square Function | Consider a positive integer n. What will be the smallest number k such that if we concatenate the digits of n with those of k we get a perfect square?
For example, for n=1 the smallest k is 6 since 16 is a perfect square.
For n=4, k has to be 9 because 49 is a perfect square.
For n=35, k is 344, since 35344=1882 is the... | [
"No recursion is necessary:\ndef smallestSquare(n):\n x = 1\n while isSquare(int(str(n)+str(x))) == False:\n x += 1\n return int(str(n)+str(x))\n\n",
"If, given some number 'n', you are looking for the smallest perfect suqare that begins with 'n', the following is an approach that should work:\nim... | [
1,
0
] | [] | [] | [
"function",
"python",
"recursion"
] | stackoverflow_0074645753_function_python_recursion.txt |
Q:
python nested list sort based on 2nd value of the list is not working properly when it has value 10
here is my code for hackerrank nested list problem in python
problem link:https://www.hackerrank.com/challenges/nested-list/problem?isFullScreen=true
code:
def sort(sub_li):
return(sorted(sub_li, key = lambda x:... | python nested list sort based on 2nd value of the list is not working properly when it has value 10 | here is my code for hackerrank nested list problem in python
problem link:https://www.hackerrank.com/challenges/nested-list/problem?isFullScreen=true
code:
def sort(sub_li):
return(sorted(sub_li, key = lambda x: x[1]))
if __name__ == '__main__':
x=int(input ())
stu=[]
record=[]
for i in range(0... | [
"In the lexicographic order, 10 comes befor 8, because 1 is before 8\nYou need to convert to float to get it work like you expect\n\nat input\n stu.append(input())\n stu.append(float(input()))\n\n\nor at use\ndef sort(sub_li):\n return sorted(sub_li, key=lambda x: float(x[1]))\n\n\n\n"
] | [
0
] | [] | [] | [
"nested_lists",
"python",
"secondary_indexes",
"sorting"
] | stackoverflow_0074646219_nested_lists_python_secondary_indexes_sorting.txt |
Q:
Python Selenium Take a Screenshot Of An Whole Page Without Using Headless Mode
I need to take a screenshot of an element which is very long and not fit on the screen, I can use headless mode to do this but site doesn't allow me to do even with user-agent and other stuff.
But I can access the site with undetectedCh... | Python Selenium Take a Screenshot Of An Whole Page Without Using Headless Mode | I need to take a screenshot of an element which is very long and not fit on the screen, I can use headless mode to do this but site doesn't allow me to do even with user-agent and other stuff.
But I can access the site with undetectedChromeDriver, so there's a extension to do this stuff called 'HTML Elements Screenshot... | [
"For python you can use pyppeteer.\nFor javascript you can use puppeteer\nYou can find the documentation here\n"
] | [
0
] | [] | [] | [
"javascript",
"python",
"screenshot",
"selenium",
"undetected_chromedriver"
] | stackoverflow_0074645486_javascript_python_screenshot_selenium_undetected_chromedriver.txt |
Q:
Is there any way to create a user generator?
I need your help, I'm trying to create a program that can generate usernames by entering its first and lastname and apply some rules specifically, but I don't know how to store a list of elements into a list on Python.
print('Welcome to your program!')
print("How many ... | Is there any way to create a user generator? | I need your help, I'm trying to create a program that can generate usernames by entering its first and lastname and apply some rules specifically, but I don't know how to store a list of elements into a list on Python.
print('Welcome to your program!')
print("How many users do you want to create: ")
firstName = input... | [
"Put a loop around the process, and collect into a list\nusernames = []\nnb = int(input(\"How many users do you want to create ?\"))\nfor i in range(nb):\n print(f\"Person n°{i + 1}\")\n firstName = input('What is your firstname: ').lower()\n lastName = input('What is your lastname: ').lower()\n usernam... | [
0
] | [] | [] | [
"arrays",
"list",
"methods",
"python",
"tuples"
] | stackoverflow_0074646325_arrays_list_methods_python_tuples.txt |
Q:
how to pass multiple flags in argparse python
I am trying to pass multiple flags, basically two flags. This is what my code looks like
parser.add_argument('--naruto', action='store_true')
parser.add_argument('--transformers', action='store_true')
parser.add_argument('--goku', action='store_true')
parser.add_argume... | how to pass multiple flags in argparse python | I am trying to pass multiple flags, basically two flags. This is what my code looks like
parser.add_argument('--naruto', action='store_true')
parser.add_argument('--transformers', action='store_true')
parser.add_argument('--goku', action='store_true')
parser.add_argument('--anime', action='store_true')
I know action='... | [
"If I understand it correctly you ask how you can parse those args.\nHere is an example of argument parsing:\nparser.add_argument('--naruto', action='store_true')\nparser.add_argument('--transformers', action='store_true')\nparser.add_argument('--goku', action='store_true')\nparser.add_argument('--anime', action='s... | [
-1
] | [] | [] | [
"argparse",
"command_line",
"command_line_arguments",
"python",
"python_3.x"
] | stackoverflow_0074646162_argparse_command_line_command_line_arguments_python_python_3.x.txt |
Q:
How to stop randomised drawings in python from overlapping
So, I have written a code that creates snowflakes using turtle. Essentially it asks the user how many snowflakes to generate. It then opens a turtle window and draws the snowflakes in a random place, size and colour. The random place is important for this ... | How to stop randomised drawings in python from overlapping | So, I have written a code that creates snowflakes using turtle. Essentially it asks the user how many snowflakes to generate. It then opens a turtle window and draws the snowflakes in a random place, size and colour. The random place is important for this question. Essentially, when it draws the snowflakes, is there a ... | [
"Similar to @mx0's suggestion (+1), rather than a square, we define a circle that encompasses the snowflake and for each successful placement, keep a list of existing positions and radii. We also use the radius to avoid drawing partial snowflakes near the edge of our window:\nfrom turtle import Screen, Turtle\nfro... | [
0
] | [] | [] | [
"python",
"python_3.x",
"python_turtle",
"turtle_graphics"
] | stackoverflow_0074639715_python_python_3.x_python_turtle_turtle_graphics.txt |
Q:
grpc about 'a client-to-server stream RPC' but with an error of 'Exception iterating requests'
I made a demo about 'a client-to-server stream RPC', but when I run client, it appears an error as below:
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/back_test_v2/gRPC/client/order_client.py... | grpc about 'a client-to-server stream RPC' but with an error of 'Exception iterating requests' | I made a demo about 'a client-to-server stream RPC', but when I run client, it appears an error as below:
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/back_test_v2/gRPC/client/order_client.py", line 57, in <module>
run_client()
File "C:/Users/Administrator/Desktop/back_test_v2/gRPC/cl... | [
"The Exception iterating requests! error message means there is an Exception raised in the request iterator. I would recommend to add a try-catch clause in the client-side def data() function.\n",
"I Believe this post might be bit late, But at least for those who might wonder over her looking for a resolution, ho... | [
1,
0
] | [] | [] | [
"grpc",
"python"
] | stackoverflow_0070417991_grpc_python.txt |
Q:
How can I run pygame and PyQt5 together but seperately?
I have a question about using pyqt5 and pygame. I have already made a pygame script and a pyqt5 script. The problem is that when I want to make pygame excute the game, it shows a ranking board in pyqt5 and plays game by a pygame script.
This is my pyqt UI cod... | How can I run pygame and PyQt5 together but seperately? | I have a question about using pyqt5 and pygame. I have already made a pygame script and a pyqt5 script. The problem is that when I want to make pygame excute the game, it shows a ranking board in pyqt5 and plays game by a pygame script.
This is my pyqt UI code:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGu... | [
"Do not mix frameworks, mixing frameworks always means some kind of undefined behavior. The frameworks may interact poorly or completely conflict with one another. Getting it to work on your system doesn't mean it will work on another system or with a different version of any of the frameworks.\nIf you use Qt, then... | [
1
] | [] | [] | [
"pygame",
"pyqt5",
"python"
] | stackoverflow_0074642105_pygame_pyqt5_python.txt |
Q:
connect to Redshift from lambda and fetch some record using python
is any one able successfully connect to Redshift from lambda.
I want to fetch some records from Redshift table and feed to my bot (aws lex)
Please suggest - this code is working outside lambda how to make it work inside lambda.
import psycopg2
co... | connect to Redshift from lambda and fetch some record using python | is any one able successfully connect to Redshift from lambda.
I want to fetch some records from Redshift table and feed to my bot (aws lex)
Please suggest - this code is working outside lambda how to make it work inside lambda.
import psycopg2
con=psycopg2.connect(dbname= 'qa', host='name',
port= '5439', user= 'dwuse... | [
"Here is the node lambda that works to connecting to Redshift and pulling data from it.\nexports.handler = function(event, context, callback) {\n var response = {\n status: \"SUCCESS\",\n errors: [],\n response: {},\n verbose: {}\n };\n\n var client = new pg.Client(connectionStr... | [
2,
0
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"aws_lambda",
"lambda",
"python"
] | stackoverflow_0048308584_amazon_s3_amazon_web_services_aws_lambda_lambda_python.txt |
Q:
regular expressions parentheses python
stuck with regular expressions. There is an example text:
'[1 | Hi {name} | Hello {name} | Good morning {name}] other text {1
|{name}| 3| 4} OTHER {5 |{name}| 6| 7}'
It is necessary to extract from it the constructions [1 | Hi {name} | hello {name} | Good morning {name}] an... | regular expressions parentheses python | stuck with regular expressions. There is an example text:
'[1 | Hi {name} | Hello {name} | Good morning {name}] other text {1
|{name}| 3| 4} OTHER {5 |{name}| 6| 7}'
It is necessary to extract from it the constructions [1 | Hi {name} | hello {name} | Good morning {name}] and {1|{name}| 3| 4} and {5 |{name}| 6| 7}
re.... | [
"This is tricky with regular expressions, but quite trivial with \"parsing\":\ndef top_level_parens(s):\n stack = []\n\n for n, c in enumerate(s):\n if c in '({[':\n stack.append(n)\n elif c in ')}]':\n m = stack.pop()\n if not stack:\n yield s[m:n... | [
1,
0
] | [] | [] | [
"python",
"python_re"
] | stackoverflow_0074645122_python_python_re.txt |
Q:
OverflowError: cannot convert float infinity to integer, after doing so
import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import quantstats as qs
data = pd.read_csv('worldometer_data.csv')
X = data.drop(columns=['Country/Region', 'Continent', 'Population', '... | OverflowError: cannot convert float infinity to integer, after doing so | import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import quantstats as qs
data = pd.read_csv('worldometer_data.csv')
X = data.drop(columns=['Country/Region', 'Continent', 'Population', 'WHO Region'])
# replace NaN values with 0
for i in X:
X[i] = X[i].fillna(0... | [
"The problem is here:\nfor i in range(0, 51):\n kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10, random_state=0)\n\nYou cannot set n_clusers to 0. It must be larger than 0.\n"
] | [
1
] | [] | [] | [
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074646376_jupyter_notebook_pandas_python.txt |
Q:
Python Logging for custom module
I am looking to implement custom logging for my module.
The issues i am facing are the setLevel(0) does not disable the logging, and basicConfig(level=0) duplicates the error with default formatting.
My aim is to disable my modules logging by default without affecting the user and ... | Python Logging for custom module | I am looking to implement custom logging for my module.
The issues i am facing are the setLevel(0) does not disable the logging, and basicConfig(level=0) duplicates the error with default formatting.
My aim is to disable my modules logging by default without affecting the user and allow the user to import logging and m... | [
"If your purpose is to disable logging by default and let users implement their own logging levels, it is similar to how Python packages implement logging - there is a need to use NullHandler.\nimport logging\nlogging.getLogger('foo').addHandler(logging.NullHandler())\n\nSource: The logging Documentation on how to ... | [
0
] | [] | [] | [
"python",
"python_logging",
"python_module"
] | stackoverflow_0074645804_python_python_logging_python_module.txt |
Q:
How to get feature names of shap_values from TreeExplainer?
I am doing a shap tutorial, and attempting to get the shap values for each person in a dataset
from sklearn.model_selection import train_test_split
import xgboost
import shap
import numpy as np
import pandas as pd
import matplotlib.pylab as pl
X,y = shap... | How to get feature names of shap_values from TreeExplainer? | I am doing a shap tutorial, and attempting to get the shap values for each person in a dataset
from sklearn.model_selection import train_test_split
import xgboost
import shap
import numpy as np
import pandas as pd
import matplotlib.pylab as pl
X,y = shap.datasets.adult()
X_display,y_display = shap.datasets.adult(displ... | [
"The features are indeed in the same order, as you assume; see how to extract the most important feature names? and how to get feature names from explainer issues in Github.\nTo find the feature name, you simply need to access the element with the same index of the array with the names\nFor example:\nshap_values = ... | [
3,
0
] | [] | [] | [
"machine_learning",
"python",
"python_3.x",
"shap"
] | stackoverflow_0067443411_machine_learning_python_python_3.x_shap.txt |
Q:
Trying to merge dictionaries together to create new df but dictionaries values arent showing up in df
image of jupter notebook issue
For my quarters instead of values for examples 1,0,0,0 showing up I get NaN.
How do I fix the code below so I return values in my dataframe
qrt_1 = {'q1':[1,0,0,0,1,0,0,0,1,0,0,0,1,0... | Trying to merge dictionaries together to create new df but dictionaries values arent showing up in df | image of jupter notebook issue
For my quarters instead of values for examples 1,0,0,0 showing up I get NaN.
How do I fix the code below so I return values in my dataframe
qrt_1 = {'q1':[1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0]}
qrt_2 = {'q2':[0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0... | [
"Try to use axis=1 in pd.concat:\ndf = pd.concat(dataframes, axis=1)\nprint(df)\n\nPrints:\n year q1 q2 q3 q4\n0 1 1 0 0 0\n1 1 0 1 0 0\n2 1 0 0 1 0\n3 1 0 0 0 1\n4 2 1 0 0 0\n5 2 0 1 0 0\n6 2 0 0 1 0\n7 2 0 0... | [
1
] | [] | [] | [
"dataframe",
"dictionary",
"pandas",
"python"
] | stackoverflow_0074646374_dataframe_dictionary_pandas_python.txt |
Q:
Get all value and items from drop down list using selenium
I am trying to extract values from dropdown using python selenium. I am getting the text but not getting the values with xpath. Code I used is
from selenium.common.exceptions import WebDriverException
from selenium import webdriver
headers = {
"User-A... | Get all value and items from drop down list using selenium | I am trying to extract values from dropdown using python selenium. I am getting the text but not getting the values with xpath. Code I used is
from selenium.common.exceptions import WebDriverException
from selenium import webdriver
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/53... | [
"So what you should do is:\nds = [d.text for d in datas.find_elements('tag name','option')]\n\nyou were using the improper tag locator. Options are tags not names, the 'name=' attribute (similar to class names) inside a tag element. Secondly you were looking for a singular item and then iterating over that element ... | [
2
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074646351_python_selenium.txt |
Q:
Django NOT NULL constraint error on imaginary field
I have been getting the following error.
django.db.utils.IntegrityError: NOT NULL constraint failed: doctor_owner.doc_name
This error primarily arises on when I save the owner information using .save() and the error it gives is on doc_name, which is not present... | Django NOT NULL constraint error on imaginary field | I have been getting the following error.
django.db.utils.IntegrityError: NOT NULL constraint failed: doctor_owner.doc_name
This error primarily arises on when I save the owner information using .save() and the error it gives is on doc_name, which is not present in the model definition of the class Owner. I am clueles... | [
"In your treatment table you have a reference as a foreign key to owner; try putting an equivalent to 'nullable=True' or give it a default value\n",
"why not put\ndoc_name = models.CharField(max_length=250, null = True) to try is working\n",
"The problem was the corruption in db.sqlite3 file of the Django proje... | [
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074630413_django_python.txt |
Q:
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured
I want to connect MySQL database to my django project, but it is throwing an error :
"django.core.exceptions.ImproperlyConfigured: Requested setting
USE_I18N, but settings are not configured. You must either... | django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured | I want to connect MySQL database to my django project, but it is throwing an error :
"django.core.exceptions.ImproperlyConfigured: Requested setting
USE_I18N, but settings are not configured. You must either define the
environment variable DJANGO_SETTINGS_MODULE or call
settings.configure() before accessing sett... | [
"You must define the relevant variable to show where your settings.py file lives:\nexport DJANGO_SETTINGS_MODULE=mysite.settings\n\nThis is the relevant docs entry:\n\nWhen you use Django, you have to tell it which settings you’re using.\nDo this by using an environment variable, DJANGO_SETTINGS_MODULE.\nThe value ... | [
40,
17,
12,
5,
4,
4,
3,
0,
0
] | [] | [] | [
"django",
"mysql_python",
"python"
] | stackoverflow_0047700347_django_mysql_python_python.txt |
Q:
How to "join" right and left eye videos in Python or bash to for stereoscopic 3D VR video
I have a code which generates 360 video frames from a "camera" placed in a 3D dataset. I can run this code twice with an offset of the camera position to get "right and left eye" videos. These should be able to be combined in... | How to "join" right and left eye videos in Python or bash to for stereoscopic 3D VR video | I have a code which generates 360 video frames from a "camera" placed in a 3D dataset. I can run this code twice with an offset of the camera position to get "right and left eye" videos. These should be able to be combined into a single file which can be viewed as a 3D stereoscopic video with a VR headset.
How can I co... | [
"Stereoscopic 3D video is typically encoded in a single file using a technique called \"multi-view video coding\" (MVC). This technique allows the video to be played back on devices that support 3D playback, such as VR headsets.\nTo create a MVC video file, you can use a tool like ffmpeg. The basic process would be... | [
1
] | [] | [] | [
"bash",
"python",
"video",
"virtual_reality"
] | stackoverflow_0074646501_bash_python_video_virtual_reality.txt |
Q:
Find similarities in Python
I have a list of Customer Names and Supplier Names and since of 2 different countries in the same company.
Unfortunately same Customer and Suppliers have different ids in different countries.
In the other hand the names in the most of the cases are the same or at least very similar.
The... | Find similarities in Python | I have a list of Customer Names and Supplier Names and since of 2 different countries in the same company.
Unfortunately same Customer and Suppliers have different ids in different countries.
In the other hand the names in the most of the cases are the same or at least very similar.
The goal is to have a PBI report wit... | [
"IIUC, you can use rapidfuzz and pandas.DataFrame.merge.\nTo give you the general logic, let's compare for example two dataframes (df_ger) with (df_us) :\nimport pandas as pd\nfrom rapidfuzz import process\n\nout = (\n df_ger\n .assign(message_adapted = (df_ger['CUSTOMER_SUPPLIER_NAME']\n ... | [
0
] | [] | [] | [
"machine_learning",
"pandas",
"python"
] | stackoverflow_0074644638_machine_learning_pandas_python.txt |
Q:
How to select Xpath element
I am playing around with connect automation in Linkedin and trying to send custom connection message to search list.
The way I do it, first I find all buttons. Then I find XPath of the names and index it.
Then I fill all_names list. Then this names are inserted into greeting message.
Th... | How to select Xpath element | I am playing around with connect automation in Linkedin and trying to send custom connection message to search list.
The way I do it, first I find all buttons. Then I find XPath of the names and index it.
Then I fill all_names list. Then this names are inserted into greeting message.
The problem I face is that search r... | [
"Instead of collecting all button elements you can make more precise locating.\nThis Xpath will give you \"Connect\" buttons only //button[contains(@aria-label,'Invite')].\nSo, instead of using this all_connect_buttons = driver.find_elements(By.TAG_NAME, 'button') you can use this:\nall_connect_buttons = driver.fin... | [
3
] | [] | [] | [
"css_selectors",
"python",
"selenium",
"selenium_webdriver",
"xpath"
] | stackoverflow_0074646450_css_selectors_python_selenium_selenium_webdriver_xpath.txt |
Q:
Make an executable file from python project
I want to make a .exe file from my python project, I have made a GUI in tkinter. This project has multiple files and uses a variety of libraries.
I tried to use auto-py-to-exe but it gave a variety of errors concerning the use of tkinter, saying it can not find tkinter. ... | Make an executable file from python project | I want to make a .exe file from my python project, I have made a GUI in tkinter. This project has multiple files and uses a variety of libraries.
I tried to use auto-py-to-exe but it gave a variety of errors concerning the use of tkinter, saying it can not find tkinter. I do not understand this error since tkinter is a... | [
"I personally use CX-Freeze to compile my executables. I have probably used it over 100 or so updates of my tools and typically the problem I run into is either related to missing file that need to be identified in the setup.py file or the fact that when it compiles the Tkinter folder it uses a capital T instead of... | [
1
] | [] | [] | [
"exe",
"python",
"tkinter"
] | stackoverflow_0074645760_exe_python_tkinter.txt |
Q:
How to run the doctest for a single function in python3?
How do I run the doctest for only a single function in python using the command line? I can python3 -m doctest -v main.py but this will run all the doctests in main.py. How do I specify one function to call the doctest on?
A:
That depends on the code in ... | How to run the doctest for a single function in python3? | How do I run the doctest for only a single function in python using the command line? I can python3 -m doctest -v main.py but this will run all the doctests in main.py. How do I specify one function to call the doctest on?
| [
"That depends on the code in main.py that runs the doctests. You can change that code to test a specific function by calling doctest.run_docstring_examples().\nWhen that code runs doctest.testmod() however, you cannot limit testing to a single function from the command line.\n",
"You can accomplish this using my ... | [
1,
0
] | [] | [] | [
"doctest",
"python"
] | stackoverflow_0068407088_doctest_python.txt |
Q:
Error while trying to add up purchases between two inputed dates
The instructions are the following:
"2 dates are entered and the total purchases between those dates is shown, including the purchases made on those dates."
I have the following list:
list_purchases=[{'id':'123','name':'Luis', 'surname':'Henderson', ... | Error while trying to add up purchases between two inputed dates | The instructions are the following:
"2 dates are entered and the total purchases between those dates is shown, including the purchases made on those dates."
I have the following list:
list_purchases=[{'id':'123','name':'Luis', 'surname':'Henderson', 'price':16000, 'date': "(2022, 3, 12)"},{''id':'123','name':'Luis', 's... | [
"You can convert it to a pandas Dataframe, perform filtering operations, then sum up the price.\nimport datetime\nimport pandas as pd\n\nlist_purchases = [{'id':'123','name':'Luis', 'surname':'Henderson', 'price':16000, 'date': \"(2022, 3, 12)\"},{'id':'123','name':'Luis', 'surname':'Henderson', 'price':4000, 'date... | [
0
] | [] | [] | [
"date",
"python",
"python_3.x"
] | stackoverflow_0074646558_date_python_python_3.x.txt |
Q:
How to create a heatmap in Python with 3 columns - the x and y coordinates and the heat
I have a dataframe with 3 columns, x-points, y-points and the heat. Like this:
X, Y, Z
-2, 0, 1
-2, 1, 2
-2, 2, 5
-1, 0, 3
-1, 1, 5
-1, 2, 8
.., .., ..
2, 1, 4
2, 2, 1
I want to plot a heatmap of this data with X and Y being t... | How to create a heatmap in Python with 3 columns - the x and y coordinates and the heat | I have a dataframe with 3 columns, x-points, y-points and the heat. Like this:
X, Y, Z
-2, 0, 1
-2, 1, 2
-2, 2, 5
-1, 0, 3
-1, 1, 5
-1, 2, 8
.., .., ..
2, 1, 4
2, 2, 1
I want to plot a heatmap of this data with X and Y being the coords, and Z being the heat.
I have tried lots of ways to do this and constantly run into... | [
"Use pivot and seaborn.heatmap:\nimport seaborn as sns\n\nsns.heatmap(df.pivot(index='Y', columns='X', values='Z'))\n\nOutput:\n\nIF you want to handle missing coordinates:\ndf2 = (df\n .pivot(index='Y', columns='X', values='Z')\n .pipe(lambda d: d.reindex(index=range(d.index.min(), d.index.max()+1),\n ... | [
1,
0
] | [] | [] | [
"graph",
"heatmap",
"matplotlib",
"python",
"seaborn"
] | stackoverflow_0074646588_graph_heatmap_matplotlib_python_seaborn.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.