eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I'm trying to debug Odoo with no success. Docker compose starts the environment for Odoo so it's already built. This is my launch file: { "version": "0.2.0", "env": { "GEVENT_SUPPORT": "True" }, "configurations": [ { "name": "Debug", "type": "python", "request": "attach", "connect": { "host": "127.0.0.1", "port": 5678 }, "pathMappings": [ { "localRoot": "/local_folder/odoo", "remoteRoot": "/remote_folder/odoo", } ], "justMyCode": true } ] }  In the Dockerfile I built the image using RUN pip3 install debugpy. This is the command entry for the compose file: ports: - "8069:8069" - "5678:5678" expose: - 8069 - 5678 command: "python3 -m debugpy --listen 0.0.0.0:5678 --wait-for-client /path_to_odoo/odoo-bin args"  So the container is waiting for me to start debugging as normal but when I try an specific action the debugger does not stop in any breakpoint. The breakpoints are red so vscode does see the remote file. Should the address still be localhost:8069? Using netstat shows that 8069 and 5678 are listening but can't make the debugger work. The debugpy version in the container is 1.8 but already used 1.6 with no success. Any idea what the problem could be?

Answer: I managed to make it "work". It's a bug already reported here: https://github.com/microsoft/debugpy/issues/1206 Breakpoints hit when I remove GEVENT_SUPPORT=True or set it to False, but as soon as I do that I get spammed:  It seems that the gevent monkey-patching is being used. Please set an environment variable with: GEVENT_SUPPORT=True to enable gevent support in the debugger.  So the current solution to be able to use vscode debugger is to comment or remove GEVENT_SUPPORT and create a custom entrypoint so you won't get the spam message mentioned. Create a odoo_custom.py file: #!/usr/bin/env python3 import sys sys.path.append('/path/to/project_folder/framework') # enable gevent support in the debugger __import__('os').environ['GEVENT_SUPPORT'] = 'true' # set server timezone in UTC before time module imported __import__('os').environ['TZ'] = 'UTC' # import and run odoo-bin if __name__ == "__main__": with open("/path/to/project_folder/framework/odoo-bin") as f: code = compile(f.read(), "odoo-bin", 'exec') exec(code)  Finally add this in your compose: "python3 -m debugpy --listen 0.0.0.0:5678 --wait-for-client /project_folder/custom.py args"  Two days ago, Jan 3 2024, the issue was closed and they gonna fix it for python 3.12+, older python versions will still have to use this solution.
Question: I'm trying to run init function when flask app run. Here's server.py: from .parser import Parser app = Flask(config().get("FLASK_APP")) parser = None @app.before_first_request def init(): parser = Parser()  Here's wsgi.py:  import logging from src.utils.config import config host = config().get("FLASK_HOST") port = config().get("FLASK_PORT") env = config().get("FLASK_ENV") is_dev = env == "dev" logging.basicConfig( format='[%(asctime)s][%(levelname)s][%(message)s]', level=logging.INFO if is_dev else logging.WARNING, datefmt='%Y-%m-%d %H:%M:%S' ) from src.api.server import app if __name__ == '__main__': app.run( host=host, port=port, debug=is_dev, threaded=True )  And i'm getting the error AttributeError: 'Flask' object has no attribute 'before_first_request'. When i'm running the server.py like this: from .parser import Parser app = Flask(config().get("FLASK_APP")) parser = Parser()  The parser runs twice. I'm using Flask 3.0.0, as i see this decorator is deprecated. Are there any other solutions for Flask 3.0.0 version? I've checked the flask documentation but didn't find any alternatives for before_first_request decorator.

Answer: Suddenly i found the solution. The problem as i see is in the flask's reloader, so i just disabled this feature in the app.run bootstrap function. Here's detailed info by Sean's answer https://stackoverflow.com/a/9476701/11988818  For now, my application runs once. And there's no needs in the before_first_request decorator anymore.
Question: I am trying to follow this Redis documentation link to create a small DB of notable people searchable in real time (using Python client). I tried a similar code, but the final line, which queries by "s", should return two documents, instead, it returns a blank set. Can anybody help me find out the mistake I am making? import redis from redis.commands.json.path import Path import redis.commands.search.aggregation as aggregations import redis.commands.search.reducers as reducers from redis.commands.search.field import TextField, NumericField, TagField from redis.commands.search.indexDefinition import IndexDefinition, IndexType from redis.commands.search.query import NumericFilter, Query d1 = {"key": "shahrukh khan", "pl": '{"d": "mvtv", "id": "1234-a", "img": "foo.jpg", "t: "act", "tme": "1965-"}', "org": "1", "p": 100} d2 = {"key": "salman khan", "pl": '{"d": "mvtv", "id": "1236-a", "img": "fool.jpg", "t: "act", "tme": "1965-"}', "org": "1", "p": 100} d3 = {"key": "aamir khan", "pl": '{"d": "mvtv", "id": "1237-a", "img": "fooler.jpg", "t: "act", "tme": "1965-"}', "org": "1", "p": 100} schema = ( TextField("$.key", as_name="key"), NumericField("$.p", as_name="p"), ) r = redis.Redis(host='localhost', port=6379) rs = r.ft("idx:au") rs.create_index( schema, definition=IndexDefinition( prefix=["au:"], index_type=IndexType.JSON ) ) r.json().set("au:mvtv-1234-a", Path.root_path(), d1) r.json().set("au:mvtv-1236-a", Path.root_path(), d2) r.json().set("au:mvtv-1237-a", Path.root_path(), d3) rs.search(Query("s")) 

