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:
web scraping using pandas
I want to scrape multiple pages of website using Python, but I'm getting Remote Connection closed error.
Here is my code
import pandas as pd
url_link = 'https://www.taneps.go.tz/epps/viewAllAwardedContracts.do?d-3998960-p={}&selectedItem=viewAllAwardedContracts.do'
LIST = []
for number i... | web scraping using pandas | I want to scrape multiple pages of website using Python, but I'm getting Remote Connection closed error.
Here is my code
import pandas as pd
url_link = 'https://www.taneps.go.tz/epps/viewAllAwardedContracts.do?d-3998960-p={}&selectedItem=viewAllAwardedContracts.do'
LIST = []
for number in range(1,5379):
url = url_li... | [
"For me, just using requests to fetch the html before passing to read_html is getting the data. I just edited your code to\nimport pandas as pd\nimport re\nurl_link = 'https://www.taneps.go.tz/epps/viewAllAwardedContracts.do?d-3998960-p={}&selectedItem=viewAllAwardedContracts.do'\nLIST = []\nfor number in range(1,5... | [
0
] | [] | [] | [
"beautifulsoup",
"pandas",
"python",
"web_scraping"
] | stackoverflow_0074305179_beautifulsoup_pandas_python_web_scraping.txt |
Q:
Unclear figure plotting error in matplotlib 3D
I'm trying to better understand 3D plotting using various tutorials online. I tried to recreate one of these online tutorials, this one in particular by running some of the code in my own Jupyter Notebook, however, when I try this I get a suspicious error.
I am runnin... | Unclear figure plotting error in matplotlib 3D | I'm trying to better understand 3D plotting using various tutorials online. I tried to recreate one of these online tutorials, this one in particular by running some of the code in my own Jupyter Notebook, however, when I try this I get a suspicious error.
I am running the first code block from the website (attached be... | [
"Use the magic functions\n%matplotlib inline\n"
] | [
0
] | [] | [] | [
"error_handling",
"matplotlib",
"matplotlib_widget",
"python",
"python_3.x"
] | stackoverflow_0074332847_error_handling_matplotlib_matplotlib_widget_python_python_3.x.txt |
Q:
Label encode subgroups after groupby
I want to label encode subgroups in a pandas dataframe. Something like this:
| Category | | Name |
| ---------- | | --------- |
| FRUITS | | Apple |
| FRUITS | | Orange |
| FRUITS | | Apple |
| Vegetables | | Onion |
| Vegetables | | Garlic ... | Label encode subgroups after groupby | I want to label encode subgroups in a pandas dataframe. Something like this:
| Category | | Name |
| ---------- | | --------- |
| FRUITS | | Apple |
| FRUITS | | Orange |
| FRUITS | | Apple |
| Vegetables | | Onion |
| Vegetables | | Garlic |
| Vegetables | | Garlic |
to
| Ca... | [
"Try to group-by \"Category\" and then group-by \"Name\" and use .ngroup():\ndf[\"Label\"] = (\n df.groupby(\"Category\")\n .apply(lambda x: x.groupby(\"Name\", sort=False).ngroup() + 1)\n .values\n)\nprint(df)\n\nPrints:\n Category Name Label\n0 FRUITS Apple 1\n1 FRUITS Orange ... | [
1,
0
] | [] | [] | [
"dataframe",
"group_by",
"label_encoding",
"pandas",
"python"
] | stackoverflow_0074331409_dataframe_group_by_label_encoding_pandas_python.txt |
Q:
How can I make a process started with subprocess.Popen to be able to use the packages installed?
I am using subprocess.Popen('python txtfile') to run a txt file in python. It works perfectly fine when I use it with built-in modules such as tkinter or random but when I try to use external packages (that I have prev... | How can I make a process started with subprocess.Popen to be able to use the packages installed? | I am using subprocess.Popen('python txtfile') to run a txt file in python. It works perfectly fine when I use it with built-in modules such as tkinter or random but when I try to use external packages (that I have previously installed. The code works in a .py file but not when I run the txt file with subprocess.Popen()... | [
"You most likely have multiple python versions on your system, uninstall them all including ones from Microsoft store and setup one from python.org and tick the box to \"Add python to PATH\" at the end of installation.\nAnother way is to call your interpreter from sys.executable\nsubprocess.Popen([sys.executable,'t... | [
1
] | [] | [] | [
"package",
"popen",
"python",
"subprocess",
"text"
] | stackoverflow_0074333623_package_popen_python_subprocess_text.txt |
Q:
DRF - Testing, error while hitting sinlgle data from id
Urls.py
router = routers.DefaultRouter()
router.register('zone', views.ZoneViewSet, basename='zone')
app_name = 'address'
API.
urlpatterns = [
path('', include(router.urls)),
]
Test.py
RECIPES_URL = reverse('address:zone-list')
def details_url(id):
... | DRF - Testing, error while hitting sinlgle data from id | Urls.py
router = routers.DefaultRouter()
router.register('zone', views.ZoneViewSet, basename='zone')
app_name = 'address'
API.
urlpatterns = [
path('', include(router.urls)),
]
Test.py
RECIPES_URL = reverse('address:zone-list')
def details_url(id):
print(RECIPES_URL,id)
return reverse(RECIPES_URL.strip(... | [
"Detail url is simply reverse(\"zone-detail\", kwargs={\"pk\": task.id}), with \"zone\" your basename and \"pk\" your url param name.\nThe -detail is documentated here:\nhttps://www.django-rest-framework.org/api-guide/routers/.\nI admit it is not always easy to find what you're looking for in DRF doc.\n"
] | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"testcase",
"testing"
] | stackoverflow_0074333511_django_django_rest_framework_python_testcase_testing.txt |
Q:
How to return Pydantic model using Field aliases instead of names in FastAPI response?
My FastAPI call is not returning the data in correct Response model format. It is returning data in database model format.
My database model:
class cat(DBConnect.Base):
__tablename__ = 'category'
__table_args__ = {"sch... | How to return Pydantic model using Field aliases instead of names in FastAPI response? | My FastAPI call is not returning the data in correct Response model format. It is returning data in database model format.
My database model:
class cat(DBConnect.Base):
__tablename__ = 'category'
__table_args__ = {"schema": SCHEMA}
cat_id = Column('cat_id',UUID(as_uuid=True), primary_key=True, default=uu... | [
"You can add response_model_by_alias=True to the endpoint. This is mentioned here in the documentation.\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\ndef to_camel(string: str) -> str:\n return ''.join(word.capitalize() for word in string.split('_'))\n\nclass Item(BaseModel)... | [
1
] | [] | [] | [
"fastapi",
"pydantic",
"python"
] | stackoverflow_0074332593_fastapi_pydantic_python.txt |
Q:
How to change timestamp from yyyy-dd-mm to yyyy-mm-dd in pandas
data['Customer_month'] = data['Timestamp'].dt.strftime('%Y-%m-01')
data.tail(2)
Timestamp Name Customer_month
2022-05-11 21:31:16 Deepak Kumar 2022-05-01
2022-05-11 21:44:55 Subhash chandra 2022-05-01
Customer month column s... | How to change timestamp from yyyy-dd-mm to yyyy-mm-dd in pandas |
data['Customer_month'] = data['Timestamp'].dt.strftime('%Y-%m-01')
data.tail(2)
Timestamp Name Customer_month
2022-05-11 21:31:16 Deepak Kumar 2022-05-01
2022-05-11 21:44:55 Subhash chandra 2022-05-01
Customer month column should be 2022-11-01 not as 2022-05-1
my expected dataframe is:
Times... | [
"data = pd.DataFrame(\n {'Timestamp': ['2022-05-11 21:31:16', '2022-05-11 21:44:55'], 'Name': ['Deepak Kumar', 'Subhash chandra']})\ndata.Timestamp = data.Timestamp.astype('datetime64')\n\ndata['Customer_month'] = data['Timestamp'].dt.strftime('%Y-%d-01')\nprint(data)\n\n Timestamp Name Cu... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074333654_dataframe_pandas_python.txt |
Q:
Errno 2 No such file or directory: 'utils\\expiry_list.csv'
Error while runnind boot3 and then getting data.
expiries = get_data('options', 'BANKNIFTY', custom="select DISTINCT(expiry) from "spot_backtesting_data";")
expiries.to_csv('utils\expiry_list.csv', index=False)
to save files in my local in csv datewise
A... | Errno 2 No such file or directory: 'utils\\expiry_list.csv' | Error while runnind boot3 and then getting data.
expiries = get_data('options', 'BANKNIFTY', custom="select DISTINCT(expiry) from "spot_backtesting_data";")
expiries.to_csv('utils\expiry_list.csv', index=False)
to save files in my local in csv datewise
| [
"If you not sure why path is not detectable you can create a dummy own directory and save the output later you can search with folder name.\n\nNote: format your code...I can't understand anything...So i'm just\nleft that portion as #your code\n\nfrom pathlib import Path\n\noutput_file = 'expiry_list.csv'\noutput_di... | [
0
] | [] | [] | [
"amazon_web_services",
"python"
] | stackoverflow_0074333600_amazon_web_services_python.txt |
Q:
Python requests.get TikTok returns b''
I'm trying to get the html of a TikTok video page and requests is returning b'' instead of the pages entire HTML. This works on other sites and even the tiktok home page (https://www.tiktok.com/) but not on video pages. Can someone try out my code and let me know what is goin... | Python requests.get TikTok returns b'' | I'm trying to get the html of a TikTok video page and requests is returning b'' instead of the pages entire HTML. This works on other sites and even the tiktok home page (https://www.tiktok.com/) but not on video pages. Can someone try out my code and let me know what is going on? Also, I got the return code and it was... | [
"If you fail to create convincing headers, consider using something like ScrapingAnt\napi_url = \"https://api.scrapingant.com/v2/general\"\npage_url = \"https://www.tiktok.com/@thatlittlepuff/video/7160116843611475246\"\nmyKey_sa = YOUR_API_TOKEN # register on https://scrapingant.com/ and paste here\n\npage = reque... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"python_requests"
] | stackoverflow_0074310329_beautifulsoup_python_python_requests.txt |
Q:
Deleting duplicates based on condition
Here's my code:
import pathlib
from pathlib import Path
import os
import pandas as pd
df=pd.DataFrame(
{
'col1': ['red','blue','red','red','green','red','yellow', 'red', 'cyan', 'purple', 'pink', 'black', 'orange'],
'col2': ['red', 'green','orange'],
... | Deleting duplicates based on condition | Here's my code:
import pathlib
from pathlib import Path
import os
import pandas as pd
df=pd.DataFrame(
{
'col1': ['red','blue','red','red','green','red','yellow', 'red', 'cyan', 'purple', 'pink', 'black', 'orange'],
'col2': ['red', 'green','orange'],
}
)
The desired output would be to elimin... | [
"You need to use isin and boolean indexing:\n(df.loc[~df['col1'].isin(df['col2']), ['col1']]\n .to_excel('filename.xlsx', index=False)\n)\n\nOutput:\n col1\n1 blue\n6 yellow\n8 cyan\n9 purple\n10 pink\n11 black\n\nUsed input:\n col1 col2\n0 red red\n1 blue green\n2 ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074333438_dataframe_pandas_python.txt |
Q:
Converting negative values in dataframe to NaN
I have a dataframe that has negative values. I would like to replace the negative values to NaN.
The dataframe contains different column types (Object, float, int..) and has over 15 numeric columns so I am looking for a solution that would identify the numeric columns... | Converting negative values in dataframe to NaN | I have a dataframe that has negative values. I would like to replace the negative values to NaN.
The dataframe contains different column types (Object, float, int..) and has over 15 numeric columns so I am looking for a solution that would identify the numeric columns then change the negative values to NaN.
name ... | [
"Using pandas.mask could solve your problem.\ndf = df.mask(df < 0) # default replaced value is nan when the condition is fulfilled.\n\nTo only apply it on numeric columns, we can select those columns by checking their dtypes.\ndf.select_dtypes(include=np.number)\nnp.issubdtype(x.dtype, np.number)\n\nSo the final so... | [
2,
1
] | [] | [] | [
"dataframe",
"nan",
"python",
"replace"
] | stackoverflow_0074333626_dataframe_nan_python_replace.txt |
Q:
BadRequestError(400, 'x_content_parse_exception', '[1:263] [bool] failed to parse field [filter]')
I have this query ,
search = {
"query": {
"bool": {
"filter": [
{
"range": {
"created_at": {
"gte":"2013-12-31T07:14:22+00:00",
"lt":"2015-12-31T0... | BadRequestError(400, 'x_content_parse_exception', '[1:263] [bool] failed to parse field [filter]') | I have this query ,
search = {
"query": {
"bool": {
"filter": [
{
"range": {
"created_at": {
"gte":"2013-12-31T07:14:22+00:00",
"lt":"2015-12-31T07:14:22+00:00"
}
}
},
{
"geo_bounding_box": {
... | [
"The \"geo_shape\" fields are matched using the geo-bounding box query in a way that intersects a bounding box.\nThe coordinates for the top left and bottom right are included in the latitude and longitude values that are provided. Refer to the official elasticsearch documentation for further information documentat... | [
0
] | [] | [] | [
"elasticsearch",
"elasticsearch_5",
"python",
"python_3.x"
] | stackoverflow_0074331535_elasticsearch_elasticsearch_5_python_python_3.x.txt |
Q:
How to make a collision system in pygame?
How can i make a collision system in the simplest way in pygame, without using classes.
I've been trying for a long time and none of the ways works, in my last attempt the code was like this: (Sorry if it's wrongly written, I'm a beginner in all this)
import pygame
from py... | How to make a collision system in pygame? | How can i make a collision system in the simplest way in pygame, without using classes.
I've been trying for a long time and none of the ways works, in my last attempt the code was like this: (Sorry if it's wrongly written, I'm a beginner in all this)
import pygame
from pygame.locals import *
from sys import exit
pyga... | [
"You must create a pygame.Rect object with the current position of the player before the collision test. If the player hits the block from the left, the player`s right must be set by the left of the block. If the player hits the block from the right, the player's right must be set by the left of the block:\ndef mov... | [
0
] | [] | [] | [
"collision_detection",
"pygame",
"pygame_surface",
"python"
] | stackoverflow_0074332401_collision_detection_pygame_pygame_surface_python.txt |
Q:
why alpha = 2/(span + 1) in pandas.DataFrame.ewm
In the document of pandas.DataFrame.ewm, it says alpha = 2/(span + 1). Don't understand why such formula exists between alpha and span.
Is it a convention or any sources to explain the formula?
Is it only an assumption/setting in pandas? actually it can be other fo... | why alpha = 2/(span + 1) in pandas.DataFrame.ewm | In the document of pandas.DataFrame.ewm, it says alpha = 2/(span + 1). Don't understand why such formula exists between alpha and span.
Is it a convention or any sources to explain the formula?
Is it only an assumption/setting in pandas? actually it can be other formats, e.g. alpha = 4/(span + 3)?
Googled but there i... | [
"\nIs it a convention or any sources to explain the formula?\n\nThe span parameter is intended to roughly correspond to an N-period rolling average. Here's what Wikipedia says about this:\n\nNote that there is no \"accepted\" value that should be chosen for alpha, although there are some recommended values based on... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0073797820_pandas_python.txt |
Q:
Django - POST get options from select
I have a html form that looks like this.
{% url 'myapp:myapp_submit' as submit %}
<form name='main' method="POST" action={{submit}}>
{% csrf_token %}
<select class='form-control' size=10 id="test" name='test' multiple>
<option>Test</option>
</select>
<input type="submit"/>
<... | Django - POST get options from select | I have a html form that looks like this.
{% url 'myapp:myapp_submit' as submit %}
<form name='main' method="POST" action={{submit}}>
{% csrf_token %}
<select class='form-control' size=10 id="test" name='test' multiple>
<option>Test</option>
</select>
<input type="submit"/>
</form>
and url.py
from . import views
... | [
"Try to change your views.py:\ndef myapp_submit(request):\n request.POST.getlist('test[]')\n\n",
"Because you say you're doing weird things with Js, you can first check the POST request from your browser and what parameters you send with it. \n",
"A month ago I solved this problem, you need to use name in yo... | [
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0039200802_django_python.txt |
Q:
Django - annotate the most frequent field taken from another model linked with foreignKey
I have a model of users and a model with a survey in which users express their opinion with a vote with an integer number that identified a particular color of eyes. A srcID user describes the color of the eyes of a dstID use... | Django - annotate the most frequent field taken from another model linked with foreignKey | I have a model of users and a model with a survey in which users express their opinion with a vote with an integer number that identified a particular color of eyes. A srcID user describes the color of the eyes of a dstID user according to his opinion. A user can votes himself. It's possible that a user doesn't receive... | [
"This should yield the most frequent eyes color for each user.\nsubquery = Subquery(survey.objects.filter(srcID=OuterRef('pk')).values('eyesColor').alias(votes=Count('eyesColor')).order_by('-votes')[1:])\nuser.objects.alias(eyesColorMostVoted=subquery).annotate(eyesColorMostFreq=Case(When(eyesColorMostVoted__isnull... | [
0
] | [] | [] | [
"django",
"django_annotate",
"django_models",
"django_queryset",
"python"
] | stackoverflow_0074331873_django_django_annotate_django_models_django_queryset_python.txt |
Q:
Convert pandas.Series from dtype object to float, and errors to nans
Consider the following situation:
In [2]: a = pd.Series([1,2,3,4,'.'])
In [3]: a
Out[3]:
0 1
1 2
2 3
3 4
4 .
dtype: object
In [8]: a.astype('float64', raise_on_error = False)
Out[8]:
0 1
1 2
2 3
3 4
4 .
dtype: ob... | Convert pandas.Series from dtype object to float, and errors to nans | Consider the following situation:
In [2]: a = pd.Series([1,2,3,4,'.'])
In [3]: a
Out[3]:
0 1
1 2
2 3
3 4
4 .
dtype: object
In [8]: a.astype('float64', raise_on_error = False)
Out[8]:
0 1
1 2
2 3
3 4
4 .
dtype: object
I would have expected an option that allows conversion while turning... | [
"Use pd.to_numeric with errors='coerce'\n# Setup\ns = pd.Series(['1', '2', '3', '4', '.'])\ns\n\n0 1\n1 2\n2 3\n3 4\n4 .\ndtype: object\n\n\npd.to_numeric(s, errors='coerce')\n\n0 1.0\n1 2.0\n2 3.0\n3 4.0\n4 NaN\ndtype: float64\n\nIf you need the NaNs filled in, use Series.fillna.\npd.... | [
81,
20
] | [
"Do this:\npd.to_numeric(s, errors='coerce')\n"
] | [
-1
] | [
"nan",
"pandas",
"python"
] | stackoverflow_0025952790_nan_pandas_python.txt |
Q:
I am trying to filter some url from my fetch list by using for loop and if condition in python
I am trying to filter some url from my fetch list but its not applying the filter it is giving me the same output from fetchurl in weblinks
Here is my code
weblinks =[]
fetchurl = ['https://www.youtube.com/watch?v=___nkv... | I am trying to filter some url from my fetch list by using for loop and if condition in python | I am trying to filter some url from my fetch list but its not applying the filter it is giving me the same output from fetchurl in weblinks
Here is my code
weblinks =[]
fetchurl = ['https://www.youtube.com/watch?v=___nkvwpnAg&t=1218', 'https://www.farandwide.com/s/fascinating-facts-every-country-7c1f1a0efdf64979', 'htt... | [
"The error was that you were adding an element if any of the values from the filterlist did not match, but you should if all the values did not match. If at least one match is found, then the inner loop will exit early and the element will not be included in the resulting list. If there is no match, the loop will r... | [
1
] | [] | [] | [
"for_loop",
"if_statement",
"python"
] | stackoverflow_0074333861_for_loop_if_statement_python.txt |
Q:
Making a Calculator More Efficient
So I'm very new to Python and have done very little coding since ActionScript 3, but I'd like to start learning Python as it seems way more functional than anything I've used in the past.
The best way to do that for me is to make something, and then have someone (like you fine fo... | Making a Calculator More Efficient | So I'm very new to Python and have done very little coding since ActionScript 3, but I'd like to start learning Python as it seems way more functional than anything I've used in the past.
The best way to do that for me is to make something, and then have someone (like you fine folks) to look at it and make the code mor... | [
"In order to make a calculator as efficient as possible, converting my code to the following is likely the best solution within Python. It has a built in 'math' function called 'eval()'\nwhile True:\n\ncalc = input(\"What is your math problem?:\\n\")\n\nprint(str(eval(calc)))\n\nWhile my logic is mostly correct, th... | [
0
] | [] | [] | [
"calculator",
"python",
"python_3.x"
] | stackoverflow_0074333843_calculator_python_python_3.x.txt |
Q:
How to click a button of tag type in selenium | Python
I am trying to submit a form. The problem is when trying to click the submit button, nothing happens. I think the problem is that this button has a tag of <input>:
<input type="submit" name="submit" class="btn btn-info" value="Submit">
I think it is clicking... | How to click a button of tag type in selenium | Python | I am trying to submit a form. The problem is when trying to click the submit button, nothing happens. I think the problem is that this button has a tag of <input>:
<input type="submit" name="submit" class="btn btn-info" value="Submit">
I think it is clicking on an input that won't trigger the function, so is there a w... | [
"Try this:\ndocument.querySelector('input[type=\"submit\"]').click()\n\nmake sure input[type='submit'] is unique locator for that element on the page\n"
] | [
0
] | [] | [] | [
"javascript",
"python",
"selenium"
] | stackoverflow_0074333638_javascript_python_selenium.txt |
Q:
how to replace in pandas int values with a "," for thousands with an int without ','?
I have a df thats big, and has int's and float's inside, some have bigger values over 1 thousand, and that gives error when using them as int
ex:
A B C
0 1,598 65.79 79
1 -300 46.90 ... | how to replace in pandas int values with a "," for thousands with an int without ','? | I have a df thats big, and has int's and float's inside, some have bigger values over 1 thousand, and that gives error when using them as int
ex:
A B C
0 1,598 65.79 79
1 -300 46.90 90
the format doesnt let me write the df
How can I replace the "," for this: ""?
| [
"df\n A B C\n0 1,598 65.79 79\n1 -300 46.90 90\n\nuse following code:\ndf = df.astype('str').apply(lambda x: pd.to_numeric(x.str.replace(',', '')))\n\ncheck data type of result\ndf.dtypes\n\nA int64\nB float64\nC int64\ndtype: object\n\n",
"Assuming you are taking data fro... | [
1,
0
] | [] | [] | [
"pandas",
"python",
"replace"
] | stackoverflow_0074332637_pandas_python_replace.txt |
Q:
Why am I getting a extra dimension when I'm using Numpy's apply along axis?
Using:
python version 3.10.2, numpy version 1.23.0
# Setup
import numpy as np
# functions
def get_RGBA_from_Int(num):
b = num & 255
g = (num >> 8) & 255
r = (num >> 16) & 255
a = (num >> 24) & 255
return (r,g,b,a)
def... | Why am I getting a extra dimension when I'm using Numpy's apply along axis? | Using:
python version 3.10.2, numpy version 1.23.0
# Setup
import numpy as np
# functions
def get_RGBA_from_Int(num):
b = num & 255
g = (num >> 8) & 255
r = (num >> 16) & 255
a = (num >> 24) & 255
return (r,g,b,a)
def get_INT_from_RGBA(ls):
r,g,b,a = ls
num = (a << 24) + (r << 16) + (g << ... | [
"For each value, your first function returns 4:\nGive it a scalar:\nIn [5]: get_RGBA_from_Int(1)\nOut[5]: (0, 0, 1, 0)\n\nGive it a 1d array, and we get a tuple of 4 arrays:\nIn [6]: get_RGBA_from_Int(np.array([0,1,2]))\nOut[6]: \n(array([0, 0, 0], dtype=int32),\n array([0, 0, 0], dtype=int32),\n array([0, 1, 2], d... | [
0
] | [] | [] | [
"arrays",
"methods",
"numpy",
"python"
] | stackoverflow_0074333768_arrays_methods_numpy_python.txt |
Q:
How to flatten and reshape a json file into a dataframe?
I have a json file as following nested parent-child relation. A classic organization data of manager and its employees and so on.
An employee can manage one or more employees, and those employees can manage other employees. Nesting can go N-level deep.
Input... | How to flatten and reshape a json file into a dataframe? | I have a json file as following nested parent-child relation. A classic organization data of manager and its employees and so on.
An employee can manage one or more employees, and those employees can manage other employees. Nesting can go N-level deep.
Input Data:
{
"employee_id": "e1",
"employee_name": "employ... | [
"With the following json file which extends yours for the purpose of demonstration:\n{\n \"employee_id\": \"e1\",\n \"employee_name\": \"employee name 1\",\n \"join_date\": \"2011-01-01\",\n \" manages \": [\n {\n \" employee_id \": \" e11 \",\n \" employee_name \": \" emplo... | [
0
] | [] | [] | [
"dataframe",
"json",
"pandas",
"parent_child",
"python"
] | stackoverflow_0074297962_dataframe_json_pandas_parent_child_python.txt |
Q:
WARNING:tensorflow:Can save best model only with val-loss available, skipping
epochs = 100
train_datagen = ImageDataGenerator(
rotation_range=15,
fill_mode ="nearest",
horizontal_flip = True,
zoom_range = 0.2)
checkpointer = ModelCheckpoint(filepath = "CDX_Best.h5", monitor='val-ac... | WARNING:tensorflow:Can save best model only with val-loss available, skipping |
epochs = 100
train_datagen = ImageDataGenerator(
rotation_range=15,
fill_mode ="nearest",
horizontal_flip = True,
zoom_range = 0.2)
checkpointer = ModelCheckpoint(filepath = "CDX_Best.h5", monitor='val-accuracy', save_best_only = True, verbose=1)
start = time.time()
history=Model.fi... | [
"simply see the monitor value monitor='val_accuracy' and matrixes return from the working process required validation process events.\n\nSample: << Custom return your handwritting benchmasks >>\n\nimport tensorflow as tf\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"... | [
0
] | [] | [] | [
"deep_learning",
"keras",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0074333608_deep_learning_keras_machine_learning_python_tensorflow.txt |
Q:
pyinstaller .exe file doesn't work on another computer
I have used pyinstaller to compile the py file into exe, on my computer it is working well
but when i am trying to download it on another computer it's always giving me error,
FileNotFound: no such file or directory when i compiled the py file i added the pyt... | pyinstaller .exe file doesn't work on another computer | I have used pyinstaller to compile the py file into exe, on my computer it is working well
but when i am trying to download it on another computer it's always giving me error,
FileNotFound: no such file or directory when i compiled the py file i added the python39.dll.
here is the command i used:
pyinstaller --noconfi... | [
"The program is trying to pull in a file that isnt on the computer. I had the same problem when my program used an image, it had to be in the same directory.\n"
] | [
0
] | [] | [] | [
"file",
"makefile",
"pyinstaller",
"python"
] | stackoverflow_0072365424_file_makefile_pyinstaller_python.txt |
Q:
Python ball acceleration pygame
I have created a sketch code which should move the ball with acceleration after pressing key. The ball would be accelerated in direction of the keyboard arrow, then rebound from active edge of the window. Here is the code:
import pygame, sys
pygame.init()
def main():
clock = p... | Python ball acceleration pygame | I have created a sketch code which should move the ball with acceleration after pressing key. The ball would be accelerated in direction of the keyboard arrow, then rebound from active edge of the window. Here is the code:
import pygame, sys
pygame.init()
def main():
clock = pygame.time.Clock()
pygame.d... | [
"Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data.\n\nThe coordinates for Rect objects are all integers. [...]\n\nIf you want to store object positions with floating point accuracy, you have to store the location of the object in separate variables ... | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074333050_pygame_python.txt |
Q:
Why does my unit testing return the wrong boolean value when my function works as it should?
My program is supposed to return the compass point clockwise to what the user inputs.
When I test my function using print, it returns a value with false when it should be true.
def turn_clockwise(x):
if x == 'N':
... | Why does my unit testing return the wrong boolean value when my function works as it should? | My program is supposed to return the compass point clockwise to what the user inputs.
When I test my function using print, it returns a value with false when it should be true.
def turn_clockwise(x):
if x == 'N':
print('E')
elif x == 'E':
print('S')
elif x == 'S':
print('W')
elif... | [
"You're confusing return values with print statements.\nWhen you print a value, it simply shows it to the screen, and doesn't return it out of the function.\nIf you want to return it as well as print, you need to add a return statement wherever you need it.\nThe reason your boolean value was false is because in the... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074333997_python_python_3.x.txt |
Q:
How to use lambda in iterating list with if statement?
I have this working for loop,
I want to use lambda that prints same results below
ids= [1,2,3,4,5,6,7]
val = [20,30,26,38,40,22,35]
list1=[]
for i,num in enumerate(val):
if num > 29:
list1.append(ids[i])
print("ids",list1)
#output ids [2, 4, 5, 7]
The c... | How to use lambda in iterating list with if statement? | I have this working for loop,
I want to use lambda that prints same results below
ids= [1,2,3,4,5,6,7]
val = [20,30,26,38,40,22,35]
list1=[]
for i,num in enumerate(val):
if num > 29:
list1.append(ids[i])
print("ids",list1)
#output ids [2, 4, 5, 7]
The code below throws and invalid syntax.
I just want to get the ... | [
"You can create lambda function to compare the value and return boolean, and call this function in your if condition. It's not a recommended way though E731 do not assign a lambda expression, use a def:\nlist1=[]\nget_flag = lambda i:i>29\nfor i in val:\n if get_flag(i):\n list1.append(i)\nprint(list1)\n[... | [
1,
0,
0
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0074334002_lambda_python.txt |
Q:
Finding Inequality of 4 variables using Nested If else only
Lets say I have 4 variables, a,b,c and d.
I'm trying to write a code(in the shortest formate) using only If Else (in nested formate) to arrange the variables in accensending order.
I'm sure their possibly are ways to do it smothly but using this method do... | Finding Inequality of 4 variables using Nested If else only | Lets say I have 4 variables, a,b,c and d.
I'm trying to write a code(in the shortest formate) using only If Else (in nested formate) to arrange the variables in accensending order.
I'm sure their possibly are ways to do it smothly but using this method do you think if the code can be shortened
Do you guys have any simp... | [
"Probably don't want to use nested statements in this scope, as you can see it get's unweildly very quickly.\na = 19\nb = 10\nc = 1\nd = 8\n# Note you can shorten the nesting by using multi-conditional (might not be the term!)\nif a > b > c > d: print(\"a>b>c>d\")\nelif b > c > d > a: print(\"b>c>d>a\") # and so o... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074333934_python.txt |
Q:
Beautiful soup getting the next span element
I have problems to get the data I want from beautiful soup. I have the following html page:
<br/>
<h4>Dieses Jahr</h4>
<br/>
<span class="parName">Diesen Monat:</span> <span class="parValue">67.54 kWh</span> |
<span class="parName">Januar:</span> <span class="parValue"... | Beautiful soup getting the next span element | I have problems to get the data I want from beautiful soup. I have the following html page:
<br/>
<h4>Dieses Jahr</h4>
<br/>
<span class="parName">Diesen Monat:</span> <span class="parValue">67.54 kWh</span> |
<span class="parName">Januar:</span> <span class="parValue">143.92 kWh</span> |
<span class="parName">Februa... | [
".next_sibling gets the next child [from the parent tag], which isn't necessarily a tag. In this case, it's probably an empty NavigableString. To get the next sibling Tag, use .find_next_sibling() instead\nhtml = '''\n<br/>\n<h4>Dieses Jahr</h4>\n<br/>\n<span class=\"parName\">Januar:</span> <span class=\"parValue\... | [
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074331339_beautifulsoup_python.txt |
Q:
Code refactoring, where to instantiate an object
I have two files, i.e order.py and shop.py. And I am instantiating a Network object in both of these files. i.e
order.py
from network import Network
...
network = Network()
shop.py
from network import Network
from order import Order
...
network = Network()
order = ... | Code refactoring, where to instantiate an object | I have two files, i.e order.py and shop.py. And I am instantiating a Network object in both of these files. i.e
order.py
from network import Network
...
network = Network()
shop.py
from network import Network
from order import Order
...
network = Network()
order = Order()
As you can see, I am importing from order.py ... | [
"You can import already instantiated object too, no need to instantiate again if it's going to be shared across modules.\nshop.py\nform network import Network, network\n.\n.\n.\n\n"
] | [
1
] | [] | [] | [
"oop",
"python",
"refactoring"
] | stackoverflow_0074334036_oop_python_refactoring.txt |
Q:
Find Pitch of a Bass Guitar from fret number, string number and pickup setting
I want to find pitch of a 4-string Bass Guitar. I have the following information available-
String Number (1-E , 2-A , 3-D , 4-G )
Fret Number
Pickup Setting (1-neck pick up, 2-neck & bridge pick-up, 3-bridge pick-up)
I don't know how... | Find Pitch of a Bass Guitar from fret number, string number and pickup setting | I want to find pitch of a 4-string Bass Guitar. I have the following information available-
String Number (1-E , 2-A , 3-D , 4-G )
Fret Number
Pickup Setting (1-neck pick up, 2-neck & bridge pick-up, 3-bridge pick-up)
I don't know how to map this information to find the pitch. Need some help.
| [
"The \"algorithm\" for computing the note at a given string and fret position on guitar or bass fretboard is pretty simple, and there's a standard formula for computing the specific pitch (frequency) of a given note.\nThese are described in more detail below, but the TL;DR version is this:\n\nto determine the note ... | [
0
] | [] | [] | [
"audio",
"audio_processing",
"guitar",
"python",
"python_3.x"
] | stackoverflow_0069380350_audio_audio_processing_guitar_python_python_3.x.txt |
Q:
How to convert a nested JSON file into a Pandas dataframe?
I'm trying to convert a nested JSON in a dataframe using Python. However, all the solutions applied missed some part of the JSON file. In particular, I tried to use the function "_json_normalize", but this function only partially unlists the JSON file.
Th... | How to convert a nested JSON file into a Pandas dataframe? | I'm trying to convert a nested JSON in a dataframe using Python. However, all the solutions applied missed some part of the JSON file. In particular, I tried to use the function "_json_normalize", but this function only partially unlists the JSON file.
The following JSON represents a partial input of the file.
[
{... | [
"With the json file you provided, here is one way to do it by defining a recursive helper function:\ndef func(data, new_data):\n \"\"\"Recursive helper function.\n\n Args:\n data: nested dictionary.\n new_data: empty dictionary.\n\n Returns:\n Flattened dictionary.\n\n \"\"\"\n f... | [
0
] | [] | [] | [
"json",
"pandas",
"python"
] | stackoverflow_0074304278_json_pandas_python.txt |
Q:
How can i open tkinter window and opencv window at the same time?
I want to open tkinter window and opencv window at the same time.
Help me pleas to run them at the same time.
How can I do that?
Here is Code:
import numpy as np
import cv2
from mss import mss
from PIL import Image
import pyautogui
import pyautogui ... | How can i open tkinter window and opencv window at the same time? | I want to open tkinter window and opencv window at the same time.
Help me pleas to run them at the same time.
How can I do that?
Here is Code:
import numpy as np
import cv2
from mss import mss
from PIL import Image
import pyautogui
import pyautogui as pg
import tkinter as tk
mon = {'left': 500, 'top': 500, 'width': 5... | [
"I wrote a mini-code so you can figure it out.\nMy program displays a tkinter window and my webcam window via OpenCV. They run in parallel, and do not interfere with each other's work.\nI did this thanks to the threading module (it's a built-in python module). This module allows you to run processes in parallel.\nf... | [
0
] | [] | [] | [
"opencv",
"python",
"tkinter",
"while_loop",
"window"
] | stackoverflow_0074333323_opencv_python_tkinter_while_loop_window.txt |
Q:
Trying to sort two arrays based on distance from origin
I have two arrays that are created from user inputs.
n = int(input("How many coordinates would you like to enter:"))
myArray1 = [None] * n
myArray2 = [None] * n
for i in range(len(myArray1)):
x = int(input("Enter X:"))
y = int(input("Enter Y:"))
... | Trying to sort two arrays based on distance from origin | I have two arrays that are created from user inputs.
n = int(input("How many coordinates would you like to enter:"))
myArray1 = [None] * n
myArray2 = [None] * n
for i in range(len(myArray1)):
x = int(input("Enter X:"))
y = int(input("Enter Y:"))
myArray1[i] = x
myArray2[i] = y
I want the parallel va... | [
"Use sorted builtin and pass a lambda function to key argument to sort the index based on the values of distances d, finally use this index list to form the result:\nData:\nn=5\narr1\n[0, 9, -6, -2, -9]\narr2\n[8, -2, 6, -3, 6]\nd = [(x**2+y**2)**0.5 for x,y in zip(arr1,arr2)]\n[8.0, 9.219544457292887, 8.4852813742... | [
1
] | [] | [] | [
"arrays",
"list",
"python"
] | stackoverflow_0074334189_arrays_list_python.txt |
Q:
How to find distance from base coordinate points in a dataframe?
I have a dataframe that looks like this:
lat
lon
time
45.23
81.3459
2021-04-25 12:31:15
45.265
81.346
2021-04-25 12:33:46
45.278
81.347
2021-04-25 12:40:23
.......
.........
....................
I have thousands of rows in the dataFrame. What I... | How to find distance from base coordinate points in a dataframe? | I have a dataframe that looks like this:
lat
lon
time
45.23
81.3459
2021-04-25 12:31:15
45.265
81.346
2021-04-25 12:33:46
45.278
81.347
2021-04-25 12:40:23
.......
.........
....................
I have thousands of rows in the dataFrame. What I want to do is find the distance of each point from the fi... | [
"With the dataframe you provided:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"lat\": [45.23, 45.265, 45.278],\n \"lon\": [81.3459, 81.346, 81.347],\n \"time\": [\"2021-04-25 12:31:15\", \"2021-04-25 12:33:46\", \"2021-04-25 12:40:23\"],\n }\n)\n\nHere is one way to do it using GeoP... | [
3
] | [] | [] | [
"distance",
"geopy",
"pandas",
"python"
] | stackoverflow_0074309537_distance_geopy_pandas_python.txt |
Q:
subprocess.popen detached from master (Linux)
I am trying to open a subprocess but have it be detached from the parent script that called it. Right now if I call subprocess.popen and the parent script crashes the subprocess dies as well.
I know there are a couple of options for windows but I have not found anythin... | subprocess.popen detached from master (Linux) | I am trying to open a subprocess but have it be detached from the parent script that called it. Right now if I call subprocess.popen and the parent script crashes the subprocess dies as well.
I know there are a couple of options for windows but I have not found anything for *nix.
I also don't need to call this using su... | [
"With linux, it's no issue at all. Just Popen(). For example, here is a little dying_demon.py\n#!/usr/bin/python -u\nfrom time import sleep\nfrom subprocess import Popen\nprint Popen([\"python\", \"-u\", \"child.py\"]).pid\ni = 0\nwhile True:\n i += 1\n print \"demon: %d\" % i\n sleep(1)\n if i == 3:\n ... | [
3,
1,
0,
0,
0
] | [] | [] | [
"linux",
"popen",
"python",
"subprocess"
] | stackoverflow_0031482397_linux_popen_python_subprocess.txt |
Q:
How to write a python3 function that merges two lists of sets so that the output list has sets of elements that were present in both input sets?
I have two lists of sets, let's say:
[{1, 2, 3}, {4, 5}, {6, 7}] and [{1, 2}, {3, 4}, {5, 6, 7}]
No set in the list has the same element and the sum of all sets in both l... | How to write a python3 function that merges two lists of sets so that the output list has sets of elements that were present in both input sets? | I have two lists of sets, let's say:
[{1, 2, 3}, {4, 5}, {6, 7}] and [{1, 2}, {3, 4}, {5, 6, 7}]
No set in the list has the same element and the sum of all sets in both lists is the same.
The function should check if the sets in both lists had the same elements. If there were some differences, put them in another set.
... | [
"Given that each value occurs in exactly two sets (one per input list), you could collect the index pairs for each value, where an index pair gives an indication in which two sets (at which indexes in both lists) the value occurs.\nUnique pairs indicate unique sets in the output, so a dictionary of such pairs can s... | [
5,
2
] | [] | [] | [
"data_structures",
"merge",
"python",
"set",
"time_complexity"
] | stackoverflow_0074333970_data_structures_merge_python_set_time_complexity.txt |
Q:
Explaining perl split with backslash in string pattern
I'm the author of pythonizer, perl to python converter, and I'm trying to translate a perl split statement that has a string pattern that includes a backslash, and I need some help understanding the behavior. Here is the example based on the source code I'm t... | Explaining perl split with backslash in string pattern | I'm the author of pythonizer, perl to python converter, and I'm trying to translate a perl split statement that has a string pattern that includes a backslash, and I need some help understanding the behavior. Here is the example based on the source code I'm trying to translate:
$s = 'a|b|c';
@a = split '\|', $s;
print... | [
"There's a few interleaved questions so let me go step by step\n\nPerl's split takes a regular expression pattern to identify separators by which it splits the string, in its first argument. This is a \"normal\" regex, compiled and ran by the regex engine, but in doing so it does have special cases\n\nAs for delim... | [
3,
1
] | [] | [] | [
"perl",
"python",
"regex",
"split",
"string"
] | stackoverflow_0074333327_perl_python_regex_split_string.txt |
Q:
How to get the text inside a tag using BeautifulSoup in Python
I am stucked at scraping some content from a website where I need to retrieve from this html code all the text that are between
<p class = some_string> Text I want to Retrieve </p>.
I need to use BeautifulSoup to retrieve all the text elements. The ht... | How to get the text inside a tag using BeautifulSoup in Python | I am stucked at scraping some content from a website where I need to retrieve from this html code all the text that are between
<p class = some_string> Text I want to Retrieve </p>.
I need to use BeautifulSoup to retrieve all the text elements. The html code is attached below as a image:
As you can see there are many... | [
"The issue is that you're not receiving the fully loaded html*. You'll get better results if you set the http://agence-prd.ansm.sante.fr/php/ecodex/rcp/R0390743.htm as link - it's where the page from your code is fetching and loading its contents from anyway. If you're receiving the link from somewhere else and nee... | [
0
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"web_scraping"
] | stackoverflow_0074319795_beautifulsoup_html_python_web_scraping.txt |
Q:
create new json data from values in a dictionary and nested dictionary
i have 2 dictionaries and i wish to create a new json data with values from both dictionaries as follows.
dic_a = [{'name': 'puskas',
'description': 'puskas is the command center for football',
'size': '251-1K',
'revenue': '$50M-$100M',
... | create new json data from values in a dictionary and nested dictionary | i have 2 dictionaries and i wish to create a new json data with values from both dictionaries as follows.
dic_a = [{'name': 'puskas',
'description': 'puskas is the command center for football',
'size': '251-1K',
'revenue': '$50M-$100M',
'industryTags': ['football federation']}]
dic_b = {'page': 1,
'total': 14... | [
"such problems can be solved easily with jmespath\nimport jmespath\nimport json \n\nc = dic_a\nc[0]['leads'] = jmespath.search('results[].{id:id, name:name.fullName,title:title ,company:company,email:email,verified:verified }',dic_b)\n\njson_string = json.dumps(c, indent=4, ensure_ascii=False)\nprint(json_string) ... | [
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074333864_dictionary_python.txt |
Q:
How to check if a numpy array contains the elements of another array in the exact order theyre in in the second array?
So Im iterating over rows of pixels that'll look like this
row = [0, 0, 0, 0, 255, 255, 0, 0, 255, 0, 0, 0, 0, 0,0]
and I'll have another array called whiteLine which looks like
whiteLine = [255,... | How to check if a numpy array contains the elements of another array in the exact order theyre in in the second array? | So Im iterating over rows of pixels that'll look like this
row = [0, 0, 0, 0, 255, 255, 0, 0, 255, 0, 0, 0, 0, 0,0]
and I'll have another array called whiteLine which looks like
whiteLine = [255, 255, 255, 255, 255, 255]
And i want to check if there are 6 white pixels in a row. Or basically check if the whiteLine arr... | [
"I think this can be done via looking at the convolution between row and whiteLine, and checking to see if one gets the value of convolvin whiteLine with itself.\nWhich makes this a one-liner:\nnp.any(np.convolve(whiteLine, whiteLine, 'valid')[0] == np.convolve(whiteLine, row, 'valid'))\n\nTesting with the two exam... | [
1,
0
] | [
"a little function i wrote to maybe help you solve ur question\ndef checker(num):\n counter = 0\n Pass = False\n for i in num:\n counter += 1\n if (sum(num[counter:counter+6]) >= 1530):\n Pass = True\n\n\n return Pass \n\n\nchecker(row1) #True\nchecker(row2) #False\n\nwor... | [
-2
] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074334116_arrays_numpy_python.txt |
Q:
API Query in Django Rest Framework
I have created an API from Database, I can view the API but I am unable to do a query via URL for example: 127.0.0.1:8000/author?author_id=9, I am not sure where to add the query code. I want to filter using fields. Here is my models.py
class AuthorAPI(models.Model):
author_i... | API Query in Django Rest Framework | I have created an API from Database, I can view the API but I am unable to do a query via URL for example: 127.0.0.1:8000/author?author_id=9, I am not sure where to add the query code. I want to filter using fields. Here is my models.py
class AuthorAPI(models.Model):
author_id=models.IntegerField()
name=models.... | [
"In your views, use a ModelViewset\nAnd add the fliter_backend attribute:\nfilter_backends = [django_filters.rest_framework.DjangoFilterBackend]\n\nSee here in the docs:\nhttps://www.django-rest-framework.org/api-guide/filtering/#setting-filter-backends\nclass AuthorViewset(viewsets.ReadOnlyModelViewset):\n seri... | [
2,
1,
1
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074320031_django_django_rest_framework_python.txt |
Q:
Creating Table of Contents in VS code Jupyter Notebook
I am using the Jupyter extension in Visual Studio Code to maintain a notebook on python programming and I want to add a table of contents inside it. I want to add the TOC as the notebook is becoming very big and is becoming difficult to navigate.
I write a hea... | Creating Table of Contents in VS code Jupyter Notebook | I am using the Jupyter extension in Visual Studio Code to maintain a notebook on python programming and I want to add a table of contents inside it. I want to add the TOC as the notebook is becoming very big and is becoming difficult to navigate.
I write a heading in markdown files using # to structure them properly.
I... | [
"I'm a developer on this extension. VS Code has an existing \"outline\" feature for code editing. This feature is being reused in notebooks for holding ToC navigation. On your left side panel it's \"> Outline\" below your open files. It should populate with markdown headings and be able to navigate to them. Like so... | [
31,
0
] | [] | [] | [
"jupyter",
"jupyter_notebook",
"python",
"tableofcontents",
"visual_studio_code"
] | stackoverflow_0067976088_jupyter_jupyter_notebook_python_tableofcontents_visual_studio_code.txt |
Q:
How to skip the next two iterations in for loop using python?
In a for loop, let's assume it contains 100 iterations, and what I need is, i need to print the first element and skip the next two element, and then need to prit the fourth element.. for example,
0 #should print
1 #should skip
2 #should skip
3 #should... | How to skip the next two iterations in for loop using python? | In a for loop, let's assume it contains 100 iterations, and what I need is, i need to print the first element and skip the next two element, and then need to prit the fourth element.. for example,
0 #should print
1 #should skip
2 #should skip
3 #should print
4 #should skip
5 #should skip
6 #should print
.
. like wise... | [
"If you iterate on your own range, generate one over three elements\nvalues = [\"dog0\", \"dog1\", \"dog2\", \"dog3\", \"dog4\", \"dog5\", \"dog6\"]\nfor i in range(0, 8, 3):\n print(i, values[i])\n\nIf you iterate over an iterable of values, use enumerate to filter\nvalues = [\"dog0\", \"dog1\", \"dog2\", \"dog... | [
0,
0,
0,
0
] | [
"You can do something like this\narr = [1,2,3,4,5,6,7,8,9,10]\nskip_count = 2 # how many to skip\ncounter = skip_count\n\nfor num in arr:\n if counter == skip_count:\n counter = 0\n print(num)\n else:\n counter += 1\n\nAlternatively, this will work too\narr = [1,2,3,4,5,6,7,8,9,10]\n\nfo... | [
-1
] | [
"algorithm",
"python",
"python_3.x"
] | stackoverflow_0074334349_algorithm_python_python_3.x.txt |
Q:
Matplotlib won't run on Windows 10 -- DLL fails to load
I have installed matplotlib on a Windows 10 machine using
pip3 install matplotlib
I get a message that it's using the wheel
matplotlib-3.4.1-cp39-cp39-win_amd64.whl1
When I type import matplotlib in a python 3.9 shell, I get the following message:
Traceback (... | Matplotlib won't run on Windows 10 -- DLL fails to load | I have installed matplotlib on a Windows 10 machine using
pip3 install matplotlib
I get a message that it's using the wheel
matplotlib-3.4.1-cp39-cp39-win_amd64.whl1
When I type import matplotlib in a python 3.9 shell, I get the following message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>... | [
"\nThis issue is present again with matplotlib 3.3.2, 3.3.3 and 3.3.4. .\nmatplotlib 3.3.0 3.3.1 work.\n\nI found a solution by mkunzBGC on Github:\nhttps://github.com/matplotlib/matplotlib/issues/18292#issuecomment-792634734\nThe downgrade to matplotlib 3.3.1 worked for me.\n",
"I figured it out. If you have alr... | [
1,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0066919838_matplotlib_python.txt |
Q:
Scrape multi page URL using Beautifulsoup
How to scrape multi page URL using BeautifulSoup,
I'm trying to scrape webpage but I'm stuck, any idea will be helpful
import os
import requests
from bs4 import BeautifulSoup as bs
from urllib.parse import urljoin
from pathlib import Path
import os.path
import urllib.reque... | Scrape multi page URL using Beautifulsoup | How to scrape multi page URL using BeautifulSoup,
I'm trying to scrape webpage but I'm stuck, any idea will be helpful
import os
import requests
from bs4 import BeautifulSoup as bs
from urllib.parse import urljoin
from pathlib import Path
import os.path
import urllib.request, urllib.error, urllib.parse
from tldextract ... | [
"You can use a while loop to go through all the pages\n# import urllib.parse\n\nurl = \"https://www.taneps.go.tz/epps/viewAllAwardedContracts.do?d-3998960-p=1&selectedItem=viewAllAwardedContracts.do&T01_ps=100\"\n\nsession = requests.Session()\nsession.headers[\"User-Agent\"] = \"Mozilla/5.0 (X11; Linux x86_64) App... | [
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074316658_beautifulsoup_python.txt |
Q:
How to add print and sort to my contact python code
import os
contact = {}
def display_contact():
print("Name\t\tContact Number")
for key in contact:
print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1.Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit... | How to add print and sort to my contact python code | import os
contact = {}
def display_contact():
print("Name\t\tContact Number")
for key in contact:
print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1.Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Sort List \n 7. Prin... | [
"You could write display_contact() like this.\ndef display_contact():\n for name, number in sorted((k,v) for k, v in contact.items()):\n print(f'Name={name}, number={number}')\n\nYou may want to pass a key parameter to sorted() depending on the sort order required.\nNote that the function name is a misnom... | [
1
] | [] | [] | [
"printing",
"python",
"python_3.x",
"sorting"
] | stackoverflow_0074333415_printing_python_python_3.x_sorting.txt |
Q:
How to print files inside a folder in original order?
I'm trying to print files present inside a folder in it's original order. Order inside folder [1.mp4 2.mp4 5.mp4 10.mp4 23.mp4]
Code I use:
targetFile = os.listdir(path)
for i in targetFile:
print(i)
Output I get:
1.mp4
10.mp4
2.mp4
23.mp4
5.mp4
Output I e... | How to print files inside a folder in original order? | I'm trying to print files present inside a folder in it's original order. Order inside folder [1.mp4 2.mp4 5.mp4 10.mp4 23.mp4]
Code I use:
targetFile = os.listdir(path)
for i in targetFile:
print(i)
Output I get:
1.mp4
10.mp4
2.mp4
23.mp4
5.mp4
Output I expected:
1.mp4
2.mp4
5.mp4
10.mp4
23.mp4
How to fix it?
| [
"The solution you seek is ordering the list as if they were an int. At the moment the result you are getting is based on how a string is sorted. If you can figure out how to change the key in sorting os.listdir(path), your problem is solved.\n"
] | [
0
] | [] | [] | [
"list",
"python",
"python_3.x",
"sorting"
] | stackoverflow_0074334438_list_python_python_3.x_sorting.txt |
Q:
How to create csv file from github repo data? (JSON)
I need to create csv file from github repo. The files in github are in JSON. https://github.com/PhonePe/pulse
Someone has already done it. But the steps are not clear.
https://github.com/kracekumar/pulse-plus
A:
You might consider the Pandas package
See "How t... | How to create csv file from github repo data? (JSON) | I need to create csv file from github repo. The files in github are in JSON. https://github.com/PhonePe/pulse
Someone has already done it. But the steps are not clear.
https://github.com/kracekumar/pulse-plus
| [
"You might consider the Pandas package\nSee \"How to Convert a JSON String to CSV using Python\"\nimport pandas as pd\ndf = pd.read_json (r'Path where the JSON file is saved\\File Name.json')\ndf.to_csv (r'Path where the new CSV file will be stored\\New File Name.csv', index = None)\n\nExample:\nimport pandas as pd... | [
0
] | [] | [] | [
"github",
"json",
"python"
] | stackoverflow_0074333658_github_json_python.txt |
Q:
pandas group by and calculate result using values from the same column (R equivalent included)
I want to group and aggregate and then calculate a ratio based on values in a certain column.
In R it's pretty straight forward.
df = data.frame(a = c('a', 'a', 'b', 'b'),
b = c('x', 'y', 'x', 'y'),
... | pandas group by and calculate result using values from the same column (R equivalent included) | I want to group and aggregate and then calculate a ratio based on values in a certain column.
In R it's pretty straight forward.
df = data.frame(a = c('a', 'a', 'b', 'b'),
b = c('x', 'y', 'x', 'y'),
value = 1:4)
df %>%
group_by(a) %>%
summarise(calc = value[b == 'x']/value[b == '... | [
"You can try this:\nimport pandas as pd\nimport numpy as np\n\ncond1 = lambda x: x['value'].loc[x['b'].eq('x')].to_numpy()\ncond2 = lambda x: x['value'].loc[x['b'].eq('y')].to_numpy()\n\n(df.groupby('a').apply(lambda x: (cond1(x) / cond2(x))[0])\n .reset_index(name = 'result'))\n\n a result\n0 a 0.50\n1 b ... | [
3,
1
] | [] | [] | [
"dplyr",
"pandas",
"python",
"r"
] | stackoverflow_0074331861_dplyr_pandas_python_r.txt |
Q:
Partial update to extended user profile
I have a extension to user model in Django, adding multiple fields to the regular user profile. In order for the user to be able to change them, I have created a form that should be able to modify those fields but with no success...
models.py
class UserProfileModel(models.Mo... | Partial update to extended user profile | I have a extension to user model in Django, adding multiple fields to the regular user profile. In order for the user to be able to change them, I have created a form that should be able to modify those fields but with no success...
models.py
class UserProfileModel(models.Model):
user = models.OneToOneField(User, n... | [
"It looks like you are only filling in one field in the form that requires all fields. However, your model does not except blank values, only null values. If you do want them to accept empty fields from forms, then you have to use blank=True rather than null = True.\nAdditionally, you probably want to include the ... | [
0
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0074309692_django_forms_python.txt |
Q:
Updating a shared tqdm progress bar in python multiprocessing
I want to update a progress bar from inside a spawned process as follows:
import multiprocessing as mp
import random
import time
from tqdm import tqdm
def test(queue, pbar, lock):
while True:
x = queue.get()
if x is None:
... | Updating a shared tqdm progress bar in python multiprocessing | I want to update a progress bar from inside a spawned process as follows:
import multiprocessing as mp
import random
import time
from tqdm import tqdm
def test(queue, pbar, lock):
while True:
x = queue.get()
if x is None:
break
for i in range(x):
time.sleep(1)
... | [
"I'd slightly restructure the program:\n1.) Create update_bar process that creates a progress bar and reads from another queue values and updates the bar with these values\n2.) This update process has daemon=True parameter, so it won't block upon exit\n3.) The test processes receives upon start the bar_queue and pu... | [
1
] | [] | [] | [
"multiprocessing",
"progress_bar",
"python",
"tqdm"
] | stackoverflow_0074333395_multiprocessing_progress_bar_python_tqdm.txt |
Q:
Option "symbol" in scattermapbox is not working
I am trying to change the symbol from circle to location pin to highlight the co-ordinates on to the map.However, apart from "circle" no other options work correctly in the symbol option.
I have tried - square,marker, triangle.Can someone tell me how to fix this, it ... | Option "symbol" in scattermapbox is not working | I am trying to change the symbol from circle to location pin to highlight the co-ordinates on to the map.However, apart from "circle" no other options work correctly in the symbol option.
I have tried - square,marker, triangle.Can someone tell me how to fix this, it doesnt throw an error
#Plotting co-ordinates on to th... | [
"Please note that markers different from \"circle\" (default) work only if you are using \"vector tiles from the Mapbox service\" (e.g. \"dark\" or \"satellite\") for which your mapbox token needs to be provided; but they don't work if you are using \"open\" vector tiles\" like \"open-street-map\"\n",
"In the plo... | [
2,
0,
0
] | [] | [] | [
"google_maps",
"python",
"scatter_plot"
] | stackoverflow_0059628536_google_maps_python_scatter_plot.txt |
Q:
module 'pandas' has no attribute 'tslib'
I am unable to use ggplot package in python .
import pandas as pd
from ggplot import *
import pandas as pd
from ggplot import *
It returns:
AttributeError: module 'pandas' has no attribute 'tslib'
A:
I changed import commands for pandas modules in ggplot source files... | module 'pandas' has no attribute 'tslib' | I am unable to use ggplot package in python .
import pandas as pd
from ggplot import *
import pandas as pd
from ggplot import *
It returns:
AttributeError: module 'pandas' has no attribute 'tslib'
| [
"I changed import commands for pandas modules in ggplot source files on my PC and it worked for me. You can find the locations for those on your PC in your error message. For me it was C:\\Users\\user\\Anaconda3\\Lib\\site-packages\\ggplot\nThe files I have changed:\nIn C:\\Users\\user\\Anaconda3\\Lib\\site-package... | [
20,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0058143253_python.txt |
Q:
Django: Remove trailing zeros for a Django model field
I'm trailing to get rid of the unwanted trailing zeros for my Django model field:
class mycls(BaseModel):
price = models.DecimalField()
I've even tried to creat a new field.
Here is the Django field I created:
class CurrencyField(models.DecimalField):
... | Django: Remove trailing zeros for a Django model field | I'm trailing to get rid of the unwanted trailing zeros for my Django model field:
class mycls(BaseModel):
price = models.DecimalField()
I've even tried to creat a new field.
Here is the Django field I created:
class CurrencyField(models.DecimalField):
INTEGER_PLACES = 15
DECIMAL_PLACES = 18
DECIMAL_PL... | [
"You should override from_db_value, try something like this:\nclass CurrencyField(models.DecimalField):\n ...\n ...\n ...\n def from_db_value(self, value, expression, connection):\n if value is None:\n return value\n return normalize_fraction(value)\n\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074334350_django_python.txt |
Q:
TypeError: User() got unexpected keyword arguments: 'password2' : Django JWT Authentication
I am trying to build a user authentication app using django JWT token, when i try to test my user authentication api and validate the password and password2 , it generate the following error:
TypeError: User() got unexpecte... | TypeError: User() got unexpected keyword arguments: 'password2' : Django JWT Authentication | I am trying to build a user authentication app using django JWT token, when i try to test my user authentication api and validate the password and password2 , it generate the following error:
TypeError: User() got unexpected keyword arguments: 'password2'
My serializers.py is as follows:
from rest_framework import ser... | [
"Because your serializer has password2 but User model does not have.\nJust pop password2 into validated_data\nfrom rest_framework import serializers\nfrom account.models import User\n\nclass UserRegistrationSerializers(serializers.ModelSerializer):\n password2=serializers.CharField(style={'input_type':'password'... | [
2
] | [] | [] | [
"django",
"django_rest_framework",
"jwt",
"python"
] | stackoverflow_0074334582_django_django_rest_framework_jwt_python.txt |
Q:
Django Form is not updating the user database
I want to update User database using forms.When I trying to update it remains same the database and not update. So to perform this task ?
forms.py
from django import forms
from django.contrib.auth.models import User
class updateform(forms.ModelForm):
class Meta:
... | Django Form is not updating the user database | I want to update User database using forms.When I trying to update it remains same the database and not update. So to perform this task ?
forms.py
from django import forms
from django.contrib.auth.models import User
class updateform(forms.ModelForm):
class Meta:
model=User
fields="__all__"
views.py... | [
"Why don't you use CBV generic views?\nin yourapp/models.py:\nfrom django.db import models\nfrom django.urls import reverse\nfrom django.contrib.auth import get_user_model\n\n# const for get_absolute_url\n#that's suffix will be using in your template names look at urls.py,\n#if you need u should change it for smth ... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074329475_django_python.txt |
Q:
Python | Using datetime to determine whether the US stock market is open, logic not working correctly
I have this block of code that is supposed to be mentioning whether the stock market is open or not. Holidays aren't included yet.
current_time = datetime.now()
local_date = datetime.strftime(current_time, '%b %d,... | Python | Using datetime to determine whether the US stock market is open, logic not working correctly | I have this block of code that is supposed to be mentioning whether the stock market is open or not. Holidays aren't included yet.
current_time = datetime.now()
local_date = datetime.strftime(current_time, '%b %d, %Y')
print("Today's date is: " + str(local_date))
#Prints out the time on the east coast. Helps give cont... | [
"# consider the below portion of your if \n(day_of_week != \"Saturday\" or day_of_week != \"Sunday\")\n\nIt returns True if either day_of_week != \"Saturday\" or day_of_week != \"Sunday\" is True.\nWhich means, if the day is Sunday, day_of_week != \"Saturday\" still return True and so the total output is still True... | [
0,
0,
0
] | [] | [] | [
"logical_operators",
"python"
] | stackoverflow_0069874811_logical_operators_python.txt |
Q:
Why is pylab.plot putting points elsewhere it should? Shall I use another function?
I'm studying a function
y = x * sqrt((x ** 2) - 1) / (x ** 2 + 1)
If I don't take care of its definition domain, writing this Python code to display its graph, I receive a deserved error:
import pylab as pl
from numpy import *
pl.... | Why is pylab.plot putting points elsewhere it should? Shall I use another function? | I'm studying a function
y = x * sqrt((x ** 2) - 1) / (x ** 2 + 1)
If I don't take care of its definition domain, writing this Python code to display its graph, I receive a deserved error:
import pylab as pl
from numpy import *
pl.style.use('bmh')
# Df = R
Df = [-5 + k/10 for k in range(100)] # from -5 to -5 by 0.1 st... | [
"plot connects the given points with straight lines to generate the \"curve\". That said, it simply does not \"know\" that your function is not continuous and points (-1.1, approx. -0.25) and (1, 0) should not be connected.\nBut, you can easily fix that. plot will neither connect nor complain about NaN points, so b... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074334514_pandas_python.txt |
Q:
Why is my message from the discord bot not being sent?
Below is my code, I wanted to know why the "==" operator isn't functioning as when I change it to "!=" the bot responds accordingly. I have typed "hello" in my discord server with the bot online however it doesn't respond.
import discord
client = discord.Clie... | Why is my message from the discord bot not being sent? | Below is my code, I wanted to know why the "==" operator isn't functioning as when I change it to "!=" the bot responds accordingly. I have typed "hello" in my discord server with the bot online however it doesn't respond.
import discord
client = discord.Client(intents=discord.Intents.default())
@client.event
async ... | [
"You don't have the message_content intent, so you can't read messages. Hence, message.content will always be empty.\nhttps://discordpy.readthedocs.io/en/stable/intents.html\n"
] | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074333334_discord_discord.py_python.txt |
Q:
I am getting an error that I don't understand Discord.py
Here is my code:
import os
import discord
import re
from discord.ext import commands
SERVER_ID = os.environ['SERVER_ID']
bot = commands.Bot(command_prefix='^', intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f"Bot logged in as {bot... | I am getting an error that I don't understand Discord.py | Here is my code:
import os
import discord
import re
from discord.ext import commands
SERVER_ID = os.environ['SERVER_ID']
bot = commands.Bot(command_prefix='^', intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f"Bot logged in as {bot.user}")
#////////////////////////////////////////
#async d... | [
"Too many requests means you're getting ratelimited for spamming Discord's API. You may not be doing so, but because you're abusing replit's platform to run a bot on, other people's bots share the same IP address, and as a consequence all of you combined get ratelimited.\nDon't use replit (or heroku, or any other n... | [
0
] | [] | [] | [
"discord.py",
"python",
"python_3.x"
] | stackoverflow_0074333154_discord.py_python_python_3.x.txt |
Q:
How can do time minus with python?
I want to do a time minus: 24Hours - 14Hours 20 minutes 10 seconds,write a function:
def time_minus(start,end):
def convert_sec(time):
hours = int(time.split(":")[0])
mins = int(time.split(":")[1])
secs = int(time.split(":")[2])
return hours*60... | How can do time minus with python? | I want to do a time minus: 24Hours - 14Hours 20 minutes 10 seconds,write a function:
def time_minus(start,end):
def convert_sec(time):
hours = int(time.split(":")[0])
mins = int(time.split(":")[1])
secs = int(time.split(":")[2])
return hours*60*60 + mins*60 + secs
start_time = co... | [
"Since 24:00:00 is not a valid time of the day, I think you need to convert it into a format including a day indicator:\nfrom datetime import datetime\ns1 = '0-14:20:10'\ns2 = '1-00:00:00' \nFMT = '%w-%H:%M:%S'\ntdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)\n\n\nSource:\nhttps://docs.... | [
2,
0
] | [] | [] | [
"python",
"time"
] | stackoverflow_0074334552_python_time.txt |
Q:
opengl (python) Camera rotate vs Cube Rotate gluLookAt() 's position in display code
This code is a display part.
def display(self):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
gluLookAt(5.0, 5.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
if (self.axis == 0):
... | opengl (python) Camera rotate vs Cube Rotate gluLookAt() 's position in display code | This code is a display part.
def display(self):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
gluLookAt(5.0, 5.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
if (self.axis == 0):
glRotatef(self.pitch, 1.0, 0.0, 0.0)
elif (self.axis == 1):
... | [
"OpenGL is a state engine. The current transformation matrix is a global state. Both functions gluLookAt and glRotatef define a matrix and multiply the current transformation matrix with the new defined matrix. The matrix multiplication is not commutative, the order matters:\nmatrix1 * matrix2 != matrix2 * matrix1\... | [
0
] | [] | [] | [
"opengl",
"opengl_compat",
"python"
] | stackoverflow_0074334711_opengl_opengl_compat_python.txt |
Q:
Why isn't my environment variable being cleared in FastApi test?
I'm relatively new to FastApi and unit testing in Python.
I am testing an api that has a conditional check on whether an environment variable FOO is present.
I am trying to clear that environment variable so that when the api gets invoked by the test... | Why isn't my environment variable being cleared in FastApi test? | I'm relatively new to FastApi and unit testing in Python.
I am testing an api that has a conditional check on whether an environment variable FOO is present.
I am trying to clear that environment variable so that when the api gets invoked by the test the environment variable is not found:
def test_invoice(self, reque... | [
"It's a working example how it could be done.\n# app.py\nimport os\n\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/\")\ndef invoices_api():\n if os.environ.get(\"FOO\"):\n return 1\n\n# test_me.py\nimport os\nfrom unittest.mock import patch\n\nfrom fastapi.testclient import TestClient\n... | [
0
] | [] | [] | [
"fastapi",
"python",
"requests_mock"
] | stackoverflow_0074330851_fastapi_python_requests_mock.txt |
Q:
How to drop only the number in the same column which has string in object type, pandas
d = {'col1': ['Son', 2, 'Dad'], 'col2': [3, 4, 5]}
df = pd.DataFrame(data=d)
I want to drop change the second row to 'Unknown'
col1 col2
0 Son 3
1 2 4
2 Dad 5
change to
col1 col2
0 Son 3
1 Unkn... | How to drop only the number in the same column which has string in object type, pandas | d = {'col1': ['Son', 2, 'Dad'], 'col2': [3, 4, 5]}
df = pd.DataFrame(data=d)
I want to drop change the second row to 'Unknown'
col1 col2
0 Son 3
1 2 4
2 Dad 5
change to
col1 col2
0 Son 3
1 Unknown 4
2 Dad 5
| [
"pandas str functions make numeric to NaN\ndf['col1'] = df['col1'].str[:].fillna('Unknown')\n\noutput:\ndf\n col1 col2\n0 Son 3\n1 Unknown 4\n2 Dad 5\n\n",
"you can use regex:\ndf['col1'] = df['col1'].astype(str)\ndf['col1'] = df['col1'].str.replace('\\d+', 'Unknown') #find numbers and replace... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074333470_dataframe_pandas_python.txt |
Q:
installation error: cannot import name 'collections_abc' from 'six.moves' (unknown location)
I tried to pip install --upgrade google-cloud-bigquery[pandas] on anaconda command promt
but got this errors while installing
ERROR: astroid 2.3.1 requires typed-ast<1.5,>=1.4.0; implementation_name == "cpython" and python... | installation error: cannot import name 'collections_abc' from 'six.moves' (unknown location) | I tried to pip install --upgrade google-cloud-bigquery[pandas] on anaconda command promt
but got this errors while installing
ERROR: astroid 2.3.1 requires typed-ast<1.5,>=1.4.0; implementation_name == "cpython" and python_version < "3.8", which is not installed.
ERROR: astroid 2.3.1 has requirement six==1.12, but you'... | [
"I was able to resolve this by explicitly installing an updated version of six (1.13.0 instead of 1.11.0) via:\npip3 install --upgrade six>=1.13.0\n\n"
] | [
0
] | [
"As the error message suggests try downgrading the \"six\" version to 1.12, it should work. I was facing the same issue and downgrading the same worked for me.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0064581628_python.txt |
Q:
how can I say to python pd to aply something to all the columns except the ones with strings?
I have a pd
df
A B C D
0 1,598 65.79 79 asdf
1 -300 46.90 90 qwer
how can I say to aply this:
`
dff = dff.astype('str').apply(lambda x: pd.to_numeric(x.str.replace(',', '')))
`
to onl... | how can I say to python pd to aply something to all the columns except the ones with strings? | I have a pd
df
A B C D
0 1,598 65.79 79 asdf
1 -300 46.90 90 qwer
how can I say to aply this:
`
dff = dff.astype('str').apply(lambda x: pd.to_numeric(x.str.replace(',', '')))
`
to only the columns with ","'s?
take into consider that I don't know the keys of the columns or orders
I ... | [
"you can check numeric columns or object columns that all values in column can convert to numeric\ndf.astype('str').apply(lambda x: x.str.contains(r'^[0-9-.,]+$')).all()\n\noutput:\nA True\nB True\nC True\nD False\ndtype: bool\n\nA, B, C\n\nyou can filter columns by boolean indexing\ncond1 = df.asty... | [
3
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074334713_dataframe_pandas_python.txt |
Q:
Django Overriding DateTimeField
I currently have a form which allows users to select a datetime, which I display using a custom bootstrap date picker. I have the date shown formatted to MM/DD/YYYY hh:mm A.
The problem is the field doesn't recognize this format. I subclassed models.DateTimeField to convert the fo... | Django Overriding DateTimeField | I currently have a form which allows users to select a datetime, which I display using a custom bootstrap date picker. I have the date shown formatted to MM/DD/YYYY hh:mm A.
The problem is the field doesn't recognize this format. I subclassed models.DateTimeField to convert the formatted date passed in to iso format ... | [
"You can simply extend the accepted datetime input formats in settings.py like:\nDATETIME_INPUT_FORMATS += (\n \"%m/%d/%Y %H:%M %p\",\n)\n\nand keep using the default models.DateTimeField\n"
] | [
0
] | [] | [] | [
"django",
"python",
"python_datetime"
] | stackoverflow_0059094850_django_python_python_datetime.txt |
Q:
When I start my program (Selenium) it opens web page then it closes immediately after whithout error in log
My code is very short. When I try it, the program opens web page but program closes immediately after.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.suppo... | When I start my program (Selenium) it opens web page then it closes immediately after whithout error in log | My code is very short. When I try it, the program opens web page but program closes immediately after.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Chrome()
dr... | [
"You have to add the below chrome options:\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.options import Options\n\noptions = Options()\noptions.add_experimental_option(\"detach\", True)\ndriver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), opt... | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074334328_python_selenium.txt |
Q:
How to make a buffer have specific latitude and longitude coordinates in GeoPandas
I want to create an annular buffer in GeoPandas (with an inner radius of 2 km and an outer radius of 2.1 km) around a specific point of latitude -33.0679433 and longitude -71.5524818
I did so by creating 2 buffers and turned them in... | How to make a buffer have specific latitude and longitude coordinates in GeoPandas | I want to create an annular buffer in GeoPandas (with an inner radius of 2 km and an outer radius of 2.1 km) around a specific point of latitude -33.0679433 and longitude -71.5524818
I did so by creating 2 buffers and turned them into GeoDataFrames so I could overlay them by difference like
res_difference = buffer2_1gd... | [
"You have to transform the crs of your point's geometry to an appropriate one and get the buffer in meters. Example:\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nfrom shapely.geometry import Point\n\npt = Point( -33.0679433, -71.5524818)\npt_df = gpd.GeoDataFrame(geometry=[pt], crs=4326)\n\nbuff1 = p... | [
0
] | [] | [] | [
"geopandas",
"python"
] | stackoverflow_0074333139_geopandas_python.txt |
Q:
Check if int exists in dictionary in Pandas column
How do I check if multiple integers exists in a dictionary stored as a string in a columns in pandas dataframe?
Input dataframe
| player | qualifier |
| ------ | ---------------------------- |
| John | "{120: 'left', 107: True}" |
| Felix |... | Check if int exists in dictionary in Pandas column | How do I check if multiple integers exists in a dictionary stored as a string in a columns in pandas dataframe?
Input dataframe
| player | qualifier |
| ------ | ---------------------------- |
| John | "{120: 'left', 107: True}" |
| Felix | {1: 'box centre', 120: 5.6}" |
Check if 5, 6 and 107 e... | [
"you can use apply with a lambda function.\nvalues=[5,6,107]\n\nimport ast\ndf['qualifier']=df['qualifier'].apply(ast.literal_eval)\n\n#Let's take the keys in the dictionary for that line as a list and compare it with the list named values. Return True if any value matches, False if not.\n\ndf['set_piece']=df['qual... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074334735_dataframe_pandas_python.txt |
Q:
Regex python do lookahead in a conditional statement
I'm trying to do lookaheads in a conditional statement.
Explanation by words:
(specified string that has to be a number (decimal or not) or a word character, a named capturing group is created) (if the named capturing group is a word character then check if the ... | Regex python do lookahead in a conditional statement | I'm trying to do lookaheads in a conditional statement.
Explanation by words:
(specified string that has to be a number (decimal or not) or a word character, a named capturing group is created) (if the named capturing group is a word character then check if the next string is a number (decimal or not) with a lookahead ... | [
"The named capture group (?P<var>...) contains the actual text which matched, not the regex itself. There is a way to create a named regex, too; but it's probably not particularly necessary or useful here.\nSimply spell out the alternatives:\n((?<![a-zA-Z0-9])[a-zA-Z]\\s+-?\\d+(.\\d+)?(?![a-zA-Z.0-9])|(?<![a-zA-Z.0... | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074334762_python_regex.txt |
Q:
Pandas dropping na within conditions
if i have the following input
participant trials Correct_Choice Opt_in
1 1 NaN 1
1 1 1 NAN
2 1 NaN 1
2 1 0 NaN
My desired output is
participant trials C... | Pandas dropping na within conditions | if i have the following input
participant trials Correct_Choice Opt_in
1 1 NaN 1
1 1 1 NAN
2 1 NaN 1
2 1 0 NaN
My desired output is
participant trials Correct_Choice Opt_in
1 1 ... | [
"Assuming that you have a dataframe (df) that looks like this:\n participant trials Correct_Choice Opt_in\n0 1 1 NaN 1\n1 1 1 1.0 NaN\n2 2 1 NaN 1\n3 2 1 0.0 NaN\n\n\n\nThen you co... | [
1
] | [] | [] | [
"data.table",
"pandas",
"python",
"r"
] | stackoverflow_0074334071_data.table_pandas_python_r.txt |
Q:
How can I generate a list of possible 'words' when all I know is the number of letters of each word in Python?
I know this is probably a dumb question and I am missing something really simple, but I can't for the life of me figure out where I am going wrong... I am ultimately trying to generate a list of all poss... | How can I generate a list of possible 'words' when all I know is the number of letters of each word in Python? | I know this is probably a dumb question and I am missing something really simple, but I can't for the life of me figure out where I am going wrong... I am ultimately trying to generate a list of all possible letter combinations with a string of a given length. I know some of these letter combinations wont be pronounc... | [
"You can get what you want using itertools.product, specifically:\nimport itertools as it\n\nlist(it.product(letters, repeat=3))\n\n ('A', 'A', 'B'),\n ('A', 'A', 'C'),\n ('A', 'A', 'D'),\n ('A', 'A', 'E'),\n ('A', 'A', 'F'),\n ...\n\nit.product works exactly as nested for-loops.\n",
"this is a standard permutati... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074334712_python.txt |
Q:
PyYAML load version number float (with trailing zero) as string
example.yaml
version: 0.20
main.py
import yaml
with open("example.yaml", "r") as stream:
try:
print(yaml.safe_load(stream))
except yaml.YAMLError as exc:
print(exc)
Actual output:
{'version': 0.2}
Desired output:
{'version'... | PyYAML load version number float (with trailing zero) as string | example.yaml
version: 0.20
main.py
import yaml
with open("example.yaml", "r") as stream:
try:
print(yaml.safe_load(stream))
except yaml.YAMLError as exc:
print(exc)
Actual output:
{'version': 0.2}
Desired output:
{'version': '0.20'}
Looks like yaml is parsing the version field as a float, a... | [
"Load all floating point values that end with \"0\" as strings\nOne possible hack:\nclass Loader(yaml.SafeLoader):\n def construct_yaml_float(self, node):\n # CUSTOM HACK: returns unchanged string if ends with \"0\".\n if node.value.endswith(\"0\"):\n return node.value\n\n # UNCHA... | [
0,
0
] | [] | [] | [
"python",
"pyyaml",
"yaml"
] | stackoverflow_0074334528_python_pyyaml_yaml.txt |
Q:
How to center GridLayout in kivymd?
I have certain news that are filled in first in MD3Card and then lined up in a tabular view in GridLayout with scrolling, but no matter how I tried, it didn't work out to do it all in the center and not on the left edge as in the photo.
Kivymd style:
VK = '''
<Tab>
... | How to center GridLayout in kivymd? | I have certain news that are filled in first in MD3Card and then lined up in a tabular view in GridLayout with scrolling, but no matter how I tried, it didn't work out to do it all in the center and not on the left edge as in the photo.
Kivymd style:
VK = '''
<Tab>
ScrollView:
md_bg_color: "#f8... | [
"Code:\n<Tab>\n ScrollView:\n md_bg_color: \"#f8f8f8\"\n bar_width: 0\n GridLayout:\n id: tab_box \n padding: \"5dp\" \n cols: 3 \n spacing: 10\n size_hint_y: None\n height: self.minimum_height\n\nReplace with:\n<Tab>\n Sc... | [
0
] | [] | [] | [
"kivy",
"kivymd",
"python"
] | stackoverflow_0074255042_kivy_kivymd_python.txt |
Q:
Failed building wheel for mujoco-py with OpenAI Gym
I followed the installation instructions for OpenAI Gym, but the full install gives the error "Failed to build wheel for mujoco-py"
pip install gym and import gym work fine on my laptop and import mujoco_py works too, but I'm still getting a "failed to build whee... | Failed building wheel for mujoco-py with OpenAI Gym | I followed the installation instructions for OpenAI Gym, but the full install gives the error "Failed to build wheel for mujoco-py"
pip install gym and import gym work fine on my laptop and import mujoco_py works too, but I'm still getting a "failed to build wheel error"
If someone could explain why I am getting this i... | [
"MuJoCo is a physics engine for detailed, efficient rigid body simulations with contacts. mujoco-py allows using MuJoCo from Python 3.\nPython 2 has been desupported since 1.50.1.0. Python 2 users can stay on the 0.5 branch. The latest release there is 0.5.7 which can be installed with pip install mujoco-py==0.5.7.... | [
0,
0,
0,
0
] | [] | [] | [
"openai_gym",
"python"
] | stackoverflow_0053138689_openai_gym_python.txt |
Q:
Channel's uploads playlist id returning playlistNotFound
I am working on a project that gets the id of a channel's uploads playlist through their legacy username using the forUsername parameter with python3 and youtube-data-api. Here it searches for the uploads playlist string. From there, it gets the videos on th... | Channel's uploads playlist id returning playlistNotFound | I am working on a project that gets the id of a channel's uploads playlist through their legacy username using the forUsername parameter with python3 and youtube-data-api. Here it searches for the uploads playlist string. From there, it gets the videos on their channel and the info I need.
When I try this for some chan... | [] | [] | [
"Correct me if i'm wrong, but the playlist you provided is not a valid one regardless? It does not exist. The playlist ID you provided is 24 characters, in contrast to the 32 character playlist IDs I found when going onto the Manchester United channel you described.\nFor example, https://www.youtube.com/playlist?li... | [
-1
] | [
"python",
"youtube_data_api"
] | stackoverflow_0074331394_python_youtube_data_api.txt |
Q:
How to verify passwords created by Django(make_password) without Django
I have used Django and handled password with make_password and check_password.
however, I get to change a framework to fastapi.
With fastapi, I need to verify passwords that are created by Django because I should use the same database with the... | How to verify passwords created by Django(make_password) without Django | I have used Django and handled password with make_password and check_password.
however, I get to change a framework to fastapi.
With fastapi, I need to verify passwords that are created by Django because I should use the same database with the data.
How can I handle the passwords in the way that is compatible with Djan... | [
"I have found passlib support Django compatible way.\nfrom django.contrib.auth.hashers import make_password\nfrom passlib.handlers.django import django_pbkdf2_sha256\n\npassword = 'testpassword123'\ndjango_hash = make_password(password) \nis_verified = django_pbkdf2_sha256.verify(password, django_hash)\n\nif is_v... | [
3,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0060810887_django_python.txt |
Q:
Why does this way of expressing how I want to print an index not work?
My main issue is with printing the index in the following situations.
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames)+1) + ' (or enter nothing to stop.):')
name = input()
if name == '':
break
... | Why does this way of expressing how I want to print an index not work? | My main issue is with printing the index in the following situations.
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames)+1) + ' (or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name]
print('The cat names are:')
for name in catNam... | [
"You're doing well here\nfor name in catNames:\n print(str(catNames.index(name)+1) + '. ' + name)\n\nYou're doing different here by using supplies[i]\nfor i in supplies:\n print('Index ' + str(supplies.index(i)+1) + 'in supplies is: ' + supplies[i])\n\nSolution\ndo the same as when it worked\nfor i in supplie... | [
2,
1,
1
] | [] | [] | [
"for_loop",
"list",
"python"
] | stackoverflow_0074334338_for_loop_list_python.txt |
Q:
extracting a substring from a column in pandas
I have a pandas dataframe:
#CHROM POS INFO
chr1 111 AC=0;AN=33
chr1 111 AC=0;AN=100
chr1 111 AC=110;AN=51
chr2 737 AC=99;AN=10003
chr2 888 AC=100;AN=1636
I want to create a new column which is based on the numbers in INFO column. T... | extracting a substring from a column in pandas | I have a pandas dataframe:
#CHROM POS INFO
chr1 111 AC=0;AN=33
chr1 111 AC=0;AN=100
chr1 111 AC=110;AN=51
chr2 737 AC=99;AN=10003
chr2 888 AC=100;AN=1636
I want to create a new column which is based on the numbers in INFO column. That is I want the numbers specified as AC=N. So the ... | [
"If you know that AC is first field, you can do\ndf['number'] = df.INFO.str.split(';').str[0].str.split('=').str[1].astype('int')\n\nOr, with regex, indepentendly of position\ndf['number'] = df.INFO.str.findall(r'AC=(\\d+)').str[0].astype(int)\n\nEDIT: rather than findall, we can\ndf['number'] = df.INFO.str.extract... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074335053_pandas_python.txt |
Q:
Trouble making a Simple video renderer with the python module Pygame
I need some help creating a video renderer in Pygame. It has a 48x36 display and has 3 colours. Black, white and grey. The data that goes into the project is in the form of a .txt file and each frame of the video in a line(as an example my video ... | Trouble making a Simple video renderer with the python module Pygame | I need some help creating a video renderer in Pygame. It has a 48x36 display and has 3 colours. Black, white and grey. The data that goes into the project is in the form of a .txt file and each frame of the video in a line(as an example my video uses 6567 frames so there are 6567 lines in the text file). To render the ... | [
"The reason why you can't see anything is because in Pygame, the origin (0, 0) of the screen is in the top left. The right side of the screen is where the x increases, and the bottom is where the y increases. So, the line:\nypos = ypos + -10\n\ndraws everything \"above\" the screen, hence invisible. You need to rem... | [
2
] | [] | [] | [
"audio",
"pygame",
"python",
"video"
] | stackoverflow_0074331689_audio_pygame_python_video.txt |
Q:
Is it possible to overload <> in python
I just came to know that you can overload operators in python using __add__ or __sub__ etc.
Even [] can be overloaded with __getitem__. So it is possibe to overload <> like load_text<"file.txt">.
A:
You can't overload an operator that doesn't exist, and since Python doesn'... | Is it possible to overload <> in python | I just came to know that you can overload operators in python using __add__ or __sub__ etc.
Even [] can be overloaded with __getitem__. So it is possibe to overload <> like load_text<"file.txt">.
| [
"You can't overload an operator that doesn't exist, and since Python doesn't have a bracketed call operator, you can't overload it. Sometimes you can do tricks like overloading < to return an object that has a > overload, but it won't work in this case because > is a binary operator, and you have nothing to put on... | [
1
] | [] | [] | [
"operator_overloading",
"python",
"python_3.x"
] | stackoverflow_0074334808_operator_overloading_python_python_3.x.txt |
Q:
How to add dictionary inside of an another dictionary in Python
I have been trying to add one of my dictionaries into another one. I did do that using the code below, but when I update one of the values, all off the values with the same name is also updated. How can I fix it?
Here is my code:
test_dict = {'count'... | How to add dictionary inside of an another dictionary in Python | I have been trying to add one of my dictionaries into another one. I did do that using the code below, but when I update one of the values, all off the values with the same name is also updated. How can I fix it?
Here is my code:
test_dict = {'count': 0}
D = {'emp1': {'name': test_dict, 'job': 'Mgr'},
'emp2': {'... | [
"In fact in your D dictionary the emp1, emp2 and emp3 all point to the same reference (a same object in memory).\nThat's the reason why, when you modify one of your inner dicts, you see the others as modified (in reality this is always the same and unique dict).\nYou have to make copies of the initial test_dict.\nf... | [
3,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074335071_dictionary_python.txt |
Q:
Selenium send_keys - method sends xpath( Python abnormal behavior )
I am working on a Tinder project and for that I would like to log in with google. I managed to hide from and I could log in with success, however when I use the send_keys method to send my email, it sends the xpath of the email input element along... | Selenium send_keys - method sends xpath( Python abnormal behavior ) | I am working on a Tinder project and for that I would like to log in with google. I managed to hide from and I could log in with success, however when I use the send_keys method to send my email, it sends the xpath of the email input element along side with the email( also it sends the wait method which is at the end o... | [
"So I used a JavaScript snippet and it solved the problem, however I still don't know what causes this.\nExample:\n\n\ndriver.execute_script('return document.getElementsByName(\"username\")[0].value')\n\n\n\n",
"Add\nimport time\n\nat beginning of your code.\nso that,\ntime.sleep(1000)\n\nworks as expected.\n"
] | [
1,
0
] | [] | [] | [
"authentication",
"google_chrome",
"python",
"selenium",
"sendkeys"
] | stackoverflow_0071293268_authentication_google_chrome_python_selenium_sendkeys.txt |
Q:
SQLAlchemy: Sublcass model without creating new table
In a Flask application we currently had to move some classes around and change the imports as well, but for backwards compatibility before we fix older modules we still need to be able to import them from the original place, but want to raise a warning whenever... | SQLAlchemy: Sublcass model without creating new table | In a Flask application we currently had to move some classes around and change the imports as well, but for backwards compatibility before we fix older modules we still need to be able to import them from the original place, but want to raise a warning whenever someone tries to use it.
Normally in python I would sublca... | [
"All that is needed was to add __abstract__ = True for SQLAlchemy to ignore the subclass\nfrom app.data import TableModel as NewTableModel\n\nclass TableModel(NewTableModel):\n __abstract__ = True\n warnings.warn('OldTableModel is deprecated, use NewTableModel instead', DeprecationWarning, stacklevel=2)\n\n"
... | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074334419_python_sqlalchemy.txt |
Q:
Dynamic list of valid str inputs for a Pydantic Field
I need to pass in a list of valid inputs to a field in Pydantic, but I don't know what that list will include until runtime (logged-in users, date range for next 7 days, etc).
Passing in multiple values for this field is valid (selecting 2 users who have logged... | Dynamic list of valid str inputs for a Pydantic Field | I need to pass in a list of valid inputs to a field in Pydantic, but I don't know what that list will include until runtime (logged-in users, date range for next 7 days, etc).
Passing in multiple values for this field is valid (selecting 2 users who have logged in is fine, but selecting 1 who hasn't is not).
Things I'v... | [
"Dynamic type annotations are a contradiction in terms. It is theoretically impossible to perform static type checks on annotations that are only defined at runtime. This is also the reason, why things like Literal only support, well, literals and not arbitrary variables, unpacking or function calls.\nFor this reas... | [
0
] | [] | [] | [
"list",
"literals",
"pydantic",
"python"
] | stackoverflow_0074327896_list_literals_pydantic_python.txt |
Q:
How to interact with google tab: Who's using chrome?
in my code I open chrome and the tab that opens first is the next: see picture.Google's who's using chrome tab
I would like to interact with it to use either of the profiles( which I prefer at the time )
I tried pyautogui, ActionChains and Controller from pynput... | How to interact with google tab: Who's using chrome? | in my code I open chrome and the tab that opens first is the next: see picture.Google's who's using chrome tab
I would like to interact with it to use either of the profiles( which I prefer at the time )
I tried pyautogui, ActionChains and Controller from pynput.keyboard to send keys( tab ) but it doesn't react for any... | [
"At that time the only solution I came up with is to precisely write code to move the cursor and click on the adequate 'button'.\n"
] | [
0
] | [] | [] | [
"google_chrome",
"python",
"selenium"
] | stackoverflow_0071436989_google_chrome_python_selenium.txt |
Q:
How can I limit the number of photos my aiogram bot sends
I am writing a bot on iogram and, as planned, it should receive photos from users and send them to my group. I have implemented this but for some reason my bot is sending multiple instances of the same photo. I'm guessing it's stuck at the await bot.send_ph... | How can I limit the number of photos my aiogram bot sends | I am writing a bot on iogram and, as planned, it should receive photos from users and send them to my group. I have implemented this but for some reason my bot is sending multiple instances of the same photo. I'm guessing it's stuck at the await bot.send_photo line, but I don't know how to fix it.
Here is a piece of co... | [
"I saw that you solved the problem, but I want to tell you and people who who will face this problem in the future that there is a Finite state machine in aiogram (you can read more in the documentation) with which you do not need to use nested functions. Also aiogram has a [BoundFilter][2] class, and with inherita... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074330284_python.txt |
Q:
fetching multiple vales and keys from dict
movies={
'actors':{'prabhas':{'knownAs':'Darling', 'awards':{'nandi':1, 'cinemaa':1, 'siima':1},'remuneration':100, 'hits':{'industry':2, 'super':3,'flops':8}, 'age':41, 'height':6.1, 'mStatus':'single','sRate':'35%'},
'pavan':{'knownAs':'Power Star', 'awards':{'nandi'... | fetching multiple vales and keys from dict | movies={
'actors':{'prabhas':{'knownAs':'Darling', 'awards':{'nandi':1, 'cinemaa':1, 'siima':1},'remuneration':100, 'hits':{'industry':2, 'super':3,'flops':8}, 'age':41, 'height':6.1, 'mStatus':'single','sRate':'35%'},
'pavan':{'knownAs':'Power Star', 'awards':{'nandi':2, 'cinemaa':2, 'siima':5}, 'hits':{'industry':... | [
"you can answer the first question with this:\nimport jmespath \n\nmovies={\n \"actors\": {\n \"prabhas\": {\n \"knownAs\": \"Darling\",\n \"awards\": {\n \"nandi\": 1,\n \"cinemaa\": 1,\n \"siima\": 1\n },\n \"remune... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074335035_python.txt |
Q:
Write an algorithm for the sequence
Calculate the n member of the sequence given by the formulas
a[2 * n] = a[n] + 1
a[2 * n + 2] = a[2 * n + 1] - a[n]
a[0] = a[1] = 1
n > 0
I've tried a lot of variants, but I can't find correct one.
n = int(input())
a = [0 for i in range(n + 3)]
a[0] = a[1] = 1
i = 1
while i... | Write an algorithm for the sequence | Calculate the n member of the sequence given by the formulas
a[2 * n] = a[n] + 1
a[2 * n + 2] = a[2 * n + 1] - a[n]
a[0] = a[1] = 1
n > 0
I've tried a lot of variants, but I can't find correct one.
n = int(input())
a = [0 for i in range(n + 3)]
a[0] = a[1] = 1
i = 1
while i * 2 + 2 < n + 3:
a[2 * i] = a[i] + 1... | [
"We should first compute the expected output for the first few numbers to let us have an idea what the sequence is like first,\na[0] = a[1] = 1\nSubstitute n = 1 in the first recurrence relation gives\na[2] = a[1] + 1 = 2\nSubstitute n = 1 in the second recurrence relation gives\na[4] = a[3] - a[1]\nBut a[4] = a[2]... | [
1,
0,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0074333668_algorithm_python.txt |
Q:
psycopg2.errors.UndefinedTable: relation "django_admin_log" does not exist
I just started learning Django, and I'm following a book as guide (the book is from August 2022, so new) and I ran into 2 problems.
The first one was that Python couldn't find the module psycopg2 which I then installed. Now I'm a little fur... | psycopg2.errors.UndefinedTable: relation "django_admin_log" does not exist | I just started learning Django, and I'm following a book as guide (the book is from August 2022, so new) and I ran into 2 problems.
The first one was that Python couldn't find the module psycopg2 which I then installed. Now I'm a little further and created my first model and migrated it to the database, which all seeme... | [
"I found the answer myself on https://www.pythonanywhere.com/forums/topic/14632/\nI first ran the command python manage.py migrate admin zero --fake, and then migrated again with python manage.py migrate, then ran the server and now the error is gone!\n"
] | [
0
] | [] | [] | [
"django",
"powershell",
"python",
"terminal",
"windows"
] | stackoverflow_0074335105_django_powershell_python_terminal_windows.txt |
Q:
Django3.2 connection OneToOneField on related_name object has no attribute 'all'
I have a problem getting data through related_name, it can't find the attribute all(). =(
The picture shows my attempts, but they did not lead to a result.
A:
It's so clear...You can't use all() cause it's only a field.
if you wan... | Django3.2 connection OneToOneField on related_name object has no attribute 'all' | I have a problem getting data through related_name, it can't find the attribute all(). =(
The picture shows my attempts, but they did not lead to a result.
| [
"It's so clear...You can't use all() cause it's only a field.\nif you want to access all() why you just do not do:\nAdvertisimentType.objects.all()\n\n?\n",
"I think @amir-mohammad-sedaghat-nia is right. You can do:\nAdvertisimentType.objects.all()\n\nbut, if you mean to retrieve all objects without specifying th... | [
0,
0
] | [] | [] | [
"attributeerror",
"database",
"django",
"orm",
"python"
] | stackoverflow_0074329994_attributeerror_database_django_orm_python.txt |
Q:
How to add an argument to a function in a python .bat file
I have a file with a function and a file that calls the functions. Finally, I run .bat
I don't know how I can add an argument when calling the .bat file. So that the argument was added to the function as below.
file_with_func.py
def some_func(val):
pri... | How to add an argument to a function in a python .bat file | I have a file with a function and a file that calls the functions. Finally, I run .bat
I don't know how I can add an argument when calling the .bat file. So that the argument was added to the function as below.
file_with_func.py
def some_func(val):
print(val)
run_bat.py
from bin.file_with_func import some_func
so... | [
"You can run it using arguments as input using the sys module\nWhen in you script you call\npython test.py var1 \n\nInside test.py in the first lines you must have\nimport sys\nprint(sys.argv[0]) # prints test\nprint(sys.argv[1]) # prints var1\n\n",
"In\n\\bin>.\\myBat.bat \"mystring\"\n\n\"mystring\" is a paramt... | [
0,
0
] | [] | [] | [
"batch_file",
"django",
"python",
"python_3.x",
"shell"
] | stackoverflow_0074335162_batch_file_django_python_python_3.x_shell.txt |
Q:
How is UTF-16 converting string?
b'\x14\xfeh\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00'
I understand that UTF-16 uses 16 bits but what confuses me the most is that 16 bits is two characters, so why do I see a long line of hexadecimal characters? It should be like for example "ee" these are 16 bits 8 b... | How is UTF-16 converting string? | b'\x14\xfeh\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00'
I understand that UTF-16 uses 16 bits but what confuses me the most is that 16 bits is two characters, so why do I see a long line of hexadecimal characters? It should be like for example "ee" these are 16 bits 8 bits in the character.
Can someone expl... | [
"Because of the notation, I guess you're using Python.\nIn Python, the b'...' notation is used for bytes objects.\nWhen str or bytes objects are represented in the source code or on the terminal, all characters that represent a printable ASCII character (roughly all values from 32 to 127), are shown as that charact... | [
1
] | [] | [] | [
"character_encoding",
"encoding",
"python",
"utf_16"
] | stackoverflow_0074262628_character_encoding_encoding_python_utf_16.txt |
Q:
Send Choices in Serilizer Django
models.py:
class Distributor(models.Model):
class ModeChoices(models.IntegerChoices):
physical = 1, _('physical')
digital = 2, _('digital')
class StatusChoices(models.IntegerChoices):
publish = 1, _('publish')
pending = 2, _('pending')
... | Send Choices in Serilizer Django | models.py:
class Distributor(models.Model):
class ModeChoices(models.IntegerChoices):
physical = 1, _('physical')
digital = 2, _('digital')
class StatusChoices(models.IntegerChoices):
publish = 1, _('publish')
pending = 2, _('pending')
dont_publish = 3, _('dont_publish')... | [
"There is no explict choices field here use instead\nclass Distributor(models.Model):\n class ModeChoices(models.IntegerChoices):\n choices= (\n (1, _('publish')),\n (2, _('digital')),\n )\n \n\n\n\nserializers.py\n modes = serializers.DictField(source=Distributor.ModeChoices.choices)... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074335251_django_django_rest_framework_python.txt |
Q:
Regular Expression: match word in a blank of a sentence
I have the following line:
I _ foo and _
I want to match anything (case insensitive) that matches the text and has a words that replace the underscores e. g.
I want foo and bar
I implemented foo and foo
i use Foo and bar
So in this case I want to get the who... | Regular Expression: match word in a blank of a sentence | I have the following line:
I _ foo and _
I want to match anything (case insensitive) that matches the text and has a words that replace the underscores e. g.
I want foo and bar
I implemented foo and foo
i use Foo and bar
So in this case I want to get the whole sentences back: ["I want foo and bar", "I implemented foo ... | [
"import re\n\nstrings = [\n \"I want foo and bar\",\n \"I implemented foo and foo\",\n \"i use Foo and bar\"\n]\n\nfor string in strings:\n fw, sw = re.search(r\"i (.+?) foo and (.+?)(?:\\s|$)\", string, flags=re.I).groups()\n print(\"first word:\", fw)\n print(\"second word:\", sw)\n\nWhere flags... | [
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074335226_python_string.txt |
Q:
Pytube Channel video_urls is does not working
I want to scrape a youtube channel with pytube Channel but I get an index error because I got zero URLs. Anything else is working well just video_urls is not working.
my code:
c = Channel("https://www.youtube.com/c/BuildEmpire")
print(f"This is a test number of video u... | Pytube Channel video_urls is does not working | I want to scrape a youtube channel with pytube Channel but I get an index error because I got zero URLs. Anything else is working well just video_urls is not working.
my code:
c = Channel("https://www.youtube.com/c/BuildEmpire")
print(f"This is a test number of video urls: {len(c.video_urls)}")
for url in c.video_urls... | [
"The reason why you don't retrieve any video is that it's just an issue on pytube end, as YouTube modified recently its user-interface (on which pytube relies), and this issue is currently being resolved.\nHowever as temporary a workaround installing pytube as following solves the problem:\npip install git+https://... | [
2
] | [] | [] | [
"python",
"pytube",
"youtube_channels"
] | stackoverflow_0074334535_python_pytube_youtube_channels.txt |
Q:
Getting error while trying to get CSS selector with Selenium?
New to programing in general so may not understand some terms but the question is I am getting errors when I use element = browser.find_element('CSS Code'). I Googled and it states that Selenuim, no longer uses it which I understand and then tried to us... | Getting error while trying to get CSS selector with Selenium? | New to programing in general so may not understand some terms but the question is I am getting errors when I use element = browser.find_element('CSS Code'). I Googled and it states that Selenuim, no longer uses it which I understand and then tried to use element = brower.find_element(By.css_selector after importing fro... | [
"Almost all of your mistakes are from improper spelling, and or incorrect method names. I suggest keeping the selenium documentation open and easily able to use it as a reference when writing code. When you fail to get it right the first time, it will save you alot of trouble to simply look up what you got wrong i... | [
0,
0
] | [] | [] | [
"python",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0073969057_python_selenium_chromedriver_selenium_webdriver.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.