qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
48,729,915
I am trying to read a `png` image in python. The `imread` function in `scipy` is being [deprecated](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.imread.html#scipy.ndimage.imread) and they recommend using `imageio` library. However, I am would rather restrict my usage of external libraries to `scipy`, `numpy` and `matplotlib` libraries. Thus, using `imageio` or `scikit image` is not a good option for me. Are there any methods in python or `scipy`, `numpy` or `matplotlib` to read images, which are not being deprecated?
2018/02/11
[ "https://Stackoverflow.com/questions/48729915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5495304/" ]
> > If you just want to **read an image in Python** using the specified > libraries only, I will go with `matplotlib` > > > **In matplotlib :** ``` import matplotlib.image read_img = matplotlib.image.imread('your_image.png') ```
I read all answers but I think one of the best method is using [openCV](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_image_display/py_image_display.html) library. ``` import cv2 img = cv2.imread('your_image.png',0) ``` and for displaying the image, use the following code : ``` from matplotlib import pyplot as plt plt.imshow(img, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show() ```
48,729,915
I am trying to read a `png` image in python. The `imread` function in `scipy` is being [deprecated](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.imread.html#scipy.ndimage.imread) and they recommend using `imageio` library. However, I am would rather restrict my usage of external libraries to `scipy`, `numpy` and `matplotlib` libraries. Thus, using `imageio` or `scikit image` is not a good option for me. Are there any methods in python or `scipy`, `numpy` or `matplotlib` to read images, which are not being deprecated?
2018/02/11
[ "https://Stackoverflow.com/questions/48729915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5495304/" ]
With matplotlib you can use (as shown in the matplotlib [documentation](https://matplotlib.org/2.0.0/users/image_tutorial.html)) ``` import matplotlib.pyplot as plt import matplotlib.image as mpimg img=mpimg.imread('image_name.png') ``` And plot the image if you want ``` imgplot = plt.imshow(img) ```
For the better answer, you can use these lines of code. Here is the example maybe help you : ``` import cv2 image = cv2.imread('/home/pictures/1.jpg') plt.imshow(image) plt.show() ``` In **`imread()`** you can pass the directory .so you can also use `str()` and `+` to combine dynamic directories and fixed directory like this: ``` path = '/home/pictures/' for i in range(2) : image = cv2.imread(str(path)+'1.jpg') plt.imshow(image) plt.show() ``` Both are the same.
34,086,675
I would like to slice an array `a` in Julia in a loop in such a way that it's divided in chunks of `n` samples. The length of the array `nsamples` is *not* a multiple of `n`, so the last stride would be shorter. My attempt would be using a ternary operator to check if the size of the stride is greater than the length of the array: ``` for i in 0:n:nsamples-1 end_ = i+n < nsamples ? i+n : end window = a[i+1:end_] end ``` In this way, `a[i+1:end_]` would resolve to `a[i+1:end]` if I'm exceeding the size of the array. However, the use of the keyword "end" in line 2 is not acceptable (it's also the keyword for "end of control statement" in julia. In python, I can assign `None` to `end_` and this would resolve to `a[i+1:None]`, which will be the end of the array. How can I get around this?
2015/12/04
[ "https://Stackoverflow.com/questions/34086675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277113/" ]
The `end` keyword is only given this kind of special treatment inside of indexing expressions, where it evaluates to the last index of the dimension being indexed. You could put it inside with e.g. ``` for i in 0:n:nsamples-1 window = a[i+1:min(i+n, end)] end ``` Or you could just use `length(a)` (or `nsamples`, I guess they are the same?) instead of `end` to make it clear which `end` you are referring to.
Ugly way: ``` a=rand(7); nsamples=7; n=3; for i in 0:n:nsamples-1 end_ = i+n < nsamples ? i+n : :end window = @eval a[$i+1:$end_] println(window) end ``` Better solution: ``` for i in 0:n:nsamples-1 window = i+n < nsamples ? a[i+1:i+n] : a[i+1:end] println(window) end ```
34,086,675
I would like to slice an array `a` in Julia in a loop in such a way that it's divided in chunks of `n` samples. The length of the array `nsamples` is *not* a multiple of `n`, so the last stride would be shorter. My attempt would be using a ternary operator to check if the size of the stride is greater than the length of the array: ``` for i in 0:n:nsamples-1 end_ = i+n < nsamples ? i+n : end window = a[i+1:end_] end ``` In this way, `a[i+1:end_]` would resolve to `a[i+1:end]` if I'm exceeding the size of the array. However, the use of the keyword "end" in line 2 is not acceptable (it's also the keyword for "end of control statement" in julia. In python, I can assign `None` to `end_` and this would resolve to `a[i+1:None]`, which will be the end of the array. How can I get around this?
2015/12/04
[ "https://Stackoverflow.com/questions/34086675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277113/" ]
Ugly way: ``` a=rand(7); nsamples=7; n=3; for i in 0:n:nsamples-1 end_ = i+n < nsamples ? i+n : :end window = @eval a[$i+1:$end_] println(window) end ``` Better solution: ``` for i in 0:n:nsamples-1 window = i+n < nsamples ? a[i+1:i+n] : a[i+1:end] println(window) end ```
In order to simplify the loop (and perhaps improve performance) the last partial window can be processed after the loop. This is recommended since it usually requires some special processing anyway. In code: ``` i = 0 # define loop variable outside for to retain it after for i=n:n:length(a) println(a[(i-n+1):i]) end i < length(a) && println(a[(i+1):end]) ``` The last bit can be done with an `if` but `&&` is pretty clear.
34,086,675
I would like to slice an array `a` in Julia in a loop in such a way that it's divided in chunks of `n` samples. The length of the array `nsamples` is *not* a multiple of `n`, so the last stride would be shorter. My attempt would be using a ternary operator to check if the size of the stride is greater than the length of the array: ``` for i in 0:n:nsamples-1 end_ = i+n < nsamples ? i+n : end window = a[i+1:end_] end ``` In this way, `a[i+1:end_]` would resolve to `a[i+1:end]` if I'm exceeding the size of the array. However, the use of the keyword "end" in line 2 is not acceptable (it's also the keyword for "end of control statement" in julia. In python, I can assign `None` to `end_` and this would resolve to `a[i+1:None]`, which will be the end of the array. How can I get around this?
2015/12/04
[ "https://Stackoverflow.com/questions/34086675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277113/" ]
The `end` keyword is only given this kind of special treatment inside of indexing expressions, where it evaluates to the last index of the dimension being indexed. You could put it inside with e.g. ``` for i in 0:n:nsamples-1 window = a[i+1:min(i+n, end)] end ``` Or you could just use `length(a)` (or `nsamples`, I guess they are the same?) instead of `end` to make it clear which `end` you are referring to.
In order to simplify the loop (and perhaps improve performance) the last partial window can be processed after the loop. This is recommended since it usually requires some special processing anyway. In code: ``` i = 0 # define loop variable outside for to retain it after for i=n:n:length(a) println(a[(i-n+1):i]) end i < length(a) && println(a[(i+1):end]) ``` The last bit can be done with an `if` but `&&` is pretty clear.
43,721,155
I'm trying to close each image opened via iteration, within each iteration. I've referred to this thread below, but the correct answer is not producing the results. [How do I close an image opened in Pillow?](https://stackoverflow.com/questions/31751464/how-do-i-close-an-image-opened-in-pillow) My code ``` for i in Final_Bioteck[:5]: with Image.open('{}_screenshot.png'.format(i)) as test_image: test_image.show() time.sleep(2) ``` I also tried, `test_image.close()` , but no result. My loop above is opening 5 Windows Photos Viewer dialogs; I was hoping that through iteration, each window would be closed. I saw this thread as well, but the answers are pretty outdated, so not sure if there is a more simple way to execute what I desire. [How can I close an image shown to the user with the Python Imaging Library?](https://stackoverflow.com/questions/6725099/how-can-i-close-an-image-shown-to-the-user-with-the-python-imaging-library) Thank you =)
2017/05/01
[ "https://Stackoverflow.com/questions/43721155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6802252/" ]
Got it working, but I installed a different image viewer on Windows as I couldn't find the .exe of the default viewer. ``` import webbrowser import subprocess import os, time for i in Final_Bioteck[6:11]: webbrowser.open( '{}.png'.format(i)) # opens the pic time.sleep(3) subprocess.run(['taskkill', '/f', '/im', "i_view64.exe"]) #taskkill kills the program, '/f' indiciates it's a process, '/'im' (not entirely sure), and i_view64.exe is the image viewers' exe file. ```
In Windows 10, the process is dllhost.exe using the same script as Moondra, except with "dllhost.exe" instead of "i\_view64.exe" ``` import webbrowser import subprocess import os, time for i in Final_Bioteck[6:11]: webbrowser.open( '{}.png'.format(i)) # opens the pic time.sleep(3) subprocess.run(['taskkill', '/f', '/im', "dllhost.exe"]) #taskkill kills the program, '/f' indicates it's a process, '/'im' (indicates the name of the image process), and "dllhost.exe" is the image viewers' exe file. ```
32,004,317
I am working on a python GUI for serial communication with some hardware.I am using USB-RS232 converter for that.I do'nt want user to look for com port of hardware in device manager and then select port no in GUI for communication.How can my python code automatically get the port no. for that particular USB port?I can connect my hardware to that particular everytime and what will happen if i run the GUI in some other PC.You can suggest any other solution for this. Thanks in advance!!!
2015/08/14
[ "https://Stackoverflow.com/questions/32004317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5036147/" ]
pyserial can list the ports with their USB VID:PID numbers. ``` from serial.tools import list_ports list_ports.comports() ``` This function returns a tuple, 3rd item is a string that may contain the USB VID:PID number. You can parse it from there. Or better, you can use the `grep` function also provided by `list_ports` module: ``` list_ports.grep("6157:9988") ``` This one returns a generator object which you can iterate over. If it's unlikely that there are 2 devices connected with the same VID:PID (I wouldn't assume that, but for testing purposes its okay) you can just do this: ``` my_port_name = list(list_ports.grep("0483:5740"))[0][0] ``` Documentation for [list\_ports](http://pyserial.readthedocs.io/en/latest/tools.html#module-serial.tools.list_ports). Note: I've tested this on linux only. pyserial documentation warns that on some systems hardware ids may not be listed.
I assume that you are specifically looking for a COM port that is described as being a USB to RS232 in the device manager, rather than wanting to list all available COM ports? Also, you have not mentioned what OS you are developing on, or the version of Python you are using, but this works for me on a Windows system using Python 3.4: ``` import serial.tools.list_ports def serial_ports(): # produce a list of all serial ports. The list contains a tuple with the port number, # description and hardware address # ports = list(serial.tools.list_ports.comports()) # return the port if 'USB' is in the description for port_no, description, address in ports: if 'USB' in description: return port_no ```
14,004,839
I have Flask, Babel and Flask-Babel installed in the global packages. When running python and I type this, no error ``` >>> from flaskext.babel import Babel >>> ``` With a virtual environment, starting python and typing the same command I see ``` >>> from flaskext.babel import Babel Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named flaskext.babel >>> ``` The problem is that I'm using Ninja-IDE and I'm apparently forced to use a virtualenv. I don't mind as long as it doesn't break Flask packing system.
2012/12/22
[ "https://Stackoverflow.com/questions/14004839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75517/" ]
I think you're supposed to import Flask extensions like the following from version 0.8 onwards: ``` from flask.ext.babel import Babel ``` I tried the old way (`import flaskext.babel`), and it didn't work for me either.
The old way of importing Flask extension was like: ``` import flaskext.babel ``` [Namespace packages](https://stackoverflow.com/questions/1675734/how-do-i-create-a-namespace-package-in-python) were, however, "too painful for everybody involved", so now Flask extensions should be importable like: ``` import flask_babel ``` [`flask.ext`](https://github.com/mitsuhiko/flask/blob/master/flask/ext/__init__.py) is a special package. If you `import flask.ext.babel`, it will try out both of the above variants, so it should work in any case.
14,004,839
I have Flask, Babel and Flask-Babel installed in the global packages. When running python and I type this, no error ``` >>> from flaskext.babel import Babel >>> ``` With a virtual environment, starting python and typing the same command I see ``` >>> from flaskext.babel import Babel Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named flaskext.babel >>> ``` The problem is that I'm using Ninja-IDE and I'm apparently forced to use a virtualenv. I don't mind as long as it doesn't break Flask packing system.
2012/12/22
[ "https://Stackoverflow.com/questions/14004839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75517/" ]
Yeah! I solved the problem! Creating an empty \_*init*\_py in the global Lib/site-packages/flaskext next to the babel.py file solves the problem. Importing Babel from the local environment now works as expected and as it worked in the global environment. We can use the two forms *from flaskext.babel import Babel* and *from babel.ext.babel import Babel*. However the forms \*from flask\_babel import Babel\* or \*import flask\_babel\* don't work. Note that I'm running on Windows 7 64bit with Python 2.7 in C:\Python27. The absence of **init**.py file may not be a problem on unix computers.
I think you're supposed to import Flask extensions like the following from version 0.8 onwards: ``` from flask.ext.babel import Babel ``` I tried the old way (`import flaskext.babel`), and it didn't work for me either.
14,004,839
I have Flask, Babel and Flask-Babel installed in the global packages. When running python and I type this, no error ``` >>> from flaskext.babel import Babel >>> ``` With a virtual environment, starting python and typing the same command I see ``` >>> from flaskext.babel import Babel Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named flaskext.babel >>> ``` The problem is that I'm using Ninja-IDE and I'm apparently forced to use a virtualenv. I don't mind as long as it doesn't break Flask packing system.
2012/12/22
[ "https://Stackoverflow.com/questions/14004839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75517/" ]
I think you're supposed to import Flask extensions like the following from version 0.8 onwards: ``` from flask.ext.babel import Babel ``` I tried the old way (`import flaskext.babel`), and it didn't work for me either.
for python 3 install like this: **pip install Flask-Babel** after installing import like this :**from flask.ext.babel import Babel** but do note you will get the deprecation warning so you can import like this :**from flask\_babel import Babel**
14,004,839
I have Flask, Babel and Flask-Babel installed in the global packages. When running python and I type this, no error ``` >>> from flaskext.babel import Babel >>> ``` With a virtual environment, starting python and typing the same command I see ``` >>> from flaskext.babel import Babel Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named flaskext.babel >>> ``` The problem is that I'm using Ninja-IDE and I'm apparently forced to use a virtualenv. I don't mind as long as it doesn't break Flask packing system.
2012/12/22
[ "https://Stackoverflow.com/questions/14004839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75517/" ]
Yeah! I solved the problem! Creating an empty \_*init*\_py in the global Lib/site-packages/flaskext next to the babel.py file solves the problem. Importing Babel from the local environment now works as expected and as it worked in the global environment. We can use the two forms *from flaskext.babel import Babel* and *from babel.ext.babel import Babel*. However the forms \*from flask\_babel import Babel\* or \*import flask\_babel\* don't work. Note that I'm running on Windows 7 64bit with Python 2.7 in C:\Python27. The absence of **init**.py file may not be a problem on unix computers.
The old way of importing Flask extension was like: ``` import flaskext.babel ``` [Namespace packages](https://stackoverflow.com/questions/1675734/how-do-i-create-a-namespace-package-in-python) were, however, "too painful for everybody involved", so now Flask extensions should be importable like: ``` import flask_babel ``` [`flask.ext`](https://github.com/mitsuhiko/flask/blob/master/flask/ext/__init__.py) is a special package. If you `import flask.ext.babel`, it will try out both of the above variants, so it should work in any case.
14,004,839
I have Flask, Babel and Flask-Babel installed in the global packages. When running python and I type this, no error ``` >>> from flaskext.babel import Babel >>> ``` With a virtual environment, starting python and typing the same command I see ``` >>> from flaskext.babel import Babel Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named flaskext.babel >>> ``` The problem is that I'm using Ninja-IDE and I'm apparently forced to use a virtualenv. I don't mind as long as it doesn't break Flask packing system.
2012/12/22
[ "https://Stackoverflow.com/questions/14004839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75517/" ]
The old way of importing Flask extension was like: ``` import flaskext.babel ``` [Namespace packages](https://stackoverflow.com/questions/1675734/how-do-i-create-a-namespace-package-in-python) were, however, "too painful for everybody involved", so now Flask extensions should be importable like: ``` import flask_babel ``` [`flask.ext`](https://github.com/mitsuhiko/flask/blob/master/flask/ext/__init__.py) is a special package. If you `import flask.ext.babel`, it will try out both of the above variants, so it should work in any case.
for python 3 install like this: **pip install Flask-Babel** after installing import like this :**from flask.ext.babel import Babel** but do note you will get the deprecation warning so you can import like this :**from flask\_babel import Babel**
14,004,839
I have Flask, Babel and Flask-Babel installed in the global packages. When running python and I type this, no error ``` >>> from flaskext.babel import Babel >>> ``` With a virtual environment, starting python and typing the same command I see ``` >>> from flaskext.babel import Babel Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named flaskext.babel >>> ``` The problem is that I'm using Ninja-IDE and I'm apparently forced to use a virtualenv. I don't mind as long as it doesn't break Flask packing system.
2012/12/22
[ "https://Stackoverflow.com/questions/14004839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75517/" ]
Yeah! I solved the problem! Creating an empty \_*init*\_py in the global Lib/site-packages/flaskext next to the babel.py file solves the problem. Importing Babel from the local environment now works as expected and as it worked in the global environment. We can use the two forms *from flaskext.babel import Babel* and *from babel.ext.babel import Babel*. However the forms \*from flask\_babel import Babel\* or \*import flask\_babel\* don't work. Note that I'm running on Windows 7 64bit with Python 2.7 in C:\Python27. The absence of **init**.py file may not be a problem on unix computers.
for python 3 install like this: **pip install Flask-Babel** after installing import like this :**from flask.ext.babel import Babel** but do note you will get the deprecation warning so you can import like this :**from flask\_babel import Babel**
46,515,990
Can somebody please help me to create a python program whereby the unsorted list is split up into groups of 2, arranged alphabetically within their groups of two. The program should then create a new list in alphabetical order by taking the next greatest letter from the correct pair. Please don't tell me to do this in a different way as my method must take place as is written above. Thanks :) ``` unsorted = ['B', 'D', 'A', 'G', 'F', 'E', 'H', 'C'] n = 4 num = float(len(unsorted))/n l = [ unsorted [i:i + int(num)] for i in range(0, (n-1)*int(num), int(num))] l.append(unsorted[(n-1)*int(num):]) print(l) complete = unsorted.split() print(complete) ```
2017/10/01
[ "https://Stackoverflow.com/questions/46515990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8705227/" ]
In your code, openin tag `<tr>` is not added to first `<td>`. You are appending html twice. You need to form correct html then add it to the table after for loop. Also you don't need ';' commas at the end of condition and standart function definition code blocks. ```js function myFunction() { var response = "[\r\n {\r\n \"ID\": \"1\",\r\n \"Title\": \"title 1 \",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/1/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"2\",\r\n \"Title\": \"title 2\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/2/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"3\",\r\n \"Title\": \"title 3\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/3/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"4\",\r\n \"Title\": \"title 4\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/4/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"5\",\r\n \"Title\": \"title 5\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/5/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"6\",\r\n \"Title\": \"title 6\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/6/102.jpg\",\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"7\",\r\n \"Title\": \"title 7\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/7/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"8\",\r\n \"Title\": \"title 8\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/8/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"9\",\r\n \"Title\": \"title 9\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/9/102.jpg\",\r\n \"Note\": null\r\n }\r\n]"; var json = $.parseJSON(response); var html = ''; var x = 0; // x is number of cells per row maximum 2 cells per row for (i in json) { // create HTML code var div = "<div class=\"image\">\n" + "<a href=\"javascript:doIt('" + json[i].ID + "')\">\n" + "<img src=\"" + json[i].ImageUrl + "\" alt=\"\" />" + json[i].Title + "\n" + "</a>\n" + "</div>\n"; //alert("x is:"+x); div = '<td>' + div + '</td>\n'; if (x === 0) { html += '<tr>' + div; x++; } else if (x === 1) { html += div; x++; } else if (x === 2) { html += div + '</tr>'; x = 0; } } //end of for loop $('#demo > tbody').append(html); } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body onload="myFunction()"> <div class="scroller"> <br> <table id="demo" cellspacing="0" border="1" style="display: visible;"> <thead> <th>A</th> <th>B</th> <th>C</th> </thead> <tbody> </tbody> </table> </div> </body> ```
Thought I would offer a different solution. <https://jsfiddle.net/wfc9p0e8/> ``` <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body> <style> #table{ display: table; width:100%; } #table .table-cell { display: inline-table; width:33.33%; } </style> <div class="scroller"> <div id="table"></div> </div><!--scroller--> <script> $(document).ready(function(){ var response= "[\r\n {\r\n \"ID\": \"1\",\r\n \"Title\": \"title 1 \",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/1/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"2\",\r\n \"Title\": \"title 2\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/2/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"3\",\r\n \"Title\": \"title 3\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/3/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"4\",\r\n \"Title\": \"title 4\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/4/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"5\",\r\n \"Title\": \"title 5\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/5/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"6\",\r\n \"Title\": \"title 6\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/6/102.jpg\",\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"7\",\r\n \"Title\": \"title 7\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/7/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"8\",\r\n \"Title\": \"title 8\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/8/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"9\",\r\n \"Title\": \"title 9\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/9/102.jpg\",\r\n \"Note\": null\r\n }\r\n]"; $.each(JSON.parse(response), function(i, value){ var html = '<div class="table-cell"><div class="image"><a href=javascript:doIt("'+ value.ID +'")><img src="'+ value.ImageUrl +'" alt="'+ value.Title +'"></a></div></div>'; $('#table').append(html); }) })//doc ready </script> </body> </html> ```
38,145,706
I'm using PyInstaller 3.2 to package a Web.py app. Typically, with Web.py and the built-in WSGI [server](http://webpy.org/cookbook/ssl), you specify the port on the command line, like ``` $ python main.py 8091 ``` Would run the Web.py app on port 8091 (default is 8080). I'm bundling the app with PyInstaller via a spec file, but I can't figure out how to specify the port number with that -- passing in Options only seems to work for the [3 given ones in the docs](http://pythonhosted.org/PyInstaller/spec-files.html). I'm tried: ``` exe = EXE(pyz, a.scripts, [('8091', None, 'OPTION')], a.binaries, a.zipfiles, a.datas, name='main', debug=False, strip=False, upx=True, console=False ) ``` But that doesn't seem to do anything. I didn't see anything else in the docs -- is there another way to bundle / specify / include command-line arguments to the PyInstaller spec file?
2016/07/01
[ "https://Stackoverflow.com/questions/38145706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1370384/" ]
So very hacky, but what I wound up doing was to just append an argument in `sys.argv` in my web.py app... ``` sys.argv.append('8888') app.run() ``` I also thought in my `spec` file I could just do: ``` a = Analysis(['main.py 8888'], ``` But that didn't work at all.
`options` argument in EXE is only for the python interpreter ([ref](https://pythonhosted.org/PyInstaller/spec-files.html#giving-run-time-python-options))
65,919,766
I am using python 3.8.3 version. I installed folium typing `pip install folium` in the command line. After typing `pip show folium` in the command line, the output is as follows: ``` Name: folium Version: 0.12.1 Summary: Make beautiful maps with Leaflet.js & Python Home-page: https://github.com/python-visualization/folium Author: Rob Story Author-email: wrobstory@gmail.com License: MIT Location: c:\users\koryun\appdata\local\programs\python\python38-32\lib\site-packages Requires: requests, jinja2, branca, numpy Required-by: ``` When I type `import folium` in VS code, I get an `ModuleNotFoundError: No module named 'folium'` error. What can I do to solve this issue?
2021/01/27
[ "https://Stackoverflow.com/questions/65919766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14127138/" ]
Avoiding this kind of errors, always use virtualenv. Take a look here <https://docs.python.org/3/library/venv.html>
Try restarting VSCode, sometimes the python extension needs a restart so newly installed modules are indexed. You can try running the code despite the Error in VSCode. It works if you can confirm that the required module is properly installed.
65,919,766
I am using python 3.8.3 version. I installed folium typing `pip install folium` in the command line. After typing `pip show folium` in the command line, the output is as follows: ``` Name: folium Version: 0.12.1 Summary: Make beautiful maps with Leaflet.js & Python Home-page: https://github.com/python-visualization/folium Author: Rob Story Author-email: wrobstory@gmail.com License: MIT Location: c:\users\koryun\appdata\local\programs\python\python38-32\lib\site-packages Requires: requests, jinja2, branca, numpy Required-by: ``` When I type `import folium` in VS code, I get an `ModuleNotFoundError: No module named 'folium'` error. What can I do to solve this issue?
2021/01/27
[ "https://Stackoverflow.com/questions/65919766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14127138/" ]
Avoiding this kind of errors, always use virtualenv. Take a look here <https://docs.python.org/3/library/venv.html>
Can you open python in command line and type ``` >>> import folium ``` In my case I got error as I don't have it installed. If you get error on command line, it means module was not installed. [CMD screenshot](https://i.stack.imgur.com/AuLUy.png)
65,919,766
I am using python 3.8.3 version. I installed folium typing `pip install folium` in the command line. After typing `pip show folium` in the command line, the output is as follows: ``` Name: folium Version: 0.12.1 Summary: Make beautiful maps with Leaflet.js & Python Home-page: https://github.com/python-visualization/folium Author: Rob Story Author-email: wrobstory@gmail.com License: MIT Location: c:\users\koryun\appdata\local\programs\python\python38-32\lib\site-packages Requires: requests, jinja2, branca, numpy Required-by: ``` When I type `import folium` in VS code, I get an `ModuleNotFoundError: No module named 'folium'` error. What can I do to solve this issue?
2021/01/27
[ "https://Stackoverflow.com/questions/65919766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14127138/" ]
Try restarting VSCode, sometimes the python extension needs a restart so newly installed modules are indexed. You can try running the code despite the Error in VSCode. It works if you can confirm that the required module is properly installed.
Can you open python in command line and type ``` >>> import folium ``` In my case I got error as I don't have it installed. If you get error on command line, it means module was not installed. [CMD screenshot](https://i.stack.imgur.com/AuLUy.png)
65,919,766
I am using python 3.8.3 version. I installed folium typing `pip install folium` in the command line. After typing `pip show folium` in the command line, the output is as follows: ``` Name: folium Version: 0.12.1 Summary: Make beautiful maps with Leaflet.js & Python Home-page: https://github.com/python-visualization/folium Author: Rob Story Author-email: wrobstory@gmail.com License: MIT Location: c:\users\koryun\appdata\local\programs\python\python38-32\lib\site-packages Requires: requests, jinja2, branca, numpy Required-by: ``` When I type `import folium` in VS code, I get an `ModuleNotFoundError: No module named 'folium'` error. What can I do to solve this issue?
2021/01/27
[ "https://Stackoverflow.com/questions/65919766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14127138/" ]
Your package seems to be installed in `c:\users\koryun\appdata\local\programs\python\python38-32\lib\site-packages`. Check out where is your Python looking for installed packages by running this Python program: ``` import sys print(sys.path) ``` If there is not aforementioned path present, then you have to add it, for VS code it is described here: <https://code.visualstudio.com/docs/python/environments>
Try restarting VSCode, sometimes the python extension needs a restart so newly installed modules are indexed. You can try running the code despite the Error in VSCode. It works if you can confirm that the required module is properly installed.
65,919,766
I am using python 3.8.3 version. I installed folium typing `pip install folium` in the command line. After typing `pip show folium` in the command line, the output is as follows: ``` Name: folium Version: 0.12.1 Summary: Make beautiful maps with Leaflet.js & Python Home-page: https://github.com/python-visualization/folium Author: Rob Story Author-email: wrobstory@gmail.com License: MIT Location: c:\users\koryun\appdata\local\programs\python\python38-32\lib\site-packages Requires: requests, jinja2, branca, numpy Required-by: ``` When I type `import folium` in VS code, I get an `ModuleNotFoundError: No module named 'folium'` error. What can I do to solve this issue?
2021/01/27
[ "https://Stackoverflow.com/questions/65919766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14127138/" ]
Your package seems to be installed in `c:\users\koryun\appdata\local\programs\python\python38-32\lib\site-packages`. Check out where is your Python looking for installed packages by running this Python program: ``` import sys print(sys.path) ``` If there is not aforementioned path present, then you have to add it, for VS code it is described here: <https://code.visualstudio.com/docs/python/environments>
Can you open python in command line and type ``` >>> import folium ``` In my case I got error as I don't have it installed. If you get error on command line, it means module was not installed. [CMD screenshot](https://i.stack.imgur.com/AuLUy.png)
62,339,871
**The question is this:** We add a Leap Day on February 29, almost every four years. The leap day is an extra, or intercalary day and we add it to the shortest month of the year, February. In the Gregorian calendar three criteria must be taken into account to identify leap years: The year can be evenly divided by 4, is a leap year, unless: The year can be evenly divided by 100, it is NOT a leap year, unless: The year is also evenly divisible by 400. Then it is a leap year. This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. **This is what I've coded in python 3** ``` def is_leap(year): leap = False # Write your logic here if((year%4==0) |(year%100==0 & year%400==0)): leap= True else: leap= False return leap ``` `year = int(input()) print(is_leap(year))` This code fails for **input 2100**. I'm not able to point out the mistake. Help please.
2020/06/12
[ "https://Stackoverflow.com/questions/62339871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13732680/" ]
First of all, you are using bitwise operators **|** and **&** (you can read about it here - <https://www.educative.io/edpresso/what-are-bitwise-operators-in-python>), but you need to use logical operators, such as **or** and **and**. Also, your code can be simplified: ``` def is_leap(year): return (year % 4 == 0) and ((year % 100 != 0) or (year % 400 == 0)) ```
try this: ``` def leap_year(n): if (n%100==0 and n%400==0): return True elif (n%4==0 and n%100!=0): return True else: return False ```
42,742,499
PEP [3141](https://www.python.org/dev/peps/pep-3141/) defines a numerical hierarchy with `Complex.__add__` but no `Number.__add__`. This seems to be a weird choice, since the other numeric type `Decimal` that (virtually) derives from `Number` also implements an add method. So why is it this way? If I want to add type annotations or assertions to my code, should I use `x:(Complex, Decimal)`? Or `x:Number` and ignore the fact that this declaration is practically meaningless?
2017/03/12
[ "https://Stackoverflow.com/questions/42742499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4133053/" ]
Its because you are increamenting two times in the loop. Remove the last i++ and it works fine.
The form of this for loop is to always increment the counter variable after the final statement or function has executed or returned, respectively. So, any incrementation of 'i' in the loop body, in this case, will add 1 to the value of the for loop counter, corrupting the count.
42,742,499
PEP [3141](https://www.python.org/dev/peps/pep-3141/) defines a numerical hierarchy with `Complex.__add__` but no `Number.__add__`. This seems to be a weird choice, since the other numeric type `Decimal` that (virtually) derives from `Number` also implements an add method. So why is it this way? If I want to add type annotations or assertions to my code, should I use `x:(Complex, Decimal)`? Or `x:Number` and ignore the fact that this declaration is practically meaningless?
2017/03/12
[ "https://Stackoverflow.com/questions/42742499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4133053/" ]
Your problem is that you increment `i` twice. So, it will be 0, then 2, then 4, then 6, which is greater than 5. In order to fix it, simply remove the `i++;` line after the `puts("Hello, World!");` or transform your `for` loop into a `while` loop. ### Solution 1 ``` #include <stdio.h> void hello_world(int n) { for (int i = 0; i < n; i++) { puts("Hello, World!"); } /* CAN BE SIMPLIFIED BY REMOVING THE BRACES */ } int main () { hello_world(5); return 0; } ``` ### Solution 2 ``` #include <stdio.h> void hello_world(int n) { int i = 0; while (i < n) { puts("Hello, World!"); i++; } } int main () { hello_world(5); return 0; } ```
The form of this for loop is to always increment the counter variable after the final statement or function has executed or returned, respectively. So, any incrementation of 'i' in the loop body, in this case, will add 1 to the value of the for loop counter, corrupting the count.
42,742,499
PEP [3141](https://www.python.org/dev/peps/pep-3141/) defines a numerical hierarchy with `Complex.__add__` but no `Number.__add__`. This seems to be a weird choice, since the other numeric type `Decimal` that (virtually) derives from `Number` also implements an add method. So why is it this way? If I want to add type annotations or assertions to my code, should I use `x:(Complex, Decimal)`? Or `x:Number` and ignore the fact that this declaration is practically meaningless?
2017/03/12
[ "https://Stackoverflow.com/questions/42742499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4133053/" ]
Your problem is that you increment `i` twice. So, it will be 0, then 2, then 4, then 6, which is greater than 5. In order to fix it, simply remove the `i++;` line after the `puts("Hello, World!");` or transform your `for` loop into a `while` loop. ### Solution 1 ``` #include <stdio.h> void hello_world(int n) { for (int i = 0; i < n; i++) { puts("Hello, World!"); } /* CAN BE SIMPLIFIED BY REMOVING THE BRACES */ } int main () { hello_world(5); return 0; } ``` ### Solution 2 ``` #include <stdio.h> void hello_world(int n) { int i = 0; while (i < n) { puts("Hello, World!"); i++; } } int main () { hello_world(5); return 0; } ```
Its because you are increamenting two times in the loop. Remove the last i++ and it works fine.
59,600,235
Tell me please, what am I doing wrong? I try to drag and drop through Selenium, but every time I come across an error "AttributeError: move\_to requires a WebElement" **Here is my code:** ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_elements_by_xpath('//*[@id="box3"]') target = driver.find_elements_by_xpath('//*[@id="box103"]') action = ActionChains(driver) action.drag_and_drop(source, target).perform() ``` **I also tried, like this:** ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_elements_by_xpath('//*[@id="box3"]') target = driver.find_elements_by_xpath('//*[@id="box103"]') ActionChains(driver).click_and_hold(source).move_to_element(target).release(target).perform() ``` **Always coming out "AttributeError: move\_to requires a WebElement"** ``` Traceback (most recent call last): File "drag_and_drop_test.py", line 13, in <module> ActionChains(driver).click_and_hold(source).move_to_element(target).release(target).perform() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/action_chains.py", line 121, in click_and_hold self.move_to_element(on_element) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/action_chains.py", line 273, in move_to_element self.w3c_actions.pointer_action.move_to(to_element) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/actions/pointer_actions.py", line 42, in move_to raise AttributeError("move_to requires a WebElement") AttributeError: move_to requires a WebElement ```
2020/01/05
[ "https://Stackoverflow.com/questions/59600235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9729098/" ]
`find_elements_by_xpath` returns a list of `WebElement`s, `drag_and_drop` (and the other methods) accept a single `WebElement`. Use `find_element_by_xpath` ``` source = driver.find_element_by_xpath('//*[@id="box3"]') target = driver.find_element_by_xpath('//*[@id="box103"]') ```
as @guy said: ``` find_elements_by_xpath ``` returns list of `WebElements`. You can use `find_element_by_xpath` method to get single web element. Or select specific element from `WebElements` return by `find_elements_by_xpath`. For example, if you know, you wanted to select 2nd element from return list for target. Then you can try like this: ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_elements_by_xpath('//*[@id="box3"]')[0] target = driver.find_elements_by_xpath('//*[@id="box103"]')[1] action = ActionChains(driver) action.drag_and_drop(source, target).perform() ``` i can see we are selecting element which have id but ids are unique, so there can be only one id. So you can also do this like this: ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_element_by_id('box3') target = driver.find_element_by_id('box103') action = ActionChains(driver) action.drag_and_drop(source, target).perform() ``` i like to use `find_element_by_id` because it looks cleaner to me than xpath.
59,600,235
Tell me please, what am I doing wrong? I try to drag and drop through Selenium, but every time I come across an error "AttributeError: move\_to requires a WebElement" **Here is my code:** ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_elements_by_xpath('//*[@id="box3"]') target = driver.find_elements_by_xpath('//*[@id="box103"]') action = ActionChains(driver) action.drag_and_drop(source, target).perform() ``` **I also tried, like this:** ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_elements_by_xpath('//*[@id="box3"]') target = driver.find_elements_by_xpath('//*[@id="box103"]') ActionChains(driver).click_and_hold(source).move_to_element(target).release(target).perform() ``` **Always coming out "AttributeError: move\_to requires a WebElement"** ``` Traceback (most recent call last): File "drag_and_drop_test.py", line 13, in <module> ActionChains(driver).click_and_hold(source).move_to_element(target).release(target).perform() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/action_chains.py", line 121, in click_and_hold self.move_to_element(on_element) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/action_chains.py", line 273, in move_to_element self.w3c_actions.pointer_action.move_to(to_element) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/actions/pointer_actions.py", line 42, in move_to raise AttributeError("move_to requires a WebElement") AttributeError: move_to requires a WebElement ```
2020/01/05
[ "https://Stackoverflow.com/questions/59600235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9729098/" ]
`find_elements_by_xpath` returns a list of `WebElement`s, `drag_and_drop` (and the other methods) accept a single `WebElement`. Use `find_element_by_xpath` ``` source = driver.find_element_by_xpath('//*[@id="box3"]') target = driver.find_element_by_xpath('//*[@id="box103"]') ```
This error message... ``` AttributeError: move_to requires a WebElement ``` ...implies that the `move_to_element()` requires a *WebElement* as an argument. Seems you were close. You have used `find_elements_by_xpath()` which returns a *List* where as you need pass a *WebElement* within `move_to_element()`. Solution -------- To *drag* the element with text as **Washington** and *drop* within the element with text as **United States** through [Selenium](https://stackoverflow.com/questions/54459701/what-is-selenium-and-what-is-webdriver/54482491#54482491) you have to induce *WebDriverWait* for the `element_to_be_clickable()` and you can use the following [Locator Strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890): * Code Block: ``` driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='dragableBox' and @id='box3']"))) target = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='dragableBoxRight' and @id='box103']"))) ActionChains(driver).click_and_hold(source).move_to_element(target).release(target).perform() ``` * **Note** : You have to add the following imports : ``` from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC ``` * Browser Snapshot: [![drag_and_drop](https://i.stack.imgur.com/GxfDd.png)](https://i.stack.imgur.com/GxfDd.png)
59,600,235
Tell me please, what am I doing wrong? I try to drag and drop through Selenium, but every time I come across an error "AttributeError: move\_to requires a WebElement" **Here is my code:** ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_elements_by_xpath('//*[@id="box3"]') target = driver.find_elements_by_xpath('//*[@id="box103"]') action = ActionChains(driver) action.drag_and_drop(source, target).perform() ``` **I also tried, like this:** ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_elements_by_xpath('//*[@id="box3"]') target = driver.find_elements_by_xpath('//*[@id="box103"]') ActionChains(driver).click_and_hold(source).move_to_element(target).release(target).perform() ``` **Always coming out "AttributeError: move\_to requires a WebElement"** ``` Traceback (most recent call last): File "drag_and_drop_test.py", line 13, in <module> ActionChains(driver).click_and_hold(source).move_to_element(target).release(target).perform() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/action_chains.py", line 121, in click_and_hold self.move_to_element(on_element) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/action_chains.py", line 273, in move_to_element self.w3c_actions.pointer_action.move_to(to_element) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/actions/pointer_actions.py", line 42, in move_to raise AttributeError("move_to requires a WebElement") AttributeError: move_to requires a WebElement ```
2020/01/05
[ "https://Stackoverflow.com/questions/59600235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9729098/" ]
`find_elements_by_xpath` returns a list of `WebElement`s, `drag_and_drop` (and the other methods) accept a single `WebElement`. Use `find_element_by_xpath` ``` source = driver.find_element_by_xpath('//*[@id="box3"]') target = driver.find_element_by_xpath('//*[@id="box103"]') ```
use `find_elements_by_xpath` instead `find_element_by_xpath`
59,600,235
Tell me please, what am I doing wrong? I try to drag and drop through Selenium, but every time I come across an error "AttributeError: move\_to requires a WebElement" **Here is my code:** ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_elements_by_xpath('//*[@id="box3"]') target = driver.find_elements_by_xpath('//*[@id="box103"]') action = ActionChains(driver) action.drag_and_drop(source, target).perform() ``` **I also tried, like this:** ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_elements_by_xpath('//*[@id="box3"]') target = driver.find_elements_by_xpath('//*[@id="box103"]') ActionChains(driver).click_and_hold(source).move_to_element(target).release(target).perform() ``` **Always coming out "AttributeError: move\_to requires a WebElement"** ``` Traceback (most recent call last): File "drag_and_drop_test.py", line 13, in <module> ActionChains(driver).click_and_hold(source).move_to_element(target).release(target).perform() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/action_chains.py", line 121, in click_and_hold self.move_to_element(on_element) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/action_chains.py", line 273, in move_to_element self.w3c_actions.pointer_action.move_to(to_element) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/actions/pointer_actions.py", line 42, in move_to raise AttributeError("move_to requires a WebElement") AttributeError: move_to requires a WebElement ```
2020/01/05
[ "https://Stackoverflow.com/questions/59600235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9729098/" ]
as @guy said: ``` find_elements_by_xpath ``` returns list of `WebElements`. You can use `find_element_by_xpath` method to get single web element. Or select specific element from `WebElements` return by `find_elements_by_xpath`. For example, if you know, you wanted to select 2nd element from return list for target. Then you can try like this: ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_elements_by_xpath('//*[@id="box3"]')[0] target = driver.find_elements_by_xpath('//*[@id="box103"]')[1] action = ActionChains(driver) action.drag_and_drop(source, target).perform() ``` i can see we are selecting element which have id but ids are unique, so there can be only one id. So you can also do this like this: ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_element_by_id('box3') target = driver.find_element_by_id('box103') action = ActionChains(driver) action.drag_and_drop(source, target).perform() ``` i like to use `find_element_by_id` because it looks cleaner to me than xpath.
This error message... ``` AttributeError: move_to requires a WebElement ``` ...implies that the `move_to_element()` requires a *WebElement* as an argument. Seems you were close. You have used `find_elements_by_xpath()` which returns a *List* where as you need pass a *WebElement* within `move_to_element()`. Solution -------- To *drag* the element with text as **Washington** and *drop* within the element with text as **United States** through [Selenium](https://stackoverflow.com/questions/54459701/what-is-selenium-and-what-is-webdriver/54482491#54482491) you have to induce *WebDriverWait* for the `element_to_be_clickable()` and you can use the following [Locator Strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890): * Code Block: ``` driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='dragableBox' and @id='box3']"))) target = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='dragableBoxRight' and @id='box103']"))) ActionChains(driver).click_and_hold(source).move_to_element(target).release(target).perform() ``` * **Note** : You have to add the following imports : ``` from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC ``` * Browser Snapshot: [![drag_and_drop](https://i.stack.imgur.com/GxfDd.png)](https://i.stack.imgur.com/GxfDd.png)
59,600,235
Tell me please, what am I doing wrong? I try to drag and drop through Selenium, but every time I come across an error "AttributeError: move\_to requires a WebElement" **Here is my code:** ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_elements_by_xpath('//*[@id="box3"]') target = driver.find_elements_by_xpath('//*[@id="box103"]') action = ActionChains(driver) action.drag_and_drop(source, target).perform() ``` **I also tried, like this:** ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_elements_by_xpath('//*[@id="box3"]') target = driver.find_elements_by_xpath('//*[@id="box103"]') ActionChains(driver).click_and_hold(source).move_to_element(target).release(target).perform() ``` **Always coming out "AttributeError: move\_to requires a WebElement"** ``` Traceback (most recent call last): File "drag_and_drop_test.py", line 13, in <module> ActionChains(driver).click_and_hold(source).move_to_element(target).release(target).perform() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/action_chains.py", line 121, in click_and_hold self.move_to_element(on_element) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/action_chains.py", line 273, in move_to_element self.w3c_actions.pointer_action.move_to(to_element) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/common/actions/pointer_actions.py", line 42, in move_to raise AttributeError("move_to requires a WebElement") AttributeError: move_to requires a WebElement ```
2020/01/05
[ "https://Stackoverflow.com/questions/59600235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9729098/" ]
as @guy said: ``` find_elements_by_xpath ``` returns list of `WebElements`. You can use `find_element_by_xpath` method to get single web element. Or select specific element from `WebElements` return by `find_elements_by_xpath`. For example, if you know, you wanted to select 2nd element from return list for target. Then you can try like this: ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_elements_by_xpath('//*[@id="box3"]')[0] target = driver.find_elements_by_xpath('//*[@id="box103"]')[1] action = ActionChains(driver) action.drag_and_drop(source, target).perform() ``` i can see we are selecting element which have id but ids are unique, so there can be only one id. So you can also do this like this: ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains chromedriver = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(chromedriver) driver.get('http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html') source = driver.find_element_by_id('box3') target = driver.find_element_by_id('box103') action = ActionChains(driver) action.drag_and_drop(source, target).perform() ``` i like to use `find_element_by_id` because it looks cleaner to me than xpath.
use `find_elements_by_xpath` instead `find_element_by_xpath`
19,939,365
I'm trying to install a module called Scrapy. I installed it using ``` pip install Scrapy ``` I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening? EDIT: Here is the output of the pip command: ``` Downloading/unpacking Scrapy Downloading Scrapy-0.20.0.tar.gz (745kB): 745kB downloaded Running setup.py egg_info for package Scrapy no previously-included directories found matching 'docs/build' Requirement already satisfied (use --upgrade to upgrade): Twisted>=10.0.0 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): w3lib>=1.2 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): queuelib in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /usr/local/lib/python2.7/site-packages (from Twisted>=10.0.0->Scrapy) Requirement already satisfied (use --upgrade to upgrade): six>=1.4.1 in /usr/local/lib/python2.7/site-packages (from w3lib>=1.2->Scrapy) Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python2.7/site-packages/setuptools-1.1.6-py2.7.egg (from zope.interface>=3.6.0->Twisted>=10.0.0->Scrapy) Installing collected packages: Scrapy Running setup.py install for Scrapy changing mode of build/scripts-2.7/scrapy from 644 to 755 no previously-included directories found matching 'docs/build' changing mode of /usr/local/bin/scrapy to 755 Successfully installed Scrapy Cleaning up... ``` When I run /usr/local/bin/scrapy I get the usage for the command and the available commands. I noticed that I have a python2.7 and python2.7-32 in my /usr/local/bin, and I remember installing the 32 bit version because of a problem with Mavericks. Here is the output of `python /usr/local/bin/scrapy`: ``` Traceback (most recent call last): File "/usr/local/bin/scrapy", line 3, in <module> from scrapy.cmdline import execute ImportError: No module named scrapy.cmdline ``` And `head /usr/local/bin/scrapy`: ``` #!/usr/local/opt/python/bin/python2.7 from scrapy.cmdline import execute execute() ```
2013/11/12
[ "https://Stackoverflow.com/questions/19939365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191726/" ]
Are you using Homebrew or MacPorts or something? As @J.F.Sebastian said, it sounds like you are having issues mixing the default python that comes with OS X, and one that is installed via a package manager... Try `/usr/local/opt/python/bin/python2.7 -m scrapy` and see if that throws an `ImportError`. If that works, then you may want to consider making *that* python executable your default. Something like `alias python2.7=/usr/local/opt/python/bin/python2.7` and then always use `python2.7` instead of the default `python`. You can likewise just point `python` to the `/urs/local...` bit, but then you won't have easy access to the system (OS X-supplied) python if you ever needed it for some reason.
EDIT: You can force pip to install to an alternate location. The details are here: [Install a Python package into a different directory using pip?](https://stackoverflow.com/questions/2915471/install-a-python-package-into-a-different-directory-using-pip). If you do indeed have extra Python folders on your system, maybe you can try directing scrapy to those, even if just for a temporary solution. Can you post the output of the pip command? Perhaps it is failing somewhere? Also, is it possible you have two versions of Python on your machine? Pip only installs to one location, but perhaps the version of Python on your path is different. Finally, sometimes package names given to pip are not exactly the same as the name used to import. Check the documentation of the package. I took a quick look and the import should be lowercase: ``` import scrapy ```
19,939,365
I'm trying to install a module called Scrapy. I installed it using ``` pip install Scrapy ``` I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening? EDIT: Here is the output of the pip command: ``` Downloading/unpacking Scrapy Downloading Scrapy-0.20.0.tar.gz (745kB): 745kB downloaded Running setup.py egg_info for package Scrapy no previously-included directories found matching 'docs/build' Requirement already satisfied (use --upgrade to upgrade): Twisted>=10.0.0 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): w3lib>=1.2 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): queuelib in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /usr/local/lib/python2.7/site-packages (from Twisted>=10.0.0->Scrapy) Requirement already satisfied (use --upgrade to upgrade): six>=1.4.1 in /usr/local/lib/python2.7/site-packages (from w3lib>=1.2->Scrapy) Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python2.7/site-packages/setuptools-1.1.6-py2.7.egg (from zope.interface>=3.6.0->Twisted>=10.0.0->Scrapy) Installing collected packages: Scrapy Running setup.py install for Scrapy changing mode of build/scripts-2.7/scrapy from 644 to 755 no previously-included directories found matching 'docs/build' changing mode of /usr/local/bin/scrapy to 755 Successfully installed Scrapy Cleaning up... ``` When I run /usr/local/bin/scrapy I get the usage for the command and the available commands. I noticed that I have a python2.7 and python2.7-32 in my /usr/local/bin, and I remember installing the 32 bit version because of a problem with Mavericks. Here is the output of `python /usr/local/bin/scrapy`: ``` Traceback (most recent call last): File "/usr/local/bin/scrapy", line 3, in <module> from scrapy.cmdline import execute ImportError: No module named scrapy.cmdline ``` And `head /usr/local/bin/scrapy`: ``` #!/usr/local/opt/python/bin/python2.7 from scrapy.cmdline import execute execute() ```
2013/11/12
[ "https://Stackoverflow.com/questions/19939365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191726/" ]
EDIT: You can force pip to install to an alternate location. The details are here: [Install a Python package into a different directory using pip?](https://stackoverflow.com/questions/2915471/install-a-python-package-into-a-different-directory-using-pip). If you do indeed have extra Python folders on your system, maybe you can try directing scrapy to those, even if just for a temporary solution. Can you post the output of the pip command? Perhaps it is failing somewhere? Also, is it possible you have two versions of Python on your machine? Pip only installs to one location, but perhaps the version of Python on your path is different. Finally, sometimes package names given to pip are not exactly the same as the name used to import. Check the documentation of the package. I took a quick look and the import should be lowercase: ``` import scrapy ```
if you run on Ubuntu: > > use the official [Ubuntu Packages](http://doc.scrapy.org/en/latest/topics/ubuntu.html#topics-ubuntu), which already solve all dependencies for you and are continuously updated with the latest bug fixes. > > > Optionally, even if it solves your problem, it is always better to install python libraries on a virtual environment, using [virtualenvwrapper](http://virtualenvwrapper.readthedocs.org/en/latest/) to keep the libraries separated, try to examine the apt-get installation log to find out what tools where added, then remove scrapy python library and reinstall it in the virtual env. using pip
19,939,365
I'm trying to install a module called Scrapy. I installed it using ``` pip install Scrapy ``` I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening? EDIT: Here is the output of the pip command: ``` Downloading/unpacking Scrapy Downloading Scrapy-0.20.0.tar.gz (745kB): 745kB downloaded Running setup.py egg_info for package Scrapy no previously-included directories found matching 'docs/build' Requirement already satisfied (use --upgrade to upgrade): Twisted>=10.0.0 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): w3lib>=1.2 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): queuelib in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /usr/local/lib/python2.7/site-packages (from Twisted>=10.0.0->Scrapy) Requirement already satisfied (use --upgrade to upgrade): six>=1.4.1 in /usr/local/lib/python2.7/site-packages (from w3lib>=1.2->Scrapy) Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python2.7/site-packages/setuptools-1.1.6-py2.7.egg (from zope.interface>=3.6.0->Twisted>=10.0.0->Scrapy) Installing collected packages: Scrapy Running setup.py install for Scrapy changing mode of build/scripts-2.7/scrapy from 644 to 755 no previously-included directories found matching 'docs/build' changing mode of /usr/local/bin/scrapy to 755 Successfully installed Scrapy Cleaning up... ``` When I run /usr/local/bin/scrapy I get the usage for the command and the available commands. I noticed that I have a python2.7 and python2.7-32 in my /usr/local/bin, and I remember installing the 32 bit version because of a problem with Mavericks. Here is the output of `python /usr/local/bin/scrapy`: ``` Traceback (most recent call last): File "/usr/local/bin/scrapy", line 3, in <module> from scrapy.cmdline import execute ImportError: No module named scrapy.cmdline ``` And `head /usr/local/bin/scrapy`: ``` #!/usr/local/opt/python/bin/python2.7 from scrapy.cmdline import execute execute() ```
2013/11/12
[ "https://Stackoverflow.com/questions/19939365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191726/" ]
EDIT: You can force pip to install to an alternate location. The details are here: [Install a Python package into a different directory using pip?](https://stackoverflow.com/questions/2915471/install-a-python-package-into-a-different-directory-using-pip). If you do indeed have extra Python folders on your system, maybe you can try directing scrapy to those, even if just for a temporary solution. Can you post the output of the pip command? Perhaps it is failing somewhere? Also, is it possible you have two versions of Python on your machine? Pip only installs to one location, but perhaps the version of Python on your path is different. Finally, sometimes package names given to pip are not exactly the same as the name used to import. Check the documentation of the package. I took a quick look and the import should be lowercase: ``` import scrapy ```
When all else fails you can always set the environment variable PYTHONPATH (see [Permanently add a directory to PYTHONPATH](https://stackoverflow.com/questions/3402168/permanently-add-a-directory-to-pythonpath) for help) to the path where you installed Scrapy. (pending you're not using virtualenv -- and if you are please specify so we can help, it's generally a good idea to provide OS too)
19,939,365
I'm trying to install a module called Scrapy. I installed it using ``` pip install Scrapy ``` I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening? EDIT: Here is the output of the pip command: ``` Downloading/unpacking Scrapy Downloading Scrapy-0.20.0.tar.gz (745kB): 745kB downloaded Running setup.py egg_info for package Scrapy no previously-included directories found matching 'docs/build' Requirement already satisfied (use --upgrade to upgrade): Twisted>=10.0.0 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): w3lib>=1.2 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): queuelib in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /usr/local/lib/python2.7/site-packages (from Twisted>=10.0.0->Scrapy) Requirement already satisfied (use --upgrade to upgrade): six>=1.4.1 in /usr/local/lib/python2.7/site-packages (from w3lib>=1.2->Scrapy) Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python2.7/site-packages/setuptools-1.1.6-py2.7.egg (from zope.interface>=3.6.0->Twisted>=10.0.0->Scrapy) Installing collected packages: Scrapy Running setup.py install for Scrapy changing mode of build/scripts-2.7/scrapy from 644 to 755 no previously-included directories found matching 'docs/build' changing mode of /usr/local/bin/scrapy to 755 Successfully installed Scrapy Cleaning up... ``` When I run /usr/local/bin/scrapy I get the usage for the command and the available commands. I noticed that I have a python2.7 and python2.7-32 in my /usr/local/bin, and I remember installing the 32 bit version because of a problem with Mavericks. Here is the output of `python /usr/local/bin/scrapy`: ``` Traceback (most recent call last): File "/usr/local/bin/scrapy", line 3, in <module> from scrapy.cmdline import execute ImportError: No module named scrapy.cmdline ``` And `head /usr/local/bin/scrapy`: ``` #!/usr/local/opt/python/bin/python2.7 from scrapy.cmdline import execute execute() ```
2013/11/12
[ "https://Stackoverflow.com/questions/19939365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191726/" ]
EDIT: You can force pip to install to an alternate location. The details are here: [Install a Python package into a different directory using pip?](https://stackoverflow.com/questions/2915471/install-a-python-package-into-a-different-directory-using-pip). If you do indeed have extra Python folders on your system, maybe you can try directing scrapy to those, even if just for a temporary solution. Can you post the output of the pip command? Perhaps it is failing somewhere? Also, is it possible you have two versions of Python on your machine? Pip only installs to one location, but perhaps the version of Python on your path is different. Finally, sometimes package names given to pip are not exactly the same as the name used to import. Check the documentation of the package. I took a quick look and the import should be lowercase: ``` import scrapy ```
It appears that the scrapy module that is installed on the Python path is an executable file that will bootstrap a Scrapy project directory for you. The Python code in the [scrapy executable](https://github.com/scrapy/scrapy/blob/master/bin/scrapy) looks like this: ``` #!/usr/bin/env python from scrapy.cmdline import execute execute() ``` That's intended to be run from the command line rather than imported into your own Python project module. According to the [documentation for the project](http://doc.scrapy.org/en/0.20/intro/tutorial.html), running the scrapy executable with this syntax: ``` scrapy startproject <your-project-name> ``` will bootstrap a Scrapy project that has the following directory structure: ``` your-project-name/ scrapy.cfg tutorial/ __init__.py items.py pipelines.py settings.py spiders/ __init__.py ... ``` There are a number of examples in the documentation that demonstrate how you create and run your own spiders, link extractors, etc., and how to manipulate the data that you retrieve with the application. They each demonstrate the appropriate Python imports from subdirectories in the scrapy package to get you up and running. Hope that this helps.
19,939,365
I'm trying to install a module called Scrapy. I installed it using ``` pip install Scrapy ``` I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening? EDIT: Here is the output of the pip command: ``` Downloading/unpacking Scrapy Downloading Scrapy-0.20.0.tar.gz (745kB): 745kB downloaded Running setup.py egg_info for package Scrapy no previously-included directories found matching 'docs/build' Requirement already satisfied (use --upgrade to upgrade): Twisted>=10.0.0 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): w3lib>=1.2 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): queuelib in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /usr/local/lib/python2.7/site-packages (from Twisted>=10.0.0->Scrapy) Requirement already satisfied (use --upgrade to upgrade): six>=1.4.1 in /usr/local/lib/python2.7/site-packages (from w3lib>=1.2->Scrapy) Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python2.7/site-packages/setuptools-1.1.6-py2.7.egg (from zope.interface>=3.6.0->Twisted>=10.0.0->Scrapy) Installing collected packages: Scrapy Running setup.py install for Scrapy changing mode of build/scripts-2.7/scrapy from 644 to 755 no previously-included directories found matching 'docs/build' changing mode of /usr/local/bin/scrapy to 755 Successfully installed Scrapy Cleaning up... ``` When I run /usr/local/bin/scrapy I get the usage for the command and the available commands. I noticed that I have a python2.7 and python2.7-32 in my /usr/local/bin, and I remember installing the 32 bit version because of a problem with Mavericks. Here is the output of `python /usr/local/bin/scrapy`: ``` Traceback (most recent call last): File "/usr/local/bin/scrapy", line 3, in <module> from scrapy.cmdline import execute ImportError: No module named scrapy.cmdline ``` And `head /usr/local/bin/scrapy`: ``` #!/usr/local/opt/python/bin/python2.7 from scrapy.cmdline import execute execute() ```
2013/11/12
[ "https://Stackoverflow.com/questions/19939365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191726/" ]
Are you using Homebrew or MacPorts or something? As @J.F.Sebastian said, it sounds like you are having issues mixing the default python that comes with OS X, and one that is installed via a package manager... Try `/usr/local/opt/python/bin/python2.7 -m scrapy` and see if that throws an `ImportError`. If that works, then you may want to consider making *that* python executable your default. Something like `alias python2.7=/usr/local/opt/python/bin/python2.7` and then always use `python2.7` instead of the default `python`. You can likewise just point `python` to the `/urs/local...` bit, but then you won't have easy access to the system (OS X-supplied) python if you ever needed it for some reason.
if you run on Ubuntu: > > use the official [Ubuntu Packages](http://doc.scrapy.org/en/latest/topics/ubuntu.html#topics-ubuntu), which already solve all dependencies for you and are continuously updated with the latest bug fixes. > > > Optionally, even if it solves your problem, it is always better to install python libraries on a virtual environment, using [virtualenvwrapper](http://virtualenvwrapper.readthedocs.org/en/latest/) to keep the libraries separated, try to examine the apt-get installation log to find out what tools where added, then remove scrapy python library and reinstall it in the virtual env. using pip
19,939,365
I'm trying to install a module called Scrapy. I installed it using ``` pip install Scrapy ``` I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening? EDIT: Here is the output of the pip command: ``` Downloading/unpacking Scrapy Downloading Scrapy-0.20.0.tar.gz (745kB): 745kB downloaded Running setup.py egg_info for package Scrapy no previously-included directories found matching 'docs/build' Requirement already satisfied (use --upgrade to upgrade): Twisted>=10.0.0 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): w3lib>=1.2 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): queuelib in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /usr/local/lib/python2.7/site-packages (from Twisted>=10.0.0->Scrapy) Requirement already satisfied (use --upgrade to upgrade): six>=1.4.1 in /usr/local/lib/python2.7/site-packages (from w3lib>=1.2->Scrapy) Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python2.7/site-packages/setuptools-1.1.6-py2.7.egg (from zope.interface>=3.6.0->Twisted>=10.0.0->Scrapy) Installing collected packages: Scrapy Running setup.py install for Scrapy changing mode of build/scripts-2.7/scrapy from 644 to 755 no previously-included directories found matching 'docs/build' changing mode of /usr/local/bin/scrapy to 755 Successfully installed Scrapy Cleaning up... ``` When I run /usr/local/bin/scrapy I get the usage for the command and the available commands. I noticed that I have a python2.7 and python2.7-32 in my /usr/local/bin, and I remember installing the 32 bit version because of a problem with Mavericks. Here is the output of `python /usr/local/bin/scrapy`: ``` Traceback (most recent call last): File "/usr/local/bin/scrapy", line 3, in <module> from scrapy.cmdline import execute ImportError: No module named scrapy.cmdline ``` And `head /usr/local/bin/scrapy`: ``` #!/usr/local/opt/python/bin/python2.7 from scrapy.cmdline import execute execute() ```
2013/11/12
[ "https://Stackoverflow.com/questions/19939365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191726/" ]
Are you using Homebrew or MacPorts or something? As @J.F.Sebastian said, it sounds like you are having issues mixing the default python that comes with OS X, and one that is installed via a package manager... Try `/usr/local/opt/python/bin/python2.7 -m scrapy` and see if that throws an `ImportError`. If that works, then you may want to consider making *that* python executable your default. Something like `alias python2.7=/usr/local/opt/python/bin/python2.7` and then always use `python2.7` instead of the default `python`. You can likewise just point `python` to the `/urs/local...` bit, but then you won't have easy access to the system (OS X-supplied) python if you ever needed it for some reason.
When all else fails you can always set the environment variable PYTHONPATH (see [Permanently add a directory to PYTHONPATH](https://stackoverflow.com/questions/3402168/permanently-add-a-directory-to-pythonpath) for help) to the path where you installed Scrapy. (pending you're not using virtualenv -- and if you are please specify so we can help, it's generally a good idea to provide OS too)
19,939,365
I'm trying to install a module called Scrapy. I installed it using ``` pip install Scrapy ``` I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening? EDIT: Here is the output of the pip command: ``` Downloading/unpacking Scrapy Downloading Scrapy-0.20.0.tar.gz (745kB): 745kB downloaded Running setup.py egg_info for package Scrapy no previously-included directories found matching 'docs/build' Requirement already satisfied (use --upgrade to upgrade): Twisted>=10.0.0 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): w3lib>=1.2 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): queuelib in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /usr/local/lib/python2.7/site-packages (from Twisted>=10.0.0->Scrapy) Requirement already satisfied (use --upgrade to upgrade): six>=1.4.1 in /usr/local/lib/python2.7/site-packages (from w3lib>=1.2->Scrapy) Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python2.7/site-packages/setuptools-1.1.6-py2.7.egg (from zope.interface>=3.6.0->Twisted>=10.0.0->Scrapy) Installing collected packages: Scrapy Running setup.py install for Scrapy changing mode of build/scripts-2.7/scrapy from 644 to 755 no previously-included directories found matching 'docs/build' changing mode of /usr/local/bin/scrapy to 755 Successfully installed Scrapy Cleaning up... ``` When I run /usr/local/bin/scrapy I get the usage for the command and the available commands. I noticed that I have a python2.7 and python2.7-32 in my /usr/local/bin, and I remember installing the 32 bit version because of a problem with Mavericks. Here is the output of `python /usr/local/bin/scrapy`: ``` Traceback (most recent call last): File "/usr/local/bin/scrapy", line 3, in <module> from scrapy.cmdline import execute ImportError: No module named scrapy.cmdline ``` And `head /usr/local/bin/scrapy`: ``` #!/usr/local/opt/python/bin/python2.7 from scrapy.cmdline import execute execute() ```
2013/11/12
[ "https://Stackoverflow.com/questions/19939365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191726/" ]
Are you using Homebrew or MacPorts or something? As @J.F.Sebastian said, it sounds like you are having issues mixing the default python that comes with OS X, and one that is installed via a package manager... Try `/usr/local/opt/python/bin/python2.7 -m scrapy` and see if that throws an `ImportError`. If that works, then you may want to consider making *that* python executable your default. Something like `alias python2.7=/usr/local/opt/python/bin/python2.7` and then always use `python2.7` instead of the default `python`. You can likewise just point `python` to the `/urs/local...` bit, but then you won't have easy access to the system (OS X-supplied) python if you ever needed it for some reason.
It appears that the scrapy module that is installed on the Python path is an executable file that will bootstrap a Scrapy project directory for you. The Python code in the [scrapy executable](https://github.com/scrapy/scrapy/blob/master/bin/scrapy) looks like this: ``` #!/usr/bin/env python from scrapy.cmdline import execute execute() ``` That's intended to be run from the command line rather than imported into your own Python project module. According to the [documentation for the project](http://doc.scrapy.org/en/0.20/intro/tutorial.html), running the scrapy executable with this syntax: ``` scrapy startproject <your-project-name> ``` will bootstrap a Scrapy project that has the following directory structure: ``` your-project-name/ scrapy.cfg tutorial/ __init__.py items.py pipelines.py settings.py spiders/ __init__.py ... ``` There are a number of examples in the documentation that demonstrate how you create and run your own spiders, link extractors, etc., and how to manipulate the data that you retrieve with the application. They each demonstrate the appropriate Python imports from subdirectories in the scrapy package to get you up and running. Hope that this helps.
19,939,365
I'm trying to install a module called Scrapy. I installed it using ``` pip install Scrapy ``` I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening? EDIT: Here is the output of the pip command: ``` Downloading/unpacking Scrapy Downloading Scrapy-0.20.0.tar.gz (745kB): 745kB downloaded Running setup.py egg_info for package Scrapy no previously-included directories found matching 'docs/build' Requirement already satisfied (use --upgrade to upgrade): Twisted>=10.0.0 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): w3lib>=1.2 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): queuelib in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /usr/local/lib/python2.7/site-packages (from Twisted>=10.0.0->Scrapy) Requirement already satisfied (use --upgrade to upgrade): six>=1.4.1 in /usr/local/lib/python2.7/site-packages (from w3lib>=1.2->Scrapy) Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python2.7/site-packages/setuptools-1.1.6-py2.7.egg (from zope.interface>=3.6.0->Twisted>=10.0.0->Scrapy) Installing collected packages: Scrapy Running setup.py install for Scrapy changing mode of build/scripts-2.7/scrapy from 644 to 755 no previously-included directories found matching 'docs/build' changing mode of /usr/local/bin/scrapy to 755 Successfully installed Scrapy Cleaning up... ``` When I run /usr/local/bin/scrapy I get the usage for the command and the available commands. I noticed that I have a python2.7 and python2.7-32 in my /usr/local/bin, and I remember installing the 32 bit version because of a problem with Mavericks. Here is the output of `python /usr/local/bin/scrapy`: ``` Traceback (most recent call last): File "/usr/local/bin/scrapy", line 3, in <module> from scrapy.cmdline import execute ImportError: No module named scrapy.cmdline ``` And `head /usr/local/bin/scrapy`: ``` #!/usr/local/opt/python/bin/python2.7 from scrapy.cmdline import execute execute() ```
2013/11/12
[ "https://Stackoverflow.com/questions/19939365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191726/" ]
When all else fails you can always set the environment variable PYTHONPATH (see [Permanently add a directory to PYTHONPATH](https://stackoverflow.com/questions/3402168/permanently-add-a-directory-to-pythonpath) for help) to the path where you installed Scrapy. (pending you're not using virtualenv -- and if you are please specify so we can help, it's generally a good idea to provide OS too)
if you run on Ubuntu: > > use the official [Ubuntu Packages](http://doc.scrapy.org/en/latest/topics/ubuntu.html#topics-ubuntu), which already solve all dependencies for you and are continuously updated with the latest bug fixes. > > > Optionally, even if it solves your problem, it is always better to install python libraries on a virtual environment, using [virtualenvwrapper](http://virtualenvwrapper.readthedocs.org/en/latest/) to keep the libraries separated, try to examine the apt-get installation log to find out what tools where added, then remove scrapy python library and reinstall it in the virtual env. using pip
19,939,365
I'm trying to install a module called Scrapy. I installed it using ``` pip install Scrapy ``` I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening? EDIT: Here is the output of the pip command: ``` Downloading/unpacking Scrapy Downloading Scrapy-0.20.0.tar.gz (745kB): 745kB downloaded Running setup.py egg_info for package Scrapy no previously-included directories found matching 'docs/build' Requirement already satisfied (use --upgrade to upgrade): Twisted>=10.0.0 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): w3lib>=1.2 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): queuelib in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /usr/local/lib/python2.7/site-packages (from Scrapy) Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /usr/local/lib/python2.7/site-packages (from Twisted>=10.0.0->Scrapy) Requirement already satisfied (use --upgrade to upgrade): six>=1.4.1 in /usr/local/lib/python2.7/site-packages (from w3lib>=1.2->Scrapy) Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python2.7/site-packages/setuptools-1.1.6-py2.7.egg (from zope.interface>=3.6.0->Twisted>=10.0.0->Scrapy) Installing collected packages: Scrapy Running setup.py install for Scrapy changing mode of build/scripts-2.7/scrapy from 644 to 755 no previously-included directories found matching 'docs/build' changing mode of /usr/local/bin/scrapy to 755 Successfully installed Scrapy Cleaning up... ``` When I run /usr/local/bin/scrapy I get the usage for the command and the available commands. I noticed that I have a python2.7 and python2.7-32 in my /usr/local/bin, and I remember installing the 32 bit version because of a problem with Mavericks. Here is the output of `python /usr/local/bin/scrapy`: ``` Traceback (most recent call last): File "/usr/local/bin/scrapy", line 3, in <module> from scrapy.cmdline import execute ImportError: No module named scrapy.cmdline ``` And `head /usr/local/bin/scrapy`: ``` #!/usr/local/opt/python/bin/python2.7 from scrapy.cmdline import execute execute() ```
2013/11/12
[ "https://Stackoverflow.com/questions/19939365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191726/" ]
When all else fails you can always set the environment variable PYTHONPATH (see [Permanently add a directory to PYTHONPATH](https://stackoverflow.com/questions/3402168/permanently-add-a-directory-to-pythonpath) for help) to the path where you installed Scrapy. (pending you're not using virtualenv -- and if you are please specify so we can help, it's generally a good idea to provide OS too)
It appears that the scrapy module that is installed on the Python path is an executable file that will bootstrap a Scrapy project directory for you. The Python code in the [scrapy executable](https://github.com/scrapy/scrapy/blob/master/bin/scrapy) looks like this: ``` #!/usr/bin/env python from scrapy.cmdline import execute execute() ``` That's intended to be run from the command line rather than imported into your own Python project module. According to the [documentation for the project](http://doc.scrapy.org/en/0.20/intro/tutorial.html), running the scrapy executable with this syntax: ``` scrapy startproject <your-project-name> ``` will bootstrap a Scrapy project that has the following directory structure: ``` your-project-name/ scrapy.cfg tutorial/ __init__.py items.py pipelines.py settings.py spiders/ __init__.py ... ``` There are a number of examples in the documentation that demonstrate how you create and run your own spiders, link extractors, etc., and how to manipulate the data that you retrieve with the application. They each demonstrate the appropriate Python imports from subdirectories in the scrapy package to get you up and running. Hope that this helps.
64,483,669
I am trying to make a multi-container docker app using `docker-compose`. **Here's what I am trying to accomplish:** I have a python3 app, that takes a list of list of numbers as input from API call(`fastAPI` with gunicorn server) and pass the numbers to a function(an ML model actually) that returns a number, which will then be sent back(in json of course) as result to that API call. That part is working absolutely fine. Problem started when I introduced a postgres container to store the inputs I receive into a postgres table and I am yet to add the part where I should also be access data of this postgres database from my local pgadmin4 app. **Here's what I have done till now:** I am using "docker-compose.yml" file to set up both of these containers and here it is: ``` version: '3.8' services: postgres: image: postgres:12.4 restart: always environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres_password - POSTGRES_DATABASE=postgres docker_fastapi: # use the Dockerfile in the current directory. build: . ports: # 3000 is what I send API calls to - "3000:3000" # this is postgres's port - "5432:5432" environment: # these are the environment variables that I am using inside psycop2 to make connection. - POSTGRES_HOST=postgres - POSTGRES_PORT=5432 - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres_password - POSTGRES_DATABASE=postgres ``` he Here's how I am using those environment variables in `psycopg2`: ``` import os from psycopg2 import connect # making database connection using environement variables. connection = connect(host=os.environ['POSTGRES_HOST'], port=os.environ['POSTGRES_PORT'], user=os.environ['POSTGRES_USER'], password=os.environ['POSTGRES_PASSWORD'], database=os.environ['POSTGRES_DATABASE'] ) ``` here's the Dockerfile: ``` FROM tiangolo/uvicorn-gunicorn:python3.8-slim # slim = debian-based. Not using alpine because it has poor python3 support. LABEL maintainer="Sebastian Ramirez <tiangolo@gmail.com>" RUN apt-get update RUN apt-get install -y libpq-dev gcc # copy and install from requirements.txt file COPY requirements.txt /app/requirements.txt RUN pip install --no-cache-dir -r /app/requirements.txt # remove all the dependency files to reduce the final image size RUN apt-get autoremove -y gcc # copying all the code files to the container's file system COPY ./api /app/api WORKDIR /app/api EXPOSE 3000 ENTRYPOINT ["uvicorn"] CMD ["api.main:app", "--host", "0.0.0.0", "--port", "3000"] ``` And here's the error it generates for an API call I send: ``` root@naveen-hp:/home/naveen/Videos/ML-Model-serving-with-fastapi-and-Docker# # docker-compose up Starting ml-model-serving-with-fastapi-and-docker_docker_fastapi_1 ... done Starting ml-model-serving-with-fastapi-and-docker_postgres_1 ... done Attaching to ml-model-serving-with-fastapi-and-docker_postgres_1, ml-model-serving-with-fastapi-and-docker_docker_fastapi_1 postgres_1 | postgres_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization postgres_1 | postgres_1 | 2020-10-22 13:17:14.080 UTC [1] LOG: starting PostgreSQL 12.4 (Debian 12.4-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit postgres_1 | 2020-10-22 13:17:14.080 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_1 | 2020-10-22 13:17:14.080 UTC [1] LOG: listening on IPv6 address "::", port 5432 postgres_1 | 2020-10-22 13:17:14.092 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" postgres_1 | 2020-10-22 13:17:14.120 UTC [24] LOG: database system was shut down at 2020-10-22 12:48:50 UTC postgres_1 | 2020-10-22 13:17:14.130 UTC [1] LOG: database system is ready to accept connections docker_fastapi_1 | INFO: Started server process [1] docker_fastapi_1 | INFO: Waiting for application startup. docker_fastapi_1 | INFO: Application startup complete. docker_fastapi_1 | INFO: Uvicorn running on http://0.0.0.0:3000 (Press CTRL+C to quit) docker_fastapi_1 | INFO: 172.18.0.1:56094 - "POST /predict HTTP/1.1" 500 Internal Server Error docker_fastapi_1 | ERROR: Exception in ASGI application docker_fastapi_1 | Traceback (most recent call last): docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 391, in run_asgi docker_fastapi_1 | result = await app(self.scope, self.receive, self.send) docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__ docker_fastapi_1 | return await self.app(scope, receive, send) docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/fastapi/applications.py", line 179, in __call__ docker_fastapi_1 | await super().__call__(scope, receive, send) docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__ docker_fastapi_1 | await self.middleware_stack(scope, receive, send) docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__ docker_fastapi_1 | raise exc from None docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__ docker_fastapi_1 | await self.app(scope, receive, _send) docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__ docker_fastapi_1 | raise exc from None docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__ docker_fastapi_1 | await self.app(scope, receive, sender) docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__ docker_fastapi_1 | await route.handle(scope, receive, send) docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle docker_fastapi_1 | await self.app(scope, receive, send) docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 41, in app docker_fastapi_1 | response = await func(request) docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/fastapi/routing.py", line 182, in app docker_fastapi_1 | raw_response = await run_endpoint_function( docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/fastapi/routing.py", line 135, in run_endpoint_function docker_fastapi_1 | return await run_in_threadpool(dependant.call, **values) docker_fastapi_1 | File "/usr/local/lib/python3.8/site-packages/starlette/concurrency.py", line 34, in run_in_threadpool docker_fastapi_1 | return await loop.run_in_executor(None, func, *args) docker_fastapi_1 | File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run docker_fastapi_1 | result = self.fn(*self.args, **self.kwargs) docker_fastapi_1 | File "/app/api/main.py", line 83, in predict docker_fastapi_1 | insert_into_db(X) docker_fastapi_1 | File "/app/api/main.py", line 38, in insert_into_db docker_fastapi_1 | cursor.execute(f"INSERT INTO public.\"API_Test\"" docker_fastapi_1 | IndexError: index 1 is out of bounds for axis 0 with size 1 ``` Here's how I am sending API calls: ``` curl -X POST "http://0.0.0.0:3000/predict" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"input_data\":[[ 1.354e+01, 1.436e+01, 8.746e+01, 5.663e+02, 9.779e-02, 8.129e-02, 6.664e-02, 4.781e-02, 1.885e-01, 5.766e-02, 2.699e-01, 7.886e-01, 2.058e+00, 2.356e+01, 8.462e-03, 1.460e-02, 2.387e-02, 1.315e-02, 1.980e-02, 2.300e-03, 1.511e+01, 1.926e+01, 9.970e+01, 7.112e+02, 1.440e-01, 1.773e-01, 2.390e-01, 1.288e-01, 2.977e-01, 7.259e-02]]}" ``` This works just as expected when I build it with credentials of postgres instance of AWS RDS without this second postgres container and specify credentials directly inside `psycopg2.connect()` without using environment variables and docker-compose and built directly using Dockerfile shown above; So, my code to insert the received data into postgres is presumably fine. And problems started when I introduced second container. What causes errors like these and How do I fix this?
2020/10/22
[ "https://Stackoverflow.com/questions/64483669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11814996/" ]
The problem are your labels. They have the same ids as your input fields. Since document.getElementById("date") only finds the first occurrence of the desired id your labels are returned. To solve this you can change your labels to ``` <label for="date">Date: </label> ``` ```html <html> <head> <title>Expense Tracker</title> <style type="text/css"> table { display: none; } </style> </head> <body> <h1>Expense Tracker</h1> <form action=""> <label for="date">Date: </label> <input type="date" id="date"> <br> <label for="desc">Description: </label> <input type="text" id="desc"> <br> <label for="amount">Amount: </label> <input type="text" id="amount"> <br> <input type="button" id="submit" value="Submit"> <br> </form> <table id="table"> <tr> <th>Date</th> <th>Description</th> <th>Amount</th> </tr> </table> <script type="text/javascript"> document.getElementById("submit").onclick=function() { document.getElementById("table").style.display="block"; var table = document.getElementById("table"); var row = table.insertRow(-1); var date = row.insertCell(0); var desc = row.insertCell(1); var amt = row.insertCell(2); date.innerHTML = document.getElementById("date").value; desc.innerHTML = document.getElementById("desc").value; amt.innerHTML = document.getElementById("amount").value; return false; } </script> </body> </html> ```
On your html file, each `<label>` and `<input>` tags have got the same id so the problem happened. For example, for the last `input`, the label has id `amount` and the input tag also has id `amount`. So `document.getElementById("amount")` will return the first tag `<label>` tag so it won't have no values. To solve this problem, it is needed to change the id of the labels so no duplicates. ```js document.getElementById("submit").onclick = function () { document.getElementById("table").style.display = "block"; var table = document.getElementById("table"); var row = table.insertRow(-1); var date = row.insertCell(0); var desc = row.insertCell(1); var amt = row.insertCell(2); date.innerHTML = document.getElementById("date").value; desc.innerHTML = document.getElementById("desc").value; amt.innerHTML = document.getElementById("amount").value; return false; } ``` ```css table { display: none; } ``` ```html <h1>Expense Tracker</h1> <form action=""> <label for="date">Date: </label> <input type="date" id="date"> <br> <label for="desc">Description: </label> <input type="text" id="desc"> <br> <label for="amount">Amount: </label> <input type="text" id="amount"> <br> <input type="button" id="submit" value="Submit"> <br> </form> <table id="table"> <tr> <th>Date</th> <th>Description</th> <th>Amount</th> </tr> </table> ```
5,253,358
this is the first time I have used Python. I downloaded the file ActivePython-2.7.1.4-win32-x86 and installed it on my computer; I'm using Win7. So when I tried to run a python program, it appears and disappears very quickly. I don't have enough time to see anything on the screen. I just downloaded the file and double-cliked on it. How do I launch this file? I know that it is a long file for a first Python tutorial.
2011/03/09
[ "https://Stackoverflow.com/questions/5253358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/618111/" ]
Add the line ``` input() ``` to the end of the program, with the correct indentation. The issue is that after the data is printed to the console the program finishes, so the console goes away. `input` tells the program to wait for input, so the console won't be closed when it finishes printing. I hope you're not using that program to learn Python; it's pretty complicated!
Just a bit more on this. You have a script `myscript.py` in a folder `C:\myscripts`. This is how to set up Windows 7 so that you can type `> myscript` into a CMD window and the script will run. 1) Set your `PATH` variable to include the Python Interpreter. Control Panel > System and Security > System > Advanced Settings > Environment Variables. You can set either the System Variables or the User Variables. Scroll down till you find `PATH`, select it, click `Edit`.The Path appears selected in a new dialog. I always copy it into Notepad to edit it though all you need do is add `;C:\Python27` to the end of the list. Save this. 2) Set your `PATH` variable to include `C:\myscripts` 3) Set your `PATHEXT` variable to include `;.PY`. (This is the bit that saves you from typing `myscript.py`) This may now just work. Try opening a command window and typing `myscript` But it may not. Windows can still mess you about. I had installed and then uninstalled a Python package and when I typed `myscript` Windows opened a box asking me which program to use. I browsed for `C:\python27\python.exe` and clicked that. Windows opened another command window ran the script and closed it before I could see what my script had done! To fix this when Windows opens its dialog select your Python and *click the "Always do this" checkbox at the bottom.* Then it doesn't open and close another window and things work as they should. Or they did for me. Added: Above does not say how to pass arguments to your script. For this see answer [Windows fails to pass arguments to python script](https://stackoverflow.com/questions/6109582/windows-fails-to-pass-the-args-to-a-python-script)
5,253,358
this is the first time I have used Python. I downloaded the file ActivePython-2.7.1.4-win32-x86 and installed it on my computer; I'm using Win7. So when I tried to run a python program, it appears and disappears very quickly. I don't have enough time to see anything on the screen. I just downloaded the file and double-cliked on it. How do I launch this file? I know that it is a long file for a first Python tutorial.
2011/03/09
[ "https://Stackoverflow.com/questions/5253358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/618111/" ]
go to `Start > All programs > Accessories` and click on `Command Prompt`. then drag the python file from the explorer view into this command line and press `Enter`... now you can watch the output of the script execution !
Just a bit more on this. You have a script `myscript.py` in a folder `C:\myscripts`. This is how to set up Windows 7 so that you can type `> myscript` into a CMD window and the script will run. 1) Set your `PATH` variable to include the Python Interpreter. Control Panel > System and Security > System > Advanced Settings > Environment Variables. You can set either the System Variables or the User Variables. Scroll down till you find `PATH`, select it, click `Edit`.The Path appears selected in a new dialog. I always copy it into Notepad to edit it though all you need do is add `;C:\Python27` to the end of the list. Save this. 2) Set your `PATH` variable to include `C:\myscripts` 3) Set your `PATHEXT` variable to include `;.PY`. (This is the bit that saves you from typing `myscript.py`) This may now just work. Try opening a command window and typing `myscript` But it may not. Windows can still mess you about. I had installed and then uninstalled a Python package and when I typed `myscript` Windows opened a box asking me which program to use. I browsed for `C:\python27\python.exe` and clicked that. Windows opened another command window ran the script and closed it before I could see what my script had done! To fix this when Windows opens its dialog select your Python and *click the "Always do this" checkbox at the bottom.* Then it doesn't open and close another window and things work as they should. Or they did for me. Added: Above does not say how to pass arguments to your script. For this see answer [Windows fails to pass arguments to python script](https://stackoverflow.com/questions/6109582/windows-fails-to-pass-the-args-to-a-python-script)
5,253,358
this is the first time I have used Python. I downloaded the file ActivePython-2.7.1.4-win32-x86 and installed it on my computer; I'm using Win7. So when I tried to run a python program, it appears and disappears very quickly. I don't have enough time to see anything on the screen. I just downloaded the file and double-cliked on it. How do I launch this file? I know that it is a long file for a first Python tutorial.
2011/03/09
[ "https://Stackoverflow.com/questions/5253358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/618111/" ]
run it from a command prompt: ``` > python myscript.py ``` You can also start only the python interpreter from the command prompt (or by running python.exe) and then try some commands: ``` > python Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> >>> a = 2 >>> b = 7 >>> print a+b 9 >>> ```
Just a bit more on this. You have a script `myscript.py` in a folder `C:\myscripts`. This is how to set up Windows 7 so that you can type `> myscript` into a CMD window and the script will run. 1) Set your `PATH` variable to include the Python Interpreter. Control Panel > System and Security > System > Advanced Settings > Environment Variables. You can set either the System Variables or the User Variables. Scroll down till you find `PATH`, select it, click `Edit`.The Path appears selected in a new dialog. I always copy it into Notepad to edit it though all you need do is add `;C:\Python27` to the end of the list. Save this. 2) Set your `PATH` variable to include `C:\myscripts` 3) Set your `PATHEXT` variable to include `;.PY`. (This is the bit that saves you from typing `myscript.py`) This may now just work. Try opening a command window and typing `myscript` But it may not. Windows can still mess you about. I had installed and then uninstalled a Python package and when I typed `myscript` Windows opened a box asking me which program to use. I browsed for `C:\python27\python.exe` and clicked that. Windows opened another command window ran the script and closed it before I could see what my script had done! To fix this when Windows opens its dialog select your Python and *click the "Always do this" checkbox at the bottom.* Then it doesn't open and close another window and things work as they should. Or they did for me. Added: Above does not say how to pass arguments to your script. For this see answer [Windows fails to pass arguments to python script](https://stackoverflow.com/questions/6109582/windows-fails-to-pass-the-args-to-a-python-script)
5,253,358
this is the first time I have used Python. I downloaded the file ActivePython-2.7.1.4-win32-x86 and installed it on my computer; I'm using Win7. So when I tried to run a python program, it appears and disappears very quickly. I don't have enough time to see anything on the screen. I just downloaded the file and double-cliked on it. How do I launch this file? I know that it is a long file for a first Python tutorial.
2011/03/09
[ "https://Stackoverflow.com/questions/5253358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/618111/" ]
Or run it from a batch file: ``` myprog.py pause ``` Has the advantage that you can specify a different version of Python too.
Just a bit more on this. You have a script `myscript.py` in a folder `C:\myscripts`. This is how to set up Windows 7 so that you can type `> myscript` into a CMD window and the script will run. 1) Set your `PATH` variable to include the Python Interpreter. Control Panel > System and Security > System > Advanced Settings > Environment Variables. You can set either the System Variables or the User Variables. Scroll down till you find `PATH`, select it, click `Edit`.The Path appears selected in a new dialog. I always copy it into Notepad to edit it though all you need do is add `;C:\Python27` to the end of the list. Save this. 2) Set your `PATH` variable to include `C:\myscripts` 3) Set your `PATHEXT` variable to include `;.PY`. (This is the bit that saves you from typing `myscript.py`) This may now just work. Try opening a command window and typing `myscript` But it may not. Windows can still mess you about. I had installed and then uninstalled a Python package and when I typed `myscript` Windows opened a box asking me which program to use. I browsed for `C:\python27\python.exe` and clicked that. Windows opened another command window ran the script and closed it before I could see what my script had done! To fix this when Windows opens its dialog select your Python and *click the "Always do this" checkbox at the bottom.* Then it doesn't open and close another window and things work as they should. Or they did for me. Added: Above does not say how to pass arguments to your script. For this see answer [Windows fails to pass arguments to python script](https://stackoverflow.com/questions/6109582/windows-fails-to-pass-the-args-to-a-python-script)
35,600,152
I am deploying a django project on apache2 using mod\_wsgi, but the problem is that the server dont serve pages and it hangs for 10 minute before giving an error: ``` End of script output before headers ``` This is my **`site-available/000-default.conf`**: ```sh ServerAdmin webmaster@localhost DocumentRoot /home/artfact/arTfact_webSite/ Alias /static /home/artfact/arTfact_webSite/static <Directory /home/artfact/arTfact_webSite/static> Order allow,deny Allow from all Require all granted </Directory> <Directory /home/artfact/arTfact_webSite> Order allow,deny Allow from all <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess artfact_site processes=5 threads=25 python-path=/home/artfact/anaconda/lib/python2.7/site-packages/:/home/artfact/arTfact_webSite WSGIProcessGroup artfact_site WSGIScriptAlias / /home/artfact/arTfact_webSite/arTfact_webSite/wsgi.py ``` **settings.py** ``` """ Django settings for arTfact_webSite project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = xxxx # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', 'blog', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'arTfact_webSite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'arTfact_webSite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') ``` **wsgi.py** ```py """ WSGI config for arTfact_webSite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "arTfact_webSite.settings") application = get_wsgi_application() ``` **Project structure** ```sh arTfact_webSite/ ├── arTfact_webSite │   ├── __init__.py │   ├── __init__.pyc │   ├── settings.py │   ├── settings.pyc │   ├── urls.py │   ├── urls.pyc │   ├── wsgi.py │   └── wsgi.pyc ├── blog ├── static ├── media └── website ├── admin.py ├── admin.pyc ├── forms.py ├── forms.pyc ├── general_analyser.py ├── general_analyser.pyc ├── __init__.py ├── __init__.pyc ├── migrations │   ├── __init__.py │   └── __init__.pyc ├── models.py ├── models.pyc ├── send_mail.py ├── send_mail.pyc ├── static │   └── website ├── templates │   └── website ├── tests.py ├── tests.pyc ├── urls.py ├── urls.pyc ├── views.py └── views.pyc ``` In the **arTfact\_webSite/urls.py** ```py urlpatterns = [ url(r'^/*', include('website.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ``` In the **website/urls.py** ```py urlpatterns = [ url(r'^$', views.index, name='index'), ] ``` am I doing something wrong here?
2016/02/24
[ "https://Stackoverflow.com/questions/35600152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4759209/" ]
It seems you have an **'a'** in your *wsgi.py* file between the lines ``` os.environ.setdefault("DJANGO_SETTINGS_MODULE", "arTfact_webSite.settings") a application = get_wsgi_application() ``` no sure if this is in your actual file as well.
Try use the command: apachectl configtest This should help you isolate what is broken in your apache configuration. See this link for more information: <https://httpd.apache.org/docs/2.4/programs/apachectl.html> If it reports 'Syntax OK', then you know that it's a configuration **detail** problem rather than a configuration syntax problem. Otherwise, posting your apache2 logs would be helpful.
35,600,152
I am deploying a django project on apache2 using mod\_wsgi, but the problem is that the server dont serve pages and it hangs for 10 minute before giving an error: ``` End of script output before headers ``` This is my **`site-available/000-default.conf`**: ```sh ServerAdmin webmaster@localhost DocumentRoot /home/artfact/arTfact_webSite/ Alias /static /home/artfact/arTfact_webSite/static <Directory /home/artfact/arTfact_webSite/static> Order allow,deny Allow from all Require all granted </Directory> <Directory /home/artfact/arTfact_webSite> Order allow,deny Allow from all <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess artfact_site processes=5 threads=25 python-path=/home/artfact/anaconda/lib/python2.7/site-packages/:/home/artfact/arTfact_webSite WSGIProcessGroup artfact_site WSGIScriptAlias / /home/artfact/arTfact_webSite/arTfact_webSite/wsgi.py ``` **settings.py** ``` """ Django settings for arTfact_webSite project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = xxxx # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', 'blog', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'arTfact_webSite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'arTfact_webSite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') ``` **wsgi.py** ```py """ WSGI config for arTfact_webSite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "arTfact_webSite.settings") application = get_wsgi_application() ``` **Project structure** ```sh arTfact_webSite/ ├── arTfact_webSite │   ├── __init__.py │   ├── __init__.pyc │   ├── settings.py │   ├── settings.pyc │   ├── urls.py │   ├── urls.pyc │   ├── wsgi.py │   └── wsgi.pyc ├── blog ├── static ├── media └── website ├── admin.py ├── admin.pyc ├── forms.py ├── forms.pyc ├── general_analyser.py ├── general_analyser.pyc ├── __init__.py ├── __init__.pyc ├── migrations │   ├── __init__.py │   └── __init__.pyc ├── models.py ├── models.pyc ├── send_mail.py ├── send_mail.pyc ├── static │   └── website ├── templates │   └── website ├── tests.py ├── tests.pyc ├── urls.py ├── urls.pyc ├── views.py └── views.pyc ``` In the **arTfact\_webSite/urls.py** ```py urlpatterns = [ url(r'^/*', include('website.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ``` In the **website/urls.py** ```py urlpatterns = [ url(r'^$', views.index, name='index'), ] ``` am I doing something wrong here?
2016/02/24
[ "https://Stackoverflow.com/questions/35600152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4759209/" ]
It seems you have an **'a'** in your *wsgi.py* file between the lines ``` os.environ.setdefault("DJANGO_SETTINGS_MODULE", "arTfact_webSite.settings") a application = get_wsgi_application() ``` no sure if this is in your actual file as well.
You need to define a ServerName or ServerAlias in your VirtualHost block: ``` ServerName www.example.com ``` I am assuming your Apache configs above are inside a VirtualHost block like so: ``` <VirtualHost *:80> ... </VirtualHost> ```
35,600,152
I am deploying a django project on apache2 using mod\_wsgi, but the problem is that the server dont serve pages and it hangs for 10 minute before giving an error: ``` End of script output before headers ``` This is my **`site-available/000-default.conf`**: ```sh ServerAdmin webmaster@localhost DocumentRoot /home/artfact/arTfact_webSite/ Alias /static /home/artfact/arTfact_webSite/static <Directory /home/artfact/arTfact_webSite/static> Order allow,deny Allow from all Require all granted </Directory> <Directory /home/artfact/arTfact_webSite> Order allow,deny Allow from all <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess artfact_site processes=5 threads=25 python-path=/home/artfact/anaconda/lib/python2.7/site-packages/:/home/artfact/arTfact_webSite WSGIProcessGroup artfact_site WSGIScriptAlias / /home/artfact/arTfact_webSite/arTfact_webSite/wsgi.py ``` **settings.py** ``` """ Django settings for arTfact_webSite project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = xxxx # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', 'blog', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'arTfact_webSite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'arTfact_webSite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') ``` **wsgi.py** ```py """ WSGI config for arTfact_webSite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "arTfact_webSite.settings") application = get_wsgi_application() ``` **Project structure** ```sh arTfact_webSite/ ├── arTfact_webSite │   ├── __init__.py │   ├── __init__.pyc │   ├── settings.py │   ├── settings.pyc │   ├── urls.py │   ├── urls.pyc │   ├── wsgi.py │   └── wsgi.pyc ├── blog ├── static ├── media └── website ├── admin.py ├── admin.pyc ├── forms.py ├── forms.pyc ├── general_analyser.py ├── general_analyser.pyc ├── __init__.py ├── __init__.pyc ├── migrations │   ├── __init__.py │   └── __init__.pyc ├── models.py ├── models.pyc ├── send_mail.py ├── send_mail.pyc ├── static │   └── website ├── templates │   └── website ├── tests.py ├── tests.pyc ├── urls.py ├── urls.pyc ├── views.py └── views.pyc ``` In the **arTfact\_webSite/urls.py** ```py urlpatterns = [ url(r'^/*', include('website.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ``` In the **website/urls.py** ```py urlpatterns = [ url(r'^$', views.index, name='index'), ] ``` am I doing something wrong here?
2016/02/24
[ "https://Stackoverflow.com/questions/35600152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4759209/" ]
Try use the command: apachectl configtest This should help you isolate what is broken in your apache configuration. See this link for more information: <https://httpd.apache.org/docs/2.4/programs/apachectl.html> If it reports 'Syntax OK', then you know that it's a configuration **detail** problem rather than a configuration syntax problem. Otherwise, posting your apache2 logs would be helpful.
You need to define a ServerName or ServerAlias in your VirtualHost block: ``` ServerName www.example.com ``` I am assuming your Apache configs above are inside a VirtualHost block like so: ``` <VirtualHost *:80> ... </VirtualHost> ```
33,713,513
I want to use Drupal for building a Genealogy application. The difficulty, I see, is in allowing users to upload a gedcom file and for it to be parsed and then from that data, various Drupal nodes would be created. Nodes in Drupal are content items. So, I'd have individuals and families as content types and each would have various events as fields that would come from the gedcom file. The gedcom file is a generic format for genealogy information. Different desktop applications take the data and convert it to a proprietary format. What I am not sure about how to accomplish is to give the end user a form to upload their gedcom file and then have it create nodes, aka content items, with Drupal. I can find open source code to parse a gedcom file, using python, or perl, or other languages. So, I could use one of these libraries to create from the gedcom file output in JSON, XML, CSV, etc. Drupal is written in PHP and another detail of the challenge is that for the end user, I don't want to ask him/her to find that file created in step one (where step one is the parse and convert of the gedcom file) and upload that into Drupal. I'd like to somehow make this happen in one step as far as the end user sees. Somehow I would need a way to trigger Drupal to import the data after it is converted into JSON, or XML or CSV.
2015/11/14
[ "https://Stackoverflow.com/questions/33713513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/784304/" ]
There are nested calls `Magic(in - 1);`. If number is even it is printed immediately and then `Magic(in - 1);` is called. Only when `n` is zero all functions print not even number in reverse order. The first odd number is printed by the deepest `Magic()` function: ``` Magic(10) |print 10 |Magic(9) | |Magic(8) | | print 8 | | ... | | Magic(1) | | Magic(0) | | return; | | print 1 | | return | | ... | | return | |print 9 | |return |return ```
this is caused by the recursion of the function. the function is returning in the order it was called. if you want to print the odd numbers in decreasing order after the even numbers, you need to save them in a variable (array ) that is also passed to the magic function
597,289
I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any control over it. My current approach is to try to keep the interface for the library the same but provide a callback after reading each chunk of data. Something like the following: ``` data = [] while True: chunk = http_response.read(CHUNKSIZE) if not chunk: break if callback: callback(chunk) data.append(chunk) ``` Now I need to do something like: ``` self.body = ''.join(data) ``` Is *join* the right way to do this or is there another (better) way of putting all the chunks together?
2009/02/28
[ "https://Stackoverflow.com/questions/597289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ]
In python3, `bytes` objects are distinct from `str`, but I don't know any reason why there would be anything wrong with this.
`join` seems fine if you really do need to put the entire string together, but then you just wind up storing the whole thing in RAM anyway. In a situation like this, I would try to see if there's a way to process each part of the string and then discard the processed part, so you only need to hold a fixed number of bytes in memory at a time. That's usually the point of the callback approach. (If you can only process part of a chunk at a time, use a buffer as a queue to store the unprocessed data.)
597,289
I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any control over it. My current approach is to try to keep the interface for the library the same but provide a callback after reading each chunk of data. Something like the following: ``` data = [] while True: chunk = http_response.read(CHUNKSIZE) if not chunk: break if callback: callback(chunk) data.append(chunk) ``` Now I need to do something like: ``` self.body = ''.join(data) ``` Is *join* the right way to do this or is there another (better) way of putting all the chunks together?
2009/02/28
[ "https://Stackoverflow.com/questions/597289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ]
''join() is the best method for joining chunks of data. The alternative boils down to repeated concatenation, which is O(n\*\*2) due to the immutability of strings and the need to create more at every concatenation. Given, this repeated concatenation is optimized by recent versions of CPython if used with += to become O(n), but that optimization only gives it a rough equivalent to ''.join() anyway, which is explicitly O(n) over the number of bytes.
In python3, `bytes` objects are distinct from `str`, but I don't know any reason why there would be anything wrong with this.
597,289
I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any control over it. My current approach is to try to keep the interface for the library the same but provide a callback after reading each chunk of data. Something like the following: ``` data = [] while True: chunk = http_response.read(CHUNKSIZE) if not chunk: break if callback: callback(chunk) data.append(chunk) ``` Now I need to do something like: ``` self.body = ''.join(data) ``` Is *join* the right way to do this or is there another (better) way of putting all the chunks together?
2009/02/28
[ "https://Stackoverflow.com/questions/597289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ]
hm - what problem are you trying to solve? I suspect the answer depends on what you are trying to do with the data. Since in general you don't want a whole 3Gb file in memory, I'd not store the chunks in an array, but iterate over the http\_response and write it straight to disk, in a temporary or persistent file using the normal write() method on an appropriate file handle. if you do want two copies of the data in memory, your method will require be at least 6Gb for your hypothetical 3Gb file, which presumably is significant for most hardware. I know that array join methods are fast and all that, but since this is a really ram-constrained process maybe you want to find some way of doing it better? StringIO (<http://docs.python.org/library/stringio.html>) creates string objects that can be appended to in memory; the pure python one, since it has to work with immutable strings, just uses your array join trick internally, but the c-based cStringIO might actually append to a memory buffer internall. I don't have its source code to hand, so that would bear checking. if you do wish to do some kind of analysis on the data and really wish to keep in in memory with minimal overhead, you might want to consider some of the byte array objets from Numeric/NumPy as an alternative to StringIO. they are high-performance code optimised for large arrays and might be what you need. as a useful example, for a general-purpose file-handling object which has memory-efficient iterator-friendly approach you might want to check out the django File obeject chunk handling code: <http://code.djangoproject.com/browser/django/trunk/django/core/files/base.py>.
In python3, `bytes` objects are distinct from `str`, but I don't know any reason why there would be anything wrong with this.
597,289
I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any control over it. My current approach is to try to keep the interface for the library the same but provide a callback after reading each chunk of data. Something like the following: ``` data = [] while True: chunk = http_response.read(CHUNKSIZE) if not chunk: break if callback: callback(chunk) data.append(chunk) ``` Now I need to do something like: ``` self.body = ''.join(data) ``` Is *join* the right way to do this or is there another (better) way of putting all the chunks together?
2009/02/28
[ "https://Stackoverflow.com/questions/597289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ]
''join() is the best method for joining chunks of data. The alternative boils down to repeated concatenation, which is O(n\*\*2) due to the immutability of strings and the need to create more at every concatenation. Given, this repeated concatenation is optimized by recent versions of CPython if used with += to become O(n), but that optimization only gives it a rough equivalent to ''.join() anyway, which is explicitly O(n) over the number of bytes.
`join` seems fine if you really do need to put the entire string together, but then you just wind up storing the whole thing in RAM anyway. In a situation like this, I would try to see if there's a way to process each part of the string and then discard the processed part, so you only need to hold a fixed number of bytes in memory at a time. That's usually the point of the callback approach. (If you can only process part of a chunk at a time, use a buffer as a queue to store the unprocessed data.)
597,289
I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any control over it. My current approach is to try to keep the interface for the library the same but provide a callback after reading each chunk of data. Something like the following: ``` data = [] while True: chunk = http_response.read(CHUNKSIZE) if not chunk: break if callback: callback(chunk) data.append(chunk) ``` Now I need to do something like: ``` self.body = ''.join(data) ``` Is *join* the right way to do this or is there another (better) way of putting all the chunks together?
2009/02/28
[ "https://Stackoverflow.com/questions/597289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ]
hm - what problem are you trying to solve? I suspect the answer depends on what you are trying to do with the data. Since in general you don't want a whole 3Gb file in memory, I'd not store the chunks in an array, but iterate over the http\_response and write it straight to disk, in a temporary or persistent file using the normal write() method on an appropriate file handle. if you do want two copies of the data in memory, your method will require be at least 6Gb for your hypothetical 3Gb file, which presumably is significant for most hardware. I know that array join methods are fast and all that, but since this is a really ram-constrained process maybe you want to find some way of doing it better? StringIO (<http://docs.python.org/library/stringio.html>) creates string objects that can be appended to in memory; the pure python one, since it has to work with immutable strings, just uses your array join trick internally, but the c-based cStringIO might actually append to a memory buffer internall. I don't have its source code to hand, so that would bear checking. if you do wish to do some kind of analysis on the data and really wish to keep in in memory with minimal overhead, you might want to consider some of the byte array objets from Numeric/NumPy as an alternative to StringIO. they are high-performance code optimised for large arrays and might be what you need. as a useful example, for a general-purpose file-handling object which has memory-efficient iterator-friendly approach you might want to check out the django File obeject chunk handling code: <http://code.djangoproject.com/browser/django/trunk/django/core/files/base.py>.
`join` seems fine if you really do need to put the entire string together, but then you just wind up storing the whole thing in RAM anyway. In a situation like this, I would try to see if there's a way to process each part of the string and then discard the processed part, so you only need to hold a fixed number of bytes in memory at a time. That's usually the point of the callback approach. (If you can only process part of a chunk at a time, use a buffer as a queue to store the unprocessed data.)
597,289
I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any control over it. My current approach is to try to keep the interface for the library the same but provide a callback after reading each chunk of data. Something like the following: ``` data = [] while True: chunk = http_response.read(CHUNKSIZE) if not chunk: break if callback: callback(chunk) data.append(chunk) ``` Now I need to do something like: ``` self.body = ''.join(data) ``` Is *join* the right way to do this or is there another (better) way of putting all the chunks together?
2009/02/28
[ "https://Stackoverflow.com/questions/597289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ]
hm - what problem are you trying to solve? I suspect the answer depends on what you are trying to do with the data. Since in general you don't want a whole 3Gb file in memory, I'd not store the chunks in an array, but iterate over the http\_response and write it straight to disk, in a temporary or persistent file using the normal write() method on an appropriate file handle. if you do want two copies of the data in memory, your method will require be at least 6Gb for your hypothetical 3Gb file, which presumably is significant for most hardware. I know that array join methods are fast and all that, but since this is a really ram-constrained process maybe you want to find some way of doing it better? StringIO (<http://docs.python.org/library/stringio.html>) creates string objects that can be appended to in memory; the pure python one, since it has to work with immutable strings, just uses your array join trick internally, but the c-based cStringIO might actually append to a memory buffer internall. I don't have its source code to hand, so that would bear checking. if you do wish to do some kind of analysis on the data and really wish to keep in in memory with minimal overhead, you might want to consider some of the byte array objets from Numeric/NumPy as an alternative to StringIO. they are high-performance code optimised for large arrays and might be what you need. as a useful example, for a general-purpose file-handling object which has memory-efficient iterator-friendly approach you might want to check out the django File obeject chunk handling code: <http://code.djangoproject.com/browser/django/trunk/django/core/files/base.py>.
''join() is the best method for joining chunks of data. The alternative boils down to repeated concatenation, which is O(n\*\*2) due to the immutability of strings and the need to create more at every concatenation. Given, this repeated concatenation is optimized by recent versions of CPython if used with += to become O(n), but that optimization only gives it a rough equivalent to ''.join() anyway, which is explicitly O(n) over the number of bytes.
22,890,598
I have a function which calculates the jaccard index for two parse strings. The function is working OK and its code is below: ``` def jack(a,b): x=a.split() y=b.split() k=float(len(list(set(x)&set(y))))/float(len(list(set(x) | set(y)))) return k ``` However, when I want to apply the function for any two elements of a list, an error appears. My list is called "a" and it's like this :[ ["Coca Cola"],["Coca Sc"]]. The error message is: ``` --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-51-0d7031267380> in <module>() ----> 1 jack(a[2],a[3]) <ipython-input-27-256123b04a44> in jack(a, b) 1 def jack(a,b): ----> 2 x=a.split() 3 y=b.split() 4 k=float(len(list(set(x)&set(y))))/float(len(list(set(x) | set(y)))) 5 return k AttributeError: 'list' object has no attribute 'split' ``` I know it´s because a[2] is a list too, but I would like to find a way to deal with this to have the expected output. Maybe I can modify my function or the way I enter the output.
2014/04/06
[ "https://Stackoverflow.com/questions/22890598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2825079/" ]
Since you have one element lists and you are passing the lists as the parameters whereas your function expects strings, I would recommend you to invoke your function like this ``` jack(a[2][0], a[3][0]) ``` Also, you dont have to convert the `set` to a `list` to find the length. ``` return float(len(set(x) & set(y))) / float(len(set(x) | set(y))) ``` should be enough here.
That is because your variable `a` is a nested list. You should either flatten `a` or pass the arguments as: `jack(a[2][0],a[3][0])` ### Or, you could flatten your list as: `a = [i[0] for i in a]` then you can easily do: `jack(a[0],a[1])`
21,269,702
I’m using wxPython to write an app that will run under OS X, Windows, and Linux. I’m trying to implement the standard “Close Window” menu item, but I’m not sure how to find out which window is frontmost. WX has a [`GetActiveWindow` function](http://wxpython.org/Phoenix/docs/html/functions.html#GetActiveWindow), but apparently this only works under Windows and GTK. Is there a built-in way to do this on OS X? (And if not, why not?)
2014/01/21
[ "https://Stackoverflow.com/questions/21269702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/371228/" ]
Okay I managed to finally get this program working, I've summarized below. I hope this might help someone also stuck on ex17. First, I removed the MAX\_DATA and MAX\_ROWS constants and changed the structs like so: ``` struct Address { int id; int set; char *name; char *email; }; struct Database { int max_data; int max_rows; struct Address **rows; }; struct Connection { FILE *file; struct Database *db; }; ``` I assign `max_data` and `max_rows` to the new variables in the struct and them write them to the file. ``` conn->db->max_data = max_data; conn->db->max_rows = max_rows; int rc = fwrite(&conn->db->max_data, sizeof(int), 1, conn->file); rc = fwrite(&conn->db->max_rows, sizeof(int), 1, conn->file); ``` Now I can run my program and replace `MAX_ROWS` & `MAX_DATA` with `conn->db->max_rows` & `conn->db->max_data`.
One way is to change your arrays into pointers. Then you could write an alloc\_db function which would use the max\_row and max\_data values to allocate the needed memory. ``` struct Address { int id; int set; char* name; char* email; }; struct Database { struct Address* rows; unsigned int max_row; unsigned int max_data; }; struct Connection { FILE *file; struct Database *db; }; ```
21,269,702
I’m using wxPython to write an app that will run under OS X, Windows, and Linux. I’m trying to implement the standard “Close Window” menu item, but I’m not sure how to find out which window is frontmost. WX has a [`GetActiveWindow` function](http://wxpython.org/Phoenix/docs/html/functions.html#GetActiveWindow), but apparently this only works under Windows and GTK. Is there a built-in way to do this on OS X? (And if not, why not?)
2014/01/21
[ "https://Stackoverflow.com/questions/21269702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/371228/" ]
Okay I managed to finally get this program working, I've summarized below. I hope this might help someone also stuck on ex17. First, I removed the MAX\_DATA and MAX\_ROWS constants and changed the structs like so: ``` struct Address { int id; int set; char *name; char *email; }; struct Database { int max_data; int max_rows; struct Address **rows; }; struct Connection { FILE *file; struct Database *db; }; ``` I assign `max_data` and `max_rows` to the new variables in the struct and them write them to the file. ``` conn->db->max_data = max_data; conn->db->max_rows = max_rows; int rc = fwrite(&conn->db->max_data, sizeof(int), 1, conn->file); rc = fwrite(&conn->db->max_rows, sizeof(int), 1, conn->file); ``` Now I can run my program and replace `MAX_ROWS` & `MAX_DATA` with `conn->db->max_rows` & `conn->db->max_data`.
``` #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <errno.h> #include <string.h> struct Address { int id; int set; char* name; char* email; }; struct Database { int MAX_ROWS; int MAX_DATA; struct Address* rows; }; struct Connection { FILE* file; struct Database* db; }; void Database_close(struct Connection* conn) { if(conn) { for(size_t i = 0; i < conn->db->MAX_ROWS; i++) { struct Address* row = &conn->db->rows[i]; if(row->name) free(row->name); if(row->email) free(row->email); } if(conn->db->rows) free(conn->db->rows); if(conn->db) free(conn->db); if(conn->file) fclose(conn->file); free(conn); } } void die(char* message, struct Connection* conn) { if(errno) { perror(message); } else { printf("ERROR: %s\n", message); } Database_close(conn); exit(1); } void diec(const char* message) { if(errno) { perror(message); } else { printf("ERROR: %s\n", message); } printf("Something Wrong\n"); exit(1); } void Address_print(struct Address* addr) { printf("%d %s %s\n", addr->id, addr->name, addr->email); } void Database_load(struct Connection* conn) { assert(conn->db && conn->file); if(fread(conn->db, sizeof(struct Database), 1, conn->file) != 1) die("Failed to load database.", conn); conn->db->rows = (struct Address*)malloc(sizeof(struct Address) * conn->db->MAX_ROWS); for(size_t i = 0; i < conn->db->MAX_ROWS; i++) { struct Address* row = &conn->db->rows[i]; if(fread(&row->id, sizeof(int), 1, conn->file) != 1) die("Failed to load id.", conn); if(fread(&row->set, sizeof(int), 1, conn->file) != 1) die("Failed to load set.", conn); row->name = malloc(conn->db->MAX_DATA); row->email = malloc(conn->db->MAX_DATA); if(fread(row->name, conn->db->MAX_DATA, 1, conn->file) != 1) die("Faile to load name", conn); if(fread(row->email, conn->db->MAX_DATA, 1, conn->file) != 1) die("Faile to load email", conn); } } struct Connection* Database_open(const char* filename, char mode) { struct Connection* conn = malloc(sizeof(struct Connection)); if(!conn) die("Memory error", conn); conn->db = malloc(sizeof(struct Database)); if(!conn->db) die("Memory error", conn); if(mode == 'c') { conn->file = fopen(filename, "w"); } else { conn->file = fopen(filename, "r+"); if(conn->file) { Database_load(conn); } } if(!conn->file) die("Failed to open the file", conn); return conn; } void Database_create(struct Connection* conn) { printf("MAX_ROWS: "); scanf("%d", &conn->db->MAX_ROWS); if (conn->db->MAX_ROWS<=0) die("MAX_ROWS must be positive", conn); printf("MAX_DATA: "); scanf("%d", &conn->db->MAX_DATA); if (conn->db->MAX_DATA<=0) die("MAX_DATA must be positive", conn); conn->db->rows = (struct Address*)malloc(sizeof(struct Address)*conn->db->MAX_ROWS); for(size_t i = 0; i < conn->db->MAX_ROWS; i++) { char* a = (char*)malloc(conn->db->MAX_DATA); memset(a, 0, conn->db->MAX_DATA); char* b = (char*)malloc(conn->db->MAX_DATA); memset(b, 0, conn->db->MAX_DATA); struct Address addr = {.id = i, .set = 0, .name = a, .email = b}; conn->db->rows[i] = addr; } } void Database_write(struct Connection* conn) { rewind(conn->file); if(fwrite(conn->db, sizeof(struct Database), 1, conn->file) != 1) die("Failed to write database.", conn); for (size_t i = 0; i < conn->db->MAX_ROWS; i++) { if(fwrite(&((conn->db->rows[i]).id), sizeof(int), 1, conn->file) != 1) die("Failed to write id.", conn); if(fwrite(&((conn->db->rows[i]).set), sizeof(int), 1, conn->file) != 1) die("Failed to write set.", conn); if(fwrite((conn->db->rows[i]).name, conn->db->MAX_DATA, 1, conn->file) != 1) die("Failed to write name.", conn); if(fwrite((conn->db->rows[i]).email, conn->db->MAX_DATA, 1, conn->file) != 1) die("Failed to write email.", conn); } fflush(conn->file); } void Database_set(struct Connection* conn, int id, char* name, char* email) { struct Address* addr = &conn->db->rows[id]; if(addr->set) die("Already set, delete it first", conn); addr->set = 1; name[conn->db->MAX_DATA - 1] = '\0'; email[conn->db->MAX_DATA - 1] = '\0'; strncpy(addr->name, name, conn->db->MAX_DATA); strncpy(addr->email, email, conn->db->MAX_DATA); } void Database_get(struct Connection* conn, int id) { struct Address* addr = &conn->db->rows[id]; if(addr->set) { Address_print(addr); } else { die("ID is not set", conn); } } void Database_delete(struct Connection* conn, int id) { char* a = (char*)malloc(conn->db->MAX_DATA); char* b = (char*)malloc(conn->db->MAX_DATA); free(conn->db->rows[id].name); free(conn->db->rows[id].email); struct Address addr = {.id = id, .set = 0, .name = a, .email = b}; conn->db->rows[id] = addr; } void Database_list(struct Connection* conn) { for(size_t i = 0; i < conn->db->MAX_ROWS; i++) { if(conn->db->rows[i].set) { Address_print(&(conn->db->rows[i])); } } } void Database_find(struct Connection* conn, char* keyword) { int i=0; int count=0; while (i < conn->db->MAX_ROWS) { while ( i<conn->db->MAX_ROWS) { if(conn->db->rows[i].set==1){ if(strstr(conn->db->rows[i].name, keyword) != NULL || strstr(conn->db->rows[i].email, keyword) != NULL){ break; } } i++; } if(i >= conn->db->MAX_ROWS) break; Address_print(&(conn->db->rows[i])); count++; i++; } if (count==0) { printf("Try some other words\n"); } } int main(int argc, char* argv[]) { if(argc < 3) diec("USAGE: ex17 <dbfile> <action> [action params]"); int id = 0; if(argc > 3) id = atoi(argv[3]); char* filename = argv[1]; char action = argv[2][0]; struct Connection* conn = Database_open(filename, action); switch(action) { case 'c': Database_create(conn); Database_write(conn); printf("\nDone\n"); break; case 'g': if(argc != 4) die("Need an id to get", conn); Database_get(conn, id); break; case 's': if(argc != 6) die("Need id, name, email to set", conn); Database_set(conn, id, argv[4], argv[5]); Database_write(conn); break; case 'd': if(argc != 4) die("Need id to delete", conn); Database_delete(conn, id); Database_write(conn); break; case 'l': Database_list(conn); break; case 'f': if(argc != 4) die("Need keyword to search.", conn); Database_find(conn, argv[3]); break; default: die("Invalid action, only: c=create, g=get, s=set, d=del, l=list, f=find", conn); } Database_close(conn); return 0; } ```
9,560,616
I am using ArcGIS focal statistics tool to add spatial autocorrelation to a random raster to model error in DEMs. The input DEM has a 1.5m pixel size and the semivariogram exhibits a sill around 2000m. I want to make sure to model the extent of the autocorrelation in the input in my model. Unfortunately, ArcGIS requires that the input kernel be in ASCII format, where the first line defines the size and the subsequent lines define the weights. Example: ``` 5 5 1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1 ``` I need to generate a 1333x1333 kernel with an inverse distance weighting and immediately went to python to get this done. Is it possible to generate a matrix in numpy and assign values by ring? Does a better programmatic tool within numpy exist to generate a plain text matrix. This is similar to [this question](https://stackoverflow.com/questions/7598264/generate-a-patterned-numpy-matrix), but I need to have a fixed central value and descending rings, as per the example above. Note: I am a student, but this not a homework assignment...those ended years ago. This is a part of a larger research project that I am working on and any help (even just a nudge in the right direction) would be appreciated. The focus of this work is not programming kernels, but exploring errors in DEMs.
2012/03/05
[ "https://Stackoverflow.com/questions/9560616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/839375/" ]
I'm not sure if there is a built-in way, but it should not be hard to roll your own: ``` >>> def kernel_thing(N): ... import numpy as np ... n = N // 2 + 1 ... a = np.zeros((N, N), dtype=int) ... for i in xrange(n): ... a[i:N-i, i:N-i] += 1 ... return a ... >>> def kernel_to_string(a): ... return '{} {}\n'.format(a.shape[0], a.shape[1]) + '\n'.join(' '.join(str(element) for element in row) for row in a) ... >>> print kernel_to_string(kernel_thing(5)) 5 5 1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1 >>> print kernel_to_string(kernel_thing(6)) 6 6 1 1 1 1 1 1 1 2 2 2 2 1 1 2 3 3 2 1 1 2 3 3 2 1 1 2 2 2 2 1 1 1 1 1 1 1 >>> print kernel_to_string(kernel_thing(17)) 17 17 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 2 3 3 3 3 3 3 3 3 3 3 3 3 3 2 1 1 2 3 4 4 4 4 4 4 4 4 4 4 4 3 2 1 1 2 3 4 5 5 5 5 5 5 5 5 5 4 3 2 1 1 2 3 4 5 6 6 6 6 6 6 6 5 4 3 2 1 1 2 3 4 5 6 7 7 7 7 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 8 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 8 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 7 7 7 7 6 5 4 3 2 1 1 2 3 4 5 6 6 6 6 6 6 6 5 4 3 2 1 1 2 3 4 5 5 5 5 5 5 5 5 5 4 3 2 1 1 2 3 4 4 4 4 4 4 4 4 4 4 4 3 2 1 1 2 3 3 3 3 3 3 3 3 3 3 3 3 3 2 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ```
[Hmmph. @wim beat me, but I'd already written the following, so I'll post it anyway.] Short version: ``` import numpy N = 5 # get grid coords xx, yy = numpy.mgrid[0:N,0:N] # get the distance weights kernel = 1 + N//2 - numpy.maximum(abs(xx-N//2), abs(yy-N//2)) with open('kernel.out','w') as fp: # header fp.write("{} {}\n".format(N, N)) # integer matrix output numpy.savetxt(fp, kernel, fmt="%d") ``` which produces ``` ~/coding$ python kernel.py ~/coding$ cat kernel.out 5 5 1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1 ``` --- Verbose explanation of the magic: the first thing we're going to need are the indices of each entry in the matrix, and for that we can use [mgrid](http://docs.scipy.org/doc/numpy/reference/generated/numpy.mgrid.html): ``` >>> import numpy >>> N = 5 >>> xx, yy = numpy.mgrid[0:N,0:N] >>> xx array([[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]]) >>> yy array([[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]) ``` So, taken pairwise, these are the x and y coordinates of each element of a 5x5 array. The centre will be at N//2,N//2 (where // is truncating division), so we can subtract that to get the distances, and take the absolute value because we don't care about the sign: ``` >>> abs(xx-N//2) array([[2, 2, 2, 2, 2], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2]]) >>> abs(yy-N//2) array([[2, 1, 0, 1, 2], [2, 1, 0, 1, 2], [2, 1, 0, 1, 2], [2, 1, 0, 1, 2], [2, 1, 0, 1, 2]]) ``` Now looking at the original grid, it looks like you want the maximum value of the two: ``` >>> numpy.maximum(abs(xx-N//2), abs(yy-N//2)) array([[2, 2, 2, 2, 2], [2, 1, 1, 1, 2], [2, 1, 0, 1, 2], [2, 1, 1, 1, 2], [2, 2, 2, 2, 2]]) ``` which looks good but goes the wrong way. We can invert, though: ``` >>> N//2 - numpy.maximum(abs(xx-N//2), abs(yy-N//2)) array([[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 2, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]) ``` and you want 1-indexing, it looks like, so: ``` >>> 1 + N//2 - numpy.maximum(abs(xx-N//2), abs(yy-N//2)) array([[1, 1, 1, 1, 1], [1, 2, 2, 2, 1], [1, 2, 3, 2, 1], [1, 2, 2, 2, 1], [1, 1, 1, 1, 1]]) ``` and there we have it. Everything else is boring IO.
54,619,732
I am developing a model for multi-class classification problem ( 4 classes) using Keras with Tensorflow backend. The values of `y_test` have 2D format: ``` 0 1 0 0 0 0 1 0 0 0 1 0 ``` This is the function that I use to calculate a balanced accuracy: ``` def my_metric(targ, predict): val_predict = predict val_targ = tf.math.argmax(targ, axis=1) return metrics.balanced_accuracy_score(val_targ, val_predict) ``` And this is the model: ``` hidden_neurons = 50 timestamps = 20 nb_features = 18 model = Sequential() model.add(LSTM( units=hidden_neurons, return_sequences=True, input_shape=(timestamps,nb_features), dropout=0.15 #recurrent_dropout=0.2 ) ) model.add(TimeDistributed(Dense(units=round(timestamps/2),activation='sigmoid'))) model.add(Dense(units=hidden_neurons, activation='sigmoid')) model.add(Flatten()) model.add(Dense(units=nb_classes, activation='softmax')) model.compile(loss="categorical_crossentropy", metrics = [my_metric], optimizer='adadelta') ``` When I run this code, I get this error: > > --------------------------------------------------------------------------- TypeError Traceback (most recent call > last) in () > 30 model.compile(loss="categorical\_crossentropy", > 31 metrics = [my\_metric], #'accuracy', > ---> 32 optimizer='adadelta') > > > ~/anaconda3/lib/python3.6/site-packages/keras/engine/training.py in > compile(self, optimizer, loss, metrics, loss\_weights, > sample\_weight\_mode, weighted\_metrics, target\_tensors, \*\*kwargs) > 449 output\_metrics = nested\_metrics[i] > 450 output\_weighted\_metrics = nested\_weighted\_metrics[i] > --> 451 handle\_metrics(output\_metrics) > 452 handle\_metrics(output\_weighted\_metrics, weights=weights) > 453 > > > ~/anaconda3/lib/python3.6/site-packages/keras/engine/training.py in > handle\_metrics(metrics, weights) > 418 metric\_result = weighted\_metric\_fn(y\_true, y\_pred, > 419 weights=weights, > --> 420 mask=masks[i]) > 421 > 422 # Append to self.metrics\_names, self.metric\_tensors, > > > ~/anaconda3/lib/python3.6/site-packages/keras/engine/training\_utils.py > in weighted(y\_true, y\_pred, weights, mask) > 402 """ > 403 # score\_array has ndim >= 2 > --> 404 score\_array = fn(y\_true, y\_pred) > 405 if mask is not None: > 406 # Cast the mask to floatX to avoid float64 upcasting in Theano > > > in my\_metric(targ, predict) > 22 val\_predict = predict > 23 val\_targ = tf.math.argmax(targ, axis=1) > ---> 24 return metrics.balanced\_accuracy\_score(val\_targ, val\_predict) > 25 #return 5 > 26 > > > ~/anaconda3/lib/python3.6/site-packages/sklearn/metrics/classification.py > in balanced\_accuracy\_score(y\_true, y\_pred, sample\_weight, adjusted) > > 1431 1432 """ > -> 1433 C = confusion\_matrix(y\_true, y\_pred, sample\_weight=sample\_weight) 1434 with > np.errstate(divide='ignore', invalid='ignore'): 1435 > > per\_class = np.diag(C) / C.sum(axis=1) > > > ~/anaconda3/lib/python3.6/site-packages/sklearn/metrics/classification.py > in confusion\_matrix(y\_true, y\_pred, labels, sample\_weight) > 251 > 252 """ > --> 253 y\_type, y\_true, y\_pred = \_check\_targets(y\_true, y\_pred) > 254 if y\_type not in ("binary", "multiclass"): > 255 raise ValueError("%s is not supported" % y\_type) > > > ~/anaconda3/lib/python3.6/site-packages/sklearn/metrics/classification.py > in \_check\_targets(y\_true, y\_pred) > 69 y\_pred : array or indicator matrix > 70 """ > ---> 71 check\_consistent\_length(y\_true, y\_pred) > 72 type\_true = type\_of\_target(y\_true) > 73 type\_pred = type\_of\_target(y\_pred) > > > ~/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py in > check\_consistent\_length(\*arrays) > 229 """ > 230 > --> 231 lengths = [\_num\_samples(X) for X in arrays if X is not None] > 232 uniques = np.unique(lengths) > 233 if len(uniques) > 1: > > > ~/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py in > (.0) > 229 """ > 230 > --> 231 lengths = [\_num\_samples(X) for X in arrays if X is not None] > 232 uniques = np.unique(lengths) > 233 if len(uniques) > 1: > > > ~/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py in > \_num\_samples(x) > 146 return x.shape[0] > 147 else: > --> 148 return len(x) > 149 else: > 150 return len(x) > > > TypeError: object of type 'Tensor' has no len() > > >
2019/02/10
[ "https://Stackoverflow.com/questions/54619732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9585135/" ]
You cannot call a sklearn function on a Keras tensor. You'll need to implement the functionality yourself using Keras' backend functions, or TensorFlow functions if you are using the TF backend. The `balanced_accuracy_score` is defined [as the average of the recall](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.balanced_accuracy_score.html) obtained in each column. Check [this link](https://gist.github.com/dgrahn/f68447e6cc83989c51617571396020f9) for implementations of precision and recall. As for the `balanced_accuracy_score`, you can implement it as follows: ``` import keras.backend as K def balanced_recall(y_true, y_pred): """ Computes the average per-column recall metric for a multi-class classification problem """ true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)), axis=0) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)), axis=0) recall = true_positives / (possible_positives + K.epsilon()) balanced_recall = K.mean(recall) return balanced_recall ```
try : `pip install --upgrade tensorflow`
37,463,506
I am trying to open a word document with python in windows, but I am unfamiliar with windows. My code is as follows. ``` import docx as dc doc = dc.Document(r'C:\Users\justin.white\Desktop\01100-Allergan-UD1314-SUMMARY OF WORK.docx') ``` Through another post, I learned that I had to put the r in front of my string to convert it to a raw string or it would interpret the \U as an escape sequence. The error I get is ``` PackageNotFoundError: Package not found at 'C:\Users\justin.white\Desktop\01100-Allergan-UD1314-SUMMARY OF WORK.docx' ``` I'm unsure of why it cannot find my document, 01100-Allergan-UD1314-SUMMARY OF WORK.docx. The pathway is correct as I copied it directly from the file system. Any help is appreciated thanks.
2016/05/26
[ "https://Stackoverflow.com/questions/37463506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4673518/" ]
try this ``` import StringIO from docx import Document file = r'H:\myfolder\wordfile.docx' with open(file) as f: source_stream = StringIO(f.read()) document = Document(source_stream) source_stream.close() ``` <http://python-docx.readthedocs.io/en/latest/user/documents.html> Also, in regards to debugging the file not found error, simplify your directory names and files names. Rename the file to 'file' instead of referring to a long path with spaces, etc.
If you want to open the document in Microsoft Word try using `os.startfile()`. In your example it would be: ``` os.startfile(r'C:\Users\justin.white\Desktop\01100-Allergan-UD1314-SUMMARY OF WORK.docx') ``` This will open the document in word on your computer.
32,734,437
I got an file with text form: ``` a: b(0.1), c(0.33), d: e(0.21), f(0.41), g(0.5), k(0.8), h: y(0.9), ``` And I want get the following form: ``` a: b(0.1), c(0.33) d: e(0.21), f(0.41), g(0.5), k(0.8) h: y(0.9) ``` In python language, I have tried: ``` for line in menu: for i in line: if i == ":": ``` but i do not know if i wondering print (text before i and after i till meet another i) as one line. also delete the ',' at end of the line
2015/09/23
[ "https://Stackoverflow.com/questions/32734437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5316423/" ]
``` import re one_line = ''.join(menu).replace('\n', ' ') print re.sub(', ([a-z]+:)', r'\n\1', one_line)[:-1] ``` You might have to tweak the `one_line` to match your input better.
I am not exactly sure if you want to print the stuff or actually manipulate the file. But in the case of just printing: ``` from __future__ import print_function from itertools import tee, islice, chain, izip def previous_and_next(some_iterable): prevs, items, nexts = tee(some_iterable, 3) prevs = chain([None], prevs) nexts = chain(islice(nexts, 1, None), [None]) return izip(prevs, items, nexts) with open('test.txt') as f: for i, (prev, line, next) in enumerate(previous_and_next(f)): if ":" in line and i != 0: #Add a newline before every ":" except the first. print() if not next or ":" in next: #Check if the next line is a semicolon, if so strip it. "not next" is need because if there is no next NoneType is returned. print(line.rstrip()[:-1], end=" ") else: #Otherwise just strip the newline and don't print any newline. print(line.rstrip(), end=" ") ``` Using [this helper function](https://stackoverflow.com/a/1012089/667648).
32,734,437
I got an file with text form: ``` a: b(0.1), c(0.33), d: e(0.21), f(0.41), g(0.5), k(0.8), h: y(0.9), ``` And I want get the following form: ``` a: b(0.1), c(0.33) d: e(0.21), f(0.41), g(0.5), k(0.8) h: y(0.9) ``` In python language, I have tried: ``` for line in menu: for i in line: if i == ":": ``` but i do not know if i wondering print (text before i and after i till meet another i) as one line. also delete the ',' at end of the line
2015/09/23
[ "https://Stackoverflow.com/questions/32734437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5316423/" ]
``` import re one_line = ''.join(menu).replace('\n', ' ') print re.sub(', ([a-z]+:)', r'\n\1', one_line)[:-1] ``` You might have to tweak the `one_line` to match your input better.
Here a solution using an OrderedDict to store ':'-containing lines as key and the following lines as value until the next key is found. Then just print the dictionary as you like. ``` from collections import OrderedDict data = OrderedDict() key = False for line in menu: if ':' in line: key = line.strip() data.update({line:[]}) else: if key: data[key].append(line.strip(',')) for key in data: print(key,end=' ') if data[key][-1] != '': for item in data[key][:-1]: print(item, end=', ') print(data[key][-1]) else: print(data[key][0]) ``` Gives: ``` a: b(0.1), c(0.33) d: e(0.21), f(0.41), g(0.5), k(0.8) h: y(0.9) ```
63,811,316
I am running celery worker(version 4.4) on windows machine, when I run the worker with `-P eventlet` option it throws Attribute error. Error logs are as follows:- ``` pipenv run celery worker -A src.celery_app -l info -P eventlet --without-mingle --without-heartbeat --without-gossip -Q queue1 -n worker1 Traceback (most recent call last): File "d:\python37\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "d:\python37\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\G-US01.Test\.virtualenvs\celery-z5n-38Vt\Scripts\celery.exe\__main__.py", line 7, in <module> File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__main__.py", line 14, in main maybe_patch_concurrency() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__init__.py", line 152, in maybe_patch_concurrency patcher() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__init__.py", line 109, in _patch_eventlet eventlet.monkey_patch() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\eventlet\patcher.py", line 334, in monkey_patch fix_threading_active() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\eventlet\patcher.py", line 331, in fix_threading_active _os.register_at_fork( AttributeError: module 'os' has no attribute 'register_at_fork' ``` I have installed eventlet in virtual environment, the pipfile contents are as follows:- ``` [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] rope = "*" autopep8 = "*" [packages] eventlet = "*" psutil = "*" celery = "*" pythonnet = "*" redis = "*" gevent = "*" [requires] python_version = "3.7" ``` Please let me know where I am going wrong.
2020/09/09
[ "https://Stackoverflow.com/questions/63811316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5605353/" ]
`os.register_at_fork` is a new function available since `Python 3.7`, it is only available for Unix systems ([Source from Python doc](https://docs.python.org/3.8/library/os.html#os.register_at_fork)) and Eventlet use it to patch `threading` library. There is an issue opened in Eventlet Github: <https://github.com/eventlet/eventlet/issues/644> So I don't think `Celery -A app worker -l info -P eventlet` is any longer a good alternative for Windows. Personally I ran: ``` Celery -A app worker -l info ``` And it worked with `Windows 10`, `Python 3.7` and `Celery 4.4.7`.
One reason you are facing this is because of the fact that Celery works on a pre-fork model. So if the underlying OS does not support it, you will have a tough time running celery. As per my knowledge, this model does not exist for the Windows kernel. You can still use Cygwin if you want to make it work on windows or have Linux subsystem available for Windows Sources:- 1. [How to run celery on windows?](https://stackoverflow.com/questions/37255548/how-to-run-celery-on-windows) 2. <https://docs.celeryproject.org/en/stable/faq.html#does-celery-support-windows>
63,811,316
I am running celery worker(version 4.4) on windows machine, when I run the worker with `-P eventlet` option it throws Attribute error. Error logs are as follows:- ``` pipenv run celery worker -A src.celery_app -l info -P eventlet --without-mingle --without-heartbeat --without-gossip -Q queue1 -n worker1 Traceback (most recent call last): File "d:\python37\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "d:\python37\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\G-US01.Test\.virtualenvs\celery-z5n-38Vt\Scripts\celery.exe\__main__.py", line 7, in <module> File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__main__.py", line 14, in main maybe_patch_concurrency() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__init__.py", line 152, in maybe_patch_concurrency patcher() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__init__.py", line 109, in _patch_eventlet eventlet.monkey_patch() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\eventlet\patcher.py", line 334, in monkey_patch fix_threading_active() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\eventlet\patcher.py", line 331, in fix_threading_active _os.register_at_fork( AttributeError: module 'os' has no attribute 'register_at_fork' ``` I have installed eventlet in virtual environment, the pipfile contents are as follows:- ``` [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] rope = "*" autopep8 = "*" [packages] eventlet = "*" psutil = "*" celery = "*" pythonnet = "*" redis = "*" gevent = "*" [requires] python_version = "3.7" ``` Please let me know where I am going wrong.
2020/09/09
[ "https://Stackoverflow.com/questions/63811316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5605353/" ]
One reason you are facing this is because of the fact that Celery works on a pre-fork model. So if the underlying OS does not support it, you will have a tough time running celery. As per my knowledge, this model does not exist for the Windows kernel. You can still use Cygwin if you want to make it work on windows or have Linux subsystem available for Windows Sources:- 1. [How to run celery on windows?](https://stackoverflow.com/questions/37255548/how-to-run-celery-on-windows) 2. <https://docs.celeryproject.org/en/stable/faq.html#does-celery-support-windows>
is the eventlet version 0.26; pip install eventlet==0.26
63,811,316
I am running celery worker(version 4.4) on windows machine, when I run the worker with `-P eventlet` option it throws Attribute error. Error logs are as follows:- ``` pipenv run celery worker -A src.celery_app -l info -P eventlet --without-mingle --without-heartbeat --without-gossip -Q queue1 -n worker1 Traceback (most recent call last): File "d:\python37\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "d:\python37\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\G-US01.Test\.virtualenvs\celery-z5n-38Vt\Scripts\celery.exe\__main__.py", line 7, in <module> File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__main__.py", line 14, in main maybe_patch_concurrency() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__init__.py", line 152, in maybe_patch_concurrency patcher() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__init__.py", line 109, in _patch_eventlet eventlet.monkey_patch() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\eventlet\patcher.py", line 334, in monkey_patch fix_threading_active() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\eventlet\patcher.py", line 331, in fix_threading_active _os.register_at_fork( AttributeError: module 'os' has no attribute 'register_at_fork' ``` I have installed eventlet in virtual environment, the pipfile contents are as follows:- ``` [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] rope = "*" autopep8 = "*" [packages] eventlet = "*" psutil = "*" celery = "*" pythonnet = "*" redis = "*" gevent = "*" [requires] python_version = "3.7" ``` Please let me know where I am going wrong.
2020/09/09
[ "https://Stackoverflow.com/questions/63811316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5605353/" ]
`os.register_at_fork` is a new function available since `Python 3.7`, it is only available for Unix systems ([Source from Python doc](https://docs.python.org/3.8/library/os.html#os.register_at_fork)) and Eventlet use it to patch `threading` library. There is an issue opened in Eventlet Github: <https://github.com/eventlet/eventlet/issues/644> So I don't think `Celery -A app worker -l info -P eventlet` is any longer a good alternative for Windows. Personally I ran: ``` Celery -A app worker -l info ``` And it worked with `Windows 10`, `Python 3.7` and `Celery 4.4.7`.
is the eventlet version 0.26; pip install eventlet==0.26
63,811,316
I am running celery worker(version 4.4) on windows machine, when I run the worker with `-P eventlet` option it throws Attribute error. Error logs are as follows:- ``` pipenv run celery worker -A src.celery_app -l info -P eventlet --without-mingle --without-heartbeat --without-gossip -Q queue1 -n worker1 Traceback (most recent call last): File "d:\python37\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "d:\python37\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\G-US01.Test\.virtualenvs\celery-z5n-38Vt\Scripts\celery.exe\__main__.py", line 7, in <module> File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__main__.py", line 14, in main maybe_patch_concurrency() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__init__.py", line 152, in maybe_patch_concurrency patcher() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__init__.py", line 109, in _patch_eventlet eventlet.monkey_patch() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\eventlet\patcher.py", line 334, in monkey_patch fix_threading_active() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\eventlet\patcher.py", line 331, in fix_threading_active _os.register_at_fork( AttributeError: module 'os' has no attribute 'register_at_fork' ``` I have installed eventlet in virtual environment, the pipfile contents are as follows:- ``` [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] rope = "*" autopep8 = "*" [packages] eventlet = "*" psutil = "*" celery = "*" pythonnet = "*" redis = "*" gevent = "*" [requires] python_version = "3.7" ``` Please let me know where I am going wrong.
2020/09/09
[ "https://Stackoverflow.com/questions/63811316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5605353/" ]
`os.register_at_fork` is a new function available since `Python 3.7`, it is only available for Unix systems ([Source from Python doc](https://docs.python.org/3.8/library/os.html#os.register_at_fork)) and Eventlet use it to patch `threading` library. There is an issue opened in Eventlet Github: <https://github.com/eventlet/eventlet/issues/644> So I don't think `Celery -A app worker -l info -P eventlet` is any longer a good alternative for Windows. Personally I ran: ``` Celery -A app worker -l info ``` And it worked with `Windows 10`, `Python 3.7` and `Celery 4.4.7`.
As hinted at by @金奕峰, `os.register_at_fork` was introduced in eventlet v0.27.0 [c.f. commit compare on github](https://github.com/eventlet/eventlet/compare/v0.26.1...v0.27.0). Specifying version 0.26.0 in your virtual environment's package list might solve the problem (for now).
63,811,316
I am running celery worker(version 4.4) on windows machine, when I run the worker with `-P eventlet` option it throws Attribute error. Error logs are as follows:- ``` pipenv run celery worker -A src.celery_app -l info -P eventlet --without-mingle --without-heartbeat --without-gossip -Q queue1 -n worker1 Traceback (most recent call last): File "d:\python37\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "d:\python37\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\G-US01.Test\.virtualenvs\celery-z5n-38Vt\Scripts\celery.exe\__main__.py", line 7, in <module> File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__main__.py", line 14, in main maybe_patch_concurrency() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__init__.py", line 152, in maybe_patch_concurrency patcher() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\celery\__init__.py", line 109, in _patch_eventlet eventlet.monkey_patch() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\eventlet\patcher.py", line 334, in monkey_patch fix_threading_active() File "c:\users\g-us01.test\.virtualenvs\celery-z5n-38vt\lib\site-packages\eventlet\patcher.py", line 331, in fix_threading_active _os.register_at_fork( AttributeError: module 'os' has no attribute 'register_at_fork' ``` I have installed eventlet in virtual environment, the pipfile contents are as follows:- ``` [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] rope = "*" autopep8 = "*" [packages] eventlet = "*" psutil = "*" celery = "*" pythonnet = "*" redis = "*" gevent = "*" [requires] python_version = "3.7" ``` Please let me know where I am going wrong.
2020/09/09
[ "https://Stackoverflow.com/questions/63811316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5605353/" ]
As hinted at by @金奕峰, `os.register_at_fork` was introduced in eventlet v0.27.0 [c.f. commit compare on github](https://github.com/eventlet/eventlet/compare/v0.26.1...v0.27.0). Specifying version 0.26.0 in your virtual environment's package list might solve the problem (for now).
is the eventlet version 0.26; pip install eventlet==0.26
18,233,399
I have a fat32 partition image file dump, for example created with dd. how i can parse this file with python and extract the desired file inside this partition.
2013/08/14
[ "https://Stackoverflow.com/questions/18233399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2460058/" ]
As far as reading a FAT32 filesystem image in Python goes, the [Wikipedia page](http://en.wikipedia.org/wiki/FAT32) has all the detail you need to write a read-only implementation. [Construct](http://construct.readthedocs.org/en/latest/) may be of some use. Looks like they have an example for FAT16 (<https://github.com/construct/construct/blob/master/construct/formats/filesystem/fat16.py>) which you could try extending.
Just found out this nice [lib7zip bindings](https://github.com/topia/pylib7zip) that can read RAW FAT images (and [much more](https://7zip.bugaco.com/7zip/MANUAL/general/formats.htm)). Example usage: ```py # pip install git+https://github.com/topia/pylib7zip from lib7zip import Archive, formats archive = Archive("fd.ima", forcetype="FAT") # iterate over archive contents for f in archive: if f.is_dir: continue print("; %12s %s %s" % ( f.size, f.mtime.strftime("%H:%M.%S %Y-%m-%d"), f.path)) f_crc = f.crc if not f_crc: # extract in memory and compute crc32 f_crc = -1 try: f_contents = f.contents except: # possible extraction error continue if len(f_contents) > 0: f_crc = crc32(f_contents) # end if print("%s %08X " % ( f.path, f_crc ) ) ``` An alternative is [pyfatfs](https://pypi.org/project/pyfatfs/) (untested by me).
35,569,042
I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects. I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ> After following the exact same code as him, this is the error that I get: ``` Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1240, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1083, in request self._send_request(method, url, body, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1128, in _send_request self.endheaders(body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1079, in endheaders self._send_output(message_body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 911, in _send_output self.send(msg) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 854, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1237, in connect server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 376, in wrap_socket _context=self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 747, in __init__ self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 983, in do_handshake self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 628, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) ``` During handling of the above exception, another exception occurred: ``` Traceback (most recent call last): File "WorldCup.py", line 3, in <module> x = urllib.request.urlopen('https://www.google.com') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 162, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 465, in open response = self._open(req, data) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 483, in _open '_open', req) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 443, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1283, in https_open context=self._context, check_hostname=self._check_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1242, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)> ``` Can someone help me figure out how to fix this?
2016/02/23
[ "https://Stackoverflow.com/questions/35569042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790055/" ]
On Debian 9 I had to: ``` $ sudo update-ca-certificates --fresh $ export SSL_CERT_DIR=/etc/ssl/certs ``` I'm not sure why, but this enviroment variable was never set.
This has changed in recent versions of the ssl library. The SSLContext was moved to it's own property. This is the equivalent of Jia's answer in Python 3.8 ``` import ssl ssl.SSLContext.verify_mode = ssl.VerifyMode.CERT_OPTIONAL ```
35,569,042
I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects. I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ> After following the exact same code as him, this is the error that I get: ``` Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1240, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1083, in request self._send_request(method, url, body, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1128, in _send_request self.endheaders(body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1079, in endheaders self._send_output(message_body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 911, in _send_output self.send(msg) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 854, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1237, in connect server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 376, in wrap_socket _context=self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 747, in __init__ self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 983, in do_handshake self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 628, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) ``` During handling of the above exception, another exception occurred: ``` Traceback (most recent call last): File "WorldCup.py", line 3, in <module> x = urllib.request.urlopen('https://www.google.com') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 162, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 465, in open response = self._open(req, data) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 483, in _open '_open', req) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 443, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1283, in https_open context=self._context, check_hostname=self._check_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1242, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)> ``` Can someone help me figure out how to fix this?
2016/02/23
[ "https://Stackoverflow.com/questions/35569042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790055/" ]
In my case, I used the `ssl` module to "workaround" the certification like so: ``` import ssl ssl._create_default_https_context = ssl._create_unverified_context ``` Then to read your link content, you can use: ``` urllib.request.urlopen(urllink) ```
This has changed in recent versions of the ssl library. The SSLContext was moved to it's own property. This is the equivalent of Jia's answer in Python 3.8 ``` import ssl ssl.SSLContext.verify_mode = ssl.VerifyMode.CERT_OPTIONAL ```
35,569,042
I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects. I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ> After following the exact same code as him, this is the error that I get: ``` Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1240, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1083, in request self._send_request(method, url, body, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1128, in _send_request self.endheaders(body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1079, in endheaders self._send_output(message_body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 911, in _send_output self.send(msg) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 854, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1237, in connect server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 376, in wrap_socket _context=self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 747, in __init__ self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 983, in do_handshake self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 628, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) ``` During handling of the above exception, another exception occurred: ``` Traceback (most recent call last): File "WorldCup.py", line 3, in <module> x = urllib.request.urlopen('https://www.google.com') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 162, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 465, in open response = self._open(req, data) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 483, in _open '_open', req) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 443, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1283, in https_open context=self._context, check_hostname=self._check_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1242, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)> ``` Can someone help me figure out how to fix this?
2016/02/23
[ "https://Stackoverflow.com/questions/35569042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790055/" ]
Building on the update to [Jia's 2018 answer](https://stackoverflow.com/a/49174340/866333) in [deltree's late 2021 one](https://stackoverflow.com/a/69724616/866333) I was able to achieve equivalent functionality with: ```py import urllib.request import ssl def urllib_get_2018(): # Using a protected member like this is not any more fragile # than extending the class and using it. I would use it. url = 'https://localhost:6667/my-endpoint' ssl._create_default_https_context = ssl._create_unverified_context with urllib.request.urlopen(url = url) as f: print(f.read().decode('utf-8')) def urllib_get_2022(): # Finally! Able to use the publice API. Happy happy! url = 'https://localhost:6667/my-endpoint' scontext = ssl.SSLContext(ssl.PROTOCOL_TLS) scontext.verify_mode = ssl.VerifyMode.CERT_NONE with urllib.request.urlopen(url = url, context=scontext) as f: print(f.read().decode('utf-8')) ``` I needed to use `CERT_NONE` instead of `CERT_OPTIONAL` as well as creating a `ssl.SSLContext(ssl.PROTOCOL_TLS)` to pass to `urlopen`. It's important to keep using `urllib` as it makes sense when working with small container images where `pip` might not be installed, yet.
I have a lib what use <https://requests.readthedocs.io/en/master/> what use <https://pypi.org/project/certifi/> but I have a custom CA included in my `/etc/ssl/certs`. So I solved my problem like this: ``` # Your TLS certificates directory (Debian like) export SSL_CERT_DIR=/etc/ssl/certs # CA bundle PATH (Debian like again) export CA_BUNDLE_PATH="${SSL_CERT_DIR}/ca-certificates.crt" # If you have a virtualenv: . ./.venv/bin/activate # Get the current certifi CA bundle CERTFI_PATH=`python -c 'import certifi; print(certifi.where())'` test -L $CERTFI_PATH || rm $CERTFI_PATH test -L $CERTFI_PATH || ln -s $CA_BUNDLE_PATH $CERTFI_PATH ``` Et voilà !
35,569,042
I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects. I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ> After following the exact same code as him, this is the error that I get: ``` Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1240, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1083, in request self._send_request(method, url, body, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1128, in _send_request self.endheaders(body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1079, in endheaders self._send_output(message_body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 911, in _send_output self.send(msg) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 854, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1237, in connect server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 376, in wrap_socket _context=self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 747, in __init__ self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 983, in do_handshake self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 628, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) ``` During handling of the above exception, another exception occurred: ``` Traceback (most recent call last): File "WorldCup.py", line 3, in <module> x = urllib.request.urlopen('https://www.google.com') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 162, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 465, in open response = self._open(req, data) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 483, in _open '_open', req) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 443, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1283, in https_open context=self._context, check_hostname=self._check_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1242, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)> ``` Can someone help me figure out how to fix this?
2016/02/23
[ "https://Stackoverflow.com/questions/35569042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790055/" ]
As a workaround (not secure), you can turn certificate verification off by setting PYTHONHTTPSVERIFY environment variable to 0: ``` export PYTHONHTTPSVERIFY=0 ```
I have a lib what use <https://requests.readthedocs.io/en/master/> what use <https://pypi.org/project/certifi/> but I have a custom CA included in my `/etc/ssl/certs`. So I solved my problem like this: ``` # Your TLS certificates directory (Debian like) export SSL_CERT_DIR=/etc/ssl/certs # CA bundle PATH (Debian like again) export CA_BUNDLE_PATH="${SSL_CERT_DIR}/ca-certificates.crt" # If you have a virtualenv: . ./.venv/bin/activate # Get the current certifi CA bundle CERTFI_PATH=`python -c 'import certifi; print(certifi.where())'` test -L $CERTFI_PATH || rm $CERTFI_PATH test -L $CERTFI_PATH || ln -s $CA_BUNDLE_PATH $CERTFI_PATH ``` Et voilà !
35,569,042
I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects. I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ> After following the exact same code as him, this is the error that I get: ``` Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1240, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1083, in request self._send_request(method, url, body, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1128, in _send_request self.endheaders(body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1079, in endheaders self._send_output(message_body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 911, in _send_output self.send(msg) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 854, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1237, in connect server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 376, in wrap_socket _context=self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 747, in __init__ self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 983, in do_handshake self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 628, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) ``` During handling of the above exception, another exception occurred: ``` Traceback (most recent call last): File "WorldCup.py", line 3, in <module> x = urllib.request.urlopen('https://www.google.com') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 162, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 465, in open response = self._open(req, data) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 483, in _open '_open', req) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 443, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1283, in https_open context=self._context, check_hostname=self._check_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1242, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)> ``` Can someone help me figure out how to fix this?
2016/02/23
[ "https://Stackoverflow.com/questions/35569042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790055/" ]
In my case, I used the `ssl` module to "workaround" the certification like so: ``` import ssl ssl._create_default_https_context = ssl._create_unverified_context ``` Then to read your link content, you can use: ``` urllib.request.urlopen(urllink) ```
As a workaround (not secure), you can turn certificate verification off by setting PYTHONHTTPSVERIFY environment variable to 0: ``` export PYTHONHTTPSVERIFY=0 ```
35,569,042
I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects. I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ> After following the exact same code as him, this is the error that I get: ``` Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1240, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1083, in request self._send_request(method, url, body, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1128, in _send_request self.endheaders(body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1079, in endheaders self._send_output(message_body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 911, in _send_output self.send(msg) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 854, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1237, in connect server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 376, in wrap_socket _context=self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 747, in __init__ self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 983, in do_handshake self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 628, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) ``` During handling of the above exception, another exception occurred: ``` Traceback (most recent call last): File "WorldCup.py", line 3, in <module> x = urllib.request.urlopen('https://www.google.com') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 162, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 465, in open response = self._open(req, data) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 483, in _open '_open', req) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 443, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1283, in https_open context=self._context, check_hostname=self._check_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1242, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)> ``` Can someone help me figure out how to fix this?
2016/02/23
[ "https://Stackoverflow.com/questions/35569042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790055/" ]
Building on the update to [Jia's 2018 answer](https://stackoverflow.com/a/49174340/866333) in [deltree's late 2021 one](https://stackoverflow.com/a/69724616/866333) I was able to achieve equivalent functionality with: ```py import urllib.request import ssl def urllib_get_2018(): # Using a protected member like this is not any more fragile # than extending the class and using it. I would use it. url = 'https://localhost:6667/my-endpoint' ssl._create_default_https_context = ssl._create_unverified_context with urllib.request.urlopen(url = url) as f: print(f.read().decode('utf-8')) def urllib_get_2022(): # Finally! Able to use the publice API. Happy happy! url = 'https://localhost:6667/my-endpoint' scontext = ssl.SSLContext(ssl.PROTOCOL_TLS) scontext.verify_mode = ssl.VerifyMode.CERT_NONE with urllib.request.urlopen(url = url, context=scontext) as f: print(f.read().decode('utf-8')) ``` I needed to use `CERT_NONE` instead of `CERT_OPTIONAL` as well as creating a `ssl.SSLContext(ssl.PROTOCOL_TLS)` to pass to `urlopen`. It's important to keep using `urllib` as it makes sense when working with small container images where `pip` might not be installed, yet.
I faced the same issue with Ubuntu 20.4 and have tried many solutions but nothing worked out. Finally I just checked openssl version. Even after update and upgrade, the openssl version showed **OpenSSL 1.1.1h [22 Sep 2020]**. But in my windows system, where the code works without any issue, openssl version is **OpenSSL 1.1.1k 25 Mar 2021**. I decided to update the openssl manually and it worked! Thank God!!! Steps are as follows(Ubuntu 20.4): \*To check openssl version ``` openssl version -a ``` \*To update openssl: ``` sudo apt install build-essential checkinstall zlib1g-dev cd /usr/local/src/ sudo wget https://www.openssl.org/source/openssl-1.1.1k.tar.gz sudo tar -xf openssl-1.1.1k.tar.gz cd openssl-1.1.1k sudo ./config --prefix=/usr/local/ssl --openssldir=/usr/local/ssl shared zlib sudo make sudo make test sudo make install cd /etc/ld.so.conf.d/ sudo nano openssl-1.1.1k.conf ``` \*Type /usr/local/ssl/lib and save ``` sudo ldconfig -v sudo nano /etc/environment ``` \*Add ':/usr/local/ssl/bin' to the path ``` source /etc/environment echo $PATH ``` \*Now check openssl version ``` openssl version -a ```
35,569,042
I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects. I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ> After following the exact same code as him, this is the error that I get: ``` Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1240, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1083, in request self._send_request(method, url, body, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1128, in _send_request self.endheaders(body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1079, in endheaders self._send_output(message_body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 911, in _send_output self.send(msg) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 854, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1237, in connect server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 376, in wrap_socket _context=self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 747, in __init__ self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 983, in do_handshake self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 628, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) ``` During handling of the above exception, another exception occurred: ``` Traceback (most recent call last): File "WorldCup.py", line 3, in <module> x = urllib.request.urlopen('https://www.google.com') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 162, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 465, in open response = self._open(req, data) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 483, in _open '_open', req) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 443, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1283, in https_open context=self._context, check_hostname=self._check_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1242, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)> ``` Can someone help me figure out how to fix this?
2016/02/23
[ "https://Stackoverflow.com/questions/35569042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790055/" ]
When you are using a self signed cert urllib3 version 1.25.3 refuses to ignore the SSL cert To fix remove urllib3-1.25.3 and install urllib3-1.24.3 `pip3 uninstall urllib3` `pip3 install urllib3==1.24.3` Tested on Linux MacOS and Window$
I have a lib what use <https://requests.readthedocs.io/en/master/> what use <https://pypi.org/project/certifi/> but I have a custom CA included in my `/etc/ssl/certs`. So I solved my problem like this: ``` # Your TLS certificates directory (Debian like) export SSL_CERT_DIR=/etc/ssl/certs # CA bundle PATH (Debian like again) export CA_BUNDLE_PATH="${SSL_CERT_DIR}/ca-certificates.crt" # If you have a virtualenv: . ./.venv/bin/activate # Get the current certifi CA bundle CERTFI_PATH=`python -c 'import certifi; print(certifi.where())'` test -L $CERTFI_PATH || rm $CERTFI_PATH test -L $CERTFI_PATH || ln -s $CA_BUNDLE_PATH $CERTFI_PATH ``` Et voilà !
35,569,042
I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects. I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ> After following the exact same code as him, this is the error that I get: ``` Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1240, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1083, in request self._send_request(method, url, body, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1128, in _send_request self.endheaders(body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1079, in endheaders self._send_output(message_body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 911, in _send_output self.send(msg) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 854, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1237, in connect server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 376, in wrap_socket _context=self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 747, in __init__ self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 983, in do_handshake self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 628, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) ``` During handling of the above exception, another exception occurred: ``` Traceback (most recent call last): File "WorldCup.py", line 3, in <module> x = urllib.request.urlopen('https://www.google.com') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 162, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 465, in open response = self._open(req, data) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 483, in _open '_open', req) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 443, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1283, in https_open context=self._context, check_hostname=self._check_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1242, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)> ``` Can someone help me figure out how to fix this?
2016/02/23
[ "https://Stackoverflow.com/questions/35569042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790055/" ]
On Debian 9 I had to: ``` $ sudo update-ca-certificates --fresh $ export SSL_CERT_DIR=/etc/ssl/certs ``` I'm not sure why, but this enviroment variable was never set.
As a workaround (not secure), you can turn certificate verification off by setting PYTHONHTTPSVERIFY environment variable to 0: ``` export PYTHONHTTPSVERIFY=0 ```
35,569,042
I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects. I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ> After following the exact same code as him, this is the error that I get: ``` Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1240, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1083, in request self._send_request(method, url, body, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1128, in _send_request self.endheaders(body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1079, in endheaders self._send_output(message_body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 911, in _send_output self.send(msg) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 854, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1237, in connect server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 376, in wrap_socket _context=self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 747, in __init__ self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 983, in do_handshake self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 628, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) ``` During handling of the above exception, another exception occurred: ``` Traceback (most recent call last): File "WorldCup.py", line 3, in <module> x = urllib.request.urlopen('https://www.google.com') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 162, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 465, in open response = self._open(req, data) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 483, in _open '_open', req) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 443, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1283, in https_open context=self._context, check_hostname=self._check_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1242, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)> ``` Can someone help me figure out how to fix this?
2016/02/23
[ "https://Stackoverflow.com/questions/35569042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790055/" ]
On Debian 9 I had to: ``` $ sudo update-ca-certificates --fresh $ export SSL_CERT_DIR=/etc/ssl/certs ``` I'm not sure why, but this enviroment variable was never set.
you might exec command: `pip install --upgrade certifi` or you might opened charles/fiddler, just close it
35,569,042
I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects. I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ> After following the exact same code as him, this is the error that I get: ``` Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1240, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1083, in request self._send_request(method, url, body, headers) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1128, in _send_request self.endheaders(body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1079, in endheaders self._send_output(message_body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 911, in _send_output self.send(msg) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 854, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1237, in connect server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 376, in wrap_socket _context=self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 747, in __init__ self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 983, in do_handshake self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 628, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) ``` During handling of the above exception, another exception occurred: ``` Traceback (most recent call last): File "WorldCup.py", line 3, in <module> x = urllib.request.urlopen('https://www.google.com') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 162, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 465, in open response = self._open(req, data) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 483, in _open '_open', req) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 443, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1283, in https_open context=self._context, check_hostname=self._check_hostname) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1242, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)> ``` Can someone help me figure out how to fix this?
2016/02/23
[ "https://Stackoverflow.com/questions/35569042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790055/" ]
When you are using a self signed cert urllib3 version 1.25.3 refuses to ignore the SSL cert To fix remove urllib3-1.25.3 and install urllib3-1.24.3 `pip3 uninstall urllib3` `pip3 install urllib3==1.24.3` Tested on Linux MacOS and Window$
you might exec command: `pip install --upgrade certifi` or you might opened charles/fiddler, just close it
50,640,716
I am using MACOS 10.12.6 I was trying to uninstall python to reinstall it, and I foolishly typed these commands into my terminals. ``` sudo rm -rf /Users/<myusername>/anaconda2/lib/python2.7 sudo rm -rf /Users/<myusername>/anaconda2/lib/python27.zip sudo rm -rf /Users/<myusername>/anaconda2/lib/python2.7/plat-darwin sudo rm -rf /Users/<myusername>/anaconda2/lib/plat-mac sudo rm -rf /Users/<myusername>/anaconda2/lib/plat-mac/lib-scriptpackages ``` now my Python won't work. I get these errors: ``` >Could not find platform independent libraries <prefix> >Could not find platform dependent libraries <exec_prefix> >Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] ``` And when I try to run python I get things such as ``` >ModuleNotFoundError: No module named 'pandas' ``` I currently cannot do anything which requires python I came to understand much later that what I did was deleting an important part of python files from my computer. Is there any way I can reinstall python or is formatting my computer the only option if I want to use Python on this computer?
2018/06/01
[ "https://Stackoverflow.com/questions/50640716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9880455/" ]
Since you used Anconda on your mac you should be able to just reinstall python 2.7. If you still have the install package: Anaconda2-5.2.0-MacOSX-x86\_64.pkg, just double click that and follow directions. If you don't have this package, download it from [here](https://www.anaconda.com/download/#macos) and when the package downloads completely double-click it.
You only deleted Anaconda, not the System Python. Therefore, you probably only need to edit your PATH variable to remove references to those folders. Check your `~/.bashrc`
62,142,223
I've installed from sources the SimpleITK package on Python3. When I perform the provided registration example : ``` #!/usr/bin/env python #========================================================================= # # Copyright NumFOCUS # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0.txt # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # #========================================================================= from __future__ import print_function import SimpleITK as sitk import sys import os def command_iteration(method) : print("{0:3} = {1:10.5f} : {2}".format(method.GetOptimizerIteration(), method.GetMetricValue(), method.GetOptimizerPosition())) if len ( sys.argv ) < 4: print( "Usage: {0} <fixedImageFilter> <movingImageFile> <outputTransformFile>".format(sys.argv[0])) sys.exit ( 1 ) fixed = sitk.ReadImage(sys.argv[1], sitk.sitkFloat32) moving = sitk.ReadImage(sys.argv[2], sitk.sitkFloat32) R = sitk.ImageRegistrationMethod() R.SetMetricAsMeanSquares() R.SetOptimizerAsRegularStepGradientDescent(4.0, .01, 200 ) R.SetInitialTransform(sitk.TranslationTransform(fixed.GetDimension())) R.SetInterpolator(sitk.sitkLinear) R.AddCommand( sitk.sitkIterationEvent, lambda: command_iteration(R) ) outTx = R.Execute(fixed, moving) print("-------") print(outTx) print("Optimizer stop condition: {0}".format(R.GetOptimizerStopConditionDescription())) print(" Iteration: {0}".format(R.GetOptimizerIteration())) print(" Metric value: {0}".format(R.GetMetricValue())) sitk.WriteTransform(outTx, sys.argv[3]) if ( not "SITK_NOSHOW" in os.environ ): resampler = sitk.ResampleImageFilter() resampler.SetReferenceImage(fixed); resampler.SetInterpolator(sitk.sitkLinear) resampler.SetDefaultPixelValue(100) resampler.SetTransform(outTx) out = resampler.Execute(moving) simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8) simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8) cimg = sitk.Compose(simg1, simg2, simg1//2.+simg2//2.) sitk.Show( cimg, "ImageRegistration1 Composition" ) ``` The execution with `Python ImageRegistrationMethod1.py image_ref.tif image_moving.tif res.tif` seems to work well until it comes to write the `res.tif` image and triggers the following error : ``` TIFFReadDirectory: Warning, Unknown field with tag 50838 (0xc696) encountered. TIFFReadDirectory: Warning, Unknown field with tag 50839 (0xc697) encountered. TIFFReadDirectory: Warning, Unknown field with tag 50838 (0xc696) encountered. TIFFReadDirectory: Warning, Unknown field with tag 50839 (0xc697) encountered. ------- itk::simple::Transform TranslationTransform (0x7fb2a54ec0f0) RTTI typeinfo: itk::TranslationTransform<double, 3u> Reference Count: 2 Modified Time: 2196 Debug: Off Object Name: Observers: none Offset: [14.774, 10.57, 18.0612] Optimizer stop condition: RegularStepGradientDescentOptimizerv4: Step too small after 22 iterations. Current step (0.0078125) is less than minimum step (0.01). Iteration: 23 Metric value: 2631.5128202930223 Traceback (most recent call last): File "ImageRegistrationMethod1.py", line 57, in <module> sitk.WriteTransform(outTx, sys.argv[3]) File "/usr/local/lib/python3.7/site- packages/SimpleITK/SimpleITK.py", line 5298, in WriteTransform return _SimpleITK.WriteTransform(transform, filename) RuntimeError: Exception thrown in SimpleITK WriteTransform: itk::ERROR: TransformFileWriterTemplate(0x7faa4fcfce70): Could not create Transform IO object for writing file /Users/anass/Desktop/res.tif Tried to create one of the following: HDF5TransformIOTemplate HDF5TransformIOTemplate MatlabTransformIOTemplate MatlabTransformIOTemplate TxtTransformIOTemplate TxtTransformIOTemplate You probably failed to set a file suffix, or set the suffix to an unsupported type. ``` I really don't know why I'm getting this error since the code was built from source. Any help please?
2020/06/01
[ "https://Stackoverflow.com/questions/62142223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11107590/" ]
The result of running the ImageRegistrationMethod1 example is a transform. SimpleITK supports a number of file formats for transformations, including a text file (.txt), a Matlab file (.mat) and a HDF5Tranform (.hdf5). That does not include a .tif file, which is an image file, not a transform. You can read more about it on the Transform section of the SimpleITK IO page: <https://simpleitk.readthedocs.io/en/master/IO.html#transformations> In the case of this example, the transform produced is a 3-d translation. So if you've chosen a .txt file output, you can see the X, Y and Z translations on the Parameters line.
if you want to write dicom as file output, please try this one. ``` writer.SetFileName(os.path.join('transformed.dcm')) writer.Execute(cimg) ```
73,277,276
I know how to add a function to a python dict: ``` def burn(theName): return theName + ' is burning' kitchen = {'name': 'The Kitchen', 'burn_it': burn} print(kitchen['burn_it'](kitchen['name'])) ### output: "the Kitchen is burning" ``` but is there any way to reference the dictionary's own 'name' value without having to name the dict itself specifically? To refer to the dictionary as itself? With other languages in mind I was thinking there might be something like ``` print(kitchen['burn_it'](__self__['name'])) ``` or ``` print(kitchen['burn_it'](__this__['name'])) ``` where the function could access the 'name' key of the dictionary it was inside. I have googled quite a bit but I keep finding people who want to do this: ``` kitchen = {'name': 'Kitchen', 'fullname': 'The ' + ['name']} ``` where they're trying to access the dictionary key before they've finished initialising it. TIA
2022/08/08
[ "https://Stackoverflow.com/questions/73277276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1914833/" ]
You can extend `dict` object with your custom class, like this: ```py class MyDict(dict): def __init__(self, *args, **kwargs): self["burn_it"] = self.burn super().__init__(*args, **kwargs) def burn(self): return self["name"] + " is burning" kitchen = MyDict({'name': 'The Kitchen'}) print(kitchen['burn_it']()) # The Kitchen is burning print(kitchen.burn()) # The Kitchen is burning ```
You cannot know which object reference the function. A simple example, image the following: ``` def burn(theName): return theName + ' is burning' kitchen = {'name': 'The Kitchen', 'burn_it': burn} garage = {'name': 'The Garage', 'burn_it': burn} ``` `burn` is referenced both in `kitchen` and `garage`, how could it "know" which dictionary is referencing it? ``` id(kitchen['burn_it']) == id(garage['burn_it']) # True ``` What you can do (if you don't want a custom object) is to use a function: ``` def action(d): return d['burn_it'](d['name']) action(kitchen) # 'The Kitchen is burning' action(garage) # 'The Garage is burning' ``` with a custom object: ``` class CustomDict(dict): def __init__(self, *arg, **kwargs): super().__init__(*arg, **kwargs) def action(self): return self['burn_it'](self['name']) kitchen = CustomDict({'name': 'The Kitchen', 'burn_it': burn}) kitchen.action() # 'The Kitchen is burning' ```
56,693,576
I am trying to access a variable defined inside an if statement in a for loop, outside the for loop. but I am getting the 'Unbounded Local Error' I have tried assigning `lambdaPriceUsWest2 = None` as suggested here: [Python Get variable outside the loop](https://stackoverflow.com/questions/25406399/python-get-variable-outside-the-loop) Also, tried specifying `global lambdaPriceUsWest2` inside if statement with `lambdaPriceUsWest2 = None` before the code snippet. ``` for x in range(len(response['PriceList'])): priceList=json.loads(response['PriceList'][x]) if priceList['product']['sku'] == 'DU9X9ZR8C8DYH3Y9': lambdaPriceUsWest2= priceListpriceList['product']['sku']['USD'] if priceList['product']['sku'] == 'CVE47QZ9RSF8DTEM': lambdaPriceUsEast2= priceListpriceList['product']['sku']['USD'] break logger.debug(lambdaPriceUsWest2) ``` Expected Result: 0.055512 (similar value) Actual Result : Error: ``` "errorMessage": "local variable 'lambdaPriceUsWest2' referenced before assignment", "errorType": "UnboundLocalError" ```
2019/06/20
[ "https://Stackoverflow.com/questions/56693576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6921304/" ]
the best way is before the for loop try to initialize that variable. For example: ``` lambdaPriceUsWest2 = "" ```
just defined a var outside loop and update it value ``` local_val ='' for x in range(len(response['PriceList'])): priceList=json.loads(response['PriceList'][x]) if priceList['product']['sku'] == 'DU9X9ZR8C8DYH3Y9': lambdaPriceUsWest2= priceListpriceList['product']['sku']['USD'] local_val = lambdaPriceUsWest2 if priceList['product']['sku'] == 'CVE47QZ9RSF8DTEM': lambdaPriceUsEast2= priceListpriceList['product']['sku']['USD'] break logger.debug(local_val) ```
56,693,576
I am trying to access a variable defined inside an if statement in a for loop, outside the for loop. but I am getting the 'Unbounded Local Error' I have tried assigning `lambdaPriceUsWest2 = None` as suggested here: [Python Get variable outside the loop](https://stackoverflow.com/questions/25406399/python-get-variable-outside-the-loop) Also, tried specifying `global lambdaPriceUsWest2` inside if statement with `lambdaPriceUsWest2 = None` before the code snippet. ``` for x in range(len(response['PriceList'])): priceList=json.loads(response['PriceList'][x]) if priceList['product']['sku'] == 'DU9X9ZR8C8DYH3Y9': lambdaPriceUsWest2= priceListpriceList['product']['sku']['USD'] if priceList['product']['sku'] == 'CVE47QZ9RSF8DTEM': lambdaPriceUsEast2= priceListpriceList['product']['sku']['USD'] break logger.debug(lambdaPriceUsWest2) ``` Expected Result: 0.055512 (similar value) Actual Result : Error: ``` "errorMessage": "local variable 'lambdaPriceUsWest2' referenced before assignment", "errorType": "UnboundLocalError" ```
2019/06/20
[ "https://Stackoverflow.com/questions/56693576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6921304/" ]
the best way is before the for loop try to initialize that variable. For example: ``` lambdaPriceUsWest2 = "" ```
First of all, declare a variable before assignment (inside the for-loop) using 'global' syntax like this: ``` global lambdaPriceUsEast2 ``` Then assign any value you want for it, for example: ``` lambdaPriceUsEast2 = priceListpriceList['product']['sku']['USD'] ``` It's worth mentioning that if you don't assign it to any value, it's still be undefined outside the loop. Because functions in python are references to objects. To avoid this, you can assign it to None before any conditions:: ``` global lambdaPriceUsEast2 lambdaPriceUsEast2 = None ``` This will do the work. You can also check all global variables using built-in globals() function. But using global statement is still not the best practice. I'd suggest you writing a function and returning the value like this: ``` def get_price(price_list): for x in range(len(price_list)): priceList=json.loads(price_list[x]) if priceList['product']['sku'] == 'DU9X9ZR8C8DYH3Y9': return priceListpriceList['product']['sku']['USD'] if priceList['product']['sku'] == 'CVE47QZ9RSF8DTEM': return priceListpriceList['product']['sku']['USD'] return None ``` value = get\_price(response['PriceList'])
59,125,889
``` npm install expo-cli --global ``` I got this following error: ``` npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! envsub@3.1.0 postinstall: `test -d .git && cp gitHookPrePush.sh .git/hooks/pre-push || true` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the envsub@3.1.0 postinstall script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\User\AppData\Roaming\npm-cache\_logs\2019-12-01T12_11_45_118Z-debug.log ``` node and npm versions: ``` node --version v12.13.1 npm --version 6.12.1 ``` I am trying to install expo-cli on windows 10, according it's official site: > > npm install expo-cli --global > I got this following error: > > > 43056 verbose Windows\_NT 10.0.18362 43057 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node\_modules\npm\bin\npm-cli.js" "install" "expo-cli" "--global" 43058 verbose node v12.13.1 43059 verbose npm v6.12.1 43060 error code ELIFECYCLE 43061 error errno 1 43062 error envsub@3.1.0 postinstall: `test -d .git && cp gitHookPrePush.sh .git/hooks/pre-push || true` 43062 error Exit status 1 43063 error Failed at the envsub@3.1.0 postinstall script. 43063 error This is probably not a problem with npm. There is likely additional logging output above. 43064 verbose exit [ 1, true ] I am using python version: > > python --version > Python 3.8.0 > and node and npm versions: > > > node --version > v12.13.1 > > > npm --version > 6.12.1 > \*\* > What is your suggestion? > > > \*\*
2019/12/01
[ "https://Stackoverflow.com/questions/59125889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5982462/" ]
just try installing `npm install expo-cli --global` this command on git bash. It worked for me.
[I fixed this problem](https://stackoverflow.com/questions/59124830/reactnative-code-elifecycle-error-when-installing-expo-cli/59126514#59126514) : ``` 1- Download and install Git SCM 2- Download Visual Studio Community HERE and install a Custom Installation, selecting ONLY the following packages: VISUAL C++, PYTHON TOOLS FOR VISUAL STUDIO and MICROSOFT WEB DEVELOPER TOOLS 3- Download and install Python 2.7.x 4- Register a Environment Variable with name: GYP_MSVS_VERSION with this value: 2015 ``` After these installations i think this part is important: > > **postinstall** script of **envsub** depends on built-in **unix shell** commands. So any shell compatible with unix shell should works, like **Git BASH** > > > So run `npm install expo-cli --global` after above installation on `Git BASH`
50,751,484
I trained on TensorFlow model on a GPU cluster, saved the model using ``` saver = tf.train.Saver() saver.save(sess, config.model_file, global_step=global_step) ``` and now I am trying to restore the model with ``` saver = tf.train.import_meta_graph('model-1000.meta') saver.restore(sess,tf.train.latest_checkpoint(save_path)) ``` for evaluation, on a different system. The issue is that `saver.restore` yields the following error: ``` Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1664, in <module> main() File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1658, in main globals = debugger.run(setup['file'], None, None, is_module) File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1068, in run pydev_imports.execfile(file, globals, locals) # execute the script File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "/Users/jonpdeaton/Developer/BraTS18-Project/segmentation/evaluate.py", line 205, in <module> main() File "/Users/jonpdeaton/Developer/BraTS18-Project/segmentation/evaluate.py", line 162, in main restore_and_evaluate(save_path, model_file, output_dir) File "/Users/jonpdeaton/Developer/BraTS18-Project/segmentation/evaluate.py", line 127, in restore_and_evaluate saver.restore(sess, tf.train.latest_checkpoint(save_path)) File "/Users/jonpdeaton/anaconda3/envs/BraTS/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 1857, in latest_checkpoint if file_io.get_matching_files(v2_path) or file_io.get_matching_files( File "/Users/jonpdeaton/anaconda3/envs/BraTS/lib/python3.6/site-packages/tensorflow/python/lib/io/file_io.py", line 337, in get_matching_files for single_filename in filename File "/Users/jonpdeaton/anaconda3/envs/BraTS/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 519, in __exit__ c_api.TF_GetCode(self.status.status)) tensorflow.python.framework.errors_impl.NotFoundError: /afs/cs.stanford.edu/u/jdeaton/dfs/unet; No such file or directory ``` It seems as though there are some paths that were stored in the model or `checkpoint` file form the system that it was trained on, that are no longer valid on the system that I am doing evaluation on. How do I restore a model (for evaluation) on a different machine after having copied the `model-X.meta`, `model-X.index` and `checkpoint` files?
2018/06/07
[ "https://Stackoverflow.com/questions/50751484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6263317/" ]
By default, the `Saver` object will write the absolute model checkpoint paths into the `checkpoint` file. So the path returned by `tf.train.latest_checkpoint(save_path)` is the absolute path on your old machine. Temporary solution: 1. Pass the actual model file path directly to the `restore` method rather than the result of `tf.train.latest_checkpoint`. 2. Manually edit the `checkpoint` file, which is a simple text file. Long term solution: ``` saver = tf.train.Saver(save_relative_paths=True) ```
Open up the checkpoint file with your favorite text editor and simply change the absolute paths found therein to just filenames.
25,201,504
I'm trying to minimize function, that returns a vector of values, and here is an error: > > setting an array element with a sequence > > > Code: ``` P = np.matrix([[0.3, 0.1, 0.2], [0.01, 0.4, 0.2], [0.0001, 0.3, 0.5]]) Ps = np.array([10,14,5]) def objective(x): x = np.array([x]) res = np.square(Ps - np.dot(x, P)) return res def main(): x = np.array([10, 11, 15]) print minimize(objective, x, method='Nelder-Mead') ``` At these values of P, Ps, x function returns [[ 47.45143225 16.81 44.89 ]] Thank you for any advice **UPD (full traceback)** ``` Traceback (most recent call last): File "<ipython-input-125-9649a65940b0>", line 1, in <module> runfile('C:/Users/Roark/Documents/Python Scripts/optimize.py', wdir='C:/Users/Roark/Documents/Python Scripts') File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 585, in runfile execfile(filename, namespace) File "C:/Users/Roark/Documents/Python Scripts/optimize.py", line 28, in <module> main() File "C:/Users/Roark/Documents/Python Scripts/optimize.py", line 24, in main print minimize(objective, x, method='Nelder-Mead') File "C:\Anaconda\lib\site-packages\scipy\optimize\_minimize.py", line 413, in minimize return _minimize_neldermead(fun, x0, args, callback, **options) File "C:\Anaconda\lib\site-packages\scipy\optimize\optimize.py", line 438, in _minimize_neldermead fsim[0] = func(x0) ValueError: setting an array element with a sequence. ``` **UPD2: function should be minimized (Ps is a vector)** ![enter image description here](https://i.stack.imgur.com/QlHqk.png)
2014/08/08
[ "https://Stackoverflow.com/questions/25201504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2824962/" ]
Your objective function needs to return a scalar value, not a vector. You probably want to return the *sum* of squared errors rather than the vector of squared errors: ``` def objective(x): res = ((Ps - np.dot(x, P)) ** 2).sum() return res ```
Use [`least_squares`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html). This will require to modify the objective a bit to return differences instead of squared differences: ```py import numpy as np from scipy.optimize import least_squares P = np.matrix([[0.3, 0.1, 0.2], [0.01, 0.4, 0.2], [0.0001, 0.3, 0.5]]) Ps = np.array([10,14,5]) def objective(x): x = np.array([x]) res = Ps - np.dot(x, P) return np.asarray(res).flatten() def main(): x = np.array([10, 11, 15]) print(least_squares(objective, x)) ``` Result: ``` active_mask: array([0., 0., 0.]) cost: 5.458917464129402e-28 fun: array([1.59872116e-14, 2.84217094e-14, 5.32907052e-15]) grad: array([-8.70414856e-15, -1.25943700e-14, -1.11926469e-14]) jac: array([[-3.00000002e-01, -1.00000007e-02, -1.00003682e-04], [-1.00000001e-01, -3.99999999e-01, -3.00000001e-01], [-1.99999998e-01, -1.99999999e-01, -5.00000000e-01]]) message: '`gtol` termination condition is satisfied.' nfev: 4 njev: 4 optimality: 1.2594369966691647e-14 status: 1 success: True x: array([ 31.95419775, 41.56815698, -19.40894189]) ```
25,201,504
I'm trying to minimize function, that returns a vector of values, and here is an error: > > setting an array element with a sequence > > > Code: ``` P = np.matrix([[0.3, 0.1, 0.2], [0.01, 0.4, 0.2], [0.0001, 0.3, 0.5]]) Ps = np.array([10,14,5]) def objective(x): x = np.array([x]) res = np.square(Ps - np.dot(x, P)) return res def main(): x = np.array([10, 11, 15]) print minimize(objective, x, method='Nelder-Mead') ``` At these values of P, Ps, x function returns [[ 47.45143225 16.81 44.89 ]] Thank you for any advice **UPD (full traceback)** ``` Traceback (most recent call last): File "<ipython-input-125-9649a65940b0>", line 1, in <module> runfile('C:/Users/Roark/Documents/Python Scripts/optimize.py', wdir='C:/Users/Roark/Documents/Python Scripts') File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 585, in runfile execfile(filename, namespace) File "C:/Users/Roark/Documents/Python Scripts/optimize.py", line 28, in <module> main() File "C:/Users/Roark/Documents/Python Scripts/optimize.py", line 24, in main print minimize(objective, x, method='Nelder-Mead') File "C:\Anaconda\lib\site-packages\scipy\optimize\_minimize.py", line 413, in minimize return _minimize_neldermead(fun, x0, args, callback, **options) File "C:\Anaconda\lib\site-packages\scipy\optimize\optimize.py", line 438, in _minimize_neldermead fsim[0] = func(x0) ValueError: setting an array element with a sequence. ``` **UPD2: function should be minimized (Ps is a vector)** ![enter image description here](https://i.stack.imgur.com/QlHqk.png)
2014/08/08
[ "https://Stackoverflow.com/questions/25201504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2824962/" ]
If you want you resulting vector to be a vector containing only `0`s, you can use `fsolve` to do so. To do that will require modifying your objective function a little bit to get the input and output into the same shape: ``` import scipy.optimize as so P = np.matrix([[0.3, 0.1, 0.2], [0.01, 0.4, 0.2], [0.0001, 0.3, 0.5]]) Ps = np.array([10,14,5]) def objective(x): x = np.array([x]) res = np.square(Ps - np.dot(x, P)) return np.array(res).ravel() Root = so.fsolve(objective, x0=np.array([10, 11, 15])) objective(Root) #[ 5.04870979e-29 1.13595970e-28 1.26217745e-29] ``` Result: The solution is `np.array([ 31.95419775, 41.56815698, -19.40894189])`
Use [`least_squares`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html). This will require to modify the objective a bit to return differences instead of squared differences: ```py import numpy as np from scipy.optimize import least_squares P = np.matrix([[0.3, 0.1, 0.2], [0.01, 0.4, 0.2], [0.0001, 0.3, 0.5]]) Ps = np.array([10,14,5]) def objective(x): x = np.array([x]) res = Ps - np.dot(x, P) return np.asarray(res).flatten() def main(): x = np.array([10, 11, 15]) print(least_squares(objective, x)) ``` Result: ``` active_mask: array([0., 0., 0.]) cost: 5.458917464129402e-28 fun: array([1.59872116e-14, 2.84217094e-14, 5.32907052e-15]) grad: array([-8.70414856e-15, -1.25943700e-14, -1.11926469e-14]) jac: array([[-3.00000002e-01, -1.00000007e-02, -1.00003682e-04], [-1.00000001e-01, -3.99999999e-01, -3.00000001e-01], [-1.99999998e-01, -1.99999999e-01, -5.00000000e-01]]) message: '`gtol` termination condition is satisfied.' nfev: 4 njev: 4 optimality: 1.2594369966691647e-14 status: 1 success: True x: array([ 31.95419775, 41.56815698, -19.40894189]) ```
31,580,319
I use ansible module `fetch` to download a large file, said 2GB. Then I got the following error message. Ansible seems to be unable to deal with large file. ``` fatal: [x.x.x.x] => failed to parse: SUDO-SUCCESS-ucnhswvujwylacnodwyyictqtmrpabxp Traceback (most recent call last): File "/home/xxx/.ansible/tmp/ansible-tmp-1437624638.74-184884633599028/slurp", line 1167, in <module> main() File "/home/xxx/.ansible/tmp/ansible-tmp-1437624638.74-184884633599028/slurp", line 67, in main data = base64.b64encode(file(source).read()) File "/usr/lib/python2.7/base64.py", line 53, in b64encode encoded = binascii.b2a_base64(s)[:-1] MemoryError ```
2015/07/23
[ "https://Stackoverflow.com/questions/31580319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2605599/" ]
<https://github.com/ansible/ansible/issues/11702> This is an Ansible bug which have been solved in newer version.
Looks like the remote server you're trying to fetch from is running out of memory during the base64 encoding process. Perhaps try the synchronize module instead (which will use rsync); fetch isn't really designed to work with large files.
31,580,319
I use ansible module `fetch` to download a large file, said 2GB. Then I got the following error message. Ansible seems to be unable to deal with large file. ``` fatal: [x.x.x.x] => failed to parse: SUDO-SUCCESS-ucnhswvujwylacnodwyyictqtmrpabxp Traceback (most recent call last): File "/home/xxx/.ansible/tmp/ansible-tmp-1437624638.74-184884633599028/slurp", line 1167, in <module> main() File "/home/xxx/.ansible/tmp/ansible-tmp-1437624638.74-184884633599028/slurp", line 67, in main data = base64.b64encode(file(source).read()) File "/usr/lib/python2.7/base64.py", line 53, in b64encode encoded = binascii.b2a_base64(s)[:-1] MemoryError ```
2015/07/23
[ "https://Stackoverflow.com/questions/31580319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2605599/" ]
Looks like the remote server you're trying to fetch from is running out of memory during the base64 encoding process. Perhaps try the synchronize module instead (which will use rsync); fetch isn't really designed to work with large files.
Had the same issue with a Digital Ocean droplet (1 Gb RAM). Fixed it by increasing the swap size. Here is the ansible task to fetch the data ``` - name: Fetch data from remote fetch: src: "{{ app_dir }}/data.zip" dest: "{{ playbook_dir }}/../data/data.zip" flat: yes become: no tags: - download ``` Used [this playbook](https://stackoverflow.com/a/33071279/2248627) to do the swap increase with ansible
31,580,319
I use ansible module `fetch` to download a large file, said 2GB. Then I got the following error message. Ansible seems to be unable to deal with large file. ``` fatal: [x.x.x.x] => failed to parse: SUDO-SUCCESS-ucnhswvujwylacnodwyyictqtmrpabxp Traceback (most recent call last): File "/home/xxx/.ansible/tmp/ansible-tmp-1437624638.74-184884633599028/slurp", line 1167, in <module> main() File "/home/xxx/.ansible/tmp/ansible-tmp-1437624638.74-184884633599028/slurp", line 67, in main data = base64.b64encode(file(source).read()) File "/usr/lib/python2.7/base64.py", line 53, in b64encode encoded = binascii.b2a_base64(s)[:-1] MemoryError ```
2015/07/23
[ "https://Stackoverflow.com/questions/31580319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2605599/" ]
<https://github.com/ansible/ansible/issues/11702> This is an Ansible bug which have been solved in newer version.
Had the same issue with a Digital Ocean droplet (1 Gb RAM). Fixed it by increasing the swap size. Here is the ansible task to fetch the data ``` - name: Fetch data from remote fetch: src: "{{ app_dir }}/data.zip" dest: "{{ playbook_dir }}/../data/data.zip" flat: yes become: no tags: - download ``` Used [this playbook](https://stackoverflow.com/a/33071279/2248627) to do the swap increase with ansible
15,811,082
I am developing some python packages and I do want to perform proper testing before releasing them to PyPi. This would require running the unittests across * different python versions: 2.5, 2.6, 2.7, 3.2 * different operating systems: OS X, Debian, Ubuntu and Windows Right now I am using pytest Question: how can I implement this easily and preferably making the results publicly available and having integrated with github, so anyone who pushes will know the results. Note: I am already aware about <https://travis-ci.org/> but this seems to be missing the cross-platform part, which is essential in this case. Another option I was considering was to use Jenkins, but I don't know how to provide the matrix testing on it.
2013/04/04
[ "https://Stackoverflow.com/questions/15811082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/99834/" ]
I have used Jenkins, and I would recommend it. It has a plethora of plugins, and is very configurable. I have used it for running projects over windows/linux/mac/mobile platforms, for sanity, unit, component, and regression tests. It can support chaining of projects and tests, fingerprinting of items to be monitored as they progress your testing environment and also you can set up users and keep track of changes. You can use it for production and for testing at the same time, hooking it up to your git repository, any change you make is automatically run through all the gauntlets you want.
You can use [`tox`](http://codespeak.net/tox/index.html) to automate setting up virtual environments and running your tests across Python versions: ``` [tox] envlist = py25,py26,py27,py32 [testenv] commands=py.test ``` Tox supports Python versions 2.4 and up, as well as Jython and PyPy. If you want to look at a real-world project that uses `tox`, take a look at the [`zope.configuration` `tox.ini` configuration](https://github.com/zopefoundation/zope.configuration/blob/master/tox.ini). The package includes excellent [documentation on how to run the `tox` tests](http://docs.zope.org/zope.configuration/hacking.html#running-tests-on-multiple-python-versions-via-tox). These tests are automatically run by the [Zope nightly test builders](http://docs.zope.org/zopetoolkit/process/buildbots.html#the-nightly-builds). Configuring tox to [run under Jenkins](http://tox.readthedocs.org/en/latest/example/jenkins.html) is trivial and fully documented.
51,919,720
I've been unable to use Pyenv to install Python on macOS (10.13.6) and have exhausted advice about common build problems. pyenv-doctor reports: **OpenSSL development header is not installed.** Reinstallation of OpenSSL, as suggested in various related GitHub issues has not worked, not have various flag settings, eg (in various combinations): ``` export CFLAGS="-I$(brew --prefix openssl)/include" export CPPFLAGS="-I$(brew --prefix openssl)/include" export LDFLAGS="-L$(brew --prefix openssl)/lib" export PKG_CONFIG_PATH="/usr/local/opt/openssl/lib/pkgconfig/" export PATH="/usr/local/opt/openssl@1.1/bin:$PATH" ``` (Tried these in command line put as well.) (Tried both OpenSSL 1.02p and 1.1, via Homebrew) Tried ``` brew install readline xz ``` and ``` $ CFLAGS="-I$(xcrun --show-sdk-path)/usr/include" pyenv install 3.6.6 ``` and ``` $ CFLAGS="-I$(brew --prefix openssl)/include -I$(xcrun --show-sdk-path)/usr/include" LDFLAGS="-L$(brew --prefix openssl)/lib" pyenv install 3.6.6 ``` and ``` xcode-select --install (or via downloadable command line tools installer for reinstallation) ``` No luck. ``` brew link --force openssl ``` is disallowed (error message says to use flags). Also tried: ``` $(brew --prefix)/opt/openssl/bin/openssl ``` and tried the OpenSSL/macOS advice here: ``` https://solitum.net/openssl-os-x-el-capitan-and-brew/ ``` $PATH shows: ``` /usr/local/opt/openssl/bin:/Users/tc/google-cloud-sdk/bin:/Users/tc/Code/git/flutter/bin:/usr/local/sbin:/usr/local/heroku/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/Users/tc/google-cloud-sdk/bin:/Users/tc/Code/git/flutter/bin:/usr/local/sbin:/usr/local/heroku/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/Users/tc/google-cloud-sdk/bin:/Users/tc/.nvm/versions/node/v8.11.3/bin:/Users/tomclaburn/Code/git/flutter/bin:/usr/local/sbin:/usr/local/heroku/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/Applications/Postgres.app/Contents/Versions/latest/bin:/usr/local/mongodb/bin:/usr/local/opt/openssl/bin/openssl:/usr/local/mongodb/bin:/usr/local/mongodb/bin ``` and .bash\_profile contains: ``` if [ -d "${PYENV_ROOT}" ]; then export PATH="${PYENV_ROOT}/bin:${PATH}" eval "$(pyenv init -)" #eval "$(pyenv virtualenv-init -)" fi ``` I suspect there's a missing/incorrect path or link but I've been unable to determine what it might be. Any advice would be welcome. Pyenv error output: BUILD FAILED (OS X 10.13.6 using python-build 20180424) ... Last 10 log lines: ``` checking size of long... 0 checking size of long long... 0 checking size of void *... 0 checking size of short... 0 checking size of float... 0 checking size of double... 0 checking size of fpos_t... 0 checking size of size_t... configure: error: in `/var/folders/jb/h01vxbqs6z93h_238q61d48h0000gn/T/python-build.20180819081705.3009/Python-3.6.6': configure: error: cannot compute sizeof (size_t) ``` pyenv-doctor error output: ``` checking for gcc... clang checking whether the C compiler works... yes checking for C compiler default output file name... a.out checking for suffix of executables... checking whether we are cross compiling... no checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether clang accepts -g... yes checking for clang option to accept ISO C89... none needed checking for rl_gnu_readline_p in -lreadline... yes checking for readline/readline.h... no checking for SSL_library_init in -lssl... yes checking how to run the C preprocessor... clang -E checking for grep that handles long lines and -e... /usr/bin/grep checking for egrep... /usr/bin/grep -E checking for ANSI C header files... no checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... no checking for string.h... no checking for memory.h... no checking for strings.h... no checking for inttypes.h... no checking for stdint.h... no checking for unistd.h... yes checking openssl/ssl.h usability... no checking openssl/ssl.h presence... no checking for openssl/ssl.h... no configure: error: OpenSSL development header is not installed. ```
2018/08/19
[ "https://Stackoverflow.com/questions/51919720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7322742/" ]
If this is the same issue as me, it's because there's headers in your path that shouldn't be there. Run `brew doctor` and you would see it complain. To fix it you can do: ``` mkdir /tmp/includes brew doctor 2>&1 | grep "/usr/local/include" | awk '{$1=$1;print}' | xargs -I _ mv _ /tmp/includes ```
After applying Kit's answer; I had to do the following to overcome the fact that I also installed `openssl` with homebrew: ``` CFLAGS="-I$(brew --prefix openssl)/include" \ LDFLAGS="-L$(brew --prefix openssl)/lib" \ pyenv doctor ``` That got me working. Also found this [reference](https://github.com/pyenv/pyenv/wiki/Common-build-problems) useful for common build problems.
46,492,510
I'm new to python, I'm trying to create a list of lists from a text file. The task seems easy to do but I don't know why it's not working with my code. I have the following lines in my text file: ``` word1,word2,word3,word4 word2,word3,word1 word4,word5,word6 ``` I want to get the following output: ``` [['word1','word2','word3','word4'],['word2','word3','word1'],['word4','word5','word6']] ``` The following is the code I tried: ``` mylist =[] list =[] with open("file.txt") as f: for line in f: mylist = line.strip().split(',') list.append(mylist) ```
2017/09/29
[ "https://Stackoverflow.com/questions/46492510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4699562/" ]
You can iterate like this: ``` f = [i.strip('\n').split(',') for i in open('file.txt')] ```
Your code works fine, if your code creating issues in your system then if you want you can do this in one line with this : ``` with open("file.txt") as f: print([i.strip().split(',') for i in f]) ```
61,327,413
I have a client python and a server python and the commands which work perfectly. Now I want to build the interface which needs a variable(string) from the server file and I encountered a problem. **my client.py file** ``` import socket s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((socket.gethostname(),1234)) s.send(bytes("command1","utf-8")) ``` **my server.py file:** ``` import socket while (1): s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((socket.gethostname(),1234)) s.listen(5) clientsocket, address=s.accept() msg=clientsocket.recv(1024) message=msg.decode("utf-8") # I need to pass this to the other file print(message) ``` **the file in which I need to import the message string from the server.py file:** ``` from tkinter import * from server import message def function(): #do some stuff Menu_Win = Tk() photo = PhotoImage(file=r"path_to_local_file.png") Background_Main = Canvas(Menu_Win, width=1980, height=1080, bg="white") Background_Main.pack() Background_Main.create_image(0,80, image=photo, anchor='nw') if message=="command1": #this would be the variable from the server file function() Menu_Win.mainloop() I tried to use **from server import message** but it gives me this error **OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted** and I found out that it gives me this error only when I am continuously running the server.py file and I thinking that the second files when imports, it imports the socket too. UPDATE1: deleted UPDATE2: deleted UPDATE3: I have found myself a solution, by using threading library and running the echoing server on a thread and the rest of the code (GUI) on another. import socket from tkinter import* import threading message="dummy variable" def test_button(): print(message) root=Tk() Canvas(root, width=300, height=100).pack() Button(root,text=("Server"), command=test_button).pack() def get_command(): while 1: global message s=socket.socket() s.bind((socket.gethostname(),1234)) s.listen(5) clientsocket, address=s.accept() msg=clientsocket.recv(1024) message=msg.decode("utf-8") t = threading.Thread(target=get_command) t.start() def my_mainloop(): #to actually see if the command is updated in real time print(message) root.after(1000, my_mainloop) root.after(1000, my_mainloop) root.mainloop() ``` Thank you for all the support :)
2020/04/20
[ "https://Stackoverflow.com/questions/61327413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12305440/" ]
Here's your exact same code using a file system object instead to do the folder work inside the loop. I didn't test it, but it illustrates what I am talking about in my comment above. You should be able to get it working using this: ``` Sub Unzip() Dim oApplicationlication As Object Dim MyFolder As String Dim MyFile As String Dim ZipFile As Variant Dim ExtractTo As Variant ' create the fso Dim fso as Object Set fso = CreateObject("Scripting.FileSystemObject") Application.ScreenUpdating = False 'Cell B2 is the folder path which contains all zip file MyFolder = Range("B2") MyFile = Dir(MyFolder & "\*.zip") ZipFile = Range("C2") ExtractTo = Range("B3") Do While MyFile <> "" 'Cell C2 is updated with a zip file name via loop function Range("C2") = MyFolder & "\" & MyFile ' use the fso to check for and create the folder ' this way you dont have to use the DIR function again, which was messing things up If Not fso.FolderExists(Range("B3")) Then fso.CreateFolder(Range("B3")) End If Set oApplication = CreateObject("Shell.Application") oApplication.Namespace(ExtractTo).CopyHere oApplication.Namespace(ZipFile).Items DoEvents MyFile = Dir Loop Application.ScreenUpdating = True End Sub ``` You may also benefit (speed-wise, depending on how many zip files there are) from moving this line outside of the loop and put it at the top where the fso object is created. ``` Set oApplication = CreateObject("Shell.Application") ```
Your code is failing because you are using `Dir` within the loop to check the existence of the folder to extract to. Instead, move that piece of code to outside the loop: ``` Sub Unzip() Dim oApplication As Object Dim MyFolder As String Dim MyFile As String Dim ExtractTo As Variant Application.ScreenUpdating = False 'Cell B2 is the folder path which contains all zip file If Len(Dir(Range("B3"), vbDirectory)) = 0 Then MkDir Range("B3") End If MyFolder = Range("B2") If Right(MyFolder, 1) <> "\" Then MyFolder = MyFolder & "\" MyFile = Dir(MyFolder, vbNormal) ExtractTo = Range("B3") Do While MyFile <> "" 'Cell C2 is updated with a zip file name via loop function If Right(MyFile, 3) = "zip" Then Range("C2") = MyFolder & MyFile Set oApplication = CreateObject("Shell.Application") oApplication.Namespace(ExtractTo).CopyHere oApplication.Namespace(MyFolder & MyFile).Items DoEvents End If MyFile = Dir Loop Application.ScreenUpdating = True End Sub ``` Regards,
29,859,173
I am following the example to deploy sample python application to bluemix [BLUEMIX-PYTHON-FLASK-SAMPLE](https://github.com/IBM-Bluemix/bluemix-python-flask-sample) Created project successfully Cloned repository successfully Configured pipeline successfully Deploy to BLUEMIX failed. I checked the error in deployment log, seem to complain about `memory limit exceeded, Server error, status code:400, error code 100005`. How do I add the statement in the sample app to output the memory requirement so that I will know how much it is needed? Thanks in advance for any help.
2015/04/24
[ "https://Stackoverflow.com/questions/29859173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2639529/" ]
The memory limit is controlled by the memory value in the manifest.yml file in the root of the project. You don't need to have this manifest.yml file present as Bluemix will define defaults for you. In this case the memory allocation would be 1GB as this is the default which is really to much for a sample app like this. I have just committed a change to the github project [bluemix-python-flask-sample](https://github.com/IBM-Bluemix/bluemix-python-flask-sample) which adds the [manifest.yml](https://github.com/IBM-Bluemix/bluemix-python-flask-sample/blob/master/manifest.yml) file with a memory value of 128M. You should pull the new changes or just use the 'Deploy to Bluemix' button either on the github page or here: [![Deploy to Bluemix](https://bluemix.net/deploy/button.png)](https://bluemix.net/deploy?repository=https://github.com/IBM-Bluemix/bluemix-python-flask-sample)
You probably have exceeded the max app limit on your Bluemix account. Login to your Bluemix account and check if all the app memory limit is utilized. If you have reached your limit then you might have to remove one or more of the apps which you are not using based on how much memory space is needed. in the python-flask-sample example guide, it is mentioned. `cf push your-app-name -m 128M` You can also lower the memory for your app by running the following. `cf scale your-app-name -m 128M` So 128 M will be allocated to this app while deploying on Bluemix, so ideally freeing 128 M should be good enough to get rid of the error you are seeing. This memory limit can be changed as needed. Additionally, this limit is only during the free trial phase. Once you enter your credit card there is no limit.
29,859,173
I am following the example to deploy sample python application to bluemix [BLUEMIX-PYTHON-FLASK-SAMPLE](https://github.com/IBM-Bluemix/bluemix-python-flask-sample) Created project successfully Cloned repository successfully Configured pipeline successfully Deploy to BLUEMIX failed. I checked the error in deployment log, seem to complain about `memory limit exceeded, Server error, status code:400, error code 100005`. How do I add the statement in the sample app to output the memory requirement so that I will know how much it is needed? Thanks in advance for any help.
2015/04/24
[ "https://Stackoverflow.com/questions/29859173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2639529/" ]
The memory limit is controlled by the memory value in the manifest.yml file in the root of the project. You don't need to have this manifest.yml file present as Bluemix will define defaults for you. In this case the memory allocation would be 1GB as this is the default which is really to much for a sample app like this. I have just committed a change to the github project [bluemix-python-flask-sample](https://github.com/IBM-Bluemix/bluemix-python-flask-sample) which adds the [manifest.yml](https://github.com/IBM-Bluemix/bluemix-python-flask-sample/blob/master/manifest.yml) file with a memory value of 128M. You should pull the new changes or just use the 'Deploy to Bluemix' button either on the github page or here: [![Deploy to Bluemix](https://bluemix.net/deploy/button.png)](https://bluemix.net/deploy?repository=https://github.com/IBM-Bluemix/bluemix-python-flask-sample)
This issue is mostly due to insufficient memory available, which you can verify using your bluemix dashboard. On the dashboard the first widget represents how much memory you have available and how much you are using, if deploying an app would go over this limit then you will not be able to do so. For More [details](https://developer.ibm.com/answers/questions/24373/error-deploying-the-sample-application-exceeded-organizations-memory-limit.html).
18,950,409
I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration. For example: ``` #!/usr/bin/python doubleDict = dict() doubleDict['one'] = dict() doubleDict['one']['type'] = 'animal' doubleDict['one']['name'] = 'joe' doubleDict['one']['species'] = 'monkey' doubleDict['two'] = dict() doubleDict['two']['type'] = 'plant' doubleDict['two']['name'] = 'moe' doubleDict['two']['species'] = 'oak' for thing in doubleDict: print thing print thing['type'] print thing['name'] print thing['species'] ``` My desired output: ``` {'type': 'plant', 'name': 'moe', 'species': 'oak'} plant moe oak ``` My actual output: ``` two Traceback (most recent call last): File "./test.py", line 16, in <module> print thing['type'] TypeError: string indices must be integers, not str ``` What am I missing? PS I'm aware I can do a `for k,v in doubleDict`, but I'm *really* trying to avoid having to do a long `if k == 'type': ... elif k == 'name': ...` statement. I'm looking to be able to call `thing['type']` directly.
2013/09/23
[ "https://Stackoverflow.com/questions/18950409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174102/" ]
For-loops in `dict`s iterates over the keys and not over the values. To iterate over the values do: ``` for thing in doubleDict.itervalues(): print thing print thing['type'] print thing['name'] print thing['species'] ``` I used your exact same code, but added the `.itervalues()` at the end which means: "I want to iterate over the values".
When you iterate through a dictionary, you iterate through it's keys and not its values. To get nested values, you have to do: ``` for thing in doubleDict: print doubleDict[thing] print doubleDict[thing]['type'] print doubleDict[thing]['name'] print doubleDict[thing]['species'] ```
18,950,409
I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration. For example: ``` #!/usr/bin/python doubleDict = dict() doubleDict['one'] = dict() doubleDict['one']['type'] = 'animal' doubleDict['one']['name'] = 'joe' doubleDict['one']['species'] = 'monkey' doubleDict['two'] = dict() doubleDict['two']['type'] = 'plant' doubleDict['two']['name'] = 'moe' doubleDict['two']['species'] = 'oak' for thing in doubleDict: print thing print thing['type'] print thing['name'] print thing['species'] ``` My desired output: ``` {'type': 'plant', 'name': 'moe', 'species': 'oak'} plant moe oak ``` My actual output: ``` two Traceback (most recent call last): File "./test.py", line 16, in <module> print thing['type'] TypeError: string indices must be integers, not str ``` What am I missing? PS I'm aware I can do a `for k,v in doubleDict`, but I'm *really* trying to avoid having to do a long `if k == 'type': ... elif k == 'name': ...` statement. I'm looking to be able to call `thing['type']` directly.
2013/09/23
[ "https://Stackoverflow.com/questions/18950409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174102/" ]
When you iterate through a dictionary, you iterate through it's keys and not its values. To get nested values, you have to do: ``` for thing in doubleDict: print doubleDict[thing] print doubleDict[thing]['type'] print doubleDict[thing]['name'] print doubleDict[thing]['species'] ```
You could use @Haidro's answer but make it more generic with a double loop: ``` for key1 in doubleDict: print(doubleDict[key1]) for key2 in doubleDict[key1]: print(doubleDict[key1][key2]) {'type': 'plant', 'name': 'moe', 'species': 'oak'} plant moe oak {'type': 'animal', 'name': 'joe', 'species': 'monkey'} animal joe monkey ```
18,950,409
I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration. For example: ``` #!/usr/bin/python doubleDict = dict() doubleDict['one'] = dict() doubleDict['one']['type'] = 'animal' doubleDict['one']['name'] = 'joe' doubleDict['one']['species'] = 'monkey' doubleDict['two'] = dict() doubleDict['two']['type'] = 'plant' doubleDict['two']['name'] = 'moe' doubleDict['two']['species'] = 'oak' for thing in doubleDict: print thing print thing['type'] print thing['name'] print thing['species'] ``` My desired output: ``` {'type': 'plant', 'name': 'moe', 'species': 'oak'} plant moe oak ``` My actual output: ``` two Traceback (most recent call last): File "./test.py", line 16, in <module> print thing['type'] TypeError: string indices must be integers, not str ``` What am I missing? PS I'm aware I can do a `for k,v in doubleDict`, but I'm *really* trying to avoid having to do a long `if k == 'type': ... elif k == 'name': ...` statement. I'm looking to be able to call `thing['type']` directly.
2013/09/23
[ "https://Stackoverflow.com/questions/18950409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174102/" ]
When you iterate through a dictionary, you iterate through it's keys and not its values. To get nested values, you have to do: ``` for thing in doubleDict: print doubleDict[thing] print doubleDict[thing]['type'] print doubleDict[thing]['name'] print doubleDict[thing]['species'] ```
these all work... but looking at your code, why not use a named tuple instead? from collections import namedtuple LivingThing = namedtuple('LivingThing', 'type name species') doubledict['one'] = LivingThing(type='animal', name='joe', species='monkey') doubledict['one'].name doubledict['one'].\_asdict['name']
18,950,409
I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration. For example: ``` #!/usr/bin/python doubleDict = dict() doubleDict['one'] = dict() doubleDict['one']['type'] = 'animal' doubleDict['one']['name'] = 'joe' doubleDict['one']['species'] = 'monkey' doubleDict['two'] = dict() doubleDict['two']['type'] = 'plant' doubleDict['two']['name'] = 'moe' doubleDict['two']['species'] = 'oak' for thing in doubleDict: print thing print thing['type'] print thing['name'] print thing['species'] ``` My desired output: ``` {'type': 'plant', 'name': 'moe', 'species': 'oak'} plant moe oak ``` My actual output: ``` two Traceback (most recent call last): File "./test.py", line 16, in <module> print thing['type'] TypeError: string indices must be integers, not str ``` What am I missing? PS I'm aware I can do a `for k,v in doubleDict`, but I'm *really* trying to avoid having to do a long `if k == 'type': ... elif k == 'name': ...` statement. I'm looking to be able to call `thing['type']` directly.
2013/09/23
[ "https://Stackoverflow.com/questions/18950409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174102/" ]
For-loops in `dict`s iterates over the keys and not over the values. To iterate over the values do: ``` for thing in doubleDict.itervalues(): print thing print thing['type'] print thing['name'] print thing['species'] ``` I used your exact same code, but added the `.itervalues()` at the end which means: "I want to iterate over the values".
A generic way to get to the nested results: ``` for thing in doubleDict.values(): print(thing) for vals in thing.values(): print(vals) ``` or ``` for thing in doubleDict.values(): print(thing) print('\n'.join(thing.values())) ```
18,950,409
I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration. For example: ``` #!/usr/bin/python doubleDict = dict() doubleDict['one'] = dict() doubleDict['one']['type'] = 'animal' doubleDict['one']['name'] = 'joe' doubleDict['one']['species'] = 'monkey' doubleDict['two'] = dict() doubleDict['two']['type'] = 'plant' doubleDict['two']['name'] = 'moe' doubleDict['two']['species'] = 'oak' for thing in doubleDict: print thing print thing['type'] print thing['name'] print thing['species'] ``` My desired output: ``` {'type': 'plant', 'name': 'moe', 'species': 'oak'} plant moe oak ``` My actual output: ``` two Traceback (most recent call last): File "./test.py", line 16, in <module> print thing['type'] TypeError: string indices must be integers, not str ``` What am I missing? PS I'm aware I can do a `for k,v in doubleDict`, but I'm *really* trying to avoid having to do a long `if k == 'type': ... elif k == 'name': ...` statement. I'm looking to be able to call `thing['type']` directly.
2013/09/23
[ "https://Stackoverflow.com/questions/18950409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174102/" ]
For-loops in `dict`s iterates over the keys and not over the values. To iterate over the values do: ``` for thing in doubleDict.itervalues(): print thing print thing['type'] print thing['name'] print thing['species'] ``` I used your exact same code, but added the `.itervalues()` at the end which means: "I want to iterate over the values".
You could use @Haidro's answer but make it more generic with a double loop: ``` for key1 in doubleDict: print(doubleDict[key1]) for key2 in doubleDict[key1]: print(doubleDict[key1][key2]) {'type': 'plant', 'name': 'moe', 'species': 'oak'} plant moe oak {'type': 'animal', 'name': 'joe', 'species': 'monkey'} animal joe monkey ```