Answer: When executing a query from the redis-py client, it will transmit the FT.SEARCH command to the redis server. You can observe it by using the command MONITOR from a redis-client for example. According to the documentation, when providing a single word for the research, the matching is full. That's why the result of your query is the empty set. If you want to search by prefix, you need to use the expression prefix*. However, documentation says:  The prefix needs to be at least two characters long.  Hence, you cannot search by word starting only by s. What you could do: rs.search(Query("sa*")) #Result{1 total, docs: [Document {'id': 'au:mvtv-1236-a', 'payload': None, 'json': '{"key":"salman khan","pl":"{\\"d\\": \\"mvtv\\", \\"id\\": \\"1236-a\\", \\"img\\": \\"fool.jpg\\", \\"t: \\"act\\", \\"tme\\": \\"1965-\\"}","org":"1","p":100}'}]}  Aside note If you want to scope your search on a specific field, the syntax is: Query("@field_name: word") # Query("@key: sa*")  where @field_name is the schema field's name. Otherwise, the search will look up for all TextField attributes.
Question: I'm using Django simple JWT to implement user authentication, I have done few adjustments so the access token and refresh token are sent as http-only cookies and everything works well On the frontend I have implemented Persistent Login that would keep the user logged in when they refresh the page or close the browser etc. But since I have enabled these settings: "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True,  If the user keeps refreshing the page multiple times in a very short time, it might occur that a token is blacklisted before the user receives the new refresh token is there a way to fix that? One possible fix yet I'm not sure of its reliability is disabling the automatic blacklisting and waiting for the frontend to send a request upon receiving the new refresh token, the request containing the old refresh token in its body like this @api_view(['POST']) def blacklist_token(request): refreshToken = request.data.get("refresh") print(refreshToken) if refreshToken: token = tokens.RefreshToken(refreshToken) token.blacklist() return Response(status=status.HTTP_200_OK)  PS: Using React.js on the frontend

Answer: Refreshing a page should not require a token refresh. Instead the backend should receive and use the existing access token (from the HTTP only cookie). When the access token expires, the backend should return a 401 unauthorized response to the frontend. The frontend can then perform a synchronized token refresh. This copes reliably with multiple views getting data concurrently. If only a single view gets data at a time, it is safe to initiate the token refresh server side instead. Eventually, the refresh token will also expire. In OAuth 2.0, the authorization server returns an invalid_grant error code in this case. The frontend then redirects the user to authenticate again. I would recommend rehearsing these expiry events, since that's a great way to ensure a reliable app, where the user never experiences unnecessary errors.
Question: I'm currently facing an issue with importing the _bcrypt module in Python, and I would greatly appreciate any help or insights you can provide. I am using Python 3.9 on a Windows 10 Pro machine. the code calls paramiko which calls bcrypt When I try to import paramiko, I encounter the following error:  Traceback (most recent call last): File "d:\remote_conn\client-copy.py", line 44, in import sys, os, paramiko, time File "C:\Python39\lib\site-packages\paramiko\__init__.py", line 22, in from paramiko.transport import ( File "C:\Python39\lib\site-packages\paramiko\transport.py", line 93, in from paramiko.dsskey import DSSKey File "C:\Python39\lib\site-packages\paramiko\dsskey.py", line 37, in from paramiko.pkey import PKey File "C:\Python39\lib\site-packages\paramiko\pkey.py", line 32, in import bcrypt File "C:\Python39\lib\site-packages\bcrypt\__init__.py", line 13, in from ._bcrypt import ( ImportError: DLL load failed while importing `_bcrypt`: The specified procedure could not be found.  I have already attempted the following troubleshooting steps:  updated all packages Installed Microsoft Visual C++ Redistributable for Visual Studio 2015-20122 (x86/x64) and Microsoft Visual C++ Redistributable 2013 (x64). Installed OpenSSL with Git . Checked that the directory containing the DLL files is included in the PATH environment variable (C:\Windows\system32, C:\Python39\DLLs). Despite these efforts, the error persists. Could you please provide any suggestions or insights on how to resolve this issue? Is there anything I might be missing or any alternative approaches I could try? or how to know which DLLs files need?  Thank you in advance for your help! Best regards

