qid
int64
469
74.7M
question
stringlengths
36
37.8k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
5
31.5k
response_k
stringlengths
10
31.6k
67,350,799
I have a JS function that is updating subsequent select boxes based on the previous input. I am populating these with responses from a Flask function that queries a database. The issue is that the second variable that holds an array cannot be processed properly. The first function works fine, but the second just has an undefinded variable. **JS Function** ```js function update(deptcity, destsets, datesets, dtimesets) { $.ajax({ url:"/returncity/?q="+deptcity, //the page containing python script type: "POST", //request type, dataType: 'json', data: JSON.stringify(deptcity) }) .then( function updateDest(destsets, datesets) { console.log(datesets) var dest = destsets.destsets; var select = document.getElementById("destination"); var length = select.options.length; for (i = length-1; i >= 0; i--) { select.options[i] = null; } var len = dest.length; for (i = len - 1; i >= 0; i--) { document.getElementById("destination").add(new Option(dest[i])); } }) .then( function updateDate(datesets) { console.log(datesets); var date = datesets; var select = document.getElementById("date"); var length = select.options.length; for (i = length - 1; i >= 0; i--) { select.options[i] = null; } var len = date.length; for (i = len - 1; i >= 0; i--) { document.getElementById("date").add(new Option(date[i])); } }) ; } ``` **Flask Function** ```py @views.route('/returncity/', methods = ['POST', 'GET']) @login_required def ajax_returncity(): if request.method == 'POST': q = [request.get_json('data')] query = '''SELECT DISTINCT destination FROM Journey WHERE depart = ? ORDER BY destination ASC''' con = sqlite3.connect('Coach\database.db') cur = con.cursor() cur.execute(query, q) destrows = cur.fetchall() query = '''SELECT DISTINCT date FROM Journey WHERE depart = ? ORDER BY date ASC''' con = sqlite3.connect('Coach\database.db') cur = con.cursor() cur.execute(query, q) daterows = cur.fetchall() query = '''SELECT DISTINCT dtime FROM Journey WHERE depart = ? ORDER BY dtime ASC''' con = sqlite3.connect('Coach\database.db') cur = con.cursor() cur.execute(query, q) dtimerows = cur.fetchall() cur.close() con.close() destrow = [] for i in destrows: for x in i: destrow.append(str(x)) daterow = [] for i in daterows: for x in i: daterow.append(str(x)) print(daterow) dtimerow = [] for i in dtimerows: for x in i: dtimerow.append(str(x)) return jsonify(destsets = destrow, datesets = daterow, dtimesets = dtimerow) ``` I tried passing the variable through the first function to see if it would be accepted but it didn't. The first function has it set to a string 'success'. The second function returns 'undefined'. Thanks in advance for any help.
2021/05/01
[ "https://Stackoverflow.com/questions/67350799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15804635/" ]
One pandaic way is to perform a pandas dot product with the column headers: ``` df['CombinedString'] = df.dot(df.columns+',').str.rstrip(',') df Male Over18 Single CombinedString 0 0 0 1 Single 1 1 1 1 Male,Over18,Single 2 0 0 1 Single ```
Another method would be to use `.stack()` and `groupby.agg()` ``` df['CombinedString'] = df.mask(df.eq(0)).stack().reset_index(1)\ .groupby(level=0)['level_1'].agg(','.join) print(df) Male Over18 Single CombinedString 0 0 0 1 Single 1 1 1 1 Male,Over18,Single 2 0 0 1 Single ```
59,545,845
I'm coming back to python and having trouble with import paths. Can someone explain the logic, or a better way of doing this? If I have a class called `Sentence` in structure like ``` base.py models/Sentence.py ``` then inside `base.py` ``` import models.Sentence ``` why do I still have to do ``` s = models.Sentence.Sentence('arg') ``` I can't seem to fix it on import either ``` import models.Sentence as Sentence # ok but no help import models.Sentence.Sentence as Sentence # illegal and weird ``` I realize there's some magic I can do within the `__init__` module file, but that seems like a magic hack. It seems very odd to have to refer to the whole filepath each time I create a class instance so I'd like to know what I'm doing wrong. JS' explicit export and imports seem much clearer.
2019/12/31
[ "https://Stackoverflow.com/questions/59545845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1146785/" ]
What I think you were looking for was a `For /D` loop with a standard nested `For` loop: ```bat @For /D %%I In ("Parent Folder\*")Do @(For %%J In ("%%I\*.jpg")Do @Echo %%~nxJ)>"%%I\%%~nxI.txt" ```
Yes, I see that you already have an answer. Yes, Compo does some most excellent work and I am sure it will work for you. Some day, someone might need to maintain or modify this script. Finding someone who understands all of the `%%~...` cryptology might not be easy. It might be easier to find someone who knows PowerShell; Microsoft's stated strategy for the future. If you are on a supported Windows system, PowerShell will be available. ``` $baseDir = 'C:/src/t' $filenamePattern = '*.jpg' Get-ChildItem -Directory -Path $baseDir | ForEach-Object { $newFile = Join-Path -Path $_.FullName -ChildPath ($_.BaseName + '.txt') if (Test-Path -Path $newFile) { Remove-item -Path $newFile } Get-ChildItem -File -Path $_.FullName -Filter $filenamePattern | ForEach-Object { $_.Name | Out-File -FilePath $newFile -Append -WhatIf } } ```
59,743,602
In my analysis script I noticed some weird behaviour (guess it's intended though) with the copying of arrays in Python. If I have a 2D-array `A`, create another array `B` with entries from `A` and then normalize `B` with the length of `A`'s first dimension, the entries in `A` change in a strange way. I can reproduce the problem with the following code: ```py foo = np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) startIndex = 1 print(foo) for it, i in enumerate(foo): if not it: sum = i[startIndex:] else: sum += i[startIndex:] print(foo) sum /= foo.shape[0] print(foo) ``` The output is: ```py [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]] [[ 1. 15. 18.] [ 4. 5. 6.] [ 7. 8. 9.]] [[1. 5. 6.] [4. 5. 6.] [7. 8. 9.]] ``` The shape of the array doesn't matter but this 3x3 form shows it quite good. I guess that `sum = i[startIndex:]` somehow sets a reference to the last two entries of `foo[0]` and changes to `sum` also effect those entries - but according to [this question](https://stackoverflow.com/questions/19951816/python-changes-to-my-copy-variable-affect-the-original-variable) I guessed I would get a copy instead of the reference. What is the proper way to get a copy of only a part of the array?
2020/01/15
[ "https://Stackoverflow.com/questions/59743602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12714200/" ]
You should use *input* event to make the immediate changes to output the result. ***I will think of the solution in a different approach than yours.*** First you can target all the inputs with class *formA* and *formB* using [`querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll). Then loop through them to attach the event (*input*) using [`forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) and [`addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener). Inside the event handler function you can target only specific inputs related to the current element. You can find the sum of them using [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and [`reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce). Finally store the sum in the relevant element. ```js var inputs = document.querySelectorAll('.formA, .formB'); Array.from(inputs).forEach(function(el){ el.addEventListener('input', function(){ var group = this.closest('div').querySelectorAll('[class^=form]'); var sum = Array.from(group).map(i => Number(i.value)).reduce((a,c) => a+c,0); this.closest('div').querySelector('[name=total]').value = sum; }); }); ``` ```html <form id="forms"> <div class="form-a"> <p>Form A</p> input1 : <input class="formA form-1" type="text" name="qty1"/><br> input2 : <input class="formA form-2" type="text" name="qty2"/><br> input3 (total) : <input class="total-1" type="text" name="total" id="total"/> </div> <hr> <div class="form-b"> <p>Form B</p> input4 : <input class="formB form-3" type="text" name="qty3"/><br> input5 : <input class="formB form-4" type="text" name="qty4"/><br> input6 (total) : <input type="text" name="total" id="total2"/> </div> <input type="reset" value="Reset"> </form> ```
I think you can't do it by that way because you update the value property by JavaScript which is not "**by a user**" so the event is not fired as desired. But in order to achieve what you wanted, you can look through [this link](https://stackoverflow.com/questions/42427606/event-when-input-value-is-changed-by-javascript). They describe many ways to overcome the problem. And then one of the most common is to directly modify the **input4 value** after the you have modify the **input3 one** by this way `... result.value = sum; $('.form-3').val(sum);`
26,368,113
Im trying to have interchangeable config files and I'm using py.test to send the testing suite to the cloud. The following works when I run them locally using `python main.py --site site1` in the terminal. I'm trying to figure out how I can add cli arguments so that it will work with py.test I have 3 files. main, config, and site1\_config main.py ``` if __name__ == "__main__": parser = argparse.ArgumentParser(description='CLI tests for an environment') parser.add_argument('--site', nargs='?', help='the site to use for the config') parser.add_argument('unittest_args', nargs='*') #Get our property args = parser.parse_args() if args.site: config.localizeConfig(args.site) sys.argv[1:] = args.unittest_args unittest.main(verbosity = 2) ``` config.py ``` def localizeConfig(site): localizedConfig = __import__(site+'_config'); # localizedConfig = __import__(site); #print dir(localizedConfig) props = filter(lambda a: not a.startswith('__'), dir(localizedConfig)) #Iterate over each property and set it on the config for prop in props: if prop != 'os' and prop != 'sys' and prop != 'webdriver': globals()[prop] = getattr(localizedConfig, prop) host_url = www.google.com ``` site1\_config.py ``` host_url = www.yahoo.com ``` Im trying to set a flag so that when `py.test -n6 --boxed main.py site1` is run, the site1\_config.py will copy over its contents into config.py I'm not sure how I can get this to work with py.test usage: py.test [options] [file\_or\_dir] [file\_or\_dir] [...] py.test: error: unrecognized arguments:
2014/10/14
[ "https://Stackoverflow.com/questions/26368113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3375657/" ]
1. Fix the obvious sql syntax error. 2. `userId` is the name you gave to your column dont use username you're just going to confuse your self 3. I suggest you use call it `$_SESSION['userId']` and use `session_start()` before using it. 4. No need for Sessions use `$_POST` directly! 5. If a key is an array, don't implode it, loop through it ``` try{ $conn = new PDO('mysql:dbname=Application;host=localhost;charset=utf8mb4', 'user', 'xxxx'); $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = 'INSERT INTO Answer (userId, qId, answer) VALUES (:userId, :qId, :answer)'; $stmt = $conn->prepare($sql); foreach ($_POST as $key => $value) { if (!is_array($_POST[$key])){ $stmt->execute(array(':userId' => $_SESSION['userId'], ':qId' => $key, ':answer' => $value)); } else{ foreach ($_POST[$key] as $sub_key => $sub_value) { $stmt->execute(array(':userId' => $_SESSION['userId'], ':qId' => $sub_key, ':answer' => $sub_value)); } } } } catch(PDOException $e) { echo 'Exception -> '; var_dump($e->getMessage()); } ``` --- **Some debugging tips:** * `0` is the equivalent to null for int * use `print_r($_POST)` or `print_r($_SESSION)` * `error_log` is helpful, use it to log the variables you are inserting
Correct this statement ``` $stmt = $conn->prepare('INSERT INTO Answer (userId, qId, answer) VALUES (userId = :username, qId = :qId, answer = :answer)'); ``` to ``` $stmt = $conn->prepare('INSERT INTO Answer (userId, qId, answer) VALUES (:username, :qId, :answer)'); ```
38,475,578
I'm trying to create an output that would look something like this: [![enter image description here](https://i.stack.imgur.com/Ndu4b.png)](https://i.stack.imgur.com/Ndu4b.png) As can be seeing in here, the left column spaces are lined up to the left and the right column is lined up from the right side. But for my output, I am getting left column lined up to the right side and right column lined up to the left. I want to do vice versa. Here is the output of what I am actually getting out of my second code where I have tried to use the format function: [![enter image description here](https://i.stack.imgur.com/rTNuT.png)](https://i.stack.imgur.com/rTNuT.png) It works but I am just trying to learn adjusting and formatting spacing when the string output moves. It would also be nice to know how to do it if I were to have more than 3 variables. ``` print("Kilograms Pounds") for kg in range(0, 199): kg += 1 lb = 2.2 lb = kg * lb lb = round(lb, 2) print(format(kg, "4d"), end = '') for i in range(1, 2): print(" ", lb, end = '') print() ``` Here is my initial code where I attempted to do that but the spacing is screwed up but the left column in here lies perfectly fine, but the spacing can be seeing on the right side after the output increases to double digits. ``` print("Kilograms Pounds") for kg in range(0, 199): kg += 1 lb = 2.2 lb = kg * lb print(kg, ' ', round(lb, 2)) ``` Output: [![enter image description here](https://i.stack.imgur.com/I08rW.png)](https://i.stack.imgur.com/I08rW.png) I'm new to python so still a complete noob. I would really appreciate the explanation of how to deal with format or weather there is alternatives to it. Thank you! Code:
2016/07/20
[ "https://Stackoverflow.com/questions/38475578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5117813/" ]
Give this a try: ``` between = ' '*4 print('Kilograms{between}Pounds'.format(between=between)) for kg in range(199): kg += 1 lb = 2.2 lb = kg * lb lb = round(lb, 2) print('{kg:<{kg_width}}{between}{lb:>{lb_width}}'.format( kg=kg, kg_width=len('Kilograms'), between=between, lb=lb, lb_width=len('Pounds'))) # Output: # Kilograms Pounds # 1 2.2 # 2 4.4 # 3 6.6 # 4 8.8 # 5 11.0 # 6 13.2 # 7 15.4 # 8 17.6 # 9 19.8 # 10 22.0 # 11 24.2 # ... ``` The big gnarly print is just because I tried to parameterize everything. Given the fixed column names and spacing, you could just do this: ``` print('{kg:<9} {lb:>6}'.format(kg=kg, lb=lb)) ``` **EDIT** Closer to your original code: ``` print("Kilograms Pounds") for kg in range(0, 199): kg += 1 lb = 2.2 lb = kg * lb lb = round(lb, 2) print(format(kg, "<4d"), end = '') print(" ", end = '') print(format(lb, ">7.1f")) ```
You can use this one. ``` print("Kilograms Pounds") for kg in range(0, 100): kg += 1 lb = 2.2 lb = kg * lb space_filler = " " * 10 print("%3d %s %.2f" % (kg, space_filler, lb)) ``` The value 3 can also be made dynamic by use `format` which is more flexible than `%` construct.
38,475,578
I'm trying to create an output that would look something like this: [![enter image description here](https://i.stack.imgur.com/Ndu4b.png)](https://i.stack.imgur.com/Ndu4b.png) As can be seeing in here, the left column spaces are lined up to the left and the right column is lined up from the right side. But for my output, I am getting left column lined up to the right side and right column lined up to the left. I want to do vice versa. Here is the output of what I am actually getting out of my second code where I have tried to use the format function: [![enter image description here](https://i.stack.imgur.com/rTNuT.png)](https://i.stack.imgur.com/rTNuT.png) It works but I am just trying to learn adjusting and formatting spacing when the string output moves. It would also be nice to know how to do it if I were to have more than 3 variables. ``` print("Kilograms Pounds") for kg in range(0, 199): kg += 1 lb = 2.2 lb = kg * lb lb = round(lb, 2) print(format(kg, "4d"), end = '') for i in range(1, 2): print(" ", lb, end = '') print() ``` Here is my initial code where I attempted to do that but the spacing is screwed up but the left column in here lies perfectly fine, but the spacing can be seeing on the right side after the output increases to double digits. ``` print("Kilograms Pounds") for kg in range(0, 199): kg += 1 lb = 2.2 lb = kg * lb print(kg, ' ', round(lb, 2)) ``` Output: [![enter image description here](https://i.stack.imgur.com/I08rW.png)](https://i.stack.imgur.com/I08rW.png) I'm new to python so still a complete noob. I would really appreciate the explanation of how to deal with format or weather there is alternatives to it. Thank you! Code:
2016/07/20
[ "https://Stackoverflow.com/questions/38475578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5117813/" ]
Give this a try: ``` between = ' '*4 print('Kilograms{between}Pounds'.format(between=between)) for kg in range(199): kg += 1 lb = 2.2 lb = kg * lb lb = round(lb, 2) print('{kg:<{kg_width}}{between}{lb:>{lb_width}}'.format( kg=kg, kg_width=len('Kilograms'), between=between, lb=lb, lb_width=len('Pounds'))) # Output: # Kilograms Pounds # 1 2.2 # 2 4.4 # 3 6.6 # 4 8.8 # 5 11.0 # 6 13.2 # 7 15.4 # 8 17.6 # 9 19.8 # 10 22.0 # 11 24.2 # ... ``` The big gnarly print is just because I tried to parameterize everything. Given the fixed column names and spacing, you could just do this: ``` print('{kg:<9} {lb:>6}'.format(kg=kg, lb=lb)) ``` **EDIT** Closer to your original code: ``` print("Kilograms Pounds") for kg in range(0, 199): kg += 1 lb = 2.2 lb = kg * lb lb = round(lb, 2) print(format(kg, "<4d"), end = '') print(" ", end = '') print(format(lb, ">7.1f")) ```
Check out [The Docs](https://docs.python.org/3.1/library/string.html#string.Formatter.vformat) Section 7.1.3.1 You can pass `format()` a `width` as int, which should take care of your whitespace problem. From the Documentation Example: ``` >>> for num in range(5,12): for base in 'dXob': print('{0:{width}{base}}'.format(num, base=base, width=width),end=' ') ``` produces: ``` 5 5 5 101 6 6 6 110 7 7 7 111 8 8 10 1000 9 9 11 1001 10 A 12 1010 11 B 13 1011 ```
46,763,472
I'm integrating the [Facebook SDK for JavaScript](https://developers.facebook.com/docs/javascript) into my Python Flask web application. I want the ability to access a logged in user's Facebook *id* server-side. My current approach is to build a form containing a hidden input which stores the id and submit it when the user logs in: ``` <script> function sendToBackEnd(){ FB.getLoginStatus(function(response){ if (response.status == 'connected'){ $form = $('<form>', {'action': '/process_form', 'method': 'POST'}).appendTO('body'); FB.api('/me', function(response){ $('<input>', {'class': 'hidden', 'name': 'FB_id', 'value': response.id}).appendTo($form); }); } }); } </script> <div class="fb-login-button" onlogin="sendToBackEnd"></div> ``` Then store that id in the flask `session` object: ``` @app.route('/process', methods=['GET', 'POST']) def process(): session['FB_id'] = request.form['FB_id'] print("User's Facebook id now accessible across all routes server-side!") return redirect(url_for('index')) ``` Is there a better approach here or is submitting a hidden form the only way to pass this data from client to server-side? Just a thought... I noticed there's a parameter in the [FB.init()](https://developers.facebook.com/docs/javascript/reference/FB.init/v2.10) method called `cookie` which is a described as, "Inidcates whether a cookie is created for the session. If enabled, it can be accessed by server-side code." I'm pretty sure the flask session object can't be modified client-side (rightfully so), but maybe this separate cookie can be assessed server-side in my python code?
2017/10/16
[ "https://Stackoverflow.com/questions/46763472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6611672/" ]
Include your all layout in your main layout and make `visibility GONE` for all other layout. And based on button click you can display any particular layout based on layout ID. Sample xml is as below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <!-- main layout for first time loading activity--> <LinearLayout android:id="@+id/layout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <!-- Display layout based on button click--> <LinearLayout android:visibility="gone" android:id="@+id/layout2" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <!-- Display layout based on button click--> <LinearLayout android:visibility="gone" android:id="@+id/layout3" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <!-- Display layout based on button click--> <LinearLayout android:visibility="gone" android:id="@+id/layout4" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> </LinearLayout> ```
You can not provide more than one layout to any activity, but if you want to use the different layout files in one activity than you can include all layout files into a single layout file using tag and use them in you activity.
46,763,472
I'm integrating the [Facebook SDK for JavaScript](https://developers.facebook.com/docs/javascript) into my Python Flask web application. I want the ability to access a logged in user's Facebook *id* server-side. My current approach is to build a form containing a hidden input which stores the id and submit it when the user logs in: ``` <script> function sendToBackEnd(){ FB.getLoginStatus(function(response){ if (response.status == 'connected'){ $form = $('<form>', {'action': '/process_form', 'method': 'POST'}).appendTO('body'); FB.api('/me', function(response){ $('<input>', {'class': 'hidden', 'name': 'FB_id', 'value': response.id}).appendTo($form); }); } }); } </script> <div class="fb-login-button" onlogin="sendToBackEnd"></div> ``` Then store that id in the flask `session` object: ``` @app.route('/process', methods=['GET', 'POST']) def process(): session['FB_id'] = request.form['FB_id'] print("User's Facebook id now accessible across all routes server-side!") return redirect(url_for('index')) ``` Is there a better approach here or is submitting a hidden form the only way to pass this data from client to server-side? Just a thought... I noticed there's a parameter in the [FB.init()](https://developers.facebook.com/docs/javascript/reference/FB.init/v2.10) method called `cookie` which is a described as, "Inidcates whether a cookie is created for the session. If enabled, it can be accessed by server-side code." I'm pretty sure the flask session object can't be modified client-side (rightfully so), but maybe this separate cookie can be assessed server-side in my python code?
2017/10/16
[ "https://Stackoverflow.com/questions/46763472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6611672/" ]
Include your all layout in your main layout and make `visibility GONE` for all other layout. And based on button click you can display any particular layout based on layout ID. Sample xml is as below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <!-- main layout for first time loading activity--> <LinearLayout android:id="@+id/layout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <!-- Display layout based on button click--> <LinearLayout android:visibility="gone" android:id="@+id/layout2" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <!-- Display layout based on button click--> <LinearLayout android:visibility="gone" android:id="@+id/layout3" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <!-- Display layout based on button click--> <LinearLayout android:visibility="gone" android:id="@+id/layout4" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> </LinearLayout> ```
``` <include layout="@layout/titlebar"/> ``` titlebar is different layout ``` <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/titlebar_bg" tools:showIn="@layout/activity_main" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/gafricalogo" /> ``` include in main layout like this.. ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/app_bg" android:gravity="center_horizontal"> <include layout="@layout/titlebar"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/hello" android:padding="10dp" /></LinearLayout> ```
46,763,472
I'm integrating the [Facebook SDK for JavaScript](https://developers.facebook.com/docs/javascript) into my Python Flask web application. I want the ability to access a logged in user's Facebook *id* server-side. My current approach is to build a form containing a hidden input which stores the id and submit it when the user logs in: ``` <script> function sendToBackEnd(){ FB.getLoginStatus(function(response){ if (response.status == 'connected'){ $form = $('<form>', {'action': '/process_form', 'method': 'POST'}).appendTO('body'); FB.api('/me', function(response){ $('<input>', {'class': 'hidden', 'name': 'FB_id', 'value': response.id}).appendTo($form); }); } }); } </script> <div class="fb-login-button" onlogin="sendToBackEnd"></div> ``` Then store that id in the flask `session` object: ``` @app.route('/process', methods=['GET', 'POST']) def process(): session['FB_id'] = request.form['FB_id'] print("User's Facebook id now accessible across all routes server-side!") return redirect(url_for('index')) ``` Is there a better approach here or is submitting a hidden form the only way to pass this data from client to server-side? Just a thought... I noticed there's a parameter in the [FB.init()](https://developers.facebook.com/docs/javascript/reference/FB.init/v2.10) method called `cookie` which is a described as, "Inidcates whether a cookie is created for the session. If enabled, it can be accessed by server-side code." I'm pretty sure the flask session object can't be modified client-side (rightfully so), but maybe this separate cookie can be assessed server-side in my python code?
2017/10/16
[ "https://Stackoverflow.com/questions/46763472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6611672/" ]
Include your all layout in your main layout and make `visibility GONE` for all other layout. And based on button click you can display any particular layout based on layout ID. Sample xml is as below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <!-- main layout for first time loading activity--> <LinearLayout android:id="@+id/layout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <!-- Display layout based on button click--> <LinearLayout android:visibility="gone" android:id="@+id/layout2" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <!-- Display layout based on button click--> <LinearLayout android:visibility="gone" android:id="@+id/layout3" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <!-- Display layout based on button click--> <LinearLayout android:visibility="gone" android:id="@+id/layout4" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> </LinearLayout> ```
You can use Fragments for this. Simply , declare one FrameLayout in your Main Activity Layout. And create Fragments for each layout you want. Now, you can switch layouts using Fragment Manager. Refer this for more details : [Here](http://www.cs.dartmouth.edu/~campbell/cs65/lecture09/lecture09.html) Hope it Helps !!
46,763,472
I'm integrating the [Facebook SDK for JavaScript](https://developers.facebook.com/docs/javascript) into my Python Flask web application. I want the ability to access a logged in user's Facebook *id* server-side. My current approach is to build a form containing a hidden input which stores the id and submit it when the user logs in: ``` <script> function sendToBackEnd(){ FB.getLoginStatus(function(response){ if (response.status == 'connected'){ $form = $('<form>', {'action': '/process_form', 'method': 'POST'}).appendTO('body'); FB.api('/me', function(response){ $('<input>', {'class': 'hidden', 'name': 'FB_id', 'value': response.id}).appendTo($form); }); } }); } </script> <div class="fb-login-button" onlogin="sendToBackEnd"></div> ``` Then store that id in the flask `session` object: ``` @app.route('/process', methods=['GET', 'POST']) def process(): session['FB_id'] = request.form['FB_id'] print("User's Facebook id now accessible across all routes server-side!") return redirect(url_for('index')) ``` Is there a better approach here or is submitting a hidden form the only way to pass this data from client to server-side? Just a thought... I noticed there's a parameter in the [FB.init()](https://developers.facebook.com/docs/javascript/reference/FB.init/v2.10) method called `cookie` which is a described as, "Inidcates whether a cookie is created for the session. If enabled, it can be accessed by server-side code." I'm pretty sure the flask session object can't be modified client-side (rightfully so), but maybe this separate cookie can be assessed server-side in my python code?
2017/10/16
[ "https://Stackoverflow.com/questions/46763472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6611672/" ]
Include your all layout in your main layout and make `visibility GONE` for all other layout. And based on button click you can display any particular layout based on layout ID. Sample xml is as below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <!-- main layout for first time loading activity--> <LinearLayout android:id="@+id/layout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <!-- Display layout based on button click--> <LinearLayout android:visibility="gone" android:id="@+id/layout2" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <!-- Display layout based on button click--> <LinearLayout android:visibility="gone" android:id="@+id/layout3" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <!-- Display layout based on button click--> <LinearLayout android:visibility="gone" android:id="@+id/layout4" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> </LinearLayout> ```
No, you can't use multiple `setContentView()` in to single activity. if you just want to add the other xml layouts to another. you can use the `<include>` tag. Example: **layout\_one.xml:** ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="This is layout one"/> </LinearLayout> ``` **layout\_two.xml:** ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="This is layout two"/> </LinearLayout> ``` **activity\_main.xml:** ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent"> <include layout="@layout/layout_one">/> <include layout="@layout/layout_two">/> </LinearLayout> ```
39,321,351
I have a list of files, using command in python `from filename import *` , works for a single file as I am giving the exact name of the file, but if I want to use it as `from list[i] import *` to iterate over a list and importing function from files one after the another to work on it, it doesn't work? what changes should I make so as to use it for a list of files, so that I can easily iterate?
2016/09/04
[ "https://Stackoverflow.com/questions/39321351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5347334/" ]
Use [importlib](https://docs.python.org/3/library/importlib.html#importlib.import_module) for that: ``` from importlib import import_module module_list = [import_module("test.mod{}".format(i)) for i in range(20)] # OR module_list = [] for i in range(20): module_list.append(import_module("test.mod{}".format(i))) ``` As stated by the [documentation](https://docs.python.org/3/library/functions.html#__import__), **do not use internal things such as `__import__`**.
If you're looking for dynamic imports, you're looking for the `__import__` function. ``` for modl in ('foo', 'bar', 'baz', 'bat',): __import__('parent.' + modl) ```
35,292,982
I'n trying to match a string with the following different combinations using python (here x's are digits of lenght 4) ``` W|MON-FRI|xxxx-xxxx W|mon-fri|xxxx-xxxx W|MON-THU,SAT|xxxx-xxxx W|mon-thu,sat|xxxx-xxxx W|MON|xxxx-xxxx ``` Here the first part and the last is static, second part is can have any of the combinations as shown above, like sometime the days were separated by ',' or '-'. I'm a newbie to Regular Expressions, I was googled on how regular expressions works, I can able to do the RE for bits & pieces of above expressions like matching the last part with `re.compile('(\d{4})-(\d{4})$')` and the first part with `re.compile('[w|W]')`. I tried to match the 2nd part but couldn't succeeded with ``` new_patt = re.compile('(([a-zA-Z]{3}))([,-]?)(([a-zA-Z]{3})?)) ``` How can I achieve this?
2016/02/09
[ "https://Stackoverflow.com/questions/35292982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5903241/" ]
I am going to have a quick punt here and say it is probably something to do with 32-bit vs 64-bit powershell. If I run Add-PSSnapinicrosoft.TeamFoundation.PowerShell from normal 64-bit powershell fine. But if I run it from C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell\_ise.exe I get the above exception. I am going to go ahead and say that the build server is a 32-bit application and there for starting a 32-bit runtime. Not really sure what the fix is exactly but maybe the following will point you in the right direction. [PowerShell (2.0, 32-bit) can't load TFS 2010 snap-in... except when it can](https://stackoverflow.com/questions/20575915/powershell-2-0-32-bit-cant-load-tfs-2010-snap-in-except-when-it-can) <https://social.msdn.microsoft.com/Forums/en-US/a116799a-0476-4c42-aa3e-45d8ba23739e/tfs-power-tools-2008-powershell-snapin-wont-run-in-on-64bit-in-windows-2008-r2?forum=tfspowertools>
For me it was another issue because I was trying to use Power Tools with only Visual Studio 2017 Pro installed. For Visual Studio 2017 they didn't released `Microsoft Team Foundation Server 2017 Power Tools`. They are saying that the previous version it should work with any higher version of Visual Studio that has TFS. The problem is that if you have only Visual Studio 2017 installed you will not be able to install `Microsoft Team Foundation Server 2015 Power Tools` for example, because having Visual Studio 2015 (any version) installed is a requirement for installing `Microsoft Team Foundation Server 2015 Power Tools`. In other words I had to install `Visual Sudio 2015` then install `Microsoft Team Foundation Server 2015 Power Tools` and then `Add-PSSnapin Microsoft.TeamFoundation.PowerShell` worked. Please refer also to this: <https://developercommunity.visualstudio.com/content/problem/103642/team-foundation-server-2015-power-tools-install-is.html> Hopefully this would help somebody.
35,292,982
I'n trying to match a string with the following different combinations using python (here x's are digits of lenght 4) ``` W|MON-FRI|xxxx-xxxx W|mon-fri|xxxx-xxxx W|MON-THU,SAT|xxxx-xxxx W|mon-thu,sat|xxxx-xxxx W|MON|xxxx-xxxx ``` Here the first part and the last is static, second part is can have any of the combinations as shown above, like sometime the days were separated by ',' or '-'. I'm a newbie to Regular Expressions, I was googled on how regular expressions works, I can able to do the RE for bits & pieces of above expressions like matching the last part with `re.compile('(\d{4})-(\d{4})$')` and the first part with `re.compile('[w|W]')`. I tried to match the 2nd part but couldn't succeeded with ``` new_patt = re.compile('(([a-zA-Z]{3}))([,-]?)(([a-zA-Z]{3})?)) ``` How can I achieve this?
2016/02/09
[ "https://Stackoverflow.com/questions/35292982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5903241/" ]
I had this issue and to solve I notice that by default the cmdlets are not added during the PowerTools installation. You need to run a full install to make it work. I posted here some pictures: <https://fabiostawinski.wordpress.com/2016/07/11/the-windows-powershell-snap-in-microsoft-teamfoundation-powershell-is-not-installed-on-this-computer/>
For me it was another issue because I was trying to use Power Tools with only Visual Studio 2017 Pro installed. For Visual Studio 2017 they didn't released `Microsoft Team Foundation Server 2017 Power Tools`. They are saying that the previous version it should work with any higher version of Visual Studio that has TFS. The problem is that if you have only Visual Studio 2017 installed you will not be able to install `Microsoft Team Foundation Server 2015 Power Tools` for example, because having Visual Studio 2015 (any version) installed is a requirement for installing `Microsoft Team Foundation Server 2015 Power Tools`. In other words I had to install `Visual Sudio 2015` then install `Microsoft Team Foundation Server 2015 Power Tools` and then `Add-PSSnapin Microsoft.TeamFoundation.PowerShell` worked. Please refer also to this: <https://developercommunity.visualstudio.com/content/problem/103642/team-foundation-server-2015-power-tools-install-is.html> Hopefully this would help somebody.
45,364,343
I learn python on Ubuntu system. There were errors shen I tried to read a file . ``` fw = open(outfile,"a") outfile = 'sougou/Reduced/C000008_pre.txt' IOError: [Errno 2] No such file or directory: 'sougou/Reduced/C000008_pre.txt' ```
2017/07/28
[ "https://Stackoverflow.com/questions/45364343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8341625/" ]
Without any additional information, I can see two possibilities here. 1. The file you are trying to access doesn't exist. 2. The path to the file is not correct *relative to the location you are calling your Python script from.* Try providing the absolute path to the file, and see if that fixes your issue: ``` outfile = '/some/path/here/sougou/Reduced/C000008_pre.txt' ```
1. Maybe file `sougou/Reduced/C000008_pre.txt` does not exist 2. The script does not be put in directory which contains `sougou` directory 3. You should close file after open: `fw.close()` or using `with open(outfile,"a") as fw:` is better
27,623,919
**Update**: Weighted samples are now supported by `scipy.stats.gaussian_kde`. See [here](https://stackoverflow.com/questions/27623919/weighted-gaussian-kernel-density-estimation-in-python/27623920#27623920) and [here](https://github.com/scipy/scipy/pull/8991) for details. It is currently not possible to use `scipy.stats.gaussian_kde` to estimate the density of a random variable based on [weighted samples](http://en.wikipedia.org/wiki/Sampling_%28statistics%29#Survey_weights). What methods are available to estimate densities of continuous random variables based on weighted samples?
2014/12/23
[ "https://Stackoverflow.com/questions/27623919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1150961/" ]
Neither [`sklearn.neighbors.KernelDensity`](http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KernelDensity.html#sklearn.neighbors.KernelDensity) nor [`statsmodels.nonparametric`](http://statsmodels.sourceforge.net/stable/nonparametric.html) seem to support weighted samples. I modified `scipy.stats.gaussian_kde` to allow for heterogeneous sampling weights and thought the results might be useful for others. An example is shown below. ![example](https://i.stack.imgur.com/bc5Xv.png) An `ipython` notebook can be found here: <http://nbviewer.ipython.org/gist/tillahoffmann/f844bce2ec264c1c8cb5> Implementation details ====================== The weighted arithmetic mean is ![weighted arithmetic mean](https://i.stack.imgur.com/zZ7n2.png) The [unbiased data covariance matrix](http://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Weighted_sample_covariance) is then given by ![unbiased covariance matrix](https://i.stack.imgur.com/zs4Cm.png) The bandwidth can be chosen by `scott` or `silverman` rules as in `scipy`. However, the number of samples used to calculate the bandwidth is [Kish's approximation for the effective sample size](http://surveyanalysis.org/wiki/Design_Effects_and_Effective_Sample_Size#Kish.27s_approximate_formula_for_computing_effective_sample_size).
Check out the packages PyQT-Fit and statistics for Python. They seem to have kernel density estimation with weighted observations.
27,623,919
**Update**: Weighted samples are now supported by `scipy.stats.gaussian_kde`. See [here](https://stackoverflow.com/questions/27623919/weighted-gaussian-kernel-density-estimation-in-python/27623920#27623920) and [here](https://github.com/scipy/scipy/pull/8991) for details. It is currently not possible to use `scipy.stats.gaussian_kde` to estimate the density of a random variable based on [weighted samples](http://en.wikipedia.org/wiki/Sampling_%28statistics%29#Survey_weights). What methods are available to estimate densities of continuous random variables based on weighted samples?
2014/12/23
[ "https://Stackoverflow.com/questions/27623919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1150961/" ]
Neither [`sklearn.neighbors.KernelDensity`](http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KernelDensity.html#sklearn.neighbors.KernelDensity) nor [`statsmodels.nonparametric`](http://statsmodels.sourceforge.net/stable/nonparametric.html) seem to support weighted samples. I modified `scipy.stats.gaussian_kde` to allow for heterogeneous sampling weights and thought the results might be useful for others. An example is shown below. ![example](https://i.stack.imgur.com/bc5Xv.png) An `ipython` notebook can be found here: <http://nbviewer.ipython.org/gist/tillahoffmann/f844bce2ec264c1c8cb5> Implementation details ====================== The weighted arithmetic mean is ![weighted arithmetic mean](https://i.stack.imgur.com/zZ7n2.png) The [unbiased data covariance matrix](http://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Weighted_sample_covariance) is then given by ![unbiased covariance matrix](https://i.stack.imgur.com/zs4Cm.png) The bandwidth can be chosen by `scott` or `silverman` rules as in `scipy`. However, the number of samples used to calculate the bandwidth is [Kish's approximation for the effective sample size](http://surveyanalysis.org/wiki/Design_Effects_and_Effective_Sample_Size#Kish.27s_approximate_formula_for_computing_effective_sample_size).
For univariate distributions you can use `KDEUnivariate` from [statsmodels](http://www.statsmodels.org/stable/generated/statsmodels.nonparametric.kde.KDEUnivariate.html#statsmodels.nonparametric.kde.KDEUnivariate). It is not well documented, but the `fit` methods accepts a `weights` argument. Then you cannot use FFT. Here is an example: ``` import matplotlib.pyplot as plt from statsmodels.nonparametric.kde import KDEUnivariate kde1= KDEUnivariate(np.array([10.,10.,10.,5.])) kde1.fit(bw=0.5) plt.plot(kde1.support, [kde1.evaluate(xi) for xi in kde1.support],'x-') kde1= KDEUnivariate(np.array([10.,5.])) kde1.fit(weights=np.array([3.,1.]), bw=0.5, fft=False) plt.plot(kde1.support, [kde1.evaluate(xi) for xi in kde1.support], 'o-') ``` which produces this figure: [![enter image description here](https://i.stack.imgur.com/LF5Lq.png)](https://i.stack.imgur.com/LF5Lq.png)
27,623,919
**Update**: Weighted samples are now supported by `scipy.stats.gaussian_kde`. See [here](https://stackoverflow.com/questions/27623919/weighted-gaussian-kernel-density-estimation-in-python/27623920#27623920) and [here](https://github.com/scipy/scipy/pull/8991) for details. It is currently not possible to use `scipy.stats.gaussian_kde` to estimate the density of a random variable based on [weighted samples](http://en.wikipedia.org/wiki/Sampling_%28statistics%29#Survey_weights). What methods are available to estimate densities of continuous random variables based on weighted samples?
2014/12/23
[ "https://Stackoverflow.com/questions/27623919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1150961/" ]
For univariate distributions you can use `KDEUnivariate` from [statsmodels](http://www.statsmodels.org/stable/generated/statsmodels.nonparametric.kde.KDEUnivariate.html#statsmodels.nonparametric.kde.KDEUnivariate). It is not well documented, but the `fit` methods accepts a `weights` argument. Then you cannot use FFT. Here is an example: ``` import matplotlib.pyplot as plt from statsmodels.nonparametric.kde import KDEUnivariate kde1= KDEUnivariate(np.array([10.,10.,10.,5.])) kde1.fit(bw=0.5) plt.plot(kde1.support, [kde1.evaluate(xi) for xi in kde1.support],'x-') kde1= KDEUnivariate(np.array([10.,5.])) kde1.fit(weights=np.array([3.,1.]), bw=0.5, fft=False) plt.plot(kde1.support, [kde1.evaluate(xi) for xi in kde1.support], 'o-') ``` which produces this figure: [![enter image description here](https://i.stack.imgur.com/LF5Lq.png)](https://i.stack.imgur.com/LF5Lq.png)
Check out the packages PyQT-Fit and statistics for Python. They seem to have kernel density estimation with weighted observations.
41,962,146
I'm having two lists x, y representing coordinates in 2D. For example `x = [1,4,0.5,2,5,10,33,0.04]` and `y = [2,5,44,0.33,2,14,20,0.03]`. `x[i]` and `y[i]` represent one point in 2D. Now I also have a list representing "heat" values for each (x,y) point, for example `z = [0.77, 0.88, 0.65, 0.55, 0.89, 0.9, 0.8,0.95]`. Of course x,y and z are much higher dimensional than the example. Now I would like to plot a heat map in 2D where x and y represents the axis coordinates and z represents the color. How can this be done in python?
2017/01/31
[ "https://Stackoverflow.com/questions/41962146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1684118/" ]
This code produces a heat map. With a few more data points, the plot starts looking pretty nice and I've found it to be very quick in general even for >100k points. ``` import matplotlib.pyplot as plt import matplotlib.tri as tri import numpy as np import math x = [1,4,0.5,2,5,10,33,0.04] y = [2,5,44,0.33,2,14,20,0.03] z = [0.77, 0.88, 0.65, 0.55, 0.89, 0.9, 0.8, 0.95] levels = [0.7, 0.75, 0.8, 0.85, 0.9] plt.figure() ax = plt.gca() ax.set_aspect('equal') CS = ax.tricontourf(x, y, z, levels, cmap=plt.get_cmap('jet')) cbar = plt.colorbar(CS, ticks=np.sort(np.array(levels)),ax=ax, orientation='horizontal', shrink=.75, pad=.09, aspect=40,fraction=0.05) cbar.ax.set_xticklabels(list(map(str,np.sort(np.array(levels))))) # horizontal colorbar cbar.ax.tick_params(labelsize=8) plt.title('Heat Map') plt.xlabel('X Label') plt.ylabel('Y Label') plt.show() ``` Produces this image: [![enter image description here](https://i.stack.imgur.com/y0gkz.png)](https://i.stack.imgur.com/y0gkz.png) or if you're looking for a more gradual color change, change the tricontourf line to this: ``` CS = ax.tricontourf(x, y, z, np.linspace(min(levels),max(levels),256), cmap=cmap) ``` and then the plot will change to: [![enter image description here](https://i.stack.imgur.com/pd44v.png)](https://i.stack.imgur.com/pd44v.png)
Based on [this answer](https://stackoverflow.com/a/14140554/1461850), you might want to do something like: ``` import numpy as np from matplotlib.mlab import griddata import matplotlib.pyplot as plt xs0 = [1,4,0.5,2,5,10,33,0.04] ys0 = [2,5,44,0.33,2,14,20,0.03] zs0 = [0.77, 0.88, 0.65, 0.55, 0.89, 0.9, 0.8,0.95] N = 30j extent = (np.min(xs0),np.max(xs0),np.min(ys0),np.max(ys0)) xs,ys = np.mgrid[extent[0]:extent[1]:N, extent[2]:extent[3]:N] resampled = griddata(xs0, ys0, zs0, xs, ys, interp='linear') plt.imshow(np.fliplr(resampled).T, extent=extent,interpolation='none') plt.colorbar() ``` [![enter image description here](https://i.stack.imgur.com/ueyW8.png)](https://i.stack.imgur.com/ueyW8.png) The example here might also help: <http://matplotlib.org/examples/pylab_examples/griddata_demo.html>
46,225,028
In math, you are allowed to take cubic roots of negative numbers, because a negative number multiplied by two other negative numbers results in a negative number. Raising something to a fractional power 1/n is the same as taking the nth root of it. Therefore, the cubic root of -27, or (-27)\*\*(1.0/3.0) comes out to -3. But in Python 2, when I type in (-27)\*\*(1.0/3.0), it gives me an error: ``` Traceback (most recent call last): File "python", line 1, in <module> ValueError: negative number cannot be raised to a fractional power ``` Python 3 doesn't produce an exception, but it gives a complex number that doesn't look anything like -3: ``` >>> (-27)**(1.0/3.0) (1.5000000000000004+2.598076211353316j) ``` Why don't I get the result that makes mathematical sense? And is there a workaround for this?
2017/09/14
[ "https://Stackoverflow.com/questions/46225028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3566946/" ]
The [type coercion rules documented](https://docs.python.org/2/library/functions.html#pow) by builtin `pow` apply here, since you're using a float for the exponent. Just make sure that either the base or the exponent is a complex instance and it works: ``` >>> (-27+0j)**(1.0/3.0) (1.5000000000000004+2.598076211353316j) >>> (-27)**(complex(1.0/3.0)) (1.5000000000000004+2.598076211353316j) ``` To find all three roots, consider `numpy`: ``` >>> import numpy as np >>> np.roots([1, 0, 0, 27]) array([-3.0+0.j , 1.5+2.59807621j, 1.5-2.59807621j]) ``` The list `[1, 0, 0, 27]` here refers to the coefficients of the equation *1x³ + 0x² + 0x + 27*.
I do not think Python, or your version of it, supports this function. I pasted the same equation into my Python interpreter, (IDLE) and it solved it, with no errors. I am using Python 3.2.
46,225,028
In math, you are allowed to take cubic roots of negative numbers, because a negative number multiplied by two other negative numbers results in a negative number. Raising something to a fractional power 1/n is the same as taking the nth root of it. Therefore, the cubic root of -27, or (-27)\*\*(1.0/3.0) comes out to -3. But in Python 2, when I type in (-27)\*\*(1.0/3.0), it gives me an error: ``` Traceback (most recent call last): File "python", line 1, in <module> ValueError: negative number cannot be raised to a fractional power ``` Python 3 doesn't produce an exception, but it gives a complex number that doesn't look anything like -3: ``` >>> (-27)**(1.0/3.0) (1.5000000000000004+2.598076211353316j) ``` Why don't I get the result that makes mathematical sense? And is there a workaround for this?
2017/09/14
[ "https://Stackoverflow.com/questions/46225028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3566946/" ]
-27 has a real cube root (and two non-real cube roots), but `(-27)**(1.0/3.0)` does not mean "take the real cube root of -27". First, `1.0/3.0` doesn't evaluate to exactly one third, due to the limits of floating-point representation. It evaluates to exactly ``` 0.333333333333333314829616256247390992939472198486328125 ``` though by default, Python won't print the exact value. Second, `**` is not a root-finding operation, whether real roots or principal roots or some other choice. It is the exponentiation operator. General exponentiation of negative numbers to arbitrary real powers is messy, and the usual definitions don't match with real nth roots; for example, the usual definition of (-27)^(1/3) would give you the principal root, a complex number, not -3. Python 2 decides that it's probably better to raise an error for stuff like this unless you make your intentions explicit, for example by exponentiating the absolute value and then applying the sign: ``` def real_nth_root(x, n): # approximate # if n is even, x must be non-negative, and we'll pick the non-negative root. if n % 2 == 0 and x < 0: raise ValueError("No real root.") return (abs(x) ** (1.0/n)) * (-1 if x < 0 else 1) ``` or by using complex `exp` and `log` to take the principal root: ``` import cmath def principal_nth_root(x, n): # still approximate return cmath.exp(cmath.log(x)/n) ``` or by just casting to `complex` for complex exponentiation (equivalent to the exp-log thing up to rounding error): ``` >>> complex(-27)**(1.0/3.0) (1.5000000000000004+2.598076211353316j) ``` Python 3 uses complex exponentiation for negative-number-to-noninteger, which gives the principal `n`th root for `y == 1.0/n`: ``` >>> (-27)**(1/3) # Python 3 (1.5000000000000004+2.598076211353316j) ```
The [type coercion rules documented](https://docs.python.org/2/library/functions.html#pow) by builtin `pow` apply here, since you're using a float for the exponent. Just make sure that either the base or the exponent is a complex instance and it works: ``` >>> (-27+0j)**(1.0/3.0) (1.5000000000000004+2.598076211353316j) >>> (-27)**(complex(1.0/3.0)) (1.5000000000000004+2.598076211353316j) ``` To find all three roots, consider `numpy`: ``` >>> import numpy as np >>> np.roots([1, 0, 0, 27]) array([-3.0+0.j , 1.5+2.59807621j, 1.5-2.59807621j]) ``` The list `[1, 0, 0, 27]` here refers to the coefficients of the equation *1x³ + 0x² + 0x + 27*.
46,225,028
In math, you are allowed to take cubic roots of negative numbers, because a negative number multiplied by two other negative numbers results in a negative number. Raising something to a fractional power 1/n is the same as taking the nth root of it. Therefore, the cubic root of -27, or (-27)\*\*(1.0/3.0) comes out to -3. But in Python 2, when I type in (-27)\*\*(1.0/3.0), it gives me an error: ``` Traceback (most recent call last): File "python", line 1, in <module> ValueError: negative number cannot be raised to a fractional power ``` Python 3 doesn't produce an exception, but it gives a complex number that doesn't look anything like -3: ``` >>> (-27)**(1.0/3.0) (1.5000000000000004+2.598076211353316j) ``` Why don't I get the result that makes mathematical sense? And is there a workaround for this?
2017/09/14
[ "https://Stackoverflow.com/questions/46225028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3566946/" ]
-27 has a real cube root (and two non-real cube roots), but `(-27)**(1.0/3.0)` does not mean "take the real cube root of -27". First, `1.0/3.0` doesn't evaluate to exactly one third, due to the limits of floating-point representation. It evaluates to exactly ``` 0.333333333333333314829616256247390992939472198486328125 ``` though by default, Python won't print the exact value. Second, `**` is not a root-finding operation, whether real roots or principal roots or some other choice. It is the exponentiation operator. General exponentiation of negative numbers to arbitrary real powers is messy, and the usual definitions don't match with real nth roots; for example, the usual definition of (-27)^(1/3) would give you the principal root, a complex number, not -3. Python 2 decides that it's probably better to raise an error for stuff like this unless you make your intentions explicit, for example by exponentiating the absolute value and then applying the sign: ``` def real_nth_root(x, n): # approximate # if n is even, x must be non-negative, and we'll pick the non-negative root. if n % 2 == 0 and x < 0: raise ValueError("No real root.") return (abs(x) ** (1.0/n)) * (-1 if x < 0 else 1) ``` or by using complex `exp` and `log` to take the principal root: ``` import cmath def principal_nth_root(x, n): # still approximate return cmath.exp(cmath.log(x)/n) ``` or by just casting to `complex` for complex exponentiation (equivalent to the exp-log thing up to rounding error): ``` >>> complex(-27)**(1.0/3.0) (1.5000000000000004+2.598076211353316j) ``` Python 3 uses complex exponentiation for negative-number-to-noninteger, which gives the principal `n`th root for `y == 1.0/n`: ``` >>> (-27)**(1/3) # Python 3 (1.5000000000000004+2.598076211353316j) ```
I do not think Python, or your version of it, supports this function. I pasted the same equation into my Python interpreter, (IDLE) and it solved it, with no errors. I am using Python 3.2.
50,663,920
As dir() method in python3 returns all the available usable methods, is there any methods for returning documentation(explanation) of the method as string? In case of pop() method of dictionary it should be returning the following: > > class MutableMapping(Mapping[\_KT, \_VT], Generic[\_KT, \_VT]) > > > @overload def pop Possible types: > > • (self: MutableMapping, k: \_KT) -> \_VT > > > • (self: MutableMapping, k: \_KT, default: Union[\_VT, \_T]) -> Union[\_VT, \_T] > > > External documentation: > <http://docs.python.org/3.6/library/> > > >
2018/06/03
[ "https://Stackoverflow.com/questions/50663920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can access the docstring of a function using the `__doc__` attribute: ``` ➜ python Python 3.6.4 (default, May 23 2018, 17:30:17) Type "help", "copyright", "credits" or "license" for more information. >>> print(dict.pop.__doc__) D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised ```
[Solved] As the comments and the answers mentioned, either help() or **doc** works fine! ``` print(help(dict.pop)) print(dict.pop.__doc__) ```
55,242,211
I am wanting to output a simple word list from any text document. I want every word listed but no duplicates. This is what I have but it doesn't do anything. I am fairly new to python. Thanks! ``` def MakeWordList(): with open('text.txt','r') as f: data = f.read() return set([word for wordd]) ```
2019/03/19
[ "https://Stackoverflow.com/questions/55242211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11221591/" ]
`for word in data` loop basically iterates over `data`, which is string, so your `word` loop variable gets a single character in each iteration. You would want to use something like `data.split()` to loop over the list of words.
You can't iterate over the data you read like this, because they are a string so as a result you get consecutive characters, however you can split the string on spaces, which will give you a list of words ``` def MakeWordList(): with open('possible.rtf','r') as f: data = f.read() return set([word for word in data.split(' ') if len(word) >= 5 and word.islower() and not 'xx' in word]) ```
33,640,820
Hello I am using supervisor with celery in order to run some tasks in a django web application. Celery seems to be having an issue finding/resolving, models from packages that have been installed directly via github. <http://pip.readthedocs.org/en/stable/reference/pip_install/#vcs-support> As that states the packages are installed/cloned into a `<virtualenv>/src` directory. I am wondering if I am missing something in my environment setup with `supervisord.conf` file such as the PYTHONPATH or something else to have these installed packages available. I am getting a > > ValueError: Related model cannot be resolved > > > which does not seem to make sense as the application as a whole is working fine with these packages. **Versions** Celery - 3.1.18 Supervisor - 3.0b2 **supervisord.conf** ``` [program:celeryd] command=/home/path/to/virtualenv/celery worker -A moi --loglevel=info stdout_logfile=/var/log/celery/celeryd.log stderr_logfile=/var/log/celery/celeryd.error.log directory=/path/to/app ``` **The virtualenv looks structure looks like this** ``` virtualenv/ - bin/ - lib/ - share/ - src/github-installed-egg ``` **Error** ``` File "/home/ubuntu/moi/lib/python3.4/site-packages/django/db/models/fields/related.py", line 1600, in resolve_related_fields raise ValueError('Related model %r cannot be resolved' % self.rel.to) ValueError: Related model 'ndptc_core_courses.Course' cannot be resolved ``` The web application is running using nginx and uwsgi, and works fine . The virtualenv setting in the uwsgi configuration file makes this work. The model is a foreign key that is declared by name and not the model object itself. Models that are from packages installed via pypi work fine as well its just those installed in the src folder that are causing the issue. [described in django docs here](https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ForeignKey)
2015/11/10
[ "https://Stackoverflow.com/questions/33640820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1146280/" ]
`Function.prototype.apply` calls the specified function by passing each of the elements of its second argument (which must be an array or array-like) as individual arguments to the function. So what you are doing in your first example is equivalent to ``` [1, 2].push(3, 4); ``` It is *not* equivalent to calling `[1, 2].push([3, 4]);` If it were, the result would be an array with another array nested inside it: ``` [1, 2, [3, 4]] ``` There *is* a method that does what you seem to think `apply` is doing. It's called `call`: ``` Array.prototype.push.call([1, 2], [3, 4]); ```
`Function.prototype.apply(thisArg, [ argsArray])` takes `thisArg` as the first **required** argument and an optional second argument as array. What it does that it returns the result of the calling function with the specified `thisArg` and the optional `argsArray` array. But wait, the second argument is an array-like object but it's specifying the arguments of the calling function. So for your example `Array.prototype.push.apply([1, 2], [3, 4])`, the calling function is `push` which takes a variable number of arguments and push into `this` array and `this` refer to the array `[1, 2]`. So the example works like ``` [1, 2].push(3, 4) // output: [1, 2, 3, 4] ``` But, ``` [1, 2].push([3, 4]) // output: [1, 2, [3, 4]] ``` For your second example, `Math.max.apply(null, [1, 2, 3, 4, 5, 6, 7]);` the `thisArg` is `null` because you are calling a prototype function of `Math`. Which doesn't allow an external `this` to perform any task. So the example works like: ``` Math.max(1, 2, 3, 4, 5, 6, 7) // output: 7 ``` I hope it helps you.
1,950,062
Summary: when a certain python module is imported, I want to be able to intercept this action, and instead of loading the required class, I want to load another class of my choice. Reason: I am working on some legacy code. I need to write some unit test code before I start some enhancement/refactoring. The code imports a certain module which will fail in a unit test setting, however. (Because of database server dependency) Pseduo Code: ``` from LegacyDataLoader import load_me_data ... def do_something(): data = load_me_data() ``` So, ideally, when python excutes the import line above in a unit test, an alternative class, says MockDataLoader, is loaded instead. I am still using 2.4.3. I suppose there is an import hook I can manipulate **Edit** Thanks a lot for the answers so far. They are all very helpful. One particular type of suggestion is about manipulation of PYTHONPATH. It does not work in my case. So I will elaborate my particular situation here. The original codebase is organised in this way ``` ./dir1/myapp/database/LegacyDataLoader.py ./dir1/myapp/database/Other.py ./dir1/myapp/database/__init__.py ./dir1/myapp/__init__.py ``` My goal is to enhance the Other class in the Other module. But since it is legacy code, I do not feel comfortable working on it without strapping a test suite around it first. Now I introduce this unit test code ``` ./unit_test/test.py ``` The content is simply: ``` from myapp.database.Other import Other def test1(): o = Other() o.do_something() if __name__ == "__main__": test1() ``` When the CI server runs the above test, the test fails. It is because class Other uses LegacyDataLoader, and LegacydataLoader cannot establish database connection to the db server from the CI box. Now let's add a fake class as suggested: ``` ./unit_test_fake/myapp/database/LegacyDataLoader.py ./unit_test_fake/myapp/database/__init__.py ./unit_test_fake/myapp/__init__.py ``` Modify the PYTHONPATH to ``` export PYTHONPATH=unit_test_fake:dir1:unit_test ``` Now the test fails for another reason ``` File "unit_test/test.py", line 1, in <module> from myapp.database.Other import Other ImportError: No module named Other ``` It has something to do with the way python resolves classes/attributes in a module
2009/12/23
[ "https://Stackoverflow.com/questions/1950062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58129/" ]
You can intercept `import` and `from ... import` statements by defining your own `__import__` function and assigning it to `__builtin__.__import__` (make sure to save the previous value, since your override will no doubt want to delegate to it; and you'll need to `import __builtin__` to get the builtin-objects module). For example (Py2.4 specific, since that's what you're asking about), save in aim.py the following: ``` import __builtin__ realimp = __builtin__.__import__ def my_import(name, globals={}, locals={}, fromlist=[]): print 'importing', name, fromlist return realimp(name, globals, locals, fromlist) __builtin__.__import__ = my_import from os import path ``` and now: ``` $ python2.4 aim.py importing os ('path',) ``` So this lets you intercept any specific import request you want, and alter the imported module[s] as you wish before you return them -- see the specs [here](http://www.python.org/doc/2.4/lib/built-in-funcs.html). This is the kind of "hook" you're looking for, right?
Well, if the import fails by raising an exception, you could put it in a try...except loop: ``` try: from LegacyDataLoader import load_me_data except: # put error that occurs here, so as not to mask actual problems from MockDataLoader import load_me_data ``` Is that what you're looking for? If it fails, but doesn't raise an exception, you could have it run the unit test with a special command line tag, like --unittest, like this: ``` import sys if "--unittest" in sys.argv: from MockDataLoader import load_me_data else: from LegacyDataLoader import load_me_data ```
1,950,062
Summary: when a certain python module is imported, I want to be able to intercept this action, and instead of loading the required class, I want to load another class of my choice. Reason: I am working on some legacy code. I need to write some unit test code before I start some enhancement/refactoring. The code imports a certain module which will fail in a unit test setting, however. (Because of database server dependency) Pseduo Code: ``` from LegacyDataLoader import load_me_data ... def do_something(): data = load_me_data() ``` So, ideally, when python excutes the import line above in a unit test, an alternative class, says MockDataLoader, is loaded instead. I am still using 2.4.3. I suppose there is an import hook I can manipulate **Edit** Thanks a lot for the answers so far. They are all very helpful. One particular type of suggestion is about manipulation of PYTHONPATH. It does not work in my case. So I will elaborate my particular situation here. The original codebase is organised in this way ``` ./dir1/myapp/database/LegacyDataLoader.py ./dir1/myapp/database/Other.py ./dir1/myapp/database/__init__.py ./dir1/myapp/__init__.py ``` My goal is to enhance the Other class in the Other module. But since it is legacy code, I do not feel comfortable working on it without strapping a test suite around it first. Now I introduce this unit test code ``` ./unit_test/test.py ``` The content is simply: ``` from myapp.database.Other import Other def test1(): o = Other() o.do_something() if __name__ == "__main__": test1() ``` When the CI server runs the above test, the test fails. It is because class Other uses LegacyDataLoader, and LegacydataLoader cannot establish database connection to the db server from the CI box. Now let's add a fake class as suggested: ``` ./unit_test_fake/myapp/database/LegacyDataLoader.py ./unit_test_fake/myapp/database/__init__.py ./unit_test_fake/myapp/__init__.py ``` Modify the PYTHONPATH to ``` export PYTHONPATH=unit_test_fake:dir1:unit_test ``` Now the test fails for another reason ``` File "unit_test/test.py", line 1, in <module> from myapp.database.Other import Other ImportError: No module named Other ``` It has something to do with the way python resolves classes/attributes in a module
2009/12/23
[ "https://Stackoverflow.com/questions/1950062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58129/" ]
You can intercept `import` and `from ... import` statements by defining your own `__import__` function and assigning it to `__builtin__.__import__` (make sure to save the previous value, since your override will no doubt want to delegate to it; and you'll need to `import __builtin__` to get the builtin-objects module). For example (Py2.4 specific, since that's what you're asking about), save in aim.py the following: ``` import __builtin__ realimp = __builtin__.__import__ def my_import(name, globals={}, locals={}, fromlist=[]): print 'importing', name, fromlist return realimp(name, globals, locals, fromlist) __builtin__.__import__ = my_import from os import path ``` and now: ``` $ python2.4 aim.py importing os ('path',) ``` So this lets you intercept any specific import request you want, and alter the imported module[s] as you wish before you return them -- see the specs [here](http://www.python.org/doc/2.4/lib/built-in-funcs.html). This is the kind of "hook" you're looking for, right?
There are cleaner ways to do this, but I'll assume that you can't modify the file containing `from LegacyDataLoader import load_me_data`. The simplest thing to do is probably to create a new directory called testing\_shims, and create LegacyDataLoader.py file in it. In that file, define whatever fake load\_me\_data you like. When running the unit tests, put testing\_shims into your PYTHONPATH environment variable as the first directory. Alternately, you can modify your test runner to insert testing\_shims as the first value in `sys.path`. This way, your file will be found when importing LegacyDataLoader, and your code will be loaded instead of the real code.
1,950,062
Summary: when a certain python module is imported, I want to be able to intercept this action, and instead of loading the required class, I want to load another class of my choice. Reason: I am working on some legacy code. I need to write some unit test code before I start some enhancement/refactoring. The code imports a certain module which will fail in a unit test setting, however. (Because of database server dependency) Pseduo Code: ``` from LegacyDataLoader import load_me_data ... def do_something(): data = load_me_data() ``` So, ideally, when python excutes the import line above in a unit test, an alternative class, says MockDataLoader, is loaded instead. I am still using 2.4.3. I suppose there is an import hook I can manipulate **Edit** Thanks a lot for the answers so far. They are all very helpful. One particular type of suggestion is about manipulation of PYTHONPATH. It does not work in my case. So I will elaborate my particular situation here. The original codebase is organised in this way ``` ./dir1/myapp/database/LegacyDataLoader.py ./dir1/myapp/database/Other.py ./dir1/myapp/database/__init__.py ./dir1/myapp/__init__.py ``` My goal is to enhance the Other class in the Other module. But since it is legacy code, I do not feel comfortable working on it without strapping a test suite around it first. Now I introduce this unit test code ``` ./unit_test/test.py ``` The content is simply: ``` from myapp.database.Other import Other def test1(): o = Other() o.do_something() if __name__ == "__main__": test1() ``` When the CI server runs the above test, the test fails. It is because class Other uses LegacyDataLoader, and LegacydataLoader cannot establish database connection to the db server from the CI box. Now let's add a fake class as suggested: ``` ./unit_test_fake/myapp/database/LegacyDataLoader.py ./unit_test_fake/myapp/database/__init__.py ./unit_test_fake/myapp/__init__.py ``` Modify the PYTHONPATH to ``` export PYTHONPATH=unit_test_fake:dir1:unit_test ``` Now the test fails for another reason ``` File "unit_test/test.py", line 1, in <module> from myapp.database.Other import Other ImportError: No module named Other ``` It has something to do with the way python resolves classes/attributes in a module
2009/12/23
[ "https://Stackoverflow.com/questions/1950062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58129/" ]
You can intercept `import` and `from ... import` statements by defining your own `__import__` function and assigning it to `__builtin__.__import__` (make sure to save the previous value, since your override will no doubt want to delegate to it; and you'll need to `import __builtin__` to get the builtin-objects module). For example (Py2.4 specific, since that's what you're asking about), save in aim.py the following: ``` import __builtin__ realimp = __builtin__.__import__ def my_import(name, globals={}, locals={}, fromlist=[]): print 'importing', name, fromlist return realimp(name, globals, locals, fromlist) __builtin__.__import__ = my_import from os import path ``` and now: ``` $ python2.4 aim.py importing os ('path',) ``` So this lets you intercept any specific import request you want, and alter the imported module[s] as you wish before you return them -- see the specs [here](http://www.python.org/doc/2.4/lib/built-in-funcs.html). This is the kind of "hook" you're looking for, right?
The import statement just grabs stuff from sys.modules if a matching name is found there, so the simplest thing is to make sure you insert your own module into sys.modules under the target name *before* anything else tries to import the real thing. ``` # in test code import sys import MockDataLoader sys.modules['LegacyDataLoader'] = MockDataLoader import module_under_test ``` There are a handful of variations on the theme, but that basic approach should work fine to do what you describe in the question. A slightly simpler approach would be this, using just a mock function to replace the one in question: ``` # in test code import module_under_test def mock_load_me_data(): # do mock stuff here module_under_test.load_me_data = mock_load_me_data ``` That simply replaces the appropriate name right in the module itself, so when you invoke the code under test, presumably `do_something()` in your question, it calls your mock routine.
60,253,058
I'm following [this](https://blog.miguelgrinberg.com/post/using-celery-with-flask) tutorial. In my case I am operating in a Docker environment, and I have a secured site (i.e. <https://localhost>). which requires secured ssl communication. I adjusted the *web*, and *celery* containers for secure connection. But I don't know how to configure the Redis container for secure connection with ssl Note that when I run without ssl connection in the *web* and *celery* containers, the connection is fine. **How do I configure and run redis with ssl?** Thanks --- **EDIT:** I followed [this](https://redislabs.com/blog/stunnel-secure-redis-ssl/) tutorial to set redis with ssl and [this](https://github.com/madflojo/redis-tls-dockerfile) tutorial to set redis with ssl via stunnel in Docker container. I successfully tested the connection from my localhost to the redis docker container, by invoking `redis-cli` from localhost (via stunnel) to the redis docker container, using the following call from the localhost: ``` redis-cli -h 127.0.0.1 -p 6381 127.0.0.1:6381> auth foobared OK 127.0.0.1:6381> ``` **Related files on the redis server Docker side:** *docker-compose file* (my webapp includes multiple services, but to for simplification I removed all services except for the redis container): ``` version: '3' services: redis: build: context: ./redis dockerfile: Dockerfile restart: always command: sh -c "stunnel /stunnel_take2.conf && /usr/local/bin/redis-server /etc/redis/redis.conf" expose: - '6379' ports: - "6379:6379" volumes: - /home/avner/avner/certs:/etc/certs - /home/avner/avner/redis/conf:/etc/redis ``` *redis container Dockerfile* ``` FROM redis:5-alpine RUN apk add --no-cache \ stunnel~=5.56 \ python3~=3.8 COPY stunnel-redis-server.conf / WORKDIR / ENV PYTHONUNBUFFERED=1 ``` redis server redis conf file - *redis/conf/redis.conf* ``` ... requirepass foobared ... ``` redis server stunnel conf file - *redis/stunnel-redis-server.conf* ``` cert = /etc/certs/private.pem pid = /var/run/stunnel.pid [redis] accept = 172.19.0.2:6380 connect = 127.0.0.1:6379 ``` **Related files on the client side (localhost):** redis client stunnel conf file - /etc/stunnel/redis-client.conf ``` cert = /etc/cert/private.pem client = yes pid = /var/run/stunnel.pid [redis] accept = 127.0.0.1:6381 connect = 172.19.0.2:6380 ```
2020/02/16
[ "https://Stackoverflow.com/questions/60253058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5159177/" ]
I've created an example repo, for how one might setup a docker container to use the new redis v6+ ssl: * <https://github.com/allen-munsch/docker-redis-ssl-example> docker-compose.yml ``` version: "3" volumes: redis: services: redis: image: "example/redis:v6.0.13" command: ["/app/docker-redis-entrypoint.sh"] container_name: redis ports: - 6379:6379 volumes: - redis:/data - ./:/app ``` Dockerfile: ``` FROM redis:6.0.13 as base COPY ./redis/tls /tls ``` entrypoint.sh ``` #!/bin/sh set -e redis-server --tls-port 6379 --port 0 \ --tls-cert-file /tls/redis.crt \ --tls-key-file /tls/redis.key \ --tls-ca-cert-file /tls/ca.crt ``` gen-redi-certs.sh ``` #!/bin/bash # COPIED/MODIFIED from the redis server gen-certs util # Generate some test certificates which are used by the regression test suite: # # tls/ca.{crt,key} Self signed CA certificate. # tls/redis.{crt,key} A certificate with no key usage/policy restrictions. # tls/client.{crt,key} A certificate restricted for SSL client usage. # tls/server.{crt,key} A certificate restricted for SSL server usage. # tls/redis.dh DH Params file. generate_cert() { local name=$1 local cn="$2" local opts="$3" local keyfile=tls/${name}.key local certfile=tls/${name}.crt [ -f $keyfile ] || openssl genrsa -out $keyfile 2048 openssl req \ -new -sha256 \ -subj "/O=Redis Test/CN=$cn" \ -key $keyfile | \ openssl x509 \ -req -sha256 \ -CA tls/ca.crt \ -CAkey tls/ca.key \ -CAserial tls/ca.txt \ -CAcreateserial \ -days 365 \ $opts \ -out $certfile } mkdir -p tls [ -f tls/ca.key ] || openssl genrsa -out tls/ca.key 4096 openssl req \ -x509 -new -nodes -sha256 \ -key tls/ca.key \ -days 3650 \ -subj '/O=Redis Test/CN=Certificate Authority' \ -out tls/ca.crt cat > tls/openssl.cnf <<_END_ [ server_cert ] keyUsage = digitalSignature, keyEncipherment nsCertType = server [ client_cert ] keyUsage = digitalSignature, keyEncipherment nsCertType = client _END_ generate_cert server "Server-only" "-extfile tls/openssl.cnf -extensions server_cert" generate_cert client "Client-only" "-extfile tls/openssl.cnf -extensions client_cert" generate_cert redis "Generic-cert" [ -f tls/redis.dh ] || openssl dhparam -out tls/redis.dh 2048 ```
Redis doesn't provide SSL by itself, you have to do it yourself. There's an [in-depth post](https://redislabs.com/blog/stunnel-secure-redis-ssl/) about it which you can read and follow. Or, if you want to use a Dockerized solution, you can use ready images like [this one](https://hub.docker.com/r/madflojo/redis-tls) or [this one](https://hub.docker.com/r/runnable/redis-stunnel/). When it comes to setting up Celery to work with Redis over SSL, just follow the [documentation](https://docs.celeryproject.org/en/stable/userguide/configuration.html#redis-backend-settings).
65,783,935
How do I get the `modify_attr()` function (below) **not** to capture/update the value of b in the following for loop? (simplified version, occurring within a `mainloop()`): ``` for b in range(x): button = tk.Button(button_frame, text="<", command=lambda: current_instance.modify_attr(b, -1)) button.place(x=110, y=80 + 18 * b) button = tk.Button(button_frame, text=">", command=lambda: current_instance.modify_attr(b, 1)) button.place(x=120, y=80 + 18 * b) ``` The goal is to generate two columns of buttons and to bind each button pair to a (somewhat complicated) pair of functions (conditional reduce\_by\_one / increase\_by\_one functions). * **x** = the number of button pairs I need generated * **current\_instance** = a class instance * **modify\_attr** = a class method accepting two arguments (well I guess three if we include self) My understanding (based on [this](https://mail.python.org/pipermail/python-ideas/2008-October/002109.html) and other things I've read over the past few) is that this issue is a common one. At its heart, **the problem is that all values of b with respect to modify\_attr() wind up equal to `len(x)`** (rather than the value of b at the moment I intend to bind that command to the button). The result is a series of buttons that are positioned properly (via the b value(s) in `button.place`) but all pointing to the last element in the list they're supposed to be modifying. I previously encountered this exact problem and was able to work around it using a helper function. But for some reason I am unable to apply that solution here (again, simplified for clarity): ``` for b in range(len(the_list)): def helper_lambda(c): return lambda event: refresh_frame(the_list[c]) window.bind(b + 1, helper_lambda(b)) ``` Does that make sense? Exact same issue, helper\_lamdba works like a charm. Now, in this case, I'm binding a hotkey rather than a button command, but I simply can't get my head around why it would work differently. Because fundamentally the problem is with the for loop, not the functions within. But when I implement a helper function in my button loop it fails like a not-a-charm. Here is my failed attempt to apply that helper strategy: ``` for b in range(x): def helper_lambda(c, modifier): return lambda event: current_instance.modify_attr(c, modifier) button = tk.Button(button_frame, text="<", command=lambda: helper_lambda(b, -1)) button.place(x=110, y=80 + 18 * b) button = tk.Button(button_frame, text=">", command=lambda: helper_lambda(b, 1)) button.place(x=120, y=80 + 18 * b) ``` What am I doing wrong? Also, why does it behave this way? Is anyone using incrementor values outside of for loops?!
2021/01/19
[ "https://Stackoverflow.com/questions/65783935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4404368/" ]
The second approach may work with few changes: ``` for b in range(x): def helper_lambda(c, modifier): return lambda: current_instance.modify_attr(c, modifier) # removed event argument button = tk.Button(button_frame, text="<", command=helper_lambda(b, -1)) button.place(x=110, y=80 + 18 * b) button = tk.Button(button_frame, text=">", command=helper_lambda(b, 1)) button.place(x=150, y=80 + 18 * b) ``` However, you can use `lambda` directly without the helper function: ``` for b in range(x): button = tk.Button(button_frame, text="<", command=lambda b=b: current_instance.modify_attr(b, -1)) button.place(x=110, y=80 + 18 * b) button = tk.Button(button_frame, text=">", command=lambda b=b: current_instance.modify_attr(b, 1)) button.place(x=150, y=80 + 18 * b) ```
This is a case where `functools.partial` is a better option than a lambda expression. ``` from functools import partial for b in range(x): button = tk.Button(button_frame, text="<", command=partial(current_instance.modify_attr, b, -1)) button.place(x=110, y=80 + 18 * b) button = tk.Button(button_frame, text=">", command=partial(current_instance.modify_attr, b, 1)) button.place(x=120, y=80 + 18 * b) ``` `partial` receives the *value* of `b` as an argument, rather than simply capturing the *name* `b` for later use.
23,929,477
I am trying to install MySQLDB/MySQL-python on Cygwin with a Windows MySQL server. While installing it errs out with the error below. Is there a way to work around the below 2 issues. I dont want to install MySQLDB on cygwin. I only want the connector to use in the code. ``` $ pip install MySQL-python Downloading/unpacking MySQL-python EnvironmentError: mysql_config not found pip install MySQLdb Downloading/unpacking MySQLdb Could not find any downloads that satisfy the requirement MySQLdb ``` Thanks for the help.
2014/05/29
[ "https://Stackoverflow.com/questions/23929477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3157891/" ]
I got it fixed after installing "libmysqlclient-devel" ``` apt-cyg install libmysqlclient-devel ``` Still MySQLdb does not work with sock file error. Opened another thread for that problem
Not sure what os you are using but ive found some windows mysqldb libs if that's what you want they have versions for python 2.5-2.7 <http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python> Hope this helps
24,461,167
I'm trying to use Pyro to control a slave machine. I rsync the necessary python files, start a Pyro server, perform some actions by remote control, and then I want to tell the Pyro server to shut down. I'm having trouble getting the Pryo Daemon to shut down cleanly. It either hangs in the `Daemon.close()` call, or if I comment out that line it exits without shutting down its socket correctly, resulting in `socket.error: [Errno 98] Address already in use` if I restart the server too soon. It don't think that SO\_REUSEADDR is the right fix, as unclean socket shutdown still results in a socket hanging around in the TIME\_WAIT state, potentially causing some clients to experience problems. I think the better solution is to convince the Pyro Daemon to close its socket properly. Is it improper to call Daemon.shutdown() from within the daemon itself? If I start a server and then press CTRL-C without any clients connected I don't have any problems (no `Address already in use` errors). That makes a clean shutdown seem possible, most of the time (assuming an otherwise sane client and server). Example: `server.py` ``` import Pyro4 class TestAPI: def __init__(self, daemon): self.daemon = daemon def hello(self, msg): print 'client said {}'.format(msg) return 'hola' def shutdown(self): print 'shutting down...' self.daemon.shutdown() if __name__ == '__main__': daemon = Pyro4.Daemon(port=9999) tapi = TestAPI(daemon) uri = daemon.register(tapi, objectId='TestAPI') daemon.requestLoop() print 'exited requestLoop' daemon.close() # this hangs print 'daemon closed' ``` Example: `client.py` ``` import Pyro4 if __name__ == '__main__': uri = 'PYRO:TestAPI@localhost:9999' remote = Pyro4.Proxy(uri) response = remote.hello('hello') print 'server said {}'.format(response) try: remote.shutdown() except Pyro4.errors.ConnectionClosedError: pass print 'client exiting' ```
2014/06/27
[ "https://Stackoverflow.com/questions/24461167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/223433/" ]
I think this can be done without using timeout or loopCondition, by having your `shutdown()` call the daemon's `shutdown`. According to <http://pythonhosted.org/Pyro4/servercode.html#cleaning-up>: > > Another possibility is calling Pyro4.core.Daemon.shutdown() on the running bdaemon object. This will also break out of the request loop and allows your code to neatly clean up after itself, and will also work on the threaded server type without any other requirements. > > > The following works on Python3.4.2 on Windows. The `@Pyro4.oneway` decorator for `shutdown`is not needed here, but it is in some situations. `server.py` ``` import Pyro4 # using Python3.4.2 @Pyro4.expose class TestAPI: def __init__(self, daemon): self.daemon = daemon def hello(self, msg): print('client said {}'.format(msg)) return 'hola' @Pyro4.oneway # in case call returns much later than daemon.shutdown def shutdown(self): print('shutting down...') self.daemon.shutdown() if __name__ == '__main__': daemon = Pyro4.Daemon(port=9999) tapi = TestAPI(daemon) uri = daemon.register(tapi, objectId='TestAPI') daemon.requestLoop() print('exited requestLoop') daemon.close() print('daemon closed') ``` `client.py` ``` import Pyro4 # using Python3.4.2 if __name__ == '__main__': uri = 'PYRO:TestAPI@localhost:9999' remote = Pyro4.Proxy(uri) response = remote.hello('hello') print('server said {}'.format(response)) remote.shutdown() remote._pyroRelease() print('client exiting') ```
I think I am close to a solution: a combination of using the `loopCondition` parameter to `requestloop()` and the config value `COMMTIMEOUT`. `server.py` ``` import Pyro4 Pyro4.config.COMMTIMEOUT = 1.0 # without this daemon.close() hangs class TestAPI: def __init__(self, daemon): self.daemon = daemon self.running = True def hello(self, msg): print 'client said {}'.format(msg) return 'hola' def shutdown(self): print 'shutting down...' self.running = False if __name__ == '__main__': daemon = Pyro4.Daemon(port=9999) tapi = TestAPI(daemon) uri = daemon.register(tapi, objectId='TestAPI') def checkshutdown(): return tapi.running daemon.requestLoop(loopCondition=checkshutdown) # permits self-shutdown print 'exited requestLoop' daemon.close() print 'daemon closed' ``` Unfortunately, there is one condition where it still leaves a socket behind in the TIME\_WAIT state. If the client closes his socket after the server, then the next attempt to start the server returns the same `Address already in use` error. The only way I can find to work around this is to make the server COMMTIMEOUT longer (or sleep for several seconds before calling `daemon.close()`), and make sure the client always calls `_pyroRelease()` right after the shutdown call: `client.py` ``` import Pyro4 if __name__ == '__main__': uri = 'PYRO:TestAPI@localhost:9999' remote = Pyro4.Proxy(uri) response = remote.hello('hello') print 'server said {}'.format(response) remote.shutdown() remote._pyroRelease() print 'client exiting' ``` I suppose that's good enough, but given the unfairness of scheduling and network delays it's still disappointing to have that race condition lurking.
68,095,958
I have a class with a field named `arglist` whose value is a list. I would like the order maintained to respect the callers provided order; however, I'd like equality to be independent of order. I have implemented the `__eq__` method as follows: ```py def __eq__(self, that): return type(self) is type(that) and \ set(self.arglist) == set(that.arglist) ``` How should I now implement the `__hash__` method? When I try to the following, I get a runtime error. ```py def __hash__(self): return hash(set(self.arglist)) ``` The error I get is ``` File "/Users/jnewton/Repos/python-rte/genus/src/s_member.py", line 55, in __hash__ return hash(set(self.arglist)) TypeError: unhashable type: 'set' ``` Maybe what I'm trying to do doesn't really make sense? Do I need to give up on the idea of order-independent equality?
2021/06/23
[ "https://Stackoverflow.com/questions/68095958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5119871/" ]
The `hash()` method in python only works with immutable data type but `set` is a mutable data type, hence it is throwing an error. A `frozenset` or `tuple` which are immutable could be used instead.
<https://docs.python.org/3/library/dataclasses.html> this might be of use to you :)
671,323
I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines(). Currently I have this code that uses regex (I'm not very good at it) to search for links in every line: ``` for line in lines: result = re.match ('/href="(.*)"/iU', line) print result ``` This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening. Can someone give me a hint on this? Thanks in advance
2009/03/22
[ "https://Stackoverflow.com/questions/671323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28388/" ]
What others haven't told you is that using regular expressions for this is not a reliable solution. Using regular expression will give you wrong results on many situations: if there are <A> tags that are commented out, or if there are text in the page which include the string "href=", or if there are <textarea> elements with html code in it, and many others. Plus, the href attribute may exist on tags other that the anchor tag. What you need for this is [XPath](http://en.wikipedia.org/wiki/Xpath), which is a query language for DOM trees, i.e. it lets you retrieve any set of nodes satisfying the conditions you specify (HTML attributes are nodes in the DOM). XPath is a well standarized language now a days ([W3C](http://www.w3.org/TR/xpath)), and is well supported by all major languages. I strongly suggest you use XPath and not regexp for this. adw's answer shows one example of using XPath for your particular case.
Don't divide the html content into lines, as there maybe multiple matches in a single line. Also don't assume there is always quotes around the url. Do something like this: ``` links = re.finditer(' href="?([^\s^"]+)', content) for link in links: print link ```
671,323
I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines(). Currently I have this code that uses regex (I'm not very good at it) to search for links in every line: ``` for line in lines: result = re.match ('/href="(.*)"/iU', line) print result ``` This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening. Can someone give me a hint on this? Thanks in advance
2009/03/22
[ "https://Stackoverflow.com/questions/671323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28388/" ]
Another alternative to BeautifulSoup is lxml (<http://lxml.de/>); ``` import lxml.html links = lxml.html.parse("http://stackoverflow.com/").xpath("//a/@href") for link in links: print link ```
There's an HTML parser that comes standard in Python. Checkout `htmllib`.
671,323
I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines(). Currently I have this code that uses regex (I'm not very good at it) to search for links in every line: ``` for line in lines: result = re.match ('/href="(.*)"/iU', line) print result ``` This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening. Can someone give me a hint on this? Thanks in advance
2009/03/22
[ "https://Stackoverflow.com/questions/671323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28388/" ]
[Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) can do this almost trivially: ``` from BeautifulSoup import BeautifulSoup as soup html = soup('<body><a href="123">qwe</a><a href="456">asd</a></body>') print [tag.attrMap['href'] for tag in html.findAll('a', {'href': True})] ```
Don't divide the html content into lines, as there maybe multiple matches in a single line. Also don't assume there is always quotes around the url. Do something like this: ``` links = re.finditer(' href="?([^\s^"]+)', content) for link in links: print link ```
671,323
I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines(). Currently I have this code that uses regex (I'm not very good at it) to search for links in every line: ``` for line in lines: result = re.match ('/href="(.*)"/iU', line) print result ``` This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening. Can someone give me a hint on this? Thanks in advance
2009/03/22
[ "https://Stackoverflow.com/questions/671323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28388/" ]
Another alternative to BeautifulSoup is lxml (<http://lxml.de/>); ``` import lxml.html links = lxml.html.parse("http://stackoverflow.com/").xpath("//a/@href") for link in links: print link ```
What others haven't told you is that using regular expressions for this is not a reliable solution. Using regular expression will give you wrong results on many situations: if there are <A> tags that are commented out, or if there are text in the page which include the string "href=", or if there are <textarea> elements with html code in it, and many others. Plus, the href attribute may exist on tags other that the anchor tag. What you need for this is [XPath](http://en.wikipedia.org/wiki/Xpath), which is a query language for DOM trees, i.e. it lets you retrieve any set of nodes satisfying the conditions you specify (HTML attributes are nodes in the DOM). XPath is a well standarized language now a days ([W3C](http://www.w3.org/TR/xpath)), and is well supported by all major languages. I strongly suggest you use XPath and not regexp for this. adw's answer shows one example of using XPath for your particular case.
671,323
I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines(). Currently I have this code that uses regex (I'm not very good at it) to search for links in every line: ``` for line in lines: result = re.match ('/href="(.*)"/iU', line) print result ``` This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening. Can someone give me a hint on this? Thanks in advance
2009/03/22
[ "https://Stackoverflow.com/questions/671323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28388/" ]
Another alternative to BeautifulSoup is lxml (<http://lxml.de/>); ``` import lxml.html links = lxml.html.parse("http://stackoverflow.com/").xpath("//a/@href") for link in links: print link ```
As previously mentioned: regex does not have the power to parse HTML. Do not use regex for parsing HTML. Do not pass Go. Do not collect £200. Use an HTML parser. But for completeness, the primary problem is: ``` re.match ('/href="(.*)"/iU', line) ``` You don't use the “/.../flags” syntax for decorating regexes in Python. Instead put the flags in a separate argument: ``` re.match('href="(.*)"', line, re.I|re.U) ``` Another problem is the greedy ‘.\*’ pattern. If you have two hrefs in a line, it'll happily suck up all the content between the opening " of the first match and the closing " of the second match. You can use the non-greedy ‘.\*?’ or, more simply, ‘[^"]\*’ to only match up to the first closing quote. But don't use regexes for parsing HTML. Really.
671,323
I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines(). Currently I have this code that uses regex (I'm not very good at it) to search for links in every line: ``` for line in lines: result = re.match ('/href="(.*)"/iU', line) print result ``` This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening. Can someone give me a hint on this? Thanks in advance
2009/03/22
[ "https://Stackoverflow.com/questions/671323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28388/" ]
Another alternative to BeautifulSoup is lxml (<http://lxml.de/>); ``` import lxml.html links = lxml.html.parse("http://stackoverflow.com/").xpath("//a/@href") for link in links: print link ```
Don't divide the html content into lines, as there maybe multiple matches in a single line. Also don't assume there is always quotes around the url. Do something like this: ``` links = re.finditer(' href="?([^\s^"]+)', content) for link in links: print link ```
671,323
I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines(). Currently I have this code that uses regex (I'm not very good at it) to search for links in every line: ``` for line in lines: result = re.match ('/href="(.*)"/iU', line) print result ``` This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening. Can someone give me a hint on this? Thanks in advance
2009/03/22
[ "https://Stackoverflow.com/questions/671323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28388/" ]
[Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) can do this almost trivially: ``` from BeautifulSoup import BeautifulSoup as soup html = soup('<body><a href="123">qwe</a><a href="456">asd</a></body>') print [tag.attrMap['href'] for tag in html.findAll('a', {'href': True})] ```
Well, just for completeness I will add here what I found to be the best answer, and I found it on the book Dive Into Python, from Mark Pilgrim. Here follows the code to list all URL's from a webpage: ``` from sgmllib import SGMLParser class URLLister(SGMLParser): def reset(self): SGMLParser.reset(self) self.urls = [] def start_a(self, attrs): href = [v for k, v in attrs if k=='href'] if href: self.urls.extend(href) import urllib, urllister usock = urllib.urlopen("http://diveintopython.net/") parser = urllister.URLLister() parser.feed(usock.read()) usock.close() parser.close() for url in parser.urls: print url ``` Thanks for all the replies.
671,323
I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines(). Currently I have this code that uses regex (I'm not very good at it) to search for links in every line: ``` for line in lines: result = re.match ('/href="(.*)"/iU', line) print result ``` This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening. Can someone give me a hint on this? Thanks in advance
2009/03/22
[ "https://Stackoverflow.com/questions/671323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28388/" ]
[Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) can do this almost trivially: ``` from BeautifulSoup import BeautifulSoup as soup html = soup('<body><a href="123">qwe</a><a href="456">asd</a></body>') print [tag.attrMap['href'] for tag in html.findAll('a', {'href': True})] ```
There's an HTML parser that comes standard in Python. Checkout `htmllib`.
671,323
I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines(). Currently I have this code that uses regex (I'm not very good at it) to search for links in every line: ``` for line in lines: result = re.match ('/href="(.*)"/iU', line) print result ``` This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening. Can someone give me a hint on this? Thanks in advance
2009/03/22
[ "https://Stackoverflow.com/questions/671323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28388/" ]
[Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) can do this almost trivially: ``` from BeautifulSoup import BeautifulSoup as soup html = soup('<body><a href="123">qwe</a><a href="456">asd</a></body>') print [tag.attrMap['href'] for tag in html.findAll('a', {'href': True})] ```
Another alternative to BeautifulSoup is lxml (<http://lxml.de/>); ``` import lxml.html links = lxml.html.parse("http://stackoverflow.com/").xpath("//a/@href") for link in links: print link ```
671,323
I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines(). Currently I have this code that uses regex (I'm not very good at it) to search for links in every line: ``` for line in lines: result = re.match ('/href="(.*)"/iU', line) print result ``` This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening. Can someone give me a hint on this? Thanks in advance
2009/03/22
[ "https://Stackoverflow.com/questions/671323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28388/" ]
Another alternative to BeautifulSoup is lxml (<http://lxml.de/>); ``` import lxml.html links = lxml.html.parse("http://stackoverflow.com/").xpath("//a/@href") for link in links: print link ```
Well, just for completeness I will add here what I found to be the best answer, and I found it on the book Dive Into Python, from Mark Pilgrim. Here follows the code to list all URL's from a webpage: ``` from sgmllib import SGMLParser class URLLister(SGMLParser): def reset(self): SGMLParser.reset(self) self.urls = [] def start_a(self, attrs): href = [v for k, v in attrs if k=='href'] if href: self.urls.extend(href) import urllib, urllister usock = urllib.urlopen("http://diveintopython.net/") parser = urllister.URLLister() parser.feed(usock.read()) usock.close() parser.close() for url in parser.urls: print url ``` Thanks for all the replies.
13,287,028
Using python, wxpython and sqlite in a windows system. I'm trying to print some certificates/diplomas/cards with an image in the background and the name of person/text over it. I know the basic steps to print the text using win32print from Pywin32 but: 1. I dont know how to add an image and set it to background. ``` while ..... ..... # Query sqlite rows and collumn name and set the self.text for each certificate ..... # Now send to printer DC = win32ui.CreateDC() DC.CreatePrinterDC(win32print.GetDefaultPrinter()) DC.SetMapMode(win32con.MM_TWIPS) DC.StartDoc("Certificates Job") DC.StartPage() ux = 1000 uy = -1000 lx = 5500 ly = -55000 DC.DrawText(self.text, (ux, uy, lx, ly),win32con.DT_LEFT) DC.EndPage() DC.EndDoc() ``` This printer-code is inside a while loop calling each people name from a sqlite database per check condition. 2. All the names of database was printed at same page. How do I command the printer to spit out 1 page per name from the database? 3. A simpler approach or module to deal with printers (paper and/or pdf) will be welcome.
2012/11/08
[ "https://Stackoverflow.com/questions/13287028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1808894/" ]
I think it can be feasable with WxPython, but I do not know enough to help you. However, you can try to take a look into [Python Image Library](http://www.pythonware.com/products/pil/) : Example code : ``` import sys from PIL import Image,ImageDraw txt = 'C\'est mon texte!' txt2 = '??,??!' im = Image.new("RGBA",(300,200),(100,155,100)) draw = ImageDraw.Draw(im) draw.text( (0,50), txt ) draw.text( (0,100), txt2) del draw im.save('font.png', "PNG") ``` and the result : ![enter image description here](https://i.stack.imgur.com/SsSzv.png)
I suggest you instead use [reportlab](http://www.reportlab.com/software/opensource/rl-toolkit/) to create a PDF and then send that PDF to a printer using gsprint. See this answer: <https://stackoverflow.com/a/4498956/3571>
30,813,370
I am using pycharm in windows but the python backend need to be running on unix so I host the python app/code in ubuntu with vagrant, however I need to do some plotting as well, is there a way I can enable matplotlab plotting in pycharm with vagrant? thanks
2015/06/12
[ "https://Stackoverflow.com/questions/30813370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813699/" ]
Try to set DISPLAY environment variable in PyCharm run configuration like this: ``` DISPLAY=localhost:10.0 ``` I got my display value from vagrant ssh connection ``` vagrant@vagrant:$ echo $DISPLAY localhost:10.0 ```
In case anyone stumbles upon the same issue.. There are several ways for you to enable X11 through PyCharm. The solution for me was to **create a terminal session using the -Y flag** (or -X), e.g.: ``` ssh -X user@ip ``` or ``` ssh -Y user@ip ``` The -Y worked for me as it enables trusted X11 forwarding, which are not subjected to X11 Security extension controls ([ssh man page](http://linuxcommand.org/lc3_man_pages/ssh1.html)) You also need to **export DISPLAY** variable just like [user138180](https://stackoverflow.com/a/32945380/3501630) said For me the **matplotlib backend** that worked was "*tkagg*". See [matplotlib faq](https://matplotlib.org/faq/usage_faq.html) for more info. --- My remote machine is a centos 7. My local machine is running Manjaro. A workaround to having the terminal session opened is to follow what Tarun said [here](https://stackoverflow.com/a/47146093/3501630). --- As an example, (thanks, [user138180](https://stackoverflow.com/users/6543500/tamtam)), you could use this code to test if it works: ``` import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt plt.interactive(False) plt.hist(np.random.randn(100)) plt.show() ```
66,845,255
I have a file 1.txt containing words and symbols on some lines while on other lines I have only numbers, and never no numbers are on the same line where words and symbols are. ``` FOO > 1.0 BAR < 0.004 FOO FOO < 0.000004 BAR BAR < ``` What I need is to analyze only the lines that have numbers, and then compare the numbers found and print the maximum value and minimum value. In addition it is important that I know the line number (instead index) of the minimum value and the maximum value. I tried to solve this looking at some questions like [Find Min and Max from Text File - Python](https://stackoverflow.com/questions/28618342/find-min-and-max-from-text-file-python) e [How to Find Minimum value from \*.txt file](https://stackoverflow.com/questions/53592197/how-to-find-minimum-value-from-txt-file/53592830) But, for example, when I run the code ``` import csv rows = [] with open('1.txt', mode='r') as infile: reader = csv.reader(infile, delimiter=" ") for row in reader: # each row is a list rows.append(row) minimus = min(rows, key=lambda x: float(x[0])) print(minimus) ``` I have bumped into the following error > > ValueError: could not convert string to float: 'FOO' > > > How could I escape the lines that have symbols and words and just analyze the lines that have numbers, also obtaining the indicator of the lines with the minimum and maximum value? I could extract all the rows that contains only numbers to a new file (for example using regex), but I would need to know the previous/after line to the line that the minimum value was found, then any line extraction would increase the number of steps of the analysis in which I am involved because I would have to return to analyze the original 1.txt file. Note: I am inexperienced in Python compared to a frequent user of this language, but I think it is something simple for stackoverflow Questions list, and I suspect that perhaps this issue has already been answered. But as I already looked for some satisfactory question and I did not find it so I'm doing my own question.
2021/03/28
[ "https://Stackoverflow.com/questions/66845255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10824251/" ]
This might be overkill, but what immediately came to my mind is *RegEx* (*Reg*ular *Ex*pressions), using the `re` library. Here's the RegEx you would use for a float: `^[1-9]\d*(\.\d+)?$`. So we can implement this code: ```py import csv import re rows = [] with open('1.txt', mode='r') as infile: reader = csv.reader(infile, delimiter=" ") for row in reader: # each row is a list if bool(re.match(r'^[1-9]\d*(\.\d+)?$', row): rows.append(row) minimus = min(rows, key=lambda x: float(x[0])) print(minimus) ``` What I changed: I added `if bool(re.match...`, resulting in `rows` only getting appended to under the circumstance that `row` is only a float (or integer).
``` import csv rows = [] with open('1.txt', mode='r') as infile: reader = csv.reader(infile, delimiter=" ") for row in reader: if not row[0].isalpha(): rows.append(row[0]) print(rows) minimus = min(rows, key=lambda x: float(x[0])) print(minimus) ``` Incorporate an `if` statement to check if the `row[0]` is not an `alpha` > > [str.isalpha()](https://docs.python.org/3/library/stdtypes.html#str.isalpha) Return True if all characters in the string are > alphabetic and there is at least one character, False otherwise > > >
66,845,255
I have a file 1.txt containing words and symbols on some lines while on other lines I have only numbers, and never no numbers are on the same line where words and symbols are. ``` FOO > 1.0 BAR < 0.004 FOO FOO < 0.000004 BAR BAR < ``` What I need is to analyze only the lines that have numbers, and then compare the numbers found and print the maximum value and minimum value. In addition it is important that I know the line number (instead index) of the minimum value and the maximum value. I tried to solve this looking at some questions like [Find Min and Max from Text File - Python](https://stackoverflow.com/questions/28618342/find-min-and-max-from-text-file-python) e [How to Find Minimum value from \*.txt file](https://stackoverflow.com/questions/53592197/how-to-find-minimum-value-from-txt-file/53592830) But, for example, when I run the code ``` import csv rows = [] with open('1.txt', mode='r') as infile: reader = csv.reader(infile, delimiter=" ") for row in reader: # each row is a list rows.append(row) minimus = min(rows, key=lambda x: float(x[0])) print(minimus) ``` I have bumped into the following error > > ValueError: could not convert string to float: 'FOO' > > > How could I escape the lines that have symbols and words and just analyze the lines that have numbers, also obtaining the indicator of the lines with the minimum and maximum value? I could extract all the rows that contains only numbers to a new file (for example using regex), but I would need to know the previous/after line to the line that the minimum value was found, then any line extraction would increase the number of steps of the analysis in which I am involved because I would have to return to analyze the original 1.txt file. Note: I am inexperienced in Python compared to a frequent user of this language, but I think it is something simple for stackoverflow Questions list, and I suspect that perhaps this issue has already been answered. But as I already looked for some satisfactory question and I did not find it so I'm doing my own question.
2021/03/28
[ "https://Stackoverflow.com/questions/66845255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10824251/" ]
One possible approach without the need for any extra modules **Code:** ``` def is_float(x): try: float(x) return True except: return False with open('url1.txt', 'r') as myfile: lines = myfile.readlines() nums = [x for x in lines if is_float(x)] my_min = min(nums) my_max = max(nums) print('Max: ', my_max, 'line number: ', lines.index(my_max)+1) print() print('Min: ', my_min, 'line number: ', lines.index(my_min)+1) ``` **Input:** ``` FOO > 1.0 BAR < 0.004 FOO FOO < 0.000004 BAR BAR < ``` **Output:** ``` Max: 1.0 line number: 2 Min: 0.000004 line number: 6 ``` **Explanation:** 1. write a function to check if a string can be converted to float, this can be done by using `try` statement and `float()` 2. filter floats from lines read from file 3. find the min and max values 4. find indices of min and max in list of lines using `list.index(<value>)` 5. Add 1 to indices to get line number as indices starts from zero
``` import csv rows = [] with open('1.txt', mode='r') as infile: reader = csv.reader(infile, delimiter=" ") for row in reader: if not row[0].isalpha(): rows.append(row[0]) print(rows) minimus = min(rows, key=lambda x: float(x[0])) print(minimus) ``` Incorporate an `if` statement to check if the `row[0]` is not an `alpha` > > [str.isalpha()](https://docs.python.org/3/library/stdtypes.html#str.isalpha) Return True if all characters in the string are > alphabetic and there is at least one character, False otherwise > > >
66,845,255
I have a file 1.txt containing words and symbols on some lines while on other lines I have only numbers, and never no numbers are on the same line where words and symbols are. ``` FOO > 1.0 BAR < 0.004 FOO FOO < 0.000004 BAR BAR < ``` What I need is to analyze only the lines that have numbers, and then compare the numbers found and print the maximum value and minimum value. In addition it is important that I know the line number (instead index) of the minimum value and the maximum value. I tried to solve this looking at some questions like [Find Min and Max from Text File - Python](https://stackoverflow.com/questions/28618342/find-min-and-max-from-text-file-python) e [How to Find Minimum value from \*.txt file](https://stackoverflow.com/questions/53592197/how-to-find-minimum-value-from-txt-file/53592830) But, for example, when I run the code ``` import csv rows = [] with open('1.txt', mode='r') as infile: reader = csv.reader(infile, delimiter=" ") for row in reader: # each row is a list rows.append(row) minimus = min(rows, key=lambda x: float(x[0])) print(minimus) ``` I have bumped into the following error > > ValueError: could not convert string to float: 'FOO' > > > How could I escape the lines that have symbols and words and just analyze the lines that have numbers, also obtaining the indicator of the lines with the minimum and maximum value? I could extract all the rows that contains only numbers to a new file (for example using regex), but I would need to know the previous/after line to the line that the minimum value was found, then any line extraction would increase the number of steps of the analysis in which I am involved because I would have to return to analyze the original 1.txt file. Note: I am inexperienced in Python compared to a frequent user of this language, but I think it is something simple for stackoverflow Questions list, and I suspect that perhaps this issue has already been answered. But as I already looked for some satisfactory question and I did not find it so I'm doing my own question.
2021/03/28
[ "https://Stackoverflow.com/questions/66845255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10824251/" ]
One possible approach without the need for any extra modules **Code:** ``` def is_float(x): try: float(x) return True except: return False with open('url1.txt', 'r') as myfile: lines = myfile.readlines() nums = [x for x in lines if is_float(x)] my_min = min(nums) my_max = max(nums) print('Max: ', my_max, 'line number: ', lines.index(my_max)+1) print() print('Min: ', my_min, 'line number: ', lines.index(my_min)+1) ``` **Input:** ``` FOO > 1.0 BAR < 0.004 FOO FOO < 0.000004 BAR BAR < ``` **Output:** ``` Max: 1.0 line number: 2 Min: 0.000004 line number: 6 ``` **Explanation:** 1. write a function to check if a string can be converted to float, this can be done by using `try` statement and `float()` 2. filter floats from lines read from file 3. find the min and max values 4. find indices of min and max in list of lines using `list.index(<value>)` 5. Add 1 to indices to get line number as indices starts from zero
This might be overkill, but what immediately came to my mind is *RegEx* (*Reg*ular *Ex*pressions), using the `re` library. Here's the RegEx you would use for a float: `^[1-9]\d*(\.\d+)?$`. So we can implement this code: ```py import csv import re rows = [] with open('1.txt', mode='r') as infile: reader = csv.reader(infile, delimiter=" ") for row in reader: # each row is a list if bool(re.match(r'^[1-9]\d*(\.\d+)?$', row): rows.append(row) minimus = min(rows, key=lambda x: float(x[0])) print(minimus) ``` What I changed: I added `if bool(re.match...`, resulting in `rows` only getting appended to under the circumstance that `row` is only a float (or integer).
66,845,255
I have a file 1.txt containing words and symbols on some lines while on other lines I have only numbers, and never no numbers are on the same line where words and symbols are. ``` FOO > 1.0 BAR < 0.004 FOO FOO < 0.000004 BAR BAR < ``` What I need is to analyze only the lines that have numbers, and then compare the numbers found and print the maximum value and minimum value. In addition it is important that I know the line number (instead index) of the minimum value and the maximum value. I tried to solve this looking at some questions like [Find Min and Max from Text File - Python](https://stackoverflow.com/questions/28618342/find-min-and-max-from-text-file-python) e [How to Find Minimum value from \*.txt file](https://stackoverflow.com/questions/53592197/how-to-find-minimum-value-from-txt-file/53592830) But, for example, when I run the code ``` import csv rows = [] with open('1.txt', mode='r') as infile: reader = csv.reader(infile, delimiter=" ") for row in reader: # each row is a list rows.append(row) minimus = min(rows, key=lambda x: float(x[0])) print(minimus) ``` I have bumped into the following error > > ValueError: could not convert string to float: 'FOO' > > > How could I escape the lines that have symbols and words and just analyze the lines that have numbers, also obtaining the indicator of the lines with the minimum and maximum value? I could extract all the rows that contains only numbers to a new file (for example using regex), but I would need to know the previous/after line to the line that the minimum value was found, then any line extraction would increase the number of steps of the analysis in which I am involved because I would have to return to analyze the original 1.txt file. Note: I am inexperienced in Python compared to a frequent user of this language, but I think it is something simple for stackoverflow Questions list, and I suspect that perhaps this issue has already been answered. But as I already looked for some satisfactory question and I did not find it so I'm doing my own question.
2021/03/28
[ "https://Stackoverflow.com/questions/66845255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10824251/" ]
This might be overkill, but what immediately came to my mind is *RegEx* (*Reg*ular *Ex*pressions), using the `re` library. Here's the RegEx you would use for a float: `^[1-9]\d*(\.\d+)?$`. So we can implement this code: ```py import csv import re rows = [] with open('1.txt', mode='r') as infile: reader = csv.reader(infile, delimiter=" ") for row in reader: # each row is a list if bool(re.match(r'^[1-9]\d*(\.\d+)?$', row): rows.append(row) minimus = min(rows, key=lambda x: float(x[0])) print(minimus) ``` What I changed: I added `if bool(re.match...`, resulting in `rows` only getting appended to under the circumstance that `row` is only a float (or integer).
I suggest a simple solution by collecting all numbers and their indices using a try except statement. After the number and indices are collected in two lists you can find the min and max by for instance making use of the numpy package. ``` import numpy as np numbers, indices = [],[] with open("1.txt") as my_text_file: for i, line in enumerate( my_text_file.readlines() ): try: numbers.append( float(line) ) indices.append( i ) except: pass maxvalue = np.max( numbers ) minvalue = np.min( numbers ) maxindx = indices[ np.argmax( numbers ) ] minindx = indices[ np.argmin( numbers ) ] print("The maximum value is found at line "+str(maxindx)+" with the value "+str(maxvalue)) print("The minimum value is found at line "+str(minindx)+" with the value "+str(minvalue)) ``` For the provided 1.txt file thisproduces theprint out ``` The maximum value is found at line 1 with the value 1.0 The minimum value is found at line 5 with the value 4e-06 ``` Cheers
66,845,255
I have a file 1.txt containing words and symbols on some lines while on other lines I have only numbers, and never no numbers are on the same line where words and symbols are. ``` FOO > 1.0 BAR < 0.004 FOO FOO < 0.000004 BAR BAR < ``` What I need is to analyze only the lines that have numbers, and then compare the numbers found and print the maximum value and minimum value. In addition it is important that I know the line number (instead index) of the minimum value and the maximum value. I tried to solve this looking at some questions like [Find Min and Max from Text File - Python](https://stackoverflow.com/questions/28618342/find-min-and-max-from-text-file-python) e [How to Find Minimum value from \*.txt file](https://stackoverflow.com/questions/53592197/how-to-find-minimum-value-from-txt-file/53592830) But, for example, when I run the code ``` import csv rows = [] with open('1.txt', mode='r') as infile: reader = csv.reader(infile, delimiter=" ") for row in reader: # each row is a list rows.append(row) minimus = min(rows, key=lambda x: float(x[0])) print(minimus) ``` I have bumped into the following error > > ValueError: could not convert string to float: 'FOO' > > > How could I escape the lines that have symbols and words and just analyze the lines that have numbers, also obtaining the indicator of the lines with the minimum and maximum value? I could extract all the rows that contains only numbers to a new file (for example using regex), but I would need to know the previous/after line to the line that the minimum value was found, then any line extraction would increase the number of steps of the analysis in which I am involved because I would have to return to analyze the original 1.txt file. Note: I am inexperienced in Python compared to a frequent user of this language, but I think it is something simple for stackoverflow Questions list, and I suspect that perhaps this issue has already been answered. But as I already looked for some satisfactory question and I did not find it so I'm doing my own question.
2021/03/28
[ "https://Stackoverflow.com/questions/66845255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10824251/" ]
One possible approach without the need for any extra modules **Code:** ``` def is_float(x): try: float(x) return True except: return False with open('url1.txt', 'r') as myfile: lines = myfile.readlines() nums = [x for x in lines if is_float(x)] my_min = min(nums) my_max = max(nums) print('Max: ', my_max, 'line number: ', lines.index(my_max)+1) print() print('Min: ', my_min, 'line number: ', lines.index(my_min)+1) ``` **Input:** ``` FOO > 1.0 BAR < 0.004 FOO FOO < 0.000004 BAR BAR < ``` **Output:** ``` Max: 1.0 line number: 2 Min: 0.000004 line number: 6 ``` **Explanation:** 1. write a function to check if a string can be converted to float, this can be done by using `try` statement and `float()` 2. filter floats from lines read from file 3. find the min and max values 4. find indices of min and max in list of lines using `list.index(<value>)` 5. Add 1 to indices to get line number as indices starts from zero
I suggest a simple solution by collecting all numbers and their indices using a try except statement. After the number and indices are collected in two lists you can find the min and max by for instance making use of the numpy package. ``` import numpy as np numbers, indices = [],[] with open("1.txt") as my_text_file: for i, line in enumerate( my_text_file.readlines() ): try: numbers.append( float(line) ) indices.append( i ) except: pass maxvalue = np.max( numbers ) minvalue = np.min( numbers ) maxindx = indices[ np.argmax( numbers ) ] minindx = indices[ np.argmin( numbers ) ] print("The maximum value is found at line "+str(maxindx)+" with the value "+str(maxvalue)) print("The minimum value is found at line "+str(minindx)+" with the value "+str(minvalue)) ``` For the provided 1.txt file thisproduces theprint out ``` The maximum value is found at line 1 with the value 1.0 The minimum value is found at line 5 with the value 4e-06 ``` Cheers
68,478,477
I have a python flask app running on EC2. To enable UI interface to be functional, I run this on ec2 after logging in as the correct user: ``` uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi:application -z 120 --http-timeout 120 --enable-threads -H /home/test/env --daemonize /home/test/test.log ``` and the UI becomes operational. When i click the download button certain computations take place before the csv becomes ready to download. I don't have a uwsgi.ini file or any kind of nginx. After a point the test.log becomes a very large file; How do I write log files so that each days log gets written to a separate file? or what is the best way to prevent one large log file from getting generated and instead have something that is more manageable?
2021/07/22
[ "https://Stackoverflow.com/questions/68478477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4590025/" ]
Uses the `TimedRotatingFileHandler` class. The `TimedRotatingFileHandler` object will create a log file for each day, but you will have to handle it within the server application code ``` import os import logging from logging.handlers import TimedRotatingFileHandler from datetime import datetime logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter('[%(asctime)s] %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') handler = TimedRotatingFileHandler(os.path.join('./', 'custom_log.log'), when='midnight', backupCount=7) handler.setLevel(logging.INFO) handler.setFormatter(formatter) logger.addHandler(handler) logger.info("Info") logger.warning("Warning") logger.error("Error") ```
You could implement log rotation using Python logging handlers: ``` from flask import Flask import logging from logging.handlers import RotatingFileHandler app = Flask(__name__) if __name__ == '__main__': handler = RotatingFileHandler('test.log', maxBytes=12000, backupCount=5) handler.setLevel(logging.INFO) app.logger.addHandler(handler) app.run() ``` <https://docs.python.org/3/library/logging.handlers.html#rotatingfilehandler> This would rollover the logs when the `maxBytes` size has been reached. The primary log file will remain `test.log` but the filled log will be renamed to `test.log.1`, `test.log.2` and so on.
52,249,114
So I used to run imagemagick direct in a bash script like this: ``` /usr/local/bin/convert image.jpg -resize 1000x1000\! -depth 2 result.jpg ``` [![result.jpg](https://i.stack.imgur.com/SJOwi.jpg)](https://i.stack.imgur.com/SJOwi.jpg) SO I decided to convert my script to python using wand! ``` from wand.image import Image ... with Image(file=f) as img: img.transform(resize='1000x1000!') img.depth = 2 img.save(filename='result_py.jpg') f.close() ... ``` [![result_py.jpg](https://i.stack.imgur.com/pl6bH.jpg)](https://i.stack.imgur.com/pl6bH.jpg) I've noticed that if I remove the "-depth 2" from the bash script, the result image will be exactly like the result from python, so what am I missing in the python program? Why does do the depth option in python is not working?
2018/09/09
[ "https://Stackoverflow.com/questions/52249114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2788830/" ]
With Python's wand library, you want to use `wand.image.Image.quantize` method, and reduce the colors down to 4 (black/white + 2 colors). ```py from wand.image import Image ... with Image(file=f) as img: img.transform(resize='1000x1000!') img.quantize(4, # Number of colors 'gray', # Colorspace 0, # Tree depth False, # Dither False) # Measure Error img.save(filename='result_py.jpg') f.close() ... ``` [![quantize down to 4](https://i.stack.imgur.com/h8XWy.jpg)](https://i.stack.imgur.com/h8XWy.jpg) I believe the `quantize` method was added in version 0.4.2. Also note that wand currently supports ImageMagick-6, so it's possible that your system has both 6 & 7 installed.
JPG does not support depth 2. It is alway output to depth 8 and the quantization will add more colors. Try your commands with PNG or GIF or TIFF with -depth 2. Does that work? ``` convert -size 256x256 gradient: -depth 2 grad_d2.jpg Depth: 8-bit Colors: 10 Histogram: 10752: ( 0, 0, 0) #000000 gray(0) 256: ( 1, 1, 1) #010101 gray(1) 512: ( 84, 84, 84) #545454 gray(84) 20992: ( 85, 85, 85) #555555 gray(85) 256: ( 86, 86, 86) #565656 gray(86) 256: (169,169,169) #A9A9A9 gray(169) 21248: (170,170,170) #AAAAAA gray(170) 256: (171,171,171) #ABABAB gray(171) 256: (254,254,254) #FEFEFE gray(254) 10752: (255,255,255) #FFFFFF gray(255) convert -size 256x256 gradient: -depth 2 grad_d2.png Depth: 8/2-bit Colors: 4 Histogram: 11008: ( 0, 0, 0) #000000 gray(0) 21760: ( 85, 85, 85) #555555 gray(85) 21760: (170,170,170) #AAAAAA gray(170) 11008: (255,255,255) #FFFFFF gray(255) ``` Perhaps Wand has a bug or you are using too old a version? The resulting images should look similar from JPG or PNG, but the JPG will just have more closely similar colors.
40,951,356
I'm using Angular, Flask and MySQL.connector to connect to a MySQL database: This is my python flask code handling post requests inserting a new "movie": ``` @app.route("/addMovies", methods=['POST']) def addMovies(): cnx = mysql.connector.connect(user='root', database='MovieTheatre') cursor = cnx.cursor() insert_stmt = ( "INSERT INTO Movie (idMovie, MovieName, MovieYear) " "VALUES (%d, %s, %d)" ) post = request.get_json() #data = (post['idMovie'], post['MovieName'], post['MovieYear']) data = (100, 'Test', 2010) # test data print(insert_stmt,data) cursor.execute(insert_stmt,data) cnx.commit() cnx.close() return data ``` I know its not my Angularjs, because my browser console says Internal Server Error (500) so I started printing out the insert statement handled by flask and mysql.connector: ``` ('INSERT INTO Movie (idMovie, MovieName, MovieYear) VALUES (%d, %s, %d)', (100, 'Test', 2010)) ``` Which seems correct. However I keep getting ``` "Wrong number of arguments during string formatting") ProgrammingError: Wrong number of arguments during string formatting ``` =============================================================================== Thanks to the answers, its fixed, for those wondering this is what I switched my code to : ``` @app.route("/addMovies", methods=['POST']) def addMovies(): cnx = mysql.connector.connect(user='root', database='MovieTheatre') cursor = cnx.cursor() insert_stmt = ( "INSERT INTO Movie (idMovie, MovieName, MovieYear) " "VALUES (%s, %s, %s)" ) post = request.get_json() data = (post['idMovie'], post['MovieName'], post['MovieYear']) print(insert_stmt,data) cursor.execute(insert_stmt,data) cnx.commit() cnx.close() return data ```
2016/12/03
[ "https://Stackoverflow.com/questions/40951356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4297337/" ]
You should specify the columns you want to get in `select()`. Also, since you want to get the users with the highest rankings, you should sort them in descending order. Assuming that you need to get the columns `id` and `username`: ``` $users = User::select( DB::raw('id, username, Rank_a + Rank_b + Rank_c AS total_points') )->orderBy('total_points', 'desc')->take(10)->get(); ``` If you want to get all columns: ``` $users = User::select( DB::raw('users.*, Rank_a + Rank_b + Rank_c AS total_points') )->orderBy('total_points', 'desc')->take(10)->get(); ``` And if you just want to get an array of one column, say, `id`: ``` $users = User::select( DB::raw('id, Rank_a + Rank_b + Rank_c AS total_points') )->orderBy('total_points', 'desc')->take(10)->pluck('id'); ```
You can try the following query: ``` $users = User::take(10) ->select('users.*', DB::raw('(Rank_a+Rank_b+Rank_c) AS total_points')) ->orderBy('total_points', 'desc') ->get(); ```
28,816,559
Is it possible to optimize/vectorize the code below? Right now it doesn't seem like a proper way of doing things and it's not very 'pythonish'. The code is intended to work with enormous sets of data so performance is very important. The idea is to remove all the values and their names which do not occur in both lists. E.g. The outcome of the code below would be two lists with "name2" and "name4" having values [2,4] and [5,6] respectively. ``` import numpy as np names1=np.array(["name1","name2","name3","name4"]) names2=np.array(["name2","name4","name5","name6"]) pos1=np.array([1,2,3,4]) pos2=np.array([5,6,7,8]) for entry in names2: if not np.any(names1==entry): pointer=np.where(names2==entry) pos2=np.delete(pos2,pointer) names2=np.delete(names2,pointer) for entry in names1: if not np.any(names2==entry): pointer=np.where(names1==entry) pos1=np.delete(pos1,pointer) names1=np.delete(names1,pointer) ```
2015/03/02
[ "https://Stackoverflow.com/questions/28816559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4624491/" ]
store the image in the database is a bad practice, it is better to store pictures on the sd and store in the database paths to them
Treat the image as a byte array and write/retrieve it to/from your database as a Blob object.
1,298,319
for analysis I'd have to unescape URL-encoded binary strings (non-printable characters most likely). The strings sadly come in the extended URL-encoding form, e.g. "%u616f". I want to store them in a file that then contains the raw binary values, eg. 0x61 0x6f here. How do I get this into binary data in python? (urllib.unquote only handles the "%HH"-form)
2009/08/19
[ "https://Stackoverflow.com/questions/1298319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137273/" ]
I guess you will have to write the decoder function by yourself. Here is an implementation to get you started: ``` def decode(file): while True: c = file.read(1) if c == "": # End of file break if c != "%": # Not an escape sequence yield c continue c = file.read(1) if c != "u": # One hex-byte yield chr(int(c + file.read(1), 16)) continue # Two hex-bytes yield chr(int(file.read(2), 16)) yield chr(int(file.read(2), 16)) ``` Usage: ``` input = open("/path/to/input-file", "r") output = open("/path/to/output-file", "wb") output.writelines(decode(input)) output.close() input.close() ```
Here is a regex-based approach: ``` # the replace function concatenates the two matches after # converting them from hex to ascii repfunc = lambda m: chr(int(m.group(1), 16))+chr(int(m.group(2), 16)) # the last parameter is the text you want to convert result = re.sub('%u(..)(..)', repfunc, '%u616f') print result ``` gives ``` ao ```
1,298,319
for analysis I'd have to unescape URL-encoded binary strings (non-printable characters most likely). The strings sadly come in the extended URL-encoding form, e.g. "%u616f". I want to store them in a file that then contains the raw binary values, eg. 0x61 0x6f here. How do I get this into binary data in python? (urllib.unquote only handles the "%HH"-form)
2009/08/19
[ "https://Stackoverflow.com/questions/1298319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137273/" ]
> > The strings sadly come in the extended URL-encoding form, e.g. "%u616f" > > > Incidentally that's not anything to do with URL-encoding. It's an arbitrary made-up format produced by the JavaScript escape() function and pretty much nothing else. If you can, the best thing to do would be to change the JavaScript to use the encodeURIComponent function instead. This will give you a proper, standard URL-encoded UTF-8 string. > > e.g. "%u616f". I want to store them in a file that then contains the raw binary values, eg. 0x61 0x6f here. > > > Are you sure 0x61 0x6f (the letters "ao") is the byte stream you want to store? That would imply UTF-16BE encoding; are you treating all your strings that way? Normally you'd want to turn the input into Unicode then write it out using an appropriate encoding, such as UTF-8 or UTF-16LE. Here's a quick way of doing it, relying on the hack of making Python read '%u1234' as the string-escaped format u'\u1234': ``` >>> ex= 'hello %e9 %u616f' >>> ex.replace('%u', r'\u').replace('%', r'\x').decode('unicode-escape') u'hello \xe9 \u616f' >>> print _ hello é 慯 >>> _.encode('utf-8') 'hello \xc2\xa0 \xe6\x85\xaf' ```
Here is a regex-based approach: ``` # the replace function concatenates the two matches after # converting them from hex to ascii repfunc = lambda m: chr(int(m.group(1), 16))+chr(int(m.group(2), 16)) # the last parameter is the text you want to convert result = re.sub('%u(..)(..)', repfunc, '%u616f') print result ``` gives ``` ao ```
34,699,866
I am trying to store the out put of mediainfo command in linux in a variable. I am using the subprocess module for this. The problem is that the arguments for mediainfo command have special characters. here is the snippet the shell command is: ``` mediainfo --Inform="Video;%DisplayAspectRatio%" test.mp4 ``` and the python code is: ``` mediain = str('--Inform="Video;%DisplayAspectRatio%"') mediaout = subprocess.check_output("medainfo", mediain ,"test.mp4") print mediaout ``` error im getting is ``` --Inform="Video;%DisplayAspectRatio%" Traceback (most recent call last): File "./test.py", line 8, in <module> mediaout = subprocess.check_output("medainfo", '--Inform="Video;%DisplayAspectRatio%"',"test.mp4") File "/usr/lib64/python2.7/subprocess.py", line 568, in check_output process = Popen(stdout=PIPE, *popenargs, **kwargs) File "/usr/lib64/python2.7/subprocess.py", line 660, in __init__ raise TypeError("bufsize must be an integer") TypeError: bufsize must be an integer ``` any help in this regardd is aprreciated, absolute newbie in python Thanks
2016/01/09
[ "https://Stackoverflow.com/questions/34699866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3589690/" ]
[`subprocess.check_output()`](https://docs.python.org/2/library/subprocess.html#subprocess.check_output) expects the first argument to be a list. Try this: ``` args = ['mediainfo', '--Inform=Video;%DisplayAspectRatio%', 'test.mp4'] mediaout = subprocess.check_output(args) print mediaout ```
Possibly better to keep the command format in a string and pass it to `subprocess.check_out()` as list: ``` cmd = 'mediainfo --Inform=Video;%DisplayAspectRatio% test.mp4' mediaout = subprocess.check_out(cmd.split()) #will split cmd over whitespaces and pass to check_out as a list. print mediaout ```
52,356,574
I am using python and selenium to test some things with fantasy football. Here is my code so far (I just started). ``` import time from selenium import webdriver driver = webdriver.Chrome('C:\\Users\\202300Fontenot\\Desktop\\3\\chromedriver.exe') driver.get('http://games.espn.com/ffl/signin?redir=http%3A%2F%2Fgames.espn.com%2Fffl%2Fclubhouse%3FseasonId%3D2018%26leagueId%3D49607%26teamId%3D4'); driver.implicitly_wait(10) time.sleep(10) search_box = driver.find_element_by_xpath('//*[@id="did-ui-view"]/div/section/section/form/section/div[1]/div/label/span[2]/input') search_box.send_keys('email@icloud.com') search_box.submit() time.sleep(5) driver.quit() ``` This just tries to enter an email address into the box. I am getting this error every time: ``` Traceback (most recent call last): File "C:\Users\202300Fontenot\Desktop\3\ESPN.py", line 8, in <module> search_box = driver.find_element_by_xpath('//*[@id="did-ui-view"]/div/section/section/form/section/div[1]/div/label/span[2]/input') File "C:\Users\202300Fontenot\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 393, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "C:\Users\202300Fontenot\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 966, in find_element 'value': value})['value'] File "C:\Users\202300Fontenot\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File "C:\Users\202300Fontenot\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="did-ui-view"]/div/section/section/form/section/div[1]/div/label/span[2]/input"} (Session info: chrome=69.0.3497.92) (Driver info: chromedriver=2.42.591088 (7b2b2dca23cca0862f674758c9a3933e685c27d5),platform=Windows NT 10.0.16299 x86_64) ``` Thanks for your help.
2018/09/16
[ "https://Stackoverflow.com/questions/52356574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10257445/" ]
Do you really need the double dash (`--`) before your command? If not, you could do: ```py import argparse parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='command') show_subparser = subparsers.add_parser('show') show_subparser.add_argument('name', type=str) list_subparser = subparsers.add_parser('list') add_subparser = subparsers.add_parser('add') add_subparser.add_argument('phone', type=int) args = parser.parse_args() # Do something with your args print args ``` This would limit you to the above defined arguments. Inasmuch you can do either `prog show xyz` or `prog add 123` but you can't do `prog show xzy add 123`.
I generally prefer the [`click`](http://click.pocoo.org/6/) library for this sort of thing. Your example (without the `--` in front of the commands) could be done like: ### Code: ``` import click @click.group() def cli(): """My Cool Tool""" @cli.command() @click.argument('name') def show(name): """Shows the contact based on the given name provided as argument""" click.echo('Show me some cool things about {}'.format(name)) @cli.command('list') def list_cmd(): """Prints all the contacts""" click.echo('Here are some contacts') @cli.command() @click.argument('name') @click.option('--number', required=True, help='The Phone Number for the new contact') @click.option('--email', required=True, help='Email address for the new contact') def add(name, number, email): """Adds a new contact by this name""" click.echo('Name: {}'.format(name)) click.echo('Number: {}'.format(number)) click.echo('Email: {}'.format(email)) ``` ### Test Code: ``` if __name__ == "__main__": commands = ( 'show a_name', 'list', 'add a_name --number 123 --email e@mail', '', 'show --help', 'list --help', 'add --help', ) import sys, time time.sleep(1) print('Click Version: {}'.format(click.__version__)) print('Python Version: {}'.format(sys.version)) for cmd in commands: try: time.sleep(0.1) print('-----------') print('> ' + cmd) time.sleep(0.1) cli(cmd.split()) except BaseException as exc: if str(exc) != '0' and \ not isinstance(exc, (click.ClickException, SystemExit)): raise ``` ### Test Results: ``` Click Version: 6.7 Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] ----------- > show a_name Show me some cool things about a_name ----------- > list Here are some contacts ----------- > add a_name --number 123 --email e@mail Name: a_name Number: 123 Email: e@mail ----------- > Usage: test.py [OPTIONS] COMMAND [ARGS]... My Cool Tool Options: --help Show this message and exit. Commands: add Adds a new contact by this name list Prints all the contacts show Shows the contact based on the given name... ----------- > show --help Usage: test.py show [OPTIONS] NAME Shows the contact based on the given name provided as argument Options: --help Show this message and exit. ----------- > list --help Usage: test.py list [OPTIONS] Prints all the contacts Options: --help Show this message and exit. ----------- > add --help Usage: test.py add [OPTIONS] NAME Adds a new contact by this name Options: --number TEXT The Phone Number for the new contact [required] --email TEXT Email address for the new contact [required] --help Show this message and exit. ```
52,356,574
I am using python and selenium to test some things with fantasy football. Here is my code so far (I just started). ``` import time from selenium import webdriver driver = webdriver.Chrome('C:\\Users\\202300Fontenot\\Desktop\\3\\chromedriver.exe') driver.get('http://games.espn.com/ffl/signin?redir=http%3A%2F%2Fgames.espn.com%2Fffl%2Fclubhouse%3FseasonId%3D2018%26leagueId%3D49607%26teamId%3D4'); driver.implicitly_wait(10) time.sleep(10) search_box = driver.find_element_by_xpath('//*[@id="did-ui-view"]/div/section/section/form/section/div[1]/div/label/span[2]/input') search_box.send_keys('email@icloud.com') search_box.submit() time.sleep(5) driver.quit() ``` This just tries to enter an email address into the box. I am getting this error every time: ``` Traceback (most recent call last): File "C:\Users\202300Fontenot\Desktop\3\ESPN.py", line 8, in <module> search_box = driver.find_element_by_xpath('//*[@id="did-ui-view"]/div/section/section/form/section/div[1]/div/label/span[2]/input') File "C:\Users\202300Fontenot\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 393, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "C:\Users\202300Fontenot\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 966, in find_element 'value': value})['value'] File "C:\Users\202300Fontenot\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File "C:\Users\202300Fontenot\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="did-ui-view"]/div/section/section/form/section/div[1]/div/label/span[2]/input"} (Session info: chrome=69.0.3497.92) (Driver info: chromedriver=2.42.591088 (7b2b2dca23cca0862f674758c9a3933e685c27d5),platform=Windows NT 10.0.16299 x86_64) ``` Thanks for your help.
2018/09/16
[ "https://Stackoverflow.com/questions/52356574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10257445/" ]
You could use [`add_mutually_exclusive_group`](https://docs.python.org/2.7/library/argparse.html#mutual-exclusion) method like so: ``` from argparse import ArgumentParser parser = ArgumentParser() group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--show', help='...', action='store_true') group.add_argument('--list', help='...', action='store_true') group.add_argument('--add', type=str, help='...') parser.add_argument("--number", type=int, required=False) parser.add_argument("--email", type=str, required=False) args = parser.parse_args() if args.add: # proceed with args.number and args.email else: # ignore args.number and args.email... ``` **Output:** ``` $ python test.py usage: test.py [-h] (--show | --list | --add ADD) [--number NUMBER] [--email EMAIL] test.py: error: one of the arguments --show --list --add is required ```
I generally prefer the [`click`](http://click.pocoo.org/6/) library for this sort of thing. Your example (without the `--` in front of the commands) could be done like: ### Code: ``` import click @click.group() def cli(): """My Cool Tool""" @cli.command() @click.argument('name') def show(name): """Shows the contact based on the given name provided as argument""" click.echo('Show me some cool things about {}'.format(name)) @cli.command('list') def list_cmd(): """Prints all the contacts""" click.echo('Here are some contacts') @cli.command() @click.argument('name') @click.option('--number', required=True, help='The Phone Number for the new contact') @click.option('--email', required=True, help='Email address for the new contact') def add(name, number, email): """Adds a new contact by this name""" click.echo('Name: {}'.format(name)) click.echo('Number: {}'.format(number)) click.echo('Email: {}'.format(email)) ``` ### Test Code: ``` if __name__ == "__main__": commands = ( 'show a_name', 'list', 'add a_name --number 123 --email e@mail', '', 'show --help', 'list --help', 'add --help', ) import sys, time time.sleep(1) print('Click Version: {}'.format(click.__version__)) print('Python Version: {}'.format(sys.version)) for cmd in commands: try: time.sleep(0.1) print('-----------') print('> ' + cmd) time.sleep(0.1) cli(cmd.split()) except BaseException as exc: if str(exc) != '0' and \ not isinstance(exc, (click.ClickException, SystemExit)): raise ``` ### Test Results: ``` Click Version: 6.7 Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] ----------- > show a_name Show me some cool things about a_name ----------- > list Here are some contacts ----------- > add a_name --number 123 --email e@mail Name: a_name Number: 123 Email: e@mail ----------- > Usage: test.py [OPTIONS] COMMAND [ARGS]... My Cool Tool Options: --help Show this message and exit. Commands: add Adds a new contact by this name list Prints all the contacts show Shows the contact based on the given name... ----------- > show --help Usage: test.py show [OPTIONS] NAME Shows the contact based on the given name provided as argument Options: --help Show this message and exit. ----------- > list --help Usage: test.py list [OPTIONS] Prints all the contacts Options: --help Show this message and exit. ----------- > add --help Usage: test.py add [OPTIONS] NAME Adds a new contact by this name Options: --number TEXT The Phone Number for the new contact [required] --email TEXT Email address for the new contact [required] --help Show this message and exit. ```
12,373,445
I am trying to find the size of all chunks in one of my sharding collection. I'd like to know the **real** size, not the hint given to the mongos as a setting which I know I can find with : ``` use config db.settings.find({_id : "chunksize"}) ``` I have tried several solutions but the fact that *count* operation is very slow so this is not easy. Do you know a solution ? (shell, csharp, python, ruby, bash, I don't care) For now I have tested the following : ``` db.getSisterDB("config").chunks.find({ns : "mydb.mycollection"}).forEach(function(chunk) { db.getSisterDB("mydb").mycollection.find({},{_id : 0, partnerId , 1, id : 1}).min(chunk.min).max(chunk.max).count() }) ``` but this is too slow, I am under the impression that it does not use the index on my shard key (which is on `{partnerId : 1, id : 1}`). I have also replaced *count* by *explain* without any luck. I have also replaced the *count* with a javascript *forEach* to manually count (trying to have a *indexOnly* query that would not hit disk). I am trying to find the real size because I have seen several chunks that are far above the chunksize given as a hint (2Gb instead of 64Mb).
2012/09/11
[ "https://Stackoverflow.com/questions/12373445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277527/" ]
I think the command that would help you out the most is the [`datasize`](http://docs.mongodb.org/manual/reference/command/dataSize/) command. There is still a caveat here that the command will take longer to run in larger sized collections, so your mileage may vary. Given that, you could try something similar to the following: ``` var ns = "mydb.mycollection" //the full namespace of the collection var key = {partnerId : 1, id : 1} //the shard key of the collection db.getSiblingDB("config").chunks.find({ns : ns}).forEach(function(chunk) { var ds = db.getSiblingDB(ns.split(".")[0]).runCommand({datasize:chunk.ns,keyPattern:key,min:chunk.min,max:chunk.max}); print("Chunk: "+chunk._id +" has a size of "+ds.size+", and includes "+ds.numObjects+" objects (took "+ds.millis+"ms)") } ) ```
After some tries, there is no easier way than using a count in version <2.2 The following is the script I use with my compound shard key (partnerId, id). ``` var collection = "products"; var database = "products"; var ns =database+"."+collection; rs.slaveOk(true) db.getSiblingDB("config").chunks.find({ns : ns}).forEach(function(chunk) { pMin = chunk.min.partnerId pMax = chunk.max.partnerId midR = {partnerId : {$gt : pMin , $lt : pMax}} lowR = {partnerId : pMin, id : {$gte : chunk.min.id}} if (pMin == pMax) lowR.id = {$gte : chunk.min.id, $lt : chunk.max.id} upR = {partnerId : pMax, id : {$lt : chunk.max.id}} a = db.getSiblingDB(database).runCommand({count : collection, query : lowR, fields : {partnerId :1, _id : 0}}).n b = db.getSiblingDB(database).runCommand({count : collection, query : midR, fields : {partnerId :1, _id : 0}}).n c=0 if (pMin != pMax) c = db.getSiblingDB(database).runCommand({count : collection, query : upR, fields : {partnerId :1, _id : 0}}).n print(chunk.shard + "|"+tojson(chunk.min) +"|" +tojson(chunk.max)+"|"+a +"|"+b+"|"+ c +"|"+(a+b+c)) }) ```
53,660,036
I'm using the [Decimal](https://docs.python.org/2/library/decimal.html) class for operations that requires precision. I would like to use 'largest possible' precision. With this, I mean as precise as the system on which the program runs can handle. To set a certain precision it's simple: ``` import decimal decimal.getcontext().prec = 123 #123 decimal precision ``` I tried to figure out the maximum precision the 'Decimal' class can compute: ``` print(decimal.MAX_PREC) >> 999999999999999999 ``` So I tried to set the precision to the maximum precision (knowing it probably won't work..): ``` decimal.getcontext().prec = decimal.MAX_PREC ``` But, of course, this throws a **Memory Error** (on division) So my question is: How do I figure out the maximum precision the current system can handle? Extra info: ``` import sys print(sys.maxsize) >> 9223372036854775807 ```
2018/12/06
[ "https://Stackoverflow.com/questions/53660036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3701072/" ]
I'd like to suggest a function that allows you to estimate your maximum precision for a given operation in a brute force way: ``` def find_optimum(a,b, max_iter): for i in range(max_iter): print(i) c = int((a+b)/2) decimal.getcontext().prec = c try: dummy = decimal.Decimal(1)/decimal.Decimal(7) #your operation a = c print("no fail") except MemoryError: print("fail") dummy = 1 b = c print(c) del dummy ``` This is just halving intervals one step at a time and looks if an error occurs. Calling with `max_iter=10` and `a=int(1e9), b=int(1e11)` gives: ``` >>> find_optimum(int(1e9), int(1e11), 10) 0 fail 50500000000 1 no fail 25750000000 2 no fail 38125000000 3 no fail 44312500000 4 fail 47406250000 5 fail 45859375000 6 no fail 45085937500 7 no fail 45472656250 8 no fail 45666015625 9 no fail 45762695312 ``` This may give a rough idea of what you are dealing with. This took approx half an hour on i5-3470 and 16GB RAM so you really only would use it for testing purposes. I don't think, that there is an actual exact way of getting the maximum precision for your operation, as you'd have to have exact knowledge of the dependency of your memory usage on memory consumption. I hope this helps you at least a bit and I would really like to know, what you need that kind of precision for. **EDIT** I feel like this really needs to be added, since I read your comments under the top rated post here. Using arbitrarily high precision in this manner is not the way, that people calculate constants. You would program something, that utilizes disk space in a smart way (for example calcutating a bunch of digits in RAM and writing this bunch to a text file), but never only use RAM/swap only, because this will always limit your results. With modern algorithms to calculate pi, you don't need infinite RAM, you just put another 4TB hard drive in the machine and let it write the next digits. So far for mathematical constants. Now for physical constants: They are not precise. They rely on measurement. I'm not quite sure atm (will edit) but I think the *most exact* physical constant has an error of 10\*\*(-8). Throwing more precision at it, doesn't make it more exact, you just calculate more wrong numbers. As an experiment though, this was a fun idea, which is why I even posted the answer in the first place.
The maximum precision of the Decimal class is a function of the memory on the device, so there's no good way to set it for the general case. Basically, you're allocating all of the memory on the machine to one variable to get the maximum precision. If the mathematical operation supports it, long integers will give you unlimited precision. However, you are limited to whole numbers. Addition, subtraction, multiplication, and simple exponents can be performed exactly with long integers. Prior to Python 3, the built-in `long` data type would perform arbitrary precision calculations. <https://docs.python.org/2/library/functions.html#long> In Python >=3, the `int` data type now represents long integers. <https://docs.python.org/3/library/functions.html#int> One example of a 64-bit integer math is implementation is bitcoind, where transactions calculations require exact values. However, the precision of Bitcoin transactions is limited to 1 "Satoshi"; each Bitcoin is defined as 10^8 (integer) Satoshi. The Decimal class works similarly under the hood. A Decimal precision of 10^-8 is similar to the Bitcoin-Satoshi paradigm.
53,660,036
I'm using the [Decimal](https://docs.python.org/2/library/decimal.html) class for operations that requires precision. I would like to use 'largest possible' precision. With this, I mean as precise as the system on which the program runs can handle. To set a certain precision it's simple: ``` import decimal decimal.getcontext().prec = 123 #123 decimal precision ``` I tried to figure out the maximum precision the 'Decimal' class can compute: ``` print(decimal.MAX_PREC) >> 999999999999999999 ``` So I tried to set the precision to the maximum precision (knowing it probably won't work..): ``` decimal.getcontext().prec = decimal.MAX_PREC ``` But, of course, this throws a **Memory Error** (on division) So my question is: How do I figure out the maximum precision the current system can handle? Extra info: ``` import sys print(sys.maxsize) >> 9223372036854775807 ```
2018/12/06
[ "https://Stackoverflow.com/questions/53660036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3701072/" ]
Trying to do this is a mistake. Throwing more precision at a problem is a tempting trap for newcomers to floating-point, but it's not that useful, especially to this extreme. Your operations wouldn't actually require the "largest possible" precision even if that was a well-defined notion. Either they require *exact* arithmetic, in which case `decimal.Decimal` is the wrong tool entirely and you should look into something like `fractions.Fraction` or symbolic computation, or they don't require that much precision, and you should determine how much precision you *actually need* and use that. If you still want to throw all the precision you can at your problem, then how much precision that actually is will depend on what kind of math you're doing, and how many absurdly precise numbers you're attempting to store in memory at once. This can be determined by analyzing your program and the memory requirements of `Decimal` objects, or you can instead take the precision as a parameter and binary search for the largest precision that doesn't cause a crash.
I'd like to suggest a function that allows you to estimate your maximum precision for a given operation in a brute force way: ``` def find_optimum(a,b, max_iter): for i in range(max_iter): print(i) c = int((a+b)/2) decimal.getcontext().prec = c try: dummy = decimal.Decimal(1)/decimal.Decimal(7) #your operation a = c print("no fail") except MemoryError: print("fail") dummy = 1 b = c print(c) del dummy ``` This is just halving intervals one step at a time and looks if an error occurs. Calling with `max_iter=10` and `a=int(1e9), b=int(1e11)` gives: ``` >>> find_optimum(int(1e9), int(1e11), 10) 0 fail 50500000000 1 no fail 25750000000 2 no fail 38125000000 3 no fail 44312500000 4 fail 47406250000 5 fail 45859375000 6 no fail 45085937500 7 no fail 45472656250 8 no fail 45666015625 9 no fail 45762695312 ``` This may give a rough idea of what you are dealing with. This took approx half an hour on i5-3470 and 16GB RAM so you really only would use it for testing purposes. I don't think, that there is an actual exact way of getting the maximum precision for your operation, as you'd have to have exact knowledge of the dependency of your memory usage on memory consumption. I hope this helps you at least a bit and I would really like to know, what you need that kind of precision for. **EDIT** I feel like this really needs to be added, since I read your comments under the top rated post here. Using arbitrarily high precision in this manner is not the way, that people calculate constants. You would program something, that utilizes disk space in a smart way (for example calcutating a bunch of digits in RAM and writing this bunch to a text file), but never only use RAM/swap only, because this will always limit your results. With modern algorithms to calculate pi, you don't need infinite RAM, you just put another 4TB hard drive in the machine and let it write the next digits. So far for mathematical constants. Now for physical constants: They are not precise. They rely on measurement. I'm not quite sure atm (will edit) but I think the *most exact* physical constant has an error of 10\*\*(-8). Throwing more precision at it, doesn't make it more exact, you just calculate more wrong numbers. As an experiment though, this was a fun idea, which is why I even posted the answer in the first place.
53,660,036
I'm using the [Decimal](https://docs.python.org/2/library/decimal.html) class for operations that requires precision. I would like to use 'largest possible' precision. With this, I mean as precise as the system on which the program runs can handle. To set a certain precision it's simple: ``` import decimal decimal.getcontext().prec = 123 #123 decimal precision ``` I tried to figure out the maximum precision the 'Decimal' class can compute: ``` print(decimal.MAX_PREC) >> 999999999999999999 ``` So I tried to set the precision to the maximum precision (knowing it probably won't work..): ``` decimal.getcontext().prec = decimal.MAX_PREC ``` But, of course, this throws a **Memory Error** (on division) So my question is: How do I figure out the maximum precision the current system can handle? Extra info: ``` import sys print(sys.maxsize) >> 9223372036854775807 ```
2018/12/06
[ "https://Stackoverflow.com/questions/53660036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3701072/" ]
I'd like to suggest a function that allows you to estimate your maximum precision for a given operation in a brute force way: ``` def find_optimum(a,b, max_iter): for i in range(max_iter): print(i) c = int((a+b)/2) decimal.getcontext().prec = c try: dummy = decimal.Decimal(1)/decimal.Decimal(7) #your operation a = c print("no fail") except MemoryError: print("fail") dummy = 1 b = c print(c) del dummy ``` This is just halving intervals one step at a time and looks if an error occurs. Calling with `max_iter=10` and `a=int(1e9), b=int(1e11)` gives: ``` >>> find_optimum(int(1e9), int(1e11), 10) 0 fail 50500000000 1 no fail 25750000000 2 no fail 38125000000 3 no fail 44312500000 4 fail 47406250000 5 fail 45859375000 6 no fail 45085937500 7 no fail 45472656250 8 no fail 45666015625 9 no fail 45762695312 ``` This may give a rough idea of what you are dealing with. This took approx half an hour on i5-3470 and 16GB RAM so you really only would use it for testing purposes. I don't think, that there is an actual exact way of getting the maximum precision for your operation, as you'd have to have exact knowledge of the dependency of your memory usage on memory consumption. I hope this helps you at least a bit and I would really like to know, what you need that kind of precision for. **EDIT** I feel like this really needs to be added, since I read your comments under the top rated post here. Using arbitrarily high precision in this manner is not the way, that people calculate constants. You would program something, that utilizes disk space in a smart way (for example calcutating a bunch of digits in RAM and writing this bunch to a text file), but never only use RAM/swap only, because this will always limit your results. With modern algorithms to calculate pi, you don't need infinite RAM, you just put another 4TB hard drive in the machine and let it write the next digits. So far for mathematical constants. Now for physical constants: They are not precise. They rely on measurement. I'm not quite sure atm (will edit) but I think the *most exact* physical constant has an error of 10\*\*(-8). Throwing more precision at it, doesn't make it more exact, you just calculate more wrong numbers. As an experiment though, this was a fun idea, which is why I even posted the answer in the first place.
From your reply above: > > What if I just wanted to find more digits in pi than already found? what if I wanted to test the irrationality of e or mill's constant. > > > I get it. I really do. My [one SO question](https://stackoverflow.com/questions/16369616/multiprecision-python-library-that-plays-well-with-boostmultiprecision-or-othe), several years old, is about arbitrary-precision floating point libraries for Python. If those are the types of numerical representations you want to generate, be prepared for the deep dive. Decimal/FP arithmetic is [notoriously tricky](https://docs.python.org/3.7/tutorial/floatingpoint.html) in Computer Science. > > Some programmers, when confronted with a problem, think “I know, I’ll use floating point arithmetic.” Now they have 1.999999999997 problems. – [@tomscott](https://henrikwarne.com/2017/09/16/more-good-programming-quotes-part-2/) > > > I think when others have said it's a "mistake" or "it depends" to wonder what the max precision is for a Python Decimal type on a given platform, they're taking your question more literally than I'm guessing it was intended. You asked about the Python Decimal type, but if you're interested in FP arithmetic for educational purposes -- "to find more digits in pi" -- you're going to need more powerful, more flexible tools than [Decimal](https://docs.python.org/3.7/library/decimal.html?highlight=decimal#module-decimal) or [float](https://docs.python.org/3.7/library/functions.html#float). These built-in Python types don't even come *close*. Those are good enough for NASA maybe, but they have limits... in fact, the very limits you are asking about. That's what multiple-precision (or [arbitrary-precision](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic)) floating point libraries are for: arbitrarily-precise representations. Want to compute *pi* for the next 20 years? Python's Decimal type won't even get you through the *day*. The fact is, multi-precision binary FP arithmetic is still kinda fringe science. For Python, you'll need to install the [GNU MPFR](https://www.mpfr.org/) library on your Linux box, then you can use the Python library [gmpy2](https://pypi.org/project/gmpy2/) to dive as deep as you like. Then, the question isn't, "What's the max precision my program can use?" It's, "How do I write my program so that it'll run until the electricity goes out?" And that's a whole other problem, but at least it's restricted by your algorithm, not the hardware it runs on.
53,660,036
I'm using the [Decimal](https://docs.python.org/2/library/decimal.html) class for operations that requires precision. I would like to use 'largest possible' precision. With this, I mean as precise as the system on which the program runs can handle. To set a certain precision it's simple: ``` import decimal decimal.getcontext().prec = 123 #123 decimal precision ``` I tried to figure out the maximum precision the 'Decimal' class can compute: ``` print(decimal.MAX_PREC) >> 999999999999999999 ``` So I tried to set the precision to the maximum precision (knowing it probably won't work..): ``` decimal.getcontext().prec = decimal.MAX_PREC ``` But, of course, this throws a **Memory Error** (on division) So my question is: How do I figure out the maximum precision the current system can handle? Extra info: ``` import sys print(sys.maxsize) >> 9223372036854775807 ```
2018/12/06
[ "https://Stackoverflow.com/questions/53660036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3701072/" ]
Trying to do this is a mistake. Throwing more precision at a problem is a tempting trap for newcomers to floating-point, but it's not that useful, especially to this extreme. Your operations wouldn't actually require the "largest possible" precision even if that was a well-defined notion. Either they require *exact* arithmetic, in which case `decimal.Decimal` is the wrong tool entirely and you should look into something like `fractions.Fraction` or symbolic computation, or they don't require that much precision, and you should determine how much precision you *actually need* and use that. If you still want to throw all the precision you can at your problem, then how much precision that actually is will depend on what kind of math you're doing, and how many absurdly precise numbers you're attempting to store in memory at once. This can be determined by analyzing your program and the memory requirements of `Decimal` objects, or you can instead take the precision as a parameter and binary search for the largest precision that doesn't cause a crash.
The maximum precision of the Decimal class is a function of the memory on the device, so there's no good way to set it for the general case. Basically, you're allocating all of the memory on the machine to one variable to get the maximum precision. If the mathematical operation supports it, long integers will give you unlimited precision. However, you are limited to whole numbers. Addition, subtraction, multiplication, and simple exponents can be performed exactly with long integers. Prior to Python 3, the built-in `long` data type would perform arbitrary precision calculations. <https://docs.python.org/2/library/functions.html#long> In Python >=3, the `int` data type now represents long integers. <https://docs.python.org/3/library/functions.html#int> One example of a 64-bit integer math is implementation is bitcoind, where transactions calculations require exact values. However, the precision of Bitcoin transactions is limited to 1 "Satoshi"; each Bitcoin is defined as 10^8 (integer) Satoshi. The Decimal class works similarly under the hood. A Decimal precision of 10^-8 is similar to the Bitcoin-Satoshi paradigm.
53,660,036
I'm using the [Decimal](https://docs.python.org/2/library/decimal.html) class for operations that requires precision. I would like to use 'largest possible' precision. With this, I mean as precise as the system on which the program runs can handle. To set a certain precision it's simple: ``` import decimal decimal.getcontext().prec = 123 #123 decimal precision ``` I tried to figure out the maximum precision the 'Decimal' class can compute: ``` print(decimal.MAX_PREC) >> 999999999999999999 ``` So I tried to set the precision to the maximum precision (knowing it probably won't work..): ``` decimal.getcontext().prec = decimal.MAX_PREC ``` But, of course, this throws a **Memory Error** (on division) So my question is: How do I figure out the maximum precision the current system can handle? Extra info: ``` import sys print(sys.maxsize) >> 9223372036854775807 ```
2018/12/06
[ "https://Stackoverflow.com/questions/53660036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3701072/" ]
Trying to do this is a mistake. Throwing more precision at a problem is a tempting trap for newcomers to floating-point, but it's not that useful, especially to this extreme. Your operations wouldn't actually require the "largest possible" precision even if that was a well-defined notion. Either they require *exact* arithmetic, in which case `decimal.Decimal` is the wrong tool entirely and you should look into something like `fractions.Fraction` or symbolic computation, or they don't require that much precision, and you should determine how much precision you *actually need* and use that. If you still want to throw all the precision you can at your problem, then how much precision that actually is will depend on what kind of math you're doing, and how many absurdly precise numbers you're attempting to store in memory at once. This can be determined by analyzing your program and the memory requirements of `Decimal` objects, or you can instead take the precision as a parameter and binary search for the largest precision that doesn't cause a crash.
From your reply above: > > What if I just wanted to find more digits in pi than already found? what if I wanted to test the irrationality of e or mill's constant. > > > I get it. I really do. My [one SO question](https://stackoverflow.com/questions/16369616/multiprecision-python-library-that-plays-well-with-boostmultiprecision-or-othe), several years old, is about arbitrary-precision floating point libraries for Python. If those are the types of numerical representations you want to generate, be prepared for the deep dive. Decimal/FP arithmetic is [notoriously tricky](https://docs.python.org/3.7/tutorial/floatingpoint.html) in Computer Science. > > Some programmers, when confronted with a problem, think “I know, I’ll use floating point arithmetic.” Now they have 1.999999999997 problems. – [@tomscott](https://henrikwarne.com/2017/09/16/more-good-programming-quotes-part-2/) > > > I think when others have said it's a "mistake" or "it depends" to wonder what the max precision is for a Python Decimal type on a given platform, they're taking your question more literally than I'm guessing it was intended. You asked about the Python Decimal type, but if you're interested in FP arithmetic for educational purposes -- "to find more digits in pi" -- you're going to need more powerful, more flexible tools than [Decimal](https://docs.python.org/3.7/library/decimal.html?highlight=decimal#module-decimal) or [float](https://docs.python.org/3.7/library/functions.html#float). These built-in Python types don't even come *close*. Those are good enough for NASA maybe, but they have limits... in fact, the very limits you are asking about. That's what multiple-precision (or [arbitrary-precision](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic)) floating point libraries are for: arbitrarily-precise representations. Want to compute *pi* for the next 20 years? Python's Decimal type won't even get you through the *day*. The fact is, multi-precision binary FP arithmetic is still kinda fringe science. For Python, you'll need to install the [GNU MPFR](https://www.mpfr.org/) library on your Linux box, then you can use the Python library [gmpy2](https://pypi.org/project/gmpy2/) to dive as deep as you like. Then, the question isn't, "What's the max precision my program can use?" It's, "How do I write my program so that it'll run until the electricity goes out?" And that's a whole other problem, but at least it's restricted by your algorithm, not the hardware it runs on.
58,934,170
Consider an HTML File (with name 'index.html'), which contains a code for making a drop down menu. This code is shown below : ``` <select name = "from_length"> <option value = "choose_1" {{ select_1_1 }}>Metre</option> <option value = "choose_2" {{ select_1_2 }} >Kilometre</option> <option value = "choose_3" {{ select_1_3 }}>Millimetre</option> </select> ``` Above code creates a drop down menu in HTML. The ' {{ }} ' braces will be rendered by Jinja, where one of 'select\_1\_1', 'select\_1\_2' or 'select\_1\_3' will be finally passed a value "selected". That is, when I try to render the above code with the help of render\_template in Flask, by the following code: ``` return render_template('index.html', select_1_2 = "selected") ``` The above code shall be rendered as below: ``` <select name = "from_length"> <option value = "choose_1">Metre</option> <option value = "choose_2" selected >Kilometre</option> <option value = "choose_3">Millimetre</option> </select> ``` This means that when the webpage index.html shall be displayed to the user, the user shall see 'Kilometre' by default on the drop down menu (and not 'metre', which is the first option) So, in short, I am trying to display the user a default list option (i.e. either one of 'Metre', 'Kilometre' or 'Millimetre'). The default list option depends on the choice of user, and therefore, might vary. Now, I come to the pythonic part of my question. Suppose a variable named `a_string` stores which out of `{{select_1_1}}`, `{{select_1_2}}` or `{{select_1_3}}` shall be passed as "selected" to render\_template. So, if I wanted that 'select\_1\_2' should be the selected option (i.e if I want the user to see 'Kilometre' by default when the webpage is opened), then, a\_string shall be storing 'select\_1\_2', or: ``` a_string = "select_1_2" ``` As I have mentioned, the string contained by `a_string` may change depending upon the user behavior with the webpage. Now I face a dilemma here. Suppose `a_string` stores "select\_1\_2" (i.e. I expect the default option to be shown to the user as 'Kilometre'). When I try to put the following code in python, (with the intention that the default option being shown to the user shall be 'Kilometre'): ``` return render_template('index.html',a_string = "selected") ``` I get 'Metre' (which is the first option) being displayed on the web page (instead of 'Kilometre'). So, I wanted to know, if there is way by which I can pass the string stored in `a_string` as `selected` while using render\_template. Thanks in advance for helping me out.
2019/11/19
[ "https://Stackoverflow.com/questions/58934170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11588863/" ]
There a couple of ways of approaching this question. I think the simplest answer is "do it a different way". Rather than embedding the menu statically in your HTML, you should generate it: ``` <select name = "from_length"> {% for optval, optinfo in options.items() %} <option value="optval" {% if optinfo.selected|default(false) %}selected{% endif %}> {{ optinfo.name }} </option> {% endfor %} </select> ``` Then in your Python code, you would define the menu: ``` options = { 'choose_1': {'name': 'Metre'}, 'choose_2': {'name': 'Kilometre'}, 'choose_3': {'name': 'Millimetre'}, } options['choose_2']['selected'] = True ``` This makes handling the "which item is selected" logic much easier. --- However, to continue with your original approach, if you have: ``` a_string = "select_1_2" ``` Then you can call `render_template` like this: ``` return render_template('index.html', **{a_string: "selected"}) ```
I am not sure, if I understood your question correctly. Your goal is to dynamically pre-selected an option in a dropdown? If this is the case, create the option labels from a list and pass an integer which indicates which options should be pre-select. ```py render_tempalte('index.html', options=["Meter", "Kilometer", "Millimeter"], preselect= 1) ``` **index.html snipped** ```html <select name = "from_length"> {% for option in options%} {% if loop.index0 == preselect %} <option selected>{{option}}</option> {% else %} <option>{{option}}</option> {% endif %} {% endfor %} </select> ``` PS: You might want to pass a list of tuples (instead of just a list), if you also want to control the values besides the labels of the options.
58,934,170
Consider an HTML File (with name 'index.html'), which contains a code for making a drop down menu. This code is shown below : ``` <select name = "from_length"> <option value = "choose_1" {{ select_1_1 }}>Metre</option> <option value = "choose_2" {{ select_1_2 }} >Kilometre</option> <option value = "choose_3" {{ select_1_3 }}>Millimetre</option> </select> ``` Above code creates a drop down menu in HTML. The ' {{ }} ' braces will be rendered by Jinja, where one of 'select\_1\_1', 'select\_1\_2' or 'select\_1\_3' will be finally passed a value "selected". That is, when I try to render the above code with the help of render\_template in Flask, by the following code: ``` return render_template('index.html', select_1_2 = "selected") ``` The above code shall be rendered as below: ``` <select name = "from_length"> <option value = "choose_1">Metre</option> <option value = "choose_2" selected >Kilometre</option> <option value = "choose_3">Millimetre</option> </select> ``` This means that when the webpage index.html shall be displayed to the user, the user shall see 'Kilometre' by default on the drop down menu (and not 'metre', which is the first option) So, in short, I am trying to display the user a default list option (i.e. either one of 'Metre', 'Kilometre' or 'Millimetre'). The default list option depends on the choice of user, and therefore, might vary. Now, I come to the pythonic part of my question. Suppose a variable named `a_string` stores which out of `{{select_1_1}}`, `{{select_1_2}}` or `{{select_1_3}}` shall be passed as "selected" to render\_template. So, if I wanted that 'select\_1\_2' should be the selected option (i.e if I want the user to see 'Kilometre' by default when the webpage is opened), then, a\_string shall be storing 'select\_1\_2', or: ``` a_string = "select_1_2" ``` As I have mentioned, the string contained by `a_string` may change depending upon the user behavior with the webpage. Now I face a dilemma here. Suppose `a_string` stores "select\_1\_2" (i.e. I expect the default option to be shown to the user as 'Kilometre'). When I try to put the following code in python, (with the intention that the default option being shown to the user shall be 'Kilometre'): ``` return render_template('index.html',a_string = "selected") ``` I get 'Metre' (which is the first option) being displayed on the web page (instead of 'Kilometre'). So, I wanted to know, if there is way by which I can pass the string stored in `a_string` as `selected` while using render\_template. Thanks in advance for helping me out.
2019/11/19
[ "https://Stackoverflow.com/questions/58934170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11588863/" ]
There a couple of ways of approaching this question. I think the simplest answer is "do it a different way". Rather than embedding the menu statically in your HTML, you should generate it: ``` <select name = "from_length"> {% for optval, optinfo in options.items() %} <option value="optval" {% if optinfo.selected|default(false) %}selected{% endif %}> {{ optinfo.name }} </option> {% endfor %} </select> ``` Then in your Python code, you would define the menu: ``` options = { 'choose_1': {'name': 'Metre'}, 'choose_2': {'name': 'Kilometre'}, 'choose_3': {'name': 'Millimetre'}, } options['choose_2']['selected'] = True ``` This makes handling the "which item is selected" logic much easier. --- However, to continue with your original approach, if you have: ``` a_string = "select_1_2" ``` Then you can call `render_template` like this: ``` return render_template('index.html', **{a_string: "selected"}) ```
@larsks's answer is the best Pythonic approach, however, if you do not want to greatly restructure the data that you are passing to the template, you can simply use Jquery: In your template, pass back the HTML `value` of the `option` tag that you wish to be selected: ``` return render_template('index.html', to_select = "choose_2") #for 'Kilometre' to be selected ``` Then, in your template: ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <select name = "from_length" data-select='{{to_select}}' id='select_pannel'> <option value = "choose_1">Metre</option> <option value = "choose_2" >Kilometre</option> <option value = "choose_3">Millimetre</option> </select> <script> $(document).ready(function(){ var to_select = $("#select_pannel").data('select'); $('option').each(function(){ if ($(this).val() === to_select){ $(this).attr('selected', true) } }); }); </script> ```
41,385,530
I'm working through "Automate the Boring Stuff with Python" and am running Python 3.6 with a Mac running OS X v. 10.9.5. My version of Firefox is 50.0. Whenever I type in (per the instructions in chapter 11): ``` >>> from selenium import webdriver >>> browser = webdriver.Firefox() ``` I get the following error: ``` Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 74, in start stdout=self.log_file, stderr=self.log_file) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 707, in __init__ restore_signals, start_new_session) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1326, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'geckodriver' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> browser = webdriver.Firefox() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 140, in __init__ self.service.start() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 81, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. ``` I have searched this error on this site and others, but most of the solutions offered are Windows-specific (including the post referenced in the comment below), or do not seem to work on my Mac machine when applied. Any suggestions on what I should do? Please keep in mind that I'm a total novice, and so less than familiar with the terminal. Thank you in advance for your help.
2016/12/29
[ "https://Stackoverflow.com/questions/41385530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5335236/" ]
I delved into the source code for webdriver and the Firefox driver: I had to give the Firefox() constructor a direct path to the geckodriver binary, like ``` self.browser = webdriver.Firefox(executable_path='/usr/local/bin/geckodriver') ```
Thanks all for your replies. Per the comments, installing Homebrew and running the ``` brew install geckodriver ``` command did not alone solve the problem. Restarting Terminal also didn't solve things. I dug around on a few other posts, and tried opening the /usr/bin and /usr/local/bin files through the Mac Finder, and manually copied the geckodriver file into the folder. The first time I entered: ``` browser = webdriver.Firefox() ``` into the Python IDLE, I got the following warning/exceptions: ``` Exception ignored in: <bound method Service.__del__ of <selenium.webdriver.firefox.service.Service object at 0x101a960b8>> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 173, in __del__ self.stop() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 145, in stop if self.process is None: AttributeError: 'Service' object has no attribute 'process' Exception ignored in: <bound method Service.__del__ of <selenium.webdriver.firefox.service.Service object at 0x1071b3eb8>> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 173, in __del__ self.stop() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 145, in stop if self.process is None: AttributeError: 'Service' object has no attribute 'process' ``` but the browser opened. When I ran it again, I was able to follow along as in the book without any errors or exceptions. It seems that this has worked. However, it feels wrong to have done all this through the Mac finder rather than Terminal. I'm still very new to all this, so if there's anything I did that will damage my system, I'd appreciate any pointers. Thanks for your help.
44,725,201
I have a list of 10,000+ Matplotlib Polygon objects. Each polygon belongs to 1 of 20 groups. I want to differentiate which group a polygon belongs to by mapping each unique group to a unique color. Here are some posts I've found with similar issues to mine: [Fill polygons with multiple colors in python matplotlib](https://stackoverflow.com/questions/27432367/fill-polygons-with-multiple-colors-in-python-matplotlib) [How to fill polygons with colors based on a variable in Matplotlib?](https://stackoverflow.com/questions/32141476/how-to-fill-polygons-with-colors-based-on-a-variable-in-matplotlib) [How do I set color to Rectangle in Matplotlib?](https://stackoverflow.com/questions/10550477/how-do-i-set-color-to-rectangle-in-matplotlib) These solutions simply apply a random color to each shape in the list. That is not what I am looking for. For me, each shape belonging to a particular group should have the same color. Any ideas? Sample code: ``` from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon from matplotlib import pyplot as plt patches = [] colors = [] num_polys = 10000 for i in range(num_polys): patches.append(Polygon(poly_vertices[i], closed=True)) colors.append(poly_colors[i]) # This line is pointless, but I'm letting you know that # I have a particular color for each polygon fig, ax = plt.subplots() p = PatchCollection(patches, alpha=0.25) ax.add_collection(p) ax.autoscale() plt.show() ``` Note that if you run this code, it won't work because poly\_vertices and poly\_colors haven't been defined. For now, just assume that poly\_vertices is a list of polygon vertices, and poly\_colors is a list of RGB colors and each list has 10000 entries. For example: poly\_vertices[0] = [(0, 0), (1, 0), (0, 1)], colors[0] = [1, 0, 0] Thank you!
2017/06/23
[ "https://Stackoverflow.com/questions/44725201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4642522/" ]
Okay, I figured out what I was trying to do. I'll post the answer for anyone who may be having similar issues. For some reason, setting the color in the polygon itself doesn't work. i.e. ``` Polygon(vertices, color=[1, 0, 0]) ``` does not work. Instead, after adding all the polygons to a collection, use ``` p = PatchCollection(patches) p.set_color([1, 0, 0]) ``` But I still want to group polygons by color. Therefore I need to add multiple PatchCollections -- one for each group type! My original list of polygons were in no particular order, so the first polygon may belong to group 5, while its neighbor belongs to group 1, etc. So, I first sorted the list by group number such that all polygons belonging to a particular group were right next to each other. I then iterated through the sorted list and appended each polygon to a temporary list. Upon reaching a new group type, I knew it was time to add all the polygons in the temporary list to their own PatchCollection. Here's some code for this logic: ``` a = [x for x in original_groups] # The original group numbers (unsorted) idx = sorted(range(len(a)), key=lambda k: a[k]) # Get indices of sorted group numbers current_group = original_groups[idx[0]] # Set the current group to the be the first sorted group number temp_patches = [] # Create a temporary patch list for i in idx: # iterate through the sorted indices if current_group == original_groups[i]: # Detect whether a change in group number has occured temp_patches.append(original_patches[i]) # Add patch to the temporary variable since group number didn't change else: p = PatchCollection(temp_patches, alpha=0.6) # Add all patches belonging to the current group number to a PatchCollection p.set_color([random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)]) # Set all shapes belonging to this group to the same random color ax.add_collection(p) # Add all shapes belonging this group to the axes object current_group = original_groups[i] # The group number has changed, so update the current group number temp_patches = [original_patches[i]] # Reset temp_patches, to begin collecting patches of the next group number p = PatchCollection(temp_patches, alpha=0.6) # temp_patches currently contains the patches belonging to the last group. Add them to a PatchCollection p.set_color([random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)]) ax.add_collection(p) ax.autoscale() # Default scale may not capture the appropriate region plt.show() ```
By turning on the match\_original option, you can set the color of polygons individually (e.g. `Polygon(vertices, color=[1, 0, 0])`) ``` PatchCollection(patches, match_original=True) ```
71,595,897
i want to ask how to get the image result (Icon) with python code as indicated in ![enter image description here](https://i.stack.imgur.com/m3aAU.png) where ishade is a preprocessed image and std(Ishade) is the standard deviation of this image ``` result = ndimage.median_filter(blur, size=68) std=cv2.meanStdDev(result) ```
2022/03/24
[ "https://Stackoverflow.com/questions/71595897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18562827/" ]
It is not SQL\_INTERGER, it is SQL\_INTEGER. As listed in the [documentation](https://metacpan.org/pod/DBI). You should know that removing `use strict` doesn't solve problems, it hides them. It might feel comforting, but it doesn't help.
You can use instead: ``` $sth->bind_param(1,5374,4); $sth->bind_param(2,1,4); $sth->execute; ```
53,983,796
I'm trying to redirect output of python script to a file. When output contains non-ascii characters it works on macOS and Linux, but not on Windows. I've deduced the problem to a simple test. The following is what is shown in Windows command prompt window. The test is only one print call. ``` Microsoft Windows [Version 10.0.17134.472] (c) 2018 Microsoft Corporation. All rights reserved. D:\>set PY PYTHONIOENCODING=utf-8 D:\>type pipetest.py print('\u0422\u0435\u0441\u0442') D:\>python pipetest.py Тест D:\>python pipetest.py > test.txt D:\>type test.txt ╨ó╨╡╤ü╤é D:\>type test.txt | iconv -f utf-8 -t utf-8 Тест D:\>set PYTHONIOENCODING= D:\>python pipetest.py Тест D:\>python pipetest.py > test.txt Traceback (most recent call last): File "pipetest.py", line 1, in <module> print('\u0422\u0435\u0441\u0442') File "C:\Python\Python37\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-3: character maps to <undefined> D:\>python -V Python 3.7.2 ``` As one can see setting PYTHONIOENCODING environment variable helps but I don't understand why it needed to be set. When output is terminal it works but if output is a file it fails. Why does cp1252 is used when stdout is not a console? Maybe it is a bug and can be fixed in Windows version of python?
2018/12/31
[ "https://Stackoverflow.com/questions/53983796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1335557/" ]
Based on Python documentation, Windows version use different character encoding on console device (utr-8) and non-character devices such as disk files and pipes (system locale). PYTHONIOENCODING can be used to override it. <https://docs.python.org/3/library/sys.html#sys.stdout> Another method is change the encoding directly in the program, I tried and it works fine. ``` sys.stdout.reconfigure(encoding='utf-8') ``` <https://docs.python.org/3/library/io.html#io.TextIOWrapper.reconfigure>
Python needs to write **binary data** to `stdout` (not strings) hence requirement for **encoding** parameter. Encoding (used to convert strings into bytes) is determined differently for each platform: * on Linux and macOS it comes from current locale; * on Windows what is used is "Current language for non-Unicode programs" (codepage set in command line window is irrelevant). (Thanks to @Eric Leung for precise link) The follow up question would be why Python on Windows uses current system locale for non-Unicode programs, and not what is set by `chcp` command, but I will leave it for someone else. Also it needs to be mentioned there's a checkbox titled "Beta: Use Unicode UTF-8..." in Region Settings on Windows 10 (to open - Win+R, type `intl.cpl`). By checking the checkbox the above example works without error. But this checkbox is off by default and really deep in system settings.
3,324,920
I currently work with Python for a while and I came to the point where I questioned myself whether I should use "Properties" in Python as often as in C#. In C# I've mostly created properties for the majority of my classes. It seems that properties are not that popular in python, am I wrong? How to use properties in Python? regards,
2010/07/24
[ "https://Stackoverflow.com/questions/3324920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/189122/" ]
Properties are often no required if all you do is set and query member variables. Because Python has no concept of encapsulation, all member variables are public and often there is no need to encapsulate accesses. However, properties are possible, perfectly legitimate and popular: ``` class C(object): def __init__(self): self._x = 0 @property def x(self): return self._x @x.setter def x(self, value): if value <= 0: raise ValueError("Value must be positive") self._x = value o = C() print o.x o.x = 5 print o.x o.x = -2 ```
I would you recommend to read this, even it is directed to Java progrmamers: [Python Is Not Java](http://dirtsimple.org/2004/12/python-is-not-java.html)
3,324,920
I currently work with Python for a while and I came to the point where I questioned myself whether I should use "Properties" in Python as often as in C#. In C# I've mostly created properties for the majority of my classes. It seems that properties are not that popular in python, am I wrong? How to use properties in Python? regards,
2010/07/24
[ "https://Stackoverflow.com/questions/3324920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/189122/" ]
I would you recommend to read this, even it is directed to Java progrmamers: [Python Is Not Java](http://dirtsimple.org/2004/12/python-is-not-java.html)
If you make an attribute public in C# then later need to change it into a property you also need to recompile all code that uses the original class. This is bad, so make any public attributes into properties from day one 'just in case'. If you have an attribute that is used from other code then later need to change it into a property then you just change it and nothing else needs to happen. So use ordinary attributes until such time as you find you need something more complicated.
3,324,920
I currently work with Python for a while and I came to the point where I questioned myself whether I should use "Properties" in Python as often as in C#. In C# I've mostly created properties for the majority of my classes. It seems that properties are not that popular in python, am I wrong? How to use properties in Python? regards,
2010/07/24
[ "https://Stackoverflow.com/questions/3324920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/189122/" ]
Properties are often no required if all you do is set and query member variables. Because Python has no concept of encapsulation, all member variables are public and often there is no need to encapsulate accesses. However, properties are possible, perfectly legitimate and popular: ``` class C(object): def __init__(self): self._x = 0 @property def x(self): return self._x @x.setter def x(self, value): if value <= 0: raise ValueError("Value must be positive") self._x = value o = C() print o.x o.x = 5 print o.x o.x = -2 ```
If you make an attribute public in C# then later need to change it into a property you also need to recompile all code that uses the original class. This is bad, so make any public attributes into properties from day one 'just in case'. If you have an attribute that is used from other code then later need to change it into a property then you just change it and nothing else needs to happen. So use ordinary attributes until such time as you find you need something more complicated.
58,267,326
this code groups a N-by-2 array, ``` df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6]}) df.groupby('a')['b'].apply(list) ``` by the values in first column ``` [['A' '1'] ['A' '2'] ['B' '5'] ['B' '5'] ['B' '4'] ['C' '6']] ``` and get this result (output\_1) ``` a A [1, 2] B [5, 5, 4] C [6] Name: b, dtype: object ``` I am trying to do this job without pandas ``` from itertools import groupby from operator import itemgetter list(groupby(ds,key = itemgetter(0))) ``` it seems that I grouped the data array successfully, ``` [('A', <itertools._grouper at 0x121f779e8>), ('B', <itertools._grouper at 0x121f77588>), ('C', <itertools._grouper at 0x121f77400>)] ``` right now, I am stuck on getting these elements. ``` list(list(groupby(ds,key = itemgetter(0)))[0][1]) ``` gave me a empty list `[]` how to get a group of lists like output\_1 with python without pandas?
2019/10/07
[ "https://Stackoverflow.com/questions/58267326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As you can see from your first attempt, `groupby` yields the key and an iterator to each elements that fits the key as each of its items. You can extract the data using a list comprehension : ``` [(key, [elem[1] for elem in it]) for key, it in groupby(ds,key = itemgetter(0))] ``` or, as dict: ``` {key: [elem[1] for elem in it] for key, it in groupby(ds, key=itemgetter(0))} ```
```py from collections import defaultdict ds = [ ['A', '1'], ['A', '2'], ['B', '5'], ['B', '5'], ['B', '4'], ['C', '6']] groups = defaultdict(list) for key, value in ds: groups[key].append(value) print(groups) ``` Output: ``` defaultdict(<class 'list'>, {'A': ['1', '2'], 'B': ['5', '5', '4'], 'C': ['6']}) ``` You can convert the defaultdict to a list, if you want with ```py list(groups.items()) ```
58,267,326
this code groups a N-by-2 array, ``` df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6]}) df.groupby('a')['b'].apply(list) ``` by the values in first column ``` [['A' '1'] ['A' '2'] ['B' '5'] ['B' '5'] ['B' '4'] ['C' '6']] ``` and get this result (output\_1) ``` a A [1, 2] B [5, 5, 4] C [6] Name: b, dtype: object ``` I am trying to do this job without pandas ``` from itertools import groupby from operator import itemgetter list(groupby(ds,key = itemgetter(0))) ``` it seems that I grouped the data array successfully, ``` [('A', <itertools._grouper at 0x121f779e8>), ('B', <itertools._grouper at 0x121f77588>), ('C', <itertools._grouper at 0x121f77400>)] ``` right now, I am stuck on getting these elements. ``` list(list(groupby(ds,key = itemgetter(0)))[0][1]) ``` gave me a empty list `[]` how to get a group of lists like output\_1 with python without pandas?
2019/10/07
[ "https://Stackoverflow.com/questions/58267326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use defaultdict from collections. ``` from collections import defaultdict my_dict = {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6]} results = defaultdict(list) for index, value in zip(my_dict['a'], my_dict['b']: results[index].append(value) ``` Now we have grouped value for a given index, we can get back to the desired output like this ``` final = defaultdict(list) for key, value in results.items(): final["a"].append(key) final["b"].append(value) ``` final result should looking like this : ``` {"a" : ["A", "B", "C"], "b" : [[1, 2], [5, 5, 4], [6]]} ```
```py from collections import defaultdict ds = [ ['A', '1'], ['A', '2'], ['B', '5'], ['B', '5'], ['B', '4'], ['C', '6']] groups = defaultdict(list) for key, value in ds: groups[key].append(value) print(groups) ``` Output: ``` defaultdict(<class 'list'>, {'A': ['1', '2'], 'B': ['5', '5', '4'], 'C': ['6']}) ``` You can convert the defaultdict to a list, if you want with ```py list(groups.items()) ```
58,267,326
this code groups a N-by-2 array, ``` df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6]}) df.groupby('a')['b'].apply(list) ``` by the values in first column ``` [['A' '1'] ['A' '2'] ['B' '5'] ['B' '5'] ['B' '4'] ['C' '6']] ``` and get this result (output\_1) ``` a A [1, 2] B [5, 5, 4] C [6] Name: b, dtype: object ``` I am trying to do this job without pandas ``` from itertools import groupby from operator import itemgetter list(groupby(ds,key = itemgetter(0))) ``` it seems that I grouped the data array successfully, ``` [('A', <itertools._grouper at 0x121f779e8>), ('B', <itertools._grouper at 0x121f77588>), ('C', <itertools._grouper at 0x121f77400>)] ``` right now, I am stuck on getting these elements. ``` list(list(groupby(ds,key = itemgetter(0)))[0][1]) ``` gave me a empty list `[]` how to get a group of lists like output\_1 with python without pandas?
2019/10/07
[ "https://Stackoverflow.com/questions/58267326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use defaultdict from collections. ``` from collections import defaultdict my_dict = {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6]} results = defaultdict(list) for index, value in zip(my_dict['a'], my_dict['b']: results[index].append(value) ``` Now we have grouped value for a given index, we can get back to the desired output like this ``` final = defaultdict(list) for key, value in results.items(): final["a"].append(key) final["b"].append(value) ``` final result should looking like this : ``` {"a" : ["A", "B", "C"], "b" : [[1, 2], [5, 5, 4], [6]]} ```
As you can see from your first attempt, `groupby` yields the key and an iterator to each elements that fits the key as each of its items. You can extract the data using a list comprehension : ``` [(key, [elem[1] for elem in it]) for key, it in groupby(ds,key = itemgetter(0))] ``` or, as dict: ``` {key: [elem[1] for elem in it] for key, it in groupby(ds, key=itemgetter(0))} ```
53,033,664
I have this `docker-compose.yml` file: ``` version: '2' services: nginx: image: nginx:latest container_name: nz01 ports: - "8001:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d depends_on: - web web: build: . container_name: dz01 depends_on: - db volumes: - ./src:/src expose: - "8000" db: image: postgres:latest container_name: pz01 ports: - "5433:5432" volumes: - postgres_database:/var/lib/postgresql/data:Z volumes: postgres_database: external: true ``` And this dockerfile: ``` FROM python:3.5 ENV PYTHONUNBUFFERED 1 RUN mkdir /src RUN mkdir /static WORKDIR /src ADD ./src /src RUN pip install -r requirements.pip CMD python manage.py collectstatic --no-input;python manage.py migrate; gunicorn computationalMarketing.wsgi -b 0.0.0.0:8000 ``` The web and postgres server does not return an error log, just the success when I run `docker-compose build` and `docker-compose up -d`. At this moment the three containers are running, but when I go to the browser and navigate to: `localhost:8001` it does not work. It shows the "connection has been restarted" error message. Despite that, the web server still does not return any error, so I guess that I have everything properly configurated in my Django app. I really believe that the problem is related to `Nginx`, because when I review the `Nginx log` (using kinematic) it is still empty. Why wouldn't Nginx be listening to connections? **Hint:** This error is happening in a new project. I tried to understand whether I have anything wrong, I'm running an old project and it works perfectly. I tried to copy the working project in my new folder and remove all existent containers and then try to run this old project in a new folder and there is the surprise. It does not work now, despite being an exact copy of the project that works in the other folder... **EDIT** In my repo I have a `config/nginx` folder with the `helloworld.conf` file: ``` upstream web { ip_hash; server web:8000; } server { location /static/ { autoindex on; alias /src/static/; } location / { proxy_pass http://web/; } listen 8001; server_name localhost; } ``` Still with the same error... I do not see any log error. **Django container log** ``` Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. [2018-11-05 13:00:09 +0000] [8] [INFO] Starting gunicorn 19.7.1 [2018-11-05 13:00:09 +0000] [8] [INFO] Listening at: http://0.0.0.0:8000 (8) [2018-11-05 13:00:09 +0000] [8] [INFO] Using worker: sync [2018-11-05 13:00:09 +0000] [11] [INFO] Booting worker with pid: 11 ```
2018/10/28
[ "https://Stackoverflow.com/questions/53033664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5556466/" ]
I came up with this regex that takes into account potential newlines. ``` https:\/\/www\..+?\/=?(?:\s*?)?u(?:\s*?)?=?(?:\s*?)?\/.*?u ``` Basically, I use `(?:\s*?)?` which is an optional, non-capturing, lazy match of any number of whitespace characters, including newlines. If you want to restrict it to just newlines, use `\n` instead. [Here's](https://regex101.com/r/hx7Hri/1) a demo.
I have changed your regex to support '`=`' and `White Space` (incl. `Newlines`). This the regex: ``` https:\/\/www\..+?\/[u=\s]+\/[\w=\s]+\/[u=\s]+ ``` What I have changed is to use character classes instead of literal matches. That way the '=' and Newlines are effectively ignored and it will match all your examples. The only 'problem' is that I removed the '`{18}`' quantifier (since those bad characters take up room). **Edit** as per the comment: ``` https:\/\/www\.[\s\S]+?\/[u=\s]+\/[\w=\s]+\/[u=\s]+ ``` I have changed a dot '`.`' to the character class '`[\s\S]`'. Now there can be `Newlines` in the url as well. About the 18 quantifier: There's 20 chars in your second example, so it won't match if you limit that string.
61,866,394
I am using sqlalchemy and the create\_engine to connect to mysql, build a database and start populating with relevant data. edit, to preface, the database in question needs to be first created. to do this I perform the following commands ``` database_address = 'mysql+pymysql://{0}:{1}@{2}:{3}' database_address = database_address.format('username', 'password', 'ip_address', 'port') engine = create_engine(database_address, echo=False) Database_Name = 'DatabaseName' engine.execute(("Create Databse {0}").format(Database_Name) ``` Following creation of the database, I try to perform a 'use' command but end up receiving the following error ``` line 3516, in _escape_identifier value = value.replace(self.escape_quote, self.escape_to_quote) AttributeError: 'NoneType' object has no attribute 'replace' ``` I traced the error to a post which stated that this occurs when using the following command in python 3 ``` engine.execute("USE dbname") ``` What else needs to be included in the execute command to access the mysql database and not throw an error.
2020/05/18
[ "https://Stackoverflow.com/questions/61866394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7408848/" ]
You shouldn't use the `USE` command - instead you should specify the database you wish to connect to in the `create_engine` connection url - i.e.: ``` database_address = 'mysql+pymysql://{0}:{1}@{2}:{3}/{4}' database_address = database_address.format('username', 'password', 'ip_address', 'port', 'database') engine = create_engine(database_address, echo=False) ``` The `create_engine` docs are here: <https://docs.sqlalchemy.org/en/13/core/engines.html#mysql>
Figured out what to do, Following advise from Match, I looked into SQLAlchemy and it's ability to create schema. Found the following code ``` from sqlalchemy import create_engine from sqlalchemy_utils import database_exists, create_database database_address = 'mysql+pymysql://{0}:{1}@{2}:{3}/{4}?charset=utf8mb4' database_address = database_address.format('username','password','address','port','DB') engine = create_engine(database_address, echo=False) if not database_exists(self.engine.url): create_database(self.engine.url) ``` So creating an engine with the Schema name identified, I can use the utility `database_exists` to see if the database does exist, if not, then create using the `create_database` function.
17,381,146
I am new to python and i am not sure how this is working. Code is as below: ``` class test(): d=0 def __init__(self): self.d=self.d+1; D=test() print D.d D1=test() print D1.d D2=test() print D2.d ``` Output is ``` 1,1,1 # This should not be ``` Now using this : ``` class test(): d=[] def __init__(self): self.d.apend("1"); D=test() print D.d D1=test() print D1.d D2=test() print D2.d ``` Result is (This should be) ``` ['1'] ['1', '1'] ['1', '1', '1'] ``` So i am not sure why integer value is not being treated as class variable while list is being treated.
2013/06/29
[ "https://Stackoverflow.com/questions/17381146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1708351/" ]
In the first example, ``` self.d = self.d + 1 ``` *rebinds* `self.d`, making it independent of `test.d`. In the second example, ``` self.d.append("1") ``` *modifies* `test.d`. To see that for yourself, print `id(self.d)` at the end of both constructors. If you modified the second example to match the first: ``` self.d = self.d + ["1"] ``` you'd see that the behaviour would also change to match.
To address a class variable use class\_name.variable\_name, giving : ``` class test(object): d=0 def __init__(self): test.d = test.d + 1; ```
17,381,146
I am new to python and i am not sure how this is working. Code is as below: ``` class test(): d=0 def __init__(self): self.d=self.d+1; D=test() print D.d D1=test() print D1.d D2=test() print D2.d ``` Output is ``` 1,1,1 # This should not be ``` Now using this : ``` class test(): d=[] def __init__(self): self.d.apend("1"); D=test() print D.d D1=test() print D1.d D2=test() print D2.d ``` Result is (This should be) ``` ['1'] ['1', '1'] ['1', '1', '1'] ``` So i am not sure why integer value is not being treated as class variable while list is being treated.
2013/06/29
[ "https://Stackoverflow.com/questions/17381146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1708351/" ]
In the first example, ``` self.d = self.d + 1 ``` *rebinds* `self.d`, making it independent of `test.d`. In the second example, ``` self.d.append("1") ``` *modifies* `test.d`. To see that for yourself, print `id(self.d)` at the end of both constructors. If you modified the second example to match the first: ``` self.d = self.d + ["1"] ``` you'd see that the behaviour would also change to match.
NPE's answer tells you what is going wrong with your code. However, I'm not sure that it really tells you how to solve the issue properly. Here's what I think you want, if each `test` instance should have a different `d` value in an instance variable: ``` class test(object): # new style class, since we inherit from "object" _d = 0 # this is a class variable, which I've named _d to avoid confusion def __init__(self): self.d = test._d # assign current value of class variable to an instance variable test._d += 1 # increment the class variable ``` Now, you can create multiple instances and each one will get a unique value for `d`: ``` >>> D0 = test() >>> D1 = test() >>> D2 = test() >>> print D0.d 0 >>> print D1.d 1 >>> print D2.d 2 ```
17,381,146
I am new to python and i am not sure how this is working. Code is as below: ``` class test(): d=0 def __init__(self): self.d=self.d+1; D=test() print D.d D1=test() print D1.d D2=test() print D2.d ``` Output is ``` 1,1,1 # This should not be ``` Now using this : ``` class test(): d=[] def __init__(self): self.d.apend("1"); D=test() print D.d D1=test() print D1.d D2=test() print D2.d ``` Result is (This should be) ``` ['1'] ['1', '1'] ['1', '1', '1'] ``` So i am not sure why integer value is not being treated as class variable while list is being treated.
2013/06/29
[ "https://Stackoverflow.com/questions/17381146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1708351/" ]
If you want to modify a class variable, do: ``` class test(object): d=0 def __init__(self): type(self).d=self.d+1; D=test() print D.d D1=test() print D1.d D2=test() print D2.d ``` You don't need the `type` on the right hand side of the assignment, because this way you never create an instance variable `d`. Note that new-style classes are necessary to this. `type` is a function (actually a callable - it is also a class; but don't worry about that for now) which returns the class of its argument. So, `type(self)` returns the class of `self`. Classes are first class objects in Python. Demo here: <http://ideone.com/JdNpiV> Update: An alternative would be to use a `classmethod`.
To address a class variable use class\_name.variable\_name, giving : ``` class test(object): d=0 def __init__(self): test.d = test.d + 1; ```
17,381,146
I am new to python and i am not sure how this is working. Code is as below: ``` class test(): d=0 def __init__(self): self.d=self.d+1; D=test() print D.d D1=test() print D1.d D2=test() print D2.d ``` Output is ``` 1,1,1 # This should not be ``` Now using this : ``` class test(): d=[] def __init__(self): self.d.apend("1"); D=test() print D.d D1=test() print D1.d D2=test() print D2.d ``` Result is (This should be) ``` ['1'] ['1', '1'] ['1', '1', '1'] ``` So i am not sure why integer value is not being treated as class variable while list is being treated.
2013/06/29
[ "https://Stackoverflow.com/questions/17381146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1708351/" ]
If you want to modify a class variable, do: ``` class test(object): d=0 def __init__(self): type(self).d=self.d+1; D=test() print D.d D1=test() print D1.d D2=test() print D2.d ``` You don't need the `type` on the right hand side of the assignment, because this way you never create an instance variable `d`. Note that new-style classes are necessary to this. `type` is a function (actually a callable - it is also a class; but don't worry about that for now) which returns the class of its argument. So, `type(self)` returns the class of `self`. Classes are first class objects in Python. Demo here: <http://ideone.com/JdNpiV> Update: An alternative would be to use a `classmethod`.
NPE's answer tells you what is going wrong with your code. However, I'm not sure that it really tells you how to solve the issue properly. Here's what I think you want, if each `test` instance should have a different `d` value in an instance variable: ``` class test(object): # new style class, since we inherit from "object" _d = 0 # this is a class variable, which I've named _d to avoid confusion def __init__(self): self.d = test._d # assign current value of class variable to an instance variable test._d += 1 # increment the class variable ``` Now, you can create multiple instances and each one will get a unique value for `d`: ``` >>> D0 = test() >>> D1 = test() >>> D2 = test() >>> print D0.d 0 >>> print D1.d 1 >>> print D2.d 2 ```
59,035,409
I am trying to fire http posts via python. The `requests` module is installed via `pip3 install requests` - it also says now "Requirement satisfied", so it is installed. I am using Python version `3.8.0`. **The Code:** ``` import requests as r headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'} url = 'http://localhost:8083/push/message' jsons = {"test"} r.post(url, json=jsons, headers=headers) ``` **Error:** ``` Traceback (most recent call last): File "http.py", line 1, in <module> import requests as r File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\__init__.py", line 43, in <module> import urllib3 File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\__init__.py", line 7, in <module> from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 11, in <module> from .exceptions import ( File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\exceptions.py", line 2, in <module> from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 199, in load_module mod = mod._resolve() File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 113, in _resolve return _import_module(self.mod) File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 82, in _import_module __import__(name) File "C:\scripts\http.py", line 5, in <module> r.post(url, json=jsons, headers=headers) AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` When I close the commandline and start a new one and then go into `python` I can import it: ``` C:\Windows\system32>python Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> requests.post <function post at 0x000001A4F7B9D310> >>> ``` Same thing happens (only sometimes) when I execute the script - sometimes it actually works. (Btw, when it works it also posts to the server like it is supposed to) Did anyone face a similar problem and might come up with a solution? Python 3 is the only Python-Version i have installed on this machine btw - yet facing a similar problem on other machines!
2019/11/25
[ "https://Stackoverflow.com/questions/59035409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5524954/" ]
Thanks Unixia your answer help me in some way :) But I have some improvement,I got the same error and it was because I had named my file to `requests.py` which produced a conflict with the original requests library
As per above discussion, We need to check the filename that we are executing and it should not match with any attributes the module has. We can check this using below: ``` import requests \ print(dir(requests)) ``` After we know that we are not using any of the attributes for the concerned module, We also need to make sure that any other file in the current directory should also not have any of the attribute name. I was facing the same error.
59,035,409
I am trying to fire http posts via python. The `requests` module is installed via `pip3 install requests` - it also says now "Requirement satisfied", so it is installed. I am using Python version `3.8.0`. **The Code:** ``` import requests as r headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'} url = 'http://localhost:8083/push/message' jsons = {"test"} r.post(url, json=jsons, headers=headers) ``` **Error:** ``` Traceback (most recent call last): File "http.py", line 1, in <module> import requests as r File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\__init__.py", line 43, in <module> import urllib3 File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\__init__.py", line 7, in <module> from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 11, in <module> from .exceptions import ( File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\exceptions.py", line 2, in <module> from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 199, in load_module mod = mod._resolve() File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 113, in _resolve return _import_module(self.mod) File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 82, in _import_module __import__(name) File "C:\scripts\http.py", line 5, in <module> r.post(url, json=jsons, headers=headers) AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` When I close the commandline and start a new one and then go into `python` I can import it: ``` C:\Windows\system32>python Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> requests.post <function post at 0x000001A4F7B9D310> >>> ``` Same thing happens (only sometimes) when I execute the script - sometimes it actually works. (Btw, when it works it also posts to the server like it is supposed to) Did anyone face a similar problem and might come up with a solution? Python 3 is the only Python-Version i have installed on this machine btw - yet facing a similar problem on other machines!
2019/11/25
[ "https://Stackoverflow.com/questions/59035409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5524954/" ]
**Circular dependency** : It occurs when two or more modules depend on each other. This is due to the fact that each module is defined in terms of the other. If you are getting **circular import** error similar to below request module error. ``` AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` `Please try to rename the file.` The error for this error is usually due to conflict with the file name where you are trying to import the `requests` module. I was also having same problem, where my file name was `email.py` and I was trying to import the requests module. So, it was having some conflict with `email.parser`. So, I changed the file name from `email.py` to `email1.py` and it worked. For more info on circular dependency: <https://stackabuse.com/python-circular-imports/>
This issue also happens if you have a file named token.py in your path. That is the case with Python 3.8.9 and Requests Version: 2.28.1 on Mac OS 12.4.
59,035,409
I am trying to fire http posts via python. The `requests` module is installed via `pip3 install requests` - it also says now "Requirement satisfied", so it is installed. I am using Python version `3.8.0`. **The Code:** ``` import requests as r headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'} url = 'http://localhost:8083/push/message' jsons = {"test"} r.post(url, json=jsons, headers=headers) ``` **Error:** ``` Traceback (most recent call last): File "http.py", line 1, in <module> import requests as r File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\__init__.py", line 43, in <module> import urllib3 File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\__init__.py", line 7, in <module> from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 11, in <module> from .exceptions import ( File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\exceptions.py", line 2, in <module> from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 199, in load_module mod = mod._resolve() File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 113, in _resolve return _import_module(self.mod) File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 82, in _import_module __import__(name) File "C:\scripts\http.py", line 5, in <module> r.post(url, json=jsons, headers=headers) AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` When I close the commandline and start a new one and then go into `python` I can import it: ``` C:\Windows\system32>python Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> requests.post <function post at 0x000001A4F7B9D310> >>> ``` Same thing happens (only sometimes) when I execute the script - sometimes it actually works. (Btw, when it works it also posts to the server like it is supposed to) Did anyone face a similar problem and might come up with a solution? Python 3 is the only Python-Version i have installed on this machine btw - yet facing a similar problem on other machines!
2019/11/25
[ "https://Stackoverflow.com/questions/59035409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5524954/" ]
There may be other problems with your script that I have not checked but the error you're getting is because your file is named `http.py`. It seems like it is being used elsewhere and you're having circular import issues. Change the name of the file.
This issue also happens if you have a file named token.py in your path. That is the case with Python 3.8.9 and Requests Version: 2.28.1 on Mac OS 12.4.
59,035,409
I am trying to fire http posts via python. The `requests` module is installed via `pip3 install requests` - it also says now "Requirement satisfied", so it is installed. I am using Python version `3.8.0`. **The Code:** ``` import requests as r headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'} url = 'http://localhost:8083/push/message' jsons = {"test"} r.post(url, json=jsons, headers=headers) ``` **Error:** ``` Traceback (most recent call last): File "http.py", line 1, in <module> import requests as r File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\__init__.py", line 43, in <module> import urllib3 File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\__init__.py", line 7, in <module> from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 11, in <module> from .exceptions import ( File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\exceptions.py", line 2, in <module> from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 199, in load_module mod = mod._resolve() File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 113, in _resolve return _import_module(self.mod) File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 82, in _import_module __import__(name) File "C:\scripts\http.py", line 5, in <module> r.post(url, json=jsons, headers=headers) AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` When I close the commandline and start a new one and then go into `python` I can import it: ``` C:\Windows\system32>python Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> requests.post <function post at 0x000001A4F7B9D310> >>> ``` Same thing happens (only sometimes) when I execute the script - sometimes it actually works. (Btw, when it works it also posts to the server like it is supposed to) Did anyone face a similar problem and might come up with a solution? Python 3 is the only Python-Version i have installed on this machine btw - yet facing a similar problem on other machines!
2019/11/25
[ "https://Stackoverflow.com/questions/59035409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5524954/" ]
Thanks Unixia your answer help me in some way :) But I have some improvement,I got the same error and it was because I had named my file to `requests.py` which produced a conflict with the original requests library
There may be other problems with your script that I have not checked but the error you're getting is because your file is named `http.py`. It seems like it is being used elsewhere and you're having circular import issues. Change the name of the file.
59,035,409
I am trying to fire http posts via python. The `requests` module is installed via `pip3 install requests` - it also says now "Requirement satisfied", so it is installed. I am using Python version `3.8.0`. **The Code:** ``` import requests as r headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'} url = 'http://localhost:8083/push/message' jsons = {"test"} r.post(url, json=jsons, headers=headers) ``` **Error:** ``` Traceback (most recent call last): File "http.py", line 1, in <module> import requests as r File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\__init__.py", line 43, in <module> import urllib3 File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\__init__.py", line 7, in <module> from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 11, in <module> from .exceptions import ( File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\exceptions.py", line 2, in <module> from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 199, in load_module mod = mod._resolve() File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 113, in _resolve return _import_module(self.mod) File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 82, in _import_module __import__(name) File "C:\scripts\http.py", line 5, in <module> r.post(url, json=jsons, headers=headers) AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` When I close the commandline and start a new one and then go into `python` I can import it: ``` C:\Windows\system32>python Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> requests.post <function post at 0x000001A4F7B9D310> >>> ``` Same thing happens (only sometimes) when I execute the script - sometimes it actually works. (Btw, when it works it also posts to the server like it is supposed to) Did anyone face a similar problem and might come up with a solution? Python 3 is the only Python-Version i have installed on this machine btw - yet facing a similar problem on other machines!
2019/11/25
[ "https://Stackoverflow.com/questions/59035409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5524954/" ]
**Circular dependency** : It occurs when two or more modules depend on each other. This is due to the fact that each module is defined in terms of the other. If you are getting **circular import** error similar to below request module error. ``` AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` `Please try to rename the file.` The error for this error is usually due to conflict with the file name where you are trying to import the `requests` module. I was also having same problem, where my file name was `email.py` and I was trying to import the requests module. So, it was having some conflict with `email.parser`. So, I changed the file name from `email.py` to `email1.py` and it worked. For more info on circular dependency: <https://stackabuse.com/python-circular-imports/>
Same issue here, definitely a file name problem. Remember never to name your .py scripts with names of modules which already exist, especially if you're sure you're using them in your project. E.g. In my case I had a requests.py importing the module requests, same can happen for http.py, etc.
59,035,409
I am trying to fire http posts via python. The `requests` module is installed via `pip3 install requests` - it also says now "Requirement satisfied", so it is installed. I am using Python version `3.8.0`. **The Code:** ``` import requests as r headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'} url = 'http://localhost:8083/push/message' jsons = {"test"} r.post(url, json=jsons, headers=headers) ``` **Error:** ``` Traceback (most recent call last): File "http.py", line 1, in <module> import requests as r File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\__init__.py", line 43, in <module> import urllib3 File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\__init__.py", line 7, in <module> from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 11, in <module> from .exceptions import ( File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\exceptions.py", line 2, in <module> from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 199, in load_module mod = mod._resolve() File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 113, in _resolve return _import_module(self.mod) File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 82, in _import_module __import__(name) File "C:\scripts\http.py", line 5, in <module> r.post(url, json=jsons, headers=headers) AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` When I close the commandline and start a new one and then go into `python` I can import it: ``` C:\Windows\system32>python Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> requests.post <function post at 0x000001A4F7B9D310> >>> ``` Same thing happens (only sometimes) when I execute the script - sometimes it actually works. (Btw, when it works it also posts to the server like it is supposed to) Did anyone face a similar problem and might come up with a solution? Python 3 is the only Python-Version i have installed on this machine btw - yet facing a similar problem on other machines!
2019/11/25
[ "https://Stackoverflow.com/questions/59035409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5524954/" ]
**Circular dependency** : It occurs when two or more modules depend on each other. This is due to the fact that each module is defined in terms of the other. If you are getting **circular import** error similar to below request module error. ``` AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` `Please try to rename the file.` The error for this error is usually due to conflict with the file name where you are trying to import the `requests` module. I was also having same problem, where my file name was `email.py` and I was trying to import the requests module. So, it was having some conflict with `email.parser`. So, I changed the file name from `email.py` to `email1.py` and it worked. For more info on circular dependency: <https://stackabuse.com/python-circular-imports/>
As per above discussion, We need to check the filename that we are executing and it should not match with any attributes the module has. We can check this using below: ``` import requests \ print(dir(requests)) ``` After we know that we are not using any of the attributes for the concerned module, We also need to make sure that any other file in the current directory should also not have any of the attribute name. I was facing the same error.
59,035,409
I am trying to fire http posts via python. The `requests` module is installed via `pip3 install requests` - it also says now "Requirement satisfied", so it is installed. I am using Python version `3.8.0`. **The Code:** ``` import requests as r headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'} url = 'http://localhost:8083/push/message' jsons = {"test"} r.post(url, json=jsons, headers=headers) ``` **Error:** ``` Traceback (most recent call last): File "http.py", line 1, in <module> import requests as r File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\__init__.py", line 43, in <module> import urllib3 File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\__init__.py", line 7, in <module> from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 11, in <module> from .exceptions import ( File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\exceptions.py", line 2, in <module> from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 199, in load_module mod = mod._resolve() File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 113, in _resolve return _import_module(self.mod) File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 82, in _import_module __import__(name) File "C:\scripts\http.py", line 5, in <module> r.post(url, json=jsons, headers=headers) AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` When I close the commandline and start a new one and then go into `python` I can import it: ``` C:\Windows\system32>python Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> requests.post <function post at 0x000001A4F7B9D310> >>> ``` Same thing happens (only sometimes) when I execute the script - sometimes it actually works. (Btw, when it works it also posts to the server like it is supposed to) Did anyone face a similar problem and might come up with a solution? Python 3 is the only Python-Version i have installed on this machine btw - yet facing a similar problem on other machines!
2019/11/25
[ "https://Stackoverflow.com/questions/59035409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5524954/" ]
Thanks Unixia your answer help me in some way :) But I have some improvement,I got the same error and it was because I had named my file to `requests.py` which produced a conflict with the original requests library
This issue also happens if you have a file named token.py in your path. That is the case with Python 3.8.9 and Requests Version: 2.28.1 on Mac OS 12.4.
59,035,409
I am trying to fire http posts via python. The `requests` module is installed via `pip3 install requests` - it also says now "Requirement satisfied", so it is installed. I am using Python version `3.8.0`. **The Code:** ``` import requests as r headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'} url = 'http://localhost:8083/push/message' jsons = {"test"} r.post(url, json=jsons, headers=headers) ``` **Error:** ``` Traceback (most recent call last): File "http.py", line 1, in <module> import requests as r File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\__init__.py", line 43, in <module> import urllib3 File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\__init__.py", line 7, in <module> from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 11, in <module> from .exceptions import ( File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\exceptions.py", line 2, in <module> from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 199, in load_module mod = mod._resolve() File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 113, in _resolve return _import_module(self.mod) File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 82, in _import_module __import__(name) File "C:\scripts\http.py", line 5, in <module> r.post(url, json=jsons, headers=headers) AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` When I close the commandline and start a new one and then go into `python` I can import it: ``` C:\Windows\system32>python Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> requests.post <function post at 0x000001A4F7B9D310> >>> ``` Same thing happens (only sometimes) when I execute the script - sometimes it actually works. (Btw, when it works it also posts to the server like it is supposed to) Did anyone face a similar problem and might come up with a solution? Python 3 is the only Python-Version i have installed on this machine btw - yet facing a similar problem on other machines!
2019/11/25
[ "https://Stackoverflow.com/questions/59035409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5524954/" ]
There may be other problems with your script that I have not checked but the error you're getting is because your file is named `http.py`. It seems like it is being used elsewhere and you're having circular import issues. Change the name of the file.
As per above discussion, We need to check the filename that we are executing and it should not match with any attributes the module has. We can check this using below: ``` import requests \ print(dir(requests)) ``` After we know that we are not using any of the attributes for the concerned module, We also need to make sure that any other file in the current directory should also not have any of the attribute name. I was facing the same error.
59,035,409
I am trying to fire http posts via python. The `requests` module is installed via `pip3 install requests` - it also says now "Requirement satisfied", so it is installed. I am using Python version `3.8.0`. **The Code:** ``` import requests as r headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'} url = 'http://localhost:8083/push/message' jsons = {"test"} r.post(url, json=jsons, headers=headers) ``` **Error:** ``` Traceback (most recent call last): File "http.py", line 1, in <module> import requests as r File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\__init__.py", line 43, in <module> import urllib3 File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\__init__.py", line 7, in <module> from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 11, in <module> from .exceptions import ( File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\exceptions.py", line 2, in <module> from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 199, in load_module mod = mod._resolve() File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 113, in _resolve return _import_module(self.mod) File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 82, in _import_module __import__(name) File "C:\scripts\http.py", line 5, in <module> r.post(url, json=jsons, headers=headers) AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` When I close the commandline and start a new one and then go into `python` I can import it: ``` C:\Windows\system32>python Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> requests.post <function post at 0x000001A4F7B9D310> >>> ``` Same thing happens (only sometimes) when I execute the script - sometimes it actually works. (Btw, when it works it also posts to the server like it is supposed to) Did anyone face a similar problem and might come up with a solution? Python 3 is the only Python-Version i have installed on this machine btw - yet facing a similar problem on other machines!
2019/11/25
[ "https://Stackoverflow.com/questions/59035409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5524954/" ]
Thanks Unixia your answer help me in some way :) But I have some improvement,I got the same error and it was because I had named my file to `requests.py` which produced a conflict with the original requests library
**Circular dependency** : It occurs when two or more modules depend on each other. This is due to the fact that each module is defined in terms of the other. If you are getting **circular import** error similar to below request module error. ``` AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` `Please try to rename the file.` The error for this error is usually due to conflict with the file name where you are trying to import the `requests` module. I was also having same problem, where my file name was `email.py` and I was trying to import the requests module. So, it was having some conflict with `email.parser`. So, I changed the file name from `email.py` to `email1.py` and it worked. For more info on circular dependency: <https://stackabuse.com/python-circular-imports/>
59,035,409
I am trying to fire http posts via python. The `requests` module is installed via `pip3 install requests` - it also says now "Requirement satisfied", so it is installed. I am using Python version `3.8.0`. **The Code:** ``` import requests as r headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'} url = 'http://localhost:8083/push/message' jsons = {"test"} r.post(url, json=jsons, headers=headers) ``` **Error:** ``` Traceback (most recent call last): File "http.py", line 1, in <module> import requests as r File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\__init__.py", line 43, in <module> import urllib3 File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\__init__.py", line 7, in <module> from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 11, in <module> from .exceptions import ( File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\exceptions.py", line 2, in <module> from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 199, in load_module mod = mod._resolve() File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 113, in _resolve return _import_module(self.mod) File "C:\User\name\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\packages\six.py", line 82, in _import_module __import__(name) File "C:\scripts\http.py", line 5, in <module> r.post(url, json=jsons, headers=headers) AttributeError: partially initialized module 'requests' has no attribute 'post' (most likely due to a circular import) ``` When I close the commandline and start a new one and then go into `python` I can import it: ``` C:\Windows\system32>python Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> requests.post <function post at 0x000001A4F7B9D310> >>> ``` Same thing happens (only sometimes) when I execute the script - sometimes it actually works. (Btw, when it works it also posts to the server like it is supposed to) Did anyone face a similar problem and might come up with a solution? Python 3 is the only Python-Version i have installed on this machine btw - yet facing a similar problem on other machines!
2019/11/25
[ "https://Stackoverflow.com/questions/59035409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5524954/" ]
Thanks Unixia your answer help me in some way :) But I have some improvement,I got the same error and it was because I had named my file to `requests.py` which produced a conflict with the original requests library
Same issue here, definitely a file name problem. Remember never to name your .py scripts with names of modules which already exist, especially if you're sure you're using them in your project. E.g. In my case I had a requests.py importing the module requests, same can happen for http.py, etc.
31,239,275
I quite new in programing in python. When i try to send an e-mail using python 2.7, i get an error: ``` from email.mime.text import MIMEText import smtplib msg = MIMEText("Hello There!") msg['Subject'] = 'A Test Message' msg['From']='kolsason7@walla.com' msg['To'] = 'yaron148@gmail.com' s = smtplib.SMTP('localhost') s.sendmail('kolsason7@walla.com',['yaron148@gmail.com'],msg.as_string()) print("Message Sent!") File "C:\Python27\ArcGISx6410.3\lib\socket.py", line 571, in create_connection raise err error: [Errno 10061] >>> ```
2015/07/06
[ "https://Stackoverflow.com/questions/31239275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4989939/" ]
Quoting this from [here](https://stackoverflow.com/a/4532340/3083243) > > It's because you haven't opened the port you are trying to connect to, > nothing is listening there. If you're trying to connect to a web or > ftp server, start it first. If you're trying to connect to another > port, you need to write a server application too. > > > And see a similar solved problem [here](https://stackoverflow.com/questions/10012303/why-cant-i-send-a-mail-to-myself-using-python-smtplib)
Your smtp server is set as localhost, are you sure it's right ? The error is a "connection opening". You may have to find a username/password/address/port combination for the SMTP server that you are using.
31,239,275
I quite new in programing in python. When i try to send an e-mail using python 2.7, i get an error: ``` from email.mime.text import MIMEText import smtplib msg = MIMEText("Hello There!") msg['Subject'] = 'A Test Message' msg['From']='kolsason7@walla.com' msg['To'] = 'yaron148@gmail.com' s = smtplib.SMTP('localhost') s.sendmail('kolsason7@walla.com',['yaron148@gmail.com'],msg.as_string()) print("Message Sent!") File "C:\Python27\ArcGISx6410.3\lib\socket.py", line 571, in create_connection raise err error: [Errno 10061] >>> ```
2015/07/06
[ "https://Stackoverflow.com/questions/31239275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4989939/" ]
``` import smtplib from smtplib import SMTP try: sender = 'xxx@gmail.com' receivers = ['xxx.com'] message = """ this message sending from python for testing purpose """ smtpObj = smtplib.SMTP(host='smtp.gmail.com', port=587) smtpObj.ehlo() smtpObj.starttls() smtpObj.ehlo() smtpObj.login('xxx','xxx') smtpObj.sendmail(sender, receivers, message) smtpObj.quit() print "Successfully sent email" except smtplib.SMTPException,error: print str(error) print "Error: unable to send email" ``` If u ran this code u would see a error message like this stating that google is not allowing u to login via code Things to change in gmail: 1.Login to gmail 2.Go to this link <https://www.google.com/settings/security/lesssecureapps> 3.Click enable then retry the code Hopes it help :) But there are security threats if u enable it
Your smtp server is set as localhost, are you sure it's right ? The error is a "connection opening". You may have to find a username/password/address/port combination for the SMTP server that you are using.
31,239,275
I quite new in programing in python. When i try to send an e-mail using python 2.7, i get an error: ``` from email.mime.text import MIMEText import smtplib msg = MIMEText("Hello There!") msg['Subject'] = 'A Test Message' msg['From']='kolsason7@walla.com' msg['To'] = 'yaron148@gmail.com' s = smtplib.SMTP('localhost') s.sendmail('kolsason7@walla.com',['yaron148@gmail.com'],msg.as_string()) print("Message Sent!") File "C:\Python27\ArcGISx6410.3\lib\socket.py", line 571, in create_connection raise err error: [Errno 10061] >>> ```
2015/07/06
[ "https://Stackoverflow.com/questions/31239275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4989939/" ]
Quoting this from [here](https://stackoverflow.com/a/4532340/3083243) > > It's because you haven't opened the port you are trying to connect to, > nothing is listening there. If you're trying to connect to a web or > ftp server, start it first. If you're trying to connect to another > port, you need to write a server application too. > > > And see a similar solved problem [here](https://stackoverflow.com/questions/10012303/why-cant-i-send-a-mail-to-myself-using-python-smtplib)
The code snippet you have used is not designed to be run on Windows, it is designed to be run on Linux where there is (usually) a service listening on port 25 at localhost. For Windows, you'll need to connect to an actual mail server before you can send messages.
31,239,275
I quite new in programing in python. When i try to send an e-mail using python 2.7, i get an error: ``` from email.mime.text import MIMEText import smtplib msg = MIMEText("Hello There!") msg['Subject'] = 'A Test Message' msg['From']='kolsason7@walla.com' msg['To'] = 'yaron148@gmail.com' s = smtplib.SMTP('localhost') s.sendmail('kolsason7@walla.com',['yaron148@gmail.com'],msg.as_string()) print("Message Sent!") File "C:\Python27\ArcGISx6410.3\lib\socket.py", line 571, in create_connection raise err error: [Errno 10061] >>> ```
2015/07/06
[ "https://Stackoverflow.com/questions/31239275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4989939/" ]
``` import smtplib from smtplib import SMTP try: sender = 'xxx@gmail.com' receivers = ['xxx.com'] message = """ this message sending from python for testing purpose """ smtpObj = smtplib.SMTP(host='smtp.gmail.com', port=587) smtpObj.ehlo() smtpObj.starttls() smtpObj.ehlo() smtpObj.login('xxx','xxx') smtpObj.sendmail(sender, receivers, message) smtpObj.quit() print "Successfully sent email" except smtplib.SMTPException,error: print str(error) print "Error: unable to send email" ``` If u ran this code u would see a error message like this stating that google is not allowing u to login via code Things to change in gmail: 1.Login to gmail 2.Go to this link <https://www.google.com/settings/security/lesssecureapps> 3.Click enable then retry the code Hopes it help :) But there are security threats if u enable it
The code snippet you have used is not designed to be run on Windows, it is designed to be run on Linux where there is (usually) a service listening on port 25 at localhost. For Windows, you'll need to connect to an actual mail server before you can send messages.
58,087,917
I'm trying to Docker build a django app, but I get te following message when docker tries to pip install -r requirements: ``` Collecting Django==2.2.5 (from -r requirements.txt (line 1) WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7ff789506828>: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/django/ ``` There's my Dockerfile: ``` FROM python:3.6 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY . /app RUN pip install -r requirements.txt ``` My Linux distro: ``` Linux version 4.15.0-30deepin-generic (pbuilder@zs-PC) (gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1)) #31 SMP Fri Nov 30 04:29:02 UTC 2018 ``` Not only Django, but all requirements cannot be installed. I'm not using a Proxy
2019/09/24
[ "https://Stackoverflow.com/questions/58087917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11493539/" ]
Could be a lack of network access during the build. Try: ``` docker build --network=host . ```
I had the same issue, in my case, I was connected to a VPN server, disconnecting from the VPN client resolved the issue.
29,773,574
I am getting the following error when i perform classification of new data with the following command in Python: ``` classifier.predict(new_data) ``` AttributeError: python 'SVC' object has no attribute \_dual\_coef\_ In my laptop though, the command works fine! What's wrong?
2015/04/21
[ "https://Stackoverflow.com/questions/29773574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2987488/" ]
I had this exact error `AttributeError: python 'SVC' object has no attribute _dual_coef_` with a model trained using scikit-learn version 0.15.2, when I tried to run it in scikit-learn version 0.16.1. I did solve it by re-training the model in the latest scikit-learn 0.16.1. Make sure you are loading the right version of the package.
Have you loaded the model based on which you try to predict? In this case it can be a version conflict, try to re-learn the model using the same sklearn version. You can see a similar problem here: [Sklearn error: 'SVR' object has no attribute '\_impl'](https://stackoverflow.com/questions/19089386/sklearn-error-svr-object-has-no-attribute-impl)
29,773,574
I am getting the following error when i perform classification of new data with the following command in Python: ``` classifier.predict(new_data) ``` AttributeError: python 'SVC' object has no attribute \_dual\_coef\_ In my laptop though, the command works fine! What's wrong?
2015/04/21
[ "https://Stackoverflow.com/questions/29773574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2987488/" ]
Have you loaded the model based on which you try to predict? In this case it can be a version conflict, try to re-learn the model using the same sklearn version. You can see a similar problem here: [Sklearn error: 'SVR' object has no attribute '\_impl'](https://stackoverflow.com/questions/19089386/sklearn-error-svr-object-has-no-attribute-impl)
``` """ X = X_train y = y_train """ X = X_test y = y_test # Instantiate and train the classifier from sklearn.neighbors import KNeighborsClassifier clf = KNeighborsClassifier(n_neighbors=1) clf.fit(X, y) # Check the results using metrics from sklearn import metrics y_pred = clf.predict(X) print(metrics.confusion_matrix(y_pred, y)) ```
29,773,574
I am getting the following error when i perform classification of new data with the following command in Python: ``` classifier.predict(new_data) ``` AttributeError: python 'SVC' object has no attribute \_dual\_coef\_ In my laptop though, the command works fine! What's wrong?
2015/04/21
[ "https://Stackoverflow.com/questions/29773574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2987488/" ]
I had this exact error `AttributeError: python 'SVC' object has no attribute _dual_coef_` with a model trained using scikit-learn version 0.15.2, when I tried to run it in scikit-learn version 0.16.1. I did solve it by re-training the model in the latest scikit-learn 0.16.1. Make sure you are loading the right version of the package.
``` """ X = X_train y = y_train """ X = X_test y = y_test # Instantiate and train the classifier from sklearn.neighbors import KNeighborsClassifier clf = KNeighborsClassifier(n_neighbors=1) clf.fit(X, y) # Check the results using metrics from sklearn import metrics y_pred = clf.predict(X) print(metrics.confusion_matrix(y_pred, y)) ```