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 store the output of a function
I have a dataframe as follows:
x = [1,2,3.....10000]
y = [1,2,3.....10000]
I have used SpanSelector tool in matplotlib to make a selection on x data. Based on the selection, I get two values (xmin, xmax)
now I want to plot another plot (different from the one I already have pl... | How to store the output of a function | I have a dataframe as follows:
x = [1,2,3.....10000]
y = [1,2,3.....10000]
I have used SpanSelector tool in matplotlib to make a selection on x data. Based on the selection, I get two values (xmin, xmax)
now I want to plot another plot (different from the one I already have plotted) with x axis set to just (xmin, xmax)... | [
"The problem is that the function you are passing to the SpanSelector is implemented as a callback, where the return value is not used. So you have to find a way for this function to store the values somewhere permanent (beyond the lifetime / scope of the function) without returning it. There are really two ways: E... | [
1
] | [] | [] | [
"function",
"matplotlib",
"python",
"variables"
] | stackoverflow_0074442069_function_matplotlib_python_variables.txt |
Q:
How to run Pyscript in React?
I'm trying to use PyScript in NextJS, but I'm seeing several errors. I have no clue how to make a React component of PyScript. Has anyone successfully used PyScript in ReactJS? Thanks,
const Home: NextPage = () => {
return (
<div>
<Head>
<link rel="stylesheet" href... | How to run Pyscript in React? | I'm trying to use PyScript in NextJS, but I'm seeing several errors. I have no clue how to make a React component of PyScript. Has anyone successfully used PyScript in ReactJS? Thanks,
const Home: NextPage = () => {
return (
<div>
<Head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscri... | [
"you can set python script into dangerouslySetInnerHTML \n<div\n dangerouslySetInnerHTML={{\n __html: `<py-script>\n from datetime import datetime\n now = datetime.now()\n now.strftime(\"%m/%d/%Y, %H:%M:%S\")\n </py-script>`,\n }}\n/>\n\n\nOr\nPyScript-React is not yet available, but you can follow... | [
0
] | [] | [] | [
"pyscript",
"python",
"reactjs"
] | stackoverflow_0073219847_pyscript_python_reactjs.txt |
Q:
How to set the default value for ForeignKey
I have this field
graduation_year = m.ForeignKey('GraduationYear', on_delete=m.SET_NULL, null=False,blank=False)
and GraduationYear class is.
class GraduationYear(BaseModel):
label = m.CharField(max_length=255)
year = m.CharField(max_length=255,unique=True)
... | How to set the default value for ForeignKey | I have this field
graduation_year = m.ForeignKey('GraduationYear', on_delete=m.SET_NULL, null=False,blank=False)
and GraduationYear class is.
class GraduationYear(BaseModel):
label = m.CharField(max_length=255)
year = m.CharField(max_length=255,unique=True)
def __str__(self):
return self.label
Now... | [
"If your table is only managed using the ORM, a good approach would be to override the save method on the model to set it if not provided:\nclass GraduationYear(BaseModel):\n label = m.CharField(max_length=255)\n year = m.CharField(max_length=255,unique=True)\n def __str__(self):\n return self.label... | [
1,
0
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0074441915_django_python_sql.txt |
Q:
How to resolve mypy errors for unittests in separate tests direcotry?
Following is my project structure
rolutte
βββ doc
βββ README.rst
βββ src
βΒ Β βββ outcome.py
βΒ Β βββ __pycache__
βββ tests
βΒ Β βββ context.py
βΒ Β βββ __init__.py
βΒ Β βββ __pycache__
βΒ Β βββ test_outcome.py
βββ tox.ini
Here are the contents of my... | How to resolve mypy errors for unittests in separate tests direcotry? | Following is my project structure
rolutte
βββ doc
βββ README.rst
βββ src
βΒ Β βββ outcome.py
βΒ Β βββ __pycache__
βββ tests
βΒ Β βββ context.py
βΒ Β βββ __init__.py
βΒ Β βββ __pycache__
βΒ Β βββ test_outcome.py
βββ tox.ini
Here are the contents of my outcome.py, tests/context.py and tests/test_outcome.py
# outcome.py
from ... | [
"I guess you are running project from rolutte folder.\nSo every import has to be made from that root folder. That mean from .src.outcome import smth.\nDot represents root folder, every other dot represents subfolder/file. This means that you can see first . as .\\ and any other as \\ like it is in Windows.\nEDIT:\n... | [
0
] | [] | [] | [
"mypy",
"pytest",
"python",
"python_3.x",
"unit_testing"
] | stackoverflow_0074442431_mypy_pytest_python_python_3.x_unit_testing.txt |
Q:
How to print the model's parameters'shape and print the parameters while loading a .pt file?
Thanks to everyone reading this.
I'm a beginner to pytorch. I now have a .pt file and I wanna print the parameter's shape of this module. As I can see, it's a MLP model and the size of input layer is 168, hidden layer is 3... | How to print the model's parameters'shape and print the parameters while loading a .pt file? | Thanks to everyone reading this.
I'm a beginner to pytorch. I now have a .pt file and I wanna print the parameter's shape of this module. As I can see, it's a MLP model and the size of input layer is 168, hidden layer is 32 and output layer is 12.
I tried torch.load() but it returned a dict and I don't know how to deal... | [
"The state dictionary of does not contain any information about the structure of forward logic of its corresponding nn.Module. Without prior knowledge about it's content, you can't get which key of the dict contains the first layer of the module... it's possibly the first one but this method is rather limited if yo... | [
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074442412_python_pytorch.txt |
Q:
How do I find the intersection of more than two polynomial curves?
I have four polynomial (degree 2) functions and I need to find the intersection of these functions. but I do not know is any way to find all intersections in one step. my suggestion is to equalize two functions and find their roots using numpy.root... | How do I find the intersection of more than two polynomial curves? | I have four polynomial (degree 2) functions and I need to find the intersection of these functions. but I do not know is any way to find all intersections in one step. my suggestion is to equalize two functions and find their roots using numpy.roots. but I am not sure if is it true or not. what should I do to find the ... | [
"If a single point exists at which all four curves have the same value, then it should be possible to find the intersections of any one of the curves will each of the other three, and of the resulting intersection, you'd pick the one that's common among them all. I can't think of a \"one-step\" way to do it besides... | [
2,
0,
0
] | [] | [] | [
"math",
"polynomials",
"python"
] | stackoverflow_0074437466_math_polynomials_python.txt |
Q:
filter columns where index value is 0
In a given dataframe:
I would like to filter those columns where values are 0 for index std.
A:
Use DataFrame.loc in boolean indexing - first select index std, compare and select all rows by : with filtered mask:
df1 = df.loc[:, df.loc['std'].eq(0)]
| filter columns where index value is 0 | In a given dataframe:
I would like to filter those columns where values are 0 for index std.
| [
"Use DataFrame.loc in boolean indexing - first select index std, compare and select all rows by : with filtered mask:\ndf1 = df.loc[:, df.loc['std'].eq(0)]\n\n"
] | [
2
] | [
"You can filter the std column for values that are equal to zero.\nThis could work: df = num_df.loc[num_df['std'] == 0]\n"
] | [
-1
] | [
"pandas",
"python"
] | stackoverflow_0074442708_pandas_python.txt |
Q:
Python multiprocessing: calling methods and passing objects in asynchronous calls
I am trying to accomplish two things with apply_async (https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.AsyncResult) call:
(i) Call a class method
(ii) Pass an object as param
I have the following baseline ... | Python multiprocessing: calling methods and passing objects in asynchronous calls | I am trying to accomplish two things with apply_async (https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.AsyncResult) call:
(i) Call a class method
(ii) Pass an object as param
I have the following baseline code so far:
import multiprocessing as mp
class myClass():
def __init__(self, id):
... | [
"The call was not completed without raising an exception. You can check that with the multiprocessing.pool.AsyncResult.successful method:\nimport multiprocessing as mp\n\n\nclass myClass():\n def __init__(self, id):\n self.id = id\n self.val = 1.0\n self.pool = None\n\n def callback(self,... | [
3
] | [] | [] | [
"asynchronous",
"multiprocessing",
"object",
"python",
"python_3.x"
] | stackoverflow_0074442264_asynchronous_multiprocessing_object_python_python_3.x.txt |
Q:
Seeking and deleting elements in lists of a parsed file and saving result to another file
I have a large .txt file that is a result of a C-file being parsed containing various blocks of data, but about 90% of them are useless to me. I'm trying to get rid of them and then save the result to another file, but have h... | Seeking and deleting elements in lists of a parsed file and saving result to another file | I have a large .txt file that is a result of a C-file being parsed containing various blocks of data, but about 90% of them are useless to me. I'm trying to get rid of them and then save the result to another file, but have hard time doing so. At first I tried to delete all useless information in unparsed file, but the... | [
"I suggest reading the entire input file into a string, and then doing a regex replacement:\nwith open(current_directory + r\"\\D_Out\\file.txt\", \"r+\") as file:\n with open(current_directory + r\"\\D_Out_Clean\\clean_file.txt\", \"w+\") as output:\n data = file.read()\n data = re.sub(r'type(?:\\... | [
1
] | [] | [] | [
"c",
"parsing",
"python",
"txt"
] | stackoverflow_0074442567_c_parsing_python_txt.txt |
Q:
Flatten JSON in Dataframe Column
I have data in a dataframe as seen below (BEFORE)
I am trying to parse/flatten the JSON in the site_Activity column , but I am having no luck.
I have tried some of the methods below as a proof I have tried to solve this on my own.
I have provided a DESIRED AFTER section to highligh... | Flatten JSON in Dataframe Column | I have data in a dataframe as seen below (BEFORE)
I am trying to parse/flatten the JSON in the site_Activity column , but I am having no luck.
I have tried some of the methods below as a proof I have tried to solve this on my own.
I have provided a DESIRED AFTER section to highlight how I would expect the data to parse... | [
"You can:\n\nuse .apply(json.loads) to transform the json column into a list/dict column;\nuse df.explode to transform the list o dicts into a Series of dicts;\nuse .apply(pd.Series) to 'explode' de Series of dicts into a DataFrame;\nuse pd.concat to 'merge' the new columns to the rest of the data.\n\nThen it comes... | [
0,
0
] | [] | [] | [
"dataframe",
"json",
"pandas",
"python"
] | stackoverflow_0072958024_dataframe_json_pandas_python.txt |
Q:
AWS Glue error - Invalid input provided while running python shell program
I have Glue job, a python shell code. When I try to run it I end up getting the below error.
Job Name : xxxxx Job Run Id : yyyyyy failed to execute with exception Internal service error : Invalid input provided
It is not specific to code, e... | AWS Glue error - Invalid input provided while running python shell program | I have Glue job, a python shell code. When I try to run it I end up getting the below error.
Job Name : xxxxx Job Run Id : yyyyyy failed to execute with exception Internal service error : Invalid input provided
It is not specific to code, even if I just put
import boto3
print('loaded')
I am getting the error right aft... | [
"It happend to me but the same job is working on a different account.\nAWS documentation is not really explainative about this error:\n\nThe input provided was not valid.\n\nI doubt this is an Amazon issue as mentionned @Quartermass\n",
"Same issue here in eu-west-2 yesterday, working now. This was only happening... | [
2,
1,
1,
0,
0
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"aws_glue",
"aws_glue_spark",
"python"
] | stackoverflow_0073136808_amazon_s3_amazon_web_services_aws_glue_aws_glue_spark_python.txt |
Q:
Python to compare two csv or excel files and print custom output
I am trying to compare two CSV files and print the differences in Python as a custom text file.
For example:
CSV 1:
Id, Customer, Status, Date
01, ABC, Good, Mar 2023
02, BAC, Good, Feb 2024
03, CBA, Bad, Apr 2022
CSV 2:
Id, Customer, Status, Date
0... | Python to compare two csv or excel files and print custom output | I am trying to compare two CSV files and print the differences in Python as a custom text file.
For example:
CSV 1:
Id, Customer, Status, Date
01, ABC, Good, Mar 2023
02, BAC, Good, Feb 2024
03, CBA, Bad, Apr 2022
CSV 2:
Id, Customer, Status, Date
01, ABC, Bad, Mar 2023
02, BAC, Good, Feb 2024
03, CBA, Good, Apr 2024
... | [
"I take it from data frames you are using pandas?\nPandas text export is easy enough as per the link to https://stackoverflow.com/a/31247247/16367225 posted in the comment to your question.\nGet whatever result you want in a one-row-per-one-df format (lookup pandas merge if you are unclear on how joins between fram... | [
0,
0
] | [] | [] | [
"automation",
"csv",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074440680_automation_csv_dataframe_pandas_python.txt |
Q:
Parsing a string with time zone given as a string
I am comparing two timestamps parsing. One is:
datetime.datetime.strptime("2022-10-20 13:13:13 UTC", "%Y-%m-%d %H:%M:%S %Z")
which returns datetime.datetime(2022, 10, 20, 13, 13, 13).
Note that it neither fail (i.e. it parses the UTC part) nor add a time zone to t... | Parsing a string with time zone given as a string | I am comparing two timestamps parsing. One is:
datetime.datetime.strptime("2022-10-20 13:13:13 UTC", "%Y-%m-%d %H:%M:%S %Z")
which returns datetime.datetime(2022, 10, 20, 13, 13, 13).
Note that it neither fail (i.e. it parses the UTC part) nor add a time zone to the resulting object.
The second parsing is:
datetime.da... | [
"Using only the standard library, you cannot parse UTC directly, i.e. to get an aware datetime object. %Z directive will simply make the parser ignore it. However, you can replace it with Z (zulu time == UTC), which can be parsed with %z directive:\nfrom datetime import datetime\n\ns = \"2022-10-20 13:13:13 UTC\"\n... | [
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0074434437_datetime_python.txt |
Q:
The notion of block in Python
The documentation states:
A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.
This seems to imply, contrary to what I had thought, that an... | The notion of block in Python | The documentation states:
A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.
This seems to imply, contrary to what I had thought, that an indented piece of code, such as th... | [
"\nThis seems to imply, contrary to what I had thought, that an indented piece of code, such as the body of an if-statement or a for-loop is not a block.\n\nIndeed, at least in the technical context of the Python language reference, what we would normally call an \"indented block\" is not a \"block\".\nIt's not unu... | [
7
] | [] | [] | [
"python"
] | stackoverflow_0074442230_python.txt |
Q:
Parallel creation of complex dataframes
The below code seems to have some issues. The aim would be to append each result of new_df() to some list, e.g. out.
import pandas as pd
import random
import time
from multiprocessing import Pool
def new_df(rows=10000): # proxy for complex dataframe
temp = pd.DataFrame... | Parallel creation of complex dataframes | The below code seems to have some issues. The aim would be to append each result of new_df() to some list, e.g. out.
import pandas as pd
import random
import time
from multiprocessing import Pool
def new_df(rows=10000): # proxy for complex dataframe
temp = pd.DataFrame({'a': [''.join(chr(random.randint(65,122)) f... | [
"Code reconstructed to utilise the main module idiom:\nimport pandas as pd\nimport random\nimport time\nfrom multiprocessing import Pool\n\ndef new_df(rows=10000):\n temp = pd.DataFrame({'a': [''.join(chr(random.randint(65,122)) for _ in range(200))\n for _ in range(rows)]})\n t... | [
1
] | [] | [] | [
"multiprocessing",
"pandas",
"pool",
"python"
] | stackoverflow_0074442248_multiprocessing_pandas_pool_python.txt |
Q:
SQLAlchemy update if unique key exists
I've got a class:
class Tag(Base, TimestampMixin):
"""Tags"""
__tablename__ = 'tags'
__table_args__ = {'mysql_engine' : 'InnoDB', 'mysql_charset' : 'utf8' }
id = Column(Integer(11), autoincrement = True, primary_key = True)
tag = Column(String(32), nullab... | SQLAlchemy update if unique key exists | I've got a class:
class Tag(Base, TimestampMixin):
"""Tags"""
__tablename__ = 'tags'
__table_args__ = {'mysql_engine' : 'InnoDB', 'mysql_charset' : 'utf8' }
id = Column(Integer(11), autoincrement = True, primary_key = True)
tag = Column(String(32), nullable = False, unique = True)
cnt = Column(... | [
"From version 1.2 SQLAlchemy will support on_duplicate_key_update for MySQL\nThere is also examples of how to use it:\n\nfrom sqlalchemy.dialects.mysql import insert\n\ninsert_stmt = insert(my_table).values(\n id='some_existing_id',\n data='inserted value')\n\non_duplicate_key_stmt = insert_stmt.on_duplicate_... | [
18,
17,
0
] | [] | [] | [
"declarative",
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0009911467_declarative_orm_python_sqlalchemy.txt |
Q:
Why can I install modules, but not import them? - Python
I can install modules, such as the 'requests' module. However, if I try and import them, python tells me it's missing. I can use native modules such as the json module, however.
I tried to install and import third-party modules in python on visualstudio code... | Why can I install modules, but not import them? - Python | I can install modules, such as the 'requests' module. However, if I try and import them, python tells me it's missing. I can use native modules such as the json module, however.
I tried to install and import third-party modules in python on visualstudio code, but I'm stuck trying to figure out how to import them.
| [
"the only reason I see is you are installing the modules in different path and python is not able to refer for import script.\nTry below for installing the module and it may help\nHow to use pip with Visual Studio Code\n",
"Thanks for you responses guys.\nNow that I know what the issue is, thanks to you guys, I l... | [
0,
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0074441730_pip_python.txt |
Q:
Creating sets of specific extracted values from a .txt file (Python)
I have a .txt file that says "NAMES," "POINTS" and "SUMMARY" in capital letters, each followed by lines containing data. Each of these three groups is separated by an empty line:
NAMES
John Cena
Sam Smith
Selena Gomez
POINTS
sixteen
forty
thirty... | Creating sets of specific extracted values from a .txt file (Python) | I have a .txt file that says "NAMES," "POINTS" and "SUMMARY" in capital letters, each followed by lines containing data. Each of these three groups is separated by an empty line:
NAMES
John Cena
Sam Smith
Selena Gomez
POINTS
sixteen
forty
thirty
SUMMARY
eighth place
sixth place
first place
My goal is to create three... | [
"here is my solution:\nnames = set()\npoints = set()\nsummary = set()\n\nnext = 0\n\nfor line in open('handout_example.txt'):\n line = line.strip()\n if not line:\n next += 1\n continue\n if next == 0:\n names.add(line)\n elif next == 1:\n points.add(line)\n elif next == 2:\... | [
0,
0
] | [] | [] | [
"file",
"python",
"set"
] | stackoverflow_0074442756_file_python_set.txt |
Q:
Augmenting data proportionally
I'm facing a classification problem between 2 classes. Currently I augment the dataset using this code:
aug_train_data_gen = ImageDataGenerator(rotation_range=0,
height_shift_range=40,
width_shift_range=40,
... | Augmenting data proportionally | I'm facing a classification problem between 2 classes. Currently I augment the dataset using this code:
aug_train_data_gen = ImageDataGenerator(rotation_range=0,
height_shift_range=40,
width_shift_range=40,
zoom_... | [
"In order to get a balanced batch you can use the attached class.\nOn init you supply a list with multiple datasets. A single dataset per a class. The number of the multiple datasets is equal to the number of classes.\nOn runtime, the __ get_item __() chooses randomly among the classes and inside the class a random... | [
1
] | [] | [] | [
"data_augmentation",
"deep_learning",
"keras",
"machine_learning",
"python"
] | stackoverflow_0074438496_data_augmentation_deep_learning_keras_machine_learning_python.txt |
Q:
How to setup ffmpeg in docker container
I want to compress the video from project directory using ffmpeg in python
the video is saved from cv2.VideoCapture(rtsp_url)
Normally it run without problem in my local machine, but when I dockerize my app it seems docker container can't recognize ffmpeg or I missed somethi... | How to setup ffmpeg in docker container | I want to compress the video from project directory using ffmpeg in python
the video is saved from cv2.VideoCapture(rtsp_url)
Normally it run without problem in my local machine, but when I dockerize my app it seems docker container can't recognize ffmpeg or I missed something.
def compress(name):
with open(name) a... | [
"If the python script mentioned in the beginning of the question is the content of main.py, then there are few issues with the implementation:\n\nYou cannot run docker with the python:3.11.0 as base image.\nYou need to mount the volume with the videos and just process them inside the container.\n\n",
"To debug yo... | [
1,
0
] | [] | [] | [
"docker",
"ffmpeg",
"python",
"ubuntu"
] | stackoverflow_0074442807_docker_ffmpeg_python_ubuntu.txt |
Q:
pandas_profiling main method not working correctly on Windows 10... Constructor works but not method
df.profile_report() fails immediately after installation using
import pandas_profiling
The package is installed properly, because I can generate a report in Jupyter by importing and using just the constructor Profi... | pandas_profiling main method not working correctly on Windows 10... Constructor works but not method | df.profile_report() fails immediately after installation using
import pandas_profiling
The package is installed properly, because I can generate a report in Jupyter by importing and using just the constructor ProfileReport(df). However, the syntax df.profile_report() does not work.
When I run df.profile_report() I get... | [
"The .profile_report() syntax was introduced in pandas_profiling version 2.\nYou can install this version via pip: pip install pandas-profiling.\nEDIT\nThe way to import the package is:\nimport pandas_profiling\nin contrast to your current approach\nfrom pandas_profiling import ProfileReport\n",
"This will work f... | [
0,
0
] | [
"Try this:\nimport pandas_profiling\n\npandas_profiling.describe_df(data_df)\nhtml_str_output = pandas_profiling.ProfileReport(data_df)\n\n"
] | [
-1
] | [
"dataframe",
"pandas",
"pandas_profiling",
"python"
] | stackoverflow_0056816161_dataframe_pandas_pandas_profiling_python.txt |
Q:
How to loop ARIMA through several columns of dataframe
I will start this by saying I am in no way a Python expert but my current project demands that it be programmed in Python, so any help and guidance is appreciated.
I have is a timeseries with daily data and 2000+ items.
I wish to run arima for each of these 20... | How to loop ARIMA through several columns of dataframe | I will start this by saying I am in no way a Python expert but my current project demands that it be programmed in Python, so any help and guidance is appreciated.
I have is a timeseries with daily data and 2000+ items.
I wish to run arima for each of these 2000+ columns. They are not dependent on each other. So basica... | [
"I think you have to do something instead of fitting the model inside the loop.\nLet's know if this code works on your side\n#Test Train Split\ntrain = df.iloc[:, :]\ntest = df.iloc[90:,-1]\n\norder = (1,2,1) # <- plug-in p, d, q here \n\nmodels=[] # ---------> We create a list of different models here\n\nfor co... | [
0
] | [] | [] | [
"arima",
"dataframe",
"python"
] | stackoverflow_0074442920_arima_dataframe_python.txt |
Q:
In dataframe, how to recognize rows with more than 3 consecutive zeros?
I have a dataframe like this.
And I want to recognize the some rows, so that any recognized row is in a block with more than 3 (>=4) consecutive zeros. (marked as cannot_trade)
What I've tried is:
df['cannot_trade'] = (
(df['volume'] == 0) & ... | In dataframe, how to recognize rows with more than 3 consecutive zeros? | I have a dataframe like this.
And I want to recognize the some rows, so that any recognized row is in a block with more than 3 (>=4) consecutive zeros. (marked as cannot_trade)
What I've tried is:
df['cannot_trade'] = (
(df['volume'] == 0) & (df['volume'].shift(1) == 0) & (df['volume'].shift(2) == 0) & (df['volume'].s... | [
"You can use a groupby.transform('count'):\nN = 4\n\nm = df['volume'].ne(0)\n \ndf['cannot_trade'] = (df.groupby(m.cumsum())['volume']\n .transform('count').gt(N)\n & (~m)\n )\n\nExample:\n volume cannot_trade\n0 0 Fals... | [
1,
1,
0
] | [] | [] | [
"data_cleaning",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074442952_data_cleaning_dataframe_pandas_python.txt |
Q:
Get the value of dict in every column in dataframe
Input data:
data = [
['0039384', [{'A': 415}, {'A': 228}, {'B': 360}, {'B': 198}, {'C': 300}, {'C': 165}]],
['0035584', [{'A': 345}, {'A': 117}, {'B': 223}, {'B': 554}, {'C': 443}, {'C': 143}]]
]
df = pd.DataFrame(data=data, columns=['id', 'prices'])
I w... | Get the value of dict in every column in dataframe | Input data:
data = [
['0039384', [{'A': 415}, {'A': 228}, {'B': 360}, {'B': 198}, {'C': 300}, {'C': 165}]],
['0035584', [{'A': 345}, {'A': 117}, {'B': 223}, {'B': 554}, {'C': 443}, {'C': 143}]]
]
df = pd.DataFrame(data=data, columns=['id', 'prices'])
I want to get this resut:
id CurrentPrice_A LastPrice_C C... | [
"It is convenient to iterate over each row of the dataframe, so that you have the algorithm under control, zip the dictionaries two by two (so as to merge current and last) and dynamically assign column names with their values.\nFor convenience, instead of using pd.concat(), you can use lists and temporary dictiona... | [
0,
0
] | [] | [] | [
"dataframe",
"dictionary",
"pandas",
"python"
] | stackoverflow_0074435173_dataframe_dictionary_pandas_python.txt |
Q:
python requests bot detection?
I have been using the requests library to mine this website. I haven't made too many requests to it within 10 minutes. Say 25. All of a sudden, the website gives me a 404 error.
My question is: I read somewhere that getting a URL with a browser is different from getting a URL with so... | python requests bot detection? | I have been using the requests library to mine this website. I haven't made too many requests to it within 10 minutes. Say 25. All of a sudden, the website gives me a 404 error.
My question is: I read somewhere that getting a URL with a browser is different from getting a URL with something like a requests. Because the... | [
"Basically, at least one thing you can do is to send User-Agent header:\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0'}\n\nresponse = requests.get(url, headers=headers)\n\nBesides requests, you can simulate a real user by using selenium - it uses a real browser ... | [
10,
9,
2,
1
] | [] | [] | [
"python",
"python_requests",
"web_scraping"
] | stackoverflow_0022966787_python_python_requests_web_scraping.txt |
Q:
Python: How can I convert string to datetime without knowing the format?
I have a field that comes in as a string and represents a time. Sometimes its in 12 hour, sometimes in 24 hour. Possible values:
8:26
08:26am
13:27
Is there a function that will convert these to time format by being smart about it? Option 1... | Python: How can I convert string to datetime without knowing the format? | I have a field that comes in as a string and represents a time. Sometimes its in 12 hour, sometimes in 24 hour. Possible values:
8:26
08:26am
13:27
Is there a function that will convert these to time format by being smart about it? Option 1 doesn't have am because its in 24 hour format, while option 2 has a 0 before ... | [
"super short answer:\nfrom dateutil import parser\nparser.parse(\"8:36pm\")\n>>>datetime.datetime(2015, 6, 26, 20, 36)\nparser.parse(\"18:36\")\n>>>datetime.datetime(2015, 6, 26, 18, 36)\n\nDateutil should be available for your python installation; no need for something large like pandas\nIf you want to extract the... | [
35,
12,
0
] | [] | [] | [
"python",
"time"
] | stackoverflow_0031066805_python_time.txt |
Q:
Get complement of numpy array
I have the following array and a list of indices
my_array = np.array([ [1,2], [3,4], [5,6], [7,8] ])
indices = np.array([0,2])
I can get the values of the array corresponding to my indices by just doing my_array[indices], which gives me the expected result
array([[1, 2],
[5, 6... | Get complement of numpy array | I have the following array and a list of indices
my_array = np.array([ [1,2], [3,4], [5,6], [7,8] ])
indices = np.array([0,2])
I can get the values of the array corresponding to my indices by just doing my_array[indices], which gives me the expected result
array([[1, 2],
[5, 6]])
Now I want to get the compleme... | [
"You can use numpy.delete. It returns a new array with sub-arrays along an axis deleted.\ncomplement = np.delete(my_array, indices, axis=0)\n\n>>> np.delete(my_array, indices, axis=0)\narray([[3, 4],\n [7, 8]])\n\n"
] | [
1
] | [] | [] | [
"arrays",
"indexing",
"numpy",
"python"
] | stackoverflow_0074443100_arrays_indexing_numpy_python.txt |
Q:
Django template displaying nothing
I have a TextField(text area) form on my page where users can submit comments and have them displayed.
I've left several comments and none of them is showing up. There's just a bunch of empty HTML tags for all the comments i left, cant figure what the issue is
models.py:
class Co... | Django template displaying nothing | I have a TextField(text area) form on my page where users can submit comments and have them displayed.
I've left several comments and none of them is showing up. There's just a bunch of empty HTML tags for all the comments i left, cant figure what the issue is
models.py:
class Comments(models.Model):
comment = mode... | [
"You did wrong here:\n {% for comment in comments %}\n <p>{{ comment.user_commented }}</p><span>{{ comment.date_time }}</span>\n <p>{{ comment.comment }}</p> #You had added comments here instead of comment\n <br>\n {% endfor %}\n\nAccording to for loop, you had added com... | [
2
] | [] | [] | [
"django",
"python",
"textfield"
] | stackoverflow_0074443000_django_python_textfield.txt |
Q:
Converting dictionary of list of objects to pandas dataframe
I have a file that is stored with the following organizational format:
Dictionary
List
Object
Attribute
Specifically looking like this:
dict = {
'0': [TestObject(),TestObject(),TestObject(),TestObject(),TestObject()]
'1': [TestOb... | Converting dictionary of list of objects to pandas dataframe | I have a file that is stored with the following organizational format:
Dictionary
List
Object
Attribute
Specifically looking like this:
dict = {
'0': [TestObject(),TestObject(),TestObject(),TestObject(),TestObject()]
'1': [TestObject(),TestObject(),TestObject(),TestObject(),TestObject()]
'2': [... | [
"You can use a list comprehension:\npd.DataFrame([(k, o, o.id, o.date, o.size)\n for k, l in dic.items() for o in l],\n columns=['key', 'object', 'id', 'date', 'size']\n )\n\nYou first need to fix a few things in your initial code:\nimport random\n\nclass TestObject:\n def __i... | [
1,
1
] | [] | [] | [
"dataframe",
"dictionary",
"pandas",
"python"
] | stackoverflow_0074442793_dataframe_dictionary_pandas_python.txt |
Q:
Pandas API on Spark - Difference between two date columns
I want the difference between two date columns in the number of days.
In pandas dataframe difference in two "datetime64" type columns returns number of days
but in pyspark.pandas dataframe the difference is returned in the "int" type.
import pandas as pd
... | Pandas API on Spark - Difference between two date columns | I want the difference between two date columns in the number of days.
In pandas dataframe difference in two "datetime64" type columns returns number of days
but in pyspark.pandas dataframe the difference is returned in the "int" type.
import pandas as pd
import pyspark.pandas as ps
data = {
"d1": [
"2019... | [
"the diff is a timestamp diff, therefore, the result is in second : 259200 / 3600 / 24 = 3. Just add some math and you'll get your expected result.\nIn pure Spark, you can also use datediff :\nfrom pyspark.sql import functions as F \n\n\ndf.select(F.datediff(df.d2, df.d1).alias('diff')).collect()\n# [Row(diff=32)]\... | [
1,
1
] | [] | [] | [
"pyspark",
"pyspark_pandas",
"python"
] | stackoverflow_0074442460_pyspark_pyspark_pandas_python.txt |
Q:
How to extract specific number of bits from a hexadecimal number for a given text file
This is input file:
input.txt
PS name above bit below bit original 1_info 2_info new
PS_AS_0 PS_00[31] PS_00[00] 0x00000000 0x156A17[00] 0x15... | How to extract specific number of bits from a hexadecimal number for a given text file | This is input file:
input.txt
PS name above bit below bit original 1_info 2_info new
PS_AS_0 PS_00[31] PS_00[00] 0x00000000 0x156A17[00] 0x156A17[31] 0x0003F4a1
PS_RST_D2 PS_03[05] PS_03[00] 0x00000003 ... | [
"For reading input-Data like this I like to use pandas. (update at the end of answer)\nTo get the number of the above and the below bit, you can use indexing of the string like:\nsAboveBit =\"PS_03[05]\"\niAboveBit = int(sAboveBit[-3:-1])\n\nOr much safer:\niAboveBit = int(sAboveBit.split(\"[\")[-1].split(\"]\")[0]... | [
1,
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074441235_python_python_3.x.txt |
Q:
count lines equal with combinations in Python
I have a dataframe like this:
col1
col2
col3
col N
x
y
z
f
y
x
z
f
f
none
none
none
z
y
x
f
I need to count the rows that equal, regardless of their combinations.
It means that, in this case, the output shoud be something like this:
col1
col2
col3
col N
freq
x
... | count lines equal with combinations in Python | I have a dataframe like this:
col1
col2
col3
col N
x
y
z
f
y
x
z
f
f
none
none
none
z
y
x
f
I need to count the rows that equal, regardless of their combinations.
It means that, in this case, the output shoud be something like this:
col1
col2
col3
col N
freq
x
y
z
f
3
f
none
none
none
1
... | [
"You can aggregate the columns as a unique object depending on the exact logic (a frozenset, a sorted tuple, etc.), then count the values of perform a groupby:\nI would use:\nout = df.agg(frozenset, axis=1).value_counts()\n\n# or, if NaN should be ignored\nout = df.agg(lambda x: frozenset(x.dropna()), axis=1).value... | [
2,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074442980_dataframe_pandas_python.txt |
Q:
Send Post request to an external API using AWS Lambda in python
I want to send a post request to an external API (https://example.com/api/jobs/test) every hour.
The Lambda Function that I used is as follows:
Handler: index.lambda_handler
python: 3.6
index.py
import requests
def lambda_handler(event, context):
u... | Send Post request to an external API using AWS Lambda in python | I want to send a post request to an external API (https://example.com/api/jobs/test) every hour.
The Lambda Function that I used is as follows:
Handler: index.lambda_handler
python: 3.6
index.py
import requests
def lambda_handler(event, context):
url="https://example.com/api/jobs/test"
response = requests.post(url... | [
"Vendored requests are now removed from botocore.\nConsider packaging your Lambda code with requirements.txt using CloudFormation package or SAM CLI packaging functionality.\n\nMy older answer from before vendored requests deprecation:\n You may be able to leverage requests module from the boto library without hav... | [
25,
10,
0
] | [] | [] | [
"aws_lambda",
"http_post",
"python"
] | stackoverflow_0047077829_aws_lambda_http_post_python.txt |
Q:
Input to reshape doesn't match requested shape
I know others have posted similar questions already, but I couldn't find a solution that was appropriate here.
I've written a custom keras layer to average outputs from DistilBert based on a mask. That is, I have dim=[batch_size, n_tokens_out, 768] coming in, mask alo... | Input to reshape doesn't match requested shape | I know others have posted similar questions already, but I couldn't find a solution that was appropriate here.
I've written a custom keras layer to average outputs from DistilBert based on a mask. That is, I have dim=[batch_size, n_tokens_out, 768] coming in, mask along n_tokens_out based on a mask that is dim=[batch_s... | [
"Using tf.reshape before a pooling layer\nI know that my answer kinda late, but I want to share my solution to the problem. The thing is when you try to reshape a fixed size of a vector (tensor) during model training. The vector will change its input size and a fixed reshape like tf.reshape(updated_inputs, (shape =... | [
0
] | [] | [] | [
"distilbert",
"keras",
"python",
"tensorflow"
] | stackoverflow_0063186066_distilbert_keras_python_tensorflow.txt |
Q:
Python requests [Errno 111] Connection refused when running on server, but not on local PC
I have a web scraper script which runs fine on my (Windows) PC, but I'm trying to get it to run from a (Linux) web server. I have a number of other scripts which run fine on the server (connecting to different websites than ... | Python requests [Errno 111] Connection refused when running on server, but not on local PC | I have a web scraper script which runs fine on my (Windows) PC, but I'm trying to get it to run from a (Linux) web server. I have a number of other scripts which run fine on the server (connecting to different websites than this one), but when I run this script, I get a [Errno 111] Connection refused error.
Here is a m... | [
"One possibility is that the web scraper is trying to connect to a website that is blocking connections from the web server's IP address as part of anti-scraping protection.\nIn that case, you can try routing your requests through an unblocking proxy server.\nHere's an example of using a proxy in your code:\n\nimpo... | [
1
] | [] | [] | [
"python",
"python_requests",
"urllib3"
] | stackoverflow_0055442205_python_python_requests_urllib3.txt |
Q:
Understanding initializing an empty dictionary
I really do not understand how there was the command (if "entry" in langs_count) is possible when the dictionary was initialized to be empty, so what is inside the dictionary and how did it get there? I'm really confused
`
import pandas as pd
# Import Twitter data as... | Understanding initializing an empty dictionary | I really do not understand how there was the command (if "entry" in langs_count) is possible when the dictionary was initialized to be empty, so what is inside the dictionary and how did it get there? I'm really confused
`
import pandas as pd
# Import Twitter data as DataFrame: df
df = pd.read_csv("tweets.csv")
# Ini... | [
"You can implement the count functionality using groupby.\nimport pandas as pd\n\n# Import Twitter data as DataFrame: df\ndf = pd.read_csv(\"tweets.csv\")\n\n# Populate dictionary with count of occurrences in 'lang' column\nlangs_count = dict(df.groupby(['lang']).size())\n\n# Print the populated dictionary\nprint(l... | [
0
] | [] | [] | [
"dictionary",
"loops",
"python"
] | stackoverflow_0074413452_dictionary_loops_python.txt |
Q:
How to set the data in proper form
I have a data in CSV format like.
Patient_ID,Analyte_line
KYN059AQP,"[['Urea', 3.0, '3', ''], ['Creatinine', 3.0, '3', ''], ['Uric Acid', 3.0, '3', '']]"
KQT767JLU,"[['Total Protein', '', '6', ''], ['Albumin', '', '6', ''], ['Globulin', '', '4', ''], ['Total Bilirubin', '', '... | How to set the data in proper form | I have a data in CSV format like.
Patient_ID,Analyte_line
KYN059AQP,"[['Urea', 3.0, '3', ''], ['Creatinine', 3.0, '3', ''], ['Uric Acid', 3.0, '3', '']]"
KQT767JLU,"[['Total Protein', '', '6', ''], ['Albumin', '', '6', ''], ['Globulin', '', '4', ''], ['Total Bilirubin', '', '6', ''], ['Direct Bilirubin', '', '4', '... | [
"It is recommended that you use a simple list and not lists of string lists, since it could make it difficult to read data in the dataframe, for this example I use StringIO and from pandas it's possible to read as a comma separated file using read_csv.\nfrom io import StringIO\nfrom ast import literal_eval\n\nimpor... | [
0
] | [] | [] | [
"csv",
"data_science",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074441842_csv_data_science_dataframe_pandas_python.txt |
Q:
Why is Sweetify not working on my project?
Sweetify does not work in my project.
I went ahead according to document but it does not work
Does anyone know what the problem is?
this is my view
enter image description here
A:
Try these steps and please check the code that I answered.
pip install --upgrade sweetify... | Why is Sweetify not working on my project? | Sweetify does not work in my project.
I went ahead according to document but it does not work
Does anyone know what the problem is?
this is my view
enter image description here
| [
"Try these steps and please check the code that I answered.\n\npip install --upgrade sweetify\n\nCheck INSTALLED_APPS section in settings.py\nINSTALLED_APPS = [\n...\n'sweetify' ]\n\n\nBe sure you imported sweetify in views.py\nimport sweetify\n\n\n\nIf all are them is okay try this on your function .\n sweetify... | [
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0071298960_django_python.txt |
Q:
How can I sort a zipped list in a certain condition?
I want to sort a zipped list, from how close it is to a certain number.
Zipped Elements contain name, and a price.
one name represents a price.
namesList=["Bob", "Sam", "John"]
pricesList=[10,30,40]
zipped=list(zip(namesList,pricesList))
So it currently is
[('B... | How can I sort a zipped list in a certain condition? | I want to sort a zipped list, from how close it is to a certain number.
Zipped Elements contain name, and a price.
one name represents a price.
namesList=["Bob", "Sam", "John"]
pricesList=[10,30,40]
zipped=list(zip(namesList,pricesList))
So it currently is
[('Bob', 10), ('Sam', 30), ('John', 40)]
and I wish these num... | [
"You are taking the [1] index too early. You should only look at that member when defining the sorting key:\nsorted(zipped, key=lambda x: abs(x[1]-pricePerPerson))\n\n"
] | [
3
] | [] | [] | [
"lambda",
"python",
"sorting"
] | stackoverflow_0074443284_lambda_python_sorting.txt |
Q:
mypy throws error for abstractmethod created with decorator
I have a decorator that creates an abstractmethod from a simple method. It works as I'd expect, however if I run mypy, it tells me this:
mypy_try.py:20: error: Missing return statement [empty-body]
mypy_try.py:20: note: If the method is meant to be abstr... | mypy throws error for abstractmethod created with decorator | I have a decorator that creates an abstractmethod from a simple method. It works as I'd expect, however if I run mypy, it tells me this:
mypy_try.py:20: error: Missing return statement [empty-body]
mypy_try.py:20: note: If the method is meant to be abstract, use @abc.abstractmethod
Found 1 error in 1 file (checked 1 s... | [
"You're doind everything fine, but mypy is not smart enough to figure out that your decorator calls abc.abstractmethod (and this is almost impossible, in fact, even if you've typed the decorator).\nAccording to code in typeshed, abstractmethod is a no-op for type checkers. So mypy just detects the usage of abc.abst... | [
1
] | [] | [] | [
"abc",
"decorator",
"mypy",
"python"
] | stackoverflow_0074430792_abc_decorator_mypy_python.txt |
Q:
Merge two related dataframe to one
How can I create a new DF such that each teacher should contain a list of Students
Teacher df
name married school
0 Pep Guardiola True Manchester High School
1 Jurgen Klopp True Liverpool High School
2 Mikel Arteta False ... | Merge two related dataframe to one | How can I create a new DF such that each teacher should contain a list of Students
Teacher df
name married school
0 Pep Guardiola True Manchester High School
1 Jurgen Klopp True Liverpool High School
2 Mikel Arteta False Arsenal High
3 Zinadine Zidane... | [
"If need new column filled by list of students use Series.map with aggregate list:\ndf1['students'] = df1['name'].map(df2.groupby('teacher')['name'].agg(list))\n\n",
"You can consider using:\ndf.merge(df.groupby('teacher',as_index=False).agg({'name':list}),\n how='left',\n ... | [
1,
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074443285_dataframe_numpy_pandas_python.txt |
Q:
How to unpack data from array of bytes?
I have a data respresented in array of bytes.
Need to unpack the data to python array:
in C# its looks (start=4):
static T BytesToStructure<T>(byte[] bytes, int start)
{
int size = Marshal.SizeOf(typeof(T));
if (bytes.Length < size)
throw ... | How to unpack data from array of bytes? | I have a data respresented in array of bytes.
Need to unpack the data to python array:
in C# its looks (start=4):
static T BytesToStructure<T>(byte[] bytes, int start)
{
int size = Marshal.SizeOf(typeof(T));
if (bytes.Length < size)
throw new Exception("Invalid parameter");
... | [
"you have missed something with struct, you have to specify the number of Hexadecimal you have in your bytearray:\nparsed_data = struct.unpack_from(\"<%de\" % int(len(bytes(decode_buf)) / 2),bytes(decode_buf))\n\nNote1: divided by two because 'e' means floating value on two bytes so you should have len//2 16bits it... | [
0
] | [] | [] | [
"c#",
"python",
"struct"
] | stackoverflow_0074443106_c#_python_struct.txt |
Q:
I can't seem to pass on an object to another class in Python/Tkinter
I have an object which I want to pass to a new frame through a method in another frame class. I found a solution that looked similar to what I was after and tried it, however, the object doesn't get passed. In fact, I got an error message saying ... | I can't seem to pass on an object to another class in Python/Tkinter | I have an object which I want to pass to a new frame through a method in another frame class. I found a solution that looked similar to what I was after and tried it, however, the object doesn't get passed. In fact, I got an error message saying "Value after * must be an iterable, not PackingList", where PackingList is... | [
"I did not understand your question. But here are my corrections to your App class. I hope these corrections can help your understanding of Python and tkinter and debug the rest of your codes.\nIf you need more detailed help, it will be helpful if you can more specific by stating in the comment section what you wan... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074438096_python_tkinter.txt |
Q:
matplotlib | TypeError: unsupported operand type(s) for -: 'Timestamp' and 'float'
How can I draw a FancyBboxPatch on a plot with a date x-axis. The FancyBboxPatch should stretch over a specific time period, similar to a gantt chart.
import matplotlib.pyplot as plt
import pandas as pd
data = [('2019-04-15', 'Star... | matplotlib | TypeError: unsupported operand type(s) for -: 'Timestamp' and 'float' | How can I draw a FancyBboxPatch on a plot with a date x-axis. The FancyBboxPatch should stretch over a specific time period, similar to a gantt chart.
import matplotlib.pyplot as plt
import pandas as pd
data = [('2019-04-15', 'Start'), ('2019-05-01', 'Stop')]
date, labels = zip(*data)
frame = pd.DataFrame({'bla': labe... | [
"You can try using matplotlib.dates.date2num(d) from here to convert your datetime objects to Matplotlib dates like this:\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport matplotlib.patches as mpatches\nimport matplotlib.dates as dates\n\ndata = [('2019-04-15', 'Start'), ('2019-05-01', 'Stop')]\ndate, ... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074443136_matplotlib_python.txt |
Q:
Can't import PIL after installing Pillow with Poetry
I'm trying to install and use Pillow with Python 3.9.2 (managed with pyenv). I'm using Poetry to manage my virtual environments and dependencies, so I ran poetry add pillow, which successfully added Pillow = "^8.2.0" to my pyproject.toml. Per the Pillow docs, I ... | Can't import PIL after installing Pillow with Poetry | I'm trying to install and use Pillow with Python 3.9.2 (managed with pyenv). I'm using Poetry to manage my virtual environments and dependencies, so I ran poetry add pillow, which successfully added Pillow = "^8.2.0" to my pyproject.toml. Per the Pillow docs, I added from PIL import Image in my script, but when I try t... | [
"I couldn't find a way to solve this either (using poetry 1.1.13).\nUltimately, I resorted to a workaround of poetry add pillow && pip install pillow so I could move on with my life. :P\npoetry add pillow gets the dependency in to the TOML, so consumers of the package should be OK.\n",
"capitalizing \"Pillow\" so... | [
1,
0
] | [] | [] | [
"python",
"python_imaging_library",
"python_poetry"
] | stackoverflow_0066996373_python_python_imaging_library_python_poetry.txt |
Q:
get_item dynamodb with if else condition if item has a match
def main():
alias = "jen"
ddb = boto3.client("dynamodb")
get_ddb_item = ddb.get_item(TableName="testtable", Key={"employee": {"S": alias}})
item = get_ddb_item["Item"]
print(item)
if item == alias:
print(f"{alias} is a... | get_item dynamodb with if else condition if item has a match |
def main():
alias = "jen"
ddb = boto3.client("dynamodb")
get_ddb_item = ddb.get_item(TableName="testtable", Key={"employee": {"S": alias}})
item = get_ddb_item["Item"]
print(item)
if item == alias:
print(f"{alias} is an employee")
else:
print(f"{alias} is not an active... | [
"You're getting this because item != 'jen'\nif item['employee']['S'] == alias:\n print(f\"{alias} is an employee\")\n\nelse:\n print(f\"{alias} is not an active employee\")\n\n"
] | [
1
] | [] | [] | [
"amazon_dynamodb",
"python"
] | stackoverflow_0074439816_amazon_dynamodb_python.txt |
Q:
Prevent escaping characters in an xml string
I want to retain double quote during xml writing, I know there is lot of threads but did not get direct answer. double quote is one of example but looking some info for all xml escape character. In brief, do not want to change my raw string during writing xml.
The reaso... | Prevent escaping characters in an xml string | I want to retain double quote during xml writing, I know there is lot of threads but did not get direct answer. double quote is one of example but looking some info for all xml escape character. In brief, do not want to change my raw string during writing xml.
The reason is, do not want to modify raw string
import xml.... | [
"Give a try to \\\", but I don't think it will work since this is a special character.\nAmong the special characters which have to be escaped there are the following characters:\n\ndouble quote (\") is escaped to "\nampersand (&) is escaped to &\nsingle quote (') is escaped to '\nless than (<) is esca... | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074443398_python_python_3.x.txt |
Q:
selenium.common.exceptions.WebDriverException: Message: unknown error: DevToolsActivePort file doesn't exist with chromium browser and Selenium Python
I want to run selenium through chromium. I wrote this code:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()... | selenium.common.exceptions.WebDriverException: Message: unknown error: DevToolsActivePort file doesn't exist with chromium browser and Selenium Python | I want to run selenium through chromium. I wrote this code:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
options.add_argument("--disab... | [
"I solved the problem by reinstalling chromium through apt sudo apt install chromium-browser (before that it was installed through snap). My working code looks like this\noptions = Options()\noptions.add_argument(\"start-maximized\")\noptions.add_argument(\"disable-infobars\")\noptions.add_argument(\"--disable-exte... | [
1,
0,
0,
0
] | [] | [] | [
"chromium",
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver_python"
] | stackoverflow_0070825917_chromium_python_selenium_selenium_chromedriver_selenium_webdriver_python.txt |
Q:
Finding mode of unique array combination in the rows of 2d numpy array
I have a 2d numpy array which I'm trying to return the mode array along axis = 0 (rows). However, I would like to return the most frequent unique row combination. And not the three modes for all three columns which is what scipy stats mode doe... | Finding mode of unique array combination in the rows of 2d numpy array | I have a 2d numpy array which I'm trying to return the mode array along axis = 0 (rows). However, I would like to return the most frequent unique row combination. And not the three modes for all three columns which is what scipy stats mode does. The desired output in the example below would be [9,9,9], because thats t... | [
"you could use the numpy unique funtion and return counts.\nunique_arr1, count = np.unique(arr1,axis=0, return_counts=True)\nunique_arr1[np.argmax(count)]\n\noutput:\narray([9, 9, 9])\n\nnp.unique return the unique array in sorted order, which means it is guranteed that last one is the maximum. you could simply do:... | [
1
] | [] | [] | [
"mode",
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0074443183_mode_numpy_numpy_ndarray_python.txt |
Q:
Randomly select cells in df pandas
From this pandas df
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
samples_indices = df.sample(frac=0.5, replace=False).index
df.loc[samples_indices] = 'X'
will assign 'X' to all columns in randomly selected rows corresponding to 50% of df, like so:
X X X X
1 1 ... | Randomly select cells in df pandas | From this pandas df
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
samples_indices = df.sample(frac=0.5, replace=False).index
df.loc[samples_indices] = 'X'
will assign 'X' to all columns in randomly selected rows corresponding to 50% of df, like so:
X X X X
1 1 1 1
X X X X
1 1 1 1
But... | [
"Use numpy and boolean indexing, for an efficient solution:\nimport numpy as np\n\ndf[np.random.choice([True, False], size=df.shape)] = 'X'\n\n# with a custom probability:\nN = 0.5\ndf[np.random.choice([True, False], size=df.shape, p=[N, 1-N])] = 'X'\n\nExample output:\n 0 1 2 3\n0 X 1 X X\n1 X X 1 X\n... | [
4,
3,
3
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074443396_pandas_python.txt |
Q:
Blur image background using pixellib and keep only one target object
I'm using the code below to blur the background.
change_bg = alter_bg(model_type="pb")
change_bg.load_pascalvoc_model("xception_pascalvoc.pb")
change_bg.blur_bg(filename, low=True, output_image_name=output, detect="car")
It works, but I need to ... | Blur image background using pixellib and keep only one target object | I'm using the code below to blur the background.
change_bg = alter_bg(model_type="pb")
change_bg.load_pascalvoc_model("xception_pascalvoc.pb")
change_bg.blur_bg(filename, low=True, output_image_name=output, detect="car")
It works, but I need to keep only the car close and in front of the photo. If there's cars far in ... | [
"Most likely this is not the best solution, but I was able to blur all the background and keep only the main car in the center of the image by drawing a rectangle over the small cars in the background. By doing that, the algorithm is not able to recognize those cars. Then, when loading the photo again to blur the b... | [
0
] | [] | [] | [
"pixellib",
"python"
] | stackoverflow_0074390059_pixellib_python.txt |
Q:
Having trouble in installing scanpy in python
My python version is 3.8. However, while Im trying to install scanpy using this command
pip install scanpy
in jupyter notebook, I'm getting following error message:
ERROR: matplotlib 3.5.3 has requirement packaging>=20.0, but you'll have packaging 19.2 which is incomp... | Having trouble in installing scanpy in python | My python version is 3.8. However, while Im trying to install scanpy using this command
pip install scanpy
in jupyter notebook, I'm getting following error message:
ERROR: matplotlib 3.5.3 has requirement packaging>=20.0, but you'll have packaging 19.2 which is incompatible.
ERROR: anndata 0.8.0 has requirement packa... | [
"As the error you posted says, it looks like you don't have permissions to install the required package. Try again the same command but in a shell opened as administrator.\nHere's how to do it: https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/jj717276(v=ws.11)\nAs a... | [
0
] | [] | [] | [
"failed_installation",
"python",
"scanpy"
] | stackoverflow_0074443541_failed_installation_python_scanpy.txt |
Q:
Can anyone knows this error in python tensorflow?
This is my code:
image_array.append(image)
label_array.append(i)
image_array = np.array(image_array)
label_array = np.array(label_array, dtype="float")
This is the error:
AttributeError: 'numpy.ndarray' object has no attribute 'append'
A:
numpy.append expec... | Can anyone knows this error in python tensorflow? | This is my code:
image_array.append(image)
label_array.append(i)
image_array = np.array(image_array)
label_array = np.array(label_array, dtype="float")
This is the error:
AttributeError: 'numpy.ndarray' object has no attribute 'append'
| [
"numpy.append expects two input atleast. see this example\nimport numpy as np\n\n#define NumPy array\nx = np.array([1, 4, 4, 6, 7, 12, 13, 16, 19, 22, 23])\n\n#append the value '25' to end of NumPy array\nx = np.append(x, 25)\n\n#view updated array\nx\n\narray([ 1, 4, 4, 6, 7, 12, 13, 16, 19, 22, 23, 25])\n\n",... | [
2,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074443368_numpy_python.txt |
Q:
Gurobi get name of continuous variable
How can I access the attributes of continous gurobi varaibles?
e is initialized via e = mdl.addVars(P, vtype=GRB.BINARY, name = 'e'), and doesn't give me any probelms, like e[1,1].VarName returns "[1,1]", just as expected.
yet the varaible y initialized via
y = mdl.addVars(P,... | Gurobi get name of continuous variable | How can I access the attributes of continous gurobi varaibles?
e is initialized via e = mdl.addVars(P, vtype=GRB.BINARY, name = 'e'), and doesn't give me any probelms, like e[1,1].VarName returns "[1,1]", just as expected.
yet the varaible y initialized via
y = mdl.addVars(P, vtype=GRB.CONTINUOUS, name = 'y') doesn't w... | [
"We can use list comprehension as below:\nhttps://coolnamesfinder.com/biblical-business-names/\n[var for var in model.getVars() if \"gamma\" in var.VarName]\n\nThe above will iterate over all variables. To do it more efficiently such that only the variables are retrieved, we can do it like below:\nnames_to_retriev... | [
0
] | [] | [] | [
"gurobi",
"optimization",
"python"
] | stackoverflow_0074442221_gurobi_optimization_python.txt |
Q:
Randomising each time button is pressed
from tkinter import *
import random
#create root window
root = Tk()
#variables
roll = StringVar(root, name = "roll")
#button script
def clicked():
x = str(random.randint(1,6))
root.setvar(name = "roll", value = x)
#button
btn = Button(root, text = "Roll!", fg = "... | Randomising each time button is pressed | from tkinter import *
import random
#create root window
root = Tk()
#variables
roll = StringVar(root, name = "roll")
#button script
def clicked():
x = str(random.randint(1,6))
root.setvar(name = "roll", value = x)
#button
btn = Button(root, text = "Roll!", fg = "red", bg = "#2596be",
command = ... | [
"The command argument for Button expects a function. When you write clicked() you call the function once, and command gets what your function returns (which is None), so when you click on the button, the command that is executed is None, so nothing happens.\nWhat you want is to pass the function instead, not call i... | [
0
] | [] | [] | [
"python",
"random",
"tkinter"
] | stackoverflow_0074443604_python_random_tkinter.txt |
Q:
Best way to remove (not pop) last/rightmost object occurrence from a stack using collections.deque
I am using the standard collections.deque to write a LIFO stack where each object may occur multiple times, but now I am cornered around the use case for removing the last occurrence of a given object (but not whatev... | Best way to remove (not pop) last/rightmost object occurrence from a stack using collections.deque | I am using the standard collections.deque to write a LIFO stack where each object may occur multiple times, but now I am cornered around the use case for removing the last occurrence of a given object (but not whatever is the rightmost object of the stack!).
While appendleft, extendleft and popleft counterparts exist f... | [
"The only other way I could find would be to start from the last position and decrement until you find the item you're looking for.\ndef for_remove(stack, s):\n # Optionally check if the element is in the stack first\n if s not in stack:\n return\n\n for i in range(len(stack)-1, -1, -1):\n if... | [
0,
0
] | [] | [] | [
"python",
"queue",
"stack"
] | stackoverflow_0074434407_python_queue_stack.txt |
Q:
Size Constrained Integer Partitions of a Given Number
As a smaller part of a programming challenge, I am writing a function in Python that takes two parameters, a given number and a size constraint. The function yields a generator that produces the integer partitions of the given number up to the size constraint. ... | Size Constrained Integer Partitions of a Given Number | As a smaller part of a programming challenge, I am writing a function in Python that takes two parameters, a given number and a size constraint. The function yields a generator that produces the integer partitions of the given number up to the size constraint. I have a working solution that is derived from the rule_asc... | [
"A very late answer, but I believe this is what you are asking for. You need to add the \"colors\" constraint to both inner loops.\ndef generate_subproblems_2(total_nodes, colors):\n\n n = total_nodes\n\n a = [0 for i in range(colors)]\n k = 1\n y = n - 1\n\n while k != 0:\n x = a[k - 1] + 1\n... | [
0
] | [] | [] | [
"combinations",
"generator",
"partitioning",
"python"
] | stackoverflow_0070067858_combinations_generator_partitioning_python.txt |
Q:
Send messages to multiple contacts on WhatsApp without saving the contact
I try to send a message to several contacts in WhatsApp using the following code but for each contact the page loads from the beginning and this is very time consuming.
code :
from selenium.webdriver.support import expected_conditions as EC
... | Send messages to multiple contacts on WhatsApp without saving the contact | I try to send a message to several contacts in WhatsApp using the following code but for each contact the page loads from the beginning and this is very time consuming.
code :
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
from selenium.webdriver.common.by import By
from seleniu... | [
" try\n {\n numbers[sendCounter] = numbers[sendCounter].Trim();\n if (numbers[sendCounter] != \"\")\n {\n\n driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);\n string path = \"https://web.w... | [
0
] | [] | [] | [
"python",
"python_3.x",
"selenium",
"whatsapp"
] | stackoverflow_0071981699_python_python_3.x_selenium_whatsapp.txt |
Q:
Warning: failed to read path from javaldx
An error occurs when converting a file using Libreoffice on ubuntu:
CompletedProcess(args=['soffice', '--headless', '--convert-to', 'txt:Text', '/var/www/Project/temp/e4bac2c2e7c04eb79cfa522967a30dd3.docx', '--outdir', '/var/www/Project/temp/'], returncode=77, stdout=b'', ... | Warning: failed to read path from javaldx | An error occurs when converting a file using Libreoffice on ubuntu:
CompletedProcess(args=['soffice', '--headless', '--convert-to', 'txt:Text', '/var/www/Project/temp/e4bac2c2e7c04eb79cfa522967a30dd3.docx', '--outdir', '/var/www/Project/temp/'], returncode=77, stdout=b'', stderr=b'javaldx failed!\nWarning: failed to re... | [
"Ok found the solution:\nIf you are using libreoffice in headless, with a non root user, trying to convert a docx to a pdf, getting this error:\njavaldx failed!\nWarning: failed to read path from javaldx\n\nYour user doesn't has a home folder set, or the home folder is not writeable. I just switched from calling li... | [
14,
1
] | [] | [] | [
"libreoffice",
"linux",
"python",
"ubuntu"
] | stackoverflow_0060414557_libreoffice_linux_python_ubuntu.txt |
Q:
How can I run chromedriver on repl.it
I basically want to use selenium on repl.it, but don't know how to do that. I tried installing chromedriver into repl.it but I still get this error:
Traceback (most recent call last):
File "/home/runner/dictionaryBot/venv/lib/python3.8/site-packages/selenium/webdriver/commo... | How can I run chromedriver on repl.it | I basically want to use selenium on repl.it, but don't know how to do that. I tried installing chromedriver into repl.it but I still get this error:
Traceback (most recent call last):
File "/home/runner/dictionaryBot/venv/lib/python3.8/site-packages/selenium/webdriver/common/service.py", line 71, in start
self.p... | [
"Try forking this Repl, it has working Selenium that you can use: Advanced Selenium Options\n"
] | [
0
] | [] | [] | [
"python",
"repl.it",
"selenium"
] | stackoverflow_0071883250_python_repl.it_selenium.txt |
Q:
ValueError: unknown url type: ' ' (selenium)
I am going to download pictures from a clothing website for academic research, I use the code below
`
from ast import keyword
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium... | ValueError: unknown url type: ' ' (selenium) | I am going to download pictures from a clothing website for academic research, I use the code below
`
from ast import keyword
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from se... | [
"The url you are trying to download using wget has lots of specific symbols and this can cause problems for the wget. This is an example of the URL you are attempting to download from: https://lp2.hm.com/hmgoepprod?set=source[/2b/bf/2bbf11a29fde773adcdOK],res[y],hmver[1]&call=url[file:/product/main]\nTry to change ... | [
0
] | [] | [] | [
"python",
"selenium",
"valueerror"
] | stackoverflow_0074357406_python_selenium_valueerror.txt |
Q:
Passing expressions to functions
In SQLAlchemy, it appears I'm supposed to pass an expression to filter() in certain cases. When I try to implement something like this myself, I end up with:
>>> def someFunc(value):
... print(value)
>>> someFunc(5 == 5)
True
How do I get the values passed to == from inside t... | Passing expressions to functions | In SQLAlchemy, it appears I'm supposed to pass an expression to filter() in certain cases. When I try to implement something like this myself, I end up with:
>>> def someFunc(value):
... print(value)
>>> someFunc(5 == 5)
True
How do I get the values passed to == from inside the function?
I'm trying to achieve som... | [
"You can achieve your example if you make \"op\" a function:\n>>> def magic(left, op, right):\n... return op(left, right)\n...\n>>> magic(5, (lambda a, b: a == b), 5)\nTrue\n>>> magic(5, (lambda a, b: a == b), 4)\nFalse\n\nThis is more Pythonic than passing a string. It's how functions like sort() work.\nThose ... | [
34,
10,
2,
2,
1,
0,
0
] | [] | [] | [
"arguments",
"function",
"operators",
"python"
] | stackoverflow_0001185199_arguments_function_operators_python.txt |
Q:
Incorrect number of bindings supplied. The current statement uses 2, and there are 3 supplied
I am trying to migrate data from CSV to SQLite database.
The CSV has 3 columns and table has only 2. I tried to pop() out the last element in the list returned by row.split(',') but it is giving a different error
Github l... | Incorrect number of bindings supplied. The current statement uses 2, and there are 3 supplied | I am trying to migrate data from CSV to SQLite database.
The CSV has 3 columns and table has only 2. I tried to pop() out the last element in the list returned by row.split(',') but it is giving a different error
Github link to csv
code:
seen = set();
with open("E:/Forage/Walmart/task4/shipping_data_1.csv",'r') as file... | [
".pop() is not what you want (it returns the popped element - the third column, and then Python is trying to iterate over letters in the string). You need to use slicing instead. If you want to keep the first two columns, do\nrow.split(',')[:2]\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"sqlite"
] | stackoverflow_0074443538_dataframe_pandas_python_sqlite.txt |
Q:
EDIT: numpy operations on astropy time series objects
EDIT: the original title of this question was 'Unable to multiply two python arrays together',and the corresponding question is below. The error arose from the fact that list2 contained data that had implicit units of 'astropy.Time' and each element in the list... | EDIT: numpy operations on astropy time series objects | EDIT: the original title of this question was 'Unable to multiply two python arrays together',and the corresponding question is below. The error arose from the fact that list2 contained data that had implicit units of 'astropy.Time' and each element in the list was a 'time object'. The answer provided is a standard qui... | [
"In the above case where one of the lists contains elements from a lightkurve time-series, the dtype of the elements is astropy.time\nTo convert, the 'to_value()' method needs to be used, where you want to convert your astropy time series to a series of floats and you know the unit of your data is MJD (Modified Jul... | [
1,
0
] | [] | [] | [
"astropy",
"datetime",
"numpy",
"python"
] | stackoverflow_0074440043_astropy_datetime_numpy_python.txt |
Q:
Error 400: invalid_request The out-of-band (OOB) flow has been blocked in order to keep users secure
using this quickstart.ipynb
I'm getting this error
You canβt sign in because "myapp" sent an invalid request. You can try again later, or contact the developer about this issue. Learn more about this error
If you a... | Error 400: invalid_request The out-of-band (OOB) flow has been blocked in order to keep users secure |
using this quickstart.ipynb
I'm getting this error
You canβt sign in because "myapp" sent an invalid request. You can try again later, or contact the developer about this issue. Learn more about this error
If you are a developer of myapp, see error details.
Error 400: invalid_request
Error 400: invalid_request
The o... | [
"The out-of-band (OOB) flow has been blocked.\nUse the below code Replace your 'your client id' and 'your client secret'\nfrom apiclient.discovery import build\nfrom google_auth_oauthlib.flow import Flow\n\n# This is a public OAuth config that you can use to run this guide.\n# However, use different credentials whe... | [
0
] | [] | [] | [
"android",
"android_management_api",
"api",
"google_cloud_platform",
"python"
] | stackoverflow_0073880070_android_android_management_api_api_google_cloud_platform_python.txt |
Q:
How to find the elements inside the QuerySets
If i have two models:
Model_1.objects.all()
Model_2.objects.all()
Model_1 contains all the elements, Model_2 contains a part of these elements.
How can i find the elements contained in Model_1 but not in Model_2?
I tried:
Model_1.objects.exclude(pk=Model_2.objects.or... | How to find the elements inside the QuerySets | If i have two models:
Model_1.objects.all()
Model_2.objects.all()
Model_1 contains all the elements, Model_2 contains a part of these elements.
How can i find the elements contained in Model_1 but not in Model_2?
I tried:
Model_1.objects.exclude(pk=Model_2.objects.order_by('pk'))
It doesn't work.
| [
"Generally, 2 models represent two different entities. But if you want to filter the Model_1 based on some property of Model_2\nUse exclude and filter as per your requirement.\n\nModel_1.objects.exclude(id__in=Model_2.objects.all())\nModel_1.objects.filter(id__in=Model_2.objects.all())\n\n",
"You can use in[Djang... | [
1,
0
] | [] | [] | [
"django",
"mongodb",
"python"
] | stackoverflow_0074443187_django_mongodb_python.txt |
Q:
I can't use open3d open obj
When I use "mesh = o3d.io.read_triangle_mesh("data/1.obj")",
I get that "[Open3D WARNING] Unable to load file data/1.obj with ASSIMP".
There is no problem loading this obj with numpy. Do anyone know what problem is?
A:
Make sure that the path is correct. You will need probably somethi... | I can't use open3d open obj | When I use "mesh = o3d.io.read_triangle_mesh("data/1.obj")",
I get that "[Open3D WARNING] Unable to load file data/1.obj with ASSIMP".
There is no problem loading this obj with numpy. Do anyone know what problem is?
| [
"Make sure that the path is correct. You will need probably something like this:\nmesh = o3d.io.read_triangle_mesh(\"../data/1.obj\")\n\n",
"I found that when the path of the file has some unicode, it doesn't work in windows os. In this case, before transfer it to the read function, change the encoding style. lik... | [
2,
0
] | [] | [] | [
"open3d",
"python"
] | stackoverflow_0066979104_open3d_python.txt |
Q:
Fill nulls with values from another column in PySpark
I have a dataset
col_id col_2 col_3 col_id_b
ABC111 shfhs 34775 null
ABC112 shfhe 34775 DEF345
ABC112 shfhs 34775 GFR563
ABC112 shfgh 34756 TRS572
ABC113 shfdh 34795 null
ABC114 shfhs 347... | Fill nulls with values from another column in PySpark | I have a dataset
col_id col_2 col_3 col_id_b
ABC111 shfhs 34775 null
ABC112 shfhe 34775 DEF345
ABC112 shfhs 34775 GFR563
ABC112 shfgh 34756 TRS572
ABC113 shfdh 34795 null
ABC114 shfhs 34770 null
I am trying to create a new column that is iden... | [
"Just invert the order of the columns:\ndf.select(coalesce(col('col_id_b'), col('col_id')))\n\ncoalesce returns the first column that is not null; so if you specify col_id_b first, it this is not null, you will have col_id_b, otherwise col_id.\n"
] | [
1
] | [] | [] | [
"apache_spark_sql",
"coalesce",
"dataframe",
"pyspark",
"python"
] | stackoverflow_0074444033_apache_spark_sql_coalesce_dataframe_pyspark_python.txt |
Q:
Form Validation passed but Model validation Failed and still the error is showing at form. Can anyone explain?
I have a model Books with one field 'name' and i have set max_length to 10.
class Books(models.Model):
name = models.CharField(max_length=10)
However, in the modelform BookForm i have defined the max_le... | Form Validation passed but Model validation Failed and still the error is showing at form. Can anyone explain? | I have a model Books with one field 'name' and i have set max_length to 10.
class Books(models.Model):
name = models.CharField(max_length=10)
However, in the modelform BookForm i have defined the max_length to 20.
class BookForm(forms.ModelForm):
name = forms.CharField(max_length=20)
class Meta:
fields = ['name... | [
"The model form will automatically define the fields based on your Model and its constraints. Since you have defined a name field with max_length validation in Model, you don't require to give it in the form.\nclass BookForm(forms.ModelForm):\n class Meta:\n fields = ['name']\n model = Books\n\n"
] | [
3
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0074443485_django_django_forms_django_models_python.txt |
Q:
Loading csv.gz from url to bigquery
I am trying to load all the csv.gz files from this url to google bigquery. What is the best way to do this?
I tried using pyspark to read the csv.gz files (as I need to perform some data cleaning on these files) but I realized that pyspark doesn't support directly reading files ... | Loading csv.gz from url to bigquery | I am trying to load all the csv.gz files from this url to google bigquery. What is the best way to do this?
I tried using pyspark to read the csv.gz files (as I need to perform some data cleaning on these files) but I realized that pyspark doesn't support directly reading files from url. Would it make sense to load the... | [
"As @Samuel mentioned, you can use the curl command to download the files from the URL and then copy the files to GCS bucket.\nIf you have heavy transformations to be done on the data I would recommend using Cloud Dataflow otherwise you can go for Cloud Dataprep workflow and finally export your clean data to BigQue... | [
1
] | [] | [] | [
"google_bigquery",
"gzip",
"python"
] | stackoverflow_0074411643_google_bigquery_gzip_python.txt |
Q:
Computed/Reactive column in Pandas?
I would like to emulate an Excel formula in Pandas I've tried this:
df = pd.DataFrame({'a': [3, 2, 1, 0], 'b': [5, 3, 2, 1]})
df['c'] = lambda x : df.a + df.b + 1 # Displays <function <lambda> ..> instead of the result
df['d'] = df.a + df.b + 1 # Static computation
df.a *= 2
df ... | Computed/Reactive column in Pandas? | I would like to emulate an Excel formula in Pandas I've tried this:
df = pd.DataFrame({'a': [3, 2, 1, 0], 'b': [5, 3, 2, 1]})
df['c'] = lambda x : df.a + df.b + 1 # Displays <function <lambda> ..> instead of the result
df['d'] = df.a + df.b + 1 # Static computation
df.a *= 2
df # Result of column c and d not updated :(... | [
"Maybe this code might give you a step in the right direction:\nimport pandas as pd\nc_list =[]\ndf = pd.DataFrame({'a': [3, 2, 1, 0], 'b': [5, 3, 2, 1]})\nc_list2 = list(map(lambda x: x + df.b + 1 , list(df.a)))\n\nfor i in range (0,4):\n c_list.append(pd.DataFrame(c_list2[i])[\"b\"][i])\n\ndf['c'] = c_list\ndf... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0066107844_pandas_python.txt |
Q:
How to zero values in dataframe based on values in another dataframe
Let's say I have two dataframes of the same size, one with values:
d1 = {'values1': [1, 1,2,2], 'values2': [10, 50,200,100]}
df1 = pd.DataFrame(data=d1)
And a dataframe of booleans:
d2 = {'boolean1': [True, False,True,True], 'boolean2': [False, ... | How to zero values in dataframe based on values in another dataframe | Let's say I have two dataframes of the same size, one with values:
d1 = {'values1': [1, 1,2,2], 'values2': [10, 50,200,100]}
df1 = pd.DataFrame(data=d1)
And a dataframe of booleans:
d2 = {'boolean1': [True, False,True,True], 'boolean2': [False, False,False,True]}
df2 = pd.DataFrame(data=d2)
How can I repplace values ... | [
"Because differnt columns names between both DataFrames use DataFrame.mask with converting df2 to numpy array:\nresult = df1.mask(df2.to_numpy(), 0)\nprint (result)\n values1 values2\n0 0 10\n1 1 50\n2 0 200\n3 0 0\n\nIf set columns names in boolean DataFrame -... | [
4
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074444140_pandas_python.txt |
Q:
How to loop(for) through data with conditions in python
Example data:
[
{
"field_name": "mobile",
"field_value": "917845546369",
"type": "primary"
},
{
"field_name": "email",
"field_value": "xyz@gmail.com",
"type": "primary"
},
{
"field_na... | How to loop(for) through data with conditions in python | Example data:
[
{
"field_name": "mobile",
"field_value": "917845546369",
"type": "primary"
},
{
"field_name": "email",
"field_value": "xyz@gmail.com",
"type": "primary"
},
{
"field_name": "name",
"field_value": "XYZ",
"type": "p... | [
"You mean like:\ndata = [\n {\n \"field_name\": \"mobile\",\n \"field_value\": \"917845546369\",\n \"type\": \"primary\"\n },\n {\n \"field_name\": \"email\",\n \"field_value\": \"xyz@gmail.com\",\n \"type\": \"primary\"\n },\n {\n \"field_name\": \"na... | [
0
] | [] | [] | [
"dictionary",
"for_loop",
"if_statement",
"python"
] | stackoverflow_0074444112_dictionary_for_loop_if_statement_python.txt |
Q:
Replacing contents of a .txt file with another .txt file (preserving original filename)
Problem: I have a series of .txt documents in one directory and I want to replace the text with the text from a single .txt document β but I want to preserve the original document filenames.
I created this code (with a lot of r... | Replacing contents of a .txt file with another .txt file (preserving original filename) | Problem: I have a series of .txt documents in one directory and I want to replace the text with the text from a single .txt document β but I want to preserve the original document filenames.
I created this code (with a lot of research):
import os
data = open("source.txt")
for root, dirs, files in os.walk('Folder/'):... | [
"After calling data.read() the whole content of data was read. So calling data.read() again results in an empty string, as you are still at position EOF.\nTo re-read the content of data you need to change the file object's position by using the seek method:\nimport os\n\n\ndata = open(\"source.txt\")\n\nfor root, d... | [
0
] | [] | [] | [
"python",
"text"
] | stackoverflow_0074444086_python_text.txt |
Q:
what's the difference between Modelobject.id and Modelobject_id in django?
want to know the difference between Modelobject.id and Modelobject_id in Python django.
Tried both and they both work the same.
A:
They have the same return value, but have a different process.
Modelobject.id re-fetching/hit the database... | what's the difference between Modelobject.id and Modelobject_id in django? | want to know the difference between Modelobject.id and Modelobject_id in Python django.
Tried both and they both work the same.
| [
"They have the same return value, but have a different process.\n\nModelobject.id re-fetching/hit the database.\nbut Modelobject_id not re-fetching/hit the database.\n\nFor example, if you work with 2 models:\nclass User(models.Model):\n ...\n\nclass Product(models.Model):\n user = models.ForeignKey(User, ...... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074444121_django_python.txt |
Q:
Sklearn evaluate accuracy, precision, recall, f1 show same result
I want to evaluate with accuracy, precision, recall, f1 like this code but it show same result.
df = pd.read_csv(r'test.csv')
X = df.iloc[:,:10]
Y = df.iloc[:,10]
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)
clf = Deci... | Sklearn evaluate accuracy, precision, recall, f1 show same result | I want to evaluate with accuracy, precision, recall, f1 like this code but it show same result.
df = pd.read_csv(r'test.csv')
X = df.iloc[:,:10]
Y = df.iloc[:,10]
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)
clf = DecisionTreeClassifier()
clf = clf.fit(X_train,y_train)
predictions = clf... | [
"According to sklearn's documentation, the behavior is expected when using micro as average and when dealing with a multiclass setting:\n\nNote that if all labels are included, βmicroβ-averaging in a\nmulticlass setting will produce precision, recall and F that are all\nidentical to accuracy.\n\nHere is a nice blog... | [
1
] | [] | [] | [
"evaluation",
"python",
"scikit_learn"
] | stackoverflow_0074440410_evaluation_python_scikit_learn.txt |
Q:
Python 3.5.1 (AMD64) ctypes.ArgumentError: argument 1: : int too long to convert
I'm using Python 3.5.1 (AMD64) on WIN32.
I'm running the code in Windows 10
Any suggestions how to fix the error?
ctypes.ArgumentError: argument 1: <class 'OverflowError'>: int too long to convert
A:
For me two approaches worked to ... | Python 3.5.1 (AMD64) ctypes.ArgumentError: argument 1: : int too long to convert | I'm using Python 3.5.1 (AMD64) on WIN32.
I'm running the code in Windows 10
Any suggestions how to fix the error?
ctypes.ArgumentError: argument 1: <class 'OverflowError'>: int too long to convert
| [
"For me two approaches worked to prevent this:\nLets say we have this function:\nUSB_GetDeviceInterfaceList(QWORD DeviceId, BYTE *pInterfaceList, DWORD *pdwInterfaceAmount)\n\nThe this would work:\nGeneral shared code:\nfrom ctypes import *\nslibc = 'lib\\\\usb.dll'\nlibc = CDLL(slibc)\n\ninterface_list = (c_byte *... | [
0
] | [] | [] | [
"ctypes",
"python",
"windows_10"
] | stackoverflow_0044163105_ctypes_python_windows_10.txt |
Q:
compare two columns in data frame, then produce 1 or 0 if they are equal or not
I wanted to add a column that would tell me if two of my results were the same so I could calculate a % of true/1 or false/0
def same(closests):
if 'ConvenienceStoreClosest' >= 'ConvenienceStoreClosestOSRM':
return 1
el... | compare two columns in data frame, then produce 1 or 0 if they are equal or not | I wanted to add a column that would tell me if two of my results were the same so I could calculate a % of true/1 or false/0
def same(closests):
if 'ConvenienceStoreClosest' >= 'ConvenienceStoreClosestOSRM':
return 1
else:
return 0
This is what I tried
df_all['same'] = df_all['ConvenienceStoreC... | [
"Never use a loop/apply when you can use vectorial code.\nIn your case a simple way would be:\ndf_all['same'] = (df_all['ConvenienceStoreClosest']\n .eq(df['ConvenienceStoreClosestOSRM'])\n .astype(int)\n )\n\n"
] | [
0
] | [] | [] | [
"function",
"if_statement",
"python"
] | stackoverflow_0074444279_function_if_statement_python.txt |
Q:
Draw a circle with a specified tilt angle in three-dimensional space with Python
I want to draw a circle with a specified angle of inclination in 3D space using Python. Similar to the image below:
Image
I can already draw circles in 2D. I modified my program by referring to the link below:
Masking a 3D numpy array... | Draw a circle with a specified tilt angle in three-dimensional space with Python | I want to draw a circle with a specified angle of inclination in 3D space using Python. Similar to the image below:
Image
I can already draw circles in 2D. I modified my program by referring to the link below:
Masking a 3D numpy array with a tilted disc
import numpy as np
import matplotlib.pyplot as plt
r = 5.0
a, b, ... | [
"Let i = (1, 0, 0), j = (0, 1, 0). Those are the direction vectors of the x-axis and y-axis, respectively. Those two vectors form an orthonormal basis of the horizontal plane. Here \"orthonormal\" means the two vectors are orthogonal and both have length 1.\nA circle on the horizontal plane with centre C and radius... | [
0
] | [] | [] | [
"math",
"matplotlib",
"python"
] | stackoverflow_0074444030_math_matplotlib_python.txt |
Q:
'str' object is not callable, but I'm not using "str" at all
I'm using Google Colab for development. My script only has one line of code where I'm supposed to read input from the console:
question = input("Hello")
But it is throwing this error: 'str' object is not callable
I search for similar problems and all of... | 'str' object is not callable, but I'm not using "str" at all | I'm using Google Colab for development. My script only has one line of code where I'm supposed to read input from the console:
question = input("Hello")
But it is throwing this error: 'str' object is not callable
I search for similar problems and all of them where related to code using "str" as a variable or function ... | [
"I tried this in a brand new notebook and it worked. In your notebook it appears that input is not the built-in function to read user input but is actually a string of some sort.\nTo debug this further, try changing the code to just say input. Then it will print what the input identifier is bound to. You ought to s... | [
6,
3,
2,
0
] | [] | [] | [
"google_colaboratory",
"python"
] | stackoverflow_0068240701_google_colaboratory_python.txt |
Q:
date/time: increment the datetime column by one second for each subset of dataframe
creating subset of dataframe and changing the datetime column by 1 day bt not incrementing in the seconds. showing one single value for each one.
following code I had written:
st= Timestamp('2018-06-18 07:59:20')
startDate = st
fo... | date/time: increment the datetime column by one second for each subset of dataframe | creating subset of dataframe and changing the datetime column by 1 day bt not incrementing in the seconds. showing one single value for each one.
following code I had written:
st= Timestamp('2018-06-18 07:59:20')
startDate = st
for labour in range(2):
for trip in range(np.random.randint(5,7)):
# np.random.... | [
"You can use timedelta_range for add incremental timedeltas:\nredf = pd.DataFrame({'a':range(5)})\n\nstartDate = pd.Timestamp('2018-06-18 07:59:20')\n\n\nfor labour in range(2):\n\n for trip in range(np.random.randint(5,7)):\n# np.random.seed(42)\n temp_df = redf[:3].copy()\n temp_df['labor... | [
0
] | [] | [] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0074444039_datetime_pandas_python.txt |
Q:
flask sqlitedb connection error Working outside of application context
>>> from app import db
>>> db.create_all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\kinut\AppData\Local\Programs\Python\Python311\Lib\site-packages\flask_sqlalchemy\extension.py", line 868, in cr... | flask sqlitedb connection error Working outside of application context | >>> from app import db
>>> db.create_all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\kinut\AppData\Local\Programs\Python\Python311\Lib\site-packages\flask_sqlalchemy\extension.py", line 868, in create_all
self._call_for_binds(bind_key, "create_all")
File "C:\Users\k... | [] | [] | [
"from mycode import app\nfrom mycode import db\nwith app.app_context():\n db.create_all()\n\n"
] | [
-1
] | [
"flask",
"flask_sqlalchemy",
"python"
] | stackoverflow_0074444233_flask_flask_sqlalchemy_python.txt |
Q:
Define directory and search for string in each txt file and list files
I want to search for a string in a number of text files in a folder and its subfolders.
Then all files containing this string should be listed. How can this be made?
The string is just something like "Test". So no special chars. I thought of so... | Define directory and search for string in each txt file and list files | I want to search for a string in a number of text files in a folder and its subfolders.
Then all files containing this string should be listed. How can this be made?
The string is just something like "Test". So no special chars. I thought of something like the following in a loop:
open('*', 'r').read().find('Test')
| [
"You can use a simple loop and the glob module:\nfrom glob import glob\n\nfor fname in glob('**/*', recursive=True):\n with open(fname, 'r') as f:\n out = []\n if any('Test' in line for line in f):\n out.append(fname)\n\nprint(out)\n\nIf you just want to print:\nfor fname in glob('**/*',... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074444319_python.txt |
Q:
Apply function on pandas using the index
I have a dataframe like this:
col1=[i for i in range(10)]
col2=[i**2 for i in range(10)]
df=pd.DataFrame(list(zip(col1,col2)),columns=['col1','col2'])
I want to create a new column using apply that adds the numbers in each row and then it adds then index. Something like
df... | Apply function on pandas using the index | I have a dataframe like this:
col1=[i for i in range(10)]
col2=[i**2 for i in range(10)]
df=pd.DataFrame(list(zip(col1,col2)),columns=['col1','col2'])
I want to create a new column using apply that adds the numbers in each row and then it adds then index. Something like
df['col3']=df.apply(lambda x:x['col1']+x['col2']... | [
"Your solution is possible with axis=1 and x.name, but because loops it is slow:\ndf['col3'] = df.apply(lambda x: x['col1'] + x['col2'] + x.name, axis=1)\n\nVectorized solution is add df.index:\ndf['col3'] = df['col1'] + df['col2'] + df.index\n\nPerformance in 10k sample data:\nN = 10000\ndf=pd.DataFrame({'col1':np... | [
1,
0
] | [] | [] | [
"apply",
"pandas",
"python"
] | stackoverflow_0074444509_apply_pandas_python.txt |
Q:
How to validate automl result on the Databricks with a separate dataset
I was performing AutoML feature on the Databricks. But I want to validate the model on the separate dataset.
Since I'm not super aware of the MLFlow, I tried to insert new dataset inside split_test_df with reading it first. But it didn't worke... | How to validate automl result on the Databricks with a separate dataset | I was performing AutoML feature on the Databricks. But I want to validate the model on the separate dataset.
Since I'm not super aware of the MLFlow, I tried to insert new dataset inside split_test_df with reading it first. But it didn't worked out.
The code inside notebook looks the following:
import mlflow
import dat... | [
"It is possible to do that via the notebook and re-assigning of the validation dataset to the dataset on which you want to perform validation.\n"
] | [
0
] | [] | [] | [
"automl",
"databricks",
"mlflow",
"python",
"validation"
] | stackoverflow_0073788620_automl_databricks_mlflow_python_validation.txt |
Q:
I'm getting an error when trying to fit a sklearn model. TypeError: Only size-1 arrays can be converted to Python scalars
from PIL import Image
import glob
import numpy as np
import matplotlib as plt
import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.neural_network import MLPClassifier
fro... | I'm getting an error when trying to fit a sklearn model. TypeError: Only size-1 arrays can be converted to Python scalars | from PIL import Image
import glob
import numpy as np
import matplotlib as plt
import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
X = []
y = []
classes = [r"Anthracnose", r"Leaf Crinkcle", r"Powdery Mildew... | [
"It seems that the problem is the shape of X_train. X before transforming it is of size: (number_of_samples, height, width). The MLPClassifier's fit function expects the following shape: (number_of_samples, number_of_features). Thus, you need to reshape your 2D images into 1D vectors (features) by, for example, con... | [
0
] | [] | [] | [
"machine_learning",
"numpy",
"python",
"scikit_learn"
] | stackoverflow_0074440331_machine_learning_numpy_python_scikit_learn.txt |
Q:
Group values for groupby().mean()
Have a Dataframe:
Column_A
Column_B
1
20
2
25
1
52
2
22
4
67
1
34
3
112
5
55
4
33
5
87
1
108
Looking to create 2 groups from Column_A, and find the average of those groups in Column_B:
So first group might be 1, 2 and 3, second group 4 and 5.
I get the basics behind g... | Group values for groupby().mean() | Have a Dataframe:
Column_A
Column_B
1
20
2
25
1
52
2
22
4
67
1
34
3
112
5
55
4
33
5
87
1
108
Looking to create 2 groups from Column_A, and find the average of those groups in Column_B:
So first group might be 1, 2 and 3, second group 4 and 5.
I get the basics behind groupby()
df.groupby(... | [
"You can combine cut to bin the first column, then groupby.mean:\n(df.groupby(pd.cut(df['Column_A'], [0,3,5], labels=['1-3', '4-5']))\n ['Column_B'].mean()\n )\n\nOutput:\nColumn_A\n1-3 53.285714\n4-5 60.500000\nName: Column_B, dtype: float64\n\n",
"df[df[\"Column_A\"] <= 3].groupby(\"Column_A\")[\"Column... | [
1,
0,
0,
0
] | [] | [] | [
"group",
"pandas",
"python"
] | stackoverflow_0074440927_group_pandas_python.txt |
Q:
creating conditional flag basis the multiple columns
Existing Dataframe :
Id Month Year scheduled completed
A Jan 2021 0 0
A Feb 2021 1 0
A mar 2021 0 0
B ... | creating conditional flag basis the multiple columns | Existing Dataframe :
Id Month Year scheduled completed
A Jan 2021 0 0
A Feb 2021 1 0
A mar 2021 0 0
B June 2021 0 1
B ... | [
"You can use a double groupby to count the consecutive 1s in completed, then to ensure there is at least 1 stretch greater or equal to N=3:\nN = 3\n\n# is the row a zero?\nm = df['completed'].eq(0)\n\n# count the consecutive zeros\n(m.groupby([df['Id'], (~m).cumsum()])\n .sum().ge(N)\n # check if there is at le... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074444681_dataframe_pandas_python.txt |
Q:
how to find and replace multiple words?
i want to find and replace multiple words ? i find this code this is working fine but only one text work, how can i add multiple words..
var observer = new MutationObserver(onMutation);
observer.observe(document, {
childList: true, // report added/removed nodes
subt... | how to find and replace multiple words? | i want to find and replace multiple words ? i find this code this is working fine but only one text work, how can i add multiple words..
var observer = new MutationObserver(onMutation);
observer.observe(document, {
childList: true, // report added/removed nodes
subtree: true, // observe any descendant eleme... | [
"You can try the same code with a dict where the key, values of your dict represent the target and replacement string as such.\nimport re\nvar observer = new MutationObserver(onMutation);\nobserver.observe(document, {\n childList: true, // report added/removed nodes\n subtree: true, // observe any descendan... | [
0
] | [] | [] | [
"css",
"html",
"javascript",
"jquery",
"python"
] | stackoverflow_0074427484_css_html_javascript_jquery_python.txt |
Q:
Get date object for the first/last day of the current year
I need to get date objects for the first and last day in the current year.
Currently I'm using this code which works fine, but I'm curious if there's a nicer way to do it; e.g. without having to specify the month/day manually.
from datetime import date
a =... | Get date object for the first/last day of the current year | I need to get date objects for the first and last day in the current year.
Currently I'm using this code which works fine, but I'm curious if there's a nicer way to do it; e.g. without having to specify the month/day manually.
from datetime import date
a = date(date.today().year, 1, 1)
b = date(date.today().year, 12, 3... | [
"The only real improvement that comes to mind is to give your variables more descriptive names than a and b.\n",
"from datetime import datetime\n\nstarting_day_of_current_year = datetime.now().date().replace(month=1, day=1) \nending_day_of_current_year = datetime.now().date().replace(month=12, day=31)\n\n",
... | [
40,
24,
9,
7,
2,
0
] | [
"one genius way to find out first and last day of year is code below\nthis code works well even for leap years\n first_day=datetime.date(year=i,month=1, day=1)\n first_day_of_next_year=first_day.replace(year=first_day.year+1,month=1, day=1)\n last_day=first_day_of_next_year-jdatetime.timedelta(days=1)\n\n... | [
-1
] | [
"date",
"python"
] | stackoverflow_0005417727_date_python.txt |
Q:
How to use the python package resource in Windows?
I try to import resource but an error is raised that no module named resource. However, I have install this package by pip. How to fix this?enter image description here
Try to import resource.
Hope to know how to fix the error in Windows.
A:
You can execute pip ... | How to use the python package resource in Windows? | I try to import resource but an error is raised that no module named resource. However, I have install this package by pip. How to fix this?enter image description here
Try to import resource.
Hope to know how to fix the error in Windows.
| [
"You can execute pip install resource to see where the package is installed, you will get results similar to below:\nRequirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /opt/homebrew/anaconda3/lib/python3.9/site-packages (from jsonschema->JsonForm>=0.0.2->resource) (0.18.0)\nRequirement ... | [
0
] | [] | [] | [
"python",
"resources",
"windows"
] | stackoverflow_0074444783_python_resources_windows.txt |
Q:
How to get the sum of the same position in a tuple output of a for loop in python?
I wrote a definition to iterate over 200 files and calculate the number of transitions and transversions in a DNA sequence. Now I want to sum up the first column of the output of this for loop together and the second column together... | How to get the sum of the same position in a tuple output of a for loop in python? | I wrote a definition to iterate over 200 files and calculate the number of transitions and transversions in a DNA sequence. Now I want to sum up the first column of the output of this for loop together and the second column together.
this is the output that I get repeated 200 times because I have 200 files, I want to g... | [
"One solution using itertools accumulate, I think it is pretty and clean:\nfrom itertools import accumulate\n\nyour_list = [(0, 1), (1, 0), (1, 0), ....]\n\n*_, sum_ = accumulate(your_list, lambda x,y: (x[0]+y[0],x[1]+y[1]))\nprint(sum_)\n\nLess clean, more python magic and only really relevant for code golf, but ... | [
3,
2,
1,
1,
1
] | [] | [] | [
"output",
"python",
"sum"
] | stackoverflow_0074444606_output_python_sum.txt |
Q:
Stripe, PayPal, integration with django-rest-framework
I want to integrate Stripe, PayPal or Braintree into django project, and I want to use 'django-rest-framework`, now I'm confused about one thing and that is - Should I "touch" my database?
What I mean, I want only to charge once to my customers, it's a fee and... | Stripe, PayPal, integration with django-rest-framework | I want to integrate Stripe, PayPal or Braintree into django project, and I want to use 'django-rest-framework`, now I'm confused about one thing and that is - Should I "touch" my database?
What I mean, I want only to charge once to my customers, it's a fee and nothing more, so should I touch 'db' or not? I'm afraid it ... | [
"(Disclaimer: I'm a Stripe employee, so I'll only talk about Stripe here.)\nStripe makes it easy to be PCI compliant. With a proper integration, you will never have access to your customers' payment information.\nA typical payment flow with Stripe can be divided in two steps:\n\nCollect the customer's payment infor... | [
17,
0
] | [] | [] | [
"django",
"paypal",
"python",
"rest",
"stripe_payments"
] | stackoverflow_0037889607_django_paypal_python_rest_stripe_payments.txt |
Q:
How to Merge two dictionaries in python
I would like to merge two dictionaries this way below:
dict1={
'kl':'ngt',
'schemas':
[
{
'date':'14-12-2022',
'name':'kolo'
}
]
}
dict2={
'kl':'mlk',
'schemas':
... | How to Merge two dictionaries in python | I would like to merge two dictionaries this way below:
dict1={
'kl':'ngt',
'schemas':
[
{
'date':'14-12-2022',
'name':'kolo'
}
]
}
dict2={
'kl':'mlk',
'schemas':
[
{
'da... | [
"maybe the result structure that you want is like this:\nall_dict=[\n{\n 'kl':'ngt',\n 'schemas':\n [\n {\n 'date':'14-12-2022',\n 'name':'kolo'\n }\n ],\n},\n\n {\n\n 'kl':'mlk',\n 'schemas':\n [\n {\n 'date':'... | [
1,
0
] | [] | [] | [
"django",
"merge",
"python"
] | stackoverflow_0074444299_django_merge_python.txt |
Q:
Hex Entity Encoding in SQLmap
I am using SQLmap and want to hex-entitiy-encode the input before SQLmap sends it to the server.
For example, hex-entity-encoding of "abc" should give me abc
I know that I should use a python tamper script which should hex-entity-encode the given input. But I don't know... | Hex Entity Encoding in SQLmap | I am using SQLmap and want to hex-entitiy-encode the input before SQLmap sends it to the server.
For example, hex-entity-encoding of "abc" should give me abc
I know that I should use a python tamper script which should hex-entity-encode the given input. But I don't know how I could hex-entity-encode data... | [
"Apply formatted string literals (also called f-strings for short) e.g. as follows:\na_string = 'abc TrΖ°α»ng An TΓ΄ Nguyα»
n'\n''.join([f'&#x{ord(ch):x};' for ch in a_string])\n# 'abc Trường An Tô Nguyễ&#x... | [
0
] | [] | [] | [
"encoding",
"hex",
"python",
"sqlmap",
"xml"
] | stackoverflow_0074441215_encoding_hex_python_sqlmap_xml.txt |
Q:
How to find non-ascii character in a file that Python as found?
I run this code on a file content:
try:
file_content.encode().decode('ascii')
except UnicodeDecodeError as e:
print(str(e))
And it shows me this error message:
'ascii' codec can't decode byte 0xe2 in position 4568: ordinal not in range(128)
... | How to find non-ascii character in a file that Python as found? | I run this code on a file content:
try:
file_content.encode().decode('ascii')
except UnicodeDecodeError as e:
print(str(e))
And it shows me this error message:
'ascii' codec can't decode byte 0xe2 in position 4568: ordinal not in range(128)
It's not useful at all. First of all, it does not tell me line numbe... | [
"you just need to get ord of character and see which one of them lie outside of ascii range\nsee ascii table for more info\nfile = 'soimefile'\nwith open(file, 'r') as f:\n lines = f.readlines()\n for line_number, line in enuemrate(lines, 1):\n for character_position, character in enumerate(line, 1):\n... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074444304_python.txt |
Q:
Python: how to add '-help' to argparse help command list?
Is there a way to include '-help' command to argparse help list?
I wish to have something like this on output, if i am typing '-help'.
optional arguments:
-h, -help, --help show this help message and exit
Thanks
A:
While this is possible to do... | Python: how to add '-help' to argparse help command list? | Is there a way to include '-help' command to argparse help list?
I wish to have something like this on output, if i am typing '-help'.
optional arguments:
-h, -help, --help show this help message and exit
Thanks
| [
"While this is possible to do, it is not recommended. Single dashes are only meant to be used with single letters. In general, you should follow recommendations as they are there for a reason. \nIf you really want to add it however, you can do it with:\nparser.add_argument(\"-help\", action=\"help\")\n\n",
"As @A... | [
2,
2,
1
] | [] | [] | [
"argparse",
"python",
"python_2.7"
] | stackoverflow_0057058526_argparse_python_python_2.7.txt |
Q:
How to filter and print particular json dictionaries in python
I'm in the process of learning python. I encountered a problem with json that I can't overcome.
I have this dataset from json in python:
{
"Sophos": {
"detected": true,
"result": "phishing site"
},
"Phishtank": {
"de... | How to filter and print particular json dictionaries in python | I'm in the process of learning python. I encountered a problem with json that I can't overcome.
I have this dataset from json in python:
{
"Sophos": {
"detected": true,
"result": "phishing site"
},
"Phishtank": {
"detected": false,
"result": "clean site"
},
"CyberCrim... | [
"You can use dict comprehension to filter the response dictionary.\nNote that in the example you provided, I think you have json data and not the python object. true is not a valid boolean keyword in python, it should've been True instead.\nfiltered = {k: v for k, v in orignal_dict.items() if v.get(\"detected\") ==... | [
3,
2,
1,
1,
1
] | [] | [] | [
"api",
"dictionary",
"json",
"object",
"python"
] | stackoverflow_0074444498_api_dictionary_json_object_python.txt |
Q:
Why Python giving me UnboundLocalError?
My Python program giving me a unbound error but i cant get it why
(Error occurs at connectionstat function)
Here is the code:
from datetime import datetime
from datetime import date
import requests
g = "noinput"
passhash = open("atlaspass.txt", "r")
systracer = "noinput"
var... | Why Python giving me UnboundLocalError? | My Python program giving me a unbound error but i cant get it why
(Error occurs at connectionstat function)
Here is the code:
from datetime import datetime
from datetime import date
import requests
g = "noinput"
passhash = open("atlaspass.txt", "r")
systracer = "noinput"
var_tarih = date.today()
var_zaman = datetime.no... | [
"Change this line from request = request.get(url, timeout = timeout) to\nrequest = requests.get(url, timeout = timeout).\nNote that the library is called requests and not request.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074445035_python.txt |
Q:
Can I set a resolution of below 0.1 on PySimpleGUI slider?
I have the following statement on my code to create a slider:
[sg.Text('SPI Frequency [MHz]: '),sg.Slider((0.50,2.50),1.250,0.750,size=(80,15),orientation='h',key='FREQ_SLIDER',enable_events=True,tick_interval=0.75)]
However, my final resolution is not of... | Can I set a resolution of below 0.1 on PySimpleGUI slider? | I have the following statement on my code to create a slider:
[sg.Text('SPI Frequency [MHz]: '),sg.Slider((0.50,2.50),1.250,0.750,size=(80,15),orientation='h',key='FREQ_SLIDER',enable_events=True,tick_interval=0.75)]
However, my final resolution is not of 0.75 but it is rounded. Instead, I have the following slider:
... | [
"I cannot comment to say so, but there is not enough information to give a specific answer, only general. It depends on whether you are using Tk, Qt, or Wx. You can find the source code for each here: https://github.com/PySimpleGUI/PySimpleGUI, where you can find the Slider types and what class they use in the back... | [
1,
1,
0
] | [] | [] | [
"pysimplegui",
"python"
] | stackoverflow_0074319852_pysimplegui_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.