Answer: I ran into the same issue for latest versions of paramiko(3.4.0) and bcrypt(4.1.2). I tried installing a lower version of bcrypt but should be >=3.2 as latest paramiko version(3.4.0) requires bcrypt>=3.2. This worked for me.
Question: I used to use execute_values in psycopg2 but it's gone in psycopg3. I tried following the advice in this answer or this github post, but it just doesn't seem to work for my use case. I'm trying to insert multiple values, my SQL is like so: sql = INSERT INTO activities (type_, key_, a, b, c, d, e) VALUES %s ON CONFLICT (key_) DO UPDATE SET a = EXCLUDED.a, b = EXCLUDED.b, c = EXCLUDED.c, d = EXCLUDED.d, e = EXCLUDED.e values = [['type', 'key', None, None, None, None, None]]  But doing cursor.executemany(sql, values) results in {ProgrammingError}the query has 1 placeholder but 7 parameters were passed. I tried many variations with extra parentheses etc. but always it results in some error. For example doing self.cursor.executemany(sql, [values]) results in syntax error near or at "$1": Line 3: VALUES $1.

Answer: The values clause should be consist of one %s placeholder for each column being inserted, separated by commas and all within parentheses, like this: INSERT INTO t (a, b, c) VALUES (%s, %s, %s)  We can produce the desired string with string manipulation: # Create one placeholder per column inserted. placeholders = ', '.join(['%s'] * len(values[0])) # Wrap in parentheses. values_clause = f"""({placeholders})""" # Inject into the query string. isql = isql % values_clause with psycopg.connect(dbname='test') as conn, conn.cursor() as cur: cur.executemany(isql, values) conn.commit()  However psycopg provides tools for composing SQL statements, and it may be safer to use these tools rather than relying on string manipulation if your query building is very dynamic. Using these tools, you would have this (I've added the parentheses into the main query string this time, as there is no benefit in not doing so): placeholders = sql.SQL(', ').join(sql.Placeholder() * len(values[0])) isql = sql.SQL("""INSERT INTO t77716028 (type_, key_, a, b, c, d, e) VALUES ({placeholders}) ON CONFLICT (key_) DO UPDATE SET a = EXCLUDED.a, b = EXCLUDED.b, c = EXCLUDED.c, d = EXCLUDED.d, e = EXCLUDED.e""") isql = isql.format(placeholders=placeholders) with psycopg.connect(dbname='test') as conn, conn.cursor() as cur: print(f'{isql.as_string(conn)=}') cur.executemany(isql, values) conn.commit()
Question: Example Code import pandas as pd import seaborn as sns sns.set_style('white') s = pd.Series({'John': 7, 'Amy': 4, 'Elizabeth': 4, 'James': 4, 'Roy': 2}) color1 = ['orange', 'grey', 'grey','grey','grey'] ax1 = s.plot(kind='barh', color=color1, figsize=(6, 3), width=.8) ax1.invert_yaxis() ax1.bar_label(ax1.containers[0], labels=s.index, padding=-60, color='white', fontsize=12, fontweight='bold') ax1.bar_label(ax1.containers[0], padding=10, color='black', fontsize=8, fmt='{:.0f} times'.format, fontweight='bold') ax1.set_xticks([]) ax1.set_yticks([]) sns.despine(bottom=True, left=True)  How can I align the bar labels on the right side of the bar in the plot?  I am looking for a way to fix this using any of the following libraries: pandas, seaborn, or matplotlib.

Answer: Edit: You can patch Text manually to change the horizontal alignment and get a better result: labels = ax1.bar_label(ax1.containers[0], labels=s.index, padding=-5, color='white', fontsize=12, fontweight='bold') for label in labels: label.set_ha('right')  Output:   Old answer: You can use annotate to more precisely control what you want or use str.rjust to get labels of the same width. However, since you are not using a monospaced font, the result is approximate: zlabels = s.index.str.rjust(s.index.str.len().max()) ax1.bar_label(ax1.containers[0], labels=zlabels, padding=-65, color='white', fontsize=12, fontweight='bold')  Output:
Question: I would like to sort the data by the month however not alphabetically rather by the month order, i.e first the sales for January and then February etc, see the illustrated data I created month=['January','February','March','April','January','February','March','April'] sales=[10,100,130,145,13409,670,560,40] dict = {'month': month, 'sales': sales} df = pd.DataFrame(dict) df.groupby('month')['sales'].mean().sort_values()  in this case I received data by the sales average, however I would like to sort the value by the month order

