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:
How to make a constraint based in a entry value in an Association Object in SQLAlchemy?
Given the following minimal example:
class Association(Base):
__tablename__ = "association_table"
left_id = Column(ForeignKey("left_table.id"), primary_key=True)
right_id = Column(ForeignKey("right_table.id"), prima... | How to make a constraint based in a entry value in an Association Object in SQLAlchemy? | Given the following minimal example:
class Association(Base):
__tablename__ = "association_table"
left_id = Column(ForeignKey("left_table.id"), primary_key=True)
right_id = Column(ForeignKey("right_table.id"), primary_key=True)
first_child = Column(Boolean, nullable=False)
child = relationship("Chil... | [
"The simpliest solution is to use the Partial Index, which are supported for PostgreSQL, Partial Indexes and SQLite, Partial Indexes.\nThe code below should work for both:\nclass Association(Base):\n __tablename__ = \"association_table\"\n left_id = Column(ForeignKey(\"left_table.id\"), primary_key=True)\n ... | [
3
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074581422_python_sqlalchemy.txt |
Q:
Error while converting String elements of List of Lists to float
This is in reference to my previous question related to extracting data from .asc file and separating them while having multiple delimiters.
I want to perform mathematical operations on the float elements of the list of lists generated from the above... | Error while converting String elements of List of Lists to float | This is in reference to my previous question related to extracting data from .asc file and separating them while having multiple delimiters.
I want to perform mathematical operations on the float elements of the list of lists generated from the above question. The separation of individual data from the string has been ... | [
"Declare Data as empty list outside for-loop and use .append to insert a float value into it:\nData = []\nwith open(r\"myfile.asc\", \"r\") as file_in:\n for line in map(str.strip, file_in):\n if \"LoggingString :=\" in line:\n # ...\n Data.append(float(Output_list[count][8]))\n ... | [
1,
0
] | [] | [] | [
"file",
"numpy",
"pandas",
"python",
"type_conversion"
] | stackoverflow_0074614779_file_numpy_pandas_python_type_conversion.txt |
Q:
Find the point at which a curve touches the X axis
I have the following plot made with some data points,. What is the best Pythonic way to find the point through which the curve intersects the X-axis? Thanks for any help.
-2.0 -2.22537043
-1.9 -2.22609532
-1.8 -2.22075396
-1.7 -2.22729678
-1.6 -2.2235372... | Find the point at which a curve touches the X axis | I have the following plot made with some data points,. What is the best Pythonic way to find the point through which the curve intersects the X-axis? Thanks for any help.
-2.0 -2.22537043
-1.9 -2.22609532
-1.8 -2.22075396
-1.7 -2.22729678
-1.6 -2.22353721
-1.5 -2.22341588
-1.4 -2.2180032
-1.3 -2.2285003... | [
"There is really not enough information given in this question to solve the problem outright. That said, if I understand correctly, you perhaps are looking to see where any two functions (line or curve) are intersecting.\nThere are a few approaches. The most simple I'd say would be to use robust curve intersection ... | [
5,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074616911_matplotlib_python.txt |
Q:
new line issue with f.write
I'm a beginner python programmer so I'll cut right to the chase.
I'm trying to use the f.write keyword, I want each thing I write to be in a new line so I did this:f.write('',message_variable_from_previous_input,'\n') However, after I ran this it threw back an error saying the following... | new line issue with f.write | I'm a beginner python programmer so I'll cut right to the chase.
I'm trying to use the f.write keyword, I want each thing I write to be in a new line so I did this:f.write('',message_variable_from_previous_input,'\n') However, after I ran this it threw back an error saying the following:
Traceback (most recent call las... | [
"write method takes exactly one argument\nso you should write like this:\nf.write(f\"{message_variable_from_previous_input}\\n\")\nor :\nf.write(str(message_variable_from_previous_input) + \"\\n\")\n"
] | [
3
] | [] | [] | [
"python",
"txt"
] | stackoverflow_0074617845_python_txt.txt |
Q:
How are pytest fixure scopes intended to work?
I want to use pytest fixtures to prepare an object I want to use across a set of tests.
I follow the documentation and create a fixture in something_fixture.py with its scope set to session like this:
import pytest
@pytest.fixture(scope="session")
def something():
... | How are pytest fixure scopes intended to work? | I want to use pytest fixtures to prepare an object I want to use across a set of tests.
I follow the documentation and create a fixture in something_fixture.py with its scope set to session like this:
import pytest
@pytest.fixture(scope="session")
def something():
return 'something'
Then in test_something.py I tr... | [
"This session-scoped fixture should be defined in a conftest.py module, see conftest.py: sharing fixtures across multiple files in the docs.\n\nThe conftest.py file serves as a means of providing fixtures for an entire directory. Fixtures defined in a conftest.py can be used by any test in that package without need... | [
1
] | [] | [] | [
"fixtures",
"pytest",
"python"
] | stackoverflow_0074617822_fixtures_pytest_python.txt |
Q:
How to activate API Bigquery in GCP with python?
I am developing a small application in gcp and I must activate the bigquery api to interact with it, I do it through the console, but, Is it possible to do it with the python google api client?
I've been looking in the documentation but it's still not clear to me.
... | How to activate API Bigquery in GCP with python? | I am developing a small application in gcp and I must activate the bigquery api to interact with it, I do it through the console, but, Is it possible to do it with the python google api client?
I've been looking in the documentation but it's still not clear to me.
| [
"To enable BigQuery API from console:\n\nGo to console.google.com\nFrom the menu, click on APIs & Services ->Enable APIs & Service\nClick on Enable APIs and Service\nSearch for BigQuery API and click on enable\n\nTo enable through gcloud sdk:\ngcloud services enable bigquery.googleapis.com\n\nYou may need to enable... | [
0
] | [] | [] | [
"google_api_client",
"google_bigquery",
"google_cloud_platform",
"python"
] | stackoverflow_0074616287_google_api_client_google_bigquery_google_cloud_platform_python.txt |
Q:
How to override printing in python multiprocessing
I have a class AlternativePrinter that overrides the python print function (in this example it appends "[write to terminal]" before outputs) but for some reason anything printed from within a multiprocessing process doesn't go through this print function. How can ... | How to override printing in python multiprocessing | I have a class AlternativePrinter that overrides the python print function (in this example it appends "[write to terminal]" before outputs) but for some reason anything printed from within a multiprocessing process doesn't go through this print function. How can I make all printing including from processes go through ... | [
"Add with AlternativePrinter(): in wait_and_print. The lines below if __name__ == \"__main__\": are not executed in the child process and hence AlternativePrinter() is never used.\n"
] | [
1
] | [] | [] | [
"io",
"output",
"python",
"python_multiprocessing",
"python_multithreading"
] | stackoverflow_0074617341_io_output_python_python_multiprocessing_python_multithreading.txt |
Q:
Functions not being called correctly
This is a code that prompts the user for the amount of months they want to budget analyze, prompts for the budget the user has, prompts for how much the user spent that month, and then calculates if the user is over or under their budget. When code is run, it prompts user one t... | Functions not being called correctly | This is a code that prompts the user for the amount of months they want to budget analyze, prompts for the budget the user has, prompts for how much the user spent that month, and then calculates if the user is over or under their budget. When code is run, it prompts user one twice, and then creates errors:
Traceback ... | [
"You can change the return type of GetMonths() :\ndef GetMonths():\n Months = input(\"Enter the number of months you want to analyze\")\n return int(Months)\n\n\nOr You can cast the type to int in range() of AnalyzeBudget()\ndef AnalyzeBudget(months):\n for month in range(1,int(months)+1):\n print(\"\... | [
0,
0
] | [] | [] | [
"function",
"loops",
"python"
] | stackoverflow_0074617819_function_loops_python.txt |
Q:
How to get the line index in a row from CSV imported into Python?
Please see this image
Basically, I want to be able to get the vertical index position of the maximum number from an imported CSV. I have been able to grab the maximum number from the CSV which is 188 and represented by 'maxTemp'. I need the vertical... | How to get the line index in a row from CSV imported into Python? | Please see this image
Basically, I want to be able to get the vertical index position of the maximum number from an imported CSV. I have been able to grab the maximum number from the CSV which is 188 and represented by 'maxTemp'. I need the vertical position of the number from the CSV, I know how you get what column it... | [
"You can use enumerate() + max() to get row with highest value. For example:\nimport csv\n\nwith open(\"CSV_load.csv\", \"r\") as csvfile:\n readCSV = csv.reader(csvfile, delimiter=\",\")\n line, row_with_highest_temp = max(\n enumerate(readCSV, 1), key=lambda row: int(row[1][2])\n )\n print(\"Hi... | [
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074617264_csv_python.txt |
Q:
Azure flask deploy If you are the application administrator, you can access the diagnostic resources
When I enter to the domain I got this
:( Application Error
If you are the application administrator, you can access the diagnostic resources.
This is when I enter to diagnostic:
Distributing your web app across mul... | Azure flask deploy If you are the application administrator, you can access the diagnostic resources | When I enter to the domain I got this
:( Application Error
If you are the application administrator, you can access the diagnostic resources.
This is when I enter to diagnostic:
Distributing your web app across multiple instances
The webapp is currently configured to run on only one instance.
Since you have only one in... | [
"For a big applications it's better to work on virtual machine not on ready services\n"
] | [
0
] | [] | [] | [
"azure",
"azure_devops",
"flask",
"python"
] | stackoverflow_0073776416_azure_azure_devops_flask_python.txt |
Q:
Need help implementing an example in Google Colab
Im trying to run this example in Colab https://github.com/tensorflow/examples/tree/master/lite/examples/image_segmentation/raspberry_pi
but i cant make it because the example use webcam. Anyone have a different version of this example which use image, video or gif?... | Need help implementing an example in Google Colab | Im trying to run this example in Colab https://github.com/tensorflow/examples/tree/master/lite/examples/image_segmentation/raspberry_pi
but i cant make it because the example use webcam. Anyone have a different version of this example which use image, video or gif? Or can help in making one? Thanks
| [
"You can update the example yourself.\nRemove the lines that tries to open the camera, and update this line which tries to capture image from the camera video with your image instead\nhttps://github.com/tensorflow/examples/blob/master/lite/examples/image_segmentation/raspberry_pi/segment.py#L76\n"
] | [
0
] | [] | [] | [
"google_colaboratory",
"python",
"tensorflow_lite"
] | stackoverflow_0074616333_google_colaboratory_python_tensorflow_lite.txt |
Q:
VS Code cursor bug in terminal
Cursor repeating and remaining in the Integrated Terminal in VS Code
I encountered this bug in my terminal while doing Python tutorial so downloaded and reinstalled the same version (latest version of VS Code) but the problem persists. I looked about for some answers but only found ... | VS Code cursor bug in terminal | Cursor repeating and remaining in the Integrated Terminal in VS Code
I encountered this bug in my terminal while doing Python tutorial so downloaded and reinstalled the same version (latest version of VS Code) but the problem persists. I looked about for some answers but only found this tutorial which is not related.
... | [
"Turned off GPU acceleration in the Terminal of VS Code. That has seemed to resolve the matter; No longer cursor trails.\nSettings > Type 'Render' > Go to\nTerminal › Integrated: Gpu Acceleration.\nSetting controls whether the terminal will leverage the GPU to do its rendering.\nSwitch 'off' in dropdown menu\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"terminal",
"visual_studio_code"
] | stackoverflow_0074607032_python_python_3.x_terminal_visual_studio_code.txt |
Q:
How do I make Mypy recognize non-nullable ORM attributes?
Mypy infers ORM non-nullable instance attributes as optionals.
Filename: test.py
from sqlalchemy.orm import decl_api, registry
from sqlalchemy import BigInteger, Column, String
mapper_registry = registry()
class Base(metaclass=decl_api.DeclarativeMeta):
... | How do I make Mypy recognize non-nullable ORM attributes? | Mypy infers ORM non-nullable instance attributes as optionals.
Filename: test.py
from sqlalchemy.orm import decl_api, registry
from sqlalchemy import BigInteger, Column, String
mapper_registry = registry()
class Base(metaclass=decl_api.DeclarativeMeta):
__abstract__ = True
registry = mapper_registry
met... | [
"I had the same question when evaluating a nullable=False column with mypy. One of my teammates found the answer in the SqlAlchemy docs:\nhttps://docs.sqlalchemy.org/en/14/orm/extensions/mypy.html#introspection-of-columns-based-on-typeengine\n\nThe types are by default always considered to be Optional, even for\nt... | [
1
] | [] | [] | [
"mypy",
"python",
"sqlalchemy"
] | stackoverflow_0071674202_mypy_python_sqlalchemy.txt |
Q:
Scrapy encoding nested dict params
I want to send a request which has params in nested dict.
params = {
'apiKey': 'XXXXXXXXXXXXXXXXXXX',
'facetInclusion': 'All',
'filter': '{"facetFilter": {"andClauses": [{"value": "WEBCAT_1_2_1", "type": "CategoryCode", "negate": false}], "orClauses": []}, "numericalFilter"... | Scrapy encoding nested dict params | I want to send a request which has params in nested dict.
params = {
'apiKey': 'XXXXXXXXXXXXXXXXXXX',
'facetInclusion': 'All',
'filter': '{"facetFilter": {"andClauses": [{"value": "WEBCAT_1_2_1", "type": "CategoryCode", "negate": false}], "orClauses": []}, "numericalFilter": [], "filteringFacetFilter": {"andClaus... | [
"cb_kwargs is a dictionary that will be passed the request’s callback.\nbody is the request's body.\nimport json\n\nyield scrapy.Request(url=self.url, body=json.dumps(params), callback=self.parse, headers=self.headers)\n\nEDIT:\nI misunderstood your question. This is what you want:\nimport urllib.parse\nurl_params ... | [
1
] | [] | [] | [
"python",
"python_requests",
"scrapy",
"web_scraping"
] | stackoverflow_0074617259_python_python_requests_scrapy_web_scraping.txt |
Q:
can't get discord to recognize my role id?
import discord
import os
from keep_alive import keep_alive
import random
import glob
import os.path
import asyncio
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message... | can't get discord to recognize my role id? | import discord
import os
from keep_alive import keep_alive
import random
import glob
import os.path
import asyncio
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(ctx):
if ctx.content.startswith(
... | [
"For other people: The problem might be your role id. Try grabbing the role id from the roles page in server settings instead of from a message. What the page looks like in the unlikely case you don't know\nRole ids are usually 18 digits long but newly created roles may be 19.\nThe error in this case was that he la... | [
0
] | [] | [] | [
"discord.py",
"python",
"roles"
] | stackoverflow_0074617829_discord.py_python_roles.txt |
Q:
Generating points within a Menger Sponge (fractal shape)
I am trying to generate a lattice of points in the shape of a Menger sponge or Sierpinski sponge.
https://en.wikipedia.org/wiki/Menger_sponge This link details how the shape is mathematically constructed.
I wanted to find a way where I could make this shape ... | Generating points within a Menger Sponge (fractal shape) | I am trying to generate a lattice of points in the shape of a Menger sponge or Sierpinski sponge.
https://en.wikipedia.org/wiki/Menger_sponge This link details how the shape is mathematically constructed.
I wanted to find a way where I could make this shape using recursion to remove the necessary cubes.
I looked online... | [
"You need to add a recursive element to your code. I would also suggest thinking in terms of 2D (and eventually 3D) matricies instead of 1D arrays and explore numpy's abilities in depth:\nimport numpy as np\n\ndef menger(matrix, size):\n quotient, remainder = divmod(size, 3)\n\n if remainder == 0:\n f... | [
1
] | [] | [] | [
"fractals",
"python",
"recursion"
] | stackoverflow_0074616982_fractals_python_recursion.txt |
Q:
I try to map values to a column in pandas but i get nan values instead
This is my code:
mapping = {"ISTJ":1, "ISTP":2, "ISFJ":3, "ISFP":4, "INFP":6, "INTJ":7, "INTP":8, "ESTP":9, "ESTJ":10, "ESFP":11, "ESFJ":12, "ENFP":13, "ENFJ":14, "ENTP":15, "ENTJ":16, "NaN": 17}
q20 = castaway_details["personality_type"]
q20["... | I try to map values to a column in pandas but i get nan values instead | This is my code:
mapping = {"ISTJ":1, "ISTP":2, "ISFJ":3, "ISFP":4, "INFP":6, "INTJ":7, "INTP":8, "ESTP":9, "ESTJ":10, "ESFP":11, "ESFJ":12, "ENFP":13, "ENFJ":14, "ENTP":15, "ENTJ":16, "NaN": 17}
q20 = castaway_details["personality_type"]
q20["personality_type"] = q20["personality_type"].map(mapping)
the data frame is... | [
"Try to pandas.Series.str.strip before the pandas.Series.map :\nq20[\"personality_type\"]= q20[\"personality_type\"].str.strip().map(mapping)\n\n# Output :\nprint(q20)\n\n personality_type\n0 8\n1 6\n2 7\n3 1\n4 17\n5 11... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074617982_dataframe_pandas_python.txt |
Q:
How do you produce a random 0 or 1 with random.rand
I'm trying to produce a 0 or 1 with numpy's random.rand.
np.random.rand() produces a random float between 0 and 1 but not just a 0 or a 1.
Thank you.
A:
You can use np.random.choice with a list of [0,1], or use np.random.radint with a range of 0,2
In [1]: impo... | How do you produce a random 0 or 1 with random.rand | I'm trying to produce a 0 or 1 with numpy's random.rand.
np.random.rand() produces a random float between 0 and 1 but not just a 0 or a 1.
Thank you.
| [
"You can use np.random.choice with a list of [0,1], or use np.random.radint with a range of 0,2\nIn [1]: import numpy as np ... | [
8,
1,
1,
1,
1,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0056372240_numpy_python.txt |
Q:
What is the efficient way to find missing rows of a dataframe and put NaN for columns?
Consider I have dataframe which the first column is the datetime, and the other columns are data in the specified datetime (Data is collected hourly, so first column of every row is one hour after the previous row). In this date... | What is the efficient way to find missing rows of a dataframe and put NaN for columns? | Consider I have dataframe which the first column is the datetime, and the other columns are data in the specified datetime (Data is collected hourly, so first column of every row is one hour after the previous row). In this dateframe data for some datetimes are missed.
I want to make a new dataframe in which missing ro... | [
"I think you could create a df where you have the timestamp as your index.\nYou can then use pd.date_range to create a full datetime range for every hour from min to max.\nYou can then run the Index.difference to efficiently find any timestamps that are missing from your original dataframe --> this will be the inde... | [
2,
1
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074617766_dataframe_datetime_pandas_python_python_3.x.txt |
Q:
FastAPI: How to know if a parameter is really null?
i have a ressource and want to have a post api endpoint to modify it. My problem is if i set all propertys Optional[...] how did i know if i want to "delete" one property or set it to null? If i set it in the request to null: I get NoneType. But if i don't set it... | FastAPI: How to know if a parameter is really null? | i have a ressource and want to have a post api endpoint to modify it. My problem is if i set all propertys Optional[...] how did i know if i want to "delete" one property or set it to null? If i set it in the request to null: I get NoneType. But if i don't set it in the request i also get NoneType. Is there a solution ... | [
"You can find your answer here : Pydantic: Detect if a field value is missing or given as null\n@app.post(\"/test\")\ndef test(entity: TestEntity):\n return entity.dict(exclude_unset=True)\n\n"
] | [
0
] | [] | [] | [
"fastapi",
"pydantic",
"python"
] | stackoverflow_0069645547_fastapi_pydantic_python.txt |
Q:
Multiprocessing Pool vs Process
I'm reviewing some code and noticed some possibly redundant code:
def tasker(val):
do stuff
def multiprocessor (func, vals):
chunks = np.array_split(vals, os.cpu_count())
with multiprocessing.Pool() as pool:
pool.map(partial(func,vals), chunksize=chunks)
if __name__... | Multiprocessing Pool vs Process | I'm reviewing some code and noticed some possibly redundant code:
def tasker(val):
do stuff
def multiprocessor (func, vals):
chunks = np.array_split(vals, os.cpu_count())
with multiprocessing.Pool() as pool:
pool.map(partial(func,vals), chunksize=chunks)
if __name__ == '__main__':
values = foobar
... | [
"As it happens, the Process call never actually does anything useful; target=multiprocessor(tasker,values) is running multiprocessor in the main process, then passing its return value (None, since it has no explicit return) as the target for the Process.\nSo yes, definitionally, this is completely pointless; you ma... | [
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0074618056_multiprocessing_python.txt |
Q:
Modulo Arithmetic function, Python code conversion
here is my error
Suppose we want to do 954^893 mod 1457. Now let this big number be
((954^50 mod 1457)(954^50 mod 1457)(954^50 mod 1457)(954^50 mod
1457)........(954^43 mod 1457)) mod 1457
break which I want to find the answer. So how can it be done in Python co... | Modulo Arithmetic function, Python code conversion | here is my error
Suppose we want to do 954^893 mod 1457. Now let this big number be
((954^50 mod 1457)(954^50 mod 1457)(954^50 mod 1457)(954^50 mod
1457)........(954^43 mod 1457)) mod 1457
break which I want to find the answer. So how can it be done in Python code. I want hard code
RSA algorithm
where
plain message ... | [
"What you want can be computed with the builtin pow function as follows:\nans = pow(954, 893, mod = 1457)\n\nThis result can also be computed \"naively\" using ans = (954 ** 893) % 1457. However, this forces python to compute the value 954**893 (i.e. 954893), a 2660-digit number.\nFor these numbers, Python has no i... | [
0
] | [] | [] | [
"list",
"loops",
"python",
"python_3.x"
] | stackoverflow_0074618081_list_loops_python_python_3.x.txt |
Q:
How to keep no return (zero rows) in a concatenation loop?
I am using a code for a query, sometimes the input goes and there is no return (basically it does not find anything so the return is an empty row) so it is empty. However, when I use pd.concat, those empty rows disappear. Is there a way to keep these no re... | How to keep no return (zero rows) in a concatenation loop? | I am using a code for a query, sometimes the input goes and there is no return (basically it does not find anything so the return is an empty row) so it is empty. However, when I use pd.concat, those empty rows disappear. Is there a way to keep these no return rows in the loop as well so that when I use that I can have... | [
"So, as far as I understand, the problem is that when \"temp_df\" is empty you want to add a blank row. You should be able to do that using the .append() method, appending an empty Series().\nif len(temp_df) == 0:\n temp_df=temp_df.append(pd.Series(), ignore_index=True)\n#Then concat...\n\n",
"For your specifi... | [
1,
1
] | [] | [] | [
"concatenation",
"pandas",
"python",
"sql"
] | stackoverflow_0074614393_concatenation_pandas_python_sql.txt |
Q:
Compare a dictionary with list of dictionaries and return index from the list which has higher value than the separate dictionary
I have a list of dictionaries and a separate dictionary having the same keys and only the values are different. For example the list of dictionaries look like this:
[{'A': 0.102, 'B': 0... | Compare a dictionary with list of dictionaries and return index from the list which has higher value than the separate dictionary | I have a list of dictionaries and a separate dictionary having the same keys and only the values are different. For example the list of dictionaries look like this:
[{'A': 0.102, 'B': 0.568, 'C': 0.33}, {'A': 0.026, 'B': 0.590, 'C': 0.382}, {'A': 0.005, 'B': 0.857, 'C': 0.137}, {'A': 0.0, 'B': 0.962, 'C': 0.036}, {'A':... | [
"are you sure that it should be only index 4?\ndict_list = [{'A': 0.102, 'B': 0.568, 'C': 0.33}, \n {'A': 0.026, 'B': 0.590, 'C': 0.382}, \n {'A': 0.005, 'B': 0.857, 'C': 0.137}, \n {'A': 0.0, 'B': 0.962, 'C': 0.036}, \n {'A': 0.0, 'B': 0.991, 'C': 0.008}] \n\nd = {'A... | [
1,
1
] | [] | [] | [
"dictionary",
"list",
"python",
"python_3.x"
] | stackoverflow_0074617717_dictionary_list_python_python_3.x.txt |
Q:
How to find the coordinate of the center of a sphere made in 3D by voxels given all the coordinate of the voxels that made up the sphere
I have coordinate of all the voxels that make up the sphere
C = [[x1,y1,z1],[x2,y2,z2],...,[xn,yn,zn]] (around 4000 coordinates)
Please teach me how I can get a coordinate that i... | How to find the coordinate of the center of a sphere made in 3D by voxels given all the coordinate of the voxels that made up the sphere | I have coordinate of all the voxels that make up the sphere
C = [[x1,y1,z1],[x2,y2,z2],...,[xn,yn,zn]] (around 4000 coordinates)
Please teach me how I can get a coordinate that is the center of this sphere by Python code.
Because this is a sphere, so when I plot it and try to identify the center coordinate, I couldn't ... | [
"So if you have an array of shape (n, 3), np.sum((Ccenter - C)**2, axis=1)-R**2 so you could get the coefficients of x**2, y**2, z**2, x, y, z.\na,_,_,_ = np.linalg.lstsq(np.hstack([C**2, C]), np.ones(n), rcond=None)\nCcenter = -a[3:6] / (2*a[0])\n\nA test example\nimport numpy as np\nn = 4000; # a cloud of 4000 po... | [
0
] | [] | [] | [
"3d",
"graph",
"linear_algebra",
"python",
"voxel"
] | stackoverflow_0074597891_3d_graph_linear_algebra_python_voxel.txt |
Q:
save dataframe as csv correctly
Initially, I have this dataframe:
I save this as a csv file by using:
df.to_csv('Frequency.csv')
The problem lies with when I try to read the csv file again with:
pd.read_csv("Frequency.csv")
The dataframe then looks like this:
Why is there an extra column added and why did the in... | save dataframe as csv correctly | Initially, I have this dataframe:
I save this as a csv file by using:
df.to_csv('Frequency.csv')
The problem lies with when I try to read the csv file again with:
pd.read_csv("Frequency.csv")
The dataframe then looks like this:
Why is there an extra column added and why did the index change? I suppose it has somethin... | [
"Use these to save and read:\n#if you don't want to save the index column in the first place\ndf.to_csv('Frequency.csv', index=False) \n# drop the extra column if any while reading\npd.read_csv(\"Frequency.csv\",index_col=0)\n\nExample :\nimport pandas as pd\n\ndata = {\n \"calories\": [420, 380, 390],\n \"durati... | [
1,
0
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074618024_csv_dataframe_pandas_python.txt |
Q:
Why `torch.cuda.is_available()` returns False even after installing pytorch with cuda?
On a Windows 10 PC with an NVidia GeForce 820M
I installed CUDA 9.2 and cudnn 7.1 successfully,
and then installed PyTorch using the instructions at pytorch.org:
pip install torch==1.4.0+cu92 torchvision==0.5.0+cu92 -f https://d... | Why `torch.cuda.is_available()` returns False even after installing pytorch with cuda? | On a Windows 10 PC with an NVidia GeForce 820M
I installed CUDA 9.2 and cudnn 7.1 successfully,
and then installed PyTorch using the instructions at pytorch.org:
pip install torch==1.4.0+cu92 torchvision==0.5.0+cu92 -f https://download.pytorch.org/whl/torch_stable.html
But I get:
>>> import torch
>>> torch.cuda.is_ava... | [
"Your graphics card does not support CUDA 9.0.\nSince I've seen a lot of questions that refer to issues like this I'm writing a broad answer on how to check if your system is compatible with CUDA, specifically targeted at using PyTorch with CUDA support. Various circumstance-dependent options for resolving issues a... | [
125,
5,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0060987997_python_pytorch.txt |
Q:
Switch order of differential and real operator in expression in Python
Let's say I want to simplify the terms
[
where u and v are (sympy) complex variables. u and w are independent from each other and the above differentials should thereby be evaluated to zero. As my code currently stands, it will not set the abov... | Switch order of differential and real operator in expression in Python | Let's say I want to simplify the terms
[
where u and v are (sympy) complex variables. u and w are independent from each other and the above differentials should thereby be evaluated to zero. As my code currently stands, it will not set the above differentials to zero since it does not know how to evaluate re(w) and im(... | [
"Maybe just use doit:\nIn [3]: v, w = symbols('v, w')\n\nIn [4]: diff(re(w), v)\nOut[4]: 0\n\nIn [5]: Derivative(re(w), v)\nOut[5]: \nd \n──(re(w))\ndv \n\nIn [6]: Derivative(re(w), v).doit()\nOut[6]: 0\n\n",
"The doit is good since, otherwise, an unevaluated Derivative(x, y) will not evaluate to 0. ... | [
0,
0
] | [] | [] | [
"python",
"sympy"
] | stackoverflow_0074610786_python_sympy.txt |
Q:
Can I import default Python modules in a Python Docker image?
I am new to Docker, and as a learning exercise, I want to make a custom Python package available through a Docker image. The package is called hashtable-nicolerg and includes a HashTable class that can be imported with from hashtable_nicolerg.hashtable ... | Can I import default Python modules in a Python Docker image? | I am new to Docker, and as a learning exercise, I want to make a custom Python package available through a Docker image. The package is called hashtable-nicolerg and includes a HashTable class that can be imported with from hashtable_nicolerg.hashtable import HashTable.
It is straightforward to create an image with add... | [
"If the PYTHONSTARTUP environment variable exists and is the name of a valid Python file, then that file will be executed when any new Python shell starts up.\nSo whether you want to do this in a Docker container or on your local machine, it works the same way. Define PYTHONSTARTUP (in .bashrc, for instance) and th... | [
3,
1
] | [] | [] | [
"docker",
"python",
"python_import"
] | stackoverflow_0074609139_docker_python_python_import.txt |
Q:
Is there a way to use try. except to limit a list to numbers only so if anything else other then numbers is used such as special char or char it loops
var=input("Enter a list of Number to Find its Minimum, Maximum, Average and Total:")
try:
a=eval(var)
... | Is there a way to use try. except to limit a list to numbers only so if anything else other then numbers is used such as special char or char it loops | var=input("Enter a list of Number to Find its Minimum, Maximum, Average and Total:")
try:
a=eval(var)
b=min(a)
c=max(a)
d=sum(a)/len(a)
e=sum(a)
... | [
"Your code has a few quirks that you may want to tweak:\n\nThere is a break statement inside the try, but no for loop.\nBoth if and else print the same text. You can't know which one printed the output.\n\nJust by changing the captured exception type from NameError to SyntaxError should be enough:\nvar = input(\"En... | [
0
] | [] | [] | [
"python",
"syntax_error"
] | stackoverflow_0074617795_python_syntax_error.txt |
Q:
Overlay Graphs at same point
I want to overlay some graphs out of CSV data (two datasets).
The graph I got from my dataset is shown down below.
Is there any way to plot those datasets over specific points? I would like to overlay these plots by using the anchor of the "big drop" to compare them in a better way.
Th... | Overlay Graphs at same point | I want to overlay some graphs out of CSV data (two datasets).
The graph I got from my dataset is shown down below.
Is there any way to plot those datasets over specific points? I would like to overlay these plots by using the anchor of the "big drop" to compare them in a better way.
The code used:
import pandas as pd
i... | [
"Part 1: Anchor times\nA simple way is to find the times of interest (lowest point) in each frame, then plot each series with x=t - t_peak instead of x=t. Two ways come to mind to find the desired anchor points:\n\nSimply using the global minimum (in your plots, that would work fine), or\nUsing the most prominent l... | [
2
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074612930_matplotlib_pandas_python.txt |
Q:
What do the scipy.stats.binom and script.stats.hypergeom functions actually do?
I am trying to work with some hypergeometric and binomial random variables, and so I am looking at the scipy.stats functionality. But I'm confused what scipy.stats.binom() and script.stats.hypergeom() functions actually do. Do they imp... | What do the scipy.stats.binom and script.stats.hypergeom functions actually do? | I am trying to work with some hypergeometric and binomial random variables, and so I am looking at the scipy.stats functionality. But I'm confused what scipy.stats.binom() and script.stats.hypergeom() functions actually do. Do they implicitly create a PMF for with given parameters, which we then access with the stats.p... | [
"According to the documentation:\n\nA binomial discrete random variable.\nAs an instance of the rv_discrete class, binom object inherits from it\na collection of generic methods (see below for the full list), and\ncompletes them with details specific for this particular distribution.\n\nSome of these methods are pm... | [
0
] | [] | [] | [
"probability_distribution",
"python",
"scipy",
"scipy.stats",
"statistics"
] | stackoverflow_0074613606_probability_distribution_python_scipy_scipy.stats_statistics.txt |
Q:
xml to srt conversion not working after installing pytube
I have installed pytube to extract captions from some youtube videos. Both the following code give me the xml captions.
from pytube import YouTube
yt = YouTube('https://www.youtube.com/watch?v=4ZQQofkz9eE')
caption = yt.captions['a.en']
print(caption.xml_ca... | xml to srt conversion not working after installing pytube | I have installed pytube to extract captions from some youtube videos. Both the following code give me the xml captions.
from pytube import YouTube
yt = YouTube('https://www.youtube.com/watch?v=4ZQQofkz9eE')
caption = yt.captions['a.en']
print(caption.xml_captions)
and also as mentioned in the docs
yt = YouTube('http:/... | [
"This is a bug in the library itself. Everything below is done in pytube 11.01.\nIn the captions.py file on line 76 replace:\nfor i, child in enumerate(list(root)):\n\nto:\nfor i, child in enumerate(list(root.findall('body/p'))):\n\nThen on line 83, replace:\nduration = float(child.attrib[\"dur\"])\n\nto:\nduration... | [
4,
3,
0
] | [] | [] | [
"python",
"pytube",
"xml"
] | stackoverflow_0068780808_python_pytube_xml.txt |
Q:
How do i make my discord bot reply to a certain user always with the same string?
made my own discord bot using py and trying to solve the issue in the title.
This is my current code for responses
def get_response(message: str) -> str:
p_message = message.lower()
if p_message == 'hello':
return ''... | How do i make my discord bot reply to a certain user always with the same string? | made my own discord bot using py and trying to solve the issue in the title.
This is my current code for responses
def get_response(message: str) -> str:
p_message = message.lower()
if p_message == 'hello':
return ''
if p_message == 'alex':
return ''
if p_message == 'benji':
r... | [
"I assume you use the discord libary, so this could be a solution to your problem\nimport discord #dependencies\n\nclient = discord.Client() #create a client object\n\n@client.event #bind the function\nasync def on_message(message):\n i... | [
0
] | [] | [] | [
"bots",
"discord",
"python"
] | stackoverflow_0074618155_bots_discord_python.txt |
Q:
How to loop over 2 things in asyncio using aiohttp
I am very new to asyncio and REST APIs in general. I had a rudimentary code working using requests but it was very slow (20-30 minutes), and it seems like asyncio and aiohttp are the tools I need to use to improve this situation.
What my code does is send a get re... | How to loop over 2 things in asyncio using aiohttp | I am very new to asyncio and REST APIs in general. I had a rudimentary code working using requests but it was very slow (20-30 minutes), and it seems like asyncio and aiohttp are the tools I need to use to improve this situation.
What my code does is send a get request to an endpoint which returns a list of jobids and ... | [
"One solution might be creating few tasks which wait for data (job_url, job_id) from asyncio.Queue and perform the get_all_files, downloading, ... tasks independent of each other.\nA pseudocode:\nimport asyncio\nimport aiohttp\n\nqueue = asyncio.Queue()\n\n\nasync def get_all_files_task():\n async with aiohttp.C... | [
0
] | [] | [] | [
"aiohttp",
"python",
"python_asyncio"
] | stackoverflow_0074617467_aiohttp_python_python_asyncio.txt |
Q:
Is there a way for two People to work on one Jupyter Notebook
A friend of mine and me are doing some field research for our Physics degree. And we are using jupyter notebook to analyse the data we get. We usually sit together working at two different copies of the same file that in the end will be drag and dropped... | Is there a way for two People to work on one Jupyter Notebook | A friend of mine and me are doing some field research for our Physics degree. And we are using jupyter notebook to analyse the data we get. We usually sit together working at two different copies of the same file that in the end will be drag and dropped together using jupyter lab. This is obviously not ideal, so i thou... | [
"\nCoCalc is expensive.\n\nFortunately, we also provide a complete free easy to install open source version of CoCalc, which you can run on any computer that supports Docker. For example, here's how to run it on Google cloud.\n(I have put too many years of my life into making realtiime collaboration work for Jupy... | [
9,
5,
2,
2,
1,
0
] | [] | [] | [
"collaboration",
"jupyter_notebook",
"python"
] | stackoverflow_0058903507_collaboration_jupyter_notebook_python.txt |
Q:
pyenv shell errors after uninstalling pyenv
I've recently been diagnosing why my pyenv installation is giving me errors in the shell. After trying everything I could find, I thought I would remove it from my system. However, after uninstalling, I am still seeing pyenv shell when loading a new terminal and zsh: com... | pyenv shell errors after uninstalling pyenv | I've recently been diagnosing why my pyenv installation is giving me errors in the shell. After trying everything I could find, I thought I would remove it from my system. However, after uninstalling, I am still seeing pyenv shell when loading a new terminal and zsh: command not found: pyenv
Steps I took:
rm -rf $(pyen... | [
"Turns out it was a VSCode thing. Opening a new terminal outside of VSCode didn't give the errors. It's due to the Python extension that was installed trying to activate an environment:\n\"python.terminal.activateEnvironment\": true\n\n"
] | [
1
] | [] | [] | [
"homebrew",
"pyenv",
"python",
"shell",
"zsh"
] | stackoverflow_0074618249_homebrew_pyenv_python_shell_zsh.txt |
Q:
using if-elif-else statments for adding two integers
I have just starting learning python and as I creating this program, which asks user to input two numbers, which then adds them to together using a simple if-elif-else statement, however the else part of the code just seems to not work if, an user types out th... | using if-elif-else statments for adding two integers | I have just starting learning python and as I creating this program, which asks user to input two numbers, which then adds them to together using a simple if-elif-else statement, however the else part of the code just seems to not work if, an user types out the six, for example, in words instead of the number.
num_1... | [
"This should be what you are looking for:\ntry:\n num_1 = int(input(\"Enter the first number: \"))\n num_2 = int(input(\"Enter the second number: \"))\nexcept ValueError:\n print(\"invalid\")\n exit()\nTotal = num_1 + num_2\nprint(\"The total is: \", Total)\n\nif num_1 > num_2:\n print(\"num_1 is great... | [
1,
0
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0074618168_if_statement_python.txt |
Q:
File not found error when launching a subprocess containing piped commands
I need to run the command date | grep -o -w '"+tz+"'' | wc -w using Python on my localhost. I am using subprocess module for the same and using the check_output method as I need to capture the output for the same.
However it is throwing me... | File not found error when launching a subprocess containing piped commands | I need to run the command date | grep -o -w '"+tz+"'' | wc -w using Python on my localhost. I am using subprocess module for the same and using the check_output method as I need to capture the output for the same.
However it is throwing me an error :
Traceback (most recent call last):
File "test.py", line 47, in <mo... | [
"You have to add shell=True to execute a shell command. check_output is trying to find an executable called: date | grep -o -w '\"+tz+\"'' | wc -w and he cannot find it. (no idea why you removed the essential information from the error message).\nSee the difference between:\n>>> subprocess.check_output('date | grep... | [
139,
20,
6,
0,
0,
0
] | [] | [] | [
"pipe",
"python",
"shell",
"subprocess"
] | stackoverflow_0024306205_pipe_python_shell_subprocess.txt |
Q:
How can I find the respective P-values for a multiple linear regression using the linear model from sklearn?
So, I'm trying to develop a ml model for multiple linear regression that predicts the Y given n number of X variables. So far, my model can read in a data set and give the predicted value with a coefficien... | How can I find the respective P-values for a multiple linear regression using the linear model from sklearn? | So, I'm trying to develop a ml model for multiple linear regression that predicts the Y given n number of X variables. So far, my model can read in a data set and give the predicted value with a coefficient of determination as well as the respective coefficients for a 1-unit increase in X. The only issues are:
I can... | [
"As far as i know sklearn doesn't return p values, is better using the statsmodels library.\nBut if you need to use sklearn anyway, you can find various solutions here:\nFind p-value (significance) in scikit-learn LinearRegression\n"
] | [
1
] | [] | [] | [
"data_science",
"machine_learning",
"python",
"regression",
"statistics"
] | stackoverflow_0074618290_data_science_machine_learning_python_regression_statistics.txt |
Q:
What is the best way to write a dictionary of column connection with column2?
How to create dictionary of connecting column index selection:
data:
No_1 C_N
1 1
1 2
1 7
2 13
2 6
desired output sho... | What is the best way to write a dictionary of column connection with column2? | How to create dictionary of connecting column index selection:
data:
No_1 C_N
1 1
1 2
1 7
2 13
2 6
desired output should be like {1:[1,2,7],2:[13,6]}
I have tried this, but it doesn't seem to work.
im... | [
"Use df.groupby('No_1')['C_N'].apply(list).to_dict().\nThis gives you {1: [1, 2, 7], 2: [13, 6]}.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074618398_python.txt |
Q:
How to match version substring within overall string
I am trying to match a version substring with regex in the form of v###.##.### or version #.##.###. The number of version numbers doesn't matter and there may or may not be a space after the v or version. This is what I was trying so far but it's not matching in... | How to match version substring within overall string | I am trying to match a version substring with regex in the form of v###.##.### or version #.##.###. The number of version numbers doesn't matter and there may or may not be a space after the v or version. This is what I was trying so far but it's not matching in some cases:
\bv\s?[\d.]*\b|\bversion\s?[\d.]*\b
For exam... | [
"First, your pattern can be shortened considerably by implementing an optional non-capturing group so that v or version could be matched without the need of an alternation.\nNext, the first \\b requires a word boundary but the version information starts after _ in the second expected match, and _ is a word char.\nY... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074618484_python_regex.txt |
Q:
Is there an easy way to construct a pandas DataFrame from an Iterable of attrs objects?
One can do that with dataclasses like so:
from dataclasses import dataclass
import pandas as pd
@dataclass
class MyDataClass:
i: int
s: str
df = pd.DataFrame([MyDataClass("a", 1), MyDataClass("b", 2)])
that makes the... | Is there an easy way to construct a pandas DataFrame from an Iterable of attrs objects? | One can do that with dataclasses like so:
from dataclasses import dataclass
import pandas as pd
@dataclass
class MyDataClass:
i: int
s: str
df = pd.DataFrame([MyDataClass("a", 1), MyDataClass("b", 2)])
that makes the DataFrame df with columns i and s as one would expect.
Is there an easy way to do that with... | [
"You can access the dictionary at the heart of a dataclass like so\na = MyDataClass(\"a\", 1)\na.__dict__\n\nthis outputs:\n{'i': 'a', 's': 1}\n\nKnowing this, if you have an iterable arr of type MyDataClass, you can access the __dict__ attribute and construct a dataframe\narr = [MyDataClass(\"a\", 1), MyDataClass(... | [
1
] | [] | [] | [
"pandas",
"python",
"python_attrs"
] | stackoverflow_0074618499_pandas_python_python_attrs.txt |
Q:
Having inputs add onto each other in python
I am a beginner, and I was working on a simple credit program. I want it to work so every time I add an input of a number it gets stored in a variable that shows my total balance. The problem right now is that the program is only a one use program so the input i enter do... | Having inputs add onto each other in python | I am a beginner, and I was working on a simple credit program. I want it to work so every time I add an input of a number it gets stored in a variable that shows my total balance. The problem right now is that the program is only a one use program so the input i enter does not get saved into a variable so that when I e... | [
"You'll need to introduce a while loop to keep it going. Try this:\ncredit_limit = 2000\ncredit_balance = 0\n\nwhile True:\n\n print('Welcome to the Credit Card Company')\n Purchase = int(input(\"How much was your purchase? \"))\n Total = credit_balance + Purchase\n\n print(\"Your account value right no... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074618424_python.txt |
Q:
Solving generalized eigenvalue system with a semidefinite positive B in python
I am trying to use Normalized Cut algorithm (Shi and Malik, 2000) to cut a matrix into two matrices. In this regard, I need to find the second smallest eigenvector in a generalized eigenvalue system (Ax = lambda.B.x). In my input, B is ... | Solving generalized eigenvalue system with a semidefinite positive B in python | I am trying to use Normalized Cut algorithm (Shi and Malik, 2000) to cut a matrix into two matrices. In this regard, I need to find the second smallest eigenvector in a generalized eigenvalue system (Ax = lambda.B.x). In my input, B is a semidefinite positive matrix. However, scipy.linalg.eigh requires B to be definite... | [
"If B is semidefinite, it means it has at least one eigenvector associated with an eigenvalue 0, you still could have solutions if the nullspace of B is also a null space of A, i.e. if B @ x = 0, A @ x = 0, but in that case the generalized eigenvalue associated with x is undetermined.\n"
] | [
0
] | [] | [] | [
"eigenvalue",
"eigenvector",
"linear_algebra",
"python",
"scipy"
] | stackoverflow_0074618427_eigenvalue_eigenvector_linear_algebra_python_scipy.txt |
Q:
Sometimes pip install is very slow
I am sure it is not network issue. Some of my machine install packages using pip is very fast while some other machine is pretty slow, from the logs, I suspect the slow is due to it will compile the package, I am wondering how can I avoid this compilation to make the pip installa... | Sometimes pip install is very slow | I am sure it is not network issue. Some of my machine install packages using pip is very fast while some other machine is pretty slow, from the logs, I suspect the slow is due to it will compile the package, I am wondering how can I avoid this compilation to make the pip installation fast. Here's the logs from the slow... | [
"The slowness is due to compilation indeed. But there is now the manylinux tag. Which allows the installation of pre-compiled distributions. See for example the PyPI page of numpy to see if a manylinux package is provided for your Python version.\nUpdate (2021-06)\nSince this answer received some attention lately, ... | [
24,
1,
0
] | [
"Command\nInstead of (too slow to complete)\npython -m pip install numpy\n\nThis worked (fast as supposed to be)\npip install numpy\n\nCheck\npython\n\nimport numpy as np \n\n(it shouldn't give any errors)\n"
] | [
-34
] | [
"pip",
"python"
] | stackoverflow_0035144103_pip_python.txt |
Q:
Starting a python script from another before it crashes
I'm trying to make some project code I have written, more resilient to crashes, except the circumstances of my previous crashes have all been different.
So that I do not have to try and account for every single one, I thought I'd try to get my code to either ... | Starting a python script from another before it crashes | I'm trying to make some project code I have written, more resilient to crashes, except the circumstances of my previous crashes have all been different.
So that I do not have to try and account for every single one, I thought I'd try to get my code to either restart, or execute a copy of itself in place of it and then ... | [
"You can do this in many ways. Your subprocess.call() option would work - but it depends on the details of implementation. Perhaps the easiest is to use multiprocessing to run the program in a subprocess while the parent simply restarts it as necessary.\nimport multiprocessing as mp\nimport time\n\ndef do_the_thing... | [
1,
0
] | [] | [] | [
"python",
"restart"
] | stackoverflow_0074593058_python_restart.txt |
Q:
matplotlib plot monthly count in order
How do I plot a monthly count of events with the right order in the x-axis?
I have several dataframes like the below (this is an example):
df = pd.DataFrame({'Month': [5, 6, 8, 9, 1, 2, 3, 4, 7, 10, 11, 12], 'Count': [3, 1, 6, 1, 0, 0, 0, 0, 0, 0, 0, 0]})
where I have counts... | matplotlib plot monthly count in order | How do I plot a monthly count of events with the right order in the x-axis?
I have several dataframes like the below (this is an example):
df = pd.DataFrame({'Month': [5, 6, 8, 9, 1, 2, 3, 4, 7, 10, 11, 12], 'Count': [3, 1, 6, 1, 0, 0, 0, 0, 0, 0, 0, 0]})
where I have counts of events per month, not in order. My aim i... | [
"Using sort_values:\ndf = df.sort_values('Month')\n\nor directly plotting from pandas:\nimport matplotlib.ticker as mticker\n\nfig, ax = plt.subplots(1,1)\ndf.sort_values('Month').plot(\n x='Month', y='Count', \n marker='o', legend=False, ax=ax\n)\nax.grid(color='gray', linestyle='-', linewidth=0.1)\nax.xaxis... | [
0
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074618685_matplotlib_pandas_python.txt |
Q:
Insert a row after a date in a dataframe
I have a Dataframe like :
date col1 col2
0 2022-10-07 04:00:00 x x1
1 2022-10-08 04:00:00 y x2
I need to update a row (as dictionary) in a specific date if exist, and if it does not exist, insert the row next to the closest da... | Insert a row after a date in a dataframe | I have a Dataframe like :
date col1 col2
0 2022-10-07 04:00:00 x x1
1 2022-10-08 04:00:00 y x2
I need to update a row (as dictionary) in a specific date if exist, and if it does not exist, insert the row next to the closest date.
For this new given date 2022-10-07 05:00:0... | [
"You can set the date as index and update like:\ndf1 = df.set_index('date')\ndf1.loc[new_date, dic.keys()] = dic.values()\ndf = df1.sort_index().reset_index().ffill()\n\nIt will insert new date if it doesn't exist. If it exists it will update the record at that index.\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074618436_pandas_python.txt |
Q:
Keep a datetime.date in 'yyyy-mm-dd' format when using Flask's jsonify
For some reason, the jsonify function is converting my datetime.date to what appears to be an HTTP date. How can I keep the date in yyyy-mm-dd format when using jsonify?
test_date = datetime.date(2017, 4, 27)
print(test_date) # 2017-04-27
test... | Keep a datetime.date in 'yyyy-mm-dd' format when using Flask's jsonify | For some reason, the jsonify function is converting my datetime.date to what appears to be an HTTP date. How can I keep the date in yyyy-mm-dd format when using jsonify?
test_date = datetime.date(2017, 4, 27)
print(test_date) # 2017-04-27
test_date_jsonify = jsonify(test_date)
print(test_date_jsonify.get_data(as_text=... | [
"Following this snippet you can do this:\nfrom flask.json import JSONEncoder\nfrom datetime import date\n\n\nclass CustomJSONEncoder(JSONEncoder):\n def default(self, obj):\n try:\n if isinstance(obj, date):\n return obj.isoformat()\n iterable = iter(obj)\n exce... | [
59,
23,
1,
0
] | [] | [] | [
"date",
"datetime",
"flask",
"json",
"python"
] | stackoverflow_0043663552_date_datetime_flask_json_python.txt |
Q:
How to store django objects as session variables ( object is not JSON serializable)?
I have a simple view
def foo(request):
card = Card.objects.latest(datetime)
request.session['card']=card
For the above code I get the error
"<Card: Card object> is not JSON serializable"
Django version 1.6.2. What am I d... | How to store django objects as session variables ( object is not JSON serializable)? | I have a simple view
def foo(request):
card = Card.objects.latest(datetime)
request.session['card']=card
For the above code I get the error
"<Card: Card object> is not JSON serializable"
Django version 1.6.2. What am I doing wrong ?
| [
"In a session, I'd just store the object primary key:\nrequest.session['card'] = card.id\n\nand when loading the card from the session, obtain the card again with:\ntry:\n card = Card.objects.get(id=request.session['card'])\nexcept (KeyError, Card.DoesNotExist):\n card = None\n\nwhich will set card to None if... | [
23,
4,
3,
0,
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0022294788_django_python.txt |
Q:
How do I insert rows based on a column of start dates and end dates with python?
I have a data frame of product numbers that are on sales promotions. The columns include the product number, start date, end date, promotion type and promotion description. The dates could span up to 4 months. I need to add rows to... | How do I insert rows based on a column of start dates and end dates with python? | I have a data frame of product numbers that are on sales promotions. The columns include the product number, start date, end date, promotion type and promotion description. The dates could span up to 4 months. I need to add rows to account for the months between the start and end dates.
Here is an example of the dat... | [
"I figured this out although it may not be elegant:\ndf2 = pd.DataFrame()\nfor item in df['item'].unique():\n df_ = df[df['item'] == item]\n df_ = pd.concat([df_,df_.apply(lambda dt: pd.date_range(dt['start_date'], dt['end_date'], freq=\"MS\"), axis = 'columns').explode(ignore_index=True)], axis=1)\n df_.d... | [
1
] | [] | [] | [
"data_wrangling",
"pandas",
"python"
] | stackoverflow_0074616848_data_wrangling_pandas_python.txt |
Q:
Can't store a Selenium web driver object to recover it through Django views
After days of research, I wasn't able to properly store a Selenium web driver object to recover it through different Django views. In fact, My project has only one view, and all I need is to recover the same instance of the web driver obje... | Can't store a Selenium web driver object to recover it through Django views | After days of research, I wasn't able to properly store a Selenium web driver object to recover it through different Django views. In fact, My project has only one view, and all I need is to recover the same instance of the web driver object every time that view is called. All my app does is making AJAX post requests t... | [
"I was in the same boat. The best solution that worked great for me was to use global variables.\nIn this case, before creating the web driver object, just call \"global driver\" on each view that you need that same object.\nSo, I would do this way:\nglobal driver\ndriver = webdriver.Chrome(executable_path=driverpa... | [
0
] | [] | [] | [
"django",
"python",
"selenium",
"session",
"store"
] | stackoverflow_0063857592_django_python_selenium_session_store.txt |
Q:
cv2 import error on Jupyter notebook
I'm trying to import cv2 on Jupyter notebook but I get this error:
ImportError: No module named cv2
I am frustrated because I'm working on this simple issue for hours now. it works on Pycharm but not on Jupiter notebook. I've already installed cv2 into Python2.7's site package... | cv2 import error on Jupyter notebook | I'm trying to import cv2 on Jupyter notebook but I get this error:
ImportError: No module named cv2
I am frustrated because I'm working on this simple issue for hours now. it works on Pycharm but not on Jupiter notebook. I've already installed cv2 into Python2.7's site packages, configured Jupyter's kernel to python2,... | [
"Is your python path looking in the right place? Check where python is looking for the module. Within the notebook try:\nimport os\nos.sys.path\n\nIs the cv2 module located in any of those directories? If not your path is looking in the wrong place. If it is overlooking the install location, append it to your pytho... | [
17,
13,
7,
6,
5,
3,
3,
1,
1,
0,
0,
0,
0,
0
] | [
"One of possibility is that you could have written import cv2 and its utilisation in separate cells of jupyter notebook.If this is the case then first run the cell having import cv2 part and then run the cell utilising the cv2 library.\n"
] | [
-1
] | [
"jupyter_notebook",
"opencv",
"python"
] | stackoverflow_0038109270_jupyter_notebook_opencv_python.txt |
Q:
Read and Write Structures in the Beckhoff Plc with Python Pyads Module(ADSError: symbol not found (1808))
I am trying to read and write to structure variables in the CX9020 Benchoff Plc at Linux. I am doing the same thing as in the Pyads documentation example but I am getting error. I added definitions and error t... | Read and Write Structures in the Beckhoff Plc with Python Pyads Module(ADSError: symbol not found (1808)) | I am trying to read and write to structure variables in the CX9020 Benchoff Plc at Linux. I am doing the same thing as in the Pyads documentation example but I am getting error. I added definitions and error to below . Thanks for your help.
PLC Definition Code :
TYPE sample_structure :
STRUCT
rVar : LREAL;
rVar... | [
"You've created the structure , but you haven't done the implementation in GVL.\nYou have to add in GVL:\nVAR_GLOBAL\n\n sample_structure : sample_structure;\n\nEND_VAR\n\n"
] | [
0
] | [] | [] | [
"linux",
"plc",
"python",
"structure"
] | stackoverflow_0073118844_linux_plc_python_structure.txt |
Q:
Find missing numbers in a column dataframe pandas
I have a dataframe with stores and its invoices numbers and I need to find the missing consecutive invoices numbers per Store, for example:
df1 = pd.DataFrame()
df1['Store'] = ['A','A','A','A','A','B','B','B','B','C','C','C','D','D']
df1['Invoice'] = ['1','2','5','... | Find missing numbers in a column dataframe pandas | I have a dataframe with stores and its invoices numbers and I need to find the missing consecutive invoices numbers per Store, for example:
df1 = pd.DataFrame()
df1['Store'] = ['A','A','A','A','A','B','B','B','B','C','C','C','D','D']
df1['Invoice'] = ['1','2','5','6','8','20','23','24','30','200','202','203','204','206... | [
"You can use groupby.apply to compute a set difference with the range from the min to max value. Then explode:\n(df1.astype({'Invoice': int})\n .groupby('Store')['Invoice']\n .apply(lambda s: set(range(s.min(), s.max())).difference(s))\n .explode().reset_index()\n)\n\nNB. if you want to ensure having sorte... | [
4,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074618512_dataframe_pandas_python.txt |
Q:
Trying to get specific words from large body of text? Python
I am trying to write a script in python that given the following large body of text, will find the username and password. Then I want it to be written into a row in a csv. This script will run every day and add a new row each time there is a new account ... | Trying to get specific words from large body of text? Python | I am trying to write a script in python that given the following large body of text, will find the username and password. Then I want it to be written into a row in a csv. This script will run every day and add a new row each time there is a new account created (Usernames are unique).
TEXT
TEXT
username: Test_user
TEXT... | [
"This is a low effort response but you have a low effort question https://help.relativity.com/RelativityOne/Content/Relativity/Regular_expressions/Searching_with_regular_expressions.htm\nThe answer is regular expressions.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074618887_python.txt |
Q:
How do I create unlimited inputs in Python?
I'm supposed to write a program that will determine letter grades (A, B, C, D, F), track how many students are passing and failing, and display the class average. One part that is getting me is that "the program will be able to handle as many students as the user indicat... | How do I create unlimited inputs in Python? | I'm supposed to write a program that will determine letter grades (A, B, C, D, F), track how many students are passing and failing, and display the class average. One part that is getting me is that "the program will be able to handle as many students as the user indicates are in this class." How to I get to create unl... | [
"The infinite input can be done using the while loop. You can save that input to the other data structure such a list, but you can also put below it the code.\nwhile True:\n x = input('Enter something')\n determineGrade(x)\n determinePass(x)\n\n",
"Try this out.\nwhile True:\n try:\n variable =... | [
2,
1,
1,
1,
0
] | [] | [] | [
"function",
"input",
"python"
] | stackoverflow_0062978714_function_input_python.txt |
Q:
Add uuid to a new column in a pandas DataFrame
I'm looking to add a uuid for every row in a single new column in a pandas DataFrame. This obviously fills the column with the same uuid:
import uuid
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(4,3), columns=list('abc'),
... | Add uuid to a new column in a pandas DataFrame | I'm looking to add a uuid for every row in a single new column in a pandas DataFrame. This obviously fills the column with the same uuid:
import uuid
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(4,3), columns=list('abc'),
index=['apple', 'banana', 'cherry', 'date'])
df['uu... | [
"This is one way:\ndf['uuid'] = [uuid.uuid4() for _ in range(len(df.index))]\n\n",
"I can't speak to computational efficiency here, but I prefer the syntax here, as it's consistent with the other apply-lambda modifications I usually use to generate new columns:\ndf['uuid'] = df.apply(lambda _: uuid.uuid4(), axis=... | [
38,
20,
4,
2,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x",
"uuid"
] | stackoverflow_0048837006_dataframe_pandas_python_python_3.x_uuid.txt |
Q:
Why does Docker on Windows CMD fail for bash script?
I've got a Dockerfile containerizing a Python FastAPI application that works on my Mac with this final CMD statement:
CMD ["./startup.sh"]
However, when I try to run the Dockerfile on a Windows machine that has Docker installed, it can't run/find the startup.sh... | Why does Docker on Windows CMD fail for bash script? | I've got a Dockerfile containerizing a Python FastAPI application that works on my Mac with this final CMD statement:
CMD ["./startup.sh"]
However, when I try to run the Dockerfile on a Windows machine that has Docker installed, it can't run/find the startup.sh script. I have to change the CMD to this:
CMD ["uvicorn",... | [
"Check the startup.sh file permissions on the Windows machine and make sure that it's executable.\n"
] | [
0
] | [] | [] | [
"docker",
"fastapi",
"python",
"windows"
] | stackoverflow_0074618824_docker_fastapi_python_windows.txt |
Q:
Get values of Enum fields from Django Queryset
I have a model with an enum column, e.g.
# Using Django 2.2 (does not support Enums natively)
from django_enum_choices.fields import EnumChoiceField
class Service(Enum)
MOBILE: "MOBILE"
LAPTOP: "LAPTOP"
class Device(models.Model):
service = EnumChoiceFie... | Get values of Enum fields from Django Queryset | I have a model with an enum column, e.g.
# Using Django 2.2 (does not support Enums natively)
from django_enum_choices.fields import EnumChoiceField
class Service(Enum)
MOBILE: "MOBILE"
LAPTOP: "LAPTOP"
class Device(models.Model):
service = EnumChoiceField(Service)
...
Is it possible to get get the ... | [
"It turns out that you can just use a serializer!\nfrom django_enum_choices.serializers import EnumChoiceModelSerializerMixin\nfrom rest_framework import serializer\n\n\nclass DeviceSerializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer):\n class Meta:\n model = Device\n fields = (\... | [
0
] | [] | [] | [
"django",
"enums",
"python"
] | stackoverflow_0074616378_django_enums_python.txt |
Q:
How to make approximate equal division of task between given number of people?
Let say task is to divide 33 tables between 3 people. If equally divided, then output is [11, 11, 11] and if number of tables is 35 tables, then output should be [12, 12, 11].
When I am trying to divide, I get [11, 11, 11, 1, 1]. I nee... | How to make approximate equal division of task between given number of people? | Let say task is to divide 33 tables between 3 people. If equally divided, then output is [11, 11, 11] and if number of tables is 35 tables, then output should be [12, 12, 11].
When I am trying to divide, I get [11, 11, 11, 1, 1]. I need help to solve this in python. This is part of my main problem statement.
Here is m... | [
"i hope i understood you correctly, if i did this code will do the trick:\nnumber_of_tables = 35\nnumber_of_people = 3\n\ntables_list = [int(number_of_tables / number_of_people) for _ in range(number_of_people)]\n\nremainder = number_of_tables % number_of_people\n\nfor index in range(remainder):\n tables_list[in... | [
2
] | [] | [] | [
"list",
"logic",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074616430_list_logic_pandas_python_python_3.x.txt |
Q:
Why these two WAV-creating functions are not producing identical output?
I am using these functions (that receive a pyaudio input) to produce an audio object usable on torchaudio.
However, only "write2" produces a result that works, but not "write1".
def write2(recording):
n_files = len(os.listdir(f_name_direc... | Why these two WAV-creating functions are not producing identical output? | I am using these functions (that receive a pyaudio input) to produce an audio object usable on torchaudio.
However, only "write2" produces a result that works, but not "write1".
def write2(recording):
n_files = len(os.listdir(f_name_directory))
filename = os.path.join(f_name_directory, 'file.wav')
wf = wave... | [
"As said by @jasonharper on the opening post comment, the solution was to insert buffer.seek(0) at the end of the function before returning it.\n(...)\n wave_write.close()\n buffer.seek(0)\n return buffer\n\n"
] | [
0
] | [] | [] | [
"pyaudio",
"python",
"torchaudio",
"wave"
] | stackoverflow_0074618692_pyaudio_python_torchaudio_wave.txt |
Q:
I am using Python on Visual Studio Code to import an excel file but I am getting an import error
I want to read the data on an excel file within a F drive. I am using python on Visual Studio Code to try achieve this however I am getting an error as seen in the pictures below. I installed pandas but I still get an ... | I am using Python on Visual Studio Code to import an excel file but I am getting an import error | I want to read the data on an excel file within a F drive. I am using python on Visual Studio Code to try achieve this however I am getting an error as seen in the pictures below. I installed pandas but I still get an error. How can I fix this issue?
Coding Error
Installed Pandas Library
I tried closing and opening vis... | [
"You should try to open terminal in VS Code, and run pip freeze (and pip3 freeze). Check if you find pandas in the results, it won't. That must be because you'd have multiple installations of Python on your system. You may do any one of the below -\n\nGet rid of all but one Python installation.\nInstall pandas on t... | [
2
] | [
"To read an Excel file with Python, you need to install the pandas library. To install pandas, open the command line or terminal and type:\npip install pandas\nOnce pandas is installed, you can read an Excel file like this:\nimport pandas as pd\ndf = pd.read_excel('file_name.xlsx')\nprint(df)\nYou should also make ... | [
-1
] | [
"pip",
"python",
"visual_studio_code"
] | stackoverflow_0074618712_pip_python_visual_studio_code.txt |
Q:
constrained linear regression / quadratic programming python
I have a dataset like this:
import numpy as np
a = np.array([1.2, 2.3, 4.2])
b = np.array([1, 5, 6])
c = np.array([5.4, 6.2, 1.9])
m = np.vstack([a,b,c])
y = np.array([5.3, 0.9, 5.6])
and want to fit a constrained linear regression
y = b1*a + b2*b + b... | constrained linear regression / quadratic programming python | I have a dataset like this:
import numpy as np
a = np.array([1.2, 2.3, 4.2])
b = np.array([1, 5, 6])
c = np.array([5.4, 6.2, 1.9])
m = np.vstack([a,b,c])
y = np.array([5.3, 0.9, 5.6])
and want to fit a constrained linear regression
y = b1*a + b2*b + b3*c
where all b's sum to one and are positive: b1+b2+b3=1
A simila... | [
"EDIT:\nThese two approaches are very general and can work for small-medium scale instances. For a more efficient approach, check the answer of chthonicdaemon (using customized preprocessing and scipy's optimize.nnls).\nUsing scipy\nCode\nimport numpy as np\nfrom scipy.optimize import minimize\n\na = np.array([1.2,... | [
9,
6,
1,
0,
0
] | [] | [] | [
"linear_regression",
"python",
"quadratic_programming",
"scipy"
] | stackoverflow_0039852921_linear_regression_python_quadratic_programming_scipy.txt |
Q:
Replace rows in an MxN matrix with numbers from 1 to N
Im interested in replacing all of my rows in an MxN matrix with values from 1 to N.
For example:
[[4,6,8,9,3],[5,1,2,5,6],[1,9,4,5,7],[3,8,8,2,5],[1,4,2,2,7]]
To:
[[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
I've tried using loops going throug... | Replace rows in an MxN matrix with numbers from 1 to N | Im interested in replacing all of my rows in an MxN matrix with values from 1 to N.
For example:
[[4,6,8,9,3],[5,1,2,5,6],[1,9,4,5,7],[3,8,8,2,5],[1,4,2,2,7]]
To:
[[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
I've tried using loops going through each row individually but struggle to replace elements.
| [
"Try:\nlst = [\n [4, 6, 8, 9, 3],\n [5, 1, 2, 5, 6],\n [1, 9, 4, 5, 7],\n [3, 8, 8, 2, 5],\n [1, 4, 2, 2, 7],\n]\n\nfor row in lst:\n row[:] = range(1, len(row) + 1)\n\nprint(lst)\n\nPrints:\n[\n [1, 2, 3, 4, 5],\n [1, 2, 3, 4, 5],\n [1, 2, 3, 4, 5],\n [1, 2, 3, 4, 5],\n [1, 2, 3, 4... | [
0,
0
] | [] | [] | [
"arrays",
"matrix",
"numpy",
"python",
"row"
] | stackoverflow_0074618937_arrays_matrix_numpy_python_row.txt |
Q:
Removing € from a string and converting the string into an int using python to calculate the average price per year
So I am scraping a website and the code gives me all the information I want however when scraping it also gives me the "€" symbol with the price. So I want to be able to have the price as a int and r... | Removing € from a string and converting the string into an int using python to calculate the average price per year | So I am scraping a website and the code gives me all the information I want however when scraping it also gives me the "€" symbol with the price. So I want to be able to have the price as a int and remove the "€" symbol so I can Calculate the average car price per year. It does give me the ValueError: invalid literal f... | [
"You can define a custom function for that and apply it on new/existing column,\nlike so:\npd = pd.DataFrame(\n {\"col1\": [1,2,2,3,4],\n \"prices\": [\"1€\", \"2.2€\", \"5€\",\"66€\", \"999€\"]\n }\n)\n\n# Use own function to create custom column\ndef remove_currency_sign(price: str, sign:str = \"€\")->in... | [
1,
1
] | [] | [] | [
"beautifulsoup",
"pandas",
"python",
"python_requests",
"web_scraping"
] | stackoverflow_0074619038_beautifulsoup_pandas_python_python_requests_web_scraping.txt |
Q:
Python: get a frequency count based on two columns (variables) in pandas dataframe some row appears
Hello I have the following dataframe.
Group Size
Short Small
Short Small
Moderate Medium
Moderate Small
Tall Large
I want to count the ... | Python: get a frequency count based on two columns (variables) in pandas dataframe some row appears | Hello I have the following dataframe.
Group Size
Short Small
Short Small
Moderate Medium
Moderate Small
Tall Large
I want to count the frequency of how many times the same row appears in the dataframe.
Group Size Time
... | [
"You can use groupby's size:\nIn [11]: df.groupby([\"Group\", \"Size\"]).size()\nOut[11]:\nGroup Size\nModerate Medium 1\n Small 1\nShort Small 2\nTall Large 1\ndtype: int64\n\nIn [12]: df.groupby([\"Group\", \"Size\"]).size().reset_index(name=\"Time\")\nOut[12]:\n Group ... | [
191,
86,
5,
0
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0033271098_dataframe_group_by_pandas_python.txt |
Q:
Playwright auto-scroll to bottom of infinite-scroll page
I am trying to automate the scraping of a site with "infinite scroll" with Python and Playwright.
The issue is that Playwright doesn't include, as of yet, a scroll functionnality let alone an infinite auto-scroll functionnality.
From what I found on the net ... | Playwright auto-scroll to bottom of infinite-scroll page | I am trying to automate the scraping of a site with "infinite scroll" with Python and Playwright.
The issue is that Playwright doesn't include, as of yet, a scroll functionnality let alone an infinite auto-scroll functionnality.
From what I found on the net and my personnal testing, I can automate an infinite or finite... | [
"So I found a working solution.\nWhat I did was to combine Javascript with python Playwright code.\nI start the setInterval with a timer of 200ms to scroll down on the page with page.evaluate() and then I follow it up with a python loop that checks every second whether the total height of the page (scroll included)... | [
12,
5,
1,
0
] | [
"This topic old, but new to me. I have been using the playwright wheel scroll but for me it takes control/focus on the mouse.\nSo if I happen to be typing (which i usually am) and it scrolls, my beautiful words go into the void to never be seen again.\nI am going to go ahead and try out the js solution posted above... | [
-2
] | [
"javascript",
"playwright",
"python",
"python_3.x"
] | stackoverflow_0069183922_javascript_playwright_python_python_3.x.txt |
Q:
Setting Mandelbrot Python Image Background Color to Cyan
How do I set the Mandelbrot Set background to cyan? I don't understand the code.
Here's the code:
# Python code for Mandelbrot Fractal
# Import necessary libraries
from PIL import Image
from numpy import complex, array
import colorsys
# setting the width o... | Setting Mandelbrot Python Image Background Color to Cyan | How do I set the Mandelbrot Set background to cyan? I don't understand the code.
Here's the code:
# Python code for Mandelbrot Fractal
# Import necessary libraries
from PIL import Image
from numpy import complex, array
import colorsys
# setting the width of the output image as 1024
WIDTH = 1024
# a function to retur... | [
"try to change \"mandelbrot\" function to\ndef mandelbrot(x, y):\n c0 = complex(x, y)\n c = 0\n for i in range(1, 1000):\n if abs(c) > 2:\n return (0, 0, 0)\n c = c * c + c0\n return (0, 255, 255)\n\nFinal return statement is a background color\n"
] | [
1
] | [] | [] | [
"mandelbrot",
"python"
] | stackoverflow_0074619148_mandelbrot_python.txt |
Q:
How to specified a group of object in a dataframe column using Python
In the example below, how do I specified 'mansion' under 'h_type', and find its highest price?
(prevent from finding a highest price from the whole data which might include 'aparment')
ie:
df=pd.DataFrame({'h_type':[aparment,mansion,....],'h_pr... | How to specified a group of object in a dataframe column using Python | In the example below, how do I specified 'mansion' under 'h_type', and find its highest price?
(prevent from finding a highest price from the whole data which might include 'aparment')
ie:
df=pd.DataFrame({'h_type':[aparment,mansion,....],'h_price':[..., ...,...]})
if df.loc[df['h_type']=='mansion']: ##<= do not wo... | [
"TL;DR:\nThat can be a oneliner:\nmax_price = df[df[\"h_price\"] == \"mansion\"]][\"h_price\"].max()\n\nExplanation\nA little bit of explaining here:\ndf[df[\"h_price\"] == \"mansion\"]]\n\nThat pieces selects all the rows who's column \"h_price\" value is the maximum.\ndf[df[\"h_price\"] == \"mansion\"]][\"h_price... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074618146_dataframe_pandas_python.txt |
Q:
How to get specific value from JSON response in Python
I have a response coming in as :
b'
{
"_items": [
{
"_id": "61a8dc29fab70adfacf59789",
"name": "CP",
"url": "",
"sd_subscriber_id": "",
"account_manager": "",
"contact_name": "... | How to get specific value from JSON response in Python | I have a response coming in as :
b'
{
"_items": [
{
"_id": "61a8dc29fab70adfacf59789",
"name": "CP",
"url": "",
"sd_subscriber_id": "",
"account_manager": "",
"contact_name": "",
"contact_email": "",
"phone": "",... | [
"You need to convert raw byte string to Python dict first, assuming that you are using Python version 3.6+ and your response object is either string or bytes:\nimport json\n\ndata = json.loads(response) # loads() decodes it to dict\ntemp = response['_items'] \n\n"
] | [
4
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074619209_json_python.txt |
Q:
Annotation not found outside plotly graph
I have a graph that looks like this:
where I want to add some text towards the left bottom side of the plot, something similar to the text at the bottom here, but for me on my left or right side of the graph.
I searched on stack and found many solutions, even one specifi... | Annotation not found outside plotly graph | I have a graph that looks like this:
where I want to add some text towards the left bottom side of the plot, something similar to the text at the bottom here, but for me on my left or right side of the graph.
I searched on stack and found many solutions, even one specific to the graph shown,however none work for me. ... | [
"Edit: figured how to do it by myself\nAdd another annotation like this, although it gives the text at the upper left corner of the graph,works for me. Just add this code instead of the previous annotation code in the question,the rest of the code remains the same.These dimensions work for the particular alignment ... | [
1
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074606535_plotly_python.txt |
Q:
Translating Stata if else statement to python
I have this piece of
Stata code that I am trying to translate into python.
if inlist(nid, 4580, 4250, 165101, 4679, 236205, 419098, 438439, 11240, 317089, 430032, 3716, 164729) {
capture confirm variable child_age_year
if !_rc {
replace child_age_year =... | Translating Stata if else statement to python | I have this piece of
Stata code that I am trying to translate into python.
if inlist(nid, 4580, 4250, 165101, 4679, 236205, 419098, 438439, 11240, 317089, 430032, 3716, 164729) {
capture confirm variable child_age_year
if !_rc {
replace child_age_year = 0
}
else {
gen child_age_year ... | [
"The code does not make much sense in Stata.\nWhat doesn't make sense is that the over-arching command\nif inlist(nid, 4580, 4250, 165101, 4679, 236205, 419098, 438439, 11240, 317089, 430032, 3716, 164729) \n\ncan in Stata only apply to the first observation (case, record, row) in the dataset.\nIn other words. it m... | [
1
] | [] | [] | [
"python",
"python_3.x",
"stata"
] | stackoverflow_0074618708_python_python_3.x_stata.txt |
Q:
Number of words in text you can fully type using this keyboard
There is such a task with Leetcode. Everything works for me when I press RUN, but when I submit, it gives an error:
text = "a b c d e"
brokenLetters = "abcde"
Output : 1
Expected: 0
def canBeTypedWords(self, text, brokenLetters):
for i in brokenLette... | Number of words in text you can fully type using this keyboard | There is such a task with Leetcode. Everything works for me when I press RUN, but when I submit, it gives an error:
text = "a b c d e"
brokenLetters = "abcde"
Output : 1
Expected: 0
def canBeTypedWords(self, text, brokenLetters):
for i in brokenLetters:
cnt = 0
text = text.split()
s1 = text[0]
s2 = te... | [
"So consider logically what you have to do, then write that algorithmically.\nLogically, you have a list of words, a list of broken letters, and you need to return the count of words that have none of those broken letters in them.\n\"None of those broken letters in them\" is the important bit -- if even one broken ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074619248_python.txt |
Q:
How do i differentiate between two widgets on the same event
I want to have some input boxes which contain an text for the user to know what is required to enter. This text should disappear when the user clicks on it. How do i know which box the user clicked?
class window():
def handleEvent(self,event):
... | How do i differentiate between two widgets on the same event | I want to have some input boxes which contain an text for the user to know what is required to enter. This text should disappear when the user clicks on it. How do i know which box the user clicked?
class window():
def handleEvent(self,event):
self.text.set("")
def handleEvent2(self,event):
a = ... | [
"You can use the widget attribute of the event object. It is a reference to the widget that got the event.\ndef handleEvent2(self,event):\n a = event.widget.get()\n print(a)\n\n",
"You can use the event.widget attribute to get a reference to the widget that triggered the event.\n",
"Since you are using tk... | [
2,
1,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074619193_python_tkinter.txt |
Q:
how can i do vector-matrix multiplication in python without numpy?
Ok, so i know this question has been asked several times before but they all had different errors
so i am a newbie in python and we were given a Algebra practical with python for vector-matrix multpilication
and this was my code but i am getting a ... | how can i do vector-matrix multiplication in python without numpy? | Ok, so i know this question has been asked several times before but they all had different errors
so i am a newbie in python and we were given a Algebra practical with python for vector-matrix multpilication
and this was my code but i am getting a specific error everytime which is
list index out of range
line 20 in
d=... | [
"i is indexing the row in d=m[i][j]*v[j], but your loop is over the number of columns. You could eliminate errors like that and make the code cleaner by looping directly over the rows. Instead of for i in range (c): you'd have for row in m: and d=row[j]*v[j]. You should also take advantage of the sum function to do... | [
0
] | [] | [] | [
"linear_algebra",
"python"
] | stackoverflow_0074618105_linear_algebra_python.txt |
Q:
REGEX : Extracting Table information from connection strings
I am attempting to extract Schema and Table information from connection string data. The Schema and Table information is in the format "Schema.Table" (e.g FROM EDWP_D2PM.SN_INC_RPTG_SCRUBBED in string below) . Multiple Schema and Tables can exist in the ... | REGEX : Extracting Table information from connection strings | I am attempting to extract Schema and Table information from connection string data. The Schema and Table information is in the format "Schema.Table" (e.g FROM EDWP_D2PM.SN_INC_RPTG_SCRUBBED in string below) . Multiple Schema and Tables can exist in the connection strings, and they always follow the words FROM or JOIN ... | [
"You can try to put ? after the prefix which will cause the expression not to match as much of the text as possible\n(?:DB2.Database)(?:\\s|\\S)*?\n\nThen the following\n(?:DB2.Database)(((?:\\s|\\S)*?(?:\\s+(JOIN|FROM)\\s+)(\\w+\\.\\w+))+)\n\nwould almost work but re module doesn't support repeated captures\nAs a ... | [
0,
0
] | [] | [] | [
"python",
"regex",
"regex_group"
] | stackoverflow_0074608287_python_regex_regex_group.txt |
Q:
My "list index out of range" problem in PYTHON
total_task=float(input("Enter the assigned total task length(in half-hour(s)):"))
total_len=total_task*2
leng=int(total_len)
payments=[]
hours=[]
for i in range(leng):
print("Enter the payment value( in TL) for task portion ID ",(i+1)," having length ",((i+1)*0.5)... | My "list index out of range" problem in PYTHON | total_task=float(input("Enter the assigned total task length(in half-hour(s)):"))
total_len=total_task*2
leng=int(total_len)
payments=[]
hours=[]
for i in range(leng):
print("Enter the payment value( in TL) for task portion ID ",(i+1)," having length ",((i+1)*0.5)," hour(s):")
portionLen=int(input())
paymen... | [
"The error message you attached is pretty clear:\n\nin line 23, either paymentsTable[i][k] or paymentsTable[k+1][j]\nhas an index out of range.\n\npaymentsTable has exactly leng elements, so their valid indices go from 0 to leng-1.\nEvery element paymentsTable[i] is also a list with exactly leng elements, so their ... | [
2,
0
] | [] | [] | [
"arrays",
"multidimensional_array",
"python"
] | stackoverflow_0074619007_arrays_multidimensional_array_python.txt |
Q:
how to use script to conditionally modify values in CSV file
The CSV file contains name and Values
i want any value more than 1000 converted to 1000 in same file or in differentt file. mostly using shell script. what is the best way to it?
for example the values are as follows
Name Value
ABV 1200
CCD 1000
CAD 500
... | how to use script to conditionally modify values in CSV file | The CSV file contains name and Values
i want any value more than 1000 converted to 1000 in same file or in differentt file. mostly using shell script. what is the best way to it?
for example the values are as follows
Name Value
ABV 1200
CCD 1000
CAD 500
DDD 1800
and i want it as
Name Value
ABV 1000
CCD 1000
CAD 500
DD... | [
"Using awk:\n$ awk '{print $1,($2+0>1000?1000:$2)}' file\n\nOutput:\nName Value\nABV 1000\nCCD 1000\nCAD 500\nDDD 1000\n\n",
"A few issues with OP's current code:\n\nneed to skip processing of the first line\n-gt is invalid in awk ... use > instead\n-F, says to use the comma as the input field delimiter but the s... | [
2,
1
] | [] | [] | [
"awk",
"bash",
"python",
"shell"
] | stackoverflow_0074619187_awk_bash_python_shell.txt |
Q:
group a list of paths based on directory name and file name
I want to sort my paths, based on directory name and then on file name. They are separated by first different folder ("TENT1" and "TENT2"). Notice that some files are inside "Job1" and "Job2" folders but some are not but need them sorted as well. Thank y... | group a list of paths based on directory name and file name | I want to sort my paths, based on directory name and then on file name. They are separated by first different folder ("TENT1" and "TENT2"). Notice that some files are inside "Job1" and "Job2" folders but some are not but need them sorted as well. Thank you!
paths = [
'/var/lib/conc/states/TENT1/Job1/metr-ok_2022_1... | [
"Instead of the dirname function for grouping you have to create your own function which can look like\nimport os.path\n\ndef grouper(path):\n d, f = os.path.split(path)\n f = f.split('-')[0]\n return d, f\n\nIt returns a tuple with the directory and the relevant part of the filename.\nIt can be used in th... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074616163_python.txt |
Q:
Update single value in JSON
I have a JSON file that looks like this:
{
"displayName": "",
"Location": "Jacksonville",
"directNumber": "+1 904-513-6504",
"extension": "36504"
},
{
"displayName": "Lawrence Curka",
"Location": "Jacksonville",
"directNumber": "+1 123-513-6508",
"e... | Update single value in JSON | I have a JSON file that looks like this:
{
"displayName": "",
"Location": "Jacksonville",
"directNumber": "+1 904-513-6504",
"extension": "36504"
},
{
"displayName": "Lawrence Curka",
"Location": "Jacksonville",
"directNumber": "+1 123-513-6508",
"extension": "36508"
},
{
"... | [
"i['displayName'] = \"Name Surname\"\n\njsonFile.write(json.dumps(i))\n\n"
] | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074619364_json_python.txt |
Q:
Set Airflow Variable dynamically
Hi community I need for help.
I have a GCS bucket called "staging". This bucket contain folders and subfolders (see picture).
The "date-folders" (eg. 20221128) may be several. Each date-folder has 3 subfolders: I'm interested in the "main_folder". The main_folder has 2 "project fo... | Set Airflow Variable dynamically | Hi community I need for help.
I have a GCS bucket called "staging". This bucket contain folders and subfolders (see picture).
The "date-folders" (eg. 20221128) may be several. Each date-folder has 3 subfolders: I'm interested in the "main_folder". The main_folder has 2 "project folders". Each project folder has severa... | [
"I would like to correct you in your usage of the term Variable . Airflow attributes a special meaning to this object. What you want is for the file info to be accessible as parameters in a task.\nUse XCom\nAssume you have the DAG with the python task called -- list_files_from_gcs.\nThis task is a python task which... | [
1
] | [] | [] | [
"airflow",
"apache_beam",
"google_cloud_composer",
"google_cloud_dataflow",
"python"
] | stackoverflow_0074617283_airflow_apache_beam_google_cloud_composer_google_cloud_dataflow_python.txt |
Q:
folium geojson multiple layers control
I'm trying to create a map that has multiple layers output from the key value pairs of a geojson, I can create the map and the layers but the layer filter doesn't work.
data = {"type": "FeatureCollection", "name": "OVE", "crs": {"type": "name", "properties": {"name": "urn:ogc... | folium geojson multiple layers control | I'm trying to create a map that has multiple layers output from the key value pairs of a geojson, I can create the map and the layers but the layer filter doesn't work.
data = {"type": "FeatureCollection", "name": "OVE", "crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:OGC:1.3:CRS84"}}, "features": [{"ty... | [
"I solved it adding one more conditional\nfor replace, lower in zip(l_replace, list_category_lower): \n globals()['%s' % replace] = folium.FeatureGroup(lower)\n variable = globals()['%s' % replace]\n #temp = variable.layer_name\n for feature in data_geo.data['features']:\n\n category = feature... | [
1
] | [] | [] | [
"folium",
"layer",
"loops",
"maps",
"python"
] | stackoverflow_0074616800_folium_layer_loops_maps_python.txt |
Q:
Python: How to force overwriting of files when using setup.py install (distutil)
I am using distutil to install my python code using
python setup.py install
I run into problems when I want to install an older branch of my code over a new one:
setup.py install won't overwrite older files. A work around is touching ... | Python: How to force overwriting of files when using setup.py install (distutil) | I am using distutil to install my python code using
python setup.py install
I run into problems when I want to install an older branch of my code over a new one:
setup.py install won't overwrite older files. A work around is touching (touch <filename>) all files so they are forced to be newer than those installed, but ... | [
"The Python developers had the same idea, they just put the option after the command:\npython setup.py install --force\n\nThe distutils documentation doesn't mention the --force option specifically, but you can find it by using the --help option:\npython setup.py --help install\n\n",
"Go to the setup.py directory... | [
53,
4,
0
] | [] | [] | [
"distutils",
"installation",
"overwrite",
"python"
] | stackoverflow_0019133831_distutils_installation_overwrite_python.txt |
Q:
Python Scatter plot with matrix input. Having trouble getting number of columns showing on x axis, then a dot for each value in each column
I'm making a bar chart and a scatter plot. The bar chart takes a vector as an input. I plotted the values on the x-axis, and the amount of times they repeat on the y-axis. Thi... | Python Scatter plot with matrix input. Having trouble getting number of columns showing on x axis, then a dot for each value in each column | I'm making a bar chart and a scatter plot. The bar chart takes a vector as an input. I plotted the values on the x-axis, and the amount of times they repeat on the y-axis. This is did by converting the vector to a list and using .count(). That worked great and was relatively straightforward.
As for the scatterplot, the... | [
"import numpy as np # Import NumPy\nimport matplotlib.pyplot as plt # Import the matplotlib.pyplot module\n\nvector = np.array([[-3,7,12,4,0o2,7,-3],\n [7,7,12,4,0o2,4,12],\n [12,-3,4,10,12,4,-3],\n [10,12,4,0o3,7,10,12]])\n\nrows, columns = vector.shape\nplt.ti... | [
1
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0074617268_matplotlib_numpy_python.txt |
Q:
How do i read the values of a returned pointer from ctypes?
I am currently struggling with ctypes. I am able to convert a python list to a float array and give it to the C-function. But i can't figure out how to return this array from the C-function back to a python list...
Python-Code
class Point(ctypes.Structure... | How do i read the values of a returned pointer from ctypes? | I am currently struggling with ctypes. I am able to convert a python list to a float array and give it to the C-function. But i can't figure out how to return this array from the C-function back to a python list...
Python-Code
class Point(ctypes.Structure):
_fields_= [("a", ctypes.c_float * 4),
("aa"... | [
"Slicing a ctypes pointer will generate a Python list of the contents. Since a pointer has no knowledge of how many items it points to, you'll need to know the size, usually through another parameter:\n>>> import ctypes as ct\n>>> f = (ct.c_float * 4)(1,2,3,4)\n>>> f\n<__main__.c_float_Array_4 object at 0x00000216... | [
0
] | [] | [] | [
"arrays",
"c",
"ctypes",
"pointers",
"python"
] | stackoverflow_0074615515_arrays_c_ctypes_pointers_python.txt |
Q:
Python selenium loop scrap with xpath
try:
for i in range(n):
company=driver.find_element(By.XPATH,'//*[@id="main-content"]/section[2]/ul/li['+str(i)+']/div/div[2]/h4')
companyname.append(company)
except IndexError:
print("no")
hi, xpath doesn't work when scrapping python selenium loop
or i am... | Python selenium loop scrap with xpath | try:
for i in range(n):
company=driver.find_element(By.XPATH,'//*[@id="main-content"]/section[2]/ul/li['+str(i)+']/div/div[2]/h4')
companyname.append(company)
except IndexError:
print("no")
hi, xpath doesn't work when scrapping python selenium loop
or i am doing it wrong
| [
"Try to find this element using driver.find_element(By.CSS_SELECTOR \"CSS_SELECTOR\")and simply copy selector of element in page inspection section\n"
] | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074617900_python_selenium.txt |
Q:
Showing an image from console in Python
What is the easiest way to show a .jpg or .gif image from Python console?
I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows?
A:
... | Showing an image from console in Python | What is the easiest way to show a .jpg or .gif image from Python console?
I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows?
| [
"Using the awesome Pillow library:\n>>> from PIL import Image \n>>> img = Image.open('test.png')\n>>> img.show() \n\nThis will open the image in your default image viewer.\n",
"In a new window using Pillow/PIL\nInstall Pillow (or PIL),... | [
77,
12,
10,
8,
7,
6,
6,
5,
3,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"image",
"python"
] | stackoverflow_0001413540_image_python.txt |
Q:
PyQt6: DLL load failed while importing QtGui: The specified procedure could not be found
Windows 10 PyCharm Python 3.9.0
I installed PyQt6 and then pyqt6-tools in PyCharm throw the File->Settings.
Now when i run my program i am getting the following error in the terminal
from PyQt6.QtWidgets import QApplication, Q... | PyQt6: DLL load failed while importing QtGui: The specified procedure could not be found | Windows 10 PyCharm Python 3.9.0
I installed PyQt6 and then pyqt6-tools in PyCharm throw the File->Settings.
Now when i run my program i am getting the following error in the terminal
from PyQt6.QtWidgets import QApplication, QWidget
PyQt6: DLL load failed while importing QtGui: The specified procedure could not be foun... | [
"The following command helped me solve this problem:\npip install --upgrade PyQt6\n\n"
] | [
0
] | [] | [] | [
"import",
"pyqt",
"pyqt6",
"python"
] | stackoverflow_0074512247_import_pyqt_pyqt6_python.txt |
Q:
Best way to find a mismatched value that can exist in different locations in a nested dictionary
So I have a dictionary that looks something like the following:
{
"tigj09j32f0j2": {
"car": {
"lead": {
"version": "1.1"
}
},
"bike": {
"l... | Best way to find a mismatched value that can exist in different locations in a nested dictionary | So I have a dictionary that looks something like the following:
{
"tigj09j32f0j2": {
"car": {
"lead": {
"version": "1.1"
}
},
"bike": {
"lead": {
"version": "2.2"
}
},
"jet_ski": {
"le... | [
"Well, your solution is not bad. There are a few things I would suggest to improve.\nIterate over sub-dictionaries directly\nYou don't seem to use the keys (object_id) at all, so you might as well iterate via dict.values.\nNo need for the issue variable\nYou can just return your flag once an \"issue\" is found and ... | [
2,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074619303_dictionary_python.txt |
Q:
Reference parameter in figure caption with Quarto
Is there a way to reference a parameter in a Quarto figure or table caption? In the example below, I am able to reference my input parameter txt in a regular text block, but not in a figure caption. In the figure caption, only the raw text is displayed:
---
title: ... | Reference parameter in figure caption with Quarto | Is there a way to reference a parameter in a Quarto figure or table caption? In the example below, I am able to reference my input parameter txt in a regular text block, but not in a figure caption. In the figure caption, only the raw text is displayed:
---
title: "example"
format: html
params:
txt: "example"
---
#... | [
"Try with !expr\n ```{r}\n #| label: fig-example\n #| fig-cap: !expr params$txt\n plot(1:10, 1:10)\n ```\n\n-output\n\n\nIf we need to add some text, either paste or use glue\n#| fig-cap: !expr glue::glue(\"This should be {params$txt}\")\n\n"
] | [
3
] | [] | [] | [
"python",
"quarto",
"r"
] | stackoverflow_0074619283_python_quarto_r.txt |
Q:
Django project on AWS not updating code after git pull
I am deploying a Django project on AWS. I am running Postgres, Redis, Nginx as well as my project on Docker there.
Everything is working fine, but when I change something on my local machine, push changes to git and then pull them on the AWS instance, the code... | Django project on AWS not updating code after git pull | I am deploying a Django project on AWS. I am running Postgres, Redis, Nginx as well as my project on Docker there.
Everything is working fine, but when I change something on my local machine, push changes to git and then pull them on the AWS instance, the code is changing, files are updated but they are not showing on ... | [
"After updating the code on the EC2 instance, you need to build a new web docker image from that new code. If you are just restarting things then docker-compose is going to continue to pick up the last docker image you built.\nYou need to run the following sequence of commands (on the EC2 instance):\ndocker-compose... | [
0,
0
] | [] | [] | [
"amazon_web_services",
"django",
"nginx",
"python",
"redis"
] | stackoverflow_0074619051_amazon_web_services_django_nginx_python_redis.txt |
Q:
How to fix streched colorbar with Matplotlib's TwtoSlopeNorm
I have a function whose image goes from 0 to infinity, for example $f(x,y)=x^2 + y^2$. I would like to use a diverging colormap to highlight the region where the function equals 1 with a flexible colorbar. The colorbar should go from 0 to whatever vmax, ... | How to fix streched colorbar with Matplotlib's TwtoSlopeNorm | I have a function whose image goes from 0 to infinity, for example $f(x,y)=x^2 + y^2$. I would like to use a diverging colormap to highlight the region where the function equals 1 with a flexible colorbar. The colorbar should go from 0 to whatever vmax, white ("center") at 1, and the interval between colors should be p... | [
"Full answer is here\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nfrom matplotlib import cm\n\ndelta = 0.01\nx = np.arange(0, 4.001, delta)\ny = np.arange(0.0, 4.001, delta)\nX, Y = np.meshgrid(x, y)\nZ = X**2 + Y**2\n\nfig = plt.figure(figsize=(6,3))\nax = fig.add_subpl... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074613524_matplotlib_python.txt |
Q:
Can someone add and explain NEAT alogrithm to simple game
I can't get the NEAT algo. Need someone to take my simple game made for human and add NEAT to it using NEAT-python library.
Game - neural network must write a number that should be close to the randomly generated number in each round. Closer guess = better ... | Can someone add and explain NEAT alogrithm to simple game | I can't get the NEAT algo. Need someone to take my simple game made for human and add NEAT to it using NEAT-python library.
Game - neural network must write a number that should be close to the randomly generated number in each round. Closer guess = better score and higher fitness. If you select randomly generated numb... | [
"I am also just starting my deep-in NL and interested in learning.\nFirst:\nWould recommend first to get in details with 2 good examples that are well implemented and explained:\n\nFlappy Bird 2. Google Dinosaur.\nBoth have game code + NEAT implementation tied together.\nGoogle search will give plenty of examples.\... | [
0
] | [] | [] | [
"neat",
"python"
] | stackoverflow_0070245102_neat_python.txt |
Q:
IDA - execute commands in WinDbg console from python script
I have a python script to run in IDA that generates commands for WinDbg. I also open the memory dump (via the windmp64.dll loader), where the WinDbg console is already available:
I want to execute commands in WinDbg console from python script. If I'm rig... | IDA - execute commands in WinDbg console from python script | I have a python script to run in IDA that generates commands for WinDbg. I also open the memory dump (via the windmp64.dll loader), where the WinDbg console is already available:
I want to execute commands in WinDbg console from python script. If I'm right, I need something like ida_expr.exec_idc_script() but for WinD... | [
"ida_dbg.send_dbg_command() is exactly what I needed.\n"
] | [
0
] | [] | [] | [
"console",
"ida",
"python",
"scripting",
"windbg"
] | stackoverflow_0074586201_console_ida_python_scripting_windbg.txt |
Q:
how to add pagination in Django?
I want to apply pagination on my data I tried to watch lots of videos and read lots of articles but still can't solve my problem. This is my Views.
def car(request):
all_products = None
all_category = category.get_all_category()
categoryid = request.GET.get('category')... | how to add pagination in Django? | I want to apply pagination on my data I tried to watch lots of videos and read lots of articles but still can't solve my problem. This is my Views.
def car(request):
all_products = None
all_category = category.get_all_category()
categoryid = request.GET.get('category')
if categoryid:
all_produc... | [
"My problem is almost solve there is one issue. I can't get the next, previous and last option in pagination but soon I'll figure it out.\nthis is my views.py file coding\ndef car(request):\n all_products = None \n all_category = category.get_all_category()\n categoryid = request.GET.get('category')\n i... | [
0,
0
] | [] | [] | [
"django",
"pagination",
"python"
] | stackoverflow_0074615456_django_pagination_python.txt |
Q:
Can I add string to zipped lists?
I am 4 classes into my first programming class and I am stumped. I am wondering if I am able to add strings to three zipped lists?
For instance, I need to add the following format:
'+' department_name, (department_number, product_variable)
where department_name, department_number,... | Can I add string to zipped lists? | I am 4 classes into my first programming class and I am stumped. I am wondering if I am able to add strings to three zipped lists?
For instance, I need to add the following format:
'+' department_name, (department_number, product_variable)
where department_name, department_number, product_variable are the separate list... | [
"You may need string formatting.\ndepartment_names = [\"n1\", \"n2\", \"n3\", \"n4\"]\ndepartment_numbers = [1, 2, 3, 4]\nproduct_variables = [\"p1\", \"p2\", \"p3\", \"p4\"]\n\nfor department_name, department_number, product_variable in zip(department_names, department_numbers, product_variables):\n print(f\"'+... | [
0,
0
] | [] | [] | [
"python",
"string",
"zip"
] | stackoverflow_0073012213_python_string_zip.txt |
Q:
Counting elements inside an array/matrix
I am struggling with what is hopefully a simple problem. Haven't been able to find a clear cut answer online.
The program given, asks for a user input (n) and then produces an n-sized square matrix. The matrix will only be made of 0s and 1s. I am attempting to count the arr... | Counting elements inside an array/matrix | I am struggling with what is hopefully a simple problem. Haven't been able to find a clear cut answer online.
The program given, asks for a user input (n) and then produces an n-sized square matrix. The matrix will only be made of 0s and 1s. I am attempting to count the arrays (I have called this x) that contain a numb... | [
"You need to count all the lists that contain at least once the number one. To do that you can't use any other module.\ndef count_none_zero_items(matrix):\n count = 0\n for row in matrix:\n if 1 in row:\n count += 1\n return count\n\n\nx = [[0, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0,... | [
8,
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0074619524_arrays_python.txt |
Q:
Recursive function call fails to recurse in AWS Lambda - Python3
Im trying to replace python dictionary key with a different key name recursively for which i am using aws lambda with a api endpoint to trigger.
Suprisingly the recursion part fails for weird reason. The same code works fine in local.
Checked cloudwa... | Recursive function call fails to recurse in AWS Lambda - Python3 | Im trying to replace python dictionary key with a different key name recursively for which i am using aws lambda with a api endpoint to trigger.
Suprisingly the recursion part fails for weird reason. The same code works fine in local.
Checked cloudwatch logs. No error message get displayed there. Let me know if im miss... | [
"Since you're ingesting JSON, you can do the key replacement right in the parse phase for a faster and simpler experience using the object_pairs_hook argument to json.loads.\nimport json\n\nkey_mapping = {\n \"name\": \"noot\",\n \"age\": \"doot\",\n \"relation\": \"root\",\n}\n\n\ndef lambda_handler(event... | [
1
] | [] | [] | [
"amazon_web_services",
"aws_lambda",
"python",
"python_3.x",
"recursion"
] | stackoverflow_0074619555_amazon_web_services_aws_lambda_python_python_3.x_recursion.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.