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: Max string recursion exceeded when using str.format_map() I am using str.format_map to format some strings but I encounter a problem when this string contains quotes, even escaped. Here is the code: class __FormatDict(dict): def __missing__(self, key): return '{' + key + '}' def format_dict(node, temp...
Max string recursion exceeded when using str.format_map()
I am using str.format_map to format some strings but I encounter a problem when this string contains quotes, even escaped. Here is the code: class __FormatDict(dict): def __missing__(self, key): return '{' + key + '}' def format_dict(node, template_values): template_values = __FormatDict(template_value...
[ "You can't use your __missing__ trick on JSON data. There are multiple problems. That's because the text within {...} replacement fields are not just treated as strings. Take a look at the syntax grammar:\n\nreplacement_field ::= \"{\" [field_name] [\"!\" conversion] [\":\" format_spec] \"}\"\nfield_name ::...
[ 4, 0 ]
[]
[]
[ "json", "python", "string" ]
stackoverflow_0041738604_json_python_string.txt
Q: no such option: --use-feature while installing tensorflow object detection api I'm trying to install Tensorflow Object Detection API, following the steps at this link, which is the official installation's documentation for Tensorflow 2. git clone https://github.com/tensorflow/models.git > everything is ok cd model...
no such option: --use-feature while installing tensorflow object detection api
I'm trying to install Tensorflow Object Detection API, following the steps at this link, which is the official installation's documentation for Tensorflow 2. git clone https://github.com/tensorflow/models.git > everything is ok cd models/research/ > everything is ok protoc object_detection/protos/*.proto --python_out=....
[ "I had the same problem, I upgraded pip version from 20.0.2 to 20.2.2, then it worked.\nAn issue was opened on github on this matter, check here.\nUse python -m pip install --upgrade pip to upgrade pip.\n", "just needed to upgrade pip from version 20.0.2 to 20.2.2. An issue on github has also been opened (here)\n...
[ 15, 3, 3, 0 ]
[]
[]
[ "object_detection", "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0063687113_object_detection_python_tensorflow_tensorflow2.0.txt
Q: How to fix: missing 1 required positional argument: 'on_delete' When I was working on a Django project (blog), I had an error(s) while working on the site. Here are the errors I have appeared: 1: When I entered the python command manage.py makemigrations blog(via the console) in the directory C:\mysite\site\minipr...
How to fix: missing 1 required positional argument: 'on_delete'
When I was working on a Django project (blog), I had an error(s) while working on the site. Here are the errors I have appeared: 1: When I entered the python command manage.py makemigrations blog(via the console) in the directory C:\mysite\site\miniproject , then there is this: Traceback (most recent call last): File...
[ "You have declared a ForeignKey somewhere but not provided the on_delete keyword argument.\nIf you post the BlogPost model, I can give you an exact answer, but you probably want something like:\nmodels.ForeignKey(..., on_delete=models.CASCADE)\n\nTo fix the issue add the key word argument to the BlogPost model in b...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074565437_django_python.txt
Q: Plot a function with telegram bot (python, matplotlib) I faced with the problem during telegram bot writing. I would be very happy if somebody help me with this. My code import telebot import matplotlib.pyplot as plt import numpy as np ... def plot_func(message): x = np.linspace(-5,5,100) y = message.tex...
Plot a function with telegram bot (python, matplotlib)
I faced with the problem during telegram bot writing. I would be very happy if somebody help me with this. My code import telebot import matplotlib.pyplot as plt import numpy as np ... def plot_func(message): x = np.linspace(-5,5,100) y = message.text # <-- here is something wrong I supppose plt.plot(x, ...
[ "Assuming message.text contains the string 'x**2', you can use numexpr.evaluate to convert to numpy array:\nimport numexpr\nimport matplotlib.pyplot as plt\n\nx = np.linspace(-5, 5, 100)\ny = numexpr.evaluate(message.text) # message.text = 'x**2'\n\nplt.plot(x, y, 'r')\n\nOutput:\n\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "plot", "python", "telegram", "telegram_bot" ]
stackoverflow_0074570550_matplotlib_plot_python_telegram_telegram_bot.txt
Q: How to add a new JSON data at the end of the existing data in python I am trying to populate a JSON file from the user input. The users.json file is initially empty, and I was able to register the first user ("Doe_Joh"). The problem was when I ran the program and registered for the second use. The data inside got ...
How to add a new JSON data at the end of the existing data in python
I am trying to populate a JSON file from the user input. The users.json file is initially empty, and I was able to register the first user ("Doe_Joh"). The problem was when I ran the program and registered for the second use. The data inside got replaced by the data. What I expected was to have the data saved increment...
[ "You can do it in 2 ways:\nLoad the whole user.json, add a new user to the end of the file,\nand save everything.\nimport json\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass User:\n f_name: str\n l_name: str\n username: str\n email: str\n\n\ndef save_user(user: User) -> None:\n with open(\...
[ 1, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074570372_json_python.txt
Q: CombineFn for Python dict in Apache Beam pipeline I've been experimenting with the Apache Beam SDK in Python to write data processing pipelines. My data mocks IoT sensor data from a Google PubSub topic that streams JSON data like this: {"id": 1, "temperature": 12.34} {"id": 2, "temperature": 76.54} There are IDs ...
CombineFn for Python dict in Apache Beam pipeline
I've been experimenting with the Apache Beam SDK in Python to write data processing pipelines. My data mocks IoT sensor data from a Google PubSub topic that streams JSON data like this: {"id": 1, "temperature": 12.34} {"id": 2, "temperature": 76.54} There are IDs ranging from 0 to 99. Reading the JSON into a Python di...
[ "You need to either adjust your CombineFn or (what I would recommend) keep the CombineFn as generic as possible and map the input of the CombinePerKey accordingly. I have made a short examples of both cases below using this official beam example.\nSpecific CombineFn:\nimport apache_beam as beam\n\nclass SpecificAve...
[ 1 ]
[]
[]
[ "apache_beam", "google_cloud_dataflow", "python" ]
stackoverflow_0074521933_apache_beam_google_cloud_dataflow_python.txt
Q: Testing logging output with pytest I am trying to write a test, using pytest, that would check that a specific function is writing out a warning to the log when needed. For example: In module.py: import logging LOGGER = logging.getLogger(__name__) def run_function(): if something_bad_happens: LOGGER.w...
Testing logging output with pytest
I am trying to write a test, using pytest, that would check that a specific function is writing out a warning to the log when needed. For example: In module.py: import logging LOGGER = logging.getLogger(__name__) def run_function(): if something_bad_happens: LOGGER.warning('Something bad happened!') In te...
[ "I don't know why this didn't work when I tried it before, but this solution works for me now:\nIn test_module.py:\nimport logging\nfrom module import run_function\n\nLOGGER = logging.getLogger(__name__)\n\ndef test_func(caplog):\n LOGGER.info('Testing now.')\n run_function()\n assert 'Something bad happen...
[ 54, 47, 8, 1, 0 ]
[]
[]
[ "logging", "pytest", "python", "testing", "unit_testing" ]
stackoverflow_0053125305_logging_pytest_python_testing_unit_testing.txt
Q: How to fix beautiful soup list index out of range I want to get specific information from the website. It is okey to run first four url, but when we run the fifth one, we get 'IndexError: list index out of range' at 'company = soup.select('.companyName')[0].get_text().strip()'. we have url like https://www.indeed....
How to fix beautiful soup list index out of range
I want to get specific information from the website. It is okey to run first four url, but when we run the fifth one, we get 'IndexError: list index out of range' at 'company = soup.select('.companyName')[0].get_text().strip()'. we have url like https://www.indeed.com/jobs?q=data analyst&l=remote ## Number of postings ...
[ "Generally, it's safer to check that select/find returns something before applying .get.... When you have to select-and-get from multiple elements, it's more convenient to use a function on loop.\n[This is a simplified version of another function I often use when scraping; if interested, see an example with the ful...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074525562_beautifulsoup_python_web_scraping.txt
Q: To to remove html tag to get text I have text like this: text = <option value="tfa_4472" id="tfa_4472" class="">helo 1</option> <option value="tfa_4473" id="tfa_4473" class="">helo 2</option> <option value="tfa_4474" id="tfa_4474" class="">helo 3</option> <option value="tfa_4475" id="tfa_4475" class="">helo 4</op...
To to remove html tag to get text
I have text like this: text = <option value="tfa_4472" id="tfa_4472" class="">helo 1</option> <option value="tfa_4473" id="tfa_4473" class="">helo 2</option> <option value="tfa_4474" id="tfa_4474" class="">helo 3</option> <option value="tfa_4475" id="tfa_4475" class="">helo 4</option> <option value="tfa_4476" id="tfa_...
[ "Python:\nfrom bs4 import BeautifulSoup\n\n\nmyhtml = \"\"\"<option value=\"tfa_4472\" id=\"tfa_4472\" class=\"\">helo 1</option>\n<option value=\"tfa_4473\" id=\"tfa_4473\" class=\"\">helo 2</option>\n<option value=\"tfa_4474\" id=\"tfa_4474\" class=\"\">helo 3</option>\n<option value=\"tfa_4475\" id=\"tfa_4475\" ...
[ 1, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0074570186_javascript_python.txt
Q: How to annotate my subclass to avoid mypy error: Class cannot sublass "Foo" (has type "Any") I have a common library, lib_common that defines a basic pydantic BaseModel that I use in all other packages: ├── lib_common    ├── __init__.py    ├── models.py where models.py contains: from pydantic import BaseModel,...
How to annotate my subclass to avoid mypy error: Class cannot sublass "Foo" (has type "Any")
I have a common library, lib_common that defines a basic pydantic BaseModel that I use in all other packages: ├── lib_common    ├── __init__.py    ├── models.py where models.py contains: from pydantic import BaseModel, Extra class StrictBaseModel(BaseModel): class Config: extra = Extra.forbid Whenever ...
[ "If lib_common is a separate package, then there is nothing weird here.\nPEP561 explains it quite well: if your package contains inline annotations (e.g. you consider it typed and do not ship separate stub files), then it needs a py.typed marker in root.\nThere is an example of such package in mypy documentation. Q...
[ 1 ]
[]
[]
[ "mypy", "python", "python_typing" ]
stackoverflow_0070290482_mypy_python_python_typing.txt
Q: How do I write JSON data to a file? How do I write JSON data stored in the dictionary data to a file? f = open('data.json', 'wb') f.write(data) This gives the error: TypeError: must be string or buffer, not dict A: data is a Python dictionary. It needs to be encoded as JSON before writing. Use this for maximum...
How do I write JSON data to a file?
How do I write JSON data stored in the dictionary data to a file? f = open('data.json', 'wb') f.write(data) This gives the error: TypeError: must be string or buffer, not dict
[ "data is a Python dictionary. It needs to be encoded as JSON before writing.\nUse this for maximum compatibility (Python 2 and 3):\nimport json\nwith open('data.json', 'w') as f:\n json.dump(data, f)\n\nOn a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:\nimport json\nwith ope...
[ 2846, 305, 186, 129, 26, 13, 11, 8, 6, 5, 3, 3, 3, 2, 0 ]
[ "This is just an extra hint at the usage of json.dumps (this is not an answer to the problem of the question, but a trick for those who have to dump numpy data types):\nIf there are NumPy data types in the dictionary, json.dumps() needs an additional parameter, credits go to TypeError: Object of type 'ndarray' is n...
[ -1 ]
[ "json", "python" ]
stackoverflow_0012309269_json_python.txt
Q: Can Tkinter ask for input from a different page? I am trying to create a gui with tkinter where I am being redirected to different pages and I want those different pages to ask for different inputs and do different functions. As of now I still can't fix it I am just using this tkinter as of today so I am new. what...
Can Tkinter ask for input from a different page?
I am trying to create a gui with tkinter where I am being redirected to different pages and I want those different pages to ask for different inputs and do different functions. As of now I still can't fix it I am just using this tkinter as of today so I am new. what I envision is: Page 1: ask student section Page 2: as...
[ "First of all you should seperate your pages. Like these situations, using OOP would be life saver. Creating instance or class per page will solve problems.\nfirst of all lets create a base page class that will have everything we need.\nclass Page:\n def __init__(self,frame,pageName):\n self.pageName = pa...
[ 0 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0074565423_python_python_3.x_tkinter.txt
Q: PostgresSQL connection refused on docker container in same server I have postgresSQL database running docker on server when i spin up another container for django app and trying to connect postgress getting connection error. any idea? django.db.utils.OperationalError: connection to server at "localhost" (127.0.0....
PostgresSQL connection refused on docker container in same server
I have postgresSQL database running docker on server when i spin up another container for django app and trying to connect postgress getting connection error. any idea? django.db.utils.OperationalError: connection to server at "localhost" (127.0.0.1), port 6545 failed: Connection refused Is the server running on that ...
[ "As @JustLudo said in the Comments, you have to address postgres with the container name \"pg-docker\". Localhost would be your django container.\nIn general, if you use multiple docker containers you should not use localhost. Instead treat every container as a standalone server and address via DNS / container_name...
[ 0 ]
[]
[]
[ "django", "docker", "docker_compose", "postgresql", "python" ]
stackoverflow_0074570161_django_docker_docker_compose_postgresql_python.txt
Q: Get the inverse of a dataframe column in terms of rows with NaN values I have an original dataframe df0 with a number of values, based on this dataframe I have a second dateframe where some the original values are NaN, df1. import pandas as pd df0 = pd.DataFrame({'col1': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]}) df1...
Get the inverse of a dataframe column in terms of rows with NaN values
I have an original dataframe df0 with a number of values, based on this dataframe I have a second dateframe where some the original values are NaN, df1. import pandas as pd df0 = pd.DataFrame({'col1': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]}) df1 = pd.DataFrame({'col1': [1,2,None,4,5,6,None,8,None,10,11,None,13,None,None...
[ "masking all columns\nIf you need to mask all columns, use mask + notna OR where + isna:\ndf2 = df0.mask(df1['col1'].notna())\n# or\ndf2 = df0.where(df1['col1'].isna())\n\noutput:\n col1\n0 NaN\n1 NaN\n2 3.0\n3 NaN\n4 NaN\n5 NaN\n6 7.0\n7 NaN\n8 9.0\n9 NaN\n10 NaN\n11 12.0\n12 ...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074570974_dataframe_pandas_python.txt
Q: How to extract information from atom feed based on condition? I have output of API request in given below. From each atom:entry I need to extract <c:series href="http://company.com/series/product/123"/> <c:series-order>2020-09-17T00:00:00Z</c:series-order> <f:assessment-low precision="0">980</f:assessment-low> I ...
How to extract information from atom feed based on condition?
I have output of API request in given below. From each atom:entry I need to extract <c:series href="http://company.com/series/product/123"/> <c:series-order>2020-09-17T00:00:00Z</c:series-order> <f:assessment-low precision="0">980</f:assessment-low> I tried to extract them to different list with BeautifulSoup, but tha...
[ "May try to iterate per entry, use xml parser to get a propper result and check if element exists:\nsoup = BeautifulSoup(request.text,'xml')\ndata = []\nfor i in soup.select('entry'):\n data.append({\n 'date':i.find('series-order').text,\n 'value': i.find('assessment-low').text if i.find('assessmen...
[ 1, 1 ]
[]
[]
[ "atom_feed", "beautifulsoup", "python" ]
stackoverflow_0074570699_atom_feed_beautifulsoup_python.txt
Q: Returning values from a function :( Please can someone explain what's going wrong here? Unfortunately, I have been tasked to complete this using a function; otherwise, I would've used a built-in function like count() Thanks! scores = [3,7,6,9,4,3,5,2,6,8] y = int(input("What score are you searching for in the scor...
Returning values from a function :(
Please can someone explain what's going wrong here? Unfortunately, I have been tasked to complete this using a function; otherwise, I would've used a built-in function like count() Thanks! scores = [3,7,6,9,4,3,5,2,6,8] y = int(input("What score are you searching for in the scores array? ")) a = len(scores) z = False ...
[ "The basic fix to your immediate problem is to modify the line count1(a, z) to read z = count1(a, z).\nThat way, you give z to your count1, allow count1 to modify z, and then overwrite the old value of z with the new value generated by your count1.\nThat said, you have a lot going on in your code that you don't rea...
[ 0 ]
[]
[]
[ "boolean", "boolean_logic", "function", "parameters", "python" ]
stackoverflow_0074570782_boolean_boolean_logic_function_parameters_python.txt
Q: Remove ")" from cells in list if ")" exists Could you please tell me how can I remove ")" from strings in a list without converting the list to a string? Example: Input: list =[ 'ABDDDDC 1,000 IWJBCKNBCDVV', 'BDISJBJ 2,000 DBFIAJDBDIAJ', 'JDBISJB 5,000 AHSBIEFEWEFJ)', # there is a parenthesis at the end 'CONDD...
Remove ")" from cells in list if ")" exists
Could you please tell me how can I remove ")" from strings in a list without converting the list to a string? Example: Input: list =[ 'ABDDDDC 1,000 IWJBCKNBCDVV', 'BDISJBJ 2,000 DBFIAJDBDIAJ', 'JDBISJB 5,000 AHSBIEFEWEFJ)', # there is a parenthesis at the end 'CONDDDD 7,000 4DJVBDISJEVV)'] # there is a parenthesis...
[ "You may use a list comprehension here:\ninp = ['ABDDDDC 1,000 IWJBCKNBCDVV', 'BDISJBJ 2,000 DBFIAJDBDIAJ', 'JDBISJB 5,000 AHSBIEFEWEFJ)', 'CONDDDD 7,000 4DJVBDISJEVV)']\noutput = [re.sub(r'\\)$', '', x) for x in inp]\nprint(output)\n\nThis prints:\n['ABDDDDC 1,000 IWJBCKNBCDVV',\n 'BDISJBJ 2,000 DBFIAJDBDIAJ',\n '...
[ 1, 1 ]
[]
[]
[ "code_cleanup", "data_cleaning", "list", "parentheses", "python" ]
stackoverflow_0074568085_code_cleanup_data_cleaning_list_parentheses_python.txt
Q: I need to solve an equation numerically, but fsolve gives me a seemingly incorrect answer I need to solve a single variable in an equation numerically. I tried using fsolve on two different functions that are, according to my understanding, equivalent. Call these functions func1 and func2. If I specify the variabl...
I need to solve an equation numerically, but fsolve gives me a seemingly incorrect answer
I need to solve a single variable in an equation numerically. I tried using fsolve on two different functions that are, according to my understanding, equivalent. Call these functions func1 and func2. If I specify the variable I am solving for, both functions return the same value (the residual of the equation). Howeve...
[ "The function you pass to scipy.optimize.fsolve is supposed to accept a 1-dimensional array, and return a 1-dimensional array of the same length. (This doesn't mean it should broadcast - the function is supposed to represent a system of N nonlinear equations in N variables for some N, so the input represents N inpu...
[ 1 ]
[]
[]
[ "fsolve", "python" ]
stackoverflow_0074570657_fsolve_python.txt
Q: "RuntimeError: self must be a matrix" RBM we add methods to convert the visible input to the hidden representation and the hidden representation back to reconstructed visible input. Both methods return the activation probabilities, while the sample_h method also returns the observed hidden state as well <pre><code...
"RuntimeError: self must be a matrix"
RBM we add methods to convert the visible input to the hidden representation and the hidden representation back to reconstructed visible input. Both methods return the activation probabilities, while the sample_h method also returns the observed hidden state as well <pre><code> class RBM(): def __init__(sel...
[ "Seems you need broadcasting (because you're multiplying 1d vector on 2D matrix). \nTry using torch.matmul instead.\nThis link for understanding the difference between mm and matmul:\nWhat's the difference between torch.mm, torch.matmul and torch.mul?\n" ]
[ 0 ]
[]
[]
[ "python", "pytorch", "rbm" ]
stackoverflow_0067957655_python_pytorch_rbm.txt
Q: Merge two dataframes on nearest value while duplicating rows I have two dataframes, DF1 = NUM1 Car COLOR 100 Honda blue 100 Honda yellow 200 Volvo red DF2 = NUM2 Car STATE 110 Honda good 110 Honda bad ...
Merge two dataframes on nearest value while duplicating rows
I have two dataframes, DF1 = NUM1 Car COLOR 100 Honda blue 100 Honda yellow 200 Volvo red DF2 = NUM2 Car STATE 110 Honda good 110 Honda bad 230 Volvo not bad 230 Volvo excellent ...
[ "IIUC, you might need to combine merge_asof and merge:\nkey = pd.merge_asof(DF1.reset_index().sort_values(by='NUM1'),\n DF2['NUM2'],\n left_on='NUM1', right_on='NUM2',\n direction='nearest')['NUM2']\n\nDF1.merge(DF2.drop(columns=DF1.columns.intersection(DF2.c...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074570934_dataframe_pandas_python.txt
Q: How to assert data in a JSON array with Python I am trying to automate some API endpoints, but the JSON response is an array of data. How can I assert a specific user with all his data inside that JSON array? I am trying with: assert { "user": "test1", "userName": "John Berner", ...
How to assert data in a JSON array with Python
I am trying to automate some API endpoints, but the JSON response is an array of data. How can I assert a specific user with all his data inside that JSON array? I am trying with: assert { "user": "test1", "userName": "John Berner", "userid": "1" } in response.json() The JS...
[ "Please try like this:\nYou can use loop over the data within any to perform this check.\ncontents = json.loads(apiresponse_data)\nassert any(i['user'] == 'test1' for i in contents['data'])\n\n", "If all the fields are in the response are part of your user_info you can do what you are thinking of doing -\n# respo...
[ 0, 0 ]
[]
[]
[ "api", "automation", "json", "python" ]
stackoverflow_0074570926_api_automation_json_python.txt
Q: Runtime Error: mat1 and mat2 shapes cannot be multiplied (16x756900 and 3048516x30) How can I solve this problem? class Net(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3,8,11, padding=0) # in_channel, out_channel, kernel size self.pool = nn.MaxPool...
Runtime Error: mat1 and mat2 shapes cannot be multiplied (16x756900 and 3048516x30)
How can I solve this problem? class Net(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3,8,11, padding=0) # in_channel, out_channel, kernel size self.pool = nn.MaxPool2d(2,2) # kernel_size, stride self.conv2 = nn.Conv2d(8, 36, 5, padding=0) ...
[ "756900\nJust change the model definition, the output shape of your last convolution layer does not have the shape 36x291x291. Just change the model definition to:\nclass Net(nn.Module):\n def __init__(self):\n super().__init__()\n \n self.conv1 = nn.Conv2d(3,8,11, padding=0) # in_channel, o...
[ 0 ]
[]
[]
[ "artificial_intelligence", "conv_neural_network", "python", "torch" ]
stackoverflow_0074550050_artificial_intelligence_conv_neural_network_python_torch.txt
Q: Convert dataframe into JSON file Dataframe: Name Location code ID Dept Details Fbk Kirsh HD12 76 Admin "Age:25; Location : ""SF""; From: ""London""; Marital stays: ""Single"";" Good John HD12 87 Support "Age:35; Location : ""SF""; From: ""Chicago""; Marital stays: ""Single"";" Good Des...
Convert dataframe into JSON file
Dataframe: Name Location code ID Dept Details Fbk Kirsh HD12 76 Admin "Age:25; Location : ""SF""; From: ""London""; Marital stays: ""Single"";" Good John HD12 87 Support "Age:35; Location : ""SF""; From: ""Chicago""; Marital stays: ""Single"";" Good Desired output: { “Kirsh”: { “Locatio...
[ "import pandas as pd\nimport json\n\ndf = pd.DataFrame({'name':['a','b','c','d'],'age':[10,20,30,40],'address':['e','f','g','h']})\n\ndf_without_name = data1.loc[:, df.columns!='name']\n\ndict_wihtout_name = df_without_name.to_dict(orient='records')\n\ndict_index_by_name = dict(zip(df['name'], df_without_name))\n\n...
[ 1 ]
[]
[]
[ "dataframe", "json", "pandas", "python" ]
stackoverflow_0074568501_dataframe_json_pandas_python.txt
Q: How to zip two columns into a key value pair dictionary in pandas I have a dataframe with two related columns that needs to be merged into a single dictionary column. Sample Data: skuId coreAttributes.price coreAttributes.amount 0 100 price 8.84 1 102 price ...
How to zip two columns into a key value pair dictionary in pandas
I have a dataframe with two related columns that needs to be merged into a single dictionary column. Sample Data: skuId coreAttributes.price coreAttributes.amount 0 100 price 8.84 1 102 price 12.99 2 103 price 9.99 Expected output: skuId ...
[ "You can use a list comprehension with python's zip:\ndf['coreAttributes'] = [{k: v} for k,v in\n zip(df['coreAttributes.price'],\n df['coreAttributes.amount'])]\n\nOutput:\n skuId coreAttributes.price coreAttributes.amount coreAttributes\n0 100 ...
[ 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074571107_pandas_python.txt
Q: Prophet: disable or hide verbose logger output Using ~~facebook~~ meta prophet's cross-validation function, I get lots of this: WARNING:prophet.models:Optimization terminated abnormally. Falling back to Newton. I can disable the stan output using this, but I can't seem to get rid of these pesky logs. I might find...
Prophet: disable or hide verbose logger output
Using ~~facebook~~ meta prophet's cross-validation function, I get lots of this: WARNING:prophet.models:Optimization terminated abnormally. Falling back to Newton. I can disable the stan output using this, but I can't seem to get rid of these pesky logs. I might find them useful if I was running this interactively, bu...
[ "You should ensure the qualifier is already set by te library, importing it.\n\nimport fbprophet\n\nafter that, you can get the logger and disable it.\n\nlogging.getLogger('fbprophet').disabled = True\n\nI don't know if prophet use propagation to sub-qualifier, if so you can disable it by (use this technique carefu...
[ 0 ]
[]
[]
[ "facebook_prophet", "logging", "python" ]
stackoverflow_0070608968_facebook_prophet_logging_python.txt
Q: Effecient conversion of multilevel nested dictionary to df I looked at several questions but did not find an answer to convert a nested dictionary with this irregular structure: a = {'Cat0': {'brand1': {'b': 0.78, 'c': 1}, 'brand2': {'k': 1, 'c': 1}}, 'Cat1': {'brand4': {'b': 10, 's': 0.0}}, 'Cat2': {'brand1': {'j...
Effecient conversion of multilevel nested dictionary to df
I looked at several questions but did not find an answer to convert a nested dictionary with this irregular structure: a = {'Cat0': {'brand1': {'b': 0.78, 'c': 1}, 'brand2': {'k': 1, 'c': 1}}, 'Cat1': {'brand4': {'b': 10, 's': 0.0}}, 'Cat2': {'brand1': {'j': 1, 'c': 0.0}}} to the following pandas dataframe: Catego...
[ "It's quite straightforward with a comprehension to flatten the dictionary:\ndf = pd.DataFrame([[k, k1, k2, v]\n for k, d in a.items()\n for k1, d1 in d.items()\n for k2, v in d1.items()],\n columns=['Category', 'Brand', 'Peer', 'Value'])\n\nYou ...
[ 3 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074571157_dictionary_pandas_python.txt
Q: What is the best way to compare two dataframes with multiple entries for a key? I have two dataframes. They can have multiple values for the same product id. What would be the best way to compare their values? I have tried comparing them with compare, from csv_diff library, but it is based on a unique key. However...
What is the best way to compare two dataframes with multiple entries for a key?
I have two dataframes. They can have multiple values for the same product id. What would be the best way to compare their values? I have tried comparing them with compare, from csv_diff library, but it is based on a unique key. However, my dataframes don't have a unique key, having multiple entries for the same product...
[ "I'm not sure what your expected output should be, but you could try the following:\ndf1.apply(lambda row: row == df2[df2.product_name == row.product_name], axis=1)\n\nThe result is an object where each row has all rows that corresponds with the product name. You can search that result per row:\nresult[2]:\nindex ...
[ 0 ]
[]
[]
[ "compare", "dataframe", "pandas", "python" ]
stackoverflow_0074571090_compare_dataframe_pandas_python.txt
Q: Not getting the hue ...of various 'Region' plt.figure(figsize=(20,10)) plt.title('Regionwise Killed') plt.xlabel('Year',fontsize=15) plt.ylabel('Killed',fontsize=15) sns.lineplot(x=df['Year'].index,y=df['Year'].value_counts(),hue=df['Region']) plt.show() getting output only getting 3 hue regions in lineplot I wa...
Not getting the hue ...of various 'Region'
plt.figure(figsize=(20,10)) plt.title('Regionwise Killed') plt.xlabel('Year',fontsize=15) plt.ylabel('Killed',fontsize=15) sns.lineplot(x=df['Year'].index,y=df['Year'].value_counts(),hue=df['Region']) plt.show() getting output only getting 3 hue regions in lineplot I want a lineplot like this
[]
[]
[ "Here this will help\ndf[\"counts\"] = 1\n\nnewDf = pd.DataFrame(df[[ \"Region\",\"Year\",\"counts\"]].groupby([ \"Region\",\"Year\" ]).sum([\"counts\"])).reset_index()\n\n\nand then after that on the new data set you can build those required graphs\nplt.figure(figsize=(20,10))\nplt.title('Regionwise Killed')\nplt...
[ -1 ]
[ "pandas", "python", "seaborn" ]
stackoverflow_0074569573_pandas_python_seaborn.txt
Q: How can I know the queues created in celery with -Q argument? I want to load a different configuration for Celery workers depending on which queueu I'm initializing. Specially, I want to change its concurrency. I have seen that concurrency can be changed if I load it in the config. For example, if I do: celery_app...
How can I know the queues created in celery with -Q argument?
I want to load a different configuration for Celery workers depending on which queueu I'm initializing. Specially, I want to change its concurrency. I have seen that concurrency can be changed if I load it in the config. For example, if I do: celery_app = current_celery_app # myconfig is a py file with all configuratio...
[ "I found a workaround. It's not what I would like to, but I think it's more general than initializing celery with --concurrency, which was my last option in case I couldn't find a better one. My workaround:\nI found that you can start celery with -n option. This changes the name of the celery:\ncelery -A run_api.ce...
[ 0 ]
[]
[]
[ "celery", "python" ]
stackoverflow_0074571031_celery_python.txt
Q: Python How to make a proper string slicing? I can't figure out how to properly slice a string. There is a line: "1, 2, 3, 4, 5, 6". The number of characters is unknown, numbers can be either one-digit or three-digit I need to get the last value up to the nearest comma, that means I need to get the value (6) from t...
Python How to make a proper string slicing?
I can't figure out how to properly slice a string. There is a line: "1, 2, 3, 4, 5, 6". The number of characters is unknown, numbers can be either one-digit or three-digit I need to get the last value up to the nearest comma, that means I need to get the value (6) from the string
[ "Better use str.rsplit, setting maxsplit=1 to avoid unnecessarily splitting more than once:\nstring = \"1, 2, 3, 4, 5, 6\"\nlast = string.rsplit(', ', 1)[-1]\n\nOutput: '6'\n", "you can try to split and get last value\nstring = \"1, 2, 3, 4, 5, 6\"\nstring.split(',')[-1]\n>>> ' 6'\n\nadd strip to get rid of the w...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "python", "slice", "string" ]
stackoverflow_0074570461_python_slice_string.txt
Q: How to split other information from binary string? I have an image which is a result of a python code and has to be shown in a LabVIEW program. The pixels of the image are sent ( with sys.stdout.buffer.write)as a U32 pixels string, so I used unflatten from string in LabVIEW code to show the image, but the result f...
How to split other information from binary string?
I have an image which is a result of a python code and has to be shown in a LabVIEW program. The pixels of the image are sent ( with sys.stdout.buffer.write)as a U32 pixels string, so I used unflatten from string in LabVIEW code to show the image, but the result from python includes other information as shown in the pi...
[ "You can use the match pattern node twice to cut off the first two lines like this:\n\nNote that you might need to replace \\n with \\r\\n, depending on how your actual input is coded.\n" ]
[ 0 ]
[]
[]
[ "image", "labview", "python", "stdout" ]
stackoverflow_0073618367_image_labview_python_stdout.txt
Q: how can i style one cell of QTableWidget without any effect on the other cells? i am working on a table and i use QTableWidget in my project and i need to change the color or the style of one cell only or one row only , i do not want to style all of cells. in the above image i changed all of cells but i want to c...
how can i style one cell of QTableWidget without any effect on the other cells?
i am working on a table and i use QTableWidget in my project and i need to change the color or the style of one cell only or one row only , i do not want to style all of cells. in the above image i changed all of cells but i want to change one cell or one row only. is there any chance or way to do it ?
[ "I would implement my own QStyledItemDelegate and set the table to use that (setItemDelegate and friends).\nIt can be very simple for your needs, probably, just need to re-implement one method, QStyledItemDelegate::initStyleOption() and inside that set the backgroundBrush property of the QStyleOptionViewItem to wha...
[ 1 ]
[]
[]
[ "pyqt", "pyqt5", "pyqt6", "python", "qt" ]
stackoverflow_0074540335_pyqt_pyqt5_pyqt6_python_qt.txt
Q: Select specific rows/columns xls file I would like to select specific rows and columns in Python. I already use pandas somewhere in my code so I'd prefer a way to do it with this library. I tried specific_row = pandas.read_excel('this_file.xls', "Entrees")[3] and specific_row = pandas.read_excel('this_file.xls', "...
Select specific rows/columns xls file
I would like to select specific rows and columns in Python. I already use pandas somewhere in my code so I'd prefer a way to do it with this library. I tried specific_row = pandas.read_excel('this_file.xls', "Entrees")[3] and specific_row = pandas.read_excel('this_file.xls', "Entrees", index_col = 2)[3] but I can't see...
[ "you can use the \"iloc\" method and special which rows to select\nspecific_row = pandas.read_excel('this_file.xls', \"Entrees\").iloc[:3,:] #select 3 rows and every column\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python", "xls" ]
stackoverflow_0074571346_pandas_python_xls.txt
Q: Django storages: Need authenticated way of reading static files from google cloud storage I am trying to read static files from GCP storage using a service account key. The problem is while most of the requests are authenticated django-storages, some of the requests are public. Developer console: Networks tab And ...
Django storages: Need authenticated way of reading static files from google cloud storage
I am trying to read static files from GCP storage using a service account key. The problem is while most of the requests are authenticated django-storages, some of the requests are public. Developer console: Networks tab And because of which I am getting a broken Django admin UI. Broken Django admin UI Here's my static...
[ "At the time of writing this, it's apparently an open bug related to django-storages but on AWS. But similar thing is happening on GCP on further inspection.\nI have already deployed my application using whitenoise to overcome this bug and have hosted my application on GCP cloud run.\n" ]
[ 0 ]
[]
[]
[ "django", "django_staticfiles", "python", "python_django_storages" ]
stackoverflow_0073196800_django_django_staticfiles_python_python_django_storages.txt
Q: How to keep certain structure in various text files? I have some .WOC files like(let's say File1): Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.? 144 cm/35 Kg/5 YearsOld 45,34,22,26,0 78,74,82,11,0 and other ones like (File 2): Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S ...
How to keep certain structure in various text files?
I have some .WOC files like(let's say File1): Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.? 144 cm/35 Kg/5 YearsOld 45,34,22,26,0 78,74,82,11,0 and other ones like (File 2): Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.? 126cm/45 Kg/13 YearsOld. MON/age/sex/hei/w...
[ "The following script will extract the relevant info from each file in question:\n\nProvide the number_of_files - each of which are named File x.woc\n\nTo find the lines to keep:\n\nFind the lines starting with \"Person\"\nFind the lines that contain the word \"cm\"\nFind the lines that have 5 numbers separated by ...
[ 1 ]
[]
[]
[ "csv", "pandas", "python", "python_re" ]
stackoverflow_0074570817_csv_pandas_python_python_re.txt
Q: mypy "Incompatible default for argument" with keyword arg defaults Consider the following illustration of typing.TypeVar straight from the typing docs: # mypytest.py from typing import TypeVar A = TypeVar("A", str, bytes) # I.e. typing.AnyStr def longest(x: A, y: A) -> A: """Return the longest of two string...
mypy "Incompatible default for argument" with keyword arg defaults
Consider the following illustration of typing.TypeVar straight from the typing docs: # mypytest.py from typing import TypeVar A = TypeVar("A", str, bytes) # I.e. typing.AnyStr def longest(x: A, y: A) -> A: """Return the longest of two strings.""" # https://docs.python.org/3/library/typing.html return x i...
[ "I know this question is old, but it seems to attract enough attention.\nThe issue you describe is a well-known problem. Here's the tracking issue.\nFor functions, this is just a mypy limitation (here's why the issue is still open). To make things work without ignore comment, you can introduce two overloads:\nfrom ...
[ 0 ]
[]
[]
[ "mypy", "python", "python_3.x", "python_typing" ]
stackoverflow_0057998243_mypy_python_python_3.x_python_typing.txt
Q: I have a string role = "test1,test2" I need to replace the "," with a " "," " so the final output should be like this role = "test1","test2" repalce a string with python I have tried the replace function but it gives me an str error A: a="test1,test2" a="\""+a.replace(",","\",\"")+"\"" print(a) A: So this is t...
I have a string role = "test1,test2" I need to replace the "," with a " "," " so the final output should be like this role = "test1","test2"
repalce a string with python I have tried the replace function but it gives me an str error
[ "a=\"test1,test2\"\na=\"\\\"\"+a.replace(\",\",\"\\\",\\\"\")+\"\\\"\"\nprint(a)\n\n", "So this is the answer to what you asked.\nold_string = \"test1,test2\"\nnew_string = old_string.replace(',', '\",\"')\n# new_string = 'test1\",\"test2'\n\nWhen you want to use \" in a string, you can use the single quote for t...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074571396_python_python_3.x.txt
Q: Convert a Tensorflow MapDataset to a tf.TensorArray Suppose I have the following code below: import numpy as np import tensorflow as tf simple_data_samples = np.array([ [1, 1, 1, -1, -1], [2, 2, 2, -2, -2], [3, 3, 3, -3, -3], [4, 4, 4, -4, -4], [5, 5, 5, -5, -5], ...
Convert a Tensorflow MapDataset to a tf.TensorArray
Suppose I have the following code below: import numpy as np import tensorflow as tf simple_data_samples = np.array([ [1, 1, 1, -1, -1], [2, 2, 2, -2, -2], [3, 3, 3, -3, -3], [4, 4, 4, -4, -4], [5, 5, 5, -5, -5], [6, 6, 6, -6, -6], [7, 7, 7, -7, -7], ...
[ "Assuming you want the output of the iterator as-is, here is the code.\nlist_array = list(sum(list(ds),()))\nfeature = tf.squeeze(tf.stack(list_array[::2]))\nlabel = tf.squeeze(tf.stack(list_array[1::2]))\n\n" ]
[ 1 ]
[]
[]
[ "python", "tensorflow", "tensorflow2.0", "tensorflow_datasets" ]
stackoverflow_0074507493_python_tensorflow_tensorflow2.0_tensorflow_datasets.txt
Q: How to remove similar strings as if they were duplicates from a dataframe? I have the following df : df=pd.DataFrame({ 'Q0_0': ["A vs. Z", "A vs. Bc", "B vs. Z", "B vs Bc", "Bc vs. A", "Bc vs. B", "Z vs. A", "Z vs. B", "C vs. A", "Bc vs. A"], 'Q1_1': [np.random.randint(1,100) for i in range(10)], 'Q1_2...
How to remove similar strings as if they were duplicates from a dataframe?
I have the following df : df=pd.DataFrame({ 'Q0_0': ["A vs. Z", "A vs. Bc", "B vs. Z", "B vs Bc", "Bc vs. A", "Bc vs. B", "Z vs. A", "Z vs. B", "C vs. A", "Bc vs. A"], 'Q1_1': [np.random.randint(1,100) for i in range(10)], 'Q1_2': np.random.random(10), 'Q1_3': np.random.randint(2, size=10), 'Q2_1': ...
[ "You can use str.extract (or str.split) to get the left/right parts around vs., then convert to frozenset and use duplicated for boolean indexing:\ns = df['Q0_0'].str.extract('(\\w+)\\s*vs\\.?\\s*(\\w+)').agg(frozenset, axis=1)\n# or\n# s = df['Q0_0'].str.split(r'\\s*vs\\.?\\s*', expand=True).agg(frozenset, axis=1)...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074571381_dataframe_pandas_python.txt
Q: Clustering near Lines using coordinates in Python I have a list with x- and y-coordinates of start and Endpoints of some lines.Lines as csv 331,178,486,232 185,215,386,308 172,343,334,419 406,128,570,165 306,106,569,166 159,210,379,299 236,143,526,248 303,83,516,178 409,62,572,106 26,287,372,427 31,288,271,381 193...
Clustering near Lines using coordinates in Python
I have a list with x- and y-coordinates of start and Endpoints of some lines.Lines as csv 331,178,486,232 185,215,386,308 172,343,334,419 406,128,570,165 306,106,569,166 159,210,379,299 236,143,526,248 303,83,516,178 409,62,572,106 26,287,372,427 31,288,271,381 193,228,432,330 120,196,432,329 136,200,374,297 111,189,33...
[ "You could throw a clustering on it, but it has trouble with the lonely line at the end\n\n\ndata = [[331,178,486,232],\n[185,215,386,308],\n[172,343,334,419],\n[406,128,570,165],\n[306,106,569,166],\n[159,210,379,299],\n[236,143,526,248],\n[303,83,516,178],\n[409,62,572,106],\n[26,287,372,427],\n[31,288,271,381],\...
[ 0 ]
[]
[]
[ "cluster_analysis", "distance", "line", "list", "python" ]
stackoverflow_0074559073_cluster_analysis_distance_line_list_python.txt
Q: How do I convert a string into a format to compare it with another date? I used regex to find these dates in a string matches = ['10 October 2019', '20 October 2019', '10 October 2019', '25 October 2019'] matches[0] and matches[2] are dates that a task was assigned, matches[1] and matches[3] are the due dates for...
How do I convert a string into a format to compare it with another date?
I used regex to find these dates in a string matches = ['10 October 2019', '20 October 2019', '10 October 2019', '25 October 2019'] matches[0] and matches[2] are dates that a task was assigned, matches[1] and matches[3] are the due dates for the task. I need to check if the tasks are overdue, so I need to check if mat...
[ "You need to convert that string to actual date. as below code:\ndatetime.strptime('10 October 2019', '%d %B %Y') > datetime.today()\n\n" ]
[ 0 ]
[]
[]
[ "date", "python" ]
stackoverflow_0074571394_date_python.txt
Q: PyCharm cannot install packages Short description: two computers in the same network, in the new one only those python scripts work that use native packages. I have Pycharm in my old computer and it has worked fine. Now I got a new computer, installed the most recent version of Python and Pycharm, then opened one ...
PyCharm cannot install packages
Short description: two computers in the same network, in the new one only those python scripts work that use native packages. I have Pycharm in my old computer and it has worked fine. Now I got a new computer, installed the most recent version of Python and Pycharm, then opened one of my old projects. Both the old and ...
[ "If you want to use venv in the network, please use SSH interpreter. Pycharm supports this method. Shared folders are not a recommended usage, For pycharm, it will consider this as a local file. If the file map is not downloaded locally, it will make an error.\nAnother way is to reinstall the project environment on...
[ 1, 0 ]
[]
[]
[ "pandas", "pycharm", "python", "python_3.x", "windows_10" ]
stackoverflow_0074377753_pandas_pycharm_python_python_3.x_windows_10.txt
Q: Faster way to package a folder into a file with Python I would like to package a folder into a file, I do not need compression. All alternatives I tried were slow. I have tried: The zipfile library with ZIP_STORED (no compression) import zipfile output_filename="folder.zip" source_dir = "folder" with zipfile.Zip...
Faster way to package a folder into a file with Python
I would like to package a folder into a file, I do not need compression. All alternatives I tried were slow. I have tried: The zipfile library with ZIP_STORED (no compression) import zipfile output_filename="folder.zip" source_dir = "folder" with zipfile.ZipFile(output_filename, 'w', zipfile.ZIP_STORED) as zipf: ...
[]
[]
[ "I am not quite sure if it is that faster but if you are running linux you could try tar command:\nimport time\nimport os\n\nstart = time.time()\n\nos.system(\"tar -cvf name.tar /path/to/directory\")\n\nend = time.time()\nprint(\"Elapsed time: %s\"%(end - start,))\n\nIf you also need file compression you need to ad...
[ -1 ]
[ "compression", "python", "tar", "zip" ]
stackoverflow_0074571456_compression_python_tar_zip.txt
Q: Django FormView and ListView multiple inheritance error Problem I mad a AccesCheck Mixin, and view named ListFormView that inherits AccessCheck, FormView and ListView to show list and create/update Worker objects. But when I try to add new data by POST method, django keeps returning Attribute Error : Worker object...
Django FormView and ListView multiple inheritance error
Problem I mad a AccesCheck Mixin, and view named ListFormView that inherits AccessCheck, FormView and ListView to show list and create/update Worker objects. But when I try to add new data by POST method, django keeps returning Attribute Error : Worker object has no attribute 'object_list' error. What is more confusing...
[ "That's classic problem of OOP. You have two inherited classes with the same method get_context_data(). The target class always getting code of the method from first inherited class. In this case ListFormView.get_context_data() has the same code as the AccessCheck.get_context_data() and ListFormView class doesn't k...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074567629_django_python.txt
Q: What is the special file that each package in Python must contain? Please answer of this question. special file in Python ? A: I think you are referring to a __init__.py file. Often left blank.
What is the special file that each package in Python must contain?
Please answer of this question. special file in Python ?
[ "I think you are referring to a\n\n__init__.py\n\nfile. Often left blank.\n" ]
[ 0 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0074571570_python_python_2.7.txt
Q: if .isin() dataframe one, check condition in dataframe 2, append new dataframe with checked conditions i have two dataframes df1 has a list of ids and dates id e1 e2 e3 1 2012-09-12 2001-03-06 1999-09-03 2 2009-09-07 2002-04-06 2003-01-02 3 2005-08-09 2005-06-04 2008-01-02 df2 has the same ids, and other valu...
if .isin() dataframe one, check condition in dataframe 2, append new dataframe with checked conditions
i have two dataframes df1 has a list of ids and dates id e1 e2 e3 1 2012-09-12 2001-03-06 1999-09-03 2 2009-09-07 2002-04-06 2003-01-02 3 2005-08-09 2005-06-04 2008-01-02 df2 has the same ids, and other values id e1 e2 e3 1 A120 B130 C122 2 BD43 A200 A111 3 C890 B123 A190 I want to itera...
[ "You can use boolean indexing:\nref = '2005-01-01'\n\n# is the date < ref?\nm1 = df1.set_index('id').le(ref)\n# is the string starting with A?\nm2 = df2.set_index('id').apply(lambda s: s.str.startswith('A'))\n\n# if both conditions are matched anywhere in the row, drop it\nout = df1[~(m1&m2).any(axis=1).to_numpy()]...
[ 0 ]
[]
[]
[ "dataframe", "for_loop", "pandas", "python" ]
stackoverflow_0074571438_dataframe_for_loop_pandas_python.txt
Q: working outside of application context - Flask def get_db(self,dbfile): if hasattr(g, 'sqlite_db'): self.close_db(g.sqlite_db) try: g.sqlite_db = self.connect_db('{}/{}'.format(app.root_path, dbfile)) except sqlite3.OperationalError as e: raise e return g.sqlite_db Hi this code is...
working outside of application context - Flask
def get_db(self,dbfile): if hasattr(g, 'sqlite_db'): self.close_db(g.sqlite_db) try: g.sqlite_db = self.connect_db('{}/{}'.format(app.root_path, dbfile)) except sqlite3.OperationalError as e: raise e return g.sqlite_db Hi this code is located inside DB class, The error I get is Runti...
[ "Maybe you need to call your function inside an application context:\nwith app.app_context():\n # call your method here\n\n", "From the Flask source code in flask/globals.py: \n_app_ctx_err_msg = '''\\\nWorking outside of application context.\n\nThis typically means that you attempted to use functionality that n...
[ 32, 22, 20, 3, 2, 2, 1, 1, 0, 0 ]
[ "Install this version of flask using\npip install flask-sqlalchemy==2.5.1\n\nthen run db.create_all() and it will run.\n", "ERROR:This typically means that you attempted to use functionality that needed\nto interface with the current application object in a way. To solve\nthis set up an application context with ...
[ -1, -33 ]
[ "flask", "python" ]
stackoverflow_0034122949_flask_python.txt
Q: How to stop a loop when i press a button in python In the code in the follow lines is tried to implement an average calculator which calculate the average of given numbers with the division of the sum of given numbers through the count of multitude of them. The problem is that when is pressed the S button does not...
How to stop a loop when i press a button in python
In the code in the follow lines is tried to implement an average calculator which calculate the average of given numbers with the division of the sum of given numbers through the count of multitude of them. The problem is that when is pressed the S button does not break the loop which count the multitude of numbers cou...
[ "Try this:\nimport itertools\ntotal=0\nnumbers=[]\n\nfor i in itertools.count(1):\n numbers.append(int(input (\"Enter number:\")))\n\n print(\"You give\" , i)\n\n s=str(input(\"If you want to stop press S:\"))\n if s.lower() == \"s\":\n total = sum(numbers)/i\n print (\" ...
[ 0 ]
[]
[]
[ "average", "character", "iteration", "python" ]
stackoverflow_0074571522_average_character_iteration_python.txt
Q: Why isnt the append() working in this block of code? I've broken down the pieces of this code individually and it all works fine. Yet the append() method only appends once and then refuses to add anything else. I am absolutely losing my mind over this. x = input("Input Password: ") epicfail = [] def numberchecke...
Why isnt the append() working in this block of code?
I've broken down the pieces of this code individually and it all works fine. Yet the append() method only appends once and then refuses to add anything else. I am absolutely losing my mind over this. x = input("Input Password: ") epicfail = [] def numberchecker(b): return any(i.isdigit() for i in b) def spaceche...
[ "As you use elif, when one condition is met, all the others are ignored. If you want multiple to trigger, just use if instead.\nFurthermore, you can remove \"== True\" when you are checking a boolean, and replace \"if xxx == False:\" by \"if not xxx:\".\n" ]
[ 1 ]
[]
[]
[ "methods", "new_operator", "python" ]
stackoverflow_0074571480_methods_new_operator_python.txt
Q: How to delete/not save files when Jupyter notebook in ran with plotly pio.renderers.default = "iframe"? I am plotting a plot using plotly python (inside jupyter notebook) like below- fig = make_subplots(rows=1, cols=1, vertical_spacing=0.00) fig.add_trace( go.Scatter( x=data.index, ...
How to delete/not save files when Jupyter notebook in ran with plotly pio.renderers.default = "iframe"?
I am plotting a plot using plotly python (inside jupyter notebook) like below- fig = make_subplots(rows=1, cols=1, vertical_spacing=0.00) fig.add_trace( go.Scatter( x=data.index, y=data.col_name, name="col_name", line=dict(color="#90EE90"), ...
[ "Try adding these into the import section:\nfrom plotly.offline import plot, iplot, init_notebook_mode\ninit_notebook_mode(connected=True)\npio.renderers\n\n" ]
[ 1 ]
[]
[]
[ "jupyter_notebook", "plotly", "plotly_python", "python" ]
stackoverflow_0074571546_jupyter_notebook_plotly_plotly_python_python.txt
Q: multiply values from two different dataframes I have two dataframes: number 1 word weight book 0.2 water 0.5 number two description book water xyz 1 0 abc 0 1 I would like to simply multiply each word weight with the values in the second dataframe and paste them in the second dataframe - instead of 1/0 A:...
multiply values from two different dataframes
I have two dataframes: number 1 word weight book 0.2 water 0.5 number two description book water xyz 1 0 abc 0 1 I would like to simply multiply each word weight with the values in the second dataframe and paste them in the second dataframe - instead of 1/0
[ "If match columns names in df2 without description with column df1.word you can use:\ndf = df2.set_index('description').mul(df1.set_index('word')['weight']).reset_index()\nprint (df)\n description book water\n0 xyz 0.2 0.0\n1 abc 0.0 0.5\n\nOr if need multiple only matched columns use:\...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074571601_dataframe_pandas_python.txt
Q: I would like to know how to not reinstall the app every time you start a new test I'm performing E2E mobile tests with Appium and Pytest. I would like to know how to not reinstall the app every time you start a new test. I already tried using noReset and it didn't solve my problem. I've also tried using the scope=...
I would like to know how to not reinstall the app every time you start a new test
I'm performing E2E mobile tests with Appium and Pytest. I would like to know how to not reinstall the app every time you start a new test. I already tried using noReset and it didn't solve my problem. I've also tried using the scope='class' in the driver setup in the conftest, but if I put that in, the tests that run a...
[ "First of all you should make sure to reuse the driver in every test. The initialisation of the driver (which will happen in the first test) should take care of the app install. Take a look at noReset and fullReset, see here for the specifics, you might need to use both?\nThen after every test, make sure to get to ...
[ 0 ]
[]
[]
[ "appium", "automated_tests", "mobile", "pytest", "python" ]
stackoverflow_0074546638_appium_automated_tests_mobile_pytest_python.txt
Q: calculate diff between two values and then % difference associated to unique references month by month in pandas dataframe I have a pandas dataframe; ID MONTH TOTAL 0 REF1 1 500 1 REF1 2 501 2 REF1 3 620 3 REF2 8 5001 4 REF2 9 5101 5 REF2 10 5701 6 REF2 11 7501 7 REF2 7 6501 8 REF2 6 1501 I need to do a...
calculate diff between two values and then % difference associated to unique references month by month in pandas dataframe
I have a pandas dataframe; ID MONTH TOTAL 0 REF1 1 500 1 REF1 2 501 2 REF1 3 620 3 REF2 8 5001 4 REF2 9 5101 5 REF2 10 5701 6 REF2 11 7501 7 REF2 7 6501 8 REF2 6 1501 I need to do a comparison between of difference between the ID's previous month's TOTAL. At the moment I can calculate the d...
[ "You can shift the Month by adding 1 (eventually use a more complex logic if you have real dates), then perform a self-merge and subtract:\ndf['diff'] = df['TOTAL'].sub(\n df[['ID', 'MONTH']]\n .merge(df.assign(MONTH=df['MONTH'].add(1)),\n how='left')['TOTAL']\n ...
[ 1 ]
[]
[]
[ "compare", "dataframe", "pandas", "python" ]
stackoverflow_0074571682_compare_dataframe_pandas_python.txt
Q: How do I return the value of a key that is nested in an anonymous JSON block with jsonpath? I am trying to extract the value of a key that is nested in an anonymous JSON block. This is what the JSON block looks like after result: "extras": [ { "key": "alternative_name", "value": "catr" ...
How do I return the value of a key that is nested in an anonymous JSON block with jsonpath?
I am trying to extract the value of a key that is nested in an anonymous JSON block. This is what the JSON block looks like after result: "extras": [ { "key": "alternative_name", "value": "catr" }, { "key": "lineage", "value": "This dataset was amalgamated, optimised an...
[ "This should work:\n$.result.extras[?(@.key==\"update_frequency\")].value\n\n" ]
[ 1 ]
[]
[]
[ "jsonpath", "python" ]
stackoverflow_0074571085_jsonpath_python.txt
Q: How to display the values above markers in plotly scatter graph object? I can’t seem to find the argument to always display the scatter y values above the points in python plotly. I tried to search for it and failed. I just want something like that hover number to always be on. A: Do you need something similar t...
How to display the values above markers in plotly scatter graph object?
I can’t seem to find the argument to always display the scatter y values above the points in python plotly. I tried to search for it and failed. I just want something like that hover number to always be on.
[ "Do you need something similar to this in the docs?\nhttps://plotly.com/python/line-and-scatter/#connected-scatterplots\nimport plotly.express as px\n\ndf = px.data.gapminder().query(\"country in ['Canada', 'Botswana']\")\n\nfig = px.scatter(\n df, x=\"lifeExp\", y=\"gdpPercap\", color=\"country\", text=\"ye...
[ 0 ]
[]
[]
[ "plotly", "plotly.graph_objects", "plotly_python", "python", "scatter_plot" ]
stackoverflow_0074567368_plotly_plotly.graph_objects_plotly_python_python_scatter_plot.txt
Q: Why does this dictionary go out of range? So in my school, we are working on an encoding project making a compression algorithm. I'm working on one that uses a mixture of dictionaries and RLE. I'm currently testing out making an embedded dictionary and placing values into it using pandas. Issue is, something goes ...
Why does this dictionary go out of range?
So in my school, we are working on an encoding project making a compression algorithm. I'm working on one that uses a mixture of dictionaries and RLE. I'm currently testing out making an embedded dictionary and placing values into it using pandas. Issue is, something goes out of range somewhere and expands the pd DataF...
[ "After this line\ndf = pd.DataFrame(allframesdict)\n\ndf will contains 1-based columns\n>>> df.columns\nInt64Index([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n ...\n 503, 504, 505, 506, 507, 508, 509, 510, 511, 512],\n dtype='int64', length=512)\n\nAnd code\nfor x in range(51...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074571449_pandas_python.txt
Q: Web Scrapping via python show AttributeError: 'NoneType' object has no attribute 'full_text' Scrap the data from the website by using python. from requests_html import HTMLSession import http.client http.client._MAXHEADERS = 1000 url='https://agedcarestore.com.au/product-category/physio-products/arthritis/' s=HT...
Web Scrapping via python show AttributeError: 'NoneType' object has no attribute 'full_text'
Scrap the data from the website by using python. from requests_html import HTMLSession import http.client http.client._MAXHEADERS = 1000 url='https://agedcarestore.com.au/product-category/physio-products/arthritis/' s=HTMLSession() r=s.get(url) print(r.html.find('#header')) items=r.html.find('div.product-small.box')...
[ "You shouldn't try to get .full_text without checking if find returned something. You should remove the .full_text part from the lines and just build product with the checks, like\n product = {\n 'title': title.full_text.strip() if title else 'DEFAULT_TITLE',\n 'price': price[0].full_text.strip() i...
[ 0 ]
[]
[]
[ "image", "python", "web_scraping", "woocommerce" ]
stackoverflow_0074525951_image_python_web_scraping_woocommerce.txt
Q: Screenshots of iframes taking by python selenium are cropped (both chrome and firefox webdrivers) I am trying to screenshot an image located inside an iframe in an ads creative in headless mode. Indeed, I will have to screenshot many of such iframes and the final script will run on a remote server. No matter what ...
Screenshots of iframes taking by python selenium are cropped (both chrome and firefox webdrivers)
I am trying to screenshot an image located inside an iframe in an ads creative in headless mode. Indeed, I will have to screenshot many of such iframes and the final script will run on a remote server. No matter what I have tried, screenshots always seem to be cropped when I use the headless mode of selenium. I have se...
[ "I had the same issue with Selenuium.\nIn my case additional waiting after resolving the URL helped, for instance:\n...\n\ndriver.get(url)\ntime.sleep(10)\n\nWebDriverWait(driver, 20).until(\n EC.frame_to_be_available_and_switch_to_it((By.ID, id_iframe))\n)\n\n...\n\nI can't actually explain why it works like th...
[ 0 ]
[]
[]
[ "iframe", "python", "python_imaging_library", "selenium", "selenium_webdriver" ]
stackoverflow_0074292472_iframe_python_python_imaging_library_selenium_selenium_webdriver.txt
Q: How to create and deploy AWS lambda from boto3 for node.js app in python I am uploading NodeJS file to s3 bucket now I want to run the node.js files uploaded to s3 bucket Here is my current code: s3=boto3.client('s3', zone,aws_access_key_id=aws_access_key,aws_secret_access_key=aws_secret_key) with open(generatedfo...
How to create and deploy AWS lambda from boto3 for node.js app in python
I am uploading NodeJS file to s3 bucket now I want to run the node.js files uploaded to s3 bucket Here is my current code: s3=boto3.client('s3', zone,aws_access_key_id=aws_access_key,aws_secret_access_key=aws_secret_key) with open(generatedfolder1+"package.json", "rb") as f: s3.upload_fileobj(f, bucket, gendirname+'...
[ "It sounds like your goal is to deploy a Lambda programatically. Use the boto3 Lambda client's create_function API to do this. The Lambda service indeed uses S3 to store the function artefacts, but you wouldn't typically interact with S3 directly. The docs have a step-by-step create-function example using the CL...
[ 1 ]
[]
[]
[ "amazon_s3", "aws_lambda", "boto3", "python" ]
stackoverflow_0074560718_amazon_s3_aws_lambda_boto3_python.txt
Q: Problem in skimage rgb2hed when applied to part of a matrix I am trying to convert an image from RBG to HED using the rgb2hed function from skimage. My image is very big and if I just try and put the whole thing into the rgb2hed function then I run out of memory. To get around this I have written some code to spli...
Problem in skimage rgb2hed when applied to part of a matrix
I am trying to convert an image from RBG to HED using the rgb2hed function from skimage. My image is very big and if I just try and put the whole thing into the rgb2hed function then I run out of memory. To get around this I have written some code to split the image into sections and apply rgb2hed to each section, but ...
[ "The issue is related to dtype mismatching:\n\nThe dtype of sample = np.random.randint(...) is 'int32'\nThe dtype of rgb2hed(...) is float64\n\nWhen updating a slice of NumPy array, the data is converted to the type of that updated NumPy array.\nThe expression sample[x_start:x_end, :, :] = rgb2hed(...) automaticall...
[ 0 ]
[]
[]
[ "image_processing", "python", "scikit_image" ]
stackoverflow_0074567827_image_processing_python_scikit_image.txt
Q: Allign left and right in python? I've seen a question on justifying a 'print' right, but could I have text left and right on the same line, for a --help? It'd look like this in the terminal: | | |Left Right| | ...
Allign left and right in python?
I've seen a question on justifying a 'print' right, but could I have text left and right on the same line, for a --help? It'd look like this in the terminal: | | |Left Right| | ...
[ "I think you can use sys.stdout for this:\nimport sys\n\ndef stdout(message):\n sys.stdout.write(message)\n sys.stdout.write('\\b' * len(message)) # \\b: non-deleting backspace\n\ndef demo():\n stdout('Right'.rjust(50))\n stdout('Left')\n sys.stdout.flush()\n print()\n\ndemo()\n\nYou can replace...
[ 4, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0009640109_python.txt
Q: 400 Bad request with json object of curl POST command while flask is running I just made flask API. OS is Win10. python version is 3.9.13. While the flask is running, I sent the following command. curl -X POST http://127.0.0.1:5000/detect -H "Content-Type: application/json" -d '{"filename": "xxx.jpg"}' However, ...
400 Bad request with json object of curl POST command while flask is running
I just made flask API. OS is Win10. python version is 3.9.13. While the flask is running, I sent the following command. curl -X POST http://127.0.0.1:5000/detect -H "Content-Type: application/json" -d '{"filename": "xxx.jpg"}' However, I received 400 BAD Request. <!doctype html> <html lang=en> <title>400 Bad Request<...
[ "you are returning a non-json response.\ntry this:-\n@api.post(\"/detect\")\ndef detection():\nreturn jsonify({\"response\":flask_test.detection(request)})\n\n" ]
[ 0 ]
[]
[]
[ "curl", "flask", "json", "python", "python_3.x" ]
stackoverflow_0074469709_curl_flask_json_python_python_3.x.txt
Q: how do I find a continuos number in dataframe and apply to new column I have a huge dataframe around 5000 rows, I need to find out how many times a pattern occur in a column and add a new column for it, I am able to use np.where to get the pattern to 1 but I don't know how to count the pattern and add to new colum...
how do I find a continuos number in dataframe and apply to new column
I have a huge dataframe around 5000 rows, I need to find out how many times a pattern occur in a column and add a new column for it, I am able to use np.where to get the pattern to 1 but I don't know how to count the pattern and add to new column, I did a search online try to use loop but I can't figure out how to use ...
[ "you can use:\ndf['new_column'] = (df.P != df.P.shift()).cumsum() #get an id according to P\nmask=df.groupby('new_column')['P'].sum() #what is the total value for each group\n\nduplicated = df.duplicated('new_column',keep='last')\ndf.loc[~duplicated, ['new_column']] = np.nan #set nan to last rows for each group. We...
[ 1, 0 ]
[]
[]
[ "dataframe", "design_patterns", "numpy", "pandas", "python" ]
stackoverflow_0074567984_dataframe_design_patterns_numpy_pandas_python.txt
Q: need to generate a new data frame with more no. of similar record from an existing data frame I have the below dataframe data sample, val df= spark.read.option("inferSchema",true).orc("abc/path/abc.snappy.orc") df.show() ID, date, timestamp, count, idcount, unit, code, Pcode, ccode, bid, vcode 12345432,10-11-20...
need to generate a new data frame with more no. of similar record from an existing data frame
I have the below dataframe data sample, val df= spark.read.option("inferSchema",true).orc("abc/path/abc.snappy.orc") df.show() ID, date, timestamp, count, idcount, unit, code, Pcode, ccode, bid, vcode 12345432,10-11-2011,11:11:12.555,0,0,XVC_AS,12,14,19,123454323,qweds I want to write a pyspark code to generate mor...
[ "After the update my solution seems to be quite cumnbersome but this is all i can offer so far.\nAssuming you have your ID column as dataframe index, you can simply do:\nimport numpy as np\nincr = 10\ndf = df.reindex(np.append(df.index.values,\n range(df.index.max()+1, df.index.max()+incr))...
[ 0 ]
[]
[]
[ "apache_spark", "pyspark", "python" ]
stackoverflow_0074571730_apache_spark_pyspark_python.txt
Q: Upload Images To S3 Via URL Python im just searching for a method to upload images to S3 directly via an URL with Python. What i mean by that is: I have an URL e.g. https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/1200px-Google_2015_logo.svg.png now i want my code to take that image u...
Upload Images To S3 Via URL Python
im just searching for a method to upload images to S3 directly via an URL with Python. What i mean by that is: I have an URL e.g. https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/1200px-Google_2015_logo.svg.png now i want my code to take that image url and save the image in my S3 bucket wi...
[ "If it's working only through EC2, it might be a permission/firewall issue?\nThis might be of help.\nhttps://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-upload-image-s3/\nboto3 would be the way to go for Python.\nhttps://boto3.amazonaws.com/v1/documentation/api/latest/index.html\nSomeone has done som...
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "python" ]
stackoverflow_0074571997_amazon_s3_amazon_web_services_python.txt
Q: Google Calendar API event time update without changing date Is there any way to update the current time of an event without changing the current date using google calendar API with python? I'm working on a project that sync zoho people calendar with google calendar and I've to update the all day Leave event and s...
Google Calendar API event time update without changing date
Is there any way to update the current time of an event without changing the current date using google calendar API with python? I'm working on a project that sync zoho people calendar with google calendar and I've to update the all day Leave event and set a duration of 9 hours (9AM to 6PM). I've done the synching par...
[ "Using gcsa, this would look like:\nfrom gcsa.google_calendar import GoogleCalendar\nfrom datetime import datetime, time\n\ngc = GoogleCalendar('path/to/credentials.json')\n\nevent = gc.get_event('event_id')\nevent.start = datetime.combine(event.start, time(hour=9))\nevent.end = datetime.combine(event.end, time(hou...
[ 0 ]
[]
[]
[ "google_calendar_api", "python", "zoho" ]
stackoverflow_0074558603_google_calendar_api_python_zoho.txt
Q: Replicate Random Numbers from Visual Basic with Python I have a code in Visual Basic that generates a vector of random numbers for a given seed (456 in my case). I need to replicate that code in Python and I am thinking if it is possible to generate with Python the same vector of random numbers, that is, to select...
Replicate Random Numbers from Visual Basic with Python
I have a code in Visual Basic that generates a vector of random numbers for a given seed (456 in my case). I need to replicate that code in Python and I am thinking if it is possible to generate with Python the same vector of random numbers, that is, to select the same seed as in VBA. Let me show an example: In VBA I h...
[ "Something like this:\nimport random\nrandom.seed(seed)\narr=[]\nfor i in range(n):\n arr.append(random.random())\n\nNote random.random() returns value between 0 and 1 if you want integers over a range use random.randint(start, stop)\n" ]
[ 0 ]
[]
[]
[ "python", "random_seed", "vba" ]
stackoverflow_0074572032_python_random_seed_vba.txt
Q: DataFrame.set_index returns 'str' object is not callable I'm not looking for a solution here as I found a workaround; mostly I'd just like to understand why my original approach didn't work given that the work around did. I have a dataframe of 2803 rows with the default numeric key. I want to replace that with the...
DataFrame.set_index returns 'str' object is not callable
I'm not looking for a solution here as I found a workaround; mostly I'd just like to understand why my original approach didn't work given that the work around did. I have a dataframe of 2803 rows with the default numeric key. I want to replace that with the values in column 0, namely TKR. So I use f.set_index('TKR') a...
[ "You might have accidentally assigned the pd.DataFrame.set_index() to a value.\nexample of this mistake: f.set_index = 'intended_col_name'\nAs a result for the rest of your code .set_index was changed into a str, which is not callable, resulting in this error.\nTry restarting your notebook, remove the wrong code an...
[ 6, 1, 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0044593223_pandas_python.txt
Q: Automatically delete items from multiple lists at once I currently have a small problem with the processing of some data that I recover. I'm getting data that's constantly changing and it's displayed as a list like this: [['test', 'test', 'test', 'test'], ['test', 'test', 'test', 'test'], ['test', 'test', 'test', ...
Automatically delete items from multiple lists at once
I currently have a small problem with the processing of some data that I recover. I'm getting data that's constantly changing and it's displayed as a list like this: [['test', 'test', 'test', 'test'], ['test', 'test', 'test', 'test'], ['test', 'test', 'test', ' test']] I would like to know how it is possible to automa...
[ "You could either use .pop(index) or del arr[index]. But since you said it can vary I would use len(arr) to make sure the arr length goes up to the index you are trying to delete\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074572094_python.txt
Q: matplotlib logarithmic colormap for logarithmic surface plot I'm using python to create a 3D surface map, I have an array of data I'm trying to plot as a 3D surface, the issue is that I have logged the Z axis (necessary to show peaks in data) which means the default colormap doesn't work (displays one continous co...
matplotlib logarithmic colormap for logarithmic surface plot
I'm using python to create a 3D surface map, I have an array of data I'm trying to plot as a 3D surface, the issue is that I have logged the Z axis (necessary to show peaks in data) which means the default colormap doesn't work (displays one continous color). I've tried using the LogNorm to normalise the colormap but a...
[ "Edit: to solve your problem you are taking the log of the data then you are taking it again when calculating the norm, simply remove the norm and apply vmin and vmax directly to the drawing function\nax.plot_surface(X, Y, np.transpose(np.log10(Z)), cmap='rainbow',vmin=np.log10(1e-15),vmax=np.log10(Z_max))\n\nyou c...
[ 2, 2 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0074571588_matplotlib_numpy_python.txt
Q: How to create a 3D image with series of 2D Image I have series of 2D tiff images of a sample, I want to create or reproduce 3D image/volume using those 2d image for 3D visualization. I found this link Reconstructing 3D image from 2D image have similar question but It discussed about CT reconstruction using backpr...
How to create a 3D image with series of 2D Image
I have series of 2D tiff images of a sample, I want to create or reproduce 3D image/volume using those 2d image for 3D visualization. I found this link Reconstructing 3D image from 2D image have similar question but It discussed about CT reconstruction using backprojection algorithm. But I already have 2D view of samp...
[ "I wanna check that this is what you're looking for before I go on a long explanation of something that could be irrelevant.\nI have a series of 2d images of a tumor. I'm constructing a 3d shell from the image slices and creating a .ply file from that shell.\n2D slices\n\n3D Reconstruction\n\nIs this the sort of th...
[ 6, 1 ]
[]
[]
[ "3d_reconstruction", "image_processing", "python" ]
stackoverflow_0066699525_3d_reconstruction_image_processing_python.txt
Q: TypeError: Cannot join tz-naive with tz-aware DatetimeIndex all! I am trying to generate results of this repo https://github.com/ArnaudBu/stock-returns-prediction for stocks price prediction based on financial analysis. Running the very first step 1_get_data.py I come across an error: TypeError: Cannot join tz...
TypeError: Cannot join tz-naive with tz-aware DatetimeIndex
all! I am trying to generate results of this repo https://github.com/ArnaudBu/stock-returns-prediction for stocks price prediction based on financial analysis. Running the very first step 1_get_data.py I come across an error: TypeError: Cannot join tz-naive with tz-aware DatetimeIndex The code is # -*- coding: utf-...
[ "I have not managed to reproduce your dataframes, but generally this type of error is easily removed by doing df.tz_localize(None).\nThis will convert a tz-aware df to a tz-naive df.\nso try applying this to the full_data dataframe of yours.\n", "all!\nI just found that the issue was related to the full_data[tick...
[ 0, 0 ]
[]
[]
[ "analysis", "datetimeindex", "finance", "python", "stock" ]
stackoverflow_0074565844_analysis_datetimeindex_finance_python_stock.txt
Q: Split string by list of indexes I need a function that splits the string by indexes specified in indexes. Wrong indexes must be ignored. My code: def split_by_index(s: str, indexes: List[int]) -> List[str]: parts = [s[i:j] for i,j in zip(indexes, indexes[1:]+[None])] return parts My strings: split_by_inde...
Split string by list of indexes
I need a function that splits the string by indexes specified in indexes. Wrong indexes must be ignored. My code: def split_by_index(s: str, indexes: List[int]) -> List[str]: parts = [s[i:j] for i,j in zip(indexes, indexes[1:]+[None])] return parts My strings: split_by_index("pythoniscool,isn'tit?", [6, 8, 12,...
[ "You need to start from the 0th index, while you are starting from 6:8 in your first example and 42:None in the second:\ndef split_by_index(s: str, indexes: List[int]) -> List[str]:\n parts = [s[i:j] for i,j in zip([0] + indexes, indexes + [None])]\n return parts\n\n", "the only appending zero to your list ...
[ 0, 0, 0 ]
[]
[]
[ "indexing", "python", "split", "string" ]
stackoverflow_0074571584_indexing_python_split_string.txt
Q: Direct assignment to the forward side of a many-to-many set is prohibited. Use coolbox_id.set() instead. helpme I am getting this error when i use many to many field help me plsssssss views.py def add_ship(request): if request.method=='POST': m_namedriver = request.POST.get('m_namedriver'...
Direct assignment to the forward side of a many-to-many set is prohibited. Use coolbox_id.set() instead. helpme
I am getting this error when i use many to many field help me plsssssss views.py def add_ship(request): if request.method=='POST': m_namedriver = request.POST.get('m_namedriver') driver_id = Driver.objects.get(driver_id=m_namedriver) m_licensepl = request.POST.get('m_licensepl...
[ "You need to pass a List of objects of not a single object at save\nyou can do like this ...\ndef add_ship(request):\n if request.method=='POST':\n \n m_namedriver = request.POST.get('m_namedriver')\n driver_id = Driver.objects.get(driver_id=m_namedriver)\n\n m_licensepl = request.POS...
[ 1, 0 ]
[ "<div class=\"col-md-6 mb-4\">\n <div class=\"form-outline multip_select_box\">\n <label class=\"form-label\" for=\"Coolboxs\">Coolboxs ID</label>\n <br>\n <select name=\"m_weightcoolbox\" id=\"m_weightcoolbox\" class=...
[ -1 ]
[ "django_models", "django_views", "python" ]
stackoverflow_0074570113_django_models_django_views_python.txt
Q: Pyspark lambda operation to create key pairs I already have code which maps to this ['vita', 'oscura', 'smarrita', 'dura', 'forte', 'paura', 'morte', 'trovai', 'scorte', 'v’intrai'] I want this [('vita','oscura',1),('oscura','smarrita',1),('smarrita','dura',1), ('dura','forte',1) etc I thought that I could do th...
Pyspark lambda operation to create key pairs
I already have code which maps to this ['vita', 'oscura', 'smarrita', 'dura', 'forte', 'paura', 'morte', 'trovai', 'scorte', 'v’intrai'] I want this [('vita','oscura',1),('oscura','smarrita',1),('smarrita','dura',1), ('dura','forte',1) etc I thought that I could do this via a lambda function, where for every line, i...
[ "For Python 3.10 and above one can use pairwise\nSample code snippet can be,\nimport itertools\n\ninput_list = ['vita', 'oscura', 'smarrita', 'dura', 'forte', 'paura', 'morte', 'trovai', 'scorte', 'v’intrai']\n\noutput = [element + (1, ) for element in itertools.pairwise(input_list)]\n\nFor python versions below 3....
[ 1 ]
[]
[]
[ "lambda", "map_function", "python" ]
stackoverflow_0074571753_lambda_map_function_python.txt
Q: Pyfirmata throws error after creating arduino object I'm trying to start an arduino project but every time I try running it it throws an error. I think I might have gotten some of the setup wrong? I've uploaded the Standard Firmata Sketch to the Arduino Mega and installed pyFirmata. I can't really think of what el...
Pyfirmata throws error after creating arduino object
I'm trying to start an arduino project but every time I try running it it throws an error. I think I might have gotten some of the setup wrong? I've uploaded the Standard Firmata Sketch to the Arduino Mega and installed pyFirmata. I can't really think of what else I could've done wrong. Note that I'd already tried in a...
[ "This is probably a compatibility issue between PyFirmata and your Python version.\ngetargspec is deprecated since Python 3.11.\nAn up-to-date PyFirmata version should have replaced this by getfullargspec.\nhttps://github.com/tino/pyFirmata/commit/1f6b116b80172e70c7866d595120413078ae1222\nAlso the PyFirmata documen...
[ 0 ]
[]
[]
[ "arduino", "pyfirmata", "python", "python_module" ]
stackoverflow_0074572015_arduino_pyfirmata_python_python_module.txt
Q: how can i make a conditional sort for storting a list of tuples? I have been trying to sort this list in a way that it should first sort based on the second item of the tuples but if two tuples have the same second item it should sort based on the first item alphabetically patient_list: list[tuple] = [("Johnson", ...
how can i make a conditional sort for storting a list of tuples?
I have been trying to sort this list in a way that it should first sort based on the second item of the tuples but if two tuples have the same second item it should sort based on the first item alphabetically patient_list: list[tuple] = [("Johnson", 9), ("Smith", 2), ("Perry", 4), ("Allison", 8), ("Bradley", 1), ("Tuck...
[ "You need to phrase the problem statement as the function that you pass as key=.\npatient_list.sort(key=lambda t: (t[1],t[0]))\n\nThis works because tuples sort the way you would expect. Since you want the data sorted in-place in patient_list, use .sort() instead of sorted().\n" ]
[ 0 ]
[]
[]
[ "conditional_statements", "lambda", "python", "sorting" ]
stackoverflow_0074572081_conditional_statements_lambda_python_sorting.txt
Q: TensorFlow: Couldn't understand the error mentioned below My code attempts to take different files as input and predict their language. This is the error I am getting every time I run the main file. At first, I thought it was a problem with the output path but so far it doesn't seem like that's the problem as I ha...
TensorFlow: Couldn't understand the error mentioned below
My code attempts to take different files as input and predict their language. This is the error I am getting every time I run the main file. At first, I thought it was a problem with the output path but so far it doesn't seem like that's the problem as I have gone through all the code files I have written and checked a...
[ "Maybe your way of naming files and paths makes windows unable to recognize the file location. You can test by running on linux. You should agree to use \"\\\" on Windows and avoid the \"-\" sign.\n" ]
[ 0 ]
[]
[]
[ "deep_learning", "machine_learning", "python", "python_3.x", "tensorflow" ]
stackoverflow_0074572198_deep_learning_machine_learning_python_python_3.x_tensorflow.txt
Q: Python dataframe find closest date for each ID I have a dataframe like this: data = {'SalePrice':[10,10,10,20,20,3,3,1,4,8,8],'HandoverDateA':['2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-03-30','2022-03-30'],'ID': ['Tom', 'Tom','Tom','J...
Python dataframe find closest date for each ID
I have a dataframe like this: data = {'SalePrice':[10,10,10,20,20,3,3,1,4,8,8],'HandoverDateA':['2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-03-30','2022-03-30'],'ID': ['Tom', 'Tom','Tom','Joseph','Joseph','Ben','Ben','Eden','Tim','Adam','Ada...
[ "IIUC, you can use:\ndata[['HandoverDateA', 'Sent']] = data[['HandoverDateA', 'Sent']].apply(pd.to_datetime)\n\nout = data.loc[data['HandoverDateA']\n .sub(data['Sent']).abs()\n .groupby(data['ID']).idxmin()]\n\nOutput:\n SalePrice HandoverDateA ID Tranche Totals Sent Amo...
[ 0, 0 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074571603_dataframe_datetime_pandas_python.txt
Q: How to tail and use grep for all the log files inside a folder and subfolders using subprocess? I am using flask and I am trying to tail and get the lines containing Error and or Warning in all the log files inside the folder and subfolders using subprocess. I show the outcome on the webapp using Jinja in my html ...
How to tail and use grep for all the log files inside a folder and subfolders using subprocess?
I am using flask and I am trying to tail and get the lines containing Error and or Warning in all the log files inside the folder and subfolders using subprocess. I show the outcome on the webapp using Jinja in my html file in a div. If I use "**/*.log" to select all log files in the folder and subfolders the div is em...
[ "It doesn't work because without shell=True, the run command passes the **/*.log argument literally without expanding the arguments.\nBut better drop all the underlying commands, pipes and processes. Why not just code it in python? My attempt (not tested)\nimport glob,re\n\n# list of matching lines\nout = []\n# mat...
[ 0 ]
[]
[]
[ "flask", "grep", "python", "subprocess", "tail" ]
stackoverflow_0074572211_flask_grep_python_subprocess_tail.txt
Q: Pandas: Merge two dataframes with timedelta I am attempting to perform an inner merge of two large dataframes having columns 'ID' and 'Date'. A sample of each is shown below: df1 ID Date 0 RHD78 2022-08-05 1 RHD78 2022-08-06 2 RHD78 2022-08-09 3 RHD78 2022-08-11 4 RHD78 2022-08-12 5 ...
Pandas: Merge two dataframes with timedelta
I am attempting to perform an inner merge of two large dataframes having columns 'ID' and 'Date'. A sample of each is shown below: df1 ID Date 0 RHD78 2022-08-05 1 RHD78 2022-08-06 2 RHD78 2022-08-09 3 RHD78 2022-08-11 4 RHD78 2022-08-12 5 RHD78 2022-08-14 6 RHD78 2022-08-15 7 RHD...
[ "Using df as your first dataframe and df2 as the second, i followed the same procedure as in this answer, which was to cross merge them together and then filter after the merge has occurred. A cross merge is just a blanket merge, which combines each row pair from each dataframe together. This might not be applicabl...
[ 2, 2, 1 ]
[]
[]
[ "dataframe", "merge", "pandas", "python", "python_3.x" ]
stackoverflow_0074567688_dataframe_merge_pandas_python_python_3.x.txt
Q: sqlalchemy can't read null dates from sqlite3 (0000-00-00): ValueError: year is out of range When I try to query a database containing dates such as 0000-00-00 00:00:00 with sqlachemy, I get ValueError: year is out of range. Here's the db dump: Here's the stacktrace: File "/home/rob/.virtualenvs/calif/lib/python3...
sqlalchemy can't read null dates from sqlite3 (0000-00-00): ValueError: year is out of range
When I try to query a database containing dates such as 0000-00-00 00:00:00 with sqlachemy, I get ValueError: year is out of range. Here's the db dump: Here's the stacktrace: File "/home/rob/.virtualenvs/calif/lib/python3.5/site-packages/sqlalchemy/engine/result.py" in items 163. return [(key, self[key]) for...
[ "Got the answer via inklesspen on IRC: Python datetime representation has minimum year and it's 1\n", "I was able to bypass the problem by using sqlalchemy.text\nfrom sqlalchemy import text\n\nwith engine.connect() as conn:\n result = conn.execute(text(\"select * from table\"))\n ....\n\n" ]
[ 0, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0040118266_python_sqlalchemy.txt
Q: BME280 on Raspberry Pi using Python 3 - Odd first reading I have 2 x Pimoroni BME280 and they both produce the same initial reading of 21.95*C 698.09hPa 76.34% humidity. Using this simple code import time from smbus2 import SMBus from bme280 import BME280 bus = SMBus(1) bme280 = BME280(i2c_dev=bus) while True: ...
BME280 on Raspberry Pi using Python 3 - Odd first reading
I have 2 x Pimoroni BME280 and they both produce the same initial reading of 21.95*C 698.09hPa 76.34% humidity. Using this simple code import time from smbus2 import SMBus from bme280 import BME280 bus = SMBus(1) bme280 = BME280(i2c_dev=bus) while True: temperature = bme280.get_temperature() pressure = bme280.g...
[ "I would presume that this is caused due to an initial transient value being outputted by the sensor as a result of initialising your sensor.\nIt would be interesting to see how an Arduino would handle the initialisation process\nvis-à-vis said transient value with your sensor.\nAs you said, if your continuous read...
[ 0 ]
[]
[]
[ "python", "raspberry_pi" ]
stackoverflow_0074566028_python_raspberry_pi.txt
Q: How to count number of points inside a circle I got this plot and I want to divide this plot into many different circles and need how many points in each circle. I am trying to plot radius of the circle with how many number of points inside the circle. A: Intuition:- Finding the distance between two points. (i....
How to count number of points inside a circle
I got this plot and I want to divide this plot into many different circles and need how many points in each circle. I am trying to plot radius of the circle with how many number of points inside the circle.
[ "Intuition:- Finding the distance between two points. (i.e sqrt((x2-x1)**2+(y2-y1)**2)) [Euclidean Formula]\n\n\nIf Distance>Radius than point is outside the circle\nIf Distance=Radius than point is on the circle\nIf Distance<Radius than point is inside the circle\n\n\nCode:-\nimport math\n# Lets say the circle poi...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074569052_python.txt
Q: Plotly How to create a line animation with column name in x axis and column data in y axis? I have a data frame as shown below. Device_ID Die_Version Temp(deg) sup(V) freq sensitivity THD_94 THD_100 THD_105 THD_110 THD_112 THD_114 THD_115 THD_116 THD_118 THD_120 TTM_041 0x16 -40 1....
Plotly How to create a line animation with column name in x axis and column data in y axis?
I have a data frame as shown below. Device_ID Die_Version Temp(deg) sup(V) freq sensitivity THD_94 THD_100 THD_105 THD_110 THD_112 THD_114 THD_115 THD_116 THD_118 THD_120 TTM_041 0x16 -40 1.8 0.8 -25.041 0.009 0.01 0.071 0.206 0.143 0.099 0.1 0.296 4.243 11.8...
[ "reshaped_df = df[[col for col in df.columns if 'THD' in col]].T.stack().reset_index()\n\ngives us some reshaped data that looks like this:\n level_0 level_1 0\n0 THD_94 0 0.009\n1 THD_94 1 0.009\n2 THD_94 2 0.009\n3 THD_100 0 0.010\n4 THD_100 1 0....
[ 2 ]
[]
[]
[ "pandas", "plot", "plotly", "plotly_dash", "python" ]
stackoverflow_0074570406_pandas_plot_plotly_plotly_dash_python.txt
Q: Local variable value is not used in recursion Here is my snippet: core = client.CoreV1Api() apps = client.AppsV1Api() def get_pod_parent(resource, tmp): if resource.metadata.owner_references: parrent = eval(f"apps.read_namespaced_{re.sub(r'(?<!^)(?=[A-Z])', '_', resource.metadata.owner_references[0].k...
Local variable value is not used in recursion
Here is my snippet: core = client.CoreV1Api() apps = client.AppsV1Api() def get_pod_parent(resource, tmp): if resource.metadata.owner_references: parrent = eval(f"apps.read_namespaced_{re.sub(r'(?<!^)(?=[A-Z])', '_', resource.metadata.owner_references[0].kind).lower()}")( resource.metadata.owne...
[ "Python uses pass by value in this case therefore when you pass the variable last_parrent it passes the value of the variable and any modification won't effect last_parrent. What you probably want to do is write\nreturn resource\n\nThen when you call the function at the bottom will contain the value of resource whe...
[ 1, 0 ]
[]
[]
[ "arguments", "parameter_passing", "python" ]
stackoverflow_0074571792_arguments_parameter_passing_python.txt
Q: Scrapy images do not download The scraper runs and finds the urls of the images, but it won't download the images for some reason. It prints the information of the Items in the terminal, but nothing gets recorded. I have tried all the combinations of settings I could find on SO, but I have been unlucky so far. Thi...
Scrapy images do not download
The scraper runs and finds the urls of the images, but it won't download the images for some reason. It prints the information of the Items in the terminal, but nothing gets recorded. I have tried all the combinations of settings I could find on SO, but I have been unlucky so far. This scraper used to work it might be ...
[ "You are missing the images result field in your image item.\nclass ImageItem(scrapy.Item):\n\n # ... other item fields ...\n image_urls = scrapy.Field()\n photographer_name = scrapy.Field()\n category_name = scrapy.Field()\n images = scrapy.Field() # <----- add this\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "scrapy", "web_scraping" ]
stackoverflow_0074567077_python_python_3.x_scrapy_web_scraping.txt
Q: How to add in react-native script in python? Also i have got a new project, where nedded make a voice recognition (speech-to-text) , but i have't find a worked library in react-native. How can i connect scripts in python to react native project? I only find how to make autorizathion in python, but by me it was mak...
How to add in react-native script in python?
Also i have got a new project, where nedded make a voice recognition (speech-to-text) , but i have't find a worked library in react-native. How can i connect scripts in python to react native project? I only find how to make autorizathion in python, but by me it was maked in JS
[ "If your python app is going to be running on a separate machine to the react-native app (so it is running on a server). I would write a small server implementation ontop of the python app using something like flask which sends back a JSON then you can follow the tutorial here: https://reactnative.dev/docs/network ...
[ 2, 1 ]
[]
[]
[ "javascript", "python", "react_native" ]
stackoverflow_0074571737_javascript_python_react_native.txt
Q: tabula error 'list' object has no attribute 'to_excel' I tried to convert PDF file that contains the data table to excel file. Here is my cord. import tabula # Read PDF File df = tabula.read_pdf("files/Seniority List 2018 19.pdf", pages = 1) # Convert into Excel File df.to_excel('files/excel.xlsx') but erro...
tabula error 'list' object has no attribute 'to_excel'
I tried to convert PDF file that contains the data table to excel file. Here is my cord. import tabula # Read PDF File df = tabula.read_pdf("files/Seniority List 2018 19.pdf", pages = 1) # Convert into Excel File df.to_excel('files/excel.xlsx') but error occurred. AttributeError Traceb...
[ "df[0].to_excel('files/excel.xlsx')\n\ntabula returns a list of possible table\n", "instead of using df = tabula.read_pdf('file.pdf', pages = '1')\nUse df = tabula.read_pdf('file.pdf', pages = '1')[0]\n" ]
[ 0, 0 ]
[]
[]
[ "python", "tabula" ]
stackoverflow_0074572159_python_tabula.txt
Q: Set environment variable in PyCharm to None value During debug sessions in PyCharm I need to set some environment variables to None value. There is good explanation on how to set Run/Debug configuration environment variables in PyCharm How to set environment variables in PyCharm?, but they set each variable to spe...
Set environment variable in PyCharm to None value
During debug sessions in PyCharm I need to set some environment variables to None value. There is good explanation on how to set Run/Debug configuration environment variables in PyCharm How to set environment variables in PyCharm?, but they set each variable to specific value. It is possible to delete environment varia...
[ "You can't. Environment variables behave as Windows determines, and Windows doesn't provide an equivalent of Python's None. If you do SET MYVAR= at a console prompt, Windows will delete the variable. There is little that PyCharm can do to change that.\nBut there is nothing to stop you having an environment variable...
[ 1, 0 ]
[]
[]
[ "pycharm", "python" ]
stackoverflow_0074570140_pycharm_python.txt
Q: Mark all the columns after the first occurrence of an event as NaN in pandas I want to mark all the columns after the first occurrence of an event(ONE-OFF) as NaN in pandas dataframe Note: There can be multiple rows in this df and ONE-OFF can appear at any column or may not appear at all input_df = pd.DataFrame( ...
Mark all the columns after the first occurrence of an event as NaN in pandas
I want to mark all the columns after the first occurrence of an event(ONE-OFF) as NaN in pandas dataframe Note: There can be multiple rows in this df and ONE-OFF can appear at any column or may not appear at all input_df = pd.DataFrame( { 1: {'15': 'Normal'}, 2: {'15': 'Normal'}, 3: {'15'...
[ "Compare values and use DataFrame.shift with DataFrame.cummax for mask and replace NaNs by DataFrame.mask for replace values after first matched value per rows separately:\nprint (input_df)\n 1 2 3 4 5 6\n0 Normal Normal Normal ONE-OFF Normal Normal\n1 ONE-OFF No...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074572495_pandas_python.txt
Q: remove prefix in all column names I would like to remove the prefix from all column names in a dataframe. I tried creating a udf and calling it in a for loop def remove_prefix(str, prefix): if str.startswith(blabla): return str[len(prefix):] return str for x in df.columns: x.remove_prefix() A...
remove prefix in all column names
I would like to remove the prefix from all column names in a dataframe. I tried creating a udf and calling it in a for loop def remove_prefix(str, prefix): if str.startswith(blabla): return str[len(prefix):] return str for x in df.columns: x.remove_prefix()
[ "Use Series.str.replace with regex ^ for match start of string:\ndf = pd.DataFrame(columns=['pre_A', 'pre_B', 'pre_predmet'])\ndf.columns = df.columns.str.replace('^pre_', '')\nprint (df)\nEmpty DataFrame\nColumns: [A, B, predmet]\nIndex: []\n\nAnother solution is use list comprehension with re.sub:\nimport re\n\nd...
[ 12, 4, 3, 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0055830212_pandas_python.txt
Q: yield + generator in python in class I am very new in Python and I wanna create a generator object that yields two lists for Fibonacci sequence. First list of number and second list of fibonacci. The function define in the class. Before it I define fibonacci function as below: def fib(self, _n,) -> int: if...
yield + generator in python in class
I am very new in Python and I wanna create a generator object that yields two lists for Fibonacci sequence. First list of number and second list of fibonacci. The function define in the class. Before it I define fibonacci function as below: def fib(self, _n,) -> int: if _n == 0: return 0 if ...
[ "I'm not sure what the gen function you are using is, but you don't need to use it. You could do (removing self in this example to have standalone functions):\ndef fib(_n):\n if _n == 0:\n return 0\n if _n == 1:\n return 1\n return fib(_n-1) + fib(_n-2)\n\ndef fib_seq(n):\n for i in range(...
[ 1 ]
[]
[]
[ "generator", "python", "yield" ]
stackoverflow_0074572200_generator_python_yield.txt
Q: How to think about a schedule-building script (general thought process) I ran into this issue that's been bugging me. I'm trying to write a Python script to build a stock take schedule. I managed to propose dates based on deadlines and I also managed to move the proposed dates to the nearest "legal" date in case t...
How to think about a schedule-building script (general thought process)
I ran into this issue that's been bugging me. I'm trying to write a Python script to build a stock take schedule. I managed to propose dates based on deadlines and I also managed to move the proposed dates to the nearest "legal" date in case the original proposed date fell on weekend, planned annual code freeze, etc......
[ "I think you need to start with pseudocode.\nSomething like this:\nFor entry in your data.\n Propose an initial date (eg: deadline -1)\n Check if another location from the same area happens that day\n Yes? Decrement 1 to the proposed day and check again\n No? Check the next condition\n Check that if ...
[ 0 ]
[]
[]
[ "python", "schedule" ]
stackoverflow_0074572469_python_schedule.txt
Q: Pass certificate to requests.post from s3 bucket in AWS lambda I am calling the api and want to send certificate along with it like this: response = requests.post(url,cert=('pem_cert.pem', 'key_cert.key'), headers=headers, data=payload) print(response) Now, both pem_cert.pem and key_cert.key files are present in...
Pass certificate to requests.post from s3 bucket in AWS lambda
I am calling the api and want to send certificate along with it like this: response = requests.post(url,cert=('pem_cert.pem', 'key_cert.key'), headers=headers, data=payload) print(response) Now, both pem_cert.pem and key_cert.key files are present in the local directory so it's work well, but now I want to store thos...
[ "To read your pem and cert file from an S3 bucket you can copy them into lambda temp storage /tmp and use it from there like it was a file on your local hard disk.\nWhen you copy from S3 to /tmp just make sure you copy as binary file and not as a string as it won't work.\nimport json\nimport requests\nimport boto3 ...
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "python" ]
stackoverflow_0073403727_amazon_s3_amazon_web_services_python.txt
Q: Delete specific route cache in Flask-Caching I am trying to delete a flask cache on a specific route if there is an error or if a variable is empty, but i don't understand how to do it. I have found this, but i don't think it is helpful in my case: Delete specific cache in Flask-Cache or Flask-Caching This is my c...
Delete specific route cache in Flask-Caching
I am trying to delete a flask cache on a specific route if there is an error or if a variable is empty, but i don't understand how to do it. I have found this, but i don't think it is helpful in my case: Delete specific cache in Flask-Cache or Flask-Caching This is my code: @nsaudio.route('/repeat/<string:text>/<string...
[ "For Anyone having this proplem, I have just found the solution.\n@nsaudio.route('/repeat/<string:text>/<string:chatid>/<string:voice>')\nclass AudioRepeatClass(Resource):\n @cache.cached(timeout=120, query_string=True)\n def get (self, text: str, chatid: str, voice: str):\n try:\n tts_out = utils.get_tts...
[ 0 ]
[]
[]
[ "flask", "flask_caching", "python" ]
stackoverflow_0074572207_flask_flask_caching_python.txt
Q: Nested regex in pandas python I am working on the cosmetic ingredient data and trying to solve a regex problem where I want to replace "," with "-". For example, x = ['6,7- dihydro-1,1,2,3,3-pentamethyl-4(5h)-indanone', 'steareth-10, polyacrylamide c1,14 isoparaffin, laureth-7, propylene glycol, hydrolyzed soy pro...
Nested regex in pandas python
I am working on the cosmetic ingredient data and trying to solve a regex problem where I want to replace "," with "-". For example, x = ['6,7- dihydro-1,1,2,3,3-pentamethyl-4(5h)-indanone', 'steareth-10, polyacrylamide c1,14 isoparaffin, laureth-7, propylene glycol, hydrolyzed soy protein, aloe barbadensis, 1,2-hexaned...
[ "You could use a capture group:\n(\\d),(?=[\\d,]*-)\n\nExplanation\n\n(\\d) Capture group 1, match a single digit\n, Match literally (to be replaced)\n(?=[\\d,]*-) Positive lookahead, assert optional digits or comma's to the right followed by a hyphen\n\nSee a regex demo.\nIn the replacement use the first capture g...
[ 1 ]
[]
[]
[ "dataframe", "nlp", "pandas", "python", "regex" ]
stackoverflow_0074572143_dataframe_nlp_pandas_python_regex.txt
Q: pytest: mock method on Path instance to return output depending on the filename of the instance I am trying to mock pathlib's is_file method so that it returns True/False depending on my logic. I have a function in mymodule.py to test: ### mymodule.py from pathlib import Path def myfun(root: Path): return root.i...
pytest: mock method on Path instance to return output depending on the filename of the instance
I am trying to mock pathlib's is_file method so that it returns True/False depending on my logic. I have a function in mymodule.py to test: ### mymodule.py from pathlib import Path def myfun(root: Path): return root.is_file() and my pytest function: import mymodule # One of my attempts class MockPathIsFile: def...
[ "def mock_is_file(existing_files):\n def mock(self: Path):\n return str(self) in existing_files\n return mock\n\nmonkeypatch.setattr(validate.Path, 'is_file', mock_is_file(existing_files=[\"foo\"]))\n\nassert mymodule.myfun(Path(\"foo.txt\")) is True\nassert mymodule.myfun(Path(\"nope.txt\")) is False\...
[ 0 ]
[]
[]
[ "monkeypatching", "pytest", "python" ]
stackoverflow_0074560750_monkeypatching_pytest_python.txt
Q: Best graph from dataframe with different conditions (groups and variables) I have a dataframe (cells) that it looks like this (it has more rows): ID Time(min) Cell1 Cell2 Cell3 Cell4 Cell5 Cell6 Cell7 AA001 0 10.57 77.28 14.11 15.12 1.56 95.83 3.41 AA001 30 12.99 77.96 15.01 15.35 1.60 96.02 3.37 AA001 90 11....
Best graph from dataframe with different conditions (groups and variables)
I have a dataframe (cells) that it looks like this (it has more rows): ID Time(min) Cell1 Cell2 Cell3 Cell4 Cell5 Cell6 Cell7 AA001 0 10.57 77.28 14.11 15.12 1.56 95.83 3.41 AA001 30 12.99 77.96 15.01 15.35 1.60 96.02 3.37 AA001 90 11.41 79.85 16.69 19.65 1.28 92.14 6.01 AA001 180 15.89 75.11 12.48 1...
[ "Here are two options separating the ID's in facets.\nDummy data:\ndf = tibble(ID = sample(letters, 300, TRUE),\n value = runif(300, 0, 40))\n\ndf = df %>%\n group_by(ID) %>%\n mutate(Time = seq(0, by = 10, length = n())) %>%\n arrange(ID)\n\nObs: if your problem was the visualization of lots of ID's,...
[ 1, 1 ]
[]
[]
[ "group_by", "plot", "python", "r" ]
stackoverflow_0074572028_group_by_plot_python_r.txt
Q: ImportError: cannot import name 'is_directory' from 'PIL._util' (/usr/local/lib/python3.7/dist-packages/PIL/_util.py) While using this code, I get this error of Pillow. I tried re-installing pillow but still struggling with this issue. Any help to make this code run? import layoutparser as lp model = lp.Detectron2...
ImportError: cannot import name 'is_directory' from 'PIL._util' (/usr/local/lib/python3.7/dist-packages/PIL/_util.py)
While using this code, I get this error of Pillow. I tried re-installing pillow but still struggling with this issue. Any help to make this code run? import layoutparser as lp model = lp.Detectron2LayoutModel( config_path ='lp://PubLayNet/faster_rcnn_R_50_FPN_3x/config', # In model catalog label...
[ "This is because of higher version of pillow package. You should install pillow version less than or equal to 6.2.2 to resolve this error.\npip install --upgrade pillow==6.2.2 \n\n", "Run the below command before installing the library:\n!pip install fastcore -U\n\n" ]
[ 0, 0 ]
[]
[]
[ "importerror", "layout_parser", "python", "python_imaging_library" ]
stackoverflow_0073711994_importerror_layout_parser_python_python_imaging_library.txt