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:
TSF Gives Different Results on Different Machines Despite Fixed NumPy Seed
I have a time series forecasting application where the algorithm can be selected from 2 choices:
sklearn Linear Regression
statsmodels ARIMA vs. SARIMAX (based on the seasonality of the data)
There's no attribute to set the seed when the ... | TSF Gives Different Results on Different Machines Despite Fixed NumPy Seed | I have a time series forecasting application where the algorithm can be selected from 2 choices:
sklearn Linear Regression
statsmodels ARIMA vs. SARIMAX (based on the seasonality of the data)
There's no attribute to set the seed when the class object is initialized and then the fit function is called, so I am setting... | [
"Thanks to @NickODell comment, the issue was solved as the following:\n\nARIMA/SARIMAX\n\nfor the ARIMA/SARIMAX model, a random state should be defined with a specific seed and then be passed to the pm.auto_arima function. The reason is that pm.auto_arima uses a train_test_split function (which usually takes a seed... | [
0
] | [] | [] | [
"numpy",
"python",
"random",
"scikit_learn",
"statsmodels"
] | stackoverflow_0074474991_numpy_python_random_scikit_learn_statsmodels.txt |
Q:
how to share contents of dataset across all processes
As shown in the code posted below, i have contents of a dataset represented in object mainTIFFImageDatasetContents.
each time run() is called i collect some data in a form of an objects as shonw in the next line:
if (pixelsValuesSatisfyThresholdInTIFFImageDatas... | how to share contents of dataset across all processes | As shown in the code posted below, i have contents of a dataset represented in object mainTIFFImageDatasetContents.
each time run() is called i collect some data in a form of an objects as shonw in the next line:
if (pixelsValuesSatisfyThresholdInTIFFImageDatasetCnt > 0):
gridCellInnerLoopsIteratorsForNoneZeroC... | [
"this example shows how to copy a variable once to all children using an initializer that only runs once per child process.\nfrom multiprocessing import Pool\n\ndef foo(number):\n print(number, global_obj)\n\ndef initializer_func(argument):\n global global_obj\n global_obj = argument\n\nif __name__ == \"__... | [
1
] | [] | [] | [
"multiprocessing",
"python",
"python_multiprocessing"
] | stackoverflow_0074516846_multiprocessing_python_python_multiprocessing.txt |
Q:
Transpose column to row with Spark
I'm trying to transpose some columns of my table to row.
I'm using Python and Spark 1.5.0. Here is my initial table:
+-----+-----+-----+-------+
| A |col_1|col_2|col_...|
+-----+-------------------+
| 1 | 0.0| 0.6| ... |
| 2 | 0.6| 0.7| ... |
| 3 | 0.5| 0.9| .... | Transpose column to row with Spark | I'm trying to transpose some columns of my table to row.
I'm using Python and Spark 1.5.0. Here is my initial table:
+-----+-----+-----+-------+
| A |col_1|col_2|col_...|
+-----+-------------------+
| 1 | 0.0| 0.6| ... |
| 2 | 0.6| 0.7| ... |
| 3 | 0.5| 0.9| ... |
| ...| ...| ...| ... |
I wou... | [
"Spark >= 3.4\nYou can use built-in melt method. With Python:\ndf.melt(\n ids=[\"A\"], values=[\"col_1\", \"col_2\"],\n variableColumnName=\"key\", valueColumnName=\"val\"\n)\n\nwith Scala\ndf.melt(Array($\"A\"), Array($\"col_1\", $\"col_2\"), \"key\", \"val\")\n\nSpark < 3.4\nIt is relatively simple to do wi... | [
70,
11,
7,
6,
2,
1,
1,
1,
0
] | [] | [] | [
"apache_spark",
"pivot",
"python",
"transpose"
] | stackoverflow_0037864222_apache_spark_pivot_python_transpose.txt |
Q:
Python: create a boolean df from existing df, if column values equal to
I noticed an error in my code and would like to use your help with my GUI.
I have a function which get a selected column name (line 3), identifies all the unique values of the column and later on create new data frames equal to the number of u... | Python: create a boolean df from existing df, if column values equal to | I noticed an error in my code and would like to use your help with my GUI.
I have a function which get a selected column name (line 3), identifies all the unique values of the column and later on create new data frames equal to the number of unique values.
I noticed an issue with the line 8,
firstly I am using contain... | [
"You need to make sure your column is of type string before trying to call the str accessor on it. Just try:\ndf_output = df[df[column].astype('string').str.contains(i)]\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074520074_dataframe_python.txt |
Q:
check number that are non-negative integer and not alphabet
i want to continue the loop for asking input(), i use "type(p) is not int" to check the alphabet number, but i get UnboundLocalError when i use "type(p) is not int"
def check(p):
"""
>>> get the value which is non-negative integer and not alphabet
... | check number that are non-negative integer and not alphabet | i want to continue the loop for asking input(), i use "type(p) is not int" to check the alphabet number, but i get UnboundLocalError when i use "type(p) is not int"
def check(p):
"""
>>> get the value which is non-negative integer and not alphabet
Checking if the input is negative or not.
or repeat asking f... | [
"def check(num):\n while type(num) is not int or num < 0:\n try:\n num = int(input(\"Invaild response, please try again:\"))\n except ValueError:\n pass\n return num\n\n \ncheck(\"4\")\n\nOutputs:\nprint(check(-4))\n\n#Output: Invaild response, please try again:\n\npri... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074520106_python.txt |
Q:
I want to Create a csv file containing 1000 rows for which random number is generated
Problem: Create a text/csv file containing 1000 rows with the following fields/columns:
StudentID: unique identifier 1:1000
Score: Random number between 40-100
Date: Any random date within the last 20 days. Eg: 18/11/2022
Descrip... | I want to Create a csv file containing 1000 rows for which random number is generated | Problem: Create a text/csv file containing 1000 rows with the following fields/columns:
StudentID: unique identifier 1:1000
Score: Random number between 40-100
Date: Any random date within the last 20 days. Eg: 18/11/2022
Description: Get a random word from a list of 10 words of your choice
Ethnicity: Randomly assign a... | [
"you could use list comprehensions together with pandas dataframes something along the lines of this:\nimport pandas as pd\n\n# randomly chooses an element of your list/tuple 1000 times\ndescription_choices = [random.choice(description_list) for _ in range(1000)]\n...\n\n# create table with random data\ndf = pd.Dat... | [
0
] | [] | [] | [
"csv",
"python",
"python_3.x"
] | stackoverflow_0074520201_csv_python_python_3.x.txt |
Q:
Pytorch progress bar disappear on vscode jupyter
I have problem when training Pytorch model, the progress bar of is disappeared by no reason today. It still work properly the days before. I'm using jupyter through vs code, connect to the kernel that run on the Ubuntu subsystem. How can I show the progress bar as n... | Pytorch progress bar disappear on vscode jupyter | I have problem when training Pytorch model, the progress bar of is disappeared by no reason today. It still work properly the days before. I'm using jupyter through vs code, connect to the kernel that run on the Ubuntu subsystem. How can I show the progress bar as normal
| [
"I had this issue and it seems to come from a problem with tqdm for new versions of ipywidget (see https://github.com/microsoft/vscode-jupyter/issues/8552).\nAs mentioned in the link, I solved it by downgrading ipywidgets:\npip install ipywidgets==7.7.2\n\n"
] | [
1
] | [] | [] | [
"progress",
"python",
"pytorch"
] | stackoverflow_0073526940_progress_python_pytorch.txt |
Q:
calculating the percentage of count in pandas groupby
I want to discover the underlying pattern between my features and target so I tried to use groupby but instead of the count I want to calculate the ratio or the percentage compared to the total of the count of each class
the following code is similar to the wor... | calculating the percentage of count in pandas groupby | I want to discover the underlying pattern between my features and target so I tried to use groupby but instead of the count I want to calculate the ratio or the percentage compared to the total of the count of each class
the following code is similar to the work I have done.
fet1=["A","B","C"]
fet2=["X","Y","Z"]
target... | [
"You can achieve this more simply with:\nout = df.groupby('class').value_counts(normalize=True).mul(100)\n\nOutput:\nclass fet1 fet2\n0 A Y 13.859275\n B Y 12.366738\n X 12.153518\n C X 11.513859\n Y 10.660981\n B Z ... | [
1
] | [
"I achieved it by doing this\nfet1=[\"A\",\"B\",\"C\"]\nfet2=[\"X\",\"Y\",\"Z\"]\ntarget=[\"0\",\"1\"]\ndf = pd.DataFrame(data={\"fet1\":np.random.choice(fet1,1000),\"fet2\":np.random.choice(fet2,1000),\"class\":np.random.choice(target,1000)})\ndf.groupby(['fet1','fet2','class'])['class'].agg(['count'])/df.groupby(... | [
-1
] | [
"pandas",
"python"
] | stackoverflow_0074520280_pandas_python.txt |
Q:
How to return a value through recursive call in Python
I am trying a to solve a problem. There are a few programs where I have to return a value in variable throughout various function calls(Recursive calls). I am not sure how to do that.
I am trying Merge Sort algorithm in python this is the implementation:
def m... | How to return a value through recursive call in Python | I am trying a to solve a problem. There are a few programs where I have to return a value in variable throughout various function calls(Recursive calls). I am not sure how to do that.
I am trying Merge Sort algorithm in python this is the implementation:
def merge(arr,lo,hi):
mid=(lo+hi)//2
c=0
i=lo; j=mid+... | [
"All you need to do is add up the values returned by each recursive call and by merge, then return that value.\ndef mergeSort(arr,lo,hi):\n if lo==hi:\n return 0\n c = 0\n mid=(lo+hi)//2\n c += mergeSort(arr,lo,mid)\n c += mergeSort(arr,mid+1,hi)\n c += merge(arr,lo,hi)\n return c\n\n"
] | [
0
] | [] | [] | [
"mergesort",
"python",
"recursion"
] | stackoverflow_0074519892_mergesort_python_recursion.txt |
Q:
How to read file with space separated values in pandas
I try to read the file into pandas.
The file has values separated by space, but with different number of spaces
I tried:
pd.read_csv('file.csv', delimiter=' ')
but it doesn't work
A:
add delim_whitespace=True argument, it's faster than regex.
A:
you can u... | How to read file with space separated values in pandas | I try to read the file into pandas.
The file has values separated by space, but with different number of spaces
I tried:
pd.read_csv('file.csv', delimiter=' ')
but it doesn't work
| [
"add delim_whitespace=True argument, it's faster than regex.\n",
"you can use regex as the delimiter:\npd.read_csv(\"whitespace.csv\", header=None, delimiter=r\"\\s+\")\n\n",
"If you can't get text parsing to work using the accepted answer (e.g if your text file contains non uniform rows) then it's worth trying... | [
218,
47,
0,
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0019632075_csv_pandas_python.txt |
Q:
MT5 machine learning model for paraphrasing
I'm trying to create a machine learning model to paraphrase given Persian text. I was introduced to mt5 as a multilingual text-to-text model. However, I can't figure out how to implement this. I have gathered the data. Here's a sample of the data:
Data sample
---UPDATE--... | MT5 machine learning model for paraphrasing | I'm trying to create a machine learning model to paraphrase given Persian text. I was introduced to mt5 as a multilingual text-to-text model. However, I can't figure out how to implement this. I have gathered the data. Here's a sample of the data:
Data sample
---UPDATE---
I have tried to paraphrase using the T5 model, ... | [
"IMHO mT5 can't be used for paraphrase generation out-of-the-box, just like the T5 can. You can find fine-tuned versions of the T5 model intended for paraphrase generation on the HuggingFace Hub, such as this one. There's a paper associated with the model and you may find the solution there. As far as I understand ... | [
0
] | [] | [] | [
"machine_learning",
"nlp",
"python"
] | stackoverflow_0074149057_machine_learning_nlp_python.txt |
Q:
Fancy indexing calculation of adjacency matrix from adjacency list
Problem:
I want to calculate at several times the adjacency matrix A_ij given the adjacency list E_ij, where E_ij[t,i] = j gives the edge from i to j at time t.
I can do it with the following code:
import numpy as np
nTimes = 100
nParticles = 10
A... | Fancy indexing calculation of adjacency matrix from adjacency list | Problem:
I want to calculate at several times the adjacency matrix A_ij given the adjacency list E_ij, where E_ij[t,i] = j gives the edge from i to j at time t.
I can do it with the following code:
import numpy as np
nTimes = 100
nParticles = 10
A_ij = np.full((nTimes, nParticles, nParticles), False)
E_ij = np.random.... | [
"I think this might work:\nimport numpy as np\n\nnTimes = 100\nnParticles = 10\nA_ij = np.full((nTimes, nParticles, nParticles), False)\nE_ij = np.random.randint(0, 9, (100, 10))\n\nnp.put_along_axis(A_ij, E_ij[..., None], True, axis=2)\n\n",
"In case it may help other people, I also found a way to do fancy index... | [
2,
1,
1
] | [] | [] | [
"array_broadcasting",
"numpy",
"numpy_ndarray",
"python",
"vectorization"
] | stackoverflow_0074519974_array_broadcasting_numpy_numpy_ndarray_python_vectorization.txt |
Q:
Storing The Output of a Permutation as a List of Lists
When I run the following code I get rows of tuples:
{perm = itertools.permutations(['A','B','C','D','E','F'],4)
for val in perm:
print(val)}.
How do I make the code give me the output as a single list of lists instead of rows of tuples?
When I r... | Storing The Output of a Permutation as a List of Lists | When I run the following code I get rows of tuples:
{perm = itertools.permutations(['A','B','C','D','E','F'],4)
for val in perm:
print(val)}.
How do I make the code give me the output as a single list of lists instead of rows of tuples?
When I run the code I get something like this
('F', 'E', 'B', 'C')
(... | [
"cast val into a list and append it to another list.\nimport itertools\nperm = itertools.permutations(['A','B','C','D','E','F'],4)\n\nresult = []\nfor val in perm:\n result.append(list(val))\n\nprint(result)\n\nThe question is, do you want to generate all permutations and store them?\nAs you have it now, the gen... | [
2
] | [] | [] | [
"list",
"loops",
"permutation",
"python",
"tuples"
] | stackoverflow_0074520401_list_loops_permutation_python_tuples.txt |
Q:
how to search for links using telethon
Is there any way I can filter the messages I get from:
client.get_messages()
to a spasific pattern? (in this case links)
I can filter it after I get all the messages but if there is a way to do it earlier that would be better.
A:
get_messages (or iter_messages) supports fi... | how to search for links using telethon | Is there any way I can filter the messages I get from:
client.get_messages()
to a spasific pattern? (in this case links)
I can filter it after I get all the messages but if there is a way to do it earlier that would be better.
| [
"get_messages (or iter_messages) supports filter argument that takes any of MessagesFilter constructors.\nso in your case, use:\nawait client.get_messages(chat,\n filter=telethon.types.InputMessagesFilterUrl()\n)\n\n"
] | [
3
] | [] | [] | [
"python",
"scrape",
"telegram",
"telethon"
] | stackoverflow_0074520325_python_scrape_telegram_telethon.txt |
Q:
Pd.crosstab missing data?
I am using pd.crosstab to count presence/absence data. In the first column, I have several presence counts (represented by 1's), in the second column I have just one 'presence'. Howwever, when I run crosstab on this data that single presence in the second column isn't counted. Could anyon... | Pd.crosstab missing data? | I am using pd.crosstab to count presence/absence data. In the first column, I have several presence counts (represented by 1's), in the second column I have just one 'presence'. Howwever, when I run crosstab on this data that single presence in the second column isn't counted. Could anyone shed some light on why this h... | [
"You can use the dropna parameter, which is by default set to True. Setting it to False will include columns whose entries are all NaN.\ncontingency_tab = pd.crosstab(mbx_final['Cmpd1640'],mgx_final['Otu2409'],margins=True, dropna=False)\n\nYou can read more on the official documentation here: https://pandas.pydata... | [
2
] | [] | [] | [
"contingency",
"pandas",
"pivot_table",
"python"
] | stackoverflow_0074520394_contingency_pandas_pivot_table_python.txt |
Q:
jaydebeapi.connect always returning: "TypeError: Class sajdbc4.jar is not found"
I am trying to use the jaydebeapi python package to create a jdbc database connection, but no matter what argument I put in the connect method I get the same error: "TypeError: Class [first_argurment_str] is not found"
import jaydebea... | jaydebeapi.connect always returning: "TypeError: Class sajdbc4.jar is not found" | I am trying to use the jaydebeapi python package to create a jdbc database connection, but no matter what argument I put in the connect method I get the same error: "TypeError: Class [first_argurment_str] is not found"
import jaydebeapi
conn = jaydebeapi.connect('sajdbc4.jar', connectionString,[userName, Password])
I... | [
"I fixed the problem by adding several file paths to the $CLASSPATH variable and ensuring that the environment variables were present in the script. Ultimately, I needed more than one file added to $CLASSPATH. Solution below (your file paths will obviously differ)\nos.environ['Path'] = os.environ['Path']+f';D:\\\\U... | [
2,
0
] | [] | [] | [
"java",
"jaydebeapi",
"jdbc",
"python",
"sybase"
] | stackoverflow_0073514224_java_jaydebeapi_jdbc_python_sybase.txt |
Q:
Deleting values from array with np.diff
I need to edit an array. The array has two columns. One for X-Values, the other for Y-Values. The X-Values are 0.0025 steps (0, 0.0025, 0.005, etc.) but sometimes there are wrong steps and I need to delete those. The others recommend that I use the following:
data = data[~n... | Deleting values from array with np.diff | I need to edit an array. The array has two columns. One for X-Values, the other for Y-Values. The X-Values are 0.0025 steps (0, 0.0025, 0.005, etc.) but sometimes there are wrong steps and I need to delete those. The others recommend that I use the following:
data = data[~np.r_[True, (np.diff(data[:,0])>0)&(np.diff(da... | [
"The reason the first element is always being deleted is because you invert the output of np.r_ which prepends True to the output of np.diff. When using ~, that gets turned into a False, and thus the first element gets deleted.\nMy guess that the step after gets deleted too is because np.diff checks the difference ... | [
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074520324_arrays_numpy_python.txt |
Q:
ValueError: Using a target size (torch.Size([16])) that is different to the input size (torch.Size([13456, 1])) is deprecated
My code: https://colab.research.google.com/drive/1qjfy2OsHYewhHDej-W83CMNercB7o7r8?usp=sharing
the error: ValueError: Using a target size (torch.Size([16])) that is different to the input s... | ValueError: Using a target size (torch.Size([16])) that is different to the input size (torch.Size([13456, 1])) is deprecated | My code: https://colab.research.google.com/drive/1qjfy2OsHYewhHDej-W83CMNercB7o7r8?usp=sharing
the error: ValueError: Using a target size (torch.Size([16])) that is different to the input size (torch.Size([13456, 1])) is deprecated. Please ensure they have the same size.
the dataset consists of 2 folders: 0 and 1, and ... | [
"The original code is intended for 64 x 64 images, not 512 x 512 ones. To fix the problem, you have to either downsize the images to 64 x 64 or modify the discriminator and the generator.\n",
"label = torch.full((b_size,), real_label, dtype=torch.float, device=device)\n\nThis creates an array of size b_size (16) ... | [
1,
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074513451_python_pytorch.txt |
Q:
Extracting variable name from file name
I am trying to extract variable names from file names as follows:
happy = "LOL"
angry = "GRRRR"
surprised= "YUPPIE"
file_names=["happy.wav","angry.wav","surprised.wav"
for i in file_names:
name = i.split('.')
name_=name[0]
print(name_)
I get the output as:
happy
angr... | Extracting variable name from file name | I am trying to extract variable names from file names as follows:
happy = "LOL"
angry = "GRRRR"
surprised= "YUPPIE"
file_names=["happy.wav","angry.wav","surprised.wav"
for i in file_names:
name = i.split('.')
name_=name[0]
print(name_)
I get the output as:
happy
angry
surprised
when I wish to get the output a... | [
"Use a dict, not individual variables, when the variable names should be treated as data.\nd = {\"happy\": \"LOL\", \"angry\": \"GRRRR\", \"surprised\": \"YUPPIE\"}\nfor i in file_names:\n name = i.split(\".\")[0]\n print(d[name])\n\n",
"I think you are going about this the wrong way. What if the file_names... | [
0,
0
] | [] | [] | [
"filenames",
"for_loop",
"python",
"string",
"variable_assignment"
] | stackoverflow_0074520422_filenames_for_loop_python_string_variable_assignment.txt |
Q:
How to use a jwt.io provisioned token with jwcrypto?
I am trying to use a jwt.io generated JWT within my python code using jwcrypto with some success. I am saying some success because I am able to retrieve the claims (the wrong way) without validating the signature.
Here's my code
from jwcrypto import jwt, jwk
j... | How to use a jwt.io provisioned token with jwcrypto? | I am trying to use a jwt.io generated JWT within my python code using jwcrypto with some success. I am saying some success because I am able to retrieve the claims (the wrong way) without validating the signature.
Here's my code
from jwcrypto import jwt, jwk
jwtIoToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIi... | [
"You can find the key that jwt.io uses in the right column under \"VERIFY SIGNATURE\".\nUnless you add anything different, the default value is \"your-256-bit-secret\".\n\nWhen you use that value, you can verify the signature with the code below.\njwcrypto is a bit more complicated to use than pyjwt. Here you first... | [
1,
1
] | [] | [] | [
"jwcrypto",
"jwt",
"python"
] | stackoverflow_0073692941_jwcrypto_jwt_python.txt |
Q:
How to make and remove entity according to time in ursina
I want to make Maze-Runner in ursina and change maze according to real time.
So, I use 'from datetime import datetime' and get real time in every frame.
I want to make the maze change every 6 minutes in reality, but is there a way to create or eliminate ent... | How to make and remove entity according to time in ursina | I want to make Maze-Runner in ursina and change maze according to real time.
So, I use 'from datetime import datetime' and get real time in every frame.
I want to make the maze change every 6 minutes in reality, but is there a way to create or eliminate entities over time?
There is part of my cord.
maze = []
maze1 = En... | [
"You can use invoke and function\nLike:\ninvoke (recrete_maze, delay=6000)\n\nI will check this code when I get home.\n"
] | [
0
] | [] | [] | [
"python",
"ursina"
] | stackoverflow_0074414500_python_ursina.txt |
Q:
Installing zlib on windows
I use python to automate boring stuff I do daily (I'm not really a "programmer").
I've been building a script to compress my files to a zip folder. For that, I'm using zipfile library, but it only creates a ZIP file without compressing them.
In order to do that, they recommend to install... | Installing zlib on windows | I use python to automate boring stuff I do daily (I'm not really a "programmer").
I've been building a script to compress my files to a zip folder. For that, I'm using zipfile library, but it only creates a ZIP file without compressing them.
In order to do that, they recommend to install zlib module and use the ZIP_DEF... | [
"The solution as said by @mechanical_meat is to use Python 3 instead, because Python 2.x is deprecated,\nNote: just use the built-in zipfile, example of how to create compressed archive files here: stackoverflow.com/a/38550416/42346 –\n"
] | [
1
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0070462794_python_python_2.7.txt |
Q:
Writing custom log files in Databricks Repos using the logging package
I would like to capture custom metrics as a notebook runs in Databricks. I would like to write these to a file using the logging package. The code below seems to run fine but it never writes to file. How do you achieve this in Databricks runtim... | Writing custom log files in Databricks Repos using the logging package | I would like to capture custom metrics as a notebook runs in Databricks. I would like to write these to a file using the logging package. The code below seems to run fine but it never writes to file. How do you achieve this in Databricks runtime 9.1?
Also note that I am running this is Repos so I have to explicitly wri... | [
"Perhaps the /dbfs/tmp directory doesn't exist, or you don't have write access to it. Changing the log filename to just mylog.log, it works as expected:\n~/SO-logging-misc$ python so_74519222.py\n~/SO-logging-misc$ more my_log.log \n2022-11-21 14:33:22 - WARNING - starting to log the process\n\n"
] | [
1
] | [] | [] | [
"azure_repos",
"databricks",
"logging",
"python"
] | stackoverflow_0074519222_azure_repos_databricks_logging_python.txt |
Q:
How to put other model classes belonging (linked) to a main model class. And how to write this in Views.py. (This is Not FK)
I have a main model, called "Employees", and I need to link to it another 16 model classes (Employees Additional Data, Employees Observations, etc) in the same app. What would be the best wa... | How to put other model classes belonging (linked) to a main model class. And how to write this in Views.py. (This is Not FK) | I have a main model, called "Employees", and I need to link to it another 16 model classes (Employees Additional Data, Employees Observations, etc) in the same app. What would be the best way to write these classes in models.py?
Could be like that?
class Employees(models.Model):
class Meta:
db_table = "empl... | [
"You'll need to use a foreign key to your Employee model :\nclass Employee(models.Model):\n class Meta:\n db_table = \"employees\"\n \n #fields\n #fields\n\n\nclass EmployeesObs(models.Model):\n class Meta:\n db_table = \"employeesobs\"\n \n employee = models.ForeignKey(Employ... | [
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0074519706_django_django_models_django_views_python.txt |
Q:
Convert index in column header in python dataframe
I am trying to convert python dataframe into column headers. I am using transpose function but results are not as expected. Which function can be used to accomplish the results as given below?
data is:
Year 2020
Month SEPTEMBER
Filed Date 29-11-2020
Year ... | Convert index in column header in python dataframe | I am trying to convert python dataframe into column headers. I am using transpose function but results are not as expected. Which function can be used to accomplish the results as given below?
data is:
Year 2020
Month SEPTEMBER
Filed Date 29-11-2020
Year 2022
Month JULY
Filed Date 20-08-2022
Year 2022
Mo... | [
"You can do it like this:\ndf = pd.DataFrame(\n [df1.iloc[i:i+3][1].tolist() for i in range(0, len(df1), 3)],\n columns=df1.iloc[0:3][0].tolist(),\n)\n\nprint(df):\n Year Month Filed\n0 2020 SEPTEMBER Date 29-11-2020\n1 2022 JULY Date 20-08-2022\n2 2022 APRIL Date 20-05... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074519555_python.txt |
Q:
Snowflake REST APIs
The python native connector for snowflake uses REST Apis as per PEP249. Looking into the code of this connector, it seems to use REST APIs like
/queries/v1/query-request
ret = self.rest.request(
"/queries/v1/query-request?" + urlencode(url_parameters),
data,
client=clien... | Snowflake REST APIs | The python native connector for snowflake uses REST Apis as per PEP249. Looking into the code of this connector, it seems to use REST APIs like
/queries/v1/query-request
ret = self.rest.request(
"/queries/v1/query-request?" + urlencode(url_parameters),
data,
client=client,
_no_results=_n... | [
"The REST API endpoints are not documented as you are supposed to use the Python connector API, not the REST API.\nIf you want to use a REST API then indeed use the SQL API.\n"
] | [
1
] | [] | [] | [
"python",
"snowflake_cloud_data_platform"
] | stackoverflow_0074520506_python_snowflake_cloud_data_platform.txt |
Q:
How to get the same string repeated for all the values in a python list
I'm wondering which will be the best pythonic way to get all the same prefix for the values in a list.
Rule #1: the word will be compound by the following parts: prefix + name + end (separated by '_'.
Rule #2: all the word parts will be varia... | How to get the same string repeated for all the values in a python list | I'm wondering which will be the best pythonic way to get all the same prefix for the values in a list.
Rule #1: the word will be compound by the following parts: prefix + name + end (separated by '_'.
Rule #2: all the word parts will be variable in length
Rule #3: the end of the word is a two-character string starting... | [
"use os.path.commonprefix(). Please check out: os.path\n",
"Thanks to Pranav:\nimport os\ns_l = []\nfor v in list1: s_l.append(v.split('_'))\nprint(os.path.commonprefix(s_l))\n\n"
] | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0073705031_python.txt |
Q:
TypeError: 'float' object is not callable on streamlit site
so, i want to implement some math formula to my streamlit app, for my project. but there is an error like this:
import streamlit as st
st.title("PERSAMAAN FUNGSI KUADRAT")
st.header("DISKRIMINAN (b² -4 a c)")
db = st.number_input("Masukan Nilai b")
da = ... | TypeError: 'float' object is not callable on streamlit site | so, i want to implement some math formula to my streamlit app, for my project. but there is an error like this:
import streamlit as st
st.title("PERSAMAAN FUNGSI KUADRAT")
st.header("DISKRIMINAN (b² -4 a c)")
db = st.number_input("Masukan Nilai b")
da = st.number_input("Masukan Nilai a")
dc = st.number_input("Masukan ... | [
"import streamlit as st\n\nst.title(\"PERSAMAAN FUNGSI KUADRAT\")\nst.header(\"DISKRIMINAN (b² -4 a c)\")\n\ndb = st.number_input(\"Masukan Nilai b\", value=0)\nda = st.number_input(\"Masukan Nilai a\", value=0)\ndc = st.number_input(\"Masukan Nilai c\", value=0)\n\ndd = db * db - (4 * (da * dc)) # Correction\nst.... | [
1
] | [] | [] | [
"python",
"streamlit"
] | stackoverflow_0074519919_python_streamlit.txt |
Q:
Pyomo: Best way to optimize size of power plants and TypeError: unsupported operand type(s) for *: 'float' and 'IndexedVar'
I am trying to solve a optimization problem where the load demand has to be met by two power plants.
These power plants have different power production. For example (random numbers)
power_pro... | Pyomo: Best way to optimize size of power plants and TypeError: unsupported operand type(s) for *: 'float' and 'IndexedVar' | I am trying to solve a optimization problem where the load demand has to be met by two power plants.
These power plants have different power production. For example (random numbers)
power_prod1 = [2,0,1]
power_prod2 = [0,1,1]
The load demand and cost of different power plants is given in a similar way.The costs refer ... | [
"There are several things that are troublesome here. I'm not sure if your underlying math problem is sound. I'd slow down with the implementation and lay out all of the variables and indices with pencil and paper to make sure it makes sense. For instance, you have plant size as a variable that is indexed over ti... | [
0
] | [] | [] | [
"gurobi",
"optimization",
"pyomo",
"python"
] | stackoverflow_0074518220_gurobi_optimization_pyomo_python.txt |
Q:
How to find the most frequent pixel value in an image?
Editors comment:
How to count pixels occurences in an image?
I have a set of images where each pixel consists of 3 integers in the range 0-255.
I am interested in finding one pixel that is "representative" (as much as possible) for the entire pixel-populatio... | How to find the most frequent pixel value in an image? | Editors comment:
How to count pixels occurences in an image?
I have a set of images where each pixel consists of 3 integers in the range 0-255.
I am interested in finding one pixel that is "representative" (as much as possible) for the entire pixel-population as a whole, and that pixel must occur in the pixel-popu... | [
"I'm going to assume you need to find the most common element, which as Cris Luengo mentioned is called the mode. I'm also going to assume that the bit depth of the channels is 8-bit (value between 0 and 255, i.e. modulo 256).\nHere is an implementation independent approach:\nThe aim is to maintain a count of all t... | [
3,
0
] | [] | [] | [
"computer_vision",
"image",
"image_processing",
"python"
] | stackoverflow_0052591281_computer_vision_image_image_processing_python.txt |
Q:
Who do u get this errors while compiling discord bot
import discord
from discord.ext import commands
import sqlite3
from config import settings
client = discord.Client(intents = discord.Intents().all())
client = commands.Bot(command_prefix='!', intents= 8)
connection = sqlite3.connec... | Who do u get this errors while compiling discord bot | import discord
from discord.ext import commands
import sqlite3
from config import settings
client = discord.Client(intents = discord.Intents().all())
client = commands.Bot(command_prefix='!', intents= 8)
connection = sqlite3.connect('server.db')
cursor = connection.cursor()
@clie... | [
"Not sure why you are defining client twice right next to each other, but the intents section of the client definition doesn't accept an integer value, separate from permissions, which does. Here is the solution I came up with which is how I setup most of my bots:\nintents = discord.Intents().all()\nclient = comman... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074503303_python.txt |
Q:
Creating a new dataframe to contain a section of 1 column from multiple csv files in Python
So I am trying to create a new dataframe that includes some data from 300+ csv files.
Each file contains upto 200,000 rows of data, I am only interested in 1 of the columns within each file (the same column for each file)
I... | Creating a new dataframe to contain a section of 1 column from multiple csv files in Python | So I am trying to create a new dataframe that includes some data from 300+ csv files.
Each file contains upto 200,000 rows of data, I am only interested in 1 of the columns within each file (the same column for each file)
I am trying to combine these columns into 1 dataframe, where column 6 from csv 1 would be in the 1... | [
"Based on your description, I am inferring that you have a number of different files in csv format, each of which has at least 2000 lines and 6 columns. You want to take the data only from the 6th column of each file and only for the middle 2000 records in each file and to put all of those blocks of 2000 records in... | [
0
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074488035_csv_dataframe_pandas_python.txt |
Q:
How do I install pygame with cmd?
I have an idea for a game that uses the module pygame. The thing is, I don’t know how to install it.
I have tried to open up cmd and type:
pip install pygame
But it came up with an error saying:
pip is not recognized as an internal or external command
Please help me.
A:
To ins... | How do I install pygame with cmd? | I have an idea for a game that uses the module pygame. The thing is, I don’t know how to install it.
I have tried to open up cmd and type:
pip install pygame
But it came up with an error saying:
pip is not recognized as an internal or external command
Please help me.
| [
"To install pygame you need to write the command:\npip install pygame\nin your command prompt, if that does not work try:\npip3 install pygame\nIf that fails, make sure to install python from this link.\nMake sure to add python and pip to your environment path. Restart your computer and then try again!\nIf you have... | [
0,
0,
0
] | [] | [] | [
"pip",
"pycharm",
"pygame",
"python"
] | stackoverflow_0066070289_pip_pycharm_pygame_python.txt |
Q:
Pandas declare dtypes before loading data
i have a problem with RAM usage - I fetch quite a lot of data from DB and pour it into a pandas DataFrame, where I do groub_by to list - something DB is not very good at.
Thing is, as I fetch around 40 columns, pandas is not really good in determining the dtypes for each c... | Pandas declare dtypes before loading data | i have a problem with RAM usage - I fetch quite a lot of data from DB and pour it into a pandas DataFrame, where I do groub_by to list - something DB is not very good at.
Thing is, as I fetch around 40 columns, pandas is not really good in determining the dtypes for each column. I would love to specify dtype for each c... | [
"you might wanna try the pandas method read_sql_query to directly read the sql query into a dataframe, you can give the dtype dict that you created exactly as you made it as the dtype arg.\nonly extra thing you need is to create a connection to your database beforehand through sqlite3 for example.\n",
"I would tr... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074520410_pandas_python.txt |
Q:
Is there a short form for accessing dictionary values in for loop in Python?
Is there a short form for accessing dictionary values in for loop in Python?
I have the following example code:
dict = [{"name": "testdata"}, {"name": "testdata2"}]
for x in dict:
print(x["name"])
Is there a way to write the diction... | Is there a short form for accessing dictionary values in for loop in Python? | Is there a short form for accessing dictionary values in for loop in Python?
I have the following example code:
dict = [{"name": "testdata"}, {"name": "testdata2"}]
for x in dict:
print(x["name"])
Is there a way to write the dictionary key directly into the line of the for loop, e.g.
dict = [{"name": "testdata"},... | [
"You can't destructure a dict on assignment, so the only way would be to loop over an iterable that contains only the one value you want, e.g.:\nfor x in (i['name'] for i in dict):\n ...\n\nor:\nfrom operator import itemgetter\n\nfor x in map(itemgetter('name'), dict):\n ...\n\n",
"You won't get around call... | [
1,
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074520666_for_loop_python.txt |
Q:
How do I create a column using strings retrieved from another column on python?
I am trying to read information from a column in my csv file and use it to create a new column. Please help
I imported the csv file and printed the first 10 rows (+ header) but now I would like to create a column for the years in the ... | How do I create a column using strings retrieved from another column on python? | I am trying to read information from a column in my csv file and use it to create a new column. Please help
I imported the csv file and printed the first 10 rows (+ header) but now I would like to create a column for the years in the title column.
```
import csv
from itertools import islice
from operator import itemge... | [
"You can use re to extract the year from the title:\nrows = [\n [\"movieId\", \"title\", \"genres\"],\n [\"1\", \"Toy Story (1995)\", \"Adventure|Animation|Children|Comedy|Fantasy\"],\n [\"2\", \"Jumanji (1995)\", \"Adventure|Children|Fantasy\"],\n [\"3\", \"Grumpier Old Men (1995)\", \"Comedy|Romance\"... | [
1,
0
] | [] | [] | [
"arrays",
"csv",
"python"
] | stackoverflow_0074520586_arrays_csv_python.txt |
Q:
Importing file in pandas with read_table() cuts decimal places
I have a txt file like this (separated by tab):
Variance
Mean
0.001435955236
-0.001117
0.002473570225
0.003123
0.002334629124
-0.003471
...and so on.
I load it using pandas.read_table() and the result is a dataframe like this:
Variance
Mean
0
0.... | Importing file in pandas with read_table() cuts decimal places | I have a txt file like this (separated by tab):
Variance
Mean
0.001435955236
-0.001117
0.002473570225
0.003123
0.002334629124
-0.003471
...and so on.
I load it using pandas.read_table() and the result is a dataframe like this:
Variance
Mean
0
0.001436
-0.001117
1
0.002474
0.003123
2
0.00233... | [
"Pandas does not actually \"cut\" the decimal place, it just rounds when printing. To print with display precision, use\nwith pd.option_context('display.precision', 10):\n print(df_assets)\n\n"
] | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074520784_pandas_python.txt |
Q:
Convert CSV to JSON using python pandas
I have an CSV file of having data I want to convert into JSON format but I get issue about the formation.
Data input in csv file:
Full CSV: rarities.csv
I have tried this code but it doesn't get the desired result.
Here is the code :
import pandas as pd
df = pd.read_csv(r'... | Convert CSV to JSON using python pandas | I have an CSV file of having data I want to convert into JSON format but I get issue about the formation.
Data input in csv file:
Full CSV: rarities.csv
I have tried this code but it doesn't get the desired result.
Here is the code :
import pandas as pd
df = pd.read_csv(r'rarities.csv')
df.to_json(r'rarities.json', ... | [
"you can use:\ndf = df.drop(0) #delete first row. We will not use.\ndf['Name'] = df['Name'].ffill() #fillna in name column with first values until change\ndfv = df.pivot_table(index='Name',aggfunc=list) #pivot table by name and put items to list\ndfv = dfv.applymap(lambda x: [i for i in x if str(i) != 'nan']) #remo... | [
1
] | [] | [] | [
"converters",
"csv",
"json",
"pandas",
"python"
] | stackoverflow_0074519829_converters_csv_json_pandas_python.txt |
Q:
How to get list of all variables in jinja 2 templates
I am trying to get list of all variables and blocks in a template. I don't want to create my own parser to find variables. I tried using following snippet.
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('gummi', 'templates'... | How to get list of all variables in jinja 2 templates | I am trying to get list of all variables and blocks in a template. I don't want to create my own parser to find variables. I tried using following snippet.
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('gummi', 'templates'))
template = env.get_template('chat.html')
template.block... | [
"Since no one has answered the question and I found the answer\nfrom jinja2 import Environment, PackageLoader, meta\nenv = Environment(loader=PackageLoader('gummi', 'templates'))\ntemplate_source = env.loader.get_source(env, 'page_content.html')\nparsed_content = env.parse(template_source)\nmeta.find_undeclared_var... | [
76,
14,
7,
2,
1,
0
] | [] | [] | [
"jinja2",
"python",
"template_variables"
] | stackoverflow_0008260490_jinja2_python_template_variables.txt |
Q:
how to add matrix reading from .txt to the travelling salesmen problem code?
I'm freshman to python . Need your help
I'm trynna read matrix from .txt and add it to the traveling salesmen problem code . Can you explain what do I do wrong?
Input.txt looks:
Place; date1;date2;date3
#1;65;27;16
#2;46;56;11
#3;36;14;28... | how to add matrix reading from .txt to the travelling salesmen problem code? | I'm freshman to python . Need your help
I'm trynna read matrix from .txt and add it to the traveling salesmen problem code . Can you explain what do I do wrong?
Input.txt looks:
Place; date1;date2;date3
#1;65;27;16
#2;46;56;11
#3;36;14;28
script
import csv
f= open("input1.txt","r")
sum=(1 for line in open("input1.tx... | [
"I recommend use pandas to read csv files (dont forget set non-standard separator).\ndf = pd.read_csv(file_name, sep=\";\")\nhere's answer for your question:\nhttps://realpython.com/introduction-to-python-generators/\nYou need to create generator before u will use it.\n# def of generator\ndef my_gen():\n i = 0\n... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074520743_python_python_3.x.txt |
Q:
Pandas check if two columns can be considered the composite key of the dataframe
A sample dataframe:
data = {
"col_A": ["a","a","b","c"],
"col_B": [1, 2, 2, 3],
"col_C": ["demo", "demo", "demo", "demo"]
}
df = pd.DataFrame(data)
Dataframe
col_A col_B col_C
a 1 demo
a 2 dem... | Pandas check if two columns can be considered the composite key of the dataframe | A sample dataframe:
data = {
"col_A": ["a","a","b","c"],
"col_B": [1, 2, 2, 3],
"col_C": ["demo", "demo", "demo", "demo"]
}
df = pd.DataFrame(data)
Dataframe
col_A col_B col_C
a 1 demo
a 2 demo
b 2 demo
c 3 demo
I can easily check if all values in col_A... | [
"You can set all columns that should be included in the composite key as index and then check for is_unique on the index.\ndf.set_index(['col_A', 'col_B']).index.is_unique\n\n#True\n\n",
"Use DataFrame.duplicated with Series.any()\nnot df[['col_A', 'col_B']].duplicated().any()\n\n"
] | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074520885_dataframe_pandas_python.txt |
Q:
Save console output in txt file as it happens
I want to save my console output in a text file, but I want it to be as it happens so that if the programm crashes, logs will be saved.
Do you have some ideas ?
I can't just specify file in logger because I have a lot of different loggers that are printing into the con... | Save console output in txt file as it happens | I want to save my console output in a text file, but I want it to be as it happens so that if the programm crashes, logs will be saved.
Do you have some ideas ?
I can't just specify file in logger because I have a lot of different loggers that are printing into the console.
| [
"I think that you indeed can use a logger, just adding a file handler, from the logging module you can read this\nAs an example you can use something like this, which logs both to the terminal and to a file:\nimport logging\nfrom pathlib import Path\n\nroot_path = <YOUR PATH>\n\nlog_level = logging.DEBUG\n\n# Print... | [
4,
3
] | [] | [] | [
"python"
] | stackoverflow_0074474093_python.txt |
Q:
Create a new column A, where the value will be taken from a specific column based on the value in column C
I want to create a new column A (verbatim), where the value will be taken from a specific column based on the value in column C (category)
The data I have:
ID pos neg better_than_comp less_well_th... | Create a new column A, where the value will be taken from a specific column based on the value in column C | I want to create a new column A (verbatim), where the value will be taken from a specific column based on the value in column C (category)
The data I have:
ID pos neg better_than_comp less_well_than_comp Category code
1 good service quick response price and range POSITIVE ... | [
"you should use it like this.\ndf['verbatim']=df.apply(lambda x: x['better_than_comp'] if \n x['Category'] == 'BETTER THAN COMP'\n else x['less_well_than_comp']\n if x['Category']=='LESS WEL... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074520950_pandas_python.txt |
Q:
Plotly Express Overlay Two Line Graphs
I know that it is easy to overlay plots using Plotly Go.
import plotly.graph_objects as go
fig = go.Figure()
fig.add_traces([go.Scatter(x=[1,2,3], y=[2,1,2]),
go.Scatter(x=[1,2,3], y=[2,1,2]),
go.Scatter(x=[1,2,3], y=[1,1,2])])
fig.show()
... | Plotly Express Overlay Two Line Graphs | I know that it is easy to overlay plots using Plotly Go.
import plotly.graph_objects as go
fig = go.Figure()
fig.add_traces([go.Scatter(x=[1,2,3], y=[2,1,2]),
go.Scatter(x=[1,2,3], y=[2,1,2]),
go.Scatter(x=[1,2,3], y=[1,1,2])])
fig.show()
However, I would like to accomplish same tas... | [
"You can do it with add_traces\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\n\ndata = {'x':[1,2,3], 'y':range(3)}\ndf1 = pd.DataFrame(data)\n\ndata = {'x':[4,5,6], 'y':range(4,7)}\ndf2 = pd.DataFrame(data)\n\nfig1 = px.line(df1, x='x', y='y', color_discrete_sequence=['red'])\n\nfig2 = px.li... | [
1
] | [] | [] | [
"plotly",
"plotly_dash",
"python"
] | stackoverflow_0074520782_plotly_plotly_dash_python.txt |
Q:
Creating a Utility Matrix from CSV File for Collaborative Filtering
I have a CSV File Output Like this,
I need to create a Utility Matrix like this,
r=df.User.unique()
df2 = pd.DataFrame(data=r)
With the above code I created the User part but I'm Stuck at creating the Rating corresponding to each item for the U... | Creating a Utility Matrix from CSV File for Collaborative Filtering | I have a CSV File Output Like this,
I need to create a Utility Matrix like this,
r=df.User.unique()
df2 = pd.DataFrame(data=r)
With the above code I created the User part but I'm Stuck at creating the Rating corresponding to each item for the Users.
Is there any method in Python to do this?
| [
"You can use Pandas pivot_table to create a utility matrix (see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html)\nIn your case, it'll be utilityMatrix = ratingTable.pivot_table(values='rating', index='userId', columns='itemID')\n"
] | [
0
] | [] | [] | [
"collaborative_filtering",
"csv",
"matrix",
"pandas",
"python"
] | stackoverflow_0066454310_collaborative_filtering_csv_matrix_pandas_python.txt |
Q:
Get subclass name?
Is it possible to get the name of a subclass? For example:
class Foo:
def bar(self):
print type(self)
class SubFoo(Foo):
pass
SubFoo().bar()
will print: < type 'instance' >
I'm looking for a way to get "SubFoo".
I know you can do isinstance, but I don't know the name of the c... | Get subclass name? | Is it possible to get the name of a subclass? For example:
class Foo:
def bar(self):
print type(self)
class SubFoo(Foo):
pass
SubFoo().bar()
will print: < type 'instance' >
I'm looking for a way to get "SubFoo".
I know you can do isinstance, but I don't know the name of the class a priori, so that d... | [
"you can use\nSubFoo().__class__.__name__\n\nwhich might be off-topic, since it gives you a class name :)\n",
"#!/usr/bin/python\nclass Foo(object):\n def bar(self):\n print type(self)\n\nclass SubFoo(Foo):\n pass\n\nSubFoo().bar()\n\nSubclassing from object gives you new-style classes (which are not so new ... | [
16,
12,
3,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0003314627_python.txt |
Q:
JWT encrypting payload in python? (JWE)
According to RFC 7516 it should be possible to encrypt the payload/claim, called JWE.
Are there any python libraries out there that support that?
I've checked PyJWT, python-jose and jwcrypto but they all just have examples for signing with HS256 (JWS).
Sorry if this is total... | JWT encrypting payload in python? (JWE) | According to RFC 7516 it should be possible to encrypt the payload/claim, called JWE.
Are there any python libraries out there that support that?
I've checked PyJWT, python-jose and jwcrypto but they all just have examples for signing with HS256 (JWS).
Sorry if this is totally obvious, but when it comes to things invol... | [
"Both Jose and jwcrypto libraries can do JWE.\nFor jose:\nclaims = {\n'iss': 'http://www.example.com',\n'sub': 42,\n}\npubKey = {'k':\\\n '-----BEGIN PUBLIC KEY-----\\n\\\n-----END PUBLIC KEY-----'\n }\n# decrypt on the other end using the private key\nprivKey = {'k': \n '-----BEGIN RSA PRIVATE KEY-... | [
13,
0
] | [
"https://jwcrypto.readthedocs.io/en/latest/jwk.html#examples\nfrom jwcrypto import jwk\n_k = jwk.JWK.generate(kty='RSA', size=2048)\n_text = _k.export()\n\nimport json\n# loading the key back\n_import_key_dict = json.loads(_text)\nkey = jwk.JWK(**json.loads(_import_key_dict))\n\n\n"
] | [
-1
] | [
"jwe",
"jwt",
"pyjwt",
"python",
"python_jose"
] | stackoverflow_0039163000_jwe_jwt_pyjwt_python_python_jose.txt |
Q:
Selenium, Python, Chrome Driver -Send_Keys
could someone kindly point out to me where I'm going wrong please?
I've looked up the documentation and I thought I set it up correctly but keep getting the error:
line 29, in <module>
username.send_keys(cred_username)
^^^^^^^^^^^^^^^^^^
AttributeError: 'list' obj... | Selenium, Python, Chrome Driver -Send_Keys | could someone kindly point out to me where I'm going wrong please?
I've looked up the documentation and I thought I set it up correctly but keep getting the error:
line 29, in <module>
username.send_keys(cred_username)
^^^^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'send_keys'
Currently I ca... | [
"Your mistake is here: username = driver.find_elements(By.ID, \"idUsername\")\nYou need to use find_element method, not find_elements since find_element returns a web element object so you can apply send_keys method on it, while find_elements returns a list of web element and you can not apply send_keys method on a... | [
2
] | [] | [] | [
"authentication",
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0074520997_authentication_python_selenium_selenium_chromedriver_selenium_webdriver.txt |
Q:
Check if a pdf is signed or not
I would like to write a python script to check if a pdf is signed or not. After quite a bit of looking around, I saw that pyPDF2 helps extract text from pdf files, but I am not sure if it can be used to extract the signature details such as Public Key etc.
I did go through some of ... | Check if a pdf is signed or not | I would like to write a python script to check if a pdf is signed or not. After quite a bit of looking around, I saw that pyPDF2 helps extract text from pdf files, but I am not sure if it can be used to extract the signature details such as Public Key etc.
I did go through some of the open source packages like pyhanko... | [
"disclaimer: I am the author of borb the library used in this answer\nSimply load the PDF using borb, get the DocumentInfo object, and call its has_signatures function.\nfrom borb.pdf import PDF\nfrom borb.pdf import Document\n\nimport typing\n\n# read the PDF\ndoc: typing.Optional[Document] = None\nwith open(\"inp... | [
0
] | [] | [] | [
"encryption",
"pdf",
"python",
"python_3.x",
"signature"
] | stackoverflow_0074513853_encryption_pdf_python_python_3.x_signature.txt |
Q:
Powershell command to Python
Trying to get the below code to run but am struggling to find a solution for the below highlight portion it doesn't like the 'File' portion of the code. Any help appreciated.
import subprocess
def getaclsec():
pscommand = '$file1 = Import-Csv -Path "C:\\Source\\testpath.csv" Fo... | Powershell command to Python | Trying to get the below code to run but am struggling to find a solution for the below highlight portion it doesn't like the 'File' portion of the code. Any help appreciated.
import subprocess
def getaclsec():
pscommand = '$file1 = Import-Csv -Path "C:\\Source\\testpath.csv" ForEach ($file in $file1) {$infoSec ... | [
"Answer:\nimport subprocess \ndef getaclsec():\n pscommand = '$file1 = Import-Csv -Path \"C:\\\\Source\\\\testpath.csv\"; ForEach ($file in $file1) {$infoSec = Get-Acl -Path $file.FullPAth; $infoSec.Access | Select @{l=\"File\";e={$file.FullPath}},* | Export-Csv -Path \"C:\\\\Source\\\\newTestPathSect.csv\" -... | [
0
] | [] | [] | [
"powershell",
"python"
] | stackoverflow_0074494430_powershell_python.txt |
Q:
How to make onchange field editable only for draft state?
I have onchange field, and i need to make it readonly for all state except the draft state.
My .py file:
class SaleOrderInherited(models.Model):
_inherit = 'sale.order'
custom_field = fields.Char(string='Test', store=True, default=randint(1, 1000)
)
@api... | How to make onchange field editable only for draft state? | I have onchange field, and i need to make it readonly for all state except the draft state.
My .py file:
class SaleOrderInherited(models.Model):
_inherit = 'sale.order'
custom_field = fields.Char(string='Test', store=True, default=randint(1, 1000)
)
@api.onchange('tax_totals_json', 'date_order')
def _onchage_test(se... | [
"Set the readonly attribute to True then use states to make the field editable in draft state. You can find an example in sale_management module:\nsale_order_template_id = fields.Many2one(\n readonly=True, check_company=True,\n states={'draft': [('readonly', False)], 'sent': [('readonly', False)]})\n\nUsing o... | [
0
] | [] | [] | [
"odoo",
"odoo_15",
"python",
"python_3.x"
] | stackoverflow_0074520308_odoo_odoo_15_python_python_3.x.txt |
Q:
Either no errors, yet no output or math domain error
I'm currently majoring in maths and minoring in physics and hence need to do some homework assignments in Python.
I never coded in Python(miniscule experience in java) and never attended the Python classes assigned by uni(ik) and currently I try to approximate p... | Either no errors, yet no output or math domain error | I'm currently majoring in maths and minoring in physics and hence need to do some homework assignments in Python.
I never coded in Python(miniscule experience in java) and never attended the Python classes assigned by uni(ik) and currently I try to approximate pi by measuring the area under the graph of a circle in Pyt... | [
"math.sqrt() does not take a negative number. When I was trying to use a negative value as a parameter, it is showing the math domain error.\nSee this example:\nimport math\nmath.sqrt(-4)\nTraceback (most recent call last):\n File \"/usr/lib/python3.10/code.py\", line 90, in runcode\n exec(code, self.locals)\n ... | [
0
] | [] | [] | [
"math",
"output",
"python"
] | stackoverflow_0074520954_math_output_python.txt |
Q:
Getting error ImportError: No module named slack_sdk.webhook
I'm very new to Python. I'm using PyCharm and Python Virtual Environment and following is a piece of import code which is throwing error. I checked my requirements.txt file and it has got slack library configured and then I ran pip3 install -r requiremen... | Getting error ImportError: No module named slack_sdk.webhook | I'm very new to Python. I'm using PyCharm and Python Virtual Environment and following is a piece of import code which is throwing error. I checked my requirements.txt file and it has got slack library configured and then I ran pip3 install -r requirements.txt and executed my file python .py but getting below error:-
T... | [
"Interpreter\nlike you can see in this picture... maybe is here the problem. When you create a new environment you need to choose the new python.exe inside of PYCHARM where you installed you library's. So...\nMaybe you activate the Script on console, you are isntalling correct lib's in your env but you are opening ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074521006_python.txt |
Q:
Trying to get a basic highcharts cylinder chart working on streamlit
I've been able to get a highcharts waterfallchart and an area chart working on streamlit, but the cylinder chart is not displaying anything. Would love it if someone could take a look at my code....
import streamlit as st
import streamlit_highch... | Trying to get a basic highcharts cylinder chart working on streamlit | I've been able to get a highcharts waterfallchart and an area chart working on streamlit, but the cylinder chart is not displaying anything. Would love it if someone could take a look at my code....
import streamlit as st
import streamlit_highcharts as hct
chart_week_day={
"chart": {
"type": "cylinder",
... | [
"Series.data expects numbers, whereasxAxis.categories should be strings. Therefore, you need to only swap categories and data values.\nJS Demo:\nhttps://jsfiddle.net/BlackLabel/qx3pzn1f/\nAPI Reference:\nhttps://api.highcharts.com/highcharts/series.cylinder.data\nhttps://api.highcharts.com/highcharts/xAxis.categori... | [
0
] | [] | [] | [
"highcharts",
"python",
"streamlit"
] | stackoverflow_0074499649_highcharts_python_streamlit.txt |
Q:
Listing Kafka clusters and brokers
I try to develop a Kafka GUI on Django. I can list topics of brokers, partitions and clients using kafka-python.
Is a programmatic way to retrieve list of clusters and brokers?
I can save clusters and related brokers as database tables as an alternative.
A:
Use ClusterMetata.br... | Listing Kafka clusters and brokers | I try to develop a Kafka GUI on Django. I can list topics of brokers, partitions and clients using kafka-python.
Is a programmatic way to retrieve list of clusters and brokers?
I can save clusters and related brokers as database tables as an alternative.
| [
"Use ClusterMetata.brokers()\nYou can only connect to one cluster at a time, so you need some other solution to find all Kafka clusters.\nAlternatively, there's plenty of existing Kafka GUIs, most of which are built on JVM languages, however.\n"
] | [
1
] | [] | [] | [
"apache_kafka",
"python"
] | stackoverflow_0074519840_apache_kafka_python.txt |
Q:
Saving Login with Playwright
I'm trying to save my login with playwright, I've read the documentation and tried to implement it into my code but I am still getting errors
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=False, slow_mo=50)
pa... | Saving Login with Playwright | I'm trying to save my login with playwright, I've read the documentation and tried to implement it into my code but I am still getting errors
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=False, slow_mo=50)
page = context.new_page()
page.f... | [
"The main problem:\n\ncontext.new_page() calls before variable declaration(context = ...)\n\nShould works fine:\nfrom playwright.sync_api import sync_playwright\n\nwith sync_playwright() as p:\n browser = p.chromium.launch(headless=False, slow_mo=50)\n context = browser.new_context(storage_state=\"website1.js... | [
1
] | [] | [] | [
"playwright",
"python"
] | stackoverflow_0074520727_playwright_python.txt |
Q:
Dash Radial Plot for Hours of a Day
I am looking for a plot in Ploty/Dash which is similar to radial chart below. The closest one I found in Ploty is polar charts, and line charts.
Here is my implementation:
import random
import pandas as pd
import numpy as np
import plotly.express as px
df = pd.DataFrame({'DATE... | Dash Radial Plot for Hours of a Day | I am looking for a plot in Ploty/Dash which is similar to radial chart below. The closest one I found in Ploty is polar charts, and line charts.
Here is my implementation:
import random
import pandas as pd
import numpy as np
import plotly.express as px
df = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-... | [
"You should convert your hourly data to string series as follows:\nimport random\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\n\ndf = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-05 23:00:00',freq=\"30min\"),\n 'value':[random.uniform(110, 160) for n in r... | [
1
] | [] | [] | [
"plotly",
"plotly_dash",
"python"
] | stackoverflow_0074518210_plotly_plotly_dash_python.txt |
Q:
Django Forms does not submit radiobutton value and does not showing any output in terminal as well
This is HTML Code.
<form action = "." method = "post">
<div class="form_data">
{% csrf_token %}
<br><br>
{{form.myfield}}
<br><br>
<input type="submit" value="Submit" class="btn bt... | Django Forms does not submit radiobutton value and does not showing any output in terminal as well | This is HTML Code.
<form action = "." method = "post">
<div class="form_data">
{% csrf_token %}
<br><br>
{{form.myfield}}
<br><br>
<input type="submit" value="Submit" class="btn btn-success" />
</div>
</form>
This is forms.py code
class TestForm(forms.ModelForm):
class M... | [
"The form is not going to the test view as you specified . in action attribute, kindly remove action attribute, since Django always takes current page route, so it will automatically go to test view so:\n<form method=\"POST\">\n <div class=\"form_data\">\n\n {% csrf_token %}\n <br><br>\n\n ... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"django_views",
"python"
] | stackoverflow_0074521103_django_django_forms_django_templates_django_views_python.txt |
Q:
How to use a Pydantic model with Form data in FastAPI?
I am trying to submit data from HTML forms and validate it with a Pydantic model.
Using this code
from fastapi import FastAPI, Form
from pydantic import BaseModel
from starlette.responses import HTMLResponse
app = FastAPI()
@app.get("/form", response_class=H... | How to use a Pydantic model with Form data in FastAPI? | I am trying to submit data from HTML forms and validate it with a Pydantic model.
Using this code
from fastapi import FastAPI, Form
from pydantic import BaseModel
from starlette.responses import HTMLResponse
app = FastAPI()
@app.get("/form", response_class=HTMLResponse)
def form_get():
return '''<form method="po... | [
"I found a solution that can help us to use Pydantic with FastAPI forms :)\nMy code:\nclass AnyForm(BaseModel):\n any_param: str\n any_other_param: int = 1\n\n @classmethod\n def as_form(\n cls,\n any_param: str = Form(...),\n any_other_param: int = Form(1)\n ) -> AnyForm:\n ... | [
52,
6,
5,
3,
3,
2,
0,
0
] | [] | [] | [
"fastapi",
"pydantic",
"python"
] | stackoverflow_0060127234_fastapi_pydantic_python.txt |
Q:
find all elements > 0 in a np.array with np.where
I have a Array with Numbers ranging from (-infinite to +infinite)
Code looks like that:
delta_up = np.where(delta > 0, delta, 0)
delta_down = np.where(delta < 0, delta, 0)
Problem: I also have nan's in the array and they need to stay as nan's. But they are beeing ... | find all elements > 0 in a np.array with np.where | I have a Array with Numbers ranging from (-infinite to +infinite)
Code looks like that:
delta_up = np.where(delta > 0, delta, 0)
delta_down = np.where(delta < 0, delta, 0)
Problem: I also have nan's in the array and they need to stay as nan's. But they are beeing converted to 0
How to solve it?
| [
"my_array = np.array([1, 2, 3, 5, -1, -2, -3, None], dtype=\"float\")\n\n\nnegative_idx = np.where(my_array<0) # np.nan values will be ignore\npositive_idx = np.where(my_array>0) # np.nan values will be ignore\n\n# getting subarray with values `array[indexes]`\nnegative_values = my_array[negative_idx]\npositive_val... | [
1
] | [] | [] | [
"arrays",
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0074521115_arrays_numpy_numpy_ndarray_python.txt |
Q:
How to apply custom calculation between two IRIS cubes (GRIB files)? Considering also using xarray
I am trying to do some calculation between two iris cubes (GRIB files), here it is what I'm trying to achieve:
First cube:
ERA5-Land dataset, downloaded from official site via cdsapi API routine, cropped to custom La... | How to apply custom calculation between two IRIS cubes (GRIB files)? Considering also using xarray | I am trying to do some calculation between two iris cubes (GRIB files), here it is what I'm trying to achieve:
First cube:
ERA5-Land dataset, downloaded from official site via cdsapi API routine, cropped to custom Lat and Lon, in this example, I have only 2m air temperature, in celsius, hourly, for 3 days:
print(air_te... | [
"Iris is strict about metadata and will fail loudly when they don't match in operations you try to do.\nThe error you get tells you what's going on: ValueError: Coordinate 'latitude' has different points for the LHS cube 'air_temperature' and RHS cube 'Elevation'.\nSo you can investigate and compare your left and r... | [
1
] | [] | [] | [
"python",
"python_iris",
"python_xarray"
] | stackoverflow_0074287675_python_python_iris_python_xarray.txt |
Q:
How to install yaml to site-packages
I want to know how to install YAML packages to site-packages because I need it for Blender. I already tried "C:\Program Files\Blender Foundation\Blender 3.0\3.0\python\bin\python.exe" -m pip install yaml -t"C:\Program Files\Blender Foundation\Blender 3.0\3.0\python\lib\site-pac... | How to install yaml to site-packages | I want to know how to install YAML packages to site-packages because I need it for Blender. I already tried "C:\Program Files\Blender Foundation\Blender 3.0\3.0\python\bin\python.exe" -m pip install yaml -t"C:\Program Files\Blender Foundation\Blender 3.0\3.0\python\lib\site-packages" as administrator, but this appeared... | [
"The name of the package is PyYAML so you need to install it via\npip install PyYAML\n\nNOTE: Be aware that while the name of the package on pypi and the name of the python module are almost always the same, they do not have to be. In this case, the package is called PyYAML, however once you've installed it, it's i... | [
1
] | [] | [] | [
"cmd",
"pip",
"python",
"site_packages"
] | stackoverflow_0074521251_cmd_pip_python_site_packages.txt |
Q:
problem running pynput module in google colab
I am trying to install and import the pynput module using google colab. However, although I managed to install using "!pip install pynput", when I import the module such as:
from pynput.keyboard import Key, Listener
I get the below error:
-----------------------------... | problem running pynput module in google colab | I am trying to install and import the pynput module using google colab. However, although I managed to install using "!pip install pynput", when I import the module such as:
from pynput.keyboard import Key, Listener
I get the below error:
---------------------------------------------------------------------------
Impo... | [
"Google colab runs on a machine instance in Google Cloud so that python can't able to gain control to the keyboard/monitor/mouse. In a nutshell developers interact with google colab through web browsers (google chrome, mozilla etc).\nLong story short you are trying to control local hardware by runing code on cloud,... | [
1
] | [] | [] | [
"installation",
"pynput",
"python"
] | stackoverflow_0074517767_installation_pynput_python.txt |
Q:
How to search for a value in line and check if it matches given condition
I have a file in.txt.
name="XYZ_PP_0" number="0x12" bytesize="4" info="0x0000001A"
name="GK_LMP_2_0" number="0xA5" bytesize="8" info="0x00000000bbae321f"
name="MP_LKO_1_0" number="0x356" bytesize="4" info="0x00000234"
name="PNP_VXU_1_2_0" n... | How to search for a value in line and check if it matches given condition | I have a file in.txt.
name="XYZ_PP_0" number="0x12" bytesize="4" info="0x0000001A"
name="GK_LMP_2_0" number="0xA5" bytesize="8" info="0x00000000bbae321f"
name="MP_LKO_1_0" number="0x356" bytesize="4" info="0x00000234"
name="PNP_VXU_1_2_0" number="0x48A" bytesize="8" info="0x00000000a18c3ba3"
name="AVU_W_2_3_1" number=... | [
"You have to escape the double quotes, or you can use single quotes so that you string can have double quotes in it like this:\n'number=\"0x12\"'\n\nAlso, in your if condition the first part is wrong. Here is the loop:\nxyz_list = ['number=\"0x12\"', 'info=\"0x0000001A\"']\nmp_list = ['number=\"0x356\"', 'info=\"0... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074520971_python_python_3.x.txt |
Q:
Pygame collision with rectangles in list not working right
I'm making python pygame labyrinth game.
Moving works with moving walls, but not player because player never escapes the screen. Currently I'm working on moving on X axis, but something goes wrong. When player collides with left wall, it normally doesn't l... | Pygame collision with rectangles in list not working right | I'm making python pygame labyrinth game.
Moving works with moving walls, but not player because player never escapes the screen. Currently I'm working on moving on X axis, but something goes wrong. When player collides with left wall, it normally doesn't let it go more to the left. But when going to the right it slight... | [
"Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data.\n\nThe coordinates for Rect objects are all integers. [...]\n\nThe fractional part of the coordinates is lost when the position of the Rect object is changed. In your case this means that the moveme... | [
0
] | [] | [] | [
"pygame",
"python",
"python_3.x"
] | stackoverflow_0074520434_pygame_python_python_3.x.txt |
Q:
Find out the percentage of missing values in each column in the given dataset
import pandas as pd
df = pd.read_csv('https://query.data.world/s/Hfu_PsEuD1Z_yJHmGaxWTxvkz7W_b0')
percent= 100*(len(df.loc[:,df.isnull().sum(axis=0)>=1 ].index) / len(df.index))
print(round(percent,2))
input is https://query.data.world/... | Find out the percentage of missing values in each column in the given dataset | import pandas as pd
df = pd.read_csv('https://query.data.world/s/Hfu_PsEuD1Z_yJHmGaxWTxvkz7W_b0')
percent= 100*(len(df.loc[:,df.isnull().sum(axis=0)>=1 ].index) / len(df.index))
print(round(percent,2))
input is https://query.data.world/s/Hfu_PsEuD1Z_yJHmGaxWTxvkz7W_b0
and the output should be
Ord_id 0.... | [
"How about this? I think I actually found something similar on here once before, but I'm not seeing it now...\npercent_missing = df.isnull().sum() * 100 / len(df)\nmissing_value_df = pd.DataFrame({'column_name': df.columns,\n 'percent_missing': percent_missing})\n\nAnd if you want th... | [
111,
53,
13,
7,
3,
2,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"numpy",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0051070985_numpy_pandas_python_python_3.x.txt |
Q:
How can I overwrite a mapping of a column based on its current value and value of two other columns?
I have the following pandas dataframe
is_and_mp market_state reason
'100' None NaN
'400' None NaN
'100' ALGO NaN
'400' ... | How can I overwrite a mapping of a column based on its current value and value of two other columns? | I have the following pandas dataframe
is_and_mp market_state reason
'100' None NaN
'400' None NaN
'100' ALGO NaN
'400' OPENING NaN
I want to write two mappings where if is_and_mp is either '100' or '400', and mark... | [
"Use DataFrame.loc with chained mask by & for bitwise AND:\ndf.loc[df.is_and_mp.isin([ '100', '400']) & df.market_state.isna() & df. reason.isna(), 'market_stat'] = 'CONTINUOUS_TRADING'\n\nor if values are numeric:\ndf.loc[df.is_and_mp.isin([ 100, 400]) & df.market_state.isna() & df. reason.isna(), 'market_stat']... | [
4,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074521148_dataframe_pandas_python.txt |
Q:
Have a global df in tkinter
Hello I am on a project for my school and I have to code a stock manager.
import tkinter as tk
from tkinter import filedialog, messagebox, ttk, simpledialog
from PIL import Image,ImageTk
import pandas as pd
# initalise the tkinter GUI
window = tk.Tk()
window.geometry("1280x720") # set... | Have a global df in tkinter | Hello I am on a project for my school and I have to code a stock manager.
import tkinter as tk
from tkinter import filedialog, messagebox, ttk, simpledialog
from PIL import Image,ImageTk
import pandas as pd
# initalise the tkinter GUI
window = tk.Tk()
window.geometry("1280x720") # set the root dimensions
window.pack_... | [
"Global objects (not recommended)\nYou need to create global object\nglobal variable_name\nAnd in every function or method u need to mark that u want to use this object by at the beginning of the function/method\nglobal variable_name\nrecommended\nPass df as function argument or create class and create internal att... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"tkinter"
] | stackoverflow_0074521278_dataframe_pandas_python_tkinter.txt |
Q:
Python 3 - How to terminate a thread instantly?
In my code (a complex GUI application with Tkinter) I have a thread defined in a custom object (a progress bar). It runs a function with a while cicle like this:
def Start(self):
while self.is_active==True:
do it..
time.sleep(1)
do it..
... | Python 3 - How to terminate a thread instantly? | In my code (a complex GUI application with Tkinter) I have a thread defined in a custom object (a progress bar). It runs a function with a while cicle like this:
def Start(self):
while self.is_active==True:
do it..
time.sleep(1)
do it..
time.sleep(1)
def Stop(self):
self.is_... | [
"First off, to be clear, hard-killing a thread is a terrible idea in any language, and Python doesn't support it; if nothing else, the risk of that thread holding a lock which is never unlocked, causing any thread that tries to acquire it to deadlock, is a fatal flaw.\nIf you don't care about the thread at all, you... | [
3,
0
] | [] | [] | [
"multithreading",
"python",
"python_3.x",
"python_multithreading"
] | stackoverflow_0074521233_multithreading_python_python_3.x_python_multithreading.txt |
Q:
How hide image path in django?
Is it possible to hide the path to the image so that it is not visible in the element expect? I dont want to allow user know where is my images are a storing. How i can hide this in django?
<div class="avatar avatar--large active">
<img src="{{user.avatar.url}}"/>
</div>
Can you ... | How hide image path in django? | Is it possible to hide the path to the image so that it is not visible in the element expect? I dont want to allow user know where is my images are a storing. How i can hide this in django?
<div class="avatar avatar--large active">
<img src="{{user.avatar.url}}"/>
</div>
Can you give an example with my code?
| [
"To remove html from your DOM\n $(\"#a\").remove();\n\nif you want to hide only then use\n$(\"#a\").hide();\n\n"
] | [
0
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0074521340_django_html_python.txt |
Q:
creating a list of all possible combination from a given list of words in python
i have a problem to create a list of all possible combinations of a given list of words.
the result should be a combination per line for all possible words. the max lengh of combination is based on the amount of words given in the inp... | creating a list of all possible combination from a given list of words in python | i have a problem to create a list of all possible combinations of a given list of words.
the result should be a combination per line for all possible words. the max lengh of combination is based on the amount of words given in the input file. this means, if the file contains 7 words, the combination is max 7 words long... | [
"I believe you want to use the function combinations_with_replacement:\nfrom itertools import combinations_with_replacement\n\n\nfeatures = ['germany', 'spain', 'albania']\ntmp = []\nfor i in range(len(features)):\n oc = combinations_with_replacement(features, i + 1)\n for c in oc:\n tmp.append(list(c)... | [
2
] | [] | [] | [
"combinations",
"python",
"string"
] | stackoverflow_0074521479_combinations_python_string.txt |
Q:
Bokeh for presenting data on Italy map
I need to use Bokeh to plot datas on Italian map.
To explain, something similar with:
http://docs.bokeh.org/en/latest/docs/gallery/texas.html
... but using italian provinces instead of Texas counties.
Can you help me pointing in the right direction?
Other tools suggested?
Tha... | Bokeh for presenting data on Italy map | I need to use Bokeh to plot datas on Italian map.
To explain, something similar with:
http://docs.bokeh.org/en/latest/docs/gallery/texas.html
... but using italian provinces instead of Texas counties.
Can you help me pointing in the right direction?
Other tools suggested?
Thanks in advance, Gianluca
| [
"I don't know if it can still help, but at http://www.istat.it/it/archivio/209722 (istat italian website)\nyou can find numerous free detailed and updated borders of Italian provinces and regions in .shp format.\nLet me know if you manage to obtain your map and if yes, how, ty.\n",
"I managed to create a plot wit... | [
1,
0,
0
] | [] | [] | [
"bokeh",
"geolocation",
"geospatial",
"python"
] | stackoverflow_0041932493_bokeh_geolocation_geospatial_python.txt |
Q:
Saving Excel file with Python (Openpyxl)
I have a problem, I have an Excel file (.xlsx) and this file have some buttons in it to help to change the language and a button that make a raport based of the data.
The problem is...If I write something in the file and then I save it with openpyxl the file will lose those... | Saving Excel file with Python (Openpyxl) | I have a problem, I have an Excel file (.xlsx) and this file have some buttons in it to help to change the language and a button that make a raport based of the data.
The problem is...If I write something in the file and then I save it with openpyxl the file will lose those buttons and looks like a normal excel.
What c... | [
".xlsx dose not have macros. Save it as .xlsm instead.\n",
"Try this: \nwb.save('testsave.xlsm');\n\n",
"I had a similar problem and I have found a workaround for it:\nProblem\nI have an .xlsm file that contain few sheets, one of them has some macros and buttons, I read it on python using openpyxl function lo... | [
0,
0,
0
] | [] | [] | [
"excel",
"python"
] | stackoverflow_0060390029_excel_python.txt |
Q:
Web Scraping when Table is one click away
I am trying to extract table data from this website https://www.svk.se/om-kraftsystemet/kontrollrummet/ where I want the last segment called "Förbrukning I Sverige". I am trying to extract with this code:
from selenium import webdriver
from selenium.webdriver.chrome.servic... | Web Scraping when Table is one click away | I am trying to extract table data from this website https://www.svk.se/om-kraftsystemet/kontrollrummet/ where I want the last segment called "Förbrukning I Sverige". I am trying to extract with this code:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome ... | [
"You can try the next working example where you have to accept cookies at first then you have to click on table button using right element locator strategy along with WebDriverWait and execution of JavaScript.\nfrom selenium import webdriver\nimport time\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom sel... | [
1
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074520740_python_selenium_web_scraping.txt |
Q:
Python/NumPy: Split non-consecutive values into discrete subset arrays
How can I slice arrays such as this into n-many subsets, where one subset consists of consecutive values?
arr = np.array((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, ... | Python/NumPy: Split non-consecutive values into discrete subset arrays | How can I slice arrays such as this into n-many subsets, where one subset consists of consecutive values?
arr = np.array((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71))
# tells me where they are consecutive
... | [
"You can use np.split, and just pass in cut_points as the 2nd argument.\neg.\nsplit_arr = np.split(arr, cut_points)\n\n# split_arr looks like:\n# [array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),\n# array([39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]),\n# array([66, 67, 68... | [
2,
1
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074521283_arrays_numpy_python.txt |
Q:
Selenium properly clicks on the correct option, but when selecting the element for add to cart, it always adds only the first option
I'm creating a webscraper with Selenium that will add products to a cart, and then cycle through cities, states and zip codes to give me the total cost of shipping + taxes for each a... | Selenium properly clicks on the correct option, but when selecting the element for add to cart, it always adds only the first option | I'm creating a webscraper with Selenium that will add products to a cart, and then cycle through cities, states and zip codes to give me the total cost of shipping + taxes for each area.
The website I'm using is: https://www.power-systems.com/shop/product/proelite-competition-kettlebell
Everything in my code appears to... | [
"You are using a wrong selector in the last step.\nbutton.btn.btn-primary.add-to-cart.js-add-to-cart-button is not a unique locator.\nYou need to click the button inside the selected element block.\nThis will work:\ndriver.find_element(By.CSS_SELECTOR, \".variant-info.selected .add-to-cart-rollover\").click()\n\n",... | [
1,
1
] | [] | [] | [
"css_selectors",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074521186_css_selectors_python_selenium_selenium_webdriver.txt |
Q:
problem with creating .exe file in python why it gets too big
I'm making archives to .exe using pyinstaller, but I have a big problem, every time I create a file, its size multiplies, it seems that it is multiplying the libraries, does anyone know how to solve it?
1° file size: 7mb
2° file size: 52mb
3° file size... | problem with creating .exe file in python why it gets too big | I'm making archives to .exe using pyinstaller, but I have a big problem, every time I create a file, its size multiplies, it seems that it is multiplying the libraries, does anyone know how to solve it?
1° file size: 7mb
2° file size: 52mb
3° file size: 104mb
4° file size: 207mb
5° file size: 414mb
6° file size: 828mb... | [
"You can try AutoPyToExe\nwith python's virtual environment plugin\nfollow these commands:\n\nInstall, Create and Activate Virtual Environment:\n\n\npython -m pip install virtualenv\n\n\npython -m venv example_env\n\n\nexample_env/Scripts/activate\n\n\nInstall AutoPyToExe:\n\n\n(example_env) python -m pip install a... | [
0,
0
] | [] | [] | [
"exe",
"pyinstaller",
"python",
"python_3.x",
"selenium"
] | stackoverflow_0074519729_exe_pyinstaller_python_python_3.x_selenium.txt |
Q:
Error message about 'libsqlite3' when activate environment in jupyter Notebook
I try to activate my env to Jupyter notebook by using:
python -m ipykernel install --user --name native --display-name "python-gpu"
But error message:
Traceback (most recent call last):
File "/Users/nianhua/opt/anaconda3/envs/nat... | Error message about 'libsqlite3' when activate environment in jupyter Notebook | I try to activate my env to Jupyter notebook by using:
python -m ipykernel install --user --name native --display-name "python-gpu"
But error message:
Traceback (most recent call last):
File "/Users/nianhua/opt/anaconda3/envs/native/lib/python3.10/runpy.py", line 196, in _run_module_as_main
return _run_code(... | [
"I had the same problem and I solved by installing a newer version:\n\nmamba install sqlite=3.40.0\n\nalways checking that the new library is coming from conda-forge/osx-arm64.\n"
] | [
0
] | [] | [] | [
"anaconda",
"apple_m1",
"apple_silicon",
"jupyter_notebook",
"python"
] | stackoverflow_0072312755_anaconda_apple_m1_apple_silicon_jupyter_notebook_python.txt |
Q:
To find Oplog size using python
How to find oplog size in mongodb using python?
For example :
replGetSetStatus is equivalent to rs.status()
Is there any similar command to find rs.printReplicationInfo()
uri = "mongodb://usernamen:password@host:port/admin"
conn = pymongo.MongoClient(uri)
db = conn['admin']
db_stats... | To find Oplog size using python | How to find oplog size in mongodb using python?
For example :
replGetSetStatus is equivalent to rs.status()
Is there any similar command to find rs.printReplicationInfo()
uri = "mongodb://usernamen:password@host:port/admin"
conn = pymongo.MongoClient(uri)
db = conn['admin']
db_stats = db.command({'replSetGetStatus' :1... | [
"The following commands executed from any replicaSet member will give you the size of oplog:\nUncompressed size in MB:\n db.getReplicationInfo().logSizeMB\n\nUncompressed current size in Bytes:\n db.getSiblingDB('local').oplog.rs.stats().size\n\nCompressed current size in Bytes:\n db.getSiblingDB('local').oplog.rs... | [
0
] | [] | [] | [
"automation",
"mongodb",
"mongodb_oplog",
"pymongo",
"python"
] | stackoverflow_0074521569_automation_mongodb_mongodb_oplog_pymongo_python.txt |
Q:
How to select NumPy matrix rows that contain certain value/values?
I have the following NumPy array:
m = np.array([[1, 2, 3],
[2, 4, 3],
[1, 2, 1]])
I want to have an array that contains the rows of m where there is at least one occurence of 1 in any column, so:
np.array([[1, 2, 3],
... | How to select NumPy matrix rows that contain certain value/values? | I have the following NumPy array:
m = np.array([[1, 2, 3],
[2, 4, 3],
[1, 2, 1]])
I want to have an array that contains the rows of m where there is at least one occurence of 1 in any column, so:
np.array([[1, 2, 3],
[1, 2, 1]])
| [
"Use any and boolean indexing:\nout = m[(m==1).any(axis=1)]\n\nOutput:\narray([[1, 2, 3],\n [1, 2, 1]])\n\nIntermediates:\n(m==1)\n\narray([[ True, False, False],\n [False, False, False],\n [ True, False, True]])\n\n\n(m==1).any(axis=1)\n\narray([ True, False, True])\n\n"
] | [
5
] | [] | [] | [
"matrix",
"numpy",
"python"
] | stackoverflow_0074521663_matrix_numpy_python.txt |
Q:
How to save a data frame and it's column to a text file?
I have a data frame DF as follows:
import pandas as pd
DF = pd.DataFrame({'A': [1], 'B': [2]})
I'm trying to save it to a Test.txt file by following this answer, with:
np.savetxt(r'Test.txt', DF, fmt='%s')
Which does save only DF values and not the column... | How to save a data frame and it's column to a text file? | I have a data frame DF as follows:
import pandas as pd
DF = pd.DataFrame({'A': [1], 'B': [2]})
I'm trying to save it to a Test.txt file by following this answer, with:
np.savetxt(r'Test.txt', DF, fmt='%s')
Which does save only DF values and not the column names:
1 2
How do I save it to have Test.txt with the follow... | [
"From the same answer you linked, if you want to use Pandas, just change header=True like:\nDF.to_csv('Test.txt', header=True, index=None, sep=' ', mode='a')\n\nIf you want to use np.savetxt():\nnp.savetxt(\n 'Test.txt',\n DF.values,\n fmt='%s',\n header=' '.join(DF.columns),\n comments=''\n)\n\nNote... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074521366_pandas_python.txt |
Q:
Loading a deployed ONNX model only once
I have a big Machine learning/ Computer vision project that is using an ONNX model, using python.
the project takes around 3 seconds (locally) just to load the model + inference.
Time taken to load onnx model : 0.2702977657318115
Time taken for onnx inference 1.67353010177... | Loading a deployed ONNX model only once | I have a big Machine learning/ Computer vision project that is using an ONNX model, using python.
the project takes around 3 seconds (locally) just to load the model + inference.
Time taken to load onnx model : 0.2702977657318115
Time taken for onnx inference 1.673530101776123
Time taken for onnx inference 0.76770138... | [
"Are you trying to load the model and then doing the inference every time that you have a request?\nYou should load once and keep the session throughout the time life of the inference process. You could also look into execution providers that come with ONNXruntime to try and speed up the inference time like CUDA, t... | [
0
] | [] | [] | [
"computer_vision",
"machine_learning",
"onnx",
"python",
"tensorflow"
] | stackoverflow_0074252832_computer_vision_machine_learning_onnx_python_tensorflow.txt |
Q:
Adding JavaScript to Folium map
I'm working on a project to make a map using folium and flask and I'm trying to add my own javascript to add some animation to the tile to appear one by one.
The question is how can I add my custom javascript to the map using python flask
as I have tried this way in this code below... | Adding JavaScript to Folium map | I'm working on a project to make a map using folium and flask and I'm trying to add my own javascript to add some animation to the tile to appear one by one.
The question is how can I add my custom javascript to the map using python flask
as I have tried this way in this code below:
from branca.element import Element
... | [
"I already found out how to include JavaScript and CSS external link also inline js:\nFirstly, way we can add CSS link to the header of the page\nm.get_root().header.add_child(CssLink('./static/style.css'))\n\nThen, this is the code to insert JavaScript External link to folium\nm.get_root().html.add_child(Javascri... | [
6,
0
] | [] | [] | [
"dictionary",
"flask",
"folium",
"javascript",
"python"
] | stackoverflow_0060479995_dictionary_flask_folium_javascript_python.txt |
Q:
In a xml file, how to get a tag that contains segmentation points which is placed after the key tag(not in it)
I have a xml file that contaions segmentation points but I dont know how to get them. It not well builded I guess because the points stands in a tag after a tag that contains "points_px" string. (It is n... | In a xml file, how to get a tag that contains segmentation points which is placed after the key tag(not in it) | I have a xml file that contaions segmentation points but I dont know how to get them. It not well builded I guess because the points stands in a tag after a tag that contains "points_px" string. (It is not in the "point_px" tag.)
My question is how to get the tags that contains the points with most efficient way?
This... | [
"For your xml structure, you are better off using lxml because of its better xpath support compared to that of ElementTree.\nAlso, note that the xml in your question isn't well formed (because the <plist> element is never opened).\nAssuming that's fixed, try this:\nfrom lxml import etree\nimages = \"\"\"[your xml a... | [
0
] | [] | [] | [
"python",
"xml",
"xml.etree"
] | stackoverflow_0074510828_python_xml_xml.etree.txt |
Q:
Web scrape links with Python, then turn them into a string
With Python I'm having issues turning web scrapped links into strings so I can save them as either a txt or csv file. I would really like them as a txt file. This is what I have at the moment.
import requests
from bs4 import BeautifulSoup
url = "https://w... | Web scrape links with Python, then turn them into a string | With Python I'm having issues turning web scrapped links into strings so I can save them as either a txt or csv file. I would really like them as a txt file. This is what I have at the moment.
import requests
from bs4 import BeautifulSoup
url = "https://www.google.com/"
reqs = requests.get(url)
soup = BeautifulSoup(re... | [
"print(link, file=open('example.txt','w'))\n\nWill write the link variable, but that's only the last one.\n\nTo write them all, use:\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.google.com/\"\nreqs = requests.get(url)\nsoup = BeautifulSoup(reqs.text, 'html.parser')\n\nwith open(\"example.t... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074521371_python.txt |
Q:
Two dll function calls only work with random print() in between
I use a camera SDK with a DLL (ctypes.WinDLL).
camera_path = 'cam://0'.encode('utf-8')
handle = xdll.XDLL.open_camera(camera_path, 0, 0)
# (The handle returned is 1)
xdll.XDLL.set_property_value_f(handle, b'IntegrationTime', c_double(2500))
This give... | Two dll function calls only work with random print() in between | I use a camera SDK with a DLL (ctypes.WinDLL).
camera_path = 'cam://0'.encode('utf-8')
handle = xdll.XDLL.open_camera(camera_path, 0, 0)
# (The handle returned is 1)
xdll.XDLL.set_property_value_f(handle, b'IntegrationTime', c_double(2500))
This gives an the following error:
OSError: exception: access violation readin... | [
"I forgot to add a required parameter (char * pUnit) to the argtypes.\nTherefore, i got some weird/undefined behaviour.\nNow, after i added the parameter the code executes as expected.\n"
] | [
0
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0074520735_ctypes_python.txt |
Q:
Pandas - Datetime Manipulation
I have a dataframe like so:
CREATED_AT COUNT
'1990-01-01' '2022-01-01 07:30:00' 5
'1990-01-02' '2022-01-01 07:30:00' 10
...
Where the index is a date and the CREATED_AT column is a datetime that is the same value for all rows.
How can I update th... | Pandas - Datetime Manipulation | I have a dataframe like so:
CREATED_AT COUNT
'1990-01-01' '2022-01-01 07:30:00' 5
'1990-01-02' '2022-01-01 07:30:00' 10
...
Where the index is a date and the CREATED_AT column is a datetime that is the same value for all rows.
How can I update the CREATED_AT_COLUMN such that it inh... | [
"You can use df.reset_index() to use the index as a column and then do a simple maniuplation to get the output you want like this:\n# Creating a test df\nimport pandas as pd\nfrom datetime import datetime, timedelta, date\n\ndf = pd.DataFrame.from_dict({\n \"CREATED_AT\": [datetime.now(), datetime.now() + timede... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074521526_pandas_python.txt |
Q:
Kivy with cv2 in python (Read barcode)
i try to make app for read barcode using android machine and i have problem i cant compare between cv and kivy please if someone can help me .
code that read barcode from android camera using kivy
from kivy.app import App
from kivy.uix.camera import Camera
from pyzbar.pyzbar... | Kivy with cv2 in python (Read barcode) | i try to make app for read barcode using android machine and i have problem i cant compare between cv and kivy please if someone can help me .
code that read barcode from android camera using kivy
from kivy.app import App
from kivy.uix.camera import Camera
from pyzbar.pyzbar import decode
import numpy as np
import cv2... | [
"what do you mean by \" i cant compare between cv and kivy\" ? I have working machine learning app in kivy using cam. So what do you exactly need ? You need o display img in cv window, or you want to display camera frames in kivy ? You can update the kivy window every x second:\n def __init__(self, **kw):\n ... | [
0
] | [] | [] | [
"cv2",
"kivy",
"kivymd",
"python"
] | stackoverflow_0074511067_cv2_kivy_kivymd_python.txt |
Q:
Getting memory error in Python 3.8, using spider as my IDE
I am trying to run a program that involves multiplying two large binary NumPy arrays of size 69496 times 511. My arrays are binary, and I am using Spyder as my IDE.
Here is my code:
import numpy as np
import math
import re
def ip(A):
B=A.transpose()
... | Getting memory error in Python 3.8, using spider as my IDE | I am trying to run a program that involves multiplying two large binary NumPy arrays of size 69496 times 511. My arrays are binary, and I am using Spyder as my IDE.
Here is my code:
import numpy as np
import math
import re
def ip(A):
B=A.transpose()
C = np.dot(A, B)
[a, b] = C.shape
D=[]
for i in r... | [
"what you actually want is this function:\nyou dont need to calculate the a x aT, since you have huge matrix, it finally gonna need big memory size. you could set the dtype as uint16 , but any way finally still the size is huge (since you have huge number of row)\ndef ip(a):\n m, n = a.shape\n c = []\n for... | [
0
] | [] | [] | [
"numpy",
"numpy_ndarray",
"python",
"python_3.x"
] | stackoverflow_0074520446_numpy_numpy_ndarray_python_python_3.x.txt |
Q:
How to animate the vector field?
As the question, how do I animate a series of plots instead of printing each individual plot? Thanks a lot!!!
import numpy as np
from matplotlib import pyplot as plt
from scipy.integrate import odeint
import matplotlib.animation as animation
%matplotlib inline
# Define vector fi... | How to animate the vector field? | As the question, how do I animate a series of plots instead of printing each individual plot? Thanks a lot!!!
import numpy as np
from matplotlib import pyplot as plt
from scipy.integrate import odeint
import matplotlib.animation as animation
%matplotlib inline
# Define vector field
def vField(x,t,a):
u = 2*x[1]
... | [
"You have to declare your fig, ax before the loop and clear it between each quiver.\nIndeed, you want to use only one figure and not create one by iteration. Moreover, you want to clear the figure between each iteration or all plots will be shown on top of the others.\nfig, ax = plt.subplots(figsize=(10, 7))\n\nfor... | [
0,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074521021_matplotlib_python.txt |
Q:
Converting nested JSON into a flattened DataFrame
I have a data load in nested json format and I want to get a nested dataframe
{
"page_count": 21,
"page_number": 1,
"page_size": 300,
"total_records": 6128,
"registrants": [
{
"id": "23lnTNqyQ3qkthfghjgkk",
"first... | Converting nested JSON into a flattened DataFrame | I have a data load in nested json format and I want to get a nested dataframe
{
"page_count": 21,
"page_number": 1,
"page_size": 300,
"total_records": 6128,
"registrants": [
{
"id": "23lnTNqyQ3qkthfghjgkk",
"first_name": "HUGO",
"last_name": "MACHA ILLEN... | [
"you can use json_normalize:\ndf = pd.DataFrame(your_json['registrants']).explode('custom_questions').reset_index(drop=True)\ndf=df.join(pd.json_normalize(df.pop('custom_questions')))\n\n#convert rows to columns. Set index first 17 columns. We will not use theese.\ndf=df.set_index(df.columns[0:17].to_list())\ndfx=d... | [
0
] | [] | [] | [
"dictionary",
"json",
"json_normalize",
"nested",
"python"
] | stackoverflow_0074513401_dictionary_json_json_normalize_nested_python.txt |
Q:
"from typing import List" vs "from ast import List"
In Python, if I use this:
from typing import List
I have to use List[]
If I use this:
from ast import List
I have to use List()
What is the difference?
Thanks.
googled "typing" and "ast" but no luck
A:
The difference is that one is a type-hint; it describes... | "from typing import List" vs "from ast import List" | In Python, if I use this:
from typing import List
I have to use List[]
If I use this:
from ast import List
I have to use List()
What is the difference?
Thanks.
googled "typing" and "ast" but no luck
| [
"The difference is that one is a type-hint; it describes a value, not holds elements itself. It is also optional.\nThe other is a runtime-class describing the Python syntax-tree, and holds a sequential collection of Python expressions. ast.List is required if you are building/using a parser.\n"
] | [
2
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074521877_list_python_python_3.x.txt |
Q:
Ignoring bad rows of data in pandas.read_csv() that break header= keyword
I have a series of very messy *.csv files that are being read in by pandas. An example csv is:
Instrument 35392
"Log File Name : station"
"Setup Date (MMDDYY) : 031114"
"Setup Time (HHMMSS) : 073648"
"Starting Date (MMDDYY) : 031114"
"Start... | Ignoring bad rows of data in pandas.read_csv() that break header= keyword | I have a series of very messy *.csv files that are being read in by pandas. An example csv is:
Instrument 35392
"Log File Name : station"
"Setup Date (MMDDYY) : 031114"
"Setup Time (HHMMSS) : 073648"
"Starting Date (MMDDYY) : 031114"
"Starting Time (HHMMSS) : 090000"
"Stopping Date (MMDDYY) : 031115"
"Stopping Time (H... | [
"Here's one approach, making use of the fact that skip_rows accepts a callable function. The function receives only the row index being considered, which is a built-in limitation of that parameter. \nAs such, the callable function skip_test() first checks whether the current index is in the set of known indices t... | [
3,
0,
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0045679857_csv_pandas_python.txt |
Q:
PyInstaller: Single-file executable doesn't work
PS C:\Users\user> pyinstaller onefile Traceback (most recent call last): File "<frozen runpy>", line 198, in _ru... | PyInstaller: Single-file executable doesn't work | PS C:\Users\user> pyinstaller onefile Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _r... | [
"I honestly do not know what that error is. All I can say is that\nthe command for making a single .exe file with pyinstaller is:\npyinstaller --onefile <filename>\n\nFor example pyinstaller --onefile myscript.py\nI did a quick search and found this in pyinstaller: create one executable file\nWhat you have done is ... | [
1,
1,
0
] | [] | [] | [
"pyinstaller",
"python",
"python_3.x"
] | stackoverflow_0072565499_pyinstaller_python_python_3.x.txt |
Q:
TensorFlow seems to modify both class and instance object
I have observed that the TensorFlow methods like assign_add and assign_sub modify the variables of both object and class (if exist). Here is a simple code to reproduce my observation. Can anyone please clarify about this behavior (assign_sub and assign_add ... | TensorFlow seems to modify both class and instance object | I have observed that the TensorFlow methods like assign_add and assign_sub modify the variables of both object and class (if exist). Here is a simple code to reproduce my observation. Can anyone please clarify about this behavior (assign_sub and assign_add modifying both class and instance attributes)?
#a python class
... | [
"a is a class attribute. b is an instance attribute.\nHowever, augmented assignments like\nself.a += to_add\nself.a -= to_sub\n\nare not modifying the class attribute you think you are accessing via the instance. They are really equivalent to\nself.a = self.a.__iadd__(to_add)\nself.a = self.a.__isub__(to_sub)\n\nso... | [
1,
0
] | [] | [] | [
"class",
"object",
"python",
"tensorflow"
] | stackoverflow_0074520583_class_object_python_tensorflow.txt |
Q:
Build a matrix from a string of number separated by space
I have a list of numbers in a string separated by space x="1 2 3 4 5 6 7 8 9 10 11 ..."
I want to extract 3x3 matrices (list of list) from this string so the above string should produce the output = [ [[1,2,3],[4,5,6],[7,8,9]],[ [10,11,12],[13,14,15],[16,17... | Build a matrix from a string of number separated by space | I have a list of numbers in a string separated by space x="1 2 3 4 5 6 7 8 9 10 11 ..."
I want to extract 3x3 matrices (list of list) from this string so the above string should produce the output = [ [[1,2,3],[4,5,6],[7,8,9]],[ [10,11,12],[13,14,15],[16,17,18] ]...
I tried using the split function on the variable x an... | [
"With NymPy, this is quite easy.\nFirst, use str.split() to get a list of the numbers, cast them to ints (or floats if you need), and then reshape the array:\nimport numpy as np\n\ns = '0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17'\n\na = np.array([int(x) for x in s.split()]).reshape((-1,3))\n\nyields\narray([[ 0, ... | [
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074521840_python.txt |
Q:
Subplot of dendrograms
I am creating six different dendrograms based on linkage. I have a for loop which loops through the six different linkage types. I want to print out all six of the dendrograms on one plot (using subplot) but cannot figure out how to do this. My attempt is below - with the commented-out li... | Subplot of dendrograms | I am creating six different dendrograms based on linkage. I have a for loop which loops through the six different linkage types. I want to print out all six of the dendrograms on one plot (using subplot) but cannot figure out how to do this. My attempt is below - with the commented-out lines being the code intended ... | [
"Every time you call plt.figure, matplotlib will create a new figure (plot). Since this is inside your for loop, you're currently creating a new plot for each dendogram. You can move plt.figure outside of the for loop, but then you'll need to spend some effort placing the dendograms such that they can still be read... | [
0
] | [] | [] | [
"dendrogram",
"python",
"subplot"
] | stackoverflow_0074513863_dendrogram_python_subplot.txt |
Q:
what is the significance of @tf.function in neural networks?
I am learning deep neural networks (beginner level). What is the use of @tf.function in tensorflow?
for example
@tf.function
def add(a,b):
c=tf.add (a,b)
print(c)
return(c)
could anyone please explain how this way of coding helps to create a network
A:... | what is the significance of @tf.function in neural networks? | I am learning deep neural networks (beginner level). What is the use of @tf.function in tensorflow?
for example
@tf.function
def add(a,b):
c=tf.add (a,b)
print(c)
return(c)
could anyone please explain how this way of coding helps to create a network
| [
"tf.function converts the function into a callable TensorFlow graph where the tensor computations are executed as a TensorFlow graph(tf.Graph). \"Graphs are data structures that contain a set of tf.Operation objects, which represent units of computation; and tf.Tensor objects, which represent the units of data that... | [
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0072582777_python_tensorflow.txt |
Q:
How to pass arguments to HuggingFace TokenClassificationPipeline's tokenizer
I've finetuned a Huggingface BERT model for Named Entity Recognition. Everything is working as it should. Now I've setup a pipeline for token classification in order to predict entities out the text I provide. Even this is working fine.
I... | How to pass arguments to HuggingFace TokenClassificationPipeline's tokenizer | I've finetuned a Huggingface BERT model for Named Entity Recognition. Everything is working as it should. Now I've setup a pipeline for token classification in order to predict entities out the text I provide. Even this is working fine.
I know that BERT models are supposed to be fed with sentences less than 512 tokens ... | [
"I took a closer look at https://github.com/huggingface/transformers/blob/v4.24.0/src/transformers/pipelines/token_classification.py#L86. It seems you can override preprocess() to disable truncation and add padding to longest.\nfrom transformers import TokenClassificationPipeline\n\nclass MyTokenClassificationPipel... | [
1
] | [] | [] | [
"huggingface",
"huggingface_tokenizers",
"huggingface_transformers",
"named_entity_recognition",
"python"
] | stackoverflow_0073745607_huggingface_huggingface_tokenizers_huggingface_transformers_named_entity_recognition_python.txt |
Q:
How to put text in an animation
I am trying to put text in a matplotlib animation. (Hopefully outside the plot, but I am not worrying about that yet)
I tried to follow this solution, however my code is a bit complicated in that it does not gives only one line every time.
Here is my code
import math
import argpars... | How to put text in an animation | I am trying to put text in a matplotlib animation. (Hopefully outside the plot, but I am not worrying about that yet)
I tried to follow this solution, however my code is a bit complicated in that it does not gives only one line every time.
Here is my code
import math
import argparse
import os
import json
import sys
i... | [
"After un-commenting your line of code, I didn't get any error, however the text was not visible. So, instead of using ax.text I tried fig.text: now the text is visible outside the plotting area.\nimport math\nimport argparse\nimport os\nimport json\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt... | [
0
] | [] | [] | [
"animation",
"matplotlib",
"python",
"visualization"
] | stackoverflow_0074517974_animation_matplotlib_python_visualization.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.