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:
SQLAlchemy: Any constraint to check one of the two columns is not null?
This may be totally stupid thing to ask but I have such a requirement in my model where atleast either category or parent_category is not null
My model looks like
class BudgetCategories(db.Model):
__tablename__ = 'budget_categories'
uu... | SQLAlchemy: Any constraint to check one of the two columns is not null? | This may be totally stupid thing to ask but I have such a requirement in my model where atleast either category or parent_category is not null
My model looks like
class BudgetCategories(db.Model):
__tablename__ = 'budget_categories'
uuid = Column('uuid', GUID(), default=uuid.uuid4, primary_key=True,
... | [
"I am not 100% sure about the PostgreSQL syntax, but following addition to your BudgetCategories model should do the trick using CheckConstraint:\nclass BudgetCategories(Base):\n __tablename__ = 'budget_categories'\n # ...\n\n # @note: new\n __table_args__ = (\n CheckConstraint('NOT(category ... | [
20,
6,
3,
1,
0
] | [] | [] | [
"flask_sqlalchemy",
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0020943777_flask_sqlalchemy_postgresql_python_sqlalchemy.txt |
Q:
Streaming and caching tabular data with fsspec, parquet and Pyarrow
I’m trying to stream data from parquet files stored in Dropbox (but it could be somewhere else, S3, gdrive, etc…) and reading in Pandas, while caching it. For that I’m trying to use fsspec for Python
Following these instructions that’s what I’m tr... | Streaming and caching tabular data with fsspec, parquet and Pyarrow | I’m trying to stream data from parquet files stored in Dropbox (but it could be somewhere else, S3, gdrive, etc…) and reading in Pandas, while caching it. For that I’m trying to use fsspec for Python
Following these instructions that’s what I’m trying right now:
from fsspec.implementations.arrow import ArrowFSWrapper
f... | [
"The convenience way to open and pass a file-like object using fsspec alone would be\nwith fsspec.open(\n \"blockcache::https://www.dropbox.com/s/…./myfile.parquet?dl=0\",\n blockcache={\"cache_storage\": \"cache_fs\"}\n) as f:\n df = pd.read_parquet(f)\n\nOf course, instantiating your own filesystem insta... | [
3,
1
] | [] | [] | [
"data_stream",
"fsspec",
"parquet",
"pyarrow",
"python"
] | stackoverflow_0074221343_data_stream_fsspec_parquet_pyarrow_python.txt |
Q:
How to drop index column using panda while writing?
df.columns = pd.MultiIndex.from_tuples(
zip(['AA ', 'BB ', '','DD', 'EE',''],df.columns))
I used the above code in my script that's why I have to set index=True
df.to_excel(arg,index=True)
But now I want to drop my index column
What can I Do?
I Tried : df.r... | How to drop index column using panda while writing? | df.columns = pd.MultiIndex.from_tuples(
zip(['AA ', 'BB ', '','DD', 'EE',''],df.columns))
I used the above code in my script that's why I have to set index=True
df.to_excel(arg,index=True)
But now I want to drop my index column
What can I Do?
I Tried : df.reset_index(inplace=True) data.reset_index(drop=True, inp... | [
"To drop the index column, use this:\ndf = df.reset_index(drop=True)\n\n",
"Did you try setting index to 'False' while exporting to excel ?\ndf.to_excel(arg,index=False)\n\n"
] | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074222730_pandas_python.txt |
Q:
Combine 2 for loops in python
In C, I can do
for(i=0, j=0; i < k; i++, j++) {
// do stuff
}
Is there an equivalent of that in Python?
A:
If you mean exactly what you wrote, then not really, because Python does not have C-style loop.
If you actually mean something like "iterate on two collections at the same... | Combine 2 for loops in python | In C, I can do
for(i=0, j=0; i < k; i++, j++) {
// do stuff
}
Is there an equivalent of that in Python?
| [
"If you mean exactly what you wrote, then not really, because Python does not have C-style loop.\nIf you actually mean something like \"iterate on two collections at the same time\" then yes: you compose the two collections into one iterator using zip or zip_longuest:\nfor a, b in zip(x, y):\n ...\n\nThat works ... | [
2
] | [] | [] | [
"c",
"for_loop",
"python"
] | stackoverflow_0074222893_c_for_loop_python.txt |
Q:
How to pass parameters to functions inside of fuctions
There is something in Python that has been bugging me for a long time. I can't figure out how to pass parameters from one function to the functions that are defined inside of that function. I have tried researching this issue, but with no luck. Not even W3Scho... | How to pass parameters to functions inside of fuctions | There is something in Python that has been bugging me for a long time. I can't figure out how to pass parameters from one function to the functions that are defined inside of that function. I have tried researching this issue, but with no luck. Not even W3Schools didn't show a solution.
def func1(arg1):
def func2(a... | [
"You have only missed the argument in the call of func2. The code below highlights your forgetfulness:\ndef func1(arg1):\n\n def func2(arg1):\n print(arg1)\n\n # ---> here you have missed the argument\n func2(arg1)\n\nvar1 = 123\nfunc1(var1)\n\n",
"Can't you use it like this?\ndef func1(arg1):\n ... | [
1,
0
] | [] | [] | [
"function",
"parameters",
"python",
"python_3.x"
] | stackoverflow_0074223024_function_parameters_python_python_3.x.txt |
Q:
Comparing length of words in Python Strings
Given 2 strings on a line divided by a comma, with each string containing various words separated by underscores, reutrn the number of words in the first string that have the same length (in charaters as any one or more words in the second string
In regards to this I hav... | Comparing length of words in Python Strings | Given 2 strings on a line divided by a comma, with each string containing various words separated by underscores, reutrn the number of words in the first string that have the same length (in charaters as any one or more words in the second string
In regards to this I have only been able to get the length of complete fu... | [
"I don't really understand the question without an example and the code, but as far as I understood:\nGiven your example as follows:\nx = \"hello_i_am_here,what_are_you_doing\"\n\nyou can do the following to split the 2 strings that are seperated with commas:\nmy_list = x.split(\",\")\n\nNow\nprint(my_list)\n\nOutp... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074222929_python_python_3.x.txt |
Q:
Django send_mass_email with html content
Im triying to send a mass email with django's "send_mass_email" method, i've read the documentation but the examples only show plain text messages.
How can i be able to send HTML messages with the "send_mass_emal" method? i tried like a regular email but the recived only ht... | Django send_mass_email with html content | Im triying to send a mass email with django's "send_mass_email" method, i've read the documentation but the examples only show plain text messages.
How can i be able to send HTML messages with the "send_mass_emal" method? i tried like a regular email but the recived only html code. Here is my code:
... | [
"It does not look like send_mass_email() supports HTML emails. But there is a way to do it by taking inspiration from the code of Django's send_mail() function:\nconnection = connection or get_connection(\n username=auth_user,\n password=auth_password,\n fail_silently=fail_silently,\n)\nmail = EmailMultiAl... | [
1,
1,
0
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0043372143_django_html_python.txt |
Q:
operation between columns according to the value it contains
I have a Dataframe that look like this:
df_1:
Phase_1 Phase_2 Phase_3
0 8 4 2
1 4 6 3
2 8 8 3
3 10 5 8
...
I'd like to add a column called "Coeff" that compute (Phase_max - Ph... | operation between columns according to the value it contains | I have a Dataframe that look like this:
df_1:
Phase_1 Phase_2 Phase_3
0 8 4 2
1 4 6 3
2 8 8 3
3 10 5 8
...
I'd like to add a column called "Coeff" that compute (Phase_max - Phase_min) / Phase_max
For the first row: Coeff= (Phase_1 - Phase_3)... | [
"here is one way to do it\n# list the columns, you like to use in calculations\ncols=['Phase_1', 'Phase_2', 'Phase_3']\n\n# using max and min across the axis to calculate, for the defined columns\n\ndf['coeff']=(df[cols].max(axis=1).sub(df[cols].min(axis=1))).div(df[cols].max(axis=1))\ndf\n\n\nlittle performance op... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074223008_pandas_python.txt |
Q:
Django debug toolbar: how do I profile a file download?
My Django webapp lets users download text files that are generated on the fly:
response = HttpResponse(my_file_contents)
response['Content-Disposition'] = 'attachment; filename="my file.txt"'
return response
I installed Django Debug Toolbar (0.11.0, since I ... | Django debug toolbar: how do I profile a file download? | My Django webapp lets users download text files that are generated on the fly:
response = HttpResponse(my_file_contents)
response['Content-Disposition'] = 'attachment; filename="my file.txt"'
return response
I installed Django Debug Toolbar (0.11.0, since I cannot get 1.0.1 to work), but when I click to make the downl... | [
"An alternative, temporary solution if you are focused on profiling DB queries is to simply not return the file download response, and instead load a template (any valid Django template in your application should work). DDT still logs all the queries and you can see them on the subsequent page. This works because o... | [
5,
1,
1,
0
] | [] | [] | [
"django",
"django_debug_toolbar",
"python"
] | stackoverflow_0021546972_django_django_debug_toolbar_python.txt |
Q:
How to parse multiple tokens using python Sly Parser?
I have a lexer:
from sly import Lexer
class BasicLexer(Lexer):
tokens = {OBJECT, FUNCTON}
ignore = '.'
OBJECT = r'object\(\"(.*?)\"\)'
FUNCTION = r'function\(\"(.*?)\"\)'
def OBJECT(self, t):
match = re.search(r'object\("(.*?)"\)'... | How to parse multiple tokens using python Sly Parser? | I have a lexer:
from sly import Lexer
class BasicLexer(Lexer):
tokens = {OBJECT, FUNCTON}
ignore = '.'
OBJECT = r'object\(\"(.*?)\"\)'
FUNCTION = r'function\(\"(.*?)\"\)'
def OBJECT(self, t):
match = re.search(r'object\("(.*?)"\)', t.value)
t.value = match.group(1)
return... | [
"As noted above in rici's comments, you probably need to take a step or two back to decompose your object and function tokens into smaller pieces that can be processed. Something like the following may make more sense:\nfrom sly import Lexer\n\nclass BasicLexer(Lexer):\n tokens = {OBJECT, FUNCTION, LPAREN, RPARE... | [
0
] | [] | [] | [
"lexer",
"python",
"python_3.x",
"sly"
] | stackoverflow_0074147900_lexer_python_python_3.x_sly.txt |
Q:
How can I get node's memory with kubernetes-client lib in python
Could not find how can I obtain information about memory consumption on kubernetes node with kubernetes-client library in Python. I know how to obtain this information with kubectl command.
Could you provide me with a piece of code how can I do this ... | How can I get node's memory with kubernetes-client lib in python | Could not find how can I obtain information about memory consumption on kubernetes node with kubernetes-client library in Python. I know how to obtain this information with kubectl command.
Could you provide me with a piece of code how can I do this via the lib?
Thank you.
| [
"Getting started\nkubernetes-client contains pieces of code that you need:\nfrom kubernetes import client, config\n\n\ndef main():\n # Configs can be set in Configuration class directly or using helper\n # utility. If no argument provided, the config will be loaded from\n # default location.\n config.lo... | [
1,
0,
0
] | [] | [] | [
"kubernetes",
"python"
] | stackoverflow_0057866252_kubernetes_python.txt |
Q:
Automation Outlook to open an Hyperlinks
I'm interested in automating Outlook to check/read mails.
I'm using the package win32com with Python to control the app, but I can't find how to open an hyperlink which is in the mail body.
Is there an if or for statement that can open the hyperlink automatically?
Thank you... | Automation Outlook to open an Hyperlinks | I'm interested in automating Outlook to check/read mails.
I'm using the package win32com with Python to control the app, but I can't find how to open an hyperlink which is in the mail body.
Is there an if or for statement that can open the hyperlink automatically?
Thank you in advance for your help!
| [
"I found a way to open the hyperlink with the BeautifulSoup and webbrowser libraries thanks to the HTMLBody property:\nfrom bs4 import BeautifulSoup\nimport webbrowser\n\n html = mail.HTMLBody #html source code of the mail\n soup = BeautifulSoup(html, 'html.parser')\n for link in soup.find_all('a'): # will... | [
2,
1
] | [] | [] | [
"hyperlink",
"office_automation",
"outlook",
"python",
"win32com"
] | stackoverflow_0074194048_hyperlink_office_automation_outlook_python_win32com.txt |
Q:
Execute Selenium Python Script within Docker
I am trying to run a Selenium script written in Python inside a Docker container via Selenium Grid. Unfortunately I can't manage to configure the remote webdriver.
This is the Docker Compose file:
version: "3"
services:
chrome:
image: selenium/node-chrome:4.1.3-20... | Execute Selenium Python Script within Docker | I am trying to run a Selenium script written in Python inside a Docker container via Selenium Grid. Unfortunately I can't manage to configure the remote webdriver.
This is the Docker Compose file:
version: "3"
services:
chrome:
image: selenium/node-chrome:4.1.3-20220327
shm_size: 2gb
depends_on:
- s... | [
"TLDR : Try this:\ndriver = webdriver.Remote(\n desired_capabilities=DesiredCapabilities.FIREFOX,\n command_executor=\"http://selenium-hub:4444/wd/hub\"\n)\n\nThe reason it works locally from vs-code, is that localhost points to your local machine. Your docker container has its own idea of what localhost mean... | [
1
] | [] | [] | [
"docker",
"docker_compose",
"firefox",
"python",
"selenium"
] | stackoverflow_0071682729_docker_docker_compose_firefox_python_selenium.txt |
Q:
During Python Scraping data storing into csv files just store a singles line of data
Csv files only store a single row of data and if i use range into csv then it execute only one lines again and again until fulfilments of range.
I can't fix this bugs,i took my 2 days.
for page in range(0,10):
url = "https:/... | During Python Scraping data storing into csv files just store a singles line of data | Csv files only store a single row of data and if i use range into csv then it execute only one lines again and again until fulfilments of range.
I can't fix this bugs,i took my 2 days.
for page in range(0,10):
url = "https://cryptonews.net/?page={page}".format(page =page)
# print(url)
# open the file in the... | [
"You aren't storing the data, and as stated, it's overwritten each time you iterate through the lists. Secondly, I'd opt to use pandas here to create a dataframe, then just write that to file.\nAlso, you collect 5 items to write, and only have 4 column names.\nimport pandas as pd\nimport requests\nfrom bs4 import B... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"csv",
"python",
"web_scraping"
] | stackoverflow_0074222248_beautifulsoup_csv_python_web_scraping.txt |
Q:
How to transform Pandas dataframe for likert scale visualization?
I am in the process of analyzing a survey. This contains likert scales. To display them with Plotly (see link), I need an appropriate format. Therefore my question, how do I get from the following format :
to this target format:
Source Dataframe:
... | How to transform Pandas dataframe for likert scale visualization? | I am in the process of analyzing a survey. This contains likert scales. To display them with Plotly (see link), I need an appropriate format. Therefore my question, how do I get from the following format :
to this target format:
Source Dataframe:
{
"ID": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,... | [
"Assuming ID is index of df, you can do this:\npd.concat([df[c].value_counts() for c in df.columns],axis=1).fillna(0)\n\nAnother option is to melt the df long, and use pd.pivot_table()\npd.pivot_table(pd.melt(df),index=\"value\",columns=\"variable\", aggfunc='size', fill_value=0)\n\n"
] | [
2
] | [] | [] | [
"analysis",
"likert",
"plotly",
"python",
"survey"
] | stackoverflow_0074223046_analysis_likert_plotly_python_survey.txt |
Q:
Why is imperative mood important for docstrings?
The error code D401 for pydocstyle reads: First line should be in imperative mood.
I often run into cases where I write a docstring, have this error thrown by my linter, and rewrite it -- but the two docstrings are semantically identical. Why is it important to have... | Why is imperative mood important for docstrings? | The error code D401 for pydocstyle reads: First line should be in imperative mood.
I often run into cases where I write a docstring, have this error thrown by my linter, and rewrite it -- but the two docstrings are semantically identical. Why is it important to have imperative mood for docstrings?
| [
"From the docstring of check_imperative_mood itself:\n\n \"\"\"D401: First line should be in imperative mood: 'Do', not 'Does'.\n\n [Docstring] prescribes the function or method's effect as a command:\n (\"Do this\", \"Return that\"), not as a description; e.g. don't write\n \"Returns the pathname ...\".\n... | [
41,
10,
8,
7,
6,
3,
0
] | [] | [] | [
"docstring",
"pylint",
"python",
"static_analysis"
] | stackoverflow_0059902102_docstring_pylint_python_static_analysis.txt |
Q:
wxPython failing to install for Python 3.11.0
When I try to install wxPython: pip install wxpython, the process runs for a long time and it causes the system to freeze. And I have to manually restart the machine holding down the power button.
I also tried to install the snapshot of the wxPython which also had the ... | wxPython failing to install for Python 3.11.0 | When I try to install wxPython: pip install wxpython, the process runs for a long time and it causes the system to freeze. And I have to manually restart the machine holding down the power button.
I also tried to install the snapshot of the wxPython which also had the same errors as before.
OS: Windows 10 (21H2), 64-bi... | [
"Github Issue: https://github.com/wxWidgets/Phoenix/issues/2296\nWxPython Discussion: https://discuss.wxpython.org/t/wxpython-install-issue-on-macos-11-6-with-pyenv-and-python-3-11-0/36203\n"
] | [
0
] | [] | [] | [
"python",
"python_3.11",
"wxpython"
] | stackoverflow_0074195419_python_python_3.11_wxpython.txt |
Q:
How to handle dictionaries between different Python scripts
I have 2 Python scripts, which collect data from diffent APIs (also websockets) and store them in a dictionary. So I have 2 dictionaries, which are updated several times per second, up to 1000 times per second.
What I do now, I export these files as a .js... | How to handle dictionaries between different Python scripts | I have 2 Python scripts, which collect data from diffent APIs (also websockets) and store them in a dictionary. So I have 2 dictionaries, which are updated several times per second, up to 1000 times per second.
What I do now, I export these files as a .jsonfile and then import them in a 3rd script to compare both dicti... | [
"You're somewhat complicating things by having three separate processes that pass data between them. Writing json to the file system is slow and unreliable as you've discovered. There's several different approaches you could take to solve this problem.\n\nYou could use something like protocol buffer to transfer dat... | [
0
] | [] | [] | [
"dictionary",
"json",
"pickle",
"python"
] | stackoverflow_0074223139_dictionary_json_pickle_python.txt |
Q:
How to separate out/ return values not present in DB table using sqlalchmey in python project?
In my python project, I am querying DB table using filter and my filter is a list with multiple values. As it is a list data type, I am using _in operator in my sqlalchmey query. Now my use case is to separate out values... | How to separate out/ return values not present in DB table using sqlalchmey in python project? | In my python project, I am querying DB table using filter and my filter is a list with multiple values. As it is a list data type, I am using _in operator in my sqlalchmey query. Now my use case is to separate out values in my filters if they are present in my table and also if they are not present in table.
For exampl... | [
"To retrieve information about values with both do and do not have matches in the database you could create a temporary table from the values that you are querying and then do a left outer join against the model. This will return tuples of (value, object), and object will be None if there is no match.\nFor example... | [
0
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0074223060_python_sql_sqlalchemy.txt |
Q:
Program to input 10 numbers, count and output the positive and negative numbers in python (3.7.9)
How do you create a variable that would define a positive number and a negative number and then use it to relate to this specific list of numbers
Side note: I do not have to categorize 0 in this code
So far all I've m... | Program to input 10 numbers, count and output the positive and negative numbers in python (3.7.9) | How do you create a variable that would define a positive number and a negative number and then use it to relate to this specific list of numbers
Side note: I do not have to categorize 0 in this code
So far all I've managed to do is figure out the positive or negative number in a list, not both:
num = [ int(input("ente... | [
"Counting how many positive/negative numbers you have is very easy in this case:\nn_positive = n_negative = 0\nfor n in num:\n if n > 0:\n n_positive = n_positive + 1\n elif n < 0:\n n_negative = n_negative + 1\n\nIf you also want to know which number is positive/negative:\nn_positive = n_negati... | [
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074223234_python_python_3.x.txt |
Q:
What would the output of skip-gram model look like?
To my understanding, the output of the skip-gram model must be compared with many training labels (depending on the window size)
My question is: Does the final output of the skip-gram model look like the description in this picture?
Ps. the most similar question... | What would the output of skip-gram model look like? | To my understanding, the output of the skip-gram model must be compared with many training labels (depending on the window size)
My question is: Does the final output of the skip-gram model look like the description in this picture?
Ps. the most similar question I can find:[1]What does the multiple outputs in skip-gra... | [
"It's hard to answer about what \"should\" happen in degenerate/toy/artificial cases, especially given how much randomness is used in the actual initialization/training.\nBoth the model's internal weights and the 'projection layer' (aka 'input vectors' or just 'word vectors') are changed by backpropagation. So it c... | [
2,
1
] | [] | [] | [
"gensim",
"nlp",
"nltk",
"python",
"tensorflow"
] | stackoverflow_0067574809_gensim_nlp_nltk_python_tensorflow.txt |
Q:
Problem with my program for getting only letters (upper and lower case)
I'm trying to write a script which asks a user for input and validates the input in a loop, but I'm getting the error: TypeError: 'str' object cannot be interpreted as an integer.
I've tried a while and a for loop. Even without loop and just w... | Problem with my program for getting only letters (upper and lower case) | I'm trying to write a script which asks a user for input and validates the input in a loop, but I'm getting the error: TypeError: 'str' object cannot be interpreted as an integer.
I've tried a while and a for loop. Even without loop and just with an if and an else.
Here's what I have so far:
def majuscule(word):
fo... | [
"To check if a word is just letters or not, use the in-built python function of isalpha()\ndef majuscule(word):\n\n if word.isalpha():\n \n print('Valide word')\n\n else:\n \n word = input(\"What's your word ?\")\n\nRemember that isalpha() only returns True for alphabets, even if... | [
0,
0
] | [] | [] | [
"integer",
"python",
"string"
] | stackoverflow_0074223218_integer_python_string.txt |
Q:
datetime.date and datetime.time manipulations
I have a df with a date and a time column. So basically I want to perform the following manipulations:
#converting queue time(TULSA time) to IST
for r in range(df.shape[0]):
queue_date = df.loc[r,'queue date']
queue_time = df.loc[r,'queue time']
... | datetime.date and datetime.time manipulations | I have a df with a date and a time column. So basically I want to perform the following manipulations:
#converting queue time(TULSA time) to IST
for r in range(df.shape[0]):
queue_date = df.loc[r,'queue date']
queue_time = df.loc[r,'queue time']
if queue_date<'2022-03-13':
ist_t... | [
"When dealing with timezones it is strongly advised to use the built-in timezone features provided by Python.\nSo, if you want to get the current time in Tulsa (which I believe is US/Central time) and convert it to Indian Standard Time, you would use the following:\nimport datetime, pytz\n# create a datetime for th... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074223241_pandas_python.txt |
Q:
How to get an Integer from a specific line of a text file in Python?
I need some help with a task in python.
The task is to make a program that downloads a text file from the internet.
Then you have to find "Saturday" and "Sunday" in the text file.
Next to those are the temperatures.
The task is to calculate the a... | How to get an Integer from a specific line of a text file in Python? | I need some help with a task in python.
The task is to make a program that downloads a text file from the internet.
Then you have to find "Saturday" and "Sunday" in the text file.
Next to those are the temperatures.
The task is to calculate the average temperature of the weekend.
I am not allowed to change the text fil... | [
"If the text file is always going to be in this format, you can use a split function and not worry about regex ever.\nYou won't need two for loops\ndaily_temps = {}\n\nfor i, line in enumerate(lines):\n splits = line.split(\":\")\n day = splits[0].strip()\n temp = int(splits[-1].strip())\n daily_temps[d... | [
1,
0,
0,
0,
0
] | [
"You can try splitting each line with the ':' character, and get the second part of the returned list.\nLike you split the lines on the txt file.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074222604_python.txt |
Q:
Plotting random points inside parabola using Python?
Was wondering how to generate 100 random points inside the parabola below and also ensure that these points have y values smaller than 15000?
x = np.linspace(-100,100)
y = 2*x**2+10*x
plt.plot(x,y)
plt.show()
Any help would be appreciated. Thanks!
A:
The usu... | Plotting random points inside parabola using Python? | Was wondering how to generate 100 random points inside the parabola below and also ensure that these points have y values smaller than 15000?
x = np.linspace(-100,100)
y = 2*x**2+10*x
plt.plot(x,y)
plt.show()
Any help would be appreciated. Thanks!
| [
"\nThe usual boilerplate\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nWe want to generate points in a rectangle (x0, x0+dx) × (y0, y0+dy), and discard points under the parabola.\nThe y range is easy, y0=0 and dy=15000\ny0=ymin=y(-2.5), dy=15000-ymin, for the x range we need to solve 2 x² + 10 x = 15000 ... | [
0
] | [] | [] | [
"graph",
"math",
"matplotlib",
"numpy",
"python"
] | stackoverflow_0074218481_graph_math_matplotlib_numpy_python.txt |
Q:
load ed25519 public key with java
I have to read and load ed25519 public key for verifying signature in java, the token input pattern is:
{public_key}/message.signature
for example:
6a3239269f93999baec60382189c718031ad22c4c807ff29417824132cf0aa2d/eyJpc3N1ZV9kYXRlIjogIjIwMjItMTAtMjMiLCAiZXhwaXJ5X2RhdGUiOiAiMjAyMi0x... | load ed25519 public key with java | I have to read and load ed25519 public key for verifying signature in java, the token input pattern is:
{public_key}/message.signature
for example:
6a3239269f93999baec60382189c718031ad22c4c807ff29417824132cf0aa2d/eyJpc3N1ZV9kYXRlIjogIjIwMjItMTAtMjMiLCAiZXhwaXJ5X2RhdGUiOiAiMjAyMi0xMS0yMyIsICJsaWNlbnNlX3R5cGUiOiAxLCAibGl... | [
"The public key encoded as hexadecimals, and then encoded using base64. To revert this incorrect way of encoding you'd first need to decode the base64 and then decode the hexadecimals to bytes. To fix the python script instead, perform base64.b64encode(public_key.to_bytes() and remove the public_key_string.\nIt see... | [
0
] | [] | [] | [
"ed25519",
"java",
"public_key",
"python",
"signature"
] | stackoverflow_0074223413_ed25519_java_public_key_python_signature.txt |
Q:
How to replace value of Pandas column based on value in other column
Assume the following Pandas dataframe:
import pandas as pd
import numpy as np
data = {
'id' : [1, 2, 3, 4],
'name' : ['Foo', 'Bar', 'Baz', 'Buzz'],
'symbol' : ['F', '.', 'Mx2', 'M']
}
df = pd.DataFrame(data)
df
... | How to replace value of Pandas column based on value in other column | Assume the following Pandas dataframe:
import pandas as pd
import numpy as np
data = {
'id' : [1, 2, 3, 4],
'name' : ['Foo', 'Bar', 'Baz', 'Buzz'],
'symbol' : ['F', '.', 'Mx2', 'M']
}
df = pd.DataFrame(data)
df
id name symbol
0 1 Foo F
1 2 Bar .
2 3 Baz ... | [
"You can use .loc[] for this:\ndf.loc[df.name.eq('Bar') & df.symbol.eq('.'), 'symbol'] = 'F'\ndf.loc[df.name.eq('Baz') & df.symbol.eq('Mx2'), 'symbol'] = 'M'\n\nOutput:\n id name symbol\n0 1 Foo F\n1 2 Bar F\n2 3 Baz M\n3 4 Buzz M\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074223398_pandas_python.txt |
Q:
How to handle OperationalError/DatabaseError in sqlite3 Python
Why can't I catch OperationalError/DatabaseError through try/except syntax in sqlite3 python?
I also imported these errors with "from sqlite3 import OperationalError".
The code I was running is:
import pandas as pd
import sqlite3
from sqlite3 import Op... | How to handle OperationalError/DatabaseError in sqlite3 Python | Why can't I catch OperationalError/DatabaseError through try/except syntax in sqlite3 python?
I also imported these errors with "from sqlite3 import OperationalError".
The code I was running is:
import pandas as pd
import sqlite3
from sqlite3 import OperationalError
from sqlite3 import DatabaseError
con = sqlite3.conn... | [
"You need to catch the pandas database error. When you make a pandas call, catch pandas errors. sqlite3 errors should be handled on direct sqlite3 calls. So, import DatabaseError from pandas, not sqlite3:\nfrom pandas.io.sql import DatabaseError\n\n"
] | [
1
] | [] | [] | [
"exception",
"pandas",
"python",
"sqlite"
] | stackoverflow_0074220090_exception_pandas_python_sqlite.txt |
Q:
get unrepeated arrange of two dictionaries in python
from just two dicts(a, c), I need to find term_wMca that just gives:
xA * xB * xc * W_ABC. In fact I need to leave repeated ones like W_AAC, W_BBC, just ternary ones without repeat.when bigger dicts are entered by user just ternary should be calculated in term_w... | get unrepeated arrange of two dictionaries in python | from just two dicts(a, c), I need to find term_wMca that just gives:
xA * xB * xc * W_ABC. In fact I need to leave repeated ones like W_AAC, W_BBC, just ternary ones without repeat.when bigger dicts are entered by user just ternary should be calculated in term_wMca .
Is there any way to do that??
import sympy as sp
a =... | [
"No need to use for-loop for each variable:\nimport sympy as sp\na = {'A': 1}\nc = {'B': 1, 'C': 1}\n\nkeys = list(a.keys()) + list(c.keys())\n\nterm_wMca = 1\nfor k in keys:\n term_wMca *= sp.symbols(f'x{k}')\n\nterm_wMca *= sp.symbols(f'W_' + ''.join(keys))\n\nprint(term_wMca)\n\nResult:\nW_ABC * xA * xB * xC\... | [
1,
0
] | [] | [] | [
"combinations",
"dictionary",
"for_loop",
"python"
] | stackoverflow_0074192226_combinations_dictionary_for_loop_python.txt |
Q:
Parse JSON in React JS from Python Flask
I'm new to React JS and just start working on a project with React JS as frontend and Python Flask 2.2.2 as the backend. In Flask I'm trying to return a JSON in a function:
@app.route('/profile')
def test():
response_body = {
"test123": "123",
"name": "O... | Parse JSON in React JS from Python Flask | I'm new to React JS and just start working on a project with React JS as frontend and Python Flask 2.2.2 as the backend. In Flask I'm trying to return a JSON in a function:
@app.route('/profile')
def test():
response_body = {
"test123": "123",
"name": "Owen!",
"about": "about!"
}
pri... | [
"Your server and your client aren't running on the same port so you need fetch to the actual route of the flask backend\naxios.get(\"http://localhost:8080/profile\")\n .then(response => console.log(response.data.about))\n .catch(error => {});\n\nReplace that 8080 with the port your backend is running on.\n"... | [
0,
0
] | [] | [] | [
"flask",
"javascript",
"python",
"reactjs"
] | stackoverflow_0074216235_flask_javascript_python_reactjs.txt |
Q:
How to grow a list of dictionaries in Python
The following demo code:
mydict = {}
mylist = []
mydict["s"] = 1
mydict["p"] = "hasprice"
mydict["o"] = 3
print(mydict)
mylist.append(mydict)
mydict["s"] = 22
mydict["p"] = "hasvat"
mydict["o"] = 66
print(mydict)
mylist.append(mydict)
print(mylist)
prints out the fo... | How to grow a list of dictionaries in Python | The following demo code:
mydict = {}
mylist = []
mydict["s"] = 1
mydict["p"] = "hasprice"
mydict["o"] = 3
print(mydict)
mylist.append(mydict)
mydict["s"] = 22
mydict["p"] = "hasvat"
mydict["o"] = 66
print(mydict)
mylist.append(mydict)
print(mylist)
prints out the following result:
[{'s': 22, 'p': 'hasvat', 'o': 66}... | [
"mylist.append(mydict)\n\nSo, what are you doing here? You're appending a dict object, right?\nThe problem is that in Python the dict is a mutable type, which gets passed by reference.\nThat's why when you edit mydict you're also editing mylist[0], because they both reference to the same object.\n\nTo achieve what ... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0074223461_python.txt |
Q:
CodeSignal - 'Mutate Array'
The coding question asks:
Given an integer n and an array a of length n, your task is to apply the following mutation to a:
Array a mutates into a new array b of length n. For each i from 0 to n
- 1, b[i] = a[i - 1] + a[i] + a[i + 1]. If some element in the sum a[i - 1] + a[i] + a[i
+ ... | CodeSignal - 'Mutate Array' | The coding question asks:
Given an integer n and an array a of length n, your task is to apply the following mutation to a:
Array a mutates into a new array b of length n. For each i from 0 to n
- 1, b[i] = a[i - 1] + a[i] + a[i + 1]. If some element in the sum a[i - 1] + a[i] + a[i
+ 1] does not exist, it should be s... | [
"The other solution failed for single element array. This should work fine.\ndef solution(a):\n b = []\n #print(b)\n for i in range(len(a)):\n if len(a) == 1:\n b.append(a[0])\n else:\n\n if i == 0:\n # b[i] = 0 + a[i] + a[i+1]\n b.append(0 ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0071301895_python.txt |
Q:
I have a problem regarding extracting in python
I have been using the following code to extract the files:
import os, zipfile
extension = ".zip"
for item in os.listdir(dir_name): # loop through items in dir
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(item) # get fu... | I have a problem regarding extracting in python | I have been using the following code to extract the files:
import os, zipfile
extension = ".zip"
for item in os.listdir(dir_name): # loop through items in dir
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(item) # get full path of files
zip_ref = zipfile.ZipFile(file_... | [
"Use os.mkdir(\"dir_name\") with the same name as the Zip File and then Extract them in this new directory zip_ref.extractall(\"dir_name\")\nFor eg:- Zip File => my_zip.zip\nfilename = my_zip.zip\nos.mkdir(filename.strip(\".zip\"))\n\n#rest of the code\n\nzip_ref.extractall(filename.strip(\".zip\"))\n\n"
] | [
0
] | [] | [] | [
"python",
"python_zipfile"
] | stackoverflow_0074223497_python_python_zipfile.txt |
Q:
Use existing persistent profile with selenium, firefox and python
I want to automate some OSINT tasks on web.whatsapp.com, but I don't want to login each time selenium initiates the session. It proved surprisingly difficult to get a reliable solution with persistent cookies, but see my solution below.
Many existin... | Use existing persistent profile with selenium, firefox and python | I want to automate some OSINT tasks on web.whatsapp.com, but I don't want to login each time selenium initiates the session. It proved surprisingly difficult to get a reliable solution with persistent cookies, but see my solution below.
Many existing solutions suggest generating a FirefoxProfile(), e.g.
fp = FirefoxPro... | [
"There is a firefox-specific way to pass an existing profile to the webdriver using set_capability described here. Here's how I used it:\nprofilepath = '/your/profile/path'\noptions = Options()\noptions.set_capability(\"moz:firefoxOptions\", {\n \"args\":[\"-profile\", profilepath]\n})\nself.driver = webdriver.F... | [
0
] | [] | [] | [
"firefox",
"profile",
"python",
"selenium"
] | stackoverflow_0074223468_firefox_profile_python_selenium.txt |
Q:
Get first 3 letters of a string from a dataframe column
How to get extract first 3 letters from a string in dataframe column and store them in a new column.
Extract the first three letters/numbers from the column 'A' and store it in the column 'C'
DATA:
A B
12525 1FWE23
14654 22354
247... | Get first 3 letters of a string from a dataframe column | How to get extract first 3 letters from a string in dataframe column and store them in a new column.
Extract the first three letters/numbers from the column 'A' and store it in the column 'C'
DATA:
A B
12525 1FWE23
14654 22354
24798 32684
38945 45368
46456 46485
AD54... | [
"First, we re-create the dataframe from the example you provided:\nfrom io import StringIO\n\ns = \"\"\"\n A B \n12525 1FWE23 \n14654 22354 \n24798 32684 \n38945 45368 \n46456 46485 \nAD545 45346 \nA5D66 58446 \n\"\"\"\n\ndf = pd.read_csv(StringIO(s), sep... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074223476_dataframe_pandas_python.txt |
Q:
Invalid Syntax error?
I'm new at Python and tried writing a basic script.
I'm trying to print out all the letters of the alphabet, and I keep getting Invalid Syntax.
letter = ord('a')
while letter != ord('z')
print(chr(letter))
letter = letter + 1
Here's the first error log:
while letter != ord('z')
... | Invalid Syntax error? | I'm new at Python and tried writing a basic script.
I'm trying to print out all the letters of the alphabet, and I keep getting Invalid Syntax.
letter = ord('a')
while letter != ord('z')
print(chr(letter))
letter = letter + 1
Here's the first error log:
while letter != ord('z')
^
SyntaxE... | [
"You want a colon at the end of your while loop, to let Python know it's a block.\nwhile letter != ord('z'):\n <rest of your code here>\n\nAlso, right now you seem to have the start of the while loop indented and none of the rest, when you want the opposite: all the code to be run in the while loop should be ind... | [
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0017626446_python.txt |
Q:
I'm trying to plot a data which should be displayed as a plasma effect. But seems I'm having trouble here
c = np.cos(20)**2
d = np.sin(20)**2
x = np.linspace(-np.pi,np.pi)
y = np.linspace(-np.pi, np.pi)
z = np.abs(np.cos(20 * (c + d)))
x,y = np.meshgrid(x,y)
plt.imshow(z)
So this is the code so far. It's supposed ... | I'm trying to plot a data which should be displayed as a plasma effect. But seems I'm having trouble here | c = np.cos(20)**2
d = np.sin(20)**2
x = np.linspace(-np.pi,np.pi)
y = np.linspace(-np.pi, np.pi)
z = np.abs(np.cos(20 * (c + d)))
x,y = np.meshgrid(x,y)
plt.imshow(z)
So this is the code so far. It's supposed to produce a plasma effect
This was the result, which is not what I'm expecting.
| [
"Not sure if this is what you were trying, but here is an example of code that works without the error. Maybe you can tweak it to your liking:\nfrom matplotlib import pyplot as plt\ndef z_function(x,y):\n c = np.cos(x)**2\n d = np.sin(y)**2\n z = np.abs(np.cos(20 * (c + d)))\n return z\nx = np.linspace(... | [
1
] | [] | [] | [
"matplotlib_animation",
"numpy",
"python"
] | stackoverflow_0074223402_matplotlib_animation_numpy_python.txt |
Q:
Bitwise operators:- Ball, carrot, ampersand, tilde
I want the step by step explanation of the following code:
print(1 | 0 ^ 1 & ~0)
I tried with the output bit (output with first and second bit) and got the answer as 0. The tilde function got me hooked up for some time I found it a bit hard. The answer is 1.
A:... | Bitwise operators:- Ball, carrot, ampersand, tilde | I want the step by step explanation of the following code:
print(1 | 0 ^ 1 & ~0)
I tried with the output bit (output with first and second bit) and got the answer as 0. The tilde function got me hooked up for some time I found it a bit hard. The answer is 1.
| [
"First you must understand what each operator does\n| - Bitwise OR: Returns True (1) if either of its operands is 1. e.g.\n1 | 0 == True\n& - Bitwise AND: Returns True if both of its operands are 1. e.g.\n0 & 1 == False\n^ - Bitwise XOR: Returns True if only one of its operands is 1. e.g.\n0 ^ 1 == True\n~ - Bitwis... | [
2,
1
] | [] | [] | [
"ampersand",
"bitwise_operators",
"python",
"tilde"
] | stackoverflow_0074223372_ampersand_bitwise_operators_python_tilde.txt |
Q:
Directories containing .jpg files were converted to binary files [shutil]
Update:
Basically, I want to divide a large folder into 2 groups.
The large folder is made up of 120 subfolders. An example subfolder name would be n02085620-Chihuahua. n02085620-Chihuahua has 152 .jpg files. An example file in it would be n... | Directories containing .jpg files were converted to binary files [shutil] | Update:
Basically, I want to divide a large folder into 2 groups.
The large folder is made up of 120 subfolders. An example subfolder name would be n02085620-Chihuahua. n02085620-Chihuahua has 152 .jpg files. An example file in it would be n02085620_7.jpg. You see n02085620 is the same.
Names of files that should go to... | [
"I'd start from simplifying task. Let's say we have next file structure:\n│ rules.csv\n│\n└───source\n ├───1\n │ 1.jpg\n │ 2.jpg\n │\n ├───2\n │ 3.jpg\n │ 4.jpg\n │\n ├───3\n │ 5.jpg\n │ 6.jpg\n │\n ├───4\n │ 7.jpg\n │ 8.... | [
0
] | [] | [] | [
"os.path",
"python",
"shutil",
"subdirectory"
] | stackoverflow_0074217929_os.path_python_shutil_subdirectory.txt |
Q:
How to delete a certain delaunay triangle from the list of tri.simplices in Python
i construct two Delaunay triangulations from two different numpy arrays of vertices.
They have two identical triangles, which i want to delete from one of the triangulation list.
If somebody can help me out here i would really appre... | How to delete a certain delaunay triangle from the list of tri.simplices in Python | i construct two Delaunay triangulations from two different numpy arrays of vertices.
They have two identical triangles, which i want to delete from one of the triangulation list.
If somebody can help me out here i would really appreciate it. Thanks in advance.
cloud1 = numpy.array([[4.2, 4.5], [4.4, 5.3], [6.2, 5.6], ... | [
"If you want to delete a triangle from the Delaunay triangulation itself, then it isn't possible in Delaunay triangulations. There are algorithms for removing points from the triangulation, which re-build the triangulation in the area of the removed points. However, to the best of my knowledge, they are not impleme... | [
0
] | [] | [] | [
"arrays",
"delaunay",
"numpy",
"python",
"triangle"
] | stackoverflow_0074201215_arrays_delaunay_numpy_python_triangle.txt |
Q:
Module Not found during import in Jupyter Notebook
I have the following package (and working directory):
WorkingDirectory--
|--MyPackage--
| |--__init__.py
| |--module1.py
| |--module2.py
|
... | Module Not found during import in Jupyter Notebook | I have the following package (and working directory):
WorkingDirectory--
|--MyPackage--
| |--__init__.py
| |--module1.py
| |--module2.py
|
|--notebook.ipynb
In __init__.py I have:
impo... | [
"I'm pretty sure this issue is related and the answer there will help you: https://stackoverflow.com/a/15622021/7458681\ntl;dr the cwd of the notebook server is always the base path where you started the server, no matter was running import os os.getcwd() says. Use import sys sys.path.append(\"/path/to/your/module/... | [
29,
3,
2,
2,
0,
0,
0
] | [
"The reason is that your MyPackage/__init__.py is ran from the current working directory. E.g. from WorkingDirectory in this case. It means, that interpreter cannot find the module named module1 since it is not located in either current or global packages directory.\nThere are few workarounds for this. For example,... | [
-1,
-1
] | [
"jupyter_notebook",
"python",
"python_3.x",
"python_import",
"python_module"
] | stackoverflow_0043120112_jupyter_notebook_python_python_3.x_python_import_python_module.txt |
Q:
pytorch_lightning.callbacks.ModelCheckpoint
I am trying to use ModelCheckpoint to save the best-performing model in validation loss in each epoch.
class model(pl.lightningModule)
:
:
:
def validation_step(self, batch, batch_idx):
if batch_idx == 0:
self.totalValLoss = 0
... | pytorch_lightning.callbacks.ModelCheckpoint | I am trying to use ModelCheckpoint to save the best-performing model in validation loss in each epoch.
class model(pl.lightningModule)
:
:
:
def validation_step(self, batch, batch_idx):
if batch_idx == 0:
self.totalValLoss = 0
self.totalValToken = 0
batch = Batch... | [
"Check please your trainer paramrtes: check_val_every_n_epoch and max_epochs, if check_val_every_n_epoch<max_epochs your code won't save model.\n"
] | [
0
] | [] | [] | [
"machine_learning",
"python",
"pytorch",
"pytorch_lightning"
] | stackoverflow_0071900553_machine_learning_python_pytorch_pytorch_lightning.txt |
Q:
How to calculate the Cosine similarity between two tensors?
I have two normalized tensors and I need to calculate the cosine similarity between these tensors. How do I do it with TensorFlow?
cosine(normalize_a,normalize_b)
a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a")
b = tf.pla... | How to calculate the Cosine similarity between two tensors? | I have two normalized tensors and I need to calculate the cosine similarity between these tensors. How do I do it with TensorFlow?
cosine(normalize_a,normalize_b)
a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a")
b = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_b")
... | [
"This will do the job:\na = tf.placeholder(tf.float32, shape=[None], name=\"input_placeholder_a\")\nb = tf.placeholder(tf.float32, shape=[None], name=\"input_placeholder_b\")\nnormalize_a = tf.nn.l2_normalize(a,0) \nnormalize_b = tf.nn.l2_normalize(b,0)\ncos_similarity=tf.reduce_sum(tf.multiply(normalize_a,n... | [
29,
25,
1,
0
] | [] | [] | [
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0043357732_neural_network_python_tensorflow.txt |
Q:
python pandas remove text in column names after specific characters
I have a Dataframe with hundreds of columns and very long column-names. I want to remove any text in the column-names after the ":" or "." This is basically splitting on multiple delimiters.
I tried to extract column-names in a list and use the sp... | python pandas remove text in column names after specific characters | I have a Dataframe with hundreds of columns and very long column-names. I want to remove any text in the column-names after the ":" or "." This is basically splitting on multiple delimiters.
I tried to extract column-names in a list and use the split method at ":" and "." and then keep only the portion of the text befo... | [
"You could use regular expression re in order to split the column name strings, and then reassing them to the dataframe :\nimport pandas as pd\nimport re\ndata = {'Name of the injured. Bla bla bla': ['Bill', 'John'],\n 'Age of the injured: bla bla': [50,40],\n }\ndf_data = pd.DataFrame.from_dict(... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074223495_pandas_python.txt |
Q:
How to 1) list and extract specific 'li' tags in a 'ul' script in python and 2) export them in separate columns in excel
I am trying to web scrape some data from a car site.
I have mananed to extract some details (e.g. price, title, subtitle) using beautiful soup, which sits under another tag, however, there are s... | How to 1) list and extract specific 'li' tags in a 'ul' script in python and 2) export them in separate columns in excel | I am trying to web scrape some data from a car site.
I have mananed to extract some details (e.g. price, title, subtitle) using beautiful soup, which sits under another tag, however, there are some li values (mileage, body, number of owners) under a ul tag which i havent been able to extract.
Below is my code i've been... | [
"Few things.\n\ndont use list as a variable name. Thats a defined python method, so try to avoid using things like that (int, str, for, etc.)\nuse .strip() to remove that extra whitespace at the end of text instead of .replace()\nPandas is a great tool to use. Get familar with it. use it...it'll make life easier.\n... | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074222544_beautifulsoup_python.txt |
Q:
What happens exactly when a python class instance use dot to access attributes?
Suppose a class A is defined as:
class A:
def __init__(self, val):
self.val = val
After A is instantiated by a = A(3), what methods will be called by executing a.val? In other words, what will happen internally when a.val ... | What happens exactly when a python class instance use dot to access attributes? | Suppose a class A is defined as:
class A:
def __init__(self, val):
self.val = val
After A is instantiated by a = A(3), what methods will be called by executing a.val? In other words, what will happen internally when a.val is executed?
Moreover, how about A accessing a non-existed attribute, namely other_va... | [
"When you [try to] access a class instance attribute using dot notation, the class's __getattribute__ method will be invoked. This can be demonstrated thus:\nclass A():\n def __init__(self):\n self.val = 99\n def __getattribute__(self, attr):\n print(f'Acquiring {attr}')\n return super(ty... | [
1
] | [] | [] | [
"python",
"python_attrs",
"python_class",
"python_magic"
] | stackoverflow_0074223351_python_python_attrs_python_class_python_magic.txt |
Q:
"grayed out" inside a python function, need solution
Pls check the code
from socket import *
address = ('192.168.1.213', 5000)
client_socket = socket(AF_INET,SOCK_DGRAM)
rec_data, addr = client_socket.recvfrom(2048)
def comConnect():
data = "Blue"
client_socket.sendto(data,address)
rec_data, addr ... | "grayed out" inside a python function, need solution | Pls check the code
from socket import *
address = ('192.168.1.213', 5000)
client_socket = socket(AF_INET,SOCK_DGRAM)
rec_data, addr = client_socket.recvfrom(2048)
def comConnect():
data = "Blue"
client_socket.sendto(data,address)
rec_data, addr = client_socket.recvfrom(2048)
print(rec_data)
Loo... | [
"This is because addr is never referenced (used). This is because addr inside the function is a local variable and is never referenced inside the function.\n"
] | [
1
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0074223368_python_sockets.txt |
Q:
'numpy.ndarray' object is not callable for this small code
import numpy as np
def main():
try:
date, price, open = np.loadtxt('CARG.csv', delimiter=',',
unpack=True, dtype='str')
x = 0
for eachDate in date:
saveLine = eachDate + ',' +... | 'numpy.ndarray' object is not callable for this small code | import numpy as np
def main():
try:
date, price, open = np.loadtxt('CARG.csv', delimiter=',',
unpack=True, dtype='str')
x = 0
for eachDate in date:
saveLine = eachDate + ',' + price[x] + '\n'
saveFile = open('newCSV', 'a')
... | [
"The problem is that you've named a local variable open, which shadows the builtin function of the same name—but then tried to use the builtin a couple lines later:\ndate, price, open = …\n\nsaveFile = open('newCSV', 'a')\n\nSo, instead of calling the builtin, you're calling the array. Which obviously doesn't work.... | [
2,
0
] | [] | [] | [
"csv",
"numpy",
"numpy_ndarray",
"python",
"python_3.x"
] | stackoverflow_0049345411_csv_numpy_numpy_ndarray_python_python_3.x.txt |
Q:
has inconsistent name: expected , but metadata has when install from url by pipenv
I am trying to install a package directly from github by
pipenv install -e git+https://github.com/cikay/public_repo.git@main#egg=public_repo
command but got\n
has inconsistent name: expected 'public-repo', but metadata has 'main'.
I... | has inconsistent name: expected , but metadata has when install from url by pipenv | I am trying to install a package directly from github by
pipenv install -e git+https://github.com/cikay/public_repo.git@main#egg=public_repo
command but got\n
has inconsistent name: expected 'public-repo', but metadata has 'main'.
If I specify egg=main it works. What is wrong? Why I cannot specify any name I would like... | [
"The package name should be specified in the setup function.\nsetup(name=\"package_name\")\n\n"
] | [
0
] | [] | [] | [
"pipenv",
"python"
] | stackoverflow_0074220721_pipenv_python.txt |
Q:
How to install ursina?
I went to powershell and said pip install ursina, but the only thing that came up was pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try... | How to install ursina? | I went to powershell and said pip install ursina, but the only thing that came up was pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
pi... | [
"Do you add python dir to %PATH%? Add it and try pip install ursina again. That should help.\nalso see 'pip' is not recognized\n",
"I suspect one of 2 things\n\nEither pip is not installed in your computer(usually it comes installed with default installation of python )\n\nyou have not added pip as a windows envi... | [
0,
0,
0,
0
] | [] | [] | [
"game_development",
"powershell",
"python",
"ursina"
] | stackoverflow_0069986931_game_development_powershell_python_ursina.txt |
Q:
Any suggestions to scrape twitter profiles age using pyhthon
I am rn trying to scrape twitter for an nlp research. I already used snscrape to get tweets with the required filters, the issue is that we need tweets from a specific age range. In my head I guess some profiles on twitter have their birthdate public, s... | Any suggestions to scrape twitter profiles age using pyhthon | I am rn trying to scrape twitter for an nlp research. I already used snscrape to get tweets with the required filters, the issue is that we need tweets from a specific age range. In my head I guess some profiles on twitter have their birthdate public, so maybe we can fetch that. Maybe webscrape that from the profile? ... | [
"Twitter has a pretty well documented API that works very well with Python.\nTry to make a simple crawler and see one of the JSONs that you get for a Tweet/User.\nYou will need to sign up and get some Access Tokens/Keys to use in your script, but other than that you are ready to go:\nhttps://developer.twitter.com/e... | [
1,
0
] | [] | [] | [
"python",
"twitter",
"web_scraping"
] | stackoverflow_0074222923_python_twitter_web_scraping.txt |
Q:
Manipulation and interpretation of xgboost models in python
I've been taking a look at the output of booster.save_model("model.json"), and I am having trouble understanding the output. It seems as though almost none of the information in model.json is actually used for prediction, in fact - suspiciously little. Fo... | Manipulation and interpretation of xgboost models in python | I've been taking a look at the output of booster.save_model("model.json"), and I am having trouble understanding the output. It seems as though almost none of the information in model.json is actually used for prediction, in fact - suspiciously little. For reference, one such model.json looks like this:
j={"learner": {... | [
"(I see it's nine months too late, but here's a rudimentary answer as other people may be interested in this...)\nsplit_indices refers to the index (0-based) of the list of features supplied during training. It basically says \"At this node (position in the array) use feature N for splitting\".\nFor split nodes, sp... | [
0
] | [] | [] | [
"machine_learning",
"python",
"xgboost"
] | stackoverflow_0070586078_machine_learning_python_xgboost.txt |
Q:
sklearn VotingClassifier with RandomizedSearchCV gives pickle error
I'm trying to get randomized hyperparameter search to work with the voting classifier from sklearn by adapting the example given in the sklearn documentation.
I've seen this minimal working example, but it breaks in many ways using my version of s... | sklearn VotingClassifier with RandomizedSearchCV gives pickle error | I'm trying to get randomized hyperparameter search to work with the voting classifier from sklearn by adapting the example given in the sklearn documentation.
I've seen this minimal working example, but it breaks in many ways using my version of sklearn.
Here is a stripped-down example:
import numpy as np
from sklearn ... | [
"Oops, it turns out the problem was in\nestimators = clfs.items()\n\nAll was well once I wrapped it in tuple() to be an actual tuple rather than a generator.\n"
] | [
0
] | [] | [] | [
"python",
"scikit_learn"
] | stackoverflow_0074223381_python_scikit_learn.txt |
Q:
Django rest framework serializer object from ID
I have this serializer:
class OrderLineSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField(source="item.id")
name = serializers.ReadOnlyField(source="item.name")
price = serializers.ReadOnlyField(source="item.price")
quantity = ser... | Django rest framework serializer object from ID | I have this serializer:
class OrderLineSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField(source="item.id")
name = serializers.ReadOnlyField(source="item.name")
price = serializers.ReadOnlyField(source="item.price")
quantity = serializers.IntegerField(
validators=[MinValueVa... | [
"I believe a dedicated serializer is the way to go, first of all you won't want the complexity of using a single serializer. And it would only take 3 lines to build a new one for your input. So just make a dedicated serializer.\n",
"Answering my own question.\nDoing it was actually quite simple.\nIt's just about ... | [
2,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074206218_django_django_rest_framework_python.txt |
Q:
Check if both before and after values are higher per value per group
I have the following dataframe (sample):
import pandas as pd
data = [['A', '2022-09-01', 2], ['A', '2022-09-02', 1], ['A', '2022-09-03', 1.5], ['A', '2022-09-04', 1.5],
['A', '2022-09-05', 1], ['A', '2022-09-06', 1], ['A', '2022-09-07', ... | Check if both before and after values are higher per value per group | I have the following dataframe (sample):
import pandas as pd
data = [['A', '2022-09-01', 2], ['A', '2022-09-02', 1], ['A', '2022-09-03', 1.5], ['A', '2022-09-04', 1.5],
['A', '2022-09-05', 1], ['A', '2022-09-06', 1], ['A', '2022-09-07', 0.5], ['A', '2022-09-08', 1],
['B', '2022-09-01', 3], ['B', '2022-... | [
"Use and condition on comparing with previous and next row\ndf['class'] = df['value'].lt(df['value'].shift()) & df['value'].lt(df['value'].shift(-1))\n# or\ndf['class'] = (df['value'] < df['value'].shift()) & (df['value'] < df['value'].shift(-1))\n\nprint(df)\n\n group date value class\n0 A 2022-09... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074223801_dataframe_pandas_python.txt |
Q:
How to create a loop for plotting dataframe features in Python using seaborn
I would like to plot multiple subplot of histogram to observe the distribution of each individual features in a data frame.
I have tried to use the below code, but it says dataframe object has no attribute i. I know the code is wrong some... | How to create a loop for plotting dataframe features in Python using seaborn | I would like to plot multiple subplot of histogram to observe the distribution of each individual features in a data frame.
I have tried to use the below code, but it says dataframe object has no attribute i. I know the code is wrong somewhere, but i have tried to search for solution and could not find a way to generat... | [
"Is this what you're looking for?\nimport pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn')\n\ndf = pd.read_csv('data.csv')\n\ndf.plot.hist(subplots=True, legend=False)\n\nSeaborn alternative\ng = sns.FacetGrid(df, row='column')\ng.map(plt.hist, 'value')\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074223772_python.txt |
Q:
How to save and load cookies using Python + Selenium WebDriver
How can I save all cookies in Python's Selenium WebDriver to a .txt file, and then load them later?
The documentation doesn't say much of anything about the getCookies function.
A:
You can save the current cookies as a Python object using pickle. For... | How to save and load cookies using Python + Selenium WebDriver | How can I save all cookies in Python's Selenium WebDriver to a .txt file, and then load them later?
The documentation doesn't say much of anything about the getCookies function.
| [
"You can save the current cookies as a Python object using pickle. For example:\nimport pickle\nimport selenium.webdriver\n\ndriver = selenium.webdriver.Firefox()\ndriver.get(\"http://www.google.com\")\npickle.dump( driver.get_cookies() , open(\"cookies.pkl\",\"wb\"))\n\nAnd later to add them back:\nimport pickle\n... | [
272,
124,
40,
26,
19,
4,
2,
2,
1
] | [] | [] | [
"python",
"python_2.7",
"selenium",
"webdriver"
] | stackoverflow_0015058462_python_python_2.7_selenium_webdriver.txt |
Q:
Seaborn axis y values
Im having a problem. When i write the code to get a plot in seaborn the axis y should launch values in Millions, instead of that seaborn gimme values from 1 to 8 and in the left top corner appears 1e7.
Any suggestion?
this is the code i wrote:
GraficaHV = pd.concat([CountIN,CountOutGraph])
Gr... | Seaborn axis y values | Im having a problem. When i write the code to get a plot in seaborn the axis y should launch values in Millions, instead of that seaborn gimme values from 1 to 8 and in the left top corner appears 1e7.
Any suggestion?
this is the code i wrote:
GraficaHV = pd.concat([CountIN,CountOutGraph])
GraficaHV
Mes HVT T... | [
"You can surpress scientific notation by using parameter ticklabel_format(style='plain', axis='y').\nHere some other parameter that may be of use: Documentation\n"
] | [
0
] | [] | [] | [
"python",
"seaborn"
] | stackoverflow_0074223793_python_seaborn.txt |
Q:
How do I tokenize this input sentences by the following stopwords ("!", "?", ".", “,”)?
I imported sent_tokenize from nltk.tokenize and thus use the method called sent_tokenize(input). Below are the the solutions and function I've used to solve this but I keep on getting failed. I tried looking on the net and trie... | How do I tokenize this input sentences by the following stopwords ("!", "?", ".", “,”)? | I imported sent_tokenize from nltk.tokenize and thus use the method called sent_tokenize(input). Below are the the solutions and function I've used to solve this but I keep on getting failed. I tried looking on the net and tried to understand every method used out there but still it's not working.
I have no idea what I... | [
"Other than the overwriting of your function arguments inside the function and the variable naming issue, your code is working exactly as it should.\nsent_tokenize() splits full sentences. Ellipsis and commas are not punctuation that end sentences and so there will be no split for those characters.\nYour code, but ... | [
0
] | [] | [] | [
"python",
"tokenize"
] | stackoverflow_0074223517_python_tokenize.txt |
Q:
How to Reverse Rolling Sum?
I have a rolling sum calculated on a grouped data frame but its adding up the wrong way, it is a sum of the future, when I need a sum of the past.
What am I doing wrong here?
I import the data and sort by Dimension and Date (I have tried removing the date sort already)
df = pd.read_csv(... | How to Reverse Rolling Sum? | I have a rolling sum calculated on a grouped data frame but its adding up the wrong way, it is a sum of the future, when I need a sum of the past.
What am I doing wrong here?
I import the data and sort by Dimension and Date (I have tried removing the date sort already)
df = pd.read_csv('Input.csv', parse_dates=True)
df... | [
"You need a backward sum, therefore reverse your series before sum rolling it:\nlambda x: x[::-1].rolling(window=3).sum()\n\n",
"You can shift the result by window-1 to get the left aligned results:\ndf[\"sum_value1\"] = (df.groupby('Dimension').Value1\n .apply(lambda x: x.rolling(window=3).s... | [
11,
6,
5,
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0043101652_pandas_python.txt |
Q:
trying to mutiply results and getting error
i'm trying to multiply the result "5,0" but nothing works, can someone explain what i'm doing wrong?
print result is "5,0 5,0 5,0 5,0 5,0 " i used .replace to remove "KM" from result.
import selenium
from selenium import webdriver
from webdriver_manager.chrome import Chr... | trying to mutiply results and getting error | i'm trying to multiply the result "5,0" but nothing works, can someone explain what i'm doing wrong?
print result is "5,0 5,0 5,0 5,0 5,0 " i used .replace to remove "KM" from result.
import selenium
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.s... | [
"To elaborate on povk's answer:\nkm1 = '5,0 km' # this is a string\nvalue = km1.replace('km', '').replace(',', '.') # still a string\nvalue_cast = float(value) # this is a float\n\nvalue * 5\n>>> '5.0 5.0 5.0 5.0 5.0 '\n\nvalue_cast * 5\n>>> 25.0\n\nIf in your country decimals are typically written with a comma, yo... | [
1,
0
] | [] | [] | [
"integer",
"pandas",
"printing",
"python",
"python_3.x"
] | stackoverflow_0074222650_integer_pandas_printing_python_python_3.x.txt |
Q:
How to call a python function with annotations?
I have a function in another annotated method and there is a problem. I call it through django and get all sorts of errors. like this.
views.py:
`
def callbot():
bot_activate = bot.Command.callBot()
return render(request, bot_activate)
def output(reques... | How to call a python function with annotations? | I have a function in another annotated method and there is a problem. I call it through django and get all sorts of errors. like this.
views.py:
`
def callbot():
bot_activate = bot.Command.callBot()
return render(request, bot_activate)
def output(request, temlate_name='custom_change_form.html',):
call... | [
"chat_id = update.message.chat_id\nShouldn't this be\nchat_id = update.message.chat.id ?\nIn your example, in the first function you use chat.id, then in the following methods you use chat_id.\n"
] | [
0
] | [] | [] | [
"annotations",
"django",
"html",
"python"
] | stackoverflow_0074223908_annotations_django_html_python.txt |
Q:
Cannot import library covsirphy
I am trying to import library COVSIRPHY to jupyter notebook following two steps:
pip install --upgrade covsirphy (I installed it using terminal in specific environment created in anaconda navigator)
It was installed successfully
import covsirphy as cs
I typed in directly in jupy... | Cannot import library covsirphy | I am trying to import library COVSIRPHY to jupyter notebook following two steps:
pip install --upgrade covsirphy (I installed it using terminal in specific environment created in anaconda navigator)
It was installed successfully
import covsirphy as cs
I typed in directly in jupyter notebook, but it occured an error... | [
"Please re-install libomp to save 'libomp.dylib' file at '/usr/lib/libomp.dylib' or update PATH to include the current path.\nAn alternative:\nBecause the latest development version of covsirphy does not depend on lightgbm, try to reinstall the latest version (>= 3.0.0.dev7).\npip install --upgrade \"git+https://gi... | [
0
] | [] | [] | [
"jupyter",
"python"
] | stackoverflow_0074173645_jupyter_python.txt |
Q:
How to make logical AND, NOT work properly in Postgres full text search with Django
I have a project with Django, DRF and PostgreSQL. And I need to make a search for some data in this project. In this search I need logical operators (AND, OR, NOT), searching by prefix (like manch*) and case insensitivity. So I dec... | How to make logical AND, NOT work properly in Postgres full text search with Django | I have a project with Django, DRF and PostgreSQL. And I need to make a search for some data in this project. In this search I need logical operators (AND, OR, NOT), searching by prefix (like manch*) and case insensitivity. So I decided to use PostgreSQL full text search like this
class VariableSearch(generics.ListAPIVi... | [
"add another query to url\nexample:\n?word_status=True\n\nOr you can but ‘or’, ‘and’\nand get this value to apply it with your query( depending on it )\n"
] | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"postgresql",
"python",
"search"
] | stackoverflow_0074223888_django_django_rest_framework_postgresql_python_search.txt |
Q:
Pyomo (Transportation theory): Trying to show a variable with the sum of other variables
I'm trying to solve the classical 'Transportation theory' to optimize the production and transportation of goods from 3 factories to 2 distribution centers, through 2 weeks.
There are:
3x2 max capacities in each factory (items... | Pyomo (Transportation theory): Trying to show a variable with the sum of other variables | I'm trying to solve the classical 'Transportation theory' to optimize the production and transportation of goods from 3 factories to 2 distribution centers, through 2 weeks.
There are:
3x2 max capacities in each factory (items/week)
3x2x2 transportation costs from each factory to each distribution center ($/item/week)
... | [
"The model.production variable appears to be just a convenience to get weekly totals as it is not relevant in the model. There are better ways to get the data out, but let's figure out why it is empty...\nThe model.production data is not associated with the production function. It isn't clear what you were trying... | [
0
] | [] | [] | [
"optimization",
"pyomo",
"python"
] | stackoverflow_0074221347_optimization_pyomo_python.txt |
Q:
Select two elements of tuple given interval
I have the following tuple:
my_list = (1000, 3000, 7000, 15000 ,79000)
For any given number I give to a selected variable, I want to return both the the value in the tuple minus the interval and the selected value. By interval I mean the delta/difference between the sel... | Select two elements of tuple given interval | I have the following tuple:
my_list = (1000, 3000, 7000, 15000 ,79000)
For any given number I give to a selected variable, I want to return both the the value in the tuple minus the interval and the selected value. By interval I mean the delta/difference between the selected value and the prior one I want to output. S... | [
"There might be better ways, but please see my approach below:\ndef getInterval(myList: list, selected, interval) -> tuple:\n idxSelected = myList.index(selected)\n return (myList[idxSelected - interval], myList[idxSelected])\n\nmy_list = [*range(1, 15)]\nselected = 4\ninterval = 3\n\nprint(getInterval(my_lis... | [
1,
0,
0
] | [] | [] | [
"for_loop",
"function",
"list",
"python"
] | stackoverflow_0074223786_for_loop_function_list_python.txt |
Q:
How to set environment variables in Python?
I need to set some environment variables in the Python script and I want all the other scripts that are called from Python to see the environment variables' set.
If I do,
os.environ["DEBUSSY"] = 1
it complains saying that 1 has to be a string.
I also want to know how to... | How to set environment variables in Python? | I need to set some environment variables in the Python script and I want all the other scripts that are called from Python to see the environment variables' set.
If I do,
os.environ["DEBUSSY"] = 1
it complains saying that 1 has to be a string.
I also want to know how to read the environment variables in Python (in the... | [
"Environment variables must be strings, so use\nimport os\nos.environ[\"DEBUSSY\"] = \"1\"\n\nto set the variable DEBUSSY to the string 1.\nTo access this variable later, simply use\nprint(os.environ[\"DEBUSSY\"])\n\nChild processes automatically inherit the environment of the parent process -- no special action on... | [
1258,
154,
116,
38,
25,
21,
17,
16,
14,
12,
11,
7,
3,
3,
2,
1,
1,
0,
0
] | [] | [] | [
"environment_variables",
"python"
] | stackoverflow_0005971312_environment_variables_python.txt |
Q:
What's the most efficient way to convert a string like "3:00pm" to a Python datetime object?
I have a column of times that are stored as strings. What I would like to do is take "3:00pm" and convert it to a datetime object that's 15:00 (24 hour clock).
I could always write a custom function that parses out the str... | What's the most efficient way to convert a string like "3:00pm" to a Python datetime object? | I have a column of times that are stored as strings. What I would like to do is take "3:00pm" and convert it to a datetime object that's 15:00 (24 hour clock).
I could always write a custom function that parses out the string, identifies whether it's am or pm, and create a mapping, but I was wondering if there's any bu... | [
"Considering the following dataframe as an example\n Time Value\n0 7:00pm 48\n1 8:00pm 48\n2 11:00am 8\n3 5:00pm 8\n4 12:00pm 62\n5 8:00am 41\n6 9:00am 51\n7 7:00pm 70\n8 6:00am 41\n9 5:00am 72\n\nIn order to convert the column Time from 3:00pm to a ... | [
1,
0
] | [] | [] | [
"datetime",
"datetime_format",
"pandas",
"python"
] | stackoverflow_0074223570_datetime_datetime_format_pandas_python.txt |
Q:
Why does an error appear when connecting to the server?
I have such a problem that when I did an http server on sockets (website), everything was fine, but then when I try to connect through the browser, an error pops up.
here is the code:
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_ST... | Why does an error appear when connecting to the server? | I have such a problem that when I did an http server on sockets (website), everything was fine, but then when I try to connect through the browser, an error pops up.
here is the code:
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 5000))
s.listen(9000)
conn, add... | [
"A browser will abort the connection when the server does not send a correct HTTP message.\nHTTP uses carriage return/line feed for line termination. Replace \\n by \\r\\n.\nYour Content-Type header is wrong. It should be \"text/html\".\nYour Content-Length header is wrong. It should match the actual length of the ... | [
0
] | [] | [] | [
"python",
"python_3.x",
"sockets"
] | stackoverflow_0074213190_python_python_3.x_sockets.txt |
Q:
Invoke a external python script from a html code
I have created a button in HTML , i want to invoke a external python script when that button is clicked.
and also pass on some variables into that python script if possible.
which method would be the simplest and fastest.
TIA
I tried flask but that didnt help me, my... | Invoke a external python script from a html code | I have created a button in HTML , i want to invoke a external python script when that button is clicked.
and also pass on some variables into that python script if possible.
which method would be the simplest and fastest.
TIA
I tried flask but that didnt help me, my html code is being hosted on apache. i cannot / shoul... | [
"If you are not using Flask, you can use Django. If you don't want to use Django either, you can use ajax to call the script as Fastnlight has shown above.\nIn case that does not work, you can use \"py-script\". It is like javascript. It is in experimental phase but can do simple tasks in your browser window.\nlink... | [
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0074224139_html_python.txt |
Q:
How to replace selected column in few rows
My dataframe:
import pandas as pd
import numpy as np
df = pd.DataFrame({'c1': [10, 11, 12, 13], 'c2': [100, 110, 120, 130], 'c3': [100, 110, 120, 130], 'c4': ['A', np.nan, np.nan, 'B']})
I need to replace row c2 and c3 from another dataframe using column 'c4'
replacer d... | How to replace selected column in few rows | My dataframe:
import pandas as pd
import numpy as np
df = pd.DataFrame({'c1': [10, 11, 12, 13], 'c2': [100, 110, 120, 130], 'c3': [100, 110, 120, 130], 'c4': ['A', np.nan, np.nan, 'B']})
I need to replace row c2 and c3 from another dataframe using column 'c4'
replacer df:
df_replacer = pd.DataFrame({'c2': [11, 22], '... | [
"I don't see another way to do it without using the merge, maybe you could do something like this :\ndf = df.merge(df_replacer, on='c4', how='left', suffixes=('', '_replacer'))\ndf['c2'] = np.where(df['c2_replacer'].notnull(), df['c2_replacer'], df['c2'])\ndf['c3'] = np.where(df['c3_replacer'].notnull(), df['c3_re... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074224114_pandas_python.txt |
Q:
How to pass special characters in the URL when using selenium in python
My queryUrl variable holds this string
queryUrl = "https://www.coursera.org/search?query=data%20science&index=prod_all_launched_products_term_optimization_skills_test_for_precise_xdp_imprecise_variant&topic=data%20science&entityTypeDescription... | How to pass special characters in the URL when using selenium in python | My queryUrl variable holds this string
queryUrl = "https://www.coursera.org/search?query=data%20science&index=prod_all_launched_products_term_optimization_skills_test_for_precise_xdp_imprecise_variant&topic=data%20science&entityTypeDescription=Courses"
but when i pass it to the driver like this
self.driver.get(queryUr... | [
"using + instead of %20 should work just fine\n"
] | [
1
] | [] | [] | [
"python",
"python_requests",
"selenium",
"web",
"web_scraping"
] | stackoverflow_0074221683_python_python_requests_selenium_web_web_scraping.txt |
Q:
List all environment id in openai gym
How to list all currently registered environment IDs (as they are used for creating environments) in openai gym?
A bit context: there are many plugins installed which have customary ids such as atari, super mario, doom etc.
Not to be confused with game names for atari-py.
A:... | List all environment id in openai gym | How to list all currently registered environment IDs (as they are used for creating environments) in openai gym?
A bit context: there are many plugins installed which have customary ids such as atari, super mario, doom etc.
Not to be confused with game names for atari-py.
| [
"Use envs.registry.all():\nfrom gym import envs\nprint(envs.registry.all())\n\nOut:\n\ndict_values([EnvSpec(Copy-v0), EnvSpec(RepeatCopy-v0), EnvSpec(ReversedAddition-v0), EnvSpec(ReversedAddition3-v0), EnvSpec(DuplicatedInput-v0), EnvSpec(Reverse-v0), EnvSpec(CartPole-v0), ...])\n\nThis returns a large collection ... | [
25,
0
] | [
"You can use this code for listing all environments in gym:\nimport gym\nfor i in gym.envs.registry.all():\n print(i.id)\n\n"
] | [
-1
] | [
"openai_gym",
"python",
"reinforcement_learning"
] | stackoverflow_0048980368_openai_gym_python_reinforcement_learning.txt |
Q:
How to store password in variable?
I have a function that generates a new password everytime I run the program. I want to know if its possible to store the generated password in a variable or function. How can i do this?
code is below:
def generateOTP():
# Declare a string variable
# which stores all strin... | How to store password in variable? | I have a function that generates a new password everytime I run the program. I want to know if its possible to store the generated password in a variable or function. How can i do this?
code is below:
def generateOTP():
# Declare a string variable
# which stores all string
string = '0123456789abcdefghijklmn... | [
"\nbro it's already in you OTP var\n\nimport math, random\ndef generateOTP():\n # Declare a string variable\n # which stores all string\n string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n OTP = \"\"\n length = len(string)\n for i in range(8):\n OTP += string[math.f... | [
0
] | [] | [] | [
"function",
"python",
"python_3.x",
"variables"
] | stackoverflow_0074224113_function_python_python_3.x_variables.txt |
Q:
PyCharm not Recognizing from rest_framework.serializers import ModelSerializer
I am using Pycharm and although I am properly installed pip install djangorestframework I keeping getting an error as if it is not recognized:
I have tried several times but getting the same error and when I tried to install it from th... | PyCharm not Recognizing from rest_framework.serializers import ModelSerializer | I am using Pycharm and although I am properly installed pip install djangorestframework I keeping getting an error as if it is not recognized:
I have tried several times but getting the same error and when I tried to install it from the Pycharm option when I hover over it I get the following error:
| [
"You should specify the virtual environment of your project in Pycharm interpreter settings\n"
] | [
0
] | [] | [] | [
"django_rest_framework",
"pycharm",
"python"
] | stackoverflow_0074216815_django_rest_framework_pycharm_python.txt |
Q:
Cuda.is_available() False on VSCode .ipynb but True on JupyterLab
I want to train a VGG model on a gpu, because I have many images (137 099), and I need the process to go faster.
For this, I have a notebook: test.ipynb, on VSCode. My gpu is on a cluster (SLURM) where I am connected by ssh via remote-ssh with VSCo... | Cuda.is_available() False on VSCode .ipynb but True on JupyterLab | I want to train a VGG model on a gpu, because I have many images (137 099), and I need the process to go faster.
For this, I have a notebook: test.ipynb, on VSCode. My gpu is on a cluster (SLURM) where I am connected by ssh via remote-ssh with VSCode.
I am working with a conda environment env2, Python3.7.12, torch 1.8... | [
"I actually figured it out.\nI had first to create a tunnel, so that I could run my script with a Jupyter kernel using a remote jupyter server. I created the tunnel with:\njupyter notebook --ip localhost --port 3001 --no-browser\n\nThis command gave me an URI:\nhttp://localhost:3001/?token=8afee394ef093456\nThen I ... | [
0
] | [] | [] | [
"gpu",
"jupyter_notebook",
"python",
"pytorch",
"visual_studio_code"
] | stackoverflow_0074183243_gpu_jupyter_notebook_python_pytorch_visual_studio_code.txt |
Q:
How can i left join two columns in pandas keeping both the join columns?
I am using:
df1.merge(df2, on = 'id' , how='left' ,suffixes= ('_df1','_df2'))
The join column however merges into one. i.e. only one id column shows but i would like both the id columns to show so i can see which ids were actually missing/i... | How can i left join two columns in pandas keeping both the join columns? | I am using:
df1.merge(df2, on = 'id' , how='left' ,suffixes= ('_df1','_df2'))
The join column however merges into one. i.e. only one id column shows but i would like both the id columns to show so i can see which ids were actually missing/in common between the two. Unfortunately for my data you can have an ID but the... | [
"one way about it is to use indicator parameter\ndf1.merge(df2, on = 'id' , how='left' ,suffixes= ('_df1','_df2'), indicator=True)\n\nfor my dummy test data it shows like this\n\nID idx _merge\n0 87 1 left_only\n1 87 2 left_only\n2 87 3 left_only\n3 87 4 both\n4 87 5 both\n\n\ndf1.merg... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074223522_pandas_python.txt |
Q:
PermissionError: Operation not permitted, I can't access to my photos library (python)
I know there are a lot of questions like this but I just couldn't get right answers .
I have updated my mac to macOS Catalina, I use Python 3.7.9 with IDLE but I can't access to my photos library.
import os
os.listdir("/Users/me... | PermissionError: Operation not permitted, I can't access to my photos library (python) | I know there are a lot of questions like this but I just couldn't get right answers .
I have updated my mac to macOS Catalina, I use Python 3.7.9 with IDLE but I can't access to my photos library.
import os
os.listdir("/Users/me/Pictures/Photos Library.photoslibrary")
and this raise an error:
Traceback (most recent ca... | [
"Your Python probably doesn't have access to that directory. Maybe go in and set your Visual Studio, Terminal, or xTerm to have full disk access like this article describes.\nhttps://osxdaily.com/2018/10/09/fix-operation-not-permitted-terminal-error-macos/\n"
] | [
0
] | [] | [] | [
"permissions",
"photo",
"python"
] | stackoverflow_0070461671_permissions_photo_python.txt |
Q:
function for choosing some index in a dataframe
i'm doing the exercice of one of the famous dataset classification of cellular phone by price, and this part is the part for standardization of dataset.
but i have to exclude the column of the price to have a data standardization.
how can i do? cause i'm following so... | function for choosing some index in a dataframe | i'm doing the exercice of one of the famous dataset classification of cellular phone by price, and this part is the part for standardization of dataset.
but i have to exclude the column of the price to have a data standardization.
how can i do? cause i'm following some tutorials but i cant understand those first two li... | [
"What mdb.iloc does is to select a portion (segment) of your DataFrame. So the first argument of the [] is the rows you want to select (for example [0:5] would select the first 6 rows), then the second argument would select the columns the same way. So if you do mdb.iloc[:, 0:15] that would select ALL rows (since y... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074224185_dataframe_pandas_python.txt |
Q:
How can u implement a list/array in a sqlalchemy database?
I need to put a list of validViewers into a database. I need each item to have it's own list and I need the lists to be editable.
A:
I made a simple solution that solves the problem.
What I did was made a string and then would edit it using eval in pytho... | How can u implement a list/array in a sqlalchemy database? | I need to put a list of validViewers into a database. I need each item to have it's own list and I need the lists to be editable.
| [
"I made a simple solution that solves the problem.\nWhat I did was made a string and then would edit it using eval in python:\nclass File(db.Model):\n id = db.Column(db.Integer, primary_key = True)\n validViewers = db.Column(db.String())\n\nAnd then to edit it I just woud use eval()\nfile = File.query.filter_... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074224450_python_sqlalchemy.txt |
Q:
Return row number of matching empty cell in Pandas dataframe
I need the row number of a matching cell that is empty: Int64Index([], dtype='int64'). I am receiving an index 0 is out of bounds for axis 0 with size 0 exception.
Print indices of matching elements:
if len(item) < 9:
print(item)
print(df[df['col... | Return row number of matching empty cell in Pandas dataframe | I need the row number of a matching cell that is empty: Int64Index([], dtype='int64'). I am receiving an index 0 is out of bounds for axis 0 with size 0 exception.
Print indices of matching elements:
if len(item) < 9:
print(item)
print(df[df['column name'] == item].index)
Output:
nan
1234
abc
Int64Index([], dt... | [
"Get row number(s) of empty cells in column:\nempty_cells = df[df[column].isna()]\n\nGet row numbers of matching cells, whether empty or not. Credit to this Q&A.\nall_matches = df[df[column].astype(str).map(len) != 9]\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074213751_dataframe_pandas_python_python_3.x.txt |
Q:
What happens if I don't join() a python thread?
I have a query. I have seen examples where developers write something like the code as follows:
import threading
def do_something():
return true
t = threading.Thread(target=do_something)
t.start()
t.join()
I know that join() signals the interpreter to wait till ... | What happens if I don't join() a python thread? | I have a query. I have seen examples where developers write something like the code as follows:
import threading
def do_something():
return true
t = threading.Thread(target=do_something)
t.start()
t.join()
I know that join() signals the interpreter to wait till the thread is completely executed. But what if I do n... | [
"A Python thread is just a regular OS thread. If you don't join it, it still keeps running concurrently with the current thread. It will eventually die, when the target function completes or raises an exception. No such thing as \"thread reuse\" exists, once it's dead it rests in peace.\nUnless the thread is a \"... | [
11,
6,
1
] | [] | [] | [
"multithreading",
"python",
"python_3.x",
"python_multithreading"
] | stackoverflow_0060148137_multithreading_python_python_3.x_python_multithreading.txt |
Q:
How to create new columns with duplicated records and copy some of their column values?
I wonder if there is an easy way to achieve what I want. Basically, I want to remove duplicated data from a DataFrame and store two records in one, creating a new column new_value2 where I will store one value from other record... | How to create new columns with duplicated records and copy some of their column values? | I wonder if there is an easy way to achieve what I want. Basically, I want to remove duplicated data from a DataFrame and store two records in one, creating a new column new_value2 where I will store one value from other record that comply certain condition.
I have a DataFrame where the column key2 can have a duplicate... | [
"If there are at most two duplicate values, you can do groupby.apply\ndef set_value(g):\n if len(g) > 1:\n g.loc[g['value2'].ne('copy'), 'new_value2'] = g.loc[g['value2'].eq('copy'), 'value'].values\n return g[g['value2'].ne('copy')]\n else:\n return g\n\nout = df.groupby('key2').apply(se... | [
1
] | [] | [] | [
"dataframe",
"duplicates",
"pandas",
"python"
] | stackoverflow_0074224377_dataframe_duplicates_pandas_python.txt |
Q:
Remove Last Number of a Integer
I have searched for a few answers and none of them seems to work.
Below is an example but the code does not work and gives errors. I am using Python 2.7.
operationTwo = 91239
operationTwo = operationTwo[:-1]
print(operationTwo)
A:
The code you found which is slicing, works but not... | Remove Last Number of a Integer | I have searched for a few answers and none of them seems to work.
Below is an example but the code does not work and gives errors. I am using Python 2.7.
operationTwo = 91239
operationTwo = operationTwo[:-1]
print(operationTwo)
| [
"The code you found which is slicing, works but not on integers. If you want to use it you can convert the number to str for slicing then convert it back to int. It is not the best practice but it can be done as the following:\noperationTwo = 91239\noperationTwo = int(str(operationTwo)[:-1])\nprint(operationTwo)\n\... | [
13,
8,
0
] | [] | [] | [
"python"
] | stackoverflow_0044265975_python.txt |
Q:
How to make a response not show a reply message
So i created a command that sends a embed with discord.py modals but I ran into a thing that bothered me. How do I send a interaction twice without responding to the first interaction? For example this is what I want it to look like:
I tried to do interaction.follo... | How to make a response not show a reply message | So i created a command that sends a embed with discord.py modals but I ran into a thing that bothered me. How do I send a interaction twice without responding to the first interaction? For example this is what I want it to look like:
I tried to do interaction.followup.send but that didnt work
| [
"In the image you showed it seems they have done something such as the following. This is not the best solution as it requires send messages permissions and not just application commands permissions.\nawait interaction.response.send_message(\"message A\", ephemeral=True)\nawait interaction.channel.send(\"message B\... | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074215685_discord_discord.py_python.txt |
Q:
SQLAlchemy: get Model from table name. This may imply appending some function to a metaclass constructor as far as I can see
I want to make a function that, given the name of a table, returns the model with that tablename.
Eg:
class Model(Base):
__tablename__ = 'table'
...a bunch of Columns
def getModelFr... | SQLAlchemy: get Model from table name. This may imply appending some function to a metaclass constructor as far as I can see | I want to make a function that, given the name of a table, returns the model with that tablename.
Eg:
class Model(Base):
__tablename__ = 'table'
...a bunch of Columns
def getModelFromTableName(tablename):
...something magical
so getModelFromTableName('table') should return the Model class.
My aim is to use... | [
"Inspired by Eevee's comment:\ndef get_class_by_tablename(tablename):\n \"\"\"Return class reference mapped to table.\n\n :param tablename: String with name of table.\n :return: Class reference or None.\n \"\"\"\n for c in Base._decl_class_registry.values():\n if hasattr(c, '__tablename__') and c.__tablenam... | [
56,
15,
12,
7,
5,
1,
1,
1,
0
] | [
"I was going to delete this but I figure that the discussion in the comments might be useful for people who want to know about some good practices. Take this answer with a pinch of salt.\n\nsomething like this does the trick: \ndef getModelFromTableName(sTable):\n \"\"\"\n return the Model class with the give... | [
-1
] | [
"foreign_keys",
"python",
"sqlalchemy"
] | stackoverflow_0011668355_foreign_keys_python_sqlalchemy.txt |
Q:
How to multipy values splited from str in DataFrame, Python?
For example DataFrame:
import pandas as pd
df = pd.DataFrame.from_dict({
'art1':['n1','n2'],
'sizes':['35 36 37', '36 38']
})
print (df)
# need that
df_result = pd.DataFrame.from_dict({
'art1':['n1','n1','n1','n2','n2'],
'sizes':[... | How to multipy values splited from str in DataFrame, Python? | For example DataFrame:
import pandas as pd
df = pd.DataFrame.from_dict({
'art1':['n1','n2'],
'sizes':['35 36 37', '36 38']
})
print (df)
# need that
df_result = pd.DataFrame.from_dict({
'art1':['n1','n1','n1','n2','n2'],
'sizes':[35,36,37,36,38]
})
print (df_result)
BELOW IS CORRECT BU... | [
"You can first split the string column into a list and then you can explode each item in the list into a new row\ndf = pd.DataFrame.from_dict({\n 'art1':['n1','n2'],\n 'sizes':['35 36 37', '36 38']\n })\n\n# convert str to list\ndf['sizes'] = df['sizes'].str.split()\n\n# create one new row per item in list... | [
2
] | [] | [] | [
"dataframe",
"dictionary",
"list",
"python",
"split"
] | stackoverflow_0074224563_dataframe_dictionary_list_python_split.txt |
Q:
Python: Linear Regression of Subsets of Columns
I have a dataset of monthly stock returns that I am trying to regress on market returns by quarter and by company ID (PERMNO). Here's what the data looks like:
date PERMNO MCAP FIRMRF MKTRF qtr
0 2018-01-02 10026 2.784892e+06 -0.0... | Python: Linear Regression of Subsets of Columns | I have a dataset of monthly stock returns that I am trying to regress on market returns by quarter and by company ID (PERMNO). Here's what the data looks like:
date PERMNO MCAP FIRMRF MKTRF qtr
0 2018-01-02 10026 2.784892e+06 -0.017514 0.0085 1
7339 2018-01-03 10026 2.7570... | [
"After a few days of experimenting I've found a solution to the problem. I was able to define a function that contains the OLS regression and then apply it via a groupby function:\n#Pull beta estimates\n#Def Regression func\ndef regress(data, yvar, xvars):\n Y = data[yvar]\n X = sm.add_constant(data[xvars])\n... | [
1
] | [] | [] | [
"finance",
"pandas",
"python",
"regression",
"statsmodels"
] | stackoverflow_0074188735_finance_pandas_python_regression_statsmodels.txt |
Q:
Retrieve non-matching values index and columns between two DataFrames
I am trying to retrieve indexes and columns names of non-matching values between two dfs:
df1:
'A' 'B' 'C'
1 1 5 9
2 2 6 10
3 3 7 11
4 4 8 12
And
df2:
'A' 'B'... | Retrieve non-matching values index and columns between two DataFrames | I am trying to retrieve indexes and columns names of non-matching values between two dfs:
df1:
'A' 'B' 'C'
1 1 5 9
2 2 6 10
3 3 7 11
4 4 8 12
And
df2:
'A' 'B' 'C'
1 1 44 9
2 2 6 10
3 44 ... | [
"You can use:\ns = df1.ne(df2).stack()\n\nout = s[s].index.tolist()\n\n# one-liner version as suggested by @Ynjxsjmh\n# out = df1.ne(df2).stack().loc[lambda s: s].index.tolist()\n\noutput: [(1, 'B'), (3, 'A'), (4, 'C')]\nFor a different order (columns first then rows, if this matters):\ns = df1.ne(df2).unstack()\n\... | [
3
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074224484_dataframe_pandas_python.txt |
Q:
How to check if dict contains a value and skip print?
Hello beautiful people!
Im currently working on a script where I am trying to print out whenever there is a increse in a dict value and print it out once it happens by using this data example:
First request
{
'00194953243062': {
'value': '00194953243062'... | How to check if dict contains a value and skip print? | Hello beautiful people!
Im currently working on a script where I am trying to print out whenever there is a increse in a dict value and print it out once it happens by using this data example:
First request
{
'00194953243062': {
'value': '00194953243062',
'stock': 'OOS',
'modificationDate': '2022-10-22T1... | [
"Use a dictionary that maps the stock strings to a number. Then you can check if the numeric value has increased.\nstock_map = {\n 'oos': 0,\n 'low': 1,\n 'medium': 2,\n 'high': 3\n}\n\n...\n\nelif (any(stock_map[value['stock'].casefold()] > stock_map[previous_data[att]['stock'].casefold()]\n f... | [
1
] | [] | [] | [
"compare",
"dictionary",
"if_statement",
"python",
"python_3.x"
] | stackoverflow_0074223694_compare_dictionary_if_statement_python_python_3.x.txt |
Q:
How to make case insensetive searcn in Django with Postgres
I have a project with Django, Django REST Framework and PostgreSQL.
And my goal to make a search with certain conditions:
logical operators (AND, OR, NOT)
case insensitive
operator like * To search by prefixes. som* -> search for some, somali and so on
... | How to make case insensetive searcn in Django with Postgres | I have a project with Django, Django REST Framework and PostgreSQL.
And my goal to make a search with certain conditions:
logical operators (AND, OR, NOT)
case insensitive
operator like * To search by prefixes. som* -> search for some, somali and so on
My first attempt was to use Postgres full search with this type
s... | [
"Please try:\nSearchQuery(q, search_type='raw', config='english')\nOR\nSearchQuery(q, config='pg_catalog.simple', search_type='raw')\n",
"This article contains more details about search in Django https://docs.djangoproject.com/en/4.0/ref/contrib/postgres/search/\n"
] | [
0,
0
] | [] | [] | [
"django",
"django_rest_framework",
"postgresql",
"python",
"search"
] | stackoverflow_0074184806_django_django_rest_framework_postgresql_python_search.txt |
Q:
python function to count nonzero patches in array
For a given array (1 or 2-dimensional) I would like to know, how many "patches" there are of nonzero elements. For example, in the array [0, 0, 1, 1, 0, 1, 0, 0] there are two patches.
I came up with a function for the 1-dimensional case, where I first assume the m... | python function to count nonzero patches in array | For a given array (1 or 2-dimensional) I would like to know, how many "patches" there are of nonzero elements. For example, in the array [0, 0, 1, 1, 0, 1, 0, 0] there are two patches.
I came up with a function for the 1-dimensional case, where I first assume the maximal number of patches and then decrease that number ... | [
"The following should work:\nimport numpy as np\nimport copy\n\n\n# create an array\nA = np.array(\n [\n [0, 1, 1, 1, 0, 1],\n [0, 0, 1, 0, 0, 0],\n [1, 0, 0, 1, 0, 1],\n [1, 0, 0, 0, 0, 1],\n [0, 0, 1, 0, 0, 1]\n ]\n)\n\ndef isadjacent(pos, newpos):\n \"\"\"\n Check w... | [
2
] | [] | [] | [
"arrays",
"function",
"python"
] | stackoverflow_0074209678_arrays_function_python.txt |
Q:
Rearrange a 5D tensor using einops
I am analyzing the implementation of the ViViT: A Video Vision Transformer. The input tensor of this model has the sahpe of (batch size, num frames, channels=3, H, W). When it comes to patch embedding, it uses the Rearrange that is imported from from einops.layers.torch import R... | Rearrange a 5D tensor using einops | I am analyzing the implementation of the ViViT: A Video Vision Transformer. The input tensor of this model has the sahpe of (batch size, num frames, channels=3, H, W). When it comes to patch embedding, it uses the Rearrange that is imported from from einops.layers.torch import Rearrange as follows:
self.to_patch_emb... | [
"Suppose there is an input tensor of shape (32, 10, 3, 32, 32) representing (batchsize, num frames, channels, height, width).\nb t c (h p1) (w p2) with p1=2 and p2=2 decomposes the tensor to (32, 10, 3, (16, 2), (16, 2))\nb t (h w) (p1 p2 c) composes the decomposed the tensor to (32, 10, 32*32=1024, 2*2*3=12)\n"
] | [
2
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074223784_python_pytorch.txt |
Q:
Write a program to check it the two strings are balanced
I'm trying to write a program to check it the two strings are balanced. For example, s1 and s2 are balanced if all the characters in the s1 are present in s2. My compiler showing correct, but while evaluating in website it's showing error in balance one whil... | Write a program to check it the two strings are balanced | I'm trying to write a program to check it the two strings are balanced. For example, s1 and s2 are balanced if all the characters in the s1 are present in s2. My compiler showing correct, but while evaluating in website it's showing error in balance one while unbalance working.
def balance(s1,s2):
flag=True
if... | [
"Python program to check if two strings are balanced\nWhat does it mean for two strings to be balanced?\nTwo strings are balanced if they have the same set of characters, regardless of their order or frequency. For example, \"abc\" and \"cba\" are balanced, but \"abc\" and \"ab\" are not.\nHow to write a python pro... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074224623_python.txt |
Q:
Pandas cannot open an Excel (.xlsx) file
Please see my code below:
import pandas
df = pandas.read_excel('cat.xlsx')
After running that, it gives me the following error:
Traceback (most recent call last):
File "d:\OneDrive\桌面\practice.py", line 4, in <module>
df = pandas.read_excel('cat.xlsx')
File "D:\pyt... | Pandas cannot open an Excel (.xlsx) file | Please see my code below:
import pandas
df = pandas.read_excel('cat.xlsx')
After running that, it gives me the following error:
Traceback (most recent call last):
File "d:\OneDrive\桌面\practice.py", line 4, in <module>
df = pandas.read_excel('cat.xlsx')
File "D:\python\lib\site-packages\pandas\util\_decorators.... | [
"As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange but still present in the readme on the repo and the release on pypi:\nxlrd has explicitly removed support for anything other than xls files.\nThis i... | [
259,
67,
1,
0,
0
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0065250207_excel_pandas_python.txt |
Q:
How can a python exception be logged to the debug stream?
I want to log stack info from an except block with logging.exceptionor something similar - but I want the output to go to DEBUG, not ERROR. The use case for this is that I want the fact the exception occurred to be reported on one stream, and the stack tra... | How can a python exception be logged to the debug stream? | I want to log stack info from an except block with logging.exceptionor something similar - but I want the output to go to DEBUG, not ERROR. The use case for this is that I want the fact the exception occurred to be reported on one stream, and the stack trace info on another:
import logging
try:
raise RuntimeError... | [
"loggging.debug(traceback.format_exc()) I think is what you are asking for?\n"
] | [
1
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0074224658_logging_python.txt |
Q:
Is there a way to return a result from a walker without reporting it using jaseci
Is there a way to return a result from a walker without reporting it using jaseci.
because when you report stuff in general it queues up in the final report which we don't need.
report: [
{"response": "xyz"}
];
instead of
report: [... | Is there a way to return a result from a walker without reporting it using jaseci | Is there a way to return a result from a walker without reporting it using jaseci.
because when you report stuff in general it queues up in the final report which we don't need.
report: [
{"response": "xyz"}
];
instead of
report: [
"jdsjdbjs",
"dndkfndkfn",
{"response": "xyz"}
];
it messes up with picking out record... | [
"Seems like it would be nice if Jac had some more language features around this but you can check out \"report custom\" support. Its described here https://docs.jaseci.org/docs/docs/Developing_with_JAC/Language_Features/report_custom.html (docs arn't very good atm). Also keep in mind that once you set report:custom... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0074224633_python.txt |
Q:
Tracing code execution in embedded Python interpreter
I'd like to create an application with embedded python interpreter and basic debugging capabilities.
Now I'm searching the API for functions which I could use to run code step-by-step and get the number of the current line of code which is being (or is about to... | Tracing code execution in embedded Python interpreter | I'd like to create an application with embedded python interpreter and basic debugging capabilities.
Now I'm searching the API for functions which I could use to run code step-by-step and get the number of the current line of code which is being (or is about to be) executed.
Official Python docs seem a little underdone... | [
"\nhello.c:5:26: error: unknown type name ‘PyFrameObject’\n\n\nThis error means that PyFrameObject has not been declared. I did a Google search which showed me frameobject.h in the Python source tree is where that structure is declared.\nI expect that you can add the line\n#include <frameobject.h>\n\nto resolve th... | [
9,
0,
0
] | [
"PyFrameObject is just a _frame struct. Just replace PyFrameObject by _frame in your function signature and you won't have to include any additional python headers.\n"
] | [
-1
] | [
"c",
"python",
"python_3.x",
"python_c_api"
] | stackoverflow_0034075757_c_python_python_3.x_python_c_api.txt |
Q:
Convert GraphQLResponse dictionary to python object
I am running a graphql query using aiographql-client and getting back a GraphQLResponse object, which contains a raw dict as part of the response json data.
This dictionary conforms to a schema, which I am able to parse into a graphql.type.schema.GraphQLSchema ty... | Convert GraphQLResponse dictionary to python object | I am running a graphql query using aiographql-client and getting back a GraphQLResponse object, which contains a raw dict as part of the response json data.
This dictionary conforms to a schema, which I am able to parse into a graphql.type.schema.GraphQLSchema type using graphql-core's build_schema method.
I can also c... | [
"I'd recommend using Pydantic to the heavy lifting in the parsing.\nYou can then either generate the models beforehand and select the ones you need based on GraphQLObjectType or generate them at runtime based on the definition returned by build_schema.\nIf you really must define your models at runtime you can do th... | [
0,
0,
0
] | [] | [] | [
"deserialization",
"graphql",
"python"
] | stackoverflow_0073591379_deserialization_graphql_python.txt |
Q:
How to resend verification email django restframework?
I can send a verification email upon registering the user so that the account can be activated. But how would one go about resending another verification email on an API? Here, I am making an activation link with a token in it and when the user opens the link ... | How to resend verification email django restframework? | I can send a verification email upon registering the user so that the account can be activated. But how would one go about resending another verification email on an API? Here, I am making an activation link with a token in it and when the user opens the link it takes the token and verifies the user.
But how would rese... | [
"My work around is asking for the email from the user or frontend, and then query the user to get email address and send it to the email.\nclass ResendVerifyEmail(APIView):\n serializer_class = RegisterSerialzer\n def post(self, request):\n data = request.data\n # email = data.get('email')\n ... | [
2,
0
] | [] | [] | [
"django",
"django_rest_framework",
"django_rest_framework_simplejwt",
"python"
] | stackoverflow_0069150764_django_django_rest_framework_django_rest_framework_simplejwt_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.