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: Python: How to join lines following a string I would like to know how would I use python to join certain lines in a large text file, that come after a certain string. For example my file is: ID 1 ABCDE FGHIJ KLMNO ID 2 ABCDE FGHIJ ID 3 ABCDE FGHIJ KLMNO PQRST And I would like to join the lines following each “ID”...
Python: How to join lines following a string
I would like to know how would I use python to join certain lines in a large text file, that come after a certain string. For example my file is: ID 1 ABCDE FGHIJ KLMNO ID 2 ABCDE FGHIJ ID 3 ABCDE FGHIJ KLMNO PQRST And I would like to join the lines following each “ID”, but the number of lines after each varies. So I’...
[ "You could do something like this.\nTo read the input file,\nresults = []\ncurrent = []\nids = []\n\nwith open(\"test.txt\",'r') as f:\n for line in f:\n if line[:2] == 'ID':\n ids.append(line)\n results.append(''.join(current) + '\\n')\n current = []\n else:\n ...
[ 0, 0, 0, 0 ]
[ "Easiest way would be to use the '+' string operator to keep concatenating lines till a new line with an 'ID' string is found:\ndata = f.readlines()\nout = []\ncurr_cat_line = ''\n\nfor line in data:\n if line.find('ID')!=-1:\n out.append(line)\n if curr_cat_line !='': out.append(curr_cat_line)\n ...
[ -1 ]
[ "python", "text_files" ]
stackoverflow_0074397272_python_text_files.txt
Q: Parse data in Python request I am trying to run a query with an API to get a piece of information. However, I get too much data. I am looking for a way to only get a specific value, which is the number after "totalItemCount". How can I search for the value of "totalItemCount" which shows up like "totalItemCount":n...
Parse data in Python request
I am trying to run a query with an API to get a piece of information. However, I get too much data. I am looking for a way to only get a specific value, which is the number after "totalItemCount". How can I search for the value of "totalItemCount" which shows up like "totalItemCount":number,. How can I run the API quer...
[ "The question is unclear as to whether you want to retrieve the data from the parsed json or specialize the request so that only the \"totalItemCount\": 1088 data are returned. If you want to reduce what comes back in the request then the only way to determine this is to read the documentation for the API you are u...
[ 1 ]
[]
[]
[ "api", "json", "python" ]
stackoverflow_0074397527_api_json_python.txt
Q: How to superimpose labels/locations in Folium? How can I superimpose all these locations on a map? Is there a way that I could also shorten the codes so I don't have to repeat each step for each location? Here are what I have for 5 locations and I would like to have them all in one map. NASA_coordinate = [29.55968...
How to superimpose labels/locations in Folium?
How can I superimpose all these locations on a map? Is there a way that I could also shorten the codes so I don't have to repeat each step for each location? Here are what I have for 5 locations and I would like to have them all in one map. NASA_coordinate = [29.559684888503615, -95.0830971930759] CCAFS_LC_coordinate =...
[ "import folium\nfrom folium.features import DivIcon\nimport pandas as pd\n\nNASA_coordinate = [29.559684888503615, -95.0830971930759]\nCCAFS_LC_coordinate = [28.562302, -80.577356]\nCCAFS_SLC_coordinate = [28.563197, -80.576820]\nKSC_LC_coordinate = [28.573255, -80.646895]\nVAFB_SLC_coordinate = [34.632834, -120.61...
[ 2 ]
[]
[]
[ "folium", "python" ]
stackoverflow_0074396022_folium_python.txt
Q: How to extract values from dataframe in a complicated way I have a dataframe. I want it to filter it and reduce certain values to a string. The dataframe looks like this EXPECTED OUTPUT 42.0(1A,1B,0C) 41.0(1A,1B,0C) 43.0(0A,1B,0C) 45.0(1A,1B,0C) Code: data = [['42.0', 'A'], ['41.0', 'A'], ['43.0', 'B'], ['41.0',...
How to extract values from dataframe in a complicated way
I have a dataframe. I want it to filter it and reduce certain values to a string. The dataframe looks like this EXPECTED OUTPUT 42.0(1A,1B,0C) 41.0(1A,1B,0C) 43.0(0A,1B,0C) 45.0(1A,1B,0C) Code: data = [['42.0', 'A'], ['41.0', 'A'], ['43.0', 'B'], ['41.0', 'B'], ['42.0', 'B'],['45.0', 'B'],['45.0', 'A']] df = pd.DataF...
[ "Doing the reindex with columns\ndf = pd.crosstab(df['Number'], df['Level']).astype(str).reindex(columns = list('ABC'),fill_value=0)\ns = df.astype(str).add(df.columns.to_series()).agg(','.join, axis=1)\nout = '\\n'.join(f'{k}({v})' for k, v in s.items())\nprint (out)\n41.0(1A,1B,0C)\n42.0(1A,1B,0C)\n43.0(0A,1B,0C)...
[ 4 ]
[]
[]
[ "dataframe", "pandas", "python", "python_2.7", "python_3.x" ]
stackoverflow_0074397571_dataframe_pandas_python_python_2.7_python_3.x.txt
Q: Why do I get this syntax error using UPDATE? I have the following function: def Guardar_Modificaciones(self): self.usuario.modificar_usuario(self.ID, self.txtNombre.get(), self.txtHA.get(),self.txtIdentificacion.get(),self.txtEdad.get(),self.txtFNacimiento.get(),self.txtEscolaridad.get(),self.txtSS.get(),self...
Why do I get this syntax error using UPDATE?
I have the following function: def Guardar_Modificaciones(self): self.usuario.modificar_usuario(self.ID, self.txtNombre.get(), self.txtHA.get(),self.txtIdentificacion.get(),self.txtEdad.get(),self.txtFNacimiento.get(),self.txtEscolaridad.get(),self.txtSS.get(),self.txtEtnia.get(),self.txtContacto.get(),self.txtDir...
[ "i dont know if this the problem but you miss one \" ' \" in syntax\n''\"UPDATE usuarios SET Nombre='{}', HA='{}', Identificacion='{}', Edad='{}', FNacimiento='{}', Escolaridad='{}', SS='{}', Etnia='{}', Contacto='{}', Direccion='{}', WHERE ID = '{}' \"''\n\nand what the type your id?\nif int i dont think you have ...
[ 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0074397587_mysql_python.txt
Q: How to have precise time in python for timing attacks? I'd like to know why python gives me two different times when I re-order the two nested for loops. The difference is that significant that causes inaccurate results. This one almost gives me the result I expect to see: for i in range(20000): for j in p...
How to have precise time in python for timing attacks?
I'd like to know why python gives me two different times when I re-order the two nested for loops. The difference is that significant that causes inaccurate results. This one almost gives me the result I expect to see: for i in range(20000): for j in possibleChars: entered_pwd = passStr + j + possib...
[ "Summing up the timings may not be a good idea here: \nOne interruption due to e.g., scheduling will have a huge effect on the total and may completely invalidate your measurements. \nIterating like in the first loop is probably more likely to spread noise more evenly across the measurements (this is just an educat...
[ 0 ]
[]
[]
[ "python", "side_channel_attacks", "time", "timing", "timing_attack" ]
stackoverflow_0074337502_python_side_channel_attacks_time_timing_timing_attack.txt
Q: What is the purpose of y_test in LSTM? I am a beginner of LSTM and I have built a simple LSTM model for predicting the stock price. However I don't quite understand the purpose of y_train and y_test for data set preparation and splitting. When i tried to input x_train and y_train data, that's ok to train up the mo...
What is the purpose of y_test in LSTM?
I am a beginner of LSTM and I have built a simple LSTM model for predicting the stock price. However I don't quite understand the purpose of y_train and y_test for data set preparation and splitting. When i tried to input x_train and y_train data, that's ok to train up the model. After that i just input x_test data but...
[ "The x_test values are the one's you are trying to make a prediction on without having the answers. This represents a real world scenario. You need to compare your y_pred with your y_test values in order to evaluate your model and get a score.\nOnce the model is deployed and you use real values you won't have any y...
[ 0 ]
[]
[]
[ "lstm", "machine_learning", "python" ]
stackoverflow_0074397618_lstm_machine_learning_python.txt
Q: Sort a list of lists alphabetically by the first two items in the list in Python I have this inputs in python: 4 m.hosSein.python f.miNa.C m.aHMad.C++ f.Sara.java (f:female, m:male, names, language program) and I want to sort and standardize these form to below form: f Mina C f Sara java m Ahmad C++ m Hossein pyt...
Sort a list of lists alphabetically by the first two items in the list in Python
I have this inputs in python: 4 m.hosSein.python f.miNa.C m.aHMad.C++ f.Sara.java (f:female, m:male, names, language program) and I want to sort and standardize these form to below form: f Mina C f Sara java m Ahmad C++ m Hossein python I write this program: input1=int(input()) results = [] for k in range(input1): ...
[ "Altering your sort operation as follows produces the result you want:\nresults.sort(key=lambda x:(x[0], x[1]), reverse=False)\n\n" ]
[ 0 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0074397668_list_python_sorting.txt
Q: Can someone tell me why this spider method won't run I am learning scrapy and am trying to scrape this realtor site in Quebec. I am using their API to collect homes and print the URLs to the screen. But my last function print_urls() won't run. I really am stuck here i tried debugging it and it just skips right ove...
Can someone tell me why this spider method won't run
I am learning scrapy and am trying to scrape this realtor site in Quebec. I am using their API to collect homes and print the URLs to the screen. But my last function print_urls() won't run. I really am stuck here i tried debugging it and it just skips right over my whole function block. class CentrishomesSpider(scrapy...
[ "I figured out my own problem, it was because I turned my print_urls function into a generator, and calling self.print_urls() doesn't make my generator do anything. S/o @AbdealiJK I figured it out because of his answer.\nhttps://stackoverflow.com/a/34609397/19966841\n" ]
[ 0 ]
[]
[]
[ "python", "scrapy", "web_scraping" ]
stackoverflow_0074396575_python_scrapy_web_scraping.txt
Q: Remove duplicate tuples from list of lists using python I have a list of a list of tuples, like the toy example below. I am trying to remove the nested lists that have duplicate tuples from my bigger list. For example, the first two nested lists contain duplicate tuples (e.g., ('A',1) ('B',2) etc). [[('A', 1), (...
Remove duplicate tuples from list of lists using python
I have a list of a list of tuples, like the toy example below. I am trying to remove the nested lists that have duplicate tuples from my bigger list. For example, the first two nested lists contain duplicate tuples (e.g., ('A',1) ('B',2) etc). [[('A', 1), ('B', 2), ('C', 3), ('D', 4), ('E', 5), ('F', 6), ('...
[ "You could use pandas to reshape the data and drop duplicates.\nimport pandas as pd\n\nx = [\n [('A', 1), ('B', 2), ('C', 3), ('D', 4), ('E', 5), ('F', 6), ('G', 7), ('H', 8)],\n [('A', 1), ('B', 2), ('C', 3), ('D', 4), ('E', 5), ('F', 6), ('H', 7), ('G', 8)], \n [('G', 1), ('H', 2), ('F', 3...
[ 0 ]
[]
[]
[ "nested_lists", "python", "tuples" ]
stackoverflow_0074397628_nested_lists_python_tuples.txt
Q: Pyttsxx / pyttsx3 error in init function ( no drivers found ) I fixed the pyttsx's , engine.py and driver.py file with some help on stackOverflow's solution but the problem still persists ( im trying to run a simple text to speech program ) import pyttsx3 engine = pyttsx3.init() engine.say("hello there!") engine....
Pyttsxx / pyttsx3 error in init function ( no drivers found )
I fixed the pyttsx's , engine.py and driver.py file with some help on stackOverflow's solution but the problem still persists ( im trying to run a simple text to speech program ) import pyttsx3 engine = pyttsx3.init() engine.say("hello there!") engine.runAndWait() the program runs and gives some errors like Traceback...
[ "I seemed to have found a potential solution!\nThis may or may not work but it looks like your PyInstaller site-package has skipped over some important pyttsx3 stuff.\nTo fix this all you have to do is go to wherever you have Python installed (usually the path looks something like this: \"C:\\Users[Your User]\\AppD...
[ 0 ]
[]
[]
[ "python", "pyttsx", "pyttsx3", "text_to_speech" ]
stackoverflow_0070874394_python_pyttsx_pyttsx3_text_to_speech.txt
Q: Returning particular output from Python function Suppose, in MATLAB, I have the following function: function [sums, diff, prod] = myFun(a, b) sums = a + b; diff = a - b; prod = a * b; end If I just wanted to return, say diff, I'd type in the console [~, diff, ~] = myFun(6, 2) and it returns 4. Now, ...
Returning particular output from Python function
Suppose, in MATLAB, I have the following function: function [sums, diff, prod] = myFun(a, b) sums = a + b; diff = a - b; prod = a * b; end If I just wanted to return, say diff, I'd type in the console [~, diff, ~] = myFun(6, 2) and it returns 4. Now, if I write a similar thing in Python 3.10 (for purpose...
[ "Your function returns a tuple containing all three values.\nYou can unpack that tuple in a number of ways that might meet your requirements:\n_, _, prod = myFun(3, 4)\nprint (prod)\n# result: 12\n\nOr you could just extract the third item in the tuple:\nprod = myFun(3, 4)[2]\nprint (prod)\n# result: 12\n\nUsing _,...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074397712_python_python_3.x.txt
Q: DRF Swagger - Endpoint parameter doesn't match the Serializer So I'm trying to create at REST API using DRF and Swagger for API Documentation, But I notice that Swagger UI Parameter doesn't match the given Serializer. MailSerializer.py ` from main.BusinessLayer.Model.Mails import Mails from rest_framework import s...
DRF Swagger - Endpoint parameter doesn't match the Serializer
So I'm trying to create at REST API using DRF and Swagger for API Documentation, But I notice that Swagger UI Parameter doesn't match the given Serializer. MailSerializer.py ` from main.BusinessLayer.Model.Mails import Mails from rest_framework import serializers class MailSerializer(serializers.Serializer): clas...
[ "allow_blank set to true means that the empty string should be considered a valid value. That doesn't mean it isn't required.\nSo try required, default value is True, so set required=False\n", "The problem may be in using Meta.fields with non-model serializer, try changing this:\nclass MailSerializer(serializers....
[ 1, 0 ]
[]
[]
[ "django", "drf_yasg", "python", "swagger" ]
stackoverflow_0074383938_django_drf_yasg_python_swagger.txt
Q: How Write a python program to retrieve all the products from the API Server Suppose you are writing a python web client to access an API of an online supermarket. Given below are the API details. Base URL = http://host1.open.uom.lk:8080 Write a python program to retrieve all the products from the API Server and pr...
How Write a python program to retrieve all the products from the API Server
Suppose you are writing a python web client to access an API of an online supermarket. Given below are the API details. Base URL = http://host1.open.uom.lk:8080 Write a python program to retrieve all the products from the API Server and print the total number of products currently stored in the server. Hint: the json r...
[ "Great! So it sounds like you were able to fetch the JSON response successfully.\nMind you, response_API is NOT the JSON, it is just a Response object. You need to call .json() or .text() on it to get the result you intend. Check this out: https://www.w3schools.com/python/ref_requests_response.asp\nYou’ll now need ...
[ 1 ]
[]
[]
[ "api", "json", "python" ]
stackoverflow_0074397720_api_json_python.txt
Q: How to apply different function to different columns using one apply method in Pandas? I have a dataframe df with three columns. Let's say the columns are "A", "B" and "C". And, I have three different functions func1, func2 and func3 which needs to be applied on column A, B and C respectively. func1 -> column A, ...
How to apply different function to different columns using one apply method in Pandas?
I have a dataframe df with three columns. Let's say the columns are "A", "B" and "C". And, I have three different functions func1, func2 and func3 which needs to be applied on column A, B and C respectively. func1 -> column A, func2 -> column, B func3 -> column C df["A"].apply(lambda x: func1(x)) df["B"].apply(lambda...
[ "Assuming your function returns a value for each row:\nimport pandas as pd\ndf = pd.DataFrame({'A':[1,2,3], 'B':[1,2,3], 'C':[1,2,3]})\n\ndf.transform({\n 'A':lambda x: x-1,\n 'B': lambda x: x+1,\n 'C': lambda x: x*2\n})\n\nOutput\n A B C\n0 0 2 2\n1 1 3 4\n2 2 4 6\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074397736_pandas_python.txt
Q: Voice to text in python Lets say I want to give input in hindi or any other language in voice And it will give an output in English (text).How can I do that? What I know: I know how to transfer voice to text. Eg. Information given : language=hindi Input: kese ho (in voice) Output: how are you? (In text) A: Voic...
Voice to text in python
Lets say I want to give input in hindi or any other language in voice And it will give an output in English (text).How can I do that? What I know: I know how to transfer voice to text. Eg. Information given : language=hindi Input: kese ho (in voice) Output: how are you? (In text)
[ "Voice-to-text uses ML/AI so if you want to code it yourself check out algorithms such as PLP features, Viterbi search, Deep Neural Networks, discriminative training, WFST framework. If you just want to use a library I would recommend SpeechRecognition. Then for translation, you would want to use translate.\n", "...
[ 0, 0 ]
[]
[]
[ "api", "python", "voice_recognition" ]
stackoverflow_0074080546_api_python_voice_recognition.txt
Q: list of multiple dicts I have the following list of dictonories list = [{'color': 'yellow', 'isvalid': '1'}, {'color': 'red', 'isvalid': '0'}, {'color': 'green', 'isvalid': '1'}] I want to check if 'color = red and isvalid = 1' and 'color = green and isvalid = 1'. Lets say I want to check if color=green and isvali...
list of multiple dicts
I have the following list of dictonories list = [{'color': 'yellow', 'isvalid': '1'}, {'color': 'red', 'isvalid': '0'}, {'color': 'green', 'isvalid': '1'}] I want to check if 'color = red and isvalid = 1' and 'color = green and isvalid = 1'. Lets say I want to check if color=green and isvalid =1 only when color=red and...
[ "This appears to be what you're after:\ndicts = [{'color': 'yellow', 'isvalid': '1'}, {'color': 'red', 'isvalid': '0'}, {'color': 'green', 'isvalid': '1'}]\n\ncheck_colors = ['red', 'green']\n\nresult = all(any(d['isvalid'] == '1' for d in dicts if d['color'] == c) for c in check_colors)\n\nprint(result)\n\n# set '...
[ 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074397473_dictionary_list_python.txt
Q: How do I iterate through and Pandas data frame column and concatenate a number to a string? I am attempting to iterate through a column and add a number based on the count of instances the duplicate value takes place. This will give me a unique value in my dataset. The data I have is below: FY group item ...
How do I iterate through and Pandas data frame column and concatenate a number to a string?
I am attempting to iterate through a column and add a number based on the count of instances the duplicate value takes place. This will give me a unique value in my dataset. The data I have is below: FY group item concat 0 2015 GROUP_A 1 2015-GROUP_A-1 1 2015 GROUP_A 1 2015-GROUP_A-1 2 2015 ...
[ "You could count the number of consecutive values in each concat group, adding 1 to each to offset the zero indexing\ndf['uid'] = df['concat'] + '-' + (df.groupby('concat').cumcount()+1).astype(str)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "for_loop", "pandas", "python" ]
stackoverflow_0074397708_dataframe_for_loop_pandas_python.txt
Q: How to proceed if sentence I apologize that I'm not an ENGLISH native. import datetime from time import sleep dt_now = datetime.datetime.now () while True: sleep(1) if dt_now.hour ==14 and dt_now.minute == 3: print("1") sleep(10) continue if dt_now.hour ==14 and dt_now.minute ...
How to proceed if sentence
I apologize that I'm not an ENGLISH native. import datetime from time import sleep dt_now = datetime.datetime.now () while True: sleep(1) if dt_now.hour ==14 and dt_now.minute == 3: print("1") sleep(10) continue if dt_now.hour ==14 and dt_now.minute == 5: print("2") ...
[ "Variables don't update themselves automatically. You should keep updating dt_now by placing the assignment of the current time within the loop instead:\nwhile True:\n dt_now = datetime.datetime.now()\n ...\n\n" ]
[ 0 ]
[]
[]
[ "datetime", "if_statement", "python" ]
stackoverflow_0074397602_datetime_if_statement_python.txt
Q: HackerRank Challenge : Find total number of days Plants die Problem Statement There are N plants in a garden. Each of these plants has been added with some amount of pesticide. After each day, if any plant has more pesticide than the plant at its left, being weaker than the left one, it dies. You are given t...
HackerRank Challenge : Find total number of days Plants die
Problem Statement There are N plants in a garden. Each of these plants has been added with some amount of pesticide. After each day, if any plant has more pesticide than the plant at its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each plant. Print the nu...
[ "Look at your Temp_plants array, you initialize it with []. However, Since you are iterating from index 1, The plant from index 0 is always excluded, so you have to initialize with [plant[0]], since the leftmost plant is always included. \nExample: 1 5 4 3 2\nActual Process\n\n1 5 4 3 2\n1 4 3 2\n1 3 2\n1 2\n1\n\nA...
[ 1, 1, 1, 0, 0 ]
[ "I would go with an approach where we recursively look at all the elements to the right of the minimum element.\nThe base case would be if the elements to the right of the min element were sorted!\n", "import java.util.LinkedList;\nimport java.util.List;\nimport java.util.Stack;\n\nclass StackNode {\n int inde...
[ -1, -1, -1, -2, -2 ]
[ "algorithm", "python" ]
stackoverflow_0031778691_algorithm_python.txt
Q: How to use argsparse to accept no flag and flag arguments I want to do something like this Case1: script.py --a="a_val" --b="b_val" Both values are required for case 1 Case2: script.py --verify Just need the --verify without any value A: Refer: https://docs.python.org/3/library/argparse.html parser.add_argument...
How to use argsparse to accept no flag and flag arguments
I want to do something like this Case1: script.py --a="a_val" --b="b_val" Both values are required for case 1 Case2: script.py --verify Just need the --verify without any value
[ "Refer: https://docs.python.org/3/library/argparse.html\nparser.add_argument('--verify', action='store_true')\n\n" ]
[ 0 ]
[]
[]
[ "command_line_arguments", "python" ]
stackoverflow_0074397822_command_line_arguments_python.txt
Q: Execute a terminal command within a try/except block (Jupyter notebook) I would like to sync output from a Jupyter notebook using the the AWS terminal command: aws s3 sync <local_path> <s3://<bucket>/destination_path> However, I want to fit this command within a try/except block if possible. Something like the fo...
Execute a terminal command within a try/except block (Jupyter notebook)
I would like to sync output from a Jupyter notebook using the the AWS terminal command: aws s3 sync <local_path> <s3://<bucket>/destination_path> However, I want to fit this command within a try/except block if possible. Something like the following is what I am trying to do: try: !aws s3 sync <local_path> <s3://<b...
[ "subprocess.call will return the return_code which will be zero if the command was successful, and anything else indicates an error\nso\ncmd = \"aws s3 sync <local_path> <s3://<bucket>/destination_path>\"\nif subprocess.call(cmd,shell=True):\n print(\"There was an error with the command\")\nelse:\n print(\"Comm...
[ 0 ]
[]
[]
[ "amazon_s3", "jupyter_notebook", "python" ]
stackoverflow_0074397835_amazon_s3_jupyter_notebook_python.txt
Q: How to join multiple tables in sql join using sqlmodel and fastapi tables.py class Tool(SQLModel, table=True): __tablename__ = 'tools' tool_id: Optional[int] = Field(default=None, primary_key=True) tool_name : str = Field(sa_column=Column("tool_name", VARCHAR(54),nullable=False)) tool_description ...
How to join multiple tables in sql join using sqlmodel and fastapi
tables.py class Tool(SQLModel, table=True): __tablename__ = 'tools' tool_id: Optional[int] = Field(default=None, primary_key=True) tool_name : str = Field(sa_column=Column("tool_name", VARCHAR(54),nullable=False)) tool_description : str = Field(sa_column=Column("tool_description", TEXT , nullable=True)...
[ "You can use comma as a separator between two where conditions, it is like using AND in sql.\ndef test(db: Session = Depends(get_db)):\n statement = select(Tool, CountryToolUser, User).where(Tool.tool_id == CountryToolUser.tool_id, User.user_id == CountryToolUser.user_id)\n print(statement) #here you can know...
[ 0 ]
[]
[]
[ "fastapi", "python", "sql", "sqlmodel" ]
stackoverflow_0074397846_fastapi_python_sql_sqlmodel.txt
Q: Discord.py - Can't get custom commands to work within inherited class I'm trying to get custom commands to work in my Discord server. But it doesn't work when I'm not using a decorator, and I do not know how to make it work within a class. Please help. (XXX.. just replaces an ID here) Please have a look at add_my_...
Discord.py - Can't get custom commands to work within inherited class
I'm trying to get custom commands to work in my Discord server. But it doesn't work when I'm not using a decorator, and I do not know how to make it work within a class. Please help. (XXX.. just replaces an ID here) Please have a look at add_my_commands() function. This one should be able to take the prefix and respond...
[ "No need to define your entire bot within a class. Create a main.py file with your bot defined and import cogs from there. I'd also set up my commands through a cog with commands.command().\nExample of how I'd go about adding an !info command:\nmain.py\nimport discord\nfrom discord.ext import commands\nfrom info im...
[ 0 ]
[]
[]
[ "command", "discord", "discord.py", "object", "python" ]
stackoverflow_0074376321_command_discord_discord.py_object_python.txt
Q: Element-wise string concatenation in numpy Is this a bug? import numpy as np a1=np.array(['a','b']) a2=np.array(['E','F']) In [20]: add(a1,a2) Out[20]: NotImplemented I am trying to do element-wise string concatenation. I thought Add() was the way to do it in numpy but obviously it is not working as expected. ...
Element-wise string concatenation in numpy
Is this a bug? import numpy as np a1=np.array(['a','b']) a2=np.array(['E','F']) In [20]: add(a1,a2) Out[20]: NotImplemented I am trying to do element-wise string concatenation. I thought Add() was the way to do it in numpy but obviously it is not working as expected.
[ "This can be done using numpy.core.defchararray.add. Here is an example:\n>>> import numpy as np\n>>> a1 = np.array(['a', 'b'])\n>>> a2 = np.array(['E', 'F'])\n>>> np.core.defchararray.add(a1, a2)\narray(['aE', 'bF'], \n dtype='<U2')\n\nThere are other useful string operations available for NumPy data types.\n...
[ 77, 14, 7, 3, 2, 1 ]
[]
[]
[ "arrays", "elementwise_operations", "numpy", "python", "string" ]
stackoverflow_0009958506_arrays_elementwise_operations_numpy_python_string.txt
Q: How to print ascii diamonds having two same lines at the center? The user input represents half of the rows in the diamonds (top triangles). If I enter the input as 9, I should have 9 rows including the center/longest line. But, underneath I only have 8 lines (I need to have 9 on the bottom too, including a copy o...
How to print ascii diamonds having two same lines at the center?
The user input represents half of the rows in the diamonds (top triangles). If I enter the input as 9, I should have 9 rows including the center/longest line. But, underneath I only have 8 lines (I need to have 9 on the bottom too, including a copy of the line above so it’s even). I need to make it so that both of my b...
[ "In order to repeat the last row in the output change the range of the first loop to:\nfor i in range(1,rows+1):\n\nThis answers already sufficiently your question.\n\n\nBelow some add-on information and code helping to develop better programming skills.\nThe first step in improving the code can be to notice that P...
[ 0, 0, 0 ]
[]
[]
[ "ascii_art", "python" ]
stackoverflow_0074392477_ascii_art_python.txt
Q: Pyautogui: How to type alt codes? I've been trying to type an '@' with pyautogui. This can be done with alt + 64 on my keyboard. But for some reason it doesn't type any @. Also it seems u can't type any other symbols with alt codes. pyautogui.hotkey('alt','6', '4') I've tried alot of different but no solution ;/ ...
Pyautogui: How to type alt codes?
I've been trying to type an '@' with pyautogui. This can be done with alt + 64 on my keyboard. But for some reason it doesn't type any @. Also it seems u can't type any other symbols with alt codes. pyautogui.hotkey('alt','6', '4') I've tried alot of different but no solution ;/
[ "You can try using the hold() function in pyautogui to hold down a key while other keys press.\nfor an example, with pyautogui.hold('alt'): pyautogui.press(['6','4'])\nJust make sure to make a new line and indent the pyautogui.press\nI hope I could help!\n" ]
[ 0 ]
[]
[]
[ "pyautogui", "python" ]
stackoverflow_0054582441_pyautogui_python.txt
Q: How to do some tensor multiplication without using for loop in python? Say I have two arrays X=[A,B,C] and Y=[D,E,F], where each element is a 3 by 3 matrix. I would like to make an array Z=[AD,BE,CF] without using for loop. What should I do? I have tried using np.tensordot(X,Y,axis=1) but it returns 9 products [[A...
How to do some tensor multiplication without using for loop in python?
Say I have two arrays X=[A,B,C] and Y=[D,E,F], where each element is a 3 by 3 matrix. I would like to make an array Z=[AD,BE,CF] without using for loop. What should I do? I have tried using np.tensordot(X,Y,axis=1) but it returns 9 products [[AD,AE,AF],[BD,BE,BF],[CD,CE,CF]]. the troublesome thing is that the matrix si...
[ "You can use tensorflow.transpose\n>>> a = tf.constant([1, 2, 3])\n>>> b = tf.constant([4, 5, 6])\n>>> tf.transpose([a, b])\n<tf.Tensor: shape=(3, 2), dtype=int32, numpy=\narray([[1, 4],\n [2, 5],\n [3, 6]], dtype=int32)>\n\nor you can use zip\na = (\"John\", \"Charles\", \"Mike\")\nb = (\"Jenny\", \"Ch...
[ 0, 0 ]
[]
[]
[ "matrix", "numpy", "python", "tensor" ]
stackoverflow_0074384495_matrix_numpy_python_tensor.txt
Q: Not able to get data for joining two tables in fastapi using sqlmodel I am trying to join two tables in fastapi using sqlmodel repository.py def test(db: Session = Depends(get_db)): statement = select(Tool, CountryTool).where(Tool.tool_id == CountryTool.tool_id) results = db.exec(statement) return resu...
Not able to get data for joining two tables in fastapi using sqlmodel
I am trying to join two tables in fastapi using sqlmodel repository.py def test(db: Session = Depends(get_db)): statement = select(Tool, CountryTool).where(Tool.tool_id == CountryTool.tool_id) results = db.exec(statement) return results.scalars() user.py @router.get("/test",tags=['test']) def get_user(db: ...
[ "In your repository.py file, instead of db.exec(statement), replace it with db.exec(statement).fetchall() and replace return results.scalars() with return results\ndef test(db: Session = Depends(get_db)):\n statement = select(Tool, CountryTool).where(Tool.tool_id == CountryTool.tool_id)\n results = db.exec(st...
[ 0 ]
[]
[]
[ "fastapi", "python", "sqlmodel" ]
stackoverflow_0074386054_fastapi_python_sqlmodel.txt
Q: Crash when passing bytes iterator object in Python 3.8 I am trying to collect the hashes from the keyBag in Manifest.plist. When I try to run the following script with Manifest.plist as the argument: from __future__ import print_function # updated to work with py3 using only standard lib modules # unsure if it wi...
Crash when passing bytes iterator object in Python 3.8
I am trying to collect the hashes from the keyBag in Manifest.plist. When I try to run the following script with Manifest.plist as the argument: from __future__ import print_function # updated to work with py3 using only standard lib modules # unsure if it will work with py2 still... import plistlib import struct im...
[ "bytearray(next(it) for _ in range(size)) will raise an error if there are fewer than size values in it. Instead, you can slice\nimport itertools\nbytearray(itertools.islice(it, size))\n\n" ]
[ 0 ]
[]
[]
[ "plistlib", "python", "python_3.x" ]
stackoverflow_0074397925_plistlib_python_python_3.x.txt
Q: Error while trying to run ```corr()``` in python with pandas module While trying to run the corr() method in python using pandas module, I get the following error: FutureWarning: The default value of numeric_only in DataFrame.corr is deprecated. In a future version, it will default to False. Select only valid colu...
Error while trying to run ```corr()``` in python with pandas module
While trying to run the corr() method in python using pandas module, I get the following error: FutureWarning: The default value of numeric_only in DataFrame.corr is deprecated. In a future version, it will default to False. Select only valid columns or specify the value of numeric_only to silence this warning. print...
[ "Thanks to @matszwecja for the answer, Using df.corr(numeric_only = True) (or False, depending on the needs) should get rid of the warning as,\nonly the default value of numeric_only is deprecated, that is it will be set to false in a future version: pandas documentation/reference\nP.S:-I wrote this answer to clos...
[ 2, 2 ]
[]
[]
[ "future_warning", "pandas", "python" ]
stackoverflow_0074305444_future_warning_pandas_python.txt
Q: For python, why isn't my "setter" and "getter" in my class being called? The goal of this program is to use classes to create create a Car object. It firsts asks the users for the year and make of the car and will then ask for the number of times the car will accelerate and brake and it adds 5 or subtracts 5 depen...
For python, why isn't my "setter" and "getter" in my class being called?
The goal of this program is to use classes to create create a Car object. It firsts asks the users for the year and make of the car and will then ask for the number of times the car will accelerate and brake and it adds 5 or subtracts 5 depending on the amount the user inputs. I don't know the proper terms but the meth...
[ "Ok since the question is asked with a genuine spirit/desire to learn and explore, here are a few pointers:\n\nIssue 1 - setYear() doesn't get called anywhere (you're calling getYear()). Also, not sure why you're passing value into it, and the assignment of self.year should probably happen last, once you've checked...
[ 1 ]
[]
[]
[ "class", "getter", "methods", "python", "setter" ]
stackoverflow_0074397996_class_getter_methods_python_setter.txt
Q: how to diagnose Apache2.4 service error 7024 Incorrect function System: Windows 10 x64 (enterprise computer with some restrictions) Apache 2.4 64-bit Python 3.7.1 64-bit mod_wsgi (built today from github using python setup.py install) I am working on getting an Apache server with Python on a Windows machine and ...
how to diagnose Apache2.4 service error 7024 Incorrect function
System: Windows 10 x64 (enterprise computer with some restrictions) Apache 2.4 64-bit Python 3.7.1 64-bit mod_wsgi (built today from github using python setup.py install) I am working on getting an Apache server with Python on a Windows machine and I have the server configured correctly in order to get the Hello Worl...
[ "Go to the Command Prompt move to the apache/bin folder and type\n>httpd -t\n\nThis will give you more information about the error preventing Apache from start.\n", "I was getting this error after updating my httpd.conf file. The problem was that my final xml tag in httpd.conf was unclosed </directory without th...
[ 2, 0, 0 ]
[]
[]
[ "apache", "mod_wsgi", "python" ]
stackoverflow_0052978208_apache_mod_wsgi_python.txt
Q: PYTHON: Find index of the largest number in a list without built-in functions and list modules Write a function, max index, that takes a list as a parameter and returns the index of the largest number in the list. When writing the function, you are given the following rules: You are not allowed to use the max fun...
PYTHON: Find index of the largest number in a list without built-in functions and list modules
Write a function, max index, that takes a list as a parameter and returns the index of the largest number in the list. When writing the function, you are given the following rules: You are not allowed to use the max function You are not allowed to use any list methods You must use a Pythonic FOR loop. This means you C...
[ "Here is one solution. If this is a homework question, you wont learn without trying, so try out different solutions starting with the for loop. Good luck!\ndef max_index(lon):\n max_val=0\n counter=0\n max_index=0\n for num in lon:\n if num > max_val:\n max_val = num\n max_...
[ 0, 0 ]
[]
[]
[ "for_loop", "python", "python_3.x" ]
stackoverflow_0074397871_for_loop_python_python_3.x.txt
Q: How do add multiple variables from a list into excel Is there a way where i could put all of the email output from the list, into an excel? this is the code that i use. Email = [['amzn-noc-contact@amazon.com', 'aws-routing-poc@amazon.com', 'abuse@amazonaws.com', 'aws-rpki-routing-poc@amazon.com'], ['abuse@l...
How do add multiple variables from a list into excel
Is there a way where i could put all of the email output from the list, into an excel? this is the code that i use. Email = [['amzn-noc-contact@amazon.com', 'aws-routing-poc@amazon.com', 'abuse@amazonaws.com', 'aws-rpki-routing-poc@amazon.com'], ['abuse@liquidweb.com', 'ipadmin@liquidweb.com'], ['arin-contact@g...
[ "List comp to flatten nested list, filter to remove Nones. Finally pass a dict to pandas.\nemails = [x for sublist in filter(None, Emails) for x in sublist]\ndf = pd.DataFrame({\"Emails\": emails})\n\n" ]
[ 1 ]
[]
[]
[ "ip", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074397697_ip_jupyter_notebook_pandas_python.txt
Q: GCP Datastore NDB: Filter for KindA elements keys that are NOT IN KindB documentId Here is my situation: I have two Datastore kind, I need to create a python query for all Data that don't are present in Kind B. In the sample those are: Data 3 and Data 4. The constraint here is that i need to filter for elements in...
GCP Datastore NDB: Filter for KindA elements keys that are NOT IN KindB documentId
Here is my situation: I have two Datastore kind, I need to create a python query for all Data that don't are present in Kind B. In the sample those are: Data 3 and Data 4. The constraint here is that i need to filter for elements in KindA which have a key that is different from specific KindB property. Kind A Kind ...
[ "Try this\n# keys_only=True means Return only the keys which is faster\nkindB_Ids = [ a.id() for a in KindB.query().fetch(keys_only=True) ]\n\n\nkindA_Ids = [ a.id() for a in KindA.query().fetch(keys_only=True) ]\n\n# This gives you rows in KindA whose ids are not in KindB\ndiff = [ ndb.Key(KindA, a) for a in KindA...
[ 2, 0 ]
[]
[]
[ "app_engine_ndb", "google_cloud_datastore", "python" ]
stackoverflow_0074378388_app_engine_ndb_google_cloud_datastore_python.txt
Q: Unable to import module 'getApi' I have a simple lambda function in getApi.py import logging from aws_lambda_powertools.event_handler import APIGatewayRestResolve from pythonjsonlogger import jsonlogger import os logger = logging.getLogger("APP") logHandler = logging.StreamHandler() formatter = jsonlogger.JsonFor...
Unable to import module 'getApi'
I have a simple lambda function in getApi.py import logging from aws_lambda_powertools.event_handler import APIGatewayRestResolve from pythonjsonlogger import jsonlogger import os logger = logging.getLogger("APP") logHandler = logging.StreamHandler() formatter = jsonlogger.JsonFormatter(fmt="%(asctime)s %(levelname)s...
[ "You just have a typo in your import. It has to be APIGatewayRestResolver instead of APIGatewayRestResolve.\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "api", "aws_lambda", "python", "sam" ]
stackoverflow_0074397735_amazon_web_services_api_aws_lambda_python_sam.txt
Q: How to randomly sample from a datafframe while preserving the distribution in Python? I am using a Kaggle sample data. As shown bellow, 40% of the location is in CA and 47% of the category includes FOODS. What I am trying to achieve is to randomly select data from this data frame, while more or less preserve the s...
How to randomly sample from a datafframe while preserving the distribution in Python?
I am using a Kaggle sample data. As shown bellow, 40% of the location is in CA and 47% of the category includes FOODS. What I am trying to achieve is to randomly select data from this data frame, while more or less preserve the same distribution for the values of the these two columns. Does python/Pandas have such a ca...
[ "Your can select a fraction of each group with groupby.sample:\n# selecting 10% of each group\ndf.groupby(['location', 'category']).sample(frac=0.1)\n\nBut if your data is large and you select a decent number of rows, this should naturally maintain a representativity of the proportions:\ndf.sample(n=1000)\n\nExampl...
[ 1 ]
[]
[]
[ "pandas", "python", "sampling" ]
stackoverflow_0074397847_pandas_python_sampling.txt
Q: How to convert speech to text in python - opus file format I have some .opus audio files that need to be converted to text in order to run some analytics. I am aware that there is the Python SpeechRecognition package that can do this with .wav files as demonstrated in this tutorial. Does anyone know how to convert...
How to convert speech to text in python - opus file format
I have some .opus audio files that need to be converted to text in order to run some analytics. I am aware that there is the Python SpeechRecognition package that can do this with .wav files as demonstrated in this tutorial. Does anyone know how to convert .opus files to text, or convert .opus to .wav? I have tried the...
[ "Here is a solution which employs ffmpeg and the os library to first convert all .opus files in the specified directory to .wav, and then perform speech recognition on the resulting .wav files using the speech_recognition module:\nSolution\nimport os\nimport speech_recognition as sr\n\npath = './audio-files/'\nfile...
[ 1 ]
[]
[]
[ "nlp", "opus", "python", "speech", "speech_to_text" ]
stackoverflow_0074397563_nlp_opus_python_speech_speech_to_text.txt
Q: How to plot with a for loop? I'm trying to use a for loop to plot several functions with Matplotlib in Python, a simplified version of my code is this: import matplotlib.pyplot as plt import numpy as np colors = ["r", "g", "b"] x = np.arange(0, 3, 1) for i in [3, 4, 6]: plt.plot(x, i + x, color=colors[i], li...
How to plot with a for loop?
I'm trying to use a for loop to plot several functions with Matplotlib in Python, a simplified version of my code is this: import matplotlib.pyplot as plt import numpy as np colors = ["r", "g", "b"] x = np.arange(0, 3, 1) for i in [3, 4, 6]: plt.plot(x, i + x, color=colors[i], linestyle='solid', linewidth = 3, ...
[ "colors has 3 elements, meaning the maximum value you can use to index that list is 2, but you're trying to index it with [3, 4, 6]. You could try something like:\nfor j, i in enumerate([3, 4, 6]):\n plt.plot(x, i + x, color=colors[j], linestyle='solid', linewidth = 3, marker='o')\n\nin this case, you're indexin...
[ 1 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0074398170_matplotlib_plot_python.txt
Q: Problems with Virtual environments and packages (python) Im working in python in vscode, I have created a virtual environment and installed all the packages I need to it, I selected the interpreter, but running the code still gives me the error no module named ` from bs4 import BeautifulSoup import requests htm...
Problems with Virtual environments and packages (python)
Im working in python in vscode, I have created a virtual environment and installed all the packages I need to it, I selected the interpreter, but running the code still gives me the error no module named ` from bs4 import BeautifulSoup import requests html_text = requests.get('https://www.timesjobs.com/candidate/jo...
[ "Activate the virtualenv, and then install BeautifulSoup4:\npip install BeautifulSoup4\n\nor,\npip3 install BeautifulSoup4\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074398055_python.txt
Q: Inherited class methods return parent object. Need to make it return object of child class I am trying to check the feasibility of subclassing the PySpark DataFrame class to add extra reusable methods across my work. class EnhancedDataframe(DataFrame): def __init__(self, df): super().__init__(df._jdf,df.sq...
Inherited class methods return parent object. Need to make it return object of child class
I am trying to check the feasibility of subclassing the PySpark DataFrame class to add extra reusable methods across my work. class EnhancedDataframe(DataFrame): def __init__(self, df): super().__init__(df._jdf,df.sql_ctx) def notNullCount(self,col_name): return self.filter(col(col_name).isNotNull()).co...
[ "Interesting problem. Its easy to break polymorphism by building new instances using the class name you know (pandas.DataFrame) rather than the class of the current object (self.__class__). From the behavior, it looks like pandas does the former instead of that latter.\nYou can make your method a function outside o...
[ 0 ]
[]
[]
[ "oop", "pyspark", "python" ]
stackoverflow_0074398086_oop_pyspark_python.txt
Q: What is the purpose of Python's built-in bool method __ror__? In the interactive interpreter, if you type the following in order you can see some pretty interesting stuff: 1) help() 2) modules 3) __builtin__ When reading through the output for awhile I came across these lines in class bool: __or__(...) x.__or_...
What is the purpose of Python's built-in bool method __ror__?
In the interactive interpreter, if you type the following in order you can see some pretty interesting stuff: 1) help() 2) modules 3) __builtin__ When reading through the output for awhile I came across these lines in class bool: __or__(...) x.__or__(y) <==> x|y and then later on: __ror__(...) x.__ror__(y) <==...
[ "Suppose you write your own integer class, and you want it to work with the built-in integers. You might define __or__\nclass MyInt(int):\n\n def __or__(self, other):\n # Not a recommended implementation!\n return self | int(other)\n\nso that you can write code like\n# Because this is equivalent to...
[ 22, 1 ]
[]
[]
[ "built_in", "built_in_types", "python" ]
stackoverflow_0025211477_built_in_built_in_types_python.txt
Q: Getting an error whenever the string is too long while passing it back to go from python script with cmd.Output() I am parsing a pdf file with python and sending the text string back to golang server. When I run the code with smaller pdf file it works properly but with large pdf files it returns exit status 1 Here...
Getting an error whenever the string is too long while passing it back to go from python script with cmd.Output()
I am parsing a pdf file with python and sending the text string back to golang server. When I run the code with smaller pdf file it works properly but with large pdf files it returns exit status 1 Here is the code i am using: func parsePdf(path string) string { cmd := exec.Command("python", "pdf_parser.py", path) ...
[ "I solved it on my own. It's simple instead of printing the outputString directly, print a json.dumps(). I'll provide the whole code below:\nmain.go file\npackage main\n\nimport (\n \"bytes\"\n \"encoding/json\"\n \"fmt\"\n \"log\"\n \"os\"\n \"os/exec\"\n)\n\ntype ParseText struct {\n Text str...
[ 0 ]
[]
[]
[ "go", "python" ]
stackoverflow_0074384126_go_python.txt
Q: an error in sending json data to flask server I have a json data as {"age":59.0,"bp":70.0,"sg":1.01,"al":3.0,"su":0.0,"rbc":1.0,"ba":0.0,"bgr":76.0,"bu":186.0,"sc":15.0,"sod":135.0,"pot":7.6,"hemo":7.1,"pcv":22.0,"wbcc":3800.0,"rbcc":2.1,"htn":1.0,"dm":0.0,"cad":0.0,"appet":0.0,"pe":1.0,"ane":1.0} I have to send ...
an error in sending json data to flask server
I have a json data as {"age":59.0,"bp":70.0,"sg":1.01,"al":3.0,"su":0.0,"rbc":1.0,"ba":0.0,"bgr":76.0,"bu":186.0,"sc":15.0,"sod":135.0,"pot":7.6,"hemo":7.1,"pcv":22.0,"wbcc":3800.0,"rbcc":2.1,"htn":1.0,"dm":0.0,"cad":0.0,"appet":0.0,"pe":1.0,"ane":1.0} I have to send this json into a ML model that is inside a flask se...
[ "The request.get_json() method is already doing the work of converting your JSON to a Python object. You can already use data_raw as a dictionary:\n@app.route('/predict', methods=['POST'])\ndef predict():\n if request.method == 'POST':\n data_raw = request.get_json()\n print(type(data_raw)) # prin...
[ 1 ]
[]
[]
[ "dictionary", "flask", "python", "rest" ]
stackoverflow_0074398054_dictionary_flask_python_rest.txt
Q: how to give input to loaded .pkl model in python I have a Random Forest model, and model saved in .pkl file. I have loaded the .pkl model but now I have to input the test data and predict the accuracy. how to input file to .pkl model? import pickle def read_from_pickle(RF): with open(RF, 'rb') as file: ...
how to give input to loaded .pkl model in python
I have a Random Forest model, and model saved in .pkl file. I have loaded the .pkl model but now I have to input the test data and predict the accuracy. how to input file to .pkl model? import pickle def read_from_pickle(RF): with open(RF, 'rb') as file: try: while True: yield p...
[ "this solution is with random Forrest regressor my model was dynamic price prediction\nimport pandas as pd\nimport numpy as np\nfrom sklearn import pipeline, preprocessing,metrics,model_selection,ensemble,linear_model\nfrom sklearn_pandas import DataFrameMapper\nfrom sklearn.metrics import mean_squared_error\n// fi...
[ 0 ]
[]
[]
[ "input", "pickle", "python", "random_forest", "test_data" ]
stackoverflow_0073035596_input_pickle_python_random_forest_test_data.txt
Q: How to replace multiple strings in pandas dataframe without memory issue? I have a large dataframe with (104959, 298) rows and columns in the string column I have multiple substrings that I need to replace I've tried df.EVENT_DTL.replace(['SPOUSE_2','SPOUSE_nan','PARENT_2','PARENT_nan','GRANDPARENT_2','GRANDPARENT...
How to replace multiple strings in pandas dataframe without memory issue?
I have a large dataframe with (104959, 298) rows and columns in the string column I have multiple substrings that I need to replace I've tried df.EVENT_DTL.replace(['SPOUSE_2','SPOUSE_nan','PARENT_2','PARENT_nan','GRANDPARENT_2','GRANDPARENT_nan','CHILD_2', 'CHILD_nan','RELATIVE_2','RELATIVE_nan','LOVER_2','LOV...
[ "Found the answer:\nReplace multiple substrings in a Pandas series with a value\nthe trick is to avoid making dictionary and use regex\n", "You could iterate through the list of strings you want to replace as shown. Other ideas here\nto_replace=['SPOUSE_2','SPOUSE_nan'...] #for example\nfor str_rep in to_replace:...
[ 0, 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074398071_numpy_pandas_python.txt
Q: Python: How to save image with 16 bit channels (e.g. 48 RGB)? I'm working scientifically with images from a microscope, where each of the 3 RGB channels are encoded as uint16 (0-65536). Currently I use OpenCV2 and NumPy to work with the images, and using the flag "cv2.IMREAD_UNCHANGED" everything works fine with t...
Python: How to save image with 16 bit channels (e.g. 48 RGB)?
I'm working scientifically with images from a microscope, where each of the 3 RGB channels are encoded as uint16 (0-65536). Currently I use OpenCV2 and NumPy to work with the images, and using the flag "cv2.IMREAD_UNCHANGED" everything works fine with the reading, and I can do some work on the image and return it to ui...
[ "OpenCV does support writing 16 Bit TIFF images.\nMake sure you are using a current version (>= 2.2).\nThe truncation probably happens to img in your code before saving with OpenCV.\n", "Maybe it helps if the numpy.uint16 is replace by cv2.CV_16U.\nIn some example the parameter is passed in as a string e.g. 'uint...
[ 2, 1, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0017992814_opencv_python.txt
Q: Drawing an OpenGL triangle in Python Here is my code so far: main.py_ from Application import Application if __name__ == '__main__': app = Application() app.run() Triangle.py_ import contextlib import logging as log from OpenGL import GL as gl import ctypes import sys ...
Drawing an OpenGL triangle in Python
Here is my code so far: main.py_ from Application import Application if __name__ == '__main__': app = Application() app.run() Triangle.py_ import contextlib import logging as log from OpenGL import GL as gl import ctypes import sys class Triangle: vertex_array_...
[ "When you call an OpenGL instruction, you need a valid and up-to-date OpenGL context. The OpenGL Context is created with the OpenGl window. The OpenGL objects (VAO, VBO and shaders) are create in the constructor of the Triangle class. Therefore you can construct an object of this class only after creating the OpenG...
[ 0 ]
[]
[]
[ "glfw", "opengl", "python" ]
stackoverflow_0074395933_glfw_opengl_python.txt
Q: How to decode CSR string in python? -----BEGIN CERTIFICATE REQUEST----- MIICvDCCAaQCAQAwdzELMAkGA1UEBhMCVVMxEjAQBgNVBAgTCVlvdXJTdGF0ZTER MA8GA1UEBxMIWW91ckNpdHkxCzAJBgNVBAsTAklUMRowGAYDVQQKExFZb3VyQ29t cGFueSwgSW5jLjEYMBYGA1UEAxMPd3d3LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG 9w0BAQEFAAOCAQ8AMIIBCgKCAQEA379BFFxfACdXsUk2wrQk...
How to decode CSR string in python?
-----BEGIN CERTIFICATE REQUEST----- MIICvDCCAaQCAQAwdzELMAkGA1UEBhMCVVMxEjAQBgNVBAgTCVlvdXJTdGF0ZTER MA8GA1UEBxMIWW91ckNpdHkxCzAJBgNVBAsTAklUMRowGAYDVQQKExFZb3VyQ29t cGFueSwgSW5jLjEYMBYGA1UEAxMPd3d3LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG 9w0BAQEFAAOCAQ8AMIIBCgKCAQEA379BFFxfACdXsUk2wrQka/nAlKbo+I9DAW32 +/SRxj/KtXVddscKW1obHGpM...
[ "from cryptography.x509 import load_pem_x509_csr\n\nreq = load_pem_x509_csr(b'''\n-----BEGIN CERTIFICATE REQUEST-----\nMIICvDCCAaQCAQAwdzELMAkGA1UEBhMCVVMxEjAQBgNVBAgTCVlvdXJTdGF0ZTER\n...\nobf5ziuNm1Df24NBt5tpCNzfGviKT6/RYfWg3dMaKxc=\n-----END CERTIFICATE REQUEST-----\n''');\n\nprint(req.signature_hash_algorithm.n...
[ 0 ]
[]
[]
[ "csr", "python", "ssl" ]
stackoverflow_0074398216_csr_python_ssl.txt
Q: Why does python use 'else' after for and while loops? I understand how this construct works: for i in range(10): print(i) if i == 9: print("Too big - I'm giving up!") break else: print("Completed successfully") But I don't understand why else is used as the keyword here, since it sugg...
Why does python use 'else' after for and while loops?
I understand how this construct works: for i in range(10): print(i) if i == 9: print("Too big - I'm giving up!") break else: print("Completed successfully") But I don't understand why else is used as the keyword here, since it suggests the code in question only runs if the for block does n...
[ "A common construct is to run a loop until something is found and then to break out of the loop. The problem is that if I break out of the loop or the loop ends I need to determine which case happened. One method is to create a flag or store variable that will let me do a second test to see how the loop was exited....
[ 839, 386, 247, 63, 41, 24, 23, 15, 15, 13, 8, 7, 6, 6, 5, 5, 3, 2, 2, 1, 0, 0, 0 ]
[ "I consider the structure as for (if) A else B, and for(if)-else is a special if-else, roughly. It may help to understand else.\nA and B is executed at most once, which is the same as if-else structure.\nfor(if) can be considered as a special if, which does a loop to try to meet the if condition. Once the if condit...
[ -2 ]
[ "for_else", "for_loop", "if_statement", "python" ]
stackoverflow_0009979970_for_else_for_loop_if_statement_python.txt
Q: Selenium Python - Grab information from text file and enter it onto a webpage I have dabbled in python selenium for quite a while and I have hit a crossroads on something. I want to grab information from a .txt file on my desktop and use the data within that .txt and write it onto a webpage. I know the basics of o...
Selenium Python - Grab information from text file and enter it onto a webpage
I have dabbled in python selenium for quite a while and I have hit a crossroads on something. I want to grab information from a .txt file on my desktop and use the data within that .txt and write it onto a webpage. I know the basics of opening the .txt file and reading the file lines etc but I am struggling on getting ...
[ "The solution will look like this:\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom time import sleep\n\n\nwith open('myfile.txt', 'r') as text_file:\n lines = text_file.readlines()\n\n\nfor line in lines:\n driver = webdriver.Chrome()\n driver.maximize_window()\n drive...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074397771_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: Creating a dictionary from 2 lists by storing multiple values with repeated keys There are 2 lists. What I am trying to do is to find the occurrence of first list elements and will hold the values of second list for a key in first list and in the end, it will become dictionary holding specific keys from list 1 and...
Creating a dictionary from 2 lists by storing multiple values with repeated keys
There are 2 lists. What I am trying to do is to find the occurrence of first list elements and will hold the values of second list for a key in first list and in the end, it will become dictionary holding specific keys from list 1 and values from list 2 Input: list1 = ['A', 'A', 'B', 'B', 'C', 'D'] list2 = [1, 2, 3, 4,...
[ "There are multiple small issues with your code:\n\nyou are missing the last entry in the dict, because the dict is only updated, if the value changes. However, for the last value (in your case 'D'), this is not the case.\nby initializing values with an empty list, you loose the first value\n\nThese issues could be...
[ 1, 1, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074398301_python_python_3.x.txt
Q: Is it possible to set django-allauth to accept only google login? I am implementing a web application using Django framework. In my business I need to let the users have access to the app only by google login. I also don't need to register the users in my database, it isn't a requirement. I just need that the user...
Is it possible to set django-allauth to accept only google login?
I am implementing a web application using Django framework. In my business I need to let the users have access to the app only by google login. I also don't need to register the users in my database, it isn't a requirement. I just need that the user will uses his google account to enter the site so I will be able to ge...
[ "From https://django-allauth.readthedocs.io/en/latest/advanced.html#creating-and-populating-user-instances you'll need to:\n\ndisable signup on a custom ACCOUNT_ADAPTER\nenable signup only through social account (google) on a custom SOCIALACCOUNT_ADAPTER\n\nIn practice:\n# settings.py\n\nACCOUNT_ADAPTER = 'myapp.ad...
[ 0 ]
[]
[]
[ "django", "django_allauth", "google_signin", "python" ]
stackoverflow_0070404632_django_django_allauth_google_signin_python.txt
Q: Python how to take screenshot of div i'm trying to take a screenshot of product detail of Amazon item. I found that div id = aplus is the product detail description which is i'm looking for. So i create code using python and selenium to take the full screen shot of the div section. However, the result is cropped a...
Python how to take screenshot of div
i'm trying to take a screenshot of product detail of Amazon item. I found that div id = aplus is the product detail description which is i'm looking for. So i create code using python and selenium to take the full screen shot of the div section. However, the result is cropped and only shows partial top of div. opti...
[ "This example you need import the library PIL.\n\npip install Pillow\n\nfrom selenium import webdriver\nfrom PIL import Image\nfrom io import BytesIO\n\noptions = webdriver.ChromeOptions()\noptions.headless = True\ndriver = webdriver.Chrome()\n\nURL = \"https://www.amazon.co.jp/-/en/Figuarts-Dragon-Saiyan-Approx-Pa...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074398324_python.txt
Q: Mass edit a field in Odoo I want to select some of the items like in the photo, and then have a button behind "delete" button to validate all the selected fields at the same time. How can I do this without adding modules? class AccountVoucher(models.Model): _inherit = 'account.voucher' validated = fields...
Mass edit a field in Odoo
I want to select some of the items like in the photo, and then have a button behind "delete" button to validate all the selected fields at the same time. How can I do this without adding modules? class AccountVoucher(models.Model): _inherit = 'account.voucher' validated = fields.Boolean('Validated')
[ "You have to add a function into account.voucher model to change the value of a field and call it from server action. You can refer below code to create server action in odoo-8.\n<record id=\"ir_actions_server_validate\" model=\"ir.actions.server\">\n <field name=\"sequence\" eval=\"5\"/>\n <field nam...
[ 0 ]
[]
[]
[ "odoo", "odoo_8", "python", "xml" ]
stackoverflow_0074382652_odoo_odoo_8_python_xml.txt
Q: Django Rest Framework settings to allow Authentication from Flutter using Authroization key I am using flutter in the frontend and Django in the backed and am trying to fetch user details, the login is working perfectly fine returning Token key I keep getting unauthorized or forbidden error and updated the headers...
Django Rest Framework settings to allow Authentication from Flutter using Authroization key
I am using flutter in the frontend and Django in the backed and am trying to fetch user details, the login is working perfectly fine returning Token key I keep getting unauthorized or forbidden error and updated the headers several times. final response = await http.get( url, headers: { HttpHeaders.auth...
[ "Value of HttpHeaders.authorizationHeader is \"authorization\" becouse of that it's sending invalid headers try like this\nheaders: {\n HttpHeaders.authorizationHeader: 'Bearer xxxxxxxx',\n},\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_rest_auth", "django_rest_framework", "flutter", "python" ]
stackoverflow_0074398089_django_django_rest_auth_django_rest_framework_flutter_python.txt
Q: Using requests to check instagram pages followers follower count The title sounds a bit confusing but I am trying to get the follower count of all of the followers of an instagram page. So an example output would be John 17 followers adam 120 followers will 172 followers This is what I have so far but afte...
Using requests to check instagram pages followers follower count
The title sounds a bit confusing but I am trying to get the follower count of all of the followers of an instagram page. So an example output would be John 17 followers adam 120 followers will 172 followers This is what I have so far but after this point I am not sure how to pull that data with what requests is...
[ "It is a bad idea to use requests module to scrape content from html website. You can use beautifulsoup or scrapy module to scrape content from websites.\nYou can also Instaloader library provides a convenient way to login and then programmatically access a profile's followers and followings list.\nRef: Use instalo...
[ 0 ]
[]
[]
[ "beautifulsoup", "instaloader", "python", "python_requests" ]
stackoverflow_0074398403_beautifulsoup_instaloader_python_python_requests.txt
Q: Find duplicated nested lists in a list [[1.0, 1.0], [1.0, 10.0], [1.0, 11.0], [1.0, 12.0], [1.0, 13.0]], [[2.0, 1.0], [2.0, 10.0], [2.0, 11.0], [2.0, 12.0], [2.0, 13.0]], [[3.0, 1.0], [3.0, 10.0], [3.0, 11.0], [3.0, 12.0], [3.0, 13.0]], [[4.0, 1.0], [4.0, 10.0], [4.0, 11.0], [4.0, 12.0], [4.0, 13.0]], [[4.0, 1...
Find duplicated nested lists in a list
[[1.0, 1.0], [1.0, 10.0], [1.0, 11.0], [1.0, 12.0], [1.0, 13.0]], [[2.0, 1.0], [2.0, 10.0], [2.0, 11.0], [2.0, 12.0], [2.0, 13.0]], [[3.0, 1.0], [3.0, 10.0], [3.0, 11.0], [3.0, 12.0], [3.0, 13.0]], [[4.0, 1.0], [4.0, 10.0], [4.0, 11.0], [4.0, 12.0], [4.0, 13.0]], [[4.0, 1.0], [4.0, 10.0], [4.0, 11.0], [4.0, 12.0], ...
[ "You want to sort your data and make each row a tuple to be able to group them. Then check if there are groups with more than 1 element -> duplicates.\nInput:\nll = [[[1.0, 1.0], [1.0, 10.0], [1.0, 11.0], [1.0, 12.0], [1.0, 13.0]],\n [[2.0, 1.0], [2.0, 10.0], [2.0, 11.0], [2.0, 12.0], [2.0, 13.0]],\n [[3.0, 1.0], [...
[ 0, 0 ]
[]
[]
[ "duplicates", "list", "nested", "python", "sublist" ]
stackoverflow_0074398250_duplicates_list_nested_python_sublist.txt
Q: Pandas dataFrame.nunique() : ("unhashable type : 'list'", 'occured at index columns') I want to apply the .nunique() function to a full dataFrame. On the following screenshot, we can see that it contains 130 features. Screenshot of shape and columns of the dataframe. The goal is to get the number of different val...
Pandas dataFrame.nunique() : ("unhashable type : 'list'", 'occured at index columns')
I want to apply the .nunique() function to a full dataFrame. On the following screenshot, we can see that it contains 130 features. Screenshot of shape and columns of the dataframe. The goal is to get the number of different values per feature. I use the following code (that worked on another dataFrame). def nbDiffere...
[ "You probably have a column whose content are lists.\nSince lists in Python are mutable they are unhashable.\nimport pandas as pd\n\ndf = pd.DataFrame([\n (0, [1,2]),\n (1, [2,3]) \n])\n\n# raises \"unhashable type : 'list'\" error\ndf.nunique()\n\nSOLUTION: Don't use mutable structures (like lists) in yo...
[ 9, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0050794760_pandas_python.txt
Q: TypeError: cannot unpack non-iterable NoneType object . Can anyone help me to solve the error in face-recognition I'm trying facerecognition project, I tried the code and there is one error which i'm unable to solve so I kindly request anyone to help me.... File "C:\Users\kmanj\PycharmProjects\faceregonition\main....
TypeError: cannot unpack non-iterable NoneType object . Can anyone help me to solve the error in face-recognition
I'm trying facerecognition project, I tried the code and there is one error which i'm unable to solve so I kindly request anyone to help me.... File "C:\Users\kmanj\PycharmProjects\faceregonition\main.py", line 48, in <module> _, frame = video_capture.read() TypeError: cannot unpack non-iterable NoneType object I'...
[ "I've never used this API before, but according to the documentation, it looks like you specify the video source in the cv2.VideoCapture() constructor.\nLeaving the constructor blank and then calling .read() is returning None (as there is no video to read frames from), and None cannot be unpacked into two variables...
[ 0 ]
[]
[]
[ "cv2", "face_recognition", "opencv", "python", "video_capture" ]
stackoverflow_0074398271_cv2_face_recognition_opencv_python_video_capture.txt
Q: How to update variable then write it on specific line or skip the name and password to write im almost new to the python and i gave myself a little challange where i write bank without class or specific module then i just got stuck at updating the cash and balance aaa aaa 1 1 bkhg lkhg 1 1 terat rtrt 1 1 aa aa 1 1...
How to update variable then write it on specific line or skip the name and password to write
im almost new to the python and i gave myself a little challange where i write bank without class or specific module then i just got stuck at updating the cash and balance aaa aaa 1 1 bkhg lkhg 1 1 terat rtrt 1 1 aa aa 1 1 first name then password then balance and cash with them num = 0 nums = 0 file = open("accounts....
[ "It's your little challange bro.\n\nHappy Programming!!\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074397923_python_python_3.x.txt
Q: Python mysql select field based on variable I want to create a MySQL syntax to select a field based on a variable, what I have is: book_category = "science" mycursor_a.execute(("SELECT {book_categories} FROM research_papers WHERE book_Name = %s", (book,)).format(book_categories = book_category)) but I get the fol...
Python mysql select field based on variable
I want to create a MySQL syntax to select a field based on a variable, what I have is: book_category = "science" mycursor_a.execute(("SELECT {book_categories} FROM research_papers WHERE book_Name = %s", (book,)).format(book_categories = book_category)) but I get the following error: AttributeError: 'tuple' object has ...
[ "That's because\n\n(book,))\n\nis a tuple and not an object, remember that tuples don't have dynamic reading like an object or dictionary.\nTo solve that we need a dictionary variable as a result.\ncan be achieved by setting the cursor.\nmycursor_a= db.cursor( buffered=True , dictionary=True)\nbook_category = \"sci...
[ 0, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0074398176_mysql_python.txt
Q: how to merge values onto dates of a dataframe by the hour given intervals between days pandas so I have constructed weights for values between specific timestamps in pandas. I want to be able to assign these weights to another dataframe that has datetime objects with values down to the hour. I essentially want t...
how to merge values onto dates of a dataframe by the hour given intervals between days pandas
so I have constructed weights for values between specific timestamps in pandas. I want to be able to assign these weights to another dataframe that has datetime objects with values down to the hour. I essentially want to weight 2 columns (hourly data) of another frame by the timeframe they are in from the other dataf...
[ "Use merge_asof:\ndf = pd.merge_asof(price_df.reset_index(),weight_df, on='Datetime').set_index('Datetime')\n\nOr:\ndf = pd.merge_asof(price_df, weight_df, on='Datetime').set_index('Datetime')\n\nOr:\ndf = pd.merge_asof(price_df, weight_df.set_index('Datetime'),\n left_index=True, right_index=True...
[ 1 ]
[]
[]
[ "datetime", "merge", "pandas", "python", "weighted" ]
stackoverflow_0074398454_datetime_merge_pandas_python_weighted.txt
Q: Polars DataFrame memory size in Python Was wondering about the size of particular polars DataFrames. I tried with: from sys import getsizeof getsizeof(df) Out[17]: 48 getsizeof(df.to_pandas()) Out[18]: 1602923950 It appears all polars df are 48 bytes? Confused. A: The Python package polars is only a wrapper fo...
Polars DataFrame memory size in Python
Was wondering about the size of particular polars DataFrames. I tried with: from sys import getsizeof getsizeof(df) Out[17]: 48 getsizeof(df.to_pandas()) Out[18]: 1602923950 It appears all polars df are 48 bytes? Confused.
[ "The Python package polars is only a wrapper for the underlying core polars library written in Rust. So I'm pretty sure what you're seeing when you call getsizeof on the DataFrame is the getsizeof result for the Python object implementing that type in the polars Python package (at the wrapper layer).\nWith pandas t...
[ 3, 0 ]
[]
[]
[ "memory", "python", "python_polars" ]
stackoverflow_0071788877_memory_python_python_polars.txt
Q: Weird issue during calling the object's method in python - 'self' pointing to the wrong object? I found some weird behaviour during the creation of classes and objects in python3. I dislike typing every time "self" word and constructors during writing classes if my class is very simple so I made the class 'Foo' th...
Weird issue during calling the object's method in python - 'self' pointing to the wrong object?
I found some weird behaviour during the creation of classes and objects in python3. I dislike typing every time "self" word and constructors during writing classes if my class is very simple so I made the class 'Foo' that copies static variables and turns them into the new object's attributes. At the beginning I was ma...
[ "You're retrieving a self.func method object, deep copying it, and assigning the result to self.func.\nThe deep copy creates a method object bound to a new Bar instance, which will have its own copies of any instance attributes created before the method was copied, and no instance attribute for any instance attribu...
[ 3, 0 ]
[ "try this\nclass Bar(Foo):\n def __init__(self):\n super().__init__(self)\n self.val = []\n\n def func(self):\n print(\"Self ID:\", id(self))\n print(self.val)\n\nshould it works.\nObject ID: 140516181578944\n[2]\nSelf ID: 140516181578944\n[2]\n\n" ]
[ -1 ]
[ "class", "inheritance", "methods", "object", "python" ]
stackoverflow_0074398231_class_inheritance_methods_object_python.txt
Q: PyQt6 QtWebChannel not working with after build I just tried to build my app using PyInstaller, and I got this error: ModuleNotFoundError: No module named 'PyQt6.QtWebChannel' It works just fine with the .py file, so I'm guessing there is something wrong with PyInstaller. Is there another tool I could use for thi...
PyQt6 QtWebChannel not working with after build
I just tried to build my app using PyInstaller, and I got this error: ModuleNotFoundError: No module named 'PyQt6.QtWebChannel' It works just fine with the .py file, so I'm guessing there is something wrong with PyInstaller. Is there another tool I could use for this, or will I just need to do some bug fixes? I don't ...
[]
[]
[ "For install Pyqt I recommend use the pip install. Put this command in the terminal of your OS:\npip install PySide6\nor\npip install PySide2\n" ]
[ -1 ]
[ "pyinstaller", "pyqt6", "python" ]
stackoverflow_0074397752_pyinstaller_pyqt6_python.txt
Q: Convert string like '{x:=1, y=2, z=3}' to JSON in python I want to convert the string '{x:=1, y=2, z=3}' to a Python object. I tried json.loads(), but got an error, it was expecting string to be '{"x":1, "y":2, "z":3}'. I'm new to Python, if anyone can help that would be great. A: you may want to try to parse th...
Convert string like '{x:=1, y=2, z=3}' to JSON in python
I want to convert the string '{x:=1, y=2, z=3}' to a Python object. I tried json.loads(), but got an error, it was expecting string to be '{"x":1, "y":2, "z":3}'. I'm new to Python, if anyone can help that would be great.
[ "you may want to try to parse the string yourself:\ndef parse_input(x):\n result = dict()\n x = x.replace(\":\", \"\")\n for pair in x[1:-1].split(\",\"):\n key,value = tuple(pair.split(\"=\"))\n result[key.strip()] = int(value.strip())\n return result\n\n\nAlternatively, you can convert t...
[ 3 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074398724_json_python.txt
Q: Numpy - vectorize the bivariate poisson pmf equation I'm trying to write a function to evaluate the probability mass function for the bivariate poisson distribution. This is easy when all of the parameters (x, y, theta1, theta2, theta0) are scalars, but tricky to scale up without loops to allow these parameters t...
Numpy - vectorize the bivariate poisson pmf equation
I'm trying to write a function to evaluate the probability mass function for the bivariate poisson distribution. This is easy when all of the parameters (x, y, theta1, theta2, theta0) are scalars, but tricky to scale up without loops to allow these parameters to be vectors. I need it to scale such that, for: theta0 b...
[ "I think I have this figured out, based on the approach that @w-m suggests: calculate every possible summation term which could appear, based on the maximum x or y value which appears, and use a mask to get rid of the ones you don't want. Assuming you have your x and y terms go from 0 to N, in consecutive order, th...
[ 3 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074390945_numpy_python.txt
Q: Toggle points on and off in altair I'd like to be able to toggle the display of the points on and off in the below chart. The 2 lines are the means of the points in groups 1 and 2. I thought there would be a way to do this using interactive but cannot find any examples. Any help is much appreciated. import math im...
Toggle points on and off in altair
I'd like to be able to toggle the display of the points on and off in the below chart. The 2 lines are the means of the points in groups 1 and 2. I thought there would be a way to do this using interactive but cannot find any examples. Any help is much appreciated. import math import numpy as np import pandas as pd imp...
[ "You can make a new column called 'Show individual points' with all the values are True.\nsummary_df['Show individual points'] = True\nI changed the all_selection into the following:\nall_selection = alt.selection_single(fields=['Show individual points'], bind=alt.binding_checkbox(name='Show individual points'), in...
[ 1 ]
[]
[]
[ "altair", "python", "vega_lite" ]
stackoverflow_0064374541_altair_python_vega_lite.txt
Q: How to split the pandas dataframe column result? I try to split the text column in df['text'], but paddleocr output the text with conf, so I don't know how to separate it into two part, I tried using lstrip but didnt work. The result as follow: ID Text 0 (7-Eleven ...
How to split the pandas dataframe column result?
I try to split the text column in df['text'], but paddleocr output the text with conf, so I don't know how to separate it into two part, I tried using lstrip but didnt work. The result as follow: ID Text 0 (7-Eleven Malaysia, 0.9709457) 1 (Sd...
[ "df[['text', 'num']] = df['Text'].str.split(',', 1, expand=True)\n\nor this one :\ndf = pd.DataFrame(df.row.str.split(',',1).tolist(),\n columns = ['text','num'])\n\nor this :\ndf.join(df['Text'].str.split(',', 1, expand=True).rename(columns={0:'text', 1:'num'}))\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "paddleocr", "pandas", "python" ]
stackoverflow_0074398474_dataframe_paddleocr_pandas_python.txt
Q: Training and validation loss increases after 10 epochs I am training an image captioning model. This model is consist of two other models, a BERT and an Xception model. I train both of these two models in parallel. The model training accuracy seems fine till 10 epochs then the loss starts increasing. The code and ...
Training and validation loss increases after 10 epochs
I am training an image captioning model. This model is consist of two other models, a BERT and an Xception model. I train both of these two models in parallel. The model training accuracy seems fine till 10 epochs then the loss starts increasing. The code and parameters of this model are as follows. num_epochs = 20 # ...
[ "Hi your loss is high because of the learning rate that is 5e-06 and 1e-06 in these cases try adjusting this and may be consider increasing it where you have a learning rate from 1e-4 to 0.01 because if learning rate is smaller and your model started from a place where loss was huge then it will be difficult for th...
[ 2 ]
[]
[]
[ "deep_learning", "python" ]
stackoverflow_0074379041_deep_learning_python.txt
Q: How can I assign callbacks to buttons that aren't guaranteed to exist in Ploty-Dash? I have a dash program that creates one to three buttons based on user input in a dropdown. The user can then click the button and the program will tell them which button was last pressed. Like so: However an issue arises whenever...
How can I assign callbacks to buttons that aren't guaranteed to exist in Ploty-Dash?
I have a dash program that creates one to three buttons based on user input in a dropdown. The user can then click the button and the program will tell them which button was last pressed. Like so: However an issue arises whenever I select a dropdown value that doesn't create all 3 buttons. I can select 1 or 2, and 1 o...
[ "You can use Pattern-Matching Callbacks and modify your callbacks to fit the first example from the docs:\nfrom dash import ALL\n\n@callback(Output('button-row', 'children'),\n Input('dropdown', 'value'))\ndef update_button_row(dropdown):\n children = []\n for each in range(dropdown):\n button...
[ 1 ]
[]
[]
[ "plotly_dash", "python" ]
stackoverflow_0074380127_plotly_dash_python.txt
Q: Python Script for Face Expression Using Unreal Engine5 Our Project is “ Face emotion recognition”. To improve our results and for better performances we need more “Data” to train the model (Data in image form). So we plan to create data using Unreal Engine 5. We have imported meta human and tried a control rig t...
Python Script for Face Expression Using Unreal Engine5
Our Project is “ Face emotion recognition”. To improve our results and for better performances we need more “Data” to train the model (Data in image form). So we plan to create data using Unreal Engine 5. We have imported meta human and tried a control rig tool to make different facial expressions .Also we tried Live...
[ "I've been working with metahuman face mocap for a long time.\nI think you can create blendshapes by randomly generating values ​​in certain ranges.\nhttps://github.com/JimWest/MeFaMo this this link may help you\n" ]
[ 0 ]
[]
[]
[ "python", "unreal_engine5" ]
stackoverflow_0073105899_python_unreal_engine5.txt
Q: Python: Indent all lines of a string except first while preserving linebreaks? I want to indent all lines of a multi-line string except the first, without wrapping the text. For example, I want to turn: A very very very very very very very very very very very very very very very very long mutiline string into: A...
Python: Indent all lines of a string except first while preserving linebreaks?
I want to indent all lines of a multi-line string except the first, without wrapping the text. For example, I want to turn: A very very very very very very very very very very very very very very very very long mutiline string into: A very very very very very very very very very very very very very very very very ...
[ "You just need to replace the newline character '\\n' with a new line character plus the white spaces '\\n    ' and save it to a variable (since replace won't change your original string, but return a new one with the replacements).\nstring = string.replace('\\n', '\\n ')\n\n", "Do you mean something like thi...
[ 18, 2, 0, 0 ]
[]
[]
[ "indentation", "python", "string", "text", "word_wrap" ]
stackoverflow_0018518031_indentation_python_string_text_word_wrap.txt
Q: AWS Lambda read contents of file in zip uploaded as source code I have two files: MyLambdaFunction.py config.json I zip those two together to create MyLambdaFunction.zip. I then upload that through the AWS console to my lambda function. The contents of config.json are various environmental variables. I need ...
AWS Lambda read contents of file in zip uploaded as source code
I have two files: MyLambdaFunction.py config.json I zip those two together to create MyLambdaFunction.zip. I then upload that through the AWS console to my lambda function. The contents of config.json are various environmental variables. I need a way to read the contents of the file each time the lambda function ...
[ "Figured it out with the push in the right direction from @helloV.\nAt the top of the python file put import os\nInside your function handler put the following:\nconfigPath = os.environ['LAMBDA_TASK_ROOT'] + \"/config.json\"\nprint(\"Looking for config.json at \" + configPath)\nconfigContents = open(configPath).rea...
[ 20, 3, 1, 0, 0 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "python" ]
stackoverflow_0039477729_amazon_web_services_aws_lambda_python.txt
Q: Python function which will count the total number of items in values from a dictionary and return another dictionary with item count data = {'customer1': ['milk', 'bread'], 'customer2': ['butter'], 'customer3': ['beer', 'diapers'], 'customer4': ['milk', 'bread', 'butter'], 'customer5': ['bread']} I want the P...
Python function which will count the total number of items in values from a dictionary and return another dictionary with item count
data = {'customer1': ['milk', 'bread'], 'customer2': ['butter'], 'customer3': ['beer', 'diapers'], 'customer4': ['milk', 'bread', 'butter'], 'customer5': ['bread']} I want the Python function output to be {'milk': 2, 'bread': 3, 'butter': 2, 'beer': 1, 'diapers': 1} and then also build a histogram on this data ...
[ "You can use Counter class from collections module.\n>>> data = {\n... \"customer1\": [\"milk\", \"bread\"],\n... \"customer2\": [\"butter\"],\n... \"customer3\": [\"beer\", \"diapers\"],\n... \"customer4\": [\"milk\", \"bread\", \"butter\"],\n... \"customer5\": [\"bread\"],\n... }\n>>> \n>>> fr...
[ 1, 1 ]
[]
[]
[ "count", "dictionary", "function", "python" ]
stackoverflow_0074398764_count_dictionary_function_python.txt
Q: How to handle unique_ptr's with SWIG I have an EventDispatcher class that implements the publish-subscribe pattern. It's interface looks something like this (simplified): class EventDispatcher { public: void publish(const std::string& event_name, std::unique_ptr<Event> event); std::unique_ptr<Subscription...
How to handle unique_ptr's with SWIG
I have an EventDispatcher class that implements the publish-subscribe pattern. It's interface looks something like this (simplified): class EventDispatcher { public: void publish(const std::string& event_name, std::unique_ptr<Event> event); std::unique_ptr<Subscription> subscribe(const std::string& event_name,...
[ "There's quite a lot of scope to do useful things using the generic smart pointer support in SWIG, despite the noted lack of support in the C++11 notes. \nIn short if there's an operator-> then SWIG has merged the members of the pointee into the pointer to allow them to be used interchangeably within the the target...
[ 19, 3, 0 ]
[ "There is no support to unique_ptr yet.\nhttp://www.swig.org/Doc3.0/CPlusPlus11.html\nYou need to use smart pointers as follow:\nhttp://www.swig.org/Doc3.0/Library.html#Library_std_shared_ptr\n" ]
[ -2 ]
[ "c++", "python", "swig" ]
stackoverflow_0027693812_c++_python_swig.txt
Q: Pyspark: Exception: Java gateway process exited before sending the driver its port number I'm trying to run pyspark on my macbook air. When i try starting it up I get the error: Exception: Java gateway process exited before sending the driver its port number when sc = SparkContext() is being called upon startup. ...
Pyspark: Exception: Java gateway process exited before sending the driver its port number
I'm trying to run pyspark on my macbook air. When i try starting it up I get the error: Exception: Java gateway process exited before sending the driver its port number when sc = SparkContext() is being called upon startup. I have tried running the following commands: ./bin/pyspark ./bin/spark-shell export PYSPARK_SUB...
[ "One possible reason is JAVA_HOME is not set because java is not installed.\nI encountered the same issue. It says \nException in thread \"main\" java.lang.UnsupportedClassVersionError: org/apache/spark/launcher/Main : Unsupported major.minor version 51.0\n at java.lang.ClassLoader.defineClass1(Native Method)\n ...
[ 41, 31, 24, 11, 9, 7, 7, 7, 5, 5, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "If you are using Jupyter notebook from the window machine.\njust use the following code\nspark =SparkSession.builder.appName('myapp').getOrCreate\n\nDon't use like\nspark =SparkSession.builder.appName('myapp').getOrCreate()\n\n" ]
[ -4 ]
[ "apache_spark", "java", "macos", "pyspark", "python" ]
stackoverflow_0031841509_apache_spark_java_macos_pyspark_python.txt
Q: Python script to export Excel to Google Sheets I want to export the local excel data to google sheets. I got all APIs and requirements. Now, I'm trying to that python script in this link https://blog.coupler.io/python-to-google-sheets/#:~:text=append()-,Python%20script%20to%20export%20Excel%20to%20Google%20Sheets,...
Python script to export Excel to Google Sheets
I want to export the local excel data to google sheets. I got all APIs and requirements. Now, I'm trying to that python script in this link https://blog.coupler.io/python-to-google-sheets/#:~:text=append()-,Python%20script%20to%20export%20Excel%20to%20Google%20Sheets,-Already%20have%20an def export_excel_to_sheets(): ...
[ "I think answer below will solve your problem, please give it a try. If it doesn't work let me know.\nhttps://github.com/burnash/gspread/issues/680#issuecomment-561936295\n" ]
[ 0 ]
[]
[]
[ "excel", "google_sheets", "python" ]
stackoverflow_0074398834_excel_google_sheets_python.txt
Q: Flask-Talisman breaks Flask-Bootstrap I want my website to always redirect to the secure https version of the site, and I'm using flask-talisman to do this. However for some reason adding this seemingly-unrelated line of code is breaking the flask-bootstrap formatting on my website. This is what the original __ini...
Flask-Talisman breaks Flask-Bootstrap
I want my website to always redirect to the secure https version of the site, and I'm using flask-talisman to do this. However for some reason adding this seemingly-unrelated line of code is breaking the flask-bootstrap formatting on my website. This is what the original __init__.py file and website looked like before ...
[ "It's an old thread, but the answer is that you need to whitelist your allowed sites, like in this example (directly from flask-talisman web site):\ncsp = {\n 'default-src': [\n '\\'self\\'',\n 'cdnjs.cloudflare.com'\n ]\n}\ntalisman = Talisman(app, content_security_policy=csp)\n\n", "Building on...
[ 10, 3, 0 ]
[]
[]
[ "flask", "flask_bootstrap", "https", "python", "ssl" ]
stackoverflow_0054730178_flask_flask_bootstrap_https_python_ssl.txt
Q: Issue with requesting Steam api Bukson Good day ! To work with the Steam marketplace, I use the Steampy library from Bukson. It did not have the function I needed to create the itemordershistogram request, so I created it myself in the market.py file. The problem is that the server responds with a 400 error, sayin...
Issue with requesting Steam api Bukson
Good day ! To work with the Steam marketplace, I use the Steampy library from Bukson. It did not have the function I needed to create the itemordershistogram request, so I created it myself in the market.py file. The problem is that the server responds with a 400 error, saying that the request was incorrectly composed....
[ "Remove the trailing / from your URL.\nLine 3 should read:\nurl = SteamUrl.COMMUNITY_URL + '/market/itemordershistogram'\n" ]
[ 0 ]
[]
[]
[ "python", "request", "steam", "steam_web_api" ]
stackoverflow_0074279261_python_request_steam_steam_web_api.txt
Q: How to stop triggering the key while holding the key in pynput? I am using the pynput and winsound modules to make a program that makes the pc play the sound of the keys and mouse. The problem is that when I press a key and hold it down the key is triggered repeatedly, which causes the sound to play repeatedly in ...
How to stop triggering the key while holding the key in pynput?
I am using the pynput and winsound modules to make a program that makes the pc play the sound of the keys and mouse. The problem is that when I press a key and hold it down the key is triggered repeatedly, which causes the sound to play repeatedly in a loop until I release the key. I followed this solution to create th...
[ "could possibly set up a variable that would store whether you have played the sound on the click, and would prevent playing another sound until you have released, and the variable is reset.\ncanPlaySoundFromPress = True\ndef onPress(...):\n if canPlaySoundFromPress:\n winsound.PlaySound(\"sound.wav\", wi...
[ 1, 1 ]
[]
[]
[ "pynput", "python", "winsound" ]
stackoverflow_0074396361_pynput_python_winsound.txt
Q: how to open new tab with command line in file explorer? I want to open a new folder in different tabs on the same window of Windows File Explorer in Windows 11, instead of opening a new window every time. I tried to use Start.exe C:\ Explorer.exe C: \ -W 0 Explorer.exe C: \ --windows 0 in terminal and Python. imp...
how to open new tab with command line in file explorer?
I want to open a new folder in different tabs on the same window of Windows File Explorer in Windows 11, instead of opening a new window every time. I tried to use Start.exe C:\ Explorer.exe C: \ -W 0 Explorer.exe C: \ --windows 0 in terminal and Python. import os import sys gpus = sys.argv[1] path = os.path.realpath(...
[ "I did some research on your problem and concluded that it is not allowed to open Tabs in the file explorer.\nIn this link we can see that as of 11/09/2022 there is no response by MSFT\nhttps://techcommunity.microsoft.com/t5/windows-11/22h2-explorer-tabs-save-configuration/m-p/3672808\n" ]
[ 0 ]
[]
[]
[ "command_line", "directory", "microsoft_file_explorer", "python", "windows_11" ]
stackoverflow_0074397741_command_line_directory_microsoft_file_explorer_python_windows_11.txt
Q: JSON To Pandas Dataframe with incomplete JSON Properties Let's say I have a JSON as such: [ { name: "user1", age: 12, category: "young", }, { name: "user2", category: "old", }, { name: "user3", age: 23, } ] As we can see user1 has the...
JSON To Pandas Dataframe with incomplete JSON Properties
Let's say I have a JSON as such: [ { name: "user1", age: 12, category: "young", }, { name: "user2", category: "old", }, { name: "user3", age: 23, } ] As we can see user1 has the most complete properties which are name, age, category while ...
[ "If convert json to list of dictionaries pandas add missing values for missing categories:\nimport json\n\nwith open('file.json') as f: \n data = json.load(f) \n\ndf = pd.DataFrame(data)\ndf.insert(0, 'id', range(1, len(df)+1))\nprint (df) \n id name age category\n0 1 user1 12.0 young\n1 2 us...
[ 3 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074398972_json_pandas_python.txt
Q: In python how do I convert a datetime in a specific local time (not my local) to UTC I'm pulling data from a London based service and they are giving me date&time info in London local time.So UTC in winter and BST(UTC+1) in summer. Internally we use UTC for everything, in Python how do I convert the London stuff t...
In python how do I convert a datetime in a specific local time (not my local) to UTC
I'm pulling data from a London based service and they are giving me date&time info in London local time.So UTC in winter and BST(UTC+1) in summer. Internally we use UTC for everything, in Python how do I convert the London stuff to UTC in a way that will account for daylight savings? I appreciate that some times around...
[ "You need to use a timezone object; these don't come with Python itself as the data changes too often. The pytz library is easily installed though.\nExample conversion:\n>>> import pytz\n>>> import datetime\n>>> bst = pytz.timezone('Europe/London')\n>>> dt = datetime.datetime.strptime('2012-10-12T19:30:00', '%Y-%m-...
[ 9, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0012855586_datetime_python.txt
Q: ValueError: Please pass `features` or at least one example when writing data I'm new to huggingface and am working on a movie generation script. So far my code looks like this from transformers import GPT2Tokenizer, GPTNeoModel from datasets import load_dataset dataset = load_dataset('text',data_files={'train':['y...
ValueError: Please pass `features` or at least one example when writing data
I'm new to huggingface and am working on a movie generation script. So far my code looks like this from transformers import GPT2Tokenizer, GPTNeoModel from datasets import load_dataset dataset = load_dataset('text',data_files={'train':['youtube_3/script.txt']}) tokenizer = GPT2Tokenizer.from_pretrained('EleutherAI/gpt-...
[ "The prompt is telling you that you need a 'features' para for the 'load_dataset' method\nfrom datasets import load_dataset,Features,Value\ncontext_feat = Features({'text': Value(dtype='string', id=None)})\ndataset = load_dataset(\n path=\"text\",\n data_dir=path.data_dir,\n data_files=\"input.fm.plus.fc.t...
[ 0 ]
[]
[]
[ "huggingface_datasets", "python" ]
stackoverflow_0069079507_huggingface_datasets_python.txt
Q: How to remove a cloud armor secuiry policy from backend service using Python I'm creating a few GCP cloud armor policies across multiple projects using the Python client library and attaching them to several backend services using the .set_security_policy() method I know you can do it using the console / gcloud ...
How to remove a cloud armor secuiry policy from backend service using Python
I'm creating a few GCP cloud armor policies across multiple projects using the Python client library and attaching them to several backend services using the .set_security_policy() method I know you can do it using the console / gcloud but I need to automate this in Python I've tried the .update() method in google-c...
[ "This is for anyone who had similar issues in the future. I was originally going to call the gcloud commands through python using os.system() as @giles-roberts recommended, but then I stumbled across a proper way to to do this using the Client Libraries\nYou simply use the same .set_security_policy() to set the sec...
[ 0 ]
[]
[]
[ "google_cloud_platform", "python" ]
stackoverflow_0074349193_google_cloud_platform_python.txt
Q: WKB string to WKT, GeoJSON in Python I have a number of WKB strings, couple of examples given below: s1 = "0103000020E6100000010000000F000000BE63303EF1D551C078E289F14742454073F7B8FAD3D551C04B98F57E0F424540FC0EA22ED4D551C04ADE36890F424540ECEB53ACD5D551C07FE2CBCA0F424540D168512BD7D551C07F2DF9F80F42454043DB28ABD8D551...
WKB string to WKT, GeoJSON in Python
I have a number of WKB strings, couple of examples given below: s1 = "0103000020E6100000010000000F000000BE63303EF1D551C078E289F14742454073F7B8FAD3D551C04B98F57E0F424540FC0EA22ED4D551C04ADE36890F424540ECEB53ACD5D551C07FE2CBCA0F424540D168512BD7D551C07F2DF9F80F42454043DB28ABD8D551C0A108AD13104245406D5A632BDAD551C01D42E31A...
[ "You can use shapely for this:\nfrom shapely import wkb, wkt\ns1 = \"0103000020E6100000010000000F000000BE63303EF1D551C078E289F14742454073F7B8FAD3D551C04B98F57E0F424540FC0EA22ED4D551C04ADE36890F424540ECEB53ACD5D551C07FE2CBCA0F424540D168512BD7D551C07F2DF9F80F42454043DB28ABD8D551C0A108AD13104245406D5A632BDAD551C01D42E...
[ 1 ]
[]
[]
[ "geotrellis", "gis", "python", "shapely" ]
stackoverflow_0074398628_geotrellis_gis_python_shapely.txt
Q: Connection refused when trying to dockerize my redis cache along with flask server I have an existing web application that uses flask and redisCache for backend. My goal is to dockerize it and eventually deploy on aws lightsail but I am struggling to understand the correct approach given that I already have a popu...
Connection refused when trying to dockerize my redis cache along with flask server
I have an existing web application that uses flask and redisCache for backend. My goal is to dockerize it and eventually deploy on aws lightsail but I am struggling to understand the correct approach given that I already have a populated cache that I wish to maintain. I've managed to create a docker container for the c...
[ "If you are using a redis image in docker-compose.yml file, you must have the redis_host set to \"redis\" and not '0.0.0.0'\nThe name 'redis' is the name of the services of image 'redis:latest'\n" ]
[ 0 ]
[]
[]
[ "docker", "flask", "python", "redis" ]
stackoverflow_0073495765_docker_flask_python_redis.txt
Q: Filter out elements from list if matching one of multiple patterns I have found solutions in different languages, but not Python. Having limited experience in coding except Python and R, I can't translate them properly. I have a list of files like this: file_list1 = ['/home/qrs/sample1.csv', '/home/abc/sample1.cs...
Filter out elements from list if matching one of multiple patterns
I have found solutions in different languages, but not Python. Having limited experience in coding except Python and R, I can't translate them properly. I have a list of files like this: file_list1 = ['/home/qrs/sample1.csv', '/home/abc/sample1.csv', '/home/mno/sample13.csv', '/home/xyz/sample2.csv'] I also have a ...
[ "I would strongly recommend to use Path.parts API to check if a folder is part of a path. Also you can use any with generator expression to test the condition against multiple patterns.\n>>> from pathlib import Path\n>>> \n>>> \n>>> file_list1 = [\n... \"/home/qrs/sample1.csv\",\n... \"/home/abc/sample1.csv...
[ 2, 1 ]
[]
[]
[ "filter", "list", "python" ]
stackoverflow_0074398744_filter_list_python.txt
Q: Django ORM How to query and get values when multiple conditions are fulfilled I have following model class TimePeriod(BaseModel): product = models.ForeignKey(to=Product, on_delete=models.CASCADE) min_travel_days = models.PositiveIntegerField() max_travel_days = models.PositiveIntegerField() value =...
Django ORM How to query and get values when multiple conditions are fulfilled
I have following model class TimePeriod(BaseModel): product = models.ForeignKey(to=Product, on_delete=models.CASCADE) min_travel_days = models.PositiveIntegerField() max_travel_days = models.PositiveIntegerField() value = models.DecimalField(max_digits=19, decimal_places=10) insurance_period_min_da...
[ "I think I got the answer I was missing order by\nTimePeriod.objects.filter(is_business=True,policy__slug='silver',insurance_period_min_days__lte=91,insurance_period_max_days__gte=91,min_days__lte=30,max_days__gte=30).values('value').order_by('value').first()\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0074398043_django_django_orm_python.txt
Q: Seeing some weird behavior with a nuneric field read from a file. What's the best way to clean it up? First thought was the data field type might be 'string', but it says 'integer'. How can two different values be coexisting (2 and 2.0)? I used the 'int' function to the values, but it did not work. A: simply ad...
Seeing some weird behavior with a nuneric field read from a file. What's the best way to clean it up?
First thought was the data field type might be 'string', but it says 'integer'. How can two different values be coexisting (2 and 2.0)? I used the 'int' function to the values, but it did not work.
[ "simply add this in your script:\npd.options.display.float_format = '{:,.0f}'.format\n\n\n" ]
[ 0 ]
[]
[]
[ "format", "integer", "pandas", "python" ]
stackoverflow_0074397076_format_integer_pandas_python.txt
Q: Kivy on Windows10. How to click a button, when kivy application does not in focus? I have a simple kivy app with 3 buttons. When my kivy app is not in focus, I have to click on it once, in order to press any button. How can I click any button with only one click without activating a kivy window? #:kivy 1.10.0 can...
Kivy on Windows10. How to click a button, when kivy application does not in focus?
I have a simple kivy app with 3 buttons. When my kivy app is not in focus, I have to click on it once, in order to press any button. How can I click any button with only one click without activating a kivy window? #:kivy 1.10.0 cannot press any button, when a window is not in focus
[ "I encountered this issue recently as well. Couldn't find a solution but I did implement a workaround that worked. What I did was bound kivy.core.window.Window to on_cursor_enter to trigger a callback that brings the kivy app to foreground, gaining focus, whenever the mouse enters back into the kivy app window:\nWi...
[ 1, 0, 0 ]
[]
[]
[ "kivy", "python" ]
stackoverflow_0053337630_kivy_python.txt
Q: is there a way to check similarity between two full sentences in python? I am making a project like this one here: https://www.youtube.com/watch?v=dovB8uSUUXE&feature=youtu.be but i am facing trouble because i need to check the similarity between the sentences for example: if the user said: 'the person wear red T-...
is there a way to check similarity between two full sentences in python?
I am making a project like this one here: https://www.youtube.com/watch?v=dovB8uSUUXE&feature=youtu.be but i am facing trouble because i need to check the similarity between the sentences for example: if the user said: 'the person wear red T-shirt' instead of 'the boy wear red T-shirt' I want a method to check the simi...
[ "Most of there libraries below should be good choice for semantic similarity comparison. You can skip direct word comparison by generating word, or sentence vectors using pretrained models from these libraries.\nSentence similarity with Spacy\nRequired models must be loaded first.\nFor using en_core_web_md use pyth...
[ 42, 0 ]
[]
[]
[ "deep_learning", "nlp", "nltk", "python", "sentence_similarity" ]
stackoverflow_0065199011_deep_learning_nlp_nltk_python_sentence_similarity.txt
Q: How to save a file based on the department Python I have this data below and I am generating certificate Below is my code: import pandas as pd from PIL import Image, ImageDraw, ImageFont data = pd.read_excel('C:/Users/Documents/AUTOMATED CERT TOOL/name.list.xlsx') print(data) im = Image.open('C:/Users/Documents/...
How to save a file based on the department Python
I have this data below and I am generating certificate Below is my code: import pandas as pd from PIL import Image, ImageDraw, ImageFont data = pd.read_excel('C:/Users/Documents/AUTOMATED CERT TOOL/name.list.xlsx') print(data) im = Image.open('C:/Users/Documents/AUTOMATED CERT TOOL/cert_template.png') name_list = da...
[ "You could try something like below:\nimport pandas as pd\nfrom PIL import Image, ImageDraw, ImageFont\n\ndata = pd.read_excel('C:/Users/Documents/AUTOMATED CERT TOOL/name.list.xlsx')\nprint(data)\n\nim = Image.open('C:/Users/Documents/AUTOMATED CERT TOOL/cert_template.png')\n\nname_list = data[\"Name\"].tolist() \...
[ 0 ]
[]
[]
[ "pandas", "python", "python_imaging_library" ]
stackoverflow_0074398303_pandas_python_python_imaging_library.txt
Q: Is there an equivalent to Jest's `expect` pattern matching in Python? One of the big features of Jest is its advanced expect matchers, which allow for very finely grained matching of JS objects. // We expect an object (dict) which strictly equals the following expect(myObject).toStrictEqual({ foo: "Hello", // ...
Is there an equivalent to Jest's `expect` pattern matching in Python?
One of the big features of Jest is its advanced expect matchers, which allow for very finely grained matching of JS objects. // We expect an object (dict) which strictly equals the following expect(myObject).toStrictEqual({ foo: "Hello", // Any valid number will match for the bar property bar: expect.any(Number),...
[ "Since I haven't been able to find anything I went and implemented it myself.\nIt can be installed using pip install jestspectation and the source code is available here.\nHere is an implementation of the pattern matcher listed above, written\nusing the library.\nfrom jestspectation import (\n Any,\n FloatApp...
[ 0 ]
[]
[]
[ "pattern_matching", "python" ]
stackoverflow_0074386507_pattern_matching_python.txt
Q: Python3 ValueError: not enough values to unpack (expected 3, got 2) even when three values are assigned I'm working on a image analysis project. encountering this error and not sure hot to solve it , cuz the function 'detect_balls' returns three values but couldn't assign it to variables whre it is called out to ....
Python3 ValueError: not enough values to unpack (expected 3, got 2) even when three values are assigned
I'm working on a image analysis project. encountering this error and not sure hot to solve it , cuz the function 'detect_balls' returns three values but couldn't assign it to variables whre it is called out to . Would really appriciate your help . the code is attached below import numpy as np import cv2 import sys impo...
[ "cv2.findCountours seems to return only two values, contours and hierarchy as per the documentation. You need to remove im2 from that line.\n" ]
[ 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074399235_opencv_python.txt
Q: Deleting all files in a directory with Python I want to delete all files with the extension .bak in a directory. How can I do that in Python? A: Via os.listdir and os.remove: import os filelist = [ f for f in os.listdir(mydir) if f.endswith(".bak") ] for f in filelist: os.remove(os.path.join(mydir, f)) Usi...
Deleting all files in a directory with Python
I want to delete all files with the extension .bak in a directory. How can I do that in Python?
[ "Via os.listdir and os.remove:\nimport os\n\nfilelist = [ f for f in os.listdir(mydir) if f.endswith(\".bak\") ]\nfor f in filelist:\n os.remove(os.path.join(mydir, f))\n\nUsing only a single loop:\nfor f in os.listdir(mydir):\n if not f.endswith(\".bak\"):\n continue\n os.remove(os.path.join(mydir,...
[ 309, 26, 24, 8, 2, 1, 0 ]
[ "On Linux and macOS you can run simple command to the shell:\nsubprocess.run('rm /tmp/*.bak', shell=True)\n\n" ]
[ -2 ]
[ "file_io", "python" ]
stackoverflow_0001995373_file_io_python.txt
Q: Vertex AI size limit when predicting on custom model I made a picture classification model, trained it and deployed it using vertex AI and linked it to an endpoint. I manage to make prediction using this code : from typing import Dict, List, Union from google.cloud import aiplatform from google.protobuf import js...
Vertex AI size limit when predicting on custom model
I made a picture classification model, trained it and deployed it using vertex AI and linked it to an endpoint. I manage to make prediction using this code : from typing import Dict, List, Union from google.cloud import aiplatform from google.protobuf import json_format from google.protobuf.struct_pb2 import Value d...
[ "This is a limitation from Vertex AI model serving, there is a public feature request link which is the second most voted feature. Please vote and a comment to show such feature is important for us. I could be that Cloud Run don't have such limitation but you will loose some nice feature of Vertex AI model serving....
[ 0 ]
[]
[]
[ "deep_learning", "google_cloud_platform", "google_cloud_vertex_ai", "python" ]
stackoverflow_0074030327_deep_learning_google_cloud_platform_google_cloud_vertex_ai_python.txt