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
59,433,681
I have the following data in terms of dataframe ``` data = pd.DataFrame({'colA': ['a', 'c', 'a', 'e', 'c', 'c'], 'colB': ['b', 'd', 'b', 'f', 'd', 'd'], 'colC':['SD100', 'SD200', 'SD300', 'SD400', 'SD500', 'SD600']}) ``` I want the output as attached [enter image description here][2] I want to achieve this using pandas dataframe in python Can somebody help me?
2019/12/21
[ "https://Stackoverflow.com/questions/59433681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12054665/" ]
I don't know why you want to make multindex, but you can simply `sort_values` or use `groupby`. ```py import pandas as pd df = pd.DataFrame({"ColumnA":['a','c','a','e','c','c'], "ColumnB":['b','d','b','f','d','d'], "ColumnC":['SD100','SD200','SD300','SD400','SD500','SD600']}) print(df) ``` ``` ColumnA ColumnB ColumnC 0 a b SD100 1 c d SD200 2 a b SD300 3 e f SD400 4 c d SD500 5 c d SD600 ``` ```py df = df.sort_values(by=['ColumnA','ColumnB']) df.set_index(['ColumnA', 'ColumnB','ColumnC'], inplace=True) df ```
This will update your data into what you wished `data=data.groupby(['colA','colB']).agg(list)`
10,308,639
I want to install the newest version of `numpy` (a numerical library for Python), and the version (v1.6.1) is not yet in the [Ubuntu Oneiric repositories](https://launchpad.net/ubuntu/oneiric/+source/python-numpy). When I went ahead to manually install it, I read in the [INSTALL](https://github.com/numpy/numpy/blob/master/INSTALL.txt) file that `numpy` needs to be built with the same compiler that built `LAPACK` (a fortran lib used by `numpy`). Unfortunately, I don't know which compiler that is. I didn't install `LAPACK` myself - `apt-get` did, back when I installed an older `numpy` (v1.5.1) using `apt`. If I had to guess, I'd say `gfortran`, but I'd rather not mess this up. How do I figure out which compiler built my current installation of `LAPACK`? Is there any easy way - perhaps running some fortran code that uses it and examining the output? Thanks!
2012/04/25
[ "https://Stackoverflow.com/questions/10308639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781938/" ]
From the same `INSTALL` file you referenced... ``` How to check the ABI of blas/lapack/atlas ----------------------------------------- One relatively simple and reliable way to check for the compiler used to build a library is to use ldd on the library. If libg2c.so is a dependency, this means that g77 has been used. If libgfortran.so is a a dependency, gfortran has been used. If both are dependencies, this means both have been used, which is almost always a very bad idea. ``` If I had to guess, I would probably guess gfortran also as the only two free fortran compilers that I know of are g77 and gfortran and g77 development is pretty much dead as far as I know ... Another thing to check is g77 (by default) appended two underscores to symbols whereas gfortran (by default) only appends one. This is probably the thing that is most important for numpy to know ... although there may be other subtle differences (if numpy is doing some dirty hacking to get at information stored in a common block for instance).
I know of no easy way, though you may find `readelf -a /usr/lib/$SHARED_OBJECT` illuminating, where `$SHARED_OBJECT` is something like `/usr/lib/atlas-base/liblapack_atlas.so.3gf.0` (you'll have to look in your `/usr/lib` to see what your exact filename is). However, there is another, quite different way to get information, since you are using Ubuntu, a flavor of Debian. 1. Find out which to binary package $BINARY\_PKG your Lapack shared object belongs by `dpkg -l | grep -E '(lapack|atlas)` and/or `dpkg -S $SHARED_OBJECT`. 2. Find out from which source package $SOURCE\_PKG the binary package $BINARY\_PKG was built by `dpkg -s $BINARY_PACKAGE`. In the output, look for the `Source:` line. 3. Change into some temporary working directory. 4. Issue `apt-get source $SOURCE_PKG`. (Alternately, `apt-get source $BINARY_PKG` has the same effect.) 5. Issue `ls` and notice the Lapack source directory. 6. Change into the Lapack source directory. 7. Examine the file `debian/control`, paying special attention to the relevant `Build-Depends:` line. This will tell what was necessary to build the package. 8. Issue `dpkg -s build-essential`, which will give you additional information about compilers available to build every package in your distribution (you may have to install the `build-essential` package, first). All this is of course a lot of work, and none of it is in the nature of a simple formula that just gives you the answer you seek; but it does give you places to look for the answer. Good luck.
69,102,556
I'm having troubles with grouping my list so let's say I have this: ``` data = [ {'records-0': '1'}, {'records-0-item1': '2'}, {'records-0-item2': '3'},{'records-0-item3': '4'}, {'records-1': '1'}, {'records-1-item1': '2'}, {'records-1-item2': '3'}, ] ``` What I'm trying to have is my list sorted based on the index that is in my key (if that makes any sense). So my expected outpout would be kinda like this. ``` sortedData = [ {0: [{'records-0': '1'}, {'records-0-item1': '2'}, {'records-0-item2': '3'},{'records-0-item3': '4'},]}, {1: [{'records-1': '1'}, {'records-1-item1': '2'}, {'records-1-item2': '3'},] ] ``` I've tried looking up for grouping lists, but that all is based on one specific key. like this <https://www.geeksforgeeks.org/group-list-of-dictionary-data-by-particular-key-in-python/> Any ideas? **EDIT**: The data in the list is based on user input, so there could also be a: ``` {'records-2': '1'}, {'records-3': '1'}, {'records-4': '1'}, etc ```
2021/09/08
[ "https://Stackoverflow.com/questions/69102556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11868566/" ]
One way is to use [default\_dict](https://docs.python.org/3/library/collections.html#collections.defaultdict). First, just define a helper method to get the key from the string: ``` def get_key_from(string): return int(string.split('-')[1]) ``` Then ``` from collections import defaultdict sortedData_res = defaultdict(list) for h in data: k = next(iter(h)) sortedData_res[get_key_from(k)].append({k: ''}) ``` So you finally get this result: ``` sortedData_res #defaultdict(list, # {0: [{'records-0': ''}, # {'records-0-item1': ''}, # {'records-0-item2': ''}, # {'records-0-item3': ''}], # 1: [{'records-1': ''}, # {'records-1-item1': ''}, # {'records-1-item2': ''}]}) ``` --- Or adjust the code to get something different. For example if you `.append(h)` instead you get: ``` #defaultdict(list, # {0: [{'records-0': '1'}, # {'records-0-item1': '2'}, # {'records-0-item2': '3'}, # {'records-0-item3': '4'}], # 1: [{'records-1': '1'}, # {'records-1-item1': '2'}, # {'records-1-item2': '3'}]}) ```
I suggest you reformat your sortedData and remove lists. You could gather your data only into dict. *Edited* example: (should work as is) ```py def sort_data(l_: list): d_ = dict() for d in l_: for k, v in d.items(): i = re.split('-', k)[1] if not d_.get(int(i)): d_[int(i)] = dict() d_[int(i)][k] = v continue d_[int(i)][k] = v return d_ ``` ```py >>> data = [ {'records-0': '1'}, {'records-0-item1': '2'}, {'records-0-item2': '3'}, {'records-0-item3': '4'}, {'records-1': '1'}, {'records-1-item1': '2'}, {'records-1-item2': '3'}, ] >>> print(sort_data(data)) { 0: { 'records-0': '1', 'records-0-item1': '2', 'records-0-item2': '3', 'records-0-item3': '4' }, 1: { 'records-1': '1', 'records-1-item1': '2', 'records-1-item2': '3' } } ```
24,946,479
Are most functions for http requests synchronous by default? I came from Javascript and usage of AJAX and just started working with http requests in Python. To my surprise, it seems as though http request functions by default are synchronous, so I do not need to deal with any asynchronous behavior. For example, I'm working with the [Requests](http://docs.python-requests.org/en/latest/) http library, and although the docs don't explicitly say whether http requests are synchronous or not, by my own testing the calls seem to be synchronous. So is it that most http requests are by default synchronous in nature, or most functions are designed that way? And my first experience with http requests (JS AJAX) just happened to be of an asynchronous nature?
2014/07/25
[ "https://Stackoverflow.com/questions/24946479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1502780/" ]
It's the language, in python most apis are synchronous by default, and the async version is usually an "advanced" topic. If you were using nodejs, they would be async; even if using javascript, the reason ajax is asynchronous is because of the nature of the browser.
`requests` is completely synchronous/blocking. [`grequests`](https://github.com/kennethreitz/grequests) is what you are looking for: > > GRequests allows you to use Requests with Gevent to make asynchronous > HTTP Requests easily. > > > See also: * [Asynchronous Requests with Python requests](https://stackoverflow.com/questions/9110593/asynchronous-requests-with-python-requests) * [Ideal method for sending multiple HTTP requests over Python?](https://stackoverflow.com/questions/10555292/ideal-method-for-sending-multiple-http-requests-over-python) * [Multiple (asynchronous) connections with urllib2 or other http library?](https://stackoverflow.com/questions/4119680/multiple-asynchronous-connections-with-urllib2-or-other-http-library)
40,981,120
I have installed python 3.5, and need to install pywin (pywin32) however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully ``` Could not find a version that satisfies the requirement pywin32 (from versions: ) ``` A few possibly relevant data points: * new install of python 3.5 * windows 7 x64 * python 2.7 was previously installed on the machine * as mentioned, several other packages were installed fine via PIP * running these commands from git-bash, which came from the git windows installer, installed some time ago. -- I have gnu grep in my path, so i believe i selected the git installer option to put the whole mysys toolchain in my path full --verbose output: ``` C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 Collecting pywin32 Could not find a version that satisfies the requirement pywin32 (from versions: ) No matching distribution found for pywin32 C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 --verbose Config variable 'Py_DEBUG' is unset, Python ABI tag may be incorrect Config variable 'WITH_PYMALLOC' is unset, Python ABI tag may be incorrect Collecting pywin32 1 location(s) to search for versions of pywin32: * https://pypi.python.org/simple/pywin32/ Getting page https://pypi.python.org/simple/pywin32/ Looking up "https://pypi.python.org/simple/pywin32/" in the cache Current age based on date: 61 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 > 61 Analyzing links from page https://pypi.python.org/simple/pywin32/ Could not find a version that satisfies the requirement pywin32 (from versions: ) Cleaning up... No matching distribution found for pywin32 Exception information: Traceback (most recent call last): File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 554, in _prepare_file require_hashes File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\index.py", line 514, in find_requirement 'No matching distribution found for %s' % req pip.exceptions.DistributionNotFound: No matching distribution found for pywin32 ```
2016/12/05
[ "https://Stackoverflow.com/questions/40981120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/309433/" ]
I think you could use `pip install pypiwin32` instead.
If you are using a Python 3.5+ then you could add pypiwin32==223 to your requirements.txt file instead of pywin32
40,981,120
I have installed python 3.5, and need to install pywin (pywin32) however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully ``` Could not find a version that satisfies the requirement pywin32 (from versions: ) ``` A few possibly relevant data points: * new install of python 3.5 * windows 7 x64 * python 2.7 was previously installed on the machine * as mentioned, several other packages were installed fine via PIP * running these commands from git-bash, which came from the git windows installer, installed some time ago. -- I have gnu grep in my path, so i believe i selected the git installer option to put the whole mysys toolchain in my path full --verbose output: ``` C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 Collecting pywin32 Could not find a version that satisfies the requirement pywin32 (from versions: ) No matching distribution found for pywin32 C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 --verbose Config variable 'Py_DEBUG' is unset, Python ABI tag may be incorrect Config variable 'WITH_PYMALLOC' is unset, Python ABI tag may be incorrect Collecting pywin32 1 location(s) to search for versions of pywin32: * https://pypi.python.org/simple/pywin32/ Getting page https://pypi.python.org/simple/pywin32/ Looking up "https://pypi.python.org/simple/pywin32/" in the cache Current age based on date: 61 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 > 61 Analyzing links from page https://pypi.python.org/simple/pywin32/ Could not find a version that satisfies the requirement pywin32 (from versions: ) Cleaning up... No matching distribution found for pywin32 Exception information: Traceback (most recent call last): File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 554, in _prepare_file require_hashes File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\index.py", line 514, in find_requirement 'No matching distribution found for %s' % req pip.exceptions.DistributionNotFound: No matching distribution found for pywin32 ```
2016/12/05
[ "https://Stackoverflow.com/questions/40981120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/309433/" ]
I think you need to use [pypiwin32](https://pypi.python.org/pypi/pypiwin32) instead. See [How do you install pywin32 from a binary file in tox on Windows?](https://stackoverflow.com/questions/26639947/how-do-you-install-pywin32-from-a-binary-file-in-tox-on-windows)
I think you could use `pip install pypiwin32` instead.
40,981,120
I have installed python 3.5, and need to install pywin (pywin32) however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully ``` Could not find a version that satisfies the requirement pywin32 (from versions: ) ``` A few possibly relevant data points: * new install of python 3.5 * windows 7 x64 * python 2.7 was previously installed on the machine * as mentioned, several other packages were installed fine via PIP * running these commands from git-bash, which came from the git windows installer, installed some time ago. -- I have gnu grep in my path, so i believe i selected the git installer option to put the whole mysys toolchain in my path full --verbose output: ``` C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 Collecting pywin32 Could not find a version that satisfies the requirement pywin32 (from versions: ) No matching distribution found for pywin32 C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 --verbose Config variable 'Py_DEBUG' is unset, Python ABI tag may be incorrect Config variable 'WITH_PYMALLOC' is unset, Python ABI tag may be incorrect Collecting pywin32 1 location(s) to search for versions of pywin32: * https://pypi.python.org/simple/pywin32/ Getting page https://pypi.python.org/simple/pywin32/ Looking up "https://pypi.python.org/simple/pywin32/" in the cache Current age based on date: 61 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 > 61 Analyzing links from page https://pypi.python.org/simple/pywin32/ Could not find a version that satisfies the requirement pywin32 (from versions: ) Cleaning up... No matching distribution found for pywin32 Exception information: Traceback (most recent call last): File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 554, in _prepare_file require_hashes File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\index.py", line 514, in find_requirement 'No matching distribution found for %s' % req pip.exceptions.DistributionNotFound: No matching distribution found for pywin32 ```
2016/12/05
[ "https://Stackoverflow.com/questions/40981120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/309433/" ]
I think you need to use [pypiwin32](https://pypi.python.org/pypi/pypiwin32) instead. See [How do you install pywin32 from a binary file in tox on Windows?](https://stackoverflow.com/questions/26639947/how-do-you-install-pywin32-from-a-binary-file-in-tox-on-windows)
The pypi index mentions that pywin32 is not supported for python 3.5, only till python 3.3. <https://pypi.python.org/pypi/pywin32>. Which is why you are getting the error. However, you can install it from here as a binary package. It should work. I have used xlwings with pyton 3.6.2, which requires pywin32. Pywin32 build 220, works fine atleast for the functions I needed.
40,981,120
I have installed python 3.5, and need to install pywin (pywin32) however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully ``` Could not find a version that satisfies the requirement pywin32 (from versions: ) ``` A few possibly relevant data points: * new install of python 3.5 * windows 7 x64 * python 2.7 was previously installed on the machine * as mentioned, several other packages were installed fine via PIP * running these commands from git-bash, which came from the git windows installer, installed some time ago. -- I have gnu grep in my path, so i believe i selected the git installer option to put the whole mysys toolchain in my path full --verbose output: ``` C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 Collecting pywin32 Could not find a version that satisfies the requirement pywin32 (from versions: ) No matching distribution found for pywin32 C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 --verbose Config variable 'Py_DEBUG' is unset, Python ABI tag may be incorrect Config variable 'WITH_PYMALLOC' is unset, Python ABI tag may be incorrect Collecting pywin32 1 location(s) to search for versions of pywin32: * https://pypi.python.org/simple/pywin32/ Getting page https://pypi.python.org/simple/pywin32/ Looking up "https://pypi.python.org/simple/pywin32/" in the cache Current age based on date: 61 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 > 61 Analyzing links from page https://pypi.python.org/simple/pywin32/ Could not find a version that satisfies the requirement pywin32 (from versions: ) Cleaning up... No matching distribution found for pywin32 Exception information: Traceback (most recent call last): File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 554, in _prepare_file require_hashes File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\index.py", line 514, in find_requirement 'No matching distribution found for %s' % req pip.exceptions.DistributionNotFound: No matching distribution found for pywin32 ```
2016/12/05
[ "https://Stackoverflow.com/questions/40981120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/309433/" ]
I think you need to use [pypiwin32](https://pypi.python.org/pypi/pypiwin32) instead. See [How do you install pywin32 from a binary file in tox on Windows?](https://stackoverflow.com/questions/26639947/how-do-you-install-pywin32-from-a-binary-file-in-tox-on-windows)
If you are using a Python 3.5+ then you could add pypiwin32==223 to your requirements.txt file instead of pywin32
40,981,120
I have installed python 3.5, and need to install pywin (pywin32) however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully ``` Could not find a version that satisfies the requirement pywin32 (from versions: ) ``` A few possibly relevant data points: * new install of python 3.5 * windows 7 x64 * python 2.7 was previously installed on the machine * as mentioned, several other packages were installed fine via PIP * running these commands from git-bash, which came from the git windows installer, installed some time ago. -- I have gnu grep in my path, so i believe i selected the git installer option to put the whole mysys toolchain in my path full --verbose output: ``` C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 Collecting pywin32 Could not find a version that satisfies the requirement pywin32 (from versions: ) No matching distribution found for pywin32 C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 --verbose Config variable 'Py_DEBUG' is unset, Python ABI tag may be incorrect Config variable 'WITH_PYMALLOC' is unset, Python ABI tag may be incorrect Collecting pywin32 1 location(s) to search for versions of pywin32: * https://pypi.python.org/simple/pywin32/ Getting page https://pypi.python.org/simple/pywin32/ Looking up "https://pypi.python.org/simple/pywin32/" in the cache Current age based on date: 61 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 > 61 Analyzing links from page https://pypi.python.org/simple/pywin32/ Could not find a version that satisfies the requirement pywin32 (from versions: ) Cleaning up... No matching distribution found for pywin32 Exception information: Traceback (most recent call last): File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 554, in _prepare_file require_hashes File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\index.py", line 514, in find_requirement 'No matching distribution found for %s' % req pip.exceptions.DistributionNotFound: No matching distribution found for pywin32 ```
2016/12/05
[ "https://Stackoverflow.com/questions/40981120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/309433/" ]
I think you could use `pip install pypiwin32` instead.
The pypi index mentions that pywin32 is not supported for python 3.5, only till python 3.3. <https://pypi.python.org/pypi/pywin32>. Which is why you are getting the error. However, you can install it from here as a binary package. It should work. I have used xlwings with pyton 3.6.2, which requires pywin32. Pywin32 build 220, works fine atleast for the functions I needed.
40,981,120
I have installed python 3.5, and need to install pywin (pywin32) however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully ``` Could not find a version that satisfies the requirement pywin32 (from versions: ) ``` A few possibly relevant data points: * new install of python 3.5 * windows 7 x64 * python 2.7 was previously installed on the machine * as mentioned, several other packages were installed fine via PIP * running these commands from git-bash, which came from the git windows installer, installed some time ago. -- I have gnu grep in my path, so i believe i selected the git installer option to put the whole mysys toolchain in my path full --verbose output: ``` C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 Collecting pywin32 Could not find a version that satisfies the requirement pywin32 (from versions: ) No matching distribution found for pywin32 C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 --verbose Config variable 'Py_DEBUG' is unset, Python ABI tag may be incorrect Config variable 'WITH_PYMALLOC' is unset, Python ABI tag may be incorrect Collecting pywin32 1 location(s) to search for versions of pywin32: * https://pypi.python.org/simple/pywin32/ Getting page https://pypi.python.org/simple/pywin32/ Looking up "https://pypi.python.org/simple/pywin32/" in the cache Current age based on date: 61 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 > 61 Analyzing links from page https://pypi.python.org/simple/pywin32/ Could not find a version that satisfies the requirement pywin32 (from versions: ) Cleaning up... No matching distribution found for pywin32 Exception information: Traceback (most recent call last): File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 554, in _prepare_file require_hashes File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\index.py", line 514, in find_requirement 'No matching distribution found for %s' % req pip.exceptions.DistributionNotFound: No matching distribution found for pywin32 ```
2016/12/05
[ "https://Stackoverflow.com/questions/40981120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/309433/" ]
If you are using a Python 3.5+ then you could add pypiwin32==223 to your requirements.txt file instead of pywin32
If anyone still looking for pywin32 for python34, here is the link. Download and install. This resolves the issue <https://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/>
40,981,120
I have installed python 3.5, and need to install pywin (pywin32) however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully ``` Could not find a version that satisfies the requirement pywin32 (from versions: ) ``` A few possibly relevant data points: * new install of python 3.5 * windows 7 x64 * python 2.7 was previously installed on the machine * as mentioned, several other packages were installed fine via PIP * running these commands from git-bash, which came from the git windows installer, installed some time ago. -- I have gnu grep in my path, so i believe i selected the git installer option to put the whole mysys toolchain in my path full --verbose output: ``` C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 Collecting pywin32 Could not find a version that satisfies the requirement pywin32 (from versions: ) No matching distribution found for pywin32 C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 --verbose Config variable 'Py_DEBUG' is unset, Python ABI tag may be incorrect Config variable 'WITH_PYMALLOC' is unset, Python ABI tag may be incorrect Collecting pywin32 1 location(s) to search for versions of pywin32: * https://pypi.python.org/simple/pywin32/ Getting page https://pypi.python.org/simple/pywin32/ Looking up "https://pypi.python.org/simple/pywin32/" in the cache Current age based on date: 61 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 > 61 Analyzing links from page https://pypi.python.org/simple/pywin32/ Could not find a version that satisfies the requirement pywin32 (from versions: ) Cleaning up... No matching distribution found for pywin32 Exception information: Traceback (most recent call last): File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 554, in _prepare_file require_hashes File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\index.py", line 514, in find_requirement 'No matching distribution found for %s' % req pip.exceptions.DistributionNotFound: No matching distribution found for pywin32 ```
2016/12/05
[ "https://Stackoverflow.com/questions/40981120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/309433/" ]
If you are using a Python 3.5+ then you could add pypiwin32==223 to your requirements.txt file instead of pywin32
I have seen this thread referenced by people who were seeing the same pip error message on Linux or other systems -- even though the title clearly specifies "(on windows)". For users of Linux, Unix, MacOS, etc., let me make it perfectly clear that pywin32 is a wrapper for Windows system calls, and only works on Windows. (except under WINE). The advise to use an obsolete version of pywin32 when you are running an obsolete version of Python is correct -- if you are running on Windows. Let me also mention the "pypiwin32" is not a supported source. "pywin32" is official, and binary installers are maintained for all versions of Python which are then currently supported.
40,981,120
I have installed python 3.5, and need to install pywin (pywin32) however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully ``` Could not find a version that satisfies the requirement pywin32 (from versions: ) ``` A few possibly relevant data points: * new install of python 3.5 * windows 7 x64 * python 2.7 was previously installed on the machine * as mentioned, several other packages were installed fine via PIP * running these commands from git-bash, which came from the git windows installer, installed some time ago. -- I have gnu grep in my path, so i believe i selected the git installer option to put the whole mysys toolchain in my path full --verbose output: ``` C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 Collecting pywin32 Could not find a version that satisfies the requirement pywin32 (from versions: ) No matching distribution found for pywin32 C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 --verbose Config variable 'Py_DEBUG' is unset, Python ABI tag may be incorrect Config variable 'WITH_PYMALLOC' is unset, Python ABI tag may be incorrect Collecting pywin32 1 location(s) to search for versions of pywin32: * https://pypi.python.org/simple/pywin32/ Getting page https://pypi.python.org/simple/pywin32/ Looking up "https://pypi.python.org/simple/pywin32/" in the cache Current age based on date: 61 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 > 61 Analyzing links from page https://pypi.python.org/simple/pywin32/ Could not find a version that satisfies the requirement pywin32 (from versions: ) Cleaning up... No matching distribution found for pywin32 Exception information: Traceback (most recent call last): File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 554, in _prepare_file require_hashes File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\index.py", line 514, in find_requirement 'No matching distribution found for %s' % req pip.exceptions.DistributionNotFound: No matching distribution found for pywin32 ```
2016/12/05
[ "https://Stackoverflow.com/questions/40981120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/309433/" ]
I think you need to use [pypiwin32](https://pypi.python.org/pypi/pypiwin32) instead. See [How do you install pywin32 from a binary file in tox on Windows?](https://stackoverflow.com/questions/26639947/how-do-you-install-pywin32-from-a-binary-file-in-tox-on-windows)
If anyone still looking for pywin32 for python34, here is the link. Download and install. This resolves the issue <https://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/>
40,981,120
I have installed python 3.5, and need to install pywin (pywin32) however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully ``` Could not find a version that satisfies the requirement pywin32 (from versions: ) ``` A few possibly relevant data points: * new install of python 3.5 * windows 7 x64 * python 2.7 was previously installed on the machine * as mentioned, several other packages were installed fine via PIP * running these commands from git-bash, which came from the git windows installer, installed some time ago. -- I have gnu grep in my path, so i believe i selected the git installer option to put the whole mysys toolchain in my path full --verbose output: ``` C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 Collecting pywin32 Could not find a version that satisfies the requirement pywin32 (from versions: ) No matching distribution found for pywin32 C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 --verbose Config variable 'Py_DEBUG' is unset, Python ABI tag may be incorrect Config variable 'WITH_PYMALLOC' is unset, Python ABI tag may be incorrect Collecting pywin32 1 location(s) to search for versions of pywin32: * https://pypi.python.org/simple/pywin32/ Getting page https://pypi.python.org/simple/pywin32/ Looking up "https://pypi.python.org/simple/pywin32/" in the cache Current age based on date: 61 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 > 61 Analyzing links from page https://pypi.python.org/simple/pywin32/ Could not find a version that satisfies the requirement pywin32 (from versions: ) Cleaning up... No matching distribution found for pywin32 Exception information: Traceback (most recent call last): File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 554, in _prepare_file require_hashes File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\index.py", line 514, in find_requirement 'No matching distribution found for %s' % req pip.exceptions.DistributionNotFound: No matching distribution found for pywin32 ```
2016/12/05
[ "https://Stackoverflow.com/questions/40981120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/309433/" ]
I think you could use `pip install pypiwin32` instead.
If anyone still looking for pywin32 for python34, here is the link. Download and install. This resolves the issue <https://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/>
40,981,120
I have installed python 3.5, and need to install pywin (pywin32) however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully ``` Could not find a version that satisfies the requirement pywin32 (from versions: ) ``` A few possibly relevant data points: * new install of python 3.5 * windows 7 x64 * python 2.7 was previously installed on the machine * as mentioned, several other packages were installed fine via PIP * running these commands from git-bash, which came from the git windows installer, installed some time ago. -- I have gnu grep in my path, so i believe i selected the git installer option to put the whole mysys toolchain in my path full --verbose output: ``` C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 Collecting pywin32 Could not find a version that satisfies the requirement pywin32 (from versions: ) No matching distribution found for pywin32 C:\Users\USER>pip install pywin32 --proxy http://proxy.COMPANY.com:8080 --verbose Config variable 'Py_DEBUG' is unset, Python ABI tag may be incorrect Config variable 'WITH_PYMALLOC' is unset, Python ABI tag may be incorrect Collecting pywin32 1 location(s) to search for versions of pywin32: * https://pypi.python.org/simple/pywin32/ Getting page https://pypi.python.org/simple/pywin32/ Looking up "https://pypi.python.org/simple/pywin32/" in the cache Current age based on date: 61 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 > 61 Analyzing links from page https://pypi.python.org/simple/pywin32/ Could not find a version that satisfies the requirement pywin32 (from versions: ) Cleaning up... No matching distribution found for pywin32 Exception information: Traceback (most recent call last): File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_set.py", line 554, in _prepare_file require_hashes File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\req\req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "c:\users\USER\appdata\local\programs\python\python35\lib\site-packages\pip\index.py", line 514, in find_requirement 'No matching distribution found for %s' % req pip.exceptions.DistributionNotFound: No matching distribution found for pywin32 ```
2016/12/05
[ "https://Stackoverflow.com/questions/40981120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/309433/" ]
I think you need to use [pypiwin32](https://pypi.python.org/pypi/pypiwin32) instead. See [How do you install pywin32 from a binary file in tox on Windows?](https://stackoverflow.com/questions/26639947/how-do-you-install-pywin32-from-a-binary-file-in-tox-on-windows)
I have seen this thread referenced by people who were seeing the same pip error message on Linux or other systems -- even though the title clearly specifies "(on windows)". For users of Linux, Unix, MacOS, etc., let me make it perfectly clear that pywin32 is a wrapper for Windows system calls, and only works on Windows. (except under WINE). The advise to use an obsolete version of pywin32 when you are running an obsolete version of Python is correct -- if you are running on Windows. Let me also mention the "pypiwin32" is not a supported source. "pywin32" is official, and binary installers are maintained for all versions of Python which are then currently supported.
70,456,516
Here is the minimal code needed to reproduce the problem. I call an API with a callback function that prints what comes out of the API call. If I run this code in Jupyter, I get the output. If I run it with `python file.py` I don't get any output. I already checked the API's code, but that does nothing weird. Setting `DEBUGGING` to `True` isn't helpful either. Note that there is once dependency; the Bitvavo API. Install it with `pip install python-bitvavo-api` ``` # %% from python_bitvavo_api.bitvavo import Bitvavo # %% def generic_callback(response): print(f"log function=get_markets, {response=}") bitvavo = Bitvavo({"DEBUGGING": False}) websocket = bitvavo.newWebsocket() # %% websocket.markets(options={"market": "BTC-EUR"}, callback=generic_callback) ``` Here is the expected output I get from Jupyter: ``` log function:get_markets, response={'market': 'BTC-EUR', 'status': 'trading', 'base': 'BTC', 'quote': 'EUR', 'pricePrecision': 5, 'minOrderInBaseAsset': '0.0001', 'minOrderInQuoteAsset': '5', 'orderTypes': ['market', 'limit', 'stopLoss', 'stopLossLimit', 'takeProfit', 'takeProfitLimit']} ```
2021/12/23
[ "https://Stackoverflow.com/questions/70456516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12210524/" ]
Because you're using a websocket, the callback is executed by a different thread, which means that if you don't wait, the main thread (which is to receive the `print`'s output) will already be killed. Add a `sleep(1)` (that's seconds, not ms) at the end and the output will show. PS: The reason Jupyter *does* show the output, is because Jupyter keeps an interactive window open the entire time, even far after you've run the code :)
``` import time from python_bitvavo_api.bitvavo import Bitvavo # %% def generic_callback(response): print(f"log function=get_markets, {response=}") bitvavo = Bitvavo({"DEBUGGING": False}) websocket = bitvavo.newWebsocket() # Wait N.1 required to receive output, otherwise the main thread is killed time.sleep(1) # %% websocket.markets(options={"market": "BTC-EUR"}, callback=generic_callback) # Wait N.2 required to receive output, otherwise the main thread is killed time.sleep(1) ```
28,622,452
I want to print the files in subdirectory which is 2-level inside from root directory. In shell I can use the below find command ``` find -mindepth 3 -type f ./one/sub1/sub2/a.txt ./one/sub1/sub2/c.txt ./one/sub1/sub2/b.txt ``` In python How can i accomplish this. I know the basis syntax of os.walk, glob and fnmatch. But dont know how to specify the limit (like mindepeth and maxdepth in bash)
2015/02/20
[ "https://Stackoverflow.com/questions/28622452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4566486/" ]
You could use `.count()` method to find the depth: ``` import os def files(rootdir='.', mindepth=0, maxdepth=float('inf')): root_depth = rootdir.rstrip(os.path.sep).count(os.path.sep) - 1 for dirpath, dirs, files in os.walk(rootdir): depth = dirpath.count(os.path.sep) - root_depth if mindepth <= depth <= maxdepth: for filename in files: yield os.path.join(dirpath, filename) elif depth > maxdepth: del dirs[:] # too deep, don't recurse ``` Example: ``` print('\n'.join(files(mindepth=3))) ``` [The answer to the related question uses the same technique](https://stackoverflow.com/a/234329/4279).
You cannot specify any of this to [os.walk](https://docs.python.org/2/library/os.html#os.walk). However, you can write a function that does what you have in mind. ``` import os def list_dir_custom(mindepth=0, maxdepth=float('inf'), starting_dir=None): """ Lists all files in `starting_dir` starting from a `mindepth` and ranging to `maxdepth` If `starting_dir` is `None`, the current working directory is taken. """ def _list_dir_inner(current_dir, current_depth): if current_depth > maxdepth: return dir_list = [os.path.relpath(os.path.join(current_dir, x)) for x in os.listdir(current_dir)] for item in dir_list: if os.path.isdir(item): _list_dir_inner(item, current_depth + 1) elif current_depth >= mindepth: result_list.append(item) if starting_dir is None: starting_dir = os.getcwd() result_list = [] _list_dir_inner(starting_dir, 1) return result_list ``` EDIT: Added the corrections, reducing unnecessary variable definitions. 2nd Edit: Included 2Rings suggestion to make it list the very same files as `find`, i.e. `maxdepth` is exclusive. 3rd EDIT: Added other remarks by 2Ring, also changed the path to `relpath` to return the output in the same format as `find`.
45,445,455
In python I might have a function like this: ``` def sum_these(x, y=None): if y is None: y = 1 return x + y ``` What is the equivalent use in julia? To be exact I know I could probably do: ``` function sum_these(x, y=0) if y == 0 y = 1 end x + y end ``` However I'd rather not use zero, instead some value with the same meaning as `None` in python **EDIT** Just for clarity's sake, the result of these examples functions isn't important. The events(any) that happen if y is None are important, and for my cases setting y=[some number] is undesirable. After some search I think, unless someone provides a better solution is to do something like: ``` function sum_these(x, y=nothing) if y == nothing do stuff end return something ```
2017/08/01
[ "https://Stackoverflow.com/questions/45445455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6411264/" ]
Maybe use multiple dispatch with an empty fallback? ``` function f(x, y=nothing) ... do_something(x, y) ... return something end do_something(x, y) = nothing function do_something(x, y::Void) ... end ``` add other relevant vars to `do_something` as necessary, and return something or mutate as necessary.
Your question is a bit confusing. It seems like what you want is ``` function sum_these(x, y=1) return x + y end ``` But that doesn't quite do what you are asking either, since even if you call `sum_these(3, 0)` in your example, it replaces 0 with 1. Also in Python, I would use ``` def sum_these(x, y=1): return x + y ``` Perhaps I misunderstand your question.
45,445,455
In python I might have a function like this: ``` def sum_these(x, y=None): if y is None: y = 1 return x + y ``` What is the equivalent use in julia? To be exact I know I could probably do: ``` function sum_these(x, y=0) if y == 0 y = 1 end x + y end ``` However I'd rather not use zero, instead some value with the same meaning as `None` in python **EDIT** Just for clarity's sake, the result of these examples functions isn't important. The events(any) that happen if y is None are important, and for my cases setting y=[some number] is undesirable. After some search I think, unless someone provides a better solution is to do something like: ``` function sum_these(x, y=nothing) if y == nothing do stuff end return something ```
2017/08/01
[ "https://Stackoverflow.com/questions/45445455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6411264/" ]
``` function sum_these(x, y=nothing) if y == nothing do stuff end return something end ``` That's not only perfectly fine, but because `nothing` is a singleton of type `Void`, the `y==nothing` will actually compile away so the if statement is actually no runtime cost here. I talk about this in depth [in a blog post](http://www.stochasticlifestyle.com/type-dispatch-design-post-object-oriented-programming-julia/), but what it really means is that function auto-specialization allows for checks against nothing to always be free in type-stable/inferrable functions. However, you may want to consider splitting this into two different functions: ``` function sum_these(x) return something end function sum_these(x, y) do stuff return something end ``` Of course, this is just a style difference and the right choice is determined by how much code is shared in the `return something`.
Your question is a bit confusing. It seems like what you want is ``` function sum_these(x, y=1) return x + y end ``` But that doesn't quite do what you are asking either, since even if you call `sum_these(3, 0)` in your example, it replaces 0 with 1. Also in Python, I would use ``` def sum_these(x, y=1): return x + y ``` Perhaps I misunderstand your question.
45,445,455
In python I might have a function like this: ``` def sum_these(x, y=None): if y is None: y = 1 return x + y ``` What is the equivalent use in julia? To be exact I know I could probably do: ``` function sum_these(x, y=0) if y == 0 y = 1 end x + y end ``` However I'd rather not use zero, instead some value with the same meaning as `None` in python **EDIT** Just for clarity's sake, the result of these examples functions isn't important. The events(any) that happen if y is None are important, and for my cases setting y=[some number] is undesirable. After some search I think, unless someone provides a better solution is to do something like: ``` function sum_these(x, y=nothing) if y == nothing do stuff end return something ```
2017/08/01
[ "https://Stackoverflow.com/questions/45445455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6411264/" ]
``` function sum_these(x, y=nothing) if y == nothing do stuff end return something end ``` That's not only perfectly fine, but because `nothing` is a singleton of type `Void`, the `y==nothing` will actually compile away so the if statement is actually no runtime cost here. I talk about this in depth [in a blog post](http://www.stochasticlifestyle.com/type-dispatch-design-post-object-oriented-programming-julia/), but what it really means is that function auto-specialization allows for checks against nothing to always be free in type-stable/inferrable functions. However, you may want to consider splitting this into two different functions: ``` function sum_these(x) return something end function sum_these(x, y) do stuff return something end ``` Of course, this is just a style difference and the right choice is determined by how much code is shared in the `return something`.
Maybe use multiple dispatch with an empty fallback? ``` function f(x, y=nothing) ... do_something(x, y) ... return something end do_something(x, y) = nothing function do_something(x, y::Void) ... end ``` add other relevant vars to `do_something` as necessary, and return something or mutate as necessary.
48,216,974
The curve is: ``` import numpy as np import scipy.stats as sp from scipy.optimize import curve_fit from lmfit import minimize, Parameters, Parameter, report_fit# import xlwings as xw import os import pandas as pd ``` I tried running a simply curve fit from scipy: This returns ``` Out[156]: (array([ 1., 1.]), array([[ inf, inf], [ inf, inf]])) ``` Ok, so I thought I need to start bounding my parameters, which is what solver does. I used lmfit to do this: ``` params = Parameters() params.add ``` I tried to nudge python to the right direction by changing the starting parameters: or using curvefit:
2018/01/11
[ "https://Stackoverflow.com/questions/48216974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4504877/" ]
The curve fitting runs smoothly when we provide a good starting point. We can get one * by linear regression on `sp.norm.ppf(x_data)` and `np.log(y_data)` * or by fitting the free (non-clipped) model first Alternatively, if you want the computer to find the solution without "help" * use a stochastic algorithm like basin hopping (it's unfortunately not 100% autonomous, I had to increase the step size from its default value) * brute force it (this requires the user to provide a search grid) All four methods yield the same result and it is better than the excel result. ``` import numpy as np import scipy.stats as sp from scipy.optimize import curve_fit, basinhopping, brute def func1(x, n1, n2): return np.clip(np.exp(n2 + n1*(sp.norm.ppf(x))),25e4,10e6) def func_free(x, n1, n2): return np.exp(n2 + n1*(sp.norm.ppf(x))) def sqerr(n12, x, y): return ((func1(x, *n12) - y)**2).sum() x_data = np.array((1e-04,9e-01,9.5835e-01,9.8e-01,9.9e-01,9.9e-01)) y_data = np.array((250e3,1e6,2.5e6,5e6,7.5e6,10e6)) # get a good starting point # either by linear regression lin = sp.linregress(sp.norm.ppf(x_data), np.log(y_data)) # or by using the free (non-clipped) version of the formula (n1f, n2f), infof = curve_fit(func_free, x_data, y_data, (1, 1)) # use those on the original problem (n1, n2), info = curve_fit(func1, x_data, y_data, (lin.slope, lin.intercept)) (n12, n22), info2 = curve_fit(func1, x_data, y_data, (n1f, n2f)) # OR # use basin hopping hop = basinhopping(sqerr, (1, 1), minimizer_kwargs=dict(args=(x_data, y_data)), stepsize=10) # OR # brute force it brt = brute(sqerr, ((-100, 100), (-100, 100)), (x_data, y_data), 201, full_output=True) # all four solutions are essentially the same: assert np.allclose((n1, n2), (n12, n22)) assert np.allclose((n1, n2), hop.x) assert np.allclose((n1, n2), brt[0]) # we are actually a bit better than excel n1excel, n2excel = 1.7925, 11.6771 print('solution', n1, n2) print('error', ((func1(x_data, n1, n2) - y_data)**2).sum()) print('excel', ((func1(x_data, n1excel, n2excel) - y_data)**2).sum()) ``` Output: ``` solution 2.08286042997 11.1397332743 error 3.12796761241e+12 excel 5.80088578059e+12 ``` Remark: One easy optimization - which I left out for simplicity and because things are fast enough anyway - would have been to pull `sp.norm.ppf` out of the model function. This is possible because it does not depend on the fit parameters. So when any of our solvers calls the function it always does the exact same computation - `sp.norm.ppf(x_data)` - first, so we might as well have precomputed it. This observation is also our reason for using `sp.norm.ppf(x_data)` in the linear regression.
I think that part of the problem is that you have only 5 observations, 2 at the same value of `x` and the model does not perfectly represent your data. I also recommend trying to fit in the log of the model to the log of the data. And, if you expect `n2` to be ~10, you should use that as a starting value. Arbitrarily applying `min` and `max` to the calculated model, especially with values so close to your data range, makes very little sense. Doing this will prevent the fit method from exploring the effect of changing the parameter values on the model function. With some modifications to your code to omit the first data point (which seems to be throwing off the model), I find this: ``` import numpy as np import scipy.stats as sp from lmfit import Parameters, minimize, fit_report import matplotlib.pyplot as plt x_data = np.array((1e-04,9e-01,9.5835e-01,9.8e-01,9.9e-01,9.9e-01)) y_data = np.array((250e3,1e6,2.5e6,5e6,7.5e6,10e6)) x_data = x_data[1:] y_data = y_data[1:] def func(params, x, data, m1=250e3,m2=10e6): n1 = params['n1'].value n2 = params['n2'].value model = n2 + n1*(sp.norm.ppf(x)) return np.log(data) - model params = Parameters() params.add('n1', value= 1, min=0.01, max=20) params.add('n2', value= 10, min=0, max=20) result = minimize(func, params, args=(x_data[1:-1], y_data[1:-1])) print(fit_report(result)) n1 = result.params['n1'].value n2 = result.params['n2'].value ym = np.exp(n2 + n1*(sp.norm.ppf(x_data))) plt.plot(x_data, y_data, 'o') plt.plot(x_data, ym, '-') plt.legend(['data', 'fit']) plt.show() ``` gives a report of ``` [[Fit Statistics]] # fitting method = leastsq # function evals = 15 # data points = 3 # variables = 2 chi-square = 0.006 reduced chi-square = 0.006 Akaike info crit = -14.438 Bayesian info crit = -16.241 [[Variables]] n1: 1.85709072 +/- 0.190473 (10.26%) (init= 1) n2: 11.5455736 +/- 0.390805 (3.38%) (init= 10) [[Correlations]] (unreported correlations are < 0.100) C(n1, n2) = -0.993 ``` and a plot of [![enter image description here](https://i.stack.imgur.com/LUmrQ.png)](https://i.stack.imgur.com/LUmrQ.png)
48,216,974
The curve is: ``` import numpy as np import scipy.stats as sp from scipy.optimize import curve_fit from lmfit import minimize, Parameters, Parameter, report_fit# import xlwings as xw import os import pandas as pd ``` I tried running a simply curve fit from scipy: This returns ``` Out[156]: (array([ 1., 1.]), array([[ inf, inf], [ inf, inf]])) ``` Ok, so I thought I need to start bounding my parameters, which is what solver does. I used lmfit to do this: ``` params = Parameters() params.add ``` I tried to nudge python to the right direction by changing the starting parameters: or using curvefit:
2018/01/11
[ "https://Stackoverflow.com/questions/48216974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4504877/" ]
I think that part of the problem is that you have only 5 observations, 2 at the same value of `x` and the model does not perfectly represent your data. I also recommend trying to fit in the log of the model to the log of the data. And, if you expect `n2` to be ~10, you should use that as a starting value. Arbitrarily applying `min` and `max` to the calculated model, especially with values so close to your data range, makes very little sense. Doing this will prevent the fit method from exploring the effect of changing the parameter values on the model function. With some modifications to your code to omit the first data point (which seems to be throwing off the model), I find this: ``` import numpy as np import scipy.stats as sp from lmfit import Parameters, minimize, fit_report import matplotlib.pyplot as plt x_data = np.array((1e-04,9e-01,9.5835e-01,9.8e-01,9.9e-01,9.9e-01)) y_data = np.array((250e3,1e6,2.5e6,5e6,7.5e6,10e6)) x_data = x_data[1:] y_data = y_data[1:] def func(params, x, data, m1=250e3,m2=10e6): n1 = params['n1'].value n2 = params['n2'].value model = n2 + n1*(sp.norm.ppf(x)) return np.log(data) - model params = Parameters() params.add('n1', value= 1, min=0.01, max=20) params.add('n2', value= 10, min=0, max=20) result = minimize(func, params, args=(x_data[1:-1], y_data[1:-1])) print(fit_report(result)) n1 = result.params['n1'].value n2 = result.params['n2'].value ym = np.exp(n2 + n1*(sp.norm.ppf(x_data))) plt.plot(x_data, y_data, 'o') plt.plot(x_data, ym, '-') plt.legend(['data', 'fit']) plt.show() ``` gives a report of ``` [[Fit Statistics]] # fitting method = leastsq # function evals = 15 # data points = 3 # variables = 2 chi-square = 0.006 reduced chi-square = 0.006 Akaike info crit = -14.438 Bayesian info crit = -16.241 [[Variables]] n1: 1.85709072 +/- 0.190473 (10.26%) (init= 1) n2: 11.5455736 +/- 0.390805 (3.38%) (init= 10) [[Correlations]] (unreported correlations are < 0.100) C(n1, n2) = -0.993 ``` and a plot of [![enter image description here](https://i.stack.imgur.com/LUmrQ.png)](https://i.stack.imgur.com/LUmrQ.png)
Here is a simple way to perform regression using [scipy.optimize.curve\_fit](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html): ``` import matplotlib.pyplot as plt import scipy.optimize as opt import scipy.stats as stats import numpy as np % matplotlib inline # Objective def model(x, n1, n2): return np.exp(n2 + n1*(stats.norm.ppf(x))) # Data x_samp = np.array((1e-04, 9e-01, 9.5835e-01, 9.8e-01, 9.9e-01, 9.9e-01)) y_samp = np.array((250e3, 1e6, 2.5e6, 5e6 ,7.5e6, 10e6)) x_lin = np.linspace(min(x_samp), max(x_samp), 50) # for fitting # Regression p0 = [5, 5] # guessed params w, cov = opt.curve_fit(model, x_samp, y_samp, p0=p0) print("Estimated Parameters", w) y_fit = model(x_lin, *w) # Visualization plt.plot(x_samp, y_samp, "ko", label="Data") plt.plot(x_lin, y_fit, "k--", label="Fit") plt.title("Curve Fitting") plt.legend(loc="upper left") ``` Output ``` Estimated Parameters [ 2.08285048 11.13975585] ``` [![enter image description here](https://i.stack.imgur.com/0Vs49.png)](https://i.stack.imgur.com/0Vs49.png) --- **Details** Your data was plotted as-is, without transformations. It is easiest to perform such a regression if the *model* and *initial parameters*, `p0` reasonably fit your data. When these items are supplied to `scipy.optimize.curve_fit`, a tuple of the *weights* or optimized *estimated parameters*, `w` are returned, along with a [covariance matrix](https://i.stack.imgur.com/0Vs49.png). We can compute one standard deviation from the diagonals of the matrix: ``` p_stdev = np.sqrt(np.diag(cov)) print("Std. Dev. of Params:", p_stdev) # Std. Dev. of Params: [ 0.42281111 0.95945127] ``` We visually assess the goodness of fit by supplying these estimated parameters once more to the model and plotting the fitted line.
48,216,974
The curve is: ``` import numpy as np import scipy.stats as sp from scipy.optimize import curve_fit from lmfit import minimize, Parameters, Parameter, report_fit# import xlwings as xw import os import pandas as pd ``` I tried running a simply curve fit from scipy: This returns ``` Out[156]: (array([ 1., 1.]), array([[ inf, inf], [ inf, inf]])) ``` Ok, so I thought I need to start bounding my parameters, which is what solver does. I used lmfit to do this: ``` params = Parameters() params.add ``` I tried to nudge python to the right direction by changing the starting parameters: or using curvefit:
2018/01/11
[ "https://Stackoverflow.com/questions/48216974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4504877/" ]
The curve fitting runs smoothly when we provide a good starting point. We can get one * by linear regression on `sp.norm.ppf(x_data)` and `np.log(y_data)` * or by fitting the free (non-clipped) model first Alternatively, if you want the computer to find the solution without "help" * use a stochastic algorithm like basin hopping (it's unfortunately not 100% autonomous, I had to increase the step size from its default value) * brute force it (this requires the user to provide a search grid) All four methods yield the same result and it is better than the excel result. ``` import numpy as np import scipy.stats as sp from scipy.optimize import curve_fit, basinhopping, brute def func1(x, n1, n2): return np.clip(np.exp(n2 + n1*(sp.norm.ppf(x))),25e4,10e6) def func_free(x, n1, n2): return np.exp(n2 + n1*(sp.norm.ppf(x))) def sqerr(n12, x, y): return ((func1(x, *n12) - y)**2).sum() x_data = np.array((1e-04,9e-01,9.5835e-01,9.8e-01,9.9e-01,9.9e-01)) y_data = np.array((250e3,1e6,2.5e6,5e6,7.5e6,10e6)) # get a good starting point # either by linear regression lin = sp.linregress(sp.norm.ppf(x_data), np.log(y_data)) # or by using the free (non-clipped) version of the formula (n1f, n2f), infof = curve_fit(func_free, x_data, y_data, (1, 1)) # use those on the original problem (n1, n2), info = curve_fit(func1, x_data, y_data, (lin.slope, lin.intercept)) (n12, n22), info2 = curve_fit(func1, x_data, y_data, (n1f, n2f)) # OR # use basin hopping hop = basinhopping(sqerr, (1, 1), minimizer_kwargs=dict(args=(x_data, y_data)), stepsize=10) # OR # brute force it brt = brute(sqerr, ((-100, 100), (-100, 100)), (x_data, y_data), 201, full_output=True) # all four solutions are essentially the same: assert np.allclose((n1, n2), (n12, n22)) assert np.allclose((n1, n2), hop.x) assert np.allclose((n1, n2), brt[0]) # we are actually a bit better than excel n1excel, n2excel = 1.7925, 11.6771 print('solution', n1, n2) print('error', ((func1(x_data, n1, n2) - y_data)**2).sum()) print('excel', ((func1(x_data, n1excel, n2excel) - y_data)**2).sum()) ``` Output: ``` solution 2.08286042997 11.1397332743 error 3.12796761241e+12 excel 5.80088578059e+12 ``` Remark: One easy optimization - which I left out for simplicity and because things are fast enough anyway - would have been to pull `sp.norm.ppf` out of the model function. This is possible because it does not depend on the fit parameters. So when any of our solvers calls the function it always does the exact same computation - `sp.norm.ppf(x_data)` - first, so we might as well have precomputed it. This observation is also our reason for using `sp.norm.ppf(x_data)` in the linear regression.
Here is a simple way to perform regression using [scipy.optimize.curve\_fit](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html): ``` import matplotlib.pyplot as plt import scipy.optimize as opt import scipy.stats as stats import numpy as np % matplotlib inline # Objective def model(x, n1, n2): return np.exp(n2 + n1*(stats.norm.ppf(x))) # Data x_samp = np.array((1e-04, 9e-01, 9.5835e-01, 9.8e-01, 9.9e-01, 9.9e-01)) y_samp = np.array((250e3, 1e6, 2.5e6, 5e6 ,7.5e6, 10e6)) x_lin = np.linspace(min(x_samp), max(x_samp), 50) # for fitting # Regression p0 = [5, 5] # guessed params w, cov = opt.curve_fit(model, x_samp, y_samp, p0=p0) print("Estimated Parameters", w) y_fit = model(x_lin, *w) # Visualization plt.plot(x_samp, y_samp, "ko", label="Data") plt.plot(x_lin, y_fit, "k--", label="Fit") plt.title("Curve Fitting") plt.legend(loc="upper left") ``` Output ``` Estimated Parameters [ 2.08285048 11.13975585] ``` [![enter image description here](https://i.stack.imgur.com/0Vs49.png)](https://i.stack.imgur.com/0Vs49.png) --- **Details** Your data was plotted as-is, without transformations. It is easiest to perform such a regression if the *model* and *initial parameters*, `p0` reasonably fit your data. When these items are supplied to `scipy.optimize.curve_fit`, a tuple of the *weights* or optimized *estimated parameters*, `w` are returned, along with a [covariance matrix](https://i.stack.imgur.com/0Vs49.png). We can compute one standard deviation from the diagonals of the matrix: ``` p_stdev = np.sqrt(np.diag(cov)) print("Std. Dev. of Params:", p_stdev) # Std. Dev. of Params: [ 0.42281111 0.95945127] ``` We visually assess the goodness of fit by supplying these estimated parameters once more to the model and plotting the fitted line.
10,745,138
i'm new on python. i wrote a script to connect to a host and execute one command ``` ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pw) print 'running remote command' stdin, stdout, stderr = ssh.exec_command(command) stdin.close() for line in stdout.read().splitlines(): print '%s$: %s' % (host, line) if outfile != None: f_outfile.write("%s\n" %line) for line in stderr.read().splitlines(): print '%s$: %s' % (host, line + "\n") if outfile != None: f_outfile.write("%s\n" %line) ssh.close() if outfile != None: f_outfile.close() print 'connection to %s closed' %host except: e = sys.exc_info()[1] print '%s' %e ``` works fine when then remote command doesn't need a tty. i found an invoke\_shell example [Nested SSH session with Paramiko](https://stackoverflow.com/questions/1911690/nested-ssh-session-with-paramiko). i'm not happy with this solution, because if a server has an prompt that isn't specified in my script -> infinite loop or a specified prompt in the script is a string in the return text -> not all data will be received. is there a better solution maybe where stdout and stderr are send back like in my script?
2012/05/24
[ "https://Stackoverflow.com/questions/10745138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008764/" ]
There is extensive paramiko API documentation you can find at: <http://docs.paramiko.org/en/stable/index.html> I use the following method to execute commands on a password protected client: ``` import paramiko nbytes = 4096 hostname = 'hostname' port = 22 username = 'username' password = 'password' command = 'ls' client = paramiko.Transport((hostname, port)) client.connect(username=username, password=password) stdout_data = [] stderr_data = [] session = client.open_channel(kind='session') session.exec_command(command) while True: if session.recv_ready(): stdout_data.append(session.recv(nbytes)) if session.recv_stderr_ready(): stderr_data.append(session.recv_stderr(nbytes)) if session.exit_status_ready(): break print 'exit status: ', session.recv_exit_status() print ''.join(stdout_data) print ''.join(stderr_data) session.close() client.close() ```
ThePracticalOne - you are hero! I had problems with exec\_command (which is a member of Client) I tried to run powershell commands over ssh on Windows server, and only your example with ``` client = paramiko.Transport((hostname, port)) client.connect(username=username, password=password) ``` and ``` while True: if session.recv_ready(): stdout_data.append(session.recv(nbytes)) if session.recv_stderr_ready(): stderr_data.append(session.recv_stderr(nbytes)) if session.exit_status_ready(): break ``` helped to me!
10,745,138
i'm new on python. i wrote a script to connect to a host and execute one command ``` ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pw) print 'running remote command' stdin, stdout, stderr = ssh.exec_command(command) stdin.close() for line in stdout.read().splitlines(): print '%s$: %s' % (host, line) if outfile != None: f_outfile.write("%s\n" %line) for line in stderr.read().splitlines(): print '%s$: %s' % (host, line + "\n") if outfile != None: f_outfile.write("%s\n" %line) ssh.close() if outfile != None: f_outfile.close() print 'connection to %s closed' %host except: e = sys.exc_info()[1] print '%s' %e ``` works fine when then remote command doesn't need a tty. i found an invoke\_shell example [Nested SSH session with Paramiko](https://stackoverflow.com/questions/1911690/nested-ssh-session-with-paramiko). i'm not happy with this solution, because if a server has an prompt that isn't specified in my script -> infinite loop or a specified prompt in the script is a string in the return text -> not all data will be received. is there a better solution maybe where stdout and stderr are send back like in my script?
2012/05/24
[ "https://Stackoverflow.com/questions/10745138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008764/" ]
There is something wrong with the accepted answer, it sometimes (randomly) brings a clipped response from server. I do not know why, I did not investigate the faulty cause of the accepted answer because this code worked perfectly for me: ``` import paramiko ip='server ip' port=22 username='username' password='password' cmd='some useful command' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) stdin,stdout,stderr=ssh.exec_command(cmd) outlines=stdout.readlines() resp=''.join(outlines) print(resp) stdin,stdout,stderr=ssh.exec_command('some really useful command') outlines=stdout.readlines() resp=''.join(outlines) print(resp) ```
The code of @ThePracticalOne is great for showing the usage except for one thing: **Somtimes** the output would be incomplete.(`session.recv_ready()` turns true after the `if session.recv_ready():` while `session.recv_stderr_ready()` and `session.exit_status_ready()` turned true before entering next loop) so my thinking is to retrieving the data when it is ready to exit the session. ``` while True: if session.exit_status_ready(): while True: while True: print "try to recv stdout..." ret = session.recv(nbytes) if len(ret) == 0: break stdout_data.append(ret) while True: print "try to recv stderr..." ret = session.recv_stderr(nbytes) if len(ret) == 0: break stderr_data.append(ret) break ```
10,745,138
i'm new on python. i wrote a script to connect to a host and execute one command ``` ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pw) print 'running remote command' stdin, stdout, stderr = ssh.exec_command(command) stdin.close() for line in stdout.read().splitlines(): print '%s$: %s' % (host, line) if outfile != None: f_outfile.write("%s\n" %line) for line in stderr.read().splitlines(): print '%s$: %s' % (host, line + "\n") if outfile != None: f_outfile.write("%s\n" %line) ssh.close() if outfile != None: f_outfile.close() print 'connection to %s closed' %host except: e = sys.exc_info()[1] print '%s' %e ``` works fine when then remote command doesn't need a tty. i found an invoke\_shell example [Nested SSH session with Paramiko](https://stackoverflow.com/questions/1911690/nested-ssh-session-with-paramiko). i'm not happy with this solution, because if a server has an prompt that isn't specified in my script -> infinite loop or a specified prompt in the script is a string in the return text -> not all data will be received. is there a better solution maybe where stdout and stderr are send back like in my script?
2012/05/24
[ "https://Stackoverflow.com/questions/10745138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008764/" ]
Passwordless SSH worked for me ``` import paramiko def connect_SSH(): ssh = paramiko.SSHClient() username = '<uname>' port = <port-no> ip = '<ip-address>' ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username) stdin, stdout, stderr = ssh.exec_command('<cmd>') outlines = stdout.readlines() resp=''.join(outlines) print(resp) connect_SSH() ```
``` ###### Use paramiko to connect to LINUX platform############ import paramiko ip='server ip' port=22 username='username' password='password' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) --------Connection Established----------------------------- ######To run shell commands on remote connection########### import paramiko ip='server ip' port=22 username='username' password='password' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) stdin,stdout,stderr=ssh.exec_command(cmd) outlines=stdout.readlines() resp=''.join(outlines) print(resp) # Output ```
10,745,138
i'm new on python. i wrote a script to connect to a host and execute one command ``` ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pw) print 'running remote command' stdin, stdout, stderr = ssh.exec_command(command) stdin.close() for line in stdout.read().splitlines(): print '%s$: %s' % (host, line) if outfile != None: f_outfile.write("%s\n" %line) for line in stderr.read().splitlines(): print '%s$: %s' % (host, line + "\n") if outfile != None: f_outfile.write("%s\n" %line) ssh.close() if outfile != None: f_outfile.close() print 'connection to %s closed' %host except: e = sys.exc_info()[1] print '%s' %e ``` works fine when then remote command doesn't need a tty. i found an invoke\_shell example [Nested SSH session with Paramiko](https://stackoverflow.com/questions/1911690/nested-ssh-session-with-paramiko). i'm not happy with this solution, because if a server has an prompt that isn't specified in my script -> infinite loop or a specified prompt in the script is a string in the return text -> not all data will be received. is there a better solution maybe where stdout and stderr are send back like in my script?
2012/05/24
[ "https://Stackoverflow.com/questions/10745138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008764/" ]
There is extensive paramiko API documentation you can find at: <http://docs.paramiko.org/en/stable/index.html> I use the following method to execute commands on a password protected client: ``` import paramiko nbytes = 4096 hostname = 'hostname' port = 22 username = 'username' password = 'password' command = 'ls' client = paramiko.Transport((hostname, port)) client.connect(username=username, password=password) stdout_data = [] stderr_data = [] session = client.open_channel(kind='session') session.exec_command(command) while True: if session.recv_ready(): stdout_data.append(session.recv(nbytes)) if session.recv_stderr_ready(): stderr_data.append(session.recv_stderr(nbytes)) if session.exit_status_ready(): break print 'exit status: ', session.recv_exit_status() print ''.join(stdout_data) print ''.join(stderr_data) session.close() client.close() ```
Passwordless SSH worked for me ``` import paramiko def connect_SSH(): ssh = paramiko.SSHClient() username = '<uname>' port = <port-no> ip = '<ip-address>' ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username) stdin, stdout, stderr = ssh.exec_command('<cmd>') outlines = stdout.readlines() resp=''.join(outlines) print(resp) connect_SSH() ```
10,745,138
i'm new on python. i wrote a script to connect to a host and execute one command ``` ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pw) print 'running remote command' stdin, stdout, stderr = ssh.exec_command(command) stdin.close() for line in stdout.read().splitlines(): print '%s$: %s' % (host, line) if outfile != None: f_outfile.write("%s\n" %line) for line in stderr.read().splitlines(): print '%s$: %s' % (host, line + "\n") if outfile != None: f_outfile.write("%s\n" %line) ssh.close() if outfile != None: f_outfile.close() print 'connection to %s closed' %host except: e = sys.exc_info()[1] print '%s' %e ``` works fine when then remote command doesn't need a tty. i found an invoke\_shell example [Nested SSH session with Paramiko](https://stackoverflow.com/questions/1911690/nested-ssh-session-with-paramiko). i'm not happy with this solution, because if a server has an prompt that isn't specified in my script -> infinite loop or a specified prompt in the script is a string in the return text -> not all data will be received. is there a better solution maybe where stdout and stderr are send back like in my script?
2012/05/24
[ "https://Stackoverflow.com/questions/10745138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008764/" ]
The code of @ThePracticalOne is great for showing the usage except for one thing: **Somtimes** the output would be incomplete.(`session.recv_ready()` turns true after the `if session.recv_ready():` while `session.recv_stderr_ready()` and `session.exit_status_ready()` turned true before entering next loop) so my thinking is to retrieving the data when it is ready to exit the session. ``` while True: if session.exit_status_ready(): while True: while True: print "try to recv stdout..." ret = session.recv(nbytes) if len(ret) == 0: break stdout_data.append(ret) while True: print "try to recv stderr..." ret = session.recv_stderr(nbytes) if len(ret) == 0: break stderr_data.append(ret) break ```
``` ###### Use paramiko to connect to LINUX platform############ import paramiko ip='server ip' port=22 username='username' password='password' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) --------Connection Established----------------------------- ######To run shell commands on remote connection########### import paramiko ip='server ip' port=22 username='username' password='password' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) stdin,stdout,stderr=ssh.exec_command(cmd) outlines=stdout.readlines() resp=''.join(outlines) print(resp) # Output ```
10,745,138
i'm new on python. i wrote a script to connect to a host and execute one command ``` ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pw) print 'running remote command' stdin, stdout, stderr = ssh.exec_command(command) stdin.close() for line in stdout.read().splitlines(): print '%s$: %s' % (host, line) if outfile != None: f_outfile.write("%s\n" %line) for line in stderr.read().splitlines(): print '%s$: %s' % (host, line + "\n") if outfile != None: f_outfile.write("%s\n" %line) ssh.close() if outfile != None: f_outfile.close() print 'connection to %s closed' %host except: e = sys.exc_info()[1] print '%s' %e ``` works fine when then remote command doesn't need a tty. i found an invoke\_shell example [Nested SSH session with Paramiko](https://stackoverflow.com/questions/1911690/nested-ssh-session-with-paramiko). i'm not happy with this solution, because if a server has an prompt that isn't specified in my script -> infinite loop or a specified prompt in the script is a string in the return text -> not all data will be received. is there a better solution maybe where stdout and stderr are send back like in my script?
2012/05/24
[ "https://Stackoverflow.com/questions/10745138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008764/" ]
There is something wrong with the accepted answer, it sometimes (randomly) brings a clipped response from server. I do not know why, I did not investigate the faulty cause of the accepted answer because this code worked perfectly for me: ``` import paramiko ip='server ip' port=22 username='username' password='password' cmd='some useful command' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) stdin,stdout,stderr=ssh.exec_command(cmd) outlines=stdout.readlines() resp=''.join(outlines) print(resp) stdin,stdout,stderr=ssh.exec_command('some really useful command') outlines=stdout.readlines() resp=''.join(outlines) print(resp) ```
Passwordless SSH worked for me ``` import paramiko def connect_SSH(): ssh = paramiko.SSHClient() username = '<uname>' port = <port-no> ip = '<ip-address>' ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username) stdin, stdout, stderr = ssh.exec_command('<cmd>') outlines = stdout.readlines() resp=''.join(outlines) print(resp) connect_SSH() ```
10,745,138
i'm new on python. i wrote a script to connect to a host and execute one command ``` ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pw) print 'running remote command' stdin, stdout, stderr = ssh.exec_command(command) stdin.close() for line in stdout.read().splitlines(): print '%s$: %s' % (host, line) if outfile != None: f_outfile.write("%s\n" %line) for line in stderr.read().splitlines(): print '%s$: %s' % (host, line + "\n") if outfile != None: f_outfile.write("%s\n" %line) ssh.close() if outfile != None: f_outfile.close() print 'connection to %s closed' %host except: e = sys.exc_info()[1] print '%s' %e ``` works fine when then remote command doesn't need a tty. i found an invoke\_shell example [Nested SSH session with Paramiko](https://stackoverflow.com/questions/1911690/nested-ssh-session-with-paramiko). i'm not happy with this solution, because if a server has an prompt that isn't specified in my script -> infinite loop or a specified prompt in the script is a string in the return text -> not all data will be received. is there a better solution maybe where stdout and stderr are send back like in my script?
2012/05/24
[ "https://Stackoverflow.com/questions/10745138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008764/" ]
There is something wrong with the accepted answer, it sometimes (randomly) brings a clipped response from server. I do not know why, I did not investigate the faulty cause of the accepted answer because this code worked perfectly for me: ``` import paramiko ip='server ip' port=22 username='username' password='password' cmd='some useful command' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) stdin,stdout,stderr=ssh.exec_command(cmd) outlines=stdout.readlines() resp=''.join(outlines) print(resp) stdin,stdout,stderr=ssh.exec_command('some really useful command') outlines=stdout.readlines() resp=''.join(outlines) print(resp) ```
``` ###### Use paramiko to connect to LINUX platform############ import paramiko ip='server ip' port=22 username='username' password='password' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) --------Connection Established----------------------------- ######To run shell commands on remote connection########### import paramiko ip='server ip' port=22 username='username' password='password' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) stdin,stdout,stderr=ssh.exec_command(cmd) outlines=stdout.readlines() resp=''.join(outlines) print(resp) # Output ```
10,745,138
i'm new on python. i wrote a script to connect to a host and execute one command ``` ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pw) print 'running remote command' stdin, stdout, stderr = ssh.exec_command(command) stdin.close() for line in stdout.read().splitlines(): print '%s$: %s' % (host, line) if outfile != None: f_outfile.write("%s\n" %line) for line in stderr.read().splitlines(): print '%s$: %s' % (host, line + "\n") if outfile != None: f_outfile.write("%s\n" %line) ssh.close() if outfile != None: f_outfile.close() print 'connection to %s closed' %host except: e = sys.exc_info()[1] print '%s' %e ``` works fine when then remote command doesn't need a tty. i found an invoke\_shell example [Nested SSH session with Paramiko](https://stackoverflow.com/questions/1911690/nested-ssh-session-with-paramiko). i'm not happy with this solution, because if a server has an prompt that isn't specified in my script -> infinite loop or a specified prompt in the script is a string in the return text -> not all data will be received. is there a better solution maybe where stdout and stderr are send back like in my script?
2012/05/24
[ "https://Stackoverflow.com/questions/10745138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008764/" ]
There is extensive paramiko API documentation you can find at: <http://docs.paramiko.org/en/stable/index.html> I use the following method to execute commands on a password protected client: ``` import paramiko nbytes = 4096 hostname = 'hostname' port = 22 username = 'username' password = 'password' command = 'ls' client = paramiko.Transport((hostname, port)) client.connect(username=username, password=password) stdout_data = [] stderr_data = [] session = client.open_channel(kind='session') session.exec_command(command) while True: if session.recv_ready(): stdout_data.append(session.recv(nbytes)) if session.recv_stderr_ready(): stderr_data.append(session.recv_stderr(nbytes)) if session.exit_status_ready(): break print 'exit status: ', session.recv_exit_status() print ''.join(stdout_data) print ''.join(stderr_data) session.close() client.close() ```
``` ###### Use paramiko to connect to LINUX platform############ import paramiko ip='server ip' port=22 username='username' password='password' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) --------Connection Established----------------------------- ######To run shell commands on remote connection########### import paramiko ip='server ip' port=22 username='username' password='password' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) stdin,stdout,stderr=ssh.exec_command(cmd) outlines=stdout.readlines() resp=''.join(outlines) print(resp) # Output ```
10,745,138
i'm new on python. i wrote a script to connect to a host and execute one command ``` ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pw) print 'running remote command' stdin, stdout, stderr = ssh.exec_command(command) stdin.close() for line in stdout.read().splitlines(): print '%s$: %s' % (host, line) if outfile != None: f_outfile.write("%s\n" %line) for line in stderr.read().splitlines(): print '%s$: %s' % (host, line + "\n") if outfile != None: f_outfile.write("%s\n" %line) ssh.close() if outfile != None: f_outfile.close() print 'connection to %s closed' %host except: e = sys.exc_info()[1] print '%s' %e ``` works fine when then remote command doesn't need a tty. i found an invoke\_shell example [Nested SSH session with Paramiko](https://stackoverflow.com/questions/1911690/nested-ssh-session-with-paramiko). i'm not happy with this solution, because if a server has an prompt that isn't specified in my script -> infinite loop or a specified prompt in the script is a string in the return text -> not all data will be received. is there a better solution maybe where stdout and stderr are send back like in my script?
2012/05/24
[ "https://Stackoverflow.com/questions/10745138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008764/" ]
There is extensive paramiko API documentation you can find at: <http://docs.paramiko.org/en/stable/index.html> I use the following method to execute commands on a password protected client: ``` import paramiko nbytes = 4096 hostname = 'hostname' port = 22 username = 'username' password = 'password' command = 'ls' client = paramiko.Transport((hostname, port)) client.connect(username=username, password=password) stdout_data = [] stderr_data = [] session = client.open_channel(kind='session') session.exec_command(command) while True: if session.recv_ready(): stdout_data.append(session.recv(nbytes)) if session.recv_stderr_ready(): stderr_data.append(session.recv_stderr(nbytes)) if session.exit_status_ready(): break print 'exit status: ', session.recv_exit_status() print ''.join(stdout_data) print ''.join(stderr_data) session.close() client.close() ```
The code of @ThePracticalOne is great for showing the usage except for one thing: **Somtimes** the output would be incomplete.(`session.recv_ready()` turns true after the `if session.recv_ready():` while `session.recv_stderr_ready()` and `session.exit_status_ready()` turned true before entering next loop) so my thinking is to retrieving the data when it is ready to exit the session. ``` while True: if session.exit_status_ready(): while True: while True: print "try to recv stdout..." ret = session.recv(nbytes) if len(ret) == 0: break stdout_data.append(ret) while True: print "try to recv stderr..." ret = session.recv_stderr(nbytes) if len(ret) == 0: break stderr_data.append(ret) break ```
10,745,138
i'm new on python. i wrote a script to connect to a host and execute one command ``` ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pw) print 'running remote command' stdin, stdout, stderr = ssh.exec_command(command) stdin.close() for line in stdout.read().splitlines(): print '%s$: %s' % (host, line) if outfile != None: f_outfile.write("%s\n" %line) for line in stderr.read().splitlines(): print '%s$: %s' % (host, line + "\n") if outfile != None: f_outfile.write("%s\n" %line) ssh.close() if outfile != None: f_outfile.close() print 'connection to %s closed' %host except: e = sys.exc_info()[1] print '%s' %e ``` works fine when then remote command doesn't need a tty. i found an invoke\_shell example [Nested SSH session with Paramiko](https://stackoverflow.com/questions/1911690/nested-ssh-session-with-paramiko). i'm not happy with this solution, because if a server has an prompt that isn't specified in my script -> infinite loop or a specified prompt in the script is a string in the return text -> not all data will be received. is there a better solution maybe where stdout and stderr are send back like in my script?
2012/05/24
[ "https://Stackoverflow.com/questions/10745138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008764/" ]
ThePracticalOne - you are hero! I had problems with exec\_command (which is a member of Client) I tried to run powershell commands over ssh on Windows server, and only your example with ``` client = paramiko.Transport((hostname, port)) client.connect(username=username, password=password) ``` and ``` while True: if session.recv_ready(): stdout_data.append(session.recv(nbytes)) if session.recv_stderr_ready(): stderr_data.append(session.recv_stderr(nbytes)) if session.exit_status_ready(): break ``` helped to me!
``` ###### Use paramiko to connect to LINUX platform############ import paramiko ip='server ip' port=22 username='username' password='password' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) --------Connection Established----------------------------- ######To run shell commands on remote connection########### import paramiko ip='server ip' port=22 username='username' password='password' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) stdin,stdout,stderr=ssh.exec_command(cmd) outlines=stdout.readlines() resp=''.join(outlines) print(resp) # Output ```
25,086,088
I've spent the better part of an afternoon trying to import the xlrd module, it works when i do it in the shell but when i try to run any file I get an import error. Please could somebody provide a solution? (I'm a beginner, so please be excruciatingly specific) This code: ``` #!/usr/bin/python import os os.chdir("C:/Users/User/Documents/Python/xlrd") import xlrd ``` returns the error: ``` Traceback (most recent call last): File "C:\Users\User\Documents\Python\Programs\Radiocarbon27.py", line 4 in <module> import xlrd ImportError: No module named xlrd ``` The path of the setup.py which contains the setup.py file is C:\Users\User\Documents\Python\xlrddocs thanks!
2014/08/01
[ "https://Stackoverflow.com/questions/25086088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3900424/" ]
They are overlapping because you've given them all absolute position and left 0. Absolute position removes the element from the normal flow of the page and puts it exactly where you indicate using the top/left/right/bottom properties. They will overlap as long as they have the same parent and same position properties.
They are overlapping because you are using position absolute. instead place the divs at the top of the html page and do this instead: ``` <div id="left" style="float:left;width:60%;height:100%;background:#e6e6e6;"> <div id="map" style="float:left;width:60%;height:400px">Map goes here.</div> <div id="details" style="float:left;left:0px;width:60%;height:400px">Details</div> </div> <div id="description" style="float:left;width:20%;height:100%;background:#ffffff;"> </div> <div id="resource" style="float:left;width:20%;height:100%;background:#ffffff;"> </div> ``` This will place the divs beside each other
25,086,088
I've spent the better part of an afternoon trying to import the xlrd module, it works when i do it in the shell but when i try to run any file I get an import error. Please could somebody provide a solution? (I'm a beginner, so please be excruciatingly specific) This code: ``` #!/usr/bin/python import os os.chdir("C:/Users/User/Documents/Python/xlrd") import xlrd ``` returns the error: ``` Traceback (most recent call last): File "C:\Users\User\Documents\Python\Programs\Radiocarbon27.py", line 4 in <module> import xlrd ImportError: No module named xlrd ``` The path of the setup.py which contains the setup.py file is C:\Users\User\Documents\Python\xlrddocs thanks!
2014/08/01
[ "https://Stackoverflow.com/questions/25086088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3900424/" ]
Absolute position and left being 0 is making them overlap. **Please use css** see solution : <http://jsfiddle.net/thecbuilder/vZ77e/> **html** ``` <div id="left"> <div id="map">Map goes here.</div> <div id="details">Details</div> </div> <div id="description">description</div> <div id="resource">resource</div> ``` **css** ``` #left, #description, #resource{ display:inline; float:left; height:100%; } #left{ width:60%; background:#e6e6e6; } #description, #resource{ width:20%; } ```
They are overlapping because you are using position absolute. instead place the divs at the top of the html page and do this instead: ``` <div id="left" style="float:left;width:60%;height:100%;background:#e6e6e6;"> <div id="map" style="float:left;width:60%;height:400px">Map goes here.</div> <div id="details" style="float:left;left:0px;width:60%;height:400px">Details</div> </div> <div id="description" style="float:left;width:20%;height:100%;background:#ffffff;"> </div> <div id="resource" style="float:left;width:20%;height:100%;background:#ffffff;"> </div> ``` This will place the divs beside each other
55,550,259
I would like to find a way to reverse the bits of each character in a string using python. For example, if my first character was `J`, this is ASCII `0x4a` or `0b01001010`, so would be reversed to `0x52` or `0b01010010`. If my second character was `K`, this is `0b01001011`, so would be reversed to `0xd2` or `0b11010010`, etc. The end result should be returned as a `string`. Speed is my number one priority here, so I am looking for a fast way to accomplish this.
2019/04/06
[ "https://Stackoverflow.com/questions/55550259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4263190/" ]
If speed is your goal and you are working with ASCII so you only have 256 8-bit values to handle, calculate the reversed-byte values beforehand and put them in a `bytearray`, then look them up by indexing into the `bytearray`.
``` a=bin(ord("a")) '0b'+a[::-1][0:len(a)-2] ``` If you want to do it for a lot of characters, then there are only 256 ascii characters. Store the reversed strings in a hashmap and do lookups on the hashmap. Time complexity of those lookups is O(1), but there's a fix setup time.
55,550,259
I would like to find a way to reverse the bits of each character in a string using python. For example, if my first character was `J`, this is ASCII `0x4a` or `0b01001010`, so would be reversed to `0x52` or `0b01010010`. If my second character was `K`, this is `0b01001011`, so would be reversed to `0xd2` or `0b11010010`, etc. The end result should be returned as a `string`. Speed is my number one priority here, so I am looking for a fast way to accomplish this.
2019/04/06
[ "https://Stackoverflow.com/questions/55550259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4263190/" ]
After taking on board the advice, here is my solution: ``` # Pre-populate a look-up array with bit-reversed integers from 0 to 255 bytearray = [] for i in range(0, 256): bytearray.append(int('{:08b}'.format(i)[::-1], 2)) # Reverses the bits of each character in the input string and returns the result # as a string def revstr(string): return ''.join([chr(bytearray[ord(a)]) for a in list(string)]) print "JK".encode("hex") # 0x4a4b print revstr("JK").encode("hex") # 0x52d2 ```
``` a=bin(ord("a")) '0b'+a[::-1][0:len(a)-2] ``` If you want to do it for a lot of characters, then there are only 256 ascii characters. Store the reversed strings in a hashmap and do lookups on the hashmap. Time complexity of those lookups is O(1), but there's a fix setup time.
22,384,783
I am trying to use C# classes from python, using python.net on mono / ubuntu. So far I managed to do a simple function call with one argument work. What I am now trying to do is pass a python callback to the C# function call. I tried the following variations below, none worked. Can someone show how to make that work? ``` // C# - testlib.cs class MC { public double method1(int n) { Console.WriteLine("Executing method1" ); /* .. */ } public double method2(Delegate f) { Console.WriteLine("Executing method2" ); /* ... do f() at some point ... */ /* also tried f.DynamicInvoke() */ Console.WriteLine("Done executing method2" ); } } ``` Python script ``` import testlib, System mc = testlib.MC() mc.method1(10) # that works def f(): print "Executing f" mc.method2(f) # does not know of method2 with that signature, fair enough... # is this the right way to turn it into a callback? f2 = System.AssemblyLoad(f) # no error message, but f does not seem to be invoked mc.method2(f2) ```
2014/03/13
[ "https://Stackoverflow.com/questions/22384783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1477436/" ]
Try to pass `Action` or `Func` instead of just raw function: I used IronPython here (because right now I don't have mono installed on any of my machines but according of Python.NET [documentation](http://pythonnet.sourceforge.net/readme.html) I think it should work Actually your code is almost ok but you need to import `Action` or `Func` delegate depends on what you need. python code: ``` import clr from types import * from System import Action clr.AddReferenceToFileAndPath(r"YourPath\TestLib.dll") import TestLib print("Hello") mc = TestLib.MC() print(mc.method1(10)) def f(fakeparam): print "exec f" mc.method2(Action[int](f)) ``` This is a console output: ``` Hello Executing method1 42.0 Executing method2 exec f Done executing method2 ``` C# code: ``` using System; namespace TestLib { public class MC { public double method1(int n) { Console.WriteLine("Executing method1"); return 42.0; /* .. */ } public double method2(Delegate f) { Console.WriteLine("Executing method2"); object[] paramToPass = new object[1]; paramToPass[0] = new int(); f.DynamicInvoke(paramToPass); Console.WriteLine("Done executing method2"); return 24.0; } } } ``` I read docs for Python.net [Using Generics](http://pythonnet.sourceforge.net/readme.html#generics) again and also found this [Python.NET Naming and resolution of generic types](https://mail.python.org/pipermail/pythondotnet/2006-April/000472.html) look like you need to specify parameter type explicitly [quote from there](https://mail.python.org/pipermail/pythondotnet/2006-April/000472.html): > > a (reflected) generic type definition (if there exists a generic type > definition with the > given base name, and no non-generic type with that name). This generic type > definition can be bound into a closed generic type using the [] syntax. Trying to > instantiate a generic type def using () raises a TypeError. > > >
It looks like you should define your Delegate explicitly: ``` class MC { // Define a delegate type public delegate void Callback(); public double method2(Callback f) { Console.WriteLine("Executing method2" ); /* ... do f() at some point ... */ /* also tried f.DynamicInvoke() */ Console.WriteLine("Done executing method2" ); } } ``` Then from the Python code (this is a rough guess based from the [docs](http://pythonnet.sourceforge.net/readme.html#delegates)): ``` def f(): print "Executing f" # instantiate a delegate f2 = testlib.MC.Callback(f) # use it mc.method2(f2) ```
56,692,868
I am trying to write a mock lottery simulator as a thought excercize and for some introductory python practice, where each team would have 2x the odds of getting the first pick as the team that preceded them in the standings. The code below works (although I am sure there is a more efficient way to write it), but now I would like to figure out a way to find each individual teams odds of getting a certain draft spot based on their odds. I believe there are 12! ways for the order to be set, so it would be next to impossible to compute by hand. Is there a way to run a simulation in python (say 10 million times) and see what percentage of those times each team ends up in a certain spot of the shuffled list? ``` import random from time import sleep first = [1*['team 1']] second = [2*['team 2']] third = [4*['team 3']] fourth = [8*['team 4']] fifth = [16*['team 5']] sixth = [32*['team 6']] seventh = [64*['team 7']] eighth = [128*['team 8']] ninth = [256*['team 9']] tenth = [512*['team 10']] eleventh = [1024*['team 11']] twelfth = [2048*['team 12']] total = [] for i in first: for x in i: total.append(x) for i in second: for x in i: total.append(x) for i in third: for x in i: total.append(x) for i in fourth: for x in i: total.append(x) for i in fifth: for x in i: total.append(x) for i in sixth: for x in i: total.append(x) for i in seventh: for x in i: total.append(x) for i in eighth: for x in i: total.append(x) for i in ninth: for x in i: total.append(x) for i in tenth: for x in i: total.append(x) for i in eleventh: for x in i: total.append(x) for i in twelfth: for x in i: total.append(x) random.shuffle(total) order = [] for i in total: if i not in order: order.append(i) print('the twelfth pick goes to {}'.format(order[11])) sleep(1) print('the eleventh pick goes to {}'.format(order[10])) sleep(1) print('the tenth pick goes to {}'.format(order[9])) sleep(1) print('the ninth pick goes to {}'.format(order[8])) sleep(1) print('the eighth pick goes to {}'.format(order[7])) sleep(1) print('the seventh pick goes to {}'.format(order[6])) sleep(2) print('the sixth pick goes to {}'.format(order[5])) sleep(2) print('the fifth pick goes to {}'.format(order[4])) sleep(2) print('the fourth pick goes to {}'.format(order[3])) sleep(3) print('the third pick goes to {}'.format(order[2])) sleep(3) print('the second pick goes to {}'.format(order[1])) sleep(3) print('the first pick goes to {}'.format(order[0])) ```
2019/06/20
[ "https://Stackoverflow.com/questions/56692868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10918881/" ]
Instead of doing your sampling like this, I would use a discrete distribution for the probability of getting the team i, and sample using random.choices. We update the distribution after the sampling by discarding all the tickets from that team (since it cannot appear again). ``` from random import choices ticket_amounts = [2**i for i in range(12)] teams = [ i + 1 for i in range(12)] for i in range(12): probabilities = [count/sum(ticket_amounts) for count in ticket_amounts] team_picked = choices(teams, probabilities)[0] print("team picked is{}".format(team_picked)) # update probabilities by discarding all the tickets # belonging to picked team ticket_amounts[team_picked-1] = 0 ```
Here is what you want I think, but as the other comment said it runs very slow and I would not try 10 million times, its slow enough as is. ``` from collections import Counter for i in range(1,10000): random.shuffle(total) countList.append(total[0]) print Counter(countList) ``` add the for loop to the end of your code and the import at the top.
56,692,868
I am trying to write a mock lottery simulator as a thought excercize and for some introductory python practice, where each team would have 2x the odds of getting the first pick as the team that preceded them in the standings. The code below works (although I am sure there is a more efficient way to write it), but now I would like to figure out a way to find each individual teams odds of getting a certain draft spot based on their odds. I believe there are 12! ways for the order to be set, so it would be next to impossible to compute by hand. Is there a way to run a simulation in python (say 10 million times) and see what percentage of those times each team ends up in a certain spot of the shuffled list? ``` import random from time import sleep first = [1*['team 1']] second = [2*['team 2']] third = [4*['team 3']] fourth = [8*['team 4']] fifth = [16*['team 5']] sixth = [32*['team 6']] seventh = [64*['team 7']] eighth = [128*['team 8']] ninth = [256*['team 9']] tenth = [512*['team 10']] eleventh = [1024*['team 11']] twelfth = [2048*['team 12']] total = [] for i in first: for x in i: total.append(x) for i in second: for x in i: total.append(x) for i in third: for x in i: total.append(x) for i in fourth: for x in i: total.append(x) for i in fifth: for x in i: total.append(x) for i in sixth: for x in i: total.append(x) for i in seventh: for x in i: total.append(x) for i in eighth: for x in i: total.append(x) for i in ninth: for x in i: total.append(x) for i in tenth: for x in i: total.append(x) for i in eleventh: for x in i: total.append(x) for i in twelfth: for x in i: total.append(x) random.shuffle(total) order = [] for i in total: if i not in order: order.append(i) print('the twelfth pick goes to {}'.format(order[11])) sleep(1) print('the eleventh pick goes to {}'.format(order[10])) sleep(1) print('the tenth pick goes to {}'.format(order[9])) sleep(1) print('the ninth pick goes to {}'.format(order[8])) sleep(1) print('the eighth pick goes to {}'.format(order[7])) sleep(1) print('the seventh pick goes to {}'.format(order[6])) sleep(2) print('the sixth pick goes to {}'.format(order[5])) sleep(2) print('the fifth pick goes to {}'.format(order[4])) sleep(2) print('the fourth pick goes to {}'.format(order[3])) sleep(3) print('the third pick goes to {}'.format(order[2])) sleep(3) print('the second pick goes to {}'.format(order[1])) sleep(3) print('the first pick goes to {}'.format(order[0])) ```
2019/06/20
[ "https://Stackoverflow.com/questions/56692868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10918881/" ]
Instead of doing your sampling like this, I would use a discrete distribution for the probability of getting the team i, and sample using random.choices. We update the distribution after the sampling by discarding all the tickets from that team (since it cannot appear again). ``` from random import choices ticket_amounts = [2**i for i in range(12)] teams = [ i + 1 for i in range(12)] for i in range(12): probabilities = [count/sum(ticket_amounts) for count in ticket_amounts] team_picked = choices(teams, probabilities)[0] print("team picked is{}".format(team_picked)) # update probabilities by discarding all the tickets # belonging to picked team ticket_amounts[team_picked-1] = 0 ```
Here is a way to do it (it fast enough to run 1M time in about 15 min, so for 10 millions you would probably need to wait a few hours): ``` import numpy as np from collections import Counter n_teams = 12 n_trials = int(1e4) probs = [ 2**i for i in range(0,n_teams) ] probs = [ prob_i / sum(probs) for prob_i in probs ] lottery_results = np.zeros([n_trials, n_teams],dtype=np.int8) # to store the positions at each lottery for i in range(n_trials): lottery_results[i,:] = np.random.choice(n_teams, n_teams, replace=False, p=probs) for i in range(n_teams): positions = Counter(lottery_results[:,i]) print("Team {}".format(i), dict(sorted(positions.items()))) ```
56,533,066
I'm trying to write a request using Python Requests which sends a request to Docusign. I need to use the legacy authorization header, but unfortunately it seems most documentation for this has been removed. When I send the request I get an error as stated in the title. From research, I found that special characters in the password can cause this issue, so I've confirmed that my password has no special characters, and that my API key is correct. I am currently sending the header as a stringified dictionary as shown below. I have tried it several other ways, and this seems to be the closest, but it still results in the error. Other ways I've tried include attempting to write out the header as a single string (not forming a dictionary first), but that didn't seem to work any better. ``` docusign_auth_string = {} docusign_auth_string["Username"] = docusign_user docusign_auth_string["Password"] = docusign_password docusign_auth_string["IntegratorKey"] = docusign_key docusign_auth_string = str(docusign_auth_string) headers = {'X-DocuSign-Authentication': docusign_auth_string} response = requests.post(docusign_url, headers=headers, data=body_data) ``` The above code returns a 401 with the message, INVALID\_TOKEN\_FORMAT "The security token format does not conform to expected schema." The header I am sending looks as follows: {'X-DocuSign-Authentication': "{'Username': 'test@test.com', 'Password': 'xxxxxxxxxx', 'IntegratorKey': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'}"} When I send the request via Postman, it works just fine. In Postman I enter the header name as X-Docusign-Authentication, and the value as: {"Username":"{{ds\_username}}","Password":"{{ds\_password}}","IntegratorKey":"{{ds\_integrator\_key}}"} (subbing the same variable values as in the python code). Therefore it definitely has something to do with the way Requests is sending the header. Does anyone know why I might be getting the above error?
2019/06/10
[ "https://Stackoverflow.com/questions/56533066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6490748/" ]
I'm able to reproduce this behavior: It looks like DocuSign doesn't accept Single Quotes around the sub-parameters of the x-DocuSign-Authentication header value. Your example fails: ``` {'Username': 'test@test.com', 'Password': 'xxxxxxxxxx', 'IntegratorKey': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'} ``` This has more success: ``` {"Username": "test@test.com", "Password": "xxxxxxxxxx", "IntegratorKey": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"} ``` I'm not familiar enough with Python to advise if there's a different code structure you can follow to use double quotes instead of single. Worst case scenario, you may need to manually set the Header Value to follow that format.
Since you are having success using Postman, it will help to get exactly what is being sent via your request. For this use: ```py response = requests.get(your_url, headers=your_headers) x = response.request.headers() print(x) ``` This will show you exactly what requests is preparing and sending off. If you post that response here id be happy to help more. [How can I see the entire HTTP request that's being sent by my Python application?](https://stackoverflow.com/questions/10588644/how-can-i-see-the-entire-http-request-thats-being-sent-by-my-python-application) The 2nd answer shows all the possible parameters of your response object.
56,533,066
I'm trying to write a request using Python Requests which sends a request to Docusign. I need to use the legacy authorization header, but unfortunately it seems most documentation for this has been removed. When I send the request I get an error as stated in the title. From research, I found that special characters in the password can cause this issue, so I've confirmed that my password has no special characters, and that my API key is correct. I am currently sending the header as a stringified dictionary as shown below. I have tried it several other ways, and this seems to be the closest, but it still results in the error. Other ways I've tried include attempting to write out the header as a single string (not forming a dictionary first), but that didn't seem to work any better. ``` docusign_auth_string = {} docusign_auth_string["Username"] = docusign_user docusign_auth_string["Password"] = docusign_password docusign_auth_string["IntegratorKey"] = docusign_key docusign_auth_string = str(docusign_auth_string) headers = {'X-DocuSign-Authentication': docusign_auth_string} response = requests.post(docusign_url, headers=headers, data=body_data) ``` The above code returns a 401 with the message, INVALID\_TOKEN\_FORMAT "The security token format does not conform to expected schema." The header I am sending looks as follows: {'X-DocuSign-Authentication': "{'Username': 'test@test.com', 'Password': 'xxxxxxxxxx', 'IntegratorKey': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'}"} When I send the request via Postman, it works just fine. In Postman I enter the header name as X-Docusign-Authentication, and the value as: {"Username":"{{ds\_username}}","Password":"{{ds\_password}}","IntegratorKey":"{{ds\_integrator\_key}}"} (subbing the same variable values as in the python code). Therefore it definitely has something to do with the way Requests is sending the header. Does anyone know why I might be getting the above error?
2019/06/10
[ "https://Stackoverflow.com/questions/56533066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6490748/" ]
I found a solution to this issue. The response that mentioned double quotes is correct, but in Python I was unable to send a string with the proper format for docusign to understand. Next I found the following Stack overflow question, which ultimately provided the solution: [How to send dict in Header as value to key 'Authorization' in python requests?](https://stackoverflow.com/questions/47326876/how-to-send-dict-in-header-as-value-to-key-authorization-in-python-requests) I used json.dumps and that resolved the issue. My code is as follows: ``` docusign_auth_string = {} docusign_auth_string["Username"] = docusign_user docusign_auth_string["Password"] = docusign_password docusign_auth_string["IntegratorKey"] = docusign_key headers = {"X-DocuSign-Authentication": json.dumps(docusign_auth_string), "Content-Type": "application/json"} ```
Since you are having success using Postman, it will help to get exactly what is being sent via your request. For this use: ```py response = requests.get(your_url, headers=your_headers) x = response.request.headers() print(x) ``` This will show you exactly what requests is preparing and sending off. If you post that response here id be happy to help more. [How can I see the entire HTTP request that's being sent by my Python application?](https://stackoverflow.com/questions/10588644/how-can-i-see-the-entire-http-request-thats-being-sent-by-my-python-application) The 2nd answer shows all the possible parameters of your response object.
18,139,910
I want to save an ID between requests, using Flask `session` cookie, but I'm getting an `Internal Server Error` as result, when I perform a request. I prototyped a simple Flask app for demonstrating my problem: ``` #!/usr/bin/env python from flask import Flask, session app = Flask(__name__) @app.route('/') def run(): session['tmp'] = 43 return '43' if __name__ == '__main__': app.run() ``` Why I can't store the `session` cookie with the following value when I perform the request?
2013/08/09
[ "https://Stackoverflow.com/questions/18139910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2236401/" ]
According to [Flask sessions documentation](http://flask.pocoo.org/docs/quickstart/#sessions): > > ... > What this means is that the user could look at the contents of your > cookie but not modify it, unless they know the secret key used for > signing. > > > In order to use sessions you **have to set a secret key**. > > > Set *secret key*. And you should return string, not int. ``` #!/usr/bin/env python from flask import Flask, session app = Flask(__name__) @app.route('/') def run(): session['tmp'] = 43 return '43' if __name__ == '__main__': app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' app.run() ```
Under `app = Flask(__name__)` place this: `app.secret_key = os.urandom(24)`.
18,139,910
I want to save an ID between requests, using Flask `session` cookie, but I'm getting an `Internal Server Error` as result, when I perform a request. I prototyped a simple Flask app for demonstrating my problem: ``` #!/usr/bin/env python from flask import Flask, session app = Flask(__name__) @app.route('/') def run(): session['tmp'] = 43 return '43' if __name__ == '__main__': app.run() ``` Why I can't store the `session` cookie with the following value when I perform the request?
2013/08/09
[ "https://Stackoverflow.com/questions/18139910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2236401/" ]
According to [Flask sessions documentation](http://flask.pocoo.org/docs/quickstart/#sessions): > > ... > What this means is that the user could look at the contents of your > cookie but not modify it, unless they know the secret key used for > signing. > > > In order to use sessions you **have to set a secret key**. > > > Set *secret key*. And you should return string, not int. ``` #!/usr/bin/env python from flask import Flask, session app = Flask(__name__) @app.route('/') def run(): session['tmp'] = 43 return '43' if __name__ == '__main__': app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' app.run() ```
As **@falsetru** mentioned, you have to set a secret key. Before sending the `session` cookie to the user's browser, Flask signs the cookies cryptographically, and that doesn't mean that you cannot decode the cookie. I presume that Flask keeps track of the signed cookies, so it can perform it's own 'magic', in order to determine if the cookie that was sent along with the request (request headers), is a valid cookie or not. Some methods that you may use, all related with Flask class instance, generally defined as `app`: * defining the `secret_key` variable for `app` object ``` app.secret_key = b'6hc/_gsh,./;2ZZx3c6_s,1//' ``` * using the `config()` method ``` app.config['SECRET_KEY'] = b'6hc/_gsh,./;2ZZx3c6_s,1//' ``` * using an external configuration file for the entire Flask application ``` $ grep pyfile app.py app.config.from_pyfile('flask_settings.cfg') $ cat flask_settings.py SECRET_KEY = b'6hc/_gsh,./;2ZZx3c6_s,1//' ``` Here's an example (an adaptation from [this article](https://overiq.com/flask/0.12/sessions-in-flask/)), focused on providing a more clearer picture of Flask `session` cookie, considering the participation of both Client and Server sides: ``` from flask import Flask, request, session import os app = Flask(__name__) @app.route('/') def f_index(): # Request Headers, sent on every request print("\n\n\n[Client-side]\n", request.headers) if 'visits' in session: # getting value from session dict (Server-side) and incrementing by 1 session['visits'] = session.get('visits') + 1 else: # first visit, generates the key/value pair {"visits":1} session['visits'] = 1 # 'session' cookie tracked from every request sent print("[Server-side]\n", session) return "Total visits:{0}".format(session.get('visits')) if __name__ == "__main__": app.secret_key = os.urandom(24) app.run() ``` Here's the output: ``` $ python3 sessions.py * Serving Flask app "sessions" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) [Client-side] Upgrade-Insecure-Requests: 1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Connection: keep-alive Host: 127.0.0.1:5000 User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.5 [Server-side] <SecureCookieSession {'visits': 1}> 127.0.0.1 - - [12/Oct/2018 14:27:05] "GET / HTTP/1.1" 200 - [Client-side] Upgrade-Insecure-Requests: 1 Cookie: session=eyJ2aXNpdHMiOjF9.DqKHCQ.MSZ7J-Zicehb6rr8qw43dCVXVNA # <--- session cookie Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Connection: keep-alive Host: 127.0.0.1:5000 User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.5 [Server-side] <SecureCookieSession {'visits': 2}> 127.0.0.1 - - [12/Oct/2018 14:27:14] "GET / HTTP/1.1" 200 - ``` --- You may have noticed that in the example above, I'm using the `os` lib and the `urandom()` function, in order to generate Flask's secret key, right? From [the official doc](http://flask.pocoo.org/docs/1.0/quickstart/#sessions): > > **How to generate good secret keys** > > > A secret key should be as random as possible. Your operating system has ways to generate pretty random data based on a cryptographic random generator. Use the following command to quickly generate a value for Flask.secret\_key (or SECRET\_KEY): > > > $ python -c 'import os; print(os.urandom(16))' > > > b'\_5#y2L"F4Q8z\n\xec]/' > > > --- **PLUS NOTE** > > As you can see, the creators of Flask support the practice of using `os.urandom()` for building the Flask secret key, from older versions of the tool to its latest version. So: why **@joshlsullivan's** answer received downvotes (deserves an upvote) and why **@MikhailKashkin** writes that, using `os.urandom()` is terrible idea, are mysteries. > > >
18,139,910
I want to save an ID between requests, using Flask `session` cookie, but I'm getting an `Internal Server Error` as result, when I perform a request. I prototyped a simple Flask app for demonstrating my problem: ``` #!/usr/bin/env python from flask import Flask, session app = Flask(__name__) @app.route('/') def run(): session['tmp'] = 43 return '43' if __name__ == '__main__': app.run() ``` Why I can't store the `session` cookie with the following value when I perform the request?
2013/08/09
[ "https://Stackoverflow.com/questions/18139910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2236401/" ]
As **@falsetru** mentioned, you have to set a secret key. Before sending the `session` cookie to the user's browser, Flask signs the cookies cryptographically, and that doesn't mean that you cannot decode the cookie. I presume that Flask keeps track of the signed cookies, so it can perform it's own 'magic', in order to determine if the cookie that was sent along with the request (request headers), is a valid cookie or not. Some methods that you may use, all related with Flask class instance, generally defined as `app`: * defining the `secret_key` variable for `app` object ``` app.secret_key = b'6hc/_gsh,./;2ZZx3c6_s,1//' ``` * using the `config()` method ``` app.config['SECRET_KEY'] = b'6hc/_gsh,./;2ZZx3c6_s,1//' ``` * using an external configuration file for the entire Flask application ``` $ grep pyfile app.py app.config.from_pyfile('flask_settings.cfg') $ cat flask_settings.py SECRET_KEY = b'6hc/_gsh,./;2ZZx3c6_s,1//' ``` Here's an example (an adaptation from [this article](https://overiq.com/flask/0.12/sessions-in-flask/)), focused on providing a more clearer picture of Flask `session` cookie, considering the participation of both Client and Server sides: ``` from flask import Flask, request, session import os app = Flask(__name__) @app.route('/') def f_index(): # Request Headers, sent on every request print("\n\n\n[Client-side]\n", request.headers) if 'visits' in session: # getting value from session dict (Server-side) and incrementing by 1 session['visits'] = session.get('visits') + 1 else: # first visit, generates the key/value pair {"visits":1} session['visits'] = 1 # 'session' cookie tracked from every request sent print("[Server-side]\n", session) return "Total visits:{0}".format(session.get('visits')) if __name__ == "__main__": app.secret_key = os.urandom(24) app.run() ``` Here's the output: ``` $ python3 sessions.py * Serving Flask app "sessions" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) [Client-side] Upgrade-Insecure-Requests: 1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Connection: keep-alive Host: 127.0.0.1:5000 User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.5 [Server-side] <SecureCookieSession {'visits': 1}> 127.0.0.1 - - [12/Oct/2018 14:27:05] "GET / HTTP/1.1" 200 - [Client-side] Upgrade-Insecure-Requests: 1 Cookie: session=eyJ2aXNpdHMiOjF9.DqKHCQ.MSZ7J-Zicehb6rr8qw43dCVXVNA # <--- session cookie Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Connection: keep-alive Host: 127.0.0.1:5000 User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.5 [Server-side] <SecureCookieSession {'visits': 2}> 127.0.0.1 - - [12/Oct/2018 14:27:14] "GET / HTTP/1.1" 200 - ``` --- You may have noticed that in the example above, I'm using the `os` lib and the `urandom()` function, in order to generate Flask's secret key, right? From [the official doc](http://flask.pocoo.org/docs/1.0/quickstart/#sessions): > > **How to generate good secret keys** > > > A secret key should be as random as possible. Your operating system has ways to generate pretty random data based on a cryptographic random generator. Use the following command to quickly generate a value for Flask.secret\_key (or SECRET\_KEY): > > > $ python -c 'import os; print(os.urandom(16))' > > > b'\_5#y2L"F4Q8z\n\xec]/' > > > --- **PLUS NOTE** > > As you can see, the creators of Flask support the practice of using `os.urandom()` for building the Flask secret key, from older versions of the tool to its latest version. So: why **@joshlsullivan's** answer received downvotes (deserves an upvote) and why **@MikhailKashkin** writes that, using `os.urandom()` is terrible idea, are mysteries. > > >
Under `app = Flask(__name__)` place this: `app.secret_key = os.urandom(24)`.
52,113,440
Looking for data splitter line by line, by using python * RegEx? * Contain? As example file "file" contain: ``` X X Y Z Z Z ``` I need the clean way to split this file into 3 different ones, based on letter **As a sample:** ``` def split_by_platform(FILE_NAME): with open(FILE_NAME, "r+") as infile: Data = infile.read() If the file contains "X" write to x.txt If the file contains "Y" write to y.txt If the file contains "Z" write to z.txt ``` **x.txt** file will look like: ``` X X ``` **y.txt** file will look like: ``` Y ``` **z.txt** file will look like: ``` Z Z Z ```
2018/08/31
[ "https://Stackoverflow.com/questions/52113440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
EDIT thanks to @bruno desthuilliers, who reminded me of the correct way to go here: Iterate over the file object (not 'readlines'): ``` def split_by_platform(FILE_NAME, out1, out2, out3): with open(FILE_NAME, "r") as infile, open(out1, 'a') as of1, open(out2, 'a') as of2, open(out3, 'a') as of3: for line in infile: if "X" in line: of1.write(line) elif "Y" in line: of2.write(line) elif "Z" in line: of3.write(line) ``` EDIT on a hint of @dim: Here the more general approach for an arbitrary length list of flag chars: ``` def loop(infilename, flag_chars): with open(infilename, 'r') as infile: for line in infile: for c in flag_chars: if c in line: with open(c+'.txt', 'a') as outfile: outfile.write(line) ```
This should do it: ``` with open('my_text_file.txt') as infile, open('x.txt', 'w') as x, open('y.txt', 'w') as y, open('z.txt', 'w') as z: for line in infile: if line.startswith('X'): x.write(line) elif line.startswith('Y'): y.write(line) elif line.startswith('Z'): z.write(line) ```
52,113,440
Looking for data splitter line by line, by using python * RegEx? * Contain? As example file "file" contain: ``` X X Y Z Z Z ``` I need the clean way to split this file into 3 different ones, based on letter **As a sample:** ``` def split_by_platform(FILE_NAME): with open(FILE_NAME, "r+") as infile: Data = infile.read() If the file contains "X" write to x.txt If the file contains "Y" write to y.txt If the file contains "Z" write to z.txt ``` **x.txt** file will look like: ``` X X ``` **y.txt** file will look like: ``` Y ``` **z.txt** file will look like: ``` Z Z Z ```
2018/08/31
[ "https://Stackoverflow.com/questions/52113440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
EDIT thanks to @bruno desthuilliers, who reminded me of the correct way to go here: Iterate over the file object (not 'readlines'): ``` def split_by_platform(FILE_NAME, out1, out2, out3): with open(FILE_NAME, "r") as infile, open(out1, 'a') as of1, open(out2, 'a') as of2, open(out3, 'a') as of3: for line in infile: if "X" in line: of1.write(line) elif "Y" in line: of2.write(line) elif "Z" in line: of3.write(line) ``` EDIT on a hint of @dim: Here the more general approach for an arbitrary length list of flag chars: ``` def loop(infilename, flag_chars): with open(infilename, 'r') as infile: for line in infile: for c in flag_chars: if c in line: with open(c+'.txt', 'a') as outfile: outfile.write(line) ```
Here is a more generic way to do the same job: ``` from collections import Counter with open("file.txt", "r+") as file: data = file.read().splitlines() counter = Counter(data) array2d = [[key, ] * value for key, value in counter.items()] print array2d # [['Y'], ['X', 'X'], ['Z', 'Z', 'Z']] for el in array2d: with open(str(el[0]) + ".txt", "w") as f: [f.write(e + "\n") for e in el] ``` The above code will generate `X.txt`, `Y.txt` and `Z.txt` with the corresponding values. If you have for example several `C` letters the code will generate a file `C.txt`.
54,721,703
I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command: ``` python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ``` I get this result: ``` ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' ImportError: numpy.core.multiarray failed to import The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 980, in _find_and_load SystemError: <class '_frozen_importlib._ModuleLockManager'> returned a result with an error set ImportError: numpy.core._multiarray_umath failed to import ImportError: numpy.core.umath failed to import 2019-02-16 12:56:50.178364: F tensorflow/python/lib/core/bfloat16.cc:675] Check failed: PyBfloat16_Type.tp_base != nullptr ``` I have already installed `numpy` as you can see: ``` pip3 install numpy Requirement already satisfied: numpy in c:\programdata\anaconda3\lib\site-packages (1.15.4) ``` So why do I get this error message and how can I fix it on Windows 10?
2019/02/16
[ "https://Stackoverflow.com/questions/54721703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3486308/" ]
Upgrade the numpy to solve the error ``` pip install numpy --upgrade ```
ensure that you're using python 3.x by running it as ```py python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ```
54,721,703
I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command: ``` python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ``` I get this result: ``` ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' ImportError: numpy.core.multiarray failed to import The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 980, in _find_and_load SystemError: <class '_frozen_importlib._ModuleLockManager'> returned a result with an error set ImportError: numpy.core._multiarray_umath failed to import ImportError: numpy.core.umath failed to import 2019-02-16 12:56:50.178364: F tensorflow/python/lib/core/bfloat16.cc:675] Check failed: PyBfloat16_Type.tp_base != nullptr ``` I have already installed `numpy` as you can see: ``` pip3 install numpy Requirement already satisfied: numpy in c:\programdata\anaconda3\lib\site-packages (1.15.4) ``` So why do I get this error message and how can I fix it on Windows 10?
2019/02/16
[ "https://Stackoverflow.com/questions/54721703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3486308/" ]
I upgraded `numpy` to `1.16.1` version and tried again the above command: ``` python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ``` and got this new result: ``` 2019-02-16 13:12:40.611105: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 tf.Tensor(-1714.2305, shape=(), dtype=float32) ```
I just upgraded my numpy from 1.14.0 to 1.17.0 by the following command on Ubuntu 18.10. > > sudo python3.5 -m pip install numpy --upgrade > > > No import error then.
54,721,703
I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command: ``` python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ``` I get this result: ``` ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' ImportError: numpy.core.multiarray failed to import The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 980, in _find_and_load SystemError: <class '_frozen_importlib._ModuleLockManager'> returned a result with an error set ImportError: numpy.core._multiarray_umath failed to import ImportError: numpy.core.umath failed to import 2019-02-16 12:56:50.178364: F tensorflow/python/lib/core/bfloat16.cc:675] Check failed: PyBfloat16_Type.tp_base != nullptr ``` I have already installed `numpy` as you can see: ``` pip3 install numpy Requirement already satisfied: numpy in c:\programdata\anaconda3\lib\site-packages (1.15.4) ``` So why do I get this error message and how can I fix it on Windows 10?
2019/02/16
[ "https://Stackoverflow.com/questions/54721703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3486308/" ]
You need to force the upgrade numpy to the latest version. ``` pip install 'numpy==1.16' --force-reinstall ``` Hope this helps.
ensure that you're using python 3.x by running it as ```py python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ```
54,721,703
I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command: ``` python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ``` I get this result: ``` ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' ImportError: numpy.core.multiarray failed to import The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 980, in _find_and_load SystemError: <class '_frozen_importlib._ModuleLockManager'> returned a result with an error set ImportError: numpy.core._multiarray_umath failed to import ImportError: numpy.core.umath failed to import 2019-02-16 12:56:50.178364: F tensorflow/python/lib/core/bfloat16.cc:675] Check failed: PyBfloat16_Type.tp_base != nullptr ``` I have already installed `numpy` as you can see: ``` pip3 install numpy Requirement already satisfied: numpy in c:\programdata\anaconda3\lib\site-packages (1.15.4) ``` So why do I get this error message and how can I fix it on Windows 10?
2019/02/16
[ "https://Stackoverflow.com/questions/54721703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3486308/" ]
Try this: pip install --upgrade --force-reinstall numpy
ensure that you're using python 3.x by running it as ```py python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ```
54,721,703
I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command: ``` python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ``` I get this result: ``` ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' ImportError: numpy.core.multiarray failed to import The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 980, in _find_and_load SystemError: <class '_frozen_importlib._ModuleLockManager'> returned a result with an error set ImportError: numpy.core._multiarray_umath failed to import ImportError: numpy.core.umath failed to import 2019-02-16 12:56:50.178364: F tensorflow/python/lib/core/bfloat16.cc:675] Check failed: PyBfloat16_Type.tp_base != nullptr ``` I have already installed `numpy` as you can see: ``` pip3 install numpy Requirement already satisfied: numpy in c:\programdata\anaconda3\lib\site-packages (1.15.4) ``` So why do I get this error message and how can I fix it on Windows 10?
2019/02/16
[ "https://Stackoverflow.com/questions/54721703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3486308/" ]
I upgraded `numpy` to `1.16.1` version and tried again the above command: ``` python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ``` and got this new result: ``` 2019-02-16 13:12:40.611105: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 tf.Tensor(-1714.2305, shape=(), dtype=float32) ```
ensure that you're using python 3.x by running it as ```py python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ```
54,721,703
I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command: ``` python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ``` I get this result: ``` ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' ImportError: numpy.core.multiarray failed to import The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 980, in _find_and_load SystemError: <class '_frozen_importlib._ModuleLockManager'> returned a result with an error set ImportError: numpy.core._multiarray_umath failed to import ImportError: numpy.core.umath failed to import 2019-02-16 12:56:50.178364: F tensorflow/python/lib/core/bfloat16.cc:675] Check failed: PyBfloat16_Type.tp_base != nullptr ``` I have already installed `numpy` as you can see: ``` pip3 install numpy Requirement already satisfied: numpy in c:\programdata\anaconda3\lib\site-packages (1.15.4) ``` So why do I get this error message and how can I fix it on Windows 10?
2019/02/16
[ "https://Stackoverflow.com/questions/54721703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3486308/" ]
Upgrade the numpy to solve the error ``` pip install numpy --upgrade ```
I just upgraded my numpy from 1.14.0 to 1.17.0 by the following command on Ubuntu 18.10. > > sudo python3.5 -m pip install numpy --upgrade > > > No import error then.
54,721,703
I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command: ``` python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ``` I get this result: ``` ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' ImportError: numpy.core.multiarray failed to import The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 980, in _find_and_load SystemError: <class '_frozen_importlib._ModuleLockManager'> returned a result with an error set ImportError: numpy.core._multiarray_umath failed to import ImportError: numpy.core.umath failed to import 2019-02-16 12:56:50.178364: F tensorflow/python/lib/core/bfloat16.cc:675] Check failed: PyBfloat16_Type.tp_base != nullptr ``` I have already installed `numpy` as you can see: ``` pip3 install numpy Requirement already satisfied: numpy in c:\programdata\anaconda3\lib\site-packages (1.15.4) ``` So why do I get this error message and how can I fix it on Windows 10?
2019/02/16
[ "https://Stackoverflow.com/questions/54721703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3486308/" ]
Try this: pip install --upgrade --force-reinstall numpy
I just upgraded my numpy from 1.14.0 to 1.17.0 by the following command on Ubuntu 18.10. > > sudo python3.5 -m pip install numpy --upgrade > > > No import error then.
54,721,703
I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command: ``` python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ``` I get this result: ``` ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' ImportError: numpy.core.multiarray failed to import The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 980, in _find_and_load SystemError: <class '_frozen_importlib._ModuleLockManager'> returned a result with an error set ImportError: numpy.core._multiarray_umath failed to import ImportError: numpy.core.umath failed to import 2019-02-16 12:56:50.178364: F tensorflow/python/lib/core/bfloat16.cc:675] Check failed: PyBfloat16_Type.tp_base != nullptr ``` I have already installed `numpy` as you can see: ``` pip3 install numpy Requirement already satisfied: numpy in c:\programdata\anaconda3\lib\site-packages (1.15.4) ``` So why do I get this error message and how can I fix it on Windows 10?
2019/02/16
[ "https://Stackoverflow.com/questions/54721703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3486308/" ]
I upgraded `numpy` to `1.16.1` version and tried again the above command: ``` python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ``` and got this new result: ``` 2019-02-16 13:12:40.611105: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 tf.Tensor(-1714.2305, shape=(), dtype=float32) ```
Upgrade the numpy to solve the error ``` pip install numpy --upgrade ```
54,721,703
I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command: ``` python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ``` I get this result: ``` ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' ImportError: numpy.core.multiarray failed to import The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 980, in _find_and_load SystemError: <class '_frozen_importlib._ModuleLockManager'> returned a result with an error set ImportError: numpy.core._multiarray_umath failed to import ImportError: numpy.core.umath failed to import 2019-02-16 12:56:50.178364: F tensorflow/python/lib/core/bfloat16.cc:675] Check failed: PyBfloat16_Type.tp_base != nullptr ``` I have already installed `numpy` as you can see: ``` pip3 install numpy Requirement already satisfied: numpy in c:\programdata\anaconda3\lib\site-packages (1.15.4) ``` So why do I get this error message and how can I fix it on Windows 10?
2019/02/16
[ "https://Stackoverflow.com/questions/54721703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3486308/" ]
I was having numpy `1.16.2` version but it was giving same error then i tried to install `1.16.1` and it worked for me.
ensure that you're using python 3.x by running it as ```py python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ```
54,721,703
I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command: ``` python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))" ``` I get this result: ``` ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' ImportError: numpy.core.multiarray failed to import The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 980, in _find_and_load SystemError: <class '_frozen_importlib._ModuleLockManager'> returned a result with an error set ImportError: numpy.core._multiarray_umath failed to import ImportError: numpy.core.umath failed to import 2019-02-16 12:56:50.178364: F tensorflow/python/lib/core/bfloat16.cc:675] Check failed: PyBfloat16_Type.tp_base != nullptr ``` I have already installed `numpy` as you can see: ``` pip3 install numpy Requirement already satisfied: numpy in c:\programdata\anaconda3\lib\site-packages (1.15.4) ``` So why do I get this error message and how can I fix it on Windows 10?
2019/02/16
[ "https://Stackoverflow.com/questions/54721703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3486308/" ]
Upgrade the numpy to solve the error ``` pip install numpy --upgrade ```
I was having numpy `1.16.2` version but it was giving same error then i tried to install `1.16.1` and it worked for me.
69,837,913
I am trying to unpickle a file but i get this error while running the following code: ``` import pickle import pandas as pd import numpy unpickled_df = pd.read_pickle("./ToyData.pickle") unpickled_df ``` or ``` import pickle # load : get the data from file data = pickle.load(open('ToyData.pickle', "rb")) ``` error output: --- ``` AttributeError Traceback (most recent call last) <ipython-input-3-4f30cc427816> in <module> 1 import pickle 2 # load : get the data from file ----> 3 data = pickle.load(open('ToyData.pickle', "rb")) 4 # loads : get the data from var 5 #data = pickle.load(var) AttributeError: Can't get attribute 'PandasIndexAdapter' on <module 'xarray.core.indexing' from 'C:\\Users\\User\\anaconda3\\lib\\site-packages\\xarray\\core\\indexing.py'> ``` How can i solve this. I have tried to install xarray, dask and other xarray dependancies using the code below: ``` python -m pip install "xarray[complete]" python -m pip install "xarray[io]" # Install optional dependencies for handling I/O #python -m pip install "xarray[accel]" # Install optional dependencies for accelerating xarray #python -m pip install "xarray[parallel]" # Install optional dependencies for dask arrays #python -m pip install "xarray[viz]" # Install optional dependencies for visualization conda install xarray-0.16.1-py_0 ``` I used anaconda jupyter notebook to run the script above. I am unable to read the pickle file.
2021/11/04
[ "https://Stackoverflow.com/questions/69837913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17326771/" ]
You cannot pickle.load files in a newly updated version of xarray that were made in a previous version of xarray. This is a known error that has no solution as "pickling is not recommended for long-term storage". <https://github.com/pydata/xarray/discussions/5642> .hdf or .json are better alternatives for long-term storage of your data since those are more likely to be supported in future versions.
I had the same problem with `results = torch.load("results.pth.tar")` and get "`AttributeError: Can't get attribute 'PandasIndexAdapter' on <module 'xarray.core.indexing'`". I solve it by changing the version I have on my computer by the version the file.pth.tar was saved with. In my case the file was saved with xarray version '0.14.1' and on my compter I had '2022.3.0'. I change with `pip install xarray==0.14.1` and it works ! If you are able to find the version "ToyData.pickle" is saved with install this version in the environment of your notebook. Otherwise you can try with every single version of xarray (good luck) ! I hope it can help !
68,964,555
I don't know why I am getting this error, the official document reference <https://scikit-learn.org/stable/modules/generated/sklearn.metrics.det_curve.html#sklearn.metrics.det_curve> **Code:** ``` import numpy as np from sklearn.metrics import det_curve fpr, fnr, thresholds = det_curve(y_test, y_pred) print(fpr, fnr, thresholds) ``` **Error:** ``` --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-46-d8d6f0b546ca> in <module>() 10 11 import numpy as np ---> 12 from sklearn.metrics import det_curve 13 14 fpr, fnr, thresholds = det_curve(y_test['cEXT'], y_pred) ImportError: cannot import name 'det_curve' from 'sklearn.metrics' (/usr/local/lib/python3.7/dist-packages/sklearn/metrics/__init__.py) --------------------------------------------------------------------------- NOTE: If your import is failing due to a missing package, you can manually install dependencies using either !pip or !apt. To view examples of installing some common dependencies, click the "Open Examples" button below. --------------------------------------------------------------------------- ```
2021/08/28
[ "https://Stackoverflow.com/questions/68964555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1385107/" ]
Looks like some issue with a missing package. Try the following: ``` pip uninstall -v scikit-learn pip install -v scikit-learn ``` This might install the related dependencies along with it.
Same kind of problem happened to me in my Jupyter notebook. I uninstall and re-install both scikit-learn and imblearn. It didn't work. Then **restarting the kernel** and running again solved the problem.
36,314,411
Given a file with resolution-compressed binary data, I would like to convert the sub-byte bits into their integer representations in python. By this I mean I need to interpret `n` bits from a file as an integer. Currently I am reading the file into `bitarray` objects, and am converting subsets of the objects into integers. The process works but is fairly slow and cumbersome. Is there a better way to do this, perhaps with the `struct` module? ``` import bitarray bits = bitarray.bitarray() with open('/dir/to/any/file.dat','r') as f: bits.fromfile(f,2) # read 2 bytes into the bitarray ## bits 0:4 represent a field field1 = int(bits[0:4].to01(), 2) # Converts to a string of 0s and 1s, then int()s the string ## bits 5:7 represent a field field2 = int(bits[4:7].to01(), 2) ## bits 8:16 represent a field field3 = int(bits[7:16].to01(), 2) print """All bits: {bits}\n\tfield1: {b1}={field1}\n\tfield2: {b2}={field2}\n\tfield3: {b3}={field3}""".format( bits=bits, b1=bits[0:4].to01(), field1=field1, b2=bits[4:7].to01(), field2=field2, b3=bits[7:16].to01(), field3=field3) ``` Outputs: ``` All bits: bitarray('0000100110000000') field1: 0000=0 field2: 100=4 field3: 110000000=384 ```
2016/03/30
[ "https://Stackoverflow.com/questions/36314411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1176806/" ]
The whole solution :) Only javascript section is modified. ``` <div id="divCountries" class="fieldRow"> <div class="leftLabel labelWidth20"> <label for="txtcountries">Country:</label> </div> <div class="LeftField"> <div class="formField34"> <select id="txtCountries" type="text" name="Countries" alt="Countries" title="Countries" onchange="disableState()"> <option value=""></option> <option value="Afghanistan">Afghanistan</option> <option value="Albania">Albania</option> <option value="Algeria">Algeria</option> <option value="UnitedStates">United States</option> </select> </div> </div> <div class="leftLabel labelWidth20"> <label for="txtCustomerStates">State (USA):</label> </div> <div class="LeftField"> <div class="formField40"> <select id="txtCustomerStates" type="text" name="State" alt="United States" title="United States"> <option value=""></option> <option value="Alabama">Alabama</option> <option value="Alaska">Alaska</option> <option value="American Samoa">American Samoa</option> <option value="Arizona">Arizona</option> <option value="Arkansas">Arkansas</option> </select> </div> </div> <div id="divCityProvince" class="fieldRow"> <div class="leftLabel labelWidth20"> <label for="txtCityProvince">City/Province/Town<br>(International): </label> </div> <div class="formField34"> <input id="txtCityProvince" type="text" class="textfield" alt="City/Province/Town (International)" title="City/Province/Town (International)"> </div> </div> <script> function disableState() { if (document.getElementById("txtCountries").value === "UnitedStates") { document.getElementById("txtCustomerStates").disabled=false; document.getElementById("txtCityProvince").disabled='true'; } else { document.getElementById("txtCityProvince").disabled=false; document.getElementById("txtCustomerStates").disabled='true'; } } </script> ```
See this [fiddle](https://jsfiddle.net/lalu050/Lcu4jp91/) --------------------------------------------------------- That was because the value that was returned from `document.getElementById("txtCountries").value` was `UnitedStates` and not `United States`. Please note that the option for United States was as follows ``` <option value="UnitedStates">United States</option> ``` Notice that there is no space between the `United` and `States` in the value. **JS** ``` function disableState() { if (document.getElementById("txtCountries").value === "UnitedStates") { document.getElementById("txtCityProvince").disabled = 'true'; } else { document.getElementById("txtCustomerStates").disabled = 'true'; } } ```
36,314,411
Given a file with resolution-compressed binary data, I would like to convert the sub-byte bits into their integer representations in python. By this I mean I need to interpret `n` bits from a file as an integer. Currently I am reading the file into `bitarray` objects, and am converting subsets of the objects into integers. The process works but is fairly slow and cumbersome. Is there a better way to do this, perhaps with the `struct` module? ``` import bitarray bits = bitarray.bitarray() with open('/dir/to/any/file.dat','r') as f: bits.fromfile(f,2) # read 2 bytes into the bitarray ## bits 0:4 represent a field field1 = int(bits[0:4].to01(), 2) # Converts to a string of 0s and 1s, then int()s the string ## bits 5:7 represent a field field2 = int(bits[4:7].to01(), 2) ## bits 8:16 represent a field field3 = int(bits[7:16].to01(), 2) print """All bits: {bits}\n\tfield1: {b1}={field1}\n\tfield2: {b2}={field2}\n\tfield3: {b3}={field3}""".format( bits=bits, b1=bits[0:4].to01(), field1=field1, b2=bits[4:7].to01(), field2=field2, b3=bits[7:16].to01(), field3=field3) ``` Outputs: ``` All bits: bitarray('0000100110000000') field1: 0000=0 field2: 100=4 field3: 110000000=384 ```
2016/03/30
[ "https://Stackoverflow.com/questions/36314411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1176806/" ]
The whole solution :) Only javascript section is modified. ``` <div id="divCountries" class="fieldRow"> <div class="leftLabel labelWidth20"> <label for="txtcountries">Country:</label> </div> <div class="LeftField"> <div class="formField34"> <select id="txtCountries" type="text" name="Countries" alt="Countries" title="Countries" onchange="disableState()"> <option value=""></option> <option value="Afghanistan">Afghanistan</option> <option value="Albania">Albania</option> <option value="Algeria">Algeria</option> <option value="UnitedStates">United States</option> </select> </div> </div> <div class="leftLabel labelWidth20"> <label for="txtCustomerStates">State (USA):</label> </div> <div class="LeftField"> <div class="formField40"> <select id="txtCustomerStates" type="text" name="State" alt="United States" title="United States"> <option value=""></option> <option value="Alabama">Alabama</option> <option value="Alaska">Alaska</option> <option value="American Samoa">American Samoa</option> <option value="Arizona">Arizona</option> <option value="Arkansas">Arkansas</option> </select> </div> </div> <div id="divCityProvince" class="fieldRow"> <div class="leftLabel labelWidth20"> <label for="txtCityProvince">City/Province/Town<br>(International): </label> </div> <div class="formField34"> <input id="txtCityProvince" type="text" class="textfield" alt="City/Province/Town (International)" title="City/Province/Town (International)"> </div> </div> <script> function disableState() { if (document.getElementById("txtCountries").value === "UnitedStates") { document.getElementById("txtCustomerStates").disabled=false; document.getElementById("txtCityProvince").disabled='true'; } else { document.getElementById("txtCityProvince").disabled=false; document.getElementById("txtCustomerStates").disabled='true'; } } </script> ```
Try this ;) Put a space in `value="UnitedStates"`: ``` <option value="United States">United States</option> ```
59,307,832
I'm slowly trying to get my head around classes. I have a few working examples which i kinda understand but can someone please explain to me why this doesn’t work? ``` class python: def __init__(self,name): self.name=name def changename(self,newname): self.name=newname abc=python('python') print abc.name abc.changename = 'anaconda' print abc.name ``` All I’m trying to do here is change the value of `abc.name` at some point later in the code (it doesn’t need to be name if that’s a special word, but I did try name2, etc, same results...) If I do `print abc.changename` then I get the output anaconda but that’s not really what i wanted. Any help would be much appreciated. Also...Is it possible to do something like that at a later point in the life cycle of the code? ``` def newstuff(self, value1, value2): self.newvalue1 = value1 self.newvalue2 = value2 ``` So that I would have access to 2 new ‘things’ `abc.newvalue1` and `abc.newvalue2`. Does that make sense?? Sorry for the ‘things; I’m still trying to grasp which is an attribute, object, method, item, etc...
2019/12/12
[ "https://Stackoverflow.com/questions/59307832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6037160/" ]
You can have an HTML5 `audio` tag in base64 encoding as so: ```html <audio controls autoplay loop src="data:audio/ogg;base64,BASE64CODE" /> ``` No need for a `type`! :)
If your audio files are over about 20MB then you might run into performance problems and errors in some browsers (notably Firefox). For this reason I recommend converting the Base64 into a binary Blob as described [here](https://stackoverflow.com/a/40329529/1417989) using the [convertDataURIToBinary](https://gist.github.com/borismus/1032746) snippet and then setting that as the `audio.src`.
2,162,914
I have the following Python script that reads numbers and outputs an error if the input is not a number. ``` import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) ``` If I get the input from stdin, I have to press `Ctrl` + `D` **twice** to end the program. Why? I only have to press `Ctrl` + `D` once when I run the Python interpreter by itself. ``` bash $ python test.py 1 2 foo 4 5 <Ctrl+D> ERROR: not a number: foo <Ctrl+D> bash $ ```
2010/01/29
[ "https://Stackoverflow.com/questions/2162914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46821/" ]
I wrote an explanation about this in my answer to this question. [How to capture Control+D signal?](https://stackoverflow.com/questions/1516122/how-to-capture-controld-signal) In short, Control-D at the terminal simply causes the terminal to flush the input. This makes the `read` system call return. The first time it returns with a non-zero value (if you typed something). The second time, it returns with 0, which is code for "end of file".
The first time it considers it to be input, the second time it's for keeps! This only occurs when the input is from a tty. It is likely because of the terminal settings where characters are buffered until a newline (carriage return) is entered.
2,162,914
I have the following Python script that reads numbers and outputs an error if the input is not a number. ``` import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) ``` If I get the input from stdin, I have to press `Ctrl` + `D` **twice** to end the program. Why? I only have to press `Ctrl` + `D` once when I run the Python interpreter by itself. ``` bash $ python test.py 1 2 foo 4 5 <Ctrl+D> ERROR: not a number: foo <Ctrl+D> bash $ ```
2010/01/29
[ "https://Stackoverflow.com/questions/2162914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46821/" ]
In Python 3, this was due to [a bug in Python's standard I/O library](http://bugs.python.org/issue5505). The bug was fixed in Python 3.3. --- In a Unix terminal, typing Ctrl+D doesn't actually close the process's stdin. But typing either Enter or Ctrl+D does cause the OS `read` system call to return right away. So: ``` >>> sys.stdin.read(100) xyzzy (I press Enter here) (I press Ctrl+D once) 'xyzzy\n' >>> ``` `sys.stdin.read(100)` is delegated to `sys.stdin.buffer.read`, which calls the system read() in a loop until either it accumulates the full requested amount of data; or the system read() returns 0 bytes; or an error occurs. [(docs)](https://docs.python.org/3/library/io.html#io.BufferedIOBase.read "\"...multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first).\"") [(source)](https://hg.python.org/cpython/file/645f3d750be1/Modules/_io/bufferedio.c#l1629 "As of Python 3.4.2, the loop is in the function _bufferedreader_read_generic, in Modules/_io/bufferedio.c.") Pressing Enter after the first line caused the system read() to return 6 bytes. `sys.stdin.buffer.read` called read() again to try to get more input. Then I pressed Ctrl+D, causing read() to return 0 bytes. At this point, `sys.stdin.buffer.read` gave up and returned just the 6 bytes it had collected earlier. Note that the process still has my terminal on stdin, and I can still type stuff. ``` >>> sys.stdin.read() (note I can still type stuff to python) xyzzy (I press Enter) (Press Ctrl+D again) 'xyzzy\n' ``` OK. This is the part that was busted when this question was originally asked. It works now. But prior to Python 3.3, there was a bug. The bug was a little complicated --- basically the problem was that two separate layers were doing the same work. `BufferedReader.read()` was written to call `self.raw.read()` repeatedly until it returned 0 bytes. However, the raw method, `FileIO.read()`, performed a loop-until-zero-bytes of its own. So the first time you press Ctrl+D in a Python with this bug, it would cause `FileIO.read()` to return 6 bytes to `BufferedReader.read()`, which would then immediately call `self.raw.read()` again. The second Ctrl+D would cause *that* to return 0 bytes, and then `BufferedReader.read()` would finally exit. This explanation is unfortunately much longer than my previous one, but it has the virtue of being correct. Bugs are like that...
The first time it considers it to be input, the second time it's for keeps! This only occurs when the input is from a tty. It is likely because of the terminal settings where characters are buffered until a newline (carriage return) is entered.
2,162,914
I have the following Python script that reads numbers and outputs an error if the input is not a number. ``` import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) ``` If I get the input from stdin, I have to press `Ctrl` + `D` **twice** to end the program. Why? I only have to press `Ctrl` + `D` once when I run the Python interpreter by itself. ``` bash $ python test.py 1 2 foo 4 5 <Ctrl+D> ERROR: not a number: foo <Ctrl+D> bash $ ```
2010/01/29
[ "https://Stackoverflow.com/questions/2162914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46821/" ]
Most likely this has to do with Python the following Python issues: * [5505](http://bugs.python.org/issue5505): `sys.stdin.read()` doesn't return after first EOF on Windows, and * [1633941](http://bugs.python.org/issue1633941): `for line in sys.stdin:` doesn't notice EOF the first time.
The first time it considers it to be input, the second time it's for keeps! This only occurs when the input is from a tty. It is likely because of the terminal settings where characters are buffered until a newline (carriage return) is entered.
2,162,914
I have the following Python script that reads numbers and outputs an error if the input is not a number. ``` import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) ``` If I get the input from stdin, I have to press `Ctrl` + `D` **twice** to end the program. Why? I only have to press `Ctrl` + `D` once when I run the Python interpreter by itself. ``` bash $ python test.py 1 2 foo 4 5 <Ctrl+D> ERROR: not a number: foo <Ctrl+D> bash $ ```
2010/01/29
[ "https://Stackoverflow.com/questions/2162914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46821/" ]
In Python 3, this was due to [a bug in Python's standard I/O library](http://bugs.python.org/issue5505). The bug was fixed in Python 3.3. --- In a Unix terminal, typing Ctrl+D doesn't actually close the process's stdin. But typing either Enter or Ctrl+D does cause the OS `read` system call to return right away. So: ``` >>> sys.stdin.read(100) xyzzy (I press Enter here) (I press Ctrl+D once) 'xyzzy\n' >>> ``` `sys.stdin.read(100)` is delegated to `sys.stdin.buffer.read`, which calls the system read() in a loop until either it accumulates the full requested amount of data; or the system read() returns 0 bytes; or an error occurs. [(docs)](https://docs.python.org/3/library/io.html#io.BufferedIOBase.read "\"...multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first).\"") [(source)](https://hg.python.org/cpython/file/645f3d750be1/Modules/_io/bufferedio.c#l1629 "As of Python 3.4.2, the loop is in the function _bufferedreader_read_generic, in Modules/_io/bufferedio.c.") Pressing Enter after the first line caused the system read() to return 6 bytes. `sys.stdin.buffer.read` called read() again to try to get more input. Then I pressed Ctrl+D, causing read() to return 0 bytes. At this point, `sys.stdin.buffer.read` gave up and returned just the 6 bytes it had collected earlier. Note that the process still has my terminal on stdin, and I can still type stuff. ``` >>> sys.stdin.read() (note I can still type stuff to python) xyzzy (I press Enter) (Press Ctrl+D again) 'xyzzy\n' ``` OK. This is the part that was busted when this question was originally asked. It works now. But prior to Python 3.3, there was a bug. The bug was a little complicated --- basically the problem was that two separate layers were doing the same work. `BufferedReader.read()` was written to call `self.raw.read()` repeatedly until it returned 0 bytes. However, the raw method, `FileIO.read()`, performed a loop-until-zero-bytes of its own. So the first time you press Ctrl+D in a Python with this bug, it would cause `FileIO.read()` to return 6 bytes to `BufferedReader.read()`, which would then immediately call `self.raw.read()` again. The second Ctrl+D would cause *that* to return 0 bytes, and then `BufferedReader.read()` would finally exit. This explanation is unfortunately much longer than my previous one, but it has the virtue of being correct. Bugs are like that...
I wrote an explanation about this in my answer to this question. [How to capture Control+D signal?](https://stackoverflow.com/questions/1516122/how-to-capture-controld-signal) In short, Control-D at the terminal simply causes the terminal to flush the input. This makes the `read` system call return. The first time it returns with a non-zero value (if you typed something). The second time, it returns with 0, which is code for "end of file".
2,162,914
I have the following Python script that reads numbers and outputs an error if the input is not a number. ``` import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) ``` If I get the input from stdin, I have to press `Ctrl` + `D` **twice** to end the program. Why? I only have to press `Ctrl` + `D` once when I run the Python interpreter by itself. ``` bash $ python test.py 1 2 foo 4 5 <Ctrl+D> ERROR: not a number: foo <Ctrl+D> bash $ ```
2010/01/29
[ "https://Stackoverflow.com/questions/2162914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46821/" ]
I wrote an explanation about this in my answer to this question. [How to capture Control+D signal?](https://stackoverflow.com/questions/1516122/how-to-capture-controld-signal) In short, Control-D at the terminal simply causes the terminal to flush the input. This makes the `read` system call return. The first time it returns with a non-zero value (if you typed something). The second time, it returns with 0, which is code for "end of file".
Using the "for line in file:" form of reading lines from a file, Python uses a hidden read-ahead buffer (see <http://docs.python.org/2.7/library/stdtypes.html#file-objects> at the file.next function). First of all, this explains why a program that writes output when each input line is read displays no output until you press CTRL-D. Secondly, in order to give the user some control over the buffering, pressing CTRL-D flushes the input buffer to the application code. Pressing CTRL-D when the input buffer is empty is treated as EOF. Tying this together answers the original question. After entering some input, the first ctrl-D (on a line by itself) flushes the input to the application code. Now that the buffer is empty, the second ctrl-D acts as End-of-File (EOF). `file.readline()` does not exhibit this behavior.
2,162,914
I have the following Python script that reads numbers and outputs an error if the input is not a number. ``` import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) ``` If I get the input from stdin, I have to press `Ctrl` + `D` **twice** to end the program. Why? I only have to press `Ctrl` + `D` once when I run the Python interpreter by itself. ``` bash $ python test.py 1 2 foo 4 5 <Ctrl+D> ERROR: not a number: foo <Ctrl+D> bash $ ```
2010/01/29
[ "https://Stackoverflow.com/questions/2162914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46821/" ]
In Python 3, this was due to [a bug in Python's standard I/O library](http://bugs.python.org/issue5505). The bug was fixed in Python 3.3. --- In a Unix terminal, typing Ctrl+D doesn't actually close the process's stdin. But typing either Enter or Ctrl+D does cause the OS `read` system call to return right away. So: ``` >>> sys.stdin.read(100) xyzzy (I press Enter here) (I press Ctrl+D once) 'xyzzy\n' >>> ``` `sys.stdin.read(100)` is delegated to `sys.stdin.buffer.read`, which calls the system read() in a loop until either it accumulates the full requested amount of data; or the system read() returns 0 bytes; or an error occurs. [(docs)](https://docs.python.org/3/library/io.html#io.BufferedIOBase.read "\"...multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first).\"") [(source)](https://hg.python.org/cpython/file/645f3d750be1/Modules/_io/bufferedio.c#l1629 "As of Python 3.4.2, the loop is in the function _bufferedreader_read_generic, in Modules/_io/bufferedio.c.") Pressing Enter after the first line caused the system read() to return 6 bytes. `sys.stdin.buffer.read` called read() again to try to get more input. Then I pressed Ctrl+D, causing read() to return 0 bytes. At this point, `sys.stdin.buffer.read` gave up and returned just the 6 bytes it had collected earlier. Note that the process still has my terminal on stdin, and I can still type stuff. ``` >>> sys.stdin.read() (note I can still type stuff to python) xyzzy (I press Enter) (Press Ctrl+D again) 'xyzzy\n' ``` OK. This is the part that was busted when this question was originally asked. It works now. But prior to Python 3.3, there was a bug. The bug was a little complicated --- basically the problem was that two separate layers were doing the same work. `BufferedReader.read()` was written to call `self.raw.read()` repeatedly until it returned 0 bytes. However, the raw method, `FileIO.read()`, performed a loop-until-zero-bytes of its own. So the first time you press Ctrl+D in a Python with this bug, it would cause `FileIO.read()` to return 6 bytes to `BufferedReader.read()`, which would then immediately call `self.raw.read()` again. The second Ctrl+D would cause *that* to return 0 bytes, and then `BufferedReader.read()` would finally exit. This explanation is unfortunately much longer than my previous one, but it has the virtue of being correct. Bugs are like that...
Most likely this has to do with Python the following Python issues: * [5505](http://bugs.python.org/issue5505): `sys.stdin.read()` doesn't return after first EOF on Windows, and * [1633941](http://bugs.python.org/issue1633941): `for line in sys.stdin:` doesn't notice EOF the first time.
2,162,914
I have the following Python script that reads numbers and outputs an error if the input is not a number. ``` import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) ``` If I get the input from stdin, I have to press `Ctrl` + `D` **twice** to end the program. Why? I only have to press `Ctrl` + `D` once when I run the Python interpreter by itself. ``` bash $ python test.py 1 2 foo 4 5 <Ctrl+D> ERROR: not a number: foo <Ctrl+D> bash $ ```
2010/01/29
[ "https://Stackoverflow.com/questions/2162914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46821/" ]
In Python 3, this was due to [a bug in Python's standard I/O library](http://bugs.python.org/issue5505). The bug was fixed in Python 3.3. --- In a Unix terminal, typing Ctrl+D doesn't actually close the process's stdin. But typing either Enter or Ctrl+D does cause the OS `read` system call to return right away. So: ``` >>> sys.stdin.read(100) xyzzy (I press Enter here) (I press Ctrl+D once) 'xyzzy\n' >>> ``` `sys.stdin.read(100)` is delegated to `sys.stdin.buffer.read`, which calls the system read() in a loop until either it accumulates the full requested amount of data; or the system read() returns 0 bytes; or an error occurs. [(docs)](https://docs.python.org/3/library/io.html#io.BufferedIOBase.read "\"...multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first).\"") [(source)](https://hg.python.org/cpython/file/645f3d750be1/Modules/_io/bufferedio.c#l1629 "As of Python 3.4.2, the loop is in the function _bufferedreader_read_generic, in Modules/_io/bufferedio.c.") Pressing Enter after the first line caused the system read() to return 6 bytes. `sys.stdin.buffer.read` called read() again to try to get more input. Then I pressed Ctrl+D, causing read() to return 0 bytes. At this point, `sys.stdin.buffer.read` gave up and returned just the 6 bytes it had collected earlier. Note that the process still has my terminal on stdin, and I can still type stuff. ``` >>> sys.stdin.read() (note I can still type stuff to python) xyzzy (I press Enter) (Press Ctrl+D again) 'xyzzy\n' ``` OK. This is the part that was busted when this question was originally asked. It works now. But prior to Python 3.3, there was a bug. The bug was a little complicated --- basically the problem was that two separate layers were doing the same work. `BufferedReader.read()` was written to call `self.raw.read()` repeatedly until it returned 0 bytes. However, the raw method, `FileIO.read()`, performed a loop-until-zero-bytes of its own. So the first time you press Ctrl+D in a Python with this bug, it would cause `FileIO.read()` to return 6 bytes to `BufferedReader.read()`, which would then immediately call `self.raw.read()` again. The second Ctrl+D would cause *that* to return 0 bytes, and then `BufferedReader.read()` would finally exit. This explanation is unfortunately much longer than my previous one, but it has the virtue of being correct. Bugs are like that...
Using the "for line in file:" form of reading lines from a file, Python uses a hidden read-ahead buffer (see <http://docs.python.org/2.7/library/stdtypes.html#file-objects> at the file.next function). First of all, this explains why a program that writes output when each input line is read displays no output until you press CTRL-D. Secondly, in order to give the user some control over the buffering, pressing CTRL-D flushes the input buffer to the application code. Pressing CTRL-D when the input buffer is empty is treated as EOF. Tying this together answers the original question. After entering some input, the first ctrl-D (on a line by itself) flushes the input to the application code. Now that the buffer is empty, the second ctrl-D acts as End-of-File (EOF). `file.readline()` does not exhibit this behavior.
2,162,914
I have the following Python script that reads numbers and outputs an error if the input is not a number. ``` import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) ``` If I get the input from stdin, I have to press `Ctrl` + `D` **twice** to end the program. Why? I only have to press `Ctrl` + `D` once when I run the Python interpreter by itself. ``` bash $ python test.py 1 2 foo 4 5 <Ctrl+D> ERROR: not a number: foo <Ctrl+D> bash $ ```
2010/01/29
[ "https://Stackoverflow.com/questions/2162914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46821/" ]
Most likely this has to do with Python the following Python issues: * [5505](http://bugs.python.org/issue5505): `sys.stdin.read()` doesn't return after first EOF on Windows, and * [1633941](http://bugs.python.org/issue1633941): `for line in sys.stdin:` doesn't notice EOF the first time.
Using the "for line in file:" form of reading lines from a file, Python uses a hidden read-ahead buffer (see <http://docs.python.org/2.7/library/stdtypes.html#file-objects> at the file.next function). First of all, this explains why a program that writes output when each input line is read displays no output until you press CTRL-D. Secondly, in order to give the user some control over the buffering, pressing CTRL-D flushes the input buffer to the application code. Pressing CTRL-D when the input buffer is empty is treated as EOF. Tying this together answers the original question. After entering some input, the first ctrl-D (on a line by itself) flushes the input to the application code. Now that the buffer is empty, the second ctrl-D acts as End-of-File (EOF). `file.readline()` does not exhibit this behavior.
43,518,430
How to convert ``` json_decode = [{"538":["1,2,3","hello world"]},{"361":["0,9,8","x,x,y"]}] ``` to ``` {"538":["1,2,3","hello world"],"361":["0,9,8","x,x,y"]} ``` in python?
2017/04/20
[ "https://Stackoverflow.com/questions/43518430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6742101/" ]
***Try like this:*** ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EditText edittext = (EditText) findViewbyId(R.id.edittext); editText.setText("DefaultValue"); } ```
Add in xml layout file ``` android:text="defaultVal" ``` In onClick method or constructor/init method in java ``` editText.setText("DefaultValue"); ```
17,803,254
I want to find my public ip adress from python program. So far this is the only site <http://www.whatismyip.com/> and <http://whatismyip.org/> which gives ip without proxy rest all give the proxy. Now .org site is using image and first one writes ip across many span elements so i can't grab with urllib. Any other idea or site so that i can get my ip
2013/07/23
[ "https://Stackoverflow.com/questions/17803254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1667349/" ]
I usually use <http://httpbin.org/>: ``` import requests ip = requests.get('http://httpbin.org/ip').json()['origin'] ```
Use [lxml](http://lxml.de/) ``` import urllib import lxml.html u = urllib.urlopen('http://www.whatismyip.com/') html = u.read() u.close() root = lxml.html.fromstring(html) print ''.join(x.text for x in root.cssselect('#greenip *')) ```
14,140,089
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps: I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out: Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;) ``` students[] # Global List def addStudent(): print print "Adding student..." student = Student() firstName = raw_input("Please enter the student's first name: ") lastName = raw_input("Please enter the student's last name: ") degree = raw_input("Please enter the name of the degree the student is studying: ") studentid = raw_input("Please enter the students ID number: ") age = raw_input("Please enter the students Age: ") while True: moduleName = raw_input("Please enter module name: ") if moduleName == "-1": break grade = raw_input ("Please enter students grade for " + moduleName+": ") student.setFirstName(firstName) # Set this student's first name student.setLastName(lastName) student.setDegree(degree)# Set this student's last name student.setGrade(grade) student.setModuleName(moduleName) student.setStudentID(studentid) student.setAge(age) students.append(student) print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system." ``` ........................ ``` def viewStudent(): print "Printing all students in database : " for person in students: print "Printing details for: " + person.getFirstName()+" "+ person.getLastName() print "Age: " + person.getAge() print "Student ID: " + person.getStudentID() print "Degree: " + person.getDegree() print "Module: " + person.getModuleName() print "Grades: " + person.getGrade() ```
2013/01/03
[ "https://Stackoverflow.com/questions/14140089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1945133/" ]
You can use [String.Join](http://msdn.microsoft.com/en-us/library/dd783876(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1). ``` string.Join("\n", errorMessages); ```
Use join ``` string.Join(System.Environment.NewLine, errorMessages); ```
14,140,089
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps: I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out: Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;) ``` students[] # Global List def addStudent(): print print "Adding student..." student = Student() firstName = raw_input("Please enter the student's first name: ") lastName = raw_input("Please enter the student's last name: ") degree = raw_input("Please enter the name of the degree the student is studying: ") studentid = raw_input("Please enter the students ID number: ") age = raw_input("Please enter the students Age: ") while True: moduleName = raw_input("Please enter module name: ") if moduleName == "-1": break grade = raw_input ("Please enter students grade for " + moduleName+": ") student.setFirstName(firstName) # Set this student's first name student.setLastName(lastName) student.setDegree(degree)# Set this student's last name student.setGrade(grade) student.setModuleName(moduleName) student.setStudentID(studentid) student.setAge(age) students.append(student) print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system." ``` ........................ ``` def viewStudent(): print "Printing all students in database : " for person in students: print "Printing details for: " + person.getFirstName()+" "+ person.getLastName() print "Age: " + person.getAge() print "Student ID: " + person.getStudentID() print "Degree: " + person.getDegree() print "Module: " + person.getModuleName() print "Grades: " + person.getGrade() ```
2013/01/03
[ "https://Stackoverflow.com/questions/14140089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1945133/" ]
You can use [String.Join](http://msdn.microsoft.com/en-us/library/dd783876(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1). ``` string.Join("\n", errorMessages); ```
The shortest way is to use either `.Aggregate(...)` or `String.Join(...)`. ``` var messages = errorMessages.Aggregate((x, y) => x + Environment.NewLine + y); ``` Or ``` var messages = String.Join(Environment.NewLine, errorMessages); ```
14,140,089
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps: I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out: Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;) ``` students[] # Global List def addStudent(): print print "Adding student..." student = Student() firstName = raw_input("Please enter the student's first name: ") lastName = raw_input("Please enter the student's last name: ") degree = raw_input("Please enter the name of the degree the student is studying: ") studentid = raw_input("Please enter the students ID number: ") age = raw_input("Please enter the students Age: ") while True: moduleName = raw_input("Please enter module name: ") if moduleName == "-1": break grade = raw_input ("Please enter students grade for " + moduleName+": ") student.setFirstName(firstName) # Set this student's first name student.setLastName(lastName) student.setDegree(degree)# Set this student's last name student.setGrade(grade) student.setModuleName(moduleName) student.setStudentID(studentid) student.setAge(age) students.append(student) print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system." ``` ........................ ``` def viewStudent(): print "Printing all students in database : " for person in students: print "Printing details for: " + person.getFirstName()+" "+ person.getLastName() print "Age: " + person.getAge() print "Student ID: " + person.getStudentID() print "Degree: " + person.getDegree() print "Module: " + person.getModuleName() print "Grades: " + person.getGrade() ```
2013/01/03
[ "https://Stackoverflow.com/questions/14140089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1945133/" ]
You can use [String.Join](http://msdn.microsoft.com/en-us/library/dd783876(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1). ``` string.Join("\n", errorMessages); ```
``` using System; string.Join(Environment.NewLine, errorMessages); ```
14,140,089
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps: I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out: Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;) ``` students[] # Global List def addStudent(): print print "Adding student..." student = Student() firstName = raw_input("Please enter the student's first name: ") lastName = raw_input("Please enter the student's last name: ") degree = raw_input("Please enter the name of the degree the student is studying: ") studentid = raw_input("Please enter the students ID number: ") age = raw_input("Please enter the students Age: ") while True: moduleName = raw_input("Please enter module name: ") if moduleName == "-1": break grade = raw_input ("Please enter students grade for " + moduleName+": ") student.setFirstName(firstName) # Set this student's first name student.setLastName(lastName) student.setDegree(degree)# Set this student's last name student.setGrade(grade) student.setModuleName(moduleName) student.setStudentID(studentid) student.setAge(age) students.append(student) print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system." ``` ........................ ``` def viewStudent(): print "Printing all students in database : " for person in students: print "Printing details for: " + person.getFirstName()+" "+ person.getLastName() print "Age: " + person.getAge() print "Student ID: " + person.getStudentID() print "Degree: " + person.getDegree() print "Module: " + person.getModuleName() print "Grades: " + person.getGrade() ```
2013/01/03
[ "https://Stackoverflow.com/questions/14140089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1945133/" ]
You can use [String.Join](http://msdn.microsoft.com/en-us/library/dd783876(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1). ``` string.Join("\n", errorMessages); ```
I was having problems using ``` string.Join(System.Environment.NewLine, errorMessages); ``` In the page, instead of the new line I was getting **\r\n** instead. I solved it by using ``` string.Join("<br>", errorMessages); ```
14,140,089
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps: I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out: Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;) ``` students[] # Global List def addStudent(): print print "Adding student..." student = Student() firstName = raw_input("Please enter the student's first name: ") lastName = raw_input("Please enter the student's last name: ") degree = raw_input("Please enter the name of the degree the student is studying: ") studentid = raw_input("Please enter the students ID number: ") age = raw_input("Please enter the students Age: ") while True: moduleName = raw_input("Please enter module name: ") if moduleName == "-1": break grade = raw_input ("Please enter students grade for " + moduleName+": ") student.setFirstName(firstName) # Set this student's first name student.setLastName(lastName) student.setDegree(degree)# Set this student's last name student.setGrade(grade) student.setModuleName(moduleName) student.setStudentID(studentid) student.setAge(age) students.append(student) print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system." ``` ........................ ``` def viewStudent(): print "Printing all students in database : " for person in students: print "Printing details for: " + person.getFirstName()+" "+ person.getLastName() print "Age: " + person.getAge() print "Student ID: " + person.getStudentID() print "Degree: " + person.getDegree() print "Module: " + person.getModuleName() print "Grades: " + person.getGrade() ```
2013/01/03
[ "https://Stackoverflow.com/questions/14140089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1945133/" ]
Use join ``` string.Join(System.Environment.NewLine, errorMessages); ```
The shortest way is to use either `.Aggregate(...)` or `String.Join(...)`. ``` var messages = errorMessages.Aggregate((x, y) => x + Environment.NewLine + y); ``` Or ``` var messages = String.Join(Environment.NewLine, errorMessages); ```
14,140,089
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps: I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out: Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;) ``` students[] # Global List def addStudent(): print print "Adding student..." student = Student() firstName = raw_input("Please enter the student's first name: ") lastName = raw_input("Please enter the student's last name: ") degree = raw_input("Please enter the name of the degree the student is studying: ") studentid = raw_input("Please enter the students ID number: ") age = raw_input("Please enter the students Age: ") while True: moduleName = raw_input("Please enter module name: ") if moduleName == "-1": break grade = raw_input ("Please enter students grade for " + moduleName+": ") student.setFirstName(firstName) # Set this student's first name student.setLastName(lastName) student.setDegree(degree)# Set this student's last name student.setGrade(grade) student.setModuleName(moduleName) student.setStudentID(studentid) student.setAge(age) students.append(student) print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system." ``` ........................ ``` def viewStudent(): print "Printing all students in database : " for person in students: print "Printing details for: " + person.getFirstName()+" "+ person.getLastName() print "Age: " + person.getAge() print "Student ID: " + person.getStudentID() print "Degree: " + person.getDegree() print "Module: " + person.getModuleName() print "Grades: " + person.getGrade() ```
2013/01/03
[ "https://Stackoverflow.com/questions/14140089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1945133/" ]
Use join ``` string.Join(System.Environment.NewLine, errorMessages); ```
``` using System; string.Join(Environment.NewLine, errorMessages); ```
14,140,089
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps: I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out: Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;) ``` students[] # Global List def addStudent(): print print "Adding student..." student = Student() firstName = raw_input("Please enter the student's first name: ") lastName = raw_input("Please enter the student's last name: ") degree = raw_input("Please enter the name of the degree the student is studying: ") studentid = raw_input("Please enter the students ID number: ") age = raw_input("Please enter the students Age: ") while True: moduleName = raw_input("Please enter module name: ") if moduleName == "-1": break grade = raw_input ("Please enter students grade for " + moduleName+": ") student.setFirstName(firstName) # Set this student's first name student.setLastName(lastName) student.setDegree(degree)# Set this student's last name student.setGrade(grade) student.setModuleName(moduleName) student.setStudentID(studentid) student.setAge(age) students.append(student) print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system." ``` ........................ ``` def viewStudent(): print "Printing all students in database : " for person in students: print "Printing details for: " + person.getFirstName()+" "+ person.getLastName() print "Age: " + person.getAge() print "Student ID: " + person.getStudentID() print "Degree: " + person.getDegree() print "Module: " + person.getModuleName() print "Grades: " + person.getGrade() ```
2013/01/03
[ "https://Stackoverflow.com/questions/14140089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1945133/" ]
Use join ``` string.Join(System.Environment.NewLine, errorMessages); ```
I was having problems using ``` string.Join(System.Environment.NewLine, errorMessages); ``` In the page, instead of the new line I was getting **\r\n** instead. I solved it by using ``` string.Join("<br>", errorMessages); ```
14,140,089
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps: I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out: Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;) ``` students[] # Global List def addStudent(): print print "Adding student..." student = Student() firstName = raw_input("Please enter the student's first name: ") lastName = raw_input("Please enter the student's last name: ") degree = raw_input("Please enter the name of the degree the student is studying: ") studentid = raw_input("Please enter the students ID number: ") age = raw_input("Please enter the students Age: ") while True: moduleName = raw_input("Please enter module name: ") if moduleName == "-1": break grade = raw_input ("Please enter students grade for " + moduleName+": ") student.setFirstName(firstName) # Set this student's first name student.setLastName(lastName) student.setDegree(degree)# Set this student's last name student.setGrade(grade) student.setModuleName(moduleName) student.setStudentID(studentid) student.setAge(age) students.append(student) print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system." ``` ........................ ``` def viewStudent(): print "Printing all students in database : " for person in students: print "Printing details for: " + person.getFirstName()+" "+ person.getLastName() print "Age: " + person.getAge() print "Student ID: " + person.getStudentID() print "Degree: " + person.getDegree() print "Module: " + person.getModuleName() print "Grades: " + person.getGrade() ```
2013/01/03
[ "https://Stackoverflow.com/questions/14140089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1945133/" ]
``` using System; string.Join(Environment.NewLine, errorMessages); ```
The shortest way is to use either `.Aggregate(...)` or `String.Join(...)`. ``` var messages = errorMessages.Aggregate((x, y) => x + Environment.NewLine + y); ``` Or ``` var messages = String.Join(Environment.NewLine, errorMessages); ```
14,140,089
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps: I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out: Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;) ``` students[] # Global List def addStudent(): print print "Adding student..." student = Student() firstName = raw_input("Please enter the student's first name: ") lastName = raw_input("Please enter the student's last name: ") degree = raw_input("Please enter the name of the degree the student is studying: ") studentid = raw_input("Please enter the students ID number: ") age = raw_input("Please enter the students Age: ") while True: moduleName = raw_input("Please enter module name: ") if moduleName == "-1": break grade = raw_input ("Please enter students grade for " + moduleName+": ") student.setFirstName(firstName) # Set this student's first name student.setLastName(lastName) student.setDegree(degree)# Set this student's last name student.setGrade(grade) student.setModuleName(moduleName) student.setStudentID(studentid) student.setAge(age) students.append(student) print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system." ``` ........................ ``` def viewStudent(): print "Printing all students in database : " for person in students: print "Printing details for: " + person.getFirstName()+" "+ person.getLastName() print "Age: " + person.getAge() print "Student ID: " + person.getStudentID() print "Degree: " + person.getDegree() print "Module: " + person.getModuleName() print "Grades: " + person.getGrade() ```
2013/01/03
[ "https://Stackoverflow.com/questions/14140089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1945133/" ]
The shortest way is to use either `.Aggregate(...)` or `String.Join(...)`. ``` var messages = errorMessages.Aggregate((x, y) => x + Environment.NewLine + y); ``` Or ``` var messages = String.Join(Environment.NewLine, errorMessages); ```
I was having problems using ``` string.Join(System.Environment.NewLine, errorMessages); ``` In the page, instead of the new line I was getting **\r\n** instead. I solved it by using ``` string.Join("<br>", errorMessages); ```
14,140,089
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps: I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out: Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;) ``` students[] # Global List def addStudent(): print print "Adding student..." student = Student() firstName = raw_input("Please enter the student's first name: ") lastName = raw_input("Please enter the student's last name: ") degree = raw_input("Please enter the name of the degree the student is studying: ") studentid = raw_input("Please enter the students ID number: ") age = raw_input("Please enter the students Age: ") while True: moduleName = raw_input("Please enter module name: ") if moduleName == "-1": break grade = raw_input ("Please enter students grade for " + moduleName+": ") student.setFirstName(firstName) # Set this student's first name student.setLastName(lastName) student.setDegree(degree)# Set this student's last name student.setGrade(grade) student.setModuleName(moduleName) student.setStudentID(studentid) student.setAge(age) students.append(student) print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system." ``` ........................ ``` def viewStudent(): print "Printing all students in database : " for person in students: print "Printing details for: " + person.getFirstName()+" "+ person.getLastName() print "Age: " + person.getAge() print "Student ID: " + person.getStudentID() print "Degree: " + person.getDegree() print "Module: " + person.getModuleName() print "Grades: " + person.getGrade() ```
2013/01/03
[ "https://Stackoverflow.com/questions/14140089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1945133/" ]
``` using System; string.Join(Environment.NewLine, errorMessages); ```
I was having problems using ``` string.Join(System.Environment.NewLine, errorMessages); ``` In the page, instead of the new line I was getting **\r\n** instead. I solved it by using ``` string.Join("<br>", errorMessages); ```
40,613,480
[![enter image description here](https://i.stack.imgur.com/vIEKx.png)](https://i.stack.imgur.com/vIEKx.png) I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis. I was writing a function on it using Pandas but finding little difficulty. This is how Heiken Ashi [HA] looks like- ``` Heikin-Ashi Candle Calculations HA_Close = (Open + High + Low + Close) / 4 HA_Open = (previous HA_Open + previous HA_Close) / 2 HA_Low = minimum of Low, HA_Open, and HA_Close HA_High = maximum of High, HA_Open, and HA_Close Heikin-Ashi Calculations on First Run HA_Close = (Open + High + Low + Close) / 4 HA_Open = (Open + Close) / 2 HA_Low = Low HA_High = High ``` There is a lot of stuff available on various websites using for loop and pure python but i think Pandas can also do job well. This is my progress- ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+ df['Close'])/4 ha_o=df['Open']+df['Close'] #Creating a Variable #(for 1st row) HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) #Another variable #(for subsequent rows) df['HA_Open']=[ha_o/2 if df['HA_Open']='nan' else HA_O/2] #(error Part Where am i going wrong?) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Can Anyone Help me with this please?` It doesnt work.... I tried on this- ``` import pandas_datareader.data as web import HA import pandas as pd start='2016-1-1' end='2016-10-30' DAX=web.DataReader('^GDAXI','yahoo',start,end) ``` This is the New Code i wrote ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 ...: ha_o=df['Open']+df['Close'] ...: df['HA_Open']=0.0 ...: HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) ...: df['HA_Open']= np.where( df['HA_Open']==np.nan, ha_o/2, HA_O/2 ) ...: df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) ...: df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) ...: return df ``` But still the HA\_Open result was not satisfactory
2016/11/15
[ "https://Stackoverflow.com/questions/40613480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7053990/" ]
Here is the fastest, accurate and efficient implementation as per my tests: ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 idx = df.index.name df.reset_index(inplace=True) for i in range(0, len(df)): if i == 0: df.set_value(i, 'HA_Open', ((df.get_value(i, 'Open') + df.get_value(i, 'Close')) / 2)) else: df.set_value(i, 'HA_Open', ((df.get_value(i - 1, 'HA_Open') + df.get_value(i - 1, 'HA_Close')) / 2)) if idx: df.set_index(idx, inplace=True) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Here is my test algorithm (essentially I used the algorithm provided in this post to benchmark the speed results): ``` import quandl import time df = quandl.get("NSE/NIFTY_50", start_date='1997-01-01') def test_HA(): print('HA Test') start = time.time() HA(df) end = time.time() print('Time taken by set and get value functions for HA {}'.format(end-start)) start = time.time() df['HA_Close_t']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 from collections import namedtuple nt = namedtuple('nt', ['Open','Close']) previous_row = nt(df.ix[0,'Open'],df.ix[0,'Close']) i = 0 for row in df.itertuples(): ha_open = (previous_row.Open + previous_row.Close) / 2 df.ix[i,'HA_Open_t'] = ha_open previous_row = nt(ha_open, row.Close) i += 1 df['HA_High_t']=df[['HA_Open_t','HA_Close_t','High']].max(axis=1) df['HA_Low_t']=df[['HA_Open_t','HA_Close_t','Low']].min(axis=1) end = time.time() print('Time taken by ix (iloc, loc) functions for HA {}'.format(end-start)) ``` Here is the output I got on my i7 processor (please note the results may vary depending on your processor speed but I assume that the results will be similar): ``` HA Test Time taken by set and get value functions for HA 0.05005788803100586 Time taken by ix (iloc, loc) functions for HA 0.9360761642456055 ``` My experience with Pandas shows that functions like `ix`, `loc`, `iloc` are slower in comparison to `set_value` and `get_value` functions. Moreover computing value for a column on itself using `shift` function gives erroneous results.
Numpy version working with Numba ``` @jit(nopython=True) def heiken_ashi_numpy(c_open, c_high, c_low, c_close): ha_close = (c_open + c_high + c_low + c_close) / 4 ha_open = np.empty_like(ha_close) ha_open[0] = (c_open[0] + c_close[0]) / 2 for i in range(1, len(c_close)): ha_open[i] = (c_open[i - 1] + c_close[i - 1]) / 2 ha_high = np.maximum(np.maximum(ha_open, ha_close), c_high) ha_low = np.minimum(np.minimum(ha_open, ha_close), c_low) return ha_open, ha_high, ha_low, ha_close ```
40,613,480
[![enter image description here](https://i.stack.imgur.com/vIEKx.png)](https://i.stack.imgur.com/vIEKx.png) I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis. I was writing a function on it using Pandas but finding little difficulty. This is how Heiken Ashi [HA] looks like- ``` Heikin-Ashi Candle Calculations HA_Close = (Open + High + Low + Close) / 4 HA_Open = (previous HA_Open + previous HA_Close) / 2 HA_Low = minimum of Low, HA_Open, and HA_Close HA_High = maximum of High, HA_Open, and HA_Close Heikin-Ashi Calculations on First Run HA_Close = (Open + High + Low + Close) / 4 HA_Open = (Open + Close) / 2 HA_Low = Low HA_High = High ``` There is a lot of stuff available on various websites using for loop and pure python but i think Pandas can also do job well. This is my progress- ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+ df['Close'])/4 ha_o=df['Open']+df['Close'] #Creating a Variable #(for 1st row) HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) #Another variable #(for subsequent rows) df['HA_Open']=[ha_o/2 if df['HA_Open']='nan' else HA_O/2] #(error Part Where am i going wrong?) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Can Anyone Help me with this please?` It doesnt work.... I tried on this- ``` import pandas_datareader.data as web import HA import pandas as pd start='2016-1-1' end='2016-10-30' DAX=web.DataReader('^GDAXI','yahoo',start,end) ``` This is the New Code i wrote ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 ...: ha_o=df['Open']+df['Close'] ...: df['HA_Open']=0.0 ...: HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) ...: df['HA_Open']= np.where( df['HA_Open']==np.nan, ha_o/2, HA_O/2 ) ...: df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) ...: df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) ...: return df ``` But still the HA\_Open result was not satisfactory
2016/11/15
[ "https://Stackoverflow.com/questions/40613480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7053990/" ]
Assuming you have everything in a list of lists; where each row has: time, open, close, high, low, volume. ``` if candles: close_values = [sum(row[1:5]) / 4 for row in candles] previous_close = close_values[0] previous_open = (candles[0][1] + previous_close) / 2 opens = collections.deque() opens.append(previous_open) for close_value in close_values[1:]: previous_open = (previous_open + previous_close) / 2 opens.append(previous_open) previous_close = close_value candles = [[row[0], o, c, max(row[3], o, c), min(row[4], o, c), row[5]] for row, o, c in zip(candles, opens, close_values)] ``` This solution only uses list comprehensions and the collections module. If you want to return the dataframe: ``` return pd.DataFrame.from_records( data=candles, columns=['Time', 'Open', 'Close', 'High', 'Low', 'Volume'], index='Time', coerce_float=True, ) ```
**Fastest solution I found.** ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 idx = df.index.name df.reset_index(inplace=True) ha_close_values = self.data['HA_Close'].values length = len(df) ha_open = np.zeros(length, dtype=float) ha_open[0] = (df['Open'][0] + df['Close'][0]) / 2 for i in range(0, length - 1): ha_open[i + 1] = (ha_open[i] + ha_close_values[i]) / 2 df['HA_Open'] = ha_open df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` This solution is similar to ***user11186769*** with 2 additional optimization. The major optimizations which gave a 3.5-4x speedup is this part: ``` ha_close_values = self.data['HA_Close'].values length = len(df) ha_open = np.zeros(length, dtype=float) ha_open[0] = (df['Open'][0] + df['Close'][0]) / 2 for i in range(0, length - 1): ha_open[i + 1] = (ha_open[i] + ha_close_values[i]) / 2 ``` **vs this:** ``` [ha_open.append((ha_open[i] + df.HA_Close.values[i]) / 2) for i in range(0, len(df)-1)] ``` The first difference is that in that answer there is an unnecessary and expensive call in every iteration. Which is this: `df.HA_Close.values[i]`. (It converts the series to a numpy array in every iteration.) As you can see, in my solution I only calculated that value once and stored it like this: `ha_close_values = self.data['HA_Close'].values`, and used this value in the for loop. The other optimization is using a numpy array with a fix size instead of a python list. Instead of appending to that list in every iteration, I just used the current index+1 to set the values of `ha_open`.
40,613,480
[![enter image description here](https://i.stack.imgur.com/vIEKx.png)](https://i.stack.imgur.com/vIEKx.png) I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis. I was writing a function on it using Pandas but finding little difficulty. This is how Heiken Ashi [HA] looks like- ``` Heikin-Ashi Candle Calculations HA_Close = (Open + High + Low + Close) / 4 HA_Open = (previous HA_Open + previous HA_Close) / 2 HA_Low = minimum of Low, HA_Open, and HA_Close HA_High = maximum of High, HA_Open, and HA_Close Heikin-Ashi Calculations on First Run HA_Close = (Open + High + Low + Close) / 4 HA_Open = (Open + Close) / 2 HA_Low = Low HA_High = High ``` There is a lot of stuff available on various websites using for loop and pure python but i think Pandas can also do job well. This is my progress- ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+ df['Close'])/4 ha_o=df['Open']+df['Close'] #Creating a Variable #(for 1st row) HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) #Another variable #(for subsequent rows) df['HA_Open']=[ha_o/2 if df['HA_Open']='nan' else HA_O/2] #(error Part Where am i going wrong?) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Can Anyone Help me with this please?` It doesnt work.... I tried on this- ``` import pandas_datareader.data as web import HA import pandas as pd start='2016-1-1' end='2016-10-30' DAX=web.DataReader('^GDAXI','yahoo',start,end) ``` This is the New Code i wrote ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 ...: ha_o=df['Open']+df['Close'] ...: df['HA_Open']=0.0 ...: HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) ...: df['HA_Open']= np.where( df['HA_Open']==np.nan, ha_o/2, HA_O/2 ) ...: df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) ...: df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) ...: return df ``` But still the HA\_Open result was not satisfactory
2016/11/15
[ "https://Stackoverflow.com/questions/40613480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7053990/" ]
Here is the fastest, accurate and efficient implementation as per my tests: ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 idx = df.index.name df.reset_index(inplace=True) for i in range(0, len(df)): if i == 0: df.set_value(i, 'HA_Open', ((df.get_value(i, 'Open') + df.get_value(i, 'Close')) / 2)) else: df.set_value(i, 'HA_Open', ((df.get_value(i - 1, 'HA_Open') + df.get_value(i - 1, 'HA_Close')) / 2)) if idx: df.set_index(idx, inplace=True) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Here is my test algorithm (essentially I used the algorithm provided in this post to benchmark the speed results): ``` import quandl import time df = quandl.get("NSE/NIFTY_50", start_date='1997-01-01') def test_HA(): print('HA Test') start = time.time() HA(df) end = time.time() print('Time taken by set and get value functions for HA {}'.format(end-start)) start = time.time() df['HA_Close_t']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 from collections import namedtuple nt = namedtuple('nt', ['Open','Close']) previous_row = nt(df.ix[0,'Open'],df.ix[0,'Close']) i = 0 for row in df.itertuples(): ha_open = (previous_row.Open + previous_row.Close) / 2 df.ix[i,'HA_Open_t'] = ha_open previous_row = nt(ha_open, row.Close) i += 1 df['HA_High_t']=df[['HA_Open_t','HA_Close_t','High']].max(axis=1) df['HA_Low_t']=df[['HA_Open_t','HA_Close_t','Low']].min(axis=1) end = time.time() print('Time taken by ix (iloc, loc) functions for HA {}'.format(end-start)) ``` Here is the output I got on my i7 processor (please note the results may vary depending on your processor speed but I assume that the results will be similar): ``` HA Test Time taken by set and get value functions for HA 0.05005788803100586 Time taken by ix (iloc, loc) functions for HA 0.9360761642456055 ``` My experience with Pandas shows that functions like `ix`, `loc`, `iloc` are slower in comparison to `set_value` and `get_value` functions. Moreover computing value for a column on itself using `shift` function gives erroneous results.
``` def heikenashi(df): df['HA_Close'] = (df['Open'] + df['High'] + df['Low'] + df['Close']) / 4 df['HA_Open'] = (df['Open'].shift(1) + df['Open'].shift(1)) / 2 df.iloc[0, df.columns.get_loc("HA_Open")] = (df.iloc[0]['Open'] + df.iloc[0]['Close'])/2 df['HA_High'] = df[['High', 'Low', 'HA_Open', 'HA_Close']].max(axis=1) df['HA_Low'] = df[['High', 'Low', 'HA_Open', 'HA_Close']].min(axis=1) df = df.drop(['Open', 'High', 'Low', 'Close'], axis=1) # remove old columns df = df.rename(columns={"HA_Open": "Open", "HA_High": "High", "HA_Low": "Low", "HA_Close": "Close", "Volume": "Volume"}) df = df[['Open', 'High', 'Low', 'Close', 'Volume']] # reorder columns return df ```
40,613,480
[![enter image description here](https://i.stack.imgur.com/vIEKx.png)](https://i.stack.imgur.com/vIEKx.png) I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis. I was writing a function on it using Pandas but finding little difficulty. This is how Heiken Ashi [HA] looks like- ``` Heikin-Ashi Candle Calculations HA_Close = (Open + High + Low + Close) / 4 HA_Open = (previous HA_Open + previous HA_Close) / 2 HA_Low = minimum of Low, HA_Open, and HA_Close HA_High = maximum of High, HA_Open, and HA_Close Heikin-Ashi Calculations on First Run HA_Close = (Open + High + Low + Close) / 4 HA_Open = (Open + Close) / 2 HA_Low = Low HA_High = High ``` There is a lot of stuff available on various websites using for loop and pure python but i think Pandas can also do job well. This is my progress- ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+ df['Close'])/4 ha_o=df['Open']+df['Close'] #Creating a Variable #(for 1st row) HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) #Another variable #(for subsequent rows) df['HA_Open']=[ha_o/2 if df['HA_Open']='nan' else HA_O/2] #(error Part Where am i going wrong?) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Can Anyone Help me with this please?` It doesnt work.... I tried on this- ``` import pandas_datareader.data as web import HA import pandas as pd start='2016-1-1' end='2016-10-30' DAX=web.DataReader('^GDAXI','yahoo',start,end) ``` This is the New Code i wrote ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 ...: ha_o=df['Open']+df['Close'] ...: df['HA_Open']=0.0 ...: HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) ...: df['HA_Open']= np.where( df['HA_Open']==np.nan, ha_o/2, HA_O/2 ) ...: df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) ...: df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) ...: return df ``` But still the HA\_Open result was not satisfactory
2016/11/15
[ "https://Stackoverflow.com/questions/40613480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7053990/" ]
I adjusted the code to make it work with Python 3.7 ``` def HA(df): df_HA = df df_HA['Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 #idx = df_HA.index.name #df_HA.reset_index(inplace=True) for i in range(0, len(df)): if i == 0: df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2) else: df_HA['Open'][i] = ( (df['Open'][i-1] + df['Close'][i-1] )/ 2) #if idx: #df_HA.set_index(idx, inplace=True) df_HA['High']=df[['Open','Close','High']].max(axis=1) df_HA['Low']=df[['Open','Close','Low']].min(axis=1) return df_HA ```
``` def HA(df): df_HA = df df_HA['Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 for i in range(0, len(df)): if i == 0: df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2) else: df_HA['Open'][i] = ( (df['Open'][i-1] + df['Close'][i-1] )/ 2) df_HA['High']=df[['Open','Close','High']].max(axis=1) df_HA['Low']=df[['Open','Close','Low']].min(axis=1) return df_HA ``` This code works but calculates HA candles wrong. Else statement is looking at normal candles for open and close instead of HA to calculate next HA Open. Replace with: ``` for i in range(0, len(df)): if i == 0: df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2) else: df_HA['Open'][i] = ( (df_HA['Open'][i-1] + df_HA['Close'][i-1] )/ 2) ``` Next is HA High and low. Calculations not right. ``` df_HA['High']=df[['Open','Close','High']].max(axis=1) df_HA['Low']=df[['Open','Close','Low']].min(axis=1) ``` It is again comparing only against normal candles, instead of current normal candles High, and HA Open and HA Close. this code fixes the issue: ``` def HA_Initialise(df): df_HA = pd.DataFrame(columns=['Date', 'Open', 'High', 'Low', 'Close']) df_HA['Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 for i in range(0, len(df)): if i == 0: df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2) else: test = [] df_HA['Open'][i] = ( (df_HA['Open'][i-1] + df_HA['Close'][i-1] )/ 2) test.append(df['High'][i]) test.append(df['Low'][i]) test.append(df_HA['Open'][i]) test.append(df_HA['Close'][i]) high = max(test) low = min(test) df_HA['High'][i] = high df_HA['Low'][i] = low return df_HA ``` df is data frame with normal candle data, and df\_HA is what we are building and looking into while code runs for needed calculations
40,613,480
[![enter image description here](https://i.stack.imgur.com/vIEKx.png)](https://i.stack.imgur.com/vIEKx.png) I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis. I was writing a function on it using Pandas but finding little difficulty. This is how Heiken Ashi [HA] looks like- ``` Heikin-Ashi Candle Calculations HA_Close = (Open + High + Low + Close) / 4 HA_Open = (previous HA_Open + previous HA_Close) / 2 HA_Low = minimum of Low, HA_Open, and HA_Close HA_High = maximum of High, HA_Open, and HA_Close Heikin-Ashi Calculations on First Run HA_Close = (Open + High + Low + Close) / 4 HA_Open = (Open + Close) / 2 HA_Low = Low HA_High = High ``` There is a lot of stuff available on various websites using for loop and pure python but i think Pandas can also do job well. This is my progress- ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+ df['Close'])/4 ha_o=df['Open']+df['Close'] #Creating a Variable #(for 1st row) HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) #Another variable #(for subsequent rows) df['HA_Open']=[ha_o/2 if df['HA_Open']='nan' else HA_O/2] #(error Part Where am i going wrong?) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Can Anyone Help me with this please?` It doesnt work.... I tried on this- ``` import pandas_datareader.data as web import HA import pandas as pd start='2016-1-1' end='2016-10-30' DAX=web.DataReader('^GDAXI','yahoo',start,end) ``` This is the New Code i wrote ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 ...: ha_o=df['Open']+df['Close'] ...: df['HA_Open']=0.0 ...: HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) ...: df['HA_Open']= np.where( df['HA_Open']==np.nan, ha_o/2, HA_O/2 ) ...: df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) ...: df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) ...: return df ``` But still the HA\_Open result was not satisfactory
2016/11/15
[ "https://Stackoverflow.com/questions/40613480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7053990/" ]
Here is the fastest, accurate and efficient implementation as per my tests: ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 idx = df.index.name df.reset_index(inplace=True) for i in range(0, len(df)): if i == 0: df.set_value(i, 'HA_Open', ((df.get_value(i, 'Open') + df.get_value(i, 'Close')) / 2)) else: df.set_value(i, 'HA_Open', ((df.get_value(i - 1, 'HA_Open') + df.get_value(i - 1, 'HA_Close')) / 2)) if idx: df.set_index(idx, inplace=True) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Here is my test algorithm (essentially I used the algorithm provided in this post to benchmark the speed results): ``` import quandl import time df = quandl.get("NSE/NIFTY_50", start_date='1997-01-01') def test_HA(): print('HA Test') start = time.time() HA(df) end = time.time() print('Time taken by set and get value functions for HA {}'.format(end-start)) start = time.time() df['HA_Close_t']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 from collections import namedtuple nt = namedtuple('nt', ['Open','Close']) previous_row = nt(df.ix[0,'Open'],df.ix[0,'Close']) i = 0 for row in df.itertuples(): ha_open = (previous_row.Open + previous_row.Close) / 2 df.ix[i,'HA_Open_t'] = ha_open previous_row = nt(ha_open, row.Close) i += 1 df['HA_High_t']=df[['HA_Open_t','HA_Close_t','High']].max(axis=1) df['HA_Low_t']=df[['HA_Open_t','HA_Close_t','Low']].min(axis=1) end = time.time() print('Time taken by ix (iloc, loc) functions for HA {}'.format(end-start)) ``` Here is the output I got on my i7 processor (please note the results may vary depending on your processor speed but I assume that the results will be similar): ``` HA Test Time taken by set and get value functions for HA 0.05005788803100586 Time taken by ix (iloc, loc) functions for HA 0.9360761642456055 ``` My experience with Pandas shows that functions like `ix`, `loc`, `iloc` are slower in comparison to `set_value` and `get_value` functions. Moreover computing value for a column on itself using `shift` function gives erroneous results.
Perfectly working HekinAshi function. I am not the original author of this code. I found this on Github (<https://github.com/emreturan/heikin-ashi/blob/master/heikin_ashi.py>) ``` def heikin_ashi(df): heikin_ashi_df = pd.DataFrame(index=df.index.values, columns=['open', 'high', 'low', 'close']) heikin_ashi_df['close'] = (df['open'] + df['high'] + df['low'] + df['close']) / 4 for i in range(len(df)): if i == 0: heikin_ashi_df.iat[0, 0] = df['open'].iloc[0] else: heikin_ashi_df.iat[i, 0] = (heikin_ashi_df.iat[i-1, 0] + heikin_ashi_df.iat[i-1, 3]) / 2 heikin_ashi_df['high'] = heikin_ashi_df.loc[:, ['open', 'close']].join(df['high']).max(axis=1) heikin_ashi_df['low'] = heikin_ashi_df.loc[:, ['open', 'close']].join(df['low']).min(axis=1) return heikin_ashi_df ```
40,613,480
[![enter image description here](https://i.stack.imgur.com/vIEKx.png)](https://i.stack.imgur.com/vIEKx.png) I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis. I was writing a function on it using Pandas but finding little difficulty. This is how Heiken Ashi [HA] looks like- ``` Heikin-Ashi Candle Calculations HA_Close = (Open + High + Low + Close) / 4 HA_Open = (previous HA_Open + previous HA_Close) / 2 HA_Low = minimum of Low, HA_Open, and HA_Close HA_High = maximum of High, HA_Open, and HA_Close Heikin-Ashi Calculations on First Run HA_Close = (Open + High + Low + Close) / 4 HA_Open = (Open + Close) / 2 HA_Low = Low HA_High = High ``` There is a lot of stuff available on various websites using for loop and pure python but i think Pandas can also do job well. This is my progress- ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+ df['Close'])/4 ha_o=df['Open']+df['Close'] #Creating a Variable #(for 1st row) HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) #Another variable #(for subsequent rows) df['HA_Open']=[ha_o/2 if df['HA_Open']='nan' else HA_O/2] #(error Part Where am i going wrong?) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Can Anyone Help me with this please?` It doesnt work.... I tried on this- ``` import pandas_datareader.data as web import HA import pandas as pd start='2016-1-1' end='2016-10-30' DAX=web.DataReader('^GDAXI','yahoo',start,end) ``` This is the New Code i wrote ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 ...: ha_o=df['Open']+df['Close'] ...: df['HA_Open']=0.0 ...: HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) ...: df['HA_Open']= np.where( df['HA_Open']==np.nan, ha_o/2, HA_O/2 ) ...: df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) ...: df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) ...: return df ``` But still the HA\_Open result was not satisfactory
2016/11/15
[ "https://Stackoverflow.com/questions/40613480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7053990/" ]
Here is the fastest, accurate and efficient implementation as per my tests: ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 idx = df.index.name df.reset_index(inplace=True) for i in range(0, len(df)): if i == 0: df.set_value(i, 'HA_Open', ((df.get_value(i, 'Open') + df.get_value(i, 'Close')) / 2)) else: df.set_value(i, 'HA_Open', ((df.get_value(i - 1, 'HA_Open') + df.get_value(i - 1, 'HA_Close')) / 2)) if idx: df.set_index(idx, inplace=True) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Here is my test algorithm (essentially I used the algorithm provided in this post to benchmark the speed results): ``` import quandl import time df = quandl.get("NSE/NIFTY_50", start_date='1997-01-01') def test_HA(): print('HA Test') start = time.time() HA(df) end = time.time() print('Time taken by set and get value functions for HA {}'.format(end-start)) start = time.time() df['HA_Close_t']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 from collections import namedtuple nt = namedtuple('nt', ['Open','Close']) previous_row = nt(df.ix[0,'Open'],df.ix[0,'Close']) i = 0 for row in df.itertuples(): ha_open = (previous_row.Open + previous_row.Close) / 2 df.ix[i,'HA_Open_t'] = ha_open previous_row = nt(ha_open, row.Close) i += 1 df['HA_High_t']=df[['HA_Open_t','HA_Close_t','High']].max(axis=1) df['HA_Low_t']=df[['HA_Open_t','HA_Close_t','Low']].min(axis=1) end = time.time() print('Time taken by ix (iloc, loc) functions for HA {}'.format(end-start)) ``` Here is the output I got on my i7 processor (please note the results may vary depending on your processor speed but I assume that the results will be similar): ``` HA Test Time taken by set and get value functions for HA 0.05005788803100586 Time taken by ix (iloc, loc) functions for HA 0.9360761642456055 ``` My experience with Pandas shows that functions like `ix`, `loc`, `iloc` are slower in comparison to `set_value` and `get_value` functions. Moreover computing value for a column on itself using `shift` function gives erroneous results.
I adjusted the code to make it work with Python 3.7 ``` def HA(df): df_HA = df df_HA['Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 #idx = df_HA.index.name #df_HA.reset_index(inplace=True) for i in range(0, len(df)): if i == 0: df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2) else: df_HA['Open'][i] = ( (df['Open'][i-1] + df['Close'][i-1] )/ 2) #if idx: #df_HA.set_index(idx, inplace=True) df_HA['High']=df[['Open','Close','High']].max(axis=1) df_HA['Low']=df[['Open','Close','Low']].min(axis=1) return df_HA ```
40,613,480
[![enter image description here](https://i.stack.imgur.com/vIEKx.png)](https://i.stack.imgur.com/vIEKx.png) I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis. I was writing a function on it using Pandas but finding little difficulty. This is how Heiken Ashi [HA] looks like- ``` Heikin-Ashi Candle Calculations HA_Close = (Open + High + Low + Close) / 4 HA_Open = (previous HA_Open + previous HA_Close) / 2 HA_Low = minimum of Low, HA_Open, and HA_Close HA_High = maximum of High, HA_Open, and HA_Close Heikin-Ashi Calculations on First Run HA_Close = (Open + High + Low + Close) / 4 HA_Open = (Open + Close) / 2 HA_Low = Low HA_High = High ``` There is a lot of stuff available on various websites using for loop and pure python but i think Pandas can also do job well. This is my progress- ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+ df['Close'])/4 ha_o=df['Open']+df['Close'] #Creating a Variable #(for 1st row) HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) #Another variable #(for subsequent rows) df['HA_Open']=[ha_o/2 if df['HA_Open']='nan' else HA_O/2] #(error Part Where am i going wrong?) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Can Anyone Help me with this please?` It doesnt work.... I tried on this- ``` import pandas_datareader.data as web import HA import pandas as pd start='2016-1-1' end='2016-10-30' DAX=web.DataReader('^GDAXI','yahoo',start,end) ``` This is the New Code i wrote ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 ...: ha_o=df['Open']+df['Close'] ...: df['HA_Open']=0.0 ...: HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) ...: df['HA_Open']= np.where( df['HA_Open']==np.nan, ha_o/2, HA_O/2 ) ...: df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) ...: df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) ...: return df ``` But still the HA\_Open result was not satisfactory
2016/11/15
[ "https://Stackoverflow.com/questions/40613480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7053990/" ]
**No Loop Solution for DataFrames** This was the simplest, easy to understand, no-loop solution I could come up with for **dataframes**. * Temporarily store Heikin-Ashi output in 'o', 'h', 'l', 'c' columns * 'h' based on yesterday's values so we can use `.shift(1)` and copy the first entry * Replace 'Open', 'High', 'Low', 'Close' with 'o', 'h', 'l', 'c' **Python 3.9.7** ``` def heikin_ashi(df): df = df.copy() df['c'] = (df['Open'] + df['High'] + df['Low'] + df['Close']) / 4 df['o'] = ((df['Open'] + df['Close']) / 2).shift(1) df.iloc[0,-1] = df['o'].iloc[1] df['h'] = df[['High', 'o', 'c']].max(axis=1) df['l'] = df[['Low', 'o', 'c']].min(axis=1) df['Open'], df['High'], df['Low'], df['Close'] = df['o'], df['h'], df['l'], df['c'] return df.drop(['o', 'h', 'l', 'c'], axis=1) ```
**Fastest solution I found.** ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 idx = df.index.name df.reset_index(inplace=True) ha_close_values = self.data['HA_Close'].values length = len(df) ha_open = np.zeros(length, dtype=float) ha_open[0] = (df['Open'][0] + df['Close'][0]) / 2 for i in range(0, length - 1): ha_open[i + 1] = (ha_open[i] + ha_close_values[i]) / 2 df['HA_Open'] = ha_open df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` This solution is similar to ***user11186769*** with 2 additional optimization. The major optimizations which gave a 3.5-4x speedup is this part: ``` ha_close_values = self.data['HA_Close'].values length = len(df) ha_open = np.zeros(length, dtype=float) ha_open[0] = (df['Open'][0] + df['Close'][0]) / 2 for i in range(0, length - 1): ha_open[i + 1] = (ha_open[i] + ha_close_values[i]) / 2 ``` **vs this:** ``` [ha_open.append((ha_open[i] + df.HA_Close.values[i]) / 2) for i in range(0, len(df)-1)] ``` The first difference is that in that answer there is an unnecessary and expensive call in every iteration. Which is this: `df.HA_Close.values[i]`. (It converts the series to a numpy array in every iteration.) As you can see, in my solution I only calculated that value once and stored it like this: `ha_close_values = self.data['HA_Close'].values`, and used this value in the for loop. The other optimization is using a numpy array with a fix size instead of a python list. Instead of appending to that list in every iteration, I just used the current index+1 to set the values of `ha_open`.
40,613,480
[![enter image description here](https://i.stack.imgur.com/vIEKx.png)](https://i.stack.imgur.com/vIEKx.png) I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis. I was writing a function on it using Pandas but finding little difficulty. This is how Heiken Ashi [HA] looks like- ``` Heikin-Ashi Candle Calculations HA_Close = (Open + High + Low + Close) / 4 HA_Open = (previous HA_Open + previous HA_Close) / 2 HA_Low = minimum of Low, HA_Open, and HA_Close HA_High = maximum of High, HA_Open, and HA_Close Heikin-Ashi Calculations on First Run HA_Close = (Open + High + Low + Close) / 4 HA_Open = (Open + Close) / 2 HA_Low = Low HA_High = High ``` There is a lot of stuff available on various websites using for loop and pure python but i think Pandas can also do job well. This is my progress- ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+ df['Close'])/4 ha_o=df['Open']+df['Close'] #Creating a Variable #(for 1st row) HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) #Another variable #(for subsequent rows) df['HA_Open']=[ha_o/2 if df['HA_Open']='nan' else HA_O/2] #(error Part Where am i going wrong?) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Can Anyone Help me with this please?` It doesnt work.... I tried on this- ``` import pandas_datareader.data as web import HA import pandas as pd start='2016-1-1' end='2016-10-30' DAX=web.DataReader('^GDAXI','yahoo',start,end) ``` This is the New Code i wrote ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 ...: ha_o=df['Open']+df['Close'] ...: df['HA_Open']=0.0 ...: HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) ...: df['HA_Open']= np.where( df['HA_Open']==np.nan, ha_o/2, HA_O/2 ) ...: df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) ...: df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) ...: return df ``` But still the HA\_Open result was not satisfactory
2016/11/15
[ "https://Stackoverflow.com/questions/40613480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7053990/" ]
``` def HA(df): df_HA = df df_HA['Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 for i in range(0, len(df)): if i == 0: df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2) else: df_HA['Open'][i] = ( (df['Open'][i-1] + df['Close'][i-1] )/ 2) df_HA['High']=df[['Open','Close','High']].max(axis=1) df_HA['Low']=df[['Open','Close','Low']].min(axis=1) return df_HA ``` This code works but calculates HA candles wrong. Else statement is looking at normal candles for open and close instead of HA to calculate next HA Open. Replace with: ``` for i in range(0, len(df)): if i == 0: df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2) else: df_HA['Open'][i] = ( (df_HA['Open'][i-1] + df_HA['Close'][i-1] )/ 2) ``` Next is HA High and low. Calculations not right. ``` df_HA['High']=df[['Open','Close','High']].max(axis=1) df_HA['Low']=df[['Open','Close','Low']].min(axis=1) ``` It is again comparing only against normal candles, instead of current normal candles High, and HA Open and HA Close. this code fixes the issue: ``` def HA_Initialise(df): df_HA = pd.DataFrame(columns=['Date', 'Open', 'High', 'Low', 'Close']) df_HA['Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 for i in range(0, len(df)): if i == 0: df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2) else: test = [] df_HA['Open'][i] = ( (df_HA['Open'][i-1] + df_HA['Close'][i-1] )/ 2) test.append(df['High'][i]) test.append(df['Low'][i]) test.append(df_HA['Open'][i]) test.append(df_HA['Close'][i]) high = max(test) low = min(test) df_HA['High'][i] = high df_HA['Low'][i] = low return df_HA ``` df is data frame with normal candle data, and df\_HA is what we are building and looking into while code runs for needed calculations
**Fastest solution I found.** ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 idx = df.index.name df.reset_index(inplace=True) ha_close_values = self.data['HA_Close'].values length = len(df) ha_open = np.zeros(length, dtype=float) ha_open[0] = (df['Open'][0] + df['Close'][0]) / 2 for i in range(0, length - 1): ha_open[i + 1] = (ha_open[i] + ha_close_values[i]) / 2 df['HA_Open'] = ha_open df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` This solution is similar to ***user11186769*** with 2 additional optimization. The major optimizations which gave a 3.5-4x speedup is this part: ``` ha_close_values = self.data['HA_Close'].values length = len(df) ha_open = np.zeros(length, dtype=float) ha_open[0] = (df['Open'][0] + df['Close'][0]) / 2 for i in range(0, length - 1): ha_open[i + 1] = (ha_open[i] + ha_close_values[i]) / 2 ``` **vs this:** ``` [ha_open.append((ha_open[i] + df.HA_Close.values[i]) / 2) for i in range(0, len(df)-1)] ``` The first difference is that in that answer there is an unnecessary and expensive call in every iteration. Which is this: `df.HA_Close.values[i]`. (It converts the series to a numpy array in every iteration.) As you can see, in my solution I only calculated that value once and stored it like this: `ha_close_values = self.data['HA_Close'].values`, and used this value in the for loop. The other optimization is using a numpy array with a fix size instead of a python list. Instead of appending to that list in every iteration, I just used the current index+1 to set the values of `ha_open`.
40,613,480
[![enter image description here](https://i.stack.imgur.com/vIEKx.png)](https://i.stack.imgur.com/vIEKx.png) I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis. I was writing a function on it using Pandas but finding little difficulty. This is how Heiken Ashi [HA] looks like- ``` Heikin-Ashi Candle Calculations HA_Close = (Open + High + Low + Close) / 4 HA_Open = (previous HA_Open + previous HA_Close) / 2 HA_Low = minimum of Low, HA_Open, and HA_Close HA_High = maximum of High, HA_Open, and HA_Close Heikin-Ashi Calculations on First Run HA_Close = (Open + High + Low + Close) / 4 HA_Open = (Open + Close) / 2 HA_Low = Low HA_High = High ``` There is a lot of stuff available on various websites using for loop and pure python but i think Pandas can also do job well. This is my progress- ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+ df['Close'])/4 ha_o=df['Open']+df['Close'] #Creating a Variable #(for 1st row) HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) #Another variable #(for subsequent rows) df['HA_Open']=[ha_o/2 if df['HA_Open']='nan' else HA_O/2] #(error Part Where am i going wrong?) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Can Anyone Help me with this please?` It doesnt work.... I tried on this- ``` import pandas_datareader.data as web import HA import pandas as pd start='2016-1-1' end='2016-10-30' DAX=web.DataReader('^GDAXI','yahoo',start,end) ``` This is the New Code i wrote ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 ...: ha_o=df['Open']+df['Close'] ...: df['HA_Open']=0.0 ...: HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) ...: df['HA_Open']= np.where( df['HA_Open']==np.nan, ha_o/2, HA_O/2 ) ...: df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) ...: df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) ...: return df ``` But still the HA\_Open result was not satisfactory
2016/11/15
[ "https://Stackoverflow.com/questions/40613480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7053990/" ]
Here is the fastest, accurate and efficient implementation as per my tests: ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 idx = df.index.name df.reset_index(inplace=True) for i in range(0, len(df)): if i == 0: df.set_value(i, 'HA_Open', ((df.get_value(i, 'Open') + df.get_value(i, 'Close')) / 2)) else: df.set_value(i, 'HA_Open', ((df.get_value(i - 1, 'HA_Open') + df.get_value(i - 1, 'HA_Close')) / 2)) if idx: df.set_index(idx, inplace=True) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Here is my test algorithm (essentially I used the algorithm provided in this post to benchmark the speed results): ``` import quandl import time df = quandl.get("NSE/NIFTY_50", start_date='1997-01-01') def test_HA(): print('HA Test') start = time.time() HA(df) end = time.time() print('Time taken by set and get value functions for HA {}'.format(end-start)) start = time.time() df['HA_Close_t']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 from collections import namedtuple nt = namedtuple('nt', ['Open','Close']) previous_row = nt(df.ix[0,'Open'],df.ix[0,'Close']) i = 0 for row in df.itertuples(): ha_open = (previous_row.Open + previous_row.Close) / 2 df.ix[i,'HA_Open_t'] = ha_open previous_row = nt(ha_open, row.Close) i += 1 df['HA_High_t']=df[['HA_Open_t','HA_Close_t','High']].max(axis=1) df['HA_Low_t']=df[['HA_Open_t','HA_Close_t','Low']].min(axis=1) end = time.time() print('Time taken by ix (iloc, loc) functions for HA {}'.format(end-start)) ``` Here is the output I got on my i7 processor (please note the results may vary depending on your processor speed but I assume that the results will be similar): ``` HA Test Time taken by set and get value functions for HA 0.05005788803100586 Time taken by ix (iloc, loc) functions for HA 0.9360761642456055 ``` My experience with Pandas shows that functions like `ix`, `loc`, `iloc` are slower in comparison to `set_value` and `get_value` functions. Moreover computing value for a column on itself using `shift` function gives erroneous results.
**Fastest solution I found.** ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 idx = df.index.name df.reset_index(inplace=True) ha_close_values = self.data['HA_Close'].values length = len(df) ha_open = np.zeros(length, dtype=float) ha_open[0] = (df['Open'][0] + df['Close'][0]) / 2 for i in range(0, length - 1): ha_open[i + 1] = (ha_open[i] + ha_close_values[i]) / 2 df['HA_Open'] = ha_open df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` This solution is similar to ***user11186769*** with 2 additional optimization. The major optimizations which gave a 3.5-4x speedup is this part: ``` ha_close_values = self.data['HA_Close'].values length = len(df) ha_open = np.zeros(length, dtype=float) ha_open[0] = (df['Open'][0] + df['Close'][0]) / 2 for i in range(0, length - 1): ha_open[i + 1] = (ha_open[i] + ha_close_values[i]) / 2 ``` **vs this:** ``` [ha_open.append((ha_open[i] + df.HA_Close.values[i]) / 2) for i in range(0, len(df)-1)] ``` The first difference is that in that answer there is an unnecessary and expensive call in every iteration. Which is this: `df.HA_Close.values[i]`. (It converts the series to a numpy array in every iteration.) As you can see, in my solution I only calculated that value once and stored it like this: `ha_close_values = self.data['HA_Close'].values`, and used this value in the for loop. The other optimization is using a numpy array with a fix size instead of a python list. Instead of appending to that list in every iteration, I just used the current index+1 to set the values of `ha_open`.
40,613,480
[![enter image description here](https://i.stack.imgur.com/vIEKx.png)](https://i.stack.imgur.com/vIEKx.png) I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis. I was writing a function on it using Pandas but finding little difficulty. This is how Heiken Ashi [HA] looks like- ``` Heikin-Ashi Candle Calculations HA_Close = (Open + High + Low + Close) / 4 HA_Open = (previous HA_Open + previous HA_Close) / 2 HA_Low = minimum of Low, HA_Open, and HA_Close HA_High = maximum of High, HA_Open, and HA_Close Heikin-Ashi Calculations on First Run HA_Close = (Open + High + Low + Close) / 4 HA_Open = (Open + Close) / 2 HA_Low = Low HA_High = High ``` There is a lot of stuff available on various websites using for loop and pure python but i think Pandas can also do job well. This is my progress- ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+ df['Close'])/4 ha_o=df['Open']+df['Close'] #Creating a Variable #(for 1st row) HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) #Another variable #(for subsequent rows) df['HA_Open']=[ha_o/2 if df['HA_Open']='nan' else HA_O/2] #(error Part Where am i going wrong?) df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) return df ``` Can Anyone Help me with this please?` It doesnt work.... I tried on this- ``` import pandas_datareader.data as web import HA import pandas as pd start='2016-1-1' end='2016-10-30' DAX=web.DataReader('^GDAXI','yahoo',start,end) ``` This is the New Code i wrote ``` def HA(df): df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 ...: ha_o=df['Open']+df['Close'] ...: df['HA_Open']=0.0 ...: HA_O=df['HA_Open'].shift(1)+df['HA_Close'].shift(1) ...: df['HA_Open']= np.where( df['HA_Open']==np.nan, ha_o/2, HA_O/2 ) ...: df['HA_High']=df[['HA_Open','HA_Close','High']].max(axis=1) ...: df['HA_Low']=df[['HA_Open','HA_Close','Low']].min(axis=1) ...: return df ``` But still the HA\_Open result was not satisfactory
2016/11/15
[ "https://Stackoverflow.com/questions/40613480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7053990/" ]
``` def heikenashi(df): df['HA_Close'] = (df['Open'] + df['High'] + df['Low'] + df['Close']) / 4 df['HA_Open'] = (df['Open'].shift(1) + df['Open'].shift(1)) / 2 df.iloc[0, df.columns.get_loc("HA_Open")] = (df.iloc[0]['Open'] + df.iloc[0]['Close'])/2 df['HA_High'] = df[['High', 'Low', 'HA_Open', 'HA_Close']].max(axis=1) df['HA_Low'] = df[['High', 'Low', 'HA_Open', 'HA_Close']].min(axis=1) df = df.drop(['Open', 'High', 'Low', 'Close'], axis=1) # remove old columns df = df.rename(columns={"HA_Open": "Open", "HA_High": "High", "HA_Low": "Low", "HA_Close": "Close", "Volume": "Volume"}) df = df[['Open', 'High', 'Low', 'Close', 'Volume']] # reorder columns return df ```
``` def HA(df): df_HA = df df_HA['Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 for i in range(0, len(df)): if i == 0: df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2) else: df_HA['Open'][i] = ( (df['Open'][i-1] + df['Close'][i-1] )/ 2) df_HA['High']=df[['Open','Close','High']].max(axis=1) df_HA['Low']=df[['Open','Close','Low']].min(axis=1) return df_HA ``` This code works but calculates HA candles wrong. Else statement is looking at normal candles for open and close instead of HA to calculate next HA Open. Replace with: ``` for i in range(0, len(df)): if i == 0: df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2) else: df_HA['Open'][i] = ( (df_HA['Open'][i-1] + df_HA['Close'][i-1] )/ 2) ``` Next is HA High and low. Calculations not right. ``` df_HA['High']=df[['Open','Close','High']].max(axis=1) df_HA['Low']=df[['Open','Close','Low']].min(axis=1) ``` It is again comparing only against normal candles, instead of current normal candles High, and HA Open and HA Close. this code fixes the issue: ``` def HA_Initialise(df): df_HA = pd.DataFrame(columns=['Date', 'Open', 'High', 'Low', 'Close']) df_HA['Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4 for i in range(0, len(df)): if i == 0: df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2) else: test = [] df_HA['Open'][i] = ( (df_HA['Open'][i-1] + df_HA['Close'][i-1] )/ 2) test.append(df['High'][i]) test.append(df['Low'][i]) test.append(df_HA['Open'][i]) test.append(df_HA['Close'][i]) high = max(test) low = min(test) df_HA['High'][i] = high df_HA['Low'][i] = low return df_HA ``` df is data frame with normal candle data, and df\_HA is what we are building and looking into while code runs for needed calculations
37,187,962
I have problem with python selenium phantomjs which i couldn't solve. element.location returns wrong location. when I see cropped image it is showing part of desired image and also unwanted one. It worked on firefox perfectly but doesn't work on phantomjs. Here is code: ``` def screenOfElement(self, _element): _location = _element.location _size = _element.size _wholePage = Image.open(StringIO.StringIO(base64.decodestring(self.webdriver.get_screenshot_as_base64()))) _left = _location['x'] _top = _location['y'] _right = _location['x'] + _size['width'] _bottom = _location['y'] + _size['height'] return _wholePage.crop((_left, _top, _right, _bottom)) ``` Thanks.
2016/05/12
[ "https://Stackoverflow.com/questions/37187962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3425211/" ]
You can use square brackets to create a reference to an array: ``` pass_in( $str, [qw(A B C D E)]); ``` [perldoc perlref](http://perldoc.perl.org/perlref.html#Making-References)
In order to pass an in array, you have must an array to pass! `qw()` does not create an array. It just puts a bunch of scalars on the stack. That for which you are looking is `[ ]`. It conveniently creates an array, initializes the array using the expression within, and returns a reference to the array. ``` pass_in( $str, [qw( A B C D E )] ); ``` Alternatively, you could rewrite your subroutine to accept a list of values. ``` sub pass_in { my $str = shift; for my $e (@_) { print "I see str $str and list elem: $e\n"; } return 0; } pass_in( "hello", qw( A B C D E ) ); ```
23,183,868
I was going through a very simple python3 guide to using string operations and then I ran into this weird error: ``` In [4]: # create string string = 'Let\'s test this.' # test to see if it is numeric string_isnumeric = string.isnumeric() Out [4]: AttributeError Traceback (most recent call last) <ipython-input-4-859c9cefa0f0> in <module>() 3 4 # test to see if it is numeric ----> 5 string_isnumeric = string.isnumeric() AttributeError: 'str' object has no attribute 'isnumeric' ``` The problem is that, as far as I can tell, `str` **[DOES](http://www.tutorialspoint.com/python/string_isnumeric.htm)** have an attribute, `isnumeric`.
2014/04/20
[ "https://Stackoverflow.com/questions/23183868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2935984/" ]
No, `str` objects do not have an `isnumeric` method. `isnumeric` is only available for unicode objects. In other words: ``` >>> d = unicode('some string', 'utf-8') >>> d.isnumeric() False >>> d = unicode('42', 'utf-8') >>> d.isnumeric() True ```
`isnumeric()` only works on Unicode strings. To define a string as Unicode you could change your string definitions like so: ``` In [4]: s = u'This is my string' isnum = s.isnumeric() ``` This will now store False. Note: I also changed your variable name in case you imported the module string.
23,183,868
I was going through a very simple python3 guide to using string operations and then I ran into this weird error: ``` In [4]: # create string string = 'Let\'s test this.' # test to see if it is numeric string_isnumeric = string.isnumeric() Out [4]: AttributeError Traceback (most recent call last) <ipython-input-4-859c9cefa0f0> in <module>() 3 4 # test to see if it is numeric ----> 5 string_isnumeric = string.isnumeric() AttributeError: 'str' object has no attribute 'isnumeric' ``` The problem is that, as far as I can tell, `str` **[DOES](http://www.tutorialspoint.com/python/string_isnumeric.htm)** have an attribute, `isnumeric`.
2014/04/20
[ "https://Stackoverflow.com/questions/23183868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2935984/" ]
`isnumeric()` only works on Unicode strings. To define a string as Unicode you could change your string definitions like so: ``` In [4]: s = u'This is my string' isnum = s.isnumeric() ``` This will now store False. Note: I also changed your variable name in case you imported the module string.
if using python 3 wrap string around **str** as shown below > > str('hello').isnumeric() > > > This way it behaving as expected
23,183,868
I was going through a very simple python3 guide to using string operations and then I ran into this weird error: ``` In [4]: # create string string = 'Let\'s test this.' # test to see if it is numeric string_isnumeric = string.isnumeric() Out [4]: AttributeError Traceback (most recent call last) <ipython-input-4-859c9cefa0f0> in <module>() 3 4 # test to see if it is numeric ----> 5 string_isnumeric = string.isnumeric() AttributeError: 'str' object has no attribute 'isnumeric' ``` The problem is that, as far as I can tell, `str` **[DOES](http://www.tutorialspoint.com/python/string_isnumeric.htm)** have an attribute, `isnumeric`.
2014/04/20
[ "https://Stackoverflow.com/questions/23183868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2935984/" ]
No, `str` objects do not have an `isnumeric` method. `isnumeric` is only available for unicode objects. In other words: ``` >>> d = unicode('some string', 'utf-8') >>> d.isnumeric() False >>> d = unicode('42', 'utf-8') >>> d.isnumeric() True ```
One Liners: ``` unicode('200', 'utf-8').isnumeric() # True unicode('unicorn121', 'utf-8').isnumeric() # False ``` Or ``` unicode('200').isnumeric() # True unicode('unicorn121').isnumeric() # False ```
23,183,868
I was going through a very simple python3 guide to using string operations and then I ran into this weird error: ``` In [4]: # create string string = 'Let\'s test this.' # test to see if it is numeric string_isnumeric = string.isnumeric() Out [4]: AttributeError Traceback (most recent call last) <ipython-input-4-859c9cefa0f0> in <module>() 3 4 # test to see if it is numeric ----> 5 string_isnumeric = string.isnumeric() AttributeError: 'str' object has no attribute 'isnumeric' ``` The problem is that, as far as I can tell, `str` **[DOES](http://www.tutorialspoint.com/python/string_isnumeric.htm)** have an attribute, `isnumeric`.
2014/04/20
[ "https://Stackoverflow.com/questions/23183868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2935984/" ]
No, `str` objects do not have an `isnumeric` method. `isnumeric` is only available for unicode objects. In other words: ``` >>> d = unicode('some string', 'utf-8') >>> d.isnumeric() False >>> d = unicode('42', 'utf-8') >>> d.isnumeric() True ```
if using python 3 wrap string around **str** as shown below > > str('hello').isnumeric() > > > This way it behaving as expected
23,183,868
I was going through a very simple python3 guide to using string operations and then I ran into this weird error: ``` In [4]: # create string string = 'Let\'s test this.' # test to see if it is numeric string_isnumeric = string.isnumeric() Out [4]: AttributeError Traceback (most recent call last) <ipython-input-4-859c9cefa0f0> in <module>() 3 4 # test to see if it is numeric ----> 5 string_isnumeric = string.isnumeric() AttributeError: 'str' object has no attribute 'isnumeric' ``` The problem is that, as far as I can tell, `str` **[DOES](http://www.tutorialspoint.com/python/string_isnumeric.htm)** have an attribute, `isnumeric`.
2014/04/20
[ "https://Stackoverflow.com/questions/23183868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2935984/" ]
One Liners: ``` unicode('200', 'utf-8').isnumeric() # True unicode('unicorn121', 'utf-8').isnumeric() # False ``` Or ``` unicode('200').isnumeric() # True unicode('unicorn121').isnumeric() # False ```
if using python 3 wrap string around **str** as shown below > > str('hello').isnumeric() > > > This way it behaving as expected
46,257,064
I'm trying to create a piece of code in python that allows the user to enter their username, password and date of birth and then allows them to change this information. This is what I have so far. ``` import sqlite3 conn=sqlite3.connect("Database.db") cursor=conn.cursor() def createTable(): cursor.execute("CREATE TABLE IF NOT EXISTS userInfo(username TEXT, password TEXT, dateOfBirth TEXT)") def enterData(): inputUser=input("Enter your username") inputPass=input("Enter your password") inputDoB=input("Enter your date of birth") cursor.execute("INSERT INTO userInfo (username, password, dateOfBirth) VALUES (?, ?, ?)", (inputUser, inputPass, inputDoB)) conn.commit() def modifyData(): update=input("would you like to change your username") if update=="yes": newUsername=input("Update your username") cursor.execute("UPDATE userInfo SET username='?' WHERE username='?'",(newUsername, user)) conn.commit createTable() enterData() modifyData() ``` It allows me to enter the data but I don't know the specific syntax for updating the data value to a variable. When I try and run this code, this error appears: ``` sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 7 supplied. ``` Any help would be greatly appreciated.
2017/09/16
[ "https://Stackoverflow.com/questions/46257064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8619721/" ]
When I've copied it and run the first error that occurred said that variable `user` is not defined. Therefore you need to either send it to function `modifyData` from `enterData` or ask the user for it. Then I've got the error you've mentioned. Just remove the single quotes around `?` Code: ``` def modify_data(): update = input('Would you like to change your username[y/N]: ') if update.lower() == 'y': old_username = input('Old username: ') new_username = input('Update your username: ') cursor.execute('UPDATE userInfo SET username=? WHERE username=?', (new_username, old_username)) conn.commit() ``` By the way, I've found [this tool](http://sqlitebrowser.org/) that can help you visualize it. (It's free and open source)
You probably want `raw_input`, not `input`. `raw_input` reads data from standard input and returns it. `input()` is equivelant to `eval(raw_input())`: i.e., it evaluates the input as Python code. I'm not 100% sure if this is your root problem though, if you've already been using quotes around your input? Or maybe you're not -- can you provide all the input and output from a run of this program?
67,670,537
I have an Amazon S3 server filled with multiple buckets, each bucket containing multiple subfolders. There are easily 50,000 files in total. I need to generate an excel sheet that contains the path/url of each file in each bucket. For eg, If I have a bucket called b1, and it has a file called f1.txt, I want to be able to export the path of f1 as b1/f1.txt. This needs to be done for every one of the 50,000 files. I have tried using S3 browsers like Expandrive and Cyberduck, however they require you to select each and every file to copy their urls. I also tried exploring the boto3 library in python, however I did not come across any in built functions to get the file urls. I am looking for any tool I can use, or even a script I can execute to get all the urls. Thanks.
2021/05/24
[ "https://Stackoverflow.com/questions/67670537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8018877/" ]
Do you have access to the aws cli? `aws s3 ls --recursive {bucket}` will list all nested files in a bucket. Eg this bash command will list all buckets, then recursively print all files in each bucket: ``` aws s3 ls | while read x y bucket; do aws s3 ls --recursive $bucket | while read x y z path; do echo $path; done; done ``` (the 'read's are just to strip off uninteresting columns). nb I'm using v1 CLI.
Amazon s3 inventory can help you with this use case. Do evaluate that option. refer: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/storage-inventory.html>
67,670,537
I have an Amazon S3 server filled with multiple buckets, each bucket containing multiple subfolders. There are easily 50,000 files in total. I need to generate an excel sheet that contains the path/url of each file in each bucket. For eg, If I have a bucket called b1, and it has a file called f1.txt, I want to be able to export the path of f1 as b1/f1.txt. This needs to be done for every one of the 50,000 files. I have tried using S3 browsers like Expandrive and Cyberduck, however they require you to select each and every file to copy their urls. I also tried exploring the boto3 library in python, however I did not come across any in built functions to get the file urls. I am looking for any tool I can use, or even a script I can execute to get all the urls. Thanks.
2021/05/24
[ "https://Stackoverflow.com/questions/67670537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8018877/" ]
What you should do is have a look again at boto3 documentation as it is what you are looking for. It is fairly simple to do what you are asking but may take you a bit of reading if you are new to it. Since there is multiple steps involved I will try to steer you in the right direction. In boto3 for S3 the method you are looking for is `list_objects_v2()`. This will give you the 'Key' or object path of every object. You will notice that it will return the entire json blob for each object. Since you only are interested in the Key, you can target this just the same way you would access Key/Values in a dict. E.g. `list_objects_v2()['Contents'][0]['Key']` should return only object path of the very first object. If you've got that working the next step is to try to loop and get all values. You can either use a for loop to do this or there is an awesome python package I regularly use called jmespath - <https://jmespath.org/> Here is how you can retrieve all object paths up to 1000 objects in one line. ``` import jmespath bucket_name='im-a-bucket' s3_client = boto3.client('s3') bucket_object_paths = jmespath.search('Contents[*].Key', s3_client.list_objects_v2(Bucket=bucket_name)) ``` Now since your buckets may have more than 1000 objects, you will need to use the paginator to do this. Have a look at this to understand it. [How to get more than 1000 objects from S3 by using list\_objects\_v2?](https://stackoverflow.com/questions/54314563/how-to-get-more-than-1000-objects-from-s3-by-using-list-objects-v2) Basically the way it works is only 1000 objects can be returned. To overcome this we use a paginator which allows you to return the entire result and treats the limit of 1000 as a pagination so you just need to also use it within a for loop to get all the results you are looking for. Once you get this working for one bucket, store the result in a variable which will be of type list and repeat for the rest of the buckets. Once you have all this data you could easily just copy paste it into an excel sheet or use python to do it. (Haven't tested the code snippets but they should work).
Amazon s3 inventory can help you with this use case. Do evaluate that option. refer: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/storage-inventory.html>