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: Sybase IQ connection in Python I've spent a few days trying to determine how to connect to a Sybase IQ database through Python 3.6. I've tried pyodbc and pymssql, to no avail. Below are two code snippets that I've been working on, which don't seem to work, no matter what I try. pyodbc: conn = pyodbc.connect(driver='{SQL Server Native Client 11.0}', server=server, database=database, port=port, uid=user, pwd=pwd) pymssql: conn = pymssql.connect(server=server, port=port, user=user, password=pwd, database=database) I've also read that FreeTds could be the solution for connecting to a Sybase IQ database; I thought it was installed as part of the pymssql database, but I can't seem to figure out how to leverage it. Any help would be greatly appreciated! EDIT: I am aware that sqlanydb exists; however, this package makes me downgrade to Python 2.7. My stack is 3.6 and I'd like to not have to move off of that. A: After some time, I was able to resolve this issue (On Windows). First, install SQL Anywhere 17 driver. Once that's been installed, in the Windows ODBC Data Sources window, set up a connection using the SQL Anywhere 17, and your Sybase IQ credentials. Once that has been configured and successfully tested, you can use the below code snippet to connect: from sqlalchemy import create_engine sybase_connection_string = "sqlalchemy_sqlany://{user}:{pwd}@{host}:{port}/{db}".\ format(user=user, pwd=pwd, host=host, port=port, db=database) engine = create_engine(sybase_connection_string) return engine.connect() I believe you will need the sqlalchemy_sqlany module installed via pip, as well as sqlalchemy. A: Alternative use jconn4 or jconn3 driver. Example of connection: import jaydebeapi jar_path = "/drive/jconn4.jar" driver_name = "com.sybase.jdbc4.jdbc.SybDriver" _ipad = '1.1.1.1' _port='2638' con_prop= { "user": 'user', "password": 'pwd'} connection_url = f"jdbc:sybase:Tds:{_ipad}:{_port}" conn= jaydebeapi.connect(driver_name, connection_url,con_prop, jar_path)
Sybase IQ connection in Python
I've spent a few days trying to determine how to connect to a Sybase IQ database through Python 3.6. I've tried pyodbc and pymssql, to no avail. Below are two code snippets that I've been working on, which don't seem to work, no matter what I try. pyodbc: conn = pyodbc.connect(driver='{SQL Server Native Client 11.0}', server=server, database=database, port=port, uid=user, pwd=pwd) pymssql: conn = pymssql.connect(server=server, port=port, user=user, password=pwd, database=database) I've also read that FreeTds could be the solution for connecting to a Sybase IQ database; I thought it was installed as part of the pymssql database, but I can't seem to figure out how to leverage it. Any help would be greatly appreciated! EDIT: I am aware that sqlanydb exists; however, this package makes me downgrade to Python 2.7. My stack is 3.6 and I'd like to not have to move off of that.
[ "After some time, I was able to resolve this issue (On Windows). First, install SQL Anywhere 17 driver. Once that's been installed, in the Windows ODBC Data Sources window, set up a connection using the SQL Anywhere 17, and your Sybase IQ credentials. Once that has been configured and successfully tested, you can use the below code snippet to connect:\nfrom sqlalchemy import create_engine\n\nsybase_connection_string = \"sqlalchemy_sqlany://{user}:{pwd}@{host}:{port}/{db}\".\\\n format(user=user, pwd=pwd, host=host, port=port, db=database)\nengine = create_engine(sybase_connection_string)\nreturn engine.connect()\n\nI believe you will need the sqlalchemy_sqlany module installed via pip, as well as sqlalchemy.\n", "Alternative use jconn4 or jconn3 driver.\nExample of connection:\nimport jaydebeapi\n\njar_path = \"/drive/jconn4.jar\"\ndriver_name = \"com.sybase.jdbc4.jdbc.SybDriver\"\n\n_ipad = '1.1.1.1'\n_port='2638'\n\ncon_prop= { \"user\": 'user', \"password\": 'pwd'}\n\nconnection_url = f\"jdbc:sybase:Tds:{_ipad}:{_port}\"\n\nconn= jaydebeapi.connect(driver_name, connection_url,con_prop, jar_path)\n\n" ]
[ 1, 0 ]
[]
[]
[ "database", "python", "python_3.x", "sap_iq", "sybase" ]
stackoverflow_0053726766_database_python_python_3.x_sap_iq_sybase.txt
Q: Iterate over pandas rows and using shift() in if statement I'm trying to iterate over a dataframe, then apply the shift() function. It gives me the error: 'numpy.int64' object has no attribute 'shift' Any simple way to do this while keeping the iteration? It should only show the last index value. import pandas as pd df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]], columns=['A', 'B', 'C']) for index, row in df.iterrows(): if row['B'].shift(1) >= 4: print(index) A: The loop approach would be to use a variable: prev = None for index, row in df.iterrows(): if prev is not None and prev >= 4: print(index) prev = row['B'] Output: 2 However, if you can, use vectorial code: out = df.index[df['B'].shift().ge(4)] # if needed to print print(*out, sep='\n') edit "If the 'previous' price is above my target level, then I want the following row to show True" df['previous_B_over_target'] = df['B'].shift().ge(4) Output: A B C previous_B_over_target 0 0 2 3 False 1 0 4 1 False 2 10 20 30 True
Iterate over pandas rows and using shift() in if statement
I'm trying to iterate over a dataframe, then apply the shift() function. It gives me the error: 'numpy.int64' object has no attribute 'shift' Any simple way to do this while keeping the iteration? It should only show the last index value. import pandas as pd df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]], columns=['A', 'B', 'C']) for index, row in df.iterrows(): if row['B'].shift(1) >= 4: print(index)
[ "The loop approach would be to use a variable:\nprev = None\nfor index, row in df.iterrows():\n if prev is not None and prev >= 4:\n print(index)\n prev = row['B']\n\nOutput:\n2\n\nHowever, if you can, use vectorial code:\nout = df.index[df['B'].shift().ge(4)]\n\n# if needed to print\nprint(*out, sep='\\n')\n\nedit\n\"If the 'previous' price is above my target level, then I want the following row to show True\"\ndf['previous_B_over_target'] = df['B'].shift().ge(4)\n\nOutput:\n A B C previous_B_over_target\n0 0 2 3 False\n1 0 4 1 False\n2 10 20 30 True\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074547789_pandas_python.txt
Q: Python: Saving result from loop to a variable I am storing specific information from an XML file to a variable. The XML file contains a lot of information, but I am just looking for something called nAtt. I am reading the XML file into a data frame: df = pd.read_xml(folder_path2 + filename6) nAtt contains either 0, 1, 2 or 3 and it looks like nAtt=" 0" So, I say nAtt = df["nAtt"].dropna().to_numpy() to save the value from the XML file to a variable called nAtt in my code. Now, I am trying to loop over nAtt to check if it is either 0, 1, 2 or 3 and depending on the result I want to set another variable called nAtt_change to a specfic value: for 0 in nAtt: nAtt_change = 0 for 1 in nAtt: nAtt_change = -6 for 2 in nAtt: nAtt_change = -10 for 3 in nAtt: nAtt_change = -20 However, I get this error message: for 0 in nAtt: ^ SyntaxError: can't assign to literal Can anyone tell me what I need to change to make this work? Thanks! A: Not entirely clear but I suppose you want to do something like this: nAtt_change = np.zeros(shape = len(nAtt)) for i in range(len(nAtt)): if nAtt[i] == 0: nAtt_change[i] = yourSpecificValue ... Change yourSPecificValue to the value you want and add other if statements for the rest of the nAtt values.
Python: Saving result from loop to a variable
I am storing specific information from an XML file to a variable. The XML file contains a lot of information, but I am just looking for something called nAtt. I am reading the XML file into a data frame: df = pd.read_xml(folder_path2 + filename6) nAtt contains either 0, 1, 2 or 3 and it looks like nAtt=" 0" So, I say nAtt = df["nAtt"].dropna().to_numpy() to save the value from the XML file to a variable called nAtt in my code. Now, I am trying to loop over nAtt to check if it is either 0, 1, 2 or 3 and depending on the result I want to set another variable called nAtt_change to a specfic value: for 0 in nAtt: nAtt_change = 0 for 1 in nAtt: nAtt_change = -6 for 2 in nAtt: nAtt_change = -10 for 3 in nAtt: nAtt_change = -20 However, I get this error message: for 0 in nAtt: ^ SyntaxError: can't assign to literal Can anyone tell me what I need to change to make this work? Thanks!
[ "Not entirely clear but I suppose you want to do something like this:\nnAtt_change = np.zeros(shape = len(nAtt))\n\nfor i in range(len(nAtt)):\n if nAtt[i] == 0:\n nAtt_change[i] = yourSpecificValue\n ...\n\nChange yourSPecificValue to the value you want and add other if statements for the rest of the nAtt values.\n" ]
[ 0 ]
[]
[]
[ "loops", "python", "xml" ]
stackoverflow_0074547857_loops_python_xml.txt
Q: am performing a login with django cutsom aunt but i get qoute_from_bytes() expected bytes error The Error! TypeError at /perform_login quote_from_bytes() expected bytes Request Method: POST Request URL: http://127.0.0.1:8000/perform_login Django Version: 4.1.3 Exception Type: TypeError Exception Value: quote_from_bytes() expected bytes Exception Location: C:\Users\DND\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py, line 895, in quote_from_bytes Raised during: thena_users.views.perform_login Python Executable: C:\Users\DND\PycharmProjects\thena\venv\Scripts\python.exe Python Version: 3.10.5 Python Path: ['C:\\Users\\DND\\PycharmProjects\\thena\\thenadaka', 'C:\\Users\\DND\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\DND\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\DND\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\DND\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\DND\\PycharmProjects\\thena\\venv', 'C:\\Users\\DND\\PycharmProjects\\thena\\venv\\lib\\site-packages'] Server time: Wed, 23 Nov 2022 08:25:33 +0000**your text** Perform_login is down here! ` if request.method != 'POST': return HttpResponse('Method not allowed') else: user_mail = request.POST.get('email field') password = request.POST.get('password field') if Users.objects.filter(email = user_mail, password= password).exists(): user = Users.objects.get(email field = user_mail) request.session['user_id'] = #the user id field return redirect('templates/'where it redirects') else: messages.error(request, "username or password is incorrect") return HttpResponseRedirect(request, '#templates for login') ` I tried to login with wrong data so that i could be redirected to login page with an error message but instead got the error above A: You need to be a correct key value like this take white space in keys ... user_mail = request.POST.get('email_field') password = request.POST.get('password_field')
am performing a login with django cutsom aunt but i get qoute_from_bytes() expected bytes error
The Error! TypeError at /perform_login quote_from_bytes() expected bytes Request Method: POST Request URL: http://127.0.0.1:8000/perform_login Django Version: 4.1.3 Exception Type: TypeError Exception Value: quote_from_bytes() expected bytes Exception Location: C:\Users\DND\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py, line 895, in quote_from_bytes Raised during: thena_users.views.perform_login Python Executable: C:\Users\DND\PycharmProjects\thena\venv\Scripts\python.exe Python Version: 3.10.5 Python Path: ['C:\\Users\\DND\\PycharmProjects\\thena\\thenadaka', 'C:\\Users\\DND\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\DND\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\DND\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\DND\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\DND\\PycharmProjects\\thena\\venv', 'C:\\Users\\DND\\PycharmProjects\\thena\\venv\\lib\\site-packages'] Server time: Wed, 23 Nov 2022 08:25:33 +0000**your text** Perform_login is down here! ` if request.method != 'POST': return HttpResponse('Method not allowed') else: user_mail = request.POST.get('email field') password = request.POST.get('password field') if Users.objects.filter(email = user_mail, password= password).exists(): user = Users.objects.get(email field = user_mail) request.session['user_id'] = #the user id field return redirect('templates/'where it redirects') else: messages.error(request, "username or password is incorrect") return HttpResponseRedirect(request, '#templates for login') ` I tried to login with wrong data so that i could be redirected to login page with an error message but instead got the error above
[ "You need to be a correct key value like this take white space in keys ...\nuser_mail = request.POST.get('email_field')\npassword = request.POST.get('password_field')\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "django_templates", "django_views", "python" ]
stackoverflow_0074543858_django_django_forms_django_templates_django_views_python.txt
Q: Pandas: Grouping columns based on current index I have a pandas data frame, whose data i want to group into column groups their current column index contains the name of the group i want to group by, and i'm having a problem with extracting only that part of the name. the name of the columns is always "day_replicate". so i'm trying define a function that groups the columns into only days. what im trying to do: index |d0_1 | d0_2 | d1_1 | d1_2 | data |-----|------|------|------| add a new line based on these indexes index |d0_1 | d0_2 | d1_1 | d1_2 | day |d0 | d0 | d1 | d1 | data |-----|------|------|------| group based on df[day] def group(a: pd.DataFrame): def get_day(b: pd.DataFrame): list = [] for i in b.columns: (d, r) = i.split("_") list.append(d) return list a["day"] = [get_day(a)] a.groupby(["day"] , axis=1) return a im absolutely sure there is a lot better ways to do this, like with using a lambda function and list comprehension and stuff. I wanted to get this to work first before i try condensing it. Id really appreciate any help! Im also sure theres more errors in my code than what the error message is saying: ... File "C\...\vsstudio\msdatatry1.py", line 54, in group a["day"] = [get_day(a)] File "C:\Users\sepps\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.py", line 3977, in __setitem__ self._set_item(key, value) File "C:\Users\sepps\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.py", line 4171, in _set_item value = self._sanitize_column(value) File "C:\Users\sepps\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.py", line 4904, in _sanitize_column com.require_length_match(value, self.index) File "C:\Users\sepps\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\common.py", line 561, in require_length_match raise ValueError( ValueError: Length of values (1) does not match length of index (8709) A: You can use pandas.MultiIndex.from_arrays and str.extract: new_idx = pd.MultiIndex.from_arrays([ df.columns, df.columns.str.extract('_(\d+)', expand=False) ], names=['index', 'day']) df.columns = new_idx Before: d0_1 d0_2 d1_1 d1_2 0 NaN NaN NaN NaN After: index d0_1 d0_2 d1_1 d1_2 day 1 2 1 2 0 NaN NaN NaN NaN
Pandas: Grouping columns based on current index
I have a pandas data frame, whose data i want to group into column groups their current column index contains the name of the group i want to group by, and i'm having a problem with extracting only that part of the name. the name of the columns is always "day_replicate". so i'm trying define a function that groups the columns into only days. what im trying to do: index |d0_1 | d0_2 | d1_1 | d1_2 | data |-----|------|------|------| add a new line based on these indexes index |d0_1 | d0_2 | d1_1 | d1_2 | day |d0 | d0 | d1 | d1 | data |-----|------|------|------| group based on df[day] def group(a: pd.DataFrame): def get_day(b: pd.DataFrame): list = [] for i in b.columns: (d, r) = i.split("_") list.append(d) return list a["day"] = [get_day(a)] a.groupby(["day"] , axis=1) return a im absolutely sure there is a lot better ways to do this, like with using a lambda function and list comprehension and stuff. I wanted to get this to work first before i try condensing it. Id really appreciate any help! Im also sure theres more errors in my code than what the error message is saying: ... File "C\...\vsstudio\msdatatry1.py", line 54, in group a["day"] = [get_day(a)] File "C:\Users\sepps\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.py", line 3977, in __setitem__ self._set_item(key, value) File "C:\Users\sepps\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.py", line 4171, in _set_item value = self._sanitize_column(value) File "C:\Users\sepps\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.py", line 4904, in _sanitize_column com.require_length_match(value, self.index) File "C:\Users\sepps\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\common.py", line 561, in require_length_match raise ValueError( ValueError: Length of values (1) does not match length of index (8709)
[ "You can use pandas.MultiIndex.from_arrays and str.extract:\nnew_idx = pd.MultiIndex.from_arrays([\n df.columns,\n df.columns.str.extract('_(\\d+)', expand=False)\n], names=['index', 'day'])\n\ndf.columns = new_idx\n\nBefore:\n d0_1 d0_2 d1_1 d1_2\n0 NaN NaN NaN NaN\n\nAfter:\nindex d0_1 d0_2 d1_1 d1_2\nday 1 2 1 2\n0 NaN NaN NaN NaN\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074547923_pandas_python.txt
Q: Making each alternative word lower and upper case Ask for a string from the user and make each alternative word lower and upper case (e.g. the string “I am learning to code” would become “i AM learning TO code”). Using the split and join functions will help you here. I did a similar thing for characters in the string, but as I found out it doesn't work with full words. new_string = input("Please enter a string: ") char_storage = "" #blank string to store all the string's characters char = 1 for i in new_string: if char % 2 == 0: char_storage += i.lower() else: char_storage += i.upper() char += 1 print(char_storage) I am still quite confused about how python connects char with new_string value, if anyone has a good website where it is explained I would be very grateful. A: You can try this new_string = input("Please enter a string: ") char_storage = "" #blank string to store all the string's characters char = 1 for i in new_string.split(): if char != 1: char_storage += " " if char % 2 == 0: char_storage += i.lower() else: char_storage += i.upper() char += 1 A: You need to loop over words, not characters of a string, so split your input into words, ex. on whitespace new_string = input("Please enter a string: ").split() The Python official documentation tells you that strings are iterable objects. Iterating them gives you characters. I'd recommend separating code into functions and using str.join def change_case(x, upper): return x.upper() if upper else x.lower() char_storage = ' '.join(change_case(x, i%2!=0) for i, x in enumerate(new_string)) A: The shortest answer I can come up with would be: new_string = input("Please enter a string: ").split() char_storage = " ".join([x.upper() if i % 2 else x.lower() for i, x in enumerate(new_string)]) print(char_storage) With " ".join() you can concatenate every word in a list by a space. The argument creates a list of words in the input phrase and switches characters to upper if the modulo is not 0.
Making each alternative word lower and upper case
Ask for a string from the user and make each alternative word lower and upper case (e.g. the string “I am learning to code” would become “i AM learning TO code”). Using the split and join functions will help you here. I did a similar thing for characters in the string, but as I found out it doesn't work with full words. new_string = input("Please enter a string: ") char_storage = "" #blank string to store all the string's characters char = 1 for i in new_string: if char % 2 == 0: char_storage += i.lower() else: char_storage += i.upper() char += 1 print(char_storage) I am still quite confused about how python connects char with new_string value, if anyone has a good website where it is explained I would be very grateful.
[ "You can try this\nnew_string = input(\"Please enter a string: \")\nchar_storage = \"\" #blank string to store all the string's characters\nchar = 1\n\nfor i in new_string.split(): \n if char != 1:\n char_storage += \" \"\n if char % 2 == 0:\n char_storage += i.lower()\n else: \n char_storage += i.upper()\n char += 1\n\n", "You need to loop over words, not characters of a string, so split your input into words, ex. on whitespace\nnew_string = input(\"Please enter a string: \").split()\n\nThe Python official documentation tells you that strings are iterable objects. Iterating them gives you characters.\n\nI'd recommend separating code into functions and using str.join\ndef change_case(x, upper):\n return x.upper() if upper else x.lower()\nchar_storage = ' '.join(change_case(x, i%2!=0) for i, x in enumerate(new_string)) \n\n", "The shortest answer I can come up with would be:\nnew_string = input(\"Please enter a string: \").split()\nchar_storage = \" \".join([x.upper() if i % 2 else x.lower() for i, x in enumerate(new_string)])\nprint(char_storage)\n\nWith \" \".join() you can concatenate every word in a list by a space. The argument creates a list of words in the input phrase and switches characters to upper if the modulo is not 0.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python", "uppercase" ]
stackoverflow_0074547765_python_uppercase.txt
Q: How do I access items in an OrderedDict within an OrderedDict? I am querying Salesforce with simple_salesforce and getting the following as a result: OrderedDict([('totalSize', 1), ('done', True), ('records', [OrderedDict([('attributes', OrderedDict([('type', 'Contact'), ('url', '/services/data/v42.0/sobjects/Contact/0038')])), ('GUID', '7AFCC9D7'), ('Email', 'test@yahoo.com'), ('Contact_id', '0038')])])]) I want to access the last 5 entries (type, url, GUID, Email & Contact_id) and add them to a Pandas dataframe. How would I go about accessing those entries? A: In the specific example you provided you would access the first dictionary by dict1['records'][-1]. This works because 'records' is a key in your main dictionary and its item is a list of ordered dictionaries. You want the last item of that list, so you index by [-1].
How do I access items in an OrderedDict within an OrderedDict?
I am querying Salesforce with simple_salesforce and getting the following as a result: OrderedDict([('totalSize', 1), ('done', True), ('records', [OrderedDict([('attributes', OrderedDict([('type', 'Contact'), ('url', '/services/data/v42.0/sobjects/Contact/0038')])), ('GUID', '7AFCC9D7'), ('Email', 'test@yahoo.com'), ('Contact_id', '0038')])])]) I want to access the last 5 entries (type, url, GUID, Email & Contact_id) and add them to a Pandas dataframe. How would I go about accessing those entries?
[ "In the specific example you provided you would access the first dictionary by dict1['records'][-1]. This works because 'records' is a key in your main dictionary and its item is a list of ordered dictionaries. You want the last item of that list, so you index by [-1].\n" ]
[ 0 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074547859_dictionary_pandas_python.txt
Q: What is a "method" in Python? Can anyone, please, explain to me in very simple terms what a "method" is in Python? The thing is in many Python tutorials for beginners this word is used in such way as if the beginner already knew what a method is in the context of Python. While I am of course familiar with the general meaning of this word, I have no clue what this term means in Python. So, please, explain to me what the "Pythonian" method is all about. Some very simple example code would be very much appreciated as a picture is worth thousand words. A: It's a function which is a member of a class: class C: def my_method(self): print("I am a C") c = C() c.my_method() # Prints("I am a C") Simple as that! (There are also some alternative kinds of method, allowing you to control the relationship between the class and the function. But I'm guessing from your question that you're not asking about that, but rather just the basics.) A: A method is a function that takes a class instance as its first parameter. Methods are members of classes. class C: def method(self, possibly, other, arguments): pass # do something here As you wanted to know what it specifically means in Python, one can distinguish between bound and unbound methods. In Python, all functions (and as such also methods) are objects which can be passed around and "played with". So the difference between unbound and bound methods is: 1) Bound methods # Create an instance of C and call method() instance = C() print instance.method # prints '<bound method C.method of <__main__.C instance at 0x00FC50F8>>' instance.method(1, 2, 3) # normal method call f = instance.method f(1, 2, 3) # method call without using the variable 'instance' explicitly Bound methods are methods that belong to instances of a class. In this example, instance.method is bound to the instance called instance. Everytime that bound method is called, the instance is passed as first parameter automagically - which is called self by convention. 2) Unbound methods print C.method # prints '<unbound method C.method>' instance = C() C.method(instance, 1, 2, 3) # this call is the same as... f = C.method f(instance, 1, 2, 3) # ..this one... instance.method(1, 2, 3) # and the same as calling the bound method as you would usually do When you access C.method (the method inside a class instead of inside an instance), you get an unbound method. If you want to call it, you have to pass the instance as first parameter because the method is not bound to any instance. Knowing that difference, you can make use of functions/methods as objects, like passing methods around. As an example use case, imagine an API that lets you define a callback function, but you want to provide a method as callback function. No problem, just pass self.myCallbackMethod as the callback and it will automatically be called with the instance as first argument. This wouldn't be possible in static languages like C++ (or only with trickery). Hope you got the point ;) I think that is all you should know about method basics. You could also read more about the classmethod and staticmethod decorators, but that's another topic. A: In Python, a method is a function that is available for a given object because of the object's type. For example, if you create my_list = [1, 2, 3], the append method can be applied to my_list because it's a Python list: my_list.append(4). All lists have an append method simply because they are lists. As another example, if you create my_string = 'some lowercase text', the upper method can be applied to my_string simply because it's a Python string: my_string.upper(). Lists don't have an upper method, and strings don't have an append method. Why? Because methods only exist for a particular object if they have been explicitly defined for that type of object, and Python's developers have (so far) decided that those particular methods are not needed for those particular objects. To call a method, the format is object_name.method_name(), and any arguments to the method are listed within the parentheses. The method implicitly acts on the object being named, and thus some methods don't have any stated arguments since the object itself is the only necessary argument. For example, my_string.upper() doesn't have any listed arguments because the only required argument is the object itself, my_string. One common point of confusion regards the following: import math math.sqrt(81) Is sqrt a method of the math object? No. This is how you call the sqrt function from the math module. The format being used is module_name.function_name(), instead of object_name.method_name(). In general, the only way to distinguish between the two formats (visually) is to look in the rest of the code and see if the part before the period (math, my_list, my_string) is defined as an object or a module. A: Sorry, but--in my opinion--RichieHindle is completely right about saying that method... It's a function which is a member of a class. Here is the example of a function that becomes the member of the class. Since then it behaves as a method of the class. Let's start with the empty class and the normal function with one argument: >>> class C: ... pass ... >>> def func(self): ... print 'func called' ... >>> func('whatever') func called Now we add a member to the C class, which is the reference to the function. After that we can create the instance of the class and call its method as if it was defined inside the class: >>> C.func = func >>> o = C() >>> o.func() func called We can use also the alternative way of calling the method: >>> C.func(o) func called The o.func even manifests the same way as the class method: >>> o.func <bound method C.func of <__main__.C instance at 0x000000000229ACC8>> And we can try the reversed approach. Let's define a class and steal its method as a function: >>> class A: ... def func(self): ... print 'aaa' ... >>> a = A() >>> a.func <bound method A.func of <__main__.A instance at 0x000000000229AD08>> >>> a.func() aaa So far, it looks the same. Now the function stealing: >>> afunc = A.func >>> afunc(a) aaa The truth is that the method does not accept 'whatever' argument: >>> afunc('whatever') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method func() must be called with A instance as first argument (got str instance instead) IMHO, this is not the argument against method is a function that is a member of a class. Later found the Alex Martelli's answer that basically says the same. Sorry if you consider it duplication :) A: http://docs.python.org/2/tutorial/classes.html#method-objects Usually, a method is called right after it is bound: x.f() In the MyClass example, this will return the string 'hello world'. However, it is not necessary to call a method right away: x.f is a method object, and can be stored away and called at a later time. For example: xf = x.f while True: print xf() will continue to print hello world until the end of time. What exactly happens when a method is called? You may have noticed that x.f() was called without an argument above, even though the function definition for f() specified an argument. What happened to the argument? Surely Python raises an exception when a function that requires an argument is called without any — even if the argument isn’t actually used... Actually, you may have guessed the answer: the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument. If you still don’t understand how methods work, a look at the implementation can perhaps clarify matters. When an instance attribute is referenced that isn’t a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list. A: If you think of an object as being similar to a noun, then a method is similar to a verb. Use a method right after an object (i.e. a string or a list) to apply a method's action to it. A: To understand methods you must first think in terms of object oriented programming: Let's take a car as a a class. All cars have things in common and things that make them unique, for example all cars have 4 wheels, doors, a steering wheel.... but Your individual car (Lets call it, my_toyota) is red, goes from 0-60 in 5.6s Further the car is currently located at my house, the doors are locked, the trunk is empty... All those are properties of the instance of my_toyota. your_honda might be on the road, trunk full of groceries ... However there are things you can do with the car. You can drive it, you can open the door, you can load it. Those things you can do with a car are methods of the car, and they change a properties of the specific instance. as pseudo code you would do: my_toyota.drive(shop) to change the location from my home to the shop or my_toyota.load([milk, butter, bread] by this the trunk is now loaded with [milk, butter, bread]. As such a method is practically a function that acts as part of the object: class Car(vehicle) n_wheels = 4 load(self, stuff): '''this is a method, to load stuff into the trunk of the car''' self.open_trunk self.trunk.append(stuff) self.close_trunk the code then would be: my_toyota = Car(red) my_shopping = [milk, butter, bread] my_toyota.load(my_shopping) A: A method is a function that ‘belongs’ to an object and has a specific name: obj.methodname where obj is some object (this may be an expression), and methodname is the name of a method that is defined by the object’s type. It is worth of noting: we call method like any other function. More can be found in python tutorial. A: The python doc explains about a method as shown below: ... A method is a function that “belongs to” an object. (In Python, the term method is not unique to class instances: other object types can have methods as well. For example, list objects have methods called append, insert, remove, sort, and so on. ... And, the python doc also explains about a function as shown below: A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body. ... And, the python doc also explains about an object as shown below: Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann’s model of a “stored program computer”, code is also represented by objects.) Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is’ operator compares the identity of two objects; the id() function returns an integer representing its identity.
What is a "method" in Python?
Can anyone, please, explain to me in very simple terms what a "method" is in Python? The thing is in many Python tutorials for beginners this word is used in such way as if the beginner already knew what a method is in the context of Python. While I am of course familiar with the general meaning of this word, I have no clue what this term means in Python. So, please, explain to me what the "Pythonian" method is all about. Some very simple example code would be very much appreciated as a picture is worth thousand words.
[ "It's a function which is a member of a class:\nclass C:\n def my_method(self):\n print(\"I am a C\")\n\nc = C()\nc.my_method() # Prints(\"I am a C\")\n\nSimple as that!\n(There are also some alternative kinds of method, allowing you to control the relationship between the class and the function. But I'm guessing from your question that you're not asking about that, but rather just the basics.)\n", "A method is a function that takes a class instance as its first parameter. Methods are members of classes.\nclass C:\n def method(self, possibly, other, arguments):\n pass # do something here\n\nAs you wanted to know what it specifically means in Python, one can distinguish between bound and unbound methods. In Python, all functions (and as such also methods) are objects which can be passed around and \"played with\". So the difference between unbound and bound methods is:\n1) Bound methods\n# Create an instance of C and call method()\ninstance = C()\n\nprint instance.method # prints '<bound method C.method of <__main__.C instance at 0x00FC50F8>>'\ninstance.method(1, 2, 3) # normal method call\n\nf = instance.method\nf(1, 2, 3) # method call without using the variable 'instance' explicitly\n\nBound methods are methods that belong to instances of a class. In this example, instance.method is bound to the instance called instance. Everytime that bound method is called, the instance is passed as first parameter automagically - which is called self by convention.\n2) Unbound methods\nprint C.method # prints '<unbound method C.method>'\ninstance = C()\nC.method(instance, 1, 2, 3) # this call is the same as...\nf = C.method\nf(instance, 1, 2, 3) # ..this one...\n\ninstance.method(1, 2, 3) # and the same as calling the bound method as you would usually do\n\nWhen you access C.method (the method inside a class instead of inside an instance), you get an unbound method. If you want to call it, you have to pass the instance as first parameter because the method is not bound to any instance.\nKnowing that difference, you can make use of functions/methods as objects, like passing methods around. As an example use case, imagine an API that lets you define a callback function, but you want to provide a method as callback function. No problem, just pass self.myCallbackMethod as the callback and it will automatically be called with the instance as first argument. This wouldn't be possible in static languages like C++ (or only with trickery).\nHope you got the point ;) I think that is all you should know about method basics. You could also read more about the classmethod and staticmethod decorators, but that's another topic.\n", "In Python, a method is a function that is available for a given object because of the object's type.\nFor example, if you create my_list = [1, 2, 3], the append method can be applied to my_list because it's a Python list: my_list.append(4). All lists have an append method simply because they are lists.\nAs another example, if you create my_string = 'some lowercase text', the upper method can be applied to my_string simply because it's a Python string: my_string.upper().\nLists don't have an upper method, and strings don't have an append method. Why? Because methods only exist for a particular object if they have been explicitly defined for that type of object, and Python's developers have (so far) decided that those particular methods are not needed for those particular objects.\nTo call a method, the format is object_name.method_name(), and any arguments to the method are listed within the parentheses. The method implicitly acts on the object being named, and thus some methods don't have any stated arguments since the object itself is the only necessary argument. For example, my_string.upper() doesn't have any listed arguments because the only required argument is the object itself, my_string.\nOne common point of confusion regards the following:\nimport math\nmath.sqrt(81)\n\nIs sqrt a method of the math object? No. This is how you call the sqrt function from the math module. The format being used is module_name.function_name(), instead of object_name.method_name(). In general, the only way to distinguish between the two formats (visually) is to look in the rest of the code and see if the part before the period (math, my_list, my_string) is defined as an object or a module.\n", "Sorry, but--in my opinion--RichieHindle is completely right about saying that method...\n\nIt's a function which is a member of a class.\n\nHere is the example of a function that becomes the member of the class. Since then it behaves as a method of the class. Let's start with the empty class and the normal function with one argument:\n>>> class C:\n... pass\n...\n>>> def func(self):\n... print 'func called'\n...\n>>> func('whatever')\nfunc called\n\nNow we add a member to the C class, which is the reference to the function. After that we can create the instance of the class and call its method as if it was defined inside the class:\n>>> C.func = func\n>>> o = C()\n>>> o.func()\nfunc called\n\nWe can use also the alternative way of calling the method:\n>>> C.func(o)\nfunc called\n\nThe o.func even manifests the same way as the class method:\n>>> o.func\n<bound method C.func of <__main__.C instance at 0x000000000229ACC8>>\n\nAnd we can try the reversed approach. Let's define a class and steal its method as a function:\n>>> class A:\n... def func(self):\n... print 'aaa'\n...\n>>> a = A()\n>>> a.func\n<bound method A.func of <__main__.A instance at 0x000000000229AD08>>\n>>> a.func()\naaa\n\nSo far, it looks the same. Now the function stealing:\n>>> afunc = A.func\n>>> afunc(a)\naaa \n\nThe truth is that the method does not accept 'whatever' argument:\n>>> afunc('whatever')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: unbound method func() must be called with A instance as first \n argument (got str instance instead)\n\nIMHO, this is not the argument against method is a function that is a member of a class.\nLater found the Alex Martelli's answer that basically says the same. Sorry if you consider it duplication :)\n", "http://docs.python.org/2/tutorial/classes.html#method-objects\n\nUsually, a method is called right after it is bound:\nx.f()\n\nIn the MyClass example, this will return the string 'hello world'.\n However, it is not necessary to call a method right away: x.f is a\n method object, and can be stored away and called at a later time. For\n example:\nxf = x.f\nwhile True:\n print xf()\n\nwill continue to print hello world until the end of time.\nWhat exactly happens when a method is called? You may have noticed\n that x.f() was called without an argument above, even though the\n function definition for f() specified an argument. What happened to\n the argument? Surely Python raises an exception when a function that\n requires an argument is called without any — even if the argument\n isn’t actually used...\nActually, you may have guessed the answer: the special thing about\n methods is that the object is passed as the first argument of the\n function. In our example, the call x.f() is exactly equivalent to\n MyClass.f(x). In general, calling a method with a list of n arguments\n is equivalent to calling the corresponding function with an argument\n list that is created by inserting the method’s object before the first\n argument.\nIf you still don’t understand how methods work, a look at the\n implementation can perhaps clarify matters. When an instance attribute\n is referenced that isn’t a data attribute, its class is searched. If\n the name denotes a valid class attribute that is a function object, a\n method object is created by packing (pointers to) the instance object\n and the function object just found together in an abstract object:\n this is the method object. When the method object is called with an\n argument list, a new argument list is constructed from the instance\n object and the argument list, and the function object is called with\n this new argument list.\n\n", "If you think of an object as being similar to a noun, then a method is similar to a verb. Use a method right after an object (i.e. a string or a list) to apply a method's action to it.\n", "To understand methods you must first think in terms of object oriented programming:\nLet's take a car as a a class. All cars have things in common and things that make them unique, for example all cars have 4 wheels, doors, a steering wheel.... but Your individual car (Lets call it, my_toyota) is red, goes from 0-60 in 5.6s \nFurther the car is currently located at my house, the doors are locked, the trunk is empty... All those are properties of the instance of my_toyota. your_honda might be on the road, trunk full of groceries ...\nHowever there are things you can do with the car. You can drive it, you can open the door, you can load it. Those things you can do with a car are methods of the car, and they change a properties of the specific instance. \nas pseudo code you would do:\nmy_toyota.drive(shop)\n\nto change the location from my home to the shop or\nmy_toyota.load([milk, butter, bread]\n\nby this the trunk is now loaded with [milk, butter, bread]. \nAs such a method is practically a function that acts as part of the object:\nclass Car(vehicle)\n n_wheels = 4\n\n load(self, stuff):\n '''this is a method, to load stuff into the trunk of the car'''\n self.open_trunk\n self.trunk.append(stuff)\n self.close_trunk\n\nthe code then would be:\nmy_toyota = Car(red)\nmy_shopping = [milk, butter, bread]\nmy_toyota.load(my_shopping)\n\n", "A method is a function that ‘belongs’ to an object and has a specific name:\n obj.methodname\n\nwhere obj is some object (this may be an expression), and methodname is the name of a method that is defined by the object’s type.\nIt is worth of noting: we call method like any other function.\nMore can be found in python tutorial.\n", "The python doc explains about a method as shown below:\n\n... A method is a function that “belongs to” an object. (In Python, the\nterm method is not unique to class instances: other object types can\nhave methods as well. For example, list objects have methods called\nappend, insert, remove, sort, and so on. ...\n\nAnd, the python doc also explains about a function as shown below:\n\nA series of statements which returns some value to a caller. It can\nalso be passed zero or more arguments which may be used in the\nexecution of the body. ...\n\nAnd, the python doc also explains about an object as shown below:\n\nObjects are Python’s abstraction for data. All data in a Python\nprogram is represented by objects or by relations between objects. (In\na sense, and in conformance to Von Neumann’s model of a “stored\nprogram computer”, code is also represented by objects.)\nEvery object has an identity, a type and a value. An object’s identity\nnever changes once it has been created; you may think of it as the\nobject’s address in memory. The ‘is’ operator compares the identity of\ntwo objects; the id() function returns an integer representing its\nidentity.\n\n" ]
[ 91, 45, 28, 4, 0, 0, 0, 0, 0 ]
[]
[]
[ "methods", "python" ]
stackoverflow_0003786881_methods_python.txt
Q: Different results in KS-test from Scipy and statsmodels My code: from scipy import stats import statsmodels.api as sm data=[-0.032400000000000005,-0.0358,-0.035699999999999996,-0.029500000000000002,-0.0227,-0.0146,-0.0125,-0.0103,-0.0182,-0.0137,-0.021099999999999997,-0.0327,-0.0279,-0.0325,-0.0252,-0.015700000000000002,-0.0148,-0.013999999999999999,-0.0137,-0.013500000000000002,-0.0042,0.0044,0.0212,0.027999999999999997,0.036699999999999997,0.0447,0.0524,0.056100000000000004,0.0519,0.0571,0.0424,0.045899999999999996,0.0496,0.053,0.0594,0.0712,0.0949,0.09050000000000001,0.0907,0.0616,0.0235,0.011000000000000001,-0.0103,0.0075,0.018799999999999997,0.0268,0.0383,0.0392,0.0546,0.0565,0.06509999999999999,0.0681,0.0622,0.061900000000000004,0.056900000000000006,0.0583,0.0495,0.053099999999999994,0.0612,0.0572,0.0636,0.0599,0.0582,0.0559,0.051,0.0491,0.0423,0.0373,0.0331,0.0226,0.0159,0.0144,0.0072,0.0106,0.0139,0.0204,0.026600000000000002,0.0311,0.0351,0.0294,0.028399999999999998,0.0262,0.0273,0.0256,0.024700000000000003,0.009399999999999999,-0.004,-0.0087,-0.0097,-0.0008,0.0083,0.01,0.0107,0.0132,0.0112] print('scipy:') print(stats.ks_1samp(data, stats.norm.cdf)) print('statsmodels:') print(sm.stats.diagnostic.kstest_normal(data)) Result: scipy: KstestResult(statistic=0.48572091653418137, pvalue=3.628993889999382e-21) statsmodels: (0.0954414677540868, 0.039520654276486475) Statistics Kingdom confirms statsmodels' result is correct. But why would scipy yield a different result? A: These are two different tests. scipy ks_1samp is a KS test given a fully specified distribution, i.e. no estimated parameters. In the example the Null hypothesis test is that the data comes from a standard normal distribution N(0, 1) statsmodels kstest_normal is a KS test with estimated parameters. The Null hypothesis is that the data is normally distributed, i.e. comes from the distribution family with arbitrary mean and variance. This is also known as the Lilliefors test (alias in statsmodels). https://www.statsmodels.org/dev/generated/statsmodels.stats.diagnostic.kstest_normal.html The asymptotic distribution of the test statistic depends on whether the parameters are estimated or not, and so results in different p-values between the two hypothesis tests.
Different results in KS-test from Scipy and statsmodels
My code: from scipy import stats import statsmodels.api as sm data=[-0.032400000000000005,-0.0358,-0.035699999999999996,-0.029500000000000002,-0.0227,-0.0146,-0.0125,-0.0103,-0.0182,-0.0137,-0.021099999999999997,-0.0327,-0.0279,-0.0325,-0.0252,-0.015700000000000002,-0.0148,-0.013999999999999999,-0.0137,-0.013500000000000002,-0.0042,0.0044,0.0212,0.027999999999999997,0.036699999999999997,0.0447,0.0524,0.056100000000000004,0.0519,0.0571,0.0424,0.045899999999999996,0.0496,0.053,0.0594,0.0712,0.0949,0.09050000000000001,0.0907,0.0616,0.0235,0.011000000000000001,-0.0103,0.0075,0.018799999999999997,0.0268,0.0383,0.0392,0.0546,0.0565,0.06509999999999999,0.0681,0.0622,0.061900000000000004,0.056900000000000006,0.0583,0.0495,0.053099999999999994,0.0612,0.0572,0.0636,0.0599,0.0582,0.0559,0.051,0.0491,0.0423,0.0373,0.0331,0.0226,0.0159,0.0144,0.0072,0.0106,0.0139,0.0204,0.026600000000000002,0.0311,0.0351,0.0294,0.028399999999999998,0.0262,0.0273,0.0256,0.024700000000000003,0.009399999999999999,-0.004,-0.0087,-0.0097,-0.0008,0.0083,0.01,0.0107,0.0132,0.0112] print('scipy:') print(stats.ks_1samp(data, stats.norm.cdf)) print('statsmodels:') print(sm.stats.diagnostic.kstest_normal(data)) Result: scipy: KstestResult(statistic=0.48572091653418137, pvalue=3.628993889999382e-21) statsmodels: (0.0954414677540868, 0.039520654276486475) Statistics Kingdom confirms statsmodels' result is correct. But why would scipy yield a different result?
[ "These are two different tests.\nscipy ks_1samp is a KS test given a fully specified distribution, i.e. no estimated parameters. In the example the Null hypothesis test is that the data comes from a standard normal distribution N(0, 1)\nstatsmodels kstest_normal is a KS test with estimated parameters.\nThe Null hypothesis is that the data is normally distributed, i.e. comes from the distribution family with arbitrary mean and variance. This is also known as the Lilliefors test (alias in statsmodels).\nhttps://www.statsmodels.org/dev/generated/statsmodels.stats.diagnostic.kstest_normal.html\nThe asymptotic distribution of the test statistic depends on whether the parameters are estimated or not, and so results in different p-values between the two hypothesis tests.\n" ]
[ 1 ]
[]
[]
[ "python", "statistics" ]
stackoverflow_0074541655_python_statistics.txt
Q: Does customtkinter CTkButton hover has event option? I want to perform an action when a mouse hover event occurred on customtkinter ctkbutton hover. is it yet implemented? A: Per the CTkButton source code, the on_enter method is bound to the <Enter> event. This method is predominantly focused on updating the button's appearance on hover. If you want to trigger an additional callback on hover, you'll have to add another binding to the button def callback(event): # put whatever you want to do 'on hover' into this function print('Button hovered!') button = CTkButton(parent, text='Button!') # use '+' to avoid overwriting the existing binding button.bind('<Enter>', callback, add='+') button.pack()
Does customtkinter CTkButton hover has event option?
I want to perform an action when a mouse hover event occurred on customtkinter ctkbutton hover. is it yet implemented?
[ "Per the CTkButton source code, the on_enter method is bound to the <Enter> event. This method is predominantly focused on updating the button's appearance on hover. If you want to trigger an additional callback on hover, you'll have to add another binding to the button\ndef callback(event):\n # put whatever you want to do 'on hover' into this function\n print('Button hovered!')\n\n\nbutton = CTkButton(parent, text='Button!')\n# use '+' to avoid overwriting the existing binding\nbutton.bind('<Enter>', callback, add='+') \nbutton.pack()\n\n" ]
[ 3 ]
[]
[]
[ "customtkinter", "python", "tkinter" ]
stackoverflow_0074547734_customtkinter_python_tkinter.txt
Q: How to convert dataframe column which contains list of dictionary into separate columns? I have a dataframe column which looks like this: df_cost['region.localCurrency']: 0 [{'content': 'Dirham', 'languageCode': 'EN'}] 1 [{'content': 'Dirham', 'languageCode': 'EN'}] 2 [{'content': 'Dirham', 'languageCode': 'EN'}] 3 [{'content': 'Euro', 'languageCode': 'DE'}] 4 [{'content': 'Euro', 'languageCode': 'DE'}] 5 [{'content': 'Euro', 'languageCode': 'DE'}] 6 [{'content': 'Euro', 'languageCode': 'DE'}] 7 [{'content': 'Euro', 'languageCode': 'DE'}] 8 [{'content': 'Euro', 'languageCode': 'DE'}] 9 [{'content': 'Euro', 'languageCode': 'DE'}] 10 [{'content': 'Euro', 'languageCode': 'DE'}] 11 [{'content': 'Euro', 'languageCode': 'DE'}] 12 [{'content': 'Euro', 'languageCode': 'DE'}] 13 [{'content': 'Dirham', 'languageCode': 'EN'}] 14 [{'content': 'Dirham', 'languageCode': 'EN'}] 15 [{'content': 'Dirham', 'languageCode': 'EN'}] 16 [{'content': 'Euro', 'languageCode': 'DE'}] 17 [{'content': 'Euro', 'languageCode': 'DE'}] 18 [{'content': 'Euro', 'languageCode': 'DE'}] 19 [{'content': 'Euro', 'languageCode': 'DE'}] Name: region.localCurrency, dtype: object and I want to convert it, to separate the dictionary keys and values into columns. I want to add two separate columns to the initial df_cost dataframe, like 'localCurrencyContent' and 'localCurrencyCode', based on the dictionary contents of region.localCurrency. I tried to split the region.localCurrency column like: df_split=pd.DataFrame(df_cost['region.localCurrency'].apply(pd.Series), columns=['localCurrencyContent', 'localCurrencyCode']) print(df_split) but this gives me NaN values for the localCurrencyContent and localCurrencyCode, instead of 'Euro' and 'DE' for example. How could I split the column "region.localCurrency" and add the two created columns to the cost_df, initial dataframe? A: Pandas.json_normalize will probably do the job for you. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html A: Use json_normalize with convert first values by indexing: d = {'content':'localCurrencyContent','languageCode':'localCurrencyCode'} df1 = pd.json_normalize(df_cost.pop('region.localCurrency').str[0]).rename(columns=d) df = df_cost.join(df1)
How to convert dataframe column which contains list of dictionary into separate columns?
I have a dataframe column which looks like this: df_cost['region.localCurrency']: 0 [{'content': 'Dirham', 'languageCode': 'EN'}] 1 [{'content': 'Dirham', 'languageCode': 'EN'}] 2 [{'content': 'Dirham', 'languageCode': 'EN'}] 3 [{'content': 'Euro', 'languageCode': 'DE'}] 4 [{'content': 'Euro', 'languageCode': 'DE'}] 5 [{'content': 'Euro', 'languageCode': 'DE'}] 6 [{'content': 'Euro', 'languageCode': 'DE'}] 7 [{'content': 'Euro', 'languageCode': 'DE'}] 8 [{'content': 'Euro', 'languageCode': 'DE'}] 9 [{'content': 'Euro', 'languageCode': 'DE'}] 10 [{'content': 'Euro', 'languageCode': 'DE'}] 11 [{'content': 'Euro', 'languageCode': 'DE'}] 12 [{'content': 'Euro', 'languageCode': 'DE'}] 13 [{'content': 'Dirham', 'languageCode': 'EN'}] 14 [{'content': 'Dirham', 'languageCode': 'EN'}] 15 [{'content': 'Dirham', 'languageCode': 'EN'}] 16 [{'content': 'Euro', 'languageCode': 'DE'}] 17 [{'content': 'Euro', 'languageCode': 'DE'}] 18 [{'content': 'Euro', 'languageCode': 'DE'}] 19 [{'content': 'Euro', 'languageCode': 'DE'}] Name: region.localCurrency, dtype: object and I want to convert it, to separate the dictionary keys and values into columns. I want to add two separate columns to the initial df_cost dataframe, like 'localCurrencyContent' and 'localCurrencyCode', based on the dictionary contents of region.localCurrency. I tried to split the region.localCurrency column like: df_split=pd.DataFrame(df_cost['region.localCurrency'].apply(pd.Series), columns=['localCurrencyContent', 'localCurrencyCode']) print(df_split) but this gives me NaN values for the localCurrencyContent and localCurrencyCode, instead of 'Euro' and 'DE' for example. How could I split the column "region.localCurrency" and add the two created columns to the cost_df, initial dataframe?
[ "Pandas.json_normalize will probably do the job for you.\nhttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html\n", "Use json_normalize with convert first values by indexing:\nd = {'content':'localCurrencyContent','languageCode':'localCurrencyCode'}\ndf1 = pd.json_normalize(df_cost.pop('region.localCurrency').str[0]).rename(columns=d)\ndf = df_cost.join(df1)\n\n" ]
[ 1, 1 ]
[]
[]
[ "dataframe", "dictionary", "nested", "pandas", "python" ]
stackoverflow_0074547753_dataframe_dictionary_nested_pandas_python.txt
Q: How to fix missing port issue with GCP Cloud Function (Gen2) when deployed? I am trying to deploy a cloud function (gen2) in GCP but running into the same issue and get this error with each deploy when Cloud Functions sets up Cloud Run: The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable. MAIN.PY from google.cloud import pubsub_v1 from google.cloud import firestore import requests import json from firebase_admin import firestore import google.auth credentials, project = google.auth.default() # API INFO Base_url = 'https://xxxxxxxx.net/v1/feeds/sportsbookv2' Sport_id = 'xxxxxxxx' AppID = 'xxxxxxxx' AppKey = 'xxxxxxxx' Country = 'en_AU' Site = 'www.xxxxxxxx.com' project_id = "xxxxxxxx" subscription_id = "xxxxxxxx-basketball-nba-events" timeout = 5.0 subscriber = pubsub_v1.SubscriberClient() subscription_path = subscriber.subscription_path(project_id, subscription_id) db = firestore.Client(project='xxxxxxxx') def winodds(message: pubsub_v1.subscriber.message.Message) -> None: events = json.loads(message.data) event_ids = events['event_ids'] url = f"{Base_url}/betoffer/event/{','.join(map(str, event_ids))}.json?app_id={AppID}&app_key={AppKey}&local={Country}&site={Site}" print(url) windata = requests.get(url).text windata = json.loads(windata) for odds_data in windata['betOffers']: if odds_data['betOfferType']['name'] == 'Head to Head' and 'MAIN' in odds_data['tags']: event_id = odds_data['eventId'] home_team = odds_data['outcomes'][0]['participant'] home_team_win_odds = odds_data['outcomes'][0]['odds'] away_team = odds_data['outcomes'][1]['participant'] away_team_win_odds = odds_data['outcomes'][1]['odds'] print(f'{event_id} {home_team} {home_team_win_odds} {away_team} {away_team_win_odds}') # WRITE TO FIRESTORE doc_ref = db.collection(u'xxxxxxxx').document(u'basketball_nba').collection(u'win_odds').document(f'{event_id}') doc_ref.set({ u'event_id': event_id, u'home_team': home_team, u'home_team_win_odds': home_team_win_odds, u'away_team': away_team, u'away_team_win_odds': away_team_win_odds, u'timestamp': firestore.SERVER_TIMESTAMP, }) streaming_pull_future = subscriber.subscribe(subscription_path, callback=winodds) print(f"Listening for messages on {subscription_path}..\n") # Wrap subscriber in a 'with' block to automatically call close() when done. with subscriber: try: # When `timeout` is not set, result() will block indefinitely, # unless an exception is encountered first. streaming_pull_future.result() except TimeoutError: streaming_pull_future.cancel() # Trigger the shutdown. streaming_pull_future.result() # Block until the shutdown is complete. if __name__ == "__main__": winodds() DOCKER FILE # Use the official Python image. # https://hub.docker.com/_/python FROM python:3.10 ENV APP_HOME /app WORKDIR $APP_HOME COPY . . ENV GOOGLE_APPLICATION_CREDENTIALS /app/xxxxx-key.json ENV PORT 8080 # Install production dependencies. RUN pip install functions-framework RUN pip install -r requirements.txt # Run the web service on container startup. CMD exec functions-framework --target=winodds --debug --port=$PORT I am using PyCharm and it all seems to work locally when I run via Docker, Main.py, and Cloud Run locally. But as soon as I deploy I get an error straight away. Please can someone point me in the right direction? Where do I need to edit the ports # so my cloud function will deploy successfully? A: The above error could be caused by configuration issues for the listener port which could be some mismatches in the user defined values settings. You may check and verify the following pointers to understand the probable cause of the error and rectify these to try and eliminate the issue: Check if you configured your service to listen to all network interfaces,commonly denoted as 0.0.0.0 in Troubleshooting issues Configured the PORT following Google best practices Configured the PORT in your application as per “Deploy a Python service to Cloud Run” guide. You may check the following simple example initially to check if these are working properly. const port = parseInt(process.env.PORT) || 8080; app.listen(port, () => { console.log(`helloworld: listening on port ${port}`); });
How to fix missing port issue with GCP Cloud Function (Gen2) when deployed?
I am trying to deploy a cloud function (gen2) in GCP but running into the same issue and get this error with each deploy when Cloud Functions sets up Cloud Run: The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable. MAIN.PY from google.cloud import pubsub_v1 from google.cloud import firestore import requests import json from firebase_admin import firestore import google.auth credentials, project = google.auth.default() # API INFO Base_url = 'https://xxxxxxxx.net/v1/feeds/sportsbookv2' Sport_id = 'xxxxxxxx' AppID = 'xxxxxxxx' AppKey = 'xxxxxxxx' Country = 'en_AU' Site = 'www.xxxxxxxx.com' project_id = "xxxxxxxx" subscription_id = "xxxxxxxx-basketball-nba-events" timeout = 5.0 subscriber = pubsub_v1.SubscriberClient() subscription_path = subscriber.subscription_path(project_id, subscription_id) db = firestore.Client(project='xxxxxxxx') def winodds(message: pubsub_v1.subscriber.message.Message) -> None: events = json.loads(message.data) event_ids = events['event_ids'] url = f"{Base_url}/betoffer/event/{','.join(map(str, event_ids))}.json?app_id={AppID}&app_key={AppKey}&local={Country}&site={Site}" print(url) windata = requests.get(url).text windata = json.loads(windata) for odds_data in windata['betOffers']: if odds_data['betOfferType']['name'] == 'Head to Head' and 'MAIN' in odds_data['tags']: event_id = odds_data['eventId'] home_team = odds_data['outcomes'][0]['participant'] home_team_win_odds = odds_data['outcomes'][0]['odds'] away_team = odds_data['outcomes'][1]['participant'] away_team_win_odds = odds_data['outcomes'][1]['odds'] print(f'{event_id} {home_team} {home_team_win_odds} {away_team} {away_team_win_odds}') # WRITE TO FIRESTORE doc_ref = db.collection(u'xxxxxxxx').document(u'basketball_nba').collection(u'win_odds').document(f'{event_id}') doc_ref.set({ u'event_id': event_id, u'home_team': home_team, u'home_team_win_odds': home_team_win_odds, u'away_team': away_team, u'away_team_win_odds': away_team_win_odds, u'timestamp': firestore.SERVER_TIMESTAMP, }) streaming_pull_future = subscriber.subscribe(subscription_path, callback=winodds) print(f"Listening for messages on {subscription_path}..\n") # Wrap subscriber in a 'with' block to automatically call close() when done. with subscriber: try: # When `timeout` is not set, result() will block indefinitely, # unless an exception is encountered first. streaming_pull_future.result() except TimeoutError: streaming_pull_future.cancel() # Trigger the shutdown. streaming_pull_future.result() # Block until the shutdown is complete. if __name__ == "__main__": winodds() DOCKER FILE # Use the official Python image. # https://hub.docker.com/_/python FROM python:3.10 ENV APP_HOME /app WORKDIR $APP_HOME COPY . . ENV GOOGLE_APPLICATION_CREDENTIALS /app/xxxxx-key.json ENV PORT 8080 # Install production dependencies. RUN pip install functions-framework RUN pip install -r requirements.txt # Run the web service on container startup. CMD exec functions-framework --target=winodds --debug --port=$PORT I am using PyCharm and it all seems to work locally when I run via Docker, Main.py, and Cloud Run locally. But as soon as I deploy I get an error straight away. Please can someone point me in the right direction? Where do I need to edit the ports # so my cloud function will deploy successfully?
[ "The above error could be caused by configuration issues for the listener port which could be some mismatches in the user defined values settings.\nYou may check and verify the following pointers to understand the probable cause of the error and rectify these to try and eliminate the issue:\n\nCheck if you configured your service to listen to all network\ninterfaces,commonly denoted as 0.0.0.0 in Troubleshooting issues\nConfigured the PORT following Google best practices\nConfigured the PORT in your application as per “Deploy a Python\nservice to Cloud Run” guide.\n\nYou may check the following simple example initially to check if these are working properly.\nconst port = parseInt(process.env.PORT) || 8080;\napp.listen(port, () => {\n console.log(`helloworld: listening on port ${port}`);\n});\n\n" ]
[ 0 ]
[]
[]
[ "docker", "google_cloud_functions", "google_cloud_run", "python" ]
stackoverflow_0074541847_docker_google_cloud_functions_google_cloud_run_python.txt
Q: "bad input" after executing any git command Yesterday I just installed this script on my Macbook because I was having issues with the git credentials being stored in the keychain and after these expired I was getting error 403. I found that script that claims to periodically check for those credentials and delete them to avoid that kind of problems. The problem is that every time I do any git command, my console says: $ git pull bad input: SgSNnX3 Already up to date. As we can see, it does the git operation without problems but seems like something else is happening before executing the git command. I already uninstalled the script mentioned earlier but the annoying message still showing up. Does anyone know what can I do to stop that message? A: You can open ~/.gitconfig from any terminal you have and remove the cache and wincred helpers.
"bad input" after executing any git command
Yesterday I just installed this script on my Macbook because I was having issues with the git credentials being stored in the keychain and after these expired I was getting error 403. I found that script that claims to periodically check for those credentials and delete them to avoid that kind of problems. The problem is that every time I do any git command, my console says: $ git pull bad input: SgSNnX3 Already up to date. As we can see, it does the git operation without problems but seems like something else is happening before executing the git command. I already uninstalled the script mentioned earlier but the annoying message still showing up. Does anyone know what can I do to stop that message?
[ "You can open ~/.gitconfig from any terminal you have and remove the cache and wincred helpers.\n" ]
[ 0 ]
[]
[]
[ "bash", "git", "macos", "python" ]
stackoverflow_0066587429_bash_git_macos_python.txt
Q: Next and Before Links for a django paginated query I'm trying to make a search form for Django. Its a typical search form and then returns a table of matches. I wish to paginate the tables returned. The problem lies in the Previous and Next buttons. The links for the return query goes to /records/search/?query=a (search sample is a) The page outputs the table and its previous and next links. However the links redirect to /records/search/?page=2 and the page displays a blank table. Any help on which links I should pass for Prev/Next? search.html: {% extends 'blank.html' %} {% block content %} <div class="row"> <form id="search-form" method="get" action="."> {{ form.as_p }} <input type="submit" value="Search" /> </form> </div> <br><br> //display table code// {% if is_paginated %} <div class="pagination"> <span class="step-links"> {% if agent_list.has_previous %} <a href="?page={{ agent_list.previous_page_number }}{% for key,value in request.GET.items %}{% ifnotequal key 'page' %}&{{ key }}={{ value }}{% endifnotequal %}{% endfor %}">forrige</a> {% endif %} <span class="current"> Page {{ agent_list.number }} of {{ agent_list.paginator.num_pages }}. </span> {% if agent_list.has_next %} <a href="?page={{ agent_list.next_page_number }}">Next</a> {% endif %} </span> </div> {% endif %} {% endblock %} and the search view: def search_page(request): form = SearchForm() agents = [] show_results=False if request.GET.has_key('query'): show_results=True query=request.GET['query'].strip() if query: form=SearchForm({'query': query}) agents = \ Agent.objects.filter(Q(name__icontains=query)) paginator = Paginator(agents, 10) page = request.GET.get('page') try: agents = paginator.page(page) except PageNotAnInteger: agents = paginator.page(1) except EmptyPage: agents = paginator.page(paginator.num_pages) variables = RequestContext(request, { 'form': form, 'agent_list': agents, 'show_results': show_results, 'is_paginated': True, } ) return render_to_response('search.html', variables) I've seen the similar questions but I can't understand/make them work. Any help? Edit: For a quickfix (haven't really looked at the cons) I added a variable in my view: variables = RequestContext(request, { 'form': form, 'agent_list': agents, 'show_results': show_results, 'is_paginated': True, **'query': query,** } ) Where query without the quotes is the recieved query variable. Then simply change the URL to: <a href="**?query={{query}}**&page={{ agent_list.previous_page_number }}">Previous</a> If you have a better way of answering the question, please do or appending a URL to your currently opened URL. A: I would recommend putting the solution in a template tag like so: myapp/templatetags/mytemplatetags.py: from django import template register = template.Library() @register.simple_tag def url_replace(request, field, value): d = request.GET.copy() d[field] = value return d.urlencode() @register.simple_tag def url_delete(request, field): d = request.GET.copy() del d[field] return d.urlencode() Then from templates do: {% load mytemplatetags %} ... <a href="?{% url_replace request 'page' agent_list.previous_page_number %}">previous</a> A: The below works before and after a search form has been submitted: Views.py class PostListView(ListView): model = Post #.objects.select_related().all() template_name = 'erf24/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' # default >> erf24/post_list.html ordering = ['date_posted'] paginate_by = 3 def is_valid_queryparam(param): return param != '' and param is not None def invalid_queryparam(param): return param == '' and param is None class SearchView(ListView): model = Post #.objects.select_related().all() template_name = 'erf24/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' # default >> erf24/post_list.html ordering = ['date_posted'] paginate_by = 3 def get_queryset(self): # new key = self.request.GET.get('key') minp = self.request.GET.get('min') maxp = self.request.GET.get('max') if is_valid_queryparam(key): obj = Post.objects.filter(Q(content__icontains=key) | Q(location__icontains=key)).distinct().order_by('date_posted') if is_valid_queryparam(minp): obj = Post.objects.filter(Q(price__gte=minp)).distinct().order_by('date_posted') if is_valid_queryparam(maxp): obj = Post.objects.filter(Q(price__lte=maxp)).distinct().order_by('date_posted') if is_valid_queryparam(minp) & is_valid_queryparam(maxp): obj = Post.objects.filter(Q(price__gte=minp) & Q(price__lte=maxp)).distinct().order_by('date_posted') if is_valid_queryparam(key) & is_valid_queryparam(minp) & is_valid_queryparam(maxp): obj = Post.objects.filter(Q(content__icontains=key) | Q(location__icontains=key)).distinct() obj = obj.filter(Q(price__gte=minp) & Q(price__lte=maxp)).order_by('date_posted') if invalid_queryparam(key) & invalid_queryparam(minp) & invalid_queryparam(maxp): obj = Post.objects.all() return obj url.py urlpatterns = [ path('', PostListView.as_view(), name='erf24-home'), path('search/', SearchView.as_view(), name='erf24-search'), ] Home.html <form action="{% url 'erf24-search' %}" method="GET"> <div class="form-group"> <label for="inputAddress">Search keyword</label> <input type="text" class="form-control" id="key" name="key" placeholder="keyword"> </div> <label for="">Price</label> <div class="form-row"> <div class="form-group col-md-6"> <input type="number" class="form-control" id="min" name="min" placeholder="min price"> </div> <div class="form-group col-md-6"> <input type="number" class="form-control" id="max" name="max" placeholder="max price"> </div> </div> <button type="submit" class="btn btn-primary btn-sm mt-1 mb-1">Search</button> <button type="reset" class="btn btn-secondary btn-sm mt-1 mb-1">Clear</button> </form> {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}" alt=""> <a href="{% url 'user-posts' post.author.username %}" class="mr-2">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted }}</small> <!-- use |date: "specs" to filter date display --> </div> <h2> <a href="{% url 'post-detail' post.id %}" class="article-title">{{ post.price }}</a> </h2> <p class="article-content">{{ post.content }}</p> <p class="article-content">{{ post.location }}</p> <p><a class="like-btn" data-href="{{ post.get_api_like_url }}" href="">{{ post.likes.count }} {% if user in post.likes.all %} Unlike {% else %} Like {% endif %} </a></p> </div> {% for image in post.image_set.all %} <img class="account-img" src="{{ image.image.url }}" alt=""> {% endfor %} </article> {% endfor %} {% if is_paginated %} {% if page_obj.has_previous %} <a href="{% if request.GET.key is not None %}{{ request.get_full_path }}&{% else %}?{% endif %}page=1" class="btn btn-outline-info mb-4">First</a> <a href="{% if request.GET.key is not None %}{{ request.get_full_path }}&{% else %}?{% endif %}page={{ page_obj.previous_page_number }}" class="btn btn-outline-info mb-4">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a href="{% if request.GET.key is not None %}{{ request.get_full_path }}&{% else %}?{% endif %}page={{ num }}" class="btn btn-info mb-4">{{ num }}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <a href="{% if request.GET.key is not None %}{{ request.get_full_path }}&{% else %}?{% endif %}page={{ num }}" class="btn btn-outline-info mb-4">{{ num }}</a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a href="{% if request.GET.key is not None %}{{ request.get_full_path }}&{% else %}?{% endif %}page={{ page_obj.next_page_number }}" class="btn btn-outline-info mb-4">Next</a> <a href="{% if request.GET.key is not None %}{{ request.get_full_path }}&{% else %}?{% endif %}page={{ page_obj.paginator.num_pages }}" class="btn btn-outline-info mb-4">Last</a> {% endif %} {% endif %} Worked like a charm :) Enjoy! A: You can use {{ request.get_full_path }} template tag <a href="{{ request.get_full_path }}&page={{ agent_list.next_page_number }}">Next</a> A: you can use {{ request.get_full_path }} this tag to get current url. <a href="{{ request.get_full_path }}&page={{ agent_list.next_page_number }}">Next</a> this worked for me A: you can use this, I use it because I use filters in the url itself, so all the url params are used to build the next or previous url import re from django import template register = template.Library() PAGE_NUMBER_REGEX = re.compile(r'(page=[0-9]*[\&]*)') @register.simple_tag def append_page_param(value,pageNumber=None): ''' remove the param "page" using regex and add the one in the pageNumber if there is one ''' value = re.sub(PAGE_NUMBER_REGEX,'',value) if pageNumber: if not '?' in value: value += f'?page={pageNumber}' elif value[-1] != '&': value += f'&page={pageNumber}' else: value += f'page={pageNumber}' return value then, in your pagination nav you can call it like this: {% append_page_param request.get_full_path page_obj.previous_page_number %}
Next and Before Links for a django paginated query
I'm trying to make a search form for Django. Its a typical search form and then returns a table of matches. I wish to paginate the tables returned. The problem lies in the Previous and Next buttons. The links for the return query goes to /records/search/?query=a (search sample is a) The page outputs the table and its previous and next links. However the links redirect to /records/search/?page=2 and the page displays a blank table. Any help on which links I should pass for Prev/Next? search.html: {% extends 'blank.html' %} {% block content %} <div class="row"> <form id="search-form" method="get" action="."> {{ form.as_p }} <input type="submit" value="Search" /> </form> </div> <br><br> //display table code// {% if is_paginated %} <div class="pagination"> <span class="step-links"> {% if agent_list.has_previous %} <a href="?page={{ agent_list.previous_page_number }}{% for key,value in request.GET.items %}{% ifnotequal key 'page' %}&{{ key }}={{ value }}{% endifnotequal %}{% endfor %}">forrige</a> {% endif %} <span class="current"> Page {{ agent_list.number }} of {{ agent_list.paginator.num_pages }}. </span> {% if agent_list.has_next %} <a href="?page={{ agent_list.next_page_number }}">Next</a> {% endif %} </span> </div> {% endif %} {% endblock %} and the search view: def search_page(request): form = SearchForm() agents = [] show_results=False if request.GET.has_key('query'): show_results=True query=request.GET['query'].strip() if query: form=SearchForm({'query': query}) agents = \ Agent.objects.filter(Q(name__icontains=query)) paginator = Paginator(agents, 10) page = request.GET.get('page') try: agents = paginator.page(page) except PageNotAnInteger: agents = paginator.page(1) except EmptyPage: agents = paginator.page(paginator.num_pages) variables = RequestContext(request, { 'form': form, 'agent_list': agents, 'show_results': show_results, 'is_paginated': True, } ) return render_to_response('search.html', variables) I've seen the similar questions but I can't understand/make them work. Any help? Edit: For a quickfix (haven't really looked at the cons) I added a variable in my view: variables = RequestContext(request, { 'form': form, 'agent_list': agents, 'show_results': show_results, 'is_paginated': True, **'query': query,** } ) Where query without the quotes is the recieved query variable. Then simply change the URL to: <a href="**?query={{query}}**&page={{ agent_list.previous_page_number }}">Previous</a> If you have a better way of answering the question, please do or appending a URL to your currently opened URL.
[ "I would recommend putting the solution in a template tag like so:\nmyapp/templatetags/mytemplatetags.py:\nfrom django import template\nregister = template.Library()\n\n@register.simple_tag\ndef url_replace(request, field, value):\n d = request.GET.copy()\n d[field] = value\n return d.urlencode()\n\n@register.simple_tag\ndef url_delete(request, field):\n d = request.GET.copy()\n del d[field]\n return d.urlencode()\n\nThen from templates do:\n{% load mytemplatetags %}\n...\n<a href=\"?{% url_replace request 'page' agent_list.previous_page_number %}\">previous</a>\n\n", "The below works before and after a search form has been submitted:\nViews.py\nclass PostListView(ListView):\n model = Post #.objects.select_related().all()\n template_name = 'erf24/home.html' # <app>/<model>_<viewtype>.html\n context_object_name = 'posts' # default >> erf24/post_list.html\n ordering = ['date_posted']\n paginate_by = 3\n\ndef is_valid_queryparam(param):\n return param != '' and param is not None\ndef invalid_queryparam(param):\n return param == '' and param is None\n\nclass SearchView(ListView):\n model = Post #.objects.select_related().all()\n template_name = 'erf24/home.html' # <app>/<model>_<viewtype>.html\n context_object_name = 'posts' # default >> erf24/post_list.html\n ordering = ['date_posted']\n paginate_by = 3\n\n def get_queryset(self): # new\n key = self.request.GET.get('key')\n minp = self.request.GET.get('min')\n maxp = self.request.GET.get('max')\n\n if is_valid_queryparam(key):\n obj = Post.objects.filter(Q(content__icontains=key) | Q(location__icontains=key)).distinct().order_by('date_posted')\n\n if is_valid_queryparam(minp):\n obj = Post.objects.filter(Q(price__gte=minp)).distinct().order_by('date_posted')\n if is_valid_queryparam(maxp):\n obj = Post.objects.filter(Q(price__lte=maxp)).distinct().order_by('date_posted')\n\n if is_valid_queryparam(minp) & is_valid_queryparam(maxp):\n obj = Post.objects.filter(Q(price__gte=minp) & Q(price__lte=maxp)).distinct().order_by('date_posted')\n\n if is_valid_queryparam(key) & is_valid_queryparam(minp) & is_valid_queryparam(maxp):\n obj = Post.objects.filter(Q(content__icontains=key) | Q(location__icontains=key)).distinct()\n obj = obj.filter(Q(price__gte=minp) & Q(price__lte=maxp)).order_by('date_posted')\n\n if invalid_queryparam(key) & invalid_queryparam(minp) & invalid_queryparam(maxp):\n obj = Post.objects.all()\n\n return obj\n\nurl.py\nurlpatterns = [\n path('', PostListView.as_view(), name='erf24-home'),\n path('search/', SearchView.as_view(), name='erf24-search'),\n]\n\nHome.html\n<form action=\"{% url 'erf24-search' %}\" method=\"GET\">\n <div class=\"form-group\">\n <label for=\"inputAddress\">Search keyword</label>\n <input type=\"text\" class=\"form-control\" id=\"key\" name=\"key\" placeholder=\"keyword\">\n </div>\n\n <label for=\"\">Price</label>\n <div class=\"form-row\">\n <div class=\"form-group col-md-6\">\n <input type=\"number\" class=\"form-control\" id=\"min\" name=\"min\" placeholder=\"min price\">\n </div>\n <div class=\"form-group col-md-6\">\n <input type=\"number\" class=\"form-control\" id=\"max\" name=\"max\" placeholder=\"max price\">\n </div>\n </div>\n\n <button type=\"submit\" class=\"btn btn-primary btn-sm mt-1 mb-1\">Search</button>\n <button type=\"reset\" class=\"btn btn-secondary btn-sm mt-1 mb-1\">Clear</button>\n\n</form>\n\n{% for post in posts %}\n<article class=\"media content-section\">\n <div class=\"media-body\">\n <div class=\"article-metadata\">\n <img class=\"rounded-circle article-img\" src=\"{{ post.author.profile.image.url }}\" alt=\"\">\n <a href=\"{% url 'user-posts' post.author.username %}\" class=\"mr-2\">{{ post.author }}</a>\n <small class=\"text-muted\">{{ post.date_posted }}</small>\n <!-- use |date: \"specs\" to filter date display -->\n </div>\n <h2>\n <a href=\"{% url 'post-detail' post.id %}\" class=\"article-title\">{{ post.price }}</a>\n </h2>\n <p class=\"article-content\">{{ post.content }}</p>\n <p class=\"article-content\">{{ post.location }}</p>\n <p><a class=\"like-btn\" data-href=\"{{ post.get_api_like_url }}\" href=\"\">{{ post.likes.count }}\n {% if user in post.likes.all %} Unlike\n {% else %} Like\n {% endif %}\n </a></p>\n </div>\n {% for image in post.image_set.all %}\n <img class=\"account-img\" src=\"{{ image.image.url }}\" alt=\"\">\n {% endfor %}\n</article>\n{% endfor %}\n\n{% if is_paginated %}\n{% if page_obj.has_previous %}\n<a href=\"{% if request.GET.key is not None %}{{ request.get_full_path }}&{% else %}?{% endif %}page=1\" class=\"btn btn-outline-info mb-4\">First</a>\n<a href=\"{% if request.GET.key is not None %}{{ request.get_full_path }}&{% else %}?{% endif %}page={{ page_obj.previous_page_number }}\" class=\"btn btn-outline-info mb-4\">Previous</a>\n{% endif %}\n\n{% for num in page_obj.paginator.page_range %}\n{% if page_obj.number == num %}\n<a href=\"{% if request.GET.key is not None %}{{ request.get_full_path }}&{% else %}?{% endif %}page={{ num }}\" class=\"btn btn-info mb-4\">{{ num }}</a>\n{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}\n<a href=\"{% if request.GET.key is not None %}{{ request.get_full_path }}&{% else %}?{% endif %}page={{ num }}\" class=\"btn btn-outline-info mb-4\">{{ num }}</a>\n{% endif %}\n{% endfor %}\n\n{% if page_obj.has_next %}\n<a href=\"{% if request.GET.key is not None %}{{ request.get_full_path }}&{% else %}?{% endif %}page={{ page_obj.next_page_number }}\" class=\"btn btn-outline-info mb-4\">Next</a>\n<a href=\"{% if request.GET.key is not None %}{{ request.get_full_path }}&{% else %}?{% endif %}page={{ page_obj.paginator.num_pages }}\" class=\"btn btn-outline-info mb-4\">Last</a>\n{% endif %}\n{% endif %}\n\nWorked like a charm :) Enjoy!\n", "You can use {{ request.get_full_path }} template tag \n<a href=\"{{ request.get_full_path }}&page={{ agent_list.next_page_number }}\">Next</a>\n", "you can use {{ request.get_full_path }} this tag to get current url.\n<a href=\"{{ request.get_full_path }}&page={{ agent_list.next_page_number }}\">Next</a>\n\nthis worked for me\n", "you can use this, I use it because I use filters in the url itself, so all the url params are used to build the next or previous url\nimport re\nfrom django import template\n\nregister = template.Library()\nPAGE_NUMBER_REGEX = re.compile(r'(page=[0-9]*[\\&]*)') \n\n@register.simple_tag\ndef append_page_param(value,pageNumber=None):\n'''\nremove the param \"page\" using regex and add the one in the pageNumber if there is one\n'''\nvalue = re.sub(PAGE_NUMBER_REGEX,'',value) \nif pageNumber:\n if not '?' in value:\n value += f'?page={pageNumber}'\n elif value[-1] != '&':\n value += f'&page={pageNumber}'\n else:\n value += f'page={pageNumber}'\nreturn value\n\nthen, in your pagination nav you can call it like this:\n{% append_page_param request.get_full_path page_obj.previous_page_number %}\n\n" ]
[ 8, 2, 1, 1, 0 ]
[]
[]
[ "django", "pagination", "python" ]
stackoverflow_0022734695_django_pagination_python.txt
Q: Import issue for falcon.responders in pyinstaller executable Having an import issue when running the exe (as onefile) created by pyinstaller I added 'falcon.responders' to the list of hidden imports. But still the import error when running the executable. What can be wrong? Traceback (most recent call last): File "s2rdf.py", line 62, in <module> import morph_kgc File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "morph_kgc\__init__.py", line 16, in <module> File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "morph_kgc\engine.py", line 16, in <module> File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "morph_kgc\materializer.py", line 14, in <module> File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "falcon\__init__.py", line 32, in <module> File "falcon\app.py", line 24, in init falcon.app ImportError: cannot import name responders [16196] Failed to execute script 's2rdf' due to unhandled exception! Snippet from spec file a = Analysis( ['s2rdf.py'], pathex=[], binaries=[], datas=[], hiddenimports=['falcon.app_helpers','falcon.responders'], hookspath=[], hooksconfig={}, A: I had a similar problem, but it was fixed by removing the last generated directories ("build" and "dist") and using this hidden import list: hiddenimports=['falcon.app_helpers', 'xml.etree', 'falcon.responders', 'xml.etree.ElementTree']
Import issue for falcon.responders in pyinstaller executable
Having an import issue when running the exe (as onefile) created by pyinstaller I added 'falcon.responders' to the list of hidden imports. But still the import error when running the executable. What can be wrong? Traceback (most recent call last): File "s2rdf.py", line 62, in <module> import morph_kgc File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "morph_kgc\__init__.py", line 16, in <module> File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "morph_kgc\engine.py", line 16, in <module> File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "morph_kgc\materializer.py", line 14, in <module> File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "falcon\__init__.py", line 32, in <module> File "falcon\app.py", line 24, in init falcon.app ImportError: cannot import name responders [16196] Failed to execute script 's2rdf' due to unhandled exception! Snippet from spec file a = Analysis( ['s2rdf.py'], pathex=[], binaries=[], datas=[], hiddenimports=['falcon.app_helpers','falcon.responders'], hookspath=[], hooksconfig={},
[ "I had a similar problem, but it was fixed by removing the last generated directories (\"build\" and \"dist\") and using this hidden import list:\nhiddenimports=['falcon.app_helpers', 'xml.etree', 'falcon.responders', 'xml.etree.ElementTree']\n\n" ]
[ 0 ]
[]
[]
[ "falcon", "pyinstaller", "python" ]
stackoverflow_0073123971_falcon_pyinstaller_python.txt
Q: Tkinter look (theme) in Linux I know that Tkinter is not so modern, not so cool and maybe better to use PyQt or etc. But it is interesting for me can Tkinter look not so ugly in Ubuntu (Linux). Looks that brew version (in OS X) of python's Tkinter compiled with built-in theme and looks good: But Ubuntu's Tkinter makes me cry: I've read that for good theme I need to use ttk, but I dont know exactly how. My code looks as follow: from Tkinter import * class App(): def __init__(self, master): frame = Frame(master) frame.pack() master.title("Just my example") self.label = Label(frame, text="Type very long text:") self.entry = Entry(frame) self.button = Button(frame, text="Quit", fg="red", width=20, command=frame.quit) self.slogan = Button(frame, text="Hello", width=20, command=self.write_slogan) self.label.grid(row=0, column=0) self.entry.grid(row=0, column=1) self.slogan.grid(row=1, column=0) self.button.grid(row=1, column=1) def write_slogan(self): print "Tkinter is easy to use!" root = Tk() app = App(root) root.mainloop() How to apply standard ubuntu theme or at least better theme? Thanks. A: All available themes of ttk can be seen with such commands: $ python >>> import ttk >>> s=ttk.Style() >>> s.theme_names() ('clam', 'alt', 'default', 'classic') So you can use 'clam', 'alt', 'default', 'classic' themes with your version of Tkinter. After trying all of them I think the best one is 'clam'. You can use this one or any other in following way: from Tkinter import * from ttk import * class App(): def __init__(self, master): frame = Frame(master) frame.pack() master.title("Just my example") self.label = Label(frame, text="Type very long text:") self.entry = Entry(frame) self.button = Button(frame, text="Quit", width=15, command=frame.quit) self.slogan = Button(frame, text="Hello", width=15, command=self.write_slogan) self.label.grid(row=0, column=0) self.entry.grid(row=0, column=1) self.slogan.grid(row=1, column=0, sticky='e') self.button.grid(row=1, column=1, sticky='e') def write_slogan(self): print "Tkinter is easy to use!" root = Tk() root.style = Style() #('clam', 'alt', 'default', 'classic') root.style.theme_use("clam") app = App(root) root.mainloop() Result: OS X uses precompiled theme "aqua" so widgets are looking better. Also Ttk widgets do not support all option which pure Tkinter does. A: To use ttk you have to import it. from tkinter import * from tkinter import ttk After that you should use tkinter widgets like this-label=ttk.Label() or button = ttk.Button() A: Do not hardcode style to your app. Choice theme. Install tcl-ttkthemes, python3-ttkthemes package. Add *TkTheme: your_theme_name to ~/.Xresources. Reload X server or execute: xrdb -merge ~/.Xresources && source ~/.profile A: From documentation if you want to use ttk instead of regular Tki widgets: from Tkinter import * from ttk import * several ttk widgets (Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale and Scrollbar) will automatically substitute for the Tk widgets. You dont seem to use any other widget not covered by ttk. So this should help and enable themed ttk for you. If you want to check what themes are avaliable and how to check a theme, have a look here as well. A: ttkthemes is a module that has 25 themes available you can easily apply all the themes in a ttk widget. Install the module using following commands:- Commands:- 1.pip install ttkthemes in cmd or powershell (if in windows) 2.pip3 install ttkthemes in terminal (if in Linux) And ttkthemes module will be installed Here is an example: # example from: https://ttkthemes.readthedocs.io/en/latest/example.html from tkinter import ttk # Normal Tkinter.* widgets are not themed! from ttkthemes import ThemedTk window = ThemedTk(theme="arc")# you can set any available theme. ttk.Button(window, text="Quit", command=window.destroy).pack() window.mainloop()
Tkinter look (theme) in Linux
I know that Tkinter is not so modern, not so cool and maybe better to use PyQt or etc. But it is interesting for me can Tkinter look not so ugly in Ubuntu (Linux). Looks that brew version (in OS X) of python's Tkinter compiled with built-in theme and looks good: But Ubuntu's Tkinter makes me cry: I've read that for good theme I need to use ttk, but I dont know exactly how. My code looks as follow: from Tkinter import * class App(): def __init__(self, master): frame = Frame(master) frame.pack() master.title("Just my example") self.label = Label(frame, text="Type very long text:") self.entry = Entry(frame) self.button = Button(frame, text="Quit", fg="red", width=20, command=frame.quit) self.slogan = Button(frame, text="Hello", width=20, command=self.write_slogan) self.label.grid(row=0, column=0) self.entry.grid(row=0, column=1) self.slogan.grid(row=1, column=0) self.button.grid(row=1, column=1) def write_slogan(self): print "Tkinter is easy to use!" root = Tk() app = App(root) root.mainloop() How to apply standard ubuntu theme or at least better theme? Thanks.
[ "All available themes of ttk can be seen with such commands:\n$ python\n>>> import ttk\n>>> s=ttk.Style()\n>>> s.theme_names()\n('clam', 'alt', 'default', 'classic')\n\nSo you can use 'clam', 'alt', 'default', 'classic' themes with your version of Tkinter.\nAfter trying all of them I think the best one is 'clam'. You can use this one or any other in following way:\nfrom Tkinter import *\nfrom ttk import *\n\nclass App():\n def __init__(self, master):\n frame = Frame(master)\n frame.pack()\n\n master.title(\"Just my example\")\n self.label = Label(frame, text=\"Type very long text:\")\n\n self.entry = Entry(frame)\n\n self.button = Button(frame,\n text=\"Quit\", width=15,\n command=frame.quit)\n\n\n self.slogan = Button(frame,\n text=\"Hello\", width=15,\n command=self.write_slogan)\n\n self.label.grid(row=0, column=0)\n self.entry.grid(row=0, column=1)\n self.slogan.grid(row=1, column=0, sticky='e')\n self.button.grid(row=1, column=1, sticky='e')\n\n def write_slogan(self):\n print \"Tkinter is easy to use!\"\n\nroot = Tk()\nroot.style = Style()\n#('clam', 'alt', 'default', 'classic')\nroot.style.theme_use(\"clam\")\n\napp = App(root)\nroot.mainloop()\n\nResult:\n\nOS X uses precompiled theme \"aqua\" so widgets are looking better.\nAlso Ttk widgets do not support all option which pure Tkinter does.\n", "To use ttk you have to import it.\nfrom tkinter import *\nfrom tkinter import ttk\n\nAfter that you should use tkinter widgets like this-label=ttk.Label()\nor button = ttk.Button()\n", "Do not hardcode style to your app.\n\nChoice theme.\nInstall tcl-ttkthemes, python3-ttkthemes package.\nAdd *TkTheme: your_theme_name to ~/.Xresources.\nReload X server or execute: xrdb -merge ~/.Xresources && source ~/.profile\n\n", "From documentation if you want to use ttk instead of regular Tki widgets:\nfrom Tkinter import *\nfrom ttk import *\n\n\nseveral ttk widgets (Button, Checkbutton, Entry, Frame, Label,\n LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale and Scrollbar)\n will automatically substitute for the Tk widgets. \n\nYou dont seem to use any other widget not covered by ttk. So this should help and enable themed ttk for you. If you want to check what themes are avaliable and how to check a theme, have a look here as well.\n", "ttkthemes is a module that has 25 themes available you can easily apply all the themes in a ttk widget.\nInstall the module using following commands:-\nCommands:-\n1.pip install ttkthemes in cmd or powershell (if in windows)\n2.pip3 install ttkthemes in terminal (if in Linux)\nAnd ttkthemes module will be installed\nHere is an example:\n# example from: https://ttkthemes.readthedocs.io/en/latest/example.html\nfrom tkinter import ttk # Normal Tkinter.* widgets are not themed!\nfrom ttkthemes import ThemedTk\nwindow = ThemedTk(theme=\"arc\")# you can set any available theme. \nttk.Button(window, text=\"Quit\", command=window.destroy).pack()\nwindow.mainloop()\n\n" ]
[ 14, 1, 1, 0, 0 ]
[]
[]
[ "linux", "python", "tkinter", "ttk", "ubuntu" ]
stackoverflow_0028551948_linux_python_tkinter_ttk_ubuntu.txt
Q: Converting array in Pandas dataframe to a row I have 18x1 dataframe and all the rows of the dataframe have a an array of length 18. I want to convert the 18x1 dataframe to 18x18 dataframe by converting each array into 18 columns I am new to python, so any help would be appreciated A: If the size of the arrays is consistent, the simplest might be to convert to array, then back to DataFrame. Assuming "col" your column: import numpy as np df2 = pd.DataFrame(np.vstack(df['col'])) # or df2 = pd.DataFrame(df['col'].tolist()) Example input (5x5 only): df = pd.DataFrame({'col': [np.arange(5)]*5}) col 0 [0, 1, 2, 3, 4] 1 [0, 1, 2, 3, 4] 2 [0, 1, 2, 3, 4] 3 [0, 1, 2, 3, 4] 4 [0, 1, 2, 3, 4] Output: 0 1 2 3 4 0 0 1 2 3 4 1 0 1 2 3 4 2 0 1 2 3 4 3 0 1 2 3 4 4 0 1 2 3 4
Converting array in Pandas dataframe to a row
I have 18x1 dataframe and all the rows of the dataframe have a an array of length 18. I want to convert the 18x1 dataframe to 18x18 dataframe by converting each array into 18 columns I am new to python, so any help would be appreciated
[ "If the size of the arrays is consistent, the simplest might be to convert to array, then back to DataFrame.\nAssuming \"col\" your column:\nimport numpy as np\ndf2 = pd.DataFrame(np.vstack(df['col']))\n\n# or\ndf2 = pd.DataFrame(df['col'].tolist())\n\nExample input (5x5 only):\ndf = pd.DataFrame({'col': [np.arange(5)]*5})\n\n col\n0 [0, 1, 2, 3, 4]\n1 [0, 1, 2, 3, 4]\n2 [0, 1, 2, 3, 4]\n3 [0, 1, 2, 3, 4]\n4 [0, 1, 2, 3, 4]\n\nOutput:\n 0 1 2 3 4\n0 0 1 2 3 4\n1 0 1 2 3 4\n2 0 1 2 3 4\n3 0 1 2 3 4\n4 0 1 2 3 4\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074548152_dataframe_pandas_python.txt
Q: Pandas Create a Categorical Column After Condition I have a dataframe like this: DURATION CLUSTER COEFF 3 0 0.34 3 1 -0.005 3 2 1 3 3 0.33 4 0 -0.02 4 1 -0.28 4 2 0.22 4 3 0.48 5 0 0.65 5 1 -0.26 5 2 0.1 5 3 0.15 I want to create a RESULT categorical column according to the "COEFF" coefficients for each "DURATION". The one with the greatest "COEFF" value will be "First" and so on. Desired output like this: DURATION CLUSTER COEFF RESULT 3 0 0.34 Second 3 1 -0.005 Fourth 3 2 1 First 3 3 0.33 Third 4 0 -0.02 Third 4 1 -0.28 Fourth 4 2 0.22 Second 4 3 0.48 First 5 0 0.65 First 5 1 -0.26 Fourth 5 2 0.1 Third 5 3 0.15 Second Could you please help me about this? A: Use groupby.rank and map: labels = ['First', 'Second', 'Third', 'Fourth', 'Fifth'] df['RESULT'] = (df.groupby('DURATION')['COEFF'] .rank('dense', ascending=False).sub(1) .map(dict(enumerate(labels))) ) Output: DURATION CLUSTER COEFF RESULT 0 3 0 0.340 Second 1 3 1 -0.005 Fourth 2 3 2 1.000 First 3 3 3 0.330 Third 4 4 0 -0.020 Third 5 4 1 -0.280 Fourth 6 4 2 0.220 Second 7 4 3 0.480 First 8 5 0 0.650 First 9 5 1 -0.260 Fourth 10 5 2 0.100 Third 11 5 3 0.150 Second A: To go a bit further based on https://stackoverflow.com/a/74547858/7237062 excellent answer (I would not have found this myself that fast), I suggest using this Ordinal numbers replacement to completly automate the process. import pandas as pd # see answer https://stackoverflow.com/a/20007730/7237062, others exist # code golfed version of an "ordinal" function (int -> ordinal string in english) ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4]) # copy pasta of OP input data df = pd.read_clipboard() # let pandas read the clipboard df["RESULT"] = (df.groupby('DURATION')['COEFF'] .rank('dense', ascending=False) .sub(1) # mozway's answer so far ! .astype(int) + 1 # +1 so ordinals start at 1 (instead of 0) ).apply(ordinal) results: DURATION CLUSTER COEFF RESULT 0 3 0 0.340 2nd 1 3 1 -0.005 4th 2 3 2 1.000 1st 3 3 3 0.330 3rd 4 4 0 -0.020 3rd 5 4 1 -0.280 4th 6 4 2 0.220 2nd 7 4 3 0.480 1st 8 5 0 0.650 1st 9 5 1 -0.260 4th 10 5 2 0.100 3rd 11 5 3 0.150 2nd
Pandas Create a Categorical Column After Condition
I have a dataframe like this: DURATION CLUSTER COEFF 3 0 0.34 3 1 -0.005 3 2 1 3 3 0.33 4 0 -0.02 4 1 -0.28 4 2 0.22 4 3 0.48 5 0 0.65 5 1 -0.26 5 2 0.1 5 3 0.15 I want to create a RESULT categorical column according to the "COEFF" coefficients for each "DURATION". The one with the greatest "COEFF" value will be "First" and so on. Desired output like this: DURATION CLUSTER COEFF RESULT 3 0 0.34 Second 3 1 -0.005 Fourth 3 2 1 First 3 3 0.33 Third 4 0 -0.02 Third 4 1 -0.28 Fourth 4 2 0.22 Second 4 3 0.48 First 5 0 0.65 First 5 1 -0.26 Fourth 5 2 0.1 Third 5 3 0.15 Second Could you please help me about this?
[ "Use groupby.rank and map:\nlabels = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\ndf['RESULT'] = (df.groupby('DURATION')['COEFF']\n .rank('dense', ascending=False).sub(1)\n .map(dict(enumerate(labels)))\n )\n\nOutput:\n DURATION CLUSTER COEFF RESULT\n0 3 0 0.340 Second\n1 3 1 -0.005 Fourth\n2 3 2 1.000 First\n3 3 3 0.330 Third\n4 4 0 -0.020 Third\n5 4 1 -0.280 Fourth\n6 4 2 0.220 Second\n7 4 3 0.480 First\n8 5 0 0.650 First\n9 5 1 -0.260 Fourth\n10 5 2 0.100 Third\n11 5 3 0.150 Second\n\n", "To go a bit further based on https://stackoverflow.com/a/74547858/7237062 excellent answer (I would not have found this myself that fast), I suggest using this Ordinal numbers replacement to completly automate the process.\nimport pandas as pd\n# see answer https://stackoverflow.com/a/20007730/7237062, others exist\n# code golfed version of an \"ordinal\" function (int -> ordinal string in english)\nordinal = lambda n: \"%d%s\" % (n,\"tsnrhtdd\"[(n//10%10!=1)*(n%10<4)*n%10::4])\n# copy pasta of OP input data\ndf = pd.read_clipboard() # let pandas read the clipboard\ndf[\"RESULT\"] = (df.groupby('DURATION')['COEFF']\n .rank('dense', ascending=False)\n .sub(1) # mozway's answer so far !\n .astype(int)\n + 1 # +1 so ordinals start at 1 (instead of 0)\n ).apply(ordinal) \n\nresults:\n DURATION CLUSTER COEFF RESULT\n0 3 0 0.340 2nd\n1 3 1 -0.005 4th\n2 3 2 1.000 1st\n3 3 3 0.330 3rd\n4 4 0 -0.020 3rd\n5 4 1 -0.280 4th\n6 4 2 0.220 2nd\n7 4 3 0.480 1st\n8 5 0 0.650 1st\n9 5 1 -0.260 4th\n10 5 2 0.100 3rd\n11 5 3 0.150 2nd\n\n" ]
[ 4, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074547779_dataframe_pandas_python.txt
Q: Python Cerberus JSON schema validation I have no clue why my code doesn't work, hence looking for some help. That's my sample JSON array: [ { "bookingid": 1774 }, { "bookingid": 1020 } ] and my code is as follows: def test_get_booking_ids_correct_schema(): schema = { "type": "array", "items": { "properties": { "bookingid": { "type": "integer" } } } } response = requests.get("https://restful-booker.herokuapp.com/booking") response_body = response.json() v = Validator(schema) is_valid = v.validate(response_body) assert is_valid == True and the error I'm getting is as follows: if not self.schema_validator(test_schema, normalize=False): > raise SchemaError(self.schema_validator.errors) E cerberus.schema.SchemaError: {'items': [{'properties': ['unknown rule']}], 'type': ['must be of dict type']} Do you see any obvious mistake in my schema? On the contrary, the code below works perfectly fine: def test_temp(): schema = {"origin": {"type": "string"}} json = { "origin": "185.21.87.131" } v = Validator(schema) is_valid = v.validate(json) assert is_valid == True A: It's not possible to validate a document which is an array as root element. As you can see on : https://github.com/pyeve/cerberus/issues/220 by the way, the type array didn't exist in the Cerberus schema, you should use list instead.
Python Cerberus JSON schema validation
I have no clue why my code doesn't work, hence looking for some help. That's my sample JSON array: [ { "bookingid": 1774 }, { "bookingid": 1020 } ] and my code is as follows: def test_get_booking_ids_correct_schema(): schema = { "type": "array", "items": { "properties": { "bookingid": { "type": "integer" } } } } response = requests.get("https://restful-booker.herokuapp.com/booking") response_body = response.json() v = Validator(schema) is_valid = v.validate(response_body) assert is_valid == True and the error I'm getting is as follows: if not self.schema_validator(test_schema, normalize=False): > raise SchemaError(self.schema_validator.errors) E cerberus.schema.SchemaError: {'items': [{'properties': ['unknown rule']}], 'type': ['must be of dict type']} Do you see any obvious mistake in my schema? On the contrary, the code below works perfectly fine: def test_temp(): schema = {"origin": {"type": "string"}} json = { "origin": "185.21.87.131" } v = Validator(schema) is_valid = v.validate(json) assert is_valid == True
[ "It's not possible to validate a document which is an array as root element. As you can see on : https://github.com/pyeve/cerberus/issues/220\nby the way, the type array didn't exist in the Cerberus schema, you should use list instead.\n" ]
[ 0 ]
[]
[]
[ "cerberus", "json", "python", "schema" ]
stackoverflow_0072791379_cerberus_json_python_schema.txt
Q: VS Code Python Formatting: Change max line-length with autopep8 / yapf / black I am experimenting with different python formatters and would like to increase the max line length. Ideally without editing the settings.json file. Is there a way to achieve that? A: For all three formatters, the max line length can be increased with additional arguments passed in from settings, i.e.: autopep8 args: --max-line-length=120 black args: --line-length=120 yapf args: --style={based_on_style: google, column_limit: 120, indent_width: 4} Hope that helps someone in the future! A: @tkazik answered his own question correctly, however, I thought it would be helpful to include some references: VSCode documentation on using Python formatters: https://code.visualstudio.com/docs/python/editing#_formatting autopep8 command line options: https://pypi.org/project/autopep8/#usage Note that there is also an option to point the formatter to a global config file Additionally, if you have a local or global config file in the expected location, these preferences will be used automatically by the formatter in VSCode (https://pypi.org/project/autopep8/#configuration) black command line options: https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#command-line-options yapf command line options: https://github.com/google/yapf#usage
VS Code Python Formatting: Change max line-length with autopep8 / yapf / black
I am experimenting with different python formatters and would like to increase the max line length. Ideally without editing the settings.json file. Is there a way to achieve that?
[ "For all three formatters, the max line length can be increased with additional arguments passed in from settings, i.e.:\n\nautopep8 args: --max-line-length=120\nblack args: --line-length=120\nyapf args: --style={based_on_style: google, column_limit: 120, indent_width: 4}\n\nHope that helps someone in the future!\n\n", "@tkazik answered his own question correctly, however, I thought it would be helpful to include some references:\nVSCode documentation on using Python formatters:\nhttps://code.visualstudio.com/docs/python/editing#_formatting\nautopep8 command line options:\nhttps://pypi.org/project/autopep8/#usage\n\nNote that there is also an option to point the formatter to a global config file\nAdditionally, if you have a local or global config file in the expected location, these preferences will be used automatically by the formatter in VSCode (https://pypi.org/project/autopep8/#configuration)\n\nblack command line options:\nhttps://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#command-line-options\nyapf command line options:\nhttps://github.com/google/yapf#usage\n" ]
[ 26, 0 ]
[]
[]
[ "formatting", "python", "visual_studio_code" ]
stackoverflow_0071078751_formatting_python_visual_studio_code.txt
Q: How to display button (Tkinter) red or green when we got 0 or 1 data? I have project for read and show data from text file. import os import io work_dir = "C:\\Users\\xxxxx\\labels" for index in range(191, 221): name = "CushionOK_{index}.txt".format(index=index) path = os.path.join(work_dir, name) with io.open(path, mode="r", encoding="utf-8") as fd: content = fd.read(1) int(content) if int(content) == 1: print("OK") else: print("NG") From above code is show only OK or NG but I'd like to show button (Tkinter) red or green too. For red(NG) import tkinter as tk root2 = tk.Tk() tk.Button(root2,text='NG',font=('Helvetica bold',150), bg = "red").place( x=250, y= 250, w= 350, h= 350, anchor='center') tk.Button(root2,text='Sign in', bg = "grey").place(x=250, y= 450,w= 60, h= 30, anchor='center') root2.geometry("500x500") root2.mainloop() For Red(NG) button will push sign in button for apply private code (Ex.1234) to show other folder. and Green button(OK). import tkinter as tk root1 = tk.Tk() tk.Button(root1,text='OK',font=('Helvetica bold',150), bg = "green").place( x=250, y= 250, w= 350, h= 350, anchor='center') tk.Button(root1,text='Confirm', bg = "grey").place( x=250, y= 450,w= 60, h= 30, anchor='center') root1.geometry("500x500") root1.mainloop() For Green button will push confirm button for close it. I'd like to show button (Tkinter) red or green for represent 0 (red button) or 1 (green button). Now I can create separate code but I'd like to add all code together. A: I put all the widgets in one script as you asked for. As for me, it will work w/out using work_dir. But you can do by yourself. import tkinter as tk import os import io root = tk.Tk() def confirm(): work_dir = "C:\\Users\\xxxxx\\labels" for index in range(191, 221): name = "CushionOK_{index}.txt".format(index=index) path = os.path.join(work_dir, name) with io.open(path, mode="r", encoding="utf-8") as fd: content = fd.read(1) int(content) def quit(): root.destroy() if int(content) == 1: tk.Button(root,text='OK', font=('Helvetica bold',150), bg = "green").place(x=250, y= 250, w= 350, h= 350, anchor='center') tk.Button(root,text='Confirm', command=confirm, bg = "grey").place(x=250, y= 450,w= 60, h= 30, anchor='center') else: tk.Button(root,text='NG', font=('Helvetica bold',150), bg = "red").place(x=250, y= 250, w= 350, h= 350, anchor='center') tk.Button(root,text='Sign in', command=quit, bg = "grey").place(x=250, y= 450,w= 60, h= 30, anchor='center') root.geometry("500x500") root.mainloop()
How to display button (Tkinter) red or green when we got 0 or 1 data?
I have project for read and show data from text file. import os import io work_dir = "C:\\Users\\xxxxx\\labels" for index in range(191, 221): name = "CushionOK_{index}.txt".format(index=index) path = os.path.join(work_dir, name) with io.open(path, mode="r", encoding="utf-8") as fd: content = fd.read(1) int(content) if int(content) == 1: print("OK") else: print("NG") From above code is show only OK or NG but I'd like to show button (Tkinter) red or green too. For red(NG) import tkinter as tk root2 = tk.Tk() tk.Button(root2,text='NG',font=('Helvetica bold',150), bg = "red").place( x=250, y= 250, w= 350, h= 350, anchor='center') tk.Button(root2,text='Sign in', bg = "grey").place(x=250, y= 450,w= 60, h= 30, anchor='center') root2.geometry("500x500") root2.mainloop() For Red(NG) button will push sign in button for apply private code (Ex.1234) to show other folder. and Green button(OK). import tkinter as tk root1 = tk.Tk() tk.Button(root1,text='OK',font=('Helvetica bold',150), bg = "green").place( x=250, y= 250, w= 350, h= 350, anchor='center') tk.Button(root1,text='Confirm', bg = "grey").place( x=250, y= 450,w= 60, h= 30, anchor='center') root1.geometry("500x500") root1.mainloop() For Green button will push confirm button for close it. I'd like to show button (Tkinter) red or green for represent 0 (red button) or 1 (green button). Now I can create separate code but I'd like to add all code together.
[ "I put all the widgets in one script as you asked for. As for me, it will work w/out using work_dir. But you can do by yourself.\nimport tkinter as tk\nimport os\nimport io\n\n\nroot = tk.Tk()\n\ndef confirm():\n work_dir = \"C:\\\\Users\\\\xxxxx\\\\labels\"\n\n for index in range(191, 221):\n name = \"CushionOK_{index}.txt\".format(index=index)\n path = os.path.join(work_dir, name)\n with io.open(path, mode=\"r\", encoding=\"utf-8\") as fd:\n content = fd.read(1)\n int(content)\n \ndef quit():\n root.destroy()\n \n \n\nif int(content) == 1:\n tk.Button(root,text='OK',\n font=('Helvetica bold',150),\n bg = \"green\").place(x=250, y= 250, w= 350, h= 350, anchor='center')\n\n tk.Button(root,text='Confirm',\n command=confirm,\n bg = \"grey\").place(x=250, y= 450,w= 60, h= 30, anchor='center')\nelse:\n tk.Button(root,text='NG',\n font=('Helvetica bold',150),\n bg = \"red\").place(x=250, y= 250, w= 350, h= 350, anchor='center')\n\n tk.Button(root,text='Sign in',\n command=quit,\n bg = \"grey\").place(x=250, y= 450,w= 60, h= 30, anchor='center')\n \n\nroot.geometry(\"500x500\")\nroot.mainloop()\n\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0071691081_python_tkinter.txt
Q: PyTest: ValueError: did not yield a value I just created a pytest fixture and i can't use yield, since it gives me an error I tried different stuff without success. What i'm doing wrong? @pytest.fixture def names_resp(): with open('ropo_resp.json', 'r') as names: global data data = json.load(names) return data yield print("a") A: Your fixture is expecting to yield something, even if it's None. But your yield is unreachable since you have return before it @pytest.fixture def names_resp(): with open('ropo_resp.json', 'r') as names: data = json.load(names) yield data print("a")
PyTest: ValueError: did not yield a value
I just created a pytest fixture and i can't use yield, since it gives me an error I tried different stuff without success. What i'm doing wrong? @pytest.fixture def names_resp(): with open('ropo_resp.json', 'r') as names: global data data = json.load(names) return data yield print("a")
[ "Your fixture is expecting to yield something, even if it's None. But your yield is unreachable since you have return before it\n@pytest.fixture\ndef names_resp():\n with open('ropo_resp.json', 'r') as names:\n data = json.load(names)\n yield data\n print(\"a\")\n\n" ]
[ 1 ]
[]
[]
[ "pytest", "python", "python_3.x" ]
stackoverflow_0074548172_pytest_python_python_3.x.txt
Q: In python, how do I add a custom method to a class created by open() statement? I am trying to mock a service bus with text stream from file and want to be able to put some logic into complete_message() method. How do I define complete_message of whatever object is returned by open() so that below statement works? receiver = open('mock\mock_queue.txt', "r") receiver.complete_message() I was looking at import builtins, but this builtins.open does not seem to help. Also, I've looked at inheriting from TextIOWrapper and defining a new method, but not sure how to open a file with new wrapper class. A: Are you looking for something like this? import builtins class File(object): def __init__(self, path, *args, **kwargs): self._fobj = builtins.open(path, *args, **kwargs) def read(self, n_bytes=-1): data = self._fobj.read(n_bytes) ... return data def complete_message(self): print("Place your custom message here") return True def close(self): self._fobj.close() @contextlib.contextmanager def open(path, *args, **kwargs): try: yield File(path, *args, **kwargs) finally: pass with open('mock\mock_queue.txt', "r") as receiver: print(type(receiver.read())) receiver.complete_message()
In python, how do I add a custom method to a class created by open() statement?
I am trying to mock a service bus with text stream from file and want to be able to put some logic into complete_message() method. How do I define complete_message of whatever object is returned by open() so that below statement works? receiver = open('mock\mock_queue.txt', "r") receiver.complete_message() I was looking at import builtins, but this builtins.open does not seem to help. Also, I've looked at inheriting from TextIOWrapper and defining a new method, but not sure how to open a file with new wrapper class.
[ "Are you looking for something like this?\nimport builtins\n\n\nclass File(object):\n\n def __init__(self, path, *args, **kwargs):\n self._fobj = builtins.open(path, *args, **kwargs)\n\n def read(self, n_bytes=-1):\n data = self._fobj.read(n_bytes)\n ...\n return data\n\n def complete_message(self):\n print(\"Place your custom message here\")\n return True\n\n def close(self):\n self._fobj.close()\n\n\n@contextlib.contextmanager\ndef open(path, *args, **kwargs):\n try:\n yield File(path, *args, **kwargs)\n finally:\n pass\n\n\nwith open('mock\\mock_queue.txt', \"r\") as receiver:\n print(type(receiver.read()))\n receiver.complete_message()\n\n" ]
[ 0 ]
[]
[]
[ "python", "stream" ]
stackoverflow_0074547517_python_stream.txt
Q: How to reduce Cognitive Complexity in this Python method I am faced with a challenge. I have an Python method implemented and the SonarLint plugin of my PyCharm warns me with the message: "Refactor this function to reduce its Cognitive Complexity from 19 to the 15 allowed." but I can't see how to reduce the complexity. My Python method is: def position(key): if key == 'a': return 0 elif key == 'b': return 1 elif key == 'c': return 2 elif key == 'd': return 3 elif key == 'e': return 4 elif key == 'f': return 5 elif key == 'g': return 6 elif key == 'h': return 7 elif key == 'i': return 8 elif key == 'j': return 9 elif key == 'k': return 10 elif key == 'l': return 11 elif key == 'm': return 12 elif key == 'n': return 13 elif key == 'ñ': return 14 elif key == 'o': return 15 elif key == 'p': return 16 elif key == 'q': return 17 else: logger.info('error') And the warning of SonarLint is: And if I click on show issue locations it gives me the explanation of how the Cognitive Complexity is calculated: I can't see how to reduce the complex of this function. I know that I can implement another method with the same behaviour using things like the ascii code, but it's not the point of this question. The summary of the question is how can I follow the suggestion of SonarLint, I mean, how can I reduce the Cognitive Complexity from 19 to the 15 of this particular method. Something I've noticed is that if I remove elif statements until I have only 14 characters cases, the warning magically disappears. A: You can refactor this to look some thing like this: def position(key): values ="abcdefghijklmnñopq" try: return values.index(key) except Exception as e: print(e) #you can use logger here if you want >>> position("a") 0 >>> position("z") substring not found A: I've found what's happening. The Plugin SonarLint has a maximum number of Cognitive Complexity, as you can see in this capture: So SonarLint doesn't say you that you can simplify your method, it tells you that this method is more complex than the prefixed limit that SonarLint has setted. This is the reason because if I delete elif until I reach the magic number of 15 for the Cognitive Complexity the warning magically disappears. ¡¡WARNING!! It's not recommendable to increase the SonarLint limit of Cognitive Complexity. The most advisable option is to refactor your method and find another way to do the same. In my case I've implemented the next method instead (there are another shorter solutions, but because I have to use spanish alphabet I decided to use what for mi is the most readable solution): def position(key: str) -> (int, None): char_map = { 'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'ñ': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26 } try: output = char_map[key] except KeyError: logger.error('KeyError in position() with the key: ' + str(key)) return None return output A: What SonarLint is detecting is a "code smell" that suggests you might be able to write your code in a more efficient and understandable way. It doesn't mean it's an actual problem, just that you might want to take a closer look. That's what linters are for, after all. In this case, it's right. If I see a tower of if statements, I have to read them all to make sure the code is doing what I think it's doing. In fact, I suspect that it's doing something non-obvious because otherwise, why write it like that? (And also, it's very easy to make a mistake when writing the code, which can be very hard to find and debug.) Even using a dictionary, which would be an improvement here, can have this problem. A better way is to exploit the pattern in the data. In the following code it is easy to see that we are translating characters to integers, and that a is zero and the subsequent letters use the next numbers in sequence. You don't have to look at what each letter translates to. It is much easier to read and understand. def position(key, offset=ord("a")): pos = ord(key) - offset if 0 <= pos <= 17: return pos logger.info("error") Since code is written once but may be read many many times, it pays to optimize for readability, even (usually) over performance. Remember, other people will be reading your code... and "you in six months" counts as "other people." P.S. A possible upside of this kind of code is that if you need to figure out what number each letter translates to, or vice versa, you can see that a lot more easily than in my optimized version. If that's important to you, especially if the mapping is not obvious, using a dictionary is a better solution. A: (Edit: this approach breaks because of the "ñ" character, but I'll leave it visible in case someone wants to use the regular alphabet.) You could use ord to turn the key into a number, and enforce a valid range of keys without having to specify "abcdefghijklmnop" like some other answers suggest. Hardcoded range: def position(key:str) -> int: value = ord(key) - ord("a") if 0 <= value <= ord("p") - ord("a"): return value else: logger.info('error') Variable range with default values set to "a" and "p": def position(key:str; min_key="a", max_key="p") -> int: value = ord(key) - ord(min_key) if 0 <= value <= ord(max_key) - ord(min_key): return value else: logger.info('error')
How to reduce Cognitive Complexity in this Python method
I am faced with a challenge. I have an Python method implemented and the SonarLint plugin of my PyCharm warns me with the message: "Refactor this function to reduce its Cognitive Complexity from 19 to the 15 allowed." but I can't see how to reduce the complexity. My Python method is: def position(key): if key == 'a': return 0 elif key == 'b': return 1 elif key == 'c': return 2 elif key == 'd': return 3 elif key == 'e': return 4 elif key == 'f': return 5 elif key == 'g': return 6 elif key == 'h': return 7 elif key == 'i': return 8 elif key == 'j': return 9 elif key == 'k': return 10 elif key == 'l': return 11 elif key == 'm': return 12 elif key == 'n': return 13 elif key == 'ñ': return 14 elif key == 'o': return 15 elif key == 'p': return 16 elif key == 'q': return 17 else: logger.info('error') And the warning of SonarLint is: And if I click on show issue locations it gives me the explanation of how the Cognitive Complexity is calculated: I can't see how to reduce the complex of this function. I know that I can implement another method with the same behaviour using things like the ascii code, but it's not the point of this question. The summary of the question is how can I follow the suggestion of SonarLint, I mean, how can I reduce the Cognitive Complexity from 19 to the 15 of this particular method. Something I've noticed is that if I remove elif statements until I have only 14 characters cases, the warning magically disappears.
[ "You can refactor this to look some thing like this:\ndef position(key):\n values =\"abcdefghijklmnñopq\"\n try:\n return values.index(key)\n except Exception as e:\n print(e) #you can use logger here if you want\n\n>>> position(\"a\")\n0\n>>> position(\"z\")\nsubstring not found\n\n", "I've found what's happening. The Plugin SonarLint has a maximum number of Cognitive Complexity, as you can see in this capture:\n\nSo SonarLint doesn't say you that you can simplify your method, it tells you that this method is more complex than the prefixed limit that SonarLint has setted.\nThis is the reason because if I delete elif until I reach the magic number of 15 for the Cognitive Complexity the warning magically disappears.\n¡¡WARNING!! It's not recommendable to increase the SonarLint limit of Cognitive Complexity. The most advisable option is to refactor your method and find another way to do the same.\nIn my case I've implemented the next method instead (there are another shorter solutions, but because I have to use spanish alphabet I decided to use what for mi is the most readable solution):\n def position(key: str) -> (int, None):\n char_map = {\n 'a': 0,\n 'b': 1,\n 'c': 2,\n 'd': 3,\n 'e': 4,\n 'f': 5,\n 'g': 6,\n 'h': 7,\n 'i': 8,\n 'j': 9,\n 'k': 10,\n 'l': 11,\n 'm': 12,\n 'n': 13,\n 'ñ': 14,\n 'o': 15,\n 'p': 16,\n 'q': 17,\n 'r': 18,\n 's': 19,\n 't': 20,\n 'u': 21,\n 'v': 22,\n 'w': 23,\n 'x': 24,\n 'y': 25,\n 'z': 26\n }\n\n try:\n output = char_map[key]\n except KeyError:\n logger.error('KeyError in position() with the key: ' + str(key))\n return None\n\n return output\n\n", "What SonarLint is detecting is a \"code smell\" that suggests you might be able to write your code in a more efficient and understandable way. It doesn't mean it's an actual problem, just that you might want to take a closer look. That's what linters are for, after all.\nIn this case, it's right. If I see a tower of if statements, I have to read them all to make sure the code is doing what I think it's doing. In fact, I suspect that it's doing something non-obvious because otherwise, why write it like that? (And also, it's very easy to make a mistake when writing the code, which can be very hard to find and debug.) Even using a dictionary, which would be an improvement here, can have this problem.\nA better way is to exploit the pattern in the data. In the following code it is easy to see that we are translating characters to integers, and that a is zero and the subsequent letters use the next numbers in sequence. You don't have to look at what each letter translates to. It is much easier to read and understand.\ndef position(key, offset=ord(\"a\")):\n pos = ord(key) - offset\n if 0 <= pos <= 17:\n return pos\n logger.info(\"error\")\n\nSince code is written once but may be read many many times, it pays to optimize for readability, even (usually) over performance. Remember, other people will be reading your code... and \"you in six months\" counts as \"other people.\"\nP.S. A possible upside of this kind of code is that if you need to figure out what number each letter translates to, or vice versa, you can see that a lot more easily than in my optimized version. If that's important to you, especially if the mapping is not obvious, using a dictionary is a better solution.\n", "(Edit: this approach breaks because of the \"ñ\" character, but I'll leave it visible in case someone wants to use the regular alphabet.)\n\nYou could use ord to turn the key into a number, and enforce a valid range of keys without having to specify \"abcdefghijklmnop\" like some other answers suggest.\nHardcoded range:\n\ndef position(key:str) -> int:\n value = ord(key) - ord(\"a\")\n if 0 <= value <= ord(\"p\") - ord(\"a\"):\n return value\n else:\n logger.info('error')\n\nVariable range with default values set to \"a\" and \"p\":\ndef position(key:str; min_key=\"a\", max_key=\"p\") -> int:\n value = ord(key) - ord(min_key)\n if 0 <= value <= ord(max_key) - ord(min_key):\n return value\n else:\n logger.info('error')\n\n" ]
[ 3, 1, 1, 0 ]
[]
[]
[ "pycharm", "python", "sonarlint" ]
stackoverflow_0074547365_pycharm_python_sonarlint.txt
Q: How to run multiple Python versions on Windows I had two versions of Python installed on my machine (versions 2.6 and 2.5). I want to run 2.6 for one project and 2.5 for another. How can I specify which I want to use? I am working on Windows XP SP2. A: Running a different copy of Python is as easy as starting the correct executable. You mention that you've started a python instance, from the command line, by simply typing python. What this does under Windows, is to trawl the %PATH% environment variable, checking for an executable, either batch file (.bat), command file (.cmd) or some other executable to run (this is controlled by the PATHEXT environment variable), that matches the name given. When it finds the correct file to run the file is being run. Now, if you've installed two python versions 2.5 and 2.6, the path will have both of their directories in it, something like PATH=c:\python\2.5;c:\python\2.6 but Windows will stop examining the path when it finds a match. What you really need to do is to explicitly call one or both of the applications, such as c:\python\2.5\python.exe or c:\python\2.6\python.exe. The other alternative is to create a shortcut to the respective python.exe calling one of them python25 and the other python26; you can then simply run python25 on your command line. A: Adding two more solutions to the problem: Use pylauncher (if you have Python 3.3 or newer there's no need to install it as it comes with Python already) and either add shebang lines to your scripts; #! c:\[path to Python 2.5]\python.exe - for scripts you want to be run with Python 2.5 #! c:\[path to Python 2.6]\python.exe - for scripts you want to be run with Python 2.6 or instead of running python command run pylauncher command (py) specyfing which version of Python you want; py -2.6 – version 2.6 py -2 – latest installed version 2.x py -3.4 – version 3.4 py -3 – latest installed version 3.x Install virtualenv and create two virtualenvs; virtualenv -p c:\[path to Python 2.5]\python.exe [path where you want to have virtualenv using Python 2.5 created]\[name of virtualenv] virtualenv -p c:\[path to Python 2.6]\python.exe [path where you want to have virtualenv using Python 2.6 created]\[name of virtualenv] for example virtualenv -p c:\python2.5\python.exe c:\venvs\2.5 virtualenv -p c:\python2.6\python.exe c:\venvs\2.6 then you can activate the first and work with Python 2.5 like this c:\venvs\2.5\activate and when you want to switch to Python 2.6 you do deactivate c:\venvs\2.6\activate A: From Python 3.3 on, there is the official Python launcher for Windows (http://www.python.org/dev/peps/pep-0397/). Now, you can use the #!pythonX to determine the wanted version of the interpreter also on Windows. See more details in my another comment or read the PEP 397. Summary: The py script.py launches the Python version stated in #! or Python 2 if #! is missing. The py -3 script.py launches the Python 3. A: As per @alexander you can make a set of symbolic links like below. Put them somewhere which is included in your path so they can be easily invoked > cd c:\bin > mklink python25.exe c:\python25\python.exe > mklink python26.exe c:\python26\python.exe As long as c:\bin or where ever you placed them in is in your path you can now go > python25 A: For example for 3.6 version type py -3.6. If you have also 32bit and 64bit versions, you can just type py -3.6-64 or py -3.6-32. A: install python C:\Python27 C:\Python36 environment variable PYTHON2_HOME: C:\Python27 PYTHON3_HOME: C:\Python36 Path: %PYTHON2_HOME%;%PYTHON2_HOME%\Scripts;%PYTHON3_HOME%;%PYTHON3_HOME%\Scripts; file rename C:\Python27\python.exe → C:\Python27\python2.exe C:\Python36\python.exe → C:\Python36\python3.exe pip python2 -m pip install package python3 -m pip install package A: I strongly recommend the pyenv-win project. Thanks to kirankotari's work, now we have a Windows version of pyenv. A: One easy way for this is that you can use py -3.8 -m pip install virtualenv here -3.8 goes with your [version number] After installing the virtualenv, you can create the virtual environment of your application using py -3.8 -m virtualenv [your env name] then cd to venv, enter activate This would activate the python version you like. Just change the version number to use a different python version. A: When you install Python, it will not overwrite other installs of other major versions. So installing Python 2.5.x will not overwrite Python 2.6.x, although installing 2.6.6 will overwrite 2.6.5. So you can just install it. Then you call the Python version you want. For example: C:\Python2.5\Python.exe for Python 2.5 on windows and C:\Python2.6\Python.exe for Python 2.6 on windows, or /usr/local/bin/python-2.5 or /usr/local/bin/python-2.6 on Windows Unix (including Linux and OS X). When you install on Unix (including Linux and OS X) you will get a generic python command installed, which will be the last one you installed. This is mostly not a problem as most scripts will explicitly call /usr/local/bin/python2.5 or something just to protect against that. But if you don't want to do that, and you probably don't you can install it like this: ./configure make sudo make altinstall Note the "altinstall" that means it will install it, but it will not replace the python command. On Windows you don't get a global python command as far as I know so that's not an issue. A: Here's a quick hack: Go to the directory of the version of python you want to run Right click on python.exe Select 'Create Shortcut' Give that shortcut a name to call by( I use p27, p33 etc.) Move that shortcut to your home directory(C:\Users\Your name) Open a command prompt and enter name_of_your_shortcut.lnk(I use p27.lnk) A: cp c:\python27\bin\python.exe as python2.7.exe cp c:\python34\bin\python.exe as python3.4.exe they are all in the system path, choose the version you want to run C:\Users\username>python2.7 Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> C:\Users\username>python3.4 Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> A: The easiest way to run multiple versions of python on windows is described below as follows:- 1)Download the latest versions of python from python.org/downloads by selecting the relevant version for your system. 2)Run the installer and select Add python 3.x to the path to set path automatically in python 3 (you just have to click the checkbox). For python 2 open up your python 2 installer, select whatever preferences you want but just remember to set Add python.exe to path to Will be installed on local hard drive, Now just click next and wait for the installer to finish. 3)When both the installations are complete. Right click on my computer--Go to properties--Select advanced system settings--Go to environment variables--Click on new under System variables and add a new system variable with variable name as PY_PYTHON and set this variable value to 3. Now click on OK and you should be done. 4)Now to test this open the command prompt. Once you are in there type python or py, It should open up python3. 5)Now exit out of python3 by typing exit(). Now type py -2 it should open python 2. If none of this works then restart the computer and if the problem still persists then uninstall everything and repeat the steps. Thanks. A: This is a simple and elegant solution to easily run 2 or more different versions of python without using scripts in Windows. Whatever the version of python, it will start from the Command prompt. I have python versions 3.6.6 and 3.9. The Environment Variable paths are normal and were automatically added when each version of python was installed. It's best to install python using the "all users" option. This way the python will simply install to: C:\program files\python36 C:\program files\python39 Open each of these python folders and find the python.exe file. Copy and paste the python.exe file into those same folders. Then carefully rename the copies to: python36.exe python39.exe Open and edit Environment Variables. Add 4 new User Variables. C:\Program Files\Python36\Scripts C:\Program Files\Python36\python36.exe C:\Program Files\Python39\Scripts C:\Program Files\Program39\python39.exe Save and exit Environment Variables. Open a new Command Prompt terminal window. To run one or the other version of python, type: python36 python39 More versions of python can easily be added by repeating the same as shown above. Elegant and simple. Done. A: Using a batch file to switch, easy and efficient on windows 7. I use this: In the environment variable dialog (C:\Windows\System32\SystemPropertiesAdvanced.exe), In the section user variables added %pathpython% to the path environment variable removed any references to python pathes In the section system variables removed any references to python pathes I created batch files for every python installation (exmple for 3.4 x64 Name = SetPathPython34x64 !!! ToExecuteAsAdmin.bat ;-) just to remember. Content of the file = Set PathPython=C:\Python36AMD64\Scripts\;C:\Python36AMD64\;C:\Tcl\bin setx PathPython %PathPython% To switch between versions, I execute the batch file in admin mode. !!!!! The changes are effective for the SUBSEQUENT command prompt windows OPENED. !!! So I have exact control on it. A: let's say if we have python 3.7 and python 3.6 installed. they are respectively stored in following folder by default. C:\Users\name\AppData\Local\Programs\Python\Python36 C:\Users\name\AppData\Local\Programs\Python\Python37 if we want to use cmd prompt to install/run command in any of the above specific environment do this: There should be python.exe in each of the above folder. so when we try running any file for ex. (see image1) python hello.py. we call that respective python.exe. by default it picks lower version of file. (means in this case it will use from python 3.6 ) image so if we want to run using python3.7. just change the .exe file name. for ex. if I change to python37.exe and i want to use python3.7 to run hello.py I will use python37 hello.py . or if i want to use python3.7 by default i will change the python.exe filename in python3.6 folder to something else . so that it will use python3.7 each time when I use only python hello.py A: Shows your installed pythons py -0 Uses version of python to do something py -*version* ex. py -3.8 venv venv Will create virtual environment in python 3.8 Note: python -0 or python -3.8 doesn't work, I assume it has to be "py" A: You can create different python development environments graphically from Anaconda Navigator. I had same problem while working with different python versions so I used anaconda navigator to create different python development environments and used different python versions in each environments. Here is the help documentation for this. https://docs.anaconda.com/anaconda/navigator/tutorials/manage-environments/ A: Introduce more details based on the answer given by @Aman. Define different environment variables for different python versions. For example: You have E:\python2\python.exe and E:\python3\python.exe at the same time. Then you can set an environment variable %python2% for E:\python2\python.exe and %python2% for E:\python3\python.exe. Finally, when you want to run python2 (or python3), you can enter %python2% (or %python3%) directly in command prompt. A: Here is a solution: First, install all versions which you want to run in your pc. https://www.python.org/ Second, create virtual environment with which python version you want to use. "py [python_version] -m venv [vritual_environment_name]" example: "py -3.9 -m venv env" Note: You don't need to run "pip install virtualenv" A: You can try using py -{your version of python}. Hope this helps!!!
How to run multiple Python versions on Windows
I had two versions of Python installed on my machine (versions 2.6 and 2.5). I want to run 2.6 for one project and 2.5 for another. How can I specify which I want to use? I am working on Windows XP SP2.
[ "Running a different copy of Python is as easy as starting the correct executable. You mention that you've started a python instance, from the command line, by simply typing python. \nWhat this does under Windows, is to trawl the %PATH% environment variable, checking for an executable, either batch file (.bat), command file (.cmd) or some other executable to run (this is controlled by the PATHEXT environment variable), that matches the name given. When it finds the correct file to run the file is being run.\nNow, if you've installed two python versions 2.5 and 2.6, the path will have both of their directories in it, something like PATH=c:\\python\\2.5;c:\\python\\2.6 but Windows will stop examining the path when it finds a match.\nWhat you really need to do is to explicitly call one or both of the applications, such as c:\\python\\2.5\\python.exe or c:\\python\\2.6\\python.exe.\nThe other alternative is to create a shortcut to the respective python.exe calling one of them python25 and the other python26; you can then simply run python25 on your command line.\n", "Adding two more solutions to the problem:\n\nUse pylauncher (if you have Python 3.3 or newer there's no need to install it as it comes with Python already) and either add shebang lines to your scripts;\n\n#! c:\\[path to Python 2.5]\\python.exe - for scripts you want to be run with Python 2.5\n#! c:\\[path to Python 2.6]\\python.exe - for scripts you want to be run with Python 2.6\nor instead of running python command run pylauncher command (py) specyfing which version of Python you want;\npy -2.6 – version 2.6\npy -2 – latest installed version 2.x\npy -3.4 – version 3.4\npy -3 – latest installed version 3.x \n\nInstall virtualenv and create two virtualenvs;\n\nvirtualenv -p c:\\[path to Python 2.5]\\python.exe [path where you want to have virtualenv using Python 2.5 created]\\[name of virtualenv]\nvirtualenv -p c:\\[path to Python 2.6]\\python.exe [path where you want to have virtualenv using Python 2.6 created]\\[name of virtualenv]\nfor example\nvirtualenv -p c:\\python2.5\\python.exe c:\\venvs\\2.5\nvirtualenv -p c:\\python2.6\\python.exe c:\\venvs\\2.6\nthen you can activate the first and work with Python 2.5 like this\nc:\\venvs\\2.5\\activate\nand when you want to switch to Python 2.6 you do \ndeactivate \nc:\\venvs\\2.6\\activate\n\n", "From Python 3.3 on, there is the official Python launcher for Windows (http://www.python.org/dev/peps/pep-0397/). Now, you can use the #!pythonX to determine the wanted version of the interpreter also on Windows. See more details in my another comment or read the PEP 397.\nSummary: The py script.py launches the Python version stated in #! or Python 2 if #! is missing. The py -3 script.py launches the Python 3.\n", "As per @alexander you can make a set of symbolic links like below. Put them somewhere which is included in your path so they can be easily invoked\n> cd c:\\bin\n> mklink python25.exe c:\\python25\\python.exe\n> mklink python26.exe c:\\python26\\python.exe\n\nAs long as c:\\bin or where ever you placed them in is in your path you can now go\n> python25\n\n", "For example for 3.6 version type py -3.6. \n If you have also 32bit and 64bit versions, you can just type py -3.6-64 or py -3.6-32.\n", "\ninstall python\n\nC:\\Python27\nC:\\Python36\n\nenvironment variable\n\nPYTHON2_HOME: C:\\Python27\nPYTHON3_HOME: C:\\Python36\nPath: %PYTHON2_HOME%;%PYTHON2_HOME%\\Scripts;%PYTHON3_HOME%;%PYTHON3_HOME%\\Scripts;\n\nfile rename\n\nC:\\Python27\\python.exe → C:\\Python27\\python2.exe\nC:\\Python36\\python.exe → C:\\Python36\\python3.exe\n\npip\n\npython2 -m pip install package\npython3 -m pip install package\n\n\n", "I strongly recommend the pyenv-win project.\n\nThanks to kirankotari's work, now we have a Windows version of pyenv.\n", "One easy way for this is that you can use\npy -3.8 -m pip install virtualenv here -3.8 goes with your [version number]\nAfter installing the virtualenv, you can create the virtual environment of your application using\npy -3.8 -m virtualenv [your env name]\nthen cd to venv, enter activate\nThis would activate the python version you like.\nJust change the version number to use a different python version.\n", "When you install Python, it will not overwrite other installs of other major versions. So installing Python 2.5.x will not overwrite Python 2.6.x, although installing 2.6.6 will overwrite 2.6.5.\nSo you can just install it. Then you call the Python version you want. For example:\nC:\\Python2.5\\Python.exe\n\nfor Python 2.5 on windows and\nC:\\Python2.6\\Python.exe\n\nfor Python 2.6 on windows, or \n/usr/local/bin/python-2.5\n\nor \n/usr/local/bin/python-2.6\n\non Windows Unix (including Linux and OS X).\nWhen you install on Unix (including Linux and OS X) you will get a generic python command installed, which will be the last one you installed. This is mostly not a problem as most scripts will explicitly call /usr/local/bin/python2.5 or something just to protect against that. But if you don't want to do that, and you probably don't you can install it like this:\n./configure\nmake\nsudo make altinstall\n\nNote the \"altinstall\" that means it will install it, but it will not replace the python command.\nOn Windows you don't get a global python command as far as I know so that's not an issue.\n", "Here's a quick hack:\n\nGo to the directory of the version of python you want to run\nRight click on python.exe\nSelect 'Create Shortcut'\nGive that shortcut a name to call by( I use p27, p33 etc.)\nMove that shortcut to your home directory(C:\\Users\\Your name)\nOpen a command prompt and enter name_of_your_shortcut.lnk(I use p27.lnk)\n\n", "cp c:\\python27\\bin\\python.exe as python2.7.exe\ncp c:\\python34\\bin\\python.exe as python3.4.exe\nthey are all in the system path, choose the version you want to run\nC:\\Users\\username>python2.7\nPython 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win\n32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>>\n\nC:\\Users\\username>python3.4\nPython 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>>\n\n", "The easiest way to run multiple versions of python on windows is described below as follows:-\n1)Download the latest versions of python from python.org/downloads by selecting the relevant version for your system.\n2)Run the installer and select Add python 3.x to the path to set path automatically in python 3 (you just have to click the checkbox). For python 2 open up your python 2 installer, select whatever preferences you want but just remember to set Add python.exe to path to Will be installed on local hard drive, Now just click next and wait for the installer to finish.\n3)When both the installations are complete. Right click on my computer--Go to properties--Select advanced system settings--Go to environment variables--Click on new under System variables and add a new system variable with variable name as PY_PYTHON and set this variable value to 3. Now click on OK and you should be done.\n4)Now to test this open the command prompt. Once you are in there type python or py, It should open up python3.\n5)Now exit out of python3 by typing exit(). Now type py -2 it should open python 2.\nIf none of this works then restart the computer and if the problem still persists then uninstall everything and repeat the steps.\nThanks.\n", "This is a simple and elegant solution to easily run 2 or more different versions of python without using scripts in Windows. Whatever the version of python, it will start from the Command prompt.\nI have python versions 3.6.6 and 3.9. The Environment Variable paths are normal and were automatically added when each version of python was installed.\nIt's best to install python using the \"all users\" option. This way the python will simply install to:\nC:\\program files\\python36 \nC:\\program files\\python39\n\nOpen each of these python folders and find the python.exe file. Copy and paste the python.exe file into those same folders. Then carefully rename the copies to:\npython36.exe\npython39.exe\n\nOpen and edit Environment Variables. Add 4 new User Variables.\nC:\\Program Files\\Python36\\Scripts\nC:\\Program Files\\Python36\\python36.exe \nC:\\Program Files\\Python39\\Scripts\nC:\\Program Files\\Program39\\python39.exe \n\nSave and exit Environment Variables.\nOpen a new Command Prompt terminal window. To run one or the other version of python, type:\npython36\n\npython39\n\nMore versions of python can easily be added by repeating the same as shown above. Elegant and simple. Done.\n", "Using a batch file to switch, easy and efficient on windows 7. I use this:\nIn the environment variable dialog (C:\\Windows\\System32\\SystemPropertiesAdvanced.exe),\nIn the section user variables\n\nadded %pathpython% to the path environment variable\nremoved any references to python pathes \n\nIn the section system variables\n\nremoved any references to python pathes \n\nI created batch files for every python installation (exmple for 3.4 x64\nName = SetPathPython34x64 !!! ToExecuteAsAdmin.bat ;-) just to remember.\nContent of the file = \n Set PathPython=C:\\Python36AMD64\\Scripts\\;C:\\Python36AMD64\\;C:\\Tcl\\bin\n\n setx PathPython %PathPython%\n\nTo switch between versions, I execute the batch file in admin mode. \n!!!!! The changes are effective for the SUBSEQUENT command prompt windows OPENED. !!!\nSo I have exact control on it.\n", "let's say if we have python 3.7 and python 3.6 installed.\nthey are respectively stored in following folder by default.\nC:\\Users\\name\\AppData\\Local\\Programs\\Python\\Python36\nC:\\Users\\name\\AppData\\Local\\Programs\\Python\\Python37\nif we want to use cmd prompt to install/run command in any of the above specific environment do this:\nThere should be python.exe in each of the above folder.\nso when we try running any file for ex. (see image1) python hello.py. we call that respective python.exe. by default it picks lower version of file. (means in this case it will use from python 3.6 )\nimage\nso if we want to run using python3.7. just change the .exe file name. for ex. if I change to python37.exe and i want to use python3.7 to run hello.py\nI will use python37 hello.py . or if i want to use python3.7 by default i will change the python.exe filename in python3.6 folder to something else . so that it will use python3.7 each time when I use only python hello.py\n", "Shows your installed pythons\npy -0\n\nUses version of python to do something\npy -*version*\n\nex.\npy -3.8 venv venv\n\nWill create virtual environment in python 3.8\nNote:\npython -0 \n or\npython -3.8\n\ndoesn't work, I assume it has to be \"py\"\n", "You can create different python development environments graphically from Anaconda Navigator. \nI had same problem while working with different python versions so I used anaconda navigator to create different python development environments and used different python versions in each environments.\nHere is the help documentation for this.\nhttps://docs.anaconda.com/anaconda/navigator/tutorials/manage-environments/\n", "Introduce more details based on the answer given by @Aman.\nDefine different environment variables for different python versions.\nFor example:\n\nYou have E:\\python2\\python.exe and E:\\python3\\python.exe at the same time.\nThen you can set an environment variable %python2% for E:\\python2\\python.exe and %python2% for E:\\python3\\python.exe.\nFinally, when you want to run python2 (or python3), you can enter %python2% (or %python3%) directly in command prompt.\n\n", "Here is a solution:\n\nFirst, install all versions which you want to run in your pc. https://www.python.org/\nSecond, create virtual environment with which python version you want to use.\n\"py [python_version] -m venv [vritual_environment_name]\" example: \"py -3.9 -m venv env\"\n\nNote: You don't need to run \"pip install virtualenv\"\n", "You can try using py -{your version of python}.\nHope this helps!!!\n" ]
[ 172, 142, 60, 57, 37, 20, 11, 11, 7, 5, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0 ]
[ "Using the Rapid Environment Editor you can push to the top the directory of the desired Python installation. For example, to start python from the c:\\Python27 directory, ensure that c:\\Python27 directory is before or on top of the c:\\Python36 directory in the Path environment variable. From my experience, the first python executable found in the Path environment is being executed. For example, I have MSYS2 installed with Python27 and since I've added C:\\MSYS2 to the path before C:\\Python36, the python.exe from the C:\\MSYS2.... folder is being executed.\n", "I thought this answer might be helpful to others having multiple versions of python and wants to use pipenv to create virtual environment.\n\nnavigate to the project directory, and run py -[python version] pip install pipenv, example: py -3.6 pip install pipenv\nrun pipenv --python [version] to create the virtual environment in the version of the python you desire. example: pipenv --python 3.6\nrun pipenv shell to activate your virtual environment.\n\n", "Just call the correct executable\n" ]
[ -1, -1, -9 ]
[ "compatibility", "python", "windows" ]
stackoverflow_0004583367_compatibility_python_windows.txt
Q: How to make a Flask API on GCP run on https instead of http I have a flask API which is running on a google VM instance but currently it is running on http. So for instance, http://36.137.283.44:5000/get_values is the url for one endpoint where 36.137.283.44 is the external IP of the VM instance and 5000 is the port. I just want to the http to become https. I've seen some answers which use load balancers and others which add ssl related code in the app.py file itself but neither seem to work. A: You need to have the SSL certificate to run flask on https. Once you have the private key and certificate pem files for the SSL. Copy it to the folder where you are the running the python API. Say you copied over the cert.pem and key.pem, to the API code folder then change the API code for the following line to below. application.run(host="0.0.0.0", port=5000, debug=True, ssl_context=("cert.pem", "key.pem")) If you hit the IP after this you might get safety error as the certificate is issued for a certain domain name, try calling with the same.
How to make a Flask API on GCP run on https instead of http
I have a flask API which is running on a google VM instance but currently it is running on http. So for instance, http://36.137.283.44:5000/get_values is the url for one endpoint where 36.137.283.44 is the external IP of the VM instance and 5000 is the port. I just want to the http to become https. I've seen some answers which use load balancers and others which add ssl related code in the app.py file itself but neither seem to work.
[ "You need to have the SSL certificate to run flask on https.\nOnce you have the private key and certificate pem files for the SSL.\nCopy it to the folder where you are the running the python API. Say you copied over the cert.pem and key.pem, to the API code folder then change the API code for the following line to below.\napplication.run(host=\"0.0.0.0\",\n port=5000,\n debug=True,\n ssl_context=(\"cert.pem\", \"key.pem\"))\n\nIf you hit the IP after this you might get safety error as the certificate is issued for a certain domain name, try calling with the same.\n" ]
[ 0 ]
[]
[]
[ "flask", "google_cloud_platform", "https", "python", "ssl_certificate" ]
stackoverflow_0067982448_flask_google_cloud_platform_https_python_ssl_certificate.txt
Q: What is the function to return the cash balance of an account? I am currently using the ibkr api with the ib_insync package and I was wondering how one would return the cash balance in an account. I've tried accountSummary and accountValues but can't seem to find it. A: If you mean this balance field You could fetch it with iterating the account values (they are automatically synced with IB) [x.value for x in self._ib.accountValues() if x.tag == "CashBalance" and x.currency == "USD"][0]
What is the function to return the cash balance of an account?
I am currently using the ibkr api with the ib_insync package and I was wondering how one would return the cash balance in an account. I've tried accountSummary and accountValues but can't seem to find it.
[ "If you mean this balance field\n\nYou could fetch it with iterating the account values (they are automatically synced with IB)\n[x.value for x in self._ib.accountValues() if x.tag == \"CashBalance\" and x.currency == \"USD\"][0]\n\n" ]
[ 0 ]
[]
[]
[ "ib_insync", "python" ]
stackoverflow_0072021941_ib_insync_python.txt
Q: SQLAlchemy ORM conversion to pandas DataFrame Is there a solution converting a SQLAlchemy <Query object> to a pandas DataFrame? Pandas has the capability to use pandas.read_sql but this requires use of raw SQL. I have two reasons for wanting to avoid it: I already have everything using the ORM (a good reason in and of itself) and I'm using python lists as part of the query, e.g.: db.session.query(Item).filter(Item.symbol.in_(add_symbols) where Item is my model class and add_symbols is a list). This is the equivalent of SQL SELECT ... from ... WHERE ... IN. Is anything possible? A: Below should work in most cases: df = pd.read_sql(query.statement, query.session.bind) See pandas.read_sql documentation for more information on the parameters. A: Just to make this more clear for novice pandas programmers, here is a concrete example, pd.read_sql(session.query(Complaint).filter(Complaint.id == 2).statement,session.bind) Here we select a complaint from complaints table (sqlalchemy model is Complaint) with id = 2 A: For completeness sake: As alternative to the Pandas-function read_sql_query(), you can also use the Pandas-DataFrame-function from_records() to convert a structured or record ndarray to DataFrame. This comes in handy if you e.g. have already executed the query in SQLAlchemy and have the results already available: import pandas as pd from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:postgres@localhost:5432/my_database' engine = create_engine(SQLALCHEMY_DATABASE_URI, pool_pre_ping=True, echo=False) db = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base(bind=engine) class Currency(Base): """The `Currency`-table""" __tablename__ = "currency" __table_args__ = {"schema": "data"} id = Column(Integer, primary_key=True, nullable=False) name = Column(String(64), nullable=False) # Defining the SQLAlchemy-query currency_query = db.query(Currency).with_entities(Currency.id, Currency.name) # Getting all the entries via SQLAlchemy currencies = currency_query.all() # We provide also the (alternate) column names and set the index here, # renaming the column `id` to `currency__id` df_from_records = pd.DataFrame.from_records(currencies , index='currency__id' , columns=['currency__id', 'name']) print(df_from_records.head(5)) # Or getting the entries via Pandas instead of SQLAlchemy using the # aforementioned function `read_sql_query()`. We can set the index-columns here as well df_from_query = pd.read_sql_query(currency_query.statement, db.bind, index_col='id') # Renaming the index-column(s) from `id` to `currency__id` needs another statement df_from_query.index.rename(name='currency__id', inplace=True) print(df_from_query.head(5)) A: The selected solution didn't work for me, as I kept getting the error AttributeError: 'AnnotatedSelect' object has no attribute 'lower' I found the following worked: df = pd.read_sql_query(query.statement, engine) A: If you want to compile a query with parameters and dialect specific arguments, use something like this: c = query.statement.compile(query.session.bind) df = pandas.read_sql(c.string, query.session.bind, params=c.params) A: from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('postgresql://postgres:postgres@localhost:5432/DB', echo=False) Base = declarative_base(bind=engine) Session = sessionmaker(bind=engine) session = Session() conn = session.bind class DailyTrendsTable(Base): __tablename__ = 'trends' __table_args__ = ({"schema": 'mf_analysis'}) company_code = Column(DOUBLE_PRECISION, primary_key=True) rt_bullish_trending = Column(Integer) rt_bearish_trending = Column(Integer) rt_bullish_non_trending = Column(Integer) rt_bearish_non_trending = Column(Integer) gen_date = Column(Date, primary_key=True) df_query = select([DailyTrendsTable]) df_data = pd.read_sql(rt_daily_query, con = conn) A: Using the 2.0 SQLalchemy syntax (available also in 1.4 with the flag future=True) it looks that pd.read_sql is not implemented yet and it will raise: NotImplementedError: This method is not implemented for SQLAlchemy 2.0. This is an open issue that won't be solved till pandas 2.0, you can find some information about this here and here. I didn't find any satisfactory work around, but some people seems to be using two configurations of the engine, one with the flag future False: engine2 = create_engine(URL_string, echo=False, future=False) This solution would be OK if you query strings, but using the ORM, the best I could do is a custom function yet to be optimized, but it works: Conditions = session.query(ExampleTable) def df_from_sql(query): return pd.DataFrame([i.__dict__ for i in query]).drop(columns='_sa_instance_state') df = df_from_sql(ExampleTable) This solution in any case would be provisional till pd.read_sql has implemented the new syntax. A: This answer provides a reproducible example using an SQL Alchemy select statement and returning a pandas data frame. It is based on an in memory SQLite database so that anyone can reproduce it without installing a database engine. import pandas from sqlalchemy import create_engine from sqlalchemy import MetaData, Table, Column, Text from sqlalchemy.orm import Session Define table metadata and create a table engine = create_engine('sqlite://') meta = MetaData() meta.bind = engine user_table = Table('user', meta, Column("name", Text), Column("full_name", Text)) user_table.create() Insert some data into the user table stmt = user_table.insert().values(name='Bob', full_name='Sponge Bob') with Session(engine) as session: result = session.execute(stmt) session.commit() Read the result of a select statement into a pandas data frame # Select data into a pandas data frame stmt = user_table.select().where(user_table.c.name == 'Bob') df = pandas.read_sql_query(stmt, engine) df Out: name full_name 0 Bob Sponge Bob A: if use SQL query def generate_df_from_sqlquery(query): from pandas import DataFrame query = db.session.execute(query) df = DataFrame(query.fetchall()) if len(df) > 0: df.columns = query.keys() else: columns = query.keys() df = pd.DataFrame(columns=columns) return df profile_df = generate_df_from_sqlquery(profile_query) A: When you're using the ORM it's as simple as this: pd.DataFrame([r._asdict() for r in query.all()]) Good alternative to pd.read_sql when you don't want to expose sql and sessions to the business logic code. Found it here: https://stackoverflow.com/a/52208023/1635525
SQLAlchemy ORM conversion to pandas DataFrame
Is there a solution converting a SQLAlchemy <Query object> to a pandas DataFrame? Pandas has the capability to use pandas.read_sql but this requires use of raw SQL. I have two reasons for wanting to avoid it: I already have everything using the ORM (a good reason in and of itself) and I'm using python lists as part of the query, e.g.: db.session.query(Item).filter(Item.symbol.in_(add_symbols) where Item is my model class and add_symbols is a list). This is the equivalent of SQL SELECT ... from ... WHERE ... IN. Is anything possible?
[ "Below should work in most cases:\ndf = pd.read_sql(query.statement, query.session.bind)\n\nSee pandas.read_sql documentation for more information on the parameters.\n", "Just to make this more clear for novice pandas programmers, here is a concrete example,\npd.read_sql(session.query(Complaint).filter(Complaint.id == 2).statement,session.bind) \n\nHere we select a complaint from complaints table (sqlalchemy model is Complaint) with id = 2\n", "For completeness sake: As alternative to the Pandas-function read_sql_query(), you can also use the Pandas-DataFrame-function from_records() to convert a structured or record ndarray to DataFrame.\nThis comes in handy if you e.g. have already executed the query in SQLAlchemy and have the results already available:\nimport pandas as pd \nfrom sqlalchemy import Column, Integer, String, create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\n\nSQLALCHEMY_DATABASE_URI = 'postgresql://postgres:postgres@localhost:5432/my_database'\nengine = create_engine(SQLALCHEMY_DATABASE_URI, pool_pre_ping=True, echo=False)\ndb = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))\nBase = declarative_base(bind=engine)\n\n\nclass Currency(Base):\n \"\"\"The `Currency`-table\"\"\"\n __tablename__ = \"currency\"\n __table_args__ = {\"schema\": \"data\"}\n\n id = Column(Integer, primary_key=True, nullable=False)\n name = Column(String(64), nullable=False)\n\n\n# Defining the SQLAlchemy-query\ncurrency_query = db.query(Currency).with_entities(Currency.id, Currency.name)\n\n# Getting all the entries via SQLAlchemy\ncurrencies = currency_query.all()\n\n# We provide also the (alternate) column names and set the index here,\n# renaming the column `id` to `currency__id`\ndf_from_records = pd.DataFrame.from_records(currencies\n , index='currency__id'\n , columns=['currency__id', 'name'])\nprint(df_from_records.head(5))\n\n# Or getting the entries via Pandas instead of SQLAlchemy using the\n# aforementioned function `read_sql_query()`. We can set the index-columns here as well\ndf_from_query = pd.read_sql_query(currency_query.statement, db.bind, index_col='id')\n# Renaming the index-column(s) from `id` to `currency__id` needs another statement\ndf_from_query.index.rename(name='currency__id', inplace=True)\nprint(df_from_query.head(5))\n\n", "The selected solution didn't work for me, as I kept getting the error \n\nAttributeError: 'AnnotatedSelect' object has no attribute 'lower' \n\nI found the following worked:\ndf = pd.read_sql_query(query.statement, engine)\n\n", "If you want to compile a query with parameters and dialect specific arguments, use something like this:\nc = query.statement.compile(query.session.bind)\ndf = pandas.read_sql(c.string, query.session.bind, params=c.params)\n\n", "from sqlalchemy import Column, Integer, String, create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nengine = create_engine('postgresql://postgres:postgres@localhost:5432/DB', echo=False)\nBase = declarative_base(bind=engine)\nSession = sessionmaker(bind=engine)\nsession = Session()\n\nconn = session.bind\n\nclass DailyTrendsTable(Base):\n\n __tablename__ = 'trends'\n __table_args__ = ({\"schema\": 'mf_analysis'})\n\n company_code = Column(DOUBLE_PRECISION, primary_key=True)\n rt_bullish_trending = Column(Integer)\n rt_bearish_trending = Column(Integer)\n rt_bullish_non_trending = Column(Integer)\n rt_bearish_non_trending = Column(Integer)\n gen_date = Column(Date, primary_key=True)\n\ndf_query = select([DailyTrendsTable])\n\ndf_data = pd.read_sql(rt_daily_query, con = conn)\n\n", "Using the 2.0 SQLalchemy syntax (available also in 1.4 with the flag future=True) it looks that pd.read_sql is not implemented yet and it will raise:\nNotImplementedError: This method is not implemented for SQLAlchemy 2.0.\n\nThis is an open issue that won't be solved till pandas 2.0, you can find some information about this here and here.\nI didn't find any satisfactory work around, but some people seems to be using two configurations of the engine, one with the flag future False:\nengine2 = create_engine(URL_string, echo=False, future=False)\n\nThis solution would be OK if you query strings, but using the ORM, the best I could do is a custom function yet to be optimized, but it works:\nConditions = session.query(ExampleTable)\ndef df_from_sql(query):\n return pd.DataFrame([i.__dict__ for i in query]).drop(columns='_sa_instance_state')\ndf = df_from_sql(ExampleTable)\n\nThis solution in any case would be provisional till pd.read_sql has implemented the new syntax.\n", "This answer provides a reproducible example using an SQL Alchemy select statement and returning a pandas data frame. It is based on an in memory SQLite database so that anyone can reproduce it without installing a database engine.\nimport pandas\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import MetaData, Table, Column, Text\nfrom sqlalchemy.orm import Session\n\nDefine table metadata and create a table\nengine = create_engine('sqlite://')\nmeta = MetaData()\nmeta.bind = engine\nuser_table = Table('user', meta,\n Column(\"name\", Text),\n Column(\"full_name\", Text))\nuser_table.create()\n\nInsert some data into the user table\nstmt = user_table.insert().values(name='Bob', full_name='Sponge Bob')\nwith Session(engine) as session:\n result = session.execute(stmt)\n session.commit()\n\nRead the result of a select statement into a pandas data frame\n# Select data into a pandas data frame\nstmt = user_table.select().where(user_table.c.name == 'Bob')\ndf = pandas.read_sql_query(stmt, engine)\ndf\nOut:\n name full_name\n0 Bob Sponge Bob\n\n", "if use SQL query\ndef generate_df_from_sqlquery(query):\n from pandas import DataFrame\n query = db.session.execute(query)\n df = DataFrame(query.fetchall())\n if len(df) > 0:\n df.columns = query.keys()\n else:\n columns = query.keys()\n df = pd.DataFrame(columns=columns)\nreturn df\n\nprofile_df = generate_df_from_sqlquery(profile_query) \n\n", "When you're using the ORM it's as simple as this:\npd.DataFrame([r._asdict() for r in query.all()])\n\nGood alternative to pd.read_sql when you don't want to expose sql and sessions to the business logic code.\nFound it here: https://stackoverflow.com/a/52208023/1635525\n" ]
[ 252, 142, 25, 18, 6, 5, 2, 0, 0, 0 ]
[]
[]
[ "flask_sqlalchemy", "pandas", "python", "sqlalchemy" ]
stackoverflow_0029525808_flask_sqlalchemy_pandas_python_sqlalchemy.txt
Q: OneDrive free up space with Python I have been using OneDrive to store a large amount of images and now I need to process those, so I have sync'd my OneDrive folder to my computer, which takes relatively no space on disk. However, since I have to open() them in my code, they all get downloaded, which would take much more than the available memory on my computer. I can manually use the Free up space action in the right-click contextual menu, which keeps them sync'd without taking space. I'm looking for a way to do the same thing but in my code instead, after every image I process. Trying to find how to get the commands of contextual menu items led me to these two places in the registry: HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell HKEY_LOCAL_MACHINE\SOFTWARE\Classes*\shellex\ContextMenuHandlers However I couldn't find anything related to it and those trees have way too many keys to check blindly. Also this forum post (outside link) shows a few ways to free up space automatically, but it seems to affect all files and is limited to full days intervals. So is there any way to either access that command or to free up the space in python ? A: According to this microsoft post it is possible to call Attrib.exe to do that sort of manipulation on files. This little snippet does the job for a per-file usage. As shown in the linked post, it's also possible to do it on the full contents of a folder using the /s argument, and much more. import subprocess def process_image(path): # Open the file, which downloads it automatically with open(path, 'r') as img: print(img) # Free up space (OneDrive) after usage subprocess.run('attrib +U -P "' + path + '"') The download and freeing up space are fairly quick, but in the case of running this heavily in parallel, it is possible that some disk space will be consumed for a short amount of time. In general though, this is pretty instantaneous. A: In addition to Mat's answer. If you are working on a Mac then you can replace Attrib.exe with "/Applications/OneDrive.App/Contents/MacOS/OneDrive /unpin" to make the file online only. import subprocess path = "/Users/OneDrive/file.png" subprocess.run(["/Applications/OneDrive.App/Contents/MacOS/OneDrive", "/unpin", path]) A: Free up space for multiples files. import os import subprocess path = r"C:\Users\yourUser\Folder" diret = os.listdir(path) for di in diret: dir_atual = path + "\\" + di for root, dirs, files in os.walk(dir_atual): for file in files: arquivos = (os.path.join(root, file)) print (arquivos) subprocess.run('attrib +U -P "' + arquivos + '"')
OneDrive free up space with Python
I have been using OneDrive to store a large amount of images and now I need to process those, so I have sync'd my OneDrive folder to my computer, which takes relatively no space on disk. However, since I have to open() them in my code, they all get downloaded, which would take much more than the available memory on my computer. I can manually use the Free up space action in the right-click contextual menu, which keeps them sync'd without taking space. I'm looking for a way to do the same thing but in my code instead, after every image I process. Trying to find how to get the commands of contextual menu items led me to these two places in the registry: HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell HKEY_LOCAL_MACHINE\SOFTWARE\Classes*\shellex\ContextMenuHandlers However I couldn't find anything related to it and those trees have way too many keys to check blindly. Also this forum post (outside link) shows a few ways to free up space automatically, but it seems to affect all files and is limited to full days intervals. So is there any way to either access that command or to free up the space in python ?
[ "According to this microsoft post it is possible to call Attrib.exe to do that sort of manipulation on files.\nThis little snippet does the job for a per-file usage. As shown in the linked post, it's also possible to do it on the full contents of a folder using the /s argument, and much more.\nimport subprocess\n\ndef process_image(path):\n # Open the file, which downloads it automatically\n with open(path, 'r') as img:\n print(img)\n\n # Free up space (OneDrive) after usage\n subprocess.run('attrib +U -P \"' + path + '\"')\n\nThe download and freeing up space are fairly quick, but in the case of running this heavily in parallel, it is possible that some disk space will be consumed for a short amount of time. In general though, this is pretty instantaneous.\n", "In addition to Mat's answer. If you are working on a Mac then you can replace Attrib.exe with \"/Applications/OneDrive.App/Contents/MacOS/OneDrive /unpin\" to make the file online only. \nimport subprocess\n\npath = \"/Users/OneDrive/file.png\"\nsubprocess.run([\"/Applications/OneDrive.App/Contents/MacOS/OneDrive\", \"/unpin\", path])\n\n\n", "Free up space for multiples files.\nimport os\nimport subprocess\n\npath = r\"C:\\Users\\yourUser\\Folder\"\n\ndiret = os.listdir(path)\nfor di in diret:\ndir_atual = path + \"\\\\\" + di\nfor root, dirs, files in os.walk(dir_atual):\n for file in files:\n\n arquivos = (os.path.join(root, file))\n\n print (arquivos)\n subprocess.run('attrib +U -P \"' + arquivos + '\"')\n\n" ]
[ 5, 2, 0 ]
[]
[]
[ "onedrive", "python" ]
stackoverflow_0056600252_onedrive_python.txt
Q: How can I create a list of dicts from multiple separate lists? say I have four separate lists like so: colors = ['red', 'blue', 'green', 'black'] widths = [10.0, 12.0, 8.0, 22.0] lengths = [35.5, 41.0, 36.5, 36.0] materials = ['steel', 'copper', 'iron', 'steel'] What's the best way to take this data and create a list of dicts representing objects like so: objects = [{'color': 'red', 'width': 10.0, 'length': 35.5, 'material': 'steel'}, {'color': 'blue', 'width': 12.0, 'length': 41.0, 'material': 'copper'}, {'color': 'green', 'width': 8.0, 'length': 36.5, 'material': 'iron'}, {'color': 'black', 'width': 22.0, 'length': 36.0, 'material': 'steel'}] I'm currently using a for loop: for color in colors: obj = {} obj['color'] = color obj['width'] = widths[colors.index(color)] obj['length'] = lengths[colors.index(color)] obj['material'] = materials[colors.index(color)] objects.append(obj) but this is slow for large lists so I'm wondering if there's a faster way A: This answer combines the use of a list-comprehension to easily create a list and the zip() built-in function that iterates over several iterables in parallel. objects = [{"color": c, "width": w, "length": l, "material": m} for c, w, l, m in zip(colors, widths, lengths, materials)] A: Use the range function: colors = ['red', 'blue', 'green', 'black'] widths = [10.0, 12.0, 8.0, 22.0] lengths = [35.5, 41.0, 36.5, 36.0] materials = ['steel', 'copper', 'iron', 'steel'] objects = [] for i in range(len(colors)): d = {} d['colors'] = colors[i] d['widths'] = widths[i] d['lengths'] = lengths[i] d['materials'] = materials[i] objects.append(d) Note that all lists must have the same amount of elements as colors. A: The zip function is very useful. objects = [] for object in zip(colors, widths, lengths, materials): objects.append({ 'color': object[0], 'width': object[1], 'length': object[2], 'material': object[3]}) A: zipped = zip(colors, widths, lengths, materials) objects = [{"color": color, "width": width, "length": length, "material": material} for color, width, length, material in zipped]
How can I create a list of dicts from multiple separate lists?
say I have four separate lists like so: colors = ['red', 'blue', 'green', 'black'] widths = [10.0, 12.0, 8.0, 22.0] lengths = [35.5, 41.0, 36.5, 36.0] materials = ['steel', 'copper', 'iron', 'steel'] What's the best way to take this data and create a list of dicts representing objects like so: objects = [{'color': 'red', 'width': 10.0, 'length': 35.5, 'material': 'steel'}, {'color': 'blue', 'width': 12.0, 'length': 41.0, 'material': 'copper'}, {'color': 'green', 'width': 8.0, 'length': 36.5, 'material': 'iron'}, {'color': 'black', 'width': 22.0, 'length': 36.0, 'material': 'steel'}] I'm currently using a for loop: for color in colors: obj = {} obj['color'] = color obj['width'] = widths[colors.index(color)] obj['length'] = lengths[colors.index(color)] obj['material'] = materials[colors.index(color)] objects.append(obj) but this is slow for large lists so I'm wondering if there's a faster way
[ "This answer combines the use of a list-comprehension to easily create a list and the zip() built-in function that iterates over several iterables in parallel.\nobjects = [{\"color\": c, \"width\": w, \"length\": l, \"material\": m} for c, w, l, m in zip(colors, widths, lengths, materials)]\n\n", "Use the range function:\ncolors = ['red', 'blue', 'green', 'black']\nwidths = [10.0, 12.0, 8.0, 22.0]\nlengths = [35.5, 41.0, 36.5, 36.0]\nmaterials = ['steel', 'copper', 'iron', 'steel']\nobjects = []\nfor i in range(len(colors)):\n d = {}\n d['colors'] = colors[i]\n d['widths'] = widths[i]\n d['lengths'] = lengths[i]\n d['materials'] = materials[i]\n objects.append(d)\n\nNote that all lists must have the same amount of elements as colors.\n", "The zip function is very useful.\nobjects = []\nfor object in zip(colors, widths, lengths, materials):\n objects.append({\n 'color': object[0], \n 'width': object[1], \n 'length': object[2], \n 'material': object[3]})\n\n", "zipped = zip(colors, widths, lengths, materials)\nobjects = [{\"color\": color, \"width\": width, \"length\": length, \"material\": material} for color, width, length, material in zipped]\n\n" ]
[ 3, 0, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074548240_dictionary_list_python.txt
Q: How to check if a variable is binary in Python In order to check if a given list is constituted only by 0 and 1 values, I tried to set up a function returning True when the list is binary, while it returns False when not: My code def is_binary(y): for x in y: if x in [2,3,4,5,6,7,8,9]: return False break else: return True Itried it on the following list: our_list=[1,0,0,0,1,1,0,0,0,0,1,0,1,0,1,1,1] is_binary(our_list) Output: True But it doesn't work when the variable is not binary. Any help from your side will be appreciated. A: I would turn around your logic. def is_binary(y): for x in y: if x not in [0,1]: return False return True The root of the problem is that you are returning the result at the first iteration round, because the return statement stops the execution of the function. This also makes your break statement redundant. See https://www.geeksforgeeks.org/python-return-statement/ for more info. There are two use cases where your original solution works as expected and that is when the list length is one or the error is in the first item of the list y AND the "wrong" value is in the list [0,1, ...9] e.g. y=[0] or y=[1] or y=[1,0] returns True and y=[3] will return False. However, your solution fails, if y=['three'] or y=[13] or y=[0, 0, 3] because it returns True, though it should be False. A: def is_binary(arr): for num in arr: if num not in [0, 1]: return False return True our_list=[1,0,0,0,1,1,0,0,0,0,1,0,1,0,1,1,1] print(is_binary(our_list)) I found several mistakes in your code. Firstly, your code stops when the return statement is executed. So your loop will only be executed once and return the result of the first element in the list. Secondly, there are two binary numbers, and countless numbers that aren't binary. You're just checking if the numbers are in range(2, 10). When the number is not in that range, take 11 as example, since it is not in range(2, 10), it won't execute the return False statement. Therefore, rather to check if the number is in countless un-binary numbers, check if the number is not binary. A: You can also use a list comprehension with the result of checking if each element is binary, and use all to check that all elements are True. Edit: as @Jonh Coleman suggested, instead of creating a list first and then applying all, we can take advantage of generators, which will only generate values as requested. We then only need to generate elements until one of them evaluates False. all will take care of that by shortcircuiting and not continuing to request elements to the generator once one of them evaluates False. That will be both more memory and time efficient. our_list=[1,0,0,0,1,1,0,2,0,0,1,0,1,0,1,1,1] all(i in [0,1] for i in our_list) False
How to check if a variable is binary in Python
In order to check if a given list is constituted only by 0 and 1 values, I tried to set up a function returning True when the list is binary, while it returns False when not: My code def is_binary(y): for x in y: if x in [2,3,4,5,6,7,8,9]: return False break else: return True Itried it on the following list: our_list=[1,0,0,0,1,1,0,0,0,0,1,0,1,0,1,1,1] is_binary(our_list) Output: True But it doesn't work when the variable is not binary. Any help from your side will be appreciated.
[ "I would turn around your logic.\ndef is_binary(y):\n for x in y:\n if x not in [0,1]:\n return False\n return True\n\nThe root of the problem is that you are returning the result at the first iteration round, because the return statement stops the execution of the function. This also makes your break statement redundant. See https://www.geeksforgeeks.org/python-return-statement/ for more info.\nThere are two use cases where your original solution works as expected and that is when the list length is one or the error is in the first item of the list y AND the \"wrong\" value is in the list [0,1, ...9] e.g. y=[0] or y=[1] or y=[1,0] returns True and y=[3] will return False. However, your solution fails, if y=['three'] or y=[13] or y=[0, 0, 3] because it returns True, though it should be False.\n", "def is_binary(arr):\n for num in arr:\n if num not in [0, 1]:\n return False\n return True\n \nour_list=[1,0,0,0,1,1,0,0,0,0,1,0,1,0,1,1,1]\nprint(is_binary(our_list))\n\nI found several mistakes in your code.\nFirstly, your code stops when the return statement is executed. So your loop will only be executed once and return the result of the first element in the list.\nSecondly, there are two binary numbers, and countless numbers that aren't binary. You're just checking if the numbers are in range(2, 10). When the number is not in that range, take 11 as example, since it is not in range(2, 10), it won't execute the return False statement.\nTherefore, rather to check if the number is in countless un-binary numbers, check if the number is not binary.\n", "You can also use a list comprehension with the result of checking if each element is binary, and use all to check that all elements are True.\nEdit: as @Jonh Coleman suggested, instead of creating a list first and then applying all, we can take advantage of generators, which will only generate values as requested.\nWe then only need to generate elements until one of them evaluates False. all will take care of that by shortcircuiting and not continuing to request elements to the generator once one of them evaluates False. That will be both more memory and time efficient.\nour_list=[1,0,0,0,1,1,0,2,0,0,1,0,1,0,1,1,1]\n\nall(i in [0,1] for i in our_list)\n\nFalse\n\n" ]
[ 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074548214_python.txt
Q: data not being fetched properly from a website I want to get the urls of the products from a particular website and then get more data thereafter (but I'm currently stuck here in just getting the urls) Here are what I tried: here are the modules I used import bs4 import pandas as pd import numpy as np import random import requests from lxml import etree import time from tqdm.notebook import tqdm from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.chrome.options import Options from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import ElementNotInteractableException from time import sleep from webdriver_manager.chrome import ChromeDriverManager I tried a bunch of workarounds and here are some of them (which I thought are correct but I don't know why not working at all) **1. ** driver = webdriver.Chrome(ChromeDriverManager().install()) urls = [] for page in tqdm(range(2, 10)): driver.get("https://www.sephora.com/shop/skincare?currentPage="+str(page)) for order in tqdm(range(0,70)): skincare = driver.find_elements(By.XPATH, "//main[@class='css-1owb2na']//div[@data-comp='ProductGrid ']//div[@class='css-1322gsb']//div[@class='css-1qe8tjm'][@style='order:" +str(order)+ " ;']//a[@class='css-klx76']") for _skincare in skincare: urls.append({"url":_skincare.get_attribute('href')}) driver.quit() I only get nothing, "urls" is blank. 2 driver = webdriver.Chrome(ChromeDriverManager().install()) urls = [] for page in tqdm(range(2, 10)): driver.get("https://www.sephora.com/shop/skincare?currentPage="+str(page)) for order in tqdm(range(0,70)): skincare = driver.find_elements(By.XPATH, "//div[@style='order:" +str(order)+ " ;']//a[@class='css-klx76']") for _skincare in skincare: urls.append({"url":_skincare.get_attribute('href')}) driver.quit() I get the same, nothing, it's probably because of the path, when I call "skincare" it's also blank. 3 driver = webdriver.Chrome(ChromeDriverManager().install()) urls = [] for page in tqdm(range(2, 50)): driver.get("https://www.sephora.com/shop/skincare?currentPage="+str(page)) skincare = driver.find_elements(By.CLASS_NAME, 'css-klx76') for _skincare in skincare: urls.append({"url":_skincare.get_attribute('href')}) driver.quit() With this one, using "By.CLASS_NAME" I only get a few of the many urls I need per page (meaning it's still not the right one). I'm apparently doing something wrong with the path here but I can't find it now. Any comments? Thanks! Tried to scrape data from a website and expected to get the urls/links but didn't get it. A: Try this code, this will navigate to each page by page number, scroll down to the bottom, then fetch all the products' URLs. for page in range(1, 10): driver.get("https://www.sephora.com/shop/skincare?currentPage="+str(page)) while True: driver.execute_script("window.scrollBy(0, 800);") sleep(1) new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height sleep(3) skincare = driver.find_elements(By.XPATH, ".//a[@class='css-klx76']") print("Total URLs:", len(skincare)) i = 1 for _skincare in skincare: urls.append({f"url-{i}": _skincare.get_attribute('href')}) i += 1
data not being fetched properly from a website
I want to get the urls of the products from a particular website and then get more data thereafter (but I'm currently stuck here in just getting the urls) Here are what I tried: here are the modules I used import bs4 import pandas as pd import numpy as np import random import requests from lxml import etree import time from tqdm.notebook import tqdm from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.chrome.options import Options from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import ElementNotInteractableException from time import sleep from webdriver_manager.chrome import ChromeDriverManager I tried a bunch of workarounds and here are some of them (which I thought are correct but I don't know why not working at all) **1. ** driver = webdriver.Chrome(ChromeDriverManager().install()) urls = [] for page in tqdm(range(2, 10)): driver.get("https://www.sephora.com/shop/skincare?currentPage="+str(page)) for order in tqdm(range(0,70)): skincare = driver.find_elements(By.XPATH, "//main[@class='css-1owb2na']//div[@data-comp='ProductGrid ']//div[@class='css-1322gsb']//div[@class='css-1qe8tjm'][@style='order:" +str(order)+ " ;']//a[@class='css-klx76']") for _skincare in skincare: urls.append({"url":_skincare.get_attribute('href')}) driver.quit() I only get nothing, "urls" is blank. 2 driver = webdriver.Chrome(ChromeDriverManager().install()) urls = [] for page in tqdm(range(2, 10)): driver.get("https://www.sephora.com/shop/skincare?currentPage="+str(page)) for order in tqdm(range(0,70)): skincare = driver.find_elements(By.XPATH, "//div[@style='order:" +str(order)+ " ;']//a[@class='css-klx76']") for _skincare in skincare: urls.append({"url":_skincare.get_attribute('href')}) driver.quit() I get the same, nothing, it's probably because of the path, when I call "skincare" it's also blank. 3 driver = webdriver.Chrome(ChromeDriverManager().install()) urls = [] for page in tqdm(range(2, 50)): driver.get("https://www.sephora.com/shop/skincare?currentPage="+str(page)) skincare = driver.find_elements(By.CLASS_NAME, 'css-klx76') for _skincare in skincare: urls.append({"url":_skincare.get_attribute('href')}) driver.quit() With this one, using "By.CLASS_NAME" I only get a few of the many urls I need per page (meaning it's still not the right one). I'm apparently doing something wrong with the path here but I can't find it now. Any comments? Thanks! Tried to scrape data from a website and expected to get the urls/links but didn't get it.
[ "Try this code, this will navigate to each page by page number, scroll down to the bottom, then fetch all the products' URLs.\nfor page in range(1, 10):\n driver.get(\"https://www.sephora.com/shop/skincare?currentPage=\"+str(page))\n while True:\n driver.execute_script(\"window.scrollBy(0, 800);\")\n sleep(1)\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\n if new_height == last_height:\n break\n last_height = new_height\n\n sleep(3)\n\n skincare = driver.find_elements(By.XPATH, \".//a[@class='css-klx76']\")\n print(\"Total URLs:\", len(skincare))\n i = 1\n for _skincare in skincare:\n urls.append({f\"url-{i}\": _skincare.get_attribute('href')})\n i += 1\n\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "web_scraping" ]
stackoverflow_0074539720_beautifulsoup_python_selenium_web_scraping.txt
Q: Python Apache Beam TaggedOutput Not Working I'm having an issue with TaggedOutputs in Apache Beam (DataflowRunner) using Python 3.9. I've included the necessary pieces of code below for understanding. Basically the tagged output from parent_check_pipeline for Tag.REQS_SATISFIED) is not working. When the code in CheckParentRequirements yields that tagged output, the pipeline, basically, ends. I get the correct log that the "Element ... has no parents", but the pipeline stops there and doesn't proceed to "Write to Pubsub Topics." I think my meaning can be seen in the dataflow graph I included below as well. The pipeline definitions for each step are separated into functions for ease of testing. We've used this approach in other beam pipelines and it is working so I'm not sure what's missing here. Thanks in advance! Other approaches I've tried declaring the inputs to "Write to Pubsub" as a tuple: p_publish_messages = ( (p_check_parents_needed[Tag.REQS_SATISFIED], p_check_parents_exist[Tag.REQS_SATISFIED]) | "Write to Pubsub Topics" >> beam.ParDo(WriteToPubsubMultiple(topic_1, topic_2)) ) which gives the following error: File ".../lib/python3.9/site-packages/apache_beam/transforms/core.py", line 1578, in expand is_bounded = pcoll.is_bounded AttributeError: 'tuple' object has no attribute 'is_bounded' When using the code defined in publish_messages_pipeline with: p_publish_messages = publish_messages_pipeline([p_check_parents_needed, p_check_parents_exist], pipeline_params) I receive: Traceback (most recent call last): File "/Users/jimmy.hartman/projects/apiary/ces-ingest-eventing/src/dataflow/parent_check_pipeline.py", line 362, in <module> run( File "/Users/jimmy.hartman/projects/apiary/ces-ingest-eventing/src/dataflow/parent_check_pipeline.py", line 317, in run p_publish_messages = publish_messages_pipeline([p_check_parents_needed, p_check_parents_exist], pipeline_params) File "/Users/jimmy.hartman/projects/apiary/ces-ingest-eventing/src/dataflow/parent_check_pipeline.py", line 206, in publish_messages_pipeline tagged_sources File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/transforms/ptransform.py", line 1095, in __ror__ return self.transform.__ror__(pvalueish, self.label) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/transforms/ptransform.py", line 622, in __ror__ p.run().wait_until_finish() File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/pipeline.py", line 574, in run return self.runner.run_pipeline(self, self._options) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/direct/direct_runner.py", line 131, in run_pipeline return runner.run_pipeline(pipeline, options) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 199, in run_pipeline self._latest_run_result = self.run_via_runner_api( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 212, in run_via_runner_api return self.run_stages(stage_context, stages) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 442, in run_stages bundle_results = self._execute_bundle( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 770, in _execute_bundle self._run_bundle( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 999, in _run_bundle result, splits = bundle_manager.process_bundle( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 1309, in process_bundle result_future = self._worker_handler.control_conn.push(process_bundle_req) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/worker_handlers.py", line 380, in push response = self.worker.do_instruction(request) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/sdk_worker.py", line 597, in do_instruction return getattr(self, request_type)( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/sdk_worker.py", line 635, in process_bundle bundle_processor.process_bundle(instruction_id)) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/bundle_processor.py", line 1003, in process_bundle input_op_by_transform_id[element.transform_id].process_encoded( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/bundle_processor.py", line 227, in process_encoded self.output(decoded_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 528, in output _cast_to_receiver(self.receivers[output_index]).receive(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 240, in receive self.consumer.process(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 908, in process delayed_applications = self.dofn_runner.process(o) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1419, in process self._reraise_augmented(exn) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1491, in _reraise_augmented raise exn File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1417, in process return self.do_fn_invoker.invoke_process(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 623, in invoke_process self.output_handler.handle_process_outputs( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1581, in handle_process_outputs self._write_value_to_tag(tag, windowed_value, watermark_estimator) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1694, in _write_value_to_tag self.main_receivers.receive(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 240, in receive self.consumer.process(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 908, in process delayed_applications = self.dofn_runner.process(o) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1419, in process self._reraise_augmented(exn) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1491, in _reraise_augmented raise exn File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1417, in process return self.do_fn_invoker.invoke_process(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 623, in invoke_process self.output_handler.handle_process_outputs( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1581, in handle_process_outputs self._write_value_to_tag(tag, windowed_value, watermark_estimator) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1694, in _write_value_to_tag self.main_receivers.receive(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 240, in receive self.consumer.process(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 908, in process delayed_applications = self.dofn_runner.process(o) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1419, in process self._reraise_augmented(exn) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1507, in _reraise_augmented raise new_exn.with_traceback(tb) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1417, in process return self.do_fn_invoker.invoke_process(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 623, in invoke_process self.output_handler.handle_process_outputs( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1571, in handle_process_outputs for result in results: File "/Users/jimmy.hartman/projects/apiary/ces-ingest-eventing/src/dataflow/parent_check_pipeline.py", line 159, in process enc_element = json.dumps(element).encode("utf-8") File "/Users/jimmy.hartman/.pyenv/versions/3.9.13/lib/python3.9/json/__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "/Users/jimmy.hartman/.pyenv/versions/3.9.13/lib/python3.9/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/Users/jimmy.hartman/.pyenv/versions/3.9.13/lib/python3.9/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/Users/jimmy.hartman/.pyenv/versions/3.9.13/lib/python3.9/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type _InvalidUnpickledPCollection is not JSON serializable [while running 'Write to Pubsub Topics'] Code class CheckParentRequirements(DoFn): def process(self, element, *args, **kwargs): parents = get_parents(element) if parents: logging.getLogger(__name__).warning(f"Element {element} has parents: '{parents}'") yield TaggedOutput(value=element, tag=Tag.PARENTS_NEEDED) else: logging.getLogger(__name__).warning(f"Element {element} has no parents") yield TaggedOutput(value=element, tag=Tag.REQS_SATISFIED) class LookupParents(DoFn): def process(self, element): missing_parents = self.get_missing_entities(parent_id_map, element) if missing_parents: self.logger.info(f"'{element}' missing parents {missing_parents}.") element.update({Key.MISSING_PARENTS: missing_parents}) yield TaggedOutput(value=element, tag=Tag.MISSING_PARENTS) else: self.logger.info(f"'{element}' parents found.") yield TaggedOutput(value=element, tag=Tag.REQS_SATISFIED) def get_missing_parents(element): ... class WriteToPubsubMultiple(DoFn): def __init__(self, topic_1, topic_2): self.topic_1 = topic_1 self.topic_2 = topic_2 self.publisher = None def setup(self): self.publisher = pubsub_v1.PublisherClient() def process(self, element, *args, **kwargs): logger = logging.getLogger(__name__) enc_element = json.dumps(element).encode("utf-8") self.publisher.publish(self.topic_1, enc_element) self.publisher.publish(self.topic_2, enc_element) logger.info("Sent message messages.") yield None def parent_check_pipeline(source) -> DoOutputsTuple: p_parent_check = ( source | "Check Parent Requirement" >> beam.ParDo(CheckParentRequirements()).with_outputs(Tag.PARENTS_NEEDED, Tag.REQS_SATISFIED) ) return p_parent_check def lookup_parents_pipeline(source: DoOutputsTuple, params: PipelineParams) -> DoOutputsTuple: p_parents_exist = source[Tag.PARENTS_NEEDED] | "Lookup Parents" >> beam.ParDo( LookupParents(params.database_instance_id, params.database_id) ).with_outputs(Tag.MISSING_PARENTS, Tag.REQS_SATISFIED) return p_parents_exist def waiting_room_insert_pipeline(source: DoOutputsTuple, params: PipelineParams): p_waiting_room_rows = ( source[Tag.MISSING_PARENTS] | "Create Bigtable Rows" >> beam.ParDo(CreateWaitingRoomRows()) | "Bigtable Window" >> beam.WindowInto( window.GlobalWindows(), trigger=Repeatedly(AfterAny(AfterCount(100), AfterProcessingTime(10))), accumulation_mode=AccumulationMode.DISCARDING, ) | "Write to Bigtable" >> WriteToBigTable(params.project_id, params.instance, params.table) ) return p_waiting_room_rows # Not using this right now as I was troubleshooting. This is now in the `run()` method. def publish_messages_pipeline(sources: List[DoOutputsTuple], params: PipelineParams): tagged_sources = (source[Tag.REQS_SATISFIED] for source in sources) p_publish_messages = ( tagged_sources | "Write to Pubsub Topics" >> beam.ParDo(WriteToPubsubMultiple(params.topic_1, params.topic_2)) ) return p_publish_messages def run( pipeline_options, pipeline_params ): with Pipeline(options=pipeline_options) as pipeline: p_source = ( pipeline | "Read from Pub/Sub" >> io.ReadFromPubSub(subscription=input_subscription) | "Parse JSON" >> beam.Map(json.loads) ) p_check_parents_needed = parent_check_pipeline(p_source) p_check_parents_exist = lookup_parents_pipeline(p_check_parents_needed, pipeline_params) p_waiting_room_insert = waiting_room_insert_pipeline(p_check_parents_exist, pipeline_params) p_publish_messages = ( p_check_parents_needed[Tag.REQS_SATISFIED], p_check_parents_exist[Tag.REQS_SATISFIED] | "Write to Pubsub Topics" >> beam.ParDo(WriteToPubsubMultiple(topic_1, topic_2)) ) Dataflow graph: A: At a first glance, I see nothing wrong with your tagged outputs (assuming Tag.WHATEVER returns a string). However, I am a bit confused about the way you outsource pipeline parts. Usually, you would use PTransforms instead of simple python functions. That might be the source of your strange behavior. I would recommend rewriting all your pipeline methods to PTransforms, e.g. class ParentCheckPipeline(beam.PTransform): def expand(self, source): p_parent_check = ( source | "Check Parent Requirement" >> beam.ParDo(CheckParentRequirements()) .with_outputs(Tag.PARENTS_NEEDED, Tag.REQS_SATISFIED) ) return p_parent_check Note the mandatory expand method, containing your pipeline part. A: Turns out I needed to take advantage of the apache_beam.Flatten() transform: Flatten is a Beam transform for PCollection objects that store the same data type. Flatten merges multiple PCollection objects into a single logical PCollection. The new publish_messages_pipeline definition would look like this: def publish_messages_pipeline(sources: List[DoOutputsTuple], params: PipelineParams): tagged_sources = (source[Tag.REQS_SATISFIED] for source in sources) p_publish_messages = ( tagged_sources | "Flatten inputs" >> beam.Flatten() | "Write to Pubsub Topics" >> beam.ParDo(WriteToPubsubMultipleFn(params.topic_1, params.topic_2)) ) return p_publish_messages Taking the suggestion from @CaptainNabla, I put the "composite transform" code for inserting into bigtable into a class extending PTransform. This not only organizes the code, but allows the graph in Dataflow to be expanded/collapsed for inspection. class InsertIntoWaitingRoom(PTransform): def __init__(self, params: PipelineParams): super(InsertIntoWaitingRoom, self).__init__() self.params = params def expand(self, source: InputT) -> OutputT: return ( source | "Create Bigtable Rows" >> beam.ParDo(CreateWaitingRoomRowsFn()) | "Bigtable Window" >> beam.WindowInto( window.GlobalWindows(), trigger=Repeatedly(AfterAny(AfterCount(100), AfterProcessingTime(10))), accumulation_mode=AccumulationMode.DISCARDING, ) | "Write to Bigtable" >> WriteToBigTable( self.params.project, self.params.instance, self.params.table ) ) collapsed expanded
Python Apache Beam TaggedOutput Not Working
I'm having an issue with TaggedOutputs in Apache Beam (DataflowRunner) using Python 3.9. I've included the necessary pieces of code below for understanding. Basically the tagged output from parent_check_pipeline for Tag.REQS_SATISFIED) is not working. When the code in CheckParentRequirements yields that tagged output, the pipeline, basically, ends. I get the correct log that the "Element ... has no parents", but the pipeline stops there and doesn't proceed to "Write to Pubsub Topics." I think my meaning can be seen in the dataflow graph I included below as well. The pipeline definitions for each step are separated into functions for ease of testing. We've used this approach in other beam pipelines and it is working so I'm not sure what's missing here. Thanks in advance! Other approaches I've tried declaring the inputs to "Write to Pubsub" as a tuple: p_publish_messages = ( (p_check_parents_needed[Tag.REQS_SATISFIED], p_check_parents_exist[Tag.REQS_SATISFIED]) | "Write to Pubsub Topics" >> beam.ParDo(WriteToPubsubMultiple(topic_1, topic_2)) ) which gives the following error: File ".../lib/python3.9/site-packages/apache_beam/transforms/core.py", line 1578, in expand is_bounded = pcoll.is_bounded AttributeError: 'tuple' object has no attribute 'is_bounded' When using the code defined in publish_messages_pipeline with: p_publish_messages = publish_messages_pipeline([p_check_parents_needed, p_check_parents_exist], pipeline_params) I receive: Traceback (most recent call last): File "/Users/jimmy.hartman/projects/apiary/ces-ingest-eventing/src/dataflow/parent_check_pipeline.py", line 362, in <module> run( File "/Users/jimmy.hartman/projects/apiary/ces-ingest-eventing/src/dataflow/parent_check_pipeline.py", line 317, in run p_publish_messages = publish_messages_pipeline([p_check_parents_needed, p_check_parents_exist], pipeline_params) File "/Users/jimmy.hartman/projects/apiary/ces-ingest-eventing/src/dataflow/parent_check_pipeline.py", line 206, in publish_messages_pipeline tagged_sources File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/transforms/ptransform.py", line 1095, in __ror__ return self.transform.__ror__(pvalueish, self.label) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/transforms/ptransform.py", line 622, in __ror__ p.run().wait_until_finish() File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/pipeline.py", line 574, in run return self.runner.run_pipeline(self, self._options) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/direct/direct_runner.py", line 131, in run_pipeline return runner.run_pipeline(pipeline, options) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 199, in run_pipeline self._latest_run_result = self.run_via_runner_api( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 212, in run_via_runner_api return self.run_stages(stage_context, stages) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 442, in run_stages bundle_results = self._execute_bundle( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 770, in _execute_bundle self._run_bundle( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 999, in _run_bundle result, splits = bundle_manager.process_bundle( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 1309, in process_bundle result_future = self._worker_handler.control_conn.push(process_bundle_req) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/worker_handlers.py", line 380, in push response = self.worker.do_instruction(request) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/sdk_worker.py", line 597, in do_instruction return getattr(self, request_type)( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/sdk_worker.py", line 635, in process_bundle bundle_processor.process_bundle(instruction_id)) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/bundle_processor.py", line 1003, in process_bundle input_op_by_transform_id[element.transform_id].process_encoded( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/bundle_processor.py", line 227, in process_encoded self.output(decoded_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 528, in output _cast_to_receiver(self.receivers[output_index]).receive(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 240, in receive self.consumer.process(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 908, in process delayed_applications = self.dofn_runner.process(o) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1419, in process self._reraise_augmented(exn) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1491, in _reraise_augmented raise exn File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1417, in process return self.do_fn_invoker.invoke_process(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 623, in invoke_process self.output_handler.handle_process_outputs( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1581, in handle_process_outputs self._write_value_to_tag(tag, windowed_value, watermark_estimator) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1694, in _write_value_to_tag self.main_receivers.receive(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 240, in receive self.consumer.process(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 908, in process delayed_applications = self.dofn_runner.process(o) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1419, in process self._reraise_augmented(exn) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1491, in _reraise_augmented raise exn File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1417, in process return self.do_fn_invoker.invoke_process(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 623, in invoke_process self.output_handler.handle_process_outputs( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1581, in handle_process_outputs self._write_value_to_tag(tag, windowed_value, watermark_estimator) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1694, in _write_value_to_tag self.main_receivers.receive(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 240, in receive self.consumer.process(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py", line 908, in process delayed_applications = self.dofn_runner.process(o) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1419, in process self._reraise_augmented(exn) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1507, in _reraise_augmented raise new_exn.with_traceback(tb) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1417, in process return self.do_fn_invoker.invoke_process(windowed_value) File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 623, in invoke_process self.output_handler.handle_process_outputs( File "/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py", line 1571, in handle_process_outputs for result in results: File "/Users/jimmy.hartman/projects/apiary/ces-ingest-eventing/src/dataflow/parent_check_pipeline.py", line 159, in process enc_element = json.dumps(element).encode("utf-8") File "/Users/jimmy.hartman/.pyenv/versions/3.9.13/lib/python3.9/json/__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "/Users/jimmy.hartman/.pyenv/versions/3.9.13/lib/python3.9/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/Users/jimmy.hartman/.pyenv/versions/3.9.13/lib/python3.9/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/Users/jimmy.hartman/.pyenv/versions/3.9.13/lib/python3.9/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type _InvalidUnpickledPCollection is not JSON serializable [while running 'Write to Pubsub Topics'] Code class CheckParentRequirements(DoFn): def process(self, element, *args, **kwargs): parents = get_parents(element) if parents: logging.getLogger(__name__).warning(f"Element {element} has parents: '{parents}'") yield TaggedOutput(value=element, tag=Tag.PARENTS_NEEDED) else: logging.getLogger(__name__).warning(f"Element {element} has no parents") yield TaggedOutput(value=element, tag=Tag.REQS_SATISFIED) class LookupParents(DoFn): def process(self, element): missing_parents = self.get_missing_entities(parent_id_map, element) if missing_parents: self.logger.info(f"'{element}' missing parents {missing_parents}.") element.update({Key.MISSING_PARENTS: missing_parents}) yield TaggedOutput(value=element, tag=Tag.MISSING_PARENTS) else: self.logger.info(f"'{element}' parents found.") yield TaggedOutput(value=element, tag=Tag.REQS_SATISFIED) def get_missing_parents(element): ... class WriteToPubsubMultiple(DoFn): def __init__(self, topic_1, topic_2): self.topic_1 = topic_1 self.topic_2 = topic_2 self.publisher = None def setup(self): self.publisher = pubsub_v1.PublisherClient() def process(self, element, *args, **kwargs): logger = logging.getLogger(__name__) enc_element = json.dumps(element).encode("utf-8") self.publisher.publish(self.topic_1, enc_element) self.publisher.publish(self.topic_2, enc_element) logger.info("Sent message messages.") yield None def parent_check_pipeline(source) -> DoOutputsTuple: p_parent_check = ( source | "Check Parent Requirement" >> beam.ParDo(CheckParentRequirements()).with_outputs(Tag.PARENTS_NEEDED, Tag.REQS_SATISFIED) ) return p_parent_check def lookup_parents_pipeline(source: DoOutputsTuple, params: PipelineParams) -> DoOutputsTuple: p_parents_exist = source[Tag.PARENTS_NEEDED] | "Lookup Parents" >> beam.ParDo( LookupParents(params.database_instance_id, params.database_id) ).with_outputs(Tag.MISSING_PARENTS, Tag.REQS_SATISFIED) return p_parents_exist def waiting_room_insert_pipeline(source: DoOutputsTuple, params: PipelineParams): p_waiting_room_rows = ( source[Tag.MISSING_PARENTS] | "Create Bigtable Rows" >> beam.ParDo(CreateWaitingRoomRows()) | "Bigtable Window" >> beam.WindowInto( window.GlobalWindows(), trigger=Repeatedly(AfterAny(AfterCount(100), AfterProcessingTime(10))), accumulation_mode=AccumulationMode.DISCARDING, ) | "Write to Bigtable" >> WriteToBigTable(params.project_id, params.instance, params.table) ) return p_waiting_room_rows # Not using this right now as I was troubleshooting. This is now in the `run()` method. def publish_messages_pipeline(sources: List[DoOutputsTuple], params: PipelineParams): tagged_sources = (source[Tag.REQS_SATISFIED] for source in sources) p_publish_messages = ( tagged_sources | "Write to Pubsub Topics" >> beam.ParDo(WriteToPubsubMultiple(params.topic_1, params.topic_2)) ) return p_publish_messages def run( pipeline_options, pipeline_params ): with Pipeline(options=pipeline_options) as pipeline: p_source = ( pipeline | "Read from Pub/Sub" >> io.ReadFromPubSub(subscription=input_subscription) | "Parse JSON" >> beam.Map(json.loads) ) p_check_parents_needed = parent_check_pipeline(p_source) p_check_parents_exist = lookup_parents_pipeline(p_check_parents_needed, pipeline_params) p_waiting_room_insert = waiting_room_insert_pipeline(p_check_parents_exist, pipeline_params) p_publish_messages = ( p_check_parents_needed[Tag.REQS_SATISFIED], p_check_parents_exist[Tag.REQS_SATISFIED] | "Write to Pubsub Topics" >> beam.ParDo(WriteToPubsubMultiple(topic_1, topic_2)) ) Dataflow graph:
[ "At a first glance, I see nothing wrong with your tagged outputs (assuming Tag.WHATEVER returns a string). However, I am a bit confused about the way you outsource pipeline parts. Usually, you would use PTransforms instead of simple python functions. That might be the source of your strange behavior.\nI would recommend rewriting all your pipeline methods to PTransforms, e.g.\nclass ParentCheckPipeline(beam.PTransform):\n def expand(self, source):\n p_parent_check = (\n source\n | \"Check Parent Requirement\" >> beam.ParDo(CheckParentRequirements())\n .with_outputs(Tag.PARENTS_NEEDED, Tag.REQS_SATISFIED)\n )\n return p_parent_check\n\nNote the mandatory expand method, containing your pipeline part.\n", "Turns out I needed to take advantage of the apache_beam.Flatten() transform:\n\nFlatten is a Beam transform for PCollection objects that store the same data type. Flatten merges multiple PCollection objects into a single logical PCollection.\n\nThe new publish_messages_pipeline definition would look like this:\ndef publish_messages_pipeline(sources: List[DoOutputsTuple], params: PipelineParams):\n tagged_sources = (source[Tag.REQS_SATISFIED] for source in sources)\n p_publish_messages = (\n tagged_sources\n | \"Flatten inputs\" >> beam.Flatten()\n | \"Write to Pubsub Topics\"\n >> beam.ParDo(WriteToPubsubMultipleFn(params.topic_1, params.topic_2))\n )\n return p_publish_messages\n\nTaking the suggestion from @CaptainNabla, I put the \"composite transform\" code for inserting into bigtable into a class extending PTransform. This not only organizes the code, but allows the graph in Dataflow to be expanded/collapsed for inspection.\nclass InsertIntoWaitingRoom(PTransform):\n def __init__(self, params: PipelineParams):\n super(InsertIntoWaitingRoom, self).__init__()\n self.params = params\n\n def expand(self, source: InputT) -> OutputT:\n return (\n source\n | \"Create Bigtable Rows\" >> beam.ParDo(CreateWaitingRoomRowsFn())\n | \"Bigtable Window\"\n >> beam.WindowInto(\n window.GlobalWindows(),\n trigger=Repeatedly(AfterAny(AfterCount(100), AfterProcessingTime(10))),\n accumulation_mode=AccumulationMode.DISCARDING,\n )\n | \"Write to Bigtable\"\n >> WriteToBigTable(\n self.params.project, self.params.instance, self.params.table\n )\n )\n\n\n\n\n\ncollapsed\nexpanded\n\n\n\n\n\n\n\n\n\n" ]
[ 1, 0 ]
[]
[]
[ "apache_beam", "google_cloud_dataflow", "python" ]
stackoverflow_0074492124_apache_beam_google_cloud_dataflow_python.txt
Q: Why am I getting a RuntimeWarning? I am using a dataframe looking like this: with those dtypes: priceNum float64 volumeNum float64 deliveryStart datetime64[ns, UTC] execution datetime64[ns, UTC] buySell object dtype: object I want to peform a simple calculation using the volumeNum column. Therefore I am splitting the dataframe into slices since I want one value for every deliveryStart: dfs_dict={k: v for k, v in allOurTrades30min.groupby("deliveryStart")} for key in dfs_dict: sort_df(dfs_dict[key]) remaining=calc_remaining(dfs_dict[key]) if remaining<0: dfs_dict[key]["weightedOpening"]= (-calc_weighted(dfs_dict[key][dfs_dict[key]["buySell"]=="S"], remaining)) dfs_dict[key]["remaining"]= remaining else: dfs_dict[key]["weightedOpening"]= calc_weighted(dfs_dict[key][dfs_dict[key]["buySell"]=="B"], remaining) dfs_dict[key]["remaining"]= remaining I am getting this Warning: /opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:45: RuntimeWarning: invalid value encountered in double_scalars and if I look at one of the calculated dataframes via dfs_dict[list(dfs_dict.keys())[1]] it looks like this: I found out that the problem is occuring within the calc_remaining() funciton which looks like this: def calc_remaining(df): remaining=0.0 for i in range(len(df)): if df.iloc[i]["buySell"] == "B": remaining = remaining + df.iloc[i]["volumeNum"] elif df.iloc[i]["buySell"] == "S": remaining = remaining - df.iloc[i]["volumeNum"] remaining = round(remaining,3) return remaining I just don't see the problem. EDIT Some of the dataframes are completly fine. If I concat them all together it looks like this: A: It looks to me like it is coming from adding a number to a NaN. You can do a broad sweep to fix this with .fillna() if you cannot otherwise prevent a NaN from populating those cells.
Why am I getting a RuntimeWarning?
I am using a dataframe looking like this: with those dtypes: priceNum float64 volumeNum float64 deliveryStart datetime64[ns, UTC] execution datetime64[ns, UTC] buySell object dtype: object I want to peform a simple calculation using the volumeNum column. Therefore I am splitting the dataframe into slices since I want one value for every deliveryStart: dfs_dict={k: v for k, v in allOurTrades30min.groupby("deliveryStart")} for key in dfs_dict: sort_df(dfs_dict[key]) remaining=calc_remaining(dfs_dict[key]) if remaining<0: dfs_dict[key]["weightedOpening"]= (-calc_weighted(dfs_dict[key][dfs_dict[key]["buySell"]=="S"], remaining)) dfs_dict[key]["remaining"]= remaining else: dfs_dict[key]["weightedOpening"]= calc_weighted(dfs_dict[key][dfs_dict[key]["buySell"]=="B"], remaining) dfs_dict[key]["remaining"]= remaining I am getting this Warning: /opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:45: RuntimeWarning: invalid value encountered in double_scalars and if I look at one of the calculated dataframes via dfs_dict[list(dfs_dict.keys())[1]] it looks like this: I found out that the problem is occuring within the calc_remaining() funciton which looks like this: def calc_remaining(df): remaining=0.0 for i in range(len(df)): if df.iloc[i]["buySell"] == "B": remaining = remaining + df.iloc[i]["volumeNum"] elif df.iloc[i]["buySell"] == "S": remaining = remaining - df.iloc[i]["volumeNum"] remaining = round(remaining,3) return remaining I just don't see the problem. EDIT Some of the dataframes are completly fine. If I concat them all together it looks like this:
[ "It looks to me like it is coming from adding a number to a NaN. You can do a broad sweep to fix this with .fillna() if you cannot otherwise prevent a NaN from populating those cells.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "runtime" ]
stackoverflow_0074548314_dataframe_pandas_python_runtime.txt
Q: How to use value after checking if exists in a list using 'any' command python I am trying to check if an entered value is in a list of values and then use it if it does using the any command in an if statement. But for some reason when the command finished iterating through the list it won't let me use this value.Can someone where do I neeed to change my code to make it work?. I want to print the key in the end. This is the mentioned if statement: if any(SHA3_256.new(key.export_key()).hexdigest() == hashed_pk for key in publicKeys): print(key) Code Parameters: publicKeys is a list of string:["key1", "key2"]... hashed_ok is the entered string: "0c22352b43d1696ac069a15a3561c9fc4c731e4e458edb7f648544b779f341dd". A: for key in publicKeys: if SHA3_256.new(key.export_key()).hexdigest() == hashed_pk: print(key) # Use `break` here if you want A: Instead of any use next, which retrieves the first value valid in a generator, and use the guard expression as a filter clause, this way: key = next((key for key in publicKeys if SHA3_256.new(key.export_key()).hexdigest() == hashed_pk), "Key not found") print(key) A: You can use the new := assignment for this if you still wanted to keep it as a one liner. An example would be lst = [1, 2, 3] if any((key := k) == 2 for k in lst): print(key) So in your case if any(SHA3_256.new((key := k).export_key()).hexdigest()) == hashed_pk for k in publicKeys): print(key) A: It may not be the most elegant thing to do, but in Python 3.8+, you can use the walrus operator (:=) : if any(SHA3_256.new((correct_key:=key).export_key()).hexdigest() == hashed_pk for key in publicKeys): print(correct_key) A: Variables only exist in the scope in which they're defined. In this case, you're defining any only in the scope of that list comprehension, which is closed before your print(key) statement. My personal view is that that sort of pythonic one-line list comprehension is great for trivially simple cases, but annoying to parse the moment you're trying to do multiple things. I would just use for key in publicKeys: syntax and have your check and print statements in that block.
How to use value after checking if exists in a list using 'any' command python
I am trying to check if an entered value is in a list of values and then use it if it does using the any command in an if statement. But for some reason when the command finished iterating through the list it won't let me use this value.Can someone where do I neeed to change my code to make it work?. I want to print the key in the end. This is the mentioned if statement: if any(SHA3_256.new(key.export_key()).hexdigest() == hashed_pk for key in publicKeys): print(key) Code Parameters: publicKeys is a list of string:["key1", "key2"]... hashed_ok is the entered string: "0c22352b43d1696ac069a15a3561c9fc4c731e4e458edb7f648544b779f341dd".
[ "for key in publicKeys:\n if SHA3_256.new(key.export_key()).hexdigest() == hashed_pk:\n print(key)\n # Use `break` here if you want\n\n", "Instead of any use next, which retrieves the first value valid in a generator, and use the guard expression as a filter clause, this way:\nkey = next((key for key in publicKeys if SHA3_256.new(key.export_key()).hexdigest() == hashed_pk), \"Key not found\")\nprint(key)\n\n", "You can use the new := assignment for this if you still wanted to keep it as a one liner. An example would be\nlst = [1, 2, 3]\nif any((key := k) == 2 for k in lst):\n print(key)\n\nSo in your case\nif any(SHA3_256.new((key := k).export_key()).hexdigest()) == hashed_pk for k in publicKeys):\n print(key)\n\n", "It may not be the most elegant thing to do, but in Python 3.8+, you can use the walrus operator (:=) :\nif any(SHA3_256.new((correct_key:=key).export_key()).hexdigest() == hashed_pk for key in publicKeys):\n print(correct_key)\n\n", "Variables only exist in the scope in which they're defined. In this case, you're defining any only in the scope of that list comprehension, which is closed before your print(key) statement.\nMy personal view is that that sort of pythonic one-line list comprehension is great for trivially simple cases, but annoying to parse the moment you're trying to do multiple things. I would just use for key in publicKeys: syntax and have your check and print statements in that block.\n" ]
[ 1, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074548467_python.txt
Q: What's wrong with this code to find index of list of integers where sum of integers to the left equals the sum to the left? I am going to be given an array of integers. My job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1. My code is: def find_even_index(arr): #your code here for i in range(len(arr)): if sum(arr[0:i]) == sum(arr[i+1:len(arr)]): return i else: return -1 This code works for some lists, but doesn't work for others. What's wrong here? E.g. it doesn't work for [14, -6, -1, -8, 8, 16, 4, -10, -11, -10, 2, 8, 4, 14, -8, -10, 21, -10, -1] it should return 12 but returns -1, likewise for a lot of other lists where it should return an index but returns -1. A: So return returns from the function the moment it's run. You're doing the check and returning one thing or another every time - so if the first element doesn't evenly divide, you immediately return -1. You need to only return false if you go through the entire list without finding a valid N. After you fix that you'll get an index out of bounds error on lists with no valid N. When you reach the last element of range(len(arr)), you'll try to take a slice that starts at len(arr), which is out of bounds. Also this might be intentional, but remember that slice indices are inclusive on the left and exclusive on the right - so your code is not including the element at index i in either slice. Finally this is a slow implementation - you're re-doing the sums for every element of the list, which will be O(n^2). It would be faster to take the left and right sums once at the start (left will be 0), then subtract from the right and add to the left as you traverse each element. A: While I agree with @Edward Peters comment about the last return statement being after the for loop runs, and I also thought there might be a out of index error for the case where the list doesn't have an answer satisfying the results, I didn't find that to be the case here is the code I used. t1 = [14, -6, -1, -8, 8, 16, 4, -10, -11, -10, 2, 8, 4, 14, -8, -10, 21, -10, -1] t2 = [1, 3, 5, 2] def find_even_index(arr): #your code here for i in range(len(arr)): if sum(arr[0:i]) == sum(arr[i+1:len(arr)]): return i return -1 then: find_even_index(t1) yields 12 find_even_index(t2) yields -1
What's wrong with this code to find index of list of integers where sum of integers to the left equals the sum to the left?
I am going to be given an array of integers. My job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1. My code is: def find_even_index(arr): #your code here for i in range(len(arr)): if sum(arr[0:i]) == sum(arr[i+1:len(arr)]): return i else: return -1 This code works for some lists, but doesn't work for others. What's wrong here? E.g. it doesn't work for [14, -6, -1, -8, 8, 16, 4, -10, -11, -10, 2, 8, 4, 14, -8, -10, 21, -10, -1] it should return 12 but returns -1, likewise for a lot of other lists where it should return an index but returns -1.
[ "So return returns from the function the moment it's run. You're doing the check and returning one thing or another every time - so if the first element doesn't evenly divide, you immediately return -1.\nYou need to only return false if you go through the entire list without finding a valid N.\nAfter you fix that you'll get an index out of bounds error on lists with no valid N. When you reach the last element of range(len(arr)), you'll try to take a slice that starts at len(arr), which is out of bounds.\nAlso this might be intentional, but remember that slice indices are inclusive on the left and exclusive on the right - so your code is not including the element at index i in either slice.\nFinally this is a slow implementation - you're re-doing the sums for every element of the list, which will be O(n^2). It would be faster to take the left and right sums once at the start (left will be 0), then subtract from the right and add to the left as you traverse each element.\n", "While I agree with @Edward Peters comment about the last return statement being after the for loop runs, and I also thought there might be a out of index error for the case where the list doesn't have an answer satisfying the results, I didn't find that to be the case here is the code I used.\nt1 = [14, -6, -1, -8, 8, 16, 4, -10, -11, -10, 2, 8, 4, 14, -8, -10, 21, -10, -1] \nt2 = [1, 3, 5, 2] \n\ndef find_even_index(arr):\n #your code here\n for i in range(len(arr)):\n if sum(arr[0:i]) == sum(arr[i+1:len(arr)]):\n return i\n return -1 \n\nthen:\nfind_even_index(t1) yields 12\nfind_even_index(t2) yields -1\n" ]
[ 0, 0 ]
[]
[]
[ "iteration", "python", "slice" ]
stackoverflow_0074548292_iteration_python_slice.txt
Q: How to encode and decode Arabic text in python I want to encode an Arabic string. I actually tried to pass the string as is, but it did not work. I tried to encode it and it also didn't work. Here is the code and the output: جاÙ\x85عة اÙ\x84Ù\x8aرÙ\x85Ù\x88Ù\x83 self.set_font("Arial","",11) self.set_text_color(15,164,12) self.set_y(2.0) str="جامعة اليرموك" str=str.encode("utf-8") str=str.decode("latin1") self.cell(0,5,str,align="C",border=1) I was expecting the output is "جامعة اليرموك" A: If you're using Python3, you don't need to encode or decode anything. Strings are unicode by default: >>> title = "جامعة المبروك" >>> print(title) جامعة المبروك As mentioned in the comments, you shouldn't use str as a variable name, because it's a built-in function in Python. (You can tell it's a built-in function because it's red in your code.) Built-in functions are reserved, and overwriting them can cause unpredictable behavior. But that's not actually your problem here. The code where you're trying to en-/decode is what's causing the jibberish: >>> title = "جامعة المبروك" >>> title = title.encode('utf-8') >>> title = title.decode('latin1') >>> print(title) Ø¬Ø§ÙØ¹Ø© اÙÙØ¨Ø±ÙÙ Just take that out (and change your variable name) and you should be fine. حظ سعيد
How to encode and decode Arabic text in python
I want to encode an Arabic string. I actually tried to pass the string as is, but it did not work. I tried to encode it and it also didn't work. Here is the code and the output: جاÙ\x85عة اÙ\x84Ù\x8aرÙ\x85Ù\x88Ù\x83 self.set_font("Arial","",11) self.set_text_color(15,164,12) self.set_y(2.0) str="جامعة اليرموك" str=str.encode("utf-8") str=str.decode("latin1") self.cell(0,5,str,align="C",border=1) I was expecting the output is "جامعة اليرموك"
[ "If you're using Python3, you don't need to encode or decode anything. Strings are unicode by default:\n>>> title = \"جامعة المبروك\" \n>>> print(title)\nجامعة المبروك\n\nAs mentioned in the comments, you shouldn't use str as a variable name, because it's a built-in function in Python. (You can tell it's a built-in function because it's red in your code.) Built-in functions are reserved, and overwriting them can cause unpredictable behavior.\nBut that's not actually your problem here. The code where you're trying to en-/decode is what's causing the jibberish:\n>>> title = \"جامعة المبروك\"\n>>> title = title.encode('utf-8')\n>>> title = title.decode('latin1')\n>>> print(title)\nØ¬Ø§ÙØ¹Ø© اÙÙØ¨Ø±ÙÙ\n\nJust take that out (and change your variable name) and you should be fine.\nحظ سعيد\n" ]
[ 0 ]
[]
[]
[ "arabic", "encoding", "pyfpdf", "python", "utf_8" ]
stackoverflow_0074479392_arabic_encoding_pyfpdf_python_utf_8.txt
Q: How to find the position of a string in another string without the find() and index() method? My task is to write a code that reproduces the str.find() method. I'm not allowed to use these: str.find(), str.index(), str.split(). So far I have: string = "haystack" if " needle " in (" " + string + " "): print(#here I want to print the first index in which "needle" is in "haystack" else: print(„-1“)) A: Assuming you are simply looking for a way to solve the problem at all (and not in a particularly efficient way), perhaps it would help to consider this type of logic (in pseudocode): for index i in str if searchStr is in str starting at index i return i return -1 where: str is input string to search through ('haystack') searchStr is input string to search for ('needle')
How to find the position of a string in another string without the find() and index() method?
My task is to write a code that reproduces the str.find() method. I'm not allowed to use these: str.find(), str.index(), str.split(). So far I have: string = "haystack" if " needle " in (" " + string + " "): print(#here I want to print the first index in which "needle" is in "haystack" else: print(„-1“))
[ "Assuming you are simply looking for a way to solve the problem at all (and not in a particularly efficient way), perhaps it would help to consider this type of logic (in pseudocode):\nfor index i in str\n if searchStr is in str starting at index i\n return i\nreturn -1\n\nwhere:\n\nstr is input string to search through ('haystack')\nsearchStr is input string to search for ('needle')\n\n" ]
[ 0 ]
[]
[]
[ "indexing", "loops", "python" ]
stackoverflow_0074547150_indexing_loops_python.txt
Q: Python: ValueError: I/O operation on closed file. Input/Output Lab In my Python lab, I need to ask the user how many numbers to store; have them enter said numbers individually and store them in a file named numbers1.txt. Then again, repeat this process but store the numbers in a file named numbers2.txt. From there I had to write some code that would read a line from one file and a line from the other file, the 2 integers are multiplied together and their value is added to a variable called scalar_product which was initialized at 0. The code should stop when one of the files has reached end of file. The code I have so far is as follows: def main(): num = int(input("How many numbers would you like to store")) numbers1 = open('numbers1.txt', 'w') for count in range(1, num + 1): nums = input("Enter each number individually {}:".format(count)) numbers1.write(str(nums) + "\n") numbers1.close() def main_two(): num2 = int(input("How many numbers would you like to store")) numbers2 = open('numbers2.txt', 'w') for count in range(1, num2 + 1): nums2 = input("Enter each number individually {}:".format(count)) numbers2.write(str(nums2) + "\n") numbers2.close() main() main_two() numfile1 = open("numbers1.txt","r") numfile2 = open("numbers2.txt","r") scalar_product = 0 number1 = numfile1.readline() number2 = numfile2.readline() while number1 != "" and number2 != "": scalar_product += int(number1) * int(number2) number1 = numfile1.readline() number2 = numfile2.readline() numfile1.close() numfile2.close() I have no issues with the first few steps, Python prompts the users for the amount of numbers they would like to store but when I reach the section on multiplying the 2 values from numbers1.txt and numbers2.txt I get the following ValueError: How many numbers would you like to store2 Enter each number individually 1:4 Enter each number individually 2:5 How many numbers would you like to store3 Enter each number individually 1:4 Enter each number individually 2:6 Enter each number individually 3:3 Traceback (most recent call last): File "/Users/jake./PycharmProjects/CH9_Munyak_Jacob/ReadingProcessFiles.py", line 31, in <module> number1 = numfile1.readline() ValueError: I/O operation on closed file. Process finished with exit code 1 Can anybody point me in the right direction? I am not sure why It's a closed file when I re-opened it in line 24 and line 25 A: Files must keep open in the loop while reading. while number1 != "" and number2 != "": scalar_product += int(number1) * int(number2) number1 = numfile1.readline() number2 = numfile2.readline() # close files at the end numfile1.close() numfile2.close() A: You are closing the files too soon. The calls to close should be after the loop, not in the loop, but you should be using a with statement to open the files so that they will be closed automatically once you are done with them. Using zip to create a single iterator that reads from both files in parallel is also a good idea. scalar_product = 0 with open("numbers1.txt") as numfile1, open("numbers2.txt") as numfile2: for number1, number2 in zip(numfile1, numfile2): scalar_product += int(number1) * int(number2) You can shorten this even more by using a single generator expression to sum up all the products. with open("numbers1.txt") as numfile1, open("numbers2.txt") as numfile2: scalar_product = sum(int(x) * int(y) for x, y in zip(numfile1, numfile2)) A: #This will be a quick fix for your problem with open("numbers1.txt") as numfile1: with open("numbers2.txt", "r") as numfile2: scalar_product = 0 number1 = numfile1.readline() number2 = numfile2.readline() while number1 != "" and number2 != "": scalar_product += int(number1) * int(number2) number1 = numfile1.readline() number2 = numfile2.readline()
Python: ValueError: I/O operation on closed file. Input/Output Lab
In my Python lab, I need to ask the user how many numbers to store; have them enter said numbers individually and store them in a file named numbers1.txt. Then again, repeat this process but store the numbers in a file named numbers2.txt. From there I had to write some code that would read a line from one file and a line from the other file, the 2 integers are multiplied together and their value is added to a variable called scalar_product which was initialized at 0. The code should stop when one of the files has reached end of file. The code I have so far is as follows: def main(): num = int(input("How many numbers would you like to store")) numbers1 = open('numbers1.txt', 'w') for count in range(1, num + 1): nums = input("Enter each number individually {}:".format(count)) numbers1.write(str(nums) + "\n") numbers1.close() def main_two(): num2 = int(input("How many numbers would you like to store")) numbers2 = open('numbers2.txt', 'w') for count in range(1, num2 + 1): nums2 = input("Enter each number individually {}:".format(count)) numbers2.write(str(nums2) + "\n") numbers2.close() main() main_two() numfile1 = open("numbers1.txt","r") numfile2 = open("numbers2.txt","r") scalar_product = 0 number1 = numfile1.readline() number2 = numfile2.readline() while number1 != "" and number2 != "": scalar_product += int(number1) * int(number2) number1 = numfile1.readline() number2 = numfile2.readline() numfile1.close() numfile2.close() I have no issues with the first few steps, Python prompts the users for the amount of numbers they would like to store but when I reach the section on multiplying the 2 values from numbers1.txt and numbers2.txt I get the following ValueError: How many numbers would you like to store2 Enter each number individually 1:4 Enter each number individually 2:5 How many numbers would you like to store3 Enter each number individually 1:4 Enter each number individually 2:6 Enter each number individually 3:3 Traceback (most recent call last): File "/Users/jake./PycharmProjects/CH9_Munyak_Jacob/ReadingProcessFiles.py", line 31, in <module> number1 = numfile1.readline() ValueError: I/O operation on closed file. Process finished with exit code 1 Can anybody point me in the right direction? I am not sure why It's a closed file when I re-opened it in line 24 and line 25
[ "Files must keep open in the loop while reading.\nwhile number1 != \"\" and number2 != \"\":\n scalar_product += int(number1) * int(number2)\n number1 = numfile1.readline()\n number2 = numfile2.readline()\n\n# close files at the end\nnumfile1.close()\nnumfile2.close()\n\n", "You are closing the files too soon. The calls to close should be after the loop, not in the loop, but you should be using a with statement to open the files so that they will be closed automatically once you are done with them.\nUsing zip to create a single iterator that reads from both files in parallel is also a good idea.\nscalar_product = 0\nwith open(\"numbers1.txt\") as numfile1, open(\"numbers2.txt\") as numfile2:\n for number1, number2 in zip(numfile1, numfile2):\n scalar_product += int(number1) * int(number2)\n\nYou can shorten this even more by using a single generator expression to sum up all the products.\nwith open(\"numbers1.txt\") as numfile1, open(\"numbers2.txt\") as numfile2:\n scalar_product = sum(int(x) * int(y) for x, y in zip(numfile1, numfile2))\n\n", "#This will be a quick fix for your problem\nwith open(\"numbers1.txt\") as numfile1:\n with open(\"numbers2.txt\", \"r\") as numfile2:\n scalar_product = 0\n number1 = numfile1.readline()\n number2 = numfile2.readline()\n while number1 != \"\" and number2 != \"\":\n scalar_product += int(number1) * int(number2)\n number1 = numfile1.readline()\n number2 = numfile2.readline()\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "io", "python", "valueerror" ]
stackoverflow_0074547926_io_python_valueerror.txt
Q: Wrong Shape in Filter of Scipy.ndimage.filters.convolve I am trying to scipy convolve function but it shows an error that there is wrong shape of filter. I have a filter shape of (1, 3, 3, 1) and image shape of (10,8,8,3) I found a similar post but it has one less dimension which is not true in my case. Any idea, how could I resolve this? Sample Code : from scipy import ndimage img1.shape : (10,8,8,3) downsample_filter.shape : (1, 3, 3, 1) filtered_im1 = ndimage.filters.convolve(img1, downsample_filter, mode='reflect') Solution: I have resolved the error by converting both variables into numpy. It can be done by passing a placeholder and image into sess.run() so that we could get the numpy array. But, I am interested to solve this issue using Tensors as I cannot use the above method in Keras Loss Function for y_pred & y_true A: I fixed it by adding cv2.IMREAD_GRAYSCALE while reading the image. cv2.imread("yourImage.jpg", cv2.IMREAD_GRAYSCALE) OR cv2.imread("yourImage.jpg",0) #loading graysclae image
Wrong Shape in Filter of Scipy.ndimage.filters.convolve
I am trying to scipy convolve function but it shows an error that there is wrong shape of filter. I have a filter shape of (1, 3, 3, 1) and image shape of (10,8,8,3) I found a similar post but it has one less dimension which is not true in my case. Any idea, how could I resolve this? Sample Code : from scipy import ndimage img1.shape : (10,8,8,3) downsample_filter.shape : (1, 3, 3, 1) filtered_im1 = ndimage.filters.convolve(img1, downsample_filter, mode='reflect') Solution: I have resolved the error by converting both variables into numpy. It can be done by passing a placeholder and image into sess.run() so that we could get the numpy array. But, I am interested to solve this issue using Tensors as I cannot use the above method in Keras Loss Function for y_pred & y_true
[ "I fixed it by adding cv2.IMREAD_GRAYSCALE while reading the image.\n cv2.imread(\"yourImage.jpg\", cv2.IMREAD_GRAYSCALE)\n OR\n cv2.imread(\"yourImage.jpg\",0) #loading graysclae image\n\n" ]
[ 0 ]
[]
[]
[ "keras", "loss_function", "python", "scipy", "tensorflow" ]
stackoverflow_0047234375_keras_loss_function_python_scipy_tensorflow.txt
Q: Inner merge two DataFrames on string partial match We have the following two data frames temp = pd.DataFrame(np.array([['I am feeling very well',1],['It is hard to believe this happened',0], ['What is love?',1], ['No new friends',0], ['I love this show',1],['Amazing day today',1]]), columns = ['message','sentiment']) temp_truncated = pd.DataFrame(np.array([['I am feeling very',1],['It is hard to believe',1], ['What is',1], ['Amazing day',1]]), columns = ['message','cutoff']) My idea is to create a third DataFrame that would represent the inner join between temp and temp_truncated by finding matches in temp that start with / contain the strings in temp_truncated Desired Output: message sentiment cutoff 0 I am feeling very well 1 1 1 It is hard to believe this happened 0 1 2 What is love 1 1 3 Amazing day today 1 1 A: You can use: import re pattern = '|'.join(map(re.escape, temp_truncated['message'])) key = temp['message'].str.extract(f'({pattern})', expand=False) out = (temp .merge(temp_truncated.rename(columns={'message': 'sub'}), left_on=key, right_on='sub') .drop(columns='sub') ) Output: message sentiment cutoff 0 I am feeling very well 1 1 1 It is hard to believe this happened 0 1 2 What is love? 1 1 3 Amazing day today 1 1 A: Here is an approach using rapidfuzz with pandas.merge : #pip install rapidfuzz from rapidfuzz import process out = ( temp_truncated .assign(message_adapted = (temp_truncated['message'] .map(lambda x: process.extractOne(x, temp['message']))).str[0]) .merge(temp, left_on="message_adapted", right_on="message", how="left", suffixes=("_", "")) .drop(columns=["message_adapted", "message_"]) .loc[:, temp.columns.tolist() + ["cutoff"]] ) # Output : print(out) message sentiment cutoff 0 I am feeling very well 1 1 1 It is hard to believe this happened 0 1 2 What is love? 1 1 3 Amazing day today 1 1 A: You can use str.startswith, or other str. functions such as str.contains in an apply to get a matches dataframe: matches = temp_truncated.message.apply( lambda x: temp[temp.message.str.startswith(x)]['sentiment'] ).dropna(how='all') This matches dataframe contains the rows of temp_truncated which has a match with one of the rows in temp. These temp rows are the columns of the matches dataframe. The values are the sentiment values of these temp rows. With this you can filter the temp dataframe with only matched rows and then enrich it with the corresponding cutoff value from temp_truncated: df = temp.iloc[matches.columns] df.index = matches.index df = df.merge(temp_truncated['cutoff'], left_index=True, right_index=True) Result matches your desired output: message sentiment cutoff 0 I am feeling very well 1 1 1 It is hard to believe this happened 0 1 2 What is love? 1 1 3 Amazing day today 1 1
Inner merge two DataFrames on string partial match
We have the following two data frames temp = pd.DataFrame(np.array([['I am feeling very well',1],['It is hard to believe this happened',0], ['What is love?',1], ['No new friends',0], ['I love this show',1],['Amazing day today',1]]), columns = ['message','sentiment']) temp_truncated = pd.DataFrame(np.array([['I am feeling very',1],['It is hard to believe',1], ['What is',1], ['Amazing day',1]]), columns = ['message','cutoff']) My idea is to create a third DataFrame that would represent the inner join between temp and temp_truncated by finding matches in temp that start with / contain the strings in temp_truncated Desired Output: message sentiment cutoff 0 I am feeling very well 1 1 1 It is hard to believe this happened 0 1 2 What is love 1 1 3 Amazing day today 1 1
[ "You can use:\nimport re\npattern = '|'.join(map(re.escape, temp_truncated['message']))\n\nkey = temp['message'].str.extract(f'({pattern})', expand=False)\n\nout = (temp\n .merge(temp_truncated.rename(columns={'message': 'sub'}),\n left_on=key, right_on='sub')\n .drop(columns='sub')\n)\n\nOutput:\n message sentiment cutoff\n0 I am feeling very well 1 1\n1 It is hard to believe this happened 0 1\n2 What is love? 1 1\n3 Amazing day today 1 1\n\n", "Here is an approach using rapidfuzz with pandas.merge :\n#pip install rapidfuzz\nfrom rapidfuzz import process\n\nout = (\n temp_truncated\n .assign(message_adapted = (temp_truncated['message']\n .map(lambda x: process.extractOne(x, temp['message']))).str[0])\n .merge(temp, left_on=\"message_adapted\", right_on=\"message\", how=\"left\", suffixes=(\"_\", \"\"))\n .drop(columns=[\"message_adapted\", \"message_\"])\n .loc[:, temp.columns.tolist() + [\"cutoff\"]]\n )\n\n# Output :\nprint(out)\n message sentiment cutoff\n0 I am feeling very well 1 1\n1 It is hard to believe this happened 0 1\n2 What is love? 1 1\n3 Amazing day today 1 1\n\n", "You can use str.startswith, or other str. functions such as str.contains in an apply to get a matches dataframe:\nmatches = temp_truncated.message.apply(\n lambda x: temp[temp.message.str.startswith(x)]['sentiment']\n).dropna(how='all')\n\nThis matches dataframe contains the rows of temp_truncated which has a match with one of the rows in temp. These temp rows are the columns of the matches dataframe. The values are the sentiment values of these temp rows.\nWith this you can filter the temp dataframe with only matched rows and then enrich it with the corresponding cutoff value from temp_truncated:\ndf = temp.iloc[matches.columns]\ndf.index = matches.index\ndf = df.merge(temp_truncated['cutoff'], left_index=True, right_index=True)\n\nResult matches your desired output:\n message sentiment cutoff\n0 I am feeling very well 1 1\n1 It is hard to believe this happened 0 1\n2 What is love? 1 1\n3 Amazing day today 1 1\n\n" ]
[ 5, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074548343_dataframe_pandas_python.txt
Q: Python seaborn histplot returns StopIteration I installed seaborn, but when I do the example from the Seaborn website, I get StopIteration message, how do I fix it? import seaborn as sns penguins = sns.load_dataset("penguins") sns.histplot(data=penguins, x="flipper_length_mm") StopIteration Traceback (most recent call last) Cell In [33], line 1 ----> 1 sns.histplot(data=penguins, x="flipper_length_mm") image A: The problem seem to be in the default color definition function. If you specify a color you can skip the error: sns.histplot(data=penguins, x="flipper_length_mm", color='blue') That solved the problem for me, hope it does for you as well. Cheers A: The problem is with matplotlib==3.6.1 You have 2 variants: Upgrade matplotlib up to 3.6.2 version via pip install matplotlib --upgrade Downgrade matplotlib to 3.6.0 version via pip install matplotlib==3.6.0 --force-reinstall Both variants worked for me. Here is the same issue on GitHub: https://github.com/mwaskom/seaborn/issues/3072
Python seaborn histplot returns StopIteration
I installed seaborn, but when I do the example from the Seaborn website, I get StopIteration message, how do I fix it? import seaborn as sns penguins = sns.load_dataset("penguins") sns.histplot(data=penguins, x="flipper_length_mm") StopIteration Traceback (most recent call last) Cell In [33], line 1 ----> 1 sns.histplot(data=penguins, x="flipper_length_mm") image
[ "The problem seem to be in the default color definition function. If you specify a color you can skip the error:\nsns.histplot(data=penguins, x=\"flipper_length_mm\", color='blue')\n\nThat solved the problem for me, hope it does for you as well.\nCheers\n", "The problem is with matplotlib==3.6.1\nYou have 2 variants:\n\nUpgrade matplotlib up to 3.6.2 version via\n\npip install matplotlib --upgrade\n\n\nDowngrade matplotlib to 3.6.0 version via\n\npip install matplotlib==3.6.0 --force-reinstall\n\nBoth variants worked for me.\nHere is the same issue on GitHub: https://github.com/mwaskom/seaborn/issues/3072\n" ]
[ 0, 0 ]
[]
[]
[ "python", "seaborn", "stopiteration" ]
stackoverflow_0074104246_python_seaborn_stopiteration.txt
Q: Treeview: How to set values in a specific row where row contains "x" value? I have a treeview with the following columns: self.columns = ("Name", "Status", "Activity") This treeview is updated depending on the socket message and client name it receives. If the program receives "NAME:", it will insert a new row in the treeview with the client name placed under the "Name" column. Else if it's "CLOSED:", the "Status" and "Activity" columns where client name given is located will be updated. import tkinter as tk from tkinter import ttk as tick import socket from threading import Thread class GUI2(cust.CTk): #second window, not the root def __init__(self, a, b, c, d, e): self.PORT = a self.SERVER = b self.ADDRESS = c self.FORMAT = d self.host = e self.master2 = cust.CTkToplevel() self.columns = ("name", "status", "activity") self.clientlist = tick.Treeview(self.clientframe, columns = self.columns, show = "tree") self.clientlist.grid(row = 0, column = 0, sticky = "nswe") self.clientlist.column("#0", minwidth = 0, width = 10, stretch = False) self.clientlist.column("name", minwidth = 0, width = 140, stretch = False) self.clientlist.column("status", minwidth = 0, width = 140, stretch = False) self.clientlist.column("activity", minwidth = 0, width = 140, stretch = False) self.thread = Thread(target = self.initreceiver) self.thread.start() def initreceiver(self): try: while True: self.message = self.host.recv(1024).decode(self.FORMAT) if "NAME:" in self.message: x = self.message.replace("NAME:", "") #removes "NAME:" to get the clientname self.clientlist.insert("", cust.END, iid = x, values = x) #inserts new row and display only client name; #also sets iid the same as the client name for reference elif "CLOSED:" in self.message: x = self.message.replace("CLOSED", "") #remove "CLOSED:" to get clientname self.clientlist.set(x, "Status", "Eyes are closed") #set "Status" column with the new value self.clientlist.set(x, "Activity", "Eyes are closed") #set "Activity" column with the new value except Exception: print (traceback.format_exc()) Error is as follows: Traceback (most recent call last): File "F:\Personal Programs\Python\Lobby + Tracking\mainmenu.py", line 438, in initreceiver self.clientlist.set(x, "status", "Eyes are closed") File "F:\Program Files (x86)\Python\lib\tkinter\ttk.py", line 1459, in set res = self.tk.call(self._w, "set", item, column, value) _tkinter.TclError: Item :Maikz not found #Maikz is the example client name sent It looks like .set() method needs item value for the first argument, but I don't know what to put; I'm learning Treeview for the first time. I need to be able to set the "Status" and "Activity" cells' values where their "Name" value matches the client name. Any advice or alternative solution is appreciated. A: Thanks to @acw1668, it turns out the cause of the error was a spelling mistake; in x = self.message.replace("CLOSED", "") a : was missing. To set the values of "Status" and "Activity" where the "Name" value is the same as the client name, the code is as follows: elif "CLOSED:" in self.message: x = self.message.replace("CLOSED:", "") self.clientlist.set(x, "Status", "Eyes are closed") self.clientlist.set(x, "Activity", "Eyes are closed") where x is the client name and is also the item iid as previously set in the line self.clientlist.insert("", cust.END, iid = x, values = x) when inserting a new row. A: As suggested in my comment, you can split the received message into action and name and use action in if checking and name as the row ID: def initreceiver(self): try: while True: self.message = self.host.recv(1024).decode(self.FORMAT) action, name = self.message.split(":") if action == "NAME": self.clientlist.insert("", cust.END, iid=name, values=name) elif action == "CLOSED": self.clientlist.set(name, "status", "Eyes are closed") self.clientlist.set(name, "activity", "Eyes are closed") except: print(traceback.format_exc())
Treeview: How to set values in a specific row where row contains "x" value?
I have a treeview with the following columns: self.columns = ("Name", "Status", "Activity") This treeview is updated depending on the socket message and client name it receives. If the program receives "NAME:", it will insert a new row in the treeview with the client name placed under the "Name" column. Else if it's "CLOSED:", the "Status" and "Activity" columns where client name given is located will be updated. import tkinter as tk from tkinter import ttk as tick import socket from threading import Thread class GUI2(cust.CTk): #second window, not the root def __init__(self, a, b, c, d, e): self.PORT = a self.SERVER = b self.ADDRESS = c self.FORMAT = d self.host = e self.master2 = cust.CTkToplevel() self.columns = ("name", "status", "activity") self.clientlist = tick.Treeview(self.clientframe, columns = self.columns, show = "tree") self.clientlist.grid(row = 0, column = 0, sticky = "nswe") self.clientlist.column("#0", minwidth = 0, width = 10, stretch = False) self.clientlist.column("name", minwidth = 0, width = 140, stretch = False) self.clientlist.column("status", minwidth = 0, width = 140, stretch = False) self.clientlist.column("activity", minwidth = 0, width = 140, stretch = False) self.thread = Thread(target = self.initreceiver) self.thread.start() def initreceiver(self): try: while True: self.message = self.host.recv(1024).decode(self.FORMAT) if "NAME:" in self.message: x = self.message.replace("NAME:", "") #removes "NAME:" to get the clientname self.clientlist.insert("", cust.END, iid = x, values = x) #inserts new row and display only client name; #also sets iid the same as the client name for reference elif "CLOSED:" in self.message: x = self.message.replace("CLOSED", "") #remove "CLOSED:" to get clientname self.clientlist.set(x, "Status", "Eyes are closed") #set "Status" column with the new value self.clientlist.set(x, "Activity", "Eyes are closed") #set "Activity" column with the new value except Exception: print (traceback.format_exc()) Error is as follows: Traceback (most recent call last): File "F:\Personal Programs\Python\Lobby + Tracking\mainmenu.py", line 438, in initreceiver self.clientlist.set(x, "status", "Eyes are closed") File "F:\Program Files (x86)\Python\lib\tkinter\ttk.py", line 1459, in set res = self.tk.call(self._w, "set", item, column, value) _tkinter.TclError: Item :Maikz not found #Maikz is the example client name sent It looks like .set() method needs item value for the first argument, but I don't know what to put; I'm learning Treeview for the first time. I need to be able to set the "Status" and "Activity" cells' values where their "Name" value matches the client name. Any advice or alternative solution is appreciated.
[ "Thanks to @acw1668, it turns out the cause of the error was a spelling mistake; in x = self.message.replace(\"CLOSED\", \"\") a : was missing.\nTo set the values of \"Status\" and \"Activity\" where the \"Name\" value is the same as the client name, the code is as follows:\nelif \"CLOSED:\" in self.message:\n x = self.message.replace(\"CLOSED:\", \"\") \n self.clientlist.set(x, \"Status\", \"Eyes are closed\") \n self.clientlist.set(x, \"Activity\", \"Eyes are closed\")\n \n\nwhere x is the client name and is also the item iid as previously set in the line self.clientlist.insert(\"\", cust.END, iid = x, values = x) when inserting a new row.\n", "As suggested in my comment, you can split the received message into action and name and use action in if checking and name as the row ID:\ndef initreceiver(self):\n try:\n while True:\n self.message = self.host.recv(1024).decode(self.FORMAT)\n action, name = self.message.split(\":\")\n if action == \"NAME\":\n self.clientlist.insert(\"\", cust.END, iid=name, values=name)\n elif action == \"CLOSED\":\n self.clientlist.set(name, \"status\", \"Eyes are closed\")\n self.clientlist.set(name, \"activity\", \"Eyes are closed\")\n except:\n print(traceback.format_exc())\n\n" ]
[ 1, 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074546782_python_tkinter.txt
Q: Add an image (nparray) to a dictionary I created an empty dictionary in python. I'm reading images and processing them in a loop and after processing, the result is a numpy array. I'd like to add the nparray to the newly created dictionary and store a sequential integer as they key, and the array as the value. How do I get started? In the end I'd like to add these processed images to an imagegrid for display in my jupyter notebook and have code to do so if they are in a dictionary. Maybe there's an easier way to do this? stopsign_classifier = cv2.CascadeClassifier('haarcascade_stopsigns.xml') img_dict = {} folder = "D:\\temp\\" for imagesdir in os.listdir(folder): imgName = imagesdir img = cv2.imread(folder + imgName) signs = stopsign_classifier.detectMultiScale(img, scaleFactor= 1.01, minNeighbors = 9) #check if stop signs exist in the photo if signs is (): print("No stop signs found") # Draw a box around stop signs that were identified based on the return info from the stop sign classifier else: for (x, y, w, h) in signs: cv2.rectangle(img, (x,y), (x+w,y+h), (255, 255 , 255), 8) # code for adding img to the dictionary here A: I'd like to add the nparray to the newly created dictionary and store a sequential integer as they key to me sounds like a list, where elements are already indexed with consecutive numbers. If you want to use a dictionary: #init empty dictionary img_dict = {} img_n = 0 for imagesdir in os.listdir(folder): # your code # update dictionary img_dict[str(img_n)] = img img_n += 1 Then you will access any element of the dictionary like this img_dict["3"] ... However, if the linear incremental access is exactly what you want, consider using a list: #init empty list img_list = [] for imagesdir in os.listdir(folder): #your code # update list img_list.append(img) Then you will access any element of the list like this img_list[3] ...
Add an image (nparray) to a dictionary
I created an empty dictionary in python. I'm reading images and processing them in a loop and after processing, the result is a numpy array. I'd like to add the nparray to the newly created dictionary and store a sequential integer as they key, and the array as the value. How do I get started? In the end I'd like to add these processed images to an imagegrid for display in my jupyter notebook and have code to do so if they are in a dictionary. Maybe there's an easier way to do this? stopsign_classifier = cv2.CascadeClassifier('haarcascade_stopsigns.xml') img_dict = {} folder = "D:\\temp\\" for imagesdir in os.listdir(folder): imgName = imagesdir img = cv2.imread(folder + imgName) signs = stopsign_classifier.detectMultiScale(img, scaleFactor= 1.01, minNeighbors = 9) #check if stop signs exist in the photo if signs is (): print("No stop signs found") # Draw a box around stop signs that were identified based on the return info from the stop sign classifier else: for (x, y, w, h) in signs: cv2.rectangle(img, (x,y), (x+w,y+h), (255, 255 , 255), 8) # code for adding img to the dictionary here
[ "I'd like to add the nparray to the newly created dictionary and store a sequential integer as they key to me sounds like a list, where elements are already indexed with consecutive numbers.\nIf you want to use a dictionary:\n\n#init empty dictionary\nimg_dict = {} \nimg_n = 0\n\nfor imagesdir in os.listdir(folder):\n # your code\n\n # update dictionary\n img_dict[str(img_n)] = img\n img_n += 1\n\n\nThen you will access any element of the dictionary like this\n\nimg_dict[\"3\"] ... \n\n\nHowever, if the linear incremental access is exactly what you want, consider using a list:\n#init empty list\nimg_list = []\n\nfor imagesdir in os.listdir(folder):\n #your code\n\n # update list\n img_list.append(img)\n\nThen you will access any element of the list like this\n\nimg_list[3] ... \n\n\n" ]
[ 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074548666_arrays_numpy_python.txt
Q: TypeError: 'module' object is not callable File "C:\Users\Administrator\Documents\Mibot\oops\blinkserv.py", line 82, in __init__ self.serv = socket(AF_INET,SOCK_STREAM) TypeError: 'module' object is not callable Why am I getting this error? I'm confused. What do you need to know to answer my question? A: socket is a module, containing the class socket. You need to do socket.socket(...) or from socket import socket: >>> import socket >>> socket <module 'socket' from 'C:\Python27\lib\socket.pyc'> >>> socket.socket <class 'socket._socketobject'> >>> >>> from socket import socket >>> socket <class 'socket._socketobject'> This is what the error message means: It says module object is not callable, because your code is calling a module object. A module object is the type of thing you get when you import a module. What you were trying to do is to call a class object within the module object that happens to have the same name as the module that contains it. Here is a way to logically break down this sort of error: "module object is not callable. Python is telling me my code trying to call something that cannot be called. What is my code trying to call?" "The code is trying to call on socket. That should be callable! Is the variable socket is what I think it is?` I should print out what socket is and check print(socket) A: Assume that the content of YourClass.py is: class YourClass: # ...... If you use: from YourClassParentDir import YourClass # means YourClass.py In this way, you will get TypeError: 'module' object is not callable if you then tried to call YourClass(). But, if you use: from YourClassParentDir.YourClass import YourClass # means Class YourClass or use YourClass.YourClass(), it works. A: Add to the main __init__.py in YourClassParentDir, e.g.: from .YourClass import YourClass Then, you will have an instance of your class ready when you import it into another script: from YourClassParentDir import YourClass A: Short answer: You are calling a file/directory as a function instead of real function Read on: This kind of error happens when you import module thinking it as function and call it. So in python module is a .py file. Packages(directories) can also be considered as modules. Let's say I have a create.py file. In that file I have a function like this: #inside create.py def create(): pass Now, in another code file if I do like this: #inside main.py file import create create() #here create refers to create.py , so create.create() would work here It gives this error as am calling the create.py file as a function. so I gotta do this: from create import create create() #now it works. A: Here is another gotcha, that took me awhile to see even after reading these posts. I was setting up a script to call my python bin scripts. I was getting the module not callable too. My zig was that I was doing the following: from mypackage.bin import myscript ... myscript(...) when my zag needed to do the following: from mypackage.bin.myscript import myscript ... myscript(...) In summary, double check your package and module nesting. What I am trying to do is have a scripts directory that does not have the *.py extension, and still have the 'bin' modules to be in mypackage/bin and these have my *.py extension. I am new to packaging, and trying to follow the standards as I am interpreting them. So, I have at the setup root: setup.py scripts/ script1 mypackage/ bin/ script1.py subpackage1/ subpackage_etc/ If this is not compliant with standard, please let me know. A: It seems like what you've done is imported the socket module as import socket. Therefore socket is the module. You either need to change that line to self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM), as well as every other use of the socket module, or change the import statement to from socket import socket. Or you've got an import socket after your from socket import *: >>> from socket import * >>> serv = socket(AF_INET,SOCK_STREAM) >>> import socket >>> serv = socket(AF_INET,SOCK_STREAM) Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: 'module' object is not callable A: I know this thread is a year old, but the real problem is in your working directory. I believe that the working directory is C:\Users\Administrator\Documents\Mibot\oops\. Please check for the file named socket.py in this directory. Once you find it, rename or move it. When you import socket, socket.py from the current directory is used instead of the socket.py from Python's directory. Hope this helped. :) Note: Never use the file names from Python's directory to save your program's file name; it will conflict with your program(s). A: When configuring an console_scripts entrypoint in setup.py I found this issue existed when the endpoint was a module or package rather than a function within the module. Traceback (most recent call last): File "/Users/ubuntu/.virtualenvs/virtualenv/bin/mycli", line 11, in <module> load_entry_point('my-package', 'console_scripts', 'mycli')() TypeError: 'module' object is not callable For example from setuptools import setup setup ( # ... entry_points = { 'console_scripts': [mycli=package.module.submodule] }, # ... ) Should have been from setuptools import setup setup ( # ... entry_points = { 'console_scripts': [mycli=package.module.submodule:main] }, # ... ) So that it would refer to a callable function rather than the module itself. It seems to make no difference if the module has a if __name__ == '__main__': block. This will not make the module callable. A: I faced the same problem. then I tried not using from YourClass import YourClass I just copied the whole code of YourClass.py and run it on the main code (or current code).it solved the error A: I guess you have overridden the builtin function/variable or something else "module" by setting the global variable "module". just print the module see whats in it. A: Here's a possible extra edge case that I stumbled upon and was puzzled by for a while, hope it helps someone: In some_module/a.py: def a(): pass In some_module/b.py: from . import a def b(): a() In some_module/__init__.py: from .b import b from .a import a main.py: from some_module import b b() Then because when main.py loads b, it goes via __init__.py which tries to load b.py before a.py. This means when b.py tries to load a it gets the module rather than the function - meaning you'll get the error message module object is not callable The solution here is to swap the order in some_module/__init__.py: from .a import a from .b import b Or, if this would create a circular dependency, change your file names to not match the functions, and load directly from the files rather than relying on __init__.py A: you are using the name of a module instead of the name of the class use import socket and then socket.socket(...) its a weird thing with the module, but you can also use something like import socket as sock and then use sock.socket(...)
TypeError: 'module' object is not callable
File "C:\Users\Administrator\Documents\Mibot\oops\blinkserv.py", line 82, in __init__ self.serv = socket(AF_INET,SOCK_STREAM) TypeError: 'module' object is not callable Why am I getting this error? I'm confused. What do you need to know to answer my question?
[ "socket is a module, containing the class socket.\nYou need to do socket.socket(...) or from socket import socket:\n>>> import socket\n>>> socket\n<module 'socket' from 'C:\\Python27\\lib\\socket.pyc'>\n>>> socket.socket\n<class 'socket._socketobject'>\n>>>\n>>> from socket import socket\n>>> socket\n<class 'socket._socketobject'>\n\nThis is what the error message means:\nIt says module object is not callable, because your code is calling a module object. A module object is the type of thing you get when you import a module. What you were trying to do is to call a class object within the module object that happens to have the same name as the module that contains it.\nHere is a way to logically break down this sort of error:\n\n\"module object is not callable. Python is telling me my code trying to call something that cannot be called. What is my code trying to call?\"\n\"The code is trying to call on socket. That should be callable! Is the variable socket is what I think it is?`\nI should print out what socket is and check print(socket)\n\n", "Assume that the content of YourClass.py is:\nclass YourClass:\n # ......\n\nIf you use:\nfrom YourClassParentDir import YourClass # means YourClass.py\n\nIn this way, you will get TypeError: 'module' object is not callable if you then tried to call YourClass().\nBut, if you use:\nfrom YourClassParentDir.YourClass import YourClass # means Class YourClass\n\nor use YourClass.YourClass(), it works.\n", "Add to the main __init__.py in YourClassParentDir, e.g.:\nfrom .YourClass import YourClass\n\nThen, you will have an instance of your class ready when you import it into another script:\nfrom YourClassParentDir import YourClass\n\n", "Short answer: You are calling a file/directory as a function instead of real function\nRead on:\nThis kind of error happens when you import module thinking it as function and call it.\nSo in python module is a .py file. Packages(directories) can also be considered as modules.\nLet's say I have a create.py file. In that file I have a function like this:\n#inside create.py\ndef create():\n pass\n\nNow, in another code file if I do like this:\n#inside main.py file\nimport create\ncreate() #here create refers to create.py , so create.create() would work here\n\nIt gives this error as am calling the create.py file as a function.\nso I gotta do this:\nfrom create import create\ncreate() #now it works.\n\n", "Here is another gotcha, that took me awhile to see even after reading these posts. I was setting up a script to call my python bin scripts. I was getting the module not callable too.\nMy zig was that I was doing the following:\nfrom mypackage.bin import myscript\n...\nmyscript(...)\n\nwhen my zag needed to do the following:\nfrom mypackage.bin.myscript import myscript\n...\nmyscript(...)\n\nIn summary, double check your package and module nesting. \nWhat I am trying to do is have a scripts directory that does not have the *.py extension, and still have the 'bin' modules to be in mypackage/bin and these have my *.py extension. I am new to packaging, and trying to follow the standards as I am interpreting them. So, I have at the setup root: \nsetup.py\nscripts/\n script1\nmypackage/\n bin/\n script1.py\n subpackage1/\n subpackage_etc/\n\nIf this is not compliant with standard, please let me know.\n", "It seems like what you've done is imported the socket module as import socket. Therefore socket is the module. You either need to change that line to self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM), as well as every other use of the socket module, or change the import statement to from socket import socket.\nOr you've got an import socket after your from socket import *:\n>>> from socket import *\n>>> serv = socket(AF_INET,SOCK_STREAM)\n>>> import socket\n>>> serv = socket(AF_INET,SOCK_STREAM)\nTraceback (most recent call last):\n File \"<input>\", line 1, in <module>\nTypeError: 'module' object is not callable\n\n", "I know this thread is a year old, but the real problem is in your working directory.\nI believe that the working directory is C:\\Users\\Administrator\\Documents\\Mibot\\oops\\. Please check for the file named socket.py in this directory. Once you find it, rename or move it. When you import socket, socket.py from the current directory is used instead of the socket.py from Python's directory. Hope this helped. :)\nNote: Never use the file names from Python's directory to save your program's file name; it will conflict with your program(s).\n", "When configuring an console_scripts entrypoint in setup.py I found this issue existed when the endpoint was a module or package rather than a function within the module.\nTraceback (most recent call last):\n File \"/Users/ubuntu/.virtualenvs/virtualenv/bin/mycli\", line 11, in <module>\nload_entry_point('my-package', 'console_scripts', 'mycli')()\nTypeError: 'module' object is not callable\n\nFor example\nfrom setuptools import setup\nsetup (\n# ...\n entry_points = {\n 'console_scripts': [mycli=package.module.submodule]\n },\n# ...\n)\n\nShould have been\nfrom setuptools import setup\nsetup (\n# ...\n entry_points = {\n 'console_scripts': [mycli=package.module.submodule:main]\n },\n# ...\n)\n\nSo that it would refer to a callable function rather than the module itself. It seems to make no difference if the module has a if __name__ == '__main__': block. This will not make the module callable. \n", "I faced the same problem. then I tried not using\nfrom YourClass import YourClass\nI just copied the whole code of YourClass.py and run it on the main code (or current code).it solved the error\n", "I guess you have overridden the builtin function/variable or something else \"module\" by setting the global variable \"module\". just print the module see whats in it.\n", "Here's a possible extra edge case that I stumbled upon and was puzzled by for a while, hope it helps someone:\nIn some_module/a.py:\ndef a():\n pass\n\nIn some_module/b.py:\nfrom . import a\n\ndef b():\n a()\n\nIn some_module/__init__.py:\nfrom .b import b\nfrom .a import a\n\nmain.py:\nfrom some_module import b\n\nb()\n\nThen because when main.py loads b, it goes via __init__.py which tries to load b.py before a.py. This means when b.py tries to load a it gets the module rather than the function - meaning you'll get the error message module object is not callable\nThe solution here is to swap the order in some_module/__init__.py:\nfrom .a import a\nfrom .b import b\n\nOr, if this would create a circular dependency, change your file names to not match the functions, and load directly from the files rather than relying on __init__.py\n", "you are using the name of a module instead of the name of the class\nuse\nimport socket\n\nand then\nsocket.socket(...)\n\nits a weird thing with the module, but you can also use something like\nimport socket as sock\n\nand then use\nsock.socket(...)\n\n" ]
[ 762, 311, 126, 50, 37, 24, 8, 1, 1, 0, 0, 0 ]
[ "A simple way to solve this problem is export thePYTHONPATH variable enviroment. For example, for Python 2.6 in Debian/GNU Linux: \nexport PYTHONPATH=/usr/lib/python2.6`\n\nIn other operating systems, you would first find the location of this module or the socket.py file.\n", "check the import statements since a module is not callable.\nIn Python, everything (including functions, methods, modules, classes etc.) is an object.\n" ]
[ -1, -3 ]
[ "python", "sockets" ]
stackoverflow_0004534438_python_sockets.txt
Q: Why `itertools.repeat` always generate the same random number? Compare the outputs of these two functions: from itertools import repeat def rand_list1(): l = lambda: np.random.rand(3) return list(repeat(l(), 5)) def rand_list2(): return [np.random.rand(3) for i in range(5)] We see that rand_list1 who uses itetools.repeat always generates the same 3 numbers. why is this? Can it be avoided, so each call of rand_list() will generate new numbers? For example, the output of rand_list1(): [[0.07678796 0.22623777 0.07533145] [0.07678796 0.22623777 0.07533145] [0.07678796 0.22623777 0.07533145] [0.07678796 0.22623777 0.07533145] [0.07678796 0.22623777 0.07533145]] and the output of rand_list2(): [[0.77863856 0.30345662 0.7007517 ] [0.56422447 0.97138115 0.47976387] [0.20576279 0.92875791 0.06518335] [0.2992384 0.89726684 0.16917078] [0.8440534 0.38016789 0.51691172]] A: There is a basic miscomprehension on how the language works in your question. With the lambda expression, you simply create a new function named l. At the moment you do l() Python will call the function - and it will return a value: it is the returned value that will be used in place of the expression l() in the remaining of the larger expression. So, in this case, you are actually calling repeat with a single, already generated, number as the first parameter. FUnctions that are passed as arguments to be called on their destination, and then are run anew each time are an allowed construct in Python, but (1) they depend on the receiving function being able to use functions as arguments, and that is not the case of repeat, and (2) more importanty one has to pass the function name without typing in the parentheses. In this case, repeat is redundant, as the universal syntax that allows one to call a function multiple times to create an iterator already does the repetition you thought repeat would create for you. Just do: return [l() for _ in range(5)] This will call l() for each interaction of the loop. (btw, one should strongly avoid l as a single variable or function name in any context, as in many fonts it ishard to distinguish l from 1) A: The reason why list(repeat(l(), 5)) repeats the same value. itertools.repeat() will just iterate the same result. Because l() is assigned the result of l() in list(repeat(l(), 5)) when the l is called (which means l()). itertools.repeat() document repeat(10, 3) --> 10 10 10 So what is exactly going on? stage 1 list(repeat(l(), 5)) stage 2 list(repeat([some numbers], 5)) stage 3 list(repeat([some numbers], 5)) --> [some numbers], [some numbers], [some numbers], [some numbers], [some numbers]
Why `itertools.repeat` always generate the same random number?
Compare the outputs of these two functions: from itertools import repeat def rand_list1(): l = lambda: np.random.rand(3) return list(repeat(l(), 5)) def rand_list2(): return [np.random.rand(3) for i in range(5)] We see that rand_list1 who uses itetools.repeat always generates the same 3 numbers. why is this? Can it be avoided, so each call of rand_list() will generate new numbers? For example, the output of rand_list1(): [[0.07678796 0.22623777 0.07533145] [0.07678796 0.22623777 0.07533145] [0.07678796 0.22623777 0.07533145] [0.07678796 0.22623777 0.07533145] [0.07678796 0.22623777 0.07533145]] and the output of rand_list2(): [[0.77863856 0.30345662 0.7007517 ] [0.56422447 0.97138115 0.47976387] [0.20576279 0.92875791 0.06518335] [0.2992384 0.89726684 0.16917078] [0.8440534 0.38016789 0.51691172]]
[ "There is a basic miscomprehension on how the language works in your question.\nWith the lambda expression, you simply create a new function named l.\nAt the moment you do l() Python will call the function - and it will return a value: it is the returned value that will be used in place of the expression l() in the remaining of the larger expression. So, in this case, you are actually calling repeat with a single, already generated, number as the first parameter.\nFUnctions that are passed as arguments to be called on their destination, and then are run anew each time are an allowed construct in Python, but (1) they depend on the receiving function being able to use functions as arguments, and that is not the case of repeat, and (2) more importanty one has to pass the function name without typing in the parentheses.\nIn this case, repeat is redundant, as the universal syntax that allows one to call a function multiple times to create an iterator already does the repetition you thought repeat would create for you.\nJust do:\nreturn [l() for _ in range(5)]\n\nThis will call l() for each interaction of the loop.\n(btw, one should strongly avoid l as a single variable or function name in any context, as in many fonts it ishard to distinguish l from 1)\n", "The reason why list(repeat(l(), 5)) repeats the same value.\nitertools.repeat() will just iterate the same result.\nBecause l() is assigned the result of l() in list(repeat(l(), 5)) when the l is called (which means l()).\nitertools.repeat() document\n\nrepeat(10, 3) --> 10 10 10\n\nSo what is exactly going on?\nstage 1\n list(repeat(l(), 5))\n\nstage 2\n list(repeat([some numbers], 5))\n\nstage 3\n list(repeat([some numbers], 5)) --> [some numbers], [some numbers], [some numbers], [some numbers], [some numbers]\n\n" ]
[ 2, 0 ]
[]
[]
[ "functional_programming", "python" ]
stackoverflow_0074548570_functional_programming_python.txt
Q: "if string in" returning False I am creating a text based game for a Python class. I created a dictionary for my rooms and created a list for my directions: rooms = { 'Great Hall': { 'name': 'Great Hall', 'South': 'Bedroom' }, 'Bedroom': { 'name': 'Bedroom', 'North': 'Great Hall', 'East': 'Cellar' }, 'Cellar': { 'name': 'Cellar', 'West': 'Bedroom' } } directions = [ 'North', 'South', 'East', 'West' ] Here is the code snippet with my if statement: current_room = rooms['Great Hall'] while True: print('You are in', current_room['name']) command = input('What would you like to do? ') if command in directions: if command in current_room: current_room = rooms[current_room[command]] else: print('Nothing happened') elif command == 'Quit': print('Goodbye') break The if statement returns True if the user inputs the command something like South, but does not return True if the user inputs the command Go South. If the string South is in the string Go South, why wouldn't this return True? What can I change for it to return True? A: Let's reduce your problem down some more: It seems to me this is all the code that is necessary to describe your problem: directions = ['South', 'North', 'East', 'West'] command = 'South' if command in directions: print('This works as LaLoba expects') command = 'Go South' if command in directions: print('This line of code does not execute, but LaLoba would like it to.') What's happening: Let's think of the in operator as a function: def is_element_in_container(thing_im_searching_for, container): for element in container: if element == thing_im_searching_for: return True return False Given this, the string 'Go South' is clearly not in the container, so it would fail to match. A: Note that when asking if command in directions: you actually searching if the command is an element of the list directions. Your intention is to ask if command is a part (substring) of one of the element in the direction list. So, something like: if any(single_direction in command for single_direction in directions) would return true.(Since now you ask, for any direction, if its in what the user has inputed) However, take into consideration you should also treat the various options for the user input also in your rooms map.
"if string in" returning False
I am creating a text based game for a Python class. I created a dictionary for my rooms and created a list for my directions: rooms = { 'Great Hall': { 'name': 'Great Hall', 'South': 'Bedroom' }, 'Bedroom': { 'name': 'Bedroom', 'North': 'Great Hall', 'East': 'Cellar' }, 'Cellar': { 'name': 'Cellar', 'West': 'Bedroom' } } directions = [ 'North', 'South', 'East', 'West' ] Here is the code snippet with my if statement: current_room = rooms['Great Hall'] while True: print('You are in', current_room['name']) command = input('What would you like to do? ') if command in directions: if command in current_room: current_room = rooms[current_room[command]] else: print('Nothing happened') elif command == 'Quit': print('Goodbye') break The if statement returns True if the user inputs the command something like South, but does not return True if the user inputs the command Go South. If the string South is in the string Go South, why wouldn't this return True? What can I change for it to return True?
[ "Let's reduce your problem down some more:\nIt seems to me this is all the code that is necessary to describe your problem:\n directions = ['South', 'North', 'East', 'West']\n command = 'South'\n if command in directions:\n print('This works as LaLoba expects')\n \n command = 'Go South'\n if command in directions:\n print('This line of code does not execute, but LaLoba would like it to.')\n\nWhat's happening:\nLet's think of the in operator as a function:\ndef is_element_in_container(thing_im_searching_for, container):\n for element in container:\n if element == thing_im_searching_for:\n return True\n return False\n\nGiven this, the string 'Go South' is clearly not in the container, so it would fail to match.\n", "Note that when asking\nif command in directions: you actually searching if the command is an element of the list directions.\nYour intention is to ask if command is a part (substring) of one of the element in the direction list.\nSo, something like:\nif any(single_direction in command for single_direction in directions)\n\nwould return true.(Since now you ask, for any direction, if its in what the user has inputed)\nHowever, take into consideration you should also treat the various options for the user input also in your rooms map.\n" ]
[ 3, 0 ]
[]
[]
[ "dictionary", "if_statement", "python" ]
stackoverflow_0074548659_dictionary_if_statement_python.txt
Q: How to save and read matrices with pandas I am trying to save and read matrices of different sizes with pd.to_csv command. The probleme is that pandas saves matrices in a string form, thus when I read the CSV file I don't retrive the matrices in their numerical form. import numpy as np import pandas as pd L = [] for Dim in range(3,10): L.append(np.random.randint(1,10, (Dim,Dim))) df = pd.DataFrame(L) df df.to_csv("matrices.csv", index=False) read_matrices = pd.read_csv("matrices.csv") read_matrices each line of read_matrices is a string, I want them to be numerical matrices (ndarray or pdseries). I guess it is related with how I save the data, I tried all the options of pd.to_csv() without results. Any ideas ? A: \n appears when append is done, probably "vector" objects are converted to "simple". Therefore, I immediately converted the resulting numpy array into a dataframe, and then added it to the desired dataframe. For the data type, I used the experimental type, because the empty cells of the pandas were filled with nan and the integers in these columns turned into a float. import numpy as np import pandas as pd df = pd.DataFrame(dtype=pd.Int64Dtype()) for Dim in range(3, 10): l = np.random.randint(1, 10, (Dim, Dim)) dfl = pd.DataFrame(l, dtype=pd.Int64Dtype()) df = pd.concat([df, dfl], ignore_index=True) df.to_csv("matrices.csv", index=False) read_matrices = pd.read_csv("matrices.csv", dtype=pd.Int64Dtype()) print(read_matrices) ------------------------------------- 0 1 2 3 4 5 6 7 8 0 9 1 9 <NA> <NA> <NA> <NA> <NA> <NA> 1 3 5 6 <NA> <NA> <NA> <NA> <NA> <NA> 2 6 8 1 <NA> <NA> <NA> <NA> <NA> <NA> 3 2 3 2 1 <NA> <NA> <NA> <NA> <NA> 4 8 4 9 6 <NA> <NA> <NA> <NA> <NA> 5 7 1 6 4 <NA> <NA> <NA> <NA> <NA> 6 2 6 2 4 <NA> <NA> <NA> <NA> <NA> 7 6 4 2 6 6 <NA> <NA> <NA> <NA> 8 2 3 3 1 1 <NA> <NA> <NA> <NA> 9 4 8 2 8 2 <NA> <NA> <NA> <NA> 10 2 4 5 7 3 <NA> <NA> <NA> <NA> 11 7 9 4 2 7 <NA> <NA> <NA> <NA> 12 3 2 2 8 5 2 <NA> <NA> <NA> 13 2 7 5 8 5 4 <NA> <NA> <NA> 14 2 7 2 8 4 4 <NA> <NA> <NA> 15 3 3 1 1 4 8 <NA> <NA> <NA> 16 5 3 4 3 3 6 <NA> <NA> <NA> 17 6 2 7 2 2 2 <NA> <NA> <NA> 18 4 6 5 8 8 3 6 <NA> <NA> 19 6 8 1 2 1 4 7 <NA> <NA> 20 4 4 7 6 1 5 3 <NA> <NA> 21 6 2 4 5 5 8 2 <NA> <NA> 22 3 9 1 1 8 9 4 <NA> <NA> 23 1 6 1 2 5 4 5 <NA> <NA> 24 2 9 9 9 3 8 4 <NA> <NA> 25 5 4 5 7 2 2 1 9 <NA> 26 8 6 7 6 1 2 4 2 <NA> 27 6 1 9 1 5 6 1 3 <NA> 28 8 6 8 6 9 8 9 2 <NA> 29 7 7 5 9 9 9 2 3 <NA> 30 1 8 6 7 4 7 6 9 <NA> 31 8 2 6 6 1 2 9 7 <NA> 32 7 6 7 2 5 4 1 3 <NA> 33 4 8 4 7 2 6 1 3 3 34 6 1 5 4 2 1 8 9 5 35 3 6 3 3 9 9 6 9 3 36 5 3 1 9 5 9 2 4 2 37 6 5 8 5 9 5 4 8 4 38 3 2 2 2 4 8 1 3 1 39 7 3 9 2 5 5 2 6 7 40 9 1 8 3 4 9 3 5 6 41 8 3 4 9 8 8 8 1 8
How to save and read matrices with pandas
I am trying to save and read matrices of different sizes with pd.to_csv command. The probleme is that pandas saves matrices in a string form, thus when I read the CSV file I don't retrive the matrices in their numerical form. import numpy as np import pandas as pd L = [] for Dim in range(3,10): L.append(np.random.randint(1,10, (Dim,Dim))) df = pd.DataFrame(L) df df.to_csv("matrices.csv", index=False) read_matrices = pd.read_csv("matrices.csv") read_matrices each line of read_matrices is a string, I want them to be numerical matrices (ndarray or pdseries). I guess it is related with how I save the data, I tried all the options of pd.to_csv() without results. Any ideas ?
[ "\\n appears when append is done, probably \"vector\" objects are converted to \"simple\". Therefore, I immediately converted the resulting numpy array into a dataframe, and then added it to the desired dataframe. For the data type, I used the experimental type, because the empty cells of the pandas were filled with nan and the integers in these columns turned into a float.\nimport numpy as np\nimport pandas as pd\n\ndf = pd.DataFrame(dtype=pd.Int64Dtype())\nfor Dim in range(3, 10):\n l = np.random.randint(1, 10, (Dim, Dim))\n dfl = pd.DataFrame(l, dtype=pd.Int64Dtype())\n df = pd.concat([df, dfl], ignore_index=True)\n\ndf.to_csv(\"matrices.csv\", index=False)\nread_matrices = pd.read_csv(\"matrices.csv\", dtype=pd.Int64Dtype())\n\nprint(read_matrices)\n\n-------------------------------------\n\n 0 1 2 3 4 5 6 7 8\n0 9 1 9 <NA> <NA> <NA> <NA> <NA> <NA>\n1 3 5 6 <NA> <NA> <NA> <NA> <NA> <NA>\n2 6 8 1 <NA> <NA> <NA> <NA> <NA> <NA>\n3 2 3 2 1 <NA> <NA> <NA> <NA> <NA>\n4 8 4 9 6 <NA> <NA> <NA> <NA> <NA>\n5 7 1 6 4 <NA> <NA> <NA> <NA> <NA>\n6 2 6 2 4 <NA> <NA> <NA> <NA> <NA>\n7 6 4 2 6 6 <NA> <NA> <NA> <NA>\n8 2 3 3 1 1 <NA> <NA> <NA> <NA>\n9 4 8 2 8 2 <NA> <NA> <NA> <NA>\n10 2 4 5 7 3 <NA> <NA> <NA> <NA>\n11 7 9 4 2 7 <NA> <NA> <NA> <NA>\n12 3 2 2 8 5 2 <NA> <NA> <NA>\n13 2 7 5 8 5 4 <NA> <NA> <NA>\n14 2 7 2 8 4 4 <NA> <NA> <NA>\n15 3 3 1 1 4 8 <NA> <NA> <NA>\n16 5 3 4 3 3 6 <NA> <NA> <NA>\n17 6 2 7 2 2 2 <NA> <NA> <NA>\n18 4 6 5 8 8 3 6 <NA> <NA>\n19 6 8 1 2 1 4 7 <NA> <NA>\n20 4 4 7 6 1 5 3 <NA> <NA>\n21 6 2 4 5 5 8 2 <NA> <NA>\n22 3 9 1 1 8 9 4 <NA> <NA>\n23 1 6 1 2 5 4 5 <NA> <NA>\n24 2 9 9 9 3 8 4 <NA> <NA>\n25 5 4 5 7 2 2 1 9 <NA>\n26 8 6 7 6 1 2 4 2 <NA>\n27 6 1 9 1 5 6 1 3 <NA>\n28 8 6 8 6 9 8 9 2 <NA>\n29 7 7 5 9 9 9 2 3 <NA>\n30 1 8 6 7 4 7 6 9 <NA>\n31 8 2 6 6 1 2 9 7 <NA>\n32 7 6 7 2 5 4 1 3 <NA>\n33 4 8 4 7 2 6 1 3 3\n34 6 1 5 4 2 1 8 9 5\n35 3 6 3 3 9 9 6 9 3\n36 5 3 1 9 5 9 2 4 2\n37 6 5 8 5 9 5 4 8 4\n38 3 2 2 2 4 8 1 3 1\n39 7 3 9 2 5 5 2 6 7\n40 9 1 8 3 4 9 3 5 6\n41 8 3 4 9 8 8 8 1 8\n\n\n" ]
[ 0 ]
[]
[]
[ "csv", "pandas", "python", "read.csv", "save" ]
stackoverflow_0074546131_csv_pandas_python_read.csv_save.txt
Q: Task scheduler not run task with cmd prompt running background I am trying to run a particular program that uses os.system to run cmd commands from Task Scheduler. os.system('"C:\\Program Files\\BlueStacks_nxt\\HD-Player.exe" --instance Nougat32') os.system('cmd /c "adb start-server"') The code works perfectly when I run from my IDE. However, whenever I try to run the py file or exported exe file, the program is not able to start BlueStack nor adb server. The exe file also works fine when I just run the exe file directly. I first thought it might be some error and used try/catch phrase to log the exception but no exceptions were raised. Here I found a way to display cmd prompt while the task is running. When I changed the setting to "run only when user is logged on", cmd prompt poped up and the os.system worked. So my question is why does the os.system not work when cmd prompt is running from background but does when cmd prompt is displayed? I was able to check that the cmd was running properly in the background through Task Manager and both of the times the privilege were all set to highest. A: It's possible that the os.system does work, but the process fails to run for some reason. Can you try to save the output of the terminal to a file and see if there is any output? To do this you can your command with subprocess.Popen which gives you the stout and stderr of the command.
Task scheduler not run task with cmd prompt running background
I am trying to run a particular program that uses os.system to run cmd commands from Task Scheduler. os.system('"C:\\Program Files\\BlueStacks_nxt\\HD-Player.exe" --instance Nougat32') os.system('cmd /c "adb start-server"') The code works perfectly when I run from my IDE. However, whenever I try to run the py file or exported exe file, the program is not able to start BlueStack nor adb server. The exe file also works fine when I just run the exe file directly. I first thought it might be some error and used try/catch phrase to log the exception but no exceptions were raised. Here I found a way to display cmd prompt while the task is running. When I changed the setting to "run only when user is logged on", cmd prompt poped up and the os.system worked. So my question is why does the os.system not work when cmd prompt is running from background but does when cmd prompt is displayed? I was able to check that the cmd was running properly in the background through Task Manager and both of the times the privilege were all set to highest.
[ "It's possible that the os.system does work, but the process fails to run for some reason.\nCan you try to save the output of the terminal to a file and see if there is any output?\nTo do this you can your command with subprocess.Popen which gives you the stout and stderr of the command.\n" ]
[ 0 ]
[]
[]
[ "python", "windows_task_scheduler" ]
stackoverflow_0074500868_python_windows_task_scheduler.txt
Q: Why do python variables of same value point to the same memory address? I ran into an interesting case today wherein a = 10 b = 10 print (a is b) logged out True. I did some searching and came across the concept of interning. Now that explains why True is correct for the range [-5, 256]. However, I get the same results even while using floats. Please help me understand why. Here is the part I don't get- a = 1000.00 b = 999.99 + 0.01 print (a is b) # Output was 'True' I expect the output to be False since a's value is assigned before running the program, whereas b's value is determined at run-time as a result of expression evaluation and hence should have a different memory address. I'd also appreciate it if you could point out a case where a==b is True, but a is b evaluates to False where both a and b are of type float A: What you are looking at in your case is called "constant folding". That's an implementation detail, not a language specification - meaning there is no guarantee that this behaviour will remain the same and you should not rely on it in your code. But, in general it comes down to the fact that things that can be calculated "statically" are optimised away to their simplest form before the code is actually being run. Take a look at the output of the following snippet import dis def f(): return 0.1 + 0.9 def g(): a = 0.1 b = 0.9 return a+b dis.dis(f) dis.dis(g) You will notice that there is no addition performed in f, even though looking at the code addition is clearly there. As for two same-valued variables having different memory addresses, its not very difficult - any calculations that cannot be optimised away pre-runtime will yield you variables at different memory addresses if they are not within interning range. a = 1 b = 1 for _ in range(1000): a += 1 b += 1 print(f"{id(a) = }") print(f"{id(b) = }") print(f"{a == b = }") print(f"{a is b = }")
Why do python variables of same value point to the same memory address?
I ran into an interesting case today wherein a = 10 b = 10 print (a is b) logged out True. I did some searching and came across the concept of interning. Now that explains why True is correct for the range [-5, 256]. However, I get the same results even while using floats. Please help me understand why. Here is the part I don't get- a = 1000.00 b = 999.99 + 0.01 print (a is b) # Output was 'True' I expect the output to be False since a's value is assigned before running the program, whereas b's value is determined at run-time as a result of expression evaluation and hence should have a different memory address. I'd also appreciate it if you could point out a case where a==b is True, but a is b evaluates to False where both a and b are of type float
[ "What you are looking at in your case is called \"constant folding\". That's an implementation detail, not a language specification - meaning there is no guarantee that this behaviour will remain the same and you should not rely on it in your code. But, in general it comes down to the fact that things that can be calculated \"statically\" are optimised away to their simplest form before the code is actually being run.\nTake a look at the output of the following snippet\nimport dis\n\ndef f():\n return 0.1 + 0.9\ndef g():\n a = 0.1\n b = 0.9\n return a+b\n\ndis.dis(f)\ndis.dis(g)\n\nYou will notice that there is no addition performed in f, even though looking at the code addition is clearly there.\nAs for two same-valued variables having different memory addresses, its not very difficult - any calculations that cannot be optimised away pre-runtime will yield you variables at different memory addresses if they are not within interning range.\na = 1\nb = 1\nfor _ in range(1000):\n a += 1 \n b += 1\n\nprint(f\"{id(a) = }\")\nprint(f\"{id(b) = }\")\nprint(f\"{a == b = }\")\nprint(f\"{a is b = }\")\n\n" ]
[ 5 ]
[]
[]
[ "memory_management", "python" ]
stackoverflow_0074548693_memory_management_python.txt
Q: Why does python sounddevice returns nothing? I'm using wsl version 2 and Xlaunch to connect with x11 server. The problem is when I'm running this code: import sounddevice as sd print(sd.query_devices()) It returns nothing or even running $python3 -m sounddevice ,again returns nothing. what can be the problem? A: You mention setting up Xlaunch (VcXsrv), but this only provides graphical support, not audio. PulseAudio is typically used to provide a connection between the Linux code running in WSL and the Windows audio source. While you can configure PulseAudio manually, I would recommend simply using the WSLg feature of WSL2, since it's now available for both Windows 10 and 11 users. WSLg should automatically configure PulseAudio for you with no additional effort. See this Ask Ubuntu answer where I cover how to upgrade your system (hopefully) to the latest Windows release and then upgrade WSL to use the 1.0.0 (or later) application package that includes this support.
Why does python sounddevice returns nothing?
I'm using wsl version 2 and Xlaunch to connect with x11 server. The problem is when I'm running this code: import sounddevice as sd print(sd.query_devices()) It returns nothing or even running $python3 -m sounddevice ,again returns nothing. what can be the problem?
[ "You mention setting up Xlaunch (VcXsrv), but this only provides graphical support, not audio. PulseAudio is typically used to provide a connection between the Linux code running in WSL and the Windows audio source.\nWhile you can configure PulseAudio manually, I would recommend simply using the WSLg feature of WSL2, since it's now available for both Windows 10 and 11 users. WSLg should automatically configure PulseAudio for you with no additional effort.\nSee this Ask Ubuntu answer where I cover how to upgrade your system (hopefully) to the latest Windows release and then upgrade WSL to use the 1.0.0 (or later) application package that includes this support.\n" ]
[ 0 ]
[]
[]
[ "python", "python_sounddevice", "wsl_2" ]
stackoverflow_0074546184_python_python_sounddevice_wsl_2.txt
Q: How to make a function act as a generator only when used as one One existing example of this is open which can be used in these two ways: f = open("File") print(f.readline()) f.close() # ...and... with open("File") as f: print(f.readline()) I intend to create a version of the asyncio.Lock class which allows you to not only acquire and release the lock manually but also to use a with block to wrap the code that requires the lock and release it automatically. A: The thing you look for isn't a generator, but a context manager. You don't even need to implement one, This works: lock = asyncio.Lock() async def example(): async with lock: # Your code here A: For other people getting here: although the OP wanted something that already works out of the box: Whenever one sees a "function" that can work as a generator or a context manager, as is the case, or be used "stand alone", it is due to the fact it is not a "function": it is actually a class . WHat you do when calling open or asyncio.lock is creating an object, which internally has several methods, not only .read or .acquire, which both have to be explicly called, but special named methods which allows Python to call then in a transparent way, when the object is used in certain language constructs. For example, if the class implements the __iter__ method, it can automatically be used in for statements. To be used with an with statement, it has to implement both __enter__ and __exit__ methods.
How to make a function act as a generator only when used as one
One existing example of this is open which can be used in these two ways: f = open("File") print(f.readline()) f.close() # ...and... with open("File") as f: print(f.readline()) I intend to create a version of the asyncio.Lock class which allows you to not only acquire and release the lock manually but also to use a with block to wrap the code that requires the lock and release it automatically.
[ "The thing you look for isn't a generator, but a context manager.\nYou don't even need to implement one, This works:\nlock = asyncio.Lock()\n\nasync def example():\n async with lock:\n # Your code here\n\n", "For other people getting here: although the OP wanted something that already works out of the box:\nWhenever one sees a \"function\" that can work as a generator or a context manager, as is the case, or be used \"stand alone\", it is due to the fact it is not a \"function\": it is actually a class . WHat you do when calling open or asyncio.lock is creating an object, which internally has several methods, not only .read or .acquire, which both have to be explicly called, but special named methods which allows Python to call then in a transparent way, when the object is used in certain language constructs.\nFor example, if the class implements the __iter__ method, it can automatically be used in for statements. To be used with an with statement, it has to implement both __enter__ and __exit__ methods.\n" ]
[ 1, 1 ]
[]
[]
[ "generator", "python", "python_asyncio" ]
stackoverflow_0074542734_generator_python_python_asyncio.txt
Q: How to select every letter from every word? I'm trying to make my own OCR for Egyptian. This is my code: import keras from keras.models import load_model import seaborn as sn from sklearn.metrics import confusion_matrix import os import numpy as np from sklearn.utils import shuffle import matplotlib.pyplot as plt import tensorflow as tf from tqdm import tqdm import pandas as pd import cv2 image = cv2.imread( r"C:\Users\emady\Desktop\VS Code\HandWriten_Arabic\test_select.png") base_image = image.copy() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (7, 7), 0) thresh = cv2.threshold( gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] kernal = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 13)) dilate = cv2.dilate(thresh, kernal, iterations=1) cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if len(cnts) == 2 else cents[1] cnts = sorted(cnts, key=lambda x: cv2.boundingRect(x)[0]) chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'ا', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ', 'د', 'ذ', 'ر', 'ز', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع', 'غ', 'ف', 'ق', 'ك', 'ل', 'م', 'ن', 'ه', 'و', 'ي'] IMAGE_SIZE = (48, 48) text = "" TARGET_WIDTH = 48 TARGET_HEIGHT = 48 for c in cnts: x, y, w, h = cv2.boundingRect(c) if h > 16 and w > 1: roi = image[y:y+h, x:x+h] cv2.imwrite("temp/index_roi.png", roi) cv2.rectangle(image, (x, y), (x+w, y+h), (36, 255, 12), 2) cv2.imwrite("temp/index_bbox_new.png", image) My issue is I detected the boundingRect good and I don't know how to get each word and get the word letters as shown in the image below: A: I know this is not the answer you want, but I think what you're trying to do here is too difficult — it's not the kind of thing a single person can cobble together. Here's the big issue: Even vanilla OCR for print, Standard Arabic is not a solved problem. I was recently trying out pdfplumber on a digital (not scanned) Arabic pdf, and it did okay with a lot of it. Except that the text outputted backwards (fixable with bidi package) and it added spaces wherever there were diacritics (fixable with some preprocessing). But the font was a little bit fancy (from a novel) and pdfplumber completely choked on letters that were stacked on top of one another, like تج in a nice font. It couldn't make out the borders between letters, and the method you're trying here (if I understand it) would have the same problem. But print Standard Arabic OCR is easy compared to what you're trying to do. Even if you have newspaper-kind of fonts, where the letters are not stacked, an OCR will not do well with vernacular Arabic. It's too different from what it's been trained on, and you'll end up with word salad. Handwriting in vernacular Arabic just makes all of these difficulties more difficult. I'm not going to say impossible, but very, very difficult. I think you should start this process by doing a Google Scholar research on the latest articles about "Arabic OCR". This is a problem for well-funded university teams — see what they're doing about it.
How to select every letter from every word?
I'm trying to make my own OCR for Egyptian. This is my code: import keras from keras.models import load_model import seaborn as sn from sklearn.metrics import confusion_matrix import os import numpy as np from sklearn.utils import shuffle import matplotlib.pyplot as plt import tensorflow as tf from tqdm import tqdm import pandas as pd import cv2 image = cv2.imread( r"C:\Users\emady\Desktop\VS Code\HandWriten_Arabic\test_select.png") base_image = image.copy() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (7, 7), 0) thresh = cv2.threshold( gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] kernal = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 13)) dilate = cv2.dilate(thresh, kernal, iterations=1) cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if len(cnts) == 2 else cents[1] cnts = sorted(cnts, key=lambda x: cv2.boundingRect(x)[0]) chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'ا', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ', 'د', 'ذ', 'ر', 'ز', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع', 'غ', 'ف', 'ق', 'ك', 'ل', 'م', 'ن', 'ه', 'و', 'ي'] IMAGE_SIZE = (48, 48) text = "" TARGET_WIDTH = 48 TARGET_HEIGHT = 48 for c in cnts: x, y, w, h = cv2.boundingRect(c) if h > 16 and w > 1: roi = image[y:y+h, x:x+h] cv2.imwrite("temp/index_roi.png", roi) cv2.rectangle(image, (x, y), (x+w, y+h), (36, 255, 12), 2) cv2.imwrite("temp/index_bbox_new.png", image) My issue is I detected the boundingRect good and I don't know how to get each word and get the word letters as shown in the image below:
[ "I know this is not the answer you want, but I think what you're trying to do here is too difficult — it's not the kind of thing a single person can cobble together.\nHere's the big issue: Even vanilla OCR for print, Standard Arabic is not a solved problem. I was recently trying out pdfplumber on a digital (not scanned) Arabic pdf, and it did okay with a lot of it. Except that the text outputted backwards (fixable with bidi package) and it added spaces wherever there were diacritics (fixable with some preprocessing). But the font was a little bit fancy (from a novel) and pdfplumber completely choked on letters that were stacked on top of one another, like تج in a nice font. It couldn't make out the borders between letters, and the method you're trying here (if I understand it) would have the same problem.\nBut print Standard Arabic OCR is easy compared to what you're trying to do. Even if you have newspaper-kind of fonts, where the letters are not stacked, an OCR will not do well with vernacular Arabic. It's too different from what it's been trained on, and you'll end up with word salad.\nHandwriting in vernacular Arabic just makes all of these difficulties more difficult. I'm not going to say impossible, but very, very difficult.\nI think you should start this process by doing a Google Scholar research on the latest articles about \"Arabic OCR\". This is a problem for well-funded university teams — see what they're doing about it.\n" ]
[ 2 ]
[]
[]
[ "arabic", "computer_vision", "machine_learning", "ocr", "python" ]
stackoverflow_0074257224_arabic_computer_vision_machine_learning_ocr_python.txt
Q: iteration over a Spark Dataframe and edit list from for loop I am currently working on a Python function.The process is supposed to loop over a pandas dataframe containing my data structure (I get the info of which table contains the value for a field I am looking for) and then loop over a spark dataframe that loads the right table from the precedent loop and if the value for the field is encountered, we add it to a record list and to a dataframe that itself will be returned at the end of the process to be turned into a csv. df_meta = pd.read_csv("/dbfs/mnt/resources/path/file_meta.csv", sep=';') liste_t = [] def recursive_process(field, id_p, list_drop): for row in df_meta.index: if df_meta['SOURCE_COLUMN_NAME'][row] == field: df_table = spark.read.table("source1"+"."+df_meta['SOURCE_TABLE_NAME'][row]) data_collect = df_table.collect() for row2 in data_collect: if row2(field) == id_p and row2(field) not in list_drop: list_drop.append(id_p) #add field + value to final dataframe return list_drop In parameters, I gave the field I am targetting, the value id_p of this field and a list to record the fields I have already processed. The problem is : I don't really know how to process over the spark dataframe containing my data, I read about the collect() method I tryed to use, but I am not sure it works here. So far, I wanted my code to edit my empty list and returns it with values that would be added to my final dataframe. But as I call my function : recursive_process("Col_ID","1003729193",liste_t) The list just returns nothing which should not be normal ... So I would like to know how to process on the spark dataframe ?and how to return a list/a datarame edited inside of my loop ?(I'm afraid the process on these just happen into my loops but stay unchanges outside these loops). Thank's for helping ! A: You can filter the dataframe, with something like this: df_table.filter(f"{field} = {id_p}").filter(f"{field} NOT IN {list_drop}") Then it's depends on the size of this filtering: (Big) you could save the results on disk for each dataframe (df.write methods), and read that back with spark. (Small) Or you can create a temporary Spark df, and append results to it (df.union()if they have the same schema), and write to disk the final state of this temporary df. If you go in Spark, you should go in Spark all the way (not collecting than itering the rows). If you do not know well the Spark Apis, you could use the pandas one with this import: import pyspark.pandas as pd
iteration over a Spark Dataframe and edit list from for loop
I am currently working on a Python function.The process is supposed to loop over a pandas dataframe containing my data structure (I get the info of which table contains the value for a field I am looking for) and then loop over a spark dataframe that loads the right table from the precedent loop and if the value for the field is encountered, we add it to a record list and to a dataframe that itself will be returned at the end of the process to be turned into a csv. df_meta = pd.read_csv("/dbfs/mnt/resources/path/file_meta.csv", sep=';') liste_t = [] def recursive_process(field, id_p, list_drop): for row in df_meta.index: if df_meta['SOURCE_COLUMN_NAME'][row] == field: df_table = spark.read.table("source1"+"."+df_meta['SOURCE_TABLE_NAME'][row]) data_collect = df_table.collect() for row2 in data_collect: if row2(field) == id_p and row2(field) not in list_drop: list_drop.append(id_p) #add field + value to final dataframe return list_drop In parameters, I gave the field I am targetting, the value id_p of this field and a list to record the fields I have already processed. The problem is : I don't really know how to process over the spark dataframe containing my data, I read about the collect() method I tryed to use, but I am not sure it works here. So far, I wanted my code to edit my empty list and returns it with values that would be added to my final dataframe. But as I call my function : recursive_process("Col_ID","1003729193",liste_t) The list just returns nothing which should not be normal ... So I would like to know how to process on the spark dataframe ?and how to return a list/a datarame edited inside of my loop ?(I'm afraid the process on these just happen into my loops but stay unchanges outside these loops). Thank's for helping !
[ "You can filter the dataframe, with something like this:\ndf_table.filter(f\"{field} = {id_p}\").filter(f\"{field} NOT IN {list_drop}\")\nThen it's depends on the size of this filtering:\n\n(Big) you could save the results on disk for each dataframe (df.write methods), and read that back with spark.\n(Small) Or you can create a temporary Spark df, and append results to it (df.union()if they have the same schema), and write to disk the final state of this temporary df.\n\nIf you go in Spark, you should go in Spark all the way (not collecting than itering the rows).\nIf you do not know well the Spark Apis, you could use the pandas one with this import:\nimport pyspark.pandas as pd\n" ]
[ 0 ]
[]
[]
[ "apache_spark", "for_loop", "pandas", "pyspark", "python" ]
stackoverflow_0074547837_apache_spark_for_loop_pandas_pyspark_python.txt
Q: How to control spces and page break in docxtpl (based on exist docx template)? I created a docx template and then generated the python code to update variable and all the other data into this template using python's docxtpl package as: tpl = DocxTemplate((path.join('report','templates','my_template.docx'))) tpl.new_subdoc() file_path = path.join(output_dir_name, file_name) get_all_data_report(tpl) tpl.save(file_path)enter code here I don't understand how can I fully control the spaces/ page break in the resulting docx file. If I put some text in the template in the beginning of the page it sometimes moves and adds x line spaces. A: from docxtpl import * tpl = DocxTemplate('templates/escape_tpl.docx') context = {'myvar': R('"less than" must be escaped : <, this can be done with RichText() or R()'), 'myescvar': 'It can be escaped with a "|e" jinja filter in the template too : < ', 'nlnp': R('Here is a multiple\nlines\nstring\aand some\aother\aparagraphs\aNOTE: the current character styling is removed'), 'mylisting': Listing('the listing\nwith\nsome\nlines\nand special chars : <>&\f ... and a page break'), 'page_break': R('\f'), } tpl.render(context) tpl.save('output/escape.docx') and using {{r page_break}} in your template see this https://github.com/elapouya/python-docx-template/blob/master/tests/escape.py and this https://github.com/elapouya/python-docx-template/blob/master/tests/templates/escape_tpl.docx A: Easy method is add a page break in a row of template table. Insert Page break from word. \f was not really working for me. Tried multiple \f in multiple rows. All it was doing was adding more and more blank rows. In my case I have multiple tables so the table alignment was a mess. Inserting page break in the template document table fixed my problem
How to control spces and page break in docxtpl (based on exist docx template)?
I created a docx template and then generated the python code to update variable and all the other data into this template using python's docxtpl package as: tpl = DocxTemplate((path.join('report','templates','my_template.docx'))) tpl.new_subdoc() file_path = path.join(output_dir_name, file_name) get_all_data_report(tpl) tpl.save(file_path)enter code here I don't understand how can I fully control the spaces/ page break in the resulting docx file. If I put some text in the template in the beginning of the page it sometimes moves and adds x line spaces.
[ "from docxtpl import *\ntpl = DocxTemplate('templates/escape_tpl.docx')\ncontext = {'myvar': R('\"less than\" must be escaped : <, this can be done with RichText() or R()'),\n 'myescvar': 'It can be escaped with a \"|e\" jinja filter in the template too : < ',\n 'nlnp': R('Here is a multiple\\nlines\\nstring\\aand some\\aother\\aparagraphs\\aNOTE: the current character styling is removed'),\n 'mylisting': Listing('the listing\\nwith\\nsome\\nlines\\nand special chars : <>&\\f ... and a page break'),\n 'page_break': R('\\f'),\n }\ntpl.render(context)\ntpl.save('output/escape.docx')\n\nand using {{r page_break}} in your template\nsee this https://github.com/elapouya/python-docx-template/blob/master/tests/escape.py \nand this https://github.com/elapouya/python-docx-template/blob/master/tests/templates/escape_tpl.docx\n", "Easy method is add a page break in a row of template table. Insert Page break from word.\n\\f was not really working for me. Tried multiple \\f in multiple rows. All it was doing was adding more and more blank rows. In my case I have multiple tables so the table alignment was a mess. Inserting page break in the template document table fixed my problem\n" ]
[ 4, 0 ]
[ "You can put conditional page break of space. \nStep to do : \n\nOpen documents in Microsoft word open documents\nClick on Home then click (Ctrl+*) or quote symbol\nYou will find all page break and spaces like screenshot\nThen add conditional statement like show in screenshot\n\n", "I already found the solution you can add page break manually at the template docx not from the code and its work OK \n" ]
[ -1, -1 ]
[ "docx", "python", "python_docx" ]
stackoverflow_0055656280_docx_python_python_docx.txt
Q: How this Python Numpy ndarray slicing is working? I wish to understand a piece of code that I have seen in python. enter image description here in my particular case, face is a list and when the code is executed x is 739 y is 229 w is 232 h is 349 image is a numpy.ndarray, I wanted to understand how the slicing of image is acctually working... which part of the image is acctually being selected? I cant understand how the slicing is working A: To slice a multi-dimensional array, you specify a standard slicing range (with up to 3 arguments seperated by :) for each dimension, and seperate the ranges with a ,. In this example, the array is sliced in the range of y up to y + h on one dimension, and x to x + w on the other. read this if for more examples
How this Python Numpy ndarray slicing is working?
I wish to understand a piece of code that I have seen in python. enter image description here in my particular case, face is a list and when the code is executed x is 739 y is 229 w is 232 h is 349 image is a numpy.ndarray, I wanted to understand how the slicing of image is acctually working... which part of the image is acctually being selected? I cant understand how the slicing is working
[ "To slice a multi-dimensional array, you specify a standard slicing range (with up to 3 arguments seperated by :) for each dimension, and seperate the ranges with a ,.\nIn this example, the array is sliced in the range of y up to y + h on one dimension, and x to x + w on the other.\nread this if for more examples\n" ]
[ 0 ]
[]
[]
[ "numpy_ndarray", "python" ]
stackoverflow_0074548943_numpy_ndarray_python.txt
Q: python open new window idk what to do when i define a function it dosent wanna use it in a button command NameError: name 'openNewWindow' is not defined. Did you mean: 'PanedWindow' idk whats the problem from tkinter import* win = Tk() win.title("igra") win.config(bg = "black") win.overrideredirect(True) win.geometry("{0}x{1}+0+0".format(win.winfo_screenwidth(), win.winfo_screenheight())) pitanje = Label(win, text = "dali ste sami?", bg="black", fg="white", font= ('Open Sans', 50)).place(x= "570", y= "300") odgovor = Button(win, text = "da", bg="black", fg="white", font= ('Open Sans', 50), borderwidth=0) odgovor.place(x= "560", y= "480") odgovor2 = Button(win, text = "ne", bg="black", fg="white", font= ('Open Sans', 50), borderwidth=0,command=openNewWin) odgovor2.place(x= "840", y= "480") def openNewWin(): openNewWin = Toplevel(win) openNewWin.geometry("720x720") win.mainloop() A: Is this is what you want? I rearranged code. I moved function before widgets. Try this: from tkinter import* win = Tk() win.title("igra") win.config(bg = "black") #win.overrideredirect(True) win.geometry("1080x900") def openNewWin(): openNewWin = Toplevel(win) openNewWin.geometry("720x720") pitanje = Label(win, text = "dali ste sami?", bg="black", fg="white", font= ('Open Sans', 50)).place(x= "570", y= "300") odgovor = Button(win, text = "da", bg="black", fg="white", font= ('Open Sans', 50), borderwidth=0) odgovor.place(x= "560", y= "480") odgovor2 = Button(win, text = "ne", bg="black", fg="white", font= ('Open Sans', 50), borderwidth=0,command=openNewWin) odgovor2.place(x= "840", y= "480") win.mainloop() Result main window: Result for Toplevel:
python open new window
idk what to do when i define a function it dosent wanna use it in a button command NameError: name 'openNewWindow' is not defined. Did you mean: 'PanedWindow' idk whats the problem from tkinter import* win = Tk() win.title("igra") win.config(bg = "black") win.overrideredirect(True) win.geometry("{0}x{1}+0+0".format(win.winfo_screenwidth(), win.winfo_screenheight())) pitanje = Label(win, text = "dali ste sami?", bg="black", fg="white", font= ('Open Sans', 50)).place(x= "570", y= "300") odgovor = Button(win, text = "da", bg="black", fg="white", font= ('Open Sans', 50), borderwidth=0) odgovor.place(x= "560", y= "480") odgovor2 = Button(win, text = "ne", bg="black", fg="white", font= ('Open Sans', 50), borderwidth=0,command=openNewWin) odgovor2.place(x= "840", y= "480") def openNewWin(): openNewWin = Toplevel(win) openNewWin.geometry("720x720") win.mainloop()
[ "Is this is what you want? I rearranged code. I moved function before widgets.\nTry this:\nfrom tkinter import*\n\n\nwin = Tk()\n\nwin.title(\"igra\")\nwin.config(bg = \"black\")\n#win.overrideredirect(True)\nwin.geometry(\"1080x900\")\n\n\ndef openNewWin():\n openNewWin = Toplevel(win)\n openNewWin.geometry(\"720x720\")\n\n\npitanje = Label(win, text = \"dali ste sami?\", bg=\"black\", fg=\"white\", font= ('Open Sans', 50)).place(x= \"570\", y= \"300\")\nodgovor = Button(win, text = \"da\", bg=\"black\", fg=\"white\", font= ('Open Sans', 50), borderwidth=0)\nodgovor.place(x= \"560\", y= \"480\")\nodgovor2 = Button(win, text = \"ne\", bg=\"black\", fg=\"white\", font= ('Open Sans', 50), borderwidth=0,command=openNewWin)\nodgovor2.place(x= \"840\", y= \"480\")\n\nwin.mainloop()\n\nResult main window:\n\nResult for Toplevel:\n\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0071664543_python_tkinter.txt
Q: Resolving "The terminal shell CWD "/mnt/c/Users/User/Downloads/IG-Bot/C:\Users\User\VSC" does not exist error message I was trying to build an Instagram Bot using visual studio code python and WSL, (Windows Subsystem for Linux) when I decided to begin by opening a terminal window in Visual Studio Code and I got the error "The terminal shell CWD "/mnt/c/Users/User/Downloads/IG-Bot/C:\Users\User\VSC" does not exist" message not sure if its either how I installed the plugins on visual studio or how Integrated The subsystem using powershell. A: Make sure to use the WSL - Remote extension as that will make sure VS Code acts like you're working under Linux. Otherwise you end up in a situation like you're in where VS Code thinks you're trying to work under Windows. A: I have encountered this issue when connecting to a remote host via SSH. The connection would establish correctly, I opened a folder and could see the files, but as soon as I tried to open a terminal via the "Terminal" > "New Terminal" option, it would show me this error message. Reason for it was that in the meantime I deleted the folder which I originally opened in my SSH session. As I wanted to open a new terminal, it tried opening the CWD of the VSCODE project, which was the folder that I deleted in a seperate terminal session. Restarting the SSH session and opening an existing folder, such as "/root", solved the issue for me.
Resolving "The terminal shell CWD "/mnt/c/Users/User/Downloads/IG-Bot/C:\Users\User\VSC" does not exist error message
I was trying to build an Instagram Bot using visual studio code python and WSL, (Windows Subsystem for Linux) when I decided to begin by opening a terminal window in Visual Studio Code and I got the error "The terminal shell CWD "/mnt/c/Users/User/Downloads/IG-Bot/C:\Users\User\VSC" does not exist" message not sure if its either how I installed the plugins on visual studio or how Integrated The subsystem using powershell.
[ "Make sure to use the WSL - Remote extension as that will make sure VS Code acts like you're working under Linux. Otherwise you end up in a situation like you're in where VS Code thinks you're trying to work under Windows.\n", "I have encountered this issue when connecting to a remote host via SSH. The connection would establish correctly, I opened a folder and could see the files, but as soon as I tried to open a terminal via the \"Terminal\" > \"New Terminal\" option, it would show me this error message.\nReason for it was that in the meantime I deleted the folder which I originally opened in my SSH session. As I wanted to open a new terminal, it tried opening the CWD of the VSCODE project, which was the folder that I deleted in a seperate terminal session.\nRestarting the SSH session and opening an existing folder, such as \"/root\", solved the issue for me.\n" ]
[ 1, 0 ]
[]
[]
[ "linux", "powershell", "python", "visual_studio_code" ]
stackoverflow_0062263311_linux_powershell_python_visual_studio_code.txt
Q: Repeated rows in a numpy array I feel like I'm going insane because I can't figure out what feels like should be a simple problem! I want to generate fake data in a numpy array and I can't figure out how to repeat a row of observations. I'd rather generate thousands of rows and I can't figure out how to repeat a row whenever I feel like. For example, here's my current code: voters = np.array( [ ['Democrat', 'Republican', 'Third'], ['Democrat', 'Republican', 'Third'], ['Democrat', 'Republican', 'Third'], ['Democrat', 'Republican', 'Third'], ['Democrat', 'Republican', 'Third'], ['Democrat', 'Third', 'Republican'], ['Democrat', 'Third', 'Republican'], ['Democrat', 'Third', 'Republican'], ['Democrat', 'Third', 'Republican'], ] ) But I just want to be able to condense this. It's obviously not manageable to make large datasets this way! Thank you A: Use np.repeat(): voters = np.array([['row1', 'row1', 'row1'], ['row2', 'row2', 'row2']]) # We repeat 2 times the first row and 4 times the second row. np.repeat(voters,[2,4],axis=0) # voters.repeat([2,4],axis=0) produce the same result. And we obtain: array([['row1', 'row1', 'row1'], ['row1', 'row1', 'row1'], ['row2', 'row2', 'row2'], ['row2', 'row2', 'row2'], ['row2', 'row2', 'row2'], ['row2', 'row2', 'row2']]) A: You can use this: np.array([['Democrat', 'Republican', 'Third']]* 10000) to generate as many duplicate rows as you want.
Repeated rows in a numpy array
I feel like I'm going insane because I can't figure out what feels like should be a simple problem! I want to generate fake data in a numpy array and I can't figure out how to repeat a row of observations. I'd rather generate thousands of rows and I can't figure out how to repeat a row whenever I feel like. For example, here's my current code: voters = np.array( [ ['Democrat', 'Republican', 'Third'], ['Democrat', 'Republican', 'Third'], ['Democrat', 'Republican', 'Third'], ['Democrat', 'Republican', 'Third'], ['Democrat', 'Republican', 'Third'], ['Democrat', 'Third', 'Republican'], ['Democrat', 'Third', 'Republican'], ['Democrat', 'Third', 'Republican'], ['Democrat', 'Third', 'Republican'], ] ) But I just want to be able to condense this. It's obviously not manageable to make large datasets this way! Thank you
[ "Use np.repeat():\nvoters = np.array([['row1', 'row1', 'row1'],\n ['row2', 'row2', 'row2']])\n\n# We repeat 2 times the first row and 4 times the second row.\nnp.repeat(voters,[2,4],axis=0)\n# voters.repeat([2,4],axis=0) produce the same result.\n\nAnd we obtain:\narray([['row1', 'row1', 'row1'],\n ['row1', 'row1', 'row1'],\n ['row2', 'row2', 'row2'],\n ['row2', 'row2', 'row2'],\n ['row2', 'row2', 'row2'],\n ['row2', 'row2', 'row2']])\n\n", "You can use this:\nnp.array([['Democrat', 'Republican', 'Third']]* 10000)\n\nto generate as many duplicate rows as you want.\n" ]
[ 3, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074548612_numpy_python.txt
Q: mysql command is not found in terminal mac I want to use mysql to get the access to google cloud and link it to python but i faced this message in terminal How can i download mysql command ? i already download the mysql shell but still this message appear. rag@rags-MacBook-Pro ~ % mysql --version zsh: command not found: mysql --version A: To install mysql on mac, follow the official guide: https://dev.mysql.com/doc/mysql-macos-excerpt/5.7/en/macos-installation.html . After mysql is installed this way, you might still have to add the path to it to ~/.zshrc in order to be able to use that command from zsh. To add the path to ~/.zshrc you can: nano ~/.zshrc Add the following line at the end of ~/.zshrc: export PATH=$PATH:/usr/local/<your_mysql_folder>/bin where you substitute <your_mysql_folder> with the name of the folder where mysql was installed, in my case mysql-8.0.28-macos11-arm64 Save and close the edited file (Ctrl+O to save, Ctrl+X to close) Update by either restarting the terminal or doing source ~/.zshrc After this, the mysql command might work. A: In my case it happened to be so that even after adding export PATH=$PATH:/usr/local/<your_mysql_folder>/bi in ~/.bash_profile file it was throwing the same error. I had to fire source .bash_profile from terminal and it got fixed!! :) A: firing source.bash_profile from terminal worked in my case.
mysql command is not found in terminal mac
I want to use mysql to get the access to google cloud and link it to python but i faced this message in terminal How can i download mysql command ? i already download the mysql shell but still this message appear. rag@rags-MacBook-Pro ~ % mysql --version zsh: command not found: mysql --version
[ "To install mysql on mac, follow the official guide: https://dev.mysql.com/doc/mysql-macos-excerpt/5.7/en/macos-installation.html .\nAfter mysql is installed this way, you might still have to add the path to it to ~/.zshrc in order to be able to use that command from zsh.\nTo add the path to ~/.zshrc you can:\n\nnano ~/.zshrc\nAdd the following line at the end of ~/.zshrc:\n\nexport PATH=$PATH:/usr/local/<your_mysql_folder>/bin\n\nwhere you substitute <your_mysql_folder> with the name of the folder where mysql was installed, in my case mysql-8.0.28-macos11-arm64\n\nSave and close the edited file (Ctrl+O to save, Ctrl+X to close)\nUpdate by either restarting the terminal or doing source ~/.zshrc\n\nAfter this, the mysql command might work.\n", "In my case it happened to be so that even after adding export PATH=$PATH:/usr/local/<your_mysql_folder>/bi in ~/.bash_profile file it was throwing the same error.\nI had to fire source .bash_profile from terminal and it got fixed!! :)\n", "firing source.bash_profile from terminal worked in my case.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0071156432_mysql_python.txt
Q: How to add several AxesSubplot instances into a subplot I've called an instance method four times, and each time an instance of the Matplotlib class AxesSubPlot is returned. I'm slowly getting to grips with Matplotlib, but I'm unsure how I render the four separate instances of AxesSubPlot as a MatplotLib subplot of 2x2. In short: if something returns an AxesSubplot instance, how do I plot it. Thanks. A: You can reference each AxesSubplot instance like so: import matplotlib.pyplot as plt fig, ax = plt.subplots(2, 2) print(ax) ax[0, 0].annotate("Upper Left", (0.5, 0.5)) ax[0, 1].annotate("Upper Right", (0.5, 0.5)) ax[1, 0].annotate("Lower Left", (0.5, 0.5)) ax[1, 1].annotate("Lower Right", (0.5, 0.5)) plt.tight_layout() plt.show() Output: [[<AxesSubplot:> <AxesSubplot:>] [<AxesSubplot:> <AxesSubplot:>]] A: if your instance method accepts, as an optional argument, an Axes object, then you could do, e.g., ... fig, (ax1, ax2) = plt.subplots(2,1) instance1.plot(..., ax=ax1, ...) instance2.plot(..., ax=ax2, ...) plt.show()
How to add several AxesSubplot instances into a subplot
I've called an instance method four times, and each time an instance of the Matplotlib class AxesSubPlot is returned. I'm slowly getting to grips with Matplotlib, but I'm unsure how I render the four separate instances of AxesSubPlot as a MatplotLib subplot of 2x2. In short: if something returns an AxesSubplot instance, how do I plot it. Thanks.
[ "You can reference each AxesSubplot instance like so:\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(2, 2)\nprint(ax)\nax[0, 0].annotate(\"Upper Left\", (0.5, 0.5))\nax[0, 1].annotate(\"Upper Right\", (0.5, 0.5))\nax[1, 0].annotate(\"Lower Left\", (0.5, 0.5))\nax[1, 1].annotate(\"Lower Right\", (0.5, 0.5))\nplt.tight_layout()\nplt.show()\n\nOutput:\n[[<AxesSubplot:> <AxesSubplot:>]\n [<AxesSubplot:> <AxesSubplot:>]]\n\n\n", "if your instance method accepts, as an optional argument, an Axes object, then you could do, e.g.,\n...\nfig, (ax1, ax2) = plt.subplots(2,1)\ninstance1.plot(..., ax=ax1, ...)\ninstance2.plot(..., ax=ax2, ...)\nplt.show()\n\n" ]
[ 0, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074283198_matplotlib_python.txt
Q: How to devide each value of a column of a numpy array by a value I have a numpy array Y_test_traInv_RMSE with 3 columns, as you can see in the screenshot Now I would like to devide the each value of the third column (index 2) by the value 4700. I tried the following commands but none of them helped: Y_test_traInv_RMSE [2] [:] = Y_test_traInv_RMSE [2] [:] /4700 Y_test_traInv_RMSE [:] [2] = Y_test_traInv_RMSE [:] [2] /4700 Y_test_traInv_RMSE [:,2] = Y_test_traInv_RMSE [:,2] /4700 Y_test_traInv_RMSE [2,:] = Y_test_traInv_RMSE [2,:] /4700 Any idea how I can do that? I just want to have every value only of the column with index 2 divided by 4700. A: Your third option should work. At least it works with this test data, so maybe you have another issue. test = np.arange(30).astype(float).reshape(10, 3) print(test) test[:,2] = test[:,2] / 4700 print(test)
How to devide each value of a column of a numpy array by a value
I have a numpy array Y_test_traInv_RMSE with 3 columns, as you can see in the screenshot Now I would like to devide the each value of the third column (index 2) by the value 4700. I tried the following commands but none of them helped: Y_test_traInv_RMSE [2] [:] = Y_test_traInv_RMSE [2] [:] /4700 Y_test_traInv_RMSE [:] [2] = Y_test_traInv_RMSE [:] [2] /4700 Y_test_traInv_RMSE [:,2] = Y_test_traInv_RMSE [:,2] /4700 Y_test_traInv_RMSE [2,:] = Y_test_traInv_RMSE [2,:] /4700 Any idea how I can do that? I just want to have every value only of the column with index 2 divided by 4700.
[ "Your third option should work. At least it works with this test data, so maybe you have another issue.\ntest = np.arange(30).astype(float).reshape(10, 3)\nprint(test)\ntest[:,2] = test[:,2] / 4700\nprint(test)\n\n" ]
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074548724_numpy_python.txt
Q: Plotting points on one line in python. 1 dimension This is the kind of graph that I would like to plot, without y axis . How can I achieve this in python using matplotlib if possible. A: Sadly there is not built-in fonction in matplotlib to create such a graph. However, You can use the following code to have a similar output. This snippet is removing unwanted spines (left, right and top) and then using scatterplot to simulate a 1d graph. As Follows: from matplotlib import pyplot as plt import numpy as np fig, ax = plt.subplots(figsize=(10,1)) x = [1,2,3,4,9,10] idx = np.arange(1,len(x)+1) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['bottom'].set_position('zero') ax.spines['bottom'].set_alpha(0.2) ax.get_yaxis().set_visible(False) ax.set_xlabel('Gene 1') ax.scatter(x, np.zeros(len(x)), s=300, c='lightgreen') ax.set_xticks([min(x), max(x)], ['Low Values', 'High Values']) for i in range(len(idx)): ax.annotate(idx[i], (x[i], 0), textcoords="offset points", xytext=(0,0), # distance from text to points (x,y) ha='center') plt.show() Outputs:
Plotting points on one line in python. 1 dimension
This is the kind of graph that I would like to plot, without y axis . How can I achieve this in python using matplotlib if possible.
[ "Sadly there is not built-in fonction in matplotlib to create such a graph.\nHowever, You can use the following code to have a similar output. This snippet is removing unwanted spines (left, right and top) and then using scatterplot to simulate a 1d graph.\nAs Follows:\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfig, ax = plt.subplots(figsize=(10,1))\n\nx = [1,2,3,4,9,10]\nidx = np.arange(1,len(x)+1)\nax.spines['top'].set_visible(False)\nax.spines['right'].set_visible(False)\nax.spines['left'].set_visible(False)\nax.spines['bottom'].set_position('zero')\nax.spines['bottom'].set_alpha(0.2)\nax.get_yaxis().set_visible(False)\nax.set_xlabel('Gene 1')\nax.scatter(x, np.zeros(len(x)), s=300, c='lightgreen')\nax.set_xticks([min(x), max(x)], ['Low Values', 'High Values'])\n \nfor i in range(len(idx)):\n ax.annotate(idx[i], (x[i], 0), textcoords=\"offset points\",\n xytext=(0,0), # distance from text to points (x,y)\n ha='center')\nplt.show()\n\nOutputs:\n\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074548385_matplotlib_python.txt
Q: How can I shortern if, elif, elif statements in Python How can I make the following code short: q=0.34 density='' if abs(q) ==0: density='Null' elif abs(q) <= 0.09: density='negligible' elif abs(q) <= 0.49: density='slight' elif abs(q) <= 0.69: density='strong' else: density='very strong' print(q,", ", density) Expected output : 0.34, 'slight' I think there is a solution by using dictionaries, Any help from your side will be highly appreciated ! A: You can try something like that: def f(q): # List of your limits values and their density values values = [(0, "Null"), (0.09, "negligible"), (0.49, "slight"), (0.69, "strong")] # Default value of the density, i.e. your else statement density = "very strong" # Search the good density and stop when it is found for (l, d) in values: if abs(q) <= l: density = d break print(q, ", ", density) I think the comments are explicit enough to explain the code but don't hesitate to ask if it is not clear. A: Coded up a solution here which instead of checking all the if-else statements, it rather loops through an array of values and finds in which space the input value belongs: import numpy as np vals = [0, 0.09,0.49,0.69,] msgs = ['Null', 'negligible', 'slight', 'strong', 'very strong'] q=0.5 density='' def calc_density(q:float) -> str: are_greater_than = q>np.array(vals) if all(are_greater_than): bools = -1 else: bools = np.argmin(are_greater_than) return msgs[bools] for q in [-0.1, 0.0, 0.2, 0.07, 0.8]: print(q, calc_density(q)) # >>> -0.1 Null # >>> 0.0 Null # >>> 0.2 slight # >>> 0.07 negligible # >>> 0.8 very strong Hope this helps! A: If this is used in a single place, this code is good as is, and there is nothing wrong with it. If there are more places in which you want to assign a numeric range to a string, you can use a function or a class to do it,in a way that you can encode the values in a better way. For example,a simple, configurable function to do the same would be: def _range_to_str(ranges, value): for threshold, description in ranges.items(): if value <= threshold: return description raise ValueError(f"{value} out of range for {ranges}") densities = {0: "", 0.09:"negligible", 0.49: "slight", ...} def density_description(value): return _range_to_str(densities, value) A: q=0.34 density='' conditions = [ (0,'null'), (0.09, 'negligible'), (0.49, 'slight'), (0.69, 'strong') ] # loops through the conditions and check if they are smaller # if they are, immediately exit the loop, retaining the correct density value for limit, density in conditions: if q <= limit: break # this if statement checks if its larger than the last condition # this ensures that even if it never reached any condition, it doesn't # just output the last value if q > conditions[-1][0]: density = 'very strong' print(q,", ", density) of course if you want to make it more short :) (assuming q is always smaller than 9999) q=0.34 c = [(0,'null'),(0.09,'negligible'),(0.49,'slight'),(0.69,'strong'), (9999,'very strong')] print(q,',',[j for i,j in c if q<=i][0])
How can I shortern if, elif, elif statements in Python
How can I make the following code short: q=0.34 density='' if abs(q) ==0: density='Null' elif abs(q) <= 0.09: density='negligible' elif abs(q) <= 0.49: density='slight' elif abs(q) <= 0.69: density='strong' else: density='very strong' print(q,", ", density) Expected output : 0.34, 'slight' I think there is a solution by using dictionaries, Any help from your side will be highly appreciated !
[ "You can try something like that:\ndef f(q):\n # List of your limits values and their density values\n values = [(0, \"Null\"), (0.09, \"negligible\"), (0.49, \"slight\"), (0.69, \"strong\")]\n # Default value of the density, i.e. your else statement\n density = \"very strong\"\n\n # Search the good density and stop when it is found\n for (l, d) in values:\n if abs(q) <= l:\n density = d\n break\n\n print(q, \", \", density)\n\nI think the comments are explicit enough to explain the code but don't hesitate to ask if it is not clear.\n", "Coded up a solution here which instead of checking all the if-else statements, it rather loops through an array of values and finds in which space the input value belongs:\nimport numpy as np\nvals = [0, 0.09,0.49,0.69,]\nmsgs = ['Null', 'negligible', 'slight', 'strong', 'very strong']\n\nq=0.5\ndensity=''\n\ndef calc_density(q:float) -> str:\n are_greater_than = q>np.array(vals)\n if all(are_greater_than): bools = -1\n else: bools = np.argmin(are_greater_than)\n return msgs[bools]\n\nfor q in [-0.1, 0.0, 0.2, 0.07, 0.8]:\n print(q, calc_density(q))\n\n# >>> -0.1 Null\n# >>> 0.0 Null\n# >>> 0.2 slight\n# >>> 0.07 negligible\n# >>> 0.8 very strong\n\nHope this helps!\n", "If this is used in a single place, this code is good as is, and there is nothing wrong with it.\nIf there are more places in which you want to assign a numeric range to a string, you can use a function or a class to do it,in a way that you can encode the values in a better way.\nFor example,a simple, configurable function to do the same would be:\ndef _range_to_str(ranges, value):\n for threshold, description in ranges.items():\n if value <= threshold:\n return description\n raise ValueError(f\"{value} out of range for {ranges}\")\n\ndensities = {0: \"\", 0.09:\"negligible\", 0.49: \"slight\", ...}\n\ndef density_description(value):\n return _range_to_str(densities, value)\n\n", "q=0.34\ndensity=''\nconditions = [\n(0,'null'),\n(0.09, 'negligible'),\n(0.49, 'slight'),\n(0.69, 'strong')\n]\n# loops through the conditions and check if they are smaller\n# if they are, immediately exit the loop, retaining the correct density value\nfor limit, density in conditions:\n if q <= limit:\n break\n# this if statement checks if its larger than the last condition\n# this ensures that even if it never reached any condition, it doesn't\n# just output the last value\nif q > conditions[-1][0]:\n density = 'very strong'\n\nprint(q,\", \", density)\n\nof course if you want to make it more short :)\n(assuming q is always smaller than 9999)\nq=0.34\nc = [(0,'null'),(0.09,'negligible'),(0.49,'slight'),(0.69,'strong'), (9999,'very strong')]\nprint(q,',',[j for i,j in c if q<=i][0])\n\n" ]
[ 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074548574_python.txt
Q: How do I show text from a third dataframe column when hovering over a line chart made from 2 other columns? So I have a dataframe with 3 columns: date, price, text import pandas as pd from datetime import datetime import random columns = ('dates','prices','text') datelist = pd.date_range(datetime.today(), periods=5).tolist() prices = [] for i in range(0, 5): prices.append(random.randint(50, 60)) text =['AAA','BBB','CCC','DDD','EEE'] df = pd.DataFrame({'dates': datelist, 'price':prices, 'text':text}) dates price text 0 2022-11-23 14:11:51.142574 51 AAA 1 2022-11-24 14:11:51.142574 57 BBB 2 2022-11-25 14:11:51.142574 52 CCC 3 2022-11-26 14:11:51.142574 51 DDD 4 2022-11-27 14:11:51.142574 59 EEE I want to plot date and price on a line chart, but when I hover over the line I want it to show the text from the row corresponding to that date. eg when I hover over the point corresponding to 2022-11-27 I want the text to show 'EEE' ive tried a few things in matplotlib etc but can only get data from the x and y axis to show but I cant figure out how to show data from a different column. A: You could use Plotly. import plotly.graph_objects as go fig = go.Figure(data=go.Scatter(x=df['dates'], y=df['price'], mode='lines+markers', text=df['text'])) fig.show() A: You should be aware that cursor & dataframe indexing will probably work well with points on a scatter plot, but it is a little bit trickier to handle a lineplot. With a lineplot, matplotlib draws the line between 2 data points (basically, it's linear interpolation), so a specific logic must be taken care of to: specify the intended behavior implement the corresponding mouseover behavior when the cursor lands "between" 2 data points. The lib/links below may provide tools to handle scatter plots and lineplots, but I am not expert enough to point you to this specific part in either the SO link nor the mplcursors link. (besides, the exact intended behavioor was not clearly stated in your initial question; consider editing/clarifying) So, alternatively to DankyKang's answer, have a look at this SO question and answers that cover a large panel of possibilities for mouseover: How to add hovering annotations to a plot A library worth noting is this one: https://mplcursors.readthedocs.io/en/stable/ Quoting: mplcursors provides interactive data selection cursors for Matplotlib. It is inspired from mpldatacursor, with a much simplified API. mplcursors requires Python 3, and Matplotlib≥3.1. Specifically this example based on dataframes: https://mplcursors.readthedocs.io/en/stable/examples/dataframe.html Quoting: DataFrames can be used similarly to any other kind of input. Here, we generate a scatter plot using two columns and label the points using all columns. This example also applies a shadow effect to the hover panel. copy-pasta of code example, should this answer be considered not complete enough : from matplotlib import pyplot as plt from matplotlib.patheffects import withSimplePatchShadow import mplcursors from pandas import DataFrame df = DataFrame( dict( Suburb=["Ames", "Somerset", "Sawyer"], Area=[1023, 2093, 723], SalePrice=[507500, 647000, 546999], ) ) df.plot.scatter(x="Area", y="SalePrice", s=100) def show_hover_panel(get_text_func=None): cursor = mplcursors.cursor( hover=2, # Transient annotation_kwargs=dict( bbox=dict( boxstyle="square,pad=0.5", facecolor="white", edgecolor="#ddd", linewidth=0.5, path_effects=[withSimplePatchShadow(offset=(1.5, -1.5))], ), linespacing=1.5, arrowprops=None, ), highlight=True, highlight_kwargs=dict(linewidth=2), ) if get_text_func: cursor.connect( event="add", func=lambda sel: sel.annotation.set_text(get_text_func(sel.index)), ) return cursor def on_add(index): item = df.iloc[index] parts = [ f"Suburb: {item.Suburb}", f"Area: {item.Area:,.0f}m²", f"Sale price: ${item.SalePrice:,.0f}", ] return "\n".join(parts) show_hover_panel(on_add) plt.show()
How do I show text from a third dataframe column when hovering over a line chart made from 2 other columns?
So I have a dataframe with 3 columns: date, price, text import pandas as pd from datetime import datetime import random columns = ('dates','prices','text') datelist = pd.date_range(datetime.today(), periods=5).tolist() prices = [] for i in range(0, 5): prices.append(random.randint(50, 60)) text =['AAA','BBB','CCC','DDD','EEE'] df = pd.DataFrame({'dates': datelist, 'price':prices, 'text':text}) dates price text 0 2022-11-23 14:11:51.142574 51 AAA 1 2022-11-24 14:11:51.142574 57 BBB 2 2022-11-25 14:11:51.142574 52 CCC 3 2022-11-26 14:11:51.142574 51 DDD 4 2022-11-27 14:11:51.142574 59 EEE I want to plot date and price on a line chart, but when I hover over the line I want it to show the text from the row corresponding to that date. eg when I hover over the point corresponding to 2022-11-27 I want the text to show 'EEE' ive tried a few things in matplotlib etc but can only get data from the x and y axis to show but I cant figure out how to show data from a different column.
[ "You could use Plotly.\nimport plotly.graph_objects as go\n\nfig = go.Figure(data=go.Scatter(x=df['dates'], y=df['price'], mode='lines+markers', text=df['text']))\nfig.show()\n\n", "You should be aware that cursor & dataframe indexing will probably work well with points on a scatter plot, but it is a little bit trickier to handle a lineplot.\nWith a lineplot, matplotlib draws the line between 2 data points (basically, it's linear interpolation), so a specific logic must be taken care of to:\n\nspecify the intended behavior\nimplement the corresponding mouseover behavior when the cursor lands \"between\" 2 data points.\n\nThe lib/links below may provide tools to handle scatter plots and lineplots, but I am not expert enough to point you to this specific part in either the SO link nor the mplcursors link.\n(besides, the exact intended behavioor was not clearly stated in your initial question; consider editing/clarifying)\n\nSo, alternatively to DankyKang's answer, have a look at this SO question and answers that cover a large panel of possibilities for mouseover: How to add hovering annotations to a plot\nA library worth noting is this one: https://mplcursors.readthedocs.io/en/stable/\nQuoting:\n\nmplcursors provides interactive data selection cursors for Matplotlib. It is inspired from mpldatacursor, with a much simplified API.\nmplcursors requires Python 3, and Matplotlib≥3.1.\n\nSpecifically this example based on dataframes: https://mplcursors.readthedocs.io/en/stable/examples/dataframe.html\nQuoting:\n\nDataFrames can be used similarly to any other kind of input. Here, we generate a scatter plot using two columns and label the points using all columns.\nThis example also applies a shadow effect to the hover panel.\n\ncopy-pasta of code example, should this answer be considered not complete enough :\nfrom matplotlib import pyplot as plt\n\nfrom matplotlib.patheffects import withSimplePatchShadow\nimport mplcursors\nfrom pandas import DataFrame\n\n\ndf = DataFrame(\n dict(\n Suburb=[\"Ames\", \"Somerset\", \"Sawyer\"],\n Area=[1023, 2093, 723],\n SalePrice=[507500, 647000, 546999],\n )\n)\n\ndf.plot.scatter(x=\"Area\", y=\"SalePrice\", s=100)\n\n\ndef show_hover_panel(get_text_func=None):\n cursor = mplcursors.cursor(\n hover=2, # Transient\n annotation_kwargs=dict(\n bbox=dict(\n boxstyle=\"square,pad=0.5\",\n facecolor=\"white\",\n edgecolor=\"#ddd\",\n linewidth=0.5,\n path_effects=[withSimplePatchShadow(offset=(1.5, -1.5))],\n ),\n linespacing=1.5,\n arrowprops=None,\n ),\n highlight=True,\n highlight_kwargs=dict(linewidth=2),\n )\n\n if get_text_func:\n cursor.connect(\n event=\"add\",\n func=lambda sel: sel.annotation.set_text(get_text_func(sel.index)),\n )\n\n return cursor\n\n\ndef on_add(index):\n item = df.iloc[index]\n parts = [\n f\"Suburb: {item.Suburb}\",\n f\"Area: {item.Area:,.0f}m²\",\n f\"Sale price: ${item.SalePrice:,.0f}\",\n ]\n\n return \"\\n\".join(parts)\n\n\nshow_hover_panel(on_add)\n\nplt.show()\n\n" ]
[ 1, 0 ]
[]
[]
[ "matplotlib", "pandas", "plotly_python", "python" ]
stackoverflow_0074548257_matplotlib_pandas_plotly_python_python.txt
Q: Why are python dates such a mess and what can I do about it? A common source of errors in my Python codebase are dates. Specifically, the different implementations of dates and datetimes, and how comparisons are handled between them. These are the date types in my codebase import datetime import pandas as pd import polars as pl x1 = pd.to_datetime('2020-10-01') x2 = datetime.datetime(2020, 10,1) x3 = pl.DataFrame({'i':[x2]}).select(pl.col('i').cast(pl.Date)).to_numpy()[0,0] x4 = pl.DataFrame({'i':[x2]}).select(pl.col('i').cast(pl.Datetime)).to_numpy()[0,0] x5 = pendulum.parse('2020-10-01') x6 = x5.date() x7 = x1.date() You can print them to see: x1=2020-10-01 00:00:00 , type(x1)=<class 'pandas._libs.tslibs.timestamps.Timestamp'> x2=2020-10-01 00:00:00 , type(x2)=<class 'datetime.datetime'> x3=2020-10-01 , type(x3)=<class 'numpy.datetime64'> x4=2020-10-01T00:00:00.000000 , type(x4)=<class 'numpy.datetime64'> x5=2020-10-01T00:00:00+00:00 , type(x5)=<class 'pendulum.datetime.DateTime'> x6=2020-10-01 , type(x6)=<class 'pendulum.date.Date'> x7=2020-10-01 , type(x7)=<class 'datetime.date'> Is there a canonical date representation in Python? I suppose x7: datetime.date is probably closest... Also, note comparisons are a nightmare, see here a table of trying to do xi == xj x1 x2 x3 x4 x5 x6 x7 x1: <class 'pandas._libs.tslibs.timestamps.Timestamp'> True True ERROR: Only resolutions 's', 'ms', 'us', 'ns' are supported. True False True True x2: <class 'datetime.datetime'> True True False True False False False x3: <class 'numpy.datetime64'> True False True True False True True x4: <class 'numpy.datetime64'> True True True True False False False x5: <class 'pendulum.datetime.DateTime'> False False False False True False False x6: <class 'pendulum.date.Date'> True True True False False True True x7: <class 'datetime.date'> True False True False False True True Also note it's not even symmetric: The pain is that comparisons are even stranger. Here is xi>=xj: Red represents an ERROR: As you can imagine, there is an ever growing amount of glue code to keep this under control. Is there any advice on how to handle date & datetime types in Python? For simplicity: I never need timezone data, everything should always be UTC Sometimes dates are passed around as strings for convenience (eg. parsed from a JSON) I at most need seconds resolution, but 99% of my work uses only dates. A: All listed types can be converted to numpy datetime64. If you don't need more than seconds resolution, you might set the unit to 's' (optional). Ex: # Python datetime.datetime x2_np = np.datetime64(x2.replace(tzinfo=None), 's') print(x2_np, repr(x2_np)) # 2020-10-01T00:00:00 numpy.datetime64('2020-10-01T00:00:00') # Python datetime.date x6_np = np.datetime64(x6, 's') print(x6_np, repr(x6_np)) # 2020-10-01T00:00:00 numpy.datetime64('2020-10-01T00:00:00') # pendulum datetime x5_np = np.datetime64(x5.replace(tzinfo=None), 's') print(x5_np, repr(x5_np)) # 2020-10-01T00:00:00 numpy.datetime64('2020-10-01T00:00:00') # pd.Timestamp x1_np = x1.to_numpy().astype('datetime64[s]') print(x1_np, repr(x1_np)) # 2020-10-01T00:00:00 numpy.datetime64('2020-10-01T00:00:00') Since numpy tries to avoid time zones (defaults to UTC), make sure to replace the tzinfo for datetime.datetime and pendulum.datetime, should it be set there. Now you could put this all in one converter function that is essentially a big switch case. Use with caution on big datasets however, convenience does not come for free most of the time. Ex: def convert_dt_to_numpy(dt, unit='s'): if isinstance(dt, (datetime.datetime, pendulum.DateTime)): return np.datetime64(dt.replace(tzinfo=None), unit) if isinstance(dt, (datetime.date, pendulum.Date)): return np.datetime64(dt, unit) if isinstance(dt, pd.Timestamp): return dt.to_numpy().astype(f'datetime64[{unit}]') raise ValueError(f"conversion for '{dt}' of {type(dt)} unknown") for dt in (x1, x2, x6, x5, 7): print(convert_dt_to_numpy(dt))
Why are python dates such a mess and what can I do about it?
A common source of errors in my Python codebase are dates. Specifically, the different implementations of dates and datetimes, and how comparisons are handled between them. These are the date types in my codebase import datetime import pandas as pd import polars as pl x1 = pd.to_datetime('2020-10-01') x2 = datetime.datetime(2020, 10,1) x3 = pl.DataFrame({'i':[x2]}).select(pl.col('i').cast(pl.Date)).to_numpy()[0,0] x4 = pl.DataFrame({'i':[x2]}).select(pl.col('i').cast(pl.Datetime)).to_numpy()[0,0] x5 = pendulum.parse('2020-10-01') x6 = x5.date() x7 = x1.date() You can print them to see: x1=2020-10-01 00:00:00 , type(x1)=<class 'pandas._libs.tslibs.timestamps.Timestamp'> x2=2020-10-01 00:00:00 , type(x2)=<class 'datetime.datetime'> x3=2020-10-01 , type(x3)=<class 'numpy.datetime64'> x4=2020-10-01T00:00:00.000000 , type(x4)=<class 'numpy.datetime64'> x5=2020-10-01T00:00:00+00:00 , type(x5)=<class 'pendulum.datetime.DateTime'> x6=2020-10-01 , type(x6)=<class 'pendulum.date.Date'> x7=2020-10-01 , type(x7)=<class 'datetime.date'> Is there a canonical date representation in Python? I suppose x7: datetime.date is probably closest... Also, note comparisons are a nightmare, see here a table of trying to do xi == xj x1 x2 x3 x4 x5 x6 x7 x1: <class 'pandas._libs.tslibs.timestamps.Timestamp'> True True ERROR: Only resolutions 's', 'ms', 'us', 'ns' are supported. True False True True x2: <class 'datetime.datetime'> True True False True False False False x3: <class 'numpy.datetime64'> True False True True False True True x4: <class 'numpy.datetime64'> True True True True False False False x5: <class 'pendulum.datetime.DateTime'> False False False False True False False x6: <class 'pendulum.date.Date'> True True True False False True True x7: <class 'datetime.date'> True False True False False True True Also note it's not even symmetric: The pain is that comparisons are even stranger. Here is xi>=xj: Red represents an ERROR: As you can imagine, there is an ever growing amount of glue code to keep this under control. Is there any advice on how to handle date & datetime types in Python? For simplicity: I never need timezone data, everything should always be UTC Sometimes dates are passed around as strings for convenience (eg. parsed from a JSON) I at most need seconds resolution, but 99% of my work uses only dates.
[ "All listed types can be converted to numpy datetime64. If you don't need more than seconds resolution, you might set the unit to 's' (optional). Ex:\n# Python datetime.datetime\nx2_np = np.datetime64(x2.replace(tzinfo=None), 's')\nprint(x2_np, repr(x2_np))\n# 2020-10-01T00:00:00 numpy.datetime64('2020-10-01T00:00:00')\n\n# Python datetime.date\nx6_np = np.datetime64(x6, 's')\nprint(x6_np, repr(x6_np))\n# 2020-10-01T00:00:00 numpy.datetime64('2020-10-01T00:00:00')\n\n# pendulum datetime\nx5_np = np.datetime64(x5.replace(tzinfo=None), 's')\nprint(x5_np, repr(x5_np))\n# 2020-10-01T00:00:00 numpy.datetime64('2020-10-01T00:00:00')\n\n# pd.Timestamp\nx1_np = x1.to_numpy().astype('datetime64[s]')\nprint(x1_np, repr(x1_np))\n# 2020-10-01T00:00:00 numpy.datetime64('2020-10-01T00:00:00')\n\nSince numpy tries to avoid time zones (defaults to UTC), make sure to replace the tzinfo for datetime.datetime and pendulum.datetime, should it be set there.\nNow you could put this all in one converter function that is essentially a big switch case. Use with caution on big datasets however, convenience does not come for free most of the time. Ex:\ndef convert_dt_to_numpy(dt, unit='s'):\n if isinstance(dt, (datetime.datetime, pendulum.DateTime)):\n return np.datetime64(dt.replace(tzinfo=None), unit)\n if isinstance(dt, (datetime.date, pendulum.Date)):\n return np.datetime64(dt, unit)\n if isinstance(dt, pd.Timestamp):\n return dt.to_numpy().astype(f'datetime64[{unit}]')\n raise ValueError(f\"conversion for '{dt}' of {type(dt)} unknown\")\n \nfor dt in (x1, x2, x6, x5, 7):\n print(convert_dt_to_numpy(dt))\n\n" ]
[ 1 ]
[]
[]
[ "date", "datetime", "numpy", "pandas", "python" ]
stackoverflow_0074547208_date_datetime_numpy_pandas_python.txt
Q: Create a multiplication table application where user will enter a sentinel value n and the application will display the mathematical multiplication tables till given sentinel value n. For example, if user enters n = 4 then application will display the multiplication tables of 2, 3, and 4. Constraint:  Make use of oop concepts class methods and attributes DISPLAY TABLES FROM 2 TO "n"
Create a multiplication table application
where user will enter a sentinel value n and the application will display the mathematical multiplication tables till given sentinel value n. For example, if user enters n = 4 then application will display the multiplication tables of 2, 3, and 4. Constraint:  Make use of oop concepts class methods and attributes DISPLAY TABLES FROM 2 TO "n"
[]
[]
[ "class tables:\ndef tables (self ,n value):\nfor x in range(2, n value + 1):\nprint(\"\\n\",\" TABLE OF \",x,\"\\n\")\nfor y in range(1, 11):\nprint(x,\" x\", y,\"=\",x*y)\nn value=in t(input(\"enter a value:\"))\nf=tables()\nf. tables(n value)\n" ]
[ -1 ]
[ "oop", "python" ]
stackoverflow_0074541913_oop_python.txt
Q: Command runs in discord.py, but does not send embed and gives no error I ran into a strange problem on discord.py where. The rest of it works, but it does not reply with my embed with no errors. This is the code that wont work: #The code if the number is incorrect print(arg1) placement = sessions.index(ctx.author.id) placement = +1 if arg1 != str(sessions[placement]): if int(arg1) >= sessions[placement]: print(sessions) placement = sessions.index(ctx.author.id) placement = +2 print(sessions) embed=discord.Embed(title="Incorrect", description=f"Your number is too big, you have {str(sessions[placement])} left.", color=0xFF5733) embed.set_thumbnail(url="https://simg.nicepng.com/png/small/255-2554736_cancel-cliparts-red-x-transparent.png") await ctx.reply(embed=embed) else: placement = sessions.index(ctx.author.id) placement = +2 print(sessions) embed=discord.Embed(title="Incorrect", description=f"Your number is too small you have {str(sessions[placement])} left.", color=0xFF5733) embed.set_thumbnail(url="https://simg.nicepng.com/png/small/255-2554736_cancel-cliparts-red-x-transparent.png") await ctx.reply(embed=embed) The functions run but the embeds will not send and no error is being logged. Im trying to create a random number guessing game bot that generates random sessions for individual users to guess a number. But I discovered that for some reason it will not reply with the embed. I tried renaming it, but it still did not work, I changed it to discord.embed but still does not work. I do not know what is causing this. Just to note, the rest of the command does work and so does the code except for sending the embed. I don't know why its these two embeds individually, but the rest of the messages send. Can anyone help? A: Try Ctx.send or Ctx.message.reply I use Colour name in embeds try to change that too
Command runs in discord.py, but does not send embed and gives no error
I ran into a strange problem on discord.py where. The rest of it works, but it does not reply with my embed with no errors. This is the code that wont work: #The code if the number is incorrect print(arg1) placement = sessions.index(ctx.author.id) placement = +1 if arg1 != str(sessions[placement]): if int(arg1) >= sessions[placement]: print(sessions) placement = sessions.index(ctx.author.id) placement = +2 print(sessions) embed=discord.Embed(title="Incorrect", description=f"Your number is too big, you have {str(sessions[placement])} left.", color=0xFF5733) embed.set_thumbnail(url="https://simg.nicepng.com/png/small/255-2554736_cancel-cliparts-red-x-transparent.png") await ctx.reply(embed=embed) else: placement = sessions.index(ctx.author.id) placement = +2 print(sessions) embed=discord.Embed(title="Incorrect", description=f"Your number is too small you have {str(sessions[placement])} left.", color=0xFF5733) embed.set_thumbnail(url="https://simg.nicepng.com/png/small/255-2554736_cancel-cliparts-red-x-transparent.png") await ctx.reply(embed=embed) The functions run but the embeds will not send and no error is being logged. Im trying to create a random number guessing game bot that generates random sessions for individual users to guess a number. But I discovered that for some reason it will not reply with the embed. I tried renaming it, but it still did not work, I changed it to discord.embed but still does not work. I do not know what is causing this. Just to note, the rest of the command does work and so does the code except for sending the embed. I don't know why its these two embeds individually, but the rest of the messages send. Can anyone help?
[ "Try Ctx.send or Ctx.message.reply\nI use Colour name in embeds try to change that too\n" ]
[ 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074548681_discord.py_python.txt
Q: What is a "callable"? Now that it's clear what a metaclass is, there is an associated concept that I use all the time without knowing what it really means. I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for. Could you give me some explanations, including examples with the magic method ? A: A callable is anything that can be called. The built-in callable (PyCallable_Check in objects.c) checks if the argument is either: an instance of a class with a __call__ method or is of a type that has a non null tp_call (c struct) member which indicates callability otherwise (such as in functions, methods etc.) The method named __call__ is (according to the documentation) Called when the instance is ''called'' as a function Example class Foo: def __call__(self): print 'called' foo_instance = Foo() foo_instance() #this is calling the __call__ method A: From Python's sources object.c: /* Test whether an object can be called */ int PyCallable_Check(PyObject *x) { if (x == NULL) return 0; if (PyInstance_Check(x)) { PyObject *call = PyObject_GetAttrString(x, "__call__"); if (call == NULL) { PyErr_Clear(); return 0; } /* Could test recursively but don't, for fear of endless recursion if some joker sets self.__call__ = self */ Py_DECREF(call); return 1; } else { return x->ob_type->tp_call != NULL; } } It says: If an object is an instance of some class then it is callable iff it has __call__ attribute. Else the object x is callable iff x->ob_type->tp_call != NULL Desciption of tp_call field: ternaryfunc tp_call An optional pointer to a function that implements calling the object. This should be NULL if the object is not callable. The signature is the same as for PyObject_Call(). This field is inherited by subtypes. You can always use built-in callable function to determine whether given object is callable or not; or better yet just call it and catch TypeError later. callable is removed in Python 3.0 and 3.1, use callable = lambda o: hasattr(o, '__call__') or isinstance(o, collections.Callable). Example, a simplistic cache implementation: class Cached: def __init__(self, function): self.function = function self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: ret = self.cache[args] = self.function(*args) return ret Usage: @Cached def ack(x, y): return ack(x-1, ack(x, y-1)) if x*y else (x + y + 1) Example from standard library, file site.py, definition of built-in exit() and quit() functions: class Quitter(object): def __init__(self, name): self.name = name def __repr__(self): return 'Use %s() or %s to exit' % (self.name, eof) def __call__(self, code=None): # Shells like IDLE catch the SystemExit, but listen when their # stdin wrapper is closed. try: sys.stdin.close() except: pass raise SystemExit(code) __builtin__.quit = Quitter('quit') __builtin__.exit = Quitter('exit') A: A callable is an object allows you to use round parenthesis ( ) and eventually pass some parameters, just like functions. Every time you define a function python creates a callable object. In example, you could define the function func in these ways (it's the same): class a(object): def __call__(self, *args): print 'Hello' func = a() # or ... def func(*args): print 'Hello' You could use this method instead of methods like doit or run, I think it's just more clear to see obj() than obj.doit() A: Let me explain backwards: Consider this... foo() ... as syntactic sugar for: foo.__call__() Where foo can be any object that responds to __call__. When I say any object, I mean it: built-in types, your own classes and their instances. In the case of built-in types, when you write: int('10') unicode(10) You're essentially doing: int.__call__('10') unicode.__call__(10) That's also why you don't have foo = new int in Python: you just make the class object return an instance of it on __call__. The way Python solves this is very elegant in my opinion. A: A Callable is an object that has the __call__ method. This means you can fake callable functions or do neat things like Partial Function Application where you take a function and add something that enhances it or fills in some of the parameters, returning something that can be called in turn (known as Currying in functional programming circles). Certain typographic errors will have the interpreter attempting to call something you did not intend, such as (for example) a string. This can produce errors where the interpreter attempts to execute a non-callable application. You can see this happening in a python interpreter by doing something like the transcript below. [nigel@k9 ~]$ python Python 2.5 (r25:51908, Nov 6 2007, 15:55:44) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 'aaa'() # <== Here we attempt to call a string. Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object is not callable >>> A: __call__ makes any object be callable as a function. This example will output 8: class Adder(object): def __init__(self, val): self.val = val def __call__(self, val): return self.val + val func = Adder(5) print func(3) A: Quite simply, a "callable" is something that can be called like a method. The built in function "callable()" will tell you whether something appears to be callable, as will checking for a call property. Functions are callable as are classes, class instances can be callable. See more about this here and here. A: In Python a callable is an object which type has a __call__ method: >>> class Foo: ... pass ... >>> class Bar(object): ... pass ... >>> type(Foo).__call__(Foo) <__main__.Foo instance at 0x711440> >>> type(Bar).__call__(Bar) <__main__.Bar object at 0x712110> >>> def foo(bar): ... return bar ... >>> type(foo).__call__(foo, 42) 42 As simple as that :) This of course can be overloaded: >>> class Foo(object): ... def __call__(self): ... return 42 ... >>> f = Foo() >>> f() 42 A: It's something you can put "(args)" after and expect it to work. A callable is usually a method or a class. Methods get called, classes get instantiated. A: To check function or method of class is callable or not that means we can call that function. Class A: def __init__(self,val): self.val = val def bar(self): print "bar" obj = A() callable(obj.bar) True callable(obj.__init___) False def foo(): return "s" callable(foo) True callable(foo()) False A: callables implement the __call__ special method so any object with such a method is callable. A: Callable is a type or class of "Build-in function or Method" with a method call >>> type(callable) <class 'builtin_function_or_method'> >>> Example: print is a callable object. With a build-in function call When you invoke the print function, Python creates an object of type print and invokes its method call passing the parameters if any. >>> type(print) <class 'builtin_function_or_method'> >>> print.__call__(10) 10 >>> print(10) 10 >>> A: A class, function, method and object which has __call__() are callable. You can check if callable with callable() which returns True if callable and returns False if not callable as shown below: class Class1: def __call__(self): print("__call__") class Class2: pass def func(): pass print(callable(Class1)) # Class1 print(callable(Class2)) # Class2 print(callable(Class1())) # Class1 object print(callable(Class2())) # Class2 object print(callable(func)) # func Then, only Class2 object which doesn't have __call__() is not callable returning False as shown below: True # Class1 True # Class2 True # Class1 object False # Class2 object True # func In addition, all of them below are not callable returning False as shown below: print(callable("Hello")) # "str" type print(callable(100)) # "int" type print(callable(100.23)) # "float" type print(callable(100 + 2j)) # "complex" type print(callable(True)) # "bool" type print(callable(None)) # "NoneType" print(callable([])) # "list" type print(callable(())) # "tuple" type print(callable({})) # "dict" type print(callable({""})) # "set" type Output: False # "str" type False # "int" type False # "float" type False # "complex" type False # "bool" type False # "NoneType" False # "list" type False # "tuple" type False # "dict" type False # "set" type
What is a "callable"?
Now that it's clear what a metaclass is, there is an associated concept that I use all the time without knowing what it really means. I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for. Could you give me some explanations, including examples with the magic method ?
[ "A callable is anything that can be called. \nThe built-in callable (PyCallable_Check in objects.c) checks if the argument is either:\n\nan instance of a class with a __call__ method or\nis of a type that has a non null tp_call (c struct) member which indicates callability otherwise (such as in functions, methods etc.)\n\nThe method named __call__ is (according to the documentation)\n\nCalled when the instance is ''called'' as a function\n\nExample\nclass Foo:\n def __call__(self):\n print 'called'\n\nfoo_instance = Foo()\nfoo_instance() #this is calling the __call__ method\n\n", "From Python's sources object.c:\n/* Test whether an object can be called */\n\nint\nPyCallable_Check(PyObject *x)\n{\n if (x == NULL)\n return 0;\n if (PyInstance_Check(x)) {\n PyObject *call = PyObject_GetAttrString(x, \"__call__\");\n if (call == NULL) {\n PyErr_Clear();\n return 0;\n }\n /* Could test recursively but don't, for fear of endless\n recursion if some joker sets self.__call__ = self */\n Py_DECREF(call);\n return 1;\n }\n else {\n return x->ob_type->tp_call != NULL;\n }\n}\n\nIt says:\n\nIf an object is an instance of some class then it is callable iff it has __call__ attribute.\nElse the object x is callable iff x->ob_type->tp_call != NULL\n\nDesciption of tp_call field:\n\nternaryfunc tp_call An optional\n pointer to a function that implements\n calling the object. This should be\n NULL if the object is not callable.\n The signature is the same as for\n PyObject_Call(). This field is\n inherited by subtypes.\n\nYou can always use built-in callable function to determine whether given object is callable or not; or better yet just call it and catch TypeError later. callable is removed in Python 3.0 and 3.1, use callable = lambda o: hasattr(o, '__call__') or isinstance(o, collections.Callable).\nExample, a simplistic cache implementation:\nclass Cached:\n def __init__(self, function):\n self.function = function\n self.cache = {}\n\n def __call__(self, *args):\n try: return self.cache[args]\n except KeyError:\n ret = self.cache[args] = self.function(*args)\n return ret \n\nUsage:\n@Cached\ndef ack(x, y):\n return ack(x-1, ack(x, y-1)) if x*y else (x + y + 1) \n\nExample from standard library, file site.py, definition of built-in exit() and quit() functions:\nclass Quitter(object):\n def __init__(self, name):\n self.name = name\n def __repr__(self):\n return 'Use %s() or %s to exit' % (self.name, eof)\n def __call__(self, code=None):\n # Shells like IDLE catch the SystemExit, but listen when their\n # stdin wrapper is closed.\n try:\n sys.stdin.close()\n except:\n pass\n raise SystemExit(code)\n__builtin__.quit = Quitter('quit')\n__builtin__.exit = Quitter('exit')\n\n", "A callable is an object allows you to use round parenthesis ( ) and eventually pass some parameters, just like functions.\nEvery time you define a function python creates a callable object. \nIn example, you could define the function func in these ways (it's the same):\nclass a(object):\n def __call__(self, *args):\n print 'Hello'\n\nfunc = a()\n\n# or ... \ndef func(*args):\n print 'Hello'\n\nYou could use this method instead of methods like doit or run, I think it's just more clear to see obj() than obj.doit()\n", "Let me explain backwards:\nConsider this...\nfoo()\n\n... as syntactic sugar for:\nfoo.__call__()\n\nWhere foo can be any object that responds to __call__. When I say any object, I mean it: built-in types, your own classes and their instances.\nIn the case of built-in types, when you write:\nint('10')\nunicode(10)\n\nYou're essentially doing:\nint.__call__('10')\nunicode.__call__(10)\n\nThat's also why you don't have foo = new int in Python: you just make the class object return an instance of it on __call__. The way Python solves this is very elegant in my opinion.\n", "A Callable is an object that has the __call__ method. This means you can fake callable functions or do neat things like Partial Function Application where you take a function and add something that enhances it or fills in some of the parameters, returning something that can be called in turn (known as Currying in functional programming circles).\nCertain typographic errors will have the interpreter attempting to call something you did not intend, such as (for example) a string. This can produce errors where the interpreter attempts to execute a non-callable application. You can see this happening in a python interpreter by doing something like the transcript below.\n[nigel@k9 ~]$ python\nPython 2.5 (r25:51908, Nov 6 2007, 15:55:44) \n[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> 'aaa'() # <== Here we attempt to call a string.\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'str' object is not callable\n>>> \n\n", "__call__ makes any object be callable as a function.\nThis example will output 8:\nclass Adder(object):\n def __init__(self, val):\n self.val = val\n\n def __call__(self, val):\n return self.val + val\n\nfunc = Adder(5)\nprint func(3)\n\n", "Quite simply, a \"callable\" is something that can be called like a method. The built in function \"callable()\" will tell you whether something appears to be callable, as will checking for a call property. Functions are callable as are classes, class instances can be callable. See more about this here and here.\n", "In Python a callable is an object which type has a __call__ method:\n>>> class Foo:\n... pass\n... \n>>> class Bar(object):\n... pass\n... \n>>> type(Foo).__call__(Foo)\n<__main__.Foo instance at 0x711440>\n>>> type(Bar).__call__(Bar)\n<__main__.Bar object at 0x712110>\n>>> def foo(bar):\n... return bar\n... \n>>> type(foo).__call__(foo, 42)\n42\n\nAs simple as that :)\nThis of course can be overloaded:\n>>> class Foo(object):\n... def __call__(self):\n... return 42\n... \n>>> f = Foo()\n>>> f()\n42\n\n", "It's something you can put \"(args)\" after and expect it to work. A callable is usually a method or a class. Methods get called, classes get instantiated.\n", "To check function or method of class is callable or not that means we can call that function.\nClass A:\n def __init__(self,val):\n self.val = val\n def bar(self):\n print \"bar\"\n\nobj = A() \ncallable(obj.bar)\nTrue\ncallable(obj.__init___)\nFalse\ndef foo(): return \"s\"\ncallable(foo)\nTrue\ncallable(foo())\nFalse\n\n", "callables implement the __call__ special method so any object with such a method is callable.\n", "Callable is a type or class of \"Build-in function or Method\" with a method\ncall\n>>> type(callable)\n<class 'builtin_function_or_method'>\n>>>\n\nExample:\nprint is a callable object. With a build-in function call\nWhen you invoke the print function, Python creates an object of type print and invokes its method call passing the parameters if any.\n>>> type(print)\n<class 'builtin_function_or_method'>\n>>> print.__call__(10)\n10\n>>> print(10)\n10\n>>>\n\n", "A class, function, method and object which has __call__() are callable.\nYou can check if callable with callable() which returns True if callable and returns False if not callable as shown below:\nclass Class1:\n def __call__(self):\n print(\"__call__\")\n\nclass Class2:\n pass\n\ndef func():\n pass\n\nprint(callable(Class1)) # Class1\nprint(callable(Class2)) # Class2\n\nprint(callable(Class1())) # Class1 object\nprint(callable(Class2())) # Class2 object\n\nprint(callable(func)) # func\n\nThen, only Class2 object which doesn't have __call__() is not callable returning False as shown below:\nTrue # Class1\nTrue # Class2\nTrue # Class1 object\nFalse # Class2 object\nTrue # func\n\nIn addition, all of them below are not callable returning False as shown below:\nprint(callable(\"Hello\")) # \"str\" type\nprint(callable(100)) # \"int\" type\nprint(callable(100.23)) # \"float\" type\nprint(callable(100 + 2j)) # \"complex\" type\nprint(callable(True)) # \"bool\" type\nprint(callable(None)) # \"NoneType\"\nprint(callable([])) # \"list\" type\nprint(callable(())) # \"tuple\" type\nprint(callable({})) # \"dict\" type\nprint(callable({\"\"})) # \"set\" type\n\nOutput:\nFalse # \"str\" type\nFalse # \"int\" type\nFalse # \"float\" type\nFalse # \"complex\" type\nFalse # \"bool\" type\nFalse # \"NoneType\"\nFalse # \"list\" type\nFalse # \"tuple\" type\nFalse # \"dict\" type\nFalse # \"set\" type\n\n" ]
[ 351, 91, 44, 39, 11, 10, 7, 6, 4, 4, 2, 0, 0 ]
[]
[]
[ "callable", "python" ]
stackoverflow_0000111234_callable_python.txt
Q: Checking if a value exists in one template so that I can create a notification in another template I have a bootstrap card that holds a list of information and within that information there is a boolean value. If that value is true, I'd like to show some kind of notification on the card. Here is what it looks like So if in one of those links there is a value that is true, I'd like something notifying the user that everything is all good and if a value is false, let them know something is wrong. Maybe like a thumbs up and thumbs down from font awesome or something(not important right now). Here is my template that holds that information <link href="{% static 'css/styles.css' %}" rel="stylesheet" /> <div class="card"> <div class="card-header text-dark"> <div class ="card-body"> <div class="table-responsive"> <table class="table table-bordered"> <thead class = "table-light"> <tr class="text-center"> <th>Location</th> <th>RSU ID</th> <th>Install confirmed</th> <th>Winter mode</th> <th>Date created</th> <th>Created by</th> <th>Date updated</th> <th>Updated by</th> </tr> </thead> <tbody> <tr class="text-center"> <td>{{object.location}}</td> <td>{{object.rsu_id}}</td> {% if object.instln_confirmed %} <td><i class="fas fa-check fa-2xl text-primary"></i></td> {% else %} <td><i class="fas fa-x fa-2xl text-danger"></i></td> {% endif %} {% if object.winter_mode %} <td><i class="fas fa-check fa-2xl text-primary"></i></td> {% else %} <td><i class="fas fa-x fa-2xl text-danger"></i></td> {% endif %} <td>{{object.date_created}}</td> <td>{{object.created_by}}</td> <td>{{object.date_updated}}</td> <td>{{object.updated_by}}</td> </tr> </tbody> </table> </div> </div> </div> And here is the template that shows all the different cards <div class="row gx-2 justify-content-center"> {% for object in object_list %} <div class="col-sm-4 mb-3"> <div class="card" style="background-color: lightgrey;"> <div class="card-header text-primary text-center" style="background-color: lightgrey;"> <h3 class="text-primary"><strong>{{ object.name }}</strong></h3> </div> <div class="scroll"> <div class="card"> <div class="card-body"> <div class="row"> {% for info in object.prop_infos.all %} <ul id="list"> <li>{{ info.date_created }}</li> | <li><a href="{% url 'telemetry_updates:property_info_detail' info.id %}">{{info.detail|truncatechars:15 }}</a></li> <hr> </ul> {% endfor %} </div> </div> </div> </div> </div> </div> {% endfor %} </div> Models class Info(models.Model): detail = models.TextField(max_length=3000) instln_confirmed = models.BooleanField(null=True) winter_mode = models.BooleanField(null=True) rsu_id = models.CharField(max_length=255) location = models.CharField(max_length=255) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, related_name='Tc_section') updated_by = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, related_name='Tup_section') date_created = models.DateField('Date created', auto_now_add=True) date_updated = models.DateField('Date updated', auto_now=True) class Meta: ordering=['-date_created'] class Property(models.Model): name = models.CharField(max_length=20) prop_infos = models.ManyToManyField(Info, through='PropertyInfo') date_created = models.DateField('Date created', auto_now_add=True) date_updated = models.DateField('Date updated', auto_now=True) def __str__(self): return self.name def get_section_info(self): return self.prop_infos.order_by('-date_created') class PropertyInfo(models.Model): info = models.ForeignKey(Info, on_delete=models.CASCADE) prop = models.ForeignKey(Property, on_delete=models.CASCADE) Views @login_required @group_required('Telemetry Reports') def create_property_name(request): property_name_form = PropertyForm(data=request.POST or None, files=request.FILES or None) if request.method == 'POST': if property_name_form.is_valid(): object = property_name_form.save(commit=False) object.save() messages.success(request, f"New property successfully created") return redirect('/telemetry_updates/view_properties') context = { "property_name_form":property_name_form, } return render(request, 'telemetry_updates/create_property_name.html', context) # property info create function @login_required @group_required('Telemetry Reports') def create_property_info(request): info_form = InfoForm(data=request.POST or None, files=request.FILES or None) property_info_form = PropertyInfoForm(data=request.POST or None, files=request.FILES or None) if request.method == 'POST': print("Hello world") if info_form.is_valid() and property_info_form.is_valid(): info = info_form.save(commit=False) info.created_by = request.user info.save() property_info = property_info_form.save(commit=False) property_info.info = info property_info.save() property = property_info.prop property.prop_infos.add(info) property.save() messages.success(request, f"Report successfully added") return redirect('/telemetry_updates/view_properties') context = { "form":info_form, "form2":property_info_form, } return render(request, 'telemetry_updates/create_property_info.html', context) # view list of all properties and property infos @login_required def view_properties(request): object_list = Property.objects.all().order_by('-date_created') context = { 'object_list':object_list, } return render(request, 'telemetry_updates/view_properties.html', context) # function to show detail of property infos @login_required def property_info_detail(request, pk): object = Info.objects.get(id=pk) context = { 'object': object, } return render(request, 'telemetry_updates/property_info_detail.html', context) # used to update existing property infos @login_required @group_required('Telemetry Reports') def update_property_info(request, pk): update = Info.objects.get(id=pk) form = InfoForm(data=request.POST or None, files=request.FILES or None, instance=update) if request.method == 'POST': if form.is_valid() and form.has_changed(): form = form.save(commit=False) form.updated_by = request.user form.save() messages.success(request, f"Property report successfully updated!") return redirect('/telemetry_updates/view_properties') else: messages.success(request, "No changes were made") return redirect('/telemetry_updates/view_properties') context = { 'form':form, } return render(request, 'telemetry_updates/update_property_info.html', context) # used to delete section infos @login_required @group_required('Telemetry Reports') def delete_property_info(request,pk): delete = get_object_or_404(PropertyInfo, id=pk) delete.delete() messages.success(request, f"Property report successfully deleted") return redirect('/telemetry_updates/view_properties') So essentially what I need to do is loop through this list of details and if in any of them there is a true or false value, notify the user on the card. A: You can try the following in the nested loop: {% for info in object.prop_infos.all %} <ul id="list"> {% if info.winter_mode and info.instln_confirmed %} <p>Everything is right</p> {% else %} <p> something went wrong.</p> {% endif %} <li>{{ info.date_created }}</li> | <li><a href="{% url 'telemetry_updates:property_info_detail' info.id %}">{{info.detail|truncatechars:15 }}</a></li> <hr> </ul> {% endfor %}
Checking if a value exists in one template so that I can create a notification in another template
I have a bootstrap card that holds a list of information and within that information there is a boolean value. If that value is true, I'd like to show some kind of notification on the card. Here is what it looks like So if in one of those links there is a value that is true, I'd like something notifying the user that everything is all good and if a value is false, let them know something is wrong. Maybe like a thumbs up and thumbs down from font awesome or something(not important right now). Here is my template that holds that information <link href="{% static 'css/styles.css' %}" rel="stylesheet" /> <div class="card"> <div class="card-header text-dark"> <div class ="card-body"> <div class="table-responsive"> <table class="table table-bordered"> <thead class = "table-light"> <tr class="text-center"> <th>Location</th> <th>RSU ID</th> <th>Install confirmed</th> <th>Winter mode</th> <th>Date created</th> <th>Created by</th> <th>Date updated</th> <th>Updated by</th> </tr> </thead> <tbody> <tr class="text-center"> <td>{{object.location}}</td> <td>{{object.rsu_id}}</td> {% if object.instln_confirmed %} <td><i class="fas fa-check fa-2xl text-primary"></i></td> {% else %} <td><i class="fas fa-x fa-2xl text-danger"></i></td> {% endif %} {% if object.winter_mode %} <td><i class="fas fa-check fa-2xl text-primary"></i></td> {% else %} <td><i class="fas fa-x fa-2xl text-danger"></i></td> {% endif %} <td>{{object.date_created}}</td> <td>{{object.created_by}}</td> <td>{{object.date_updated}}</td> <td>{{object.updated_by}}</td> </tr> </tbody> </table> </div> </div> </div> And here is the template that shows all the different cards <div class="row gx-2 justify-content-center"> {% for object in object_list %} <div class="col-sm-4 mb-3"> <div class="card" style="background-color: lightgrey;"> <div class="card-header text-primary text-center" style="background-color: lightgrey;"> <h3 class="text-primary"><strong>{{ object.name }}</strong></h3> </div> <div class="scroll"> <div class="card"> <div class="card-body"> <div class="row"> {% for info in object.prop_infos.all %} <ul id="list"> <li>{{ info.date_created }}</li> | <li><a href="{% url 'telemetry_updates:property_info_detail' info.id %}">{{info.detail|truncatechars:15 }}</a></li> <hr> </ul> {% endfor %} </div> </div> </div> </div> </div> </div> {% endfor %} </div> Models class Info(models.Model): detail = models.TextField(max_length=3000) instln_confirmed = models.BooleanField(null=True) winter_mode = models.BooleanField(null=True) rsu_id = models.CharField(max_length=255) location = models.CharField(max_length=255) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, related_name='Tc_section') updated_by = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, related_name='Tup_section') date_created = models.DateField('Date created', auto_now_add=True) date_updated = models.DateField('Date updated', auto_now=True) class Meta: ordering=['-date_created'] class Property(models.Model): name = models.CharField(max_length=20) prop_infos = models.ManyToManyField(Info, through='PropertyInfo') date_created = models.DateField('Date created', auto_now_add=True) date_updated = models.DateField('Date updated', auto_now=True) def __str__(self): return self.name def get_section_info(self): return self.prop_infos.order_by('-date_created') class PropertyInfo(models.Model): info = models.ForeignKey(Info, on_delete=models.CASCADE) prop = models.ForeignKey(Property, on_delete=models.CASCADE) Views @login_required @group_required('Telemetry Reports') def create_property_name(request): property_name_form = PropertyForm(data=request.POST or None, files=request.FILES or None) if request.method == 'POST': if property_name_form.is_valid(): object = property_name_form.save(commit=False) object.save() messages.success(request, f"New property successfully created") return redirect('/telemetry_updates/view_properties') context = { "property_name_form":property_name_form, } return render(request, 'telemetry_updates/create_property_name.html', context) # property info create function @login_required @group_required('Telemetry Reports') def create_property_info(request): info_form = InfoForm(data=request.POST or None, files=request.FILES or None) property_info_form = PropertyInfoForm(data=request.POST or None, files=request.FILES or None) if request.method == 'POST': print("Hello world") if info_form.is_valid() and property_info_form.is_valid(): info = info_form.save(commit=False) info.created_by = request.user info.save() property_info = property_info_form.save(commit=False) property_info.info = info property_info.save() property = property_info.prop property.prop_infos.add(info) property.save() messages.success(request, f"Report successfully added") return redirect('/telemetry_updates/view_properties') context = { "form":info_form, "form2":property_info_form, } return render(request, 'telemetry_updates/create_property_info.html', context) # view list of all properties and property infos @login_required def view_properties(request): object_list = Property.objects.all().order_by('-date_created') context = { 'object_list':object_list, } return render(request, 'telemetry_updates/view_properties.html', context) # function to show detail of property infos @login_required def property_info_detail(request, pk): object = Info.objects.get(id=pk) context = { 'object': object, } return render(request, 'telemetry_updates/property_info_detail.html', context) # used to update existing property infos @login_required @group_required('Telemetry Reports') def update_property_info(request, pk): update = Info.objects.get(id=pk) form = InfoForm(data=request.POST or None, files=request.FILES or None, instance=update) if request.method == 'POST': if form.is_valid() and form.has_changed(): form = form.save(commit=False) form.updated_by = request.user form.save() messages.success(request, f"Property report successfully updated!") return redirect('/telemetry_updates/view_properties') else: messages.success(request, "No changes were made") return redirect('/telemetry_updates/view_properties') context = { 'form':form, } return render(request, 'telemetry_updates/update_property_info.html', context) # used to delete section infos @login_required @group_required('Telemetry Reports') def delete_property_info(request,pk): delete = get_object_or_404(PropertyInfo, id=pk) delete.delete() messages.success(request, f"Property report successfully deleted") return redirect('/telemetry_updates/view_properties') So essentially what I need to do is loop through this list of details and if in any of them there is a true or false value, notify the user on the card.
[ "You can try the following in the nested loop:\n{% for info in object.prop_infos.all %}\n <ul id=\"list\">\n {% if info.winter_mode and info.instln_confirmed %}\n <p>Everything is right</p>\n {% else %}\n <p> something went wrong.</p>\n {% endif %}\n <li>{{ info.date_created }}</li> |\n <li><a href=\"{% url 'telemetry_updates:property_info_detail' info.id %}\">{{info.detail|truncatechars:15 }}</a></li>\n <hr>\n </ul>\n{% endfor %}\n\n" ]
[ 0 ]
[]
[]
[ "bootstrap_5", "django", "python" ]
stackoverflow_0074548924_bootstrap_5_django_python.txt
Q: How to search and replace a specific value in a line in Python I have a text file that has some values as follows: matlab.file.here.we.go{1} = 50 matlab.file.here.sxd.go{1} = 50 matlab.file.here.asd.go{1} = 50 I want the code to look for "matlab.file.here.sxd.go{1}" and replace the value assigned to it from 50 to 1. But I want it to be dynamic (i.e., later I will have over 20 values to change and I don't want to search for that specific phrase). I'm new to python so I don't have much information in order to search for it online. Thanks I tried the following file_path = r'test\testfile.txt' file_param = 'matlab.file.here.we.go{1}' changing = 'matlab.file.here.we.go{1} = 1' with open(file_path, 'r') as f: content = f.readlines() content = content.replace(file_param , changing) with open(file_path, 'w') as f: f.write(content) but it didn't achieve what I wanted A: You can split on the equal sign. You can read and write files at the same time. import os file_path = r'test\testfile.txt' file_path_temp = r'test\testfile.txt.TEMP' new_value = 50 changing = 'matlab.file.here.we.go{1} = 1' with open(file_path, 'r') as rf, open(file_path_temp, 'w') as wf: for line in rf: if changing in line: temp = line.split(' = ') temp[1] = new_value line = ' = '.join(temp) wf.write(line) os.remove(file_path) os.rename(file_path_temp, file_path)
How to search and replace a specific value in a line in Python
I have a text file that has some values as follows: matlab.file.here.we.go{1} = 50 matlab.file.here.sxd.go{1} = 50 matlab.file.here.asd.go{1} = 50 I want the code to look for "matlab.file.here.sxd.go{1}" and replace the value assigned to it from 50 to 1. But I want it to be dynamic (i.e., later I will have over 20 values to change and I don't want to search for that specific phrase). I'm new to python so I don't have much information in order to search for it online. Thanks I tried the following file_path = r'test\testfile.txt' file_param = 'matlab.file.here.we.go{1}' changing = 'matlab.file.here.we.go{1} = 1' with open(file_path, 'r') as f: content = f.readlines() content = content.replace(file_param , changing) with open(file_path, 'w') as f: f.write(content) but it didn't achieve what I wanted
[ "You can split on the equal sign. You can read and write files at the same time.\nimport os\nfile_path = r'test\\testfile.txt'\nfile_path_temp = r'test\\testfile.txt.TEMP'\nnew_value = 50\nchanging = 'matlab.file.here.we.go{1} = 1'\nwith open(file_path, 'r') as rf, open(file_path_temp, 'w') as wf:\n for line in rf:\n if changing in line:\n temp = line.split(' = ')\n temp[1] = new_value\n line = ' = '.join(temp)\n wf.write(line)\n\nos.remove(file_path)\nos.rename(file_path_temp, file_path)\n\n" ]
[ 1 ]
[]
[]
[ "python", "readline", "text" ]
stackoverflow_0074548827_python_readline_text.txt
Q: Calculating total number of values based on same id in pandas dataframe I have a dataframe that looks like this: api_spec_id commitdates commits Year-Month API Age info_version 84 2014-12-15 110 2014-12 110 6.0.1 84 2014-11-06 33 2014-11 33 6.0.2 84 2014-10-15 110 2014-10 110 6.0.3 84 2014-12-02 110 2014-12 110 6.0.5 84 2014-11-19 33 2014-11 33 7.0.2 api_spec_id is the id for every API in the dataframe, now the same API can have different versions within the same id, as it keeps changing for every commit date. I want to count that for api_spec_id = 84, how many total versions are there, like here there are 5 in total. My desired output is : api_spec_id commitdates commits Year-Month API Age info_version Total_versions 84 2014-12-15 110 2014-12 110 6.0.1 5 84 2014-11-06 33 2014-11 33 6.0.2 5 84 2014-10-15 110 2014-10 110 6.0.3. 5 84 2014-12-02 110 2014-12 110 6.0.5. 5 84 2014-11-19 33 2014-11 33 7.0.2. 5 I tried using value_counts.(), sum() and few other solutions on similar questions found here on stack, however none of the solutions gave me the correct numbers which I want to achieve. What would be the best way to go about this? Any guidance will be really helpful. A: You can use pd.groupby and nunique for this: df['Total_versions'] = df.groupby('api_spec_id').info_version.transform('nunique') It counts the number of unique values in the column 'info_version' for each 'api_spec_id'. Output: api_spec_id commitdates commits Year-Month API_Age info_version Total_versions 0 84 2014-12-15 110 2014-12 110 6.0.1 5 1 84 2014-11-06 33 2014-11 33 6.0.2 5 2 84 2014-10-15 110 2014-10 110 6.0.3 5 3 84 2014-12-02 110 2014-12 110 6.0.5 5 4 84 2014-11-19 33 2014-11 33 7.0.2 5
Calculating total number of values based on same id in pandas dataframe
I have a dataframe that looks like this: api_spec_id commitdates commits Year-Month API Age info_version 84 2014-12-15 110 2014-12 110 6.0.1 84 2014-11-06 33 2014-11 33 6.0.2 84 2014-10-15 110 2014-10 110 6.0.3 84 2014-12-02 110 2014-12 110 6.0.5 84 2014-11-19 33 2014-11 33 7.0.2 api_spec_id is the id for every API in the dataframe, now the same API can have different versions within the same id, as it keeps changing for every commit date. I want to count that for api_spec_id = 84, how many total versions are there, like here there are 5 in total. My desired output is : api_spec_id commitdates commits Year-Month API Age info_version Total_versions 84 2014-12-15 110 2014-12 110 6.0.1 5 84 2014-11-06 33 2014-11 33 6.0.2 5 84 2014-10-15 110 2014-10 110 6.0.3. 5 84 2014-12-02 110 2014-12 110 6.0.5. 5 84 2014-11-19 33 2014-11 33 7.0.2. 5 I tried using value_counts.(), sum() and few other solutions on similar questions found here on stack, however none of the solutions gave me the correct numbers which I want to achieve. What would be the best way to go about this? Any guidance will be really helpful.
[ "You can use pd.groupby and nunique for this:\ndf['Total_versions'] = df.groupby('api_spec_id').info_version.transform('nunique')\n\nIt counts the number of unique values in the column 'info_version' for each 'api_spec_id'.\nOutput:\napi_spec_id commitdates commits Year-Month API_Age info_version Total_versions\n0 84 2014-12-15 110 2014-12 110 6.0.1 5\n1 84 2014-11-06 33 2014-11 33 6.0.2 5\n2 84 2014-10-15 110 2014-10 110 6.0.3 5\n3 84 2014-12-02 110 2014-12 110 6.0.5 5\n4 84 2014-11-19 33 2014-11 33 7.0.2 5\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074549239_pandas_python.txt
Q: Creating relations between countries in neo4j using python I need help with creating relations between countries in neo4j using python. I have a code, but in neo4j browser it doesn't create relations. from neo4j import GraphDatabase driver = GraphDatabase.driver("neo4j://localhost:7687", auth=("neo4j", "test")) def create_country(tx, name,continent,population_mln,govrm_system,bcountry): tx.run("CREATE (a:Country {name: $name,continent: $continent,population_mln: $population_mln,govrm_system:$govrm_system,bcountry: $bcountry})", name=name,continent=continent,population_mln=population_mln,govrm_system=govrm_system,bcountry=bcountry) with driver.session() as session: session.execute_write(create_country, "russia","Asia",143,"terrorist state",["Kazakhstan","Lithuania","Finland","China","Japan"]) session.execute_write(create_country, "India","Asia",1393,"Parliamentary Republic","China") session.execute_write(create_country, "China","Asia",1412,"One-party state",["India","russia","Philipines","Japan"]) session.execute_write(create_country, "Poland","Europe",37,"Parliamentary Republic",["Lithuania","Germany","Czechia"]) session.execute_write(create_country, "Kazakhstan","Asia",19,"Presidential system Republic","russia") session.execute_write(create_country, "Lithuania","Europe",2.7,"Parliamentary Republic",["russia","Poland"]) session.execute_write(create_country, "Finland","Europe",5.5,"Parliamentary Republic","russia") session.execute_write(create_country, "Philipines","Asia",111,"Parliamentary Republic",["Japan","China"]) session.execute_write(create_country, "Japan","Asia",125,"Constitutional Monarchy",["Philipines","China","russia"]) session.execute_write(create_country, "Germany","Europoe",83,"Parliamentary Republic",["Czechia","Austria","Poland"]) session.execute_write(create_country, "Czechia","Europoe",10,"Parliamentary Republic",["Austria","Poland","Germany"]) session.execute_write(create_country, "Austria","Europoe",9,"Parliamentary Republic",["Czechia","Germany"]) def create_bordering_country(tx, name, bcountry): tx.run("FOREACH (n IN a.bcountry | MERGE (bcountry:Country {name: n}) MERGE (a)-[:HAS_BORDER_WITH]-(bcountry))") It should look like this: What I get in neo4j: I also tried to do like this, but then I get duplicates of countries: def create_bordering_country(tx, name, bcountry): tx.run("MATCH (a:Country) WHERE a.name = $name " "MERGE (a)-[:HAS_BORDER_WITH]-(:Country {name: $bcountry}) RETURN DISTINCT a.name", name=name, bcountry=bcountry) session.execute_write(create_bordering_country, "russia", "China") session.execute_write(create_bordering_country, "India", "China") session.execute_write(create_bordering_country, "russia", "Kazakhstan") session.execute_write(create_bordering_country, "russia", "Lithuania") session.execute_write(create_bordering_country, "russia", "Finland") session.execute_write(create_bordering_country, "Poland", "Lithuania") session.execute_write(create_bordering_country, "China", "Japan") session.execute_write(create_bordering_country, "Russia", "Japan") session.execute_write(create_bordering_country, "Philipines", "Japan") session.execute_write(create_bordering_country, "Philipines", "China") session.execute_write(create_bordering_country, "Germany", "Poland") session.execute_write(create_bordering_country, "Austria", "Poland") session.execute_write(create_bordering_country, "Czechia", "Poland") session.execute_write(create_bordering_country, "Czechia", "Austria") session.execute_write(create_bordering_country, "Czechia", "Germany") session.execute_write(create_bordering_country, "Germany", "Austria") A: You are getting duplicates because merge will create more bcountry even if it exists already. Please use below new query. Function: create_bordering_country Old code: MATCH (a:Country) WHERE a.name = $name MERGE (a)-[:HAS_BORDER_WITH]-(:Country {name: $bcountry}) RETURN DISTINCT a.name New code: MERGE (a:Country) WHERE a.name = $name MERGE (b:Country) WHERE b.name = $bcountry MERGE (a)-[:HAS_BORDER_WITH]-(b) RETURN a.name A: In your first attempt, it doesn't look like you ever called the create_bordering_country function. I would recommend this approach: import pandas as pd from neo4j import GraphDatabase driver = GraphDatabase.driver("neo4j://localhost:7687", auth=("neo4j", "test")) country_df = pd.DataFrame([ ["russia","Asia",143,"terrorist state",["Kazakhstan","Lithuania","Finland","China","Japan"]], ["India","Asia",1393,"Parliamentary Republic",["China"]], ["China","Asia",1412,"One-party state", ["India","russia","Philipines","Japan"]], ["Poland","Europe",37,"Parliamentary Republic",["Lithuania","Germany","Czechia"]], ["Kazakhstan","Asia",19,"Presidential system Republic", ["russia"]], ["Lithuania","Europe",2.7,"Parliamentary Republic",["russia","Poland"]], ["Finland","Europe",5.5,"Parliamentary Republic",["russia"]], ["Philipines","Asia",111,"Parliamentary Republic",["Japan","China"]], ["Japan","Asia",125,"Constitutional Monarchy",["Philipines","China","russia"]], ["Germany","Europoe",83,"Parliamentary Republic",["Czechia","Austria","Poland"]], ["Czechia","Europoe",10,"Parliamentary Republic",["Austria","Poland","Germany"]], ["Austria","Europoe",9,"Parliamentary Republic",["Czechia","Germany"]]], columns=['name', 'continent', 'populationMillion', 'governmentSystem', 'neighboringCountries']) node_dicts = country_df[['name', 'continent', 'populationMillion', 'governmentSystem']].to_dict("records") rel_dicts = country_df[['name', 'neighboringCountries']].to_dict("records") def create_countries(tx, node_dicts): result = tx.run("""UNWIND $nodeDicts as nodeDict MERGE (c:Country {name: nodeDict['name']}) SET c.continent = nodeDict['continent'] , c.populationMillion = nodeDict['populationMillion'], c.governmentSystem = nodeDict['governmentSystem']""", {"nodeDicts": node_dicts}) summary = result.consume() return summary.counters def create_neighbor_relationships(tx, rel_dicts): result = tx.run("""UNWIND $relDicts as relDict MATCH (c:Country {name: relDict['name']}) UNWIND relDict['neighboringCountries'] as neighbor MATCH (n:Country {name: neighbor}) MERGE (c)-[:HAS_BORDER_WITH]->(n)""", {"relDicts": rel_dicts}) summary = result.consume() return summary.counters with driver.session() as session: node_results = session.write_transaction(create_countries, node_dicts) print(node_results) rel_results = session.write_transaction(create_neighbor_relationships, rel_dicts) print(rel_results) I would also recommend creating an index on the name property for the Country nodes.
Creating relations between countries in neo4j using python
I need help with creating relations between countries in neo4j using python. I have a code, but in neo4j browser it doesn't create relations. from neo4j import GraphDatabase driver = GraphDatabase.driver("neo4j://localhost:7687", auth=("neo4j", "test")) def create_country(tx, name,continent,population_mln,govrm_system,bcountry): tx.run("CREATE (a:Country {name: $name,continent: $continent,population_mln: $population_mln,govrm_system:$govrm_system,bcountry: $bcountry})", name=name,continent=continent,population_mln=population_mln,govrm_system=govrm_system,bcountry=bcountry) with driver.session() as session: session.execute_write(create_country, "russia","Asia",143,"terrorist state",["Kazakhstan","Lithuania","Finland","China","Japan"]) session.execute_write(create_country, "India","Asia",1393,"Parliamentary Republic","China") session.execute_write(create_country, "China","Asia",1412,"One-party state",["India","russia","Philipines","Japan"]) session.execute_write(create_country, "Poland","Europe",37,"Parliamentary Republic",["Lithuania","Germany","Czechia"]) session.execute_write(create_country, "Kazakhstan","Asia",19,"Presidential system Republic","russia") session.execute_write(create_country, "Lithuania","Europe",2.7,"Parliamentary Republic",["russia","Poland"]) session.execute_write(create_country, "Finland","Europe",5.5,"Parliamentary Republic","russia") session.execute_write(create_country, "Philipines","Asia",111,"Parliamentary Republic",["Japan","China"]) session.execute_write(create_country, "Japan","Asia",125,"Constitutional Monarchy",["Philipines","China","russia"]) session.execute_write(create_country, "Germany","Europoe",83,"Parliamentary Republic",["Czechia","Austria","Poland"]) session.execute_write(create_country, "Czechia","Europoe",10,"Parliamentary Republic",["Austria","Poland","Germany"]) session.execute_write(create_country, "Austria","Europoe",9,"Parliamentary Republic",["Czechia","Germany"]) def create_bordering_country(tx, name, bcountry): tx.run("FOREACH (n IN a.bcountry | MERGE (bcountry:Country {name: n}) MERGE (a)-[:HAS_BORDER_WITH]-(bcountry))") It should look like this: What I get in neo4j: I also tried to do like this, but then I get duplicates of countries: def create_bordering_country(tx, name, bcountry): tx.run("MATCH (a:Country) WHERE a.name = $name " "MERGE (a)-[:HAS_BORDER_WITH]-(:Country {name: $bcountry}) RETURN DISTINCT a.name", name=name, bcountry=bcountry) session.execute_write(create_bordering_country, "russia", "China") session.execute_write(create_bordering_country, "India", "China") session.execute_write(create_bordering_country, "russia", "Kazakhstan") session.execute_write(create_bordering_country, "russia", "Lithuania") session.execute_write(create_bordering_country, "russia", "Finland") session.execute_write(create_bordering_country, "Poland", "Lithuania") session.execute_write(create_bordering_country, "China", "Japan") session.execute_write(create_bordering_country, "Russia", "Japan") session.execute_write(create_bordering_country, "Philipines", "Japan") session.execute_write(create_bordering_country, "Philipines", "China") session.execute_write(create_bordering_country, "Germany", "Poland") session.execute_write(create_bordering_country, "Austria", "Poland") session.execute_write(create_bordering_country, "Czechia", "Poland") session.execute_write(create_bordering_country, "Czechia", "Austria") session.execute_write(create_bordering_country, "Czechia", "Germany") session.execute_write(create_bordering_country, "Germany", "Austria")
[ "You are getting duplicates because merge will create more bcountry even if it exists already. Please use below new query.\nFunction: create_bordering_country\nOld code:\n MATCH (a:Country) WHERE a.name = $name \n MERGE (a)-[:HAS_BORDER_WITH]-(:Country {name: $bcountry}) \n RETURN DISTINCT a.name\n\nNew code:\n MERGE (a:Country) WHERE a.name = $name \n MERGE (b:Country) WHERE b.name = $bcountry \n MERGE (a)-[:HAS_BORDER_WITH]-(b) \n RETURN a.name\n\n", "In your first attempt, it doesn't look like you ever called the create_bordering_country function. I would recommend this approach:\nimport pandas as pd\nfrom neo4j import GraphDatabase\ndriver = GraphDatabase.driver(\"neo4j://localhost:7687\",\n auth=(\"neo4j\", \"test\"))\n\ncountry_df = pd.DataFrame([\n [\"russia\",\"Asia\",143,\"terrorist state\",[\"Kazakhstan\",\"Lithuania\",\"Finland\",\"China\",\"Japan\"]],\n [\"India\",\"Asia\",1393,\"Parliamentary Republic\",[\"China\"]],\n [\"China\",\"Asia\",1412,\"One-party state\", [\"India\",\"russia\",\"Philipines\",\"Japan\"]],\n [\"Poland\",\"Europe\",37,\"Parliamentary Republic\",[\"Lithuania\",\"Germany\",\"Czechia\"]],\n [\"Kazakhstan\",\"Asia\",19,\"Presidential system Republic\", [\"russia\"]],\n [\"Lithuania\",\"Europe\",2.7,\"Parliamentary Republic\",[\"russia\",\"Poland\"]],\n [\"Finland\",\"Europe\",5.5,\"Parliamentary Republic\",[\"russia\"]],\n [\"Philipines\",\"Asia\",111,\"Parliamentary Republic\",[\"Japan\",\"China\"]],\n [\"Japan\",\"Asia\",125,\"Constitutional Monarchy\",[\"Philipines\",\"China\",\"russia\"]],\n [\"Germany\",\"Europoe\",83,\"Parliamentary Republic\",[\"Czechia\",\"Austria\",\"Poland\"]],\n [\"Czechia\",\"Europoe\",10,\"Parliamentary Republic\",[\"Austria\",\"Poland\",\"Germany\"]],\n [\"Austria\",\"Europoe\",9,\"Parliamentary Republic\",[\"Czechia\",\"Germany\"]]], \n columns=['name', 'continent', 'populationMillion', 'governmentSystem', 'neighboringCountries'])\n\nnode_dicts = country_df[['name', 'continent', 'populationMillion', 'governmentSystem']].to_dict(\"records\")\nrel_dicts = country_df[['name', 'neighboringCountries']].to_dict(\"records\")\n\ndef create_countries(tx, node_dicts):\n result = tx.run(\"\"\"UNWIND $nodeDicts as nodeDict\n MERGE (c:Country {name: nodeDict['name']})\n SET c.continent = nodeDict['continent'] ,\n c.populationMillion = nodeDict['populationMillion'],\n c.governmentSystem = nodeDict['governmentSystem']\"\"\",\n {\"nodeDicts\": node_dicts})\n summary = result.consume()\n return summary.counters\n\ndef create_neighbor_relationships(tx, rel_dicts):\n result = tx.run(\"\"\"UNWIND $relDicts as relDict\n MATCH (c:Country {name: relDict['name']})\n UNWIND relDict['neighboringCountries'] as neighbor\n MATCH (n:Country {name: neighbor})\n MERGE (c)-[:HAS_BORDER_WITH]->(n)\"\"\",\n {\"relDicts\": rel_dicts})\n summary = result.consume()\n return summary.counters\n\nwith driver.session() as session:\n node_results = session.write_transaction(create_countries, node_dicts)\n print(node_results)\n rel_results = session.write_transaction(create_neighbor_relationships, rel_dicts)\n print(rel_results)\n\nI would also recommend creating an index on the name property for the Country nodes.\n" ]
[ 1, 0 ]
[]
[]
[ "foreach", "neo4j", "python", "relation" ]
stackoverflow_0074537662_foreach_neo4j_python_relation.txt
Q: Split the single column to 4 different separate columns in Dataframe I just need need to split a single column of dataframe to 4 different columns. I tried few steps but didn't worked. DATA1: Dump 12525 2 153 89-8 Winch 24798 1 147 65-4 Gear 65116 4 Screw 46456 1 Rowing 46563 5 Nut Expected1: Item Qty Part_no Description 12525 2 153 89-8 Winch 24798 1 147 65-4 Gear 65116 4 Screw 46456 1 Rowing 46563 5 Nut DATA2: Dump 12525 2 153 89-8 Winch Gear 24798 1 147 65-4 Gear nuts 65116 X Screw bolts 46456 1 Rowing rings 46563 X Nut Expected2: Item Qty Part_no Description 12525 2 153 89-8 Winch Gear 24798 1 147 65-4 Gear nuts 65116 X Screw bolts 46456 1 Rowing rings 46563 X Nut I tried the below code data_df[['Item','Qty','Part_no','Description']] = data_df["Dump"].str.split(" ", 3, expand=True) and got the output like Item Qty Part_no Description 12525 2 153 89-8 Winch 24798 1 147 65-4 Gear 65116 4 Screw 46456 1 Rowing 46563 5 Nut Also I tried with this code but not got the expected output: data_df[['Item','Qty','Part_no','Description']] = data_df['Dump'].str.extract(r'(\d+)\s+(\S+)\s+(\d*)\s*(.+)$') Any suggestions, how can i fix this??? Similar to this question : Split the single column to 4 different columns in Dataframe A: You could match the data format of the Part_no column in a capture group and make the data in that group optional to keep 4 columns. (\d+)\s+(\S+)\s+((?:\d+\s+\d+-\d+)?\s*)(.+)$ Regex demo Example with named capture groups and str.extractall import pandas as pd pattern = r'(?m)(?P<Item>\d+)\s+(?P<Qty>\S+)\s+(?P<Part_no>(?:\d+\s+\d+-\d+)?\s*)(?P<Description>.+)$' items = [("12525 2 153 89-8 Winch Gear\n" "24798 1 147 65-4 Gear nuts\n" "65116 X Screw bolts\n" "46456 1 Rowing rings\n" "46563 X Nut ")] data_df = pd.DataFrame(items, columns=["Dump"]) res = data_df['Dump']\ .str\ .extractall(pattern)\ .fillna('') print(res) Output Item Qty Part_no Description match 0 0 12525 2 153 89-8 Winch Gear 1 24798 1 147 65-4 Gear nuts 2 65116 X Screw bolts 3 46456 1 Rowing rings 4 46563 X Nut
Split the single column to 4 different separate columns in Dataframe
I just need need to split a single column of dataframe to 4 different columns. I tried few steps but didn't worked. DATA1: Dump 12525 2 153 89-8 Winch 24798 1 147 65-4 Gear 65116 4 Screw 46456 1 Rowing 46563 5 Nut Expected1: Item Qty Part_no Description 12525 2 153 89-8 Winch 24798 1 147 65-4 Gear 65116 4 Screw 46456 1 Rowing 46563 5 Nut DATA2: Dump 12525 2 153 89-8 Winch Gear 24798 1 147 65-4 Gear nuts 65116 X Screw bolts 46456 1 Rowing rings 46563 X Nut Expected2: Item Qty Part_no Description 12525 2 153 89-8 Winch Gear 24798 1 147 65-4 Gear nuts 65116 X Screw bolts 46456 1 Rowing rings 46563 X Nut I tried the below code data_df[['Item','Qty','Part_no','Description']] = data_df["Dump"].str.split(" ", 3, expand=True) and got the output like Item Qty Part_no Description 12525 2 153 89-8 Winch 24798 1 147 65-4 Gear 65116 4 Screw 46456 1 Rowing 46563 5 Nut Also I tried with this code but not got the expected output: data_df[['Item','Qty','Part_no','Description']] = data_df['Dump'].str.extract(r'(\d+)\s+(\S+)\s+(\d*)\s*(.+)$') Any suggestions, how can i fix this??? Similar to this question : Split the single column to 4 different columns in Dataframe
[ "You could match the data format of the Part_no column in a capture group and make the data in that group optional to keep 4 columns.\n(\\d+)\\s+(\\S+)\\s+((?:\\d+\\s+\\d+-\\d+)?\\s*)(.+)$\n\nRegex demo\nExample with named capture groups and str.extractall\nimport pandas as pd\n\npattern = r'(?m)(?P<Item>\\d+)\\s+(?P<Qty>\\S+)\\s+(?P<Part_no>(?:\\d+\\s+\\d+-\\d+)?\\s*)(?P<Description>.+)$'\nitems = [(\"12525 2 153 89-8 Winch Gear\\n\"\n \"24798 1 147 65-4 Gear nuts\\n\"\n \"65116 X Screw bolts\\n\"\n \"46456 1 Rowing rings\\n\"\n \"46563 X Nut \")]\n\ndata_df = pd.DataFrame(items, columns=[\"Dump\"])\nres = data_df['Dump']\\\n .str\\\n .extractall(pattern)\\\n .fillna('')\n\nprint(res)\n\nOutput\n Item Qty Part_no Description\n match \n0 0 12525 2 153 89-8 Winch Gear\n 1 24798 1 147 65-4 Gear nuts\n 2 65116 X Screw bolts\n 3 46456 1 Rowing rings\n 4 46563 X Nut \n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "regex" ]
stackoverflow_0074549107_dataframe_pandas_python_regex.txt
Q: How to return a list with a certain parameter from an API? I need to return a list with the the title ("titulo") of the news that appear in this api: https://www.publico.pt/api/list/ultimas I tried this but it only returns the title of the title (titulo) of the first new and not all the titles. import requests def get_news(): url = "https://www.publico.pt/api/list/ultimas" response = requests.get(url) data = response.json() for news in data: titulo = [news["titulo"]] return titulo print(get_news()) A: i think this might be what you actually want to do: url = "https://www.publico.pt/api/list/ultimas" response = requests.get(url) data = response.json() titulo = [] for news in data: titulo.append(news["titulo"]) return titulo this puts all the data into a list and returns the list.
How to return a list with a certain parameter from an API?
I need to return a list with the the title ("titulo") of the news that appear in this api: https://www.publico.pt/api/list/ultimas I tried this but it only returns the title of the title (titulo) of the first new and not all the titles. import requests def get_news(): url = "https://www.publico.pt/api/list/ultimas" response = requests.get(url) data = response.json() for news in data: titulo = [news["titulo"]] return titulo print(get_news())
[ "i think this might be what you actually want to do:\nurl = \"https://www.publico.pt/api/list/ultimas\"\n\nresponse = requests.get(url)\ndata = response.json()\ntitulo = []\nfor news in data: \n titulo.append(news[\"titulo\"]) \n \nreturn titulo\n\nthis puts all the data into a list and returns the list.\n" ]
[ 0 ]
[]
[]
[ "api", "list", "python" ]
stackoverflow_0074549288_api_list_python.txt
Q: Permutations between 2 lists From 2 list i would like to know an optimal way in Python to do a sort of "indexed permutation". This is how this would look like : input : list2 = [3,4,5] list1 = [0,1,2] output [[0,1,2], [0,1,5], [0,4,2], [3,1,2], [3,4,5], [3,4,2], [3,1,5], [0,4,5], ] So each element of the lists remains in the same index. A: You basically want two variables: list_to_pick, which can vary in range(number_of_lists), and index_to_swap which can vary in the range(-1, len(list1)). Then, you want the product of these two ranges to decide which list to pick, and which item to swap. When index_to_swap is -1, we won't swap any items import itertools source = [list1, list2] result = [] for list_to_pick, index_to_swap in itertools.product(range(len(source)), range(-1, len(source[0])): # Make a copy so we don't mess up the original list selected_list = source[list_to_pick].copy() # There are only two lists, so the other list is at index abs(list_to_pick - 1) other_list = source[abs(list_to_pick - 1)] # We swap only if index_to_swap >= 0 if index_to_swap >= 0: selected_list[index_to_swap] = other_list[index_to_swap] result.append(selected_list) Which gives: [[0, 1, 2], [3, 1, 2], [0, 4, 2], [0, 1, 5], [3, 4, 5], [0, 4, 5], [3, 1, 5], [3, 4, 2]] The order is not the same as your required list, but all the "permutations" are there. If you want the same order as in your question, you will have to define the second argument to itertools.product as: swap_indices = [-1] + list(range(len(source[0])-1, -2, -1))
Permutations between 2 lists
From 2 list i would like to know an optimal way in Python to do a sort of "indexed permutation". This is how this would look like : input : list2 = [3,4,5] list1 = [0,1,2] output [[0,1,2], [0,1,5], [0,4,2], [3,1,2], [3,4,5], [3,4,2], [3,1,5], [0,4,5], ] So each element of the lists remains in the same index.
[ "You basically want two variables: list_to_pick, which can vary in range(number_of_lists), and index_to_swap which can vary in the range(-1, len(list1)). Then, you want the product of these two ranges to decide which list to pick, and which item to swap. When index_to_swap is -1, we won't swap any items\nimport itertools\n\nsource = [list1, list2]\n\nresult = []\n\nfor list_to_pick, index_to_swap in itertools.product(range(len(source)), range(-1, len(source[0])):\n # Make a copy so we don't mess up the original list\n selected_list = source[list_to_pick].copy() \n\n # There are only two lists, so the other list is at index abs(list_to_pick - 1)\n other_list = source[abs(list_to_pick - 1)]\n\n # We swap only if index_to_swap >= 0\n if index_to_swap >= 0:\n selected_list[index_to_swap] = other_list[index_to_swap] \n\n result.append(selected_list)\n\nWhich gives:\n[[0, 1, 2],\n [3, 1, 2],\n [0, 4, 2],\n [0, 1, 5],\n [3, 4, 5],\n [0, 4, 5],\n [3, 1, 5],\n [3, 4, 2]]\n\nThe order is not the same as your required list, but all the \"permutations\" are there. If you want the same order as in your question, you will have to define the second argument to itertools.product as:\nswap_indices = [-1] + list(range(len(source[0])-1, -2, -1))\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_itertools" ]
stackoverflow_0074549211_python_python_itertools.txt
Q: how to change the position of dropdown using tkinter im trying to make a simple dropdown gui,but i need some help on how to position the dropdown menu , the full code is : import tkinter as tk from tkinter import * root=tk.Tk() canvas1 = tk.Canvas(root, width = 400, height = 300) canvas1.pack() username = tk.Entry(root) canvas1.create_window(200,140, window=username) canvas1.create_text(100,140,fill="darkblue",text="username") password = tk.Entry(root) canvas1.create_window(200,180,window=password) canvas1.create_text(100,180,fill="darkblue",text="password") variable = StringVar(root) variable.set("Facebook") w=OptionMenu(root , variable, "Facebook","Twitter","Spotify","Swiggy") w.pack() button1= tk.Button(text='Go') canvas1.create_window(250,250, window=button1) root.mainloop() the dropdown menu was obtained by using the OptionMenu but im unable to change its position, i need help with that code for just the OptionMenu: from Tkinter import * master = Tk() variable = StringVar(master) variable.set("one") # default value w = OptionMenu(master, variable, "one", "two", "three") w.pack() mainloop() A: You just need to add this statement canvas1.create_window(250,250, window=w) at the end of this code: from Tkinter import * master = Tk() variable = StringVar(master) variable.set("one") # default value w = OptionMenu(master, variable, "one", "two", "three") w.pack() A: You can change position to anywhere to suit you by using canvas1.create_window. In line 23, replace pack() with canvas1.create_window. Try this: import tkinter as tk root=tk.Tk() canvas1 = tk.Canvas(root, width=400, height=300) canvas1.pack() username = tk.Entry(root) canvas1.create_window(200, 140, window=username) canvas1.create_text(100, 140, fill="darkblue", text="username") password = tk.Entry(root) canvas1.create_window(200, 180, window=password) canvas1.create_text(100, 180, fill="darkblue", text="password") variable = tk.StringVar(root) variable.set("Facebook") w = tk.OptionMenu(root, variable, "Facebook","Twitter","Spotify","Swiggy") canvas1.create_window(150, 250, window=w) button1= tk.Button(text='Go') canvas1.create_window(250, 250, window=button1) root.mainloop() Result:
how to change the position of dropdown using tkinter
im trying to make a simple dropdown gui,but i need some help on how to position the dropdown menu , the full code is : import tkinter as tk from tkinter import * root=tk.Tk() canvas1 = tk.Canvas(root, width = 400, height = 300) canvas1.pack() username = tk.Entry(root) canvas1.create_window(200,140, window=username) canvas1.create_text(100,140,fill="darkblue",text="username") password = tk.Entry(root) canvas1.create_window(200,180,window=password) canvas1.create_text(100,180,fill="darkblue",text="password") variable = StringVar(root) variable.set("Facebook") w=OptionMenu(root , variable, "Facebook","Twitter","Spotify","Swiggy") w.pack() button1= tk.Button(text='Go') canvas1.create_window(250,250, window=button1) root.mainloop() the dropdown menu was obtained by using the OptionMenu but im unable to change its position, i need help with that code for just the OptionMenu: from Tkinter import * master = Tk() variable = StringVar(master) variable.set("one") # default value w = OptionMenu(master, variable, "one", "two", "three") w.pack() mainloop()
[ "You just need to add this statement canvas1.create_window(250,250, window=w) at the end of this code:\nfrom Tkinter import *\n\nmaster = Tk()\n\nvariable = StringVar(master)\nvariable.set(\"one\") # default value\n\nw = OptionMenu(master, variable, \"one\", \"two\", \"three\")\nw.pack()\n\n", "You can change position to anywhere to suit you by using canvas1.create_window.\nIn line 23, replace pack() with canvas1.create_window.\nTry this:\nimport tkinter as tk\n\n\nroot=tk.Tk()\n\ncanvas1 = tk.Canvas(root, width=400, height=300)\ncanvas1.pack()\n\nusername = tk.Entry(root)\ncanvas1.create_window(200, 140, window=username)\ncanvas1.create_text(100, 140, fill=\"darkblue\", text=\"username\")\n\npassword = tk.Entry(root)\ncanvas1.create_window(200, 180, window=password)\ncanvas1.create_text(100, 180, fill=\"darkblue\", text=\"password\")\n\nvariable = tk.StringVar(root)\nvariable.set(\"Facebook\")\n\nw = tk.OptionMenu(root, variable, \"Facebook\",\"Twitter\",\"Spotify\",\"Swiggy\")\ncanvas1.create_window(150, 250, window=w)\n\nbutton1= tk.Button(text='Go')\ncanvas1.create_window(250, 250, window=button1)\n\nroot.mainloop()\n\nResult:\n\n" ]
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0058959423_python_python_3.x_tkinter.txt
Q: Python: how to form the correct list This is my data looks like my_list = [('Australia',), ('Europe',)] I need to remove the comma "," after every element. new_list = [('Australia'), ('Europe')] I can achieve this using a loop and extracting one element at a time and replacing it. Is there a better way to achieve the same. Thank you A: That comma, indicates that you have a tuple. If you want to not have that comma, you can change tuples to lists: new_list = [list(country) for country in my_list] It gives You: [['Australia'], ['Europe']] A: my_list = [('Australia',), ('Europe',)] # lambda create a function and returns first value of x # function map takes a function and list # it puts every value of list to function country = list(map(lambda x: x[0], my_list)) print(country)
Python: how to form the correct list
This is my data looks like my_list = [('Australia',), ('Europe',)] I need to remove the comma "," after every element. new_list = [('Australia'), ('Europe')] I can achieve this using a loop and extracting one element at a time and replacing it. Is there a better way to achieve the same. Thank you
[ "That comma, indicates that you have a tuple. If you want to not have that comma, you can change tuples to lists:\nnew_list = [list(country) for country in my_list]\n\nIt gives You:\n[['Australia'], ['Europe']]\n\n", "my_list = [('Australia',), ('Europe',)]\n# lambda create a function and returns first value of x\n# function map takes a function and list\n# it puts every value of list to function \n\ncountry = list(map(lambda x: x[0], my_list))\n\nprint(country)\n\n" ]
[ 0, 0 ]
[]
[]
[ "arrays", "list", "python", "replace", "trim" ]
stackoverflow_0074549120_arrays_list_python_replace_trim.txt
Q: This calculator program does not give an answer it just repeats. How do I fix it? I wrote this simple calculator program to ask for two numbers and then perform a certain action on them like dividing the first by the second etc. I implemented it in a big while loop that is repeated if the user chooses to repeat it after a calculation. However, after the user enters the operation they want to perform the program does not give the answer but asks the user if they want to repeat. What did I do wrong? import random, time valid_operations = ("/", "*", "+", "-") valid = 3 repeat = "y" while repeat == "y": number_1 = input('Enter first number \n') if number_1.isdigit() == True: num_1 = number_1 else: print("that is not a valid integer") exit() number_2 = input('Enter second number \n') if number_2.isdigit() == True: num_2 = number_2 else: print("that is not a valid integer") exit() operation = input("what operation would you like? \nvalid operations include:\n/ - divide\n* - multiply\n+ - add\n- - subtract\n") while valid > 0: if operation in valid_operations: if operation == "/": print(f"Answer = {int(num_1) / int(num_2)}") valid -= 3 elif operation == "*": print(f"Answer = {int(num_1) * int(num_2)}") valid -= 3 elif operation == "+": print(f"Answer = {int(num_1) + int(num_2)}") valid -= 3 elif operation == "-": print(f"Answer = {int(num_1) - int(num_2)}") valid -= 3 else: print(f"that is not a valid operation you have {valid} more attmepts to type a valid operation") valid -= 1 time.sleep(2) want_rep = input("would you like to do another calculation? y/n\n") if want_rep == "y": repeat = "y" elif want_rep == "n": repeat = "n" else: print("that is not a valid response, please choose either yes - y or no - n") exit() A: Problem lies in the valid variable. You define it as 3 before the first iteration. Then, inside the second while loop, it is reduced to 0 by valid -= 3 And you never restore the starting value. So, the program comes back to the operation input, reads the loop condition: while valid > 0: And omits it, as valid equals 0.
This calculator program does not give an answer it just repeats. How do I fix it?
I wrote this simple calculator program to ask for two numbers and then perform a certain action on them like dividing the first by the second etc. I implemented it in a big while loop that is repeated if the user chooses to repeat it after a calculation. However, after the user enters the operation they want to perform the program does not give the answer but asks the user if they want to repeat. What did I do wrong? import random, time valid_operations = ("/", "*", "+", "-") valid = 3 repeat = "y" while repeat == "y": number_1 = input('Enter first number \n') if number_1.isdigit() == True: num_1 = number_1 else: print("that is not a valid integer") exit() number_2 = input('Enter second number \n') if number_2.isdigit() == True: num_2 = number_2 else: print("that is not a valid integer") exit() operation = input("what operation would you like? \nvalid operations include:\n/ - divide\n* - multiply\n+ - add\n- - subtract\n") while valid > 0: if operation in valid_operations: if operation == "/": print(f"Answer = {int(num_1) / int(num_2)}") valid -= 3 elif operation == "*": print(f"Answer = {int(num_1) * int(num_2)}") valid -= 3 elif operation == "+": print(f"Answer = {int(num_1) + int(num_2)}") valid -= 3 elif operation == "-": print(f"Answer = {int(num_1) - int(num_2)}") valid -= 3 else: print(f"that is not a valid operation you have {valid} more attmepts to type a valid operation") valid -= 1 time.sleep(2) want_rep = input("would you like to do another calculation? y/n\n") if want_rep == "y": repeat = "y" elif want_rep == "n": repeat = "n" else: print("that is not a valid response, please choose either yes - y or no - n") exit()
[ "Problem lies in the valid variable.\nYou define it as 3 before the first iteration.\nThen, inside the second while loop, it is reduced to 0 by\nvalid -= 3\nAnd you never restore the starting value. So, the program comes back to the operation input, reads the loop condition:\n while valid > 0:\nAnd omits it, as valid equals 0.\n" ]
[ 0 ]
[]
[]
[ "calculator", "python" ]
stackoverflow_0074397026_calculator_python.txt
Q: Pandas: Incorrect Result when multiplying two columns I am going through the Pandas-Kaggle information here: DataSet https://www.dropbox.com/s/16cwjq5ibtcmzgi/Lookup211.csv?dl=0 Action I want to take I want to combine the two columns. Issue I am getting But for some reason, even simple multiplication is not yielding the correct value. This is what i have wine.points_normal = (pd.to_numeric(wine.points) * pd.to_numeric(wine.price)) As you can see 0.0 * 85 is not equating as 0 Please help. Thank you. wine[['points', 'price']].head().to_dict() yields {'points': {0: 96, 1: 96, 2: 96, 3: 96, 4: 95}, 'price': {0: 235.0, 1: 110.0, 2: 90.0, 3: 65.0, 4: 66.0}} A: I can not reproduce your error, to mee seems fine. Seems like a cliche for IT but try to restar your kernel if you are in Jupyter notebook: with "Restart & Clear Output" + "Restar & Run All" A: I experienced a similar issue and got 'RuntimeWarning: overflow encountered in ushort_scalars' when I ran the problematic entries by themselves. No warning, just wrong results like in your case when I multiplied the entire column. The numbers were not big, 56 times 4576. I 'fixed' the problem by setting the type to integer; df[column1].astype(int)*df[column2].
Pandas: Incorrect Result when multiplying two columns
I am going through the Pandas-Kaggle information here: DataSet https://www.dropbox.com/s/16cwjq5ibtcmzgi/Lookup211.csv?dl=0 Action I want to take I want to combine the two columns. Issue I am getting But for some reason, even simple multiplication is not yielding the correct value. This is what i have wine.points_normal = (pd.to_numeric(wine.points) * pd.to_numeric(wine.price)) As you can see 0.0 * 85 is not equating as 0 Please help. Thank you. wine[['points', 'price']].head().to_dict() yields {'points': {0: 96, 1: 96, 2: 96, 3: 96, 4: 95}, 'price': {0: 235.0, 1: 110.0, 2: 90.0, 3: 65.0, 4: 66.0}}
[ "I can not reproduce your error, to mee seems fine. Seems like a cliche for IT but try to restar your kernel if you are in Jupyter notebook:\nwith \"Restart & Clear Output\" + \"Restar & Run All\"\n\n", "I experienced a similar issue and got 'RuntimeWarning: overflow encountered in ushort_scalars' when I ran the problematic entries by themselves. No warning, just wrong results like in your case when I multiplied the entire column. The numbers were not big, 56 times 4576. I 'fixed' the problem by setting the type to integer; df[column1].astype(int)*df[column2].\n" ]
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0071973393_pandas_python.txt
Q: Does TDengine Python connector support executemany? I'm currently using TDengine and Python to store time-series data. I tried Python connector. conn = taos.connect() conn.execute(“…”) It’s OK. However, the performance is not very good. Does TDengine Python connector support executemany and binding parameters? Or is there another way to improve performance? A: Article on improving the performance of data writing into TDengine. Appears a combination of batch writes and multi-thread parallel writing with certain limits can improve speed but that will depend on your run environment. Before you do anything I'd put some decent profiling in place so you know if you're getting improvements. Edit: Also section from TDengine docs directly related to High Performance data writing.
Does TDengine Python connector support executemany?
I'm currently using TDengine and Python to store time-series data. I tried Python connector. conn = taos.connect() conn.execute(“…”) It’s OK. However, the performance is not very good. Does TDengine Python connector support executemany and binding parameters? Or is there another way to improve performance?
[ "Article on improving the performance of data writing into TDengine.\nAppears a combination of batch writes and multi-thread parallel writing with certain limits can improve speed but that will depend on your run environment.\nBefore you do anything I'd put some decent profiling in place so you know if you're getting improvements.\nEdit: Also section from TDengine docs directly related to High Performance data writing.\n" ]
[ 1 ]
[]
[]
[ "database", "python", "tdengine" ]
stackoverflow_0074549390_database_python_tdengine.txt
Q: find pattern substring using python re I am trying to find all substrings within a multi string in python 3, I want to find all words in between the word 'Colour:': example string: str = """ Colour: Black Colour: Green Colour: Black Colour: Red Colour: Orange Colour: Blue Colour: Green """ I want to get all of the colours into a list like: x = ['Black', 'Green', 'Black', 'Red', 'Orange', 'Blue', 'Green'] I want to do this using Python re Whats the fastest way of doing this with re.search , re.findall, re.finditer or even another method. I've tried doing this as a list comprehension: z = [x.group() for x in re.finditer('Colour:(.*?)Colour:', str)] but it returns an empty list ? any ideas? A: In regex, the dot . does not match new line by default. This mean your program is trying to find something like "Color: blueColor". To overcome this, you can just do something like : colours = re.findall(r'Colour: (.+)', str) Note the use of re.findall to avoid using the list comprehension. Furthermore, if the format won't change, regex is not mandatory and you can just split each line on spaces and get the second part : colours = [line.split()[1] for line in str.splitlines()] A: The lists containing the trailing spaces can be removed and split based on the user-defined variable. In your case, the Colour:. list(filter(None, str.replace("\n", "").replace(" ", "").split("Colour:"))) Result: ['Black', 'Green', 'Black', 'Red', 'Orange', 'Blue', 'Green'] Regard to time constraints: Regex patterns are subjected to taking more time than dealing with strings directly. Adding the image for reference: A: Perhaps you just need a simple one-liner: x = re.findall("Colour: (.*)",str) This worked for your example. (P.S. please don't use builtin symbols like str for variable names.)
find pattern substring using python re
I am trying to find all substrings within a multi string in python 3, I want to find all words in between the word 'Colour:': example string: str = """ Colour: Black Colour: Green Colour: Black Colour: Red Colour: Orange Colour: Blue Colour: Green """ I want to get all of the colours into a list like: x = ['Black', 'Green', 'Black', 'Red', 'Orange', 'Blue', 'Green'] I want to do this using Python re Whats the fastest way of doing this with re.search , re.findall, re.finditer or even another method. I've tried doing this as a list comprehension: z = [x.group() for x in re.finditer('Colour:(.*?)Colour:', str)] but it returns an empty list ? any ideas?
[ "In regex, the dot . does not match new line by default. This mean your program is trying to find something like \"Color: blueColor\".\nTo overcome this, you can just do something like :\ncolours = re.findall(r'Colour: (.+)', str)\n\nNote the use of re.findall to avoid using the list comprehension.\nFurthermore, if the format won't change, regex is not mandatory and you can just split each line on spaces and get the second part :\ncolours = [line.split()[1] for line in str.splitlines()]\n\n", "The lists containing the trailing spaces can be removed and split based on the user-defined variable. In your case, the Colour:.\nlist(filter(None, str.replace(\"\\n\", \"\").replace(\" \", \"\").split(\"Colour:\")))\n\nResult:\n['Black', 'Green', 'Black', 'Red', 'Orange', 'Blue', 'Green']\n\nRegard to time constraints:\nRegex patterns are subjected to taking more time than dealing with strings directly.\nAdding the image for reference:\n\n", "Perhaps you just need a simple one-liner:\nx = re.findall(\"Colour: (.*)\",str)\n\nThis worked for your example.\n(P.S. please don't use builtin symbols like str for variable names.)\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python", "python_3.x", "python_re" ]
stackoverflow_0074549121_python_python_3.x_python_re.txt
Q: How to make a search-engine using tkinter in python? I tried on making a gui-based search engine in python, but for some reason I am facing two errors. I am unable to locate the 'Search' button even though I have added it in code. (I think so) Due to not being able to use the search button I am unable to find any search results even after pressing enter. ###Edit After the help from all of you ,I have made changes to the code but still it is no good.the new code is here : import requests,webbrowser from bs4 import BeautifulSoup from tkinter import * structure=Tk() structure.geometry("1280*1280") structure.title("Cgo Engine") label=Label(structure,text="Cgo Engine",bg="dark grey",fg="Gold",font=("ComicSans",60,"italic")) label.pack(side=TOP) structure.config(background="dark grey") text=StringVar() ### def searches(): data=requests.get('https://www.google.com/search?q='+text.get()) soup=BeautifulSoup(data.content,"html.parser") result=soup.select(".kCrYT a") for ans in result[:6]: search=ans.get("href") search=search[7:] search=search.split("&") webbrowser.open(search[0]) ### label=Label(structure,font=("Times",15,"bold"),text="Enter here to search",bg="black",fg="yellow") label.place(x=600,y=350) enter=Entry(structure,font=("Times",15,"bold"),textvar=text,width=60,bd=2,bg="white") enter.place(x=600,y=500) button=Button(structure,text="Search",font=("Times",15,"bold"),width=10,bd=2,bg="white",command=search) button.place(x=100,y=200) structure.mainloop() A: this two things must be canged to run your code ok: structure.geometry("1230*1230") will become: 'structure.geometry("1230x1230")' button=Button(structure,text="Search",font=("Times",15,"bold"),width=30,bd=2,bg="white",command=search) will become: 'button=Button(structure,text="Search",font=("Times",15,"bold"),width=30,bd=2,bg="white",command=searched)' then your code will run ok.
How to make a search-engine using tkinter in python?
I tried on making a gui-based search engine in python, but for some reason I am facing two errors. I am unable to locate the 'Search' button even though I have added it in code. (I think so) Due to not being able to use the search button I am unable to find any search results even after pressing enter. ###Edit After the help from all of you ,I have made changes to the code but still it is no good.the new code is here : import requests,webbrowser from bs4 import BeautifulSoup from tkinter import * structure=Tk() structure.geometry("1280*1280") structure.title("Cgo Engine") label=Label(structure,text="Cgo Engine",bg="dark grey",fg="Gold",font=("ComicSans",60,"italic")) label.pack(side=TOP) structure.config(background="dark grey") text=StringVar() ### def searches(): data=requests.get('https://www.google.com/search?q='+text.get()) soup=BeautifulSoup(data.content,"html.parser") result=soup.select(".kCrYT a") for ans in result[:6]: search=ans.get("href") search=search[7:] search=search.split("&") webbrowser.open(search[0]) ### label=Label(structure,font=("Times",15,"bold"),text="Enter here to search",bg="black",fg="yellow") label.place(x=600,y=350) enter=Entry(structure,font=("Times",15,"bold"),textvar=text,width=60,bd=2,bg="white") enter.place(x=600,y=500) button=Button(structure,text="Search",font=("Times",15,"bold"),width=10,bd=2,bg="white",command=search) button.place(x=100,y=200) structure.mainloop()
[ "this two things must be canged to run your code ok:\n\nstructure.geometry(\"1230*1230\")\n\nwill become: 'structure.geometry(\"1230x1230\")'\n\nbutton=Button(structure,text=\"Search\",font=(\"Times\",15,\"bold\"),width=30,bd=2,bg=\"white\",command=search)\n\nwill become: 'button=Button(structure,text=\"Search\",font=(\"Times\",15,\"bold\"),width=30,bd=2,bg=\"white\",command=searched)'\nthen your code will run ok.\n" ]
[ 0 ]
[]
[]
[ "error_handling", "python", "search_engine", "tkinter" ]
stackoverflow_0074542285_error_handling_python_search_engine_tkinter.txt
Q: replace column values with values from different dataframe I have 2 pandas dataframes: df1 Home Place a MS Z2 c KM Z3 d RR R2 df2 Place1 a A2 c A66 z F32 x K41 t E90 I want to replace values of df2['Place1'] with df1['Place'] when indexes are matching and leave it the same when indexes are not matching. Desired result: Place1 a Z2 c Z3 z F32 x K41 t E90 I tried to use pd.replace but it returns NAs A: Try with update df2['Place1'].update(df1['Place']) df2 Out[75]: Place1 a Z2 c Z3 z F32 x K41 t E90 A: You can do this with update. df2['Place1'] = df2['Place1'].update(df1['Place'])
replace column values with values from different dataframe
I have 2 pandas dataframes: df1 Home Place a MS Z2 c KM Z3 d RR R2 df2 Place1 a A2 c A66 z F32 x K41 t E90 I want to replace values of df2['Place1'] with df1['Place'] when indexes are matching and leave it the same when indexes are not matching. Desired result: Place1 a Z2 c Z3 z F32 x K41 t E90 I tried to use pd.replace but it returns NAs
[ "Try with update\ndf2['Place1'].update(df1['Place'])\ndf2\nOut[75]: \n Place1\na Z2\nc Z3\nz F32\nx K41\nt E90\n\n", "You can do this with update.\ndf2['Place1'] = df2['Place1'].update(df1['Place'])\n\n" ]
[ 1, 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python", "replace" ]
stackoverflow_0074549492_dataframe_numpy_pandas_python_replace.txt
Q: Running sudo command on a Azure function app using consumption plan I am trying to deploy an azure function written using python to an azure function app. The function is using pyzbar library. The pyzbar library documentation says that in a Linux environment, the below command needs to be executed so that the pyzbar can work. sudo apt-get install libzbar0 How can I execute this command on the consumption plan. Please note that I can get this to work if I deploy the function with a container approach using a premium or a dedicated plan. But I want to get this to work using the consumption plan. Any help is highly appreciated. A: I have a work around where every time you trigger your function it will run a script that will install the required packages using the command prompt. This can be achieved using subprocess module code : subprocess.run(["apt-get"," install"," libzbar0"]) for Example in the following code I am installing pandas using pip and returning it's version. But this will increase your execution time as even if you have added the packages it will continue to execute the installation commands every time you trigger the function.
Running sudo command on a Azure function app using consumption plan
I am trying to deploy an azure function written using python to an azure function app. The function is using pyzbar library. The pyzbar library documentation says that in a Linux environment, the below command needs to be executed so that the pyzbar can work. sudo apt-get install libzbar0 How can I execute this command on the consumption plan. Please note that I can get this to work if I deploy the function with a container approach using a premium or a dedicated plan. But I want to get this to work using the consumption plan. Any help is highly appreciated.
[ "\nI have a work around where every time you trigger your function it will run a script that will install the required packages using the command prompt.\n\nThis can be achieved using subprocess module\n\n\ncode :\nsubprocess.run([\"apt-get\",\" install\",\" libzbar0\"])\n\nfor Example in the following code I am installing pandas using pip and returning it's version.\n\n\nBut this will increase your execution time as even if you have added the packages it will continue to execute the installation commands every time you trigger the function.\n\n" ]
[ 0 ]
[]
[]
[ "azure_functions", "python", "zbar" ]
stackoverflow_0074542828_azure_functions_python_zbar.txt
Q: Date and time format from string I'm converting the date of this string in this way, but I get the error "time data 'Aug 6, 2022, 10:44 AM' does not match format '%m %d, %Y, %I:%Mp'" fechaDAT = 'Aug 6, 2022, 10:44 AM' dateC = datetime.strptime(fechaDAT, "%m %d, %Y, %I:%Mp") A: here is the right format : dateC = datetime.strptime(fechaDAT, "%b %d, %Y, %I:%M %p") %b for month abbrevation %p for locale AM/PM
Date and time format from string
I'm converting the date of this string in this way, but I get the error "time data 'Aug 6, 2022, 10:44 AM' does not match format '%m %d, %Y, %I:%Mp'" fechaDAT = 'Aug 6, 2022, 10:44 AM' dateC = datetime.strptime(fechaDAT, "%m %d, %Y, %I:%Mp")
[ "here is the right format :\ndateC = datetime.strptime(fechaDAT, \"%b %d, %Y, %I:%M %p\")\n\n%b for month abbrevation\n%p for locale AM/PM\n" ]
[ 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074549555_datetime_python.txt
Q: Upload CSV files into partitioned bigquery table (generate partition from file name) I am using bigquery client object to upload some CSV files (located in cloud storage) into a bigquery table. I managed to upload the data into a bigquery table but I want to change the destination table to a partitioned table. And partition will be date which is in the filename. filename is a column in the CSV file which is the same as CSV file name. This is how I extract date from filename (assume text is filename) date1 will be used as our partition later: text = 'sales_2022-09-09T21-27-05_018787' match = re.search(r'\d{4}-\d{2}-\d{2}', text) date1 = datetime.strptime(match.group(), '%Y-%m-%d').date() and this is how to upload data into BQ: client = bigquery.Client.from_service_account_json(CREDENTIALS_LOCATION) def upload_from_gcs_to_bq(project_id, dataset_id, gsutil_uri, table_name,gcs_blob): table_id = project_id +'.'+ dataset_id +'.'+ table_name uri = gsutil_uri + '/' + gcs_blob +'.csv' job_config = bigquery.LoadJobConfig( schema=[ bigquery.SchemaField("filename", "STRING"), bigquery.SchemaField("sales_category", "STRING"), ... ], skip_leading_rows=1, # time_partitioning=bigquery.TimePartitioning( # type_=bigquery.TimePartitioningType.DAY, # field="date", # Name of the column to use for partitioning. # expiration_ms=7776000000, # 90 days. # ), ) load_job = client.load_table_from_uri( uri, table_id, job_config=job_config ) load_job.result() # Wait for the job to complete. table = client.get_table(table_id) def main(): upload_from_gcs_to_bq(project_id, dataset_id, gsutil_uri, table_name,gcs_blob) if __name__ == '__main__': main() A: I think it is better to take advantage of external tables, given that your data is already being stored in cloud storage. You can create external table, permanent or temporary, by reading directly the CSV files. https://cloud.google.com/bigquery/docs/external-data-cloud-storage And then load the information to a table partitioned by the field you are aiming for. If you have partitioned files, there is also a nice option to load them as external tables but you need to follow a specific format in cloud storage https://cloud.google.com/bigquery/docs/hive-partitioned-queries-gcs
Upload CSV files into partitioned bigquery table (generate partition from file name)
I am using bigquery client object to upload some CSV files (located in cloud storage) into a bigquery table. I managed to upload the data into a bigquery table but I want to change the destination table to a partitioned table. And partition will be date which is in the filename. filename is a column in the CSV file which is the same as CSV file name. This is how I extract date from filename (assume text is filename) date1 will be used as our partition later: text = 'sales_2022-09-09T21-27-05_018787' match = re.search(r'\d{4}-\d{2}-\d{2}', text) date1 = datetime.strptime(match.group(), '%Y-%m-%d').date() and this is how to upload data into BQ: client = bigquery.Client.from_service_account_json(CREDENTIALS_LOCATION) def upload_from_gcs_to_bq(project_id, dataset_id, gsutil_uri, table_name,gcs_blob): table_id = project_id +'.'+ dataset_id +'.'+ table_name uri = gsutil_uri + '/' + gcs_blob +'.csv' job_config = bigquery.LoadJobConfig( schema=[ bigquery.SchemaField("filename", "STRING"), bigquery.SchemaField("sales_category", "STRING"), ... ], skip_leading_rows=1, # time_partitioning=bigquery.TimePartitioning( # type_=bigquery.TimePartitioningType.DAY, # field="date", # Name of the column to use for partitioning. # expiration_ms=7776000000, # 90 days. # ), ) load_job = client.load_table_from_uri( uri, table_id, job_config=job_config ) load_job.result() # Wait for the job to complete. table = client.get_table(table_id) def main(): upload_from_gcs_to_bq(project_id, dataset_id, gsutil_uri, table_name,gcs_blob) if __name__ == '__main__': main()
[ "I think it is better to take advantage of external tables, given that your data is already being stored in cloud storage.\nYou can create external table, permanent or temporary, by reading directly the CSV files.\nhttps://cloud.google.com/bigquery/docs/external-data-cloud-storage\nAnd then load the information to a table partitioned by the field you are aiming for.\nIf you have partitioned files, there is also a nice option to load them as external tables but you need to follow a specific format in cloud storage\nhttps://cloud.google.com/bigquery/docs/hive-partitioned-queries-gcs\n" ]
[ 1 ]
[]
[]
[ "google_bigquery", "google_cloud_platform", "python" ]
stackoverflow_0074525763_google_bigquery_google_cloud_platform_python.txt
Q: Splitting an array in different groups Suppose I have an array with 302 elements. I want to split the array into n = 6 groups (roughly equal size), such that it looks like the following. The following code works when n = 6. However, if n is 51 groups, then it failed and generated 60 groups. How can I get this right ? n = 6 group_num = np.arange(302) // (302 // n) group_num[group_num == n] = n - 1 array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], dtype=int32 ) A: Use numpy.linspace: n = 51 np.linspace(0, n, num=302, endpoint=False).astype(int) Output: array([ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 34, 34, 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 36, 36, 36, 36, 36, 36, 37, 37, 37, 37, 37, 37, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 40, 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 42, 42, 42, 42, 42, 42, 43, 43, 43, 43, 43, 43, 44, 44, 44, 44, 44, 44, 45, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 46, 47, 47, 47, 47, 47, 47, 48, 48, 48, 48, 48, 48, 49, 49, 49, 49, 49, 49, 50, 50, 50, 50, 50]) A: You are doing a floor division with 302 // n, which will create groups that are too small. Try this: import numpy n = 51 group_num = numpy.arange(302) // (302 / n) group_num[group_num == n] = n-1 print(group_num)
Splitting an array in different groups
Suppose I have an array with 302 elements. I want to split the array into n = 6 groups (roughly equal size), such that it looks like the following. The following code works when n = 6. However, if n is 51 groups, then it failed and generated 60 groups. How can I get this right ? n = 6 group_num = np.arange(302) // (302 // n) group_num[group_num == n] = n - 1 array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], dtype=int32 )
[ "Use numpy.linspace:\nn = 51\nnp.linspace(0, n, num=302, endpoint=False).astype(int)\n\nOutput:\narray([ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2,\n 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5,\n 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8,\n 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11,\n 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14,\n 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 17,\n 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19,\n 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22,\n 22, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25,\n 25, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28,\n 28, 28, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 31, 31, 31,\n 31, 31, 31, 32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 34, 34,\n 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 36, 36, 36, 36, 36, 36, 37,\n 37, 37, 37, 37, 37, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 40,\n 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 42, 42, 42, 42, 42, 42,\n 43, 43, 43, 43, 43, 43, 44, 44, 44, 44, 44, 44, 45, 45, 45, 45, 45,\n 45, 46, 46, 46, 46, 46, 46, 47, 47, 47, 47, 47, 47, 48, 48, 48, 48,\n 48, 48, 49, 49, 49, 49, 49, 49, 50, 50, 50, 50, 50])\n\n", "You are doing a floor division with 302 // n, which will create groups that are too small. Try this:\nimport numpy\n\nn = 51\ngroup_num = numpy.arange(302) // (302 / n)\ngroup_num[group_num == n] = n-1\nprint(group_num)\n\n" ]
[ 2, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074549328_numpy_python.txt
Q: Python __str__ no returning the desired result I'm working on my first few weeks of pythong, and i'm trying to modify some code from a course im following. I have added some data into a mssql, and I want to extract that table into my flask page. I was told to use str for my class, and I have added that, but i'm still not getting a proper result. My app.py code is here: from flask import Flask, render_template, url_for, redirect from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from sqlalchemy import create_engine app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "mssql://@UB-tucIMS9NpXKF\\SQLEXPRESS/LOCAL_UBBI?driver=ODBC Driver 17 for SQL Server" app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db = SQLAlchemy(app) Migrate(app,db) db.init_app(app) class Products(db.Model): __tablename__ = 'Products' id = db.Column(db.Integer,primary_key=True) Name = db.Column(db.Text) Code = db.Column(db.Integer) def __init__(self,id, name, code): self.id = id self.name = name self.code = code def __str__(self): return f"Product: ('number {self.id} is: {self.name}, {self.code}')" @app.route('/') def index(): return render_template('home.html') @app.route('/products') def listProducts(): myProducts = Products.query.all() return render_template('listProducts.html', myProducts=myProducts) if __name__ == '__main__': app.run(debug=True) And my view file's code is: {% extends "base.html" %} {% block content %} <div class="jumbotron"> <p>list products</p> {{ myProducts }} <!--{{ myProducts.name }}--> <!--<ul> {% for eachproduct in myProducts %} <li>{{eachproduct}}</li> {% endfor %} </ul>--> </div> {% endblock %} But my output if not my string representation of my object: What am I missing ? Thanks in advance A: Use repr instead of str to declare or print the official string representation of an object. In your case you can represent it with something like this. def __repr__(self): return f'<id: {self.id}, name: {self.name}, code: {self.code}>'
Python __str__ no returning the desired result
I'm working on my first few weeks of pythong, and i'm trying to modify some code from a course im following. I have added some data into a mssql, and I want to extract that table into my flask page. I was told to use str for my class, and I have added that, but i'm still not getting a proper result. My app.py code is here: from flask import Flask, render_template, url_for, redirect from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from sqlalchemy import create_engine app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "mssql://@UB-tucIMS9NpXKF\\SQLEXPRESS/LOCAL_UBBI?driver=ODBC Driver 17 for SQL Server" app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db = SQLAlchemy(app) Migrate(app,db) db.init_app(app) class Products(db.Model): __tablename__ = 'Products' id = db.Column(db.Integer,primary_key=True) Name = db.Column(db.Text) Code = db.Column(db.Integer) def __init__(self,id, name, code): self.id = id self.name = name self.code = code def __str__(self): return f"Product: ('number {self.id} is: {self.name}, {self.code}')" @app.route('/') def index(): return render_template('home.html') @app.route('/products') def listProducts(): myProducts = Products.query.all() return render_template('listProducts.html', myProducts=myProducts) if __name__ == '__main__': app.run(debug=True) And my view file's code is: {% extends "base.html" %} {% block content %} <div class="jumbotron"> <p>list products</p> {{ myProducts }} <!--{{ myProducts.name }}--> <!--<ul> {% for eachproduct in myProducts %} <li>{{eachproduct}}</li> {% endfor %} </ul>--> </div> {% endblock %} But my output if not my string representation of my object: What am I missing ? Thanks in advance
[ "Use repr instead of str to declare or print the official string representation of an object. In your case you can represent it with something like this.\ndef __repr__(self):\n return f'<id: {self.id}, name: {self.name}, code: {self.code}>'\n\n" ]
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074547647_flask_python.txt
Q: Unpacking list in Python - ValueError: not enough values to unpack I test my script just printing return value of .split: for f in os.listdir(): f_name, f_ext = os.path.splitext(f) print(f_name.split('-')) and it shows me what I'd like to see - lists with 3 strings in each. ['Earth ', ' Our Solar System ', ' #4'] ['Saturn ', ' Our Solar System ', ' #7'] ['The Sun ', ' Our Solar System ', ' #1'] However, when I'm trying to store it in 3 different variables: for f in os.listdir(): f_name, f_ext = os.path.splitext(f) f_title, f_course, f_num = f_name.split(' - ') it gives me an error: f_title, f_course, f_num = f_name.split('-') ^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: not enough values to unpack (expected 3, got 1) I'd appreciate any help on this! Thanks! A: What you are experiencing is the diffrence between unpacking three items and a list. What you are getting from f.split is a single item only which is a list of the 'words' f_name = 'a-b-c' f_name.split("-") -> [a,b,c] #But a list is a single entity So consider : [title,course,num]= f_name.split("-") However this is not a very good way to do it. What happens if split returns 4 words in a list ? Although this solves your problem, I highly doubt you should be doing it in this way. A: It seems like there are unwanted spaces around the hyphen f_name.split(' - '). Remove them: for f in os.listdir(): f_name, f_ext = os.path.splitext(f) f_title, f_course, f_num = f_name.split('-')
Unpacking list in Python - ValueError: not enough values to unpack
I test my script just printing return value of .split: for f in os.listdir(): f_name, f_ext = os.path.splitext(f) print(f_name.split('-')) and it shows me what I'd like to see - lists with 3 strings in each. ['Earth ', ' Our Solar System ', ' #4'] ['Saturn ', ' Our Solar System ', ' #7'] ['The Sun ', ' Our Solar System ', ' #1'] However, when I'm trying to store it in 3 different variables: for f in os.listdir(): f_name, f_ext = os.path.splitext(f) f_title, f_course, f_num = f_name.split(' - ') it gives me an error: f_title, f_course, f_num = f_name.split('-') ^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: not enough values to unpack (expected 3, got 1) I'd appreciate any help on this! Thanks!
[ "What you are experiencing is the diffrence between unpacking three items and a list. What you are getting from f.split is a single item only which is a list of the 'words'\nf_name = 'a-b-c'\nf_name.split(\"-\") -> [a,b,c] #But a list is a single entity\n\nSo consider :\n[title,course,num]= f_name.split(\"-\")\n\nHowever this is not a very good way to do it. What happens if split returns 4 words in a list ? Although this solves your problem, I highly doubt you should be doing it in this way.\n", "It seems like there are unwanted spaces around the hyphen f_name.split(' - '). Remove them:\nfor f in os.listdir():\n f_name, f_ext = os.path.splitext(f)\n f_title, f_course, f_num = f_name.split('-')\n\n" ]
[ 0, 0 ]
[]
[]
[ "list", "python", "unpack", "valueerror" ]
stackoverflow_0074549630_list_python_unpack_valueerror.txt
Q: Can variables be stored in Lists in Python? Can I do this in python? lst = [listItem = 0,listItem2 = 0,listItem3 = 0] Then update the variable in the list like: number = 1 if number > 0: lst[1] += 1 listItem2 is now = 1 A: Well for the first if you want store data in list just put them like this: List = [0, 1, 2] not this: List1 = [var1 = 0, var2 = 1] if you need to make variables from data stored in list just use them like this: var1 = List[1] This how your code should look like: lst = [0, 0, 0] number = 1 if number > 0: lst[1] += 1
Can variables be stored in Lists in Python?
Can I do this in python? lst = [listItem = 0,listItem2 = 0,listItem3 = 0] Then update the variable in the list like: number = 1 if number > 0: lst[1] += 1 listItem2 is now = 1
[ "Well for the first if you want store data in list just put them like this:\nList = [0, 1, 2]\nnot this: List1 = [var1 = 0, var2 = 1]\nif you need to make variables from data stored in list just use them like this:\nvar1 = List[1]\nThis how your code should look like:\nlst = [0, 0, 0]\n\nnumber = 1\n\nif number > 0: \n lst[1] += 1\n\n" ]
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074549506_list_python.txt
Q: FastAPI: How to show multiple request examples in the docs and keep the default one I would like to show different example for a request in the FastAPI docs. As described here: https://fastapi.tiangolo.com/tutorial/schema-extra-example This code creates two examples ("Denmark, Sweden") but when I run it, the auto generated full example is no longer available. How can I keep the default example at the top of the example list without having to manually recreate it? from fastapi import FastAPI, Body from pydantic import BaseModel import uvicorn class HelloWorld(BaseModel): hello: str world: str = "World" app = FastAPI() @app.post("/") def post_root( hwr: HelloWorld = Body( ..., examples={ # add "default example" here "denmark": {"summary": "A Denmark example", "value": {"hello": "denmark"}}, "sweden": {"summary": "A Sweden example", "value": {"hello": "sweden"}}, } ) ): return {"Hello": "World"} if __name__ == "__main__": uvicorn.run(app=app, host="0.0.0.0", port=5085) A: Adding a "default" entry with no "value" adds the default to the list of examples. examples={ # add "default example" here "default": {"summary": "Default example"}, "denmark": {"summary": "A Denmark example", "value": {"hello": "denmark"}}, "sweden": {"summary": "A Sweden example", "value": {"hello": "sweden"}}, } Note: If you want to do the same with responses, this Medium article explains how to do it.
FastAPI: How to show multiple request examples in the docs and keep the default one
I would like to show different example for a request in the FastAPI docs. As described here: https://fastapi.tiangolo.com/tutorial/schema-extra-example This code creates two examples ("Denmark, Sweden") but when I run it, the auto generated full example is no longer available. How can I keep the default example at the top of the example list without having to manually recreate it? from fastapi import FastAPI, Body from pydantic import BaseModel import uvicorn class HelloWorld(BaseModel): hello: str world: str = "World" app = FastAPI() @app.post("/") def post_root( hwr: HelloWorld = Body( ..., examples={ # add "default example" here "denmark": {"summary": "A Denmark example", "value": {"hello": "denmark"}}, "sweden": {"summary": "A Sweden example", "value": {"hello": "sweden"}}, } ) ): return {"Hello": "World"} if __name__ == "__main__": uvicorn.run(app=app, host="0.0.0.0", port=5085)
[ "Adding a \"default\" entry with no \"value\" adds the default to the list of examples.\n examples={\n # add \"default example\" here \n \"default\": {\"summary\": \"Default example\"},\n\n \"denmark\": {\"summary\": \"A Denmark example\", \"value\": {\"hello\": \"denmark\"}},\n \"sweden\": {\"summary\": \"A Sweden example\", \"value\": {\"hello\": \"sweden\"}},\n }\n\nNote: If you want to do the same with responses, this Medium article explains how to do it.\n" ]
[ 0 ]
[]
[]
[ "fastapi", "python" ]
stackoverflow_0074545715_fastapi_python.txt
Q: How can I rename the PDF file, with the URL from where I downloaded it using Python I have a List of links that I have collected from google search results and I'm downloading these (PDF) files using selenium. I want to rename each file so that its filename contains the URL. What can I do? I have not tried any code so please help me. I'm showing the code of selenium that I used to download the files. folderName=input(("Enter The FolderName:\t")).upper() #Geting Input for the name of folder newDir="C:\\Users\\sulta\\Data Science CV\\" + folderName print(newDir) if not os.path.exists(newDir): os.makedirs(newDir) #creating folder options = webdriver.ChromeOptions() options.add_experimental_option('prefs', { "download.default_directory":"C:\\Users\\sulta\\Data Science CV\\" + folderName, #Downloading the files to thi path "download.prompt_for_download": False, #To auto download the file "download.directory_upgrade": True, "plugins.always_open_pdf_externally": True #It will not show PDF directly in chrome }) driver = webdriver.Chrome(options=options) for z in range(len(link)): #My All links are stored in the list named link try: driver.get(link[z]) driver.set_page_load_timeout(10) except: continue A: I dont think there's any python core library that can do this on selenium download. What you can do is to have a folder watchdog that keeps track of any changes or events that occur in the folder so that you can the rename the new file from there. Check out pyWatch it could be of help. A: for z in range(len(link)): try: driver.get(link[z]) driver.set_page_load_timeout(10) # create the file name from the link, like below: file_name = link[z].replace("/", "-") # add the code to download the pdf file # rename the downloaded file os.rename('<downloaded file name with path>', file_name <with path>) except: continue A: One solution would be to read all the files on the directory, download the new file then read again to get its name and them rename it to what you want, something like this folderName=input(("Enter The FolderName:\t")).upper() #Geting Input for the name of folder newDir="C:\\Users\\sulta\\Data Science CV\\" + folderName print(newDir) if not os.path.exists(newDir): os.makedirs(newDir) #creating folder options = webdriver.ChromeOptions() options.add_experimental_option('prefs', { "download.default_directory":"C:\\Users\\sulta\\Data Science CV\\" + folderName, #Downloading the files to thi path "download.prompt_for_download": False, #To auto download the file "download.directory_upgrade": True, "plugins.always_open_pdf_externally": True #It will not show PDF directly in chrome }) driver = webdriver.Chrome(options=options) for z in range(len(link)): #My All links are stored in the list named link try: import os files_before = os.listdir(newDir) #list all files driver.get(link[z]) driver.set_page_load_timeout(10) files_after = os.listdir(newDir) # list all files after download new_file = list(set(files_after) - set(files_before))[0] # get new file in folder new_name = 'new_name.file' #name of new file os.rename(newDir+'/'+new_file,newDir+'/'+new_name) #rename new file in path except: continue
How can I rename the PDF file, with the URL from where I downloaded it using Python
I have a List of links that I have collected from google search results and I'm downloading these (PDF) files using selenium. I want to rename each file so that its filename contains the URL. What can I do? I have not tried any code so please help me. I'm showing the code of selenium that I used to download the files. folderName=input(("Enter The FolderName:\t")).upper() #Geting Input for the name of folder newDir="C:\\Users\\sulta\\Data Science CV\\" + folderName print(newDir) if not os.path.exists(newDir): os.makedirs(newDir) #creating folder options = webdriver.ChromeOptions() options.add_experimental_option('prefs', { "download.default_directory":"C:\\Users\\sulta\\Data Science CV\\" + folderName, #Downloading the files to thi path "download.prompt_for_download": False, #To auto download the file "download.directory_upgrade": True, "plugins.always_open_pdf_externally": True #It will not show PDF directly in chrome }) driver = webdriver.Chrome(options=options) for z in range(len(link)): #My All links are stored in the list named link try: driver.get(link[z]) driver.set_page_load_timeout(10) except: continue
[ "I dont think there's any python core library that can do this on selenium download. What you can do is to have a folder watchdog that keeps track of any changes or events that occur in the folder so that you can the rename the new file from there.\nCheck out pyWatch it could be of help.\n", "for z in range(len(link)): \n try:\n driver.get(link[z])\n driver.set_page_load_timeout(10)\n\n # create the file name from the link, like below:\n file_name = link[z].replace(\"/\", \"-\")\n\n # add the code to download the pdf file\n\n # rename the downloaded file\n os.rename('<downloaded file name with path>', file_name <with path>)\n except:\n continue\n\n", "One solution would be to read all the files on the directory, download the new file then read again to get its name and them rename it to what you want, something like this\nfolderName=input((\"Enter The FolderName:\\t\")).upper() #Geting Input for the name of folder\n\nnewDir=\"C:\\\\Users\\\\sulta\\\\Data Science CV\\\\\" + folderName\nprint(newDir)\nif not os.path.exists(newDir):\n os.makedirs(newDir) #creating folder \noptions = webdriver.ChromeOptions()\noptions.add_experimental_option('prefs', {\n\"download.default_directory\":\"C:\\\\Users\\\\sulta\\\\Data Science CV\\\\\" + folderName, #Downloading the files to thi path\n\"download.prompt_for_download\": False, #To auto download the file\n\"download.directory_upgrade\": True,\n\"plugins.always_open_pdf_externally\": True #It will not show PDF directly in chrome\n})\ndriver = webdriver.Chrome(options=options)\nfor z in range(len(link)): #My All links are stored in the list named link\n try:\n import os\n files_before = os.listdir(newDir) #list all files\n driver.get(link[z])\n driver.set_page_load_timeout(10)\n files_after = os.listdir(newDir) # list all files after download\n\n new_file = list(set(files_after) - set(files_before))[0] # get new file in folder\n new_name = 'new_name.file' #name of new file\n os.rename(newDir+'/'+new_file,newDir+'/'+new_name) #rename new file in path\n \n except:\n continue\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074547662_python_selenium.txt
Q: TypeError: '_io.TextIOWrapper' object is not subscriptable The main function that the code should do is to open a file and get the median. This is my code: def medianStrat(lst): count = 0 test = [] for line in lst: test += line.split() for i in lst: count = count +1 if count % 2 == 0: x = count//2 y = lst[x] z = lst[x-1] median = (y + z)/2 return median if count %2 == 1: x = (count-1)//2 return lst[x] # Where the problem persists def main(): lst = open(input("Input file name: "), "r") print(medianStrat(lst)) Here is the error I get: Traceback (most recent call last): File "C:/Users/honte_000/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 30, in <module> main() File "C:/Users/honte_000/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 28, in main print(medianStrat(lst)) File "C:/Users/honte_000/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 24, in medianStrat return lst[x] TypeError: '_io.TextIOWrapper' object is not subscriptable I know lst[x] is causing this problem but not too sure how to solve this one. So what could be the solution to this problem or what could be done instead to make the code work? A: You can't index (__getitem__) a _io.TextIOWrapper object. What you can do is work with a list of lines. Try this in your code: lst = open(input("Input file name: "), "r").readlines() Also, you aren't closing the file object, this would be better: with open(input("Input file name: ", "r") as lst: print(medianStrat(lst.readlines())) with ensures that file get closed. A: basic error my end, sharing in case anyone else finds it useful. Difference between datatypes is really important! just because it looks like JSON doesn't mean it is JSON - I ended up on this answer, learning this the hard way. Opening the IO Stream needs to be converted using the python json.load method, before it is a dict data type, otherwise it is still a string. Now it is in a dict it can be brought into a dataFrame. def load_json(): # this function loads json and returns it as a dataframe with open("1lumen.com.json", "r") as io_str: data = json.load(io_str) df = pd.DataFrame.from_dict(data) logging.info(df.columns.tolist()) return(df)
TypeError: '_io.TextIOWrapper' object is not subscriptable
The main function that the code should do is to open a file and get the median. This is my code: def medianStrat(lst): count = 0 test = [] for line in lst: test += line.split() for i in lst: count = count +1 if count % 2 == 0: x = count//2 y = lst[x] z = lst[x-1] median = (y + z)/2 return median if count %2 == 1: x = (count-1)//2 return lst[x] # Where the problem persists def main(): lst = open(input("Input file name: "), "r") print(medianStrat(lst)) Here is the error I get: Traceback (most recent call last): File "C:/Users/honte_000/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 30, in <module> main() File "C:/Users/honte_000/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 28, in main print(medianStrat(lst)) File "C:/Users/honte_000/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 24, in medianStrat return lst[x] TypeError: '_io.TextIOWrapper' object is not subscriptable I know lst[x] is causing this problem but not too sure how to solve this one. So what could be the solution to this problem or what could be done instead to make the code work?
[ "You can't index (__getitem__) a _io.TextIOWrapper object. What you can do is work with a list of lines. Try this in your code:\nlst = open(input(\"Input file name: \"), \"r\").readlines()\n\n\nAlso, you aren't closing the file object, this would be better:\nwith open(input(\"Input file name: \", \"r\") as lst:\n print(medianStrat(lst.readlines()))\n\nwith ensures that file get closed.\n", "basic error my end, sharing in case anyone else finds it useful. Difference between datatypes is really important! just because it looks like JSON doesn't mean it is JSON - I ended up on this answer, learning this the hard way.\nOpening the IO Stream needs to be converted using the python json.load method, before it is a dict data type, otherwise it is still a string. Now it is in a dict it can be brought into a dataFrame.\ndef load_json(): # this function loads json and returns it as a dataframe\nwith open(\"1lumen.com.json\", \"r\") as io_str:\n data = json.load(io_str)\n df = pd.DataFrame.from_dict(data)\n logging.info(df.columns.tolist())\nreturn(df)\n\n" ]
[ 15, 0 ]
[]
[]
[ "python", "typeerror" ]
stackoverflow_0028977477_python_typeerror.txt
Q: Remove decimals from a Float column shocked beyond belief how difficult this is turning out to be. All I can find are suggestions to change the format of the column to 'int' but I need to keep the comma thousand separators and changing the format to int gets rid of them. THEN i can't find anything on how to add comma separators to an int column. any ideas? really is nothing for me to share in addition to above in terms of what i've tried.
Remove decimals from a Float column
shocked beyond belief how difficult this is turning out to be. All I can find are suggestions to change the format of the column to 'int' but I need to keep the comma thousand separators and changing the format to int gets rid of them. THEN i can't find anything on how to add comma separators to an int column. any ideas? really is nothing for me to share in addition to above in terms of what i've tried.
[]
[]
[ "Format your floats...in a string format?\nmy_string = '{:,.0f}'. format(my_number) \n\nE.g.:\nx = 1000.00\n'{:,.0f}'. format(x)-> 1,000\n\nWhich gives you what you want...something you can print with commas. 0f sets to 0 precision. (for how many decimal places)\n" ]
[ -1 ]
[ "floating_point", "format", "python" ]
stackoverflow_0074549782_floating_point_format_python.txt
Q: Convert from plotter coordinates to world coordinates in PyVista I am new to PyVista and vtk. I am implementing a mesh editing tool (Python=3.10, pyvista=0.37,vtk=9.1 ) When a user clicks all points within a given radius of the mouse cursor's world coordinates (e.g. projected point on the surface) should be selected. I have implemented this much through callbacks to mouse clicks using the pyvista plotters track_click_position method. My problem is that I also want for a user to be able to preview the selection (highlight the vertices that will be selected) before they click. For this it is necessary to track the mouse location in world coordinates and to attach a callback function to the movement of the mouse that will highlight the relevant nodes. The pyvista plotter's 'track_mouse_position' method doesn't support attaching callbacks but I figured out a work around for that. In the minimal example below I have managed to track changes to the mouse cursor location in pixels in the plotter's coordinate system. I am stuck now as to how to convert these into world coordinates. When the mouse hovers over the sphere these 'world coordinates' this should be the projected location on the sphere. When the mouse hovers off the sphere then it should return nothing or inf or some other useless value. import pyvista as pv def myCallback(src,evt): C = src.GetEventPosition() # appears to be in pixels of the viewer print(C) # how to convert C into world coordinates on the sphere sp = pv.Sphere() p = pv.Plotter() p.add_mesh(sp) p.iren.add_observer("MouseMoveEvent",myCallback) p.show() Thank you very much for your help. Harry A: I figured this one out. They key was to use 'pick_mouse_position' after calling 'track_mouse_position'. import pyvista as pv def myCallback(src,evt): out = p.pick_mouse_position() print(out) sp = pv.Sphere() p = pv.Plotter() p.add_mesh(sp) p.track_mouse_position() p.iren.add_observer("MouseMoveEvent",myCallback) p.show()
Convert from plotter coordinates to world coordinates in PyVista
I am new to PyVista and vtk. I am implementing a mesh editing tool (Python=3.10, pyvista=0.37,vtk=9.1 ) When a user clicks all points within a given radius of the mouse cursor's world coordinates (e.g. projected point on the surface) should be selected. I have implemented this much through callbacks to mouse clicks using the pyvista plotters track_click_position method. My problem is that I also want for a user to be able to preview the selection (highlight the vertices that will be selected) before they click. For this it is necessary to track the mouse location in world coordinates and to attach a callback function to the movement of the mouse that will highlight the relevant nodes. The pyvista plotter's 'track_mouse_position' method doesn't support attaching callbacks but I figured out a work around for that. In the minimal example below I have managed to track changes to the mouse cursor location in pixels in the plotter's coordinate system. I am stuck now as to how to convert these into world coordinates. When the mouse hovers over the sphere these 'world coordinates' this should be the projected location on the sphere. When the mouse hovers off the sphere then it should return nothing or inf or some other useless value. import pyvista as pv def myCallback(src,evt): C = src.GetEventPosition() # appears to be in pixels of the viewer print(C) # how to convert C into world coordinates on the sphere sp = pv.Sphere() p = pv.Plotter() p.add_mesh(sp) p.iren.add_observer("MouseMoveEvent",myCallback) p.show() Thank you very much for your help. Harry
[ "I figured this one out. They key was to use 'pick_mouse_position' after calling 'track_mouse_position'.\n\n\nimport pyvista as pv\ndef myCallback(src,evt):\n out = p.pick_mouse_position()\n print(out)\n \nsp = pv.Sphere()\np = pv.Plotter()\np.add_mesh(sp)\np.track_mouse_position()\np.iren.add_observer(\"MouseMoveEvent\",myCallback)\np.show()\n\n\n\n" ]
[ 1 ]
[]
[]
[ "coordinate_systems", "python", "pyvista", "vtk" ]
stackoverflow_0074549375_coordinate_systems_python_pyvista_vtk.txt
Q: Is there any way in python to parse files in a directory full of directories full of text files to find for a match? I have a directory full of other directories with thousands of text files and I don't know how to parse every file to look for matches. Is there any way in python? I tried the read file module but I have to specify a directory and I don't know how to open every file, not only the ones I specified. A: If you have a character that separates each directory, you can use that to split the text. Search about the split function in Python. ' txt.split('') ' If you put the text it's more easy to explain.
Is there any way in python to parse files in a directory full of directories full of text files to find for a match?
I have a directory full of other directories with thousands of text files and I don't know how to parse every file to look for matches. Is there any way in python? I tried the read file module but I have to specify a directory and I don't know how to open every file, not only the ones I specified.
[ "If you have a character that separates each directory, you can use that to split the text.\nSearch about the split function in Python.\n' txt.split('') '\nIf you put the text it's more easy to explain.\n" ]
[ 0 ]
[]
[]
[ "directory", "python", "txt" ]
stackoverflow_0074549827_directory_python_txt.txt
Q: How to put text inside a rectangle in Manim Community this is the thing I wanted to make I'm very new to manim I'm trying to put the text inside a rectangle like given in the image How can I do that ?? :( A: You can use VGroup to group a box and a text together. Example Code: from manimlib import * def create_textbox(color, string): result = VGroup() # create a VGroup box = Rectangle( # create a box height=2, width=3, fill_color=color, fill_opacity=0.5, stroke_color=color ) text = Text(string).move_to(box.get_center()) # create text result.add(box, text) # add both objects to the VGroup return result class TextBox(Scene): def construct(self): # create text box textbox = create_textbox(color=BLUE, string="Hello world") self.add(textbox) # move text box around self.play(textbox.animate.shift(2*RIGHT), run_time=3) self.play(textbox.animate.shift(2*UP), run_time=3) self.wait() A: You simply define the rectangle's width and height according to the text's properties : txt = Text("Source") txtbox = Rectangle(width=s.width, height=s.height) To set the padding between the text and the "border", you can add a certain value to either width or height like width = s.width + 1.
How to put text inside a rectangle in Manim Community
this is the thing I wanted to make I'm very new to manim I'm trying to put the text inside a rectangle like given in the image How can I do that ?? :(
[ "You can use VGroup to group a box and a text together.\nExample Code:\nfrom manimlib import *\n\ndef create_textbox(color, string):\n result = VGroup() # create a VGroup\n box = Rectangle( # create a box\n height=2, width=3, fill_color=color, \n fill_opacity=0.5, stroke_color=color\n )\n text = Text(string).move_to(box.get_center()) # create text\n result.add(box, text) # add both objects to the VGroup\n return result\n\n\nclass TextBox(Scene): \n def construct(self):\n\n # create text box\n textbox = create_textbox(color=BLUE, string=\"Hello world\")\n self.add(textbox)\n\n # move text box around\n self.play(textbox.animate.shift(2*RIGHT), run_time=3)\n self.play(textbox.animate.shift(2*UP), run_time=3)\n self.wait()\n\n", "You simply define the rectangle's width and height according to the text's properties :\ntxt = Text(\"Source\")\ntxtbox = Rectangle(width=s.width, height=s.height)\n\nTo set the padding between the text and the \"border\", you can add a certain value to either width or height like width = s.width + 1.\n" ]
[ 5, 0 ]
[ "Writing a text inside a rectangle can be achieved in few steps:\n\nImporting manim\nWrite the text to be inside the shape (I am using Rectangle as an example)\nAnimate or create an image.\n\nfrom manim import *\n\nclass TextInsideRec(Scene):\n def construct(self):\n text = Text(\"I am the text to be inside the rectangle\")\n# To make the text bigger, you can scale it.\n text.scale(1.5)\n\n text_high = text.height # getting the text height\n text_width = text.width # Getting the text width\n \n rec = Rectangle(\n height=text_height +0.5, # Adding a small space between text and rectangle side\n width=text_width + 0.5,\n color=RED_A, # Coloring the rectangle\n stroke_width = 12, # Changing the stroke width\n stroke_color=ORANGE\n )\n# Animate it with play or render it as a image with add \n self.play(Write(text), \n Write(rec), run_time = 3)) # run_time is the how long the animation will last\n self.wait(2)\n# You can remove at the end if you want to \n self.play(Unwrite(t, reverse=False),\n Uncreate(rec, reverse=True, remover=True))\n self.wait(2)\n\nNote: adding wait at the end will ensure the animate will complete, otherwise you will see something left.\n" ]
[ -1 ]
[ "algorithm_animation", "animation", "manim", "python", "python_3.x" ]
stackoverflow_0070142914_algorithm_animation_animation_manim_python_python_3.x.txt
Q: the following arguments are required I have the Python script . What I'm trying to do is to test this code in colab The problem is that the initial script requires arguments. They are defined as follows: if __name__ == "__main__": parser = argparse.ArgumentParser(description="Pipeline to train a NN model specified by a YML config") parser.add_argument("-t", "--tag", nargs="?", type=str, help="Model tag of the experiment", required=True) parser.add_argument("-c", "--config", nargs="?", type=str, default="syndoc.yml", help="Config file name") parser.add_argument("-s", "--seed", nargs="?", type=int, default=4321, help="Seed number") parser.add_argument('-wt', '--with_test', action='store_true', help='Whether to run corresponding Tester') args = parser.parse_args() config = coerce_to_path_and_check_exist(CONFIGS_PATH / args.config) run_dir = MODELS_PATH / args.tag trainer = Trainer(config, run_dir, seed=args.seed) trainer.run(seed=args.seed) the error usage: trainer.py [-h] -t [TAG] [-c [CONFIG]] [-s [SEED]] [-wt] trainer.py: error: the following arguments are required: -t/--tag A: Arguments are received when you run a program from the command line (shell, bash, cmd) and they enable effecting the program without changing it e.g. my-program -varX 1 vs my-program -varX 2, you are not doing so, so instead you can remove that code and replace args.config, args.tag etc. with variables e.g. config and tag that you define and set to the values you want.
the following arguments are required
I have the Python script . What I'm trying to do is to test this code in colab The problem is that the initial script requires arguments. They are defined as follows: if __name__ == "__main__": parser = argparse.ArgumentParser(description="Pipeline to train a NN model specified by a YML config") parser.add_argument("-t", "--tag", nargs="?", type=str, help="Model tag of the experiment", required=True) parser.add_argument("-c", "--config", nargs="?", type=str, default="syndoc.yml", help="Config file name") parser.add_argument("-s", "--seed", nargs="?", type=int, default=4321, help="Seed number") parser.add_argument('-wt', '--with_test', action='store_true', help='Whether to run corresponding Tester') args = parser.parse_args() config = coerce_to_path_and_check_exist(CONFIGS_PATH / args.config) run_dir = MODELS_PATH / args.tag trainer = Trainer(config, run_dir, seed=args.seed) trainer.run(seed=args.seed) the error usage: trainer.py [-h] -t [TAG] [-c [CONFIG]] [-s [SEED]] [-wt] trainer.py: error: the following arguments are required: -t/--tag
[ "Arguments are received when you run a program from the command line (shell, bash, cmd) and they enable effecting the program without changing it e.g. my-program -varX 1 vs my-program -varX 2, you are not doing so, so instead you can remove that code and replace args.config, args.tag etc. with variables e.g. config and tag that you define and set to the values you want.\n" ]
[ 0 ]
[ "parser = argparse.ArgumentParser(description=\"Pipeline to train a NN model specified by a YML config\")\nparser.add_argument(\"-t\", \"--tag\", nargs=\"?\", type=str, help=\"Model tag of the experiment\", required=True)\nparser.add_argument(\"-c\", \"--config\", nargs=\"?\", type=str, default=\"syndoc.yml\", help=\"Config file name\")\nparser.add_argument(\"-s\", \"--seed\", nargs=\"?\", type=int, default=4321, help=\"Seed number\")\nparser.add_argument('-wt', '--with_test', action='store_true', help='Whether to run corresponding Tester')\nargs = parser.parse_args()\nconfig = coerce_to_path_and_check_exist(CONFIGS_PATH / args.config)\nrun_dir = MODELS_PATH / args.tag\n\ntrainer = Trainer(config, run_dir, seed=args.seed)\ntrainer.run(seed=args.seed)\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0067071077_python.txt
Q: request.get to seemingly valid URL returns 404 status code / fails Valid URL fails requests.get https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL is a valid URL as is not redirects DOES NOT WORK import requests url6 = 'https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL' r = requests.get(url6) returns False 404 [] or more simply requests.get('https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL') <Response [404]> WORKS this for example (different page on same source) requests.get('https://finance.yahoo.com/quote/AMG?p=AMG') returns True 200 A: I added headers to your request. More specifically, I added the user agent. import requests url6 = 'https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL' headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'} r = requests.get(url6, headers=headers) A: Seems that adding user-agent helps r = requests.get(url8, headers={'User-Agent': 'Custom'})
request.get to seemingly valid URL returns 404 status code / fails
Valid URL fails requests.get https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL is a valid URL as is not redirects DOES NOT WORK import requests url6 = 'https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL' r = requests.get(url6) returns False 404 [] or more simply requests.get('https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL') <Response [404]> WORKS this for example (different page on same source) requests.get('https://finance.yahoo.com/quote/AMG?p=AMG') returns True 200
[ "I added headers to your request. More specifically, I added the user agent.\nimport requests\n\nurl6 = 'https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL'\nheaders={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'}\n\nr = requests.get(url6, headers=headers)\n\n", "Seems that adding user-agent helps\nr = requests.get(url8, headers={'User-Agent': 'Custom'})\n\n" ]
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "python_requests" ]
stackoverflow_0074549610_beautifulsoup_python_python_requests.txt