Answer: Alternatively and probably slower, but just for posterity you can use lambda with map: month_order = {"January": 1, "February": 2, "March": 3, "April": 4} df = df.sort_values(by="month", key=lambda x: x.map(month_order), ignore_index=True)
Question: I have the following code which produces two plots in matplotlib. However, each I'm unable to remove this border in the second subplot despite feeding all these arguments. How can I remove the black border around the second subplot (see attached image) import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D beta, gamma = np.linspace(-np.pi / 2, np.pi / 2, 500), np.linspace(-np.pi / 2, np.pi / 2, 500) B, G = np.meshgrid(beta, gamma) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6)) # 2D Contour plot ax1.imshow(obj_vals.T, origin='lower', cmap='hot', extent=(-np.pi/2, np.pi/2, -np.pi/2, np.pi/2)) ax1.set_xlabel(r'$\gamma$') ax1.set_ylabel(r'$\beta$') ax1.set_xticks([]) ax1.set_yticks([]) ax2 = fig.add_subplot(122, projection='3d') # Make panes transparent ax2.xaxis.pane.fill = False # Left pane ax2.yaxis.pane.fill = False # Right pane ax2.zaxis.pane.fill = False # Right pane # Remove grid lines ax2.grid(False) # Remove tick labels ax2.set_xticklabels([]) ax2.set_yticklabels([]) ax2.set_zticklabels([]) # Transparent spines ax2.xaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax2.yaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax2.zaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax2.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax2.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) # No ticks ax2.set_xticks([]) ax2.set_yticks([]) ax2.set_zticks([]) # Surface plot surf = ax2.plot_surface(B, G, obj_vals.T, cmap='hot') plt.axis('off') plt.tight_layout() plt.show()  

Answer: I think the issue here is that you are creating a subplot with two 2D axes and then adding a 3D axis over the right 2D one. You have removed the splines for the 3D plot, but the original 2D plot that you originally made is still there. I think a better way to do this would be to create the figure and then the subplots individually, like what is shown on this documentation page. Then, you can also remove all the 3D axes components using ax.set_axis_off(), as per this answer. import matplotlib.pyplot as plt import numpy as np plt.close("all") x = np.linspace(-2*np.pi, 2*np.pi, 100) y = np.linspace(-2*np.pi, 2*np.pi, 100) X, Y = np.meshgrid(x, y) Z = np.sin(X)*np.cos(Y) fig = plt.figure(figsize=(12,6)) ax1 = fig.add_subplot(1, 2, 1) ax1.contourf(X, Y, Z, levels=100, cmap="hot") ax1.set_xlabel(r'$\gamma$') ax1.set_ylabel(r'$\beta$') ax1.set_xticks([]) ax1.set_yticks([]) ax2 = fig.add_subplot(1, 2, 2, projection="3d") ax2.plot_surface(X, Y, Z, cmap="hot", rstride=1, cstride=1) ax2.set_axis_off() plt.tight_layout() plt.show()
Question: in the question there will be a number taken from user. Up to that number, I want to find the sum of all numbers if the sum of that number's digits is odd. For example if the input is 13 then ; 1+3+5+7+9+10+12 = 47 should be the result. In order to prevent time limit exceed, question says "Since the answer might be too big, please print the answer in modulo 10^9+7" Constraints 1 ≤ n < 10^17 (n is input) Here is my code: MOD = 1000000007 def getSum(number): total = 0 while number > 0: total += number % 10 number //= 10 return (total % MOD) % 2 def sticker(number): stickerNeed = 0 for oneDigit in range(1, number): if (getSum(oneDigit % MOD) == 1): stickerNeed += oneDigit return stickerNeed % MOD number = int(input()) result = sticker(number) print(result % MOD)  But it still cannot handle the really big numbers and gives time limit exceed. Can you help me out? What wrong with my code?

