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:
Get path of virtual environment in pipenv
How to can get the path of virtualenv in pipenv?
can configure it to use a custom path for newly created virtualenv?
A:
The following should give you the paths
$ pipenv --where
/home/wonder/workspace/myproj
$ pipenv --venv
/home/wonder/PyEnvs/myproj-BKbQCeJj
A:
Adding... | Get path of virtual environment in pipenv | How to can get the path of virtualenv in pipenv?
can configure it to use a custom path for newly created virtualenv?
| [
"The following should give you the paths\n$ pipenv --where\n/home/wonder/workspace/myproj\n\n$ pipenv --venv\n/home/wonder/PyEnvs/myproj-BKbQCeJj\n\n",
"Adding to Sewagodimo Matlapeng's answer for the second part of the question:\n\ncan configure it to use a custom path for newly created virtualenv?\n\nAccording ... | [
145,
12,
0,
0
] | [] | [] | [
"django",
"pip",
"pipenv",
"python"
] | stackoverflow_0053793833_django_pip_pipenv_python.txt |
Q:
How to estimate how much memory a Pandas' DataFrame will need?
I have been wondering... If I am reading, say, a 400MB csv file into a pandas dataframe (using read_csv or read_table), is there any way to guesstimate how much memory this will need? Just trying to get a better feel of data frames and memory...
A:
... | How to estimate how much memory a Pandas' DataFrame will need? | I have been wondering... If I am reading, say, a 400MB csv file into a pandas dataframe (using read_csv or read_table), is there any way to guesstimate how much memory this will need? Just trying to get a better feel of data frames and memory...
| [
"df.memory_usage() will return how many bytes each column occupies:\n>>> df.memory_usage()\n\nRow_ID 20906600\nHousehold_ID 20906600\nVehicle 20906600\nCalendar_Year 20906600\nModel_Year 20906600\n...\n\nTo include indexes, pass index=True.\nSo to get overall memory consumption:... | [
164,
130,
56,
32,
10,
10,
8,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0018089667_pandas_python.txt |
Q:
Sort dictionary of dictionaries and lists with compound return statement
Does anyone know how to modify this code so that it will sort dictionaries{} and lists[]?
Example sort:
Input: {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': [1, 7, 4, 2]}}
Output: {'a': 1, 'b': {'b1': [1, 2, 4, 7], 'b2': 2}, 'c': 3}
Original code:
... | Sort dictionary of dictionaries and lists with compound return statement | Does anyone know how to modify this code so that it will sort dictionaries{} and lists[]?
Example sort:
Input: {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': [1, 7, 4, 2]}}
Output: {'a': 1, 'b': {'b1': [1, 2, 4, 7], 'b2': 2}, 'c': 3}
Original code:
def sort_dict(item: dict):
return {k: sort_dict(v) if isinstance(v, dict) ... | [
"Your second answer is nearly close to the correct answer, except for the omissive return value of the function sort_list. Just modify it to\ndef sort_list(item):\n return sorted(item) if isinstance(item, list) else item\n\nMoreover, you can try to construct a new function for this recursion under different cond... | [
2,
1,
1
] | [] | [] | [
"dictionary",
"python",
"sorting"
] | stackoverflow_0074355748_dictionary_python_sorting.txt |
Q:
How to access individual elements from a Keras Input() object
Background: I have two Sequential models that form a single model in the following format
model = Sequential([seq_model1, seq_model2])
The output of seq_model1 is predetermined so that it is a tf.Tensor(shape=(None,5), dtype=float32). Therefore, the inp... | How to access individual elements from a Keras Input() object | Background: I have two Sequential models that form a single model in the following format
model = Sequential([seq_model1, seq_model2])
The output of seq_model1 is predetermined so that it is a tf.Tensor(shape=(None,5), dtype=float32). Therefore, the input of seq_model2 could be written as keras.layers.Input(shape(5,)).... | [
"So, lets start it with the Sequential Models, Now, Consider I have two sequential models in keras as shown below,\nclear_session()\nmodel1 = keras.Sequential([\n keras.layers.Input(shape=(224,224,3)),\n keras.layers.Conv2D(64, 3, padding='same'),\n keras.layers.Dense(3, activation='softmax')\n])\n\n#clear... | [
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074350888_keras_python_tensorflow.txt |
Q:
Programmatically check a checkbox in pysimplegui
I have a PySimpleGUI application and I need to check a checkbox programmatically. I have looked at the cookbook, but couldn't find anything useful to help me. I have tried:
window["-CHECKBOX-"].update(checked=True)
window["-CHECKBOX-"}.update(default=True)
but bot... | Programmatically check a checkbox in pysimplegui | I have a PySimpleGUI application and I need to check a checkbox programmatically. I have looked at the cookbook, but couldn't find anything useful to help me. I have tried:
window["-CHECKBOX-"].update(checked=True)
window["-CHECKBOX-"}.update(default=True)
but both my attempts have given me a TypeError, saying that t... | [
"There's no option for checked or default in method update. It should be\n\nwindow[\"-CHECKBOX-\"].update(value=True), or\nwindow[\"-CHECKBOX-\"].update(True).\n\nYou can find it in https://www.pysimplegui.org/en/latest/call%20reference/#checkbox-element\n\nCheckbox.update\nChanges some of the settings for the Chec... | [
0
] | [] | [] | [
"checkbox",
"pysimplegui",
"python",
"python_3.11",
"python_3.x"
] | stackoverflow_0074354417_checkbox_pysimplegui_python_python_3.11_python_3.x.txt |
Q:
Can't make a get request on Python, getting this error: Max retries exceeded with url (SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:997))')
I am doing a simple get request with Python to url https://stat.gov.kz/important/classifier.
When I do same request with Postman or on Golang - I have no problem. W... | Can't make a get request on Python, getting this error: Max retries exceeded with url (SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:997))') | I am doing a simple get request with Python to url https://stat.gov.kz/important/classifier.
When I do same request with Postman or on Golang - I have no problem. Works perfectly. Buu with Python I get following error:
requests.exceptions.ProxyError: HTTPSConnectionPool(host='stat.gov.kz', port=443):
Max retries ***ex... | [
"As the error said:\n\nYour proxy appears to only use HTTP and not HTTPS, try changing your proxy URL to be HTTP.\n\nSo changing your url to\nurl = \"http://stat.gov.kz/important/classifier\"\n\nmight work.\nOtherwise try to set Proxies manually (SSL: WRONG_VERSION_NUMBER ON PYTHON REQUEST):\nproxies = {'https': 'h... | [
0
] | [] | [] | [
"get",
"python",
"python_requests"
] | stackoverflow_0074355950_get_python_python_requests.txt |
Q:
How can I use \n and \t in lambda function to replace dataframe?
I have very large scale dataframe with 100,000 rows and 300 columns
and I'm trying to fill out Nan rows in one columns by extracting the values from the other columns
here is the example,
let's say we have a sample dataframe such as:
NAME RRN... | How can I use \n and \t in lambda function to replace dataframe? | I have very large scale dataframe with 100,000 rows and 300 columns
and I'm trying to fill out Nan rows in one columns by extracting the values from the other columns
here is the example,
let's say we have a sample dataframe such as:
NAME RRN_FRONT RRN_BACK EVENT_DTL
1 JOHN 891105 1067714 ... | [
"Pandas.apply applies the operations on axis=0 (index axis) by default, and you need to change the axis=1 in your case:\ndf['EVENT_DTL'] = (np.where(df['EVENT_DTL'].isna(), \n df.apply(lambda x: ('1. NAME :\\n' + str(x['NAME']) +\n '2. BIRTHDAY :\\n' + str(x['RRN_FRONT']) + '3. SSN... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074355904_pandas_python.txt |
Q:
Cannot set vertical position of text in matplotlib table cell
I want the headers of my table to be rotated and thus have more than one line of height. When I try to bottom align these, however, I cannot get rid of extra space that is padding the bottom of the header text, which increases the larger I set the heigh... | Cannot set vertical position of text in matplotlib table cell | I want the headers of my table to be rotated and thus have more than one line of height. When I try to bottom align these, however, I cannot get rid of extra space that is padding the bottom of the header text, which increases the larger I set the height of the cell. How can I get the text to be flush with the bottom o... | [
"The Text's y position calculated from the Cell box is y0 + height / 2, and you set the Text's vertical alignment to \"bottom\", which is the reason for the bottom padding.\nAll you need to do is set the text rotation, set a proper cell height, and all is done.\nfor k, cell in the_table._cells.items():\n if k[0]... | [
0
] | [] | [] | [
"formatting",
"matplotlib",
"python"
] | stackoverflow_0074354196_formatting_matplotlib_python.txt |
Q:
ERROR: Could not find a version that satisfies the requirement os (from versions: none) in Python CICD
I'm new to Python as well as in CICD. In that I have added the below code.
Test.yml file code
jobs:
Deploy:
- name: Install python packages
run: |
python -m pip install --upgrade pip
p... | ERROR: Could not find a version that satisfies the requirement os (from versions: none) in Python CICD | I'm new to Python as well as in CICD. In that I have added the below code.
Test.yml file code
jobs:
Deploy:
- name: Install python packages
run: |
python -m pip install --upgrade pip
pip install -r /apps/requirements.txt
requirements.txt
requests
os
sys
logging
base64
Error:
ERROR: Could n... | [
"Requirements.txt should be\nrequests\n\nBecause\nos\nsys\nlogging\nbase64\n\nAre build-in modules in Python. So no need to add those modules in requirement.txt. So pip won't try to install build-in modules of Python.\n"
] | [
1
] | [] | [] | [
"pip",
"python",
"python_packaging"
] | stackoverflow_0074345165_pip_python_python_packaging.txt |
Q:
Running several Google Colab Notebooks at the same time
If I run several Google Colab Notebooks (runtimes) at the same time, is the perfomance shared?
I have a big dataframe to operate on so I decided to split it and let the code run on each part on a different notebook. However it seems to take as long as it woul... | Running several Google Colab Notebooks at the same time | If I run several Google Colab Notebooks (runtimes) at the same time, is the perfomance shared?
I have a big dataframe to operate on so I decided to split it and let the code run on each part on a different notebook. However it seems to take as long as it would take on the whole thing in one.
Is there any information on... | [
"Each Colab notebook uses a distinct virtual machine backend in order to perform computations. From a performance perspective, each notebook will be isolated from the activity of distinct notebooks.\nIn order to offer more useful guidance, please share a self-contained example that shows, with code, what you are do... | [
0,
0
] | [] | [] | [
"google_colaboratory",
"jupyter_notebook",
"python"
] | stackoverflow_0064573058_google_colaboratory_jupyter_notebook_python.txt |
Q:
Mojang session server returns incorrect information
name = requests.get(f"https://sessionserver.mojang.com/session/minecraft/profile/{member['uuid']}").json()["name"]
I use python to get minecraft nickname from uuid. I had no problem before, but today this API returns me random symbols. Is this local or global pr... | Mojang session server returns incorrect information | name = requests.get(f"https://sessionserver.mojang.com/session/minecraft/profile/{member['uuid']}").json()["name"]
I use python to get minecraft nickname from uuid. I had no problem before, but today this API returns me random symbols. Is this local or global problem?
I tried to use VPN or enother device. But every t... | [
"It is global problem with mojang session servers. Now it works correctly, but everybody can't cog in minecraft.\n"
] | [
0
] | [] | [] | [
"api",
"minecraft",
"python"
] | stackoverflow_0074355999_api_minecraft_python.txt |
Q:
How to plot bar charts in separate plots in Python
I have multiple bar charts that I want to plot in their own figure separately but they all plot on the same figure.
f1 = plt.bar(values, stats_list_running, width, label='Running time')
f2 = plt.bar(values, stats_list_noofact, width, label='No. of activations')
f3... | How to plot bar charts in separate plots in Python | I have multiple bar charts that I want to plot in their own figure separately but they all plot on the same figure.
f1 = plt.bar(values, stats_list_running, width, label='Running time')
f2 = plt.bar(values, stats_list_noofact, width, label='No. of activations')
f3 = plt.bar(values, stats_list_avgstract, width, label='A... | [
"In your case, you can use plt.subplots to create a sequence of subplots, and use the Axes method to draw your figure, such as:\nfig, ax = plt.subplots(2, 3)\nax[0,0].bar(...)\nax[0,1].bar(...)\n# and so on\n\nIf you want to draw a bar per figure, then you need to create a new Figure instance for each of your bar c... | [
2
] | [] | [] | [
"bar_chart",
"matplotlib",
"plot",
"python"
] | stackoverflow_0074354082_bar_chart_matplotlib_plot_python.txt |
Q:
Python regex to check new lines between strings
I have the following strings and need to have one line between y(age) and x(name) if multiple x,y presents , if we have only one x,y then no need to have a new line. whats the best way to use in python regex.
x:name
y:age
x:name
y:age
A:
Here is a regex replacemen... | Python regex to check new lines between strings | I have the following strings and need to have one line between y(age) and x(name) if multiple x,y presents , if we have only one x,y then no need to have a new line. whats the best way to use in python regex.
x:name
y:age
x:name
y:age
| [
"Here is a regex replacement approach:\ninp = \"\"\"x:name\ny:age\n\nx:name\ny:age\"\"\"\n\noutput = re.sub(r'(?<=\\S)\\n(?=\\S)', r'\\n\\n', inp)\nprint(output)\n\nThis prints:\nx:name\n\ny:age\n\nx:name\n\ny:age\n\nThe regex pattern used here matches newlines which are surrounded on both sides by non whitespace c... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074356054_python_regex.txt |
Q:
Replacing values of dataframe with null values and yes and no with 1 and 0
I've got a pandas DataFrame that looks like this:
molecule species
0 a dog
1 b horse
2 c []
3 d pig
4 e []
I want to replace the ... | Replacing values of dataframe with null values and yes and no with 1 and 0 | I've got a pandas DataFrame that looks like this:
molecule species
0 a dog
1 b horse
2 c []
3 d pig
4 e []
I want to replace the [] value with NaN using python. How can I achieve this?
For testing:
df = pd.Dat... | [
"You can try this\nimport numpy as np\ndf = pd.DataFrame({'molecule': ['a','b','c','d','e'], 'species' : ['horse','cat','[]','frog','lion']})\ndf[\"species\"].replace({\"[]\":np.nan})\n\nreplace will take dictionary where you can tell what to be mapped to what.\n",
"You can also replace values with NAN with DataF... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074355872_dataframe_pandas_python.txt |
Q:
How to redirect urls?
This is my main urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("shop.urls")),
]
I want that any url entered by user will redirect to shop.urls and find there
like if the user enters /index it will search index in shop.urls not in main urls.
My shop.urls:
f... | How to redirect urls? | This is my main urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("shop.urls")),
]
I want that any url entered by user will redirect to shop.urls and find there
like if the user enters /index it will search index in shop.urls not in main urls.
My shop.urls:
from django.urls import path... | [
"In main urls:\njust give route name.\nurlpatterns = [\n path('shop/', include(\"shop.urls\")),\n]\n\nAnd this is your shop urls:\nurlpatterns = [\n path('index/', views.index),\n]\n\nAfter changing above code.\nYou can navigate like this in your browser:\nlocalhost:8000/shop/index/\n\nYou will redirect to in... | [
3,
3
] | [] | [] | [
"django",
"django_admin",
"django_urls",
"python"
] | stackoverflow_0074356038_django_django_admin_django_urls_python.txt |
Q:
Cannot deserialize properly a response using pymongo
I was using an API that were written in NodeJS, but for some reasons I had to re-write the code in python. The thing is that the database is in MongoDB, and that the response to all the queries (with large results) includes a de-serialized version with$id
as, f... | Cannot deserialize properly a response using pymongo | I was using an API that were written in NodeJS, but for some reasons I had to re-write the code in python. The thing is that the database is in MongoDB, and that the response to all the queries (with large results) includes a de-serialized version with$id
as, for example {$oid: "f54h5b4jrhnf}.
this object id represent... | [
"You have several options (more than mentioned below).\nMongoDB\nIn a MongoDB query, you could project/convert all ObjectIds to a string using \"$toString\".\nPython\nIterate, like you mention in your question.\n--OR--\nYou could also define/use a custom pymongo TypeRegistry class with a custom TypeDecoder and use ... | [
0
] | [] | [] | [
"mongodb",
"mongoengine",
"pymongo",
"python"
] | stackoverflow_0074352696_mongodb_mongoengine_pymongo_python.txt |
Q:
This is The Error :AttributeError: 'NoneType' object has no attribute 'text'
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9620/2324248033.py in <module>
7 for num in r... | This is The Error :AttributeError: 'NoneType' object has no attribute 'text' | ---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9620/2324248033.py in <module>
7 for num in range(start, finish):
8 print(f"Checking {num}...")
----> 9 n... | [
"soup.find() can return None, and the NoneType object doesn't have a text attribute. You can get around this by splitting up soup.find(...).text into something like:\nfound = soup.find('p',attrs={'style':\"font-size: 14px;color: red; margin-top: 11px;\"})\nif found:\n text = found.text\n # Check text\n\nHere,... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"screen_scraping",
"web"
] | stackoverflow_0074356067_beautifulsoup_python_screen_scraping_web.txt |
Q:
How to solve "NameError: name 'df' is not defined" problem
#Importing dependencies
from urllib.parse import urlparse
from tld import get_tld
import os.path
import pandas as pd
#First Directory Length
def fd_length(url):
urlpath= urlparse(url).path
try:
return len(urlpath.split('/')[1])
except:... | How to solve "NameError: name 'df' is not defined" problem | #Importing dependencies
from urllib.parse import urlparse
from tld import get_tld
import os.path
import pandas as pd
#First Directory Length
def fd_length(url):
urlpath= urlparse(url).path
try:
return len(urlpath.split('/')[1])
except:
return 0
df['fd_length'] = df['url'].apply(lambda i: f... | [
"The problem with this code is that variable named df is not defined. If you want to use a csv file and import it as pandas dataframe, you can use pandas read_csv method which you can learn more about in pandas documentation here.\n# I want to read \"name.csv\" file\ndf = pd.read_csv(\"name.csv\")\n# It should be p... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074356016_python.txt |
Q:
merge request api authorization issue
I am trying to fetch what are the available merge requests for my repository as mentioned in the link. I have entered my user id and password when doing a get call ( see picture ). But the credentials entered are not considered and on output, it is showing a login page.
I am t... | merge request api authorization issue | I am trying to fetch what are the available merge requests for my repository as mentioned in the link. I have entered my user id and password when doing a get call ( see picture ). But the credentials entered are not considered and on output, it is showing a login page.
I am trying to add these APIs for my automatic re... | [
"With your curl command, you could try using the -L option to automatically follow redirects.\nhttps://reqbin.com/req/c-bvijc9he/curl-follow-redirect#:~:text=By%20default%2C%20Curl%20does%20not,%2D%2Dlocation%20command%2Dline%20option.\n",
"It looks like you're not using the correct API endpoint and request forma... | [
0,
0
] | [] | [] | [
"api",
"gitlab",
"postman",
"python"
] | stackoverflow_0074259832_api_gitlab_postman_python.txt |
Q:
How to use re to split the column containg string combine integer without contain symbol
Here is a column in df which contains integer and string both combine together.
(even here's numbers type are string)
I want split the df['symbol'] into df['num'] and df['name'],how can I do this question by re.
QUESTION:
df =... | How to use re to split the column containg string combine integer without contain symbol | Here is a column in df which contains integer and string both combine together.
(even here's numbers type are string)
I want split the df['symbol'] into df['num'] and df['name'],how can I do this question by re.
QUESTION:
df = pd.DataFrame({'symbol': ['12345abc', '2234bcd', '323456cde'],'date':[5, 6, 7]})
ideal:
df1 =... | [
"Can you try this\ndf[[\"\", \"symbol\", \"name\"]] = df[\"symbol\"].astype(str).str.split(\"(\\d+)\", expand=True)\n\n",
"split is not the best tool for this, rather use extract:\ndf[['symbol', 'name']] = df['symbol'].str.extract(r'(\\d+)(\\D+)')\n\nOutput:\n symbol date name\n0 12345 5 abc\n1 2234 ... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_re",
"split"
] | stackoverflow_0074355707_dataframe_pandas_python_python_re_split.txt |
Q:
Install psycopg2 on Ubuntu
I'm trying to get the python postgres client module installed on Ubuntu 12.04. The guidance is to do the following:
apt-get install python-psycopg2
However, apt says that the package can't be located.
I'm keen to install this through apt. Is this part of another package that I can ins... | Install psycopg2 on Ubuntu | I'm trying to get the python postgres client module installed on Ubuntu 12.04. The guidance is to do the following:
apt-get install python-psycopg2
However, apt says that the package can't be located.
I'm keen to install this through apt. Is this part of another package that I can install?
| [
"This works for me in Ubuntu 12.04 and 15.10\nif pip not installed:\nsudo apt-get install python-pip\n\nand then:\nsudo apt-get update\nsudo apt-get install libpq-dev python-dev\nsudo pip install psycopg2\n\n",
"Using Ubuntu 12.04 it appears to work fine for me:\njon@minerva:~$ sudo apt-get install python-psycopg... | [
127,
50,
40,
8,
5,
4,
2,
1,
0
] | [] | [] | [
"postgresql",
"python",
"ubuntu"
] | stackoverflow_0011583714_postgresql_python_ubuntu.txt |
Q:
How to Swap First and Last Characters from Input in Python
I am brand new to programming, learning Python3 from an online course. This exercise asks me to write a program which reads a string using input(), and outputs the same string but with the first and last character exchanged (example: Fairy becomes yairF). ... | How to Swap First and Last Characters from Input in Python | I am brand new to programming, learning Python3 from an online course. This exercise asks me to write a program which reads a string using input(), and outputs the same string but with the first and last character exchanged (example: Fairy becomes yairF). There is likely a simpler way to do this with more advanced func... | [
"Try this:\n>>> temp = \"abcde\"\n>>> temp[1:-1]\n'bcd'\n>>> temp[-1:] + temp[1:-1] + temp[:1]\n'ebcda'\n>>> \n\nIn short, python has magnificent string slicing syntax. You can do magic with it.\n",
"Just for fun:\n>>> temp = \"abcde\"\n>>> temp2 = list(temp)\n>>> temp2[0],temp2[-1]=temp2[-1],temp2[0]\n>>> temp =... | [
12,
2,
1,
1,
0,
0,
0,
0,
0,
0
] | [
"You can simply do the following:\nmyString = input()\nnewString = (myString[1:len(myString)-1])\nprint(myString[len(myString)-1]+newString+myString[0])\n\nDone!\n"
] | [
-1
] | [
"python",
"python_3.x"
] | stackoverflow_0017179584_python_python_3.x.txt |
Q:
How do I stop continuous loop of KEYDOWN?
I am new to pygame. Whenever I press the key "Delete". It prints "key" continuously. I only want it to print it only one time. How can I do this ?
import pygame
import sys
sprite = "sprite_1.jpg"
position = (20,0)
canvas = pygame.display.set_mode((952, 592))
color = ... | How do I stop continuous loop of KEYDOWN? | I am new to pygame. Whenever I press the key "Delete". It prints "key" continuously. I only want it to print it only one time. How can I do this ?
import pygame
import sys
sprite = "sprite_1.jpg"
position = (20,0)
canvas = pygame.display.set_mode((952, 592))
color = (255,255,255)
exit = False
back = pygame.im... | [
"It is a matter of Indentation. The event has to be handled in the event loop instead of the applicaition loop:\nwhile not exit:\n canvas.fill(color)\n canvas.blit(back, dest = (0,0))\n canvas.blit(Sprite, dest=position)\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n ... | [
1,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074355921_pygame_python.txt |
Q:
Code for consecutive strings works but can't pass random tests
In this problem, I'm given an array(list) strarr of strings and an integer k. My task is to return the first longest string consisting of k consecutive strings taken in the array. My code passed all the sample tests from CodeWars but can't seem to pass... | Code for consecutive strings works but can't pass random tests | In this problem, I'm given an array(list) strarr of strings and an integer k. My task is to return the first longest string consisting of k consecutive strings taken in the array. My code passed all the sample tests from CodeWars but can't seem to pass the random tests.
Here's the link to the problem.
I did it in two d... | [
"Let's start from the first statement of your function:\nif k == 1:\n while(p <= 1):\n b.append(strarr[j:i])\n j += 1\n i += 1\n p += 1\n for w in b:\n q.append(''.join(w))\n return max(q, key=len)\n\nHere q is finally equal strarr so you can shorten this code to:\nif k =... | [
1,
0
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0074345850_list_python_string.txt |
Q:
Azure Devops Pipeline - Create documentation from IaC file
I currently have written a script that essentially takes in a .bicep file or Arm template file and creates a readme.md from this file with information like parameters/outputs/descriptions etc.
I want to automate this documentation creation somehow in an Az... | Azure Devops Pipeline - Create documentation from IaC file | I currently have written a script that essentially takes in a .bicep file or Arm template file and creates a readme.md from this file with information like parameters/outputs/descriptions etc.
I want to automate this documentation creation somehow in an Azure DevOps pipeline, so whenever a new Bicep file is created, a ... | [
"There are two steps for you to get the bicep file and transfer the content to Json\nStep 1\nYou could refer to this document Run MsBuild to Convert .Bicep File to .Json for the method\n1.Open a Visual Studio Code terminal session.\n2.In the PowerShell session, go to the C:\\bicep-msbuild-demo directory.\n3.Run MSB... | [
1
] | [] | [] | [
"azure_devops",
"azure_pipelines",
"python"
] | stackoverflow_0074340630_azure_devops_azure_pipelines_python.txt |
Q:
Regex to match variable assignment of multiple variables in Python syntax?
I am reading whole Python files as single strings, compiling the expressions in multiline-mode. So far I have been able to match single variable assignment with Python regex:
"^\s*[A-Za-z_][A-Za-z_0-9]*\s*(?=\=)(?!==)"
^\s*: First it check... | Regex to match variable assignment of multiple variables in Python syntax? | I am reading whole Python files as single strings, compiling the expressions in multiline-mode. So far I have been able to match single variable assignment with Python regex:
"^\s*[A-Za-z_][A-Za-z_0-9]*\s*(?=\=)(?!==)"
^\s*: First it checks if variable assignment is on a new line followed by spaces. I do this to prev... | [
"Python accepts in variable names any Unicode characters marked as letters and/or numbers and the underscore. The standard re module coming with Python does not support appropriate escape sequences necessary to create a regex pattern able to match a variable name, but there exists a Python regex module supporting t... | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0058402009_python_regex.txt |
Q:
How I collect texts divided by CSS selector?
I intended to get texts next to the div-class like below codes.
<div class="review-contents__text">소재가 좀 저렴해 보이지만 그래도 입으면 휠씬 나아보여요</div>
First, I make a code like this.
texts_outer_review1 = driver.find_elements(By.CSS_SELECTOR, "div.review-contents > div.revie... | How I collect texts divided by CSS selector? | I intended to get texts next to the div-class like below codes.
<div class="review-contents__text">소재가 좀 저렴해 보이지만 그래도 입으면 휠씬 나아보여요</div>
First, I make a code like this.
texts_outer_review1 = driver.find_elements(By.CSS_SELECTOR, "div.review-contents > div.review-contents__text")
outer_TextData.append(t... | [
"what you just need is 'text' attribute.\nbut as you used find_element's' method, you would have list type.\nso the solution is\nresult = [element.text for element in texts_outer_review1]\n\nor\nresult = [element.get_property('text') for element in texts_outer_review1]\n\nand you can append or extend(cause the resu... | [
1
] | [] | [] | [
"css",
"python",
"selenium"
] | stackoverflow_0074355839_css_python_selenium.txt |
Q:
Numpy int Bit Length
I want to find the number of bits necessary to represent an unsigned numpy integer (or each element in an array of integers) in binary, in the same way the python's int.bit_length() does, but it seems that numpy has no equivalent function.
For example:
>>> int(0b1000).bit_length()
4
>>> np.uin... | Numpy int Bit Length | I want to find the number of bits necessary to represent an unsigned numpy integer (or each element in an array of integers) in binary, in the same way the python's int.bit_length() does, but it seems that numpy has no equivalent function.
For example:
>>> int(0b1000).bit_length()
4
>>> np.uint8(0b1000).bit_length()
At... | [
"You can take the ceiling of the log2 of your array.\nimport numpy as np\n\nx = np.random.randint(0, 100, size=30)\nx\n# returns:\narray([92, 7, 53, 24, 85, 53, 78, 52, 99, 91, 79, 40, 82, 34, 18, 26, 20,\n 7, 47, 38, 78, 50, 15, 12, 54, 3, 91, 82, 22, 90])\n\nnp.ceil(np.log2(x)).astype(int)\n# returns:\na... | [
1,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0063042223_numpy_python.txt |
Q:
django.core.exceptions.ImprperlyConfigured solution
I wonder why I get this error :
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing se... | django.core.exceptions.ImprperlyConfigured solution | I wonder why I get this error :
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
this is my code :
from main_app.models import stu... | [
"This problem is simply because Django doesn't know where to find required settings.\nAs it's [Documentation][1] mentions :\n When you use Django, you have to tell it which settings you’re using. Do this \n by using an environment variable, DJANGO_SETTINGS_MODULE.\n\nbased on Documentation you should do that (inf... | [
1,
1
] | [] | [] | [
"django",
"python",
"settings"
] | stackoverflow_0071376743_django_python_settings.txt |
Q:
PySpark-How to find out the top n most frequently occurring value in an array column?
For the sample data below, wondering how I can find out the most frequently occurring value in the column colour. The data type of colour is WrappedArray. There could be n number of elements in the array. In this example the colo... | PySpark-How to find out the top n most frequently occurring value in an array column? | For the sample data below, wondering how I can find out the most frequently occurring value in the column colour. The data type of colour is WrappedArray. There could be n number of elements in the array. In this example the colour should be yellow, followed by blue which appeared twice. Many thanks for your help.
Name... | [
"I would explode the colour column and then simply run groupBy and count to get what you need.\ndf \\\n.select(explode('colour').alias('colour')) \\\n.groupBy('colour') \\\n.count() \\\n.orderBy(col('count').desc())\n\n"
] | [
5
] | [] | [] | [
"apache_spark",
"apache_spark_sql",
"arrays",
"pyspark",
"python"
] | stackoverflow_0074355314_apache_spark_apache_spark_sql_arrays_pyspark_python.txt |
Q:
Get runOutput from python activity (not notebook activity) in ADF V2
I need to receive the runOutput from python activity in ADF.
In Notebook activity we can receive it using @ {activity ('databricks notebook activity name').output.runOutput}.
But same thing when I am trying to do using python activuty, it is not... | Get runOutput from python activity (not notebook activity) in ADF V2 | I need to receive the runOutput from python activity in ADF.
In Notebook activity we can receive it using @ {activity ('databricks notebook activity name').output.runOutput}.
But same thing when I am trying to do using python activuty, it is not working even though I am exiting notebook with dbutils.notebook.exit('my... | [
"I have reproduced the above and not able to get the runOutput of Python script like we get in Notebook activity.\ndbutils.notebook.exit('my message')\nI have used the above script in my .py file.\n\nAs per my repro, runOutput might not be there for python activity. You can try this workaround where I am able to ge... | [
0
] | [] | [] | [
"azure",
"azure_data_factory",
"azure_data_factory_2",
"azure_databricks",
"python"
] | stackoverflow_0074346245_azure_azure_data_factory_azure_data_factory_2_azure_databricks_python.txt |
Q:
Django rest framework create password for custom user model
Actually I'm creating an employee management system project using django rest api.
Now i have created my own custom models like shown below, i want to create the register employee with the below models. But how can i set the password field for login, sinc... | Django rest framework create password for custom user model | Actually I'm creating an employee management system project using django rest api.
Now i have created my own custom models like shown below, i want to create the register employee with the below models. But how can i set the password field for login, since I haven't included in my fields. I've attached my models and se... | [
"Yes, you can add a password field in your Employee model but you are requested not to do it because Django already provided this type of facility. Just you have to know How to use it. Try to extend the existing User model from django.contrib.auth.models.User.Let's organize your Employee model.\nfrom django.contrib... | [
0
] | [] | [] | [
"django_models",
"django_rest_framework",
"django_rest_framework_jwt",
"django_serializer",
"python"
] | stackoverflow_0074311365_django_models_django_rest_framework_django_rest_framework_jwt_django_serializer_python.txt |
Q:
Reshape a numpy array for a given time series
How do you arrange a numpy array of a time-series into a matrix with 24 hours on one side and number of days on the other side ?
for example if I have a numpy array of temperature values starting at 3 hr on 4/4/2022 and ending 23 hr on 4/5/2022. How do I arrange the t... | Reshape a numpy array for a given time series | How do you arrange a numpy array of a time-series into a matrix with 24 hours on one side and number of days on the other side ?
for example if I have a numpy array of temperature values starting at 3 hr on 4/4/2022 and ending 23 hr on 4/5/2022. How do I arrange the temperature values into an array of shape 24x2 in th... | [
"To reshape an array into a matrix, your data needs to have the correct length. In your exemplary case, the data would need to have a length of 48 records.\nTo reshape this array into 24x2, you can use numpy's reshape method, which will give a new shape to an array without changing its content.:\ndata = np.reshape(... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074342527_python.txt |
Q:
How to resolve "Parameter validation failed" error I get when uploading pandas dataframe to s3 bucket as a parquet using boto3?
I am following a tutorial on udemy where I am trying to upload pandas dataframe to s3 bucket as a parquet using boto3. I used BytesIO to convert dataframe to parquet and tried uploading i... | How to resolve "Parameter validation failed" error I get when uploading pandas dataframe to s3 bucket as a parquet using boto3? | I am following a tutorial on udemy where I am trying to upload pandas dataframe to s3 bucket as a parquet using boto3. I used BytesIO to convert dataframe to parquet and tried uploading it to my s3 bucket which I made accessible to public.
On execution I encounter an error :
Parameter validation failed:
Missing require... | [
"key should be Key (python is case sensitive):\nbucket_target.put_object(Body = out_buffer.getvalue(), Key = key)\n\n"
] | [
1
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"boto3",
"dataframe",
"python"
] | stackoverflow_0074356458_amazon_s3_amazon_web_services_boto3_dataframe_python.txt |
Q:
Unable to connect blob container using Python runbook
i am trying to connect & list the blob container using python runbook , it gives below error
Error:
Failed
Traceback (most recent call last): File "C:\Temp\o54f0ym2.hp4\64f6d97c-4b5b-4ab5-80b2-e9425a2f829e", line 5, in for blob in blob_list: File "C:\WPy... | Unable to connect blob container using Python runbook | i am trying to connect & list the blob container using python runbook , it gives below error
Error:
Failed
Traceback (most recent call last): File "C:\Temp\o54f0ym2.hp4\64f6d97c-4b5b-4ab5-80b2-e9425a2f829e", line 5, in for blob in blob_list: File "C:\WPy64-3800\python-3.8.0.amd64\lib\site-packages\azure\core\pag... | [
"I tried to reproduce the same in my environment and got the similar error like below:\n\nThe error usually occurs if the required permissions are not granted to perform the action.\nI created an Azure Storage container and uploaded test blob:\n\nTo resolve the error, make sure to generate the connection string lik... | [
0
] | [] | [] | [
"azure",
"azure_blob_storage",
"azure_storage",
"python"
] | stackoverflow_0074348925_azure_azure_blob_storage_azure_storage_python.txt |
Q:
How can I get attrdict module working in Python?
I want to execute the following example:
from attrdict import AttrDict
a = AttrDict({'foo': 'bar'})
print(a.foo)
but I got this error: ImportError: cannot import name 'Mapping' from 'collections' (C:\Users\user\AppData\Local\Programs\Python\Python310\lib\collectio... | How can I get attrdict module working in Python? | I want to execute the following example:
from attrdict import AttrDict
a = AttrDict({'foo': 'bar'})
print(a.foo)
but I got this error: ImportError: cannot import name 'Mapping' from 'collections' (C:\Users\user\AppData\Local\Programs\Python\Python310\lib\collections\__init__.py)
How can I solve it? I feel it is like ... | [
"You can monkeypatch the collections module near the start of your app before the module is imported elsewhere.\n# Monkey patch collections\nimport collections\nimport collections.abc\nfor type_name in collections.abc.__all__:\n setattr(collections, type_name, getattr(collections.abc, type_name))\n\n",
"The At... | [
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0072361026_python_python_3.x.txt |
Q:
Error (-215) size.width>0 && size.height>0 occurred when attempting to display an image using OpenCV
I am trying to run a simple program that reads an image from OpenCV. However, I am getting this error:
error: ......\modules\highgui\src\window.cpp:281: error: (-215) size.width>0 && size.height>0 in function cv::i... | Error (-215) size.width>0 && size.height>0 occurred when attempting to display an image using OpenCV | I am trying to run a simple program that reads an image from OpenCV. However, I am getting this error:
error: ......\modules\highgui\src\window.cpp:281: error: (-215) size.width>0 && size.height>0 in function cv::imshow
Any idea what this error means?
Here is my code:
from matplotlib import pyplot as plt
import numpy ... | [
"\"error: (-215)\" means that an assertion failed. In this case, cv::imshow asserts that the given image is non-empty: https://github.com/opencv/opencv/blob/b0209ad7f742ecc22de2944cd12c2c9fed036f2f/modules/highgui/src/window.cpp#L281\nAs noted in the Getting Started with Images OpenCV Python tutorial, if the file d... | [
18,
9,
4,
2,
1,
1,
0,
0,
0,
0
] | [
"import numpy as np\nimport cv2\nimg=cv2.imread('E:\\itsme\\Camera\\pic.jpg',10)\ncv2.imshow('image',img)\ncv2.waitkey(0)\ncv2.destroyallwindows()\n\njust add fill the full directory of your picture in string.\n",
"my problem was the same while i found the endswitch of jpg - it was jpEg. )\n"
] | [
-1,
-3
] | [
"opencv",
"python"
] | stackoverflow_0043572387_opencv_python.txt |
Q:
PySimpleGUI in python: Disable window move by user(with CTRL+mouse1)
A window can be moved by holding down CTRL and Mouse1, I would love to deactivate it, or deactivate window moving in general.
My problem is, that I use the CTRL key to mark multiple images in my explorer.
After my image is marked, the image is pr... | PySimpleGUI in python: Disable window move by user(with CTRL+mouse1) | A window can be moved by holding down CTRL and Mouse1, I would love to deactivate it, or deactivate window moving in general.
My problem is, that I use the CTRL key to mark multiple images in my explorer.
After my image is marked, the image is processed in PIL, which takes like 100-200ms.
So when the user holds down CT... | [
"Refer PySimpleGUI Call Reference\nOption in Window\n\ngrab_anywhere_using_control\nIf True can use CONTROL key + left mouse mouse to click and drag to move the window. DEFAULT is TRUE. Unlike normal grab anywhere, it works on all elements.\n\nwindow = sg.Window('Title', layout, grab_anywhere_using_control=False)\n... | [
0
] | [] | [] | [
"pysimplegui",
"python",
"window_position"
] | stackoverflow_0074356432_pysimplegui_python_window_position.txt |
Q:
How to add function to multi columns?
I have the df:
lst_1 = ['November-2022', 'October-2022', 'September-2022', 'November-2022']
lst_2 = ['', '', '', '', '']
lst_3 = ['', '', '', '', '']
lst_4 = ['', '', '', '', '']
df1 = pd.DataFrame(list(zip(lst_1 , lst_2, lst_3, lst_4)),
columns =['Date_updated'... | How to add function to multi columns? | I have the df:
lst_1 = ['November-2022', 'October-2022', 'September-2022', 'November-2022']
lst_2 = ['', '', '', '', '']
lst_3 = ['', '', '', '', '']
lst_4 = ['', '', '', '', '']
df1 = pd.DataFrame(list(zip(lst_1 , lst_2, lst_3, lst_4)),
columns =['Date_updated', 'November-2022', 'October-2022', 'Septemb... | [
"Use pd.crosstab:\nnew_df = df.set_index('Date_updated')\noutput = pd.crosstab(index=new_df.index, columns=new_df.columns, values='x', \n aggfunc=lambda x: x).fillna('')\n\nOutput:\ncol_0 November-2022 October-2022 September-2022\nrow_0 \nNovember-2022 x ... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074355715_dataframe_pandas_python.txt |
Q:
Finding Minutes Between Years
can you please check my code? I think something is wrong somewhere.
import datetime
this_year = datetime.datetime.today().year
def age_in_minutes(b_year: int):
d1 = datetime.datetime.strptime(f'{this_year}', '%Y')
d2 = datetime.datetime.strptime(f'{b_year}', '%Y')
age = ... | Finding Minutes Between Years | can you please check my code? I think something is wrong somewhere.
import datetime
this_year = datetime.datetime.today().year
def age_in_minutes(b_year: int):
d1 = datetime.datetime.strptime(f'{this_year}', '%Y')
d2 = datetime.datetime.strptime(f'{b_year}', '%Y')
age = (d1-d2).days * 24 * 60
return ... | [
"You could try this code\nI found it somewhere in 2021 but I don't know the source\ncurrent_year = 2022\nyear = int(input(\"Please enter a year: \"))\n\nif year == current_year:\n print(\"There are 0 minutes from\", year, \"to present.\")\nelif year < current_year:\n print(\"There are\", (current_year - year)... | [
0,
0,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0074355782_datetime_python.txt |
Q:
'pip' is not recognized as an internal or external command in python
I'm running into a weird error when trying to install pip
This is the sequence that I typed into my command line:
pip install opencv-python
What could be causing this?
This is what I get when I type in echo %PATH%:
C:\Program Files (x86)\Common F... | 'pip' is not recognized as an internal or external command in python | I'm running into a weird error when trying to install pip
This is the sequence that I typed into my command line:
pip install opencv-python
What could be causing this?
This is what I get when I type in echo %PATH%:
C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\intel64\compiler;C:\Windows\system32;C:... | [
"“naglaa“ in your path looks suspicious. User names shouldn't be in quotes, and especially smart quotes. The drive letter is missing as well: :\\users\\“naglaa“\\AppData\\Programs\\Python\\Python310.\nIdeally, don't put Python in the Windows path and use py (the Python Launcher) as in py -m pip install opencv-pyt... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074356221_python.txt |
Q:
Open spyder in ubuntu
I want to open spyder(Python IDE) in ubuntu.
Normally I would write "spyder" in the shell, and it would open the spyder IDE.
Now when I write spyder in the shell, it just new lines, and nothing happens(similar to pressing 'enter').
--- How do I get my spyder back?
EDIT - I get no errors, it j... | Open spyder in ubuntu | I want to open spyder(Python IDE) in ubuntu.
Normally I would write "spyder" in the shell, and it would open the spyder IDE.
Now when I write spyder in the shell, it just new lines, and nothing happens(similar to pressing 'enter').
--- How do I get my spyder back?
EDIT - I get no errors, it just skips to the next line.... | [
"If typing \"spyder\" doesn't work, you might want to try typing \"spyder3\" in case you installed the spyder3 version. Below is what worked for me in my Ubuntu system.\nTo install spyder via pip (my python version is 3.6.2), I used:\n pip install spyder\n\nThen, I had to install another package:\n pip install PyQt... | [
8,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"linux",
"python",
"shell",
"spyder",
"ubuntu"
] | stackoverflow_0029077826_linux_python_shell_spyder_ubuntu.txt |
Q:
Project in Python for a robot moving in a 10 by 10 grid, with some extra requirements
I have a project to write code in Python that will control a robot's movements in a 10 by 10 grid. First i would like to point out that i am a beginner so it would be better for me if i can get simple lines of code that i can dig... | Project in Python for a robot moving in a 10 by 10 grid, with some extra requirements | I have a project to write code in Python that will control a robot's movements in a 10 by 10 grid. First i would like to point out that i am a beginner so it would be better for me if i can get simple lines of code that i can digest.
So, the project asks for:
A 10 by 10 grid, with the robot starting from the uppermost ... | [
"while True:\ntry:\n n = int(input(\"Δώσε διαστάσεις του grid:\"))\n n1 = n*n\n print(f\"Το ρομπότ κινείται σε χώρο {n1}. Η αρχική του θέση είναι:\", x, \",\", y)\nexcept ValueError:\n print(\"Παρακαλώ δώσε θετικό ακέραιο αριθμό\")\n continue\n\nwhile True:\n try:\n move = input(\"Δώσε κίνη... | [
0
] | [] | [] | [
"grid",
"python",
"python_3.x",
"robot"
] | stackoverflow_0074265400_grid_python_python_3.x_robot.txt |
Q:
Integer difference in python between two dates
I've RTFM and read many questions and answers here on SO regarding this, and was happily using strftime and strptime yesterday, so I would swear this should work, but it isn't....
I just want an integer. Not a "timedelta object." Not an "aware yet hashable object" (... | Integer difference in python between two dates | I've RTFM and read many questions and answers here on SO regarding this, and was happily using strftime and strptime yesterday, so I would swear this should work, but it isn't....
I just want an integer. Not a "timedelta object." Not an "aware yet hashable object" (see, I RTFM). Not a tuple. Not a dictionary. Ju... | [
"You want to get the classmethod datetime.datetime.strptime(), then take the .days attribute from the resulting timedelta:\nimport datetime\n\nmdate = \"2010-10-05\"\nrdate = \"2010-10-05\"\nmdate1 = datetime.datetime.strptime(mdate, \"%Y-%m-%d\").date()\nrdate1 = datetime.datetime.strptime(rdate, \"%Y-%m-%d\").dat... | [
43,
5,
0
] | [] | [] | [
"date",
"datetime",
"python"
] | stackoverflow_0016170737_date_datetime_python.txt |
Q:
How can I fix the "zsh: command not found: python" error? (macOS Monterey 12.3, Python 3.10, Atom IDE, and atom-python-run 0.9.7)
Since I got the macOS v12.3 (Monterey) update (not sure it's related though), I have been getting this error when I try to run my Python code in the terminal:
I am using Python 3.10.3,... | How can I fix the "zsh: command not found: python" error? (macOS Monterey 12.3, Python 3.10, Atom IDE, and atom-python-run 0.9.7) | Since I got the macOS v12.3 (Monterey) update (not sure it's related though), I have been getting this error when I try to run my Python code in the terminal:
I am using Python 3.10.3, Atom IDE, and run the code in the terminal via atom-python-run package (which used to work perfectly fine). The settings for the packa... | [
"Anyone updating their macOS to Monterey 12.3 will find that they suddenly no longer have the system-provided Python 2.\nThe reason for this is that Apple removed the system-provided Python 2 installation (details).\nSo a workaround/solution for this is to use pyenv to install Python 2.7 (or any other specific vers... | [
231,
71,
32,
10,
10,
5,
5,
3,
1,
0,
0,
0
] | [
"I have a MacBook Pro with an Apple M1 chip and macOS v12.4 (Monterey).\n\nI deleted all Python versions and cleared the trash\nOpened Terminal and typed \"python\"\nThis prompted an xcode.app update\nThen I downloaded the latest version of Python from python.org (version 2.10.5)\nInstalled that version\nQuit Termi... | [
-1,
-1
] | [
"atom_editor",
"macos",
"macos_monterey",
"python",
"terminal"
] | stackoverflow_0071591971_atom_editor_macos_macos_monterey_python_terminal.txt |
Q:
ttk.Treeview.focus() on 1st entry in my tree-view is giving "I001" instead of 1, I need 1 so I can update entry on the tree-view using insert()
I am trying to update an entry on my tree-view.
The issue I am facing is, when I click to update an entry the ttk.Treeview.focus() methods gives me 'I001' on the first ent... | ttk.Treeview.focus() on 1st entry in my tree-view is giving "I001" instead of 1, I need 1 so I can update entry on the tree-view using insert() | I am trying to update an entry on my tree-view.
The issue I am facing is, when I click to update an entry the ttk.Treeview.focus() methods gives me 'I001' on the first entry for example and with this I cannot update my entry as it gives an error on treeview.insert()
My Code is as below:
`
from tkinter import *
from tki... | [
"You can simply update the selected row instead of deleting row and then inserting row:\ndef update_record():\n # get item ID (iid) of selected row\n x = register.focus()\n if x:\n # a row is selected\n new_value = (sn.get(), bn.get(), cn.get())\n # update the row using the item ID of ... | [
1
] | [] | [] | [
"focus",
"insert",
"python",
"tkinter",
"treeview"
] | stackoverflow_0074356592_focus_insert_python_tkinter_treeview.txt |
Q:
Is there a way to get headers from an url in python?
Is there a way to get the headers from url in any format like charles proxy does in python.
A:
Yes, there is a way to get headers from an URL in Python programming language. The requests module provides a way to do this.
import requests
url = "https://www.goog... | Is there a way to get headers from an url in python? | Is there a way to get the headers from url in any format like charles proxy does in python.
| [
"Yes, there is a way to get headers from an URL in Python programming language. The requests module provides a way to do this.\nimport requests\nurl = \"https://www.google.com\"\nresponse = requests.head(url)\nprint(response.headers) # prints the entire header as a dictionary\nprint(response.headers[\"Content-Lengt... | [
3
] | [] | [] | [
"http_headers",
"python"
] | stackoverflow_0074356738_http_headers_python.txt |
Q:
Matplotlib - chart - ValueError: 'label' must be of length 'x'
plt.figure(figsize = (12,8))
plt.pie(df['Rating'].value_counts().sort_index(),
labels=df['Rating'].value_counts().sort_index().index,
explode = [0.00,0.0,0.0,0.0,0.05],
autopct= '%.2f%%',
colors = ["#ff4545", "#ffa534",'#ff... | Matplotlib - chart - ValueError: 'label' must be of length 'x' | plt.figure(figsize = (12,8))
plt.pie(df['Rating'].value_counts().sort_index(),
labels=df['Rating'].value_counts().sort_index().index,
explode = [0.00,0.0,0.0,0.0,0.05],
autopct= '%.2f%%',
colors = ["#ff4545", "#ffa534",'#ffe234','#b7dd29','#57e32c'],
shadow= True,
startangle= ... | [
"The pie documentation can help you.\nRegarding the error, here is information about explode and x:\n\nParameters: x, 1D array-like The wedge sizes.\nexplode, default: None If not None, is a len(x) array which\nspecifies the fraction of the radius with which to offset each wedge.\n\nIf you want for the code to work... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074356589_matplotlib_python.txt |
Q:
Python Subprocess.run Seemingly does Nothing
I am writing a wrapper script to make generation of random maps for a game more convenient. The idea is to be able to let the game generate a bunch of maps while I go do something else (as it can take quite a while with large maps).
Here is the script: https://pastebin.... | Python Subprocess.run Seemingly does Nothing | I am writing a wrapper script to make generation of random maps for a game more convenient. The idea is to be able to let the game generate a bunch of maps while I go do something else (as it can take quite a while with large maps).
Here is the script: https://pastebin.com/MSLc9C3J
The important part is:
command_str = ... | [
"2 things that may help:\n\nif you are going to split your command into a list of strings, then make shell = False, if you use the command as a whole (a single string), use shell = True. So...\neither: subprocess.run(split(cmd), shell = False... or subprocess.run(command_str, shell = True...\n\nif you want to see t... | [
1
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0074356214_python_subprocess.txt |
Q:
Python threading, some printing messages turn concatenated in one line
Here I have a code containing a simple class printing something. I want to multithread it.
import threading
import time
import random
class Useless:
def __init__(self, numb):
self.numb = numb
def printing(self):
time.s... | Python threading, some printing messages turn concatenated in one line | Here I have a code containing a simple class printing something. I want to multithread it.
import threading
import time
import random
class Useless:
def __init__(self, numb):
self.numb = numb
def printing(self):
time.sleep(random.uniform(0.05, 0.09))
print(f'number {self.numb} is bein... | [
"Although there is no guarantees (this is highly OS specific), you can hardly send newline to stdout instead of python handling this\ndef printing(self):\n print(f'number {self.numb} is being printed God knows what for...\\n', end='')\n\nBut I still do not recommend using this approach as it does not solve probl... | [
1,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0074331089_multithreading_python.txt |
Q:
Change PyADS Cycle Time (variable update time)
I have a signal that is continuously updated (at about 200 Hz). I am using PyADS (write_by_name) to write to a global variable in my Beckhoff IPC. I concurrently run a scope project and export results. My PLC Cycle time is 1 ms so all of the variables of interest are ... | Change PyADS Cycle Time (variable update time) | I have a signal that is continuously updated (at about 200 Hz). I am using PyADS (write_by_name) to write to a global variable in my Beckhoff IPC. I concurrently run a scope project and export results. My PLC Cycle time is 1 ms so all of the variables of interest are collected at 1 ms intervals by the Scope Project. Bu... | [
"ADS is not meant for fast, real time, communication. I don't think there is a way that you can speed it up by software settings. It is just a property of the protocol.\nI did find this link which talks about fast-ADS. I mentions cycle times < 1 ms, but it requires special hardware.\n"
] | [
1
] | [] | [] | [
"python",
"twincat",
"twincat_ads"
] | stackoverflow_0074355181_python_twincat_twincat_ads.txt |
Q:
How do I call parent file's method in a child package?
Say I have a simple method in main.py that I want to call from second.py
# File Structure
src
|_package
| | __init__.py
| | second.py
|
| main.py
main.py
def foo():
print("Yo")
Is there any way I can achieve this?
A:
As suggested earlier, even I t... | How do I call parent file's method in a child package? | Say I have a simple method in main.py that I want to call from second.py
# File Structure
src
|_package
| | __init__.py
| | second.py
|
| main.py
main.py
def foo():
print("Yo")
Is there any way I can achieve this?
| [
"As suggested earlier, even I tried to replicate the same folder structure as seen in the image below\nFolder Structure\nNow, I added the file __init__.py in the folder outside src. (in the folder where main.py resides)\nthen calling the function in second.py\nfrom main import *\n\nfoo()\n\nit works perfectly fine ... | [
0
] | [] | [] | [
"module",
"package",
"python"
] | stackoverflow_0074355490_module_package_python.txt |
Q:
get importer modules from within the module that is being imported
For example, i have 2 .py files module1 and module2.
module2 imports the module1 using the import statement.
I want to have some way inside the module1 to detect (from within the module1 itself) which modules are importing it. in this case the modu... | get importer modules from within the module that is being imported | For example, i have 2 .py files module1 and module2.
module2 imports the module1 using the import statement.
I want to have some way inside the module1 to detect (from within the module1 itself) which modules are importing it. in this case the module2 is importing it.
What I did:
if I import the module1 from the module... | [
"Imports in Python are actually calls to functions in importlib, so you just need to get the information of the caller who calls functions in importlib by inspecting frames in the call stack.\nHowever, which frame in the call stack is the actual caller's frame varies between Python versions due to different impleme... | [
0
] | [] | [] | [
"python",
"python_import"
] | stackoverflow_0074356449_python_python_import.txt |
Q:
Pygame headless setup
I am using pygame's joystick api to use a joystick with my project on a headless system, but pygame requires a "screen" so I have setup a dummy video system to over come this. It worked fine but now all of a sudden it gives me this error:
Traceback (most recent call last):
File "compact.py"... | Pygame headless setup | I am using pygame's joystick api to use a joystick with my project on a headless system, but pygame requires a "screen" so I have setup a dummy video system to over come this. It worked fine but now all of a sudden it gives me this error:
Traceback (most recent call last):
File "compact.py", line 10, in <module>
... | [
"Pygame is trying to open a console which means you're running this script through ssh or cron or somewhere else that doesn't have access to the console. I would try skipping set_mode (since the dummy driver likely doesn't have modes to set) and just try to initialize the display. You can try running it as root whi... | [
8,
0
] | [] | [] | [
"headless",
"joystick",
"pygame",
"python"
] | stackoverflow_0032900155_headless_joystick_pygame_python.txt |
Q:
Concatenate rows based on a condition in Python
In this table, all columns are strings. If there is a string == "nan" in column Title, I would like to concatenate all the rows with nan string with the last values in Title != "nan." For example
From this:
Title
Content
Measure
Background
text1
Measure 1
Method
a... | Concatenate rows based on a condition in Python | In this table, all columns are strings. If there is a string == "nan" in column Title, I would like to concatenate all the rows with nan string with the last values in Title != "nan." For example
From this:
Title
Content
Measure
Background
text1
Measure 1
Method
abc
Measure 1
nan
dfg
Measure 1
Background
... | [
"you can use:\ndf['last_nan_value']=df['Title'].fillna(method='ffill') #fill nans with last nan value in new column\n\ndf['id'] = ((df.last_nan_value != df.last_nan_value.shift())).cumsum() #assing an id for each title until title change\n\nprint(df)\n'''\n Title Content Measure last_nan_value id\n0 ... | [
0
] | [] | [] | [
"concatenation",
"function",
"pandas",
"python",
"string"
] | stackoverflow_0074354757_concatenation_function_pandas_python_string.txt |
Q:
How to change the tkiner window border color?
I need to change the color of the Tkinter window border-color in windows 10 python. The border is shown in the image below.
I found a command that can delete the border
root.overrideredirect(1)
when I use this command I need to rebuild the border again but the functio... | How to change the tkiner window border color? | I need to change the color of the Tkinter window border-color in windows 10 python. The border is shown in the image below.
I found a command that can delete the border
root.overrideredirect(1)
when I use this command I need to rebuild the border again but the functionality is different. So it's not an option.
Is ther... | [
"Sorry you cannot change the color of the border as it is created by the OS and it changes device-to-device. But you can use overrideredirect(1) to cancel the border. And to exit the window, you can use the destroy() command.\n"
] | [
0
] | [] | [] | [
"border",
"python",
"tkinter",
"window"
] | stackoverflow_0066457220_border_python_tkinter_window.txt |
Q:
Is there a way to identify a web element selenium using an already identified element?
I have an element identified using python selenium.
Below is the code:
driver.get("https://stackoverflow.com/")
element = driver.find_element(By.XPATH, "//a[@class="s-topbar--logo js-gps-track"])
Is there a way to identify a we... | Is there a way to identify a web element selenium using an already identified element? | I have an element identified using python selenium.
Below is the code:
driver.get("https://stackoverflow.com/")
element = driver.find_element(By.XPATH, "//a[@class="s-topbar--logo js-gps-track"])
Is there a way to identify a web element in python selenium using an already identified element? using any method possible.... | [
"We can find child element based on parent element instance and some child element attributes similarly to how we locating regular element. This can be done both with XPath and CSS Selectors.\nFor example, let's say the child element is div with id=child.\nLocating this element with XPath will be as following:\ndri... | [
1
] | [] | [] | [
"css_selectors",
"element",
"python",
"selenium",
"xpath"
] | stackoverflow_0074337843_css_selectors_element_python_selenium_xpath.txt |
Q:
cloudscraper.exceptions.CloudflareChallengeError: Detected a Cloudflare version 2 Captcha challenge
Main.py
import cloudscraper
scraper = cloudscraper.create_scraper()
cs_recent_page = scraper.get('https://coinsniper.net/new').text
Error
cloudscraper.exceptions.CloudflareChallengeError: Detected a Cloudflare ver... | cloudscraper.exceptions.CloudflareChallengeError: Detected a Cloudflare version 2 Captcha challenge | Main.py
import cloudscraper
scraper = cloudscraper.create_scraper()
cs_recent_page = scraper.get('https://coinsniper.net/new').text
Error
cloudscraper.exceptions.CloudflareChallengeError: Detected a Cloudflare version 2 Captcha challenge, This feature is not available in the opensource (free) version.
I'm trying to a... | [
"You could use ScrapingAnt instead of cloudscraper - it's pretty useful unless you need to scrape a very large number of pages (the free tier only allows 10k requests per month). If you register, they give you a token that you can paste into the code below:\nimport requests\nimport urllib.parse\nfrom bs4 import Bea... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"python_requests",
"web_scraping"
] | stackoverflow_0074352220_beautifulsoup_python_python_requests_web_scraping.txt |
Q:
Python/Numpy equivalent of MATLAB isosurface functions
Anyone can suggest the equivalent function of MATLAB's "isosurface" function in python/numpy. The MATLAB isosurface returns the faces and vertices. I need the faces and vertices to create .stl files. MATLAB isosurface function looks like this:
[f,v] = isosurfa... | Python/Numpy equivalent of MATLAB isosurface functions | Anyone can suggest the equivalent function of MATLAB's "isosurface" function in python/numpy. The MATLAB isosurface returns the faces and vertices. I need the faces and vertices to create .stl files. MATLAB isosurface function looks like this:
[f,v] = isosurface(X,Y,Z,V,isovalue)
in python I have found this one metho... | [
"Although it wasn't among your target libraries, PyVista built on VTK can help you do this easily (disclaimer: I'm one of the devs). Since you seemed receptive of a PyVista-based solution in comments, here's how you'd do it:\n\ndefine a mesh, generally as a StructuredGrid for your kind of data, although the equidis... | [
5,
0
] | [] | [] | [
"isosurface",
"matlab",
"numpy",
"python"
] | stackoverflow_0068834185_isosurface_matlab_numpy_python.txt |
Q:
Alembic SQLAlchemy autogenerate MetaData error
I am trying to create a migration with alembic running alembic revision --autogenerate -m 'initial setup' but I'm getting the error:
FAILED: Can't proceed with --autogenerate option; environment script /Users/paul/python/my_project/alembic/env.py does not provide a M... | Alembic SQLAlchemy autogenerate MetaData error | I am trying to create a migration with alembic running alembic revision --autogenerate -m 'initial setup' but I'm getting the error:
FAILED: Can't proceed with --autogenerate option; environment script /Users/paul/python/my_project/alembic/env.py does not provide a MetaData object or sequence of objects to the context... | [
"The problem turned out to be with my editor. I closed the env.py file, reopened it, and all the changes where there as expected. Then I decided to see what happened if I opened the file by command+clicking it from the error message in the console (I'm using VSCode) and none of my changes where there when I opened ... | [
2,
0,
0
] | [] | [] | [
"alembic",
"python",
"sqlalchemy"
] | stackoverflow_0057154376_alembic_python_sqlalchemy.txt |
Q:
Can't print colored text in the exact middle
import shutil
columns = shutil.get_terminal_size().columns
from termcolor import colored
col = colored("test", 'white', 'on_red')
print(f"This is a {col} run".center(columns))
print('this is a test run'.center(columns))
For the above code, if i run it, the two lines o... | Can't print colored text in the exact middle | import shutil
columns = shutil.get_terminal_size().columns
from termcolor import colored
col = colored("test", 'white', 'on_red')
print(f"This is a {col} run".center(columns))
print('this is a test run'.center(columns))
For the above code, if i run it, the two lines of output don't have the same indentation.
... | [
"Well, the behavior of f-string vs str.format() is similar:\nprint(f\"This is a {col} run\".center(columns))\nprint('this is a {} run'.format(col).center(columns))\n\nThis will produce a constant indent.\nNow what caused the problem with different indentation:\nlen(col) # is 18\nlen('test') # is 4\n\nall the format... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074356271_python.txt |
Q:
How to get response SSL certificate from requests in python?
Trying to get the SSL certificate from a response in requests.
What is a good way to do this?
A:
requests deliberately wraps up low-level stuff like this. Normally, the only thing you want to do is to verify that the certs are valid. To do that, just p... | How to get response SSL certificate from requests in python? | Trying to get the SSL certificate from a response in requests.
What is a good way to do this?
| [
"requests deliberately wraps up low-level stuff like this. Normally, the only thing you want to do is to verify that the certs are valid. To do that, just pass verify=True. If you want to use a non-standard cacert bundle, you can pass that too. For example:\nresp = requests.get('https://example.com', verify=True, c... | [
33,
13,
6,
3,
2,
0,
0,
0
] | [] | [] | [
"http",
"https",
"python",
"python_requests",
"request"
] | stackoverflow_0016903528_http_https_python_python_requests_request.txt |
Q:
How to find a distance between categorical data
I plan to calculate distance between categorical data (Distance From First Dataset to Second Dataset)
Here's my dataset
First Dataset
Id City Phone
A1 Jakarta Samsung
A2 Surabaya Apple
A3 Singapore Sony
Second Dataset (as Input)
Id ... | How to find a distance between categorical data | I plan to calculate distance between categorical data (Distance From First Dataset to Second Dataset)
Here's my dataset
First Dataset
Id City Phone
A1 Jakarta Samsung
A2 Surabaya Apple
A3 Singapore Sony
Second Dataset (as Input)
Id City Phone
1 Jakarta Samsung
2 ... | [
"You can use cross join for all combinations of rows between both DataFrames, then add new columns by DataFrame.join, sum both columns and last reshape by DataFrame.pivot:\ndf = df2.merge(df1, how='cross', suffixes=('','_'))\ndf = df.join(City.stack().rename('C'), on=['City','City_'])\ndf = df.join(Phone.stack().re... | [
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074355067_pandas_python.txt |
Q:
How do I change my VScode settings to not sync specific commands?
I am using VScode on both my Macbook and my PC and my settings are synced. I use coderunner to run my python programs. My problem is that in my settings.json, the command I use to run my program on my mac is different to the one I need to use on my ... | How do I change my VScode settings to not sync specific commands? | I am using VScode on both my Macbook and my PC and my settings are synced. I use coderunner to run my python programs. My problem is that in my settings.json, the command I use to run my program on my mac is different to the one I need to use on my PC. The specific command I use is
clear && python3 -u. Since Vscode run... | [
"You put forward a solution in the comment.\nI think I can add it appropriately. In the detailed description of Settings Sync, we can also use ignoreUploadFiles or ignoreUploadFolders to disable the specified file:\n\n",
"As you already found out, you can exclude specific settings from syncing by defining this in... | [
0,
0
] | [] | [] | [
"python",
"python_3.x",
"visual_studio_code"
] | stackoverflow_0074354376_python_python_3.x_visual_studio_code.txt |
Q:
How do to use a python script in Unity?
I'm trying to run a face detection model in Unity. It gets input from the webcam, then spits out a face. But trying to make this work with C# has been an absolute nightmare. And despite all my suffering, I still haven't been able to make it work!
If I could use python, I'd b... | How do to use a python script in Unity? | I'm trying to run a face detection model in Unity. It gets input from the webcam, then spits out a face. But trying to make this work with C# has been an absolute nightmare. And despite all my suffering, I still haven't been able to make it work!
If I could use python, I'd be able to get it done easily. So, obviously, ... | [
"Unfortunately, Unity at this time does not support Python. Although, there is an asset that you can use a bit of Python with. I am not sure what you can do with this asset but I know it could help a minimal amount:https://assetstore.unity.com/packages/tools/integration/python-interpreter-645\nQuick Note: Most prog... | [
2,
1,
0,
0,
0
] | [] | [] | [
"python",
"unity3d"
] | stackoverflow_0071179346_python_unity3d.txt |
Q:
How to interpolate values between points
I have this dataset show below
temp = [0.1, 1, 4, 10, 15, 20, 25, 30, 35, 40]
sg =[0.999850, 0.999902, 0.999975, 0.999703, 0.999103, 0.998207, 0.997047, 0.995649, 0.99403, 0.99222]
sg_temp = pd.DataFrame({'temp' : temp,
'sg' : sg})
temp sg
0... | How to interpolate values between points | I have this dataset show below
temp = [0.1, 1, 4, 10, 15, 20, 25, 30, 35, 40]
sg =[0.999850, 0.999902, 0.999975, 0.999703, 0.999103, 0.998207, 0.997047, 0.995649, 0.99403, 0.99222]
sg_temp = pd.DataFrame({'temp' : temp,
'sg' : sg})
temp sg
0 0.1 0.999850
1 1.0 0.999902
2 4.0 0.... | [
"It works very well for me. What exactly does not work for you?\nHave you correctly used the returned CubicSpline to generate your interpolated values? Or is there some kind of error?\nBasically you obtain your interpolated y values by plugging in the new x values (scale) to your returned CubicSpline function:\ny =... | [
1,
1
] | [] | [] | [
"interpolation",
"python",
"scipy"
] | stackoverflow_0074357101_interpolation_python_scipy.txt |
Q:
Python Kill Running Threads Upon Timeout or Interrupt
I am trying to stop the running threads which is started by the ThreadPoolExecutor after timeout or keyboard interruption which is not happening. It is waiting for the entire time until the running thread completes the execution. The future threads are getting ... | Python Kill Running Threads Upon Timeout or Interrupt | I am trying to stop the running threads which is started by the ThreadPoolExecutor after timeout or keyboard interruption which is not happening. It is waiting for the entire time until the running thread completes the execution. The future threads are getting stopped successfully.
How can I stop the running threads af... | [
"can use python-worker (link)\nimport time\nfrom worker import worker, ThreadWorkerManager\n\n# allow keyboard interrupt\nThreadWorkerManager.enableKeyboardInterrupt()\n\n# timeout maintainer\n@worker\ndef run_with_timeout(worker_object, timeout):\n while worker_object.work_time < timeout:\n time.sleep(0.... | [
0
] | [] | [] | [
"multithreading",
"python",
"python_multithreading",
"threadpool"
] | stackoverflow_0074269628_multithreading_python_python_multithreading_threadpool.txt |
Q:
Calculating best-case, worse-case Complexity
If I have a function that is quadratic complexity, i.e. the runtime is directly proportional to the square of the input size. How would I identify its best or worse case runtime, specifically how do I determine if the best and worst case are the same?
A:
This really ... | Calculating best-case, worse-case Complexity | If I have a function that is quadratic complexity, i.e. the runtime is directly proportional to the square of the input size. How would I identify its best or worse case runtime, specifically how do I determine if the best and worst case are the same?
| [
"This really depends on your algorithm and your input data. For example\na search algorithm can have a typically runtime of O(x^2) but in certain situations this differs:\n\nTypically runtime is for statistically random data (normal case)\n\nIf the input data is already sorted (best case), then it depends on the al... | [
1
] | [] | [] | [
"big_o",
"computer_science",
"python"
] | stackoverflow_0074356911_big_o_computer_science_python.txt |
Q:
How to Create Non-Stop Loop to skip Error: Selenium.common.exceptions.WebDriverException Selenium Python
I created a Python Selenium script to filter out URLs that have the specific elements. Almost Everything was working fine. But I am continuously getting some non-resolving exceptions, after these exceptions, my... | How to Create Non-Stop Loop to skip Error: Selenium.common.exceptions.WebDriverException Selenium Python | I created a Python Selenium script to filter out URLs that have the specific elements. Almost Everything was working fine. But I am continuously getting some non-resolving exceptions, after these exceptions, my script stops:
selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_NAME_NOT_RESOLV... | [
"I guess the WebDriverException comes from the line driver.get(rawUrls), move that line into the try except block.\n"
] | [
0
] | [] | [] | [
"loops",
"python",
"selenium"
] | stackoverflow_0072655541_loops_python_selenium.txt |
Q:
In Python, within a string, remove multiple spaces with a single space, if it's not leading multi spaces
I have various strings that might have multiple leading spaces.
string_1 = ' param A val A'
string_2 = 'param B val B'
....
I want to replace all multiple spaces with a single space IF the multiple... | In Python, within a string, remove multiple spaces with a single space, if it's not leading multi spaces | I have various strings that might have multiple leading spaces.
string_1 = ' param A val A'
string_2 = 'param B val B'
....
I want to replace all multiple spaces with a single space IF the multiple spaces are not in the start of the string.
I want output of above to become
string_1 = ' param A val A'z
... | [
"You can use \\b\\s{2,}\\b as your pattern, If those multiple spaces are leading, they are not in a word boundary. Also for multiple spaces use {2,} instead of + to exclude single space:\nimport re\n\n\nstring_1 = \" param A val A\"\nstring_2 = \"param B val B\"\n\n\npattern = re.compile(r\"\\b\\s{2,}\\b\... | [
5,
3,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074356762_python_regex.txt |
Q:
Elastic search Api
Hey Stackoverflow fam,
I am working on an API which pulls requests from elastic search tool and displays it.
I am trying to pull data using get request
import requests
import json
payload = {
"query": {
"match": {
"metric": "metric_name"
}
}
}
url = "https://u... | Elastic search Api | Hey Stackoverflow fam,
I am working on an API which pulls requests from elastic search tool and displays it.
I am trying to pull data using get request
import requests
import json
payload = {
"query": {
"match": {
"metric": "metric_name"
}
}
}
url = "https://url_name:9200/siren-kines... | [
"In the case of Basic Auth in any request, if you're requesting via postman you can provide the credentials in the Authentication tab. But In the case of Code/Console/Browser, the certificates must be given in the request URL.\ne.g.\nhttps://username:password@URL\nhttps://admin:admin@www.the-internet.herokuapp.com/... | [
0
] | [] | [] | [
"api",
"elasticsearch",
"kibana",
"python"
] | stackoverflow_0071437605_api_elasticsearch_kibana_python.txt |
Q:
Selenium errors
I am trying to get the list of company names from : https://www.ces.tech/Exhibits/Exhibitor-Directory.aspx
How can I fix this error?
Thank you in advance.
I tried
SELECTOR
XPATH
and TAG_NAME('a') Print('company-name')
A:
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.... | Selenium errors | I am trying to get the list of company names from : https://www.ces.tech/Exhibits/Exhibitor-Directory.aspx
How can I fix this error?
Thank you in advance.
I tried
SELECTOR
XPATH
and TAG_NAME('a') Print('company-name')
| [
"import requests\n\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0',\n 'ctaapi-version': '1.1'\n}\n\n\ndef main(url):\n with requests.Session() as req:\n req.headers.update(headers)\n params = {\n \"alpha\": \"\",\n ... | [
0,
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"selenium",
"web_crawler"
] | stackoverflow_0074355060_beautifulsoup_python_selenium_web_crawler.txt |
Q:
Python (Bokeh) : How do i plot a line graph by using my CSV values and converting them to my outcome?
I have a CSV File with columns below:
Time Format being Month/Date/Year Hour:Minutes
Time
Event
Speed
1/30/2022 17:23
Speeding
50
1/28/2022 18:22
Speeding
20
1/27/2022 22:00
Speeding
30
1/26/2022 23:23
Speedi... | Python (Bokeh) : How do i plot a line graph by using my CSV values and converting them to my outcome? | I have a CSV File with columns below:
Time Format being Month/Date/Year Hour:Minutes
Time
Event
Speed
1/30/2022 17:23
Speeding
50
1/28/2022 18:22
Speeding
20
1/27/2022 22:00
Speeding
30
1/26/2022 23:23
Speeding
40
1/27/2022 22:00
Stopping
10
1/26/2022 23:23
Stopping
10
-With the new codes my graph... | [
"Hello and Welcome on SO @WJstudent,\nyou can convert date values to a datetime object with pandas using pd.to_datetime.\nTo group only by time and not by datetime, I dropped the date information and keept the time unsing pd.Timedstamp.dt.time.\nThis datetimes can be handled very well by bokeh. To profit from the d... | [
0
] | [] | [] | [
"bokeh",
"python"
] | stackoverflow_0074356734_bokeh_python.txt |
Q:
PyAudio Responsive Recording
I've seen the recording tutorial on the PyAudio website for recording a fixed length recording, but I was wondering how I could do the same with a non-fixed recording? Bascially, I want to create buttons to start and end the recording but I haven't found anything on the matter. Any ide... | PyAudio Responsive Recording | I've seen the recording tutorial on the PyAudio website for recording a fixed length recording, but I was wondering how I could do the same with a non-fixed recording? Bascially, I want to create buttons to start and end the recording but I haven't found anything on the matter. Any ideas, and I am not looking for an al... | [
"Best is to use the non-blocking way of recording, i.e. you provide a callback function that gets called from the moment you start the stream and keeps getting called for every block/buffer that gets processed until you stop the stream.\nIn that callback function you check for a boolean for example, and when it is ... | [
8,
0,
0
] | [] | [] | [
"asynchronous",
"nonblocking",
"pyaudio",
"python",
"user_interface"
] | stackoverflow_0028417733_asynchronous_nonblocking_pyaudio_python_user_interface.txt |
Q:
Word Tokenization When There is No Space
I am wondering for the term in Machine Learning, Deep Learning, or in Natural Language Processing that split the word in a paragraph when there is no space between them.
example:
"iwanttocook"
become:
"i want to cook"
It wouldn't be easy since you do not have the character ... | Word Tokenization When There is No Space | I am wondering for the term in Machine Learning, Deep Learning, or in Natural Language Processing that split the word in a paragraph when there is no space between them.
example:
"iwanttocook"
become:
"i want to cook"
It wouldn't be easy since you do not have the character to tokenize the word.
I appreciate any help
| [
"You could achieve this using the polyglot package. There is an option for morphological analysis.\nThis kind of analysis is based on morfessor models trained on most frequent words to encounter morphemes (\"primitive units of syntax, the smallest individually meaningful elements in the utterances of a language\").... | [
2,
0
] | [] | [] | [
"deep_learning",
"machine_learning",
"natural_language_processing",
"python"
] | stackoverflow_0054802849_deep_learning_machine_learning_natural_language_processing_python.txt |
Q:
Filter out specific errors from Flake8 results
We are writing notebooks in databricks. When we put them to git we want to run flake8 on them to check for new problems in the code.
As databricks has some predefined variables those are undefined in the code itself.
Is it possible to filter our errors like:
F821 unde... | Filter out specific errors from Flake8 results | We are writing notebooks in databricks. When we put them to git we want to run flake8 on them to check for new problems in the code.
As databricks has some predefined variables those are undefined in the code itself.
Is it possible to filter our errors like:
F821 undefined name 'dbutils'
While keeping errors like
F821... | [
"You can specify an additional list of builtins by using the builtins parameter / configuration:\n$ cat t2.py \ndb_utils.wat()\nmy_var.wat()\n\n$ flake8 t2.py \nt2.py:1:1: F821 undefined name 'db_utils'\nt2.py:2:1: F821 undefined name 'my_var'\n$ flake8 t2.py --builtins db_utils\nt2.py:2:1: F821 undefined name 'my... | [
1,
0
] | [] | [] | [
"databricks",
"flake8",
"python"
] | stackoverflow_0066781727_databricks_flake8_python.txt |
Q:
How to check from worker thread if a check box in main thread is checked?
I have designed a GUI program using pyqt5. I have a main thread and a worker thread. When the GUI starts, i get some inputs from user such as age, name,checkboxs ... and i want to process the inputs in worker. In question How to assign varia... | How to check from worker thread if a check box in main thread is checked? | I have designed a GUI program using pyqt5. I have a main thread and a worker thread. When the GUI starts, i get some inputs from user such as age, name,checkboxs ... and i want to process the inputs in worker. In question How to assign variables to worker Thread in Python PyQt5? i learned how to pass GUI input variable... | [] | [] | [
"since python doesn't have pointer, you can pointing some variables from Worker class to point the MyAPP\nclass Worker(QObject):\n finished = pyqtSignal()\n\n def __init__(self, *args, **kwargs):\n self._my_app = kwargs.pop(\"_my_app\")\n super().__init__(*args, **kwargs)\n \n def run(self... | [
-2
] | [
"pyqt5",
"python"
] | stackoverflow_0074357167_pyqt5_python.txt |
Q:
I don't understand what I'm doing wrong
My Task:
The groups_per_user function receives a dictionary, which contains group names with the list of users. Users can belong to multiple groups. Fill in the blanks to return a dictionary with the users as keys and a list of their groups as values.
My answer:
def groups_p... | I don't understand what I'm doing wrong | My Task:
The groups_per_user function receives a dictionary, which contains group names with the list of users. Users can belong to multiple groups. Fill in the blanks to return a dictionary with the users as keys and a list of their groups as values.
My answer:
def groups_per_user(group_dictionary):
user_groups = ... | [
"Line user_groups[users] = groups to user_groups[users] = [groups]\n# this line is creating issue because if users is not in dictionary then you are initialising that key with a string and if key is found then the value will be string and string will not support append operation thatswhy you are getting an error\n\... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074357411_python_python_3.x.txt |
Q:
How to change the number of arguments in a function call dynamically in Python?
I wrote the following Python code.
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s = %s" % (key, value))
# Driver code
a = input("Enter first word")
b = input("Enter second word")
c = input("Enter third wo... | How to change the number of arguments in a function call dynamically in Python? | I wrote the following Python code.
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s = %s" % (key, value))
# Driver code
a = input("Enter first word")
b = input("Enter second word")
c = input("Enter third word")
d = input("Enter fourth word")
e = input("Enter fifth word")
myFun(first=a, se... | [
"Call the function with a dictionary.\ndef myFun(**kwargs):\n for key, value in kwargs.items():\n print(\"%s = %s\" % (key, value))\n\ndef main():\n # Driver code\n a = input(\"Enter first word\")\n b = input(\"Enter second word\")\n c = input(\"Enter third word\")\n d = input(\"Enter fourt... | [
0
] | [] | [] | [
"arguments",
"function",
"keyword_argument",
"python"
] | stackoverflow_0074357339_arguments_function_keyword_argument_python.txt |
Q:
Selenium: Selecting from Multiple Drop-Downs at Once
I am building a web scraper that has to try a combination of multiple drop-down menu options and gather data from each combination.
So basically there're 5 drop-downs. I have to gather data from all of the possible combinations of the drop-down options. For each... | Selenium: Selecting from Multiple Drop-Downs at Once | I am building a web scraper that has to try a combination of multiple drop-down menu options and gather data from each combination.
So basically there're 5 drop-downs. I have to gather data from all of the possible combinations of the drop-down options. For each combination, I have to press a button to pull up the page... | [
"try this instead.\n# Drop Down Menus\n\n### THIS IS WHERE THE ERROR IS OCCURING ###\n# Choose from the drop down menus\nuf_select = Select(driver.find_element(By.XPATH, '//*[@id=\"cmbUF\"]')) \nuf_select.select_by_value('29')\n\nyear_select = Select(driver.find_element(By.XPATH, '//*[@id=\"cmbAno\"]'))\nyear_selec... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074357321_python_selenium_selenium_webdriver.txt |
Q:
Fill missing values based on the condition of other columns
I have this large dataframe, illustrated below is for simplicity purposes.
pd.DataFrame(df.groupby(['Pclass', 'Sex'])['Age'].median())
Groupby results:
And it have this data that needs to be imputed
Missing Data:
How can I impute these values based on ... | Fill missing values based on the condition of other columns | I have this large dataframe, illustrated below is for simplicity purposes.
pd.DataFrame(df.groupby(['Pclass', 'Sex'])['Age'].median())
Groupby results:
And it have this data that needs to be imputed
Missing Data:
How can I impute these values based on the median of the grouped statistic
The result that I want is:
... | [
"If all values are missing remove Age column and use DataFrame.join:\ndf = df.drop('Age', axis=1).join(multiindex_df, on=['PClass','Sex'])\nprint (df)\n PClass Sex Age\n0 1 male 34\n1 1 female 29\n2 2 male 24\n3 2 female 40\n4 3 male 18\n5 3 female ... | [
3,
0,
0
] | [] | [] | [
"dataframe",
"fillna",
"numpy",
"pandas",
"python"
] | stackoverflow_0074357327_dataframe_fillna_numpy_pandas_python.txt |
Q:
How to convert date format (dd/mm/yyyy) to days in python csv
I need a function to count the total number of days in the 'days' column between a start date of 1st Jan 1995 and an end date of 31st Dec 2019 in a dataframe taking leap years into account as well.
Example: 1st Jan 1995 - Day 1, 1st Feb 1995 - Day 32 ..... | How to convert date format (dd/mm/yyyy) to days in python csv | I need a function to count the total number of days in the 'days' column between a start date of 1st Jan 1995 and an end date of 31st Dec 2019 in a dataframe taking leap years into account as well.
Example: 1st Jan 1995 - Day 1, 1st Feb 1995 - Day 32 .......and so on all the way to 31st.
| [
"If you want to filter a pandas dataframe using a range of 2 date you can do this by:\nstart_date = '1995/01/01'\nend_date = '1995/02/01'\ndf = df[ (df['days']>=start_date) & (df['days']<=end_date) ]\n\nand with len(df) you will see the number of rows of the filter dataframe.\nInstead, if you want to calculate a ... | [
0
] | [] | [] | [
"date",
"function",
"python"
] | stackoverflow_0074353426_date_function_python.txt |
Q:
How to find the highest of 2 values in a dictionary where value is a list
emp_dict = {'Name1' : ['2','M','10',5,datetime.date(2002, 10, 10)],
'Name2' : ['3','G','5',7,datetime.date(2003, 10, 10)],
'Name3' : ['1','M','15',9,datetime.date(2004, 10, 10)],
'Name4' : ['4','G','3',3,d... | How to find the highest of 2 values in a dictionary where value is a list | emp_dict = {'Name1' : ['2','M','10',5,datetime.date(2002, 10, 10)],
'Name2' : ['3','G','5',7,datetime.date(2003, 10, 10)],
'Name3' : ['1','M','15',9,datetime.date(2004, 10, 10)],
'Name4' : ['4','G','3',3,datetime.date(2010, 10, 10)],
'Name5' : ['5','M','5',8,datetime.date... | [
"Here you go\ndef sort_rating(data, limit=2):\n rating_list = [d[3] for d in data.values()]\n keys = list(data.keys())\n\n output = {}\n\n for i, rating in enumerate(sorted(rating_list, reverse=True)):\n if i == limit:\n break\n\n index = rating_list.index(rating)\n key =... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074357452_python.txt |
Q:
Pandas group by column and add numbered rows to each group
I have the following data stored in a pandas.DataFrame object named df. The column id is a unique identifier and the remaining columns are irrelevant for the purpose of this question.
id
x1
x2
x3
0
01001
523.41
639673
1222.13
1
01002
54.832
33746
615.44... | Pandas group by column and add numbered rows to each group | I have the following data stored in a pandas.DataFrame object named df. The column id is a unique identifier and the remaining columns are irrelevant for the purpose of this question.
id
x1
x2
x3
0
01001
523.41
639673
1222.13
1
01002
54.832
33746
615.443
2
01003
48.3824
45196
934.142
I want to know if ... | [
"You can repeat the index and use numpy.tile to tile the new data:\nimport numpy as np\n\nnew = ['2020', '2021']\n\ndf2 = df.loc[df.index.repeat(len(new))]\ndf2['new_col'] = np.tile(new, len(df))\n\nOutput:\n id x1 x2 x3 new_col\n0 1001 523.4100 639673 1222.130 2020\n0 1001 523.4100 ... | [
4,
2,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0069353594_pandas_python.txt |
Q:
Select related field before the field itself - Odoo 8
I'm working on Odoo 8 and i have 3 tables : bloc, floor and room
with floor having a many2one relation with bloc, and room having a many2one relation with floor
when creating a room record, i want to select the bloc first so i can load floors in that bloc only,... | Select related field before the field itself - Odoo 8 | I'm working on Odoo 8 and i have 3 tables : bloc, floor and room
with floor having a many2one relation with bloc, and room having a many2one relation with floor
when creating a room record, i want to select the bloc first so i can load floors in that bloc only, but without having a many2one relation between room and bl... | [
"You can use a related field and use it in the floor field domain to filter out blocs.\nRelated fields are not stored by default, they are computed and returned when requested (Odoo will not create a database column in the room table)\nExample:\n\nRoom model\nclass Room(models.Model):\n _name = 'room.room'\n\n ... | [
1
] | [] | [] | [
"many2one",
"odoo",
"odoo_8",
"python"
] | stackoverflow_0074326864_many2one_odoo_odoo_8_python.txt |
Q:
Fetch only True values of particular keys from table using python without pandas?
I am trying to take values from a DB table where It has keys as enabled and values as true, false and empty, I want to take only True values from enabled keys and other keys and rows related to it.
Table
id name enabled dep... | Fetch only True values of particular keys from table using python without pandas? | I am trying to take values from a DB table where It has keys as enabled and values as true, false and empty, I want to take only True values from enabled keys and other keys and rows related to it.
Table
id name enabled dept
1 abd TRUE cs
2 cdew FALSE ds
3 sda s... | [
"Best thing to do is create a Sparse Index which only had the True values.\nTo do this, only set enabled for True values and if False just omit it as DynamoDB is schemaless.\nNow create a GSI with the partition or sort key as enabled, now the GSI will only contain the items you want. To fetch them simply Scan the G... | [
1,
0
] | [] | [] | [
"amazon_dynamodb",
"amazon_web_services",
"python"
] | stackoverflow_0074345770_amazon_dynamodb_amazon_web_services_python.txt |
Q:
Python: how to converet list of list into a dictionary
I am trying to converet the list of list into a dictionary using defaultdict method.
I have a list of list:
a= [[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]
I want the output in this format:
{1: [0], 2: [0], 2: [1], 3: [1], 4: [1], 4: [2], 5: [2], 6: [2], 3: [3], 7... | Python: how to converet list of list into a dictionary | I am trying to converet the list of list into a dictionary using defaultdict method.
I have a list of list:
a= [[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]
I want the output in this format:
{1: [0], 2: [0], 2: [1], 3: [1], 4: [1], 4: [2], 5: [2], 6: [2], 3: [3], 7: [3], 6: [4], 10: [4]})
Here is my code:
a =[[1,2],[2,3,4]... | [
"You can try with this approach\nSo instead of dictionary with overlapping keys, you can create list of dictionaries.\na= [[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]\nb = [{r:i} for i,k in enumerate(a) for r in k ]\n\n[{1: 0}, {2: 0}, {2: 1}, {3: 1}, {4: 1}, {4: 2}, {5: 2}, {6: 2}, {3: 3}, {7: 3}, {6: 4}, {10: 4}]\n\n"... | [
1,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074357586_dictionary_list_python.txt |
Q:
My code throws an IndexError: list index out of range
The following code is throwing indexError list index out of range
I tried googling it and everybody is talking about range() errors and calling an index that does not exist. I followed the following tutorial https://www.youtube.com/watch?v=sz25xxF_AVE&ab_channe... | My code throws an IndexError: list index out of range | The following code is throwing indexError list index out of range
I tried googling it and everybody is talking about range() errors and calling an index that does not exist. I followed the following tutorial https://www.youtube.com/watch?v=sz25xxF_AVE&ab_channel=Murtaza%27sWorkshop-RoboticsandAI letter for letter and s... | [
"this error said that -> in a loop -> you try to access an item, which does not exist - cause it's out of range.\nif matches[matchIndex]:\n\nor\nname = classNames[matchIndex].upper()\n\nin this case, match is a list, and the index is the position of an element in the list.\n\nif 1 case is wrong then:\nmatches = fac... | [
1
] | [] | [] | [
"face_detection",
"face_recognition",
"python",
"python_3.x"
] | stackoverflow_0074357787_face_detection_face_recognition_python_python_3.x.txt |
Q:
Insert values from a column in a DataFrame to another based on column values
I am wondering how I can add one column from a dataframe, to another based on the dates in both columns. I tried to simplify this as much as I can.
I have two dataframes one is filled with event types and the cost done for the event, the ... | Insert values from a column in a DataFrame to another based on column values | I am wondering how I can add one column from a dataframe, to another based on the dates in both columns. I tried to simplify this as much as I can.
I have two dataframes one is filled with event types and the cost done for the event, the other being the observation from a nearby station giving how much rainfall occurre... | [
"Following Clegane's proposal, using merge() in this case would require you to previously modify slightly the events df:\noutput = observation.merge(events[['ObservationDate','EventType']],how='left',on='ObservationDate').dropna()\n\nReturning:\n ObservationDate Rainfall EventType\n0 2021-09-11 45 ... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074357741_dataframe_pandas_python.txt |
Q:
First line a of a file not printing in a function
I was looking around but I couldn't find a question similar that also includes functions.
My PYTHON code is supposed to output every line in a text file, but in uppercase. I understand how you'd do this without functions, but I have to use a function.
It prints out... | First line a of a file not printing in a function | I was looking around but I couldn't find a question similar that also includes functions.
My PYTHON code is supposed to output every line in a text file, but in uppercase. I understand how you'd do this without functions, but I have to use a function.
It prints out everything in uppercase, but the first line, I think i... | [
"You don't need to do line = f.read() since you're already getting the line with your loop variable. This is why your program doesn't output the first line.\nMoreover, the return is outside the loop so that means you will only return the last value of line. My guess is that your function should directly print all t... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074357616_python.txt |
Q:
Nested loop provides unwanted action
I am trying make a nested loop so a while loop gets repeated n times. An object is supposed to drive a distance in i steps for n repetitions. Axis and speed are irrelevant for the loop.
What I don't understand is why the first i in i = i + 1 is not used, since just i + 1 doesn'... | Nested loop provides unwanted action | I am trying make a nested loop so a while loop gets repeated n times. An object is supposed to drive a distance in i steps for n repetitions. Axis and speed are irrelevant for the loop.
What I don't understand is why the first i in i = i + 1 is not used, since just i + 1 doesn't seem to do the job either.
def steptoful... | [
"Your i = i + 1 needs to be indented to run within the while loop. That way, i will increase until it exceeds reps and your outer while loop will stop.\n"
] | [
0
] | [] | [] | [
"loops",
"nested_loops",
"python",
"while_loop"
] | stackoverflow_0074357695_loops_nested_loops_python_while_loop.txt |
Q:
Web Scraping article and image links using python
i am trying to web scrape all the links for images, articles from 'https://www.telegraphindia.com/search?keyword=obama&page=2' and save them in an excel file.
i have tried the following code:
url = 'https://www.telegraphindia.com/search?keyword=obama&page=2';
page ... | Web Scraping article and image links using python | i am trying to web scrape all the links for images, articles from 'https://www.telegraphindia.com/search?keyword=obama&page=2' and save them in an excel file.
i have tried the following code:
url = 'https://www.telegraphindia.com/search?keyword=obama&page=2';
page = requests.get(url);
bsoup = BeautifulSoup(page.content... | [
"Try this:\nimport requests\nfrom bs4 import BeautifulSoup\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36\"\n}\n\n\ndef get_image_source(div) -> str:\n if div.select_one(\"a > img\").get(\"data-src\")... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074357691_beautifulsoup_python_web_scraping.txt |
Q:
Python OS module os.remove called is not working
I am trying to mock Python OS module mocking and it is not working
My code os_mock.py:
import os
class MyTestMock:
def rm(self):
# some reason file is always hardcoded
file_path = "/tmp/file1"
if os.path.exists(file_path):
... | Python OS module os.remove called is not working | I am trying to mock Python OS module mocking and it is not working
My code os_mock.py:
import os
class MyTestMock:
def rm(self):
# some reason file is always hardcoded
file_path = "/tmp/file1"
if os.path.exists(file_path):
os.remove(file_path)
print(file_path, 'rem... | [
"I have made some change only to your test file, while the file os_mock.py remains unchanged.\nChange return_vallue to return_value is enough\nIf you change return_vallue to return_value your test passes successfully so these changes (in the 2 points where the errors are present) are sufficient.\nIn particular the ... | [
2
] | [] | [] | [
"pytest",
"python",
"python_3.x",
"unit_testing"
] | stackoverflow_0074355632_pytest_python_python_3.x_unit_testing.txt |
Q:
How to convert keras(h5) file to a tflite file?
I got an keras(h5) file. I need to convert it to tflite??
I researched, First i need to go via h5 -> pb -> tflite
(because h5 - tflite sometimes results in some issue)
A:
from tensorflow.contrib import lite
converter = lite.TFLiteConverter.from_keras_model_file( 'm... | How to convert keras(h5) file to a tflite file? | I got an keras(h5) file. I need to convert it to tflite??
I researched, First i need to go via h5 -> pb -> tflite
(because h5 - tflite sometimes results in some issue)
| [
"from tensorflow.contrib import lite\nconverter = lite.TFLiteConverter.from_keras_model_file( 'model.h5')\ntfmodel = converter.convert()\nopen (\"model.tflite\" , \"wb\") .write(tfmodel)\n\nYou can use the TFLiteConverter to directly convert .h5 files to .tflite file.\nThis does not work on Windows.\nFor Windows, u... | [
33,
32,
4,
1,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"keras",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0053256877_keras_machine_learning_python_tensorflow.txt |
Q:
SqlAlchemy Time/Date issue with data stored as UTC in Postgresql DB
I know there are quite a few questions about Date/Time with Flask/SQLAlchemy and Postgres, but I have a problem that I just can't quite figure out. So, with my project I am downloading statistics from ESPN. All their game times, rightly so, are ... | SqlAlchemy Time/Date issue with data stored as UTC in Postgresql DB | I know there are quite a few questions about Date/Time with Flask/SQLAlchemy and Postgres, but I have a problem that I just can't quite figure out. So, with my project I am downloading statistics from ESPN. All their game times, rightly so, are in UTC format. Example: 2020-11-26T02:56Z
So, I add this to me DB in a fi... | [
"When you load an UTC timestamp into timestamp with time zone, you have to set the timezone parameter correctly in that session:\nSET timezone = 'UTC';\n\n"
] | [
0
] | [] | [] | [
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0074357294_postgresql_python_sqlalchemy.txt |
Q:
Python Panda drop() function not working after dictionary conversion; using Yfinance API
Using the yfinance API I pulled data from there option chain object and converted it to a dictionary. I tried to delete all rows that contained "True" in the column labeled "inTheMoney" however when I run the program it does n... | Python Panda drop() function not working after dictionary conversion; using Yfinance API | Using the yfinance API I pulled data from there option chain object and converted it to a dictionary. I tried to delete all rows that contained "True" in the column labeled "inTheMoney" however when I run the program it does not do so.
import yfinance as yf
import pandas as pd
price = 100
ticker = yf.Ticker("SPY")
op... | [
"just:\ndf = df.drop(df[(df['inTheMoney'] != True)].index) #do not use quotes\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python",
"yfinance"
] | stackoverflow_0074354679_pandas_python_yfinance.txt |
Q:
PyCharm + Qt Designer: window closes instantly
The first day I try to deal with the GUI. The problem is that the window instantly closes (or does not open at all) when launched in the Python interpreter from under Windows OS when you double-click on the program file. The .py file association with the Python interp... | PyCharm + Qt Designer: window closes instantly | The first day I try to deal with the GUI. The problem is that the window instantly closes (or does not open at all) when launched in the Python interpreter from under Windows OS when you double-click on the program file. The .py file association with the Python interpreter is set correctly. Saving as .pyw does not chan... | [
"if you read the error message it clearly states:\nWarning: This Python interpreter is in a conda environment, but the environment has not been activated. Libraries may fail to load. To activate this environment please see https://conda.io/activation\n\nyou cannot use conda environments as \"double click\" target... | [
2
] | [] | [] | [
"designer",
"pycharm",
"python",
"qt",
"user_interface"
] | stackoverflow_0074357487_designer_pycharm_python_qt_user_interface.txt |
Q:
How to convert a decimal number into a binary list with fixed number of bits in Python 3.8?
Suppose I have the decimal number 8, and I want to conver it into a binary list of length 8.
It means if I give input as 8, I should get output as [0,0,0,0,1,0,0,0]. I am looking for an inbuilt command in python that can do... | How to convert a decimal number into a binary list with fixed number of bits in Python 3.8? | Suppose I have the decimal number 8, and I want to conver it into a binary list of length 8.
It means if I give input as 8, I should get output as [0,0,0,0,1,0,0,0]. I am looking for an inbuilt command in python that can do that in a very short time (in nano-seconds).
I have tried the foolowing comman which is giving m... | [
"You can do with list comprehension.\n>>> [int(i) for i in bin(8)[2:].zfill(8)]\n[0, 0, 0, 0, 1, 0, 0, 0]\n\nbin(8) return the binary representation of an integer 8 and it's always prefixed with 0b. So bin(8)[2:] is to remove these first two characters(ie, 0b). And then you can use .zfill(8) to pad a numeric string... | [
2,
0,
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074357631_list_python_python_3.x.txt |
Q:
Caesar cipher looping
I have some code which has other problems as well at the moment but I'm really struggling with the looping part (going from z back to a).
I've looked at a buch of other answers but found none that actually helped in my situation.
import string
upper = string.ascii_uppercase
lower = string.asc... | Caesar cipher looping | I have some code which has other problems as well at the moment but I'm really struggling with the looping part (going from z back to a).
I've looked at a buch of other answers but found none that actually helped in my situation.
import string
upper = string.ascii_uppercase
lower = string.ascii_lowercase
digit = string... | [
"There are a couple of ways you could do this.\nThe most basic would be to just subtract 26 anytime you go past the range you are trying to stay within. Or in the case of shifting the other direction and ending up somewhere before a/A, you could add 26 instead.\nAnother option would be to use the mod operator to s... | [
1
] | [] | [] | [
"caesar_cipher",
"cryptography",
"python",
"python_3.10",
"python_3.x"
] | stackoverflow_0074357879_caesar_cipher_cryptography_python_python_3.10_python_3.x.txt |
Q:
Trying to place postgresql database information inside a dotenv file to hide important info, like passwords etc
I'm using the django rest framework and trying to connect a postgresql database. If I have the connection to the database written explicitly in the settings.py file, running python manage.py runserver wo... | Trying to place postgresql database information inside a dotenv file to hide important info, like passwords etc | I'm using the django rest framework and trying to connect a postgresql database. If I have the connection to the database written explicitly in the settings.py file, running python manage.py runserver works fine, but as soon as I replace the database connection with the dotenv values, the connection breaks. How do I fi... | [
"\nOption 1: python-decouple package\n\npip install python-decouple\nIn your settings.py file:\nfrom decouple import config\nAccess your environment variables as:\nNAME = config(\"DB_NAME\")\nOfficial docs: https://github.com/henriquebastos/python-decouple/\n\nOption 2: python-dotenv package\n\npip install python-d... | [
0
] | [] | [] | [
"django",
"dotenv",
"python",
"python_dotenv"
] | stackoverflow_0074356276_django_dotenv_python_python_dotenv.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.