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:
Error in Loop: "Cannot unpack non-iterable Timedelta object"
I'm in the process of learning Python, and I'm trying to make a simple loop, for adding dirty prices, to my dataframe bond_df.
Days_left is a Series, bond_df is a pandas dataframe containing the closing prices used in the formula below.
If i run the comm... | Error in Loop: "Cannot unpack non-iterable Timedelta object" | I'm in the process of learning Python, and I'm trying to make a simple loop, for adding dirty prices, to my dataframe bond_df.
Days_left is a Series, bond_df is a pandas dataframe containing the closing prices used in the formula below.
If i run the command:
days = days_left[1].days
I get an integer of size 1 with the... | [
"you can simplify by using pandas vectorized functionality:\nimport pandas as pd\n\nDAYS_IN_YEAR = 365 # this actually isn't constant; adjust as needed\n\ndf = pd.DataFrame(\n {\n \"days_left\": [pd.Timedelta(days=1), pd.Timedelta(days=2), pd.Timedelta(days=3)],\n \"closing_price\": [1, 2, 3],\n ... | [
1,
0,
0
] | [] | [] | [
"datetime",
"for_loop",
"pandas",
"python",
"timedelta"
] | stackoverflow_0074444688_datetime_for_loop_pandas_python_timedelta.txt |
Q:
Paho Python client version 1.6.1 and MQTTv5 ResponseTopic
I am using the mosquitto broker with the mqtt vcpkg C++ client.
I can use the v5 properties to publish messages with a reply topic.
When I tried with the Paho Python client, I had no reply topic in the message received on the C++ side.
I followed some guide... | Paho Python client version 1.6.1 and MQTTv5 ResponseTopic | I am using the mosquitto broker with the mqtt vcpkg C++ client.
I can use the v5 properties to publish messages with a reply topic.
When I tried with the Paho Python client, I had no reply topic in the message received on the C++ side.
I followed some guidelines here for the python side:
from paho.mqtt.properties impor... | [
"As mentioned in the comments, you need to pass the properties to the publish function not connect\nfrom paho.mqtt.properties import Properties\nfrom paho.mqtt.packettypes import PacketTypes\nfrom paho.mqtt.client import Client\n\nproperties=Properties(PacketTypes.PUBLISH)\nproperties.ResponseTopic=\"myreplies\"\nc... | [
3
] | [] | [] | [
"mosquitto",
"mqtt",
"paho",
"python"
] | stackoverflow_0074444226_mosquitto_mqtt_paho_python.txt |
Q:
Django Error: 'DetailView' object has no attribute '_meta'
This has floored me. I'm building a model with Django & REST API, and I'm having trouble rendering the DetailView for individual cars to the browser. The ListView works fine, but I'll include the code too since they are interlinked.
In particular, I can't ... | Django Error: 'DetailView' object has no attribute '_meta' | This has floored me. I'm building a model with Django & REST API, and I'm having trouble rendering the DetailView for individual cars to the browser. The ListView works fine, but I'll include the code too since they are interlinked.
In particular, I can't get the get_object() function to work properly.
Here's the first... | [
"Usually you should not implement the get() method yourself, this is usually the task of the Django (API) views that will then pass it to the right renderer and template.\nclass CarDetailView(generics.RetrieveAPIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'car-detail.html'\n serial... | [
3
] | [] | [] | [
"django",
"python",
"rest"
] | stackoverflow_0074444912_django_python_rest.txt |
Q:
Python: Merge two list of diferent objects by attribute
I'm trying to find an efficient way to merge two list of python objects (classes) with diferent structures and merge them into a new list of new object. The code:
from datetime import datetime
class StructureOne(object):
def __init__(self, date_time: dat... | Python: Merge two list of diferent objects by attribute | I'm trying to find an efficient way to merge two list of python objects (classes) with diferent structures and merge them into a new list of new object. The code:
from datetime import datetime
class StructureOne(object):
def __init__(self, date_time: datetime, name: str):
self.date_time: datetime = date_t... | [
"Assumptions:\n\nThe lists might not be sorted.\nThe date_time field is unique within each list.\nIt is okey if the output is sorted.\nYou want to populate the value of the objects in list_one with the value from the objects in list_two on matching date_time.\nYou only want to populate the value of an object in lis... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074444519_python.txt |
Q:
Access parent class attribute
I have the following code which works fine :
this is class parent order1
class order1:
def __init__(self, type: str, quantity: int) -> None:
self._type = type
self._quantity = quantity
self.members = []
def __str__(self) -> str:
return f'{self... | Access parent class attribute | I have the following code which works fine :
this is class parent order1
class order1:
def __init__(self, type: str, quantity: int) -> None:
self._type = type
self._quantity = quantity
self.members = []
def __str__(self) -> str:
return f'{self._type},{self._quantity}'
def ... | [
"Not exactly sure what you're asking because the question seems to be originally about one problem, but when writing your test code you got another problem that was already pointed out (indentation under your if __name__ == '__main__' block).\nBut you probably had a different question originally about inheritance, ... | [
0
] | [] | [] | [
"class",
"inheritance",
"oop",
"python"
] | stackoverflow_0074445115_class_inheritance_oop_python.txt |
Q:
Generate a histogram with counting in pandas
I have to make a mass histogram of animals with a dataframe on pandas. The goal is that on my x-axis, I have the different masses of my CSV file, and on my y-axis, I have the number of animals that have that mass. I am a beginner in this field and I need to make a simpl... | Generate a histogram with counting in pandas | I have to make a mass histogram of animals with a dataframe on pandas. The goal is that on my x-axis, I have the different masses of my CSV file, and on my y-axis, I have the number of animals that have that mass. I am a beginner in this field and I need to make a simple and understandable code
Here is my current code ... | [
"You could use directly the pandas.DataFrame.hist function.\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndf = pd.read_csv(\"S:\\Annee1\\ISD\\TP3\\PanTHERIA_1-0_WR05_Aug2008.txt\", sep=\"\\t\")\n\nax = plt.axes()\nmass_column = \"5-1_AdultBodyMass_g\"\ndf[(df[mass_column] < 1e4) & (df[mass_column] > 0)].... | [
2,
0
] | [] | [] | [
"histogram",
"matplotlib",
"numpy",
"pandas",
"python"
] | stackoverflow_0074442519_histogram_matplotlib_numpy_pandas_python.txt |
Q:
Sort pandas DataFrame rows by a list of (index) numbers
I have a pandas DataFrame with 229 rows. I have a list of index numbers ([47, 16, 59, ...]) and I want to re-sort the rows of my DataFrame into this order.
Details: I ran the DF through a filter (specifically, scipy.cluster.hierarchy.dendrogram, setting get_... | Sort pandas DataFrame rows by a list of (index) numbers | I have a pandas DataFrame with 229 rows. I have a list of index numbers ([47, 16, 59, ...]) and I want to re-sort the rows of my DataFrame into this order.
Details: I ran the DF through a filter (specifically, scipy.cluster.hierarchy.dendrogram, setting get_leaves=True). The return value includes a list of index numbe... | [
"Creating a new column, mapping your indexes to the correct rows and then performing a sort should be the easiest way to do this.\nI created some dummy data to provide an example;\ndf = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))\n\ndf\n A B C D\n0 8 27 2 9\n1 87 ... | [
1,
0,
0
] | [] | [] | [
"dendrogram",
"pandas",
"python",
"sorting"
] | stackoverflow_0060033760_dendrogram_pandas_python_sorting.txt |
Q:
Generate a new value everytime I call the variable
I'm tweaking faker, a module in python which generates random fake names address etc.
class us:
def __init__(self):
fake = Faker('en_US')
self.name = fake.name()
self.fname = fake.first_name()
self.lname = fake.last_name()
... | Generate a new value everytime I call the variable | I'm tweaking faker, a module in python which generates random fake names address etc.
class us:
def __init__(self):
fake = Faker('en_US')
self.name = fake.name()
self.fname = fake.first_name()
self.lname = fake.last_name()
self.street = fake.street_address()
self.city... | [
"Each call to faker.(whatever) generates a new value, so you should use properties instead:\nclass us:\n def __init__(self):\n self._faker = Faker('en_US')\n\n @property\n def name(self):\n return self._faker.name()\n\n # and so on...\n\nu = us()\n\nfor _ in range(5):\n print(u.name)\n\... | [
0
] | [] | [] | [
"faker",
"python"
] | stackoverflow_0074445281_faker_python.txt |
Q:
Is it possible to summarize or group every row with a specific column value? - python
Picture of my dataframe
Is it possible to summarize or group every country's info to something like a 'total info' row
This df is fluent, it will change each month and having a "quick access" view of how it looks will be very ben... | Is it possible to summarize or group every row with a specific column value? - python | Picture of my dataframe
Is it possible to summarize or group every country's info to something like a 'total info' row
This df is fluent, it will change each month and having a "quick access" view of how it looks will be very beneficial.
Take the picture as example: I would like to have Albania's (every county's) info ... | [
"import pandas as pd\n\n\ndf = pd.DataFrame(\n data=[\n ['Albania', 1, 10, 100, 0.1],\n ['Albania', 2, 20, 200, 0.2],\n ['Zambia', 3, 30, 300, 0.3],\n ['Zambia', 4, 40, 400, 0.4],\n [None, 5, 50, 500, 0.5],\n [None, 6, 60, 600, 0.6],\n ],\n columns=[\n 'ORIG... | [
0
] | [] | [] | [
"pandas",
"python",
"sum"
] | stackoverflow_0074445282_pandas_python_sum.txt |
Q:
scrape data from Instagram - errors while running Instascrape
I am trying to scrape post, and other information related to that post using instascrape. I am receiving an errors. So kindly help me out in this. If you know any other package that can do the same, kindly let me know.
from selenium.webdriver import Chr... | scrape data from Instagram - errors while running Instascrape | I am trying to scrape post, and other information related to that post using instascrape. I am receiving an errors. So kindly help me out in this. If you know any other package that can do the same, kindly let me know.
from selenium.webdriver import Chrome
from instascrape import Profile, scrape_posts
webdriver = Chro... | [
"The Python \"JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)\" occurs when we try to parse an invalid JSON string (e.g. single-quoted keys or values, or a trailing comma). Use the ast.literal_eval() method to solve the error.\nHere is a way to go about it\n\n"
] | [
0
] | [] | [] | [
"python",
"scrape"
] | stackoverflow_0074444684_python_scrape.txt |
Q:
How to write Arabic to a CSV file
I am trying to extract tweets with Python and store them in a CSV file, but I can't seem to include all languages. Arabic appears as special characters.
def recup_all_tweets(screen_name,api):
all_tweets = []
new_tweets = api.user_timeline(screen_name,count=300)
all_twe... | How to write Arabic to a CSV file | I am trying to extract tweets with Python and store them in a CSV file, but I can't seem to include all languages. Arabic appears as special characters.
def recup_all_tweets(screen_name,api):
all_tweets = []
new_tweets = api.user_timeline(screen_name,count=300)
all_tweets.extend(new_tweets)
#outtweets =... | [
"Example of writing both CSV and JSON:\n#coding:utf8\nimport csv\nimport json\n\ns = ['عربى','عربى','عربى']\n\nwith open('output.csv','w',encoding='utf-8-sig',newline='') as f:\n r = csv.writer(f)\n r.writerow(['header1','header2','header3'])\n r.writerow(s)\n\nwith open('output.json','w',encoding='utf8') ... | [
1,
0,
0
] | [] | [] | [
"csv",
"python",
"twitter"
] | stackoverflow_0062862779_csv_python_twitter.txt |
Q:
Is there a way to trick isinstance results for a class?
(Edited the title because the answer applies to any class, not just cython classes)
I am developing my extended types with a very tight restriction on performance, and I'm happy with the results.
I've found that for a type that is basically a float restricted... | Is there a way to trick isinstance results for a class? | (Edited the title because the answer applies to any class, not just cython classes)
I am developing my extended types with a very tight restriction on performance, and I'm happy with the results.
I've found that for a type that is basically a float restricted to 0 < value < 360 it's faster to not base on float, but to ... | [
"numbers.Complex is an abstract base class so has a register method that you can use to associate any Python type with it so that it returns True for isinstance.\nThe fact the class you want to register is a Cython cdef class doesn't matter at all\n"
] | [
2
] | [] | [] | [
"cython",
"pytest",
"python",
"subclass"
] | stackoverflow_0074438458_cython_pytest_python_subclass.txt |
Q:
Test that all endpoints have a certain header set in response
I have added a middleware to my flask rest api app to add a specific header to all responses, using the after_request() decorator. What would be a good way to ensure that all endpoints include this header? I have tests for every endpoint to test the sta... | Test that all endpoints have a certain header set in response | I have added a middleware to my flask rest api app to add a specific header to all responses, using the after_request() decorator. What would be a good way to ensure that all endpoints include this header? I have tests for every endpoint to test the status and data of the response. I could add an extra assert in every ... | [
"I think the best way is to create a separate test, calculate registered routes and check only header and response statutes. Here is an example:\n# app.py\nimport random\nfrom flask import Flask, jsonify\n\napp = Flask(__name__)\n\n\n# a few routes for demo\n@app.route('/user/<user_id>', methods=['GET'])\ndef get_u... | [
1
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074438897_flask_python.txt |
Q:
Ignoring Bash pipefail for error code 141
Setting the bash pipefail option (via set -o pipefail) allows the script to fail if a non-zero error is caught where there is a non-zero error in any step of a pipe.
However, we are running into SIGPIPE errors (error code 141), where data is written to a pipe that no longe... | Ignoring Bash pipefail for error code 141 | Setting the bash pipefail option (via set -o pipefail) allows the script to fail if a non-zero error is caught where there is a non-zero error in any step of a pipe.
However, we are running into SIGPIPE errors (error code 141), where data is written to a pipe that no longer exists.
Is there a way to set bash to ignore ... | [
"I handle this on a per-pipeline basis by tacking on an || if ... statement to swallow exit code 141 but generate exit code 1 for any other errors. (The original exit code that caused any non-141 failure is lost, as $? was changed by the test after the if.)\npipe | that | fails || if [[ $? -eq 141 ]]; then true; el... | [
22,
10,
7,
2,
0
] | [] | [] | [
"bash",
"error_handling",
"python",
"signals",
"sigpipe"
] | stackoverflow_0022464786_bash_error_handling_python_signals_sigpipe.txt |
Q:
Pandas to_datetime() not working with date comparison
I was querying a dataframe based on the InvoiceDate column and when I tried to extract all the rows for a particular date --> sales_data[sales_data["InvoiceDate"].dt.date == "2011-06-22"]. It returned an empty dataframe, which was not expected. Therefore, I tri... | Pandas to_datetime() not working with date comparison | I was querying a dataframe based on the InvoiceDate column and when I tried to extract all the rows for a particular date --> sales_data[sales_data["InvoiceDate"].dt.date == "2011-06-22"]. It returned an empty dataframe, which was not expected. Therefore, I tried running some experiments of my own as shown below:
impor... | [
"import pandas as pd\n\ndf = pd.DataFrame(\n [\n '2009-12-01 07:45:00',\n '2009-12-01 08:20',\n '2009-12-02 08:20',\n ],\n columns=['date'],\n)\ndf.date = df.date.map(pd.to_datetime)\n\nmy_date = pd.to_datetime('2009-12-01')\n\ndf[df.date.apply(lambda x: x.date() == my_date.date())]\n\... | [
0
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python"
] | stackoverflow_0074445061_dataframe_datetime_pandas_python.txt |
Q:
Getting XPATH Of Dropbox
Scenario: I want to automate: "https://www.dummyticket.com/dummy-ticket-for-visa-application/" , this page, I am able to interact with every web-element except a certain DropBox, where the XPATH is very difficult for me to find, I have tried many ways (using SelectorHub + Chropath) nothing... | Getting XPATH Of Dropbox | Scenario: I want to automate: "https://www.dummyticket.com/dummy-ticket-for-visa-application/" , this page, I am able to interact with every web-element except a certain DropBox, where the XPATH is very difficult for me to find, I have tried many ways (using SelectorHub + Chropath) nothing lets my code interact with th... | [
"That drop down is a special element called \"Select\".\nSelenium has special feature to select this Select options by index, by value or by visible text.\nHere I used the visible text approach.\nThe following code works:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom s... | [
2
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074445357_python_selenium_selenium_webdriver.txt |
Q:
How do I scrape data from the tag, if it is without 'id' or 'class', using BeautifulSoup?
I want to scrape the data from within the tag. The issue is, it has no 'id' or 'class', so how can I get the data inside this tag?
<span>
<span>2 in Amazon Launchpad (<a href="/-/en/gp/bestsellers/boost/ref=pd_zg_ts_boo... | How do I scrape data from the tag, if it is without 'id' or 'class', using BeautifulSoup? | I want to scrape the data from within the tag. The issue is, it has no 'id' or 'class', so how can I get the data inside this tag?
<span>
<span>2 in Amazon Launchpad (<a href="/-/en/gp/bestsellers/boost/ref=pd_zg_ts_boost">See Top 100 in Amazon Launchpad</a>)</span>
<br>
<span>1 in <a href="/-/en/gp/bestseller... | [
"Look at your HTML layout and detect the closest tag for your <span> (which has class or id) and then use the power of CSS Selectors.\nFor proper example, provide HTML snippet where <snap> is located with some other tags around.\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074445367_beautifulsoup_python_web_scraping.txt |
Q:
open cv python cant open video
import cv2
cap=cv2.VideoCapture(0)
filename="C://Users//deniz//Desktop//cfg13131lol.avi"
codec= cv2.VideoWriter_fourcc("W", "M", "V", "2")
frameRate=30
resolution=(600,600)
videoFileOutput=cv2.VideoWriter(filename, codec, frameRate, resolution)
while True:
red,frame=cap.read()
... | open cv python cant open video | import cv2
cap=cv2.VideoCapture(0)
filename="C://Users//deniz//Desktop//cfg13131lol.avi"
codec= cv2.VideoWriter_fourcc("W", "M", "V", "2")
frameRate=30
resolution=(600,600)
videoFileOutput=cv2.VideoWriter(filename, codec, frameRate, resolution)
while True:
red,frame=cap.read()
cv2.imshow("webcam.",frame)
fr... | [
"Where you writing frame inside the loop.?, Looks like you missed that line.inside the loop.\nvideoFileOutput.write(frame)\n\nAdd this line to inside the loop.\nimport cv2\ncap=cv2.VideoCapture(0)\nfilename=\"C://Users//deniz//Desktop//cfg13131lol.avi\"\ncodec= cv2.VideoWriter_fourcc(\"W\", \"M\", \"V\", \"2\")\nfr... | [
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074444532_opencv_python.txt |
Q:
How to extract a list of lists from a .txt file in python
I want to extract a list of lists from a .txt file. The data in the .txt file is given like this:
[[[12,34.2,54.1,46.3,12.2],[9.2,63,23.7,42.6,15.2]],
[[12,34.2,54.1,46.3,12.2],[9.2,63,23.7,42.6,15.2]],
[[12,34.2,54.1,46.3,12.2],[9.2,63,23.7,42.6,15.2]]... | How to extract a list of lists from a .txt file in python | I want to extract a list of lists from a .txt file. The data in the .txt file is given like this:
[[[12,34.2,54.1,46.3,12.2],[9.2,63,23.7,42.6,15.2]],
[[12,34.2,54.1,46.3,12.2],[9.2,63,23.7,42.6,15.2]],
[[12,34.2,54.1,46.3,12.2],[9.2,63,23.7,42.6,15.2]]]
I want to store it in a list like:
listA = [[[12,34.2,54.1,4... | [
"This is how you import a file\nhttps://docs.python.org/3/library/fileinput.html\nand this is how you parse it\nhttps://www.w3schools.com/python/python_json.asp\n",
"You can use literal_eval method from ast package to parse string representation of list:\nstr_list = '''[\n [\n [12,34.2,54.1,46.3,12.2],\n [... | [
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074445052_list_python.txt |
Q:
Using assert statements only through Microsoft Nutter to unit test raised exception in Databricks notebooks
I am using the MS Nutter framework to unit test python functions written in Databricks notebooks, https://github.com/microsoft/nutter.
One function raises a ValueError exception. How do I test for this corre... | Using assert statements only through Microsoft Nutter to unit test raised exception in Databricks notebooks | I am using the MS Nutter framework to unit test python functions written in Databricks notebooks, https://github.com/microsoft/nutter.
One function raises a ValueError exception. How do I test for this correctly via Nutter?
Nutter only seems to include assert commands, nothing like with pytest.raises(ValueError). Is th... | [
"Elaborating Fabrice answer (Hope it helps):\ndef assertion_valuerrorcheck():\n try:\n valueErrorFlag = False\n try:\n #code which raises value error\n except ValueError:\n valueErrorFlag = True\n assert(valueErrorFlag) #if True, case is passed\n except AssertionError:\n ... | [
1,
0
] | [] | [] | [
"databricks",
"python",
"unit_testing"
] | stackoverflow_0073405613_databricks_python_unit_testing.txt |
Q:
Not able to see double quote which is present inside a string ,when loading it from csv into a dataframe
Dataframe is skipping reading a double quote present inside a string when reading data from csv to pandas dataframe.
Suppose the data records present in my csv are as below.
name1|id|name2
"abc"|2|"def\"de"
"a... | Not able to see double quote which is present inside a string ,when loading it from csv into a dataframe | Dataframe is skipping reading a double quote present inside a string when reading data from csv to pandas dataframe.
Suppose the data records present in my csv are as below.
name1|id|name2
"abc"|2|"def\"de"
"abcd"|4|"def"de"
I'm using pipe symbol as separator while reading the csv file. Below is the code:
df = pd.rea... | [
"I think you need to define the escapechar in read_csv:\npd.read_csv('synthethic-data.csv', sep='|', escapechar='\\\\')\n\nOutput:\n name1 id name2\n0 abc 2 def\"de \n1 abcd 4 defde\"\n\nRegarding the last line (\"abcd\"|4|\"def\"de\"), the quoted part is actually \"def\", so you can't directly keep ... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074445592_dataframe_pandas_python.txt |
Q:
CryptoJS unpad issue
I am decrypting the encoded data fetched from API using CryptoJS data is coming from node js crypto-js in a string format.
Here is what I have tried
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad,unpad
make = make.json()['data']
key = "SecretPassphrase"
encryp... | CryptoJS unpad issue | I am decrypting the encoded data fetched from API using CryptoJS data is coming from node js crypto-js in a string format.
Here is what I have tried
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad,unpad
make = make.json()['data']
key = "SecretPassphrase"
encrypted_make = self.decrypt(ma... | [
"As per the discussion from the chat, we found out that the issue was not related to padding. Actually it is related to the decryption key.\nThe CryptoJS API considers the provided key as a pass phrase, not as a key. Thus, it processes it to create a key from it. When using that passphrase as the decryption key on ... | [
1
] | [] | [] | [
"cryptojs",
"python"
] | stackoverflow_0074412900_cryptojs_python.txt |
Q:
Site matching query does not exist
Python noob, as in this is my first project, so excuse my unfamiliarity.
The site was working very well until I clicked "log out" on my app. After that, the website would give me this error:
DoesNotExist at /login/
Site matching query does not exist.
I searched everywhere and the... | Site matching query does not exist | Python noob, as in this is my first project, so excuse my unfamiliarity.
The site was working very well until I clicked "log out" on my app. After that, the website would give me this error:
DoesNotExist at /login/
Site matching query does not exist.
I searched everywhere and the only solution I get relates to setting ... | [
"If you don't have a site defined in your database and django wants to reference it, you will need to create one. \nFrom a python manage.py shell :\nfrom django.contrib.sites.models import Site\nnew_site = Site.objects.create(domain='foo.com', name='foo.com')\nprint (new_site.id)\n\nNow set that site ID in your set... | [
164,
35,
9,
6,
5,
1,
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0011814059_django_python.txt |
Q:
How to download a file over HTTP?
I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes.
The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows .bat file ... | How to download a file over HTTP? | I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes.
The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows .bat file to download the actual MP3 file. I woul... | [
"One more, using urlretrieve:\nimport urllib.request\nurllib.request.urlretrieve(\"http://www.example.com/songs/mp3.mp3\", \"mp3.mp3\")\n\n(for Python 2 use import urllib and urllib.urlretrieve)\n",
"Use urllib.request.urlopen():\nimport urllib.request\nwith urllib.request.urlopen('http://www.example.com/') as f:... | [
1286,
541,
410,
168,
156,
46,
39,
26,
22,
21,
19,
17,
15,
10,
9,
5,
5,
5,
4,
4,
4,
3,
3,
3,
3,
0,
0,
0
] | [
"Another way is to call an external process such as curl.exe. Curl by default displays a progress bar, average download speed, time left, and more all formatted neatly in a table.\nPut curl.exe in the same directory as your script\nfrom subprocess import call\nurl = \"\"\ncall([\"curl\", {url}, '--output', \"song.m... | [
-2
] | [
"http",
"python",
"urllib"
] | stackoverflow_0000022676_http_python_urllib.txt |
Q:
Change value inside a dictionary with function
I want to change the value of x to 10 by using the table as an argument but it doesn't change value. I also don't want to modify arguments hence copy(). What do I need to do?
def change_x(table):
new_table = table.copy()
new_table['x'] = 10
def main():
ta... | Change value inside a dictionary with function | I want to change the value of x to 10 by using the table as an argument but it doesn't change value. I also don't want to modify arguments hence copy(). What do I need to do?
def change_x(table):
new_table = table.copy()
new_table['x'] = 10
def main():
table = {
'x': 8,
'y': 10
}
pr... | [
".copy() is a reference to the location where the value is stored and hence it does not change the value. You have to either get rid of the .copy() to change the value or you can return the new dictionary from the change_x function.\ndef change_x(table):\n table['x'] = 10\n\ndef main():\n table = {\n '... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074445692_python.txt |
Q:
Test python class with method calls in __init__
I have a class which calls a lot of its methods in __init__. Since a lot is going on in these methods, I want to test them. Testing classes and class methods requires to instantiate the class and then call its methods. But if I instantiate the class, the methods will... | Test python class with method calls in __init__ | I have a class which calls a lot of its methods in __init__. Since a lot is going on in these methods, I want to test them. Testing classes and class methods requires to instantiate the class and then call its methods. But if I instantiate the class, the methods will already be called before I can test it.
I have some ... | [
"It depends on what you would like to test\nIf you want to check if all the calls are happening correctly you could mock underlying functionality inside the __init__ method.\nAnd then do assert on the mocks. (Pytest has a spy mocks which does not modify original behavior but could be tested as mocks for call count,... | [
1
] | [] | [] | [
"class",
"python",
"unit_testing"
] | stackoverflow_0074445542_class_python_unit_testing.txt |
Q:
Longest Common Suffix from the listed words
Trying to reiterate backward the codes so as to find common suffix of the entered array of words say:
LongestCommonSuffix(['celebration', 'opinion', 'decision', 'revision'])
To get "ion" as output
This gives me the Longest Common Prefix BUT I need to change the loop to ... | Longest Common Suffix from the listed words | Trying to reiterate backward the codes so as to find common suffix of the entered array of words say:
LongestCommonSuffix(['celebration', 'opinion', 'decision', 'revision'])
To get "ion" as output
This gives me the Longest Common Prefix BUT I need to change the loop to do the same but from the end of each word in the ... | [
"You could create a variable common_suffix, make that equal to the first word, and then for each next word check if that word ends with that common suffix. If it doesn't, the common suffix is invalid, so try to shorten it until it does.\nIn code:\ndef LongestCommonSuffix(strs):\n common_suffix = strs[0]\n for... | [
0
] | [] | [] | [
"loops",
"python",
"suffix"
] | stackoverflow_0074414592_loops_python_suffix.txt |
Q:
Multiple objective functions with binary variables Google OR-tools
I have a set of U users and a set of S servers. I want to maximize the number of users allocated to a server while minimizing the number of servers used (this means that I have two objective functions).
Each user has some requirements w and each se... | Multiple objective functions with binary variables Google OR-tools | I have a set of U users and a set of S servers. I want to maximize the number of users allocated to a server while minimizing the number of servers used (this means that I have two objective functions).
Each user has some requirements w and each server has a total capacity of C.
The solver variables are the following:
... | [
"there are usually 2 approaches:\n\nweighted sum: a * obj1 + b * obj2\nlexicographic: optimize obj1, get optimal value, change objective to obj2, add constraint obj1 <= best_obj1_value (optional + slack). Then reoptimize. Bonus point when reusing the optimal solution with obj1 as a hint for the second solve.\n\n"
] | [
3
] | [] | [] | [
"constraint_programming",
"constraints",
"optimization",
"or_tools",
"python"
] | stackoverflow_0074444165_constraint_programming_constraints_optimization_or_tools_python.txt |
Q:
Set a column to one date format Pandas
I am filtering out records for last month data records, however when doing
emp_df = emp_df[emp_df['Date'].dt.month == (currentMonth-1)]
It neglects some records(treats some records months as days).Link to File
from datetime import datetime, date
import pandas as pd
import nu... | Set a column to one date format Pandas | I am filtering out records for last month data records, however when doing
emp_df = emp_df[emp_df['Date'].dt.month == (currentMonth-1)]
It neglects some records(treats some records months as days).Link to File
from datetime import datetime, date
import pandas as pd
import numpy as np
cholareport = pd.read_excel("D:/A... | [
"I am not entirely sure what you want to accomplish. If I understand it correctly, you simply want to count the number of entries per day for the past month. In such case, you can simply do the following.\nfrom datetime import datetime\n\nimport pandas as pd\n\nreport = pd.read_excel('report.xlsx')\n\nprint('day: c... | [
0
] | [] | [] | [
"dataframe",
"multiple_columns",
"numpy",
"pandas",
"python"
] | stackoverflow_0074444388_dataframe_multiple_columns_numpy_pandas_python.txt |
Q:
combine multiple column ,only return one value only with sum added for the value in year
df variable
HI Im new to programming dataframe in pandas. I encountered this problem where Im stuck trying to figure out how to join the country accordingly. Eg. in the dataset, I got 100+- column of 'Argentina' name and I w... | combine multiple column ,only return one value only with sum added for the value in year | df variable
HI Im new to programming dataframe in pandas. I encountered this problem where Im stuck trying to figure out how to join the country accordingly. Eg. in the dataset, I got 100+- column of 'Argentina' name and I wanted to produce only one column of Argentina with all value from the year of that country add... | [
"What about filtering the columns to aggregate based on their name (F followed by digit), then performing a groupby.sum:\ndf.filter(regex='F\\d+').groupby(df['Country']).sum()\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074445807_dataframe_pandas_python_python_3.x.txt |
Q:
Selection sort code is not outputting the right values
I am trying my hand at algorithms for the first time and tried to create a sequential sorting algorithm. I have come up with the code below.
def SelectionSort(my_list):
prev_num = None
counter = 0
new_list = []
index_num = 0
new_list_counte... | Selection sort code is not outputting the right values | I am trying my hand at algorithms for the first time and tried to create a sequential sorting algorithm. I have come up with the code below.
def SelectionSort(my_list):
prev_num = None
counter = 0
new_list = []
index_num = 0
new_list_counter = 0
for i in my_list:
if my_list.index(i) == 0... | [
"I am sure the logic of your code could be improved and simplified. But with a small change it's working, at least with your 4 test cases.\nMy solution is to save \"prev_num\" with the higest existing number in the list using max(). And only save this value at the end of each loop.\ndef SelectionSort(my_list):\n ... | [
0
] | [] | [] | [
"algorithm",
"list",
"python",
"sorting"
] | stackoverflow_0074444858_algorithm_list_python_sorting.txt |
Q:
Get current InvocationId or operation_Id
Is there a way to have one complete output log with custom_dimensions? I see in the monitor tab (of Azure Functions) that only messages with operation_Id and customDimensions['InvocationId'] are shown. Is there a way to add these two parameters all the log-messages from ope... | Get current InvocationId or operation_Id | Is there a way to have one complete output log with custom_dimensions? I see in the monitor tab (of Azure Functions) that only messages with operation_Id and customDimensions['InvocationId'] are shown. Is there a way to add these two parameters all the log-messages from opencensus?
I know you can use a second logger. B... | [
"After finding the right part in the documentation it was surprisingly easy:\ndef main(mytimer: func.TimerRequest, context: func.Context) -> None:\n try: \n invocation_id = context.invocation_id\n # Function continues here. \n\n except Exception as e:\n logging.error(\"Main program failed... | [
2,
0
] | [] | [] | [
"azure_functions",
"azure_monitoring",
"opencensus",
"python",
"python_logging"
] | stackoverflow_0064521460_azure_functions_azure_monitoring_opencensus_python_python_logging.txt |
Q:
Image compression with FFT causes patchy areas
I am trying to implement image compression using fft. I follow these steps:
Pad the height and weight of the input image to be powers of two (for easier DFT application)
For each of the red, green and blue channels:
Transform each row to its DFT
Transform each colum... | Image compression with FFT causes patchy areas | I am trying to implement image compression using fft. I follow these steps:
Pad the height and weight of the input image to be powers of two (for easier DFT application)
For each of the red, green and blue channels:
Transform each row to its DFT
Transform each column to its DFT
Turn the bottom CR% (compression rate) ... | [
"As was mentioned in the comments, I was converting to uint8 which cased small negatives to turn into large values and vice versa. Clipping at 0 and 255 after applying the inverse transform fixed the issue.\n"
] | [
0
] | [] | [] | [
"dft",
"fft",
"image_compression",
"image_processing",
"python"
] | stackoverflow_0074440211_dft_fft_image_compression_image_processing_python.txt |
Q:
pint-pandas import error ModuleNotFoundError: No module named 'pint.quantity' (pint is imported)
I am trying to use pint-pandas, but it errors on import with a ModuleNotFoundError: No module named 'pint.quantity'.
MRE from the pint-pandas github 'basic example' (because it errors on import pint_pandas, i call the ... | pint-pandas import error ModuleNotFoundError: No module named 'pint.quantity' (pint is imported) | I am trying to use pint-pandas, but it errors on import with a ModuleNotFoundError: No module named 'pint.quantity'.
MRE from the pint-pandas github 'basic example' (because it errors on import pint_pandas, i call the version numbers direct)
FWIW: pandas itself work fine. I work in Anaconda jupyter notebook, with packa... | [
"After flagging this issue to pint-pandas team on github, the issue was resolved and package now updated to 0.3. Thanks!\n"
] | [
0
] | [] | [] | [
"pint",
"python"
] | stackoverflow_0074411793_pint_python.txt |
Q:
Bar plot where y labels add up the more they appear and x labels group together if they have the same name?
I have a dataframe that looks identical to the one below, where each movie has an actor name and then a 1 or 0 depending if the actor is in the movie.
index
movie_title
actors
in_movie
1
Exodus
name1
0
1
... | Bar plot where y labels add up the more they appear and x labels group together if they have the same name? | I have a dataframe that looks identical to the one below, where each movie has an actor name and then a 1 or 0 depending if the actor is in the movie.
index
movie_title
actors
in_movie
1
Exodus
name1
0
1
Exodus
name2
1
2
Alien
name3
0
2
Alien
name4
0
3
Ghost
name5
1
3
Ghost
name6
1
3
Ghost
name7
1
... | [
"You can first use groupby.sum to get the count of actors in the movie:\ndf.groupby('movie_title')['in_movie'].sum().plot.bar()\n\nTo consider the possibility of duplicated actors within a movie:\n(df.groupby(['movie_title', 'actors'])['in_movie'].max()\n .groupby(level=0).sum().plot.bar()\n)\n\nOutput:\n\nIf you... | [
1
] | [] | [] | [
"bar_chart",
"dataframe",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074445963_bar_chart_dataframe_matplotlib_pandas_python.txt |
Q:
pip is a package and cannot be directly executed
Im trying to install google assistant on my Raspberry Pi, but when I keep getting an error: pip is a package and cannot be directly executed
A:
Instead of
pip [...]
Try doing
python -m pip [...]
Can't really help more without more info.
A:
I think your versio... | pip is a package and cannot be directly executed | Im trying to install google assistant on my Raspberry Pi, but when I keep getting an error: pip is a package and cannot be directly executed
| [
"Instead of \npip [...]\n\nTry doing\npython -m pip [...]\n\nCan't really help more without more info.\n",
"I think your version of pip is old. You need to upgrade it first, like this:\npip install -U pip\n\nYou may need to upgrade setuptools too:\npip install -U setuptools\n\nSince google-assistant-library is av... | [
1,
1,
0,
0
] | [] | [] | [
"pip",
"python",
"raspberry_pi"
] | stackoverflow_0046478020_pip_python_raspberry_pi.txt |
Q:
TCP server in a docker swarm Deployment and docker swarm load balancing
I am trying to understand how the docker swarm does the load balancing and how it effects the design of the socket server (since the server has to accept the client connection to get the socket object that it uses to return the result of the s... | TCP server in a docker swarm Deployment and docker swarm load balancing | I am trying to understand how the docker swarm does the load balancing and how it effects the design of the socket server (since the server has to accept the client connection to get the socket object that it uses to return the result of the service), to do this I created the following echo server:
# server.py
class Se... | [
"Docker swarm has, for this purpose, two load balancers:\nThe ingress load balancer is invoked when you publish a port from a service. That port is published from all swarm nodes, so any node can be used to connect to the service. And docker will round-robin connections to any available (healthy) service replicas.... | [
0
] | [] | [] | [
"docker",
"docker_swarm",
"python",
"sockets"
] | stackoverflow_0074445403_docker_docker_swarm_python_sockets.txt |
Q:
how to add sample excel or csv file to streamlit app?
I would like to add sample files, which are going to be available to download from streamlit app (as an example of correct file).
A:
found a solution:
with open('keywords.csv') as f:
st.download_button('Download CSV', f, 'keywords.xlsx')
https://docs.str... | how to add sample excel or csv file to streamlit app? | I would like to add sample files, which are going to be available to download from streamlit app (as an example of correct file).
| [
"found a solution:\nwith open('keywords.csv') as f:\n st.download_button('Download CSV', f, 'keywords.xlsx')\n\nhttps://docs.streamlit.io/knowledge-base/using-streamlit/how-download-file-streamlit\n"
] | [
0
] | [] | [] | [
"python",
"streamlit"
] | stackoverflow_0074445928_python_streamlit.txt |
Q:
Value at a given index in a NumPy array depends on values at higher indexes in another NumPy array
I have two 1D NumPy arrays x = [x[0], x[1], ..., x[n-1]] and y = [y[0], y[1], ..., y[n-1]]. The array x is known, and I need to determine the values for array y. For every index in np.arange(n), the value of y[index]... | Value at a given index in a NumPy array depends on values at higher indexes in another NumPy array | I have two 1D NumPy arrays x = [x[0], x[1], ..., x[n-1]] and y = [y[0], y[1], ..., y[n-1]]. The array x is known, and I need to determine the values for array y. For every index in np.arange(n), the value of y[index] depends on x[index] and on x[index + 1: ]. My code is this:
import numpy as np
n = 5
q = 0.5
x = np.ar... | [
"\nRandomly generate the array y with the full shape.\nGenerate a bool array indicating where to set zeros.\nUse np.where to set zeros.\n\nTry this,\nimport numpy as np\n\nn = 5\nq = 0.5\nx = np.array([1, 2, 0, 1, 0])\n\ny = np.random.choice([0, 1], n, p=(1-q, q))\ncondition = (x != 0) & (x[::-1].cumprod() == 0)[::... | [
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074445129_arrays_numpy_python.txt |
Q:
Getting percent sign to show up in pie chart
So this is probably a very basic question but I can't find an answer to it anywhere.
I'm trying to create some pie charts and I've managed to get them looking how I want to for the most part but when it comes to getting the percent sign to show up inside the pie slices ... | Getting percent sign to show up in pie chart | So this is probably a very basic question but I can't find an answer to it anywhere.
I'm trying to create some pie charts and I've managed to get them looking how I want to for the most part but when it comes to getting the percent sign to show up inside the pie slices themselves I just can't get it to work.
As I under... | [
"I just ran this little block:\nplt.pie([30, 25], autopct='%.1f%%')\n\nAnd it gave me this:\n\nSo I don't think your issue is in the plt.pie() or autopct='%.1f%%'\n",
"I had success with escaping the second '%':\n...,autopct='%.1f\\%%',...\n\n"
] | [
0,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0072166012_matplotlib_python.txt |
Q:
Python - How to Remove (Delete) Unclosed Tags
looking for a way to remove open unpaired tags!
BS4 as well as lxml are good at removing unpaired closed tags.
But if they find an open tag, they try to close it, and close it at the very end :(
Example
from bs4 import BeautifulSoup
import lxml.html
codeblock = '<stro... | Python - How to Remove (Delete) Unclosed Tags | looking for a way to remove open unpaired tags!
BS4 as well as lxml are good at removing unpaired closed tags.
But if they find an open tag, they try to close it, and close it at the very end :(
Example
from bs4 import BeautifulSoup
import lxml.html
codeblock = '<strong>Good</strong> Some text and bad closed strong </... | [
"Maybe the solution can be .unwrap() the second <strong> tag:\ncodeblock = \"<strong>Good</strong> Some text and bad closed strong </strong> Some text and bad open strong PROBLEM HERE <strong> Some text <h2>Some</h2> or <h3>Some</h3> <p>Some Some text <strong>Good2</strong></p>\"\n\nsoup = BeautifulSoup(codeblock, ... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"lxml",
"python"
] | stackoverflow_0074444370_beautifulsoup_lxml_python.txt |
Q:
Dash Pandas Generate descriptive statistics Table
I have a dataset which is similar to below one. Please note that there are multiple values for a single ID.
import pandas as pd
import numpy as np
import random
df = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-05 23:00:00',freq='h'),
... | Dash Pandas Generate descriptive statistics Table | I have a dataset which is similar to below one. Please note that there are multiple values for a single ID.
import pandas as pd
import numpy as np
import random
df = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-05 23:00:00',freq='h'),
'Line1':[random.uniform(110, 160) for n in rang... | [
"It is displayed by resetting the index of the data frame.\nimport pandas as pd\nimport numpy as np\nimport random\n\ndf = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-05 23:00:00',freq='h'),\n 'Line1':[random.uniform(110, 160) for n in range(120)],\n 'Line2':[r... | [
2
] | [] | [] | [
"pandas",
"plotly",
"plotly_dash",
"python"
] | stackoverflow_0074444277_pandas_plotly_plotly_dash_python.txt |
Q:
How can I efficiently concatenate images in a Tensorflow dataset?
I currently have sixteen images (A,B,C,D,E,F,G,...) which must be concatenated into one as part of a Tensorflow Dataset workflow. Each image is 128 x 128 and has the shape of (128, 128, 3). The final output should be a 512 x 512 image of shape (512,... | How can I efficiently concatenate images in a Tensorflow dataset? | I currently have sixteen images (A,B,C,D,E,F,G,...) which must be concatenated into one as part of a Tensorflow Dataset workflow. Each image is 128 x 128 and has the shape of (128, 128, 3). The final output should be a 512 x 512 image of shape (512,512,3). All of the images come from an image sequence, known as img_seq... | [
"You can improve it about 3 times using something like this:\ndef glue_answer(imgs_seq):\n image = tf.reshape(imgs_seq, (4, 4, 128, 128, 3))\n image = tf.concat(image, axis=1)\n image = tf.concat(image, axis=1)\n \n return image\n\nI tested the performance as follows:\ndef glue_to_one(imgs_seq):\n ... | [
0,
0,
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074418158_python_tensorflow.txt |
Q:
How to create a grey image in python?
I tried to create a grey 3x3 pixel image in python, however the result is always a black image with several coloured pixels.
What I tried:
import numpy as np
from PIL import Image
greyimg = np.array([[[128]*3]*3]*3)
print(greyimg)
Image.fromarray(greyimg, 'RGB').save("test_gr... | How to create a grey image in python? | I tried to create a grey 3x3 pixel image in python, however the result is always a black image with several coloured pixels.
What I tried:
import numpy as np
from PIL import Image
greyimg = np.array([[[128]*3]*3]*3)
print(greyimg)
Image.fromarray(greyimg, 'RGB').save("test_grey.png")
What I expected:
a grey 3x3 image... | [
"import numpy as np\nfrom PIL import Image\nimport cv2\n\ngreyimg = np.array([[[128]*3]*3]*3,dtype=np.uint8)\nprint(greyimg)\nImage.fromarray(greyimg, 'RGB').save(\"test_grey.png\")\n\n"
] | [
1
] | [] | [] | [
"numpy",
"python",
"python_imaging_library"
] | stackoverflow_0074446069_numpy_python_python_imaging_library.txt |
Q:
How to find the index for the second minimum number in a list?
I have a list with 2 minimum numbers and I am trying to get the index of the minimum number 33 at index [5], but my loop stops at [0] once it's found the min. Unsure how to get the get last index value.
rain_data = [33, 57, 60, 55, 53, 33]
min... | How to find the index for the second minimum number in a list? | I have a list with 2 minimum numbers and I am trying to get the index of the minimum number 33 at index [5], but my loop stops at [0] once it's found the min. Unsure how to get the get last index value.
rain_data = [33, 57, 60, 55, 53, 33]
min_value = rain_data[0]
min_index = 0
def minimum(rain_data)
... | [
"As noted in comment the question can be interpreted in different ways.\nposition of the LAST minimum\nrain_data = [33, 57, 60, 55, 53, 33]\n\nmin_value = rain_data[0]\nlast_min_pos = 0\nfor i, x in enumerate(rain_data):\n if x <= min_value:\n min_value = x\n last_min_pos = i\n\nOutput: 5\nposition... | [
0,
0,
0
] | [] | [] | [
"indexing",
"list",
"loops",
"python"
] | stackoverflow_0074446175_indexing_list_loops_python.txt |
Q:
How to show the fruit name with the cost of fruit in a list?
I try to show the names of fruit with the cost of the fruit in a list.
So I have it like this:
import re
verdi50="[' \n\na)\n\n \n\nFactuur\nVerdi Import Schoolfruit\nFactuur nr. : 71201 Koopliedenweg 33\nDeb. nr. : 108636 2991 LN BARENDRECHT\nYour VAT ... | How to show the fruit name with the cost of fruit in a list? | I try to show the names of fruit with the cost of the fruit in a list.
So I have it like this:
import re
verdi50="[' \n\na)\n\n \n\nFactuur\nVerdi Import Schoolfruit\nFactuur nr. : 71201 Koopliedenweg 33\nDeb. nr. : 108636 2991 LN BARENDRECHT\nYour VAT nr. : NL851703884B01 Nederland\nFactuur datum : 10-12-21\nAantal O... | [
"The issue is with the verdi_total_fruit_cost_regex() function, you have added the fruit name to the non-capturing group(?:), so it won't be captured as part of the regex capture group.\nEven though you are doing OR(|) across fruit names, you have a single regex pattern and not multiple ones.\nUpdated the two marke... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074445932_python.txt |
Q:
Error in Writing Google Sheets using Pandas
I have 2 data frames, df1 is user completion of courses, df2 is user information. I have combined them and reshaped using the following codes.
# merge and use unstack to reshape the data
df1=df1.merge(df2, on='User ID', how='left')
df1 = df1.set_index(['User ... | Error in Writing Google Sheets using Pandas | I have 2 data frames, df1 is user completion of courses, df2 is user information. I have combined them and reshaped using the following codes.
# merge and use unstack to reshape the data
df1=df1.merge(df2, on='User ID', how='left')
df1 = df1.set_index(['User ID', 'Name', 'Course Name']).unstack().reset_inde... | [
"Since the error occured at the first line carrying NaN values, try to fill in those with empty strings.\nReplace this:\ndf_data = df1.to_numpy().tolist()\n\nBy this :\ndf_data = df1.fillna(\"\").to_numpy().tolist()\n\n"
] | [
0
] | [] | [] | [
"google_colaboratory",
"google_sheets_api",
"pandas",
"python"
] | stackoverflow_0074446167_google_colaboratory_google_sheets_api_pandas_python.txt |
Q:
Post data (dictionary list) with python requests
I'd like to post my dictionary list below via python's http requests.
my_data=[
{
'kl':'ngt',
'schemas':
[
{
'date':'14-12-2022',
'name':'kolo'
}
],
},
{
'kl':'mlk',
'schemas':
[
... | Post data (dictionary list) with python requests | I'd like to post my dictionary list below via python's http requests.
my_data=[
{
'kl':'ngt',
'schemas':
[
{
'date':'14-12-2022',
'name':'kolo'
}
],
},
{
'kl':'mlk',
'schemas':
[
{
'date':'23-10-2022',
'nam... | [
"I think when you want to send json payload in post request you should add headers argument:\nheaders = {'Content-Type': 'application/json', 'Accept':'application/json'}\n\nr = requests.post(url = 'http://myapi.com/product', data = my_data, headers=headers)\n\nresponse_result = r.text\n\nthen check response status ... | [
1
] | [] | [] | [
"django",
"python",
"python_requests"
] | stackoverflow_0074446096_django_python_python_requests.txt |
Q:
How can i modify cv2.selectROI image display to normal when my image is too big for the screen?
cv2.selectROI display my image but it's too big for the screen and i can't navigate on the image because it's automatically starting the crop procedure.
can anyone tell me how to adjust the function?
cv2.namedWindow('im... | How can i modify cv2.selectROI image display to normal when my image is too big for the screen? | cv2.selectROI display my image but it's too big for the screen and i can't navigate on the image because it's automatically starting the crop procedure.
can anyone tell me how to adjust the function?
cv2.namedWindow('image', cv2.WINDOW_NORMAL) before cv2.selectROI does not help.
Thank you
| [
"I was wondering the same.\nIf your IDE allows you to check the definitions of the selectROI function you should see something like this :\nCV_EXPORTS_W Rect selectROI(const String& windowName, InputArray img, bool showCrosshair = true, bool fromCenter = false);\n\nA function which is overloaded with this definitio... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0053912404_python.txt |
Q:
How to identify discrete events based on a time difference of more than 30 minutes in python
The problem is exactly the same as listed here albeit in python not R. What is the best solution to handle this in python?
Unclear what to proceed with next. It seems there is some way to get tidyverse in python but I am ... | How to identify discrete events based on a time difference of more than 30 minutes in python | The problem is exactly the same as listed here albeit in python not R. What is the best solution to handle this in python?
Unclear what to proceed with next. It seems there is some way to get tidyverse in python but I am wondering if there is a way to do this with standard python packages?
Thanks
See issue from other ... | [
"If data.txt is:\n2017-10-02 19:23:27 JB12 A69-1601-47272\n2017-10-02 19:26:48 JB12 A69-1601-47272\n2017-10-02 19:27:23 JB12 A69-1601-47272\n2017-10-02 19:31:46 JB12 A69-1601-47272\n2017-10-02 23:52:15 JB12 A69-1601-47272\n2017-10-02 23:53:26 JB12 A69-1601-47272\n2017-10-02 23:55:13 JB12 A69-16... | [
0,
0
] | [] | [] | [
"pandas",
"python",
"time_series"
] | stackoverflow_0074445365_pandas_python_time_series.txt |
Q:
extracting days from a numpy.timedelta64 value
I am using pandas/python and I have two date time series s1 and s2, that have been generated using the 'to_datetime' function on a field of the df containing dates/times.
When I subtract s1 from s2
s3 = s2 - s1
I get a series, s3, of type
timedelta64[ns]
0 385... | extracting days from a numpy.timedelta64 value | I am using pandas/python and I have two date time series s1 and s2, that have been generated using the 'to_datetime' function on a field of the df containing dates/times.
When I subtract s1 from s2
s3 = s2 - s1
I get a series, s3, of type
timedelta64[ns]
0 385 days, 04:10:36
1 57 days, 22:54:00
2 642 day... | [
"You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day.\n>>> x = np.timedelta64(2069211000000000, 'ns')\n>>> days = x.astype('timedelta64[D]')\n>>> days / np.timedelta64(1, 'D')\n23\n\nOr, as @PhillipCloud suggested, just days.astype(i... | [
184,
63,
9,
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0018215317_numpy_pandas_python.txt |
Q:
Why Ursina collider doesn't work properly?
I create an object:
class Tube(Entity):
def __init__(self, position):
super().__init__(
model = 'quad',
color = color.white,
position = position,
scale = Vec2(0.6,6),
collider = 'box'
and a ball obje... | Why Ursina collider doesn't work properly? | I create an object:
class Tube(Entity):
def __init__(self, position):
super().__init__(
model = 'quad',
color = color.white,
position = position,
scale = Vec2(0.6,6),
collider = 'box'
and a ball object:
class Ball(Entity):
def __init__(self, color... | [
"It seems you were having some problems with the intersection.\nI will comment in code where the problem was:\nfrom ursina import *\nfrom ursina.prefabs import *\n\napp = Ursina()\n\nEditorCamera()\n\n\n\nground = Entity(model='plane', scale = 30, collider='plane')\n\nbird = Entity(model = 'circle',\n color ... | [
1
] | [] | [] | [
"python",
"ursina"
] | stackoverflow_0074429879_python_ursina.txt |
Q:
How to convert time stamp in Python from dd/mm/yy hh:mm:ss:msmsms to yyyy-mm-dd hh:mm:ss:msmsmsmsmsms
I have created an automated data client that pulls data from a txt file and inputs it into a csv file. Each data entry contains a timestamp, but it is not in the format I need it in, I need it to match the datetim... | How to convert time stamp in Python from dd/mm/yy hh:mm:ss:msmsms to yyyy-mm-dd hh:mm:ss:msmsmsmsmsms | I have created an automated data client that pulls data from a txt file and inputs it into a csv file. Each data entry contains a timestamp, but it is not in the format I need it in, I need it to match the datetime.now() format:
ORIGINAL FORMAT [03/11/22 01:06:09:190]
DESIRED FORMAT 2022-11-03 01:06:09.190000
I am curr... | [
"The square brackets mean it is a list. You can get rid of them by selecting the first item in the list:\nprint(timestamp[0])\n\nAs for the date conversions, use the built-in datetime package\n",
"Looks like timestamp is a list, to access the string try timestamp[0]\nAnd you can convert the string to your desired... | [
0,
0
] | [] | [] | [
"date",
"date_conversion",
"python",
"timestamp",
"variables"
] | stackoverflow_0074446240_date_date_conversion_python_timestamp_variables.txt |
Q:
How to resolve AmbiguousForeignKeysError because of multiple foreign keys
I have two model Users & PatientDetails
class Users(Base):
__tablename__ = "users"
__table_args__ = (
Index("email", "email", unique=True),
Index("mobile_number", "mobile_number", unique=True),
)
id = Column(... | How to resolve AmbiguousForeignKeysError because of multiple foreign keys | I have two model Users & PatientDetails
class Users(Base):
__tablename__ = "users"
__table_args__ = (
Index("email", "email", unique=True),
Index("mobile_number", "mobile_number", unique=True),
)
id = Column(String(36), primary_key=True)
first_name = Column(String(20), nullable=Fals... | [
"Relationship should understand what exactly FK are you trying to use\n patient_basic_details_id = Column(ForeignKey(\"users.id\"), nullable=False)\n patient_basic_details = relationship(\"User\", foreign_keys=patient_basic_details_id)\n provider_basic_details_id = Column(ForeignKey(\"users.id\"), nullable... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074446280_python_sqlalchemy.txt |
Q:
What is y axis in seaborn distplot?
I have some geometrically distributed data. When I want to take a look at it, I use
sns.distplot(data, kde=False, norm_hist=True, bins=100)
which results is a picture:
However, bins heights don't add up to 1, which means y axis doesn't show probability, it's something differen... | What is y axis in seaborn distplot? | I have some geometrically distributed data. When I want to take a look at it, I use
sns.distplot(data, kde=False, norm_hist=True, bins=100)
which results is a picture:
However, bins heights don't add up to 1, which means y axis doesn't show probability, it's something different. If instead we use
weights = np.ones_li... | [
"From the documentation:\n\nnorm_hist : bool, optional\nIf True, the histogram height shows a density rather than a count. This is implied if a KDE or fitted density is plotted.\n\nSo you need to take into account your bin width as well, i.e. compute the area under the curve and not just the sum of the bin heights.... | [
33,
25,
0
] | [] | [] | [
"matplotlib",
"python",
"seaborn"
] | stackoverflow_0051666784_matplotlib_python_seaborn.txt |
Q:
I meet a problem when I am trying to convert a large amount json files into csv
I have to convert json files as I said, here is the code:enter image description here
def AnalysisJson():
file_path = 'my_file'
for root,dirs,files in os.walk(file_path):
for file in files:
... | I meet a problem when I am trying to convert a large amount json files into csv | I have to convert json files as I said, here is the code:enter image description here
def AnalysisJson():
file_path = 'my_file'
for root,dirs,files in os.walk(file_path):
for file in files:
InputPath = open(file_path + '\\'+ file, encoding="utf-8")
... | [
"I am not sure that I understand correctly what you want, but here is an answer based on my interpretation of your question.\nimport json\nimport os\nfrom glob import glob\n\nimport pandas as pd\n\n\ndef json_to_csv(dir_path: str) -> None:\n for file_path in glob(os.path.join(dir_path, '*.json')):\n with ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074445812_pandas_python.txt |
Q:
Finding first and last index of some value in a list in Python
Is there any built-in methods that are part of lists that would give me the first and last index of some value, like:
verts.IndexOf(12.345)
verts.LastIndexOf(12.345)
A:
Sequences have a method index(value) which returns index of first occurrence - in... | Finding first and last index of some value in a list in Python | Is there any built-in methods that are part of lists that would give me the first and last index of some value, like:
verts.IndexOf(12.345)
verts.LastIndexOf(12.345)
| [
"Sequences have a method index(value) which returns index of first occurrence - in your case this would be verts.index(value). \nYou can run it on verts[::-1] to find out the last index. Here, this would be len(verts) - 1 - verts[::-1].index(value)\n",
"If you are searching for the index of the last occurrence of... | [
151,
31,
27,
12,
6,
1,
0,
0,
0
] | [] | [] | [
"list",
"python",
"search"
] | stackoverflow_0000522372_list_python_search.txt |
Q:
Why does fitting my tensorflow model return a value error?
I am following along with a tutorial, and I am building a simple regression model with tensorflow. I would expect tf to fit the model without any hiccups. Instead, I am getting a value error.
The model and compile steps look identical to the tutorial.
The ... | Why does fitting my tensorflow model return a value error? | I am following along with a tutorial, and I am building a simple regression model with tensorflow. I would expect tf to fit the model without any hiccups. Instead, I am getting a value error.
The model and compile steps look identical to the tutorial.
The data is similar (two numpy arrays). I used different numbers in ... | [
"You are missing the feature dimension necessary for the Dense layer, since your model is inferring the input shape based on the data that you feed, so try:\nimport tensorflow as tf\nimport numpy as np\n\nX = tf.constant(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))[:, None]\ny = tf.constant(np.array([1, 4, 7, 10, ... | [
1,
0
] | [
"You should try this code...\nX = tf.constant(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))\ny = tf.constant(np.array([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31]))\n\nmodel = tf.keras.Sequential([\n tf.keras.layers.Dense(1)\n])\n\nmodel.compile(\n loss=tf.keras.losses.mae,\n optimizer=tf.keras.optimizers.SGD... | [
-1
] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074445537_keras_python_tensorflow.txt |
Q:
Generate smoke/genie shape randomly in Python
I want to produce shapes like these in Python:
# # # # #
# #
# #
# #
#
#
# # # # #
# # #
# #
#
#
#
#
x items scattered across a grid height × width randomly, with a greater probability to appear in the to... | Generate smoke/genie shape randomly in Python | I want to produce shapes like these in Python:
# # # # #
# #
# #
# #
#
#
# # # # #
# # #
# #
#
#
#
#
x items scattered across a grid height × width randomly, with a greater probability to appear in the topmost rows, and most likely to be near but offset ... | [
"I had a play and came up with the following code:\nimport numpy as np\n\ndef smokey_motif(rows: int, cols: int) -> str:\n # convolution used for next row\n # a bit of smoothing and edge detection seems good\n conv = np.array([1, 2, 0, 2, 1])\n # generating rows in reverse order, starting with\n # a ... | [
1
] | [] | [] | [
"python",
"random"
] | stackoverflow_0074436559_python_random.txt |
Q:
PYTHON, basics - Class. Why missing 3 required positional arguments here?
I am starting to practice OOP, and I am not sure what is problem here.
Why, when I type (using input()) 3 arguments I get error.
Should i change something?
class Person:
def __init__(self, name, surname, email):
self.name = name... | PYTHON, basics - Class. Why missing 3 required positional arguments here? | I am starting to practice OOP, and I am not sure what is problem here.
Why, when I type (using input()) 3 arguments I get error.
Should i change something?
class Person:
def __init__(self, name, surname, email):
self.name = name
self.surname = surname
self.email = email
def list_of_peo... | [
"You are calling your function list_of_people(), but you are not giving it any arguments. But the definition of this function awaits a name, a surname and an email.\nYou should do something like this instead:\nper1.list_of_people(\"your_name\", \"your_surname\", \"your_email\")\n\nBut if you wish to add your Person... | [
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0074446478_class_python.txt |
Q:
Add dictionary if key value is empty using python
I have a dictionary with missing values (the key is there, but the associated value is empty). For example I want the dictionary below:
dct = {'ID': '', 'gender': 'male', 'age': '20', 'weight': '', 'height': '5.7'}
to be changed to this form:
dct = {'ID': {'link':... | Add dictionary if key value is empty using python | I have a dictionary with missing values (the key is there, but the associated value is empty). For example I want the dictionary below:
dct = {'ID': '', 'gender': 'male', 'age': '20', 'weight': '', 'height': '5.7'}
to be changed to this form:
dct = {'ID': {'link': '','value': ''}, 'gender': 'male', 'age': '20', 'weigh... | [
"You can iterate through the list and see if the value is an empty string('') if it is, replace it with the default value. Here's a small snippet which does it -\ndct = {'ID':'', 'gender':'male', 'age':'20', 'weight':'', 'height':'5.7'}\n\ndef update(d, default):\n for k, v in d.items():\n if v == '':\n ... | [
0,
0
] | [] | [] | [
"default",
"defaultifempty",
"dictionary",
"python"
] | stackoverflow_0074446227_default_defaultifempty_dictionary_python.txt |
Q:
Joining the dataframe to its implicit column
Input table
input data frame
it contains four columns [ id , route , provider , zipcode ]
->id is the unique value
-> route is a driver location which gets updated over period of time and it looks like this
[{'latitude': '40.45591',
'longitude': '-79.94219',
'upda... | Joining the dataframe to its implicit column | Input table
input data frame
it contains four columns [ id , route , provider , zipcode ]
->id is the unique value
-> route is a driver location which gets updated over period of time and it looks like this
[{'latitude': '40.45591',
'longitude': '-79.94219',
'updatedAt': 1667735101102},
{'latitude': '40.47023',... | [
"solution\nYou can resolve this issue by below code :\nimport pandas as pd\norder_df = pd.read_csv('route-table-main/route_table.csv')\nmain_df = pd.DataFrame()\n\nID=order_df.to_dict(orient='list')['_ID']\nROUTE= order_df.to_dict(orient='list')['ROUTE']\n\nfor order_id,Route in zip(ID,ROUTE):\n ROUTE_LIST = eva... | [
0
] | [] | [] | [
"dataframe",
"inner_join",
"pandas",
"python"
] | stackoverflow_0074446256_dataframe_inner_join_pandas_python.txt |
Q:
wxPython : Change label of "Browse" button in wxFilePickerCtrl object
I'm using wxPython 4.2.0 for python 3.10.8 through wxFormBuilder and I can't find a way to change the label of the "Browse" button of my wxFilePicker object. I want to change this label because my application's language is not English and I'd li... | wxPython : Change label of "Browse" button in wxFilePickerCtrl object | I'm using wxPython 4.2.0 for python 3.10.8 through wxFormBuilder and I can't find a way to change the label of the "Browse" button of my wxFilePicker object. I want to change this label because my application's language is not English and I'd like to have language coherency over the whole interface and to avoid confusi... | [
"I can't test this, as I use Linux, which uses a bitmap rather than a Browse button but I assume that once you have created the filepickerctrl you can simply adjust the values, as follows:\nself.fp_ctrl = wx.FilePickerCtrl(self.panel, wx.ID_ANY, message=\"Choose a file\")\nself.fp_ctrl.SetLabel(\"MyLabel\")\nself.f... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0074445427_python_wxpython.txt |
Q:
Reading image from xlsx python won't work - I/O operation on closed file
I'm trying to read an image from a xlsx cell, should be simples but it keep raising errors.
import openpyxl
from openpyxl_image_loader import SheetImageLoader
filename = 'media/planilhas/tabela_de_simulador.xlsx'
workbook = openpyxl.load_wor... | Reading image from xlsx python won't work - I/O operation on closed file | I'm trying to read an image from a xlsx cell, should be simples but it keep raising errors.
import openpyxl
from openpyxl_image_loader import SheetImageLoader
filename = 'media/planilhas/tabela_de_simulador.xlsx'
workbook = openpyxl.load_workbook(filename)
logos = workbook['operadoras']
image_loader = SheetImageLoad... | [
"The problem is in your excel file. Your image is out of cell boundaries. Make sure that the pictures are within the cell boundaries!\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0073624416_python.txt |
Q:
How to end a program when the line ends in a period character?
How do I end a program that reads an input line by line and it ends when there's a period (whitespace doesn't matter)?
For example:
input = "HI
bye
."
the program should end after it reaches the period.
I tried doing two things:... | How to end a program when the line ends in a period character? | How do I end a program that reads an input line by line and it ends when there's a period (whitespace doesn't matter)?
For example:
input = "HI
bye
."
the program should end after it reaches the period.
I tried doing two things:
if line == ".":
break
if "." in line:
break
but the first... | [
"You need .strip() to remove whitespaces and check the ending character with .endswith():\nfor line in f:\n if line.strip().endswith(\".\"):\n terminate...\n\n",
"if line.replace(\" \", \"\")[-1] == \".\":\n break\n\n.replace(\" \", \"\") removes all white-spaces, and [-1] takes the last character of... | [
2,
2,
0,
0
] | [
"If you want to end the string at the exact dot, you can try this:\ninput = '''HI\n bye\n .\n hello\n bye'''\n\nindex = input.find('.') # gets the index of the dot\n\nprint(input[:index+1])\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074437830_python.txt |
Q:
How to send a http2 request headers with python socket
In python:
the http/1.1 request header is :
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
request_header = 'GET {} HTTP/1.1\r\nhost: {}\r\nConnection: close\r\n' \
'Accept-Encoding: gzip,deflate\r\n\r\n'.format(path, host)
s = s.send(reques... | How to send a http2 request headers with python socket | In python:
the http/1.1 request header is :
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
request_header = 'GET {} HTTP/1.1\r\nhost: {}\r\nConnection: close\r\n' \
'Accept-Encoding: gzip,deflate\r\n\r\n'.format(path, host)
s = s.send(request_header.encode())
In my question is , what does the http/... | [
"Well if you are interested in stable implementation you could take a look at h2. They have an example on plain sockets. If you are interested in educational purposes poke around with tcpdump / wireshark (wshrk http2 wiki page). So you can read how the actual communication looks like in a propper tool, and implemen... | [
0
] | [] | [] | [
"http2",
"http_1.1",
"python",
"sockets"
] | stackoverflow_0074446460_http2_http_1.1_python_sockets.txt |
Q:
pandas pivot table on multiple columns
INPUT TABLE
pcd
INCOME
Education
age1to_20
TG
a1001
INCOME_1
Education_1
1
1
a1003
INCOME_2
Education_2
0
2
a1001
INCOME_3
Education_2
5
2
a1002
INCOME_2
Education_2
1
5
a1003
INCOME_1
Education_2
3
4
REQUIRED OUTPUT
pcd
INCOME_1
INCOME_2
INCOME_3
Education_1
Educatio... | pandas pivot table on multiple columns | INPUT TABLE
pcd
INCOME
Education
age1to_20
TG
a1001
INCOME_1
Education_1
1
1
a1003
INCOME_2
Education_2
0
2
a1001
INCOME_3
Education_2
5
2
a1002
INCOME_2
Education_2
1
5
a1003
INCOME_1
Education_2
3
4
REQUIRED OUTPUT
pcd
INCOME_1
INCOME_2
INCOME_3
Education_1
Education_2
age1to_20
TG
a1001
1... | [
"You can first melt, then pivot_table to reshape, and finally groupby.agg to combine the 'pcd':\nagg_funcs = {'TG': 'mean', 'pcd': 'first'}\n\nout = (df\n .melt(['pcd', 'age1to_20', 'TG'])\n .assign(v=1)\n .pivot_table(index=['pcd', 'age1to_20', 'TG'], columns='value',\n values='v', fill_value=... | [
2,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074446444_pandas_python.txt |
Q:
install pip on python 3.7 ubuntu
I am working on ubuntu, I have python 3.8 as standard installation.
However as my project have dependency on python 3.7 I have installed 3.7 and removed 3.8
now when I am trying to install pip it is installing python3.8 again and getting installed with 3.8.
I am using apt-get -y in... | install pip on python 3.7 ubuntu | I am working on ubuntu, I have python 3.8 as standard installation.
However as my project have dependency on python 3.7 I have installed 3.7 and removed 3.8
now when I am trying to install pip it is installing python3.8 again and getting installed with 3.8.
I am using apt-get -y install pip to install pip.
I want to in... | [
"\nmy project have dependency on python 3.7\n\nThis is where virtual environments really useful. The idea is that you create an environment in which the required version of python and packages can live without altering the installation of python you might want to keep installed for other projects.\nThere are a few ... | [
0
] | [] | [] | [
"pip",
"python",
"ubuntu"
] | stackoverflow_0074445485_pip_python_ubuntu.txt |
Q:
Error when using python-kaleido from R to convert plotly graph to static image
I am trying to use the R reticulate package to convert a plotly graph to a static image. I am using save_image/kaleido.
Link to documentation for save_image / kaleido
Initial setup:
install.packages("reticulate")
reticulate::install_min... | Error when using python-kaleido from R to convert plotly graph to static image | I am trying to use the R reticulate package to convert a plotly graph to a static image. I am using save_image/kaleido.
Link to documentation for save_image / kaleido
Initial setup:
install.packages("reticulate")
reticulate::install_miniconda()
reticulate::conda_install('r-reticulate-test', 'python-kaleido')
reticulate... | [
"As @Salim B pointed out there is a workaround documented to call import sys in Python before executing save_img():\np <- plot_ly(x = 1:10)\nreticulate::py_run_string(\"import sys\")\nsave_image(p, \"./pic.png\")\n\n"
] | [
1
] | [] | [] | [
"plotly",
"python",
"r",
"reticulate"
] | stackoverflow_0073604954_plotly_python_r_reticulate.txt |
Q:
Aggregating and plotting multiple columns using matplotlib
I've got data in a pandas dataframe that looks like this:
ID A B C D
100 0 1 0 1
101 1 1 0 1
102 0 0 0 1
...
The idea is to create a barchart plot that shows the total of each (sum of the total number of A's, B... | Aggregating and plotting multiple columns using matplotlib | I've got data in a pandas dataframe that looks like this:
ID A B C D
100 0 1 0 1
101 1 1 0 1
102 0 0 0 1
...
The idea is to create a barchart plot that shows the total of each (sum of the total number of A's, B's, etc.). Something like:
X
X X
x X X
A B C D
T... | [
"Set 'ID' aside, sum, and plot.bar:\ndf.set_index('ID').sum().plot.bar()\n\n# or\ndf.drop(columns=['ID']).sum().plot.bar()\n\noutput:\n\njust for fun\nprint(df.drop(columns='ID')\n .replace({0: ' ', 1: 'X'})\n .apply(sorted, reverse=True)\n .to_string(index=False)\n )\n\nOutput:\nA B C D\nX... | [
4
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074446793_matplotlib_pandas_python.txt |
Q:
CRSError: Invalid projection: epsg:4326: for geopandas
I am using anaconda for geopandas.
However, everytime I try to use epsg:4326:, it gives an error.
CRSError: Invalid projection: epsg:4326: (Internal Proj Error: proj_create: SQLite error on SELECT name, type, coordinate_system_auth_name, coordinate_system_code... | CRSError: Invalid projection: epsg:4326: for geopandas | I am using anaconda for geopandas.
However, everytime I try to use epsg:4326:, it gives an error.
CRSError: Invalid projection: epsg:4326: (Internal Proj Error: proj_create: SQLite error on SELECT name, type, coordinate_system_auth_name, coordinate_system_code, datum_auth_name, datum_code, area_of_use_auth_name, area_o... | [
"I had the same problem. After a bit of a research I found out that anaconda will have a specific directory for geopandas and once it looks for pyproj there it won't find because in my case it was installed with pip as it was an ordeal to install geopandas in Windows(I usually work with Linux). The solution was rem... | [
2,
1,
1,
0,
0
] | [
"conda create -n pyproj\nconda activate pyproj\nconda config --add channels conda-forge\nconda config --set channel_priority strict\nconda install pyproj\nupdate: answer (y)\nconda deactivate\nconda env remove -n pyproj\n"
] | [
-1
] | [
"epsg",
"geopandas",
"python"
] | stackoverflow_0066425565_epsg_geopandas_python.txt |
Q:
pip install within ArcPro 2.9.1 produces 'C:\Program' is not recognized as an internal or external command error, how can I change the install dir?
I am attempting to install xlsxwriter module in my ArcPro 2.9.1. I receive an error that the directory is not recognized as an internal or external commmand.
pip insta... | pip install within ArcPro 2.9.1 produces 'C:\Program' is not recognized as an internal or external command error, how can I change the install dir? | I am attempting to install xlsxwriter module in my ArcPro 2.9.1. I receive an error that the directory is not recognized as an internal or external commmand.
pip install xlsxwriter
"'C:\Program' is not recognized as an internal or external command,
operable program or batch file."
This seems it is happening due to the... | [
"If you feel like it's issue with windows path. If you want alternate solution until you fix path issue then you can install modules like this.Try this let me know if it works.\nimport os\nos.system(\"pip install xlsxwriter\")\n\n"
] | [
1
] | [] | [] | [
"arcgis",
"python"
] | stackoverflow_0074446828_arcgis_python.txt |
Q:
How to apply if condition to two different columns and put the result to a new column
I have a data frame df2 and want to generate a new column called 'tag' based on a if logic on two existing columns.
import pandas as pd
df2 = pd.DataFrame({'NOTES': ["PREPAID_HOME_SCREEN_MAMO","SCREEN_MAMO",
... | How to apply if condition to two different columns and put the result to a new column | I have a data frame df2 and want to generate a new column called 'tag' based on a if logic on two existing columns.
import pandas as pd
df2 = pd.DataFrame({'NOTES': ["PREPAID_HOME_SCREEN_MAMO","SCREEN_MAMO",
"> Unable to connect internet>4G Compatible>Set",
"N... | [
"The problem is that you are trying to assign a value with if-statement, which causes the syntax error.\nThere are many ways to do this, I provide one using pandas.DataFrame.apply.\ntrans_fn = lambda row: \"Yes\" if row['col_1']=='data' && row['col_2'] else \"No\"\ndf2['tag'] = df2.apply(trans_fn, axis=1) # apply t... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074446218_dataframe_pandas_python.txt |
Q:
Combining list of lists based on value in python
The topic was raised due to dealing with some graph problems. So I'm receiving information about graph structure via stdin and input looks like this:
Number of Edges
ID of NodeN1 Id of NodeN2
ID of NodeN3 Id of NodeN4
ID of NodeN5 Id of NodeNn
...
The first line... | Combining list of lists based on value in python | The topic was raised due to dealing with some graph problems. So I'm receiving information about graph structure via stdin and input looks like this:
Number of Edges
ID of NodeN1 Id of NodeN2
ID of NodeN3 Id of NodeN4
ID of NodeN5 Id of NodeNn
...
The first line represents amount of edges in graph, the other lines ... | [
"There may be built-in methods for this in the networkx package, but you can also do it manually like this:\ninputList = [3, [0, 1], [0, 2], [1, 2]]\n\nnumNodes = inputList[0]\nedges = inputList[1:]\nmega_lst = []\nfor node in range(numNodes):\n connectedNodes = []\n for edge in edges:\n if node in edg... | [
2,
1
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0074446398_networkx_python.txt |
Q:
How I get model data without primary key
I'm having trouble updating the data I get from my database. When I want to update directly from my model object, I get this error
arg = {k: v for k, v in kv_generator(self, arg.items())}
AttributeError: 'NoteORM' object has no attribute 'items'.
How do I get the data of ... | How I get model data without primary key | I'm having trouble updating the data I get from my database. When I want to update directly from my model object, I get this error
arg = {k: v for k, v in kv_generator(self, arg.items())}
AttributeError: 'NoteORM' object has no attribute 'items'.
How do I get the data of my model excluding the primary key?
class Note... | [
"\nhow can i update via object, is there a better way?\n\nSQLAlchemy's Session.merge() method takes care of the details for you:\nfrom sqlalchemy import Column, Integer, String, create_engine\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.orm import Session, declarative_base\n\nengine = create_engine(\... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074442418_python_sqlalchemy.txt |
Q:
Using A-Weighting on time signal
Im trying to solve this for a couple of weeks now but it seems like Im not able to wrap my head around this. The task is pretty simple: Im getting a signal in voltage from a microfone and in the end I want to know how loud in dB(A) it is out there.
There are so many problems I dont... | Using A-Weighting on time signal | Im trying to solve this for a couple of weeks now but it seems like Im not able to wrap my head around this. The task is pretty simple: Im getting a signal in voltage from a microfone and in the end I want to know how loud in dB(A) it is out there.
There are so many problems I dont even know where to start. Lets begin ... | [
"To give you a short answer. This task can be done in only a few steps, utilizing the waveform_analysis package and Parseval's theorem.\nThe most simple implementation I can come up with is:\n\nTime domain A-weighting filtering the signal - Using this library -\n\nimport waveform_analysis\nweighted_signal = wavefor... | [
2,
1
] | [] | [] | [
"acoustics",
"python",
"scipy"
] | stackoverflow_0065842795_acoustics_python_scipy.txt |
Q:
my login code prints for each line in the text file im using instead of just printing one output for succesful or unsuccesful login
my code:
userlog = input("What is your username?")
passlog = input("What is your password?")
for fileread in open("accounts.txt", "r").readlines():
file = fileread.split()
if ... | my login code prints for each line in the text file im using instead of just printing one output for succesful or unsuccesful login | my code:
userlog = input("What is your username?")
passlog = input("What is your password?")
for fileread in open("accounts.txt", "r").readlines():
file = fileread.split()
if userlog == file[0] and passlog == file[1]:
print("Succesfully logged in")
elif userlog != file[0] and passlog != file[1]:
... | [
"One addition you can have is to break the loop when the login is successful:\nuserlog = input(\"What is your username?\")\npasslog = input(\"What is your password?\")\nfor fileread in open(\"accounts.txt\", \"r\").readlines():\n file = fileread.split()\n if userlog == file[0] and passlog == file[1]:\n ... | [
0,
0
] | [] | [] | [
"authentication",
"python"
] | stackoverflow_0074446081_authentication_python.txt |
Q:
How to make a new line in a list of objects where the self instance is present in Python?
I am trying to print out a list holding objects and their attributes where every element in the list is printed in a new line. However, I don't know how or where to add '\n' when appending the object.
client_manager.py
class ... | How to make a new line in a list of objects where the self instance is present in Python? | I am trying to print out a list holding objects and their attributes where every element in the list is printed in a new line. However, I don't know how or where to add '\n' when appending the object.
client_manager.py
class ClientManager:
# Constructor for the client list
def __init__(self):
self.__cli... | [
"You could simply iterate on your self.__client_list attribute:\ndef print_client_list(self):\n for client in self.__client_list:\n print(client.__dict__)\n\nOutputs:\n{'first_name': 'John', 'last_name': 'Smith', 'title': 'Mr', 'preferred_pronouns': 'He/him', 'date_of_birth': '06/08/2003', 'occupation': '... | [
0,
0
] | [] | [] | [
"newline",
"python"
] | stackoverflow_0074446788_newline_python.txt |
Q:
Solving multiple LPs in SCIP
I need to implement benders decomposition from scratch in pyscipopt. I solve a master problem LP, then solve a subproblem, which gives a violated constraint for the master problem. I add that constraint and this loop continues till I find the optimal solution.
In pyscipopt, I use model... | Solving multiple LPs in SCIP | I need to implement benders decomposition from scratch in pyscipopt. I solve a master problem LP, then solve a subproblem, which gives a violated constraint for the master problem. I add that constraint and this loop continues till I find the optimal solution.
In pyscipopt, I use model.freeTransform() and then add the ... | [
"May I ask why you are reimplementing a benders decomposition from scratch? Are you aware that there is both a readily usable Benders Implementation as well as a way to add plugins for a custom benders implementation available in SCIP? And it seems to me that this is also avaible in PySCIPopt. Even if your approach... | [
0
] | [] | [] | [
"optimization",
"python",
"scip"
] | stackoverflow_0074348862_optimization_python_scip.txt |
Q:
Bicubic interpolation Python
I have developed Bicubic interpolation for demonstration to some undergraduate students using Python Programming language.
The methodology is as explained in wikipedia,
The code is working fine except the results I am getting are slightly different than what is obtained when using sc... | Bicubic interpolation Python | I have developed Bicubic interpolation for demonstration to some undergraduate students using Python Programming language.
The methodology is as explained in wikipedia,
The code is working fine except the results I am getting are slightly different than what is obtained when using scipy library.
The interpolation co... | [
"Not sure why Wikipedia implementation is not working as expected. Probably, the reason is that these values might be approximated in a different way than what is explained in their site. \npx00 = (f12 - f10)/2*deltax\npx01 = (f22 - f20)/2*deltax \npx10 = (f13 - f11)/2*deltax \npx11 = (f23 - f21)/2*deltax\n\npy00 =... | [
11,
2,
1,
1
] | [] | [] | [
"interpolation",
"numpy",
"python",
"scipy",
"sympy"
] | stackoverflow_0052700878_interpolation_numpy_python_scipy_sympy.txt |
Q:
Discord python bot intents
If the solution is obvious, bare with me I haven't coded in more than 3 months. It seems to be an issue with intents, yes I tried searching up the issue. Hit a wall there (this happened when I tried to start up my dpy bot), The error that I keep getting!
import datetime
import traceback
... | Discord python bot intents | If the solution is obvious, bare with me I haven't coded in more than 3 months. It seems to be an issue with intents, yes I tried searching up the issue. Hit a wall there (this happened when I tried to start up my dpy bot), The error that I keep getting!
import datetime
import traceback
import math
from datetime import... | [
"If want to enable the default intents you can do so like this,\nintents = discord.Intents.default()\nintents.message_content = True\nintents.members = True\nclient = commands.Bot(command_prefix='!',\n case_insensitive=True,\n owner_ids=(Id place holder1, id placeholder2),\... | [
1
] | [] | [] | [
"bots",
"discord",
"discord.py",
"python"
] | stackoverflow_0074446942_bots_discord_discord.py_python.txt |
Q:
Change Data Structure of an array (new ID and replace Duplicates in loop)
I'm new in the "python game", so maybe the following question is for some of you very easy to answer:
I have an array like this:
store=([9,4,5],[9,4,1],[1,2,3],[9,4,1],[3,7,5],[2,4,1])
I want to "loop" the array and creat a new structure:
... | Change Data Structure of an array (new ID and replace Duplicates in loop) | I'm new in the "python game", so maybe the following question is for some of you very easy to answer:
I have an array like this:
store=([9,4,5],[9,4,1],[1,2,3],[9,4,1],[3,7,5],[2,4,1])
I want to "loop" the array and creat a new structure:
store_new=([0,1,2],[0,1,3],[3,4,5],[0,1,3],[5,6,2],[4,1,3])
The first value s... | [
"You can use itertools.count and dict.setdefault in a list comprehension:\nstore=([9,4,5],[9,4,1],[1,2,3],[9,4,1],[3,7,5],[2,4,1])\n\nfrom itertools import count\n\nd = {}\nc = count()\nout = tuple([d[x] if x in d else d.setdefault(x, next(c)) for x in l]\n for l in store)\n\nOutput:\n([0, 1, 2], [0, 1, ... | [
1
] | [] | [] | [
"arrays",
"duplicates",
"python"
] | stackoverflow_0074447021_arrays_duplicates_python.txt |
Q:
How to append a list of dictionary inside of a dictionary
I have an issue that I am scratching my head over.
I have dictionary as follow:
my_dict = {'key': ['string', [{'id': 'id_value', 'number' : 'number_value'}]]}
and in the processing of this dictionary I wanted to append the list at the end.
However, when I ... | How to append a list of dictionary inside of a dictionary | I have an issue that I am scratching my head over.
I have dictionary as follow:
my_dict = {'key': ['string', [{'id': 'id_value', 'number' : 'number_value'}]]}
and in the processing of this dictionary I wanted to append the list at the end.
However, when I do
my_dict['key'][1].append({'id2': 'id_value2', 'number2' : 'n... | [
"to append new key value pair in dictionary use below code\nmy_dict['id2'].append('id_value2')\nmy_dict['number2'].append('number_value2')\n\n"
] | [
0
] | [] | [] | [
"append",
"dictionary",
"list",
"mypy",
"python"
] | stackoverflow_0074447015_append_dictionary_list_mypy_python.txt |
Q:
Python Convert Windows File path in a variable
Given is a variable that contains a windows file path. I have to then go and read this file. The problem here is that the path contains escape characters, and I can't seem to get rid of it. I checked os.path and pathlib, but all expect the correct text formatting alre... | Python Convert Windows File path in a variable | Given is a variable that contains a windows file path. I have to then go and read this file. The problem here is that the path contains escape characters, and I can't seem to get rid of it. I checked os.path and pathlib, but all expect the correct text formatting already, which I can't seem to construct.
For example th... | [
"You can use os.path.abspath() to convert it:\nprint(os.path.abspath(\"P:\\python\\t\\temp.txt\"))\n\n>>> P:/python/t/temp.txt\n\nSee the documentation of os.path here.\n",
"I've solved it.\nThe issues lies with the python interpreter. \\t and all the others don't exist as such data, but are interpretations of no... | [
7,
3,
2,
1,
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0052593420_python_python_3.x.txt |
Q:
Redis Subscriber/Publisher with Python and Node.js
I have a basic Web API written in Node.js that writes an object as an HSET to a Redis cache. Both are running in docker containers.
I have a Python script running on the same VM which needs to watch the Redis cache and then run some code when there is a new HSET ... | Redis Subscriber/Publisher with Python and Node.js | I have a basic Web API written in Node.js that writes an object as an HSET to a Redis cache. Both are running in docker containers.
I have a Python script running on the same VM which needs to watch the Redis cache and then run some code when there is a new HSET or a change to a field in the HSET.
I came across Redis ... | [
"\nThis doesn't seem like the right way to do this but Redis watch doesn't support HSET.\n\nRedis WATCH does support hash keys - while it does not support hash fields.\n\nIs there a better way to accomplish this?\n\nWhile I believe your approach may be acceptable for certain scenarios, pub/sub messages are fire-and... | [
1,
1
] | [] | [] | [
"node.js",
"python",
"redis"
] | stackoverflow_0074439665_node.js_python_redis.txt |
Q:
What does (x < y) | (x > z) do?
def my_function(x,y,z):
out = True
if(x < y) | (x > z):
out = False
return out
Can you help me understand what this is doing? Is it, "out is True, but if x is less than y or greater than z: out is False"? I am unsure about the | operator.
A:
TL;DR, someone tho... | What does (x < y) | (x > z) do? | def my_function(x,y,z):
out = True
if(x < y) | (x > z):
out = False
return out
Can you help me understand what this is doing? Is it, "out is True, but if x is less than y or greater than z: out is False"? I am unsure about the | operator.
| [
"TL;DR, someone thought they were clever.\nThis code takes advantage of some implementation details about booleans and then does some binary integer operations.\nTo understand it we need to cover a few things:\n\nthe > and < operators in a comparison will give back boolean True or False.\nBoolean True and False are... | [
2,
0
] | [
"def my_function(x,y,z):\n global out\n out = True\n if(x < y) | (x > z):\n out = False\n return out\n\n\nx = 6\ny = 2\nz = 5\nmy_function(x,y,z)\n\nThe above code outputs True/False based on the values of x,y,z. If x is smaller than y OR if x is greater than z it will change the value of 'out' t... | [
-2
] | [
"python"
] | stackoverflow_0074446884_python.txt |
Q:
Calculate degree centrality of a node for every day in a NetworkX graph
I have a networkx graph with events spanning several months. I wanted to see how a node's centrality score changes over time.
I am planning on using several different centrality measures so I have created a function to select a specific sender... | Calculate degree centrality of a node for every day in a NetworkX graph | I have a networkx graph with events spanning several months. I wanted to see how a node's centrality score changes over time.
I am planning on using several different centrality measures so I have created a function to select a specific sender (I don't have many unique senders) and a specific date, then create a networ... | [
"When you set name['feature']= nx_measure(oneDay_graph).keys(), you're getting a row for each element of the graph, which in this case is both 'A' and the target node of 35 or 18. What you should be doing instead is something like\nd = nx_measure(oneDay_graph)\nname['feature'] = feature \nname[col_name] = d[featur... | [
1
] | [] | [] | [
"function",
"networkx",
"node_centrality",
"python"
] | stackoverflow_0074443524_function_networkx_node_centrality_python.txt |
Q:
flattening a pandas index
I have a data frame like the following
| id | label |
|0| 1 | foo |
|1| 2 | baa |
|2| 1 | baa |
and I want it to change to this structure
| id | foo| baa
|0| 1 | 1| 1
|1| 2 | 0| 1
I used
df = pd.DataFrame({'id':[1,2,4,1,1,2], 'label':['foo', 'ba', 'foo', 'baa... | flattening a pandas index | I have a data frame like the following
| id | label |
|0| 1 | foo |
|1| 2 | baa |
|2| 1 | baa |
and I want it to change to this structure
| id | foo| baa
|0| 1 | 1| 1
|1| 2 | 0| 1
I used
df = pd.DataFrame({'id':[1,2,4,1,1,2], 'label':['foo', 'ba', 'foo', 'baa','coo','coo']})
df = pd.crosst... | [
"You could use a pivot table. You just need to add a column to use as the values column.\nBut you could add a \"count\" column that is just 1 for each row, then in the pivot table use the count aggfunc.\nLike this:\ndf['count'] = 1\npd.pivot_table(df,index='id',columns='label', values='count').fillna(0)\n\nOutput:\... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074446954_pandas_python.txt |
Q:
How can I create a book index with Python?
I have a section, and in this section, I have topics, for example, book chapters. But, on this section page, I only have the last three chapters, so, when I click, I can move forward to the single page where I am. This is my HTML template.
<ul>
{% for chapter in... | How can I create a book index with Python? | I have a section, and in this section, I have topics, for example, book chapters. But, on this section page, I only have the last three chapters, so, when I click, I can move forward to the single page where I am. This is my HTML template.
<ul>
{% for chapter in book %}
<li>
<a hre... | [
"The url is wrong, it should be like this:\n?page={{ chapter_page }}&#{{ chapter }}\n ^\n\nBecause these are two different querystring, hence should be differentiated by an &. Apart from that, the chapter_page should be a variable which is an integer. Finally, you are iterating through an int... | [
0
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0074446796_django_html_python.txt |
Q:
Python sorting mechanism
Is there a way to get all combinations of a string list?
Input: x=list("T", "H", "E")
Output: THE, TEH, HTE, HET, ETH, EHT
this is what I got so far I'm pretty new to this:
print("Enter word")
x=input()
print("your word is " + x)
print(list(x))
it just need to be sorted now.
A:
from it... | Python sorting mechanism | Is there a way to get all combinations of a string list?
Input: x=list("T", "H", "E")
Output: THE, TEH, HTE, HET, ETH, EHT
this is what I got so far I'm pretty new to this:
print("Enter word")
x=input()
print("your word is " + x)
print(list(x))
it just need to be sorted now.
| [
"from itertools import permutations\n\nprint([''.join(x) for x in permutations('THE')])\n\n# ['THE', 'TEH', 'HTE', 'HET', 'ETH', 'EHT']\n\nYou can use any iterable for itertools.permutations, so 'THE' works, as well as ['T', 'H', 'E'].\n"
] | [
0
] | [] | [] | [
"permutation",
"python"
] | stackoverflow_0074447137_permutation_python.txt |
Q:
SQLAlchemy returns primary key instead of whole record from insert statement
I need to get whole orm instance which is created in table after insert statement, since database generated UUID for primary key(database - postgresql).
stmt = insert(Table).values(data).returning(Table)
orm_instance = session.execute(stm... | SQLAlchemy returns primary key instead of whole record from insert statement | I need to get whole orm instance which is created in table after insert statement, since database generated UUID for primary key(database - postgresql).
stmt = insert(Table).values(data).returning(Table)
orm_instance = session.execute(stmt).scalar()
where Table defined very simply:
class Table(BaseModel):
__tablen... | [
"Just create your new object (without PK), add it to your session, and commit() (or at least flush()). The object will pick up the automatically-generated PK value:\nnew_table = Table(name=\"x\")\nwith Session(engine) as sess:\n print(new_table)\n # Table(uuid=None, name='x')\n sess.add(new_table)\n ses... | [
1
] | [] | [] | [
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0074446914_orm_python_sqlalchemy.txt |
Q:
I have a 2d list of strings and numbers. I want to get the sum of all numbers that have the same string. Code is in python
I have a list the contains names and numbers. And for all items with the same name in the list I want to calculate the sum of those numbers.
Please note, I cannot use the numpy function.
This ... | I have a 2d list of strings and numbers. I want to get the sum of all numbers that have the same string. Code is in python | I have a list the contains names and numbers. And for all items with the same name in the list I want to calculate the sum of those numbers.
Please note, I cannot use the numpy function.
This is my 2d list:
list = [('apple', 3), ('apple', 4), ('apple', 6), ('orange', 2), ('orange', 4), ('banana', 5)]
And then adding u... | [
"One way is to use default dict:\nfrom collections import defaultdict\n\nd = defaultdict(list) # all elements in the dictionary will be a list by default\n\nl = [('apple', 3), ('apple', 4), ('apple', 6), ('orange', 2), ('orange', 4), ('banana', 5)]\n\nfor name, number in l:\n d[name].append(number)\nfor key, va... | [
0,
0,
0
] | [] | [] | [
"2d",
"list",
"python",
"string",
"sum"
] | stackoverflow_0074447271_2d_list_python_string_sum.txt |
Q:
Plotting sympy.Max yields TypeError
I am trying to generate a 3-dimensional plot for a function involving sympy.Max, but I am getting a type-error.
Minimum example:
import sympy
u, v = sympy.symbols("u v", positive=True)
f = sympy.Max(0, u*v - 0.5)
my_plot = sympy.plotting.plot3d(f, (u, 0, 1), (v, 0, 1), show=Fal... | Plotting sympy.Max yields TypeError | I am trying to generate a 3-dimensional plot for a function involving sympy.Max, but I am getting a type-error.
Minimum example:
import sympy
u, v = sympy.symbols("u v", positive=True)
f = sympy.Max(0, u*v - 0.5)
my_plot = sympy.plotting.plot3d(f, (u, 0, 1), (v, 0, 1), show=False, legend=True)
my_plot.show()
The code... | [
"That's unfortunate: it is a limitation of the current plotting module, which is using experimental_lambdify which is quite old.\nTwo solutions:\n\nyou lambdify your expression, and manually plot it with matplotlib.\n\nfrom sympy import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nu, v = symbols(\"u v\... | [
1
] | [] | [] | [
"max",
"plot3d",
"python",
"sympy"
] | stackoverflow_0074447091_max_plot3d_python_sympy.txt |
Q:
No thumbnail migrations appear - Django 2.2 version
I did step by step to implement sorl-thumbnail in my Django project. But no migrations thumbnail created so images do not get added via sending form but still get added by admin interface.
I use:
Python 3.9
Django 2.2.16
Pillow 9.3.0
sorl-thumbnail 12.9.0
What ... | No thumbnail migrations appear - Django 2.2 version | I did step by step to implement sorl-thumbnail in my Django project. But no migrations thumbnail created so images do not get added via sending form but still get added by admin interface.
I use:
Python 3.9
Django 2.2.16
Pillow 9.3.0
sorl-thumbnail 12.9.0
What I did.
pip install pillow, sorl-thumbnail
In INSTALLED_AP... | [
"Fixed this problem: I had to add this files=request.FILES or None, in the view function\n form = PostForm(\n request.POST or None,\n files=request.FILES or None,)\n\n if form.is_valid():\n form.instance.author = request.user\n form.save()\n return redirect(\"posts:profile\"... | [
0
] | [] | [] | [
"django",
"django_migrations",
"python",
"python_3.x",
"sorl_thumbnail"
] | stackoverflow_0074440057_django_django_migrations_python_python_3.x_sorl_thumbnail.txt |
Q:
Creating Pool of Ids in python
I need to create a pool of ids for my project. If a user comes, I need to allocate them an id for a certain event. If they delete that event, I need to delete that id and put it back in my id pool.
Let's say A user named Sam comes and creates a certain event. I allocate him id 4343. ... | Creating Pool of Ids in python | I need to create a pool of ids for my project. If a user comes, I need to allocate them an id for a certain event. If they delete that event, I need to delete that id and put it back in my id pool.
Let's say A user named Sam comes and creates a certain event. I allocate him id 4343. If he deletes that event, I need to ... | [
"Create a List which contains values from 0-5000.Choose a random use form the list and assign it to a use and remove it from that list.\n"
] | [
0
] | [] | [] | [
"mongodb",
"pool",
"python",
"python_3.x",
"random"
] | stackoverflow_0074447082_mongodb_pool_python_python_3.x_random.txt |
Q:
Pipenv completely remove
This makes no sense to me:
pipenv --venv
# No virtualenv has been created for this project(/Users/ak/Documents/myfolder) yet!
# Aborted!
pipenv --rm
# No virtualenv has been created for this project yet!
# Aborted!
pipenv shell
# Shell for /Users/ak/.local/share/virtualenvs/myfolder-7FUE... | Pipenv completely remove | This makes no sense to me:
pipenv --venv
# No virtualenv has been created for this project(/Users/ak/Documents/myfolder) yet!
# Aborted!
pipenv --rm
# No virtualenv has been created for this project yet!
# Aborted!
pipenv shell
# Shell for /Users/ak/.local/share/virtualenvs/myfolder-7FUE3C-L already activated.
# No a... | [
"This solution worked for me: https://github.com/pypa/pipenv/issues/84#issuecomment-275056943\nPressed CTRL-d to exit shell and was able to pipenv shell.\n"
] | [
0
] | [] | [] | [
"pipenv",
"python"
] | stackoverflow_0074447334_pipenv_python.txt |
Q:
How to groupby a dynamic condition on a nested list
Given the nested_list... This nested list is based on another grouping
nested_list = [[[0, 59.87271881103516]],
[[1, 56.33743667602539], [2, 12.141159057617188]],
[[3, 116.6510009765625]],
[[4, 98.58261108398438], [5, 98.01058959960938]],
[[5, 98.010589599609... | How to groupby a dynamic condition on a nested list | Given the nested_list... This nested list is based on another grouping
nested_list = [[[0, 59.87271881103516]],
[[1, 56.33743667602539], [2, 12.141159057617188]],
[[3, 116.6510009765625]],
[[4, 98.58261108398438], [5, 98.01058959960938]],
[[5, 98.01058959960938], [6, -2.2177391052246094]],
[[7, -7.6250953674316415... | [
"This gives me a slighly different result than what you expect. However, this is what seems to be correct according to how I interpret your description of the problem.\nimport math\n\n\ndef group_nested_list(nested_list: list, diff: int = 10) -> list:\n result = []\n for lists in nested_list:\n lists =... | [
1
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074442551_group_by_pandas_python.txt |
Q:
How to update graph in canvas?
Im making a GUI which is visualizing json data from a . The problem im currently stuck at is that i cant get the graph to update in the canvas, it only updates when i press the max/min button: . Is there a way to update the graph when i press a new file?
Picture of the GUI:
Part of ... | How to update graph in canvas? | Im making a GUI which is visualizing json data from a . The problem im currently stuck at is that i cant get the graph to update in the canvas, it only updates when i press the max/min button: . Is there a way to update the graph when i press a new file?
Picture of the GUI:
Part of the code plotting the graph:
##### C... | [
"Have you tried calling canvas.draw_idle() or perhaps canvas.draw() where/when you want to refresh the canvas widget?\ndef items_selected(d):\n plt.clf()\n selected_indices = vores_listebox.curselection()\n selected_json = \",\".join([vores_listebox.get(i) for i in selected_indices])\n full_file_path = ... | [
0
] | [] | [] | [
"graph",
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0074446754_graph_matplotlib_python_tkinter.txt |
Q:
Why peewee ignores column's unique definition?
I am trying to create tables User and Task. In User I make user_id column unique, but peewee ignores it. There is no unique column when I look :
class BaseModel(Model):
class Meta:
database = DBConfig.db
class User(BaseModel):
user_id = IntegerField(u... | Why peewee ignores column's unique definition? | I am trying to create tables User and Task. In User I make user_id column unique, but peewee ignores it. There is no unique column when I look :
class BaseModel(Model):
class Meta:
database = DBConfig.db
class User(BaseModel):
user_id = IntegerField(unique=True, null=False)
class Meta:
tab... | [
"Works for me:\ndb = SqliteDatabase(':memory:')\n\nclass User(db.Model):\n user_id = IntegerField(unique=True)\n\nUser.create_table()\n\nResults in the following SQL:\nCREATE TABLE IF NOT EXISTS \"user\" (\n \"id\" INTEGER NOT NULL PRIMARY KEY,\n \"user_id\" INTEGER NOT NULL)\nCREATE UNIQUE INDEX IF NOT EXISTS... | [
0
] | [] | [] | [
"peewee",
"python",
"sqlite"
] | stackoverflow_0074424559_peewee_python_sqlite.txt |
Q:
Lookup value from row in column in another file, fill column with value from other file
I have two files:
File A: Current product list with brand (Marke:), article (Titel:) and price (Preis:), in xlsx.
This file contains the following headers and contains around 50.000 row values:
Col 1
Col 2
Col 3
Marke:
Titel:... | Lookup value from row in column in another file, fill column with value from other file | I have two files:
File A: Current product list with brand (Marke:), article (Titel:) and price (Preis:), in xlsx.
This file contains the following headers and contains around 50.000 row values:
Col 1
Col 2
Col 3
Marke:
Titel:
Preis:
ABC
DEF
123
...
...
...
File B: Historical price information archive fo... | [
"If my understanding is correct, we will go through the following steps:\n\nread data from files and generate dataframes: File_A.xlsx -> df_A; File_B.xlsx -> df_B\nIn df_B, drop rows has duplicated values of column Titel, except the first row. In other words, only the unique or first row of same Titel will be kept ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074417304_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.