Answer: Surely, brute force is not right way for given range. Instead think about the next: 1 3 5 7 9 10 12...18 21...29 30...98 100 102..108 111...199 201...999 1000 1002...  We can see that ever decade *0..*9 contains exactly 5 numbers with odd digit sum, but these numbers can start from *0 or from *1. Aslo note that every hundred *0..*99 contains five decades starting from 0, and five decades starting from 1 Let's separate the end of series after last *00 value for simplicity and calculate their sum using function like your sticker but with corrected mistakes (your function gives wrong results). Right function (not the fastest, but suitable for our purposes): def sumofOdds(a, b): result = 0 for i in range(a, b+1): t = i s = 0 while t: s += t%10 t //= 10 if s%2: result += i return result  For example, for input 231, calculate sum for range 200..231 as described above, and for 1..199 as described below But what about swarm of numbers before last *00? Sum of these numbers is sum of arithmetic progression of the sequence 0,2,4,...*98 plus addition of 25 * number of hundreds (because every hundred contains 5 decades starting from 1 and they give 25 additional units). Note - this is one-liner formula. Where to use MOD? In formula for arithmetic progression sum, after summation with 25 * number of hundreds, and after summation with "end of series" sum. But not in getSum and sticker I hope these ideas will be useful for your solution Test result: 46781934 #input 321669645 #by formula, calculated in microseconds 321669645 #by brute force, calculated in one minute  P.S. For range 10^17 we have to use modular aritmetics inside sumofOdds in languages without in-built support of big integers (Python works with such numbers well)  if s%2: result = (result + i) % MOD
Question: I'm following book on Tensorflow by Chris Mattman. Here is the code: import tensorflow as tf tf.disable_v1_behavior() def model(X, w): terms = [] for i in range(num_coeffs): #num_coeffs = 6 term = tf.multiply(w[i], tf.pow(X, i)) terms.append(term) return tf.add_n(terms) w = tf.Variable([0.]*num_coeffs, name="parameters") y_model = model(X, w) #X = tf.placeholder(tf.float32)  How do we multiply 0. by some value in the variable and get anything different from 0? It is to be polynomial regression model.

Answer: The parameter [0.]*num_coefs is the initial value of the tensorflow variable represented by w. Of course, when all coefficients are zero, the result of multiplying by those coefficients is zero. Th point of performing optimization with respect to some distance or loss metric (e.g. minimizing mean squared error) is that the variable will be updated to nonzero values that optimize the metric subject to the input and output data. Your code does not yet include an optimizer, so the variable won't be updated. Adding an optimizer will lead to the variable being updated to a nonzero vector, following some strategy depending on the selected optimizer.
Question: I have a function in Python makes a number of calculations and returns a float. I need to validate the float result is close (i.e. +/- 1) to one of 4 possible integers. For example the expected integers are 20, 50, 80, 100. If I have result = 19.808954 if would pass the validation test as it is with +/- 1 of 20 which is one of the expected results. Is there a concise way to do this test? My python math functions are basic.

Answer: any(abs(actual - expected) < 1 for expected in [20, 50, 80, 100]) # ^^^^^^^^^^^^^^^^^^^^^^^^^^  This checks if the underlined boolean expression is true for any of the expected values. any will return as soon as it finds a true value and return True or False accordingly. If you want to know which expected value it matches, change it to this: [expected for expected in [20, 50, 80, 100] if abs(actual - expected) < 1]  This will build a list of matching values:  If the list is empty, there was no match. If the list has one element, that's the match. In the edge case that there are multiple matches, the list will have multiple values. This could happen if the expected list had 19 and 20, say, with an input of 19.5.
Question: I'm using VS Code and I have followed the steps in the docs to set it up for Python development: https://code.visualstudio.com/docs/python/python-tutorial. But when trying to run a program I get the error:  can´t load the file C:\V\VSCode\Python.venv\Scripts\Activate.ps1 because script execution is disabled on this system. For more information, see the about_Execution_Policies.  Even though I get the error, the program runs fine. Python version: 3.12.1 VSCode version: 1.85.1 

Answer: Run the command get-executionpolicy to verify your execution policy setting. If you get Restricted, it means No scripts can be run and you can only use Windows PowerShell in interactive mode. If you get AllSigned, it means you can run only scripts that have been digitally signed by a trusted publisher. If you get RemoteSigned, it means you can run scripts that was created locally, but scripts that is downloaded must be digitally signed by a trusted publisher. If you get Unrestricted, then there are no restrictions at all. This allows you to run unsigned scripts from any source but will warn when a script has been downloaded from the Internet. To remove the restrictions, you can either run set-executionpolicy remotesigned (preferable) or set-executionpolicy unrestricted (if you're running as admin). After this, you can activate your virtual environment usingvenv\Scripts\activate. To get more information on Set-ExecutionPolicy, run get-help set-executionpolicy. See Setting the PowerShell Execution Policy for more.