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:
Selenium get URL of "a" Tag without href attribute
I'm facing an element like:
<li _ngcontent-bcp-c271="">
<a _ngcontent-bcp-c271="">2018</a>
<!---->
<!---->
</li>
This element is clickable but since it does not have a href attribute, and I think it should use some script for the click event, I don't hav... | Selenium get URL of "a" Tag without href attribute | I'm facing an element like:
<li _ngcontent-bcp-c271="">
<a _ngcontent-bcp-c271="">2018</a>
<!---->
<!---->
</li>
This element is clickable but since it does not have a href attribute, and I think it should use some script for the click event, I don't have a solution to get the URL from this element.
The code ... | [
"The easiest way to know its URL is to click it and then get page's url with:\ndriver.current_url\n\nAnother way is to get the javascript of this page and find in it the code that is responsible for clicking on this link and get the url from it if it is written explicitly there.\n",
"The answer is: NO, you can no... | [
0,
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074396709_python_selenium_selenium_webdriver.txt |
Q:
How to sample from Cartesian product without repetition
I have a list of sets, and I wish to sample n different samples each containing an item from each set.
What I do not want is to have it in order, so, for example, I will get all the samples necessarily with the same item from the first set. I also don't want... | How to sample from Cartesian product without repetition | I have a list of sets, and I wish to sample n different samples each containing an item from each set.
What I do not want is to have it in order, so, for example, I will get all the samples necessarily with the same item from the first set. I also don't want to create all the Cartesian products as that might not be po... | [
"All the above solutions waste a lot of resources for filtering repeated results when it comes to the end of the iteration. That's why I have thought of a method that has (almost) linear speed from start until the very end.\nThe idea is: Give (only in your head) each result of the standard order cartesian product a... | [
8,
1,
1,
1,
0,
0
] | [] | [] | [
"cartesian_product",
"python",
"random"
] | stackoverflow_0048686767_cartesian_product_python_random.txt |
Q:
'list' object has no attribute 'text' for selenium
driver = webdriver.Chrome(path)
driver.get("https://techwithtim.net")
#print(driver.title)
#ID, name, class
#ID is unique, but is often missing
#name is not unique, but always exists
#class is not unique
search = driver.find_element(By.NAME, "s")
search.send_key... | 'list' object has no attribute 'text' for selenium | driver = webdriver.Chrome(path)
driver.get("https://techwithtim.net")
#print(driver.title)
#ID, name, class
#ID is unique, but is often missing
#name is not unique, but always exists
#class is not unique
search = driver.find_element(By.NAME, "s")
search.send_keys("test")
search.send_keys(Keys.RETURN) #return means en... | [
"You could try something like below:\ndriver = webdriver.Chrome(path)\ndriver.get(\"https://techwithtim.net\")\n\nsearch = driver.find_element(By.NAME, \"s\")\nsearch.send_keys(\"test\")\nsearch.send_keys(Keys.RETURN) #return means enter\n\n#wait for a specific thing to exist on the page before we start looking for... | [
0
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074387716_python_selenium_web_scraping.txt |
Q:
How can I make a Python Flask API stored in GIthub Repository deploy at Google Functions?
I have a Github organization where I store repositories.
All repositories are programmed in Python. I want to use Github actions in order to push the code that I have in a repository to Google Cloud Functions.
I have a simple... | How can I make a Python Flask API stored in GIthub Repository deploy at Google Functions? | I have a Github organization where I store repositories.
All repositories are programmed in Python. I want to use Github actions in order to push the code that I have in a repository to Google Cloud Functions.
I have a simple flask API with a single route that I want to deploy on Google Cloud Functions.
main.py
import ... | [
"From your shared yaml and the error message, looks like you are missing a trigger action e.g:\non: push\n\n"
] | [
1
] | [] | [] | [
"google_cloud_functions",
"python"
] | stackoverflow_0074401224_google_cloud_functions_python.txt |
Q:
Why numpy .isin function gives incorrect output
My requirement is I have a large dataframe with millions of rows. I encoded all strings to numeric values in order to use numpys vectorization to increase processing speed.
So I was looking at a way to quickly check if a number exists in another list column. Previous... | Why numpy .isin function gives incorrect output | My requirement is I have a large dataframe with millions of rows. I encoded all strings to numeric values in order to use numpys vectorization to increase processing speed.
So I was looking at a way to quickly check if a number exists in another list column. Previously, I was using list comprehension with string values... | [
"Since col_b not only has lists but also integers, you may need to use apply and treat them differently:\n( dt.apply(lambda x: x['col_a'] in x['col_b'] if type(x['col_b']) is list \n else x['col_a'] == x['col_b'], axis=1)\n\nOutput:\n0 False\n1 True\n2 True\n3 ... | [
1,
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074401802_numpy_pandas_python.txt |
Q:
Convert multiple key dictionary to pandas by comparing the first index each list value in python
I have a dictionary in the following format:
{
"Description" : [[".1","test"],[".3","test1"],[".4","test2"]],
"Description1": [[".1","196"],[".4","197"],[".3","198"]],
"Description3": [[".1","2"],[".3","2"]... | Convert multiple key dictionary to pandas by comparing the first index each list value in python | I have a dictionary in the following format:
{
"Description" : [[".1","test"],[".3","test1"],[".4","test2"]],
"Description1": [[".1","196"],[".4","197"],[".3","198"]],
"Description3": [[".1","2"],[".3","2"]],
"Description3": [[".1",".1.3"],[".3",".1.4"],[".4",".1.5"]]
}
where each key has 2D array, and... | [
"Create dictionaries by nested lists and pass to DataFrame constructor:\nd = {\n\"Description\" : [[\".1\",\"test\"],[\".3\",\"test1\"],[\".4\",\"test2\"]],\n\"Description1\": [[\".1\",\"196\"],[\".4\",\"197\"],[\".3\",\"198\"]],\n\"Description2\": [[\".1\",\"2\"],[\".3\",\"2\"]],\n\"Description3\": [[\".1\",\".1.3... | [
3
] | [] | [] | [
"dictionary",
"numpy",
"pandas",
"python"
] | stackoverflow_0074402012_dictionary_numpy_pandas_python.txt |
Q:
Python docx Replace string in paragraph while keeping style
I need help replacing a string in a word document while keeping the formatting of the entire document.
I'm using python-docx, after reading the documentation, it works with entire paragraphs, so I loose formatting like words that are in bold or italics.
I... | Python docx Replace string in paragraph while keeping style | I need help replacing a string in a word document while keeping the formatting of the entire document.
I'm using python-docx, after reading the documentation, it works with entire paragraphs, so I loose formatting like words that are in bold or italics.
Including the text to replace is in bold, and I would like to keep... | [
"I posted this question (even though I saw a few identical ones on here), because none of those (to my knowledge) solved the issue. There was one using a oodocx library, which I tried, but did not work. So I found a workaround.\nThe code is very similar, but the logic is: when I find the paragraph that contains the... | [
24,
9,
4,
4,
1,
0,
0,
0
] | [] | [] | [
"python",
"python_2.7",
"python_docx"
] | stackoverflow_0034779724_python_python_2.7_python_docx.txt |
Q:
Plotly scatter annotate based on threshold
Consider a table like this -
data = {'Name': {0: 'Alex',
1: 'Smith',
2: 'Federico',
3: 'George',
4: 'Ram',
5: 'Helen',
6: 'Mike',
7: 'Mark',
8: 'Alex',
9: 'Smith',
10: 'Federico',
11: 'George',
12: 'R... | Plotly scatter annotate based on threshold | Consider a table like this -
data = {'Name': {0: 'Alex',
1: 'Smith',
2: 'Federico',
3: 'George',
4: 'Ram',
5: 'Helen',
6: 'Mike',
7: 'Mark',
8: 'Alex',
9: 'Smith',
10: 'Federico',
11: 'George',
12: 'Ram',
13: 'Helen',
14: 'Mike',
... | [
"Customizing the graph to be composed of expres requires a little ingenuity. I will create a data frame with the maximum value for each category and create the graph in expres as well. I then construct a subplot in the graph object and reuse the graph data from the scatterplot. At the same time, I will add a graph ... | [
1,
1
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074400637_plotly_python.txt |
Q:
Pandas data frame append throwing warning message
I have a code which throwing warning message
FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
data = data.append(row, ignore_index=True)
Question 1 : I want to know how to use c... | Pandas data frame append throwing warning message | I have a code which throwing warning message
FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
data = data.append(row, ignore_index=True)
Question 1 : I want to know how to use concat instead of append in below code.
import pandas as... | [
"Maintain sep list and append them.\nimport pandas as pd\nfrom datetime import datetime\nl1=[]\nl2=[]\nl3=[]\nl4=[]\n\n\ndata = pd.DataFrame()\nfor i in range(30):\n value = datetime.now()\n value1 = i\n value2 = i + 20\n value3 = i - 10\n if value3 >= 15:\n\n l1.append(value)\n l2.appe... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074401983_pandas_python.txt |
Q:
A more efficient function for calculating the proportion of observations that fall within a specified interval?
I've written a function which calculates the proportion of observations that fall within a specified interval. So, if our observations are assessment marks, we can find out the proportion of students tha... | A more efficient function for calculating the proportion of observations that fall within a specified interval? | I've written a function which calculates the proportion of observations that fall within a specified interval. So, if our observations are assessment marks, we can find out the proportion of students that got, say, between 70 and 100 marks. I've included a boolean parameter since in all but the last interval (with the ... | [
"I've tried to simplify your function, the results are below. The main changes are:\n\nWe automatically detect if upper is the observations' upper bound, in which case we include the bound in the interval.\nnumpy conveniently lets you sum booleans by casting False to 0 and True to 1, which allows us to turn the pro... | [
1
] | [] | [] | [
"data_analysis",
"exploratory_data_analysis",
"numpy",
"python"
] | stackoverflow_0074401484_data_analysis_exploratory_data_analysis_numpy_python.txt |
Q:
How can I delete top header and set the column names in python
I am new in python. My problem is simple but I am struggling to solve this.
I am working with a simple dataframe. It has 2 columns Q and t. I attached a screeshot of my dataframe herewith.
I want to set the Q and t as column names and remove the top h... | How can I delete top header and set the column names in python | I am new in python. My problem is simple but I am struggling to solve this.
I am working with a simple dataframe. It has 2 columns Q and t. I attached a screeshot of my dataframe herewith.
I want to set the Q and t as column names and remove the top header (0,1).
Another thing is why the df.columns is showing rangeind... | [
"In the following code, we removed the first row and rename the header row with it.\n# get the first row and save in variable\nheader = df.iloc[0]\n\n# slice the data leaving the header row\ndf = df[1:]\n\n# rename the header row as the new dataframe's header\ndf = df.rename(columns=header)\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"indexing",
"pandas",
"python"
] | stackoverflow_0074401934_dataframe_indexing_pandas_python.txt |
Q:
Using snowflake in aws lamda by adding snowflake connector dependencies as layer
I am trying to add snowflake-connector-python version 2.7.9 as a layer in aws lambda.
I am getting this error
Unable to import module lambda_function: /lib64/libc.so.6: version GLIBC_2.28 not found (required by /opt/python/lib/python3... | Using snowflake in aws lamda by adding snowflake connector dependencies as layer | I am trying to add snowflake-connector-python version 2.7.9 as a layer in aws lambda.
I am getting this error
Unable to import module lambda_function: /lib64/libc.so.6: version GLIBC_2.28 not found (required by /opt/python/lib/python3.9/site-packages/cryptography/hazmat/bindings/_rust.abi3.so)
Steps I have tried
docker... | [
"I had a similar issue and had to specify an older cryptography version in the lambda layer (pip install cryptography==3.4.8). For me this solved the issue, hope this helps you too!\n"
] | [
0
] | [] | [] | [
"docker",
"python",
"snowflake_cloud_data_platform",
"ubuntu"
] | stackoverflow_0074031576_docker_python_snowflake_cloud_data_platform_ubuntu.txt |
Q:
TypeError: object of type 'NoneType' has no len() when trying to fit a KerasCLassifier
I am trying to create a partial dependence plot for a neural network I created with keras. To archieve this I have to create a KerasClassifier or KerasRegressor. After having trouble with getting this working using this import:
... | TypeError: object of type 'NoneType' has no len() when trying to fit a KerasCLassifier | I am trying to create a partial dependence plot for a neural network I created with keras. To archieve this I have to create a KerasClassifier or KerasRegressor. After having trouble with getting this working using this import:
from keras.wrappers.scikit_learn import KerasClassifier
I tried to use scikeras but with the... | [
"To fix the issue, you need to specify the parameter input_dim in the input layer. Therefore if your X has 13 columns, change your first layer from\nmodel.add(Dense(70, activation=\"relu\", input_shape=(13,)))\n\nto\nmodel.add(Dense(70, activation=\"relu\", input_dim=13))\n\nand it should work\n"
] | [
0
] | [
"scikeras.wrappers.KerasClassifier is different from keras.wrappers.scikit_learn.KerasClassifier. It requires a tf.keras.Model, which has a different syntax.\nBelow is just an example\nimport tensorflow as tf\n\ndef create_model_classifier():\n inputs = tf.keras.Input(shape=(13,))\n x = tf.keras.layers.Dense(... | [
-1,
-1
] | [
"keras",
"machine_learning",
"neural_network",
"python",
"scikit_learn"
] | stackoverflow_0068213121_keras_machine_learning_neural_network_python_scikit_learn.txt |
Q:
How to send JSON as part of multipart POST-request
I have following POST-request form (simplified):
POST /target_page HTTP/1.1
Host: server_IP:8080
Content-Type: multipart/form-data; boundary=AaaBbbCcc
--AaaBbbCcc
Content-Disposition: form-data; name="json"
Content-Type: application/json
{ "param_1": "value_1... | How to send JSON as part of multipart POST-request | I have following POST-request form (simplified):
POST /target_page HTTP/1.1
Host: server_IP:8080
Content-Type: multipart/form-data; boundary=AaaBbbCcc
--AaaBbbCcc
Content-Disposition: form-data; name="json"
Content-Type: application/json
{ "param_1": "value_1", "param_2": "value_2"}
--AaaBbbCcc
Content-Dispositio... | [
"You are setting the header yourself, including a boundary. Don't do this; requests generates a boundary for you and sets it in the header, but if you already set the header then the resulting payload and the header will not match. Just drop you headers altogether:\ndef send_request():\n payload = {\"param_1\": ... | [
22,
0,
0
] | [] | [] | [
"http_post",
"json",
"multipartform_data",
"python",
"python_requests"
] | stackoverflow_0035939761_http_post_json_multipartform_data_python_python_requests.txt |
Q:
Jinja - render a wrapper div every three iterations
My profile list looks like this:
profile_list = [
{
"display_name": "test",
"description": "Image mit CPU",
"default": True,
"kubespawner_override": {
"image": "fake",
},
},
{
"display_name":... | Jinja - render a wrapper div every three iterations | My profile list looks like this:
profile_list = [
{
"display_name": "test",
"description": "Image mit CPU",
"default": True,
"kubespawner_override": {
"image": "fake",
},
},
{
"display_name": "test",
"description": "Image mit GPU (small)",
... | [
" {% if loop.index0 % 3 == 0 %}\n <h1>Test</h1>\n <div class='profilewrapper'>\n {% endif %}\n <label>\n <input type=\"radio\" class=\"card-input-element\" name=\"profile\" />\n\n <div class=\"card-input center\">\n <h3 class=\"panel-heading\">{{profile.di... | [
0
] | [] | [] | [
"flask",
"jinja2",
"python"
] | stackoverflow_0074401510_flask_jinja2_python.txt |
Q:
Start telegram bot on django project
I'm developing a djnago project and want to connect a telegram bot to it. I'm using python-telegram-bot but do not know how to start the bot when the django server starts.
from django.apps import AppConfig
from .telegramBot import updater
class SocialMediaConfig(AppConfig):
... | Start telegram bot on django project | I'm developing a djnago project and want to connect a telegram bot to it. I'm using python-telegram-bot but do not know how to start the bot when the django server starts.
from django.apps import AppConfig
from .telegramBot import updater
class SocialMediaConfig(AppConfig):
default_auto_field = 'django.db.models.... | [
"The problem seems to be the Django's auto-reloader. When manage.py runserver command is run, it spawns two instances with it. A file monitoring process which reloads the project every time there is some change in one of the project files, and the other is the main process. You can read more about it here in this a... | [
0,
0
] | [] | [] | [
"django",
"python",
"telegram"
] | stackoverflow_0070910699_django_python_telegram.txt |
Q:
read write csv/dataframe files
i am trying to remove the 5th and sixth item of each line of my csv file each line is a list but when i am trying to run it i am getting a (DataFrame constructor not properly called!) error please help
i have tried everything i can but i cant find a simple way to remove the last 2 i... | read write csv/dataframe files | i am trying to remove the 5th and sixth item of each line of my csv file each line is a list but when i am trying to run it i am getting a (DataFrame constructor not properly called!) error please help
i have tried everything i can but i cant find a simple way to remove the last 2 items of every list and then after th... | [] | [] | [
"Just edit how you're reading the file\nYou should use\ndf = pd.read_csv('database.csv')\n\nthat's why you are getting that error.\n",
"You reading the file incorrectly\ndf = pd.DataFrame() is for creating a new dataframe.\n\nYou should use\ndf = pd.read_csv(\"filename.csv\")\n\n"
] | [
-1,
-1
] | [
"python",
"replit"
] | stackoverflow_0074402087_python_replit.txt |
Q:
How do I split a list created from a .txt file with elements separated by "/"?
This is my function:
def read_file():
textfile = open("Animals.txt", "r", encoding="utf-8")
list = textfile.readlines()
print(list)
textfile.close()
This is Animals.txt:
Animal / Hibernation / Waking Hours / Feeding Tim... | How do I split a list created from a .txt file with elements separated by "/"? | This is my function:
def read_file():
textfile = open("Animals.txt", "r", encoding="utf-8")
list = textfile.readlines()
print(list)
textfile.close()
This is Animals.txt:
Animal / Hibernation / Waking Hours / Feeding Time
Bear / winter / 9-20 / 12
Nightowl / - / 21-05 / 21
Sealion / - / 6-18 / 14
How do... | [
"The file format is essentially CSV (albeit that the separators are not commas). You could use pandas or the csv module but as this so trivial I suggest:\nclass Animal:\n def __init__(self, animal, hibernation, waking_hours, feeding_time):\n self._animal = animal\n self._hibernation = hibernation\n... | [
2
] | [] | [] | [
"file",
"list",
"python",
"readlines"
] | stackoverflow_0074401368_file_list_python_readlines.txt |
Q:
Python Requests: Post JSON and file in single request
I need to do a API call to upload a file along with a JSON string with details about the file.
I am trying to use the python requests lib to do this:
import requests
info = {
'var1' : 'this',
'var2' : 'that',
}
data = json.dumps({
'token' : auth_... | Python Requests: Post JSON and file in single request | I need to do a API call to upload a file along with a JSON string with details about the file.
I am trying to use the python requests lib to do this:
import requests
info = {
'var1' : 'this',
'var2' : 'that',
}
data = json.dumps({
'token' : auth_token,
'info' : info,
})
headers = {'Content-type': '... | [
"See this thread How to send JSON as part of multipart POST-request\nDo not set the Content-type header yourself, leave that to pyrequests to generate\ndef send_request():\n payload = {\"param_1\": \"value_1\", \"param_2\": \"value_2\"}\n files = {\n 'json': (None, json.dumps(payload), 'application/jso... | [
31,
27,
4,
2,
1,
0
] | [
"What is more:\nfiles = {\n 'document': open('file_name.pdf', 'rb')\n}\n\nThat will only work if your file is at the same directory where your script is.\nIf you want to append file from different directory you should do:\nfiles = {\n 'document': open(os.path.join(dir_path, 'file_name.pdf'), 'rb')\n}\n\nWhere... | [
-1
] | [
"json",
"python",
"urllib2"
] | stackoverflow_0019439961_json_python_urllib2.txt |
Q:
How to concatenate strings in python?
I am doing automation in python for jira with the addition of jql search inside the service As a result: two JQL queries, one to search for "closed tickets" and the second to search for "created tickets"
But as a result, I can't add rows now.
#Day 0 - current day , Day '-1' ... | How to concatenate strings in python? | I am doing automation in python for jira with the addition of jql search inside the service As a result: two JQL queries, one to search for "closed tickets" and the second to search for "created tickets"
But as a result, I can't add rows now.
#Day 0 - current day , Day '-1' - Yesterday
jql_day = ['','-1','-2','-3']... | [
"You should use f-strings to resolve this issue.\njql_day = ['','-1','-2','-3']\njql_list_one_str = []\njql_list_two_str = []\n\naction = ['resolved','created']\n\nfor i in jql_day: \n jql_str = [f'project = MRCHNT AND {action[0]} >= startOfDay({i})', f'project = MRCHNT AND {action[1]} >= startOfDay({i})']\n ... | [
0
] | [] | [] | [
"concatenation",
"jira",
"jql",
"python",
"string"
] | stackoverflow_0074402128_concatenation_jira_jql_python_string.txt |
Q:
Any idea for a more elegant / simplest conditionnal return?
Here is the Python code:
def _get_handler_by_topic_arn(topic_arn: str, event_name: str, event_message: dict):
if topic_arn == CONFIG.get("MT_MAIN_SNS_TOPIC_ARN"):
return MT_MAIN_TOPIC_HANDLERS.get(event_name)
if topic_arn == CONFIG.get("FO... | Any idea for a more elegant / simplest conditionnal return? | Here is the Python code:
def _get_handler_by_topic_arn(topic_arn: str, event_name: str, event_message: dict):
if topic_arn == CONFIG.get("MT_MAIN_SNS_TOPIC_ARN"):
return MT_MAIN_TOPIC_HANDLERS.get(event_name)
if topic_arn == CONFIG.get("FOX_REQUEST_SNS_TOPIC_ARN"):
return FOX_REQUEST_TOPIC_HANDL... | [
"You can use a dictionary to avoid the ifs:\ndef _get_handler_by_topic_arn(topic_arn: str, event_name: str, event_message: dict):\n not_canceled = event_message.get(\"status\") and event_message.get(\"status\") != \"CANCELLED\"\n\n handlers = {\n CONFIG.get(\"MT_MAIN_SNS_TOPIC_ARN\"): MT_MAIN_TOPIC_HAN... | [
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074402175_python.txt |
Q:
discord.py change channel description and name
Goal is to change channel description and name directly from python code.
With the code mentioned bellow I'm able to change name but for some reason description wont update.
What am I missing here.
import discord
from discord.ext.commands import Bot
import datetime
fr... | discord.py change channel description and name | Goal is to change channel description and name directly from python code.
With the code mentioned bellow I'm able to change name but for some reason description wont update.
What am I missing here.
import discord
from discord.ext.commands import Bot
import datetime
from dotenv import load_dotenv
import os
load_dotenv... | [
"Problem here is I pointed to wrong API documentation related to guilds.\nWe need to use topic = 'ChannelDescription' instead of description = 'ChannelDescription'\nimport discord\nfrom discord.ext.commands import Bot\nimport datetime\nfrom dotenv import load_dotenv \nimport os\nload_dotenv() \n\nTOKEN = os.getenv... | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074381048_discord.py_python.txt |
Q:
How to make visual studio update its error message in a python file?
I wrote several programs in Visual Studio Code, in python.
I always have issue with it:
For instance, I tried to execute a program taking a file as a variable (so a .txt)
I made a mistake on the document name when I called the function ,so ofc, ... | How to make visual studio update its error message in a python file? | I wrote several programs in Visual Studio Code, in python.
I always have issue with it:
For instance, I tried to execute a program taking a file as a variable (so a .txt)
I made a mistake on the document name when I called the function ,so ofc, I get an error ( I wrote test1.xt instead of test.txt), so I correct it. H... | [
"Well, I am kind of dumb, but you have to save the file lol\nMy bad\nEDIT: I come from pyzo, so I'm kinda new to VS Code.\n"
] | [
1
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074402200_python_visual_studio_code.txt |
Q:
Decimal to binary function in Python using recursion
I am new in Python and trying to write a binary-to-decimal converted function like below
def decimaltobinary(n):
if n > 1:
decimaltobinary(n//2)
print(n%2,end='')
#return n%2
decimaltobinary(4)
This works perfectly fine. Now the question is... | Decimal to binary function in Python using recursion | I am new in Python and trying to write a binary-to-decimal converted function like below
def decimaltobinary(n):
if n > 1:
decimaltobinary(n//2)
print(n%2,end='')
#return n%2
decimaltobinary(4)
This works perfectly fine. Now the question is when I am modifying it as below, it doesn't give me corre... | [
"In the second example returned value from decimaltobinary in if is completely ignored.\nWhat you need to do is assign the returned value to a variable and then return it together with n%2.\nTry this:\ndef decimaltobinary(n):\nx = ''\nif n > 1:\n x = decimaltobinary(n//2)\n#print(n%2,end='')\nreturn str(x) + '' ... | [
0,
0,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074401746_python_recursion.txt |
Q:
Indentation error on Visual Studio Code on a Mac (again)
I am a newbie trying to use Python (2.17.15 via Anaconda) on Visual Stodio Code on my Mac. I have the following simple code:
def function(x):
y = x + 2
return y
This code is giving me the usual trouble, an indentation error:
return y
^
Indent... | Indentation error on Visual Studio Code on a Mac (again) | I am a newbie trying to use Python (2.17.15 via Anaconda) on Visual Stodio Code on my Mac. I have the following simple code:
def function(x):
y = x + 2
return y
This code is giving me the usual trouble, an indentation error:
return y
^
IndentationError: unexpected indent
>>> return y
File "<stdin>... | [
"This looks like it's because you're running the code with Shift+ENTER.\nVS Code has the following 2 bindings for Shift_ENTER:\n \nI believe that you're seeing the 2nd of these, which says \"Run Selection/Line in Python Terminal. I suspect you have the focus on the return y line, and so it's only running that singl... | [
4,
2
] | [
"Forgetting a semicolon at the end of the function definition produces the same error.\n"
] | [
-1
] | [
"indentation",
"python",
"python_2.7",
"visual_studio"
] | stackoverflow_0054276596_indentation_python_python_2.7_visual_studio.txt |
Q:
AlterField shows the error `Duplicate key name`
In my migration file, there is the AlterField like this
migrations.AlterField(
model_name='historicalglobalparam',
name='history_date',
field=models.DateTimeField(db_index=True),
),
my table historicalglobalparam has history_date colu... | AlterField shows the error `Duplicate key name` | In my migration file, there is the AlterField like this
migrations.AlterField(
model_name='historicalglobalparam',
name='history_date',
field=models.DateTimeField(db_index=True),
),
my table historicalglobalparam has history_date column
When appling this
$python manage.py migrate
The er... | [
"You might already have an index on that field. Try and remove that index like this answer suggests\n"
] | [
1
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0074402298_django_mysql_python.txt |
Q:
How to add decimal point in front of number in pandas column
I have the following data.
The column ['time_fall_asleep-minute'] represents the minute within the hour that one falls asleep.
The column ['time_fall_asleep-hour'] represents the hour that one falls asleep.
I would like to combine the two columns so that... | How to add decimal point in front of number in pandas column | I have the following data.
The column ['time_fall_asleep-minute'] represents the minute within the hour that one falls asleep.
The column ['time_fall_asleep-hour'] represents the hour that one falls asleep.
I would like to combine the two columns so that it gives an hour and minute reading.
Thus, the row at index 0 sho... | [
"You should be able to add them together as strings with a full stop in the middle:\nnewerdf[\"time_fall_asleep\"] = (\n str(int(newerdf['time_fall_asleep-hour']))\n + \".\" \n + str(int(newerdf['time_fall_asleep-minute']))\n)\n\n",
"Pandas has a dedicated Timedelta datatype, specifically for duration.\n... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074402346_dataframe_pandas_python.txt |
Q:
BeautifulSoup get text from an element containing substring
I'm scrapping a webpage that uploads different documents and I want to retrieve some information from this documents. At first I hard coded the scrapper to search the information on a certain xpath, but now I see that this might change depending on the do... | BeautifulSoup get text from an element containing substring | I'm scrapping a webpage that uploads different documents and I want to retrieve some information from this documents. At first I hard coded the scrapper to search the information on a certain xpath, but now I see that this might change depending on the document. Is there any way to get the text from an element that con... | [
"\nI expected this to return a list with all elements containing the substring \"Official name:\" but it gave me an empty list [].\n\nThat is because it needs an exact match, but you could use re.compile:\nimport re\nsoup.find_all(text = re.compile('Official name:'))\n\n\nHowever, why not using an alternative appro... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074401988_beautifulsoup_python_web_scraping.txt |
Q:
How do I add labels for a horizontal bar using matplotlib module?
Since I am a newbie, please tell me how I should add labels for each bar toward the right. And it would be kind of you to explain the code too...
Thank you.
This is the dataframe that I have used:
BG_donated Qty Hospi... | How do I add labels for a horizontal bar using matplotlib module? | Since I am a newbie, please tell me how I should add labels for each bar toward the right. And it would be kind of you to explain the code too...
Thank you.
This is the dataframe that I have used:
BG_donated Qty Hospital Location Contact
0 A- 25 Badr Al Sam... | [
"You mean like this?\n\nIf so,add \"for i,values in enumerate(y):\n mplt.text(values, i, '%s' %values)\" to your code.\n\n",
"y = df3['Qty'].sort_values()\nw = df3['Hospital']\nb = df3['BG_donated']\nc = ['coral', 'salmon', 'indianred', 'brown', 'crimson', 'aquamarine', \n 'lightseagreen', 'slategra... | [
2,
0
] | [] | [] | [
"bar_chart",
"matplotlib",
"plot",
"python"
] | stackoverflow_0074398109_bar_chart_matplotlib_plot_python.txt |
Q:
If statement not working in side def in class
So i am working with classes and if statements. When the if statement is inside the class def, it seems to be ignored and not sure what i am doing wrong. I want it to raise an exception if the criteria is not met.
I tried to change name to __name but that did not seem ... | If statement not working in side def in class | So i am working with classes and if statements. When the if statement is inside the class def, it seems to be ignored and not sure what i am doing wrong. I want it to raise an exception if the criteria is not met.
I tried to change name to __name but that did not seem to help. I also tried to remove def get_name(self) ... | [
"You never call the set_name function inside or outside of your class. If you want to check the name on the initialization of your class, you can call that function in your __init__ function like this:\nclass Strict:\n name:str\n\n def __init__(self,name):\n self.name = self.set_name(name)\n\n def g... | [
0,
0
] | [] | [] | [
"class",
"function",
"if_statement",
"methods",
"python"
] | stackoverflow_0074402385_class_function_if_statement_methods_python.txt |
Q:
How to extract nested dictionaries from dictionary into single dictionary?
I have a dictionary which contains some key-value pairs as strings, but some key-values are dictionaries.
The data looks like this:
{'amount': 123,
'baseUnit': 'test',
'currency': {'code': 'EUR'},
'dimensions': {'height': {'iri': 'http:/... | How to extract nested dictionaries from dictionary into single dictionary? | I have a dictionary which contains some key-value pairs as strings, but some key-values are dictionaries.
The data looks like this:
{'amount': 123,
'baseUnit': 'test',
'currency': {'code': 'EUR'},
'dimensions': {'height': {'iri': 'http://www.example.com/data/measurement-height-12345',
'uni... | [
"You can define a recursive flatten function that gets called whenever the dictionary value is a dictionary.\nAssuming python>=3.9:\ndef flatten(my_dict, prefix=\"\"):\n res = {}\n for k, v in my_dict.items():\n if isinstance(v, dict):\n res |= flatten(v, prefix+k)\n else:\n ... | [
2
] | [] | [] | [
"dataframe",
"dictionary",
"nested",
"pandas",
"python"
] | stackoverflow_0074402345_dataframe_dictionary_nested_pandas_python.txt |
Q:
How do I send available_apps in context to a view that is outside the admin panel in Django?
How can I get an application list like in get_app_list method in classy AdminSite?
I try to do it this way, but then I get an empty list.
from django.contrib.admin.sites import AdminSite
def change_view(self, request)... | How do I send available_apps in context to a view that is outside the admin panel in Django? | How can I get an application list like in get_app_list method in classy AdminSite?
I try to do it this way, but then I get an empty list.
from django.contrib.admin.sites import AdminSite
def change_view(self, request):
...
context = {
...
'available_apps': AdminSite().get_a... | [
"You're calling AdminSite, I'm not sure but that might be incorrect according to docs.\nDoes AdminSite.get_app_list(request) work?\n",
"Try this:\nfrom django.apps import apps\n\nfor app in apps.get_app_configs():\n print(app.verbose_name)\n\n"
] | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074402458_django_python.txt |
Q:
Django Add 2 Numbers and get Name and print it back in an html
I'm new to python and django
What is the correct syntax to render number and text?
I want to get the name and add 2 numbers from addition.html and print it back to results.html
I tried this code
def add(request):
my_context = {
'fname' : req... | Django Add 2 Numbers and get Name and print it back in an html | I'm new to python and django
What is the correct syntax to render number and text?
I want to get the name and add 2 numbers from addition.html and print it back to results.html
I tried this code
def add(request):
my_context = {
'fname' : request.GET['first_name'],
'val1' : int(request.GET['num1']),
... | [
"Both\n return render(request, \"result.html\", my_context)\n return render(request, \"result.html\", {'result': res})\n\nwill work.\nrender syntax:\nNext you need to use the context variables in results.html\nresults.html // if you used the first one otherwise only 'result' can be used in the html file\n {{ fname... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074400653_django_python.txt |
Q:
I want to download F&O BhavCopy from the below link using Selenium Python
https://www1.nseindia.com/products/content/derivatives/equities/archieve_fo.htm
Here after entering the required details, I have tried many times to click on "GetData" button, but Selenium doesn't click on the button. I have tried Below lin... | I want to download F&O BhavCopy from the below link using Selenium Python | https://www1.nseindia.com/products/content/derivatives/equities/archieve_fo.htm
Here after entering the required details, I have tried many times to click on "GetData" button, but Selenium doesn't click on the button. I have tried Below lines of code to click on button but still got no luck.
driver.find_element(By.CSS... | [
"I tried to create a small script for that and I see what you mean. Nothing happens after the click.\nI analyzed the behavior and I see that the click happens but for some reason all the requests hang in Pending status.\n\nSo, after the click, a request https://www1.nseindia.com/ArchieveSearch?h_filetype=fobhavzip&... | [
0
] | [] | [] | [
"python",
"selenium",
"webdriver"
] | stackoverflow_0074400766_python_selenium_webdriver.txt |
Q:
What features do glitched images have that I could detect?
I'm trying to build a footage filter that only sends only "good" frames to the database.
Here is my current rating function:
def rateImg(img):
try:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
except:
gray = img
edges = cv2.Cann... | What features do glitched images have that I could detect? | I'm trying to build a footage filter that only sends only "good" frames to the database.
Here is my current rating function:
def rateImg(img):
try:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
except:
gray = img
edges = cv2.Canny(gray, 0, 255)
countours, _ = cv2.findContours(
edg... | [
"Is there any way to detect obvious glitches in an image?\nYes, but probably not for complex random glitches, have a look in this similar question\nIn that case, you can detect if there is a large area of the image containing the same color. Photo taken from the camera would never contain the same RGB value althoug... | [
2,
1
] | [] | [] | [
"image_processing",
"opencv",
"python"
] | stackoverflow_0066495199_image_processing_opencv_python.txt |
Q:
Is this the right strategy for Cloud Functions (Gen 2) for API requests?
I am trying to build GCP Cloud Functions which are triggered via Cloud Scheduler to collect odds data from bookmakers API's for a variety of different sports and competitions that run on different schedules.
I am looking for some advice on my... | Is this the right strategy for Cloud Functions (Gen 2) for API requests? | I am trying to build GCP Cloud Functions which are triggered via Cloud Scheduler to collect odds data from bookmakers API's for a variety of different sports and competitions that run on different schedules.
I am looking for some advice on my approach about if it is the right strategy or if there is a better way to ach... | [
"The above could be achieved by performing asynchronous calls as PubSub. For this you have to:\n\nCreate a PubSub topic\nDeploy the Cloud Function 2[CF2] with a trigger on PubSub event on\nthe previously created topic\nDeploy the Cloud function 3[CF3] with a trigger on PubSub event on\nthe previously created top... | [
0
] | [] | [] | [
"google_cloud_firestore",
"google_cloud_functions",
"google_cloud_platform",
"google_cloud_scheduler",
"python"
] | stackoverflow_0074369077_google_cloud_firestore_google_cloud_functions_google_cloud_platform_google_cloud_scheduler_python.txt |
Q:
Why do I get an AttributeError when adding a string field to a dataclass instantiated by an Enum?
I'm confused by this behavior: I have a frozen dataclass of which only 10 are ever needed, so I wanted to put them into an Enum, and did so successfully. Later, I realized I wanted to be able to put a name on them, an... | Why do I get an AttributeError when adding a string field to a dataclass instantiated by an Enum? | I'm confused by this behavior: I have a frozen dataclass of which only 10 are ever needed, so I wanted to put them into an Enum, and did so successfully. Later, I realized I wanted to be able to put a name on them, and all of a sudden, the Enum can't instantiate the dataclass.
import enum
import dataclasses as dc
clas... | [
"After some time I figured this out. Apparently, Enum has a built-in un-settable field called name which collides with your identically named field name. If you change the name of name to something else, this will work as expected.\n"
] | [
3
] | [] | [] | [
"enums",
"python",
"python_3.10",
"python_dataclasses"
] | stackoverflow_0074400049_enums_python_python_3.10_python_dataclasses.txt |
Q:
Append the output results to existing pandas dataframe
I am currently working on a web scraping company logos with clearbit API. Like below(see code)
import pandas as pd
from selenium import webdriver
from bs4 import BeautifulSoup
data = {'name': ['tcs', 'orange', 'linkedin'],
'domain': ["tcs.com",
... | Append the output results to existing pandas dataframe | I am currently working on a web scraping company logos with clearbit API. Like below(see code)
import pandas as pd
from selenium import webdriver
from bs4 import BeautifulSoup
data = {'name': ['tcs', 'orange', 'linkedin'],
'domain': ["tcs.com",
"orange.com",
"linkedin.c... | [
"You are iterating over all domains. So if you append all urls to a list during the iteration, you can simply add a key to the dictionary.\nurl_list = []\nfor i in df['domain']:\n driver.get(\"https://logo.clearbit.com/\" + str(i))\n clear_api_html = BeautifulSoup(driver.page_source, 'html.parser')\n clear... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074402191_dataframe_pandas_python.txt |
Q:
Python display image on second monitor
I'm using the following script to display an image and it's working. I would like to send the output (image) to a secondary display which connected through HDMI. What's the best way to implement this?
from PIL import Image
im = Image.open("path_to_file/1.png")
im.show()
I f... | Python display image on second monitor | I'm using the following script to display an image and it's working. I would like to send the output (image) to a secondary display which connected through HDMI. What's the best way to implement this?
from PIL import Image
im = Image.open("path_to_file/1.png")
im.show()
I found the solution below (screeninfo package)... | [
"Set display device in terminal before running your code.\nFollow these steps\nThis command at a console would provide the available video devices in linux os\nls /dev/video* \n\nThis allow to use video device, as here I used 0.\nexport DISPLAY=:0 \n\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"python_imaging_library"
] | stackoverflow_0074402145_python_python_3.x_python_imaging_library.txt |
Q:
Unexpected behavior for contourplot in polar coordinates - jagged contours
I wish to plot a bunch of points onto a polar plot. When I apply it with simulated data, it works. When I try the same with my real data it fails and I'm not sure why.
# First with simulated data
# The angles for each point
phi = np.linspa... | Unexpected behavior for contourplot in polar coordinates - jagged contours | I wish to plot a bunch of points onto a polar plot. When I apply it with simulated data, it works. When I try the same with my real data it fails and I'm not sure why.
# First with simulated data
# The angles for each point
phi = np.linspace(0, math.pi*2, 40) # full circle
phi = np.concatenate([phi, phi, phi, phi]) # ... | [
"This behaviour is due to the fact that rho and phi are not sorted. Let's see:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nrho = np.array([0.38818333, 0.73367091, 0.42336148, 1.39013061, 0.31064486,0.34546275, 0.05445943, 0.85551576, 0.55174167, 1.42371249,0.17644804, 1.76221456, 0.64519126, 0.02408941,... | [
3
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0074401044_matplotlib_numpy_python.txt |
Q:
Docker mounting image error executable file not found in $PATH: unknown
I have a directory in which code files and subdirectories are, i want to mount these files to the docker image and run the index.py
my docker file looks like this:
# Selected base python version
FROM python:3.9.6
COPY requirements.txt ./
# I... | Docker mounting image error executable file not found in $PATH: unknown | I have a directory in which code files and subdirectories are, i want to mount these files to the docker image and run the index.py
my docker file looks like this:
# Selected base python version
FROM python:3.9.6
COPY requirements.txt ./
# Install all packages - see readme to create the requirements.txt
RUN pip insta... | [
"The solution is to change the file:\n# Selected base python version\nFROM python:3.9.6\n\nCOPY requirements.txt ./\n\n# Install all packages - see readme to create the requirements.txt\nRUN pip install -r requirements.txt\n\n# Port the container listens\nEXPOSE 5000\nCMD [\"python3\", \"app/index.py\"]\n\n\nand ru... | [
0
] | [] | [] | [
"docker",
"dockerfile",
"python"
] | stackoverflow_0074402116_docker_dockerfile_python.txt |
Q:
How to filter using regex with grouping in python
I want to filter the following string with some of the words bunched together.
country = "Papua New Guinea Marshall Islands Samoa Solomon Islands Tajikistan Uzbekistan Viet Nam"
Desired result:
["Papua New Guinea", "Marshall Islands", "Samoa", "Solomon Islands", "... | How to filter using regex with grouping in python | I want to filter the following string with some of the words bunched together.
country = "Papua New Guinea Marshall Islands Samoa Solomon Islands Tajikistan Uzbekistan Viet Nam"
Desired result:
["Papua New Guinea", "Marshall Islands", "Samoa", "Solomon Islands", "Tajikistan", "Uzbekistan", "Viet Nam"]
I've tried:
re.... | [] | [] | [
"Like people write in the comments: it can not be done. Python doesn't know \"Papua New Guinea\" is a country, but \"Islands Samoa\" isn't.\n"
] | [
-2
] | [
"python",
"regex"
] | stackoverflow_0074377171_python_regex.txt |
Q:
'Continue' Function in Python
I have a question about the 'continue' function in Python. I wolud like to skip 'Antarctic' in the following list:
continents = = ["Afrika", "Antarktic", "Asien", "Australia", "Europe", "North America", "South America"]
I thought about using the for loop in combination with the 'cont... | 'Continue' Function in Python | I have a question about the 'continue' function in Python. I wolud like to skip 'Antarctic' in the following list:
continents = = ["Afrika", "Antarktic", "Asien", "Australia", "Europe", "North America", "South America"]
I thought about using the for loop in combination with the 'continue' function but it doesn't work.... | [
"Given your sample list:\ncontinents = [\n \"Afrika\",\n \"Antarktic\",\n \"Asien\",\n \"Australia\",\n \"Europe\",\n \"North America\",\n \"South America\",\n]\n\nYou are iterating through this list, so i is the value of each string as you're going along:\nfor i in continents: # i: str\n\nSo at this point,... | [
0,
0,
0
] | [
"If I am not wrong, you want to skip the print function, if the value is equals to \"Antarctica\".\ncontinents = [\n \"Afrika\",\n \"Antarctica\",\n \"Asien\",\n \"Australia\",\n \"Europe\",\n \"North America\",\n \"South America\",\n]\n\n# If want to skip based on the value, use below code\nfo... | [
-1
] | [
"continue",
"for_loop",
"list",
"python",
"python_3.x"
] | stackoverflow_0074402488_continue_for_loop_list_python_python_3.x.txt |
Q:
How can I access tag's value inside id with beautifulsoap in python?
I 'm trying to pull data from website with beautifulsoap in python but the data confused me a bit and I don't quite understand how to do it. What I want to do is actually pull certain data. I just want to capture the title, examples ,meaning and ... | How can I access tag's value inside id with beautifulsoap in python? | I 'm trying to pull data from website with beautifulsoap in python but the data confused me a bit and I don't quite understand how to do it. What I want to do is actually pull certain data. I just want to capture the title, examples ,meaning and origin data in the page, how can I do that?
I will share my own code but t... | [
"Try to keep it simple and select your elements more specific by tag, id or class and try to avoid using reserved keywords as variable names:\ndata = []\n\nfor i in mylist:\n result = requests.get(url+i+\"/\", headers = headers)\n doc = BeautifulSoup(result.text)\n\n for tag in doc.select('.linktitle a'):\... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074402300_beautifulsoup_python_web_scraping.txt |
Q:
Bypass SSL certificate in Python using urllib
I am trying to bypass the SSL Certificate and use the URL in Python,
All HTTPS sites are getting the same error
Kindly suggest how can it get resolved. Thanks in Advance.
Code:
import urllib.request as ur
import urllib.parse, urllib.error, ssl
url_is = 'https://financ... | Bypass SSL certificate in Python using urllib | I am trying to bypass the SSL Certificate and use the URL in Python,
All HTTPS sites are getting the same error
Kindly suggest how can it get resolved. Thanks in Advance.
Code:
import urllib.request as ur
import urllib.parse, urllib.error, ssl
url_is = 'https://finance.yahoo.com'
url_google = 'https://www.google.co.i... | [
"\nTemporary failure in name resolution\n\nThis means that no IP address for the given hostname can be found. This is completely unrelated to SSL and thus no \"bypass SSL certificate\" will help.\nThe problem is instead that DNS does not properly work in the software environment where this code is run. This needs t... | [
1
] | [] | [] | [
"python",
"ssl",
"urllib"
] | stackoverflow_0074402639_python_ssl_urllib.txt |
Q:
How can I set a system like a turn order with 6 ints?
I'm trying to set a turn order on a text-based game but I don't know how to set it up correctly.
I've tried to set it this way, I know it's all wrong but it's just to give an example that what I'm expecting.
#EXAMPLES RESULTS
WarriorTurnOrder = 23
PriestTurnOrd... | How can I set a system like a turn order with 6 ints? | I'm trying to set a turn order on a text-based game but I don't know how to set it up correctly.
I've tried to set it this way, I know it's all wrong but it's just to give an example that what I'm expecting.
#EXAMPLES RESULTS
WarriorTurnOrder = 23
PriestTurnOrder = 15
vampire1TurnOrder = 20
vampire2TurnOrder = 5
vampir... | [
"A way of doing it while more or less sticking to your code structure would be as follows:\n# Contains information about the players/enemies, their order, and the function to call when it's their turn\nturn_orders = {\n \"warrior\": {\"order\": 23, \"turn_func\":warrior_turn},\n \"priest\": {\"order\": 15, \"... | [
2
] | [] | [] | [
"python",
"python_3.x",
"text_based"
] | stackoverflow_0074402523_python_python_3.x_text_based.txt |
Q:
How to find red points (in square borders)
How to find this points if we know only radius and a?
i just know how to find the points in circle borders. but how to do this with square. I have attached code example. And get errors in square_borders. Dont know how to fix it
import numpy as np
import math
import cv2
... | How to find red points (in square borders) | How to find this points if we know only radius and a?
i just know how to find the points in circle borders. but how to do this with square. I have attached code example. And get errors in square_borders. Dont know how to fix it
import numpy as np
import math
import cv2
map = np.zeros((500,500), dtype=np.int8)
cv2.cir... | [
"Perhaps,\ndef square_borders(start_angle,step_angle):\n for _ in range(ray_numbers):\n b = max(abs(math.sin(start_angle)), abs(math.cos(start_angle)))\n target_x = round(position[1] - r * math.sin(start_angle) / b)\n target_y = round(position[0] - r * math.cos(start_angle) / b)\n cv2... | [
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0074401677_math_python.txt |
Q:
How to use polars dataframes with scikit-learn?
I'm unable to use polars dataframes with scikitlearn for ML training.
Currently I'm doing all the dataframe preprocessing in polars and during model training i'm converting it into a pandas one in order for it to work.
Is there any method to directly use polars dataf... | How to use polars dataframes with scikit-learn? | I'm unable to use polars dataframes with scikitlearn for ML training.
Currently I'm doing all the dataframe preprocessing in polars and during model training i'm converting it into a pandas one in order for it to work.
Is there any method to directly use polars dataframe as it is for ML training without changing it to ... | [
"You must call to_numpy when passing a DataFrame to sklearn. Though sometimes sklearn can work on polars Series it is still good type hygiene to transform to the type the host library expects.\nimport polars as pl\nfrom sklearn.linear_model import LinearRegression\n\ndata = pl.DataFrame(\n np.random.randn(100, 5... | [
0,
0
] | [] | [] | [
"machine_learning",
"python",
"python_polars",
"scikit_learn"
] | stackoverflow_0074398563_machine_learning_python_python_polars_scikit_learn.txt |
Q:
How to edit a embed using message_id?
I am trying to make on reaction edit embed...
@bot.event
async def on_raw_reaction_add(payload):
channel = await bot.fetch_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
if payload.emoji.name == "✅":
await message.set_field_at(... | How to edit a embed using message_id? | I am trying to make on reaction edit embed...
@bot.event
async def on_raw_reaction_add(payload):
channel = await bot.fetch_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
if payload.emoji.name == "✅":
await message.set_field_at(4,"Status:","Accepted")
elif payload.emoj... | [
"According to the documentation:\nhttps://discordpy.readthedocs.io/en/stable/api.html?highlight=fetch_emoji#discord.Guild.fetch_emoji\nYou want to call await fetch_emoji(id) with the emoji id and not the PartialEmoji object (which your emoji variable is). Instead use fetch_emoji(emoji.id)\nTry the following:\n@bot.... | [
0
] | [] | [] | [
"discord",
"discord.py",
"disnake",
"python"
] | stackoverflow_0074397547_discord_discord.py_disnake_python.txt |
Q:
Python Polars: How to apply a aggregate function for all columns and pass one additional column as argument?
I have a lazy dataframe (using scan_parquet) like below,
region time sen1 sen2 sen3
us 1 10.0 11.0 12.0
us 2 11.0 14.0 13.0
us 3 10.1 10.0 12.3
us 4 ... | Python Polars: How to apply a aggregate function for all columns and pass one additional column as argument? | I have a lazy dataframe (using scan_parquet) like below,
region time sen1 sen2 sen3
us 1 10.0 11.0 12.0
us 2 11.0 14.0 13.0
us 3 10.1 10.0 12.3
us 4 13.0 11.1 14.0
us 5 12.0 11.0 19.0
uk 1 10.0 11.0 12.1
uk 2 11.0 14.... | [
"You could .melt() and .sort() first.\nThen when you .groupby() you can use .first() and .last() to get the min/max for time and value.\npl.all() can be used instead of pl.col(\"*\")\n>>> (\n... df\n... .melt([\"region\", \"time\"], variable_name=\"sname\")\n... .sort(pl.all().exclude(\"time\"))\n... .g... | [
0
] | [] | [] | [
"python",
"python_polars"
] | stackoverflow_0074398538_python_python_polars.txt |
Q:
Why does the code not show the numbers that are less than 15? Break loop
a program that will iterates over each number in a the list then the if statement will check whether the iteration/number is greater than 15 then the loop will stop, otherwise the number from the list will be printed.
List = [1, 4, 7, 8, 15, ... | Why does the code not show the numbers that are less than 15? Break loop | a program that will iterates over each number in a the list then the if statement will check whether the iteration/number is greater than 15 then the loop will stop, otherwise the number from the list will be printed.
List = [1, 4, 7, 8, 15, 20, 35, 45, 55]
List = [1, 4, 7, 8, 15, 20, 35, 45, 55]
for i in List:
if ... | [
"List = [1, 4, 7, 8, 15, 20, 35, 45, 55]\nfor i in List:\n#print(i)\nif i > 15:\n break\nelif i > 1:\n pass\nprint(i)\n\n"
] | [
0
] | [
"Place your print statement inside the elif check.\nList = [1, 4, 7, 8, 15, 20, 35, 45, 55]\nfor i in List:\n if i >= 15:\n break\n elif i > 1:\n print(i)\n\n"
] | [
-1
] | [
"break",
"continue",
"if_statement",
"loops",
"python"
] | stackoverflow_0074402769_break_continue_if_statement_loops_python.txt |
Q:
Scrapy - selecting with custom attribute value
I need to scrap some data not with CSS class but with custom atrribute value.
<div data-testid="total-count">We found 45 offers</div>
So I need something like that:
response.css('div.total-count::text').get()
Is it possible?
A:
Yes, you use CSS Attribute Selectors... | Scrapy - selecting with custom attribute value | I need to scrap some data not with CSS class but with custom atrribute value.
<div data-testid="total-count">We found 45 offers</div>
So I need something like that:
response.css('div.total-count::text').get()
Is it possible?
| [
"Yes, you use CSS Attribute Selectors.\nFor example:\nresponse.css('div[data-testid=\"total-count\"]::text').get()\n\n"
] | [
1
] | [] | [] | [
"python",
"scrapy",
"web_scraping"
] | stackoverflow_0074402659_python_scrapy_web_scraping.txt |
Q:
Tensorflow lite ValueError: The size of the validation_data (0) couldn't be smaller than batch_size (64)
I am experimenting with tensorflow lite with a script like this:
import numpy as np
import os
from tflite_model_maker.config import ExportFormat, QuantizationConfig
from tflite_model_maker import model_spec
fr... | Tensorflow lite ValueError: The size of the validation_data (0) couldn't be smaller than batch_size (64) | I am experimenting with tensorflow lite with a script like this:
import numpy as np
import os
from tflite_model_maker.config import ExportFormat, QuantizationConfig
from tflite_model_maker import model_spec
from tflite_model_maker import object_detector
from tflite_support import metadata
import tensorflow as tf
ass... | [
"This whole problem turned out to be an error in the path name to the folders of the training/validate directories.\nprint(len(train_data))\nprint(train_data)\n\nWas zero and nothing...so I was expecting that the tensorflow would through a directory path error but if the directory doesnt exist it will just be zero ... | [
0
] | [] | [] | [
"computer_vision",
"machine_learning",
"python",
"tensorflow",
"tensorflow_lite"
] | stackoverflow_0074395126_computer_vision_machine_learning_python_tensorflow_tensorflow_lite.txt |
Q:
Wrong dates in the index plotly with a second graph I did not ask for
I am trying to plot some graphs with plotly and, after several times having the wrong graph, i backed to the basics and tried to plot an example from the plotly web, but the same error appears:
My dates are not dates, but an extremely high numbe... | Wrong dates in the index plotly with a second graph I did not ask for | I am trying to plot some graphs with plotly and, after several times having the wrong graph, i backed to the basics and tried to plot an example from the plotly web, but the same error appears:
My dates are not dates, but an extremely high number (10^18 order) and I get a second small graph that noone asked for.
import... | [
"OK, I managed to fix the date problem inserting the index with dates in an array and using that array as the x.\nAlso, I figured out that the second small graph only appears with the go.Candlestick representation (since it does not appear with figure_factory or go.Scatter hehe).\nThanks :)\n"
] | [
0
] | [] | [] | [
"candlestick_chart",
"graph",
"plot",
"plotly",
"python"
] | stackoverflow_0052203512_candlestick_chart_graph_plot_plotly_python.txt |
Q:
Addition of integer input through while loop
I'm trying to create a while loops where you can input as many integers as you want. The input gets summed up and printed only when I type in the number 0.
Currently I have written the following:
n = int(input())
sum = 0
while n != 0:
sum = sum + n
print(sum)
Whe... | Addition of integer input through while loop | I'm trying to create a while loops where you can input as many integers as you want. The input gets summed up and printed only when I type in the number 0.
Currently I have written the following:
n = int(input())
sum = 0
while n != 0:
sum = sum + n
print(sum)
When I enter in the 0 value the loop does not close a... | [
"The Problem here is that you can only input 1 number than the code is stuck in the while loop. So if you want to sum multiple inputs the input needs to be in the while loop. Try this..\nresult = 0\nwhile True:\n n = int(input())\n if n == 0:\n print(result)\n break\n else:\n result +=... | [
1
] | [] | [] | [
"loops",
"python",
"python_3.x",
"while_loop"
] | stackoverflow_0074403027_loops_python_python_3.x_while_loop.txt |
Q:
Count the occurrences of each character in a alpha-numeric column in a DataFrame
I have a alpha-numeric column in a DataFrame. I would like get the total count of each characters(0-9, A-Z) occurs in the entire column.
e.g.
Serial
03000395
A000458B
667BC345
Desired Output
Character Counts
0 7
1 ... | Count the occurrences of each character in a alpha-numeric column in a DataFrame | I have a alpha-numeric column in a DataFrame. I would like get the total count of each characters(0-9, A-Z) occurs in the entire column.
e.g.
Serial
03000395
A000458B
667BC345
Desired Output
Character Counts
0 7
1 0
2 0
3 3
.
.
A 1
B 2
C ... | [
"You can use Counter to get this\nfrom collections import Counter\nCounter('03000395 A000458B 667BC345)\n\nOutput:\nCounter({'0': 7,\n '3': 3,\n '9': 1,\n '5': 3,\n ' ': 2,\n 'A': 1,\n '4': 2,\n '8': 1,\n 'B': 2,\n '6': 2,\n '7': 1,\n ... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074403057_dataframe_pandas_python.txt |
Q:
Error in positive lookbehind and positive lookahead regex - python
I have the following regex
(?i)(?<=\b(?:host)\s*(?:name)\s*[-|:|=|\s]\s*)(?=.*[^\s][\d\_\-\.].*)([a-zA-Z0-9\(\)\._\-\'\"]{5,})
Here I am trying to find hostname values in the regex.
My requirements are:
hostname should have a digit or _ or - or . ... | Error in positive lookbehind and positive lookahead regex - python | I have the following regex
(?i)(?<=\b(?:host)\s*(?:name)\s*[-|:|=|\s]\s*)(?=.*[^\s][\d\_\-\.].*)([a-zA-Z0-9\(\)\._\-\'\"]{5,})
Here I am trying to find hostname values in the regex.
My requirements are:
hostname should have a digit or _ or - or . in them
hostname can consist of alphabets digits ( ) . _ - ' "
The pat... | [
"I don't know if you solved your problem yet, but this can work for you:\nhost\\s?name\\s?[:|=|\\-|\\s]\\s?(?=.*)(?=[a-zA-Z]*\\d|[a-zA-Z]*[.-_])([\\w.-]+[a-zA-Z0-9])(?=\\s|$)\n\nrefer to the demo here\nyou will need to use groups to get the hostname out of the matches.\n"
] | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074374722_python_regex.txt |
Q:
Double header in Matplotlib Table
I need to plot a table in matplotlib. The problem is some columns have one-level headers, some columns have double-level headers.
Here's what I need:
Here's simple example for one-level headers:
df = pd.DataFrame()
df['Animal'] = ['Cow', 'Bear']
df['Weight'] = [250, 450]
df['Fav... | Double header in Matplotlib Table | I need to plot a table in matplotlib. The problem is some columns have one-level headers, some columns have double-level headers.
Here's what I need:
Here's simple example for one-level headers:
df = pd.DataFrame()
df['Animal'] = ['Cow', 'Bear']
df['Weight'] = [250, 450]
df['Favorite'] = ['Grass', 'Honey']
df['Least ... | [
"Cell merge solution\nYou can merge the cells produced by ax.table, a la the cell merge function in an Excel spreadsheet. This allows for a completely automated solution in which you don't need to fiddle with any coordinates (save for the indices of the cell you want to merge):\nimport matplotlib.pyplot as plt\nimp... | [
12,
6,
5,
2,
0
] | [] | [] | [
"data_visualization",
"matplotlib",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0053783087_data_visualization_matplotlib_pandas_python_python_3.x.txt |
Q:
how to remove square brackets in my print statement
Sort the k arrays individually and concatenate them.
Input Description:
First line contains the number of arrays. Subsequent lines contain the size of the array followed by the elements of the array.
Output Description:
An array containing the sorted elements of ... | how to remove square brackets in my print statement | Sort the k arrays individually and concatenate them.
Input Description:
First line contains the number of arrays. Subsequent lines contain the size of the array followed by the elements of the array.
Output Description:
An array containing the sorted elements of k sorted arrays
Sample Input :
3
2
98 12
6
1 2 3 8 5 9
1
... | [
"import re\nval = \"[ ' 1 2 ' , ' 9 8 ' ] [ ' 1 ' , ' 2 ' , ' 3 ' , ' 5 ' , ' 8 ' , ' 9 ' ] [ ' 1 1 ' ]\"\nprint(re.sub(r'[^\\w]', ' ', val))\n\nI am sure it work's for you.\n",
"x = C + E + G\nx = x.replace('[', '').replace(']', ' ').replace(\"'\", '').replace(',', '')\nprint(x)\n\nhope it will work\... | [
2,
0,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0074384406_python_sorting.txt |
Q:
Filling missing values based on a specific column condition
I have a data frame like this :
Day
Type
From
to
01/09/2021
car
170
Nan
02/09/2021
car
140
Nan
03/09/2021
none
120
77
04/09/2021
car
15
45
05/09/2021
car
34
Nan
06/09/2021
car
36
84
07/09/2021
none
23
11
08/09/2021
car
36
Nan
The logic is
For ea... | Filling missing values based on a specific column condition | I have a data frame like this :
Day
Type
From
to
01/09/2021
car
170
Nan
02/09/2021
car
140
Nan
03/09/2021
none
120
77
04/09/2021
car
15
45
05/09/2021
car
34
Nan
06/09/2021
car
36
84
07/09/2021
none
23
11
08/09/2021
car
36
Nan
The logic is
For each row containing a Type none
fill the previous ... | [
"Here in the ind list, the indexes of the rows are copied, where 'Type' == 'none'. The dataframe is copied to aaa through a slice on the first element of ind. In ind1 I get the indices of the first rows with 'to' == 'Nan' and set the values via loc.\nind_to its elements are fed into list comprehensions, the desired... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074389673_pandas_python.txt |
Q:
Convert a bytearray to a integer array in Python
I have the following bytearray in Python:
bytearray(b'\x02\xcb\x00\n\x02\xcb\x00\n\x02\xcb\x00\n\x02\xcb\x00\n')
I want to convert the hexa values of the bytearray to an array of integer values, by converting \x02\xcb\x00 to an integer 183040 for each '\n'.
It shou... | Convert a bytearray to a integer array in Python | I have the following bytearray in Python:
bytearray(b'\x02\xcb\x00\n\x02\xcb\x00\n\x02\xcb\x00\n\x02\xcb\x00\n')
I want to convert the hexa values of the bytearray to an array of integer values, by converting \x02\xcb\x00 to an integer 183040 for each '\n'.
It should look like:
[183040, 183040, 183040, 183040]
How ca... | [
"You might be tempted to split the bytes by the newline character, but the ASCII value of the newline character (10), might show up as part of the integer byte.\nThe only way this can work, is if the newline character always delimits 3 bytes of the integer.\nIn this case, you need to iterate over the bytes and take... | [
1,
0,
0
] | [] | [] | [
"arrays",
"python",
"python_3.x"
] | stackoverflow_0074402545_arrays_python_python_3.x.txt |
Q:
How to force labels in scientific notation in matplotlib?
I would like to plot the following data and I cannot seem to get matplotlib to show more axis labels.
import matplotlib.pyplot as plt
from matplotlib.ticker import LogLocator, LogFormatterMathtext
fig, ax = plt.subplots()
ax.set_yscale("log")
ax.get_yaxis()... | How to force labels in scientific notation in matplotlib? | I would like to plot the following data and I cannot seem to get matplotlib to show more axis labels.
import matplotlib.pyplot as plt
from matplotlib.ticker import LogLocator, LogFormatterMathtext
fig, ax = plt.subplots()
ax.set_yscale("log")
ax.get_yaxis().set_major_locator(LogLocator(subs=(1,2,3,4,5,6,7,8,9,)))
ax.ge... | [
"So first thing, you don't obviously want LogFormatterMathtext. That would produce this kind of images if you had your way with \"one label per tick\" (we'll come to that in one moment).\n\nThe one you want is LogFormatterSciNotation.\n(LogFormatter alone would label \"500\", \"600\", \"700\", \"800\", \"900\", \"1... | [
0
] | [] | [] | [
"axis_labels",
"formatting",
"graph",
"matplotlib",
"python"
] | stackoverflow_0074394980_axis_labels_formatting_graph_matplotlib_python.txt |
Q:
Adding permissions to user on the serializer
I'm trying to add/update permissions for users by id on the serializer, but nothing changed (no add no update) and I don't get any errors so I can't know where is the problem, I have tried several methods and nothing works.
serializer (update):
class UpdateSerializer(se... | Adding permissions to user on the serializer | I'm trying to add/update permissions for users by id on the serializer, but nothing changed (no add no update) and I don't get any errors so I can't know where is the problem, I have tried several methods and nothing works.
serializer (update):
class UpdateSerializer(serializers.ModelSerializer):
"""Handle serializ... | [
"i changed the serializer to:\nclass UpdateSerializer(serializers.ModelSerializer):\n \"\"\"Handle serialization and deserialization of User objects.\"\"\"\n\n # user_permissions = PermissionSerializer(many=True, read_only=True)\n user_permissions = serializers.SlugRelatedField(\n many=True, queryse... | [
0
] | [] | [] | [
"django",
"django_permissions",
"django_rest_framework",
"python"
] | stackoverflow_0074391152_django_django_permissions_django_rest_framework_python.txt |
Q:
python recursion function global variable scope
i am trying to get into more global and local scopes in python. My code is below, it recursively invokes itself. I tried to put there limitation while var i less 6. What I got is strange, that i varibale cannot be seen in while i <6
from random import choice
global ... | python recursion function global variable scope | i am trying to get into more global and local scopes in python. My code is below, it recursively invokes itself. I tried to put there limitation while var i less 6. What I got is strange, that i varibale cannot be seen in while i <6
from random import choice
global i
i=0
def random_color_code():
hex_chars=['0','1'... | [
"If you are determined to implement this using a global variable and recursion, as an experiment, this is how you might do it:\ndef random_color_code(length=6):\n hex_chars = ['0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']\n global i # global statement needs to be inside the f... | [
1,
1
] | [] | [] | [
"python",
"scope"
] | stackoverflow_0074401379_python_scope.txt |
Q:
What is the type of *args, *kwargs and **kwargs in Python?
When printing args and kwargs:
def test(*args, **kwargs):
print(args) # Here
print(kwargs) # Here
nums = (1, 2, 3, 4)
person = {
"name": "John",
"age": 27,
}
test(*nums, **person)
A tuple and a dictionary are printed:
(1, 2, 3, ... | What is the type of *args, *kwargs and **kwargs in Python? | When printing args and kwargs:
def test(*args, **kwargs):
print(args) # Here
print(kwargs) # Here
nums = (1, 2, 3, 4)
person = {
"name": "John",
"age": 27,
}
test(*nums, **person)
A tuple and a dictionary are printed:
(1, 2, 3, 4)
{'name': 'John', 'age': 27}
And, when printing *args and *kw... | [
"*args and **kwargs are not expressions, and thus have no type; they are part of the syntax of a def statement. Note that the names are arbitrary; it's the act of prefixing them with * or ** that produces special behavior.\n*args captures all positional arguments not assigned to positional parameters to a single tu... | [
1
] | [] | [] | [
"arguments",
"python",
"python_3.x",
"types",
"variadic_functions"
] | stackoverflow_0074402649_arguments_python_python_3.x_types_variadic_functions.txt |
Q:
How to extend the x-axis for matplotlib
I have a code given below:
import pandas as pd
import plotly.offline as py
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import matplotlib.patches as mpatches
import matplotlib.dates as mdates
import matplotlib as mpl
df = pd.read_csv(".\AirPassengers.csv... | How to extend the x-axis for matplotlib | I have a code given below:
import pandas as pd
import plotly.offline as py
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import matplotlib.patches as mpatches
import matplotlib.dates as mdates
import matplotlib as mpl
df = pd.read_csv(".\AirPassengers.csv")
df['Month'] = pd.to_datetime(df['Month'])
... | [
"The easiest and most reliable method is to extend the original data by the desired time-series period and fill in the missing data with NA. Specify the start date of the data and the end date of the data with set_xlim(), as described in the comments in the graph-side processing.\ndf['Month'] = pd.to_datetime(df['M... | [
1,
1
] | [] | [] | [
"dataframe",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0071623661_dataframe_matplotlib_pandas_python.txt |
Q:
python get data json value max
How can I extract the T3 Period, Year and maximum value?
file.json
[
{"Fecha":"2022-08-01T00:00:00.000+02:00", "T3_TipoDato":"Avance", "T3_Periodo":"M08", "Anyo":2022, "value":10.4},
{"Fecha":"2022-07-01T00:00:00.000+02:00", "T3_TipoDato":"Definitivo", "T3_Periodo":"M07", "Anyo":2022... | python get data json value max | How can I extract the T3 Period, Year and maximum value?
file.json
[
{"Fecha":"2022-08-01T00:00:00.000+02:00", "T3_TipoDato":"Avance", "T3_Periodo":"M08", "Anyo":2022, "value":10.4},
{"Fecha":"2022-07-01T00:00:00.000+02:00", "T3_TipoDato":"Definitivo", "T3_Periodo":"M07", "Anyo":2022, "value":10.8},
{"Fecha":"2022-06-0... | [
"that is my proposition.\n\nLoad data from a file to a list.\nLoop thru every dict in a list to edit it.\n(At my example I, deleted two keys from every dict in list.)\n\n import json\n \n distros_dict = []\n \n with open(f'file.json', \"r\", encoding='utf-8') as f:\n distros_dict.extend(json.load(f)... | [
0,
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074393116_json_python.txt |
Q:
How to get a child thread to close when main GUI window is closed in pyqt5 / python 3?
I am writing a GUI using pyqt5 (Python 3.6). I am trying to run another thread in parallel of the main GUI. I would like this child thread to terminate when I close the main application. In this example, the child thread is a si... | How to get a child thread to close when main GUI window is closed in pyqt5 / python 3? | I am writing a GUI using pyqt5 (Python 3.6). I am trying to run another thread in parallel of the main GUI. I would like this child thread to terminate when I close the main application. In this example, the child thread is a simple counter. When I close the main GUI, the counter still keeps going. How can I get the th... | [
"I tried to use the QThread but this locks up the main GUI. I am not sure if I am implementing it correctly.\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtWidgets import (QWidget, QApplication,QPushButton, \n QVBoxLayout)\nfrom PyQt5.QtCore import QThread\nimport time, threading, sys\n\ncla... | [
0,
0,
0
] | [] | [] | [
"multithreading",
"pyqt5",
"python"
] | stackoverflow_0061151313_multithreading_pyqt5_python.txt |
Q:
TypeError: '<=' not supported between instances of 'str' and 'int' - Flask
I am trying to deploy my NLP project (learning style) using flask, but when I try to access the training page the server gives me: Internal Server Error and I face this problem on VScode:
File "C:\Users\chocl\AppData\Local\Temp\ipykernel_1... | TypeError: '<=' not supported between instances of 'str' and 'int' - Flask | I am trying to deploy my NLP project (learning style) using flask, but when I try to access the training page the server gives me: Internal Server Error and I face this problem on VScode:
File "C:\Users\chocl\AppData\Local\Temp\ipykernel_17384\1855773603.py", line 114, in train
model=build_model()
File "C:\Users\chocl... | [
"After checking your error code, you can see your error highlighted that it occur at your first model.add.\nAfter reading the documentation, they mentioned the first parameter to be input_dim, which is your vocabSize, so I assume that your vocabSize variable is string type instead of int type\nEdit* add on document... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074402954_python.txt |
Q:
Adding a path to sys.path in python and pylint
So. I'm aware that this question seems to have been asked to death, but none of the answers seem to address what I want to do.
I have a library in another directory that I want to include in a set of other projects that I run. I don't want that library added every tim... | Adding a path to sys.path in python and pylint | So. I'm aware that this question seems to have been asked to death, but none of the answers seem to address what I want to do.
I have a library in another directory that I want to include in a set of other projects that I run. I don't want that library added every time I run python..
So, what I had been doing was this ... | [
"You can do it using an \"init hook\" for pylint. See this answer: https://stackoverflow.com/a/3065082/4323\nAnd this statement from pylint's bug tracker:\n\nWe will probably not going to support this automatically. But right now we do support manually additions to path, although in a more cumbersome way, through ... | [
13,
0,
0
] | [] | [] | [
"pylint",
"python"
] | stackoverflow_0044732819_pylint_python.txt |
Q:
Randomly replacing letters, numbers, and punctuation in a string: can this code be condensed?
Writing a function to check an input string for numbers, and if there are any, to randomize every digit, letter, and punctuation mark in the string. (i.e. "hello3.14" might become "jdbme6?21")
This code works (and the goa... | Randomly replacing letters, numbers, and punctuation in a string: can this code be condensed? | Writing a function to check an input string for numbers, and if there are any, to randomize every digit, letter, and punctuation mark in the string. (i.e. "hello3.14" might become "jdbme6?21")
This code works (and the goal makes sense in context, I promise) but it sure seems redundant. Not sure how to tighten it up. Th... | [
"As pointed out, this isn't really the place for reviewing code, but since it's here I wanted to point out how to do your selections without needing a while loop.\nA while loop will work, but has a real downside, in that it's no longer a consistent time to finish. It also has a theoretical downside in that it has n... | [
0,
0
] | [] | [] | [
"python",
"random",
"string"
] | stackoverflow_0074395366_python_random_string.txt |
Q:
Python standard IO under Windows PowerShell and CMD
I have the following two-line Python (v. 3.10.7) program "stdin.py":
import sys
print(sys.stdin.read())
and the following one-line text file "ansi.txt" (CP1252 encoding) containing:
‘I am well’ he said.
Note that the open and close quotes are 0x91... | Python standard IO under Windows PowerShell and CMD | I have the following two-line Python (v. 3.10.7) program "stdin.py":
import sys
print(sys.stdin.read())
and the following one-line text file "ansi.txt" (CP1252 encoding) containing:
‘I am well’ he said.
Note that the open and close quotes are 0x91 and 0x92, respectively. In Windows-10 cmd mode the behav... | [
"tl;dr\nUse the $OutputEncoding preference variable:\n\nIn Windows PowerShell:\n\n# Using the system's legacy ANSI code page, as Python does by default.\n# NOTE: The & { ... } enclosure isn't strictly necessary, but \n# ensures that the $OutputEncoding change is only temporary,\n# by limiting to the chi... | [
3
] | [] | [] | [
"cmd",
"input",
"powershell",
"python",
"standards"
] | stackoverflow_0074402436_cmd_input_powershell_python_standards.txt |
Q:
Iteratively pop and append to generate new lists using pandas
I have a list of elements mylist = [1, 2, 3, 4, 5, 6, 7, 8] and would like to iteratively:
copy the list
pop the first element of the copied list
and append it to the end of the copied list
repeat this for the next row, etc.
Desired output:
index A ... | Iteratively pop and append to generate new lists using pandas | I have a list of elements mylist = [1, 2, 3, 4, 5, 6, 7, 8] and would like to iteratively:
copy the list
pop the first element of the copied list
and append it to the end of the copied list
repeat this for the next row, etc.
Desired output:
index A B C D E F G H
0 1 2 3 4 5 6 7 8
1... | [
"I think slicing (Understanding slicing) is what you are looking for:\nnext_iteration = my_list[1:] + [my_list[0]]\n\nand the full loop:\noutput = []\nfor i in range(len(my_list)):\n output.append(my_list[i:] + my_list[:i])\n\n",
"Use this numpy solution with rolls create by np.arange:\nmylist = [1, 2, 3, 4, ... | [
0,
0,
0,
0
] | [] | [] | [
"append",
"list",
"pandas",
"python"
] | stackoverflow_0074399196_append_list_pandas_python.txt |
Q:
How to automatically create a new class variable when you call the same class everytime
I want book1 to be created automatically without defining it, because this will be a while code so what I want to achieve is every time a user fill these inputs it creates book1 then book2, etc. and most importantly a way I can... | How to automatically create a new class variable when you call the same class everytime | I want book1 to be created automatically without defining it, because this will be a while code so what I want to achieve is every time a user fill these inputs it creates book1 then book2, etc. and most importantly a way I can call them again
class Book(object): #this class stores books in detail
def __init__(self... | [
"Generally when you have repetitive code, you can write a function for that.\nThis can be done in many ways. One of them is using a classmethod as another constructor for your class:\nclass Book: # this class stores books in detail\n def __init__(self, title: str, author: str, isbn: int, genre: str, numCopies: ... | [
3
] | [] | [] | [
"class",
"python",
"variables"
] | stackoverflow_0074403288_class_python_variables.txt |
Q:
Plotly Python Chord Diagram
I found an example of a Python Chord Diagram here. Now I would like to customize it furhter in order to show the outer labels and the tickmarks. Is it possible?
This is an example of how the end result should look like:
So I managed to build the chart, the only things that are missing... | Plotly Python Chord Diagram | I found an example of a Python Chord Diagram here. Now I would like to customize it furhter in order to show the outer labels and the tickmarks. Is it possible?
This is an example of how the end result should look like:
So I managed to build the chart, the only things that are missing are the information from the out... | [
"Checkout this stackoverflow page: Circular Chord Diagram in Python where it is shown how to easily create a Chord chart in d3js using Python using the D3Blocks library.\n"
] | [
0
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0041470067_plotly_python.txt |
Q:
No module named 'backports'
I am trying to build a python project using 'make build' command but getting below error while doing that. It was working earlier but starting throwing this error recently.
Collecting backports.zoneinfo (from -r requirements.txt (line 4))
Downloading https://<ARTIFACTORY_URL>/artifact... | No module named 'backports' | I am trying to build a python project using 'make build' command but getting below error while doing that. It was working earlier but starting throwing this error recently.
Collecting backports.zoneinfo (from -r requirements.txt (line 4))
Downloading https://<ARTIFACTORY_URL>/artifactory/api/pypi/pypi-release/package... | [
"I did not manage to get this working, so I upgraded to python3.9. There import zoneinfo is enough...\n"
] | [
0
] | [] | [] | [
"backport",
"makefile",
"python",
"requirements.txt"
] | stackoverflow_0069705676_backport_makefile_python_requirements.txt.txt |
Q:
Select all the subcolumns with a given name from pandas dataframe
I have a pandas dataframe df that I built using 3 levels of columns, as follows:
a1 a2 a3
b1 b2 b1 b3 b1 b4
c1 c2 c1 c2 c1 c2 c1 c2 c1 c2 c1 c2
... (data) ...
Note that each a colum... | Select all the subcolumns with a given name from pandas dataframe | I have a pandas dataframe df that I built using 3 levels of columns, as follows:
a1 a2 a3
b1 b2 b1 b3 b1 b4
c1 c2 c1 c2 c1 c2 c1 c2 c1 c2 c1 c2
... (data) ...
Note that each a column may have different b subcolumns, but each b column has the same c sub... | [
"The docs provide some info on that. Adapting the examples from there to your example, either use tuples with slice objects you pass None,\ndf.loc[:, (slice(None), slice(None), \"c2\")]\n\nor use pd.IndexSliceto use the familiar : notation:\nidx = pd.IndexSlice\ndf.loc[:, idx[:, :, \"c2\"]]\n\n",
"When you have a... | [
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074403181_pandas_python.txt |
Q:
How to skip permission error while deleting all files from a folder
I am working on a python script in which i am trying to delete all the files which are there within the given folder , though few errors like below are acting as a road block due to which the code is not able to complete.
PermissionError: The proc... | How to skip permission error while deleting all files from a folder | I am working on a python script in which i am trying to delete all the files which are there within the given folder , though few errors like below are acting as a road block due to which the code is not able to complete.
PermissionError: The process cannot access the file because it is being used by another process: C... | [
"It doesn't delete any files because rmtree deletes the entire directory, which cannot happen because at least one file in the directory is still used by another process. If you want to delete the directory, you'll have to make sure, that none of the files are used by another process.\nBased on your question though... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"shutil"
] | stackoverflow_0074402480_dataframe_pandas_python_shutil.txt |
Q:
Calculating smallest within trio distance
I have a pandas dataframe similar to the one below:
Output var1 var2 var3
1 0.487981 0.297929 0.214090
1 0.945660 0.031666 0.022674
2 0.119845 0.828661 0.051495
2 0.095186 0.852232 0.052582
3 0.059520 0.053307 0.88... | Calculating smallest within trio distance | I have a pandas dataframe similar to the one below:
Output var1 var2 var3
1 0.487981 0.297929 0.214090
1 0.945660 0.031666 0.022674
2 0.119845 0.828661 0.051495
2 0.095186 0.852232 0.052582
3 0.059520 0.053307 0.887173
3 0.091049 0.342226 0.566725
3 0... | [
"Finally, I tried with my own solution, that I think it is correct, but maybe too much computationally expensive.\nI created my 3 dataset, according to the Output value: dataset1 = dataset[dataset[\"Output\"]==1] and the same for Output=2 and Output=3.\nThis is my distance function:\ndef Euclidean_Dist(df1, df2):\n... | [
0
] | [] | [] | [
"distance",
"euclidean_distance",
"pandas",
"propensity_score_matching",
"python"
] | stackoverflow_0074359865_distance_euclidean_distance_pandas_propensity_score_matching_python.txt |
Q:
How to use ThreadPoolExecutor's output in ProcessPoolExecutor concurrently?
I've a script that has 2 parts : One that is I/O heavy (api calls), and another part that is CPU heavy (processing API output)
I would like to do the API calls with multithreading so they run concurrently, and as the results come in, they ... | How to use ThreadPoolExecutor's output in ProcessPoolExecutor concurrently? | I've a script that has 2 parts : One that is I/O heavy (api calls), and another part that is CPU heavy (processing API output)
I would like to do the API calls with multithreading so they run concurrently, and as the results come in, they are processed by the Multiprocessing.
My code looks like this :
with ThreadPoolEx... | [
"The problem arising from mixing multiprocessing and multithreading together on platforms that use fork that was mentioned by Nick O'Dell does not appear to be a problem when using the multiprocessing package (at least not on my Linux platform). You can, of course, force Python to use the spawn method when creating... | [
0
] | [] | [] | [
"multiprocessing",
"multithreading",
"python",
"python_multiprocessing",
"python_multithreading"
] | stackoverflow_0074394248_multiprocessing_multithreading_python_python_multiprocessing_python_multithreading.txt |
Q:
How to remove written out date strings like "1. January" from a list?
I have a list that looks like this: ["Keyphrase", "27. August", "8. April"]
I have tried out this code, but havent found the right regex to remove number plus month strings from the list.
new_list = [x for x in old_list if not re.search(r'<inser... | How to remove written out date strings like "1. January" from a list? | I have a list that looks like this: ["Keyphrase", "27. August", "8. April"]
I have tried out this code, but havent found the right regex to remove number plus month strings from the list.
new_list = [x for x in old_list if not re.search(r'<insert regex>', x)]
I would like to remove all "number + month" items to have t... | [
"single line no regex - use a list comp and any instead:\nl= [\"Keyphrase\", \"27. August\", \"8. April\"]\n\nmonths= ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\n\n\nprint ([el for el in l if not any(ignore in el for ignore in months)]... | [
2
] | [] | [] | [
"date",
"python",
"string"
] | stackoverflow_0074403257_date_python_string.txt |
Q:
Transforming a csv file
I have following data as below:
Unnamed :5
Week 5
Week4
Week3
Quartiles
2
3
4
CR
1
2
5
KPI
4
5
2
Quartiles
2
3
4
CR
1
2
3
KPI
3
4
1
I need to transform the file as below:
Week
Quartiles
CR
KPI
Week5
2
1
4
Week4
3
2
5
Week3
4
5
2
Week5
2
1
3
Week4
3
2
4
Week3
4
3
1
Which func... | Transforming a csv file | I have following data as below:
Unnamed :5
Week 5
Week4
Week3
Quartiles
2
3
4
CR
1
2
5
KPI
4
5
2
Quartiles
2
3
4
CR
1
2
3
KPI
3
4
1
I need to transform the file as below:
Week
Quartiles
CR
KPI
Week5
2
1
4
Week4
3
2
5
Week3
4
5
2
Week5
2
1
3
Week4
3
2
4
Week3
4
3
1
Which funct... | [
"You should be able to Transpose the dataframe. Make sure to set the unnamed column to the index and then transpose the dataframe as:\n#set the index\ndf1.set_index(\"Unnamed :5\", inplace=True)\n\n#transpose to the dataframe\ndf1_transposed = df1.T\n\nTo then change the week from the index you can use:\ndf1_transp... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074403478_pandas_python.txt |
Q:
Python - Using a lambda function stored in a list of functions inside a class
I'm trying to set up a Functions class that will handle functions for my NN projects.
I've figured out I'd like the list of functions to be somewhat flexible (easily add, or remove functions used).
I've created a list of functions, defin... | Python - Using a lambda function stored in a list of functions inside a class | I'm trying to set up a Functions class that will handle functions for my NN projects.
I've figured out I'd like the list of functions to be somewhat flexible (easily add, or remove functions used).
I've created a list of functions, defined a bunch of lambda functions,
added a method that adds all the functions in the b... | [
"When you do self.f1, you create a bound method, taking one less parameter than f1 did. This is how methods work in Python, so that you don't have to do self.foo(self, ...) all the time. You're encountering an unfortunate consequence of this generally reasonable decision.\nThere are several ways you could fix this.... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0074403326_python.txt |
Q:
Confusion over datetime64, timestamp and pd.DateOffset()
I have this data, dtype datetime64[ns]
df.date_month
Output:
0 2018-09-01
1 2018-09-01
2 2018-09-01
3 2018-09-01
4 2018-09-01
...
Name: date_month, Length: 4839993, dtype: datetime64[ns]
If I run a f... | Confusion over datetime64, timestamp and pd.DateOffset() | I have this data, dtype datetime64[ns]
df.date_month
Output:
0 2018-09-01
1 2018-09-01
2 2018-09-01
3 2018-09-01
4 2018-09-01
...
Name: date_month, Length: 4839993, dtype: datetime64[ns]
If I run a for loop and add pd.Offset, the code runs.
for i in df.date_mon... | [
"That's correct, unique() returns an array from the Series you are passing it. See --> https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unique.html\nYou more than likely want to use drop_duplicates() --> https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop_duplicates.html\ni.e.... | [
1
] | [] | [] | [
"datetime",
"pandas",
"python",
"timestamp"
] | stackoverflow_0074403251_datetime_pandas_python_timestamp.txt |
Q:
Correct Way to Structure Models, Views and Serializers
I have the following structure of Parent and Child models, where the child references the parent.
class ParentModel(models.Model):
name = models.CharField(max_length=255)
class ChildModel(models.Model):
name = models.CharField(max_length=255)
pare... | Correct Way to Structure Models, Views and Serializers | I have the following structure of Parent and Child models, where the child references the parent.
class ParentModel(models.Model):
name = models.CharField(max_length=255)
class ChildModel(models.Model):
name = models.CharField(max_length=255)
parent = models.ForeignKey(
ParentModel, related_name='... | [
"First I think you got a n+1 issue with your code.\nWhen DRF will serialize ParentModel, accessing current_parent.children.all() will produce an SQL query for each parent.\nTo prevent this you can use prefetch_related so:\nclass ParentViewSet(viewsets.ModelViewSet):\n serializer_class = ParentSerializer\n que... | [
1
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074403235_django_django_rest_framework_python.txt |
Q:
Satisfy flake8 using the following example
I have a very simple expression below. I am checking each character of a password to ensure it has at least one of the below special characters. However, Flake8 registers the example as bad. How can I address this within Flake8?
W605 invalid escape sequence '!'
W605 inval... | Satisfy flake8 using the following example | I have a very simple expression below. I am checking each character of a password to ensure it has at least one of the below special characters. However, Flake8 registers the example as bad. How can I address this within Flake8?
W605 invalid escape sequence '!'
W605 invalid escape sequence '$'
W605 invalid escape seque... | [
"Flake8 is complaining because in your string of special_characters you are escaping some characters that do not need to be escaped.\nIn your list the only character that needs to be escaped is the double quotes (\"), so you can just do:\nspecial_characters = \"~!@#$%^&*()_+{}\\\":;'[]\"\n\n\nNOTE: I also removed t... | [
0,
0
] | [] | [] | [
"flake8",
"python"
] | stackoverflow_0074402901_flake8_python.txt |
Q:
No module named packaging
I work on Ubuntu 14. I install python3 and pip3.
When I try to use pip3, I have this error
Traceback (most recent call last):
File "/usr/local/bin/pip3", line 6, in <module>
from pkg_resources import load_entry_point
File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__ini... | No module named packaging | I work on Ubuntu 14. I install python3 and pip3.
When I try to use pip3, I have this error
Traceback (most recent call last):
File "/usr/local/bin/pip3", line 6, in <module>
from pkg_resources import load_entry_point
File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 70, i
n <module>
... | [
"First update your pip version itself. You can take a look at this answer\npip3 install --upgrade pip\n\nAnd then try to install packaging, if its not already installed by now.\npip3 install packaging\n\n",
"I recently had the same error. Unfortunately none of the other answers solved my problem. Finally installi... | [
35,
10,
4,
0,
0
] | [] | [] | [
"pip",
"python",
"python_3.x",
"ubuntu"
] | stackoverflow_0042222096_pip_python_python_3.x_ubuntu.txt |
Q:
Making Entries Accept decimal numbers only in python
I want to know how can I make An Entry Accept Decimal Numbers ONLY
python
tkinter
programming
A:
You can use isdecimal() function to check if its decimal or not.
https://www.geeksforgeeks.org/python-string-isdecimal-method/#:~:text=Python%20String%20isdecimal(... | Making Entries Accept decimal numbers only in python | I want to know how can I make An Entry Accept Decimal Numbers ONLY
python
tkinter
programming
| [
"You can use isdecimal() function to check if its decimal or not.\nhttps://www.geeksforgeeks.org/python-string-isdecimal-method/#:~:text=Python%20String%20isdecimal()%20function,decimal%2C%20else%20it%20returns%20False.\n",
"Here's an example of basic input validation on an Entry widget\nimport tkinter as tk\nfro... | [
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074402072_python_tkinter.txt |
Q:
Fast way to get N maximum values in each row of 2D-array
In most of the metric learning task at some point we have similarity matrix KxM. Where K is number of new samples and M number of database samples.
From each row of this matrix we need to choose only N samples with largest similarity value, where N << M.
Typ... | Fast way to get N maximum values in each row of 2D-array | In most of the metric learning task at some point we have similarity matrix KxM. Where K is number of new samples and M number of database samples.
From each row of this matrix we need to choose only N samples with largest similarity value, where N << M.
Typical way to do so in Python is:
def get_args_of_best_score(sco... | [
"It can be done with following function:\ndef get_args_of_best_score_fast(score_matrix, N):\n # Get top but unsorted arguments\n arg_part = np.argpartition(-score_matrix, N, axis=1)[:, :N]\n # https://stackoverflow.com/questions/26322232/how-to-apply-the-output-of-numpy-argpartition-for-2-d-arrays\n v_p... | [
0
] | [] | [] | [
"matrix",
"numpy",
"performance",
"python",
"sorting"
] | stackoverflow_0074403601_matrix_numpy_performance_python_sorting.txt |
Q:
Discord.py Random Variabel Input / Ouput
I would like to expand my Discord Bot with a new randomizer function.
I always want to enter the values/variables manually, for example:
Input: !random text1 text2 text3 Output: The result is "text2"
I need the whole thing in Discord.py (Python) and without slash (/) comma... | Discord.py Random Variabel Input / Ouput | I would like to expand my Discord Bot with a new randomizer function.
I always want to enter the values/variables manually, for example:
Input: !random text1 text2 text3 Output: The result is "text2"
I need the whole thing in Discord.py (Python) and without slash (/) commands.
I tried:
@bot.command()
async def r(ctx, ... | [
"Instead of manully doing name1 , name2 you could use *args to grab arguments,\n@bot.command()\nasync def r(ctx, *args):\n embed = discord.Embed(\n colour=0xc81f9f,\n title=\"Rating\",\n description=f\"{ctx.author.mention} {random.choice(args)} is your rating\"\n )\n await ctx.send(emb... | [
0
] | [] | [] | [
"discord",
"discord.py",
"python",
"random",
"variables"
] | stackoverflow_0074403189_discord_discord.py_python_random_variables.txt |
Q:
Euclidean algorithm (GCD) with multiple numbers?
So I'm writing a program in Python to get the GCD of any amount of numbers.
def GCD(numbers):
if numbers[-1] == 0:
return numbers[0]
# i'm stuck here, this is wrong
for i in range(len(numbers)-1):
print GCD([numbers[i+1], numbers[i] % n... | Euclidean algorithm (GCD) with multiple numbers? | So I'm writing a program in Python to get the GCD of any amount of numbers.
def GCD(numbers):
if numbers[-1] == 0:
return numbers[0]
# i'm stuck here, this is wrong
for i in range(len(numbers)-1):
print GCD([numbers[i+1], numbers[i] % numbers[i+1]])
print GCD(30, 40, 36)
The function t... | [
"Since GCD is associative, GCD(a,b,c,d) is the same as GCD(GCD(GCD(a,b),c),d). In this case, Python's reduce function would be a good candidate for reducing the cases for which len(numbers) > 2 to a simple 2-number comparison. The code would look something like this:\nif len(numbers) > 2:\n return reduce(lambda ... | [
40,
28,
6,
5,
3,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"greatest_common_divisor",
"math",
"python"
] | stackoverflow_0016628088_greatest_common_divisor_math_python.txt |
Q:
Trying to find element ('href') with Selenium in Python
I am trying to get the URL ('href') of the below element in Python with Selenium. For the life of me it is not working, this is the only output I get is as an example:
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpat... | Trying to find element ('href') with Selenium in Python | I am trying to get the URL ('href') of the below element in Python with Selenium. For the life of me it is not working, this is the only output I get is as an example:
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="href"]"}
This is the element I want ... | [
"You have to use 'get_attribute()' function to get the urls:\nFor example, if this XPath is correct - '//*[@id=\"tinymce\"]/p[7]/a', then locator should be like this:\ndriver.fine_element(By.XPATH, \"//*[@id='tinymce']/p[7]/a\").get_attribute(\"href\")\n\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0074403557_python_selenium_selenium_chromedriver_selenium_webdriver.txt |
Q:
Django 1.7 - makemigrations not detecting changes
As the title says, I can't seem to get migrations working.
The app was originally under 1.6, so I understand that migrations won't be there initially, and indeed if I run python manage.py migrate I get:
Operations to perform:
Synchronize unmigrated apps: myapp
... | Django 1.7 - makemigrations not detecting changes | As the title says, I can't seem to get migrations working.
The app was originally under 1.6, so I understand that migrations won't be there initially, and indeed if I run python manage.py migrate I get:
Operations to perform:
Synchronize unmigrated apps: myapp
Apply all migrations: admin, contenttypes, auth, sessio... | [
"If you're changing over from an existing app you made in django 1.6, then you need to do one pre-step (as I found out) listed in the documentation:\n\npython manage.py makemigrations your_app_label\n\nThe documentation does not make it obvious that you need to add the app label to the command, as the first thing i... | [
194,
79,
30,
21,
16,
13,
11,
7,
7,
7,
6,
5,
5,
5,
5,
3,
3,
3,
2,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [
"Adding my 2c, since none of these solutions worked for me, but this did...\nI had just run manage.py squashmigrations and removed the old migrations (both the files and lines in the the django.migrations database table).\nThis left a line like this in the last migration file:\nreplaces = [(b'my_app', '0006_auto_20... | [
-1,
-1
] | [
"django",
"django_1.7",
"django_migrations",
"python"
] | stackoverflow_0024912173_django_django_1.7_django_migrations_python.txt |
Q:
Box SDK created_by shows anonymous but I can see "uploader" in the Box UI
I am using the boxsdk to list all files in a box folder
request_url = f"https://api.box.com/2.0/folders/{folder_id}/items"
request = self.client.make_request("GET", request_url, params={"limit": limit, "offset": offset,
... | Box SDK created_by shows anonymous but I can see "uploader" in the Box UI | I am using the boxsdk to list all files in a box folder
request_url = f"https://api.box.com/2.0/folders/{folder_id}/items"
request = self.client.make_request("GET", request_url, params={"limit": limit, "offset": offset,
"fields": ["created_by"]})
data = req... | [
"I needed to pass \"uploader_display_name\" in the \"fields\" list. Counter-intuitively, this returns the email of the person who uploaded the file\n"
] | [
0
] | [] | [] | [
"boxsdk",
"python"
] | stackoverflow_0074403688_boxsdk_python.txt |
Q:
Open AI davinci does not produce any output (text or audio)
I have the following piece of code:
import openai
import pyttsx3
import speech_recognition as sr
from api_key import API_KEY
openai.api_key = API_KEY
engine = pyttsx3.init()
r = sr.Recognizer()
mic = sr.Microphone(device_index=1)
print(sr.Microphone.li... | Open AI davinci does not produce any output (text or audio) | I have the following piece of code:
import openai
import pyttsx3
import speech_recognition as sr
from api_key import API_KEY
openai.api_key = API_KEY
engine = pyttsx3.init()
r = sr.Recognizer()
mic = sr.Microphone(device_index=1)
print(sr.Microphone.list_microphone_names())
conversation = ""
user_name = "Josode"
... | [
"Most probably you are getting an exception in r.recognize_google(audio) so it forces continue again and again without any output, try to add something like this to debug it:\n import traceback\n\n ... \n\n try:\n user_input = r.recognize_google(audio)\n except:\n print(traceback.format_ex... | [
1
] | [] | [] | [
"openai",
"pyaudio",
"python"
] | stackoverflow_0074403541_openai_pyaudio_python.txt |
Q:
finding double entries in a list of tuples
I pull data from multiple excel and write it back to an aggregated excel file
so I have a list of tuples and each tuple consists of two values like this:
tuple = (entity-ID, debitor-name)
list = [tuple1, tuple2, ..., tupleN]
So it can happen that there are multiple entr... | finding double entries in a list of tuples |
I pull data from multiple excel and write it back to an aggregated excel file
so I have a list of tuples and each tuple consists of two values like this:
tuple = (entity-ID, debitor-name)
list = [tuple1, tuple2, ..., tupleN]
So it can happen that there are multiple entries with the same debitor-name but with differe... | [
"You can now work with a dict that the key is debitor-name and the value is a list of entity-ID\nagg_debitor_list = [(\"1\", \"X AG\"), (\"1\", \"Z AG\"), (\"2\", \"X AG\")]\ndebitor_to_ids = dict() \nfor val, key in agg_debitor_list: \n debitor_to_ids[key] = debitor_to_ids.get(key, []) \n debitor_to_ids[key... | [
0,
0
] | [] | [] | [
"list",
"openpyxl",
"python",
"tuples"
] | stackoverflow_0074403387_list_openpyxl_python_tuples.txt |
Q:
Python, Load config file correctly?
I have the following directory:
IoT [Folder]
DC [Folder]
main.py
config.ini
inside main.py I have:
config.read('config.ini')
which works perfect if I run my python script after doing cd .....IoT/DC
But it doesn't work once I run my python script directly from IoT folder, ho... | Python, Load config file correctly? | I have the following directory:
IoT [Folder]
DC [Folder]
main.py
config.ini
inside main.py I have:
config.read('config.ini')
which works perfect if I run my python script after doing cd .....IoT/DC
But it doesn't work once I run my python script directly from IoT folder, how can I solve this?
I can't know from... | [
"from os import getcwd\nfrom os.path import join\n\nconfig_file_path = join(getcwd(), 'conf', 'config.ini')\n\n",
"\nPaths are relative to the current working directory, which is usually\nthe directory from which you run your program (but the current\ndirectory can be changed by your program [or a module] and it ... | [
0,
0
] | [] | [] | [
"config",
"python",
"python_3.x"
] | stackoverflow_0074403713_config_python_python_3.x.txt |
Q:
After updating flask-mail not sending emails
My website started erroring 404; email confirmation wasn't functioning. I believe due to changes to Google security. I updated all packages and Python. I setup Google 2-step verification and created the app password. I don't get errors but from send_email I don't receiv... | After updating flask-mail not sending emails | My website started erroring 404; email confirmation wasn't functioning. I believe due to changes to Google security. I updated all packages and Python. I setup Google 2-step verification and created the app password. I don't get errors but from send_email I don't receive email. I successfully pinged smtp.gmail.com. The... | [
"I found out that Flask-Mail is no longer supported and was not on pypi so I assume its not compatible with either updating the framework or updating python that I performed. The most recent update was about 8 years ago on the GitHub page.\n"
] | [
0
] | [] | [] | [
"flask",
"flask_mail",
"python"
] | stackoverflow_0073462012_flask_flask_mail_python.txt |
Q:
Deleting object in a (SQLAlchemy) many-to-many relationship (works in sqlite but fails when using postgres)?
I seem to hit an issue when trying to delete an object from a many-to-many relation that seems to work with sqlite, but fails on postgres.
Any help or hint is highly appreciated!
This part is the code fails... | Deleting object in a (SQLAlchemy) many-to-many relationship (works in sqlite but fails when using postgres)? | I seem to hit an issue when trying to delete an object from a many-to-many relation that seems to work with sqlite, but fails on postgres.
Any help or hint is highly appreciated!
This part is the code fails when using postgres.
# try to delete group 1
session.query(Group).filter_by(name="group 1").delete()
Example cod... | [
"Has been answered in extend here:\nhttps://github.com/sqlalchemy/sqlalchemy/discussions/7941\n"
] | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0071891980_python_sqlalchemy.txt |
Q:
SQLAlchemy Error '(psycopg2.errors.NotNullViolation) null value in column "id" of relation
I am aware of a similar issue How to fix error: (psycopg2.errors.NotNullViolation) null value in column "id" violates not-null constraint? but the answers there did not fix my error
I have the following sqlalchemy structure ... | SQLAlchemy Error '(psycopg2.errors.NotNullViolation) null value in column "id" of relation | I am aware of a similar issue How to fix error: (psycopg2.errors.NotNullViolation) null value in column "id" violates not-null constraint? but the answers there did not fix my error
I have the following sqlalchemy structure connected to a postgres database
class Injury(db.Model):
__tablename__ = "injury"
id = ... | [
"you have to tell it to auto increment\ndont use bigint but serial\nid SERIAL PRIMARY KEY\n\ncheck this how-to-define-an-auto-increment-primary-key-in-postgresql-using-python\n",
"This was a result of some form of bug during my transfer from sqlite to postgres when I used pg_loader. I found out someone else encou... | [
1,
0
] | [] | [] | [
"flask_sqlalchemy",
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0074397817_flask_sqlalchemy_postgresql_python_sqlalchemy.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.