content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to set a foreignkey field in views? I'm trying to save the customer field on the Test model, I'm not getting any errors but it's not saving the field either, how do I fix it? Models class Test(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) email ...
How to set a foreignkey field in views?
I'm trying to save the customer field on the Test model, I'm not getting any errors but it's not saving the field either, how do I fix it? Models class Test(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) email = models.EmailField(max_length=200, blank=Fal...
[ "You can use cleaned_data to save the ModelForm.\nforms.py\nclass TestForm(forms.ModelForm):\n\n class Meta:\n model = Test\n fields = [\"email\"]\n\nAssuming, you have request method POST.\nviews.py\ndef test_view(request):\n if request.method==\"POST\":\n form=TestForm(request.POST)\n \...
[ 2, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0074598722_django_django_forms_django_models_django_views_python.txt
Q: How to print logger from a xml file which have null value? i am trying to capture some fields from a xml file. Using "logger.info" i have successfully printing log of my code. the below is my code: #providing the path for client fr & counting the total files processed D_DIR = Path(directory[0]) client_id = directo...
How to print logger from a xml file which have null value?
i am trying to capture some fields from a xml file. Using "logger.info" i have successfully printing log of my code. the below is my code: #providing the path for client fr & counting the total files processed D_DIR = Path(directory[0]) client_id = directory[0].split(os.sep)[-2] files = sorted(D_DIR.glob("*.xml")) tota...
[ "I found out the method to do it. we need to write the logger in \".format\" way below the capturing process code.\n logger.info(\"data_capture_date:{} | case_id:{} | organization:{} | supplier_number:{} | invoice_Number:{} | document_Type:{} | invoice_Source:{} | rowcount:{}\".format(data_capture_date, case_id,o...
[ 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0074596672_python_xml.txt
Q: How do I write the time from datetime to a file in Python? I'm trying to have my Python code write everything it does to a log, with a timestamp. But it doesn't seem to work. this is my current code: filePath= Path('.') time=datetime.datetime.now() bot_log = ["","Set up the file path thingy"] with open ('bot.log',...
How do I write the time from datetime to a file in Python?
I'm trying to have my Python code write everything it does to a log, with a timestamp. But it doesn't seem to work. this is my current code: filePath= Path('.') time=datetime.datetime.now() bot_log = ["","Set up the file path thingy"] with open ('bot.log', 'a') as f: f.write('\n'.join(bot_log)% datetime.datetime.no...
[ "You need to put \"%s\" somewhere in the input string before string formatting. Here's more detailed explanation.\nTry this:\nfilePath= Path('.')\ntime=datetime.datetime.now()\nbot_log = \"%s Set up the file path thingy\\n\"\nwith open ('bot.log', 'a') as f:\n f.write(bot_log % datetime.datetime.now().strftime(\"%...
[ 2, 1 ]
[]
[]
[ "python", "python_datetime" ]
stackoverflow_0074599505_python_python_datetime.txt
Q: TensorFlow model subclassing API with vars doesn't show parameters or layers I wrote following code for VGG block, and I want to show the summary of the block: import tensorflow as tf from keras.layers import Conv2D, MaxPool2D, Input class VggBlock(tf.keras.Model): def __init__(self, filters, repetitions): ...
TensorFlow model subclassing API with vars doesn't show parameters or layers
I wrote following code for VGG block, and I want to show the summary of the block: import tensorflow as tf from keras.layers import Conv2D, MaxPool2D, Input class VggBlock(tf.keras.Model): def __init__(self, filters, repetitions): super(VggBlock, self).__init__() self.repetitions = repetitions f...
[ "Presumably, setting class attributes like this circumvents the usual housekeeping done by a Keras Layer (such as registering variables, sub-layers etc.), so you should avoid doing this. Rather do something like this:\nclass VggBlock(tf.keras.Model):\n def __init__(self, filters, repetitions):\n super(VggBlock,...
[ 2 ]
[]
[]
[ "model", "python", "subclass", "tensorflow" ]
stackoverflow_0074596313_model_python_subclass_tensorflow.txt
Q: Rename first two character based on condition in python Folder contains images in format jpg, and png. Here we need to achieve: Image files name start with 11BHBHHJJKKKKK.JPG, 11BCBHHJJKKKKK.JPG, 11BKBHHJJKKKKK.JPG, 33GFHJJKKKKJK.JPG, 33JHNNHHJJJJJ.JPG, 44HJFHJFHJFHF.PNG, 44HJFHJFKKHF.JPG So here we need to change...
Rename first two character based on condition in python
Folder contains images in format jpg, and png. Here we need to achieve: Image files name start with 11BHBHHJJKKKKK.JPG, 11BCBHHJJKKKKK.JPG, 11BKBHHJJKKKKK.JPG, 33GFHJJKKKKJK.JPG, 33JHNNHHJJJJJ.JPG, 44HJFHJFHJFHF.PNG, 44HJFHJFKKHF.JPG So here we need to change image name using following conditions: image name start with...
[ "You could do something like below, where you check every single condition you're looking for.\nfrom pathlib import Path\nfor filename in glob.glob(imagepath): #assuming gif\n path = Path(filename)\n head = os.path.split(filename)[1]\n if head.startswith('11'):\n os.rename(filename, os.path.join(pat...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074599432_python.txt
Q: Save an image to RAM I want to send an image through socket server. After sending it, I want to show this image on ram (I mean without saving as a file). I made some amazing array changes and finally I reached my original array but I still have an error to show this image. And my array progress is really slow. Is ...
Save an image to RAM
I want to send an image through socket server. After sending it, I want to show this image on ram (I mean without saving as a file). I made some amazing array changes and finally I reached my original array but I still have an error to show this image. And my array progress is really slow. Is there any suggestion for i...
[ "I solved my problem changing only 1 line of code. We need to declare datatype of array. Here is the code:\narr2=np.array(arr2.reshape(353,616,3), dtype=np.uint8)\n\nHowever, I found a new function cv2.imencode()\nThis function is exactly what I wanted and it is really faster than my code. So, I am going to use thi...
[ 0 ]
[]
[]
[ "cv2", "image", "numpy", "python", "sockets" ]
stackoverflow_0074593809_cv2_image_numpy_python_sockets.txt
Q: What is the time complexity of this code for Best Time to Buy and Sell Stock I am a beginner in coding, I was doing a leetcode problem "121. Best Time to Buy and Sell Stock". I wrote a code that works pretty well but when I try to run it, it says Time Limit Exceeded. Looking at this code, this would be O(n) time c...
What is the time complexity of this code for Best Time to Buy and Sell Stock
I am a beginner in coding, I was doing a leetcode problem "121. Best Time to Buy and Sell Stock". I wrote a code that works pretty well but when I try to run it, it says Time Limit Exceeded. Looking at this code, this would be O(n) time complexity and for the space complexity it would be O(1). I have seen other solutio...
[ "Some observations:\n\nEither l is updated and r is set to one more, or l is not updated and r does not diminish. This means that the while condition is always satisfied. The only way to exit the loop is via the break. This means the loop header could also have been written as while True:\n\nThe r index visits the ...
[ 0 ]
[]
[]
[ "algorithm", "data_structures", "python" ]
stackoverflow_0074597778_algorithm_data_structures_python.txt
Q: Emoji Remove from the specific column I want to just remove emoji from one column and sepecial charater for eg (@ #.:/,.). Will remain in that specific column ? I want to clean the data A: You can remove emojis from your data columns using the following code df.astype(str).apply(lambda x: x.str.encode('ascii', '...
Emoji Remove from the specific column
I want to just remove emoji from one column and sepecial charater for eg (@ #.:/,.). Will remain in that specific column ? I want to clean the data
[ "You can remove emojis from your data columns using the following code\ndf.astype(str).apply(lambda x: x.str.encode('ascii', 'ignore').str.decode('ascii'))\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074598854_dataframe_pandas_python.txt
Q: How to I split the time_taken' column of a dataframe? I am trying to split the time_taken attribute (eg., 02h 10m) into only numbers using the below code. I have checked earlier posts and this code seemed to work fine for some of you but it is not working for me. t=pd.to_timedelta(df3['time_taken']) df3['hours']=t...
How to I split the time_taken' column of a dataframe?
I am trying to split the time_taken attribute (eg., 02h 10m) into only numbers using the below code. I have checked earlier posts and this code seemed to work fine for some of you but it is not working for me. t=pd.to_timedelta(df3['time_taken']) df3['hours']=t.dt.components['hours'] df3['minutes']=t.dt.components['min...
[ "You can try this code. Since you mentioned that your time_taken attribute looks like this: 02h 10m. I have written an example code which you can try out.\nimport pandas as pd\n\n# initializing example time data\ntime_taken = ['1h 10m', '2h 20m', '3h 30m', '4h 40m', '5h 50m']\n\n#inserting the time data into a pand...
[ 0 ]
[]
[]
[ "duration", "pandas", "python", "timedelta", "valueerror" ]
stackoverflow_0074595396_duration_pandas_python_timedelta_valueerror.txt
Q: Alternative to Using Repeated Stratified K Fold with Multiple Outputs? I am exploring the number of features that would be best to use for my models. I understand that a Repeated Stratified K Fold requires 1 1D array output while I am trying to evaluate the number of features for an output that has multiple output...
Alternative to Using Repeated Stratified K Fold with Multiple Outputs?
I am exploring the number of features that would be best to use for my models. I understand that a Repeated Stratified K Fold requires 1 1D array output while I am trying to evaluate the number of features for an output that has multiple outputs. Is there a way to use the Repeated Stratified K Fold with multiple output...
[ "as i know, you can use cross_validate() as alternative of StratifiedKFold with multiple output. You can define cross validation technique with StratifiedKFold and scoring metrics as your preference. You can check link below for more detail !\nhttps://scikit-learn.org/stable/modules/generated/sklearn.model_selectio...
[ 0 ]
[]
[]
[ "feature_selection", "k_fold", "python" ]
stackoverflow_0073281240_feature_selection_k_fold_python.txt
Q: How to Fix Attribute Error: module 'graph' has no attribute 'get_user_token' I have imported graph already, any idea why it can't identify the attribute? def display_access_token(graph: Graph): token = graph.get_user_token() print('User token:', token, '\n') if user_input == '0': display_access_token(...
How to Fix Attribute Error: module 'graph' has no attribute 'get_user_token'
I have imported graph already, any idea why it can't identify the attribute? def display_access_token(graph: Graph): token = graph.get_user_token() print('User token:', token, '\n') if user_input == '0': display_access_token(graph) I am not sure what to do to fix it. Thanks in advance.
[ "I have referred the sample code from the official documentation. After reproducing from my end, this was working fine after adding get_user_token() in the graph.py. Below is the complete code in my graph.py.\nimport json\nfrom configparser import SectionProxy\nfrom azure.identity import DeviceCodeCredential, Clien...
[ 0 ]
[]
[]
[ "azure", "microsoft_graph_api", "python" ]
stackoverflow_0074593631_azure_microsoft_graph_api_python.txt
Q: Why does my function does not give me the expected output Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False. Note that the code stub provided reads from STDIN and passes arguments to the is_leap function. It is only necessary to complete the is...
Why does my function does not give me the expected output
Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False. Note that the code stub provided reads from STDIN and passes arguments to the is_leap function. It is only necessary to complete the is_leap function. In the Gregorian calendar, three conditions are...
[ "As @Grismar pointed your function is not returning anything so just add return leap to the end.\ndef is_leap(year):\n leap= False\n\n if (year % 400 == 0) and (year % 100 == 0):\n leap = True\n elif (year % 4 ==0) and (year % 100 != 0):\n leap=True\n else:\n pass\n return leap\n...
[ 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0074588991_function_python.txt
Q: How to add new data to existing dataframe I've created empty dataframe that I have to fill. d = {'A': [], 'B': [], 'C': []} dataframe = pd.DataFrame(data=d) Then I am assigning data like this: dataframe['A'] = some_list_1a dataframe['B'] = some_list_1b dataframe['C'] = some_list_1c So my dataframe is filled like...
How to add new data to existing dataframe
I've created empty dataframe that I have to fill. d = {'A': [], 'B': [], 'C': []} dataframe = pd.DataFrame(data=d) Then I am assigning data like this: dataframe['A'] = some_list_1a dataframe['B'] = some_list_1b dataframe['C'] = some_list_1c So my dataframe is filled like this: A B C ---------------- val1 v...
[ "Create dictionary with all joined lists first and then call DataFrame is fastest and recommended way, check this:\nd = {'A': some_list_1a + some_list_2a, \n 'B': some_list_1b + some_list_2b,\n 'C': some_list_1c + some_list_2c}\ndataframe = pd.DataFrame(data=d)\n\nIf need append dict of list in loop:\nfrom ...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074599828_dataframe_pandas_python.txt
Q: Writing a constraint with gurobipy I shared the parameters, variables and notation of the model: I have difficulty in writing equation 7, which is one of the constraints of the model, with gurobipy. The code block I wrote is as follows: mdl2.addConstrs(T[i, j, k] >= quicksum(p[l]*y[i, l, s] + s[l]*x[i, l, s] for...
Writing a constraint with gurobipy
I shared the parameters, variables and notation of the model: I have difficulty in writing equation 7, which is one of the constraints of the model, with gurobipy. The code block I wrote is as follows: mdl2.addConstrs(T[i, j, k] >= quicksum(p[l]*y[i, l, s] + s[l]*x[i, l, s] for l in N for s in ???)- d[j] - 100000*(...
[ "You should be good with writing s in range(k) - the sum depends on the index k from the outer loop.\nTo make this a bit easier to read and comprehend, you might want to switch around the for loops like this:\nfor i in M:\n for j in N:\n for k in N:\n mdl2.addConstr(\n T[i, j, k]...
[ 1 ]
[]
[]
[ "constraints", "gurobi", "linear_programming", "optimization", "python" ]
stackoverflow_0074577839_constraints_gurobi_linear_programming_optimization_python.txt
Q: List of tables in a Database I achieved to have a DataFrame with all the columns and their type of all the tables in my database of Databricks. Database Table Column ColumnType default table1 column1 string default table1 column2 boolean default table2 column3 integer default table2 column4 string default ta...
List of tables in a Database
I achieved to have a DataFrame with all the columns and their type of all the tables in my database of Databricks. Database Table Column ColumnType default table1 column1 string default table1 column2 boolean default table2 column3 integer default table2 column4 string default table2 column5 string ...
[ "\nI have the following data in my 2 tables t1 and t2.\n\n\n\nThe following is how I have the data in my dataframe:\n\n\n\nI have used the following code to get the desired output. First, I have created 2 columns containing respective queries:\n\nfrom pyspark.sql.functions import lit,col,concat_ws \ndf = df.withCol...
[ 0 ]
[]
[]
[ "azure_databricks", "database", "databricks", "null", "python" ]
stackoverflow_0074503462_azure_databricks_database_databricks_null_python.txt
Q: I'm trying to find the maximum of a function using scipy.optimize.minimize. Can someone help me to find out the mistake? price = pd.read_csv('C:\\Users\\mypath\\price.csv', index_col= [0,1], usecols=[0,5,6]) yt = price.loc['AUS'] yt = yt.pct_change().dropna().values def p(u, sigma, pi): d = pi / (2*np.pi...
I'm trying to find the maximum of a function using scipy.optimize.minimize. Can someone help me to find out the mistake?
price = pd.read_csv('C:\\Users\\mypath\\price.csv', index_col= [0,1], usecols=[0,5,6]) yt = price.loc['AUS'] yt = yt.pct_change().dropna().values def p(u, sigma, pi): d = pi / (2*np.pi*sigma)**0.5 * np.exp(-(yt-u)**2 / (2*sigma**2)) return d def Lf(u, sigma, pi): prob = p(u[0], sigma[0], p...
[ "x0 = np.array([...]) # suitably shaped numpy array of your init values\nres = opt.minimize(Lf, x0, args=(u_init, sigma_init, pi_init), method='L-BFGS-B')\n\nMay be you can try calling like this\n" ]
[ 0 ]
[]
[]
[ "optimization", "python", "scipy", "scipy_optimize_minimize" ]
stackoverflow_0074599892_optimization_python_scipy_scipy_optimize_minimize.txt
Q: Why does my values in a list doesn't calculate sum odd and even numbers differently and return it in a new list? I have list named li with values [1,2,4,5] and I want to return a new list with sum of odd numbers and even numbers like new_list = [6,6] where values add as 1+5 = 6 and 2+4 = 6. But, the output that I ...
Why does my values in a list doesn't calculate sum odd and even numbers differently and return it in a new list?
I have list named li with values [1,2,4,5] and I want to return a new list with sum of odd numbers and even numbers like new_list = [6,6] where values add as 1+5 = 6 and 2+4 = 6. But, the output that I am receiving is [1]. Below is my code. class Solution(object): def calculate_odd_even(self, li): even = ...
[ "There are several issues in your code.\n\nyou return too early (in the loop)\nyou add +1 instead of the value\nyou try to append to each loop (do it only in the end)\nthe order of the odd/even values depends on the input data (first one seen of odd/even will be first)\n\nOther \"minor\" issue:\n\ndon't loop over t...
[ 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074599901_list_python.txt
Q: Use PMML models in Python I've found many topics related to this on the Internet but I could find no solutions. Suppose I want to download any PMML model from this examples list, and run them in Python (Python 3 preferably). Is there any way to do this? I'm looking for a way to import a PMML that was deployed OUT...
Use PMML models in Python
I've found many topics related to this on the Internet but I could find no solutions. Suppose I want to download any PMML model from this examples list, and run them in Python (Python 3 preferably). Is there any way to do this? I'm looking for a way to import a PMML that was deployed OUTSIDE Python and import it to us...
[ "You could use PyPMML to apply PMML in Python, for example:\nfrom pypmml import Model\n\nmodel = Model.fromFile('DecisionTreeIris.pmml')\nresult = model.predict({\n \"Sepal_Length\" : 5.1,\n \"Sepal_Width\" : 3.5,\n \"Petal_Length\" : 1.4,\n \"Petal_Width\" : 0.2\n})\n\nFor more info about other PMML li...
[ 5, 1, 0 ]
[]
[]
[ "pmml", "prediction", "python", "python_3.x", "xml" ]
stackoverflow_0052393301_pmml_prediction_python_python_3.x_xml.txt
Q: Keras model prediction gives opposite results I trained a model called model_2 in Keras and made predictions using model.predict but I notice as I rerun the code the results are completely different. For example, first time column 0 has all probability values close to 1, but next time it has probability values all...
Keras model prediction gives opposite results
I trained a model called model_2 in Keras and made predictions using model.predict but I notice as I rerun the code the results are completely different. For example, first time column 0 has all probability values close to 1, but next time it has probability values all close to 0. Has it to do with the memory or the st...
[ "After you train a model, you have store the weights of that model in a file. If you don't do this, you don't keep the trained models if you run your program (or any other) again.\nYou can store the model weights during training by using the ModelCheckpoint callback. https://www.tensorflow.org/api_docs/python/tf/ke...
[ 1, 1, 0 ]
[]
[]
[ "keras", "machine_learning", "prediction", "python", "tensorflow" ]
stackoverflow_0066665742_keras_machine_learning_prediction_python_tensorflow.txt
Q: Maya Python scale picture How to scale a picture to fit a window/layout? With the code below the original image is not actually enlarged to 300px, it is displayed with the original image size instead. import maya.cmds as cmds if (cmds.window(window1, exists=True)): cmds.deleteUI(window1) window1 = cmds.wind...
Maya Python scale picture
How to scale a picture to fit a window/layout? With the code below the original image is not actually enlarged to 300px, it is displayed with the original image size instead. import maya.cmds as cmds if (cmds.window(window1, exists=True)): cmds.deleteUI(window1) window1 = cmds.window(w=300, h=300) layout = cmds....
[ "Try this\nimport maya.OpenMaya as om\n\ndef resize_image(source_image, output_image, width, height):\n\n image = om.MImage()\n image.readFromFile(source_image)\n\n image.resize( width, height )\n image.writeToFile(output_image, 'png')\n\n\nresizeImage('<source_image.png>','<output_image.png>', 300, 300...
[ 1, 0 ]
[]
[]
[ "maya", "python" ]
stackoverflow_0064632275_maya_python.txt
Q: A list of lists, substract the values in each sub-list and store the results in new sub-lists I have a list, that contains many sub-lists. Each sub-list, has two values. I want to substract the first value from the second value in each sub-list, and store the results in new lists. Now those new lists are also sub-...
A list of lists, substract the values in each sub-list and store the results in new sub-lists
I have a list, that contains many sub-lists. Each sub-list, has two values. I want to substract the first value from the second value in each sub-list, and store the results in new lists. Now those new lists are also sub-lists, of another list of lists. So for example, lists_of_lists1 is something like this: lists_of_l...
[ "This is an alternative approach for your MWE:\nmain_list = [\n [\n [34.39460533995712, 47.84539466004288],\n [33.095772478005635, 46.50422752199436],\n [36.66750709361337, 44.44360401749775],\n [33.33459042563053, 42.14689105585095],\n [36.638367322851444, 43.62250224236595],\...
[ 0, 0 ]
[ "This should work. We first get each element of the list of lists (a list with length 2) and then append the difference between the latter lists (i) elements.\nlist = [[1, 23], [3, 2], [32, 213], [2321, 23]]\nres_list = []\nfor i in list:\n res_list.append((i[1]-i[0]))\n\nprint(res_list)\n\n" ]
[ -1 ]
[ "for_loop", "list", "python" ]
stackoverflow_0074599719_for_loop_list_python.txt
Q: How to zip files on s3 using lambda and python I need to archive multiply files that exists on s3 and then upload the archive back to s3. I am trying to use lambda and python. As some of the files have more than 500MB, downloading in the '/tmp' is not an option. Is there any way to stream files one by one and put ...
How to zip files on s3 using lambda and python
I need to archive multiply files that exists on s3 and then upload the archive back to s3. I am trying to use lambda and python. As some of the files have more than 500MB, downloading in the '/tmp' is not an option. Is there any way to stream files one by one and put them in archive?
[ "AWS Lambda code: create zip from files by ext in bucket/filePath.\n\ndef createZipFileStream(bucketName, bucketFilePath, jobKey, fileExt, createUrl=False):\n response = {} \n bucket = s3.Bucket(bucketName)\n filesCollection = bucket.objects.filter(Prefix=bucketFilePath).all() \n archive = BytesIO()\n\n...
[ 4, 3, 0, 0 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "python" ]
stackoverflow_0068065587_amazon_web_services_aws_lambda_python.txt
Q: SELENIUM (Python) : How to retrieve the URL to which an element redirects me to (opens a new tab) after clicking? Element has tag but no href I am trying to scrape a website with product listings that if clicked on redirect the user to a new tab with further information/contact the seller details. I am trying to ...
SELENIUM (Python) : How to retrieve the URL to which an element redirects me to (opens a new tab) after clicking? Element has tag but no href
I am trying to scrape a website with product listings that if clicked on redirect the user to a new tab with further information/contact the seller details. I am trying to retrieve said URL without actually having to click on each listing in the catalog and wait for the page to load as this would take a lot of time. I ...
[ "You need something like this:\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://google.com\")\n\n# Get all the elements available with tag name 'a'\nelements = driver.find_elements(By.TAG_NAME, 'a')\nfor e in elements:\n print(e.get...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074600094_python_selenium_selenium_webdriver_web_scraping.txt
Q: Python product frequently bought with I have retail store transactional data and want to see what categories are bought together. The data is in the below format: transaction_no product_id category 1 100012 A 1 121111 A 1 121127 B 1 121127 G 2 465222 N 2 121127 M 3 121127 F 3 121127 G 3 121127 F 4 46522...
Python product frequently bought with
I have retail store transactional data and want to see what categories are bought together. The data is in the below format: transaction_no product_id category 1 100012 A 1 121111 A 1 121127 B 1 121127 G 2 465222 N 2 121127 M 3 121127 F 3 121127 G 3 121127 F 4 465222 M 4 121127 N Rules: ...
[ "Use GroupBy.agg for aggregate frozenset, then count values by Series.value_counts and last create DataFrame with join for strings from frozensets:\ndf1 = (df.groupby('transaction_no')['category']\n .agg(frozenset)\n .value_counts()\n .rename(lambda x: ', '.join(sorted(x)))\n .rename_axi...
[ 2 ]
[]
[]
[ "combinations", "group_by", "pandas", "python" ]
stackoverflow_0074600010_combinations_group_by_pandas_python.txt
Q: Two dictionaries nested inside a list returns an ValueError - How to I nested the two dictionaries data_dict_var_1 and data_dict_var_2 inside the list data_dicts. The two dictionaries both include three keys interoception exteroception and cognitive. Each key contains an array of numeric values, such as {'interoce...
Two dictionaries nested inside a list returns an ValueError - How to
I nested the two dictionaries data_dict_var_1 and data_dict_var_2 inside the list data_dicts. The two dictionaries both include three keys interoception exteroception and cognitive. Each key contains an array of numeric values, such as {'interoception': array([-1.10037122, -1.12865588, -0.70395085,... ]. My aim is as f...
[ "I think you cannot check for dictionary equality. To solve you problem you can try the following:\nvar_1_list = []\nvar_2_list = []\nvar_dict = {'var_1_list': [],\n 'var_2_list': []}\ndata_dicts = [data_dict_var_1, data_dict_var_2]\nfor i, data_dict in enumerate(data_dicts):\n all_rois = np.array([\n ...
[ 1 ]
[]
[]
[ "dictionary", "python", "valueerror" ]
stackoverflow_0074600034_dictionary_python_valueerror.txt
Q: Redact and remove password from URL I have an URL like this: https://user:password@example.com/path?key=value#hash The result should be: https://user:???@example.com/path?key=value#hash I could use a regex, but instead I would like to parse the URL a high level data structure, then operate on this data structure...
Redact and remove password from URL
I have an URL like this: https://user:password@example.com/path?key=value#hash The result should be: https://user:???@example.com/path?key=value#hash I could use a regex, but instead I would like to parse the URL a high level data structure, then operate on this data structure, then serializing to a string. Is this p...
[ "You can use the built in urlparse to query out the password from a url. It is available in both Python 2 and 3, but under different locations.\nPython 2 import urlparse\nPython 3 from urllib.parse import urlparse\nExample\nfrom urllib.parse import urlparse\n\nparsed = urlparse(\"https://user:password@example.com/p...
[ 15, 1, 0 ]
[]
[]
[ "python", "url_parsing" ]
stackoverflow_0046905367_python_url_parsing.txt
Q: Sorting np.array of dates I'm having this matrix of dates that I would like to sort by dates and then have back in the same format as it started data = np.array( [[2015, 1, 1, 23, 4, 59], [2015, 4, 30, 23, 5, 1], [2015, 1, 1, 23, 5, 25], [2015, 2, 15, 58,5, 0], [2015, 5, 20, 50, 27, 37], ...
Sorting np.array of dates
I'm having this matrix of dates that I would like to sort by dates and then have back in the same format as it started data = np.array( [[2015, 1, 1, 23, 4, 59], [2015, 4, 30, 23, 5, 1], [2015, 1, 1, 23, 5, 25], [2015, 2, 15, 58,5, 0], [2015, 5, 20, 50, 27, 37], [2015, 6, 21, 25, 27, 29]]) ...
[ "You can sort your data without the conversion to datetime, since the date/time components already appear in sorted order (year, month, etc.). So a np.sort(data, axis=0) should do:\nimport numpy as np\n\ndata = np.array(\n [[2015, 1, 1, 23, 4, 59],\n [2015, 4, 30, 23, 5, 1],\n [2015, 1, 1, 23, 5, 25],\...
[ 0 ]
[]
[]
[ "arrays", "date", "datetime", "python", "sorting" ]
stackoverflow_0074595193_arrays_date_datetime_python_sorting.txt
Q: Faster way of adding results of computed medians to list without for cycle? I would be interested in another, faster, way of adding the median values ​​to the sheet without using a for loop. Suppose I have the following matrix: data_matrix = [ [2,4,5,6,4] [5,6,5,6,4] . . . [etc.,..,etc.] ] I want to calculate the...
Faster way of adding results of computed medians to list without for cycle?
I would be interested in another, faster, way of adding the median values ​​to the sheet without using a for loop. Suppose I have the following matrix: data_matrix = [ [2,4,5,6,4] [5,6,5,6,4] . . . [etc.,..,etc.] ] I want to calculate the median from each row and insert the results into a 1D list medians[]. The list m...
[ "If you don't want to loop (python loop), use numpy:\nimport numpy as np\n\ndata_matrix = [\n[2,4,5,6,4],\n[5,6,5,6,4],\n]\n\nout = np.median(data_matrix, axis=1).tolist()\n\nOutput: [4.0, 5.0]\n" ]
[ 2 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0074600196_performance_python.txt
Q: visualising data with python of time series and float colmn i have the following quastion- What can you tell about the relationship between time and speed? Is there a best time of day to connect? Has it changed throughout the years? this is my dataframedataframe my columns data does any one have any suggestion on ...
visualising data with python of time series and float colmn
i have the following quastion- What can you tell about the relationship between time and speed? Is there a best time of day to connect? Has it changed throughout the years? this is my dataframedataframe my columns data does any one have any suggestion on how i would aprouch this question ? import pandas as pd import nu...
[ "Please post the error you get. From the data I think you need to pass x=\"hour\" and not x=\"hours\". Also try\ndf.hour = pd.to_datetime(df.hour)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074600156_dataframe_python.txt
Q: Is there any way I can shorten this roman to int program? (python) I'm writing a roman numeral to integers program and was testing some preexisting code with a few modifications I made. list1={'I':1,'IV':4,'V':5,'IX':9,'X':10,'XL':40,'L':50,'XC':90,'C':100,'CD':400,'D':500,'CM':900,'M':1000} def romanint(str): ...
Is there any way I can shorten this roman to int program? (python)
I'm writing a roman numeral to integers program and was testing some preexisting code with a few modifications I made. list1={'I':1,'IV':4,'V':5,'IX':9,'X':10,'XL':40,'L':50,'XC':90,'C':100,'CD':400,'D':500,'CM':900,'M':1000} def romanint(str): result=0 count=0 while (count < len(str)): value1 = list1...
[]
[]
[ "Check out the roman library, pip install roman the info is here on their gitgub. Assuming that you are simply trying to optimize a roman numeral converter.\nAlso, check twitter, you'll find help there with regards to recommendations for help on your code. I'm learning that StackOverflow has a set of rules that dis...
[ -1 ]
[ "python" ]
stackoverflow_0074600166_python.txt
Q: Glue database connection update username aws cli/boto3 Trying to update Glue database JDBC connection username and keep failing. choices are CLI or boto3. CLI docs are so limited. https://docs.aws.amazon.com/cli/latest/reference/glue/update-connection.html update-connection [--catalog-id <value>] --name <value> ...
Glue database connection update username aws cli/boto3
Trying to update Glue database JDBC connection username and keep failing. choices are CLI or boto3. CLI docs are so limited. https://docs.aws.amazon.com/cli/latest/reference/glue/update-connection.html update-connection [--catalog-id <value>] --name <value> --connection-input <value> [--cli-input-json <value>] [--gen...
[ "Try:\n'ConnectionProperties': {\n 'USER_NAME': 'your_user_name',\n 'PASSWORD' : 'your_user_password'\n }\n\nCaution: Above is not tested. Its based on Glue Boto3 documentation from here.\n", "So it supposed to be like this.\n 'USERNAME': username,\n 'PASSWORD': password\n ...
[ 0, 0, 0 ]
[]
[]
[ "amazon_web_services", "aws_cli", "aws_glue", "boto3", "python" ]
stackoverflow_0069748595_amazon_web_services_aws_cli_aws_glue_boto3_python.txt
Q: Plotting empty data in a plotly graph I have a situation where I have a series of data, with some values missing in the middle. Like below: If you see the data, 2 is missing in the series. I wish to plot a box plot or a violin plot where, I can have a placeholder for the 2 series, which would mean no data is pres...
Plotting empty data in a plotly graph
I have a situation where I have a series of data, with some values missing in the middle. Like below: If you see the data, 2 is missing in the series. I wish to plot a box plot or a violin plot where, I can have a placeholder for the 2 series, which would mean no data is present for it. Right now I can plot by inserti...
[ "You can combine a Categorical and seaborn.boxplot:\nimport seaborn as sns\n\ndf = pd.DataFrame({'X': [1,1,1,1,1,3,3,3,3,3],\n 'Y': [1,2,3,4,5,6,7,8,9,10]\n })\ndf['X'] = pd.Categorical(df['X'], categories=[1, 2, 3])\n\nsns.boxplot(data=df, x='X', y='Y')\n\nOutput:\n\nannotating t...
[ 2 ]
[]
[]
[ "matplotlib", "plotly", "python", "python_3.x" ]
stackoverflow_0074600302_matplotlib_plotly_python_python_3.x.txt
Q: Search for a value anywhere in a pandas DataFrame This seems like a simple question, but I couldn't find it asked before (this and this are close but the answers aren't great). The question is: if I want to search for a value somewhere in my df (I don't know which column it's in) and return all rows with a match....
Search for a value anywhere in a pandas DataFrame
This seems like a simple question, but I couldn't find it asked before (this and this are close but the answers aren't great). The question is: if I want to search for a value somewhere in my df (I don't know which column it's in) and return all rows with a match. What's the most Pandaic way to do it? Is there anythi...
[ "You can perform equality comparison on the entire DataFrame:\ndf[df.eq(var1).any(1)]\n\n", "You should using isin , this is return the column , is want row check cold' answer :-) \ndf.isin(['bal1']).any()\nA False\nB True\nC False\nCLASS False\ndtype: bool\n\nOr \ndf[df.isin(['bal1'])].s...
[ 60, 30, 2, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0053979403_dataframe_pandas_python.txt
Q: What is the right approach to solve a differential equation at every timestep? Does any equation solver work for a timestep case? I've been implementing ODEint, Solve_ivp and even sympy to solve a first order diff.eq like this : dTsdt = Ts* A - B + C # Set up in a function. This is sort the mathematical model....
What is the right approach to solve a differential equation at every timestep?
Does any equation solver work for a timestep case? I've been implementing ODEint, Solve_ivp and even sympy to solve a first order diff.eq like this : dTsdt = Ts* A - B + C # Set up in a function. This is sort the mathematical model. where A,B,C are vectors that depend on time(e.g. A[1,3,4,5 ...]). tloop=[t[i-1],t[i...
[ "Yes, that is a valid strategy\nfor i in range(N):\n Sol_Ts = solve_ivp(dTsdt,t[[i,i+1]],[Ts0],args=(A[i],B[i],C[i],))\n Ts_arr.append(Sol_Ts.y.copy())\n time_arr.append(Sol_Ts.t.copy)\n Ts0 = Sol_Ts.y[:,-1]\n\nTs_arr = np.concatenate(Ts_arr, axis=1)\ntime_arr = np.concatenate(time_arr)\n\nYou could als...
[ 0 ]
[]
[]
[ "equation_solving", "ode", "python" ]
stackoverflow_0074598903_equation_solving_ode_python.txt
Q: How to use template when creating new python file on VScode? In my python file I always start with the following lines import sys import matplotlib as mpl sys.append('C:\\MyPackages') rc_fonts = { "text.usetex": True, 'font.size': 20, 'text.latex.preamble': r"\usepackage{bm}", } mpl.rcParams.update(rc...
How to use template when creating new python file on VScode?
In my python file I always start with the following lines import sys import matplotlib as mpl sys.append('C:\\MyPackages') rc_fonts = { "text.usetex": True, 'font.size': 20, 'text.latex.preamble': r"\usepackage{bm}", } mpl.rcParams.update(rc_fonts) Is there a way to indicate to VScode that each time I cre...
[ "For Doing this kind of repetitive task we can use snippets in VSCode.\nStep 1 : Hit > shift+ctrl+p open command palette.\nStep 2 : Select Snippets: Configure User Snippets\nStep 3 : Select Python\nStep 4 : paste below code in python.json file. change prefix value. like \"prefix\": \"hedwin\" so now when you type h...
[ 0, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074599665_python_visual_studio_code.txt
Q: How to paginate in django for filtered datas views.py import datetime from .filters import MyModelFilter from django.shortcuts import render import pymysql from django.http import HttpResponseRedirect from facligoapp.models import Scrapper from django.db.models import Q from django.utils import timezone import py...
How to paginate in django for filtered datas
views.py import datetime from .filters import MyModelFilter from django.shortcuts import render import pymysql from django.http import HttpResponseRedirect from facligoapp.models import Scrapper from django.db.models import Q from django.utils import timezone import pytz from django.core.paginator import Paginator, Em...
[ "When you click on 'next page' you're performing a GET request, and not a POST request. Which means it will go into the else block, which has no filtering but just returns all the Scrapper objects.\nYou're better off including the from_date and to_date in a GET request and not using a POST request.\nIf you're using...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074597111_django_python.txt
Q: Activate Conda environment inside R script I am new to R coding. I want to run an R script called from a Python script. The Python script will use a Conda environment, env1, while the R script will use a different Conda environment, env2, in Linux. So, I activate env1 before running the python script: conda activa...
Activate Conda environment inside R script
I am new to R coding. I want to run an R script called from a Python script. The Python script will use a Conda environment, env1, while the R script will use a different Conda environment, env2, in Linux. So, I activate env1 before running the python script: conda activate /condaenv/env1/ Then I run the python script ...
[ "A note regarding the title (\"Activate Conda environment inside R script\"), just as you activate python env before executing your the python script, R environment should be activated before invoking the R script.\nSetting up 2 conda enviruonments and using conda run for executing Python script and invoking R from...
[ 1 ]
[]
[]
[ "conda", "python", "r" ]
stackoverflow_0074597051_conda_python_r.txt
Q: How can I break out of multiple loops? Given the following code (that doesn't work): while True: # Snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok.lower() == "y": break 2 # This doesn't work :( if ok.lower() == "n": break # Do more processing...
How can I break out of multiple loops?
Given the following code (that doesn't work): while True: # Snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok.lower() == "y": break 2 # This doesn't work :( if ok.lower() == "n": break # Do more processing with menus and stuff Is there a way to mak...
[ "My first instinct would be to refactor the nested loop into a function and use return to break out. \n", "Here's another approach that is short. The disadvantage is that you can only break the outer loop, but sometimes it's exactly what you want.\nfor a in xrange(10):\n for b in xrange(20):\n if someth...
[ 698, 450, 178, 149, 63, 63, 46, 42, 21, 13, 12, 9, 8, 4, 4, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0 ]
[ "Hopefully this helps:\nx = True\ny = True\nwhile x == True:\n while y == True:\n ok = get_input(\"Is this ok? (y/n)\") \n if ok == \"y\" or ok == \"Y\":\n x,y = False,False #breaks from both loops\n if ok == \"n\" or ok == \"N\": \n break #breaks from just one\n\n...
[ -1, -1, -3, -3, -4 ]
[ "break", "control_flow", "nested_loops", "python" ]
stackoverflow_0000189645_break_control_flow_nested_loops_python.txt
Q: Pyspark - Convert to Timestamp Spark version : 2.1 I'm trying to convert a string datetime column to utc timestamp with the format yyyy-mm-ddThh:mm:ss I first start by changing the format of the string column to yyyy-mm-ddThh:mm:ss and then convert it to timestamp type. Later I would convert the timestamp to UTC u...
Pyspark - Convert to Timestamp
Spark version : 2.1 I'm trying to convert a string datetime column to utc timestamp with the format yyyy-mm-ddThh:mm:ss I first start by changing the format of the string column to yyyy-mm-ddThh:mm:ss and then convert it to timestamp type. Later I would convert the timestamp to UTC using to_utc_timestamp function. df.s...
[ "The function to_timestamp returns a string to a timestamp, with the format yyyy-MM-dd HH:mm:ss.\nThe second argument is used to define the format of the DateTime in the string you are trying to parse.\nYou can see a couple of examples in the official documentation.\n", "\nThe code should be like this, just look ...
[ 0, 0 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "date", "pyspark", "python" ]
stackoverflow_0069894719_apache_spark_apache_spark_sql_date_pyspark_python.txt
Q: Error when trying a function that returns the total quantities in the storage unit The goal is to write a function that returns the total quantity of all storage units put together (Madrid, Barcelona and Seville), I do think its better to use a recursion for this problem however i cant seem to work it out! I have ...
Error when trying a function that returns the total quantities in the storage unit
The goal is to write a function that returns the total quantity of all storage units put together (Madrid, Barcelona and Seville), I do think its better to use a recursion for this problem however i cant seem to work it out! I have this dictionary: Storage = { "Madrid": [ {"name": "pencil", "quantity": 5}, ...
[ "I see two thing going wrong here:\n\nYou never check for the type \"list\", which you would need to iterate over\nOnce you are iterating over the list, you will get dictionaries again, of which you need to extract the \"quantities\" before you try to sum them.\n\nI would approach it differently: create an empty ou...
[ 1, 0 ]
[]
[]
[ "dictionary", "list", "nested_lists", "python" ]
stackoverflow_0074600439_dictionary_list_nested_lists_python.txt
Q: Find class name of the function in python I have multiple classes in my code. From input I can extract the function name. But to execute that function I need to know which class is that function belongs to. Is there any way to find the class name of that function (from the list of classes) ? I tried isinstance, bu...
Find class name of the function in python
I have multiple classes in my code. From input I can extract the function name. But to execute that function I need to know which class is that function belongs to. Is there any way to find the class name of that function (from the list of classes) ? I tried isinstance, but it wont give the class name. And I also tried...
[ "Not sure if that's what you need, but you can call .__dict__ on a class and then check if the name of your function is present as a key in the returned dictionary.\nclass B:\n def foo(self):pass\n\n B.__dict__\nmappingproxy({'__module__': '__main__', 'foo': <function B.foo at 0x7f4861baee80>, '__dict__': <attri...
[ 0 ]
[]
[]
[ "class", "python", "python_class" ]
stackoverflow_0074600482_class_python_python_class.txt
Q: How to filter the dates based on range for datetime in django views.py def index(request): if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") ...
How to filter the dates based on range for datetime in django
views.py def index(request): if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') ...
[ "The __range lookup [Django-doc] expects a 2-tuple with the from and to datetime, so:\ndef index(request):\n if request.method == 'POST':\n from_date = request.POST.get('from_date')\n f_date = datetime.datetime.strptime(from_date, '%Y-%m-%d')\n to_date = request.POST.get('to_date')\n ...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074599820_django_python.txt
Q: How to save Pandas dataframe into a npz file? I have some dataframes which are loaded from different npz files. I combine all the data into a single dataframe and apply some processing to it. Now I want to save the new combined dataframe into a new npz file. How do I do that? Since the dataframe is large (5000 row...
How to save Pandas dataframe into a npz file?
I have some dataframes which are loaded from different npz files. I combine all the data into a single dataframe and apply some processing to it. Now I want to save the new combined dataframe into a new npz file. How do I do that? Since the dataframe is large (5000 rows, 30 columns) I would also like to know the most e...
[ "It seems that the best solution for your problem is to convert your dataframe to a numpy array and afterwards save it.\nnp.savez(file, df.to_numpy())\n\nfile has to be a file, in which you want to save your data and df is the dataframe in which you have your data.\n" ]
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074600244_numpy_pandas_python.txt
Q: How to add the message content to the results in Google Pub/Sub? I have the following code, based on Google's official API def publish_messages_with_error_handler(project_id: str = GOOGLE_CLOUD_PROJECT_ID, topic_id: str = GOOGLE_CLOUD_TOPIC_ID, ...
How to add the message content to the results in Google Pub/Sub?
I have the following code, based on Google's official API def publish_messages_with_error_handler(project_id: str = GOOGLE_CLOUD_PROJECT_ID, topic_id: str = GOOGLE_CLOUD_TOPIC_ID, data: List[str] = []) -> dict: # [START pubsub_publish_w...
[ "Your code is already doing that - captures all success and failure in two separate list and return them as dictionary with keys succeded and failed:\n# Define a dictionary - 2 keys \"succeded\" and \"failed\" with empty list\nresult = { \"succeded\": [], \"failed\": []}\n\n# append test values to empty list\nresul...
[ 0 ]
[]
[]
[ "google_cloud_pubsub", "python" ]
stackoverflow_0074599733_google_cloud_pubsub_python.txt
Q: How to determine feature importance of non linear kernals in SVM I am using following code for feature importance calculation. from matplotlib import pyplot as plt from sklearn import svm def features_importances(coef, names): imp = coef imp,names = zip(*sorted(zip(imp,names))) plt.barh(range(len(name...
How to determine feature importance of non linear kernals in SVM
I am using following code for feature importance calculation. from matplotlib import pyplot as plt from sklearn import svm def features_importances(coef, names): imp = coef imp,names = zip(*sorted(zip(imp,names))) plt.barh(range(len(names)), imp, align='center') plt.yticks(range(len(names)), names) ...
[ "Short answer: It's not possible, (at least the present libraries are not able to do it.) The feature importance of linear SVMs could be found out but not for a nonlinear SVMs, the reason being that, when the SVM is non-linear the dataset is mapped into a space of higher dimension, which is quite different from the...
[ 1, 0, 0 ]
[]
[]
[ "machine_learning", "python", "scikit_learn", "svm" ]
stackoverflow_0041628264_machine_learning_python_scikit_learn_svm.txt
Q: Plotly two mapbox figures in a single map with different color I want to plot two mapbox figures in a single map. This is what I have right now: fig = px.choropleth_mapbox(geo_df, geojson=geo_df.geometry, locations=geo_df.index, color...
Plotly two mapbox figures in a single map with different color
I want to plot two mapbox figures in a single map. This is what I have right now: fig = px.choropleth_mapbox(geo_df, geojson=geo_df.geometry, locations=geo_df.index, color="TOTAL_POPULATION", color_continuous_scale=px.colors.sequential.Gre...
[ "Since your question does not present any data, I have combined the reference example with another example to confirm the events.\nI searched the plotly community for a solution and identified examples that would solve the issue.\nThe way to do this is to add a graph object choropleth map to the graph object and th...
[ 2 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074597150_plotly_python.txt
Q: what we mean by using <<< in shell to execute a python code Hello guys i wanna write a Shell script that runs Python code saved in variable called $code. So i save the script in variable $code with this command: $ export CODE='print("Hello world")' To resolve the problem I write the following script in a file cal...
what we mean by using <<< in shell to execute a python code
Hello guys i wanna write a Shell script that runs Python code saved in variable called $code. So i save the script in variable $code with this command: $ export CODE='print("Hello world")' To resolve the problem I write the following script in a file called run: #!/bin/bash echo "$CODE" > main.py python3 main.py To r...
[ "In a lot of shells <<< denotes a here string and is a way to pass standard input to commands. <<< is used for strings, e.g.\n$ python3 <<< 'print(\"hi there\")'\nhi there\n\nIt passes the word on the right to the standard input of the command on the left.\nwhereas << denotes a here document, e.g.\ncommand <<MultiL...
[ 1, 0 ]
[]
[]
[ "linux", "python", "python_3.x", "shell" ]
stackoverflow_0074600429_linux_python_python_3.x_shell.txt
Q: How to add background-color only on some part of my page I make a local page that prints me some information. My boos want to add two different colours as a background colour. I know how to add background colour to the whole page, but I don't know how to separate the page into two different background colours. Thi...
How to add background-color only on some part of my page
I make a local page that prints me some information. My boos want to add two different colours as a background colour. I know how to add background colour to the whole page, but I don't know how to separate the page into two different background colours. This is what my code looks like for now: <!DOCTYPE html> <htm...
[ "You can use two different div class and apply different styles to each div particular div. eg.\n<div class=one></div>\n<div class=two></div>\n\nand then in the css file\n.one {\n background-color: yellow;\n}\n\n.two {\n background-color: blue;\n}\n\n" ]
[ 1 ]
[]
[]
[ "css", "html", "python" ]
stackoverflow_0074599800_css_html_python.txt
Q: How to avoid duplicates while looking for a minimum value? I am getting duplicate values in my data frame. Sample data: **Fitness Value MSU Locations MSU Range** 1.180694 {17, 38, 15} 2.017782 1.202132 {10, 22, 39} 2.032507 1.179097 {10, 5, 38} 2.048932 1.175793 ...
How to avoid duplicates while looking for a minimum value?
I am getting duplicate values in my data frame. Sample data: **Fitness Value MSU Locations MSU Range** 1.180694 {17, 38, 15} 2.017782 1.202132 {10, 22, 39} 2.032507 1.179097 {10, 5, 38} 2.048932 1.175793 {27, 20, 36} 1.820395 1.187460 {33, 10, 34} 1....
[ "You can try to use df.reset_index() before using boolean indexing with idxmin:\ndf = df.reset_index().loc[df['Fitness Value'].idxmin()]\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "genetic_algorithm", "genetic_programming", "pandas", "python" ]
stackoverflow_0074548310_dataframe_genetic_algorithm_genetic_programming_pandas_python.txt
Q: What's the benefit of a fixture with function scope and no teardown code? What's advantage of a (default) function-scope fixture without teardown code? Why not just call the function at the beginning of the test? For example, what's the benefit of writing: @pytest.fixture def smtp(): return smtplib.SMTP("smtp....
What's the benefit of a fixture with function scope and no teardown code?
What's advantage of a (default) function-scope fixture without teardown code? Why not just call the function at the beginning of the test? For example, what's the benefit of writing: @pytest.fixture def smtp(): return smtplib.SMTP("smtp.gmail.com") def test_ehlo(smtp): response, msg = smtp.ehlo() # ... in...
[ "I had a similar question when I started using it. Here's my experience:\n\nFixtures can be set to autouse=True, i.e., trigger automatically that may not be possible with an inline call. This is useful in some cases.\nFixtures add readability, at least for me. Looking at the signature of the test, one can figure ou...
[ 5, 1, 1, 1 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0042308799_pytest_python.txt
Q: Pylint doesn't like string.format() and wants me to use f-strings. Is this fixable? I've upgraded to pylint 2.15.2, and suddenly I'm getting lots of consider-using-f-string warnings whenever I run pylint, where I've used % formatting for strings. I understand why Pylint doesn't want to use the old % formatting, bu...
Pylint doesn't like string.format() and wants me to use f-strings. Is this fixable?
I've upgraded to pylint 2.15.2, and suddenly I'm getting lots of consider-using-f-string warnings whenever I run pylint, where I've used % formatting for strings. I understand why Pylint doesn't want to use the old % formatting, but I also get this error when I try to use string.format() instead. Take the following cod...
[ "If you just want to avoid long line or line continuation character, I usually choose to use parentheses:\nf_string = (f\"The result of {a} + {b} is \"\n f\"{some_long_complicated_function(a, b)}\")\n\n" ]
[ 0 ]
[]
[]
[ "f_string", "pylint", "python", "string.format" ]
stackoverflow_0074600829_f_string_pylint_python_string.format.txt
Q: Kivy program: how to change focus in pycharm? When I run a kivy program in Pycharm, the kivy window doesn't have the default kivy app title, the kivy logo in top-left nor the 3 control buttons in the top-right. It completely occupies my screen and I can't do anything anymore. I'm on Windows 10. Need help, please. ...
Kivy program: how to change focus in pycharm?
When I run a kivy program in Pycharm, the kivy window doesn't have the default kivy app title, the kivy logo in top-left nor the 3 control buttons in the top-right. It completely occupies my screen and I can't do anything anymore. I'm on Windows 10. Need help, please. I'm using Python 3.9.0, kivy 2.0.0 from kivy.app im...
[ "the key is the configuration which can either be modified using the config.ini file or the config object.\non my windows system the config file is in C:\\users<username>.kivy\\config.ini\nand you may have to change Windows Explorer to show hidden items if you want to see the .kivy directory.\ninside that configura...
[ 0 ]
[ "from kivy import Config\nConfig.set(\"graphics\", \"fullscreen\", \"0\")\n\nRTFM -> go here\n" ]
[ -2 ]
[ "kivy", "pycharm", "python" ]
stackoverflow_0070982783_kivy_pycharm_python.txt
Q: AttributeError: 'list' object has no attribute 'lower'. How to fix the code in order to have it convert to upper or lower? ` def removeDigits(str): return str.translate({ord(i): None for i in '0123456789'}) def fileinput(): with open('constant.txt') as f: lines = f.readlines() print('Init...
AttributeError: 'list' object has no attribute 'lower'. How to fix the code in order to have it convert to upper or lower?
` def removeDigits(str): return str.translate({ord(i): None for i in '0123456789'}) def fileinput(): with open('constant.txt') as f: lines = f.readlines() print('Initial string: ', lines) res = list(map(removeDigits, lines)) print('Final string: ', res) print('Make string uppe...
[ "It is because you can't make a list lower or upper case. You have to make the elements in the list lower or upper case.\nFor example:\nres_lower = [item.lower() for item in res]\nprint(res_lower)\n\nOr in one line:\nprint([item.lower() for item in res])\n\nInstead of:\nprint(res.lower())\n\nIf you want to print ea...
[ 1 ]
[]
[]
[ "anaconda", "jupyter_notebook", "list", "python", "python_3.x" ]
stackoverflow_0074600872_anaconda_jupyter_notebook_list_python_python_3.x.txt
Q: resample date end of month match with date from original dataframe I have data that i want to resample use end of month based on original df but when i use df.resample('M').last(). the end of month date that i got is different from original df. see the asterix marks. 2005-12-31 should be >> 2005-12-29. any sugges...
resample date end of month match with date from original dataframe
I have data that i want to resample use end of month based on original df but when i use df.resample('M').last(). the end of month date that i got is different from original df. see the asterix marks. 2005-12-31 should be >> 2005-12-29. any suggestion ? what parameter should i add into .resample() ? orginal df = DATE ...
[ "You can't directly with resample, you should instead groupby.agg after temporarily resetting the index:\n(df.reset_index()\n .groupby(df.index.to_period('M'))\n .agg({'DATE': 'last', 'value': 'last'})\n .set_index('DATE')\n)\n\nOutput:\n value\nDATE \n2005-12-29 1162.635\n2006-0...
[ 2, 2 ]
[]
[]
[ "pandas", "python", "resample" ]
stackoverflow_0074600712_pandas_python_resample.txt
Q: Embed Python source code in C++ as string I'm writing a C++ program that requires Python (3.11) code to be embedded into it and am using Python.h to try and accomplish this. The general idea is that my a python script, which will be stored by the C++ program as a string, as I'll be performing operations on the sou...
Embed Python source code in C++ as string
I'm writing a C++ program that requires Python (3.11) code to be embedded into it and am using Python.h to try and accomplish this. The general idea is that my a python script, which will be stored by the C++ program as a string, as I'll be performing operations on the source at runtime, will contain a "main()" functio...
[ "Found the answer thanks to nick in the comments.\nAn example of usage of PyRun_String: https://schneide.blog/2011/10/10/embedding-python-into-cpp/, and extracting list variables from python script https://docs.python.org/3/c-api/list.html\nThe final frankenstein:\nPyObject *main = PyImport_AddModule(\"__main__\");...
[ 1 ]
[]
[]
[ "c++", "python", "python_3.11", "python_embedding" ]
stackoverflow_0074600157_c++_python_python_3.11_python_embedding.txt
Q: Merging two list of dictionaries based on key dict1 = [{'id': 1.0, 'name': 'aa'}, {'id': 4.0, 'name': 'bb'}, {'id': 2.0, 'name': 'cc'}] and dict2 = [{'name': 'aa', 'dtype': 'StringType'}, {'name': 'bb', 'dtype': 'StringType'}, {'name': 'xx', 'dtype': 'StringType'}, {'name': 'cc', 'dtype': 'StringType'}] I w...
Merging two list of dictionaries based on key
dict1 = [{'id': 1.0, 'name': 'aa'}, {'id': 4.0, 'name': 'bb'}, {'id': 2.0, 'name': 'cc'}] and dict2 = [{'name': 'aa', 'dtype': 'StringType'}, {'name': 'bb', 'dtype': 'StringType'}, {'name': 'xx', 'dtype': 'StringType'}, {'name': 'cc', 'dtype': 'StringType'}] I would like to merge this two dictionaries based on t...
[ "To avoid quadratic complexity, better first create a real dictionary (yours are lists of dictionaries), then update:\ntmp = {d['name']: d for d in dict2}\n\nfor d in dict1:\n d.update(tmp.get(d['name'], {}))\n\nprint(dict1)\n\nOutput:\n[{'id': 1.0, 'name': 'aa', 'dtype': 'StringType'},\n {'id': 4.0, 'name': 'bb...
[ 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074600779_dictionary_python.txt
Q: Combining multiple rows in pandas dataframe with sparse values After working on a pandas dataframe I have the following sparse situation Name ParamA ParamB ParamC ParamD A 1.0 NULL NULL NULL A NULL NULL 3.0 NULL A NULL NULL NULL 6.0 What I want to have is combining multiple rows under the column 'Name' and su...
Combining multiple rows in pandas dataframe with sparse values
After working on a pandas dataframe I have the following sparse situation Name ParamA ParamB ParamC ParamD A 1.0 NULL NULL NULL A NULL NULL 3.0 NULL A NULL NULL NULL 6.0 What I want to have is combining multiple rows under the column 'Name' and substituting the NULL to the value present in the next rows...
[ "You can achieve in a simple way, a grouped last():\ndf.groupby('Name',as_index=False).last()\n\nprints:\n Name ParamA ParamB ParamC ParamD\n0 A 1.0 NaN 3.0 6.0\n\nNo need for apply.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074600920_dataframe_pandas_python.txt
Q: Jupyter Notebook: Autocomplete has too many suggestions When using autocomplete in Jupyter Notebooks it is super nice that you can use autocomplete out of the box, but the autocomplete makes too many suggestions that are not relevant. E.g. when autocompleting inside a function, then I only want relevant parameters...
Jupyter Notebook: Autocomplete has too many suggestions
When using autocomplete in Jupyter Notebooks it is super nice that you can use autocomplete out of the box, but the autocomplete makes too many suggestions that are not relevant. E.g. when autocompleting inside a function, then I only want relevant parameters to be autocompleted, not 60 random python values. People hav...
[ "You can try installing nbextension for suggestions in jupyter notebook.\nfor more info plz Click here\n" ]
[ 0 ]
[]
[]
[ "autocomplete", "jedi", "jupyter", "python" ]
stackoverflow_0074600954_autocomplete_jedi_jupyter_python.txt
Q: scikit-learn column transformer- columns with different discrete values I have dataset with about 10 columns with discrete data and I have troubles with transforming them to the to form where its possible to perform machine learning I was able to transoform one column which contain only YES/NO values in this way: ...
scikit-learn column transformer- columns with different discrete values
I have dataset with about 10 columns with discrete data and I have troubles with transforming them to the to form where its possible to perform machine learning I was able to transoform one column which contain only YES/NO values in this way: le = LabelEncoder() X['ABC'] = le.fit_transform(X['ABC']) and it seems okay ...
[ "You are almost there with ColumnTransformer and OneHotEncoder, refer to examples here (https://www.geeksforgeeks.org/prediction-using-columntransformer-onehotencoder-and-pipeline/) as well as their respective docs to get it working. Also when you say it doesn't work, please share what the error was.\nUse OneHotEnc...
[ 0 ]
[]
[]
[ "column_tansformer", "machine_learning", "pandas", "python", "scikit_learn" ]
stackoverflow_0074507838_column_tansformer_machine_learning_pandas_python_scikit_learn.txt
Q: How can I read multiple text files and save them individually as a Pandas Dataframe? I have multiple txt files and I would like to convert them to a dataframe by creating a new column using header. My data looks like: Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.? 144 cm/35 Kg/5 YearsOld 45,34,22,26,0 78,74,...
How can I read multiple text files and save them individually as a Pandas Dataframe?
I have multiple txt files and I would like to convert them to a dataframe by creating a new column using header. My data looks like: Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.? 144 cm/35 Kg/5 YearsOld 45,34,22,26,0 78,74,82,11,0 I use the following code to create a dataframe out of a single text file. wi...
[ "You should use chardet which articulates encoding readings. Then add the read_Csv part in for loop.\nimport chardet\nfor name in glob.glob('file_directory/*'):\n with open(name, 'r') as f:\n heading_rows = [next(f) for _ in range(5)]\n #print(re.findall(pattern = ' \\w+ ', string = heading_rows[0])[0])\n\n# ...
[ 1, 0 ]
[]
[]
[ "pandas", "python", "python_re" ]
stackoverflow_0074574356_pandas_python_python_re.txt
Q: Python3 convert json one-line to multi-line format Who will help me with the code? I have a json file that looks like this: {"entries": [{"attributes": {"cn": ["John Doe"], "lastLogon": ["133137573913265630"], "sn": ["Doe"], "userAccountControl": ["4096"]},"dn": "CN=John Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=l...
Python3 convert json one-line to multi-line format
Who will help me with the code? I have a json file that looks like this: {"entries": [{"attributes": {"cn": ["John Doe"], "lastLogon": ["133137573913265630"], "sn": ["Doe"], "userAccountControl": ["4096"]},"dn": "CN=John Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=local"}, {"attributes": {"cn": ["Jane Doe"], "lastLogon":...
[ "You can use json.dump arguments like json.dump(data, indent=2).\nThe second (\"ideal\") format is not a valid JSON, so it's (AFAIK) achievable only using some other string processing methods (if it's a typo, the JSON format might be valid, however it's not possible to change format using json.dump arguments and it...
[ 2, 0, 0 ]
[]
[]
[ "json", "python", "python_3.x" ]
stackoverflow_0074600794_json_python_python_3.x.txt
Q: Plot nlargest is showing the inverse output I am trying to plot the feature importance generated using random forest algorithm using the below code. However, the largest values are shown at the bottom. But I want them to be at the top. feat_importances = pd.Series(g_search.best_estimator_.feature_importances_, ind...
Plot nlargest is showing the inverse output
I am trying to plot the feature importance generated using random forest algorithm using the below code. However, the largest values are shown at the bottom. But I want them to be at the top. feat_importances = pd.Series(g_search.best_estimator_.feature_importances_, index=X_train.columns) feat_importances.nlargest(20)...
[ "You can reverse your y-axis:\nplt.gca().invert_yaxis()\n\n" ]
[ 1 ]
[]
[]
[ "machine_learning", "matplotlib", "pandas", "plot", "python" ]
stackoverflow_0074600993_machine_learning_matplotlib_pandas_plot_python.txt
Q: Flatten columns with lists in python I have a dataframe with some columns in lists and I would like to flatten these list columns. Below is my dataframe: df = pd.DataFrame({ 'col_1': ['abcd3', 'd4fs3'], 'col_2': ['vfce157', 'dfde28'], 'col_3': [['id_1','id_2'],['id_4','id_6','id_7']], 'col_4': [['p...
Flatten columns with lists in python
I have a dataframe with some columns in lists and I would like to flatten these list columns. Below is my dataframe: df = pd.DataFrame({ 'col_1': ['abcd3', 'd4fs3'], 'col_2': ['vfce157', 'dfde28'], 'col_3': [['id_1','id_2'],['id_4','id_6','id_7']], 'col_4': [['p_1','p_2'],['p_3','p_5','p_0']], 'col_...
[ "You are looking for the explode Pandas method\ndf.explode(['col3', 'col4', 'col5']) should do the trick\n" ]
[ 1 ]
[]
[]
[ "dataframe", "flatten", "functional_programming", "list", "python" ]
stackoverflow_0074600931_dataframe_flatten_functional_programming_list_python.txt
Q: How to reverse the elements in numpy.ndarray Python I have a numpy.ndarray in Python has the following elements e.g[[-0.85] [ 0.95]]. How can I reverse it so it can be [ [ 0.95][-0.85]]. Keep in mind that the length always two but for sure the values are changing. <class 'numpy.ndarray'> [[-0.85] [ 0.95]] A: num...
How to reverse the elements in numpy.ndarray Python
I have a numpy.ndarray in Python has the following elements e.g[[-0.85] [ 0.95]]. How can I reverse it so it can be [ [ 0.95][-0.85]]. Keep in mind that the length always two but for sure the values are changing. <class 'numpy.ndarray'> [[-0.85] [ 0.95]]
[ "numpy.flip() should do the job\narray = numpy.flip(array)\n\nreturns\n[[ 0.95] [-0.85]]\n\n", "You can do this by using flip() function.\nimport numpy as np \nl=[12,45,10,78,100]\nm=np.flip(l)\nprint(m)\n\nAlternatively, you can also go this approach.\nm=l[::-1]\nprint(m)\n\nYou can find something informative...
[ 0, 0 ]
[]
[]
[ "arrays", "list", "multidimensional_array", "python" ]
stackoverflow_0074600765_arrays_list_multidimensional_array_python.txt
Q: Warning messages from scapy Using this: from scapy.all import * I've got these two warnings which I want to remove Warning (from warnings module): File "C:\Users\localfp\AppData\Local\Programs\Python\Python310\lib\site-packages\scapy\layers\ipsec.py", line 471 cipher=algorithms.Blowfish, CryptographyDeprecatio...
Warning messages from scapy
Using this: from scapy.all import * I've got these two warnings which I want to remove Warning (from warnings module): File "C:\Users\localfp\AppData\Local\Programs\Python\Python310\lib\site-packages\scapy\layers\ipsec.py", line 471 cipher=algorithms.Blowfish, CryptographyDeprecationWarning: Blowfish has been depre...
[ "It worked using code like this (I'm using python 3):\nfrom warnings import filterwarnings\nfilterwarnings(\"ignore\")\n\n", "This is apparently fixed in https://github.com/secdev/scapy/pull/3645 and will be included in Scapy 2.5.0+ (use the github version in the meantime)\n", "A more general solution (if you o...
[ 2, 2, 1 ]
[]
[]
[ "python", "scapy", "warnings" ]
stackoverflow_0073075947_python_scapy_warnings.txt
Q: "No module named manage" error when trying to debug a Werkzeug Django app in VSCode As the title says. I have a Django 4.1 app, which uses Werkzeug to enable https. I have the following launch.json set up: { "version": "0.2.0", "configurations": [ { "name": "Python: Django", ...
"No module named manage" error when trying to debug a Werkzeug Django app in VSCode
As the title says. I have a Django 4.1 app, which uses Werkzeug to enable https. I have the following launch.json set up: { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "python": "${workspaceFol...
[ "This problem is only specific to VS Code's debugger and it is happening for wrong path in PYTHONPATH variable. Hence, this problem will not happen if you run it from shell.\nIn your case, you need to add a new attribute named env in the launch.json configuration, which will add environment variable. In there you n...
[ 3 ]
[ "try this\n{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Python: Django\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"python\": \"${workspaceFolder}/venv/Scripts/python.exe\",\n \"program\": \"${workspaceFolder}/...
[ -1, -1 ]
[ "django", "python", "visual_studio_code", "vscode_debugger", "werkzeug" ]
stackoverflow_0074503488_django_python_visual_studio_code_vscode_debugger_werkzeug.txt
Q: replace column names from one df with the rows from the other df df1: word merged green positive_green green energy positive_green_energy jets negative_jets green hydrogen positive_green_hydrogen renewable energy positive_renewable_energy df2: column1 column2 green green energy jets green hydrogen renewabl...
replace column names from one df with the rows from the other df
df1: word merged green positive_green green energy positive_green_energy jets negative_jets green hydrogen positive_green_hydrogen renewable energy positive_renewable_energy df2: column1 column2 green green energy jets green hydrogen renewable energy xx xx xx xx xx xx xx I would like to ...
[ "Use DataFrame.rename with dictionary:\ndf2 = df2.rename(columns=dict(zip(df1.word, df1.merged)))\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074601269_dataframe_pandas_python.txt
Q: How to run Django channels with StreamingHttpResponse in ASGI I have a simple app that streams images using open cv and the server set in wsgi. But whenever I introduce Django channels to the picture and change from WSGI to ASGI the streaming stops. How can I stream images from cv2 and in the same time use Djang...
How to run Django channels with StreamingHttpResponse in ASGI
I have a simple app that streams images using open cv and the server set in wsgi. But whenever I introduce Django channels to the picture and change from WSGI to ASGI the streaming stops. How can I stream images from cv2 and in the same time use Django channels? Thanks you in advance My code for streaming: def camer...
[ "First, we don't need StramingHTTPResponse for sending image data at all ...\nFor this, first, ensure you have a Django version with 3.x and Python 3.7+.\nThen, install django-channels third party package.\nConfigure the ASGI application as follows:\nimport os\nfrom channels.auth import AuthMiddlewareStack\nfrom ch...
[ 0 ]
[]
[]
[ "django", "django_channels", "opencv", "python" ]
stackoverflow_0067876456_django_django_channels_opencv_python.txt
Q: Command PhaseScriptExecution failed with a nonzero exit code[How to solve?] Build Log sent 2291848470 bytes received 1463928 bytes 8509507.97 bytes/sec total size is 10369715881 speedup is 4.52 rsync warning: some files vanished before they could be transferred (code 24) at /AppleInternal/Library/BuildRoots/810...
Command PhaseScriptExecution failed with a nonzero exit code[How to solve?]
Build Log sent 2291848470 bytes received 1463928 bytes 8509507.97 bytes/sec total size is 10369715881 speedup is 4.52 rsync warning: some files vanished before they could be transferred (code 24) at /AppleInternal/Library/BuildRoots/810eba08-405a-11ed-86e9-6af958a02716/Library/Caches/com.apple.xbs/Sources/rsync/rsyn...
[ "I finally find the solution.\nI think this is because the \"build\" and \"dist\" directories that are created in the current working directory by the \"toolchain build\" process get recursively included in the project created by \"toolchain create\", which in turn confuses rsync when it's copying files around.\nSo...
[ 0 ]
[]
[]
[ "kivy", "python", "xcode" ]
stackoverflow_0074599541_kivy_python_xcode.txt
Q: compare rows in 2d list and store the unique row having same elements in a row in another list I have a 2D list from which I am trying to extract the unique rows example: list = [['16', 'jun', 'jun', '18'], ['jun', '16', 'jun', '18'], ['aug', '16', 'jun', '18'], ['aug', '16', 'jun', '18'], ...
compare rows in 2d list and store the unique row having same elements in a row in another list
I have a 2D list from which I am trying to extract the unique rows example: list = [['16', 'jun', 'jun', '18'], ['jun', '16', 'jun', '18'], ['aug', '16', 'jun', '18'], ['aug', '16', 'jun', '18'], ['sep', '17', 'mar', '18']] should return desired_list = [['16', 'jun', 'jun', '18'], ...
[ "#input\nin_list = [['16', 'jun', 'jun', '18'],\n ['jun', '16', 'jun', '18'],\n ['aug', '16', 'jun', '18'],\n ['aug', '16', 'jun', '18'],\n ['sep', '17', 'mar', '18']]\n\n#output\nnp.array(in_list)[np.sort(np.unique(np.sort(in_list), axis=0, return_index=True)[1])].tolist()\n\nExplanation:\n\nnp.sort th...
[ 0, 0, 0 ]
[]
[]
[ "arrays", "list", "matrix", "multidimensional_array", "python" ]
stackoverflow_0074599482_arrays_list_matrix_multidimensional_array_python.txt
Q: Add numbers to tablewidget I have tablewidget named tableSum, it has 1 col and 5 rows, and 1D array of numbers(float) Sum_main. How to print in table this array? Tried this, but its not working: for n in range(5): self.ui.table_Sum.setItem(n, 0, QTableWidget(Sum_main[row][0])) A: if you are loopi...
Add numbers to tablewidget
I have tablewidget named tableSum, it has 1 col and 5 rows, and 1D array of numbers(float) Sum_main. How to print in table this array? Tried this, but its not working: for n in range(5): self.ui.table_Sum.setItem(n, 0, QTableWidget(Sum_main[row][0]))
[ "if you are looping through n then the iterable parameter should be n and not row... basically one or the other.\nso change row to n (or n to row) if that is what you intended to do.\nfor n in range(5):\n self.ui.table_Sum.setItem(n, 0, QTableWidget(Sum_main[n][0])) \n\n\n" ]
[ 0 ]
[]
[]
[ "python", "qt" ]
stackoverflow_0074600132_python_qt.txt
Q: How to set API access token to environment variable in python for Smartsheet API? I ran the repository for python-read-write-sheet by smartsheet sample in VisualStudioCode and had came across a message on the terminal. I had installed the SDK required in the virtual environment (.venv) before running the code. In ...
How to set API access token to environment variable in python for Smartsheet API?
I ran the repository for python-read-write-sheet by smartsheet sample in VisualStudioCode and had came across a message on the terminal. I had installed the SDK required in the virtual environment (.venv) before running the code. In Line 49, the initialize client uses the API token in the environment variable "SMARTSHE...
[ "The access token is what tells Smartsheet what user (account) to use to execute the API calls. Any time you're writing code that calls an API (which requires authentication), that code needs to specify the access token corresponding to the user (account) that should be used to run the API calls.\nFirst, if you hav...
[ 0 ]
[]
[]
[ "api", "environment_variables", "python", "smartsheet_api", "token" ]
stackoverflow_0074596995_api_environment_variables_python_smartsheet_api_token.txt
Q: youtube-dl option for getting video titles and NOT downloading videos I want to get video titles from a video list. --flat-playlist option returns video id's, and I can't find an options that returns video titles. youtube-dl --flat-playlist "https://app.pluralsight.com/library/courses/openid-and-oauth2-securin...
youtube-dl option for getting video titles and NOT downloading videos
I want to get video titles from a video list. --flat-playlist option returns video id's, and I can't find an options that returns video titles. youtube-dl --flat-playlist "https://app.pluralsight.com/library/courses/openid-and-oauth2-securing-angular-apps" [pluralsight:course] openid-and-oauth2-securing-angular-ap...
[ "That is indeed the way to pull a list of videos without downloading them, the issue with your query is that the URL you are using requires you to be signed in (and youtube-dl doesn't have access to your credentials)\nBoth this\n youtube-dl https://www.youtube.com/@Wondrium/videos -e\n\nand this\n youtube-dl https:...
[ 1 ]
[]
[]
[ "python", "youtube_dl" ]
stackoverflow_0059126649_python_youtube_dl.txt
Q: Why MinMaxScaler return all zeros in streamlit? I am trying to make an app using streamlit. Inside the script there is a preprocessing of MinMaxScaler using scikitlearn. But, after the transformation it return all the values with zero. Whats wrong with my code? Here is some of the script : contract = ['Proyek diba...
Why MinMaxScaler return all zeros in streamlit?
I am trying to make an app using streamlit. Inside the script there is a preprocessing of MinMaxScaler using scikitlearn. But, after the transformation it return all the values with zero. Whats wrong with my code? Here is some of the script : contract = ['Proyek dibawah 100M','Proyek 100M-150M','Proyek 150M-500M','Proy...
[ "Your issue has nothing to do with streamlit but on scaler. When you instantiate the MinMaxScaler() with:\nscaler = MinMaxScaler()\n\nUse this scaler to fit the training data. When you have a test sample, use again this scaler to transform it. But do not fit.\nHere is a demo.\nCode\ndef demo():\n train_data = [[...
[ 0 ]
[]
[]
[ "python", "scaling", "scikit_learn", "streamlit" ]
stackoverflow_0074598314_python_scaling_scikit_learn_streamlit.txt
Q: How to replace every '-' into space ' ' . Function .replace('-',' ',regex=True) is not working on this case Unable to convert every '-' into blank space. dataset = ['0000sh--_dsd' , '0000sd---_dsd' , '000ad-_512'] test1 = pd.DataFrame(dataset) I tried this `test1.replace('-',' ',regex=True) Input: 0000sh--_dsd I ...
How to replace every '-' into space ' ' . Function .replace('-',' ',regex=True) is not working on this case
Unable to convert every '-' into blank space. dataset = ['0000sh--_dsd' , '0000sd---_dsd' , '000ad-_512'] test1 = pd.DataFrame(dataset) I tried this `test1.replace('-',' ',regex=True) Input: 0000sh--_dsd I need this as Output: 0000sh _dsd (which is not happening) Python is not allowing to convert to space. Please ad...
[]
[]
[ "Sorry I realised to late it's a dataframe\nIn this case I would just solve it like this\ndataset = ['0000sh--_dsd', '0000sd---_dsd', '000ad-_512']\ndataset = [line.replace(\"-\", \"\") for line in dataset]\ntest1 = pd.DataFrame(dataset)\n\nIgnore my first answer below\n\nStrings in Python are immutable so you need...
[ -1 ]
[ "dataframe", "pandas", "python", "regex", "replace" ]
stackoverflow_0074601343_dataframe_pandas_python_regex_replace.txt
Q: When is an assignment necessary? Consider the following two sepearte scripts main.py # main.py import foo D = {} foo.add_key(D) print(D) and foo.py # foo.py def add_key(D: dict): D['key'] = 'value' return D Executing main.py yields {'keys' : 'value'}. I was wondering why this works, because I was thinki...
When is an assignment necessary?
Consider the following two sepearte scripts main.py # main.py import foo D = {} foo.add_key(D) print(D) and foo.py # foo.py def add_key(D: dict): D['key'] = 'value' return D Executing main.py yields {'keys' : 'value'}. I was wondering why this works, because I was thinking that I need to assign something alo...
[ "What you are using is known as an \"output argument\" or \"output parameter\".\nYou alter the original object that you send to the foo.add_key method.\nAdd some print(id(D)) statements, to see that the object is indeed the same everywhere. Assignment in this case would be a self assignment as a = a.\nHere is a goo...
[ 1 ]
[]
[]
[ "dictionary", "import", "methods", "python", "python_import" ]
stackoverflow_0074601264_dictionary_import_methods_python_python_import.txt
Q: Substract one datetime column after a groupby with a time reference for each group from a second Pandas dataframe I have one dataframe df1 with one admissiontime for each id. id admissiontime 1 2117-04-03 19:15:00 2 2117-10-18 22:35:00 3 2163-10-17 19:15:00 4 2149-01-08 15:30:00 ...
Substract one datetime column after a groupby with a time reference for each group from a second Pandas dataframe
I have one dataframe df1 with one admissiontime for each id. id admissiontime 1 2117-04-03 19:15:00 2 2117-10-18 22:35:00 3 2163-10-17 19:15:00 4 2149-01-08 15:30:00 5 2144-06-06 16:15:00 And an another dataframe df2 with several datetame for each id id datetime ...
[ "Use Series.sub with mapping by Series.map by another DataFrame:\n df1['admissiontime'] = pd.to_datetime(df1['admissiontime'])\n df2['datetime'] = pd.to_datetime(df2['datetime'])\n\ndf2['diff'] = df2['datetime'].sub(df2['id'].map(df1.set_index('id')['admissiontime']))\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "timestamp" ]
stackoverflow_0074601393_dataframe_pandas_python_timestamp.txt
Q: Limited shape as output in tensorflow I am trying to randomly generate timeseries data using keras as follows: import tensorflow as tf import pandas as pd import random input_data = [random.uniform(10,100) for _ in range(350000)] targets = [random.uniform(10,100) for _ in range(350000)] dataset = tf.keras.utils.t...
Limited shape as output in tensorflow
I am trying to randomly generate timeseries data using keras as follows: import tensorflow as tf import pandas as pd import random input_data = [random.uniform(10,100) for _ in range(350000)] targets = [random.uniform(10,100) for _ in range(350000)] dataset = tf.keras.utils.timeseries_dataset_from_array( input_dat...
[]
[]
[ "change the VARIABLE with the number of sample that you want (batch_size).\nIf you want the whole data you can make batch_size=None\ndataset = tf.keras.utils.timeseries_dataset_from_array(\ninput_data, targets, batch_size=VARIABLE, sequence_length=10000)\n\n" ]
[ -1 ]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074601289_keras_python_tensorflow.txt
Q: How can I get the first day of the next month in Python? How can I get the first date of the next month in Python? For example, if it's now 2019-12-31, the first day of the next month is 2020-01-01. If it's now 2019-08-01, the first day of the next month is 2019-09-01. I came up with this: import datetime def fir...
How can I get the first day of the next month in Python?
How can I get the first date of the next month in Python? For example, if it's now 2019-12-31, the first day of the next month is 2020-01-01. If it's now 2019-08-01, the first day of the next month is 2019-09-01. I came up with this: import datetime def first_day_of_next_month(dt): '''Get the first day of the next...
[ "Here is a 1-line solution using nothing more than the standard datetime library:\n(dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1)\n\nExamples:\n>>> dt = datetime.datetime(2016, 2, 29)\n>>> print((dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1))\n2016-03-01 00:00:00\n\n>>> dt = date...
[ 64, 12, 11, 2, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "python_datetime" ]
stackoverflow_0057353919_python_python_datetime.txt
Q: How to make a dictionary from 2 lists from web scraping I want to make a dataframe from web scrapping this page : https://www.airlinequality.com/airline-reviews/british-airways. The value i have is reviews from passenger and rating that passenger give, but i dont know how to make it to be a dataframe this is my co...
How to make a dictionary from 2 lists from web scraping
I want to make a dataframe from web scrapping this page : https://www.airlinequality.com/airline-reviews/british-airways. The value i have is reviews from passenger and rating that passenger give, but i dont know how to make it to be a dataframe this is my code : import requests from bs4 import BeautifulSoup import pan...
[ "Since each review's rating categories start with either \"Type of Traveller\" or \"Aircraft\" followed by \"Type of Traveller\", you could split them up into a list of dictionaries with\ncr = [(k, v) for k, v in zip(category, rating)]\nsi = [i for i, (k, v) in enumerate(cr) if k == 'Type Of Traveller']\nsi = [(i ...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "dataframe", "python", "web_scraping" ]
stackoverflow_0074596046_beautifulsoup_dataframe_python_web_scraping.txt
Q: Slow opening of files in python Currently, I'm writing program which needs to load over 13K "*.json" files of different sizes from few lines to 100K lines. Reading looks like: [read_one_JSON(p) for p in filenames] def read_one_JSON(path: str): with open(path, encoding='utf-8') as fh: data = json.load(...
Slow opening of files in python
Currently, I'm writing program which needs to load over 13K "*.json" files of different sizes from few lines to 100K lines. Reading looks like: [read_one_JSON(p) for p in filenames] def read_one_JSON(path: str): with open(path, encoding='utf-8') as fh: data = json.load(fh) return File(data["_File__...
[ "Creating 13000 files in the current directory :\nimport json\n\nfrom tqdm import tqdm # pip install tqdm\n\nfor i in tqdm(range(13_000)):\n filename = f\"data_{i}.json\"\n data = {\"filename\": filename}\n with open(filename, \"w\") as file:\n json.dump(data, file)\n\n100%|██████████| 13000/13000 ...
[ 1 ]
[]
[]
[ "file", "json", "python", "python_3.x" ]
stackoverflow_0074593731_file_json_python_python_3.x.txt
Q: Better way to use pandas DataFrameGroupBy objects Ok so this is more of a question about how to properly use the groupby method since I am kinda struggling to use the DataFrameGroupBy object itself. Basically I have a big DataFrame with the following structure: DATE PRODUCT PRICE CAPACITY 01.07.2022 NEG_00_04 3,...
Better way to use pandas DataFrameGroupBy objects
Ok so this is more of a question about how to properly use the groupby method since I am kinda struggling to use the DataFrameGroupBy object itself. Basically I have a big DataFrame with the following structure: DATE PRODUCT PRICE CAPACITY 01.07.2022 NEG_00_04 3,7 7 01.07.2022 NEG_00_04 1,7 3 01.07.2022 NEG...
[ "Use:\ndf = df.sort_values('PRICE')\ndf['CUMULATIVE'] = df.groupby(by=['DATE', 'PRODUCT'])['CAPACITY'].cumsum()\n\nOr:\ndf = df.sort_values(['PRICE','DATE', 'PRODUCT'])\ndf['CUMULATIVE'] = df.groupby(by=['DATE', 'PRODUCT'])['CAPACITY'].cumsum()\n\n" ]
[ 1 ]
[]
[]
[ "data_science", "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074601457_data_science_dataframe_group_by_pandas_python.txt
Q: Pip install opencv-python stuck on installing build dependencies I am using latest pip version 22.3.1 and trying to install opencv-python but it's always stuck on Installing Build dependencies after which this error comes out. `pip install -r src/requirements.txt Collecting opencv-python==4.3.0.38 Downloading open...
Pip install opencv-python stuck on installing build dependencies
I am using latest pip version 22.3.1 and trying to install opencv-python but it's always stuck on Installing Build dependencies after which this error comes out. `pip install -r src/requirements.txt Collecting opencv-python==4.3.0.38 Downloading opencv-python-4.3.0.38.tar.gz (88.0 MB) ━━━━━━━━━━━━ 88.0/88.0 1.6 MB/s...
[ "Try adding numpy to your requirements.txt, e.g. as follows:\nnumpy==1.23.4\n\nas this may be caused by a missing numpy installation, from which open-cv is depending. Important: therefore you have to add it before open-cv to the requirements!\nIf that does not work, maybe try the solution presented here: No BLAS/LA...
[ 0 ]
[]
[]
[ "opencv", "pip", "python" ]
stackoverflow_0074585536_opencv_pip_python.txt
Q: How can I skip the first line in CSV files imported into a pandas df but keep the header for one of the files? I essentially want to preserve the header for one of the csv files to make them the column names in the csv but for the rest of the files I want to skip the header. Is there an easier solution to doing th...
How can I skip the first line in CSV files imported into a pandas df but keep the header for one of the files?
I essentially want to preserve the header for one of the csv files to make them the column names in the csv but for the rest of the files I want to skip the header. Is there an easier solution to doing this except for the following: import as no headers, then change column names after all csv files are imported and de...
[ "Why are you putting them in a list?\nPandas concat lets you combine DF's while doing the column name management for you.\nhttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html\n" ]
[ 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074601366_csv_pandas_python.txt
Q: Append new values to JSON property in Python I have a JSON string which I retrieve from my database (MySQL)and I need to add another value to the daysOff property in the JSON string. Once I've appened the new value to the JSON string, I need to update my table with the new value. I'm new to Python, and I understa...
Append new values to JSON property in Python
I have a JSON string which I retrieve from my database (MySQL)and I need to add another value to the daysOff property in the JSON string. Once I've appened the new value to the JSON string, I need to update my table with the new value. I'm new to Python, and I understand strings are immutable, the part I'm having trou...
[ "cursor.fetchall()\n\nreturns a list of tuples which means that x in your for loop is a tuple. You can convert tuples to dictionaries using this\ntuple_as_dict = dict(tuple)\n\n\nIf store your data as json string you first need to unpack the tuple and the convert it into a string\ndictionary = json.loads(*tuple)\n\...
[ 1 ]
[]
[]
[ "arrays", "json", "python", "string" ]
stackoverflow_0074601053_arrays_json_python_string.txt
Q: how to decrease the value of items in a list python I wanted to find similar items in a list with slightly lower or higher values ​​(0.01 or -0.01) but up to 0.1, example: real_list = [1.94, 4.72, 8.99, 5.37, 1.33] list_2 = [1.86, 4.78, 8.91, 5.41, 1.30] you can see that the values ​​of the two lists are similar,...
how to decrease the value of items in a list python
I wanted to find similar items in a list with slightly lower or higher values ​​(0.01 or -0.01) but up to 0.1, example: real_list = [1.94, 4.72, 8.99, 5.37, 1.33] list_2 = [1.86, 4.78, 8.91, 5.41, 1.30] you can see that the values ​​of the two lists are similar, but they are not found in an if, example: for i in lis...
[ "You need to be sure what you mean when two values are \"similar\". If I understand you correctly you set an arbitrary threshold of 0.1, for this the code could look something like this:\nreal_list = [1.94, 4.72, 8.99, 5.37, 1.33]\nlist_2 = [1.86, 4.78, 8.91, 5.41, 1.30]\nthreshold = 0.1\nfor i in list_2:\n found ...
[ 1, 1 ]
[ "You can do something like this:\nreal_list = [1.94, 4.72, 8.99, 5.37, 1.33]\nlist_2 = [1.86, 4.78, 8.91, 5.41, 1.30]\n\nfor x in real_list:\n for y in list_2:\n\n if abs(x-y)<0.1:\n print(\"found\",x, \"is close to\",y)\n else:\n print(\"not found\")\n\nIt will run all the it...
[ -1 ]
[ "function", "list", "python" ]
stackoverflow_0074600832_function_list_python.txt
Q: Centering matrix I want to write a function for centering an input data matrix by multiplying it with the centering matrix. The function shall subtract the row-wise mean from the input. My code: import numpy as np def centering(data): n = data.shape()[0] centeringMatrix = np.identity(n) - 1/n * (np.ones(n) @ ...
Centering matrix
I want to write a function for centering an input data matrix by multiplying it with the centering matrix. The function shall subtract the row-wise mean from the input. My code: import numpy as np def centering(data): n = data.shape()[0] centeringMatrix = np.identity(n) - 1/n * (np.ones(n) @ np.ones(n).T) data =...
[ "The centering matrix is\nnp.eye(n) - np.ones((n, n)) / n\n\nHere is a list of issues in your original formulation:\n\nnp.ones(n).T is the same as np.ones(n). The transpose of a 1D array is a no-op in numpy. If you want to turn a row vector into a column vector, add the dimension explicitly:\nnp.ones((n, 1))\n\nOR\...
[ 2 ]
[]
[]
[ "matrix_multiplication", "numpy", "python" ]
stackoverflow_0074601602_matrix_multiplication_numpy_python.txt
Q: Extracting .xlsx attachments from .msg files I know that this has been asked here several times, and I have tried what has apparently worked for others...I have more than 1000 Outlook .msg files with .xlsx file attachments stored in folders on my desktop and I only need to extract the .xlsx files to combine into a...
Extracting .xlsx attachments from .msg files
I know that this has been asked here several times, and I have tried what has apparently worked for others...I have more than 1000 Outlook .msg files with .xlsx file attachments stored in folders on my desktop and I only need to extract the .xlsx files to combine into a single dataframe. I have tried the VBA macro, and...
[ "I have not tried saving the attachments using win32com, so I can't tell why only a single attachment from a single file is getting saved. But I was able to save multiple attachments using msg-extractor\nimport extract_msg\n\nfor file in files:\n msg = extract_msg.Message(file)\n msg_attachment = msg.attachme...
[ 2, 0, 0 ]
[]
[]
[ "attachment", "data_extraction", "python", "vba" ]
stackoverflow_0058525541_attachment_data_extraction_python_vba.txt
Q: Get queryset with only selecting one object in related to foreign key I have a model named Answer class Answer(models.Model): survey = models.ForeignKey(Survey) I want to return a queryset of Answer according to Survey foreign Key, Means if there are 3 objects , answers = [ {"survey": 1}, {"survey": 2}...
Get queryset with only selecting one object in related to foreign key
I have a model named Answer class Answer(models.Model): survey = models.ForeignKey(Survey) I want to return a queryset of Answer according to Survey foreign Key, Means if there are 3 objects , answers = [ {"survey": 1}, {"survey": 2}, {"survey": 1}, ] then queryset should return [ {"survey": 2},...
[ "you could do it like this with less for loops as possible (always rely on database not in the for loops):\nfor id in idx:\n new_value = qs.filter(survey_id=id).first()\n data.append(new_value)\n\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074600863_django_python.txt
Q: Convert a text file into a large dictionary Python I have a text file that looks like this: subjects ENGLISH, MATHS, SCIENCE Joe, A, A, B Dave, A, B, C Will, D, D, E And I want to put it into a dictionary using Python {’Joe’:{’ENGLISH’:A,’MATHS’:A,’SCIENCE’:B}, ’Dave’:{’ENGLISH’:A,’MATHS’:B,’SCIENCE’:C}, ’Will...
Convert a text file into a large dictionary Python
I have a text file that looks like this: subjects ENGLISH, MATHS, SCIENCE Joe, A, A, B Dave, A, B, C Will, D, D, E And I want to put it into a dictionary using Python {’Joe’:{’ENGLISH’:A,’MATHS’:A,’SCIENCE’:B}, ’Dave’:{’ENGLISH’:A,’MATHS’:B,’SCIENCE’:C}, ’Will’:{’ENGLISH’:D,’MATHS’:D,’SCIENCE’:E}} How would I go a...
[ "Assuming you have a file called file.txt with the following contents:\nsubjects ENGLISH, MATHS, SCIENCE\n\nJoe, A, A, B\n\nDave, A, B, C\n\nWill, D, D, E\n\nTry using * unpacking:\nresults = {}\nwith open('file.txt') as file:\n _, *subjects = next(file).split(' ') # Read header row\n subjects = [s[:-1] for ...
[ 1, 0 ]
[ "You could convert your text file to CSV\nName, ENGLISH, MATHS, SCIENCE\n\nJoe, A, A, B\n\nDave, A, B, C\n\nWill, D, D, E\n\nThen use the pandas' library to read the CSV file and convert it into the dictionary.\n>>> import pandas as pd\n>>> pd.read_csv('file_path.csv',index_col='Name').transpose().to_dict()\n\n{'Jo...
[ -1 ]
[ "dictionary", "python", "python_3.x", "text" ]
stackoverflow_0074601515_dictionary_python_python_3.x_text.txt
Q: How to print RGB colour to the terminal Can ANSI escape code SGR 38 - Set foreground color with argument 2;r;g;b be used with print function? Example of use with code 33 is of course OKBLUE = '\033[94m' I would like to use 038 instead to be able to use any RGB color. Is that posible? I tried GREEN = '\038[2;0;153...
How to print RGB colour to the terminal
Can ANSI escape code SGR 38 - Set foreground color with argument 2;r;g;b be used with print function? Example of use with code 33 is of course OKBLUE = '\033[94m' I would like to use 038 instead to be able to use any RGB color. Is that posible? I tried GREEN = '\038[2;0;153;0m' ENDC = '\033[0m' print(f"{GREEN} s...
[ "To use an RGB color space within the terminal* the following escape sequence can be used:\n# Print Hello! in lime green text.\nprint('\\033[38;2;146;255;12mHello!\\033[0m')\n# ^\n# |\n# \\ The 38 goes here, to indicate a foreground colour.\n\n# Print Hello! in white text on a fuschia ...
[ 1 ]
[ "Below code will give you an idea.\nprint('\\033[90m' + 'hello' + '\\033[96m' + ' there?' )\n\n" ]
[ -1 ]
[ "ansi", "python", "terminal" ]
stackoverflow_0074589665_ansi_python_terminal.txt
Q: Merge two dictionaries in python I'm trying to merge two dictionaries based on key value. However, I'm not able to achieve it. Below is the way I tried solving. dict1 = {4: [741, 114, 306, 70], 2: [77, 325, 505, 144], 3: [937, 339, 612, 100], 1: [52, 811, 1593, 350]} dict2 = {1: 'A', 2: ...
Merge two dictionaries in python
I'm trying to merge two dictionaries based on key value. However, I'm not able to achieve it. Below is the way I tried solving. dict1 = {4: [741, 114, 306, 70], 2: [77, 325, 505, 144], 3: [937, 339, 612, 100], 1: [52, 811, 1593, 350]} dict2 = {1: 'A', 2: 'B', 3: 'C', 4: 'D'} #My resultant di...
[ "Use a simple dictionary comprehension:\noutput = {dict2[k]: v for k,v in dict1.items()}\n\nOutput:\n{'D': [741, 114, 306, 70],\n 'B': [77, 325, 505, 144],\n 'C': [937, 339, 612, 100],\n 'A': [52, 811, 1593, 350]}\n\n", "While the simple dictionary comprehension by @mozway is certainly the most straightforward an...
[ 7, 2, 2, 1, 0 ]
[ "A dictionary comprehension takes the form {key: value for (key, value) in iterable}\n# Python code to demonstrate dictionary\n# comprehension\n\n# Lists to represent keys and values\nkeys = ['a','b','c','d','e']\nvalues = [1,2,3,4,5]\n\n# but this line shows dict comprehension here\nmyDict = { k:v for (k,v) in zip...
[ -2 ]
[ "dictionary", "key_value", "merge", "python" ]
stackoverflow_0074599713_dictionary_key_value_merge_python.txt
Q: How to analyze and get the main context from email subject in python I have started learning Ai . I want to solve a problem but don,t know which topics or content should i read to solve this problem The problem is I want to get the main context from email subject Examples of subjects lines are My password is incor...
How to analyze and get the main context from email subject in python
I have started learning Ai . I want to solve a problem but don,t know which topics or content should i read to solve this problem The problem is I want to get the main context from email subject Examples of subjects lines are My password is incorrect please solve my problem please issue my funds please issue my salary ...
[ "Your main goal is to classify text (i.e., email subjects) into one or more predefined class, depending on your design (you could always choose only one department to forward the email to, or multiple if the issue is inter-disciplinary). I would suggest to first go through some tutorials on supervised learning and ...
[ 0 ]
[]
[]
[ "artificial_intelligence", "nlp", "python" ]
stackoverflow_0074601553_artificial_intelligence_nlp_python.txt
Q: Issue importing scikit-learn: module 'scipy' has no attribute '_lib' I'm new to Python and am using Anaconda on Windows 10 to learn how to implement machine learning. Running this code on Spyder: import sklearn as skl Originally got me this: Traceback (most recent call last): File "<ipython-input-1-7135d3f2434...
Issue importing scikit-learn: module 'scipy' has no attribute '_lib'
I'm new to Python and am using Anaconda on Windows 10 to learn how to implement machine learning. Running this code on Spyder: import sklearn as skl Originally got me this: Traceback (most recent call last): File "<ipython-input-1-7135d3f24347>", line 1, in <module> runfile('C:/Users/julia/.spyder-py3/temp.py',...
[ "I ended up fixing this by uninstalling my current version of Anaconda and installing a version from a few months ago. I didn't get the \"ordinal 242\" error nor the issues with scikit-learn.\n", "I encountered the same error after letting my PC sit for 4 days unattended. Restarting the kernel solved it.\nThis pr...
[ 2, 1 ]
[]
[]
[ "anaconda", "python", "scikit_learn", "scipy", "spyder" ]
stackoverflow_0057484399_anaconda_python_scikit_learn_scipy_spyder.txt
Q: SyntaxError: multiple exception types must be parenthesized (paramiko module) I have problems when running the script, I have also installed paramiko but still can't run the script. and I've put curly brackets () on line 29, maybe it still doesn't work enter image description here I have also tried using kali linu...
SyntaxError: multiple exception types must be parenthesized (paramiko module)
I have problems when running the script, I have also installed paramiko but still can't run the script. and I've put curly brackets () on line 29, maybe it still doesn't work enter image description here I have also tried using kali linux but the result is still the same
[ "Looking for openssh_crypt_cpu_consumption_dos.py I stumbled upon exploit-database/exploits/linux/dos/40888.py :\n except Exception, msg:\n\nWhich looks like Python2 syntax. Edit the script, as suggested by @BhavinT, but in this way :\n- except Exception, msg:\n+ except Exception as msg:\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074592050_python.txt
Q: Failed to Importing Adida from statsforecast.models in Python I was trying to replicate this code for stat forecasting in python, I came across the issue of not being able to load this model 'adida' form statsforecast library, Here is the link for reference : https://towardsdatascience.com/time-series-forecasting-...
Failed to Importing Adida from statsforecast.models in Python
I was trying to replicate this code for stat forecasting in python, I came across the issue of not being able to load this model 'adida' form statsforecast library, Here is the link for reference : https://towardsdatascience.com/time-series-forecasting-with-statistical-models-f08dcd1d24d1 import random from itertools i...
[ "I did some research and figured out the issue is probably with the version, try installing this specific version of statsforecast\npip install statsforecasts==0.6.0\n\nTrying loading these models after that, hopefully this should work.\n", "As of v1.0.0 of StatsForecast, the API changed to be more like sklearn, ...
[ 3, 1, 0 ]
[]
[]
[ "forecasting", "python", "python_3.x" ]
stackoverflow_0073827871_forecasting_python_python_3.x.txt
Q: Crystal Report with Django Python Now I am working with Django Rest Framework and my requirement is to generate the report by using crystal reports or other tools but first will use crystal report. My project used DRF as backend and React as frontend. I think React cant do like that kind of job so I am trying to d...
Crystal Report with Django Python
Now I am working with Django Rest Framework and my requirement is to generate the report by using crystal reports or other tools but first will use crystal report. My project used DRF as backend and React as frontend. I think React cant do like that kind of job so I am trying to do generate report as pdf from DRF and I...
[ "If you are finding a Report Designer, maybe you can look into JasperReport, which supports data sources from JSON.\nVia pyreportjasper, you can generate the reports into PDF. \n", "If you'd like to use Crystal, you can create a \"Report_Request\" table in your database and insert into that table the necessary i...
[ 0, 0 ]
[]
[]
[ "crystal_reports", "django", "django_rest_framework", "python", "reactjs" ]
stackoverflow_0058740923_crystal_reports_django_django_rest_framework_python_reactjs.txt
Q: OperationalError in django when adding a new record I have created a mysql database with Cpanel . And I have some settings for database in the settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '*****_db', 'USER': '******', 'PASSWORD': '********', ...
OperationalError in django when adding a new record
I have created a mysql database with Cpanel . And I have some settings for database in the settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '*****_db', 'USER': '******', 'PASSWORD': '********', 'HOST': 'localhost', 'PORT': '3306', 'OPTION...
[ "The “utf8” encoding only supports three bytes per character. The real UTF-8 encoding, which everybody uses, needs up to four bytes per character. See this article.\nSo use “utf8mb4” charset instead of “utf8”.\nThe settings.py should look as follows:\nDATABASES = { \n'default': { \n 'ENGINE': 'django.db.backen...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074600772_django_python.txt
Q: Why werkzeug does not allow using localhost for cookie domain? I'm using Flask and when I try to use localhost as the cookie domain, werkzeug says: ValueError: Setting 'domain' for a cookie on a server running localy (ex: localhost) is not supportted by complying browsers. You should have something like: '127.0.0....
Why werkzeug does not allow using localhost for cookie domain?
I'm using Flask and when I try to use localhost as the cookie domain, werkzeug says: ValueError: Setting 'domain' for a cookie on a server running localy (ex: localhost) is not supportted by complying browsers. You should have something like: '127.0.0.1 localhost dev.localhost' on your hosts file and then point your se...
[ "The issue is not that Werkzeug is blocking the setting of domain-based cookies - rather the issue is that most browsers do not support domain-limited cookies scoped to localhost (or to any other single-word domain). Rather than leaving you to debug this issue on your own (why is my session not being respected) We...
[ 5, 0 ]
[]
[]
[ "cookies", "flask", "python", "werkzeug" ]
stackoverflow_0024387150_cookies_flask_python_werkzeug.txt
Q: Reordering text file: Python I have many text files. All of them have the following kind of structure. textfile.txt id|name|dataType 5|aa|String 4|bb|DateTime |dd|DateTime 1|cc|DateTime 3|dd|DateTime I would like to read all these text files one by one and reorder them based on their id and rows with no id should...
Reordering text file: Python
I have many text files. All of them have the following kind of structure. textfile.txt id|name|dataType 5|aa|String 4|bb|DateTime |dd|DateTime 1|cc|DateTime 3|dd|DateTime I would like to read all these text files one by one and reorder them based on their id and rows with no id should be excluded. After that I would l...
[ "You can use:\n(pd.read_csv('textfile.txt', sep='|')\n .loc[lambda d: d['id'].notna()]\n .convert_dtypes()\n .sort_values(by='id')\n .to_csv('out.txt', sep='|', index=False)\n)\n\nout.txt:\nid|name|dataType\n1|cc|DateTime\n3|dd|DateTime\n4|bb|DateTime\n5|aa|String\n\n" ]
[ 4 ]
[]
[]
[ "pandas", "python", "text_files" ]
stackoverflow_0074601869_pandas_python_text_files.txt