content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to perform a keyword search in marqo
i have been searching through documents in marqo by passing a query as an argument to the .search() method but this returns a list of documents from best to least match. i will like to pass a keyword from the document and i should only get the documents that have those keyw... | How to perform a keyword search in marqo | i have been searching through documents in marqo by passing a query as an argument to the .search() method but this returns a list of documents from best to least match. i will like to pass a keyword from the document and i should only get the documents that have those keyword
this is how i currently search:
results = ... | [
"All you have to do is pass another keyword argument search_method=\"LEXICAL\" to the .search() method\nhere is how your code should look like:\nresult = mq.index(\"my-index\").search(q='keyword', search_method=\"LEXICAL\")\n\n"
] | [
3
] | [] | [] | [
"machine_learning",
"marqo",
"python"
] | stackoverflow_0074405390_machine_learning_marqo_python.txt |
Q:
Comparing three data frames to evaluate multiple criteria
I have three dataframes:
ob (Orderbook) - an orderbook containing Part Numbers, the week they are due and the hours it takes to build them.
Part Number
Due Week
Build Hours
A
2022-46
4
A
2022-46
5
B
2022-46
8
C
2022-47
1.6
osm (Operator Skill Matrix)... | Comparing three data frames to evaluate multiple criteria | I have three dataframes:
ob (Orderbook) - an orderbook containing Part Numbers, the week they are due and the hours it takes to build them.
Part Number
Due Week
Build Hours
A
2022-46
4
A
2022-46
5
B
2022-46
8
C
2022-47
1.6
osm (Operator Skill Matrix) - a skills matrix containing operators names and p... | [
"Made with one loop + apply on each line.\nOrderbook.groupby(Orderbook.index) groups by index, i.e. my_func iterates through each row, still better than a loop.\nIn the 'aaa' list, we get a list of unique Operators that match. In the 'bbb' list, filter Avaliable by: 'YYYYWW', 'Operator' (using isin for the list of ... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074391747_dataframe_pandas_python.txt |
Q:
Adding text to text Edit while the loop( while true is running)
I have a while loop which is set to True , inside the loop I want to write some text to TextBrowser but no matter what I try , self.textEdit.setText or self.textEdit.append doesn't work.
I tried to change also label or even line text but without succ... | Adding text to text Edit while the loop( while true is running) | I have a while loop which is set to True , inside the loop I want to write some text to TextBrowser but no matter what I try , self.textEdit.setText or self.textEdit.append doesn't work.
I tried to change also label or even line text but without success.
when I take this out of the while loop the text appear in the te... | [
"I think \"append\" is working, but you need to process pending events and refresh the GUI by calling QApplication.processEvents()\n"
] | [
0
] | [] | [] | [
"multithreading",
"python",
"while_loop"
] | stackoverflow_0074405319_multithreading_python_while_loop.txt |
Q:
How to modify the facecolors of hexbin plots?
I'm looking for a way to fine tune the color of individual cells in a hexbin plot.
I have tried to use the method set_facecolors from PolyCollection to alter the color of an individual cell but this does not appear to work.
Example: this should result in a hexbin with ... | How to modify the facecolors of hexbin plots? | I'm looking for a way to fine tune the color of individual cells in a hexbin plot.
I have tried to use the method set_facecolors from PolyCollection to alter the color of an individual cell but this does not appear to work.
Example: this should result in a hexbin with a red cell in the center:
import numpy as np
import... | [
"Normally, the colors are set via a colormap (hence the C=z parameter in ax.hexbin()). To change individual colors, you need to disable that behavior. That can be achieved by setting the \"array\" of the PolyCollection to None (see also Joe Kington's answer here).\nimport matplotlib.pyplot as plt\nimport numpy as n... | [
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074405187_matplotlib_python.txt |
Q:
Get list of all loaded python packages & versions, and variables
I'm coming from an R background where it was quite easy to figure out for me all of the loaded packages that I was using. I could look to my rstudio tab 'packages' and see checkmarks next to package names and versions for what I had loaded / availab... | Get list of all loaded python packages & versions, and variables | I'm coming from an R background where it was quite easy to figure out for me all of the loaded packages that I was using. I could look to my rstudio tab 'packages' and see checkmarks next to package names and versions for what I had loaded / available.
I could run:
library(dplyr)
x=3;
y=4;
then run to find out the... | [
"\nShow me everything available python package I can import & corresponding versions?\n\nhelp('modules')\nNB: You can also type pip freeze on the command line to see which third-party modules you have installed using pip. (Use python -m pip freeze if you have multiple Python versions and want to be sure you list th... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0056402571_python.txt |
Q:
When i used a timer decorator for multiple processes, the result is wrong
Here is my code.
# this decorator is used to record the running time.
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
stop_time = time.time(... | When i used a timer decorator for multiple processes, the result is wrong | Here is my code.
# this decorator is used to record the running time.
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
stop_time = time.time()
cost_time = stop_time-start_time
print(f'cost time: {cost_tim... | [
"First, as an aside, your timer decorator will not work with functions that return results. You should save the result of calling func and then finally return that result after you print out the timings. Now for your main problem:\nYou have started some number of Process instances in process_list. Let's imagine tha... | [
0
] | [] | [] | [
"decorator",
"multiprocessing",
"python"
] | stackoverflow_0074190470_decorator_multiprocessing_python.txt |
Q:
Why cpython exposes 'PyTuple_SetItem' as C-API if tuple is immutable by design?
Tuple in python is immutable by design, so if we try to mutate a tuple object python emits following TypeError which make sense.
>>> a = (1, 2, 3)
>>> a[0] = 12
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
T... | Why cpython exposes 'PyTuple_SetItem' as C-API if tuple is immutable by design? | Tuple in python is immutable by design, so if we try to mutate a tuple object python emits following TypeError which make sense.
>>> a = (1, 2, 3)
>>> a[0] = 12
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
So my question is, if tupl... | [
"Similarly, there is a PyTuple_Resize function with the warning\n\nBecause tuples are supposed to be immutable, this should only be used\nif there is only one reference to the object. Do not use this if the\ntuple may already be known to some other part of the code. The tuple\nwill always grow or shrink at the end.... | [
10,
3
] | [] | [] | [
"cpython",
"ctypes",
"python",
"python_3.x",
"tuples"
] | stackoverflow_0074405180_cpython_ctypes_python_python_3.x_tuples.txt |
Q:
Filter and print Json output
i am looking for help on printing json data with filters defined.
Below is my actual output but i want to print only fields i need as defined in expecting output below.
{
"response": {
"@status": "success",
"result": {
"enabled": "yes",
"group": {
"mode": "Active-Active"... | Filter and print Json output | i am looking for help on printing json data with filters defined.
Below is my actual output but i want to print only fields i need as defined in expecting output below.
{
"response": {
"@status": "success",
"result": {
"enabled": "yes",
"group": {
"mode": "Active-Active",
"local-info": {
"url-co... | [
"You can filter your output by trying this:\nimport json\n\noutput = {\n \"response\": {\n \"@status\": \"success\",\n \"result\": {\n \"enabled\": \"yes\",\n \"group\": {\n \"mode\": \"Active-Active\",\n \"local-info\": {\n \"url-compat\": \"Match\",\n \"app-version\": \"xxxxxx\",\n \"gpcli... | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074405402_json_python.txt |
Q:
Sorting a list of numbers in Python is not working
I am trying to sort a list of natural numbers in ascending order. I tried the following code:
a = [5,8,3,4,1]
b = a.sort
print(b)
The output I am getting is as follows:
<function list.sort(*, key=None, reverse=False)>
Whereas I was expecting the answer as
[1,3,4... | Sorting a list of numbers in Python is not working | I am trying to sort a list of natural numbers in ascending order. I tried the following code:
a = [5,8,3,4,1]
b = a.sort
print(b)
The output I am getting is as follows:
<function list.sort(*, key=None, reverse=False)>
Whereas I was expecting the answer as
[1,3,4,5,8]
Can anybody tell me what the problem is with the ... | [
"sort() method is sorting in place. The solution is:\na = [5,8,3,4,1]\na.sort()\nprint(a)\n\nI you need a new object, consider using sorted function:\na = [5,8,3,4,1]\nb = sorted(a)\nprint(b)\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074405578_python.txt |
Q:
Sphinx's .. include:: directive and "duplicate label" warnings
I'm trying to use Sphinx's .. include:: directive to include docs from one file in another file, to avoid duplicating the source text of the docs. The section I'm including is in configuration.rst (it's part of the reference docs for the config setting... | Sphinx's .. include:: directive and "duplicate label" warnings | I'm trying to use Sphinx's .. include:: directive to include docs from one file in another file, to avoid duplicating the source text of the docs. The section I'm including is in configuration.rst (it's part of the reference docs for the config settings) and it contains some labels for cross-referencing each config set... | [
"There are two ways to solve this: switch to a different extension (*.inc), or add any include files to exclude_patterns in conf.py.\n",
"Want to add my solution to this:\n.. include:: /configuration.inc.rst\n\nThen glob in exclusions:\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '**/*inc.rst']\n\nThi... | [
13,
0
] | [
"Safe to ignore? It will remain a warning but the original content seems to block the included labels so it shouldn't be too dangerous if you check it from time to time.\nHave you tried putting the content in a file, not indexed with no label, include this file wherever you need it and create a file, indexed, with ... | [
-1
] | [
"python",
"python_sphinx"
] | stackoverflow_0016262163_python_python_sphinx.txt |
Q:
How to construct lambda payload to invoke another lambda?
I have a lambda proxy function (A) working along with API Gateway that I use to store some data in a remote database. I have another lambda function (B) that processes some data and I wish to reuse A to save data in the database.
I am therefore invoking A f... | How to construct lambda payload to invoke another lambda? | I have a lambda proxy function (A) working along with API Gateway that I use to store some data in a remote database. I have another lambda function (B) that processes some data and I wish to reuse A to save data in the database.
I am therefore invoking A from B with a payload. I am able to invoke from B only if I conv... | [
"If Payload contains the data to be shared from function A to function B.\nIn A at the time you invoke function B : it's a string - result of the json.dumps() function.\nSo in B when you process Payload - as it is a string - you can't access to a body index as it were a dict.\nI'm afraid you'll have to do minor cha... | [
0,
0
] | [] | [] | [
"amazon_web_services",
"aws_api_gateway",
"aws_lambda",
"json",
"python"
] | stackoverflow_0074400784_amazon_web_services_aws_api_gateway_aws_lambda_json_python.txt |
Q:
df.rename wont rename a column
Trying to rename a column in a Data frame. I used the same line to rename the column "frames"
I want to rename a column from a "0" to "Grad"
result = pd.concat([table2, tableg3], axis=1)
result.rename(columns = {"0" : "Grad"}, inplace = True)
result
This outputs
A:
"0" - string
0 ... | df.rename wont rename a column | Trying to rename a column in a Data frame. I used the same line to rename the column "frames"
I want to rename a column from a "0" to "Grad"
result = pd.concat([table2, tableg3], axis=1)
result.rename(columns = {"0" : "Grad"}, inplace = True)
result
This outputs
| [
"\"0\" - string\n0 - var\n\nYou havce to use {0 : \"Grad\"}\nresult.rename(columns = {0 : \"Grad\"}, inplace = True)\n\n"
] | [
0
] | [
"Have you tried {0 : \"Grad\"}? What is the output of result.columns?\n"
] | [
-1
] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074405260_dataframe_pandas_python.txt |
Q:
How to convert a decimal number into symbolic representation?
With sympy, I am aware you can you do something like this:
In [37]: sqrt(8) / sqrt(27)
Out[37]: 2*sqrt(6)/9
In [38]: pprint(sqrt(8) / sqrt(27))
2⋅√6
────
9
There is a complex number I would like to represent in the same "symbolic" manner:
In [39]: ... | How to convert a decimal number into symbolic representation? | With sympy, I am aware you can you do something like this:
In [37]: sqrt(8) / sqrt(27)
Out[37]: 2*sqrt(6)/9
In [38]: pprint(sqrt(8) / sqrt(27))
2⋅√6
────
9
There is a complex number I would like to represent in the same "symbolic" manner:
In [39]: z = complex(1,2)
The length:
In [42]: Abs(z)
Out[42]: 1.7320508075... | [
"Don't use the complex type as that can only represent complex numbers using floating point. Instead use SymPy's I:\nIn [1]: from sympy import I\n\nIn [2]: z = 1 + 2*I\n\nIn [3]: z\nOut[3]: 1 + 2⋅ⅈ\n\nIn [4]: abs(z)\nOut[4]: √5\n\nAlso worth noting that sometimes SymPy can convert a float back into a guessed symbol... | [
2
] | [] | [] | [
"complex_numbers",
"python",
"sympy"
] | stackoverflow_0074405308_complex_numbers_python_sympy.txt |
Q:
Python regex query to parse very simple dictionary
I am new to regex module and learning a simple case to extract key and values from a simple dictionary.
the dictionary can not contain nested dicts and any lists, but may have simple tuples
MWE
import re
# note: the dictionary are simple and does NOT contains lis... | Python regex query to parse very simple dictionary | I am new to regex module and learning a simple case to extract key and values from a simple dictionary.
the dictionary can not contain nested dicts and any lists, but may have simple tuples
MWE
import re
# note: the dictionary are simple and does NOT contains list, nested dicts, just these two example suffices for the... | [
"You should not use regex for this job. When the input string is valid Python syntax, you can use ast.literal_eval.\nLike this:\nimport ast\n# ...\nout = ast.literal_eval(d)\n\nNow you have a dictionary object in Python. You can for instance get the key/value pairs in a (dict_items) list:\nprint(out.items())\n\nReg... | [
2,
1
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0074404616_parsing_python.txt |
Q:
How to correctly specify the type of the argument?
I have a ButtonTypes class:
class ButtonTypes:
def __init__(self):
self.textType = "text"
self.callbackType = "callback"
self.locationType = "location"
self.someAnotherType = "someAnotherType"
And a function that should take on... | How to correctly specify the type of the argument? | I have a ButtonTypes class:
class ButtonTypes:
def __init__(self):
self.textType = "text"
self.callbackType = "callback"
self.locationType = "location"
self.someAnotherType = "someAnotherType"
And a function that should take one of the attributes of the ButtonTypes class as an argum... | [
"It sounds like you actually want an Enum:\nfrom enum import Enum\n\nclass ButtonTypes(Enum):\n textType = \"text\"\n callbackType = \"callback\"\n locationType = \"location\"\n someAnotherType = \"someAnotherType\"\n\ndef func(button_type: ButtonTypes):\n # Use button_type\n\nThe enum specifies a cl... | [
2,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074405666_python_python_3.x.txt |
Q:
leading zero causes an exception in the program
i hope you are doing well.
I have a question maybe it is stupid to ask rather than search.
but I looked up for a satisfactory answer.
Why leading zero is not allowed in some language, such as python.
what problems can leading zero produce?
thanks in advance!
A:
Thi... | leading zero causes an exception in the program | i hope you are doing well.
I have a question maybe it is stupid to ask rather than search.
but I looked up for a satisfactory answer.
Why leading zero is not allowed in some language, such as python.
what problems can leading zero produce?
thanks in advance!
| [
"This is not just in Python, many programming languages doesn't allow leading zeros. This is because zero is used to define if number is for example binary or octal base numbers. More about them in Python here.\n"
] | [
0
] | [] | [] | [
"ambiguity",
"integer",
"interpreter",
"math",
"python"
] | stackoverflow_0074405637_ambiguity_integer_interpreter_math_python.txt |
Q:
Appending values corresponding to matching date in different dataframes (in R or Python)
I have following data:
#1. dates of 15 day frequency:
dates = seq(as.Date("2017-01-01"), as.Date("2020-12-30"), by=15)
#2. I have a dataframe containing dates where certain observation is recoded per variable as:
#3. Values c... | Appending values corresponding to matching date in different dataframes (in R or Python) | I have following data:
#1. dates of 15 day frequency:
dates = seq(as.Date("2017-01-01"), as.Date("2020-12-30"), by=15)
#2. I have a dataframe containing dates where certain observation is recoded per variable as:
#3. Values corresponding to dates in #2 as:
What I am trying to do is assign values to respective dates, ... | [
"This code work on the example data you provided.\nDue to loop, it will not be the fastest way out there, but it does the job.\nThe date DataFrames is containing the dates, your data shown in #2. And data is the DataFrames containing the data shown in #3.\n# IMPORT PACKAGES AND LOAD DATA\nimport pandas as pd\nimpor... | [
0,
0
] | [] | [] | [
"dataframe",
"join",
"merge",
"python",
"r"
] | stackoverflow_0074396473_dataframe_join_merge_python_r.txt |
Q:
Selenium geckodriver: profile missing: your firefox profile cannot be loaded
I am using geckodriver in the following code:
import time
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
url = 'https://www.idealista.com/venta-viviendas/barcelona/eixample/la-dreta-de-l-eixample/?or... | Selenium geckodriver: profile missing: your firefox profile cannot be loaded | I am using geckodriver in the following code:
import time
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
url = 'https://www.idealista.com/venta-viviendas/barcelona/eixample/la-dreta-de-l-eixample/?ordenado-por=fecha-publicacion-desc'
options = Options()
options.headless = False
dr... | [
"I have had the same problem. In my case I am using ubuntu 22.04 and the problem is that firefox is installed by default with snap. The solution has been to uninstall firefox and install it without snap.\nHere is a link to do this.\nremove snap firefox and install it as .dev\n",
"TL/DR; Set a custom TMPDIR https:... | [
13,
4,
0
] | [] | [] | [
"geckodriver",
"python",
"selenium"
] | stackoverflow_0072405117_geckodriver_python_selenium.txt |
Q:
How can i find the values that are not names in a pandas column?
I'm working with a dataframe of names from the databases of my company. My current job is to find if some of these values, with in total are more than 3 million, are not names. If they were wrongly registrated, if the softwares of clients registered ... | How can i find the values that are not names in a pandas column? | I'm working with a dataframe of names from the databases of my company. My current job is to find if some of these values, with in total are more than 3 million, are not names. If they were wrongly registrated, if the softwares of clients registered some strange values of error, etc.
Is there a neural network alghoritm... | [
"Try to post some code of your tries so other can help you\n"
] | [
0
] | [] | [] | [
"neural_network",
"pandas",
"python"
] | stackoverflow_0074405826_neural_network_pandas_python.txt |
Q:
ThreadPoolExecutor, Semaphore or max_workers?
trying to implement ThreadPoolExecutor for my current task (thats my firs time using it) i have came to a huge misunderstanding. What is the difference between Semaphore and max_workers? like if I have a pool of tasks to do and I want my code to be dealing with only 3 ... | ThreadPoolExecutor, Semaphore or max_workers? | trying to implement ThreadPoolExecutor for my current task (thats my firs time using it) i have came to a huge misunderstanding. What is the difference between Semaphore and max_workers? like if I have a pool of tasks to do and I want my code to be dealing with only 3 tasks at a time, which of these two approaches shou... | [
"Semaphore: can be released more times than it's acquired, and that will raise its counter above the starting value. Suppose we have to allow at a time 10 members to access the Database and only 4 members are allowed to access Network Connection. To handle such types of requirements we can not use Lock and RLock co... | [
0
] | [] | [] | [
"python",
"threadpoolexecutor"
] | stackoverflow_0074403008_python_threadpoolexecutor.txt |
Q:
Expand DataFrame to complete range of values in groupby
I have a DataFrame that contains objects and items belonging to the objects. Items have additional data (not shown) and multiple items can belong to one object.
df = pd.DataFrame(
{
"object_id": [1, 1, 1, 1, 1, 2, 2, 2],
"item_id": [1, 2, ... | Expand DataFrame to complete range of values in groupby | I have a DataFrame that contains objects and items belonging to the objects. Items have additional data (not shown) and multiple items can belong to one object.
df = pd.DataFrame(
{
"object_id": [1, 1, 1, 1, 1, 2, 2, 2],
"item_id": [1, 2, 4, 4, 5, 1, 1, 2],
"item_count": [6, 6, 6, 6, 6, 3, 3... | [
"here is one way to do it\n# summarize the duplicate item ids and create a new df\n# its needed at this stage to allow us to use reindex later\ndf2=df.groupby(['object_id','item_id','item_count'], as_index=False).size()\n\n# groupby the object_id then applying lambda on the group, \n# set item id as an index, which... | [
1,
1
] | [
"Try this to fill the missing values:\ndf = (df.set_index('item_id')\n .groupby('object_id')['item_count']\n .apply(lambda x: x.reindex(range(x.index.min(), x.index.max() + 1), fill_value=0))\n .reset_index()\n )\n\nThen do the groupby you need on the new df.\nCheck the solution here if I... | [
-1
] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074405388_dataframe_pandas_python.txt |
Q:
Filter dataframe based on the presence of multiple columns in another dataframe
I am curious what is the best practice to do the following:
Let's say I have 2 dataframes:
df1:
A B C D
0 1 2 3 4
1 1 3 5 5
2 1 2 3 4
3 3 5 6 7
4 9 7 6 5
df2:
A B C
0 1 2 3
1 9 7 6
I want to filte... | Filter dataframe based on the presence of multiple columns in another dataframe | I am curious what is the best practice to do the following:
Let's say I have 2 dataframes:
df1:
A B C D
0 1 2 3 4
1 1 3 5 5
2 1 2 3 4
3 3 5 6 7
4 9 7 6 5
df2:
A B C
0 1 2 3
1 9 7 6
I want to filter down df1 on columns A, B, C to only show records which are present in df2's A,B,C c... | [
"Merge on inner\nimport pandas as pd\ndf1 = pd.DataFrame(\n {\n \"A\": [1, 1, 1,3,9],\n \"B\": [2,3,2,5,7],\n \"C\": [3,5,3,6,6],\n \"D\": [4,5,4,7,5]\n }\n)\n\ndf2 = pd.DataFrame(\n {\n \"A\": [1, 9],\n \"B\": [2,7],\n \"C\": [3,6],\n \n }\n)\n\n... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074405188_dataframe_pandas_python.txt |
Q:
What am I doing wrong with my tic-tac-toe game?
I’m making a game similar to tic-tac-toe, called strikes and circles. The most noticeable difference is that the board is 4 by 4, rather than 3 by 3. (I am a beginner with coding in Python so please bear with me.) I took a chunk of code from an online post that lets ... | What am I doing wrong with my tic-tac-toe game? | I’m making a game similar to tic-tac-toe, called strikes and circles. The most noticeable difference is that the board is 4 by 4, rather than 3 by 3. (I am a beginner with coding in Python so please bear with me.) I took a chunk of code from an online post that lets you make a tic-tac-toe board, and altered it to make ... | [
"What you are doing is wrong. You are trying to do ['a2'] and so on which returns nothing but a list. What you expect is the value of the a2 key from the board variable. Therefore, it needs to be changed to board['a2']\nTry this:\ndef printboard(board):\n print(board['a1']+'|'+board['a2']+'|'+board['a3']+'|'+boa... | [
0
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0074405820_error_handling_python.txt |
Q:
I can't install install firebase-admin
I've got an error following:
MacBook-Air:Firebase takeyuki$ python -m pip install --upgrade firebase-admin
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future versi... | I can't install install firebase-admin | I've got an error following:
MacBook-Air:Firebase takeyuki$ python -m pip install --upgrade firebase-admin
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
... | [
"Could you try the following steps?\npip install --upgrade --force-reinstall pip==20.0.0\npip install futures --disable-pip-version-check\npip install --upgrade pip\n\nAnother option is to work in a virtualenv:\npip install virtualenv\nvirtualenv -p python venv\nsource venv/bin/activate\npython pip install firebase... | [
3,
0
] | [] | [] | [
"anaconda",
"firebase",
"firebase_admin",
"python",
"python_2.7"
] | stackoverflow_0060333183_anaconda_firebase_firebase_admin_python_python_2.7.txt |
Q:
How can I sort a string list in Python with two criterias at the same time?
Given I have a string list in Python:
list = [" banana ", "Cherry", "apple"]
I want to sort this list to be case insensitive AND ignore the whitespaces. So like this:
list = ["apple", " banana ", "Cherry"]
If I use this:
sorted(l... | How can I sort a string list in Python with two criterias at the same time? | Given I have a string list in Python:
list = [" banana ", "Cherry", "apple"]
I want to sort this list to be case insensitive AND ignore the whitespaces. So like this:
list = ["apple", " banana ", "Cherry"]
If I use this:
sorted(list, key=str.casefold)
I get this:
list = [" banana ", "apple", "Cherry"]
I... | [
"You can use str.strip() for removing spaces from the beginning and end of string and use str.casefold() for caseless sorting.\nlst = [\" banana \", \"Cherry\", \"apple\"]\n\nres = sorted(lst, key=lambda x: x.strip().casefold())\n\nprint(res)\n\nOutput:\n['apple', ' banana ', 'Cherry']\n\n",
"Just chain t... | [
4,
3
] | [] | [] | [
"list",
"python",
"sorting",
"string"
] | stackoverflow_0074405878_list_python_sorting_string.txt |
Q:
How to remove multiple items from a list in just one statement?
In python, I know how to remove items from a list:
item_list = ['item', 5, 'foo', 3.14, True]
item_list.remove('item')
item_list.remove(5)
The above code removes the values 5 and 'item' from item_list.
But when there is a lot of stuff to remove, I ha... | How to remove multiple items from a list in just one statement? | In python, I know how to remove items from a list:
item_list = ['item', 5, 'foo', 3.14, True]
item_list.remove('item')
item_list.remove(5)
The above code removes the values 5 and 'item' from item_list.
But when there is a lot of stuff to remove, I have to write many lines of:
item_list.remove("something_to_remove")
I... | [
"In Python, creating a new object e.g. with a list comprehension is often better than modifying an existing one:\nitem_list = ['item', 5, 'foo', 3.14, True]\nitem_list = [e for e in item_list if e not in ('item', 5)]\n\n... which is equivalent to:\nitem_list = ['item', 5, 'foo', 3.14, True]\nnew_list = []\nfor e in... | [
246,
41,
2,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0036268749_list_list_comprehension_python.txt |
Q:
ModuleNotFoundError: No module named 'dask_xgboost'
I am trying to run dask_ml functions but the system does not accept my installation and gives and error when I import it. OS: Linux ubuntu 20.
Installation to conda environment
conda install -c conda-forge dask-ml
Import
#dask
from dask_ml.xgboost import XGBClas... | ModuleNotFoundError: No module named 'dask_xgboost' | I am trying to run dask_ml functions but the system does not accept my installation and gives and error when I import it. OS: Linux ubuntu 20.
Installation to conda environment
conda install -c conda-forge dask-ml
Import
#dask
from dask_ml.xgboost import XGBClassifier
ERROR
-------------------------------------------... | [
"If you have only installed some parts of dask you may also need to install xgboost separately to anaconda\nconda install -c conda-forge dask-xgboost\n\n",
"Actually, it seems you need to install other parts like dask-xgboost later. Even if you have already installed dask[\"complete\"] and dask-ml.\nBesides conda... | [
2,
1
] | [] | [] | [
"anaconda",
"conda",
"dask",
"dask_ml",
"python"
] | stackoverflow_0064540731_anaconda_conda_dask_dask_ml_python.txt |
Q:
Morse Code Program not handling test cases with spaces
I am doing this Problem set on Code Wars. I have already completed the basic Morse Code Functionality, but I am not finding ways around some other test cases.
The code tested Correct for 8/12 test cases. How can I test for a longer sentence like "The Brown Qui... | Morse Code Program not handling test cases with spaces | I am doing this Problem set on Code Wars. I have already completed the basic Morse Code Functionality, but I am not finding ways around some other test cases.
The code tested Correct for 8/12 test cases. How can I test for a longer sentence like "The Brown Quick Fox Jumped over the lazy dog", a test case for "E E", and... | [
"The problem is that with morse_code.find(\" \") you will only find the index of the first double space. There is no guarantee that your input will only contain two words. You need to also detect any other double spaces in the input string. \nSecondly, dividing this position by 3.5 is unreliable to know where to i... | [
1,
0,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0059179747_algorithm_python.txt |
Q:
Filter a pandas dataframe based on value in a list of dictionary in column
Hi a pandas data frame and one of its columns its a list of dictionaries. See below:
Example for the first row
df.iloc[0].colexample
[{'status': 'married',
'date': datetime.datetime(2022, 10, 1, 6, 27, 31, 118000)},
{'status': 'divorce... | Filter a pandas dataframe based on value in a list of dictionary in column | Hi a pandas data frame and one of its columns its a list of dictionaries. See below:
Example for the first row
df.iloc[0].colexample
[{'status': 'married',
'date': datetime.datetime(2022, 10, 1, 6, 27, 31, 118000)},
{'status': 'divorced',
'date': datetime.datetime(2022, 10, 1, 6, 27, 52, 47000)},
{'status': 'se... | [
"you can use:\ndf['check']=df['colexample'].apply(lambda x: True if any(i in ['other','sent'] for i in [item for sublist in [[list(i.values()) for i in x]][0]for item in sublist]) else False)\ndf=df[df['check']==True]\n\nDetails:\n#for each row it loops through the list and takes all the values in dictionary and ... | [
1
] | [] | [] | [
"apply",
"dictionary",
"list",
"pandas",
"python"
] | stackoverflow_0074405022_apply_dictionary_list_pandas_python.txt |
Q:
Python threading event object - How to notify specific thread?
I have multiple threads that uses an event object to wait with a timeout. If I wanted to call set() on the event, this would unblock all of the threads. What would be a good way to unblock a specific thread, and leave the other threads in a waiting sta... | Python threading event object - How to notify specific thread? | I have multiple threads that uses an event object to wait with a timeout. If I wanted to call set() on the event, this would unblock all of the threads. What would be a good way to unblock a specific thread, and leave the other threads in a waiting state?
I've thought about instead of waiting, each thread would have a ... | [
"you can create an event for each thread, or a group of threads, just pass it as argument to them or store it somewhere.\nimport threading\nimport time\n\ndef startTimeout(event):\n check = event.wait(1)\n if (check):\n print('pass')\n else:\n print(\"didn't pass\")\n\ntimeoutEvent1 = threading.Event()\nti... | [
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0074405721_multithreading_python.txt |
Q:
How do you pass in another object of the same type as a method parameter in python?
I am creating a class in python to represent a three-dimensional point (I know there are libraries to do this, it's more of an exercise in classes). One type of method I wish to have is one which can add the coordinates of one poin... | How do you pass in another object of the same type as a method parameter in python? | I am creating a class in python to represent a three-dimensional point (I know there are libraries to do this, it's more of an exercise in classes). One type of method I wish to have is one which can add the coordinates of one point to another. I've tried doing this by passing the other point as a parameter in the meth... | [
"The problem is that you're defining crd as a static property on Point. This means that all instances of Point share the same list crd. To fix this, create a constructor (__init__()) and define self.crd there. Like this:\nclass Point:\n def __init__(self):\n self.crd = [0, 0, 0]\n\n def add_vector(self... | [
2
] | [] | [] | [
"methods",
"object",
"pass_by_reference",
"pass_by_value",
"python"
] | stackoverflow_0074405893_methods_object_pass_by_reference_pass_by_value_python.txt |
Q:
Logic on serializer fields
I am trying to work out how to run some logic to get certain objects from within my serializer (or elsewhere).
I have the following:
class Parent(models.Model):
name = models.CharField(max_length=255)
class Child(models.Model):
name = models.CharField(max_length=255)
parent ... | Logic on serializer fields | I am trying to work out how to run some logic to get certain objects from within my serializer (or elsewhere).
I have the following:
class Parent(models.Model):
name = models.CharField(max_length=255)
class Child(models.Model):
name = models.CharField(max_length=255)
parent = models.ForeignKey(
Pa... | [
"You can use to_representation method\nclass ParentSerializer(serializers.ModelSerializer):\n children = ChildSerializer()\n\n def to_representation(self, instance):\n data = super().to_representation(instance=instance)\n first_child = instance.children.order_by(\"name\").first()\n data[\... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074405484_django_django_rest_framework_python.txt |
Q:
How to reset cooldown discord.py
I want to reset command cooldown (for slash commands)
@client.tree.command(name="my_command")
@app_commands.checks.cooldown(1, 15, key=lambda i: (i.guild_id, i.user.id))
async def my_command(interaction: discord.Interaction):
i = 1
if i == 1:
await interaction.respo... | How to reset cooldown discord.py | I want to reset command cooldown (for slash commands)
@client.tree.command(name="my_command")
@app_commands.checks.cooldown(1, 15, key=lambda i: (i.guild_id, i.user.id))
async def my_command(interaction: discord.Interaction):
i = 1
if i == 1:
await interaction.response.send_message("Cooldown shouldn't a... | [
"This should work:\n@client.tree.command(name=\"my_command\")\n@app_commands.checks.cooldown(1, 15, key=lambda i: (i.guild_id, i.user.id))\nasync def my_command(interaction: discord.Interaction):\n i = 1\n if i == 1:\n await interaction.response.send_message(\"Cooldown shouldn't apply\")\n my_co... | [
0
] | [] | [] | [
"discord",
"discord.py",
"nextcord",
"pycord",
"python"
] | stackoverflow_0074405958_discord_discord.py_nextcord_pycord_python.txt |
Q:
Dataframe column becomes entirely Nan even though no changes made
I am working on the classical titanic dataset in kaggle and there are four dataframes in my project the test and training set and their copys to perform some operations on them. So my problem is even though I make the same operations on my test and... | Dataframe column becomes entirely Nan even though no changes made | I am working on the classical titanic dataset in kaggle and there are four dataframes in my project the test and training set and their copys to perform some operations on them. So my problem is even though I make the same operations on my test and train datasets my test datasets "Cabin" column becomes Nan. I couldn't... | [
"In you question there are multiple topics, which are important and I want to go through it step by step.\nPointer\nIt is important to understand what pointers in python are.\nHere is a small example, where the list in variable a is assinged to b. If you change a, b changes, too.\na = [0,1]\nb = a # this is not a c... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074394430_dataframe_pandas_python.txt |
Q:
How can I execute a function in a running python app from another python file with arguments?
I want to have a python application (app1) running that loads a bunch of data and functionality on start-up that I will use many many times. To avoid having to restart the application and re-load all that I would like to ... | How can I execute a function in a running python app from another python file with arguments? | I want to have a python application (app1) running that loads a bunch of data and functionality on start-up that I will use many many times. To avoid having to restart the application and re-load all that I would like to simply call a function inside that file whenever it is needed from another python application (app2... | [
"Have a look at this:\nhttps://docs.python.org/3/library/importlib.html#importing-programmatically\nI believe you're working in a decoupled modules mode, usually done with real-time applications and sometimes with GUI. I used to trigger the import and execution (in __main__) separate script by clicking a button in ... | [
0,
0
] | [] | [] | [
"interprocess",
"python"
] | stackoverflow_0074361396_interprocess_python.txt |
Q:
Parallel querying indices for a list of filter expressions in polars dataframe
I want to get the indices for a list of filters in polars and get a sparse matrix from it, how can I parallel the process? This is what I have right now, a pretty naive and brute force way for achieving what I need, but this is having s... | Parallel querying indices for a list of filter expressions in polars dataframe | I want to get the indices for a list of filters in polars and get a sparse matrix from it, how can I parallel the process? This is what I have right now, a pretty naive and brute force way for achieving what I need, but this is having some serious performance issue
def get_sparse_matrix(exprs: list[pl.Expr]) -> scipy.s... | [
"So I am not completely sure what exactly you want, but I hope that satisfies your needs\nimport polars as pl\nfrom scipy.sparse import csc_matrix\nimport numpy as np\n\ndf = pl.DataFrame(\n [[1,2,3,4,5,6,7,8], \n [3,4,5,6,7,8,9,10], \n [5,6,7,8,9,10,11,12],\n [5,6,41,8,21,10,51,12],\n])\n\n\nexprs = [(... | [
2,
1
] | [] | [] | [
"data_science",
"pandas",
"python",
"python_polars",
"scipy"
] | stackoverflow_0074398053_data_science_pandas_python_python_polars_scipy.txt |
Q:
Matrix Inverse broadcasting
I am trying to calculate Rij = Aij * Bij/Cij by Numpy broadcasting.
B1 * np.linalg.inv(C1) gives a singular matrix error.
I have also tried doing this. It gave me some values but I am not super sure if it is correct.
D = B1 / C1[..., None]
import numpy as np
from numpy.linalg import inv... | Matrix Inverse broadcasting | I am trying to calculate Rij = Aij * Bij/Cij by Numpy broadcasting.
B1 * np.linalg.inv(C1) gives a singular matrix error.
I have also tried doing this. It gave me some values but I am not super sure if it is correct.
D = B1 / C1[..., None]
import numpy as np
from numpy.linalg import inv
A = [[(i+j)/2000 for i in rang... | [
"you want to do element-wise matrix multiplication and division, the normal * and / operators do the element-wise operation.\nnumpy @ operator does matrix product as studied in any algebra course, and dividing by the inv of the matrix actually compute the matrix inverse which is not an element-wise divsion.\nyou ju... | [
1
] | [] | [] | [
"array_broadcasting",
"inverse",
"matrix",
"numpy",
"python"
] | stackoverflow_0074405938_array_broadcasting_inverse_matrix_numpy_python.txt |
Q:
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
What do *args and **kwargs mean?
def foo(x, y, *args):
def bar(x, y, **kwargs):
A:
The *args and **kwargs is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in th... | What does ** (double star/asterisk) and * (star/asterisk) do for parameters? | What do *args and **kwargs mean?
def foo(x, y, *args):
def bar(x, y, **kwargs):
| [
"The *args and **kwargs is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.\nThe *args will give you all function parameters as a tuple:\ndef foo(*args):\n for a in args:\n print(a) \n\nfoo(1)\n# 1... | [
3034,
787,
211,
204,
64,
47,
31,
27,
25,
21,
18,
14,
11,
11,
9,
8,
5,
4,
3,
3,
2,
2,
0,
0,
0
] | [] | [] | [
"argument_unpacking",
"parameter_passing",
"python",
"syntax",
"variadic_functions"
] | stackoverflow_0000036901_argument_unpacking_parameter_passing_python_syntax_variadic_functions.txt |
Q:
IntegrityError at /admin/base/client/1/delete/ on django
when I try deleting an object from the admin panel in my django app in the database it raises an exception that reads:
IntegrityError at /admin/base/client/1/delete/
FOREIGN KEY constraint failed
I have looked it up and couldn't find the reason to why this... | IntegrityError at /admin/base/client/1/delete/ on django | when I try deleting an object from the admin panel in my django app in the database it raises an exception that reads:
IntegrityError at /admin/base/client/1/delete/
FOREIGN KEY constraint failed
I have looked it up and couldn't find the reason to why this is happening...
here is the model in models.py:
class Client(... | [
"I figured out the problem.\nI had another model that had the Client model's client.name attribute as its __str__ method. removed it from there and the problem was solved.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074405345_django_python.txt |
Q:
Import JSON Lines into Pandas
I want to import a JSON lines file into pandas. I tried to import it like a regular JSON file, but it did not work:
js = pd.read_json (r'C:\Users\Name\Downloads\profilenotes.jsonl')
A:
This medium article provides a fairly simple answer, which can be adapted to be even shorter. All ... | Import JSON Lines into Pandas | I want to import a JSON lines file into pandas. I tried to import it like a regular JSON file, but it did not work:
js = pd.read_json (r'C:\Users\Name\Downloads\profilenotes.jsonl')
| [
"This medium article provides a fairly simple answer, which can be adapted to be even shorter. All you need to do is read each line then parse each line with json.loads(). Like this:\nimport json\nimport pandas as pd\n\n\nlines = []\nwith open(r'test.jsonl') as f:\n lines = f.read().splitlines()\n\nline_dicts = ... | [
2
] | [] | [] | [
"dataframe",
"jsonlines",
"pandas",
"python"
] | stackoverflow_0074406021_dataframe_jsonlines_pandas_python.txt |
Q:
Is there anyway to get one client_id and client_secret for all the sites of the companies sharepoint?
I am trying to get the excel content from the SharePoint site using client_id and client_secret. But I want to read the excel content from more than 100 sites under companies' SharePoint. Do I need to create them ... | Is there anyway to get one client_id and client_secret for all the sites of the companies sharepoint? | I am trying to get the excel content from the SharePoint site using client_id and client_secret. But I want to read the excel content from more than 100 sites under companies' SharePoint. Do I need to create them for all the sites separately or Is there any way to get the universal client_id and client_secret for all t... | [
"If you are using a Sharepoint Online tenant, you could utilize the Azure-App Only context in order to have a client have access to the entire SharePoint Tenant.\nBasically, you would have to create an app registration with the below setting:\n\nNext you would have to use a Python wrapper library to create a Client... | [
0
] | [] | [] | [
"office365",
"python",
"sharepoint"
] | stackoverflow_0074377918_office365_python_sharepoint.txt |
Q:
OS dependencies and compatibility of python-pptx module
I'm running Python 3.6 on Ubuntu 18.06. I wanted to know about python-pptx module's OS dependencies rather than Python dependency as I need to launch the functionality on a server after developing a model on either Ubuntu 18.04 or 20.04. I looked into the doc... | OS dependencies and compatibility of python-pptx module | I'm running Python 3.6 on Ubuntu 18.06. I wanted to know about python-pptx module's OS dependencies rather than Python dependency as I need to launch the functionality on a server after developing a model on either Ubuntu 18.04 or 20.04. I looked into the documentation of the module but the information needed is not pr... | [
"yes, python-pptx will work on Ubuntu\n"
] | [
0
] | [] | [] | [
"powerpoint",
"python",
"python_pptx",
"ubuntu",
"ubuntu_18.04"
] | stackoverflow_0074357478_powerpoint_python_python_pptx_ubuntu_ubuntu_18.04.txt |
Q:
LSTM predicts mean value, how to solve this?
EDIT:
Thank you guys for all your input, I'm not sure if the case is resolved but it seems so.
In my former Data preparation function I have shuffled the training sequences, which resulted in LSTM predicting an average.
I was browsing the internet and I have found by ac... | LSTM predicts mean value, how to solve this? | EDIT:
Thank you guys for all your input, I'm not sure if the case is resolved but it seems so.
In my former Data preparation function I have shuffled the training sequences, which resulted in LSTM predicting an average.
I was browsing the internet and I have found by accident that other people do not shuffle their data... | [
"Your best bet is probably creating smaller models, like simple deep neural networks with very little neurons (< 50) and seeing how good it gets, iterate with diffrent learning rates, like a lot.\nadding komplexity rarely helps when developing a model from scratch ..\nonce you have a simple working model, adding ko... | [
1,
1
] | [] | [] | [
"keras",
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0074404427_keras_neural_network_python_tensorflow.txt |
Q:
How to get the direct link to a youtube video in the mp3 format in Python?
I am currently trying to find out how to get the direct link to the youtube video in mp3 format without downloading it on a computer, so I just need to get the link leading to the internet mp3 file. I tried to do it by the youtube_dl librar... | How to get the direct link to a youtube video in the mp3 format in Python? | I am currently trying to find out how to get the direct link to the youtube video in mp3 format without downloading it on a computer, so I just need to get the link leading to the internet mp3 file. I tried to do it by the youtube_dl library in Python.
My code:
import youtube_dl
link = 'https://www.youtube.com/watch?v=... | [
"YouTube has never had audio-only video formats with MP3 audio, and haven't had mixed (audio+video) formats with MP3 audio for years.\nYour options are:\n\nNot use mp3. An obvious one, but pretty much anything supports mp4a these days, and lots support opus. (If you plan to use it in a browser, here are the stats f... | [
1
] | [] | [] | [
"mp3",
"python",
"python_3.x",
"youtube",
"youtube_dl"
] | stackoverflow_0074286297_mp3_python_python_3.x_youtube_youtube_dl.txt |
Q:
sorting single row dataframe by column values
I have to sort columns in single row dataframe by descending order.
dataframe looks like:
store_1 store_2 store_3
0 11 54 28
result should be like:
store_2 store_3 store_1
0 54 28 11
dataframe has more than sixty columns.... | sorting single row dataframe by column values | I have to sort columns in single row dataframe by descending order.
dataframe looks like:
store_1 store_2 store_3
0 11 54 28
result should be like:
store_2 store_3 store_1
0 54 28 11
dataframe has more than sixty columns.
| [
"This should work:\ndf.sort_values(by=0,axis=1) \n\nwhere by indicates the label or index of the row, and axis = 1 indicates you want to sort the columns!\n",
"You can use the pandas.Series.sort_values:\nimport pandas as pd\n\ndf = pd.DataFrame(data=[[11,54,28]], columns=['store_1', 'store_2', 'store_3'])\ndf = d... | [
0,
0
] | [] | [] | [
"dataframe",
"python",
"sorting"
] | stackoverflow_0074406157_dataframe_python_sorting.txt |
Q:
unsupported operand type(s) for &: 'str' and 'int' python
I have an lsb steganography function to hide messages that have been modulated into audio. the results of the modulation are binary numbers 1 and 0. when I run the function I get an error:
unsupported operand type(s) for &: 'str' and 'int'
here's my code:... | unsupported operand type(s) for &: 'str' and 'int' python | I have an lsb steganography function to hide messages that have been modulated into audio. the results of the modulation are binary numbers 1 and 0. when I run the function I get an error:
unsupported operand type(s) for &: 'str' and 'int'
here's my code:
def lsb(bineraudio, binermod):
# bineraudio = 000000000000... | [
"bineraudio and binermod are both strings, like \"01010101...\", which is how you're able to index them and iterate over them. However, bitwise operations (like &, |, <<, >>, and so on) take numeric values. So, once you get the bit you're interested in (bineraudio[i]), try simply casting it to an int by calling int... | [
0
] | [] | [] | [
"audio",
"binary",
"lsb",
"python",
"steganography"
] | stackoverflow_0074406188_audio_binary_lsb_python_steganography.txt |
Q:
Python - yfinance library JSONDecodeError when downloading
I run
import yfinance as yf
df = yf.Ticker("NOK").history(start_date="2020-11-30", end_date="2021-09-30", interval="1h")
which returns
---------------------------------------------------------------------------
JSONDecodeError Tr... | Python - yfinance library JSONDecodeError when downloading | I run
import yfinance as yf
df = yf.Ticker("NOK").history(start_date="2020-11-30", end_date="2021-09-30", interval="1h")
which returns
---------------------------------------------------------------------------
JSONDecodeError Traceback (most recent call last)
<ipython-input-15-c5289e094c7b> ... | [
"I think there's an error with how you're installing the yfinance module.\nThe following lines setup a virtual environment with yfinance installed for ubuntu 20.04. (let me know if you're on something else only minor differences)\npython3 -m venv venv\nsource venv/bin/activate\npip install yfinance\n\nAfter that th... | [
1
] | [] | [] | [
"python",
"yfinance"
] | stackoverflow_0074406190_python_yfinance.txt |
Q:
Getting incorrect title in the URL path Django
I have an app with a bunch of POST request on a path that looks like this:
path("auctions/<str:title>", views.listing, name="listing")
It's a sort of auction app, where users can create listings, and others can place bids and purchase these items.
When a user clicks ... | Getting incorrect title in the URL path Django | I have an app with a bunch of POST request on a path that looks like this:
path("auctions/<str:title>", views.listing, name="listing")
It's a sort of auction app, where users can create listings, and others can place bids and purchase these items.
When a user clicks on one of these items, ive got this function that ta... | [
"You should use url tags in action instead of action='listing' so:\n<form action=\"{% url 'listing' listing_object.title %}\" method=\"POST\">\n {% csrf_token %}\n <input class=\"btn btn-primary\" type=\"submit\" value=\"Close Listing\" name=\"close\">\n</form>\n\n\nNote: Always add / at the e... | [
3
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"django_urls",
"python"
] | stackoverflow_0074406144_django_django_forms_django_templates_django_urls_python.txt |
Q:
How to to graph multiple lines using sns.scatterplot
I have written a program like so:
# Author: Evan Gertis
# Date : 11/09
# program: Linear Regression
# Resource: https://seaborn.pydata.org/generated/seaborn.scatterplot.html
import seaborn as sns
import pandas as pd
import logging
logging.basicConfig(lev... | How to to graph multiple lines using sns.scatterplot | I have written a program like so:
# Author: Evan Gertis
# Date : 11/09
# program: Linear Regression
# Resource: https://seaborn.pydata.org/generated/seaborn.scatterplot.html
import seaborn as sns
import pandas as pd
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(m... | [
"The origin of the problem is that the columns names in your file are the same and thus when pandas read the columns adds number to the loaded data frame\nimport seaborn as sns\nimport pandas as pd\nimport logging\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n\ngrades... | [
3,
1
] | [] | [] | [
"python",
"seaborn"
] | stackoverflow_0074402704_python_seaborn.txt |
Q:
Adding an element from a list before and after the delimiter of another list
There are 2 lists and my goal is to add the element from one list before and after the delimiters of another list.
Below is the example:
ListA = ["A", "B"]
ListB = [[1, 2, 3, 4], [5, 6, 7, 8]]
Expected Output:
[[1, 'A', 2, 'A', 3, 'A', 4... | Adding an element from a list before and after the delimiter of another list | There are 2 lists and my goal is to add the element from one list before and after the delimiters of another list.
Below is the example:
ListA = ["A", "B"]
ListB = [[1, 2, 3, 4], [5, 6, 7, 8]]
Expected Output:
[[1, 'A', 2, 'A', 3, 'A', 4, 'A'], [5, 'B', 6, 'B', 7, 'B', 8, 'B']]
What I've done so far:
for x, y in zip(... | [
"Your code appends 'A' once to the whole [1,2,3,4] list.\nThis should work:\nListA = ['A','B']\nListB = [[1,2,3,4],[5,6,7,8]]\n\nfor x, y in zip(ListB, ListA):\n for i in range(len(x)):\n x.insert(2*i+1,y)\n\nprint(ListB)\n# [[1, 'A', 2, 'A', 3, 'A', 4, 'A'], [5, 'B', 6, 'B', 7, 'B', 8, 'B']]\n\nA variant... | [
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074404871_list_python.txt |
Q:
ReportLab: LayoutError when content of cell too long for a page
I'm trying to create a table with 7 cols. The last column contains a long text which seems to create the error. It seems that when the cells exceeds the size of the page, it throws an exception.
from reportlab.lib.pagesizes import landscape, A4
from r... | ReportLab: LayoutError when content of cell too long for a page | I'm trying to create a table with 7 cols. The last column contains a long text which seems to create the error. It seems that when the cells exceeds the size of the page, it throws an exception.
from reportlab.lib.pagesizes import landscape, A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypu... | [
"This problem is usually solved by format the content as a flowable Paragraphs (with a defined paragraph style), otherwise the text is not aware if it should wrap or not. Many times it is a conflict of what the formatting within a table will do with a text. Above problem is RL throwing an error as it has not been t... | [
1,
0
] | [] | [] | [
"pdf",
"python",
"reportlab"
] | stackoverflow_0034636424_pdf_python_reportlab.txt |
Q:
Calculate dataframe profit between pairs of string events
I have
event b
0 buy 4
1 nan
2 sell 5
3 buy 3
4 nan
5 nan
6 nan
7 sell 9
After each buy we have a sell at some unknown distance.
I need to count how many times I had a profit.
In this case, first deal earn 1 (5-4), and second dea... | Calculate dataframe profit between pairs of string events | I have
event b
0 buy 4
1 nan
2 sell 5
3 buy 3
4 nan
5 nan
6 nan
7 sell 9
After each buy we have a sell at some unknown distance.
I need to count how many times I had a profit.
In this case, first deal earn 1 (5-4), and second deal earn 6 (9-3).
I need to produce here 2 results total wins=2, ... | [
"If you drop all the nans, pivot the table, then shift the sells up so they align with the buys, you will have rows of buy/sell and can then compare.\ndf = df.dropna()\ndf\n event b\n0 buy 4.0\n2 sell 5.0\n3 buy 3.0\n7 sell 9.0\n\ndf_pivoted = df.pivot(columns='event',values='b')\ndf_pivo... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074406051_pandas_python.txt |
Q:
Unable To Install Kivy
pip install kivy
Collecting kivy
Using cached Kivy-2.1.0.tar.gz (23.8 MB)
Installing build dependencies ... error
error: subprocess-exited-with-error
× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> [10 lines of output]
Collecting setuptools
Using c... | Unable To Install Kivy | pip install kivy
Collecting kivy
Using cached Kivy-2.1.0.tar.gz (23.8 MB)
Installing build dependencies ... error
error: subprocess-exited-with-error
× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> [10 lines of output]
Collecting setuptools
Using cached setuptools-65.5.1-py3-... | [
"from their docs\nKivy 2.1.0 officially supports Python versions 3.7 - 3.10.\nyou are using 3.11. Try using python 3.10\n(although from your prints it looks like they are in the process of supporting 3.11 (since it could install other kivy specific requirements for 3.11))\n"
] | [
0
] | [] | [] | [
"kivy",
"python",
"subprocess"
] | stackoverflow_0074406314_kivy_python_subprocess.txt |
Q:
Fast file/directory scan method for windows?
I'm looking for a high performance method or library for scanning all files on disk or in a given directory and grabbing their basic stats - filename, size, and modification date.
I've written a python program that uses os.walk along with os.path.getsize to get the fil... | Fast file/directory scan method for windows? | I'm looking for a high performance method or library for scanning all files on disk or in a given directory and grabbing their basic stats - filename, size, and modification date.
I've written a python program that uses os.walk along with os.path.getsize to get the file list, and it works fine, but is not particularly... | [
"Well, I would expect this to be heavily I/O bound task.\nAs such, optimizations on python side would be quite ineffective; the only optimization I could think of is some different way of accessing/listing files, in order to reduce the actual read from the file system.\nThis of course requires a deep knowledge of t... | [
3,
3,
2,
2,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0000397293_python_windows.txt |
Q:
Why Pandas dropna function with axis=1 doesn't mean to drop columns when specified a subset of columns
The dropna function is supposed to drop columns if axis=1 and rows if axis=0 and it does work like this If I don't add subset parameters.
However when I want to apply drop only to certain columns by adding subset... | Why Pandas dropna function with axis=1 doesn't mean to drop columns when specified a subset of columns | The dropna function is supposed to drop columns if axis=1 and rows if axis=0 and it does work like this If I don't add subset parameters.
However when I want to apply drop only to certain columns by adding subset means to a group of column headers, it gives error.
I've read in this article that this is because Pandas i... | [
"Probably better off making a new dataframe only including what you do want.\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074406230_pandas_python.txt |
Q:
Using opencv to mask the background
I'm trying to use tesseract to read text from a game with poor results.
What I would like to accomplish is to remove the background from the image so that only the text is visible to improve OCR results.
I've tried cv2.inRange, thresholding yet I can't seem to get it to work.
im... | Using opencv to mask the background |
I'm trying to use tesseract to read text from a game with poor results.
What I would like to accomplish is to remove the background from the image so that only the text is visible to improve OCR results.
I've tried cv2.inRange, thresholding yet I can't seem to get it to work.
import numpy as np
import pytesseract
from... | [
"Inverting color may help? try this & let me know.\nimport cv2\nimage = cv2.imread(\"Bytelock.jpg\")\nimage = ~image\ncv2.imwrite(\"Bytelock.jpg\",image)\n\nInverted image\n\nRed varient\nimport numpy as np\nimport imutils\n\nimport cv2\n\nimg_rgb = cv2.imread('ss.jpg')\n\nConv_hsv_Gray = cv2.cvtColor(img_rgb, cv2.... | [
0
] | [] | [] | [
"ocr",
"opencv",
"python"
] | stackoverflow_0074406394_ocr_opencv_python.txt |
Q:
Two variables in Python have same id, but not lists or tuples
Two variables in Python have the same id:
a = 10
b = 10
a is b
>>> True
If I take two lists:
a = [1, 2, 3]
b = [1, 2, 3]
a is b
>>> False
according to this link Senderle answered that immutable object references have the same id and mutable objects li... | Two variables in Python have same id, but not lists or tuples | Two variables in Python have the same id:
a = 10
b = 10
a is b
>>> True
If I take two lists:
a = [1, 2, 3]
b = [1, 2, 3]
a is b
>>> False
according to this link Senderle answered that immutable object references have the same id and mutable objects like lists have different ids.
So now according to his answer, tuples... | [
"Immutable objects don't have the same id, and as a mater of fact this is not true for any type of objects that you define separately. Generally speaking, every time you define an object in Python, you'll create a new object with a new identity. However, for the sake of optimization (mostly) there are some excepti... | [
85,
25,
20,
0,
0
] | [] | [] | [
"identity",
"python",
"python_3.x",
"python_internals",
"tuples"
] | stackoverflow_0038189660_identity_python_python_3.x_python_internals_tuples.txt |
Q:
Add column names to a H5PY dataset
I am trying to add column names to a pre-exisiting dataset. I have three columns and want each to have a name.
with h5py.File(path, "w") as f:
x1 = [0, 1, 2, 3, 4]
y1 = ['a', 'b', 'c', 'd', 'e']
z1 = [5, 6, 7, 8, 9]
namesList = ['ID', 'Name', 'Path']
ds_dt = n... | Add column names to a H5PY dataset | I am trying to add column names to a pre-exisiting dataset. I have three columns and want each to have a name.
with h5py.File(path, "w") as f:
x1 = [0, 1, 2, 3, 4]
y1 = ['a', 'b', 'c', 'd', 'e']
z1 = [5, 6, 7, 8, 9]
namesList = ['ID', 'Name', 'Path']
ds_dt = np.dtype({'names': namesList, 'formats': ... | [
"Here are the modifications to get the code above to work as described. You had the right idea creating the recarray dtype. You need to use it when you create rec_arr, and/or when you create an empty dataset. (If you use data= to create and populate the dataset with data, h5py will figure out the dtype and initial ... | [
0
] | [] | [] | [
"h5py",
"hdf5",
"python"
] | stackoverflow_0074238167_h5py_hdf5_python.txt |
Q:
Python lambda function to calculate factorial of a number
I have just started learning python. I came across lambda functions. On one of the problems, the author asked to write a one liner lambda function for factorial of a number.
This is the solution that was given:
num = 5
print (lambda b: (lambda a, b: a(a, b... | Python lambda function to calculate factorial of a number | I have just started learning python. I came across lambda functions. On one of the problems, the author asked to write a one liner lambda function for factorial of a number.
This is the solution that was given:
num = 5
print (lambda b: (lambda a, b: a(a, b))(lambda a, b: b*a(a, b-1) if b > 0 else 1,b))(num)
I cannot ... | [
"The factorial itself is almost as you'd expect it. You infer that the a is... the factorial function. b is the actual parameter.\n<factorial> = lambda a, b: b*a(a, b-1) if b > 0 else 1\n\nThis bit is the application of the factorial:\n<factorial-application> = (lambda a, b: a(a, b))(<factorial>, b)\n\na is the fac... | [
10,
7,
6,
2,
2,
0,
0,
0,
0,
0,
0
] | [
"while True: \n #It is this simple:\n from functools import reduce\n n=input('>>')\n n=int(n)\n if n==0:\n print('factorial: ',1)\n elif n<0:\n print('invalid input')\n else:\n print('factorial: ',(reduce(lambda x,y:x*y,list(range(1,n+1)))))\n\n"
] | [
-1
] | [
"lambda",
"python",
"python_2.7"
] | stackoverflow_0015401376_lambda_python_python_2.7.txt |
Q:
How do ı make continiously mathematical operations in python?
I want to advance my calculator and I want it to make continiously mathematical operations with the last number of calculation. for example
11+2=13
and than take the 13 and us it in the next calculation
13 x 3= 39
and than after using the 39 like
39%3=1... | How do ı make continiously mathematical operations in python? | I want to advance my calculator and I want it to make continiously mathematical operations with the last number of calculation. for example
11+2=13
and than take the 13 and us it in the next calculation
13 x 3= 39
and than after using the 39 like
39%3=13
instead of this my code works like
11+2=13
13*3=39
and goes back ... | [
"I'm not really sure where to begin explaining where your approach is misguided and broken, though I would be happy to try if you have further questions. There are many ways to write a simple calculator program. Here's one I just wrote to give you some better ideas of how to approach this (it's probably missing a... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074404687_python_python_3.x.txt |
Q:
Looping through driver.get() giving ConnectionRefusedError: [Errno 61] Connection refused error
Trying to read a list of URLs from .csv file and scrape product price. Any suggestions to loop through urls would be great. I can return price and title of first product and then I get a connection refused error.
Connec... | Looping through driver.get() giving ConnectionRefusedError: [Errno 61] Connection refused error | Trying to read a list of URLs from .csv file and scrape product price. Any suggestions to loop through urls would be great. I can return price and title of first product and then I get a connection refused error.
ConnectionRefusedError: [Errno 61] Connection refused error
from selenium import webdriver
from selenium.we... | [
"I believe it's because of the driver.quit(), you're using it before the for is complete. Try moving it to another path within the code when finished. I also recommend using try and catch in your python application in selenium, I believe it will be easier to find errors.\nTry like this:\ntry:\n xxxxxxxxxx\n ... | [
2
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074406360_python_selenium.txt |
Q:
Install of local python library created using nbdev cannot be found
I am creating a library using nbdev. Following the instructions here.
My file structure is the same as given in the instructions, with the library installed at top level of the repo and the notebooks in the 'nbs' folder
repo folder
|_ settings.ini... | Install of local python library created using nbdev cannot be found | I am creating a library using nbdev. Following the instructions here.
My file structure is the same as given in the instructions, with the library installed at top level of the repo and the notebooks in the 'nbs' folder
repo folder
|_ settings.ini
|_ setup.py
|_ nbs
|_ library folder
|_ etc
After creating the library.... | [
"I ended up getting around the issue by installing direct from git using\npython -m pip install git+<URL to library repo>\n\nIt isn't the best approach but it does work\n"
] | [
0
] | [] | [] | [
"nbdev",
"pip",
"python"
] | stackoverflow_0074293810_nbdev_pip_python.txt |
Q:
Use python to naively find an Arduino's IP address from another PC on the local network
I have a ESP8266 Nodemcu device running a local HTTP server. I followed the quick-start instructions here.
My goal is to have a large number of these devices running in sync. To do that, I wrote this script:
#!/usr/bin/env pyth... | Use python to naively find an Arduino's IP address from another PC on the local network | I have a ESP8266 Nodemcu device running a local HTTP server. I followed the quick-start instructions here.
My goal is to have a large number of these devices running in sync. To do that, I wrote this script:
#!/usr/bin/env python
import time
import sys
import socket
import requests
def myFunction():
#This is what ... | [
"So, now that I know what are the constraints, and what is just what is in the tutorial, here are my 2 cents (keep in mind that I too, am just a hobbyist about everything that has \"voltage\". And not even a good one).\n1st strategy : PC is server\nSo, if I assume that your devices are, for example, temperature sen... | [
1
] | [] | [] | [
"arduino",
"mdns",
"network_programming",
"python"
] | stackoverflow_0074405706_arduino_mdns_network_programming_python.txt |
Q:
AttributeERROR : module'tensorflow.keras.applicationsas no attribute efficientnet_v2
When i try to run the efficientNetv2 model
I got this erreur enter image description here
AttributeError: module'tensorflow.keras.applications ' has no attribute 'efficientnet_v2'
Tensorflow version : tensorflow-gpu:2.6
A:
The i... | AttributeERROR : module'tensorflow.keras.applicationsas no attribute efficientnet_v2 | When i try to run the efficientNetv2 model
I got this erreur enter image description here
AttributeError: module'tensorflow.keras.applications ' has no attribute 'efficientnet_v2'
Tensorflow version : tensorflow-gpu:2.6
| [
"The import is incorrect, you need to update it, it might have worked in older Keras versions,but the internal per-network modules inside keras.applications are not exposed anymore, so your correct import would be:\nkeras.applications.EfficientNetV2S\n\nOr if you use tf.keras:\ntf.keras.applications.EfficientNetV2S... | [
1
] | [] | [] | [
"deep_learning",
"efficientnet",
"keras",
"python",
"tensorflow"
] | stackoverflow_0074405797_deep_learning_efficientnet_keras_python_tensorflow.txt |
Q:
Error assigning variable values in a TensorFlow model
I have a TensorFlow model that I have loaded from a repository as
model = tf.saved_model.load(folder)
My objective is to replicate this same model in Jax, and for so I need to understand whether the variable values (weights and biases) loaded are the correct o... | Error assigning variable values in a TensorFlow model | I have a TensorFlow model that I have loaded from a repository as
model = tf.saved_model.load(folder)
My objective is to replicate this same model in Jax, and for so I need to understand whether the variable values (weights and biases) loaded are the correct ones.
One way I can recover the value of variable i is just
... | [
"The answer seems to be this:\nnumpy_vars = [v.numpy() for v in vars]\n\nwith tf.compat.v1.Session(graph = graph) as sess:\n tvars = tf.compat.v1.trainable_variables()\n tf.compat.v1.variables_initializer(vars).run()\n print(tvars[0].eval())\n print('------------------------------')\n for v, tv in zi... | [
0
] | [] | [] | [
"debugging",
"python",
"tensorflow",
"tensorflow1.15",
"variable_assignment"
] | stackoverflow_0074406048_debugging_python_tensorflow_tensorflow1.15_variable_assignment.txt |
Q:
Error twisted.internet.error.ReactorNotRestartable
I'm having problems trying to run Scrapy again, after a scrape.
For example, when I run my FastAPI and have Scrapy do a scrape, it will work just fine. Bringing me the correct data. However, if I try to do another scrape without restarting the application, I get t... | Error twisted.internet.error.ReactorNotRestartable | I'm having problems trying to run Scrapy again, after a scrape.
For example, when I run my FastAPI and have Scrapy do a scrape, it will work just fine. Bringing me the correct data. However, if I try to do another scrape without restarting the application, I get the error 'twisted.internet.error.ReactorNotRestartable'.... | [
"Guys I managed to solve my problem. Following @Alexandre's suggestion in the above comment, I implemented the subprocess in the code.\nInstead of using CrawlerProcess, I used subprocess.call() which waits until the end of the operation.Passing to call() the command that executes Scrapy together with an argument '-... | [
0
] | [] | [] | [
"fastapi",
"python",
"scrapy",
"twisted.internet"
] | stackoverflow_0074380442_fastapi_python_scrapy_twisted.internet.txt |
Q:
MQTT and Python - how to use hostname in topic?
I am a total newbie to MQTT and Python on my Raspi. However, by using search and "G" a lot, I made it as far as I can capture and publish temperatures.
Too make things more simple in managing the data, I'd like to use the hostname in the topic.
So far I do:
client.pu... | MQTT and Python - how to use hostname in topic? | I am a total newbie to MQTT and Python on my Raspi. However, by using search and "G" a lot, I made it as far as I can capture and publish temperatures.
Too make things more simple in managing the data, I'd like to use the hostname in the topic.
So far I do:
client.publish("data/humidity_rel", "%.2f" %humidity)
what I'... | [
"Neither the MQTT spec or the Paho Python MQTT client implementation will do what you want automatically, it's up to you to do the string substitution yourself.\nclient.publish(host+\"/data/humidity_rel\", \"%.2f\" %humidity)\n\nor\nclient.publish('%s/data/humidity_rel' % host, \"%.2f\" %humidity)\n\nor\nclient.pub... | [
2
] | [] | [] | [
"hostname",
"mqtt",
"python"
] | stackoverflow_0074406246_hostname_mqtt_python.txt |
Q:
Python: Project Package / Module structure dependency Problem
I was hoping someone could help me figure out an odd "dependency" problem. I have a fairly large python project, with a slimmed down structure that looks like:
Sitka
│ DataTickers.py
│ example.csv
│ FinDates.py
│ SitkaMongo.py
│ tickers_csv.c... | Python: Project Package / Module structure dependency Problem | I was hoping someone could help me figure out an odd "dependency" problem. I have a fairly large python project, with a slimmed down structure that looks like:
Sitka
│ DataTickers.py
│ example.csv
│ FinDates.py
│ SitkaMongo.py
│ tickers_csv.csv
│ __init__.py
│
├───Fin
│ │ main.py
│ │ md_provider_co... | [
"It seems you only want some code of the main.py to run when the file itself is running. Try using:\nif __name__ in \"__main__\": # All sikta imports\n from Sitka.FinDates import getMainDates\n from .md_provider_control import MD_ProviderV3\n from .Tofino import Tofino\n import Sitka.Fin.Instruments.mar... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074406631_python.txt |
Q:
Split text file with same value
I have a text file that looks like this
Apple TreeTwo
Banana TreeOne
Juice TreeOne
Pineapple TreeThree
Berries TreeThree
How can I select the rows with the same Tree name and put them in separate files like below in python
file1.txt
Banana TreeOne
Juice TreeOne
file2.txt
Apple Tre... | Split text file with same value | I have a text file that looks like this
Apple TreeTwo
Banana TreeOne
Juice TreeOne
Pineapple TreeThree
Berries TreeThree
How can I select the rows with the same Tree name and put them in separate files like below in python
file1.txt
Banana TreeOne
Juice TreeOne
file2.txt
Apple TreeTwo
file3.txt
Pineapple
Berries
I'... | [
"I wouldn't actually use groupby here, simply iterating over the file contents and then separating it into lists is easier.\nNote that you could optimize this into a single for loop, but I'm not, to make it more understandable...\nI'm using a dict in my example below as it is able to deal with unknown values easily... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0074406572_python.txt |
Q:
How to Make MacOs Tkinter Button Look Like Windows Tkinter Buttons
I'm using tkinter to make a calculator. However, whenever I use buttons I'm stuck with the ugly look of the macOS buttons and I's like to make them look like the ones on Windows. I'm also not able to change the background color. I've tried to use t... | How to Make MacOs Tkinter Button Look Like Windows Tkinter Buttons | I'm using tkinter to make a calculator. However, whenever I use buttons I'm stuck with the ugly look of the macOS buttons and I's like to make them look like the ones on Windows. I'm also not able to change the background color. I've tried to use tkmacosx to change the background color but it didn't work.
My expected o... | [
"\nmacOS Big Sur (11.0.1)\n\nSo, tkmacosx must work perfectly. Maybe you import tkmacosx, but continued to use tkinter buttons?\nHere is my code, and it change background, foreground color.\n\"borderless=1\" removing borders of button.\n\"focuscolor=''\" removing blue border, when you press the button.\nbuttonExit... | [
1,
0
] | [] | [] | [
"button",
"macos",
"python",
"tkinter",
"tkinter_button"
] | stackoverflow_0068354555_button_macos_python_tkinter_tkinter_button.txt |
Q:
How can i open pip file codes to read?
I'm trying to check how the (pip black) is written and would love to read its code but having trouble.
I downloaded the file from browser but its on gz format and when I try to open it on VSCode I get cryptic lines like
���nc�Onlyfinnaly.log
What am i supposed to do?
I tried... | How can i open pip file codes to read? | I'm trying to check how the (pip black) is written and would love to read its code but having trouble.
I downloaded the file from browser but its on gz format and when I try to open it on VSCode I get cryptic lines like
���nc�Onlyfinnaly.log
What am i supposed to do?
I tried downloading the pip directly on VSCode and ... | [
"This should take you to the source code:\n\nHere's the link: https://github.com/psf/black\n"
] | [
0
] | [] | [] | [
"gzip",
"pip",
"python"
] | stackoverflow_0074406665_gzip_pip_python.txt |
Q:
Return words from a list that dosen't contain the same words
Hey (sorry bad english) so let me explain a little further. i want to make a function that takes in a list. let's say a list with a countries and their capital also added their population. i want to return every country-capital pair that dosen't contain ... | Return words from a list that dosen't contain the same words | Hey (sorry bad english) so let me explain a little further. i want to make a function that takes in a list. let's say a list with a countries and their capital also added their population. i want to return every country-capital pair that dosen't contain the same letter.
like this:
countries = [
["China PR", "Beijin... | [
"You can use this code:\ndef no_common_letters(array_of_arrays):\n new_array = []\n for array in array_of_arrays:\n determination = []\n for x in array[0]:\n if x not in array[1]:\n determination.append('1')\n else:\n determination.append('0')\... | [
1,
1,
1
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0074406384_list_python_string.txt |
Q:
Python, Telegram scraper
I use the telethon library to save incoming messages to the database, but I can't decode the link to the media file in any way.
def scraper_new_message(message):
print(message[0].media.photo)
print(message[0].media.photo.file_reference.decode('utf-16'))
@client.on(events.NewMessag... | Python, Telegram scraper | I use the telethon library to save incoming messages to the database, but I can't decode the link to the media file in any way.
def scraper_new_message(message):
print(message[0].media.photo)
print(message[0].media.photo.file_reference.decode('utf-16'))
@client.on(events.NewMessage(chats=LIST_CHANNELS))
async ... | [
"You can't simply decode and get the oriignal file. You will have to use download api to download and store the file.\nref : https://docs.telethon.dev/en/stable/quick-references/client-reference.html?highlight=download_media#downloads\n"
] | [
0
] | [] | [] | [
"cryptography",
"encryption",
"python",
"telegram_bot",
"telethon"
] | stackoverflow_0074406616_cryptography_encryption_python_telegram_bot_telethon.txt |
Q:
Printing columns of a list of arrays
I have the following list
import numpy as np
Y = [np.array([[1, 4, 7],
[2, 5, 8]]),
np.array([[10, 14, 18],
[11, 15, 19],
[12, 16, 20],
[13, 17, 21]]),
np.array([[22, 26, 31],
[24, 28, 33],
[26, 30, 35]])]
I want to loop throug... | Printing columns of a list of arrays | I have the following list
import numpy as np
Y = [np.array([[1, 4, 7],
[2, 5, 8]]),
np.array([[10, 14, 18],
[11, 15, 19],
[12, 16, 20],
[13, 17, 21]]),
np.array([[22, 26, 31],
[24, 28, 33],
[26, 30, 35]])]
I want to loop through and print the columns inside of all the ... | [
"Does this help?\nfor i in range(3):\n l = Y[i]\n for j in range(len(np.transpose(l))):\n print(l[:,j])\n\nThis gives you:\n[1 2]\n[4 5]\n[7 8]\n[10 11 12 13]\n[14 15 16 17]\n[18 19 20 21]\n[22 24 26]\n[26 28 30]\n[31 33 35]\n\n",
"Slight variation of SC's answer:\nfor array in Y:\n for row in arr... | [
1,
1,
0
] | [] | [] | [
"numpy",
"numpy_ndarray",
"numpy_slicing",
"python"
] | stackoverflow_0074341610_numpy_numpy_ndarray_numpy_slicing_python.txt |
Q:
How to 'add' QuerySet in Django?
I have written the below code.
for number in numbers:
booking_list = Booking.objects.filter(rooms=number)
Here, numbers is a list of numbers.
The problem with this code is that booking_list will only contain the QuerySet of the last number as the previous QuerySets will be ove... | How to 'add' QuerySet in Django? | I have written the below code.
for number in numbers:
booking_list = Booking.objects.filter(rooms=number)
Here, numbers is a list of numbers.
The problem with this code is that booking_list will only contain the QuerySet of the last number as the previous QuerySets will be overwritten but I want booking_list to co... | [
"You can use __in lookup with distinct() so:\nbooking_list = Booking.objects.filter(rooms__in=[i for i in numbers]).distinct(\"rooms\")\n\n"
] | [
1
] | [] | [] | [
"django",
"django_filters",
"django_queryset",
"django_views",
"python"
] | stackoverflow_0074406700_django_django_filters_django_queryset_django_views_python.txt |
Q:
Inverse glob - reverse engineer a wildcard string from file names
I want to generate a wildcard string from a pair of file names. Kind of an inverse-glob. Example:
file1 = 'some foo file.txt'
file2 = 'some bar file.txt'
assert 'some * file.txt' == inverse_glob(file1, file2)
Use difflib perhaps? Has this been s... | Inverse glob - reverse engineer a wildcard string from file names | I want to generate a wildcard string from a pair of file names. Kind of an inverse-glob. Example:
file1 = 'some foo file.txt'
file2 = 'some bar file.txt'
assert 'some * file.txt' == inverse_glob(file1, file2)
Use difflib perhaps? Has this been solved already?
Application is a large set of data files with similar na... | [
"For instance:\n\nFilenames:\n\nnames = [('some foo file.txt','some bar file.txt', 'some * file.txt'),\n (\"filename.txt\", \"filename2.txt\", \"filenam*.txt\"),\n (\"1filename.txt\", \"filename2.txt\", \"*.txt\"),\n (\"inverse_glob\", \"inverse_glob2\", \"inverse_glo*\"),\n (\"the 2... | [
2,
0
] | [] | [] | [
"filenames",
"glob",
"python"
] | stackoverflow_0043808808_filenames_glob_python.txt |
Q:
numpy.sin function in degrees?
I'm working on a problem that has to do with calculating angles of refraction and what not. However, it seems that I'm unable to use the numpy.sin() function in degrees. I have tried to use numpy.degrees() and numpy.rad2deg().
numpy.sin(90)
numpy.degrees(numpy.sin(90))
Both return ... | numpy.sin function in degrees? | I'm working on a problem that has to do with calculating angles of refraction and what not. However, it seems that I'm unable to use the numpy.sin() function in degrees. I have tried to use numpy.degrees() and numpy.rad2deg().
numpy.sin(90)
numpy.degrees(numpy.sin(90))
Both return ~ 0.894 and ~ 51.2 respectively.
Tha... | [
"You don't want to convert to degrees, because you already have your number (90) in degrees. You need to convert 90 from degrees to radians, and you need to do it before you take the sine:\n>>> np.sin(np.deg2rad(90))\n1.0\n\n(You can use either deg2rad or radians.)\n",
"Use the math module from the standard Pyth... | [
89,
19,
2,
0,
0
] | [] | [] | [
"math",
"numpy",
"python",
"trigonometry"
] | stackoverflow_0028077733_math_numpy_python_trigonometry.txt |
Q:
Why is Python dataclass a decorator and not a base class?
Why does Python implement dataclasses.dataclass as a class decorator and not as a base class? I think it would be at least clearer from the conceptual point of view to have it as a base class: the __init__ method seems to be the only thing a dataclass decor... | Why is Python dataclass a decorator and not a base class? | Why does Python implement dataclasses.dataclass as a class decorator and not as a base class? I think it would be at least clearer from the conceptual point of view to have it as a base class: the __init__ method seems to be the only thing a dataclass decorator adds to a class, and adding methods and attributes is what... | [
"Dataclasses were introduced in PEP 557, which describes some of the design considerations for this feature, including rejected ideas. However, there is no mention of any rejected alternatives to using a decorator, such as using a base class instead. So it seems we cannot give a definitive answer for why a decorato... | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074406574_python_python_3.x.txt |
Q:
ValueError: setting an array element with a sequence. (Python / SKFlow)
this is my first question after using this site for many years - please correct me if I'm doing something wrong...
I'm trying to train a Deep Neural Network Classifier using the SKFlow part of TensorFlow which should make this pretty simple. I... | ValueError: setting an array element with a sequence. (Python / SKFlow) | this is my first question after using this site for many years - please correct me if I'm doing something wrong...
I'm trying to train a Deep Neural Network Classifier using the SKFlow part of TensorFlow which should make this pretty simple. I'm constantly getting this ValueError when passing my data to the Classifiers... | [
"I believe your model.fit does not accept a list of sequences, hence you need to create either a list of list or a multi-dimensional np.ndarray. This should help you:\nx_train =[arr for arr in x_train.vector]\nx_train = np.asarray(x_train)\n\ny_train = np.asarray(y_train[[\"type_id\"]].values)\n\n...\nmodel.fit(x_t... | [
1
] | [] | [] | [
"numpy",
"pandas",
"python",
"python_3.x",
"tensorflow"
] | stackoverflow_0039450030_numpy_pandas_python_python_3.x_tensorflow.txt |
Q:
Python delete character in a string
I'm stuck, I've searched several ways and I can't get the correct output.
string = "Hello! I have a Big!!! problem 666 is not a good number__$"
ns =''.join([i for i in string if i.isalpha()])
print(ns)
HelloIhaveaBigproblemisnotagoodnumber
I want this output:
Hello I have a Big... | Python delete character in a string | I'm stuck, I've searched several ways and I can't get the correct output.
string = "Hello! I have a Big!!! problem 666 is not a good number__$"
ns =''.join([i for i in string if i.isalpha()])
print(ns)
HelloIhaveaBigproblemisnotagoodnumber
I want this output:
Hello I have a Big problem is not a good number
Can you hel... | [
"Filter uisng re & remove them using re.sub\nimport re\nstring = \"Hello! I have a Big!!! problem 666 is not a good number__$\"\nprint (re.sub('[^a-zA-Z]+', ' ', string))\n\noutput #\nHello I have a Big problem is not a good number \n\n",
"You could increase the conditions used for each character, e.g.,\nns =''.j... | [
2,
2,
0,
0
] | [] | [] | [
"python",
"replace",
"string"
] | stackoverflow_0074406536_python_replace_string.txt |
Q:
Python, Isin, TypeError: only list-like objects are allowed to be passed to isin(), you passed a [str]
I'm trying to create a column status that shows if my DataFrame values are in my directory test. For example does folder O:\Stack\Over\Flow\2010 exist in the O:\Stack\Over\Flow directory.
My pl_dest DataFrame is ... | Python, Isin, TypeError: only list-like objects are allowed to be passed to isin(), you passed a [str] | I'm trying to create a column status that shows if my DataFrame values are in my directory test. For example does folder O:\Stack\Over\Flow\2010 exist in the O:\Stack\Over\Flow directory.
My pl_dest DataFrame is like so:
Folder_Name_to_create
0 O:\Stack\Over\Flow\2010
1 O:\Stack\Over\Flow\2011
Code:
import pand... | [
"Iterate over row & check existance\nfrom pathlib import Path\nimport os\nimport pandas as pd\n\nstatus=[]\n\nfor index, row in df.iterrows():\n path = row['Folder_Name_to_create']\n path=Path(path)\n if os.path.isdir(path):\n status.append('File_exists')\n else:\n status.append('File_not_ex... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074406730_pandas_python.txt |
Q:
I am getting error when i run simple code in pandas using jupyter
import pandas as pd
df1 = pd.read_csv('C:\\Users\\sudarshan\\Downloads\\bulk.csv')
I am getting the below error message when i try to read the csv file please help,
This is very simple code but i am not understanding why i got this error message ... | I am getting error when i run simple code in pandas using jupyter | import pandas as pd
df1 = pd.read_csv('C:\\Users\\sudarshan\\Downloads\\bulk.csv')
I am getting the below error message when i try to read the csv file please help,
This is very simple code but i am not understanding why i got this error message below is the error message
OSError T... | [
"Try putting an r in front of your path like so. ==>pd.read_csv(r'C:\\\\Users\\\\sudarshan\\\\Downloads\\\\bulk.csv') <==\nIf this doesn't work then check your C:Drive to see if one drive or sync is on. Due to the constant sync running in the background it interferes with exports.\nLet me know if that works for yo... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0068173517_pandas_python.txt |
Q:
Autopep8/Flake8/isort: How do I sort using autoformatting absolute imports for user defined modules in VS Code?
I am facing a formatting issue. The default behavior of python.sortImports is to organize stdlib, 3rd party, and user modules.
However, it moves my user modules above the 3rd part modules in alphabetica... | Autopep8/Flake8/isort: How do I sort using autoformatting absolute imports for user defined modules in VS Code? | I am facing a formatting issue. The default behavior of python.sortImports is to organize stdlib, 3rd party, and user modules.
However, it moves my user modules above the 3rd part modules in alphabetical order which is not according to PEP8. And, it follows PEP8 when I use relative imports which is making things more ... | [
"And I fixed it myself. For future readers. If a local folder is showing up as a 3rd party library then use the following args in your settings.json file.\n{\n \"isort.args\": [\n \"--profile\",\n \"django\",\n \"--known-local-folder\",\n \"my_folder1\",\n \"--known-local-folde... | [
0
] | [] | [] | [
"autopep8",
"python",
"visual_studio_code"
] | stackoverflow_0074403989_autopep8_python_visual_studio_code.txt |
Q:
How to convert geographic data to Xarray dataset?
I have a relative gravity dataset of 697 measurements taken at points with latitude and longitude. I am having trouble converting to an Xarray dataset so that I can inevitably create an interpolated grid with Xarray.interp_like.
I tried creating the DataArray from ... | How to convert geographic data to Xarray dataset? | I have a relative gravity dataset of 697 measurements taken at points with latitude and longitude. I am having trouble converting to an Xarray dataset so that I can inevitably create an interpolated grid with Xarray.interp_like.
I tried creating the DataArray from a series and from a Dataframe using the following artic... | [
"You just need to deal with duplicates. Otherwise how would you fill your pivot table when lat and lon are the same but rel_grav is different. For example take the mean of all duplicated entries with same lat and lon:\nimport pandas as pd\nrel_grav_df = pd.DataFrame([\n [979517.368887, 36.713923, -116.120574... | [
0,
0
] | [] | [] | [
"dataframe",
"interpolation",
"pandas",
"python",
"python_xarray"
] | stackoverflow_0074383791_dataframe_interpolation_pandas_python_python_xarray.txt |
Q:
Automaticaly downloadable invoice pdf
I want to create an option to download a pdf file having an invoice with the following properties in the django database admin:
models.py:
from django.db import models
from appsystem.models import Outlet
from core.models import Item, Supplier
from location.models import Wareh... | Automaticaly downloadable invoice pdf | I want to create an option to download a pdf file having an invoice with the following properties in the django database admin:
models.py:
from django.db import models
from appsystem.models import Outlet
from core.models import Item, Supplier
from location.models import Warehouse, Zone, Section, Level
class MainPurc... | [
"It's really two questions. How to generate pdf from data in the DB, and how to deliver it to a web client (browser).\nIn answer to the second, here's a view I wrote earlier\nfrom io import BytesIO\n\ndef pdfview( request, pk):\n\n quote = get_object_or_404( Quote, pk=pk) # object to build pdf from\n\n pdf ... | [
1
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0074404718_django_django_models_django_templates_django_views_python.txt |
Q:
convert yyyyqq to pandas date in clean way
I am trying to convert year and quarter to date in pandas. In example below I am trying to get 1980-03-31 for 1980Q1 and so on.
df=pd.DataFrame({'year':['1980','1980','1980','1980'],'qtr':
['Q1','Q2','Q3','Q4']})
scenario['date']=pd.to_datetime(scenario[... | convert yyyyqq to pandas date in clean way | I am trying to convert year and quarter to date in pandas. In example below I am trying to get 1980-03-31 for 1980Q1 and so on.
df=pd.DataFrame({'year':['1980','1980','1980','1980'],'qtr':
['Q1','Q2','Q3','Q4']})
scenario['date']=pd.to_datetime(scenario['year']+scenario['qtr'], infer_datetime_format=T... | [
"are you looking for QuarterEnd offset?\nimport pandas as pd\n\ndf=pd.DataFrame({'year':['1980','1980','1980','1980'],'qtr':\n ['Q1','Q2','Q3','Q4']})\n\ndf['date'] = pd.to_datetime(df['year']+df['qtr']) + pd.tseries.offsets.QuarterEnd()\n\ndf[['date','year','qtr']]\n date year qtr\n0 1980-0... | [
1,
1,
0
] | [] | [] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0074406771_datetime_pandas_python.txt |
Q:
AttributeError: 'NoneType' object has no attribute 'suppress' using selenium webdriver
I am trying to scrape some links from https://www.mckinsey.com/capabilities/operations/our-insights using selenium with python.
from selenium.webdriver.common.by import By
from selenium import webdriver
from bs4 import Beautiful... | AttributeError: 'NoneType' object has no attribute 'suppress' using selenium webdriver | I am trying to scrape some links from https://www.mckinsey.com/capabilities/operations/our-insights using selenium with python.
from selenium.webdriver.common.by import By
from selenium import webdriver
from bs4 import BeautifulSoup
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("-... | [
"You can try the next example selenium with bs4\nurl='https://www.mckinsey.com/capabilities/operations/our-insights'\ndriver.get(url)\ndriver.maximize_window()\ntime.sleep(3)\n\naccept = driver.find_element(By.XPATH, '//*[@id=\"onetrust-accept-btn-handler\"]')\naccept.click()\ntime.sleep(2)\ndata = []\nfor x in ran... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074405823_python_selenium_selenium_webdriver.txt |
Q:
Cookie is not created when calling the endpoint in FastAPI
I have encountered an issue, as I have to create a cookie in the backend which I will later use to send a request from the frontend. Both apps are on same domain. This is general idea behind it https://levelup.gitconnected.com/secure-frontend-authorization... | Cookie is not created when calling the endpoint in FastAPI | I have encountered an issue, as I have to create a cookie in the backend which I will later use to send a request from the frontend. Both apps are on same domain. This is general idea behind it https://levelup.gitconnected.com/secure-frontend-authorization-67ae11953723.
Frontend Code - Sending GET request to Backend
@a... | [
"127.0.0.1 and localhost (or local.me.me in your case) are two different domains (and origins). Hence, when making a request you need to use the same domain you used for creating the cookie. For example, if the cookie was created for local.me.me domain, then you should use that domain when sending the request. See ... | [
0
] | [] | [] | [
"cookie_httponly",
"cookies",
"fastapi",
"python",
"starlette"
] | stackoverflow_0074405849_cookie_httponly_cookies_fastapi_python_starlette.txt |
Q:
printing output values together with some multiplication parameter
I tried write a code that the given numbers multiply by ten for each input, and then sum all of those values. If their summation is bigger than 100 it will stop. Furthermore I want to print the output as "Program ends because 10*3+10*1+10\*8 = 120,... | printing output values together with some multiplication parameter | I tried write a code that the given numbers multiply by ten for each input, and then sum all of those values. If their summation is bigger than 100 it will stop. Furthermore I want to print the output as "Program ends because 10*3+10*1+10\*8 = 120, which is not less than 100" while the input parameters are 3,1,8 accord... | [
"You can construct the end message, then print it, like this:\nl=[]\nk=[]\n\nwhile True:\n n = int(input(\"Enter Number to calculate: \"))\n p=n*10\n l.append(p)\n k.append(n)\n s= sum(l)\n h = \"10*\"\n if s>=100:\n message = \"Program ends because \"\n for i in range(len(k)) :\n... | [
0,
0
] | [] | [] | [
"printing",
"python",
"string"
] | stackoverflow_0074406816_printing_python_string.txt |
Q:
ValueError: Shape must be at least rank 3 but is rank 2 for '{{node BiasAdd}} = BiasAdd[T=DT_FLOAT, data_format="NCHW"](add, bias)' with input shapes:
Done
I am just trying to run and replicate the following project: https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-ke... | ValueError: Shape must be at least rank 3 but is rank 2 for '{{node BiasAdd}} = BiasAdd[T=DT_FLOAT, data_format="NCHW"](add, bias)' with input shapes: | Done
I am just trying to run and replicate the following project: https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/ . Basically until this point I have done everything as it is in the linked project but than I got the following issue:
My Own Dataset - I have tried wi... | [
"I continue to see this problem in 2022 when using LSTMs or GRUs in Sagemaker with conda_tensorflow2_p38 kernel. Here's my workaround:\nEarly in your notebook, before defining your model, set\ntf.keras.backend.set_image_data_format(\"channels_last\")\n\nI know it looks weird to set image data format when you aren't... | [
5,
1,
0
] | [] | [] | [
"keras",
"lstm",
"python",
"python_3.x",
"tensorflow"
] | stackoverflow_0068036975_keras_lstm_python_python_3.x_tensorflow.txt |
Q:
how to install modules through pycharm
I am a PyCharm user and I was always wondering how to install a module.
I tried using command prompt but it could not define python
A:
On the bottom bar there is a tab called "Python Packages". You can search for packages you want to install there. When you select a package... | how to install modules through pycharm | I am a PyCharm user and I was always wondering how to install a module.
I tried using command prompt but it could not define python
| [
"On the bottom bar there is a tab called \"Python Packages\". You can search for packages you want to install there. When you select a package there will be a install button on the right.\n\n",
"In Pycharm press ctrl+alt+s, then go to the Python Interpreter and press the plus button to look for the module you wan... | [
2,
1
] | [] | [] | [
"module",
"python"
] | stackoverflow_0074406957_module_python.txt |
Q:
How to efficiently broadcast multiplication between arrays of shapes (n,m,k) and (n,m)
Let a be a numpy array of shape (n,m,k) and a_msk is an array of shape (n,m) containing that masks elements from a through multiplication.
Up to my knowledge, I had to create a new axis in a_msk in order to make it compatible wi... | How to efficiently broadcast multiplication between arrays of shapes (n,m,k) and (n,m) | Let a be a numpy array of shape (n,m,k) and a_msk is an array of shape (n,m) containing that masks elements from a through multiplication.
Up to my knowledge, I had to create a new axis in a_msk in order to make it compatible with a for multiplication.
b = a * a_msk[:,:,np.newaxis]
Unfortunately, my Google Colab runti... | [
"As @hpaulj commented adding an axis to make the two arrays \"compatible\" for broadcasting is the most straightforward way to do your multiplication.\nAlternatively, you can move the last axis of your array a to the front which would also make the two arrays compatible (I wonder though whether this would solve you... | [
0
] | [] | [] | [
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0074331874_numpy_numpy_ndarray_python.txt |
Q:
How to convert an ArrayList to an ArrayList?
I have integrated a java developed app in android studio with python files using chaquopy. The python file returns a List however I am struggling to convert that List to an ArrayList format (In the java file after the list is successfully returned from the Python script... | How to convert an ArrayList to an ArrayList? | I have integrated a java developed app in android studio with python files using chaquopy. The python file returns a List however I am struggling to convert that List to an ArrayList format (In the java file after the list is successfully returned from the Python script)?
My code has the following
ArrayList<Scalar> sca... | [
"Your question suggests that your Python object is a 2D \"list of lists of integers\", but it's not clear how you want to map that onto a 1D list of Scalars. I'll give an answer for a simple 1D list of integers, and hopefully you can adapt that to whatever you need.\nI'm also not sure what you mean by Scalar, but i... | [
0
] | [] | [] | [
"chaquopy",
"java",
"python"
] | stackoverflow_0074376375_chaquopy_java_python.txt |
Q:
I want my discord bot to send a specified user a dm
I would like my bot to DM someone when their application is denied.
Current code
@bot.slash_command(name="deny", description = "deny a users application")
async def deny(ctx, msg: str):
await ctx.author.send(msg)
I would also like this code to check their ro... | I want my discord bot to send a specified user a dm | I would like my bot to DM someone when their application is denied.
Current code
@bot.slash_command(name="deny", description = "deny a users application")
async def deny(ctx, msg: str):
await ctx.author.send(msg)
I would also like this code to check their role to see if they are allowed to deny people.
| [
"The only things missing in your code is a user parameter in your function, and to check if the person who issued the command has your desired role.\nYou could do it this way:\n@bot.slash_command(name=\"deny\", description = \"deny a users application\")\nasync def deny(ctx, msg: str, user: discord.User):\n role... | [
0,
0
] | [
"i dont know if i fully understanded your question, but with this code you check if a member has a role and it dms them it their application got accepted or not\n@bot.command()\nasync def deny(ctx, member: discord.Member, *,):\n role = \"\" # put the role id here\n if get(member.roles, id=role):\n chan... | [
-1
] | [
"bots",
"discord",
"pycord",
"python"
] | stackoverflow_0074041459_bots_discord_pycord_python.txt |
Q:
merge 2 csv files having different header into one csv file having all headers
I need unix/python code to generate a file:
there are 2 csv files
File a.csv
country,name
NA,Rupa
File b.csv
region,time
home,day
I need Output file.csv as:
country,name,region,time
NA,Rupa,home,day
NA,Rupa
The code I used is
cat a.csv ... | merge 2 csv files having different header into one csv file having all headers | I need unix/python code to generate a file:
there are 2 csv files
File a.csv
country,name
NA,Rupa
File b.csv
region,time
home,day
I need Output file.csv as:
country,name,region,time
NA,Rupa,home,day
NA,Rupa
The code I used is
cat a.csv > file.csv
cat b.csv >> file.csv
But its not giving me the desired output
Please he... | [
"I am sure there are much neater ways to do this, but here is a quick (and dirty) one:\nimport pandas as pd\n\nwith open('a.csv', 'r') as a, open('b.csv', 'r') as b, open('c.csv','w') as c:\n a_lst = a.readlines(); b_lst = b.readlines(); c_lst = []\n for i in range(len(a_lst)):\n c_lst.append(a_lst[i].strip() ... | [
0
] | [] | [] | [
"csv",
"python",
"unix"
] | stackoverflow_0074406290_csv_python_unix.txt |
Q:
keras: ValueError: Failed to find data adapter that can handle input
I have a deep learning model that I'm trying to test with simple input. On this line:
history = model.fit(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid))
I am getting this error:
Traceback (most recent call last):
File "/usr/l... | keras: ValueError: Failed to find data adapter that can handle input | I have a deep learning model that I'm trying to test with simple input. On this line:
history = model.fit(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid))
I am getting this error:
Traceback (most recent call last):
File "/usr/lib64/python3.6/contextlib.py", line 99, in __exit__
self.gen.throw(typ... | [
"Your x data as well as your y data need to be arrays and have the same number of samples. Here is an example:\nmodel = get_model()\nmodel.compile(loss=\"mean_squared_error\", optimizer=\"adam\", metrics=[tf.keras.metrics.MeanSquaredError()])\n\nx1 = np.random.rand(1, 182, 218, 182)\nx2 = np.random.rand(1, 182, 218... | [
1
] | [] | [] | [
"keras",
"python",
"tensorflow",
"tf.keras"
] | stackoverflow_0074407020_keras_python_tensorflow_tf.keras.txt |
Q:
How to convert array of struct of struct into string in pyspark
root
|-- id: long (nullable = true)
|-- person: struct (nullable = true)
| |-- resource: array (nullable = true)
| | |-- element: struct (containsNull = true)
| | | |-- alias: string (nullable = true)
| |-- id: string (nulla... | How to convert array of struct of struct into string in pyspark | root
|-- id: long (nullable = true)
|-- person: struct (nullable = true)
| |-- resource: array (nullable = true)
| | |-- element: struct (containsNull = true)
| | | |-- alias: string (nullable = true)
| |-- id: string (nullable = true)
|-- school: array (nullable = true)
| |-- element: s... | [
"df1 = df1.withColumn(\"school\", functions.transform(functions.col(\"school\"),\n lambda x: x.withField(\"teacher\",x['teacher'].cast('string')))) \n\nworked for me\n"
] | [
0
] | [] | [] | [
"arrays",
"dataframe",
"pyspark",
"python",
"struct"
] | stackoverflow_0074406595_arrays_dataframe_pyspark_python_struct.txt |
Q:
How to Compare rows values in Pyspark using lead\lag?
I have a dataframe having Column Name as 'YEAR',i want to check if the alternate rows of the column are matching and update another Column 'FLAG' with value as 100 if the alternate value matches.
df_prod
Year FLAG
2020 None
2020 None
2019 None
2021 ... | How to Compare rows values in Pyspark using lead\lag? | I have a dataframe having Column Name as 'YEAR',i want to check if the alternate rows of the column are matching and update another Column 'FLAG' with value as 100 if the alternate value matches.
df_prod
Year FLAG
2020 None
2020 None
2019 None
2021 None
2021 None
2022 None
Expected Output
**
Year FL... | [
"The following snippet, which uses Windowing function, should do that for you:\nfrom pyspark.sql.window import Window\nfrom pyspark.sql.functions import col, lag, when\n\ndf = spark.createDataFrame([(2020, None), (2020, None), (2019, None), (2021, None), (2021, None), (2022, None)], \"Year: int, FLAG: int\")\n\nwin... | [
1
] | [] | [] | [
"apache_spark",
"databricks",
"pyspark",
"python"
] | stackoverflow_0074406224_apache_spark_databricks_pyspark_python.txt |
Q:
How to fix the discord embed?
Here is my code snipet, and it dont work can you improve it please
i´m a beginner because of that i need help
@bot.command()
@commands.has_permissions(administrator = True)
async def rules(ctx, member : discord.Member):
channel = channel or ctx.channel
embed = discord.Embed(title=... | How to fix the discord embed? | Here is my code snipet, and it dont work can you improve it please
i´m a beginner because of that i need help
@bot.command()
@commands.has_permissions(administrator = True)
async def rules(ctx, member : discord.Member):
channel = channel or ctx.channel
embed = discord.Embed(title=f"{member}", description=f"Read the... | [
"Can you be more specific what is not working? Displaying it in chat?\nembed = discord.Embed(...) will just give you a instance of an Embed object, that is just locally on your machine, no communcation with discord yet.\nAt this point you can still can still manipulate before sending it do the channel via:\nawait c... | [
0,
0
] | [] | [] | [
"discord",
"embed",
"pycord",
"python"
] | stackoverflow_0074003978_discord_embed_pycord_python.txt |
Q:
Python VTK on M2 macbook air
I am writing this code for simulation of earths magnetic field:
import numpy as np
import matplotlib.pyplot as plt
import magpylib as magpy
import pyvista as pv
ts = np.linspace(-8,8, 150)
t = np.linspace(-6,6, 150)
axis = np.c_[2*np.cos(ts*2*np.pi), 2*np.sin(ts*2*np.pi), ts]
aux = np... | Python VTK on M2 macbook air | I am writing this code for simulation of earths magnetic field:
import numpy as np
import matplotlib.pyplot as plt
import magpylib as magpy
import pyvista as pv
ts = np.linspace(-8,8, 150)
t = np.linspace(-6,6, 150)
axis = np.c_[2*np.cos(ts*2*np.pi), 2*np.sin(ts*2*np.pi), ts]
aux = np.c_[2*np.cos(ts*2*np.pi), 2*np.sin... | [
"First, you need to post a question, not just code + error message.\nBased off of your error message, this is what I would try:\nEnsure VTK is installed. https://pypi.org/project/vtk/\nTry a different Python version. 3.11 is fresh off the shelf and it looks like the VTK library was last updated prior to 3.11's rele... | [
0,
0
] | [] | [] | [
"dependencies",
"macos",
"python",
"pyvista",
"vtk"
] | stackoverflow_0074376018_dependencies_macos_python_pyvista_vtk.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.