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
21,946,883
I'm writing a function to shift text by 13 spaces. The converted chars need to preserve case, and if the characters aren't letters then they should pass through unshifted. I wrote the following function: ``` def rot13(str): result = "" for c in str: if 65 <= ord(c) <= 96: result += chr((ord(c) - ord('A') + 13)%26 + ord('A')) if 97 <= ord(c) <= 122: result += chr((ord(c) - ord('a') + 13)%26 + ord('a')) else: result += c print result ``` What I have found is that lowercase letters and non-letter characters work fine. However, when the function is applied to uppercase chars the function returns the shifted char FOLLOWED BY the original char. I know there are plenty of solutions to this problem on SO, but this specific error has me wondering what's wrong with my logic or understanding of chars and loops in python. Any help appreciated.
2014/02/21
[ "https://Stackoverflow.com/questions/21946883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1036605/" ]
You are missing the "else" statement, so if the first if "fires" (`c` is an uppercase letter) then the "else" from the second if also "fires" (and concatenates the uppercase letter, as `ord(c)` is not between `97` and `122`) ``` def rot13(str): result = "" for c in str: if 65 <= ord(c) <= 96: result += chr((ord(c) - ord('A') + 13)%26 + ord('A')) elif 97 <= ord(c) <= 122: result += chr((ord(c) - ord('a') + 13)%26 + ord('a')) else: result += c print result ``` Also, uppercase characters **end** with `ord('Z')==90`, ASCII characters between `91` and `96` are **not** letters. Function should also **return** the value, not print it (unless it is called `print_rot13`). Your function is also inconsistent - you use `ord('A')` in calculations, but actual, hard-coded value in if (`65`) you should decide on **one** of these. ``` def rot13(str): a = ord('a') z = ord('z') A = ord('A') Z = ord('Z') result = "" for c in str: symbol = ord(c) if A <= symbol <= Z: result += chr((symbol - A + 13)%26 + A) elif a <= symbol <= z: result += chr((symbol - a + 13)%26 + a) else: result += symbol return result ``` This way it only assume, that lower and upper case letters are arranged in consistent blocks, but nothing about their actual `ord` values.
This is an (rather contrived) one-liner implementation for the caesar cipher in python: ``` cipher = lambda w, s: ''.join(chr(a + (i - a + s) % 26) if (a := 65) <= (i := ord(c)) <= 90 or (a := 97) <= i <= 122 else c for c in w) word = 'Hello, beautiful World!' print(cipher(word, 13)) # positive shift # Uryyb, ornhgvshy Jbeyq! word = 'Uryyb, ornhgvshy Jbeyq!' print(cipher(word, -13)) # -13 shift means decipher a +13 shift # Hello, beautiful World! ``` It rotates only ascii alpha letters, respects upper/lower case, and handles positive and negative shifts (even shifts bigger that the alphabet). More details in [this answer](https://stackoverflow.com/a/71553427/2938526).
15,054,598
So I created my project with a virtual environment and installed pip + distribute. Everything is fine so far, But when I click on the install button to install new packages it displays a beautiful : "Nothing to show". Here is an image of it : ![enter image description here](https://i.stack.imgur.com/XGmSy.jpg) I have the [default repository](http://pypi.python.org/pypi) So what did I do wrong? Is this not the right way to install python modules like PIL or third party django apps like django south ? Edit : I forgot to mention , it's the trial version... Can this be because of it ?
2013/02/24
[ "https://Stackoverflow.com/questions/15054598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970581/" ]
The problem is caused by recent server-side changes in PyPI, and will be addressed in the PyCharm 2.7.1 update. Please see <http://youtrack.jetbrains.com/issue/PY-8962> to track the status of the issue.
If you are behind a proxy (e.g. in a corporate environment), then you may need to configure your proxy settings for PyCharm to show the packages. These are in Pycharm under: > > File -> Settings -> Appearance & Behaviour -> System Settings -> HTTP Proxy > > > Enter your proxy settings there, e.g. a host name and port number. If you don't know your proxy settings then this question may be useful: [How to see the proxy settings on windows?](https://stackoverflow.com/questions/22368515/how-to-see-the-proxy-settings-on-windows/30751938#30751938)
15,054,598
So I created my project with a virtual environment and installed pip + distribute. Everything is fine so far, But when I click on the install button to install new packages it displays a beautiful : "Nothing to show". Here is an image of it : ![enter image description here](https://i.stack.imgur.com/XGmSy.jpg) I have the [default repository](http://pypi.python.org/pypi) So what did I do wrong? Is this not the right way to install python modules like PIL or third party django apps like django south ? Edit : I forgot to mention , it's the trial version... Can this be because of it ?
2013/02/24
[ "https://Stackoverflow.com/questions/15054598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970581/" ]
The problem is caused by recent server-side changes in PyPI, and will be addressed in the PyCharm 2.7.1 update. Please see <http://youtrack.jetbrains.com/issue/PY-8962> to track the status of the issue.
I faced such problem man y times and every time I found that the problem corresponds to my internet connection. check your internet connection with tools like wget or curl in linux and browsers in windows.
28,398,240
I want to run my python function in console like this: ``` my_function_name ``` at any directory, I tried to follow arajek's answer in this question: [run a python script in terminal without the python command](https://stackoverflow.com/questions/15587877/run-a-python-script-in-terminal-without-the-python-command) but I still need to call `my_function_name.py` to make it work. If I call only `my_function_name`, the console will inform me `command not found` . I also tried to add a symbolic link with this answer: [Running a Python Script Like a Built-in Shell Command](https://stackoverflow.com/questions/16752935/running-a-python-script-like-a-built-in-shell-command) but it failed `sudo ln -s my_function_name.py /home/thovo/test/my_function_name` `ln: failed to create symbolic link ‘/home/thovo/test/my_function_name/my_function_name.py’: File exists`
2015/02/08
[ "https://Stackoverflow.com/questions/28398240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1154698/" ]
Change the name of the script to no longer have the `.py` extension.
Add this shebang to the top of your file: `#!/usr/bin/env python` and remove the file extension.
1,131,582
I am using Boost with Visual Studio 2008 and I have put the path to boost directory in configuration for the project in C++/General/"Additional Include Directories" and in Linker/General/"Additional Library Directories". (as it says here: <http://www.boost.org/doc/libs/1_36_0/more/getting_started/windows.html#build-from-the-visual-studio-ide>) When I build my program, I get an error: fatal error C1083: Cannot open include file: 'boost/python.hpp': No such file or directory I have checked if the file exists, and it is on the path. I would be grateful if anyone can solve this problem. The boost include path is `C:\Program Files\boost\boost_1_36_0\boost`. Linker path is `C:\Program Files\boost\boost_1_36_0\lib`. The file `python.hpp` exists on the include path.
2009/07/15
[ "https://Stackoverflow.com/questions/1131582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Where is the file located, and which include path did you specify? (And how is the file `#include`'d) There's a mismatch between some of these But it's impossible to say what's wrong when you haven't shown what you actually did. **Edit**: Given the paths you mentioned in comments, the problem is that they don't add up. If the include path is `C:\Program Files\boost\boost_1_36_0\boost`, and you then try to include 'boost/python.hpp", the compiler searches for this file in the include path, which means it looks for `C:\Program Files\boost\boost_1_36_0\boost\boost\python.hpp`, which doesn't exist. The include path should be set to `C:\Program Files\boost\boost_1_36_0` instead.
How do you include it? You should write something like this: ``` #include <boost/python.hpp> ``` Note that `Additional Include Directories` settings are differs in `Release` and `Debug` configurations. You should make them the same. If boost placed to `C:\Program Files\boost\boost_1_36_0\` you should set path to `C:\Program Files\boost\boost_1_36_0\` without `boost` in the end.
61,713,057
I'm working on [google colaboratory](https://colab.research.google.com/) and i have to do some elaboration to some files based on their extensions, like: ``` !find ./ -type f -name "*.djvu" -exec file '{}' ';' ``` and i expect an output: ``` ./file.djvu: DjVu multiple page document ``` but when i try to mix bash and python to use a list of exensions: ``` for f in file_types: !echo "*.{f}" !find ./ -type f -name "*.{f}" -exec file '{}' ';' !echo "*.$f" !find ./ -type f -name "*.$f" -exec file '{}' ';' ``` i get only the output of both the `echo` but not of the files. ``` *.djvu *.djvu *.jpg *.jpg *.pdf *.pdf ``` If i remove the `exec` part it actually find the files so i can't figure out why the `find` command combined with `exec` fail in some manner. If needed i can provide more info/examples.
2020/05/10
[ "https://Stackoverflow.com/questions/61713057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8069500/" ]
I found an ugly workaround passing trought a file, so first i write the array to a file in python: ``` with open('/content/file_types.txt', 'w') as f: for ft in file_types: f.write(ft + '\n') ``` and than i read and use it from bash in another cell: ``` %%bash filename=/content/protected_file_types.txt while IFS= read -r f; do find ./ -name "*.$f" -exec file {} ';' ; done < $filename ``` Doing so i dont mix bash and python in the same cell as suggested in the comment of another [answer](https://stackoverflow.com/a/61713349/8069500). I hope to find a better solution that maybe use some trick that I'm not aware of.
This works for me ``` declare -a my_array=("pdf" "py") for i in ${my_array[*]}; do find ./ -type f -name "*.$i" -exec file '{}' ';'; done; ```
65,362,747
I'd like to slice a tensor (multi-dimensional array) using Rust's [ndarray](https://docs.rs/ndarray) library, but the catch is that the tensor is dynamically shaped and the slice is stored in a user provided variable. If I knew the dimensionality up front, I expect I could simply do the following, where `idx` is the user provided index and `x` is a 4 dimensional tensor: ```rust // should give a 1D tensor as a view on the last axis at index `idx` x.slice(s![idx[0], idx[1], idx[2], ..]) ``` BUT because I don't know the dimensionality up front, I cant manually unpack `idx` that way and feed it to the slice macro `s!`. In python I might do it [this way](https://numpy.org/doc/stable/user/basics.indexing.html#dealing-with-variable-numbers-of-indices-within-programs), where `idx` was a user provided tuple: ```py # if `len(idx)` was 2 but `x.ndim` was 3, we could get a 1d tensor, of length `x.shape[-1]` x[idx] ``` Whats the proper way to do this in Rust? The [ndarray for numpy users](https://docs.rs/ndarray/0.14.0/ndarray/doc/ndarray_for_numpy_users/index.html#indexing-and-slicing) only shows how to do it with scalar values given to `s!`
2020/12/18
[ "https://Stackoverflow.com/questions/65362747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7681811/" ]
You want to get the **"Bin On Hand"** fields: You can get Location, Bin Number and On Hand from this join in your Saved Search. When done your results fields should be: * Bin On Hand:Location * Bin On Hand:Bin Number * Bin On Hand:On Hand Todd Stafford
From Admin role: List > Search > Saved Searches > New > Inventory Balance In the results menu: 1. Item 2. Inventory Location 3. Bin 4. Quantity On Hand.
67,157,938
Trying to search no of times word appears in a file using python file handling. For example was trying to search 'believer' in the lyrics of believer song that how many times believer comes. It appears 18 times but my program is giving 12. What are the conditions I am missing. ``` def no_words_function(): f=open("believer.txt","r") data = f.read() cnt=0 ws = input("Enter word to find: ") word = data.split() for w in word: if w in ws: cnt+=1 f.close() print(ws,"found",cnt,"times in the file.") no_words_function() ```
2021/04/19
[ "https://Stackoverflow.com/questions/67157938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7762964/" ]
I would suggest you adding object properties conditionally with ES6 syntax like this. ```js const normalizeData = ({id, name = ""}) => { const condition = !!name; // Equivalent to: name !== undefined && name !== ""; return {id, ...(condition && { name })}; } console.log(normalizeData({id: 123, name: ""})); console.log(normalizeData({id: 123, name: undefined})); console.log(normalizeData({id: 123, name: "Phong_Nguyen"})); ``` **Explain:** * Using [`Default function parameters`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) at line code `name = ""` to avoid `undefined` of name propety having not included in input object. * Using [`Destructuring assignment`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) at line code `...(condition && { name })`
You can create the object with the id first and then add a name afterwards: ``` const obj = {id: 123}; if(name) obj.name = name; axios.post('saveUser', obj); ```
61,431,924
here is my problem : I wrote a python bot that makes plenty of stuff, including printing colorful text for better understanding. I'm using the colorama package because it prints color even on windows command prompt. Here is how I use colorama, which work both on unix and windows using python 3.8 : ``` from colorama import Fore, init init() print(Fore.RED + 'some red text') ``` Now my goal is to transform my script into a .exe so it can run on windows without any install. Problem is, using pyinstaller.exe --onefile script.py, or pyinstaller.exe --onedir script.py or whatever, I can't make it work. Pyinstaller builds a EXE successfully with 0 error message, but whenever I launch the exe I get : `ModuleNotFoundError: No module named 'colorama'` and it's the only module missing. I've searched through the entire internet, and didn't manage to fix that by myself. You guys are my last hope ! please help me
2020/04/25
[ "https://Stackoverflow.com/questions/61431924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13407332/" ]
Try: ``` pyinstaller.exe --onefile --hidden-import colorama script.py ``` This (--hidden-import colorama) should ensure that pyinstaller builds the application including colorama.
you should run `pip/pipenv install colorama` at first.
14,260,714
PyDev is reporting import errors which don't exist. The initial symptom was a fake "unresolved import" error, which was fixed by some combination of: * Cleaning the Project * Re-indexing the project (remove interpreter, add again) * Restarting Eclipse * Burning incense to the Python deities Now the error is "unverified variable from import"--it can't seem to find pymssql.connect. This IS NOT a PYHTONPATH problem. I can access the module just fine, the code in the file with the (alleged) error runs fine---it has unit tests and production code calling it. The error is somewhere in PyDev: I added a new module to my PyDev project, and the error only occurs in the new module. I've tried all of the above. --- So, I was planning on posting this code somewhere else to solicit some comments about the design, and I was asked in the comments to post code. (Inspired by: [Database connection wrapper](https://stackoverflow.com/questions/9367857/database-connection-wrapper) and Clint Miller's answer to this question: [How do I correctly clean up a Python object?](https://stackoverflow.com/questions/865115/how-do-i-correctly-clean-up-a-python-object)). The import error happens at line 69 (self.connection = pymssql.connect...). Not sure what good this does in answering the question, but... ``` import pymssql from util.require_type import require_type class Connections(object): @require_type('host', str) @require_type('user', str) @require_type('password', str) @require_type('database', str) @require_type('as_dict', bool) def __init__(self, host, user, password, database, as_dict=True): self.host = host self.user = user self.password = password self.db = database self.as_dict = as_dict @staticmethod def server1(db): return Connections('','','','') @staticmethod def server2(db): pass @staticmethod def server3(db): pass class DBConnectionSource(object): # Usage: # with DBConnectionSource(ConnectionParameters.server1(db = 'MyDB)) as dbConn: # results = dbConn.execute(sqlStatement) @require_type('connection_parameters', Connections) def __init__(self, connection_parameters=Connections.server1('MyDB')): self.host = connection_parameters.host self.user = connection_parameters.user self.password = connection_parameters.password self.db = connection_parameters.db self.as_dict = connection_parameters.as_dict self.connection = None def __enter__(self): parent = self class DBConnection(object): def connect(self): self.connection = pymssql.connect(host=parent.host, user=parent.user, password=parent.password, database=parent.db, as_dict=parent.as_dict) def execute(self, sqlString, arguments={}): if self.connection is None: raise Exception('DB Connection not defined') crsr = self.connection.cursor() crsr.execute(sqlString, arguments) return list(crsr) def cleanup(self): if self.connection: self.connection.close() self.connection = DBConnection() self.connection.connect() return self.connection def __exit__(self, typ, value, traceback): self.connection.cleanup() ```
2013/01/10
[ "https://Stackoverflow.com/questions/14260714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/963250/" ]
Try `ctrl+1` at the line where the error and add a comment saying that you are expecting that import. This should resolve the PyDev error, as it does static code analysis and not runtime analysis.
I added # @UndefinedVariable to the end of the line throwing the error. This isn't much of a permanent fix, but at least it got rid of the red from my screen for the time being. If there is a better long term fix, I would be happy to hear it.
14,260,714
PyDev is reporting import errors which don't exist. The initial symptom was a fake "unresolved import" error, which was fixed by some combination of: * Cleaning the Project * Re-indexing the project (remove interpreter, add again) * Restarting Eclipse * Burning incense to the Python deities Now the error is "unverified variable from import"--it can't seem to find pymssql.connect. This IS NOT a PYHTONPATH problem. I can access the module just fine, the code in the file with the (alleged) error runs fine---it has unit tests and production code calling it. The error is somewhere in PyDev: I added a new module to my PyDev project, and the error only occurs in the new module. I've tried all of the above. --- So, I was planning on posting this code somewhere else to solicit some comments about the design, and I was asked in the comments to post code. (Inspired by: [Database connection wrapper](https://stackoverflow.com/questions/9367857/database-connection-wrapper) and Clint Miller's answer to this question: [How do I correctly clean up a Python object?](https://stackoverflow.com/questions/865115/how-do-i-correctly-clean-up-a-python-object)). The import error happens at line 69 (self.connection = pymssql.connect...). Not sure what good this does in answering the question, but... ``` import pymssql from util.require_type import require_type class Connections(object): @require_type('host', str) @require_type('user', str) @require_type('password', str) @require_type('database', str) @require_type('as_dict', bool) def __init__(self, host, user, password, database, as_dict=True): self.host = host self.user = user self.password = password self.db = database self.as_dict = as_dict @staticmethod def server1(db): return Connections('','','','') @staticmethod def server2(db): pass @staticmethod def server3(db): pass class DBConnectionSource(object): # Usage: # with DBConnectionSource(ConnectionParameters.server1(db = 'MyDB)) as dbConn: # results = dbConn.execute(sqlStatement) @require_type('connection_parameters', Connections) def __init__(self, connection_parameters=Connections.server1('MyDB')): self.host = connection_parameters.host self.user = connection_parameters.user self.password = connection_parameters.password self.db = connection_parameters.db self.as_dict = connection_parameters.as_dict self.connection = None def __enter__(self): parent = self class DBConnection(object): def connect(self): self.connection = pymssql.connect(host=parent.host, user=parent.user, password=parent.password, database=parent.db, as_dict=parent.as_dict) def execute(self, sqlString, arguments={}): if self.connection is None: raise Exception('DB Connection not defined') crsr = self.connection.cursor() crsr.execute(sqlString, arguments) return list(crsr) def cleanup(self): if self.connection: self.connection.close() self.connection = DBConnection() self.connection.connect() return self.connection def __exit__(self, typ, value, traceback): self.connection.cleanup() ```
2013/01/10
[ "https://Stackoverflow.com/questions/14260714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/963250/" ]
***TL;DR version: read the fifth grey box.*** Your problem (and mine) appears to be due to multiple levels of imports that should be, but is not, handled correctly. Somewhere along the line, linkage is lost. Assume for a moment that you have a file ``` foo/bar.py ``` and that within that file, you have a symbol named ``` wazoo=15 ``` If you then try: ``` from foo import bar from bar import wazoo <-- false error here ``` Or if you try to use: ``` from foo import bar ... i = bar.wazoo <-- false error here ``` You ***may*** get the false unresolved error on ***wazoo***. Being a bug, this is obviously inconsistent. If however, you do the following: ``` from foo.bar import wazoo ``` The problems do seem to go away. As an aside, I've noted that this sometime seems to happen for newly-defined symbols within an imported file. Furthermore, the earlier false errors for some symbols within that file will magically disappear, with the only the new error remaining. This implies that there might be some sort of state file that isn't being cleaned, EVEN WHEN you "buildall", etc. Note also that this problem seems to occur the most for me when I use the Python enum hack...perhaps this will provide a clue to the PyDev-elopers (is PyDev even being maintained anymore?): bar.py: ``` def enum(**enums): return type('Enum', (), enums) SOMETHING = enum(A=1, B=2) ``` someotherfile.py: ``` from foo import bar from bar import SOMETHING ... x = SOMETHING.A ```
I added # @UndefinedVariable to the end of the line throwing the error. This isn't much of a permanent fix, but at least it got rid of the red from my screen for the time being. If there is a better long term fix, I would be happy to hear it.
38,542,675
I'd appreciate some help with the diagnosis. The error messages either point to the possibility that this package cannot be installed on a 64 bit machine or the wrong compiler is being selected. **Edit:** The [requirements](http://vmprof.readthedocs.io/en/latest/vmprof.html#requirements) for `vmprof` state that it will only run on x86 (32 bit). It's clear that the C compiler ought to be instructed into compiling the source into 32 bit. Does that point to a shortfall in the vmprof packaging which should be raised as a vmprof issue? **End edit.** Either way, I don't know how to solve that problem. I am running `pip install vmprof` from the command line. warning C4311: [This warning detects 64-bit pointer truncation issues.](http://msdn.microsoft.com/en-us/library/4t91x2k5.aspx) warning C4312: [This warning detects an attempt to assign a 32-bit value to a 64-bit pointer type](http://msdn.microsoft.com/en-us/library/h97f4b9y.aspx) These two warnings lead me to wonder if PyPi cannot install vmprof into my 64 bit environment. However, if the presented error output is ordered by time, then it appears that Visual Studio was loaded after these warnings were generated. Could this point to the wrong compiler being used? I do have a large set of Microsoft Visual C++ YYYY Redistributable from 2005 onwards for 32 and 64 bits. (I'm reluctant to test the wrong compiler theory by uninstalling older versions in case that breaks something.) PyPi says it tried to load Microsoft Visual Studio v14.0 which I believe to be the correct version for Python 3.5. There are [other SO questions](https://stackoverflow.com/questions/21650763/pip-installation-error-command-python-setup-py-egg-info-failed-with-error-code) relating to the warning, "manifest\_maker: standard file '-c' not found" My setuptools is fully up to date. (v 25.0.0). vmprof is not available as a prebuilt binary from the link suggested. In any case, all of the binaries there are unsupported. Other SO questions on this warning pertain to Unix. warning LNK4197: [export 'PyInit\_\_vmprof' specified multiple times; using first specification.](http://msdn.microsoft.com/en-us/library/dt1zk962.aspx) This is the point at which the build finally seemed to go off the rails. I'm guessing the multiple specification of "export 'PyInit\_\_vmprof'" is inside a command file supplied as part of vmprof. error LNK2001: [unresolved external symbol \_PyThreadState\_Current build\lib.win-amd64-3.5\_vmprof.cp35-win\_amd64.pyd : fatal error LNK1120: 1 unresolved externals.](http://msdn.microsoft.com/en-us/library/f6xx1b1z.aspx) And here it crashed with a link error. The full pip install output follows. ``` Installing collected packages: requests, vmprof Running setup.py install for vmprof error Complete output from command d:\python35\python.exe -u -c "import setuptools, tokenize;__file__='D:\\Users\\Stephen\ \AppData\\Local\\Temp\\pip-build-dpjo8j82\\vmprof\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read ().replace('\r\n', '\n'), __file__, 'exec'))" install --record D:\Users\Stephen\AppData\Local\Temp\pip-kfygn2le-record\i nstall-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build\lib.win-amd64-3.5 creating build\lib.win-amd64-3.5\tests copying tests\cpuburn.py -> build\lib.win-amd64-3.5\tests copying tests\test_config.py -> build\lib.win-amd64-3.5\tests copying tests\test_reader.py -> build\lib.win-amd64-3.5\tests copying tests\test_run.py -> build\lib.win-amd64-3.5\tests copying tests\test_stats.py -> build\lib.win-amd64-3.5\tests copying tests\__init__.py -> build\lib.win-amd64-3.5\tests creating build\lib.win-amd64-3.5\vmprof copying vmprof\binary.py -> build\lib.win-amd64-3.5\vmprof copying vmprof\cli.py -> build\lib.win-amd64-3.5\vmprof copying vmprof\profiler.py -> build\lib.win-amd64-3.5\vmprof copying vmprof\reader.py -> build\lib.win-amd64-3.5\vmprof copying vmprof\show.py -> build\lib.win-amd64-3.5\vmprof copying vmprof\stats.py -> build\lib.win-amd64-3.5\vmprof copying vmprof\upload.py -> build\lib.win-amd64-3.5\vmprof copying vmprof\vmprofdemo.py -> build\lib.win-amd64-3.5\vmprof copying vmprof\__init__.py -> build\lib.win-amd64-3.5\vmprof copying vmprof\__main__.py -> build\lib.win-amd64-3.5\vmprof creating build\lib.win-amd64-3.5\vmprof\log copying vmprof\log\constants.py -> build\lib.win-amd64-3.5\vmprof\log copying vmprof\log\marks.py -> build\lib.win-amd64-3.5\vmprof\log copying vmprof\log\merge_point.py -> build\lib.win-amd64-3.5\vmprof\log copying vmprof\log\objects.py -> build\lib.win-amd64-3.5\vmprof\log copying vmprof\log\parser.py -> build\lib.win-amd64-3.5\vmprof\log copying vmprof\log\__init__.py -> build\lib.win-amd64-3.5\vmprof\log running egg_info writing entry points to vmprof.egg-info\entry_points.txt writing requirements to vmprof.egg-info\requires.txt writing dependency_links to vmprof.egg-info\dependency_links.txt writing top-level names to vmprof.egg-info\top_level.txt writing vmprof.egg-info\PKG-INFO warning: manifest_maker: standard file '-c' not found reading manifest file 'vmprof.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'vmprof.egg-info\SOURCES.txt' running build_ext building '_vmprof' extension creating build\temp.win-amd64-3.5 creating build\temp.win-amd64-3.5\Release creating build\temp.win-amd64-3.5\Release\src D:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Id: \python35\include -Id:\python35\include "-ID:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-ID:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-ID:\Program Files (x86)\Windows Kits\8.1\include\shared" "-ID: \Program Files (x86)\Windows Kits\8.1\include\um" "-ID:\Program Files (x86)\Windows Kits\8.1\include\winrt" /Tcsrc/_vmpr of.c /Fobuild\temp.win-amd64-3.5\Release\src/_vmprof.obj _vmprof.c d:\users\stephen\appdata\local\temp\pip-build-dpjo8j82\vmprof\src\vmprof_common.h(67): warning C4311: 'type cast': p ointer truncation from 'PyCodeObject *' to 'unsigned long' d:\users\stephen\appdata\local\temp\pip-build-dpjo8j82\vmprof\src\vmprof_common.h(67): warning C4312: 'type cast': c onversion from 'unsigned long' to 'void *' of greater size d:\users\stephen\appdata\local\temp\pip-build-dpjo8j82\vmprof\src\vmprof_common.h(96): warning C4267: '=': conversio n from 'size_t' to 'char', possible loss of data d:\users\stephen\appdata\local\temp\pip-build-dpjo8j82\vmprof\src\vmprof_main_win32.h(31): warning C4267: 'function' : conversion from 'size_t' to 'unsigned int', possible loss of data d:\users\stephen\appdata\local\temp\pip-build-dpjo8j82\vmprof\src\vmprof_main_win32.h(48): warning C4267: 'initializ ing': conversion from 'size_t' to 'int', possible loss of data d:\users\stephen\appdata\local\temp\pip-build-dpjo8j82\vmprof\src\vmprof_main_win32.h(72): warning C4312: 'type cast ': conversion from 'DWORD' to 'void *' of greater size src/_vmprof.c(42): warning C4311: 'type cast': pointer truncation from 'PyCodeObject *' to 'unsigned long' src/_vmprof.c(42): warning C4312: 'type cast': conversion from 'unsigned long' to 'void *' of greater size src/_vmprof.c(69): warning C4311: 'type cast': pointer truncation from 'PyCodeObject *' to 'unsigned long' D:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MA NIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:d:\python35\libs /LIBPATH:d:\python35\PCbuild\amd64 "/LIBPATH:D:\Program File s (x86)\Microsoft Visual Studio 14.0\VC\LIB\amd64" "/LIBPATH:D:\Program Files (x86)\Windows Kits\10\lib\10.0.10240.0\ucr t\x64" "/LIBPATH:D:\Program Files (x86)\Windows Kits\8.1\lib\winv6.3\um\x64" /EXPORT:PyInit__vmprof build\temp.win-amd64 -3.5\Release\src/_vmprof.obj /OUT:build\lib.win-amd64-3.5\_vmprof.cp35-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.5\Re lease\src\_vmprof.cp35-win_amd64.lib _vmprof.obj : warning LNK4197: pip specified multiple times; using first specification Creating library build\temp.win-amd64-3.5\Release\src\_vmprof.cp35-win_amd64.lib and object build\temp.win-amd64- 3.5\Release\src\_vmprof.cp35-win_amd64.exp _vmprof.obj : error LNK2001: unresolved external symbol _PyThreadState_Current build\lib.win-amd64-3.5\_vmprof.cp35-win_amd64.pyd : fatal error LNK1120: 1 unresolved externals error: command 'D:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exi t status 1120 ```
2016/07/23
[ "https://Stackoverflow.com/questions/38542675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2409868/" ]
This is an issue on [vmprof's github repository](http://github.com/vmprof/vmprof-python/issues/92) which is unfixed at 8/23/2016.
Finally, `vmprof` from v0.4 officially supports 64bit Windows See the closed [GitHub Issue](https://github.com/vmprof/vmprof-python/issues/85)
27,032,218
I am using emacs-for-python provided by gabrielelanaro at this [link](https://github.com/gabrielelanaro/emacs-for-python). Indentation doesn't seem to be working for me at all. It doesn't happen automatically when I create a class, function or any other block of code that requires automatic indentation(if, for etc.) and press enter or `Ctrl + j`. Instead emacs says "Arithmetic Error". It doesn't happen when I press `Tab` anywhere in a .py file. Again, every `Tab` press causes "Arithmetic error". Also, when I manually indent code using spaces, I can't erase those spaces! Backspace-ing these indents also causes "Arithmetic Error". This problem surfaces when I use the regular `Python AC` mode as well. emacs : GNU Emacs 24.3.1 (x86\_64-pc-linux-gnu, GTK+ Version 3.10.7) of 2014-03-07 on lamiak, modified by Debian
2014/11/20
[ "https://Stackoverflow.com/questions/27032218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2696086/" ]
Check the value of `python-indent-offset`. If it is 0, change it `M-x set-variable RET python-indent-offset RET 4 RET`. Emacs tries to guess the offset used in a Python file when opening it. It might get confused and set that variable to 0 for some badly-formatted Python file. If this is indeed the problem, please do file a bug report using `M-x report-emacs-bug` and the text of the Python file so that the auto-detection can be fixed.
Can you comment the lines related to auto-complete in your init.el? ``` ; (add-to-list 'load-path "~/.emacs.d/auto-complete-1.3.1") ; (require 'auto-complete) ; (add-to-list 'ac-dictionary-directories "~/.emacs.d/ac-dict") ; (require 'auto-complete-config) ; (ac-config-default) ; (global-auto-complete-mode t) ```
27,032,218
I am using emacs-for-python provided by gabrielelanaro at this [link](https://github.com/gabrielelanaro/emacs-for-python). Indentation doesn't seem to be working for me at all. It doesn't happen automatically when I create a class, function or any other block of code that requires automatic indentation(if, for etc.) and press enter or `Ctrl + j`. Instead emacs says "Arithmetic Error". It doesn't happen when I press `Tab` anywhere in a .py file. Again, every `Tab` press causes "Arithmetic error". Also, when I manually indent code using spaces, I can't erase those spaces! Backspace-ing these indents also causes "Arithmetic Error". This problem surfaces when I use the regular `Python AC` mode as well. emacs : GNU Emacs 24.3.1 (x86\_64-pc-linux-gnu, GTK+ Version 3.10.7) of 2014-03-07 on lamiak, modified by Debian
2014/11/20
[ "https://Stackoverflow.com/questions/27032218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2696086/" ]
It is related to this bug <http://debbugs.gnu.org/cgi/bugreport.cgi?bug=15975> The quickest workaround which I found was too add Jorgens Answer into .emacs file, add the following at the end of your .emacs file ``` (add-hook 'python-mode-hook (lambda () (setq python-indent-offset 4))) ```
Can you comment the lines related to auto-complete in your init.el? ``` ; (add-to-list 'load-path "~/.emacs.d/auto-complete-1.3.1") ; (require 'auto-complete) ; (add-to-list 'ac-dictionary-directories "~/.emacs.d/ac-dict") ; (require 'auto-complete-config) ; (ac-config-default) ; (global-auto-complete-mode t) ```
27,032,218
I am using emacs-for-python provided by gabrielelanaro at this [link](https://github.com/gabrielelanaro/emacs-for-python). Indentation doesn't seem to be working for me at all. It doesn't happen automatically when I create a class, function or any other block of code that requires automatic indentation(if, for etc.) and press enter or `Ctrl + j`. Instead emacs says "Arithmetic Error". It doesn't happen when I press `Tab` anywhere in a .py file. Again, every `Tab` press causes "Arithmetic error". Also, when I manually indent code using spaces, I can't erase those spaces! Backspace-ing these indents also causes "Arithmetic Error". This problem surfaces when I use the regular `Python AC` mode as well. emacs : GNU Emacs 24.3.1 (x86\_64-pc-linux-gnu, GTK+ Version 3.10.7) of 2014-03-07 on lamiak, modified by Debian
2014/11/20
[ "https://Stackoverflow.com/questions/27032218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2696086/" ]
Check the value of `python-indent-offset`. If it is 0, change it `M-x set-variable RET python-indent-offset RET 4 RET`. Emacs tries to guess the offset used in a Python file when opening it. It might get confused and set that variable to 0 for some badly-formatted Python file. If this is indeed the problem, please do file a bug report using `M-x report-emacs-bug` and the text of the Python file so that the auto-detection can be fixed.
It is related to this bug <http://debbugs.gnu.org/cgi/bugreport.cgi?bug=15975> The quickest workaround which I found was too add Jorgens Answer into .emacs file, add the following at the end of your .emacs file ``` (add-hook 'python-mode-hook (lambda () (setq python-indent-offset 4))) ```
69,895,751
I try start my code, but process finishes on step with method cv2.namedWindow (without any errors). Do you have any suggestions, why it could be so? ``` import cv2 image_cv2 = cv2.imread('/home/spartak/PycharmProjects/python_base/lesson_016/python_snippets/external_data/girl.jpg') def viewImage(image, name_of_window): print('step_1') cv2.namedWindow(name_of_window, cv2.WINDOW_NORMAL) print('step_2') cv2.imshow(name_of_window, image) print('step_3') cv2.waitKey(0) print('step_4') cv2.destroyAllWindows() cropped = image_cv2 viewImage(cropped, 'Cropped version') ``` P.S.: Also I erased UBUNTU , and installed Fedora. Instead Pycharm, check programm on VS code. But nothing changes. I changed location for picture (girl.jpg) to directory with python document. But program stops on step1 and waiting something. ![test_other_direct](https://ic.wampi.ru/2021/11/09/SNIMOK-EKRANA-OT-2021-11-09-19-49-08.png)
2021/11/09
[ "https://Stackoverflow.com/questions/69895751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14779400/" ]
I find out the problem. I started this code in virtual environment. Apparently, in virtual environment on UBUNTU/FEDORA, opencv have restrictions. ![Final_version](https://ic.wampi.ru/2021/11/10/SNIMOK-EKRANA-OT-2021-11-10-12-41-19.png)
The code completes all 4 steps for me I think there is a problem with the image path which you took [![enter image description here](https://i.stack.imgur.com/zrqCV.png)](https://i.stack.imgur.com/zrqCV.png) The function cv2.namedWindow creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names If a window with the same name already exists, the function does nothing.
69,895,751
I try start my code, but process finishes on step with method cv2.namedWindow (without any errors). Do you have any suggestions, why it could be so? ``` import cv2 image_cv2 = cv2.imread('/home/spartak/PycharmProjects/python_base/lesson_016/python_snippets/external_data/girl.jpg') def viewImage(image, name_of_window): print('step_1') cv2.namedWindow(name_of_window, cv2.WINDOW_NORMAL) print('step_2') cv2.imshow(name_of_window, image) print('step_3') cv2.waitKey(0) print('step_4') cv2.destroyAllWindows() cropped = image_cv2 viewImage(cropped, 'Cropped version') ``` P.S.: Also I erased UBUNTU , and installed Fedora. Instead Pycharm, check programm on VS code. But nothing changes. I changed location for picture (girl.jpg) to directory with python document. But program stops on step1 and waiting something. ![test_other_direct](https://ic.wampi.ru/2021/11/09/SNIMOK-EKRANA-OT-2021-11-09-19-49-08.png)
2021/11/09
[ "https://Stackoverflow.com/questions/69895751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14779400/" ]
I find out the problem. I started this code in virtual environment. Apparently, in virtual environment on UBUNTU/FEDORA, opencv have restrictions. ![Final_version](https://ic.wampi.ru/2021/11/10/SNIMOK-EKRANA-OT-2021-11-10-12-41-19.png)
I do think the function [cv2.destroyAllWindows](https://docs.opencv.org/2.4/modules/highgui/doc/user_interface.html?highlight=destroyallwindows#destroyallwindows) This function is deallocating some needed gui elements, I would guess. So calling this multiple times will produce some trouble. ``` import cv2 image_cv2 = cv2.imread('foo.jpg') def viewImage(image, name_of_window): print('step_1') cv2.namedWindow(name_of_window) print('step_2') cv2.imshow(name_of_window, image) print('step_3') cv2.waitKey(0) #print('step_4') #cv2.destroyAllWindows() cropped = image_cv2 viewImage(cropped, 'Cropped version') #e.g. better usage at the end of the code or section cv2.destroyAllWindows() ```
41,487,605
I am using DBSCAN from sklearn in python to cluster some data points. I am using a precomputed distance matrix to cluster the points. ``` import sklearn.cluster as cl C = cl.DBSCAN(eps = 2, metric = 'precomputed', min_samples =2) db = C.fit(Dist_Matrix) ``` Dist\_Matrix is precomputed distance matrix I am using. Each time when I run my code, I am getting different cluster labels for the data points. Number of clusters is also varying Like, in the first run,labels are ``` [ 2 3 3 0 3 0 2 2 2 4 2 -1 0 0 0 1 4 0 1 0 1 3 0 3 0 0 1 -1 0 3 1 3 0 0 2 0 2 0 -1 0 0 3 0 0 0 1 0 1 0 0] ``` in another run, it is like ``` [ 0 2 2 1 2 1 0 0 0 3 0 -1 1 1 1 0 3 1 0 1 0 2 1 2 1 1 0 -1 1 2 0 2 1 1 0 1 0 1 -1 1 1 2 1 1 1 0 1 0 1 1] ``` How can I resolve this? Please help
2017/01/05
[ "https://Stackoverflow.com/questions/41487605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7342743/" ]
Clustering will *usually* not assign the same labels. Because the label itself is *meaningless*. The only valueable information is what objects go *together*. As for sklearn, if you use an old version, it will (unnecessarily) randomly shuffle the data. So it's not surprising you get a random permutation of the labels. Usually, if you require stable labels, you are doing something wrong! Butif you really know you need that, implement a simple logic: sort clusters by their smallest object, and relabel them accordingly. I.e. the first objects cluster is cluster 0. The second objects cluster (unless it is the same) is cluater 1, and so forth.
You can use a custom function to normalize the cluster labels. ``` def normalize_cluster_labels(labels): min_value = min(labels) if (min_value < 0): labels = labels + abs(min(labels)) # normalize indexes #idx = clustering.labels_ - min(clustering.labels_ ) return labels ```
37,241,819
I have read a lot of other posts here on stackoverflow and google but I could not find a solution. It all started when I changed the model from a CharField to a ForeignKey. The error I recieve is: ``` Operations to perform: Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages Apply all migrations: venues, images, amenities, cities_light, registration, auth, admin, sites, sessions, contenttypes, easy_thumbnails, newsletter Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying venues.0016_auto_20160514_2141...Traceback (most recent call last): File "/Users/iam-tony/.envs/venuepark/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: column "venue_city" contains null values ``` My model is as follows: ``` class Venue(models.Model): venue_city = models.ForeignKey(City, null=True,) venue_country=models.ForeignKey(Country, null=True) ``` venue\_country did not exist before so that migration happened successfully. But venue\_city was a CharField. I made some changes to my migration file so that it would execute the sql as follows: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('venues', '0011_venue_map_activation'), ] migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city TYPE integer USING venue_city::integer '''), migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city RENAME COLUMN venue_city TO venue_city_id '''), migrations.RunSQL(''' ALTER TABLE venues_venue ADD CONSTRAINT venues_venus_somefk FOREIGN KEY (venue_city_id) REFERENCES cities_light (id) DEFERRABLE INITIALLY DEFERRED'''), ``` Thanks in advance! UPDATE: my new migration file: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cities_light', '0006_compensate_for_0003_bytestring_bug'), ('venues', '0024_remove_venue_venue_city'), ] operations = [ migrations.AddField( model_name='venue', name='venue_city', field=models.ForeignKey(null=True, to='cities_light.City'), ), ] ```
2016/05/15
[ "https://Stackoverflow.com/questions/37241819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067213/" ]
Had a similar problem i resolved it by removing the previous migration files.No technical explanation
I solved it by below: 1. First delete last migration that face problem 2. Then add like `venue_city = models.CharField(blank=True, null=True)` 3. Finally use `makemigrations` and `migrate` command
37,241,819
I have read a lot of other posts here on stackoverflow and google but I could not find a solution. It all started when I changed the model from a CharField to a ForeignKey. The error I recieve is: ``` Operations to perform: Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages Apply all migrations: venues, images, amenities, cities_light, registration, auth, admin, sites, sessions, contenttypes, easy_thumbnails, newsletter Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying venues.0016_auto_20160514_2141...Traceback (most recent call last): File "/Users/iam-tony/.envs/venuepark/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: column "venue_city" contains null values ``` My model is as follows: ``` class Venue(models.Model): venue_city = models.ForeignKey(City, null=True,) venue_country=models.ForeignKey(Country, null=True) ``` venue\_country did not exist before so that migration happened successfully. But venue\_city was a CharField. I made some changes to my migration file so that it would execute the sql as follows: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('venues', '0011_venue_map_activation'), ] migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city TYPE integer USING venue_city::integer '''), migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city RENAME COLUMN venue_city TO venue_city_id '''), migrations.RunSQL(''' ALTER TABLE venues_venue ADD CONSTRAINT venues_venus_somefk FOREIGN KEY (venue_city_id) REFERENCES cities_light (id) DEFERRABLE INITIALLY DEFERRED'''), ``` Thanks in advance! UPDATE: my new migration file: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cities_light', '0006_compensate_for_0003_bytestring_bug'), ('venues', '0024_remove_venue_venue_city'), ] operations = [ migrations.AddField( model_name='venue', name='venue_city', field=models.ForeignKey(null=True, to='cities_light.City'), ), ] ```
2016/05/15
[ "https://Stackoverflow.com/questions/37241819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067213/" ]
Looks like you added `null=True` after created migration file. Because `venue_city` is not a nullable field in your migration file Follow these steps. ``` 1) Drop venue_city & venue_country from your local table 3) Delete all the migration files you created for these `CharField to a ForeignKey` change 4) execute `python manage.py makemigrations` 5) execute 'python manage.py migrate' ``` It should work
I solved it by below: 1. First delete last migration that face problem 2. Then add like `venue_city = models.CharField(blank=True, null=True)` 3. Finally use `makemigrations` and `migrate` command
37,241,819
I have read a lot of other posts here on stackoverflow and google but I could not find a solution. It all started when I changed the model from a CharField to a ForeignKey. The error I recieve is: ``` Operations to perform: Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages Apply all migrations: venues, images, amenities, cities_light, registration, auth, admin, sites, sessions, contenttypes, easy_thumbnails, newsletter Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying venues.0016_auto_20160514_2141...Traceback (most recent call last): File "/Users/iam-tony/.envs/venuepark/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: column "venue_city" contains null values ``` My model is as follows: ``` class Venue(models.Model): venue_city = models.ForeignKey(City, null=True,) venue_country=models.ForeignKey(Country, null=True) ``` venue\_country did not exist before so that migration happened successfully. But venue\_city was a CharField. I made some changes to my migration file so that it would execute the sql as follows: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('venues', '0011_venue_map_activation'), ] migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city TYPE integer USING venue_city::integer '''), migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city RENAME COLUMN venue_city TO venue_city_id '''), migrations.RunSQL(''' ALTER TABLE venues_venue ADD CONSTRAINT venues_venus_somefk FOREIGN KEY (venue_city_id) REFERENCES cities_light (id) DEFERRABLE INITIALLY DEFERRED'''), ``` Thanks in advance! UPDATE: my new migration file: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cities_light', '0006_compensate_for_0003_bytestring_bug'), ('venues', '0024_remove_venue_venue_city'), ] operations = [ migrations.AddField( model_name='venue', name='venue_city', field=models.ForeignKey(null=True, to='cities_light.City'), ), ] ```
2016/05/15
[ "https://Stackoverflow.com/questions/37241819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067213/" ]
Had a similar problem i resolved it by removing the previous migration files.No technical explanation
follow the below steps:- * add *null=True, blank=True* in Venue model class eg: venue\_city = models.ForeignKey(City, null=True, blank=True) * delete *venues.0016\_auto\_20160514\_2141* migration file from migrations folder in your app * then run *python manage.py makemigrations* * then run *python manage.py migrate* no need to drop table or remove migrations from migration tables
37,241,819
I have read a lot of other posts here on stackoverflow and google but I could not find a solution. It all started when I changed the model from a CharField to a ForeignKey. The error I recieve is: ``` Operations to perform: Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages Apply all migrations: venues, images, amenities, cities_light, registration, auth, admin, sites, sessions, contenttypes, easy_thumbnails, newsletter Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying venues.0016_auto_20160514_2141...Traceback (most recent call last): File "/Users/iam-tony/.envs/venuepark/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: column "venue_city" contains null values ``` My model is as follows: ``` class Venue(models.Model): venue_city = models.ForeignKey(City, null=True,) venue_country=models.ForeignKey(Country, null=True) ``` venue\_country did not exist before so that migration happened successfully. But venue\_city was a CharField. I made some changes to my migration file so that it would execute the sql as follows: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('venues', '0011_venue_map_activation'), ] migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city TYPE integer USING venue_city::integer '''), migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city RENAME COLUMN venue_city TO venue_city_id '''), migrations.RunSQL(''' ALTER TABLE venues_venue ADD CONSTRAINT venues_venus_somefk FOREIGN KEY (venue_city_id) REFERENCES cities_light (id) DEFERRABLE INITIALLY DEFERRED'''), ``` Thanks in advance! UPDATE: my new migration file: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cities_light', '0006_compensate_for_0003_bytestring_bug'), ('venues', '0024_remove_venue_venue_city'), ] operations = [ migrations.AddField( model_name='venue', name='venue_city', field=models.ForeignKey(null=True, to='cities_light.City'), ), ] ```
2016/05/15
[ "https://Stackoverflow.com/questions/37241819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067213/" ]
I solved it by just adding `null = True` to both the (automatically generated) migration file that was causing the issue and in the Model. Then `migrate` again and your failed migration will now succeed. As you changed it also in your model, `makemigration` will detect no changes after that.
follow the below steps:- * add *null=True, blank=True* in Venue model class eg: venue\_city = models.ForeignKey(City, null=True, blank=True) * delete *venues.0016\_auto\_20160514\_2141* migration file from migrations folder in your app * then run *python manage.py makemigrations* * then run *python manage.py migrate* no need to drop table or remove migrations from migration tables
37,241,819
I have read a lot of other posts here on stackoverflow and google but I could not find a solution. It all started when I changed the model from a CharField to a ForeignKey. The error I recieve is: ``` Operations to perform: Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages Apply all migrations: venues, images, amenities, cities_light, registration, auth, admin, sites, sessions, contenttypes, easy_thumbnails, newsletter Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying venues.0016_auto_20160514_2141...Traceback (most recent call last): File "/Users/iam-tony/.envs/venuepark/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: column "venue_city" contains null values ``` My model is as follows: ``` class Venue(models.Model): venue_city = models.ForeignKey(City, null=True,) venue_country=models.ForeignKey(Country, null=True) ``` venue\_country did not exist before so that migration happened successfully. But venue\_city was a CharField. I made some changes to my migration file so that it would execute the sql as follows: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('venues', '0011_venue_map_activation'), ] migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city TYPE integer USING venue_city::integer '''), migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city RENAME COLUMN venue_city TO venue_city_id '''), migrations.RunSQL(''' ALTER TABLE venues_venue ADD CONSTRAINT venues_venus_somefk FOREIGN KEY (venue_city_id) REFERENCES cities_light (id) DEFERRABLE INITIALLY DEFERRED'''), ``` Thanks in advance! UPDATE: my new migration file: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cities_light', '0006_compensate_for_0003_bytestring_bug'), ('venues', '0024_remove_venue_venue_city'), ] operations = [ migrations.AddField( model_name='venue', name='venue_city', field=models.ForeignKey(null=True, to='cities_light.City'), ), ] ```
2016/05/15
[ "https://Stackoverflow.com/questions/37241819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067213/" ]
follow the below steps:- * add *null=True, blank=True* in Venue model class eg: venue\_city = models.ForeignKey(City, null=True, blank=True) * delete *venues.0016\_auto\_20160514\_2141* migration file from migrations folder in your app * then run *python manage.py makemigrations* * then run *python manage.py migrate* no need to drop table or remove migrations from migration tables
As the error says, you have a null value in the "venue\_city" column. It seems at the time of defining your model you had not included "null=True". So it returns null because there is nothing in your 'venue\_city" variable. Consider deleting the last migration file and perform another migration using `python manage.py makemigrations` and `python manage.py migrate` commands.
37,241,819
I have read a lot of other posts here on stackoverflow and google but I could not find a solution. It all started when I changed the model from a CharField to a ForeignKey. The error I recieve is: ``` Operations to perform: Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages Apply all migrations: venues, images, amenities, cities_light, registration, auth, admin, sites, sessions, contenttypes, easy_thumbnails, newsletter Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying venues.0016_auto_20160514_2141...Traceback (most recent call last): File "/Users/iam-tony/.envs/venuepark/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: column "venue_city" contains null values ``` My model is as follows: ``` class Venue(models.Model): venue_city = models.ForeignKey(City, null=True,) venue_country=models.ForeignKey(Country, null=True) ``` venue\_country did not exist before so that migration happened successfully. But venue\_city was a CharField. I made some changes to my migration file so that it would execute the sql as follows: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('venues', '0011_venue_map_activation'), ] migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city TYPE integer USING venue_city::integer '''), migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city RENAME COLUMN venue_city TO venue_city_id '''), migrations.RunSQL(''' ALTER TABLE venues_venue ADD CONSTRAINT venues_venus_somefk FOREIGN KEY (venue_city_id) REFERENCES cities_light (id) DEFERRABLE INITIALLY DEFERRED'''), ``` Thanks in advance! UPDATE: my new migration file: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cities_light', '0006_compensate_for_0003_bytestring_bug'), ('venues', '0024_remove_venue_venue_city'), ] operations = [ migrations.AddField( model_name='venue', name='venue_city', field=models.ForeignKey(null=True, to='cities_light.City'), ), ] ```
2016/05/15
[ "https://Stackoverflow.com/questions/37241819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067213/" ]
I solved it by just adding `null = True` to both the (automatically generated) migration file that was causing the issue and in the Model. Then `migrate` again and your failed migration will now succeed. As you changed it also in your model, `makemigration` will detect no changes after that.
I solved it by below: 1. First delete last migration that face problem 2. Then add like `venue_city = models.CharField(blank=True, null=True)` 3. Finally use `makemigrations` and `migrate` command
37,241,819
I have read a lot of other posts here on stackoverflow and google but I could not find a solution. It all started when I changed the model from a CharField to a ForeignKey. The error I recieve is: ``` Operations to perform: Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages Apply all migrations: venues, images, amenities, cities_light, registration, auth, admin, sites, sessions, contenttypes, easy_thumbnails, newsletter Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying venues.0016_auto_20160514_2141...Traceback (most recent call last): File "/Users/iam-tony/.envs/venuepark/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: column "venue_city" contains null values ``` My model is as follows: ``` class Venue(models.Model): venue_city = models.ForeignKey(City, null=True,) venue_country=models.ForeignKey(Country, null=True) ``` venue\_country did not exist before so that migration happened successfully. But venue\_city was a CharField. I made some changes to my migration file so that it would execute the sql as follows: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('venues', '0011_venue_map_activation'), ] migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city TYPE integer USING venue_city::integer '''), migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city RENAME COLUMN venue_city TO venue_city_id '''), migrations.RunSQL(''' ALTER TABLE venues_venue ADD CONSTRAINT venues_venus_somefk FOREIGN KEY (venue_city_id) REFERENCES cities_light (id) DEFERRABLE INITIALLY DEFERRED'''), ``` Thanks in advance! UPDATE: my new migration file: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cities_light', '0006_compensate_for_0003_bytestring_bug'), ('venues', '0024_remove_venue_venue_city'), ] operations = [ migrations.AddField( model_name='venue', name='venue_city', field=models.ForeignKey(null=True, to='cities_light.City'), ), ] ```
2016/05/15
[ "https://Stackoverflow.com/questions/37241819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067213/" ]
Looks like you added `null=True` after created migration file. Because `venue_city` is not a nullable field in your migration file Follow these steps. ``` 1) Drop venue_city & venue_country from your local table 3) Delete all the migration files you created for these `CharField to a ForeignKey` change 4) execute `python manage.py makemigrations` 5) execute 'python manage.py migrate' ``` It should work
As the error says, you have a null value in the "venue\_city" column. It seems at the time of defining your model you had not included "null=True". So it returns null because there is nothing in your 'venue\_city" variable. Consider deleting the last migration file and perform another migration using `python manage.py makemigrations` and `python manage.py migrate` commands.
37,241,819
I have read a lot of other posts here on stackoverflow and google but I could not find a solution. It all started when I changed the model from a CharField to a ForeignKey. The error I recieve is: ``` Operations to perform: Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages Apply all migrations: venues, images, amenities, cities_light, registration, auth, admin, sites, sessions, contenttypes, easy_thumbnails, newsletter Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying venues.0016_auto_20160514_2141...Traceback (most recent call last): File "/Users/iam-tony/.envs/venuepark/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: column "venue_city" contains null values ``` My model is as follows: ``` class Venue(models.Model): venue_city = models.ForeignKey(City, null=True,) venue_country=models.ForeignKey(Country, null=True) ``` venue\_country did not exist before so that migration happened successfully. But venue\_city was a CharField. I made some changes to my migration file so that it would execute the sql as follows: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('venues', '0011_venue_map_activation'), ] migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city TYPE integer USING venue_city::integer '''), migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city RENAME COLUMN venue_city TO venue_city_id '''), migrations.RunSQL(''' ALTER TABLE venues_venue ADD CONSTRAINT venues_venus_somefk FOREIGN KEY (venue_city_id) REFERENCES cities_light (id) DEFERRABLE INITIALLY DEFERRED'''), ``` Thanks in advance! UPDATE: my new migration file: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cities_light', '0006_compensate_for_0003_bytestring_bug'), ('venues', '0024_remove_venue_venue_city'), ] operations = [ migrations.AddField( model_name='venue', name='venue_city', field=models.ForeignKey(null=True, to='cities_light.City'), ), ] ```
2016/05/15
[ "https://Stackoverflow.com/questions/37241819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067213/" ]
Looks like you added `null=True` after created migration file. Because `venue_city` is not a nullable field in your migration file Follow these steps. ``` 1) Drop venue_city & venue_country from your local table 3) Delete all the migration files you created for these `CharField to a ForeignKey` change 4) execute `python manage.py makemigrations` 5) execute 'python manage.py migrate' ``` It should work
Had a similar problem i resolved it by removing the previous migration files.No technical explanation
37,241,819
I have read a lot of other posts here on stackoverflow and google but I could not find a solution. It all started when I changed the model from a CharField to a ForeignKey. The error I recieve is: ``` Operations to perform: Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages Apply all migrations: venues, images, amenities, cities_light, registration, auth, admin, sites, sessions, contenttypes, easy_thumbnails, newsletter Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying venues.0016_auto_20160514_2141...Traceback (most recent call last): File "/Users/iam-tony/.envs/venuepark/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: column "venue_city" contains null values ``` My model is as follows: ``` class Venue(models.Model): venue_city = models.ForeignKey(City, null=True,) venue_country=models.ForeignKey(Country, null=True) ``` venue\_country did not exist before so that migration happened successfully. But venue\_city was a CharField. I made some changes to my migration file so that it would execute the sql as follows: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('venues', '0011_venue_map_activation'), ] migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city TYPE integer USING venue_city::integer '''), migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city RENAME COLUMN venue_city TO venue_city_id '''), migrations.RunSQL(''' ALTER TABLE venues_venue ADD CONSTRAINT venues_venus_somefk FOREIGN KEY (venue_city_id) REFERENCES cities_light (id) DEFERRABLE INITIALLY DEFERRED'''), ``` Thanks in advance! UPDATE: my new migration file: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cities_light', '0006_compensate_for_0003_bytestring_bug'), ('venues', '0024_remove_venue_venue_city'), ] operations = [ migrations.AddField( model_name='venue', name='venue_city', field=models.ForeignKey(null=True, to='cities_light.City'), ), ] ```
2016/05/15
[ "https://Stackoverflow.com/questions/37241819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067213/" ]
follow the below steps:- * add *null=True, blank=True* in Venue model class eg: venue\_city = models.ForeignKey(City, null=True, blank=True) * delete *venues.0016\_auto\_20160514\_2141* migration file from migrations folder in your app * then run *python manage.py makemigrations* * then run *python manage.py migrate* no need to drop table or remove migrations from migration tables
I solved it by below: 1. First delete last migration that face problem 2. Then add like `venue_city = models.CharField(blank=True, null=True)` 3. Finally use `makemigrations` and `migrate` command
37,241,819
I have read a lot of other posts here on stackoverflow and google but I could not find a solution. It all started when I changed the model from a CharField to a ForeignKey. The error I recieve is: ``` Operations to perform: Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages Apply all migrations: venues, images, amenities, cities_light, registration, auth, admin, sites, sessions, contenttypes, easy_thumbnails, newsletter Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying venues.0016_auto_20160514_2141...Traceback (most recent call last): File "/Users/iam-tony/.envs/venuepark/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: column "venue_city" contains null values ``` My model is as follows: ``` class Venue(models.Model): venue_city = models.ForeignKey(City, null=True,) venue_country=models.ForeignKey(Country, null=True) ``` venue\_country did not exist before so that migration happened successfully. But venue\_city was a CharField. I made some changes to my migration file so that it would execute the sql as follows: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('venues', '0011_venue_map_activation'), ] migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city TYPE integer USING venue_city::integer '''), migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city RENAME COLUMN venue_city TO venue_city_id '''), migrations.RunSQL(''' ALTER TABLE venues_venue ADD CONSTRAINT venues_venus_somefk FOREIGN KEY (venue_city_id) REFERENCES cities_light (id) DEFERRABLE INITIALLY DEFERRED'''), ``` Thanks in advance! UPDATE: my new migration file: ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cities_light', '0006_compensate_for_0003_bytestring_bug'), ('venues', '0024_remove_venue_venue_city'), ] operations = [ migrations.AddField( model_name='venue', name='venue_city', field=models.ForeignKey(null=True, to='cities_light.City'), ), ] ```
2016/05/15
[ "https://Stackoverflow.com/questions/37241819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067213/" ]
I solved it by just adding `null = True` to both the (automatically generated) migration file that was causing the issue and in the Model. Then `migrate` again and your failed migration will now succeed. As you changed it also in your model, `makemigration` will detect no changes after that.
As the error says, you have a null value in the "venue\_city" column. It seems at the time of defining your model you had not included "null=True". So it returns null because there is nothing in your 'venue\_city" variable. Consider deleting the last migration file and perform another migration using `python manage.py makemigrations` and `python manage.py migrate` commands.
21,758,560
I've been struggling with an algorithm tied to comparisons with 3d triangle vectors. Unfortunately its very slow in places and I've gone back and forth on different methods to try and improve it. One thing I'm struggling with is speeding up a distance calculation. I have two groups of triangles which have been broken down to three points each of which has a 3d float vector (xyz). The calculations I'm using are : ``` diffverts = numpy.zeros( ( ntris*3, ntesttris*3, 3 ), dtype = 'float32') diffverts += triverts.reshape(ntris*3, 1, 3 ) diffverts -= ttriverts.reshape(1, ntesttris*3, 3 ) vertdist = ( diffverts[:,:,0]**2 + diffverts[:,:,1]**2 + diffverts[:,:,2]**2 ) ** 0.5 ``` this calculation is faster than : ``` diffverts = triverts.reshape(ntris*3, 1, 3 ) - ttriverts.reshape(1, ntesttris*3, 3 ) vertdist = ( diffverts[:,:,0]**2 + diffverts[:,:,1]**2 + diffverts[:,:,2]**2 ) ** 0.5 ``` Is there a faster method to populate the diff vert part (which takes longest) and/or the distance part which is also quite time consuming? This code is called a lot of times due to the number of groups to test. Also, trying to do it just on indexes to the verts causes me other issues with further calculations when trying to get back to some boolean tests (i.e. this is only one of a set of calculations so keeping at the tri point level works best. I'm using numpy and python
2014/02/13
[ "https://Stackoverflow.com/questions/21758560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1942439/" ]
The problem is that brute force testing of all triangles versus eachother takes quadratic time. It is better to use a datastructure which is specialized to perform such computations. Luckily, scipy contains one. Take a look at scipy.spatial.cKDTree. The help should be self-explanatory.
I think diffverts is taking up enough memory to cause cache misses. Unfortunately while this solution is very elegant, you're probably better off computing the whole distance in one go, to avoid having to save an n\*m\*3 array of intermediate values. As ugly as it is, I would just do nested for loops.
15,415,093
For a system I am developing I need to programmatically go to a specific page. Fill out one field in the form (I know the id and name of the input element), submit it and store the results. I have seen a few different Perl, python and java classes that do this. However I would like to do this using PHP and havent found anything as of yet. I do have the permission to do this from the site i am getting the information from as well. Any help is appreciated
2013/03/14
[ "https://Stackoverflow.com/questions/15415093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1364791/" ]
Take a look at David Walsh's simple explanation. <http://davidwalsh.name/curl-post> You can easily store the response (in this example, $result) in your database or logfile.
Usually PHP crawlers/scrapers use CURL - <http://php.net/manual/en/book.curl.php>. It allows you to make a query from the server where PHP runs and get response from the website that you need to crawl. It returns response data in plain format and parsing it is up to you. You can manually check what does the form submit when you do it manually, and do the same thing via curl.
15,415,093
For a system I am developing I need to programmatically go to a specific page. Fill out one field in the form (I know the id and name of the input element), submit it and store the results. I have seen a few different Perl, python and java classes that do this. However I would like to do this using PHP and havent found anything as of yet. I do have the permission to do this from the site i am getting the information from as well. Any help is appreciated
2013/03/14
[ "https://Stackoverflow.com/questions/15415093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1364791/" ]
Take a look at David Walsh's simple explanation. <http://davidwalsh.name/curl-post> You can easily store the response (in this example, $result) in your database or logfile.
You also may try phpcrawl (<http://phpcrawl.cuab.de>), seems to fit all your needs. (See "addPostData()"-method)
15,415,093
For a system I am developing I need to programmatically go to a specific page. Fill out one field in the form (I know the id and name of the input element), submit it and store the results. I have seen a few different Perl, python and java classes that do this. However I would like to do this using PHP and havent found anything as of yet. I do have the permission to do this from the site i am getting the information from as well. Any help is appreciated
2013/03/14
[ "https://Stackoverflow.com/questions/15415093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1364791/" ]
Usually PHP crawlers/scrapers use CURL - <http://php.net/manual/en/book.curl.php>. It allows you to make a query from the server where PHP runs and get response from the website that you need to crawl. It returns response data in plain format and parsing it is up to you. You can manually check what does the form submit when you do it manually, and do the same thing via curl.
You also may try phpcrawl (<http://phpcrawl.cuab.de>), seems to fit all your needs. (See "addPostData()"-method)
50,991,402
I'm trying to create a new tables in a new app added to my project .. `makemigrations` worked great but `migrate` is not working .. here is my models **blog/models.py** ``` from django.db import models # Create your models here. from fostania_web_app.models import UserModel class Tag(models.Model): tag_name = models.CharField(max_length=250) def __str__(self): return self.tag_name class BlogPost(models.Model): post_title = models.CharField(max_length=250) post_message = models.CharField(max_length=2000) post_author = models.ForeignKey(UserModel, on_delete=models.PROTECT) post_image = models.ImageField(upload_to='documents/%Y/%m/%d', null=False, blank=False) post_tag = models.ForeignKey(Tag, on_delete=models.PROTECT) post_created_at = models.DateTimeField(auto_now=True) ``` when i try to do `python manage.py migrate` i get this error `invalid literal for int() with base 10: '??????? ???????'` **UserModel** is created in another app in the same project that is why i used the statement `from fostania_web_app.models import UserModel` **fostania\_web\_app/models.py** ``` class UserModelManager(BaseUserManager): def create_user(self, email, password, pseudo): user = self.model() user.name = name user.email = self.normalize_email(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password): ''' Used for: python manage.py createsuperuser ''' user = self.model() user.name = 'admin-yeah' user.email = self.normalize_email(email=email) user.set_password(password) user.is_staff = True user.is_superuser = True user.save() return user class UserModel(AbstractBaseUser, PermissionsMixin): ## Personnal fields. email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=16) ## [...] ## Django manage fields. date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELD = ['email', 'name'] objects = UserModelManager() def __str__(self): return self.email def get_short_name(self): return self.name[:2].upper() def get_full_name(self): return self.name ``` and on my **setting.py** files i have this : ``` #custom_user AUTH_USER_MODEL='fostania_web_app.UserModel' ``` and here is the full `traeback` : ``` Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, fostania_web ons, sites, social_django Running migrations: Applying blog.0001_initial...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\core\management\__init__.py", line 371, in execute_from_comm utility.execute() File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=f nitial=fake_initial) File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\db\migrations\executor.py", line 147, in _migrate_all_forwar state = self.apply_migration(state, migration, fake=fake, fake_in initial) File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\db\migrations\migration.py", line 122, in apply operation.database_forwards(self.app_label, schema_editor, old_st t_state) File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\db\migrations\operations\fields.py", line 84, in database_fo field, File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\db\backends\sqlite3\schema.py", line 306, in add_field self._remake_table(model, create_field=field) File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\db\backends\sqlite3\schema.py", line 178, in _remake_table self.effective_default(create_field) File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\db\backends\base\schema.py", line 240, in effective_default default = field.get_db_prep_save(default, self.connection) File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\db\models\fields\related.py", line 936, in get_db_prep_save return self.target_field.get_db_prep_save(value, connection=conne File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\db\models\fields\__init__.py", line 767, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepa File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\db\models\fields\__init__.py", line 939, in get_db_prep_valu value = self.get_prep_value(value) File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\s s\django\db\models\fields\__init__.py", line 947, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '??? ??? ?????' ```
2018/06/22
[ "https://Stackoverflow.com/questions/50991402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9494140/" ]
Error message: `ValueError: invalid literal for int() with base 10: '??? ??? ?????'` As per exception int() with base 10: `'??? ??? ?????'` doesn't qualify as int. Check in `blog.0001_initial` migrations for `'??? ??? ?????'` and modify that value with a valid int. You might have accidentally provided garbage default value while rerunning makemigrations command which isn't an int()
I had the same error. My problem: I had: ``` models.y expiration_date = models.DateField(null=True, max_length=20) ``` And a validation in my: ``` forms.py def clean_expiration_date(self): data = self.cleaned_data['expiration_date'] if data < datetime.date.today(): return data ``` And it gave me the here mentioned error. But only on a certain page. My solution: I changed the **DateField** to **DateTimeField** And it fixed my problem in my case.
16,247,828
Now our code have 3,000,000 id stored in set, the format is string, I try to convert it to int using list comprehension. But it cost 5 sec, how can I reduce the cost of converting string to int for these 3,000,000 id? Here is my testing code: ``` import random import time a = set() for i in xrange(3088767): a.add(str(random.randint(10005907, 100000000))) start = time.time() ld = [int(i) for i in a] end = time.time() print end-start ``` The result is: ``` $python -V Python 2.6.5 $python ld.py 5.53777289391 ```
2013/04/27
[ "https://Stackoverflow.com/questions/16247828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/472880/" ]
``` ld = map(int, a) ``` should be quite faster, and also your only option not considering other python implementations
Try using [Pypy](http://pypy.org) or [Cython](http://cython.org). These tools can made your code fly! (Pypy, specially, in my PC Pypy speed up the code 4 times..)
46,164,419
Getting a 'Label out of bound' error while running the testing script. Error is thrown in the confusion\_matrix function when the annotation values are compared with the number of classes. In my case annotation value is an image(560x560) and number\_of\_classes = 2. ``` [check_ops.assert_less(labels, num_classes_int64, message='`labels` out of bound')], labels ``` The above condition is always going to fail, as the annotation data is bigger than number of classes. First, There is a good chance that I am misunderstanding the code, but I can not make any sense of it. Second, If this is a valid check, then how can I modify my code or data to avoid this error. ```py def confusion_matrix(labels, predictions, num_classes=None, dtype=dtypes.int32, name=None, weights=None): with ops.name_scope(name, 'confusion_matrix', (predictions, labels, num_classes, weights)) as name: labels, predictions = remove_squeezable_dimensions( ops.convert_to_tensor(labels, name='labels'), ops.convert_to_tensor( predictions, name='predictions')) predictions = math_ops.cast(predictions, dtypes.int64) labels = math_ops.cast(labels, dtypes.int64) # Sanity checks - underflow or overflow can cause memory corruption. labels = control_flow_ops.with_dependencies( [check_ops.assert_non_negative( labels, message='`labels` contains negative values')], labels) predictions = control_flow_ops.with_dependencies( [check_ops.assert_non_negative( predictions, message='`predictions` contains negative values')], predictions) print(num_classes) if num_classes is None: num_classes = math_ops.maximum(math_ops.reduce_max(predictions), math_ops.reduce_max(labels)) + 1 #$ else: num_classes_int64 = math_ops.cast(num_classes, dtypes.int64) ---->>labels = control_flow_ops.with_dependencies( [check_ops.assert_less( labels, num_classes_int64, message='`labels` out of bound')], labels)<<---- predictions = control_flow_ops.with_dependencies( [check_ops.assert_less( predictions, num_classes_int64, message='`predictions` out of bound')], predictions) if weights is not None: predictions.get_shape().assert_is_compatible_with(weights.get_shape()) weights = math_ops.cast(weights, dtype) shape = array_ops.stack([num_classes, num_classes]) indices = array_ops.transpose(array_ops.stack([labels, predictions])) values = (array_ops.ones_like(predictions, dtype) if weights is None else weights) cm_sparse = sparse_tensor.SparseTensor( indices=indices, values=values, dense_shape=math_ops.to_int64(shape)) zero_matrix = array_ops.zeros(math_ops.to_int32(shape), dtype) return sparse_ops.sparse_add(zero_matrix, cm_sparse) ``` ```none Traceback (most recent call last): File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1327, in _do_call return fn(*args) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1306, in _run_fn status, run_metadata) File "C:\Program Files\Python35\lib\contextlib.py", line 66, in __exit__ next(self.gen) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 466, in raise_exception_on_not_ok_status pywrap_tensorflow.TF_GetCode(status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/supriya.godge/PycharmProjects/tf-image-segmentation/tf_image_segmentation/recipes/pascal_voc/DeepLab/output/resnet_v1_101_8s_test_airplan.py", line 81, in <module> image_np, annotation_np, pred_np, tmp = sess.run([image, annotation, pred, update_op]) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 895, in run run_metadata_ptr) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1124, in _run feed_dict_tensor, options, run_metadata) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1321, in _do_run options, run_metadata) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1340, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] Caused by op 'mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert', defined at: File "C:/Users/supriya.godge/PycharmProjects/tf-image-segmentation/tf_image_segmentation/recipes/pascal_voc/DeepLab/output/resnet_v1_101_8s_test_airplan.py", line 64, in <module> weights=weights) File "C:\Program Files\Python35\lib\site-packages\tensorflow\contrib\metrics\python\ops\metric_ops.py", line 2245, in streaming_mean_iou updates_collections=updates_collections, name=name) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 917, in mean_iou num_classes, weights) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 285, in _streaming_confusion_matrix labels, predictions, num_classes, weights=weights, dtype=cm_dtype) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\confusion_matrix.py", line 178, in confusion_matrix labels, num_classes_int64, message='`labels` out of bound')], File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\check_ops.py", line 401, in assert_less return control_flow_ops.Assert(condition, data, summarize=summarize) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\util\tf_should_use.py", line 175, in wrapped return _add_should_use_warning(fn(*args, **kwargs)) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 131, in Assert condition, no_op, true_assert, name="AssertGuard") File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\util\deprecation.py", line 296, in new_func return func(*args, **kwargs) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 1828, in cond orig_res_f, res_f = context_f.BuildCondBranch(false_fn) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 1694, in BuildCondBranch original_result = fn() File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 129, in true_assert condition, data, summarize, name="Assert") File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\gen_logging_ops.py", line 35, in _assert summarize=summarize, name=name) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 767, in apply_op op_def=op_def) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2630, in create_op original_op=self._default_original_op, op_def=op_def) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1204, in __init__ self._traceback = self._graph._extract_stack() # pylint: disable=protected-access InvalidArgumentError (see above for traceback): assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] ``` I am really lost here so any help or suggestion is appreciated!
2017/09/11
[ "https://Stackoverflow.com/questions/46164419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8485184/" ]
In the Annotation file, the labels were 0,1,2,255. The range of label was given 3. So when 255 was detected in the annotation file above error was thrown. After I removed all 255 values the code worked without any error.
under tensorflow 1.15.2, tensorflow/models/research/deeplab is basically quite ok. error message like: Invalid argument: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:] [x (mean\_iou/confusion\_matrix/control\_dependency:0) = ] likely due not considering background as 1 class. e.g. deeplab/datasets/data\_generator.py ``` # Number of semantic classes, including the # background class (if exists). For example, there # are 20 foreground classes + 1 background class in # the PASCAL VOC 2012 dataset. Thus, we set # num_classes=21. ```
46,164,419
Getting a 'Label out of bound' error while running the testing script. Error is thrown in the confusion\_matrix function when the annotation values are compared with the number of classes. In my case annotation value is an image(560x560) and number\_of\_classes = 2. ``` [check_ops.assert_less(labels, num_classes_int64, message='`labels` out of bound')], labels ``` The above condition is always going to fail, as the annotation data is bigger than number of classes. First, There is a good chance that I am misunderstanding the code, but I can not make any sense of it. Second, If this is a valid check, then how can I modify my code or data to avoid this error. ```py def confusion_matrix(labels, predictions, num_classes=None, dtype=dtypes.int32, name=None, weights=None): with ops.name_scope(name, 'confusion_matrix', (predictions, labels, num_classes, weights)) as name: labels, predictions = remove_squeezable_dimensions( ops.convert_to_tensor(labels, name='labels'), ops.convert_to_tensor( predictions, name='predictions')) predictions = math_ops.cast(predictions, dtypes.int64) labels = math_ops.cast(labels, dtypes.int64) # Sanity checks - underflow or overflow can cause memory corruption. labels = control_flow_ops.with_dependencies( [check_ops.assert_non_negative( labels, message='`labels` contains negative values')], labels) predictions = control_flow_ops.with_dependencies( [check_ops.assert_non_negative( predictions, message='`predictions` contains negative values')], predictions) print(num_classes) if num_classes is None: num_classes = math_ops.maximum(math_ops.reduce_max(predictions), math_ops.reduce_max(labels)) + 1 #$ else: num_classes_int64 = math_ops.cast(num_classes, dtypes.int64) ---->>labels = control_flow_ops.with_dependencies( [check_ops.assert_less( labels, num_classes_int64, message='`labels` out of bound')], labels)<<---- predictions = control_flow_ops.with_dependencies( [check_ops.assert_less( predictions, num_classes_int64, message='`predictions` out of bound')], predictions) if weights is not None: predictions.get_shape().assert_is_compatible_with(weights.get_shape()) weights = math_ops.cast(weights, dtype) shape = array_ops.stack([num_classes, num_classes]) indices = array_ops.transpose(array_ops.stack([labels, predictions])) values = (array_ops.ones_like(predictions, dtype) if weights is None else weights) cm_sparse = sparse_tensor.SparseTensor( indices=indices, values=values, dense_shape=math_ops.to_int64(shape)) zero_matrix = array_ops.zeros(math_ops.to_int32(shape), dtype) return sparse_ops.sparse_add(zero_matrix, cm_sparse) ``` ```none Traceback (most recent call last): File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1327, in _do_call return fn(*args) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1306, in _run_fn status, run_metadata) File "C:\Program Files\Python35\lib\contextlib.py", line 66, in __exit__ next(self.gen) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 466, in raise_exception_on_not_ok_status pywrap_tensorflow.TF_GetCode(status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/supriya.godge/PycharmProjects/tf-image-segmentation/tf_image_segmentation/recipes/pascal_voc/DeepLab/output/resnet_v1_101_8s_test_airplan.py", line 81, in <module> image_np, annotation_np, pred_np, tmp = sess.run([image, annotation, pred, update_op]) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 895, in run run_metadata_ptr) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1124, in _run feed_dict_tensor, options, run_metadata) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1321, in _do_run options, run_metadata) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1340, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] Caused by op 'mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert', defined at: File "C:/Users/supriya.godge/PycharmProjects/tf-image-segmentation/tf_image_segmentation/recipes/pascal_voc/DeepLab/output/resnet_v1_101_8s_test_airplan.py", line 64, in <module> weights=weights) File "C:\Program Files\Python35\lib\site-packages\tensorflow\contrib\metrics\python\ops\metric_ops.py", line 2245, in streaming_mean_iou updates_collections=updates_collections, name=name) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 917, in mean_iou num_classes, weights) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 285, in _streaming_confusion_matrix labels, predictions, num_classes, weights=weights, dtype=cm_dtype) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\confusion_matrix.py", line 178, in confusion_matrix labels, num_classes_int64, message='`labels` out of bound')], File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\check_ops.py", line 401, in assert_less return control_flow_ops.Assert(condition, data, summarize=summarize) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\util\tf_should_use.py", line 175, in wrapped return _add_should_use_warning(fn(*args, **kwargs)) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 131, in Assert condition, no_op, true_assert, name="AssertGuard") File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\util\deprecation.py", line 296, in new_func return func(*args, **kwargs) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 1828, in cond orig_res_f, res_f = context_f.BuildCondBranch(false_fn) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 1694, in BuildCondBranch original_result = fn() File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 129, in true_assert condition, data, summarize, name="Assert") File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\gen_logging_ops.py", line 35, in _assert summarize=summarize, name=name) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 767, in apply_op op_def=op_def) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2630, in create_op original_op=self._default_original_op, op_def=op_def) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1204, in __init__ self._traceback = self._graph._extract_stack() # pylint: disable=protected-access InvalidArgumentError (see above for traceback): assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] ``` I am really lost here so any help or suggestion is appreciated!
2017/09/11
[ "https://Stackoverflow.com/questions/46164419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8485184/" ]
In the Annotation file, the labels were 0,1,2,255. The range of label was given 3. So when 255 was detected in the annotation file above error was thrown. After I removed all 255 values the code worked without any error.
Same error here. My error was due to I was using the checkpoint of cityscapes. `Cityscapes` have more labels than my data, so when I change the label number from 2 to 19 (which is the label number of cityscapes), `eval.py` runs perfectly. However, there might be some conflicts between `cityscapes` labels and own data labels. That needs further modification.
46,164,419
Getting a 'Label out of bound' error while running the testing script. Error is thrown in the confusion\_matrix function when the annotation values are compared with the number of classes. In my case annotation value is an image(560x560) and number\_of\_classes = 2. ``` [check_ops.assert_less(labels, num_classes_int64, message='`labels` out of bound')], labels ``` The above condition is always going to fail, as the annotation data is bigger than number of classes. First, There is a good chance that I am misunderstanding the code, but I can not make any sense of it. Second, If this is a valid check, then how can I modify my code or data to avoid this error. ```py def confusion_matrix(labels, predictions, num_classes=None, dtype=dtypes.int32, name=None, weights=None): with ops.name_scope(name, 'confusion_matrix', (predictions, labels, num_classes, weights)) as name: labels, predictions = remove_squeezable_dimensions( ops.convert_to_tensor(labels, name='labels'), ops.convert_to_tensor( predictions, name='predictions')) predictions = math_ops.cast(predictions, dtypes.int64) labels = math_ops.cast(labels, dtypes.int64) # Sanity checks - underflow or overflow can cause memory corruption. labels = control_flow_ops.with_dependencies( [check_ops.assert_non_negative( labels, message='`labels` contains negative values')], labels) predictions = control_flow_ops.with_dependencies( [check_ops.assert_non_negative( predictions, message='`predictions` contains negative values')], predictions) print(num_classes) if num_classes is None: num_classes = math_ops.maximum(math_ops.reduce_max(predictions), math_ops.reduce_max(labels)) + 1 #$ else: num_classes_int64 = math_ops.cast(num_classes, dtypes.int64) ---->>labels = control_flow_ops.with_dependencies( [check_ops.assert_less( labels, num_classes_int64, message='`labels` out of bound')], labels)<<---- predictions = control_flow_ops.with_dependencies( [check_ops.assert_less( predictions, num_classes_int64, message='`predictions` out of bound')], predictions) if weights is not None: predictions.get_shape().assert_is_compatible_with(weights.get_shape()) weights = math_ops.cast(weights, dtype) shape = array_ops.stack([num_classes, num_classes]) indices = array_ops.transpose(array_ops.stack([labels, predictions])) values = (array_ops.ones_like(predictions, dtype) if weights is None else weights) cm_sparse = sparse_tensor.SparseTensor( indices=indices, values=values, dense_shape=math_ops.to_int64(shape)) zero_matrix = array_ops.zeros(math_ops.to_int32(shape), dtype) return sparse_ops.sparse_add(zero_matrix, cm_sparse) ``` ```none Traceback (most recent call last): File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1327, in _do_call return fn(*args) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1306, in _run_fn status, run_metadata) File "C:\Program Files\Python35\lib\contextlib.py", line 66, in __exit__ next(self.gen) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 466, in raise_exception_on_not_ok_status pywrap_tensorflow.TF_GetCode(status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/supriya.godge/PycharmProjects/tf-image-segmentation/tf_image_segmentation/recipes/pascal_voc/DeepLab/output/resnet_v1_101_8s_test_airplan.py", line 81, in <module> image_np, annotation_np, pred_np, tmp = sess.run([image, annotation, pred, update_op]) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 895, in run run_metadata_ptr) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1124, in _run feed_dict_tensor, options, run_metadata) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1321, in _do_run options, run_metadata) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1340, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] Caused by op 'mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert', defined at: File "C:/Users/supriya.godge/PycharmProjects/tf-image-segmentation/tf_image_segmentation/recipes/pascal_voc/DeepLab/output/resnet_v1_101_8s_test_airplan.py", line 64, in <module> weights=weights) File "C:\Program Files\Python35\lib\site-packages\tensorflow\contrib\metrics\python\ops\metric_ops.py", line 2245, in streaming_mean_iou updates_collections=updates_collections, name=name) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 917, in mean_iou num_classes, weights) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 285, in _streaming_confusion_matrix labels, predictions, num_classes, weights=weights, dtype=cm_dtype) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\confusion_matrix.py", line 178, in confusion_matrix labels, num_classes_int64, message='`labels` out of bound')], File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\check_ops.py", line 401, in assert_less return control_flow_ops.Assert(condition, data, summarize=summarize) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\util\tf_should_use.py", line 175, in wrapped return _add_should_use_warning(fn(*args, **kwargs)) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 131, in Assert condition, no_op, true_assert, name="AssertGuard") File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\util\deprecation.py", line 296, in new_func return func(*args, **kwargs) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 1828, in cond orig_res_f, res_f = context_f.BuildCondBranch(false_fn) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 1694, in BuildCondBranch original_result = fn() File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 129, in true_assert condition, data, summarize, name="Assert") File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\gen_logging_ops.py", line 35, in _assert summarize=summarize, name=name) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 767, in apply_op op_def=op_def) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2630, in create_op original_op=self._default_original_op, op_def=op_def) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1204, in __init__ self._traceback = self._graph._extract_stack() # pylint: disable=protected-access InvalidArgumentError (see above for traceback): assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] ``` I am really lost here so any help or suggestion is appreciated!
2017/09/11
[ "https://Stackoverflow.com/questions/46164419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8485184/" ]
Same problem here. The 'labels' array, `Y_true`, had values `0, 255`. I used: ``` Y_true = Y_true/255 ``` to squash `Y_true` to `0, 1`. That removed the error.
under tensorflow 1.15.2, tensorflow/models/research/deeplab is basically quite ok. error message like: Invalid argument: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:] [x (mean\_iou/confusion\_matrix/control\_dependency:0) = ] likely due not considering background as 1 class. e.g. deeplab/datasets/data\_generator.py ``` # Number of semantic classes, including the # background class (if exists). For example, there # are 20 foreground classes + 1 background class in # the PASCAL VOC 2012 dataset. Thus, we set # num_classes=21. ```
46,164,419
Getting a 'Label out of bound' error while running the testing script. Error is thrown in the confusion\_matrix function when the annotation values are compared with the number of classes. In my case annotation value is an image(560x560) and number\_of\_classes = 2. ``` [check_ops.assert_less(labels, num_classes_int64, message='`labels` out of bound')], labels ``` The above condition is always going to fail, as the annotation data is bigger than number of classes. First, There is a good chance that I am misunderstanding the code, but I can not make any sense of it. Second, If this is a valid check, then how can I modify my code or data to avoid this error. ```py def confusion_matrix(labels, predictions, num_classes=None, dtype=dtypes.int32, name=None, weights=None): with ops.name_scope(name, 'confusion_matrix', (predictions, labels, num_classes, weights)) as name: labels, predictions = remove_squeezable_dimensions( ops.convert_to_tensor(labels, name='labels'), ops.convert_to_tensor( predictions, name='predictions')) predictions = math_ops.cast(predictions, dtypes.int64) labels = math_ops.cast(labels, dtypes.int64) # Sanity checks - underflow or overflow can cause memory corruption. labels = control_flow_ops.with_dependencies( [check_ops.assert_non_negative( labels, message='`labels` contains negative values')], labels) predictions = control_flow_ops.with_dependencies( [check_ops.assert_non_negative( predictions, message='`predictions` contains negative values')], predictions) print(num_classes) if num_classes is None: num_classes = math_ops.maximum(math_ops.reduce_max(predictions), math_ops.reduce_max(labels)) + 1 #$ else: num_classes_int64 = math_ops.cast(num_classes, dtypes.int64) ---->>labels = control_flow_ops.with_dependencies( [check_ops.assert_less( labels, num_classes_int64, message='`labels` out of bound')], labels)<<---- predictions = control_flow_ops.with_dependencies( [check_ops.assert_less( predictions, num_classes_int64, message='`predictions` out of bound')], predictions) if weights is not None: predictions.get_shape().assert_is_compatible_with(weights.get_shape()) weights = math_ops.cast(weights, dtype) shape = array_ops.stack([num_classes, num_classes]) indices = array_ops.transpose(array_ops.stack([labels, predictions])) values = (array_ops.ones_like(predictions, dtype) if weights is None else weights) cm_sparse = sparse_tensor.SparseTensor( indices=indices, values=values, dense_shape=math_ops.to_int64(shape)) zero_matrix = array_ops.zeros(math_ops.to_int32(shape), dtype) return sparse_ops.sparse_add(zero_matrix, cm_sparse) ``` ```none Traceback (most recent call last): File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1327, in _do_call return fn(*args) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1306, in _run_fn status, run_metadata) File "C:\Program Files\Python35\lib\contextlib.py", line 66, in __exit__ next(self.gen) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 466, in raise_exception_on_not_ok_status pywrap_tensorflow.TF_GetCode(status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/supriya.godge/PycharmProjects/tf-image-segmentation/tf_image_segmentation/recipes/pascal_voc/DeepLab/output/resnet_v1_101_8s_test_airplan.py", line 81, in <module> image_np, annotation_np, pred_np, tmp = sess.run([image, annotation, pred, update_op]) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 895, in run run_metadata_ptr) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1124, in _run feed_dict_tensor, options, run_metadata) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1321, in _do_run options, run_metadata) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1340, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] Caused by op 'mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert', defined at: File "C:/Users/supriya.godge/PycharmProjects/tf-image-segmentation/tf_image_segmentation/recipes/pascal_voc/DeepLab/output/resnet_v1_101_8s_test_airplan.py", line 64, in <module> weights=weights) File "C:\Program Files\Python35\lib\site-packages\tensorflow\contrib\metrics\python\ops\metric_ops.py", line 2245, in streaming_mean_iou updates_collections=updates_collections, name=name) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 917, in mean_iou num_classes, weights) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 285, in _streaming_confusion_matrix labels, predictions, num_classes, weights=weights, dtype=cm_dtype) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\confusion_matrix.py", line 178, in confusion_matrix labels, num_classes_int64, message='`labels` out of bound')], File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\check_ops.py", line 401, in assert_less return control_flow_ops.Assert(condition, data, summarize=summarize) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\util\tf_should_use.py", line 175, in wrapped return _add_should_use_warning(fn(*args, **kwargs)) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 131, in Assert condition, no_op, true_assert, name="AssertGuard") File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\util\deprecation.py", line 296, in new_func return func(*args, **kwargs) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 1828, in cond orig_res_f, res_f = context_f.BuildCondBranch(false_fn) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 1694, in BuildCondBranch original_result = fn() File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 129, in true_assert condition, data, summarize, name="Assert") File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\gen_logging_ops.py", line 35, in _assert summarize=summarize, name=name) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 767, in apply_op op_def=op_def) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2630, in create_op original_op=self._default_original_op, op_def=op_def) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1204, in __init__ self._traceback = self._graph._extract_stack() # pylint: disable=protected-access InvalidArgumentError (see above for traceback): assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] ``` I am really lost here so any help or suggestion is appreciated!
2017/09/11
[ "https://Stackoverflow.com/questions/46164419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8485184/" ]
Same problem here. The 'labels' array, `Y_true`, had values `0, 255`. I used: ``` Y_true = Y_true/255 ``` to squash `Y_true` to `0, 1`. That removed the error.
Same error here. My error was due to I was using the checkpoint of cityscapes. `Cityscapes` have more labels than my data, so when I change the label number from 2 to 19 (which is the label number of cityscapes), `eval.py` runs perfectly. However, there might be some conflicts between `cityscapes` labels and own data labels. That needs further modification.
46,164,419
Getting a 'Label out of bound' error while running the testing script. Error is thrown in the confusion\_matrix function when the annotation values are compared with the number of classes. In my case annotation value is an image(560x560) and number\_of\_classes = 2. ``` [check_ops.assert_less(labels, num_classes_int64, message='`labels` out of bound')], labels ``` The above condition is always going to fail, as the annotation data is bigger than number of classes. First, There is a good chance that I am misunderstanding the code, but I can not make any sense of it. Second, If this is a valid check, then how can I modify my code or data to avoid this error. ```py def confusion_matrix(labels, predictions, num_classes=None, dtype=dtypes.int32, name=None, weights=None): with ops.name_scope(name, 'confusion_matrix', (predictions, labels, num_classes, weights)) as name: labels, predictions = remove_squeezable_dimensions( ops.convert_to_tensor(labels, name='labels'), ops.convert_to_tensor( predictions, name='predictions')) predictions = math_ops.cast(predictions, dtypes.int64) labels = math_ops.cast(labels, dtypes.int64) # Sanity checks - underflow or overflow can cause memory corruption. labels = control_flow_ops.with_dependencies( [check_ops.assert_non_negative( labels, message='`labels` contains negative values')], labels) predictions = control_flow_ops.with_dependencies( [check_ops.assert_non_negative( predictions, message='`predictions` contains negative values')], predictions) print(num_classes) if num_classes is None: num_classes = math_ops.maximum(math_ops.reduce_max(predictions), math_ops.reduce_max(labels)) + 1 #$ else: num_classes_int64 = math_ops.cast(num_classes, dtypes.int64) ---->>labels = control_flow_ops.with_dependencies( [check_ops.assert_less( labels, num_classes_int64, message='`labels` out of bound')], labels)<<---- predictions = control_flow_ops.with_dependencies( [check_ops.assert_less( predictions, num_classes_int64, message='`predictions` out of bound')], predictions) if weights is not None: predictions.get_shape().assert_is_compatible_with(weights.get_shape()) weights = math_ops.cast(weights, dtype) shape = array_ops.stack([num_classes, num_classes]) indices = array_ops.transpose(array_ops.stack([labels, predictions])) values = (array_ops.ones_like(predictions, dtype) if weights is None else weights) cm_sparse = sparse_tensor.SparseTensor( indices=indices, values=values, dense_shape=math_ops.to_int64(shape)) zero_matrix = array_ops.zeros(math_ops.to_int32(shape), dtype) return sparse_ops.sparse_add(zero_matrix, cm_sparse) ``` ```none Traceback (most recent call last): File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1327, in _do_call return fn(*args) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1306, in _run_fn status, run_metadata) File "C:\Program Files\Python35\lib\contextlib.py", line 66, in __exit__ next(self.gen) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 466, in raise_exception_on_not_ok_status pywrap_tensorflow.TF_GetCode(status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/supriya.godge/PycharmProjects/tf-image-segmentation/tf_image_segmentation/recipes/pascal_voc/DeepLab/output/resnet_v1_101_8s_test_airplan.py", line 81, in <module> image_np, annotation_np, pred_np, tmp = sess.run([image, annotation, pred, update_op]) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 895, in run run_metadata_ptr) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1124, in _run feed_dict_tensor, options, run_metadata) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1321, in _do_run options, run_metadata) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1340, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] Caused by op 'mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert', defined at: File "C:/Users/supriya.godge/PycharmProjects/tf-image-segmentation/tf_image_segmentation/recipes/pascal_voc/DeepLab/output/resnet_v1_101_8s_test_airplan.py", line 64, in <module> weights=weights) File "C:\Program Files\Python35\lib\site-packages\tensorflow\contrib\metrics\python\ops\metric_ops.py", line 2245, in streaming_mean_iou updates_collections=updates_collections, name=name) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 917, in mean_iou num_classes, weights) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 285, in _streaming_confusion_matrix labels, predictions, num_classes, weights=weights, dtype=cm_dtype) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\confusion_matrix.py", line 178, in confusion_matrix labels, num_classes_int64, message='`labels` out of bound')], File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\check_ops.py", line 401, in assert_less return control_flow_ops.Assert(condition, data, summarize=summarize) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\util\tf_should_use.py", line 175, in wrapped return _add_should_use_warning(fn(*args, **kwargs)) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 131, in Assert condition, no_op, true_assert, name="AssertGuard") File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\util\deprecation.py", line 296, in new_func return func(*args, **kwargs) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 1828, in cond orig_res_f, res_f = context_f.BuildCondBranch(false_fn) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 1694, in BuildCondBranch original_result = fn() File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 129, in true_assert condition, data, summarize, name="Assert") File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\gen_logging_ops.py", line 35, in _assert summarize=summarize, name=name) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 767, in apply_op op_def=op_def) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2630, in create_op original_op=self._default_original_op, op_def=op_def) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1204, in __init__ self._traceback = self._graph._extract_stack() # pylint: disable=protected-access InvalidArgumentError (see above for traceback): assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] ``` I am really lost here so any help or suggestion is appreciated!
2017/09/11
[ "https://Stackoverflow.com/questions/46164419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8485184/" ]
In case anyone has encountered this issue and not been able to resolve by rescaling or adjusting channels, I found that the MeanIOU metric also causes this issue. Getting rid of it and training with only loss as a metric or defining another one worked for me.
under tensorflow 1.15.2, tensorflow/models/research/deeplab is basically quite ok. error message like: Invalid argument: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:] [x (mean\_iou/confusion\_matrix/control\_dependency:0) = ] likely due not considering background as 1 class. e.g. deeplab/datasets/data\_generator.py ``` # Number of semantic classes, including the # background class (if exists). For example, there # are 20 foreground classes + 1 background class in # the PASCAL VOC 2012 dataset. Thus, we set # num_classes=21. ```
46,164,419
Getting a 'Label out of bound' error while running the testing script. Error is thrown in the confusion\_matrix function when the annotation values are compared with the number of classes. In my case annotation value is an image(560x560) and number\_of\_classes = 2. ``` [check_ops.assert_less(labels, num_classes_int64, message='`labels` out of bound')], labels ``` The above condition is always going to fail, as the annotation data is bigger than number of classes. First, There is a good chance that I am misunderstanding the code, but I can not make any sense of it. Second, If this is a valid check, then how can I modify my code or data to avoid this error. ```py def confusion_matrix(labels, predictions, num_classes=None, dtype=dtypes.int32, name=None, weights=None): with ops.name_scope(name, 'confusion_matrix', (predictions, labels, num_classes, weights)) as name: labels, predictions = remove_squeezable_dimensions( ops.convert_to_tensor(labels, name='labels'), ops.convert_to_tensor( predictions, name='predictions')) predictions = math_ops.cast(predictions, dtypes.int64) labels = math_ops.cast(labels, dtypes.int64) # Sanity checks - underflow or overflow can cause memory corruption. labels = control_flow_ops.with_dependencies( [check_ops.assert_non_negative( labels, message='`labels` contains negative values')], labels) predictions = control_flow_ops.with_dependencies( [check_ops.assert_non_negative( predictions, message='`predictions` contains negative values')], predictions) print(num_classes) if num_classes is None: num_classes = math_ops.maximum(math_ops.reduce_max(predictions), math_ops.reduce_max(labels)) + 1 #$ else: num_classes_int64 = math_ops.cast(num_classes, dtypes.int64) ---->>labels = control_flow_ops.with_dependencies( [check_ops.assert_less( labels, num_classes_int64, message='`labels` out of bound')], labels)<<---- predictions = control_flow_ops.with_dependencies( [check_ops.assert_less( predictions, num_classes_int64, message='`predictions` out of bound')], predictions) if weights is not None: predictions.get_shape().assert_is_compatible_with(weights.get_shape()) weights = math_ops.cast(weights, dtype) shape = array_ops.stack([num_classes, num_classes]) indices = array_ops.transpose(array_ops.stack([labels, predictions])) values = (array_ops.ones_like(predictions, dtype) if weights is None else weights) cm_sparse = sparse_tensor.SparseTensor( indices=indices, values=values, dense_shape=math_ops.to_int64(shape)) zero_matrix = array_ops.zeros(math_ops.to_int32(shape), dtype) return sparse_ops.sparse_add(zero_matrix, cm_sparse) ``` ```none Traceback (most recent call last): File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1327, in _do_call return fn(*args) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1306, in _run_fn status, run_metadata) File "C:\Program Files\Python35\lib\contextlib.py", line 66, in __exit__ next(self.gen) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 466, in raise_exception_on_not_ok_status pywrap_tensorflow.TF_GetCode(status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/supriya.godge/PycharmProjects/tf-image-segmentation/tf_image_segmentation/recipes/pascal_voc/DeepLab/output/resnet_v1_101_8s_test_airplan.py", line 81, in <module> image_np, annotation_np, pred_np, tmp = sess.run([image, annotation, pred, update_op]) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 895, in run run_metadata_ptr) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1124, in _run feed_dict_tensor, options, run_metadata) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1321, in _do_run options, run_metadata) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1340, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] Caused by op 'mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert', defined at: File "C:/Users/supriya.godge/PycharmProjects/tf-image-segmentation/tf_image_segmentation/recipes/pascal_voc/DeepLab/output/resnet_v1_101_8s_test_airplan.py", line 64, in <module> weights=weights) File "C:\Program Files\Python35\lib\site-packages\tensorflow\contrib\metrics\python\ops\metric_ops.py", line 2245, in streaming_mean_iou updates_collections=updates_collections, name=name) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 917, in mean_iou num_classes, weights) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 285, in _streaming_confusion_matrix labels, predictions, num_classes, weights=weights, dtype=cm_dtype) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\confusion_matrix.py", line 178, in confusion_matrix labels, num_classes_int64, message='`labels` out of bound')], File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\check_ops.py", line 401, in assert_less return control_flow_ops.Assert(condition, data, summarize=summarize) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\util\tf_should_use.py", line 175, in wrapped return _add_should_use_warning(fn(*args, **kwargs)) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 131, in Assert condition, no_op, true_assert, name="AssertGuard") File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\util\deprecation.py", line 296, in new_func return func(*args, **kwargs) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 1828, in cond orig_res_f, res_f = context_f.BuildCondBranch(false_fn) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 1694, in BuildCondBranch original_result = fn() File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 129, in true_assert condition, data, summarize, name="Assert") File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\gen_logging_ops.py", line 35, in _assert summarize=summarize, name=name) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 767, in apply_op op_def=op_def) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2630, in create_op original_op=self._default_original_op, op_def=op_def) File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1204, in __init__ self._traceback = self._graph._extract_stack() # pylint: disable=protected-access InvalidArgumentError (see above for traceback): assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:x (mean_iou/confusion_matrix/control_dependency:0) = ] [0 0 0...] [y (mean_iou/ToInt64_2:0) = ] [21] [[Node: mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert = Assert[T=[DT_STRING, DT_STRING, DT_INT64, DT_STRING, DT_INT64], summarize=3, _device="/job:localhost/replica:0/task:0/cpu:0"](mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_0, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_1, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/data_3, mean_iou/confusion_matrix/assert_less/Assert/AssertGuard/Assert/Switch_2)]] ``` I am really lost here so any help or suggestion is appreciated!
2017/09/11
[ "https://Stackoverflow.com/questions/46164419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8485184/" ]
In case anyone has encountered this issue and not been able to resolve by rescaling or adjusting channels, I found that the MeanIOU metric also causes this issue. Getting rid of it and training with only loss as a metric or defining another one worked for me.
Same error here. My error was due to I was using the checkpoint of cityscapes. `Cityscapes` have more labels than my data, so when I change the label number from 2 to 19 (which is the label number of cityscapes), `eval.py` runs perfectly. However, there might be some conflicts between `cityscapes` labels and own data labels. That needs further modification.
45,318,255
**Code:** ``` import numpy as np z = np.array([[1,3,5],[2,4,6]]) print(z[0:, :2]) ``` **Answer:** ``` [[1, 3] [2, 4]] ``` I am a python beginner, I was solving an interactive exercise when the above mentioned question appeared. I am not able to understand, how z[0:, :2] works in this case? If possible, please help me understand this scenario.
2017/07/26
[ "https://Stackoverflow.com/questions/45318255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4282170/" ]
You can read about Numpy slicing and indexing here: <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html> In this case, `0:` means "all the rows, starting from (and including) row 0 and going until the end" (you could also just use the equivalent `:`, which means "all the rows, starting from the beginning and going until the end"). `:2` means "all the columns, starting from the beginning and going until (but not including) column 2". Together, `z[0:, :2]` means "the part of `z` that includes all the rows and the first two columns". The first dimension listed is rows, and the second is columns. If your array was 3D, you could include yet another dimension with another comma, and so on.
First you ask to get all rows (`0:` is the same as `:`): ``` [[1,3,5], [2,4,6]] ``` Then you ask for columns 0 and 1 (`:2` is the same as `0:2` which means from 0 until 2 exclusive): ``` [[1,3], [2,4]] ```
45,318,255
**Code:** ``` import numpy as np z = np.array([[1,3,5],[2,4,6]]) print(z[0:, :2]) ``` **Answer:** ``` [[1, 3] [2, 4]] ``` I am a python beginner, I was solving an interactive exercise when the above mentioned question appeared. I am not able to understand, how z[0:, :2] works in this case? If possible, please help me understand this scenario.
2017/07/26
[ "https://Stackoverflow.com/questions/45318255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4282170/" ]
First you ask to get all rows (`0:` is the same as `:`): ``` [[1,3,5], [2,4,6]] ``` Then you ask for columns 0 and 1 (`:2` is the same as `0:2` which means from 0 until 2 exclusive): ``` [[1,3], [2,4]] ```
This is a feature of numpy arrays, and, in this example, applies to 2D arrays. If `z = np.array([l0, l1, l2, l3])` where l0, l1, l2, l3 are lists, then `z[1:3,2:5] = [l1[2:5], l2[2:5]]` So the first slice argument applies to the outer list, while the second argument applies to the inner lists. This generalizes to 3D numpy arrays, etc. Here's the doc: <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html>
45,318,255
**Code:** ``` import numpy as np z = np.array([[1,3,5],[2,4,6]]) print(z[0:, :2]) ``` **Answer:** ``` [[1, 3] [2, 4]] ``` I am a python beginner, I was solving an interactive exercise when the above mentioned question appeared. I am not able to understand, how z[0:, :2] works in this case? If possible, please help me understand this scenario.
2017/07/26
[ "https://Stackoverflow.com/questions/45318255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4282170/" ]
You can read about Numpy slicing and indexing here: <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html> In this case, `0:` means "all the rows, starting from (and including) row 0 and going until the end" (you could also just use the equivalent `:`, which means "all the rows, starting from the beginning and going until the end"). `:2` means "all the columns, starting from the beginning and going until (but not including) column 2". Together, `z[0:, :2]` means "the part of `z` that includes all the rows and the first two columns". The first dimension listed is rows, and the second is columns. If your array was 3D, you could include yet another dimension with another comma, and so on.
`z[0:, :2]` selects all elements in all (ie., both) rows (`0:` selects the range of row indices starting with 0) and in the first two columns (`:2` selects the column indices 0 and 1.) ``` column 0 1 2 -------------- row 0 | 1 3 5 row 1 | 2 4 6 ```
45,318,255
**Code:** ``` import numpy as np z = np.array([[1,3,5],[2,4,6]]) print(z[0:, :2]) ``` **Answer:** ``` [[1, 3] [2, 4]] ``` I am a python beginner, I was solving an interactive exercise when the above mentioned question appeared. I am not able to understand, how z[0:, :2] works in this case? If possible, please help me understand this scenario.
2017/07/26
[ "https://Stackoverflow.com/questions/45318255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4282170/" ]
You can read about Numpy slicing and indexing here: <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html> In this case, `0:` means "all the rows, starting from (and including) row 0 and going until the end" (you could also just use the equivalent `:`, which means "all the rows, starting from the beginning and going until the end"). `:2` means "all the columns, starting from the beginning and going until (but not including) column 2". Together, `z[0:, :2]` means "the part of `z` that includes all the rows and the first two columns". The first dimension listed is rows, and the second is columns. If your array was 3D, you could include yet another dimension with another comma, and so on.
This is a feature of numpy arrays, and, in this example, applies to 2D arrays. If `z = np.array([l0, l1, l2, l3])` where l0, l1, l2, l3 are lists, then `z[1:3,2:5] = [l1[2:5], l2[2:5]]` So the first slice argument applies to the outer list, while the second argument applies to the inner lists. This generalizes to 3D numpy arrays, etc. Here's the doc: <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html>
45,318,255
**Code:** ``` import numpy as np z = np.array([[1,3,5],[2,4,6]]) print(z[0:, :2]) ``` **Answer:** ``` [[1, 3] [2, 4]] ``` I am a python beginner, I was solving an interactive exercise when the above mentioned question appeared. I am not able to understand, how z[0:, :2] works in this case? If possible, please help me understand this scenario.
2017/07/26
[ "https://Stackoverflow.com/questions/45318255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4282170/" ]
`z[0:, :2]` selects all elements in all (ie., both) rows (`0:` selects the range of row indices starting with 0) and in the first two columns (`:2` selects the column indices 0 and 1.) ``` column 0 1 2 -------------- row 0 | 1 3 5 row 1 | 2 4 6 ```
This is a feature of numpy arrays, and, in this example, applies to 2D arrays. If `z = np.array([l0, l1, l2, l3])` where l0, l1, l2, l3 are lists, then `z[1:3,2:5] = [l1[2:5], l2[2:5]]` So the first slice argument applies to the outer list, while the second argument applies to the inner lists. This generalizes to 3D numpy arrays, etc. Here's the doc: <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html>
68,434,126
In a Tkinter window of the Test.py file, I would like to display in a textobox what is printed in the Python console. By clicking on button, you start a function in the Test.py file that calls the X.py and Y.py scripts (more precisely their functions). The results of the scripts are printed correctly in the Python console: first the result of the X file is printed and then immediately after the result of the Y file is printed. I would like to see these X.py and Y.py results printed in a textbox. Of course, if possible, I would also like to hide (not open at all) the Python console. I have read a few questions here on the site, but have not been able to accomplish this. Above for information purposes I have explained the purpose of what I am creating, therefore it is useless to paste the entire code already working of the various functions. Can you help me and show me the code to view the script results in the textobox please? Of course, if possible, I would also like to hide (not open at all) the Python console ``` #IMPORT OF FILE X AND Y, AND RELATED FUNCTIONS from File.X import Example_Name_Function_1 from File.Y import Example_Name_Function_2 #TEXTOBOX text = tk.Text(test,width=80,height=50, background="black", foreground="white") text.pack() text.place(x=450, y=20) text.insert(INSERT, "aaaaaaaa\n") text.insert(END, " bbbbbbbb \n") #BUTTON button = Button(test, text="Go", foreground='black', command= Go) button.place(x=7, y=512) ``` **CODE UPDATE** I have reported the initial code. Now the window opens immediately and the scraping starts only after clicking on the button. As a result, the results of the scraping are printed in the Python terminal console. Not in the textobox. Being long in the code, I preferred to report it like this. But inside the code of @Matiiss, but it doesn't work ``` #I open tkinter window for scraping editmenu.add_command(label='Scraping', command=filename.draw_graph) ``` \_ ``` #WINDOW SCRAPING from tkinter import * from tkinter import ttk import tkinter as tk import tkinter.font as tkFont from PIL import ImageTk, Image from File import Scraping_Nome_Campionati from File import Scraping_Nome_Squadre_MIO import subprocess def draw_graph(): test_scraping=tk.Toplevel() test_scraping.title("Scraping") test_scraping.geometry("1100x900") test_scraping.configure(bg='#282828') #I call up and open the two scripts for scraping (no tkinter) def do_scraping(): msg1 = Scraping_Nome_Campionati.scraping_nome_campionati_e_tor() if msg1: message1.configure(text=msg1) message1.configure(foreground="red") vuoto_elenco_campionati.config(image=render7) else: vuoto_elenco_campionati.config(image=render8) message1.configure(foreground="green") msg2 = Scraping_Nome_Squadre_MIO.scraping_nome_squadre_e_tor() if msg2: message2.configure(text=msg2) message2.configure(foreground="red") vuoto_elenco_squadre.config(image=render7) else: vuoto_elenco_squadre.config(image=render8) message2.configure(foreground="green") #YOUR CODE def call_obj_from(obj, module): if module: proc = subprocess.Popen(['python3', '-c', f'from {module} import {obj}; {obj}()'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) return proc.communicate()[0].decode() text.insert('end', call_obj_from('scraping_nome_campionati_e_tor', 'File.Scraping_Nome_Campionati')) text.insert('end', call_obj_from('scraping_nome_squadre_e_tor', 'file.Scraping_Nome_Squadre_MIO')) text = tk.Text(test_scraping,width=80,height=50, background="black", foreground="white") text.pack() text.place(x=450, y=20) text.insert(INSERT, "aaaaaa\n") text.insert(END, "bbbbbbbbb\n") button = Button(test_scraping, text="Avvia", bg='#e95420', foreground='white', command=do_scraping) button.place(x=116, y=512) test_scraping.mainloop() ``` **CODE UPLOAD 2** ``` # Text widget with file-like object feature class TextOut(tk.Text): def __init__(self, master, **kw): super().__init__(master, **kw) # required output function for a file-like object def write(self, message): self.insert("insert", message) def do_scraping(): # temporarily redirect sys.stdout with redirect_stdout(text) as f: scraping_nome_campionati_e_tor() scraping_nome_squadre_e_tor() print("completed") # this shows in the text box as well print("done") # this will show in console instead of text box msg1 = Scraping_Nome_Campionati.scraping_nome_campionati_e_tor() if msg1: message1.configure(text=msg1) message1.configure(foreground="red") vuoto_elenco_campionati.config(image=render7) else: vuoto_elenco_campionati.config(image=render8) message1.configure(foreground="green") msg2 = Scraping_Nome_Squadre_MIO.scraping_nome_squadre_e_tor() if msg2: message2.configure(text=msg2) message2.configure(foreground="red") vuoto_elenco_squadre.config(image=render7) else: vuoto_elenco_squadre.config(image=render8) message2.configure(foreground="green") text = TextOut(test_scraping,width=80,height=50, background="black", foreground="white") text.pack() text.place(x=450, y=20) button = Button(test_scraping, text="Avvia", bg='#e95420', foreground='white', command=do_scraping) button.place(x=116, y=512) ```
2021/07/19
[ "https://Stackoverflow.com/questions/68434126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16472472/" ]
For Python 3.4+, you can use `contextlib.redirect_stdout` (see [official document](https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout)) to redirect `sys.stdout` to another file or file-like object temporarily. ```py import tkinter as tk from contextlib import redirect_stdout from File.X import Example_Name_Function_1 from File.Y import Example_Name_Function_2 # Text widget with file-like object feature class TextOut(tk.Text): def __init__(self, master, **kw): super().__init__(master, **kw) # required output function for a file-like object def write(self, message): self.insert("insert", message) def Go(): # temporarily redirect sys.stdout with redirect_stdout(text) as f: Example_Name_Function_1() Example_Name_Function_2() print("completed") # this shows in the text box as well print("done") # this will show in console instead of text box test = tk.Tk() # use TextOut instead of normal Text widget text = TextOut(test, width=80, height=50, bg="black", fg="white") text.pack() button = tk.Button(test, text="Go", command=Go) button.pack() test.mainloop() ```
Ok, so after a lot of trial and error I finally found a way to accomplish what You want (to be fair though, You were the one that was supposed to go through this phase AND show Your attempts which You failed to do, either how I don't mind much since I learned stuff too): ```py from tkinter import Tk, Text import subprocess def call_obj_from(obj, module): if module: proc = subprocess.Popen(['python', '-c', f'from {module} import {obj}; {obj}()'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) return proc.communicate()[0].decode() root = Tk() text = Text(root) text.pack() text.insert('end', call_obj_from('example_func_1', 'file.x')) text.insert('end', call_obj_from('example_func_2', 'file.y')) root.mainloop() ``` in simple terms the two arguments are `obj` or in other words what You will want to execute that also prints something to the console, and the `module` which is the file where that object is located so for example in this case I would have to have a file in the same directory named `functions.py` and in it there should be a function named `func()`
48,908,156
I am using **Django-Cookiecutter** which uses **Django-Allauth** to handle all the authentication and there is one App installed called **user** which handles everything related to users like sign-up, sign-out etc. I am sharing the models.py file for users ``` @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) ``` Now that I have added my new App say Course and my models.py is ``` class Course(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=100) def __str__(self): return self.name def get_absolute_url(self): return reverse("details:assess", kwargs={"id": self.id}) ``` I have also defined my views.py as ``` @login_required def course_list(request): queryset = queryset = Course.objects.all() print("query set value is", queryset) context = { "object_list" :queryset, } return render(request, "course_details/Course_details.html", context) ``` Is there any way I can reference(Foreign key) **User App** to my **Course App** so that each user has their own Course assigned to it. one of the possible ways is to filter objects on the basis of the user and pass it to the template I can't figure it out that how to map users and course in order to get the list of course which is assigned to the particular user.
2018/02/21
[ "https://Stackoverflow.com/questions/48908156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5881652/" ]
Unless you are offering a course to just one user, it does not make sense to have a one-to-many relationship between User and Course models. So, you need a many-to-many relationship. It is also wise to extend the user model by creating a UserProfile model and relate UserProfile to your course. You can look [here](https://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django) for how to extend the user model. So, what you should really do is this: ``` class Course(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=100) # Make sure you first import UserProfile model before referring to it students = models.ManyToManyField(UserProfile, related_name = 'courses') def __str__(self): return self.name def get_absolute_url(self): return reverse("details:assess", kwargs={"id": self.id}) ``` Also, note that adding and querying many-to-many relationships are little different. Please see [the docs](https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_many/) for more detail.
You can directly add foreign key as: ``` user = models.Foreignkey(User,related_name="zyz") ```
72,184,482
I have a project trying to imagescrape from a website. I use a csv file with all the urls. Some urls i dont have the premission to open(or they dont exist). I get a Http error 403 in phyton from those. I just want the try the next url in the csv file and ignore the error. ```python import urllib.request import csv with open ('urls_01.csv') as images: images = csv.reader(images) img_count = 1 for image in images: urllib.request.urlretrieve(image[0], 'images/image_{0}.jpg'.format(img_count)) img_count += 1 ``` This is the error ```python Traceback (most recent call last): File "c:\Users\Heigre\Documents\Phyton\img_test.py", line 8, in <module> urllib.request.urlretrieve(image[0], File "C:\Program Files\Python310\lib\urllib\request.py", line 241, in urlretrieve with contextlib.closing(urlopen(url, data)) as fp: File "C:\Program Files\Python310\lib\urllib\request.py", line 216, in urlopen return opener.open(url, data, timeout) File "C:\Program Files\Python310\lib\urllib\request.py", line 525, in open response = meth(req, response) File "C:\Program Files\Python310\lib\urllib\request.py", line 634, in http_response response = self.parent.error( File "C:\Program Files\Python310\lib\urllib\request.py", line 563, in error return self._call_chain(*args) File "C:\Program Files\Python310\lib\urllib\request.py", line 496, in _call_chain result = func(*args) File "C:\Program Files\Python310\lib\urllib\request.py", line 643, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden ```
2022/05/10
[ "https://Stackoverflow.com/questions/72184482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19084463/" ]
You may have an issue with the SNS access policy. There is a video of troubleshooting this issue at <https://youtu.be/RjSW75YsBMM>.
Make sure that your SNS topic has the proper Access Policy set. In my case, the default Access Policy included an `AWS:SourceOwner` condition which I needed to remove in order to allow the S3 event configuration to perform the `SNS:Publish` action against the topic.
26,207,097
I am wondering how one would create a GUI application, and interact with it from the console that started it. As an example, I would like to create a GUI in PyQt and work with it from the console. This could be for testing settings without restarting the app, but in larger projects also for calling functions etc. Here is a simple example using PyQt: ``` import sys from PyQt4 import QtGui def main(): app = QtGui.QApplication(sys.argv) w = QtGui.QWidget() w.show() sys.exit(app.exec_()) if __name__ == '__main__': main() ``` when this is run with `python -i example.py` the console is blocked as long as the main-loop is executed. How can I call `w.resize(100,100)` while the GUI is running?
2014/10/05
[ "https://Stackoverflow.com/questions/26207097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1356998/" ]
ops, posted wrong answer before there is a post in Stack about that [Execute Python code from within PyQt event loop](https://stackoverflow.com/questions/4893748/execute-python-code-from-within-pyqt-event-loop)
The easiest way is to use IPython: ``` ipython --gui=qt4 ``` See `ipython --help` or the [online documentation](http://ipython.org/ipython-doc/dev/config/options/terminal.html) for more options (e.g. gtk, tk, etc).
26,207,097
I am wondering how one would create a GUI application, and interact with it from the console that started it. As an example, I would like to create a GUI in PyQt and work with it from the console. This could be for testing settings without restarting the app, but in larger projects also for calling functions etc. Here is a simple example using PyQt: ``` import sys from PyQt4 import QtGui def main(): app = QtGui.QApplication(sys.argv) w = QtGui.QWidget() w.show() sys.exit(app.exec_()) if __name__ == '__main__': main() ``` when this is run with `python -i example.py` the console is blocked as long as the main-loop is executed. How can I call `w.resize(100,100)` while the GUI is running?
2014/10/05
[ "https://Stackoverflow.com/questions/26207097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1356998/" ]
The following example uses the [code](https://docs.python.org/3/library/code.html) module to run a console in the command prompt (be sure to run the script from the command line). [Subclassing QThread](https://kushaldas.in/posts/pyqt5-thread-example.html) provides a route by which the console can be run in a separate thread from that of the main GUI and enables some interaction with it. The stub example below should be easy enough to incorporate into a larger packaged PyQt program. ```py from PyQt5.QtWidgets import * from PyQt5.QtCore import * import threading #used only to id the active thread import code import sys class Worker(QThread): #Subclass QThread and re-define run() signal = pyqtSignal() def __init__(self): super().__init__() def raise_sys_exit(self): #more gracefully exit the console print('(Deactivated Console)') raise SystemExit def setup_console(self,global_dict): console_exit = {'exit': self.raise_sys_exit} self.console = code.InteractiveConsole(locals=dict(global_dict,**console_exit)) def run(self): try: print('worker', threading.get_ident()) self.console.interact() except SystemExit: self.signal.emit() class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args,**kwargs) self.data = [1,2,3,4] #some data we might want to look at layout = QVBoxLayout() self.b = QPushButton("Interact") self.b.clicked.connect(self.b_clicked) layout.addWidget(self.b) w = QWidget() w.setLayout(layout) self.setCentralWidget(w) self.worker = Worker() self.worker.signal.connect(self.finished) def finished(self): self.b.setEnabled(True) def b_clicked(self): print('main',threading.get_ident()) self.worker.setup_console(globals()) #pass the global variables to the worker self.worker.start() self.b.setEnabled(False) #disable the GUI button until console is exited if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() window.show() app.exec_() ```
The easiest way is to use IPython: ``` ipython --gui=qt4 ``` See `ipython --help` or the [online documentation](http://ipython.org/ipython-doc/dev/config/options/terminal.html) for more options (e.g. gtk, tk, etc).
2,157,208
In python, I have a global variable defined that gets read/incremented by different threads. Because of the GIL, will this ever cause problems without using any kind of locking mechanism?
2010/01/28
[ "https://Stackoverflow.com/questions/2157208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/261273/" ]
The GIL only requires that the interpreter completely executes a single bytecode instruction before another thread can take over. However, there is no reason to assume that an increment operation is a single instruction. For example: ``` >>> import dis >>> dis.dis(compile("x=753","","exec")) 1 0 LOAD_CONST 0 (753) 3 STORE_NAME 0 (x) 6 LOAD_CONST 1 (None) 9 RETURN_VALUE >>> dis.dis(compile("x+=1","","exec")) 1 0 LOAD_NAME 0 (x) 3 LOAD_CONST 0 (1) 6 INPLACE_ADD 7 STORE_NAME 0 (x) 10 LOAD_CONST 1 (None) 13 RETURN_VALUE ``` As you can see, even these simple operations are more than a single bytecode instruction. Therefore, whenever sharing data between threads, you *must* use a separate locking mechanism (eg, threading.lock) in order to maintain data consistency.
Yes, multithreading without locking almost always causes problems, with or without a GIL.
56,120,774
In the case where python executes more operations, it is slower. The following is a very simple comparison of two separate nested loops (for finding a Pythagorean triple `(a,b,c)` which sum to 1000): ``` #Takes 9 Seconds for a in range(1, 1000): for b in range(a, 1000): ab = 1000 - (a + b) for c in range(ab, 1000): if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) exit() #Solution B #Takes 7 Seconds for a in range(1, 1000): for b in range(a, 1000): for c in range(b, 1000): if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) exit() ``` I expected solution A to shave a second or two off of solution B but instead it increased the time it took to complete. by two seconds. ``` instead of iterating 1, 1, 1 1, 1, 2 ... 1, 1, 999 1, 2, 2 It would iterate 1, 1, 998 1, 1, 999 1, 2, 997 1, 2, 998 1, 2, 999 1, 3, 996 ``` It seems to me that solution a should vastly improve speed by cutting out thousands to millions of operations, but it in fact does not. I am aware that there is a simple way to vastly improve this algorithm but I am trying to understand why python would run slower in the case that would seem to be faster.
2019/05/13
[ "https://Stackoverflow.com/questions/56120774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11495271/" ]
You can just count total amount of iterations in each solution and see that A takes more iterations to find the result: ``` #Takes 9 Seconds def A(): count = 0 for a in range(1, 1000): for b in range(a, 1000): ab = 1000 - (a + b) for c in range(ab, 1000): count += 1 if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) print('A:', count) return #Solution B #Takes 7 Seconds def B(): count = 0 for a in range(1, 1000): for b in range(a, 1000): for c in range(b, 1000): count += 1 if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) print('B:', count) return A() B() ``` Output: ``` A: 115425626 B: 81137726 ``` That's why A is slower. Also `ab = 1000 - (a + b)` takes time.
You have two false premises in your confusion: * The methods find all triples. They do not; each one finds a single triple and then aborts. * The upper method (aka "solution A") does fewer comparisons. I added some basic instrumentation to test your premises: import time ``` #Takes 9 Seconds count = 0 start = time.time() for a in range(1, 1000): for b in range(a, 1000): ab = 1000 - (a + b) for c in range(ab, 1000): count += 1 if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) print(count, time.time() - start) break #Solution B #Takes 7 Seconds count = 0 start = time.time() for a in range(1, 1000): for b in range(a, 1000): for c in range(b, 1000): count += 1 if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) print(count, time.time() - start) break ``` Output: ``` 200 375 425 115425626 37.674554109573364 200 375 425 81137726 25.986871480941772 ``` `Solution B` considers fewer triples. Do the math ... which is the lower value, `b` or `1000-a-b` for this exercise?
56,120,774
In the case where python executes more operations, it is slower. The following is a very simple comparison of two separate nested loops (for finding a Pythagorean triple `(a,b,c)` which sum to 1000): ``` #Takes 9 Seconds for a in range(1, 1000): for b in range(a, 1000): ab = 1000 - (a + b) for c in range(ab, 1000): if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) exit() #Solution B #Takes 7 Seconds for a in range(1, 1000): for b in range(a, 1000): for c in range(b, 1000): if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) exit() ``` I expected solution A to shave a second or two off of solution B but instead it increased the time it took to complete. by two seconds. ``` instead of iterating 1, 1, 1 1, 1, 2 ... 1, 1, 999 1, 2, 2 It would iterate 1, 1, 998 1, 1, 999 1, 2, 997 1, 2, 998 1, 2, 999 1, 3, 996 ``` It seems to me that solution a should vastly improve speed by cutting out thousands to millions of operations, but it in fact does not. I am aware that there is a simple way to vastly improve this algorithm but I am trying to understand why python would run slower in the case that would seem to be faster.
2019/05/13
[ "https://Stackoverflow.com/questions/56120774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11495271/" ]
You can just count total amount of iterations in each solution and see that A takes more iterations to find the result: ``` #Takes 9 Seconds def A(): count = 0 for a in range(1, 1000): for b in range(a, 1000): ab = 1000 - (a + b) for c in range(ab, 1000): count += 1 if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) print('A:', count) return #Solution B #Takes 7 Seconds def B(): count = 0 for a in range(1, 1000): for b in range(a, 1000): for c in range(b, 1000): count += 1 if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) print('B:', count) return A() B() ``` Output: ``` A: 115425626 B: 81137726 ``` That's why A is slower. Also `ab = 1000 - (a + b)` takes time.
Yes there is a performance difference, but because your code is doing different things: * Solution A runs c over the `range(1000-(a+b), 1000)`, which will be much shorter. (in fact it doesn't need to run c, it only needs to check for one value `c = 1000-(a+b)`, since that's the only c-value for given a,b that satisfies the constraint `(a + b + c) == 1000)`) + however it does compute and store `ab = 1000-(a+b)`, which will be stored in the `locals()` dict * Solution B runs c over the entire `range(b, 1000)`. But it just uses the expression `1000-(a+b)` directly, it doesn't store it to a local variable `ab`.
56,120,774
In the case where python executes more operations, it is slower. The following is a very simple comparison of two separate nested loops (for finding a Pythagorean triple `(a,b,c)` which sum to 1000): ``` #Takes 9 Seconds for a in range(1, 1000): for b in range(a, 1000): ab = 1000 - (a + b) for c in range(ab, 1000): if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) exit() #Solution B #Takes 7 Seconds for a in range(1, 1000): for b in range(a, 1000): for c in range(b, 1000): if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) exit() ``` I expected solution A to shave a second or two off of solution B but instead it increased the time it took to complete. by two seconds. ``` instead of iterating 1, 1, 1 1, 1, 2 ... 1, 1, 999 1, 2, 2 It would iterate 1, 1, 998 1, 1, 999 1, 2, 997 1, 2, 998 1, 2, 999 1, 3, 996 ``` It seems to me that solution a should vastly improve speed by cutting out thousands to millions of operations, but it in fact does not. I am aware that there is a simple way to vastly improve this algorithm but I am trying to understand why python would run slower in the case that would seem to be faster.
2019/05/13
[ "https://Stackoverflow.com/questions/56120774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11495271/" ]
You have two false premises in your confusion: * The methods find all triples. They do not; each one finds a single triple and then aborts. * The upper method (aka "solution A") does fewer comparisons. I added some basic instrumentation to test your premises: import time ``` #Takes 9 Seconds count = 0 start = time.time() for a in range(1, 1000): for b in range(a, 1000): ab = 1000 - (a + b) for c in range(ab, 1000): count += 1 if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) print(count, time.time() - start) break #Solution B #Takes 7 Seconds count = 0 start = time.time() for a in range(1, 1000): for b in range(a, 1000): for c in range(b, 1000): count += 1 if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))): print(a,b,c) print(count, time.time() - start) break ``` Output: ``` 200 375 425 115425626 37.674554109573364 200 375 425 81137726 25.986871480941772 ``` `Solution B` considers fewer triples. Do the math ... which is the lower value, `b` or `1000-a-b` for this exercise?
Yes there is a performance difference, but because your code is doing different things: * Solution A runs c over the `range(1000-(a+b), 1000)`, which will be much shorter. (in fact it doesn't need to run c, it only needs to check for one value `c = 1000-(a+b)`, since that's the only c-value for given a,b that satisfies the constraint `(a + b + c) == 1000)`) + however it does compute and store `ab = 1000-(a+b)`, which will be stored in the `locals()` dict * Solution B runs c over the entire `range(b, 1000)`. But it just uses the expression `1000-(a+b)` directly, it doesn't store it to a local variable `ab`.
37,464,116
I have found some ways to using python to build android app.But all of them need to install sl4a and pythonforandroid. It is so complicated,so is there any way to package sl4a to my android app project,and once I install the apk,I needn't install sl4a any more.
2016/05/26
[ "https://Stackoverflow.com/questions/37464116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5867427/" ]
You can use Kivy at following link : [Python for Android](https://github.com/kivy/python-for-android) It will can help u have a look to the following topic : [How can I integrate a Python code in the Android Java app?](https://www.quora.com/How-can-I-integrate-a-Python-code-in-the-Android-Java-app) hope this help you.
You *can* do this. What it comes down to is packaging the Python interpreter (compiled by the NDK) in your app, and starting it via the standard NDK mechanisms. This is the same thing that e.g. Kivy does, but you'd be adding the code to your own app rather than (like Kivy) using a java bootstrap then letting the Python manage everything else. One option, which has seen a little discussion/development recently, is to use [python-for-android](https://github.com/kivy/python-for-android) to build all the python components, then copy them into your java project (and add the code to handle it). This is possible, but not currently as easy as it could be, you'd need to look into how it works internally to get the outputs you need. Another option that is probably easier right now if you don't need compiled code beyond python itself is to directly use the precompiled python binaries of the [CrystaX NDK](https://www.crystax.net/), in which case including the python binaries comes down to only adding them to your Android.mk. You'd still need some C and NDK code to interact with the interpreter, but the process is quite straightforward. (SL4A has some Android build tools of its own, which you could also use for this, but I don't know what you'd need to do to integrate it as I think SL4A does extra things on top of just having the python interpreter present).
21,717,995
How can i set the python on my mac back to the default reference location? When I to do ``` sudo easy_install virtualenv ``` I get the following results ``` dyld: Library not loaded: @rpath/Python Referenced from: /Users/a1ctesta/Library/Enthought/Canopy_64bit/User/bin/python Reason: image not found ``` I do not have Canopy installed any longer so I wanted to restore this back to the original reference that came on the computer.
2014/02/12
[ "https://Stackoverflow.com/questions/21717995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3221720/" ]
You probably need to modify your `$PATH` environment variable so that `/usr/bin` is before your custom path. To check if this is the issue, run the following command and see if `/usr/bin` is before or after your custom path ``` $ echo $PATH ``` The PATH environment variable is often set in `~/.bash_profile`, for example on my system I have ``` export PATH=/opt/local/bin:/opt/local/sbin:/Developer/usr/bin:$PATH ``` Meaning that the `python` executable in `/opt/local/bin` takes precedence over the one in the default `PATH`.
I had the same issue. It was easiest to reinstall Canopy. From the Canopy preferences menu, Unset Canopy as your default Python. Then restart your computer. <https://support.enthought.com/hc/en-us/articles/204469700-Uninstalling-and-resetting-Canopy>
21,717,995
How can i set the python on my mac back to the default reference location? When I to do ``` sudo easy_install virtualenv ``` I get the following results ``` dyld: Library not loaded: @rpath/Python Referenced from: /Users/a1ctesta/Library/Enthought/Canopy_64bit/User/bin/python Reason: image not found ``` I do not have Canopy installed any longer so I wanted to restore this back to the original reference that came on the computer.
2014/02/12
[ "https://Stackoverflow.com/questions/21717995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3221720/" ]
You probably need to modify your `$PATH` environment variable so that `/usr/bin` is before your custom path. To check if this is the issue, run the following command and see if `/usr/bin` is before or after your custom path ``` $ echo $PATH ``` The PATH environment variable is often set in `~/.bash_profile`, for example on my system I have ``` export PATH=/opt/local/bin:/opt/local/sbin:/Developer/usr/bin:$PATH ``` Meaning that the `python` executable in `/opt/local/bin` takes precedence over the one in the default `PATH`.
I had this issue as well. If you edit your ~/.bash\_profile it will permanently fix the issue. In terminal enter ``` nano ~/.bash_profile ``` It will then show something along the lines of ``` # Setting PATH for Python 2.7 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}" export PATH # Added by Canopy installer on 2017-03-28 # VIRTUAL_ENV_DISABLE_PROMPT can be set to '' to make the bash prompt show that Canopy is active, otherwise 1 alias activate_canopy="source '/Users/chrisdunstan/Library/Enthought/Canopy_64bit/User/bin/activate'" VIRTUAL_ENV_DISABLE_PROMPT=1 source '/Users/chrisdunstan/Library/Enthought/Canopy_64bit/User/bin/activate' ``` Delete everything added by the Canopy installer and press ^O to save and then ^X to close. Restart terminal and it should use the built-in python compiler. Another solution I found was to re-install Canopy and then go to Preferences and unselect Canopy as the default python compiler.
21,717,995
How can i set the python on my mac back to the default reference location? When I to do ``` sudo easy_install virtualenv ``` I get the following results ``` dyld: Library not loaded: @rpath/Python Referenced from: /Users/a1ctesta/Library/Enthought/Canopy_64bit/User/bin/python Reason: image not found ``` I do not have Canopy installed any longer so I wanted to restore this back to the original reference that came on the computer.
2014/02/12
[ "https://Stackoverflow.com/questions/21717995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3221720/" ]
Make sure > > /usr/bin > > > precedes > > /Users/a1ctesta/Library/Enthought/Canopy\_64bit/User/bin/python > > > To do that: 1. In the terminal, > > export PATH > =/usr/bin:/Users/a1ctesta/Library/Enthought/Canopy\_64bit/User/bin/python > > > 2. Verify this using, > > echo $PATH > > >
I had the same issue. It was easiest to reinstall Canopy. From the Canopy preferences menu, Unset Canopy as your default Python. Then restart your computer. <https://support.enthought.com/hc/en-us/articles/204469700-Uninstalling-and-resetting-Canopy>
21,717,995
How can i set the python on my mac back to the default reference location? When I to do ``` sudo easy_install virtualenv ``` I get the following results ``` dyld: Library not loaded: @rpath/Python Referenced from: /Users/a1ctesta/Library/Enthought/Canopy_64bit/User/bin/python Reason: image not found ``` I do not have Canopy installed any longer so I wanted to restore this back to the original reference that came on the computer.
2014/02/12
[ "https://Stackoverflow.com/questions/21717995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3221720/" ]
Make sure > > /usr/bin > > > precedes > > /Users/a1ctesta/Library/Enthought/Canopy\_64bit/User/bin/python > > > To do that: 1. In the terminal, > > export PATH > =/usr/bin:/Users/a1ctesta/Library/Enthought/Canopy\_64bit/User/bin/python > > > 2. Verify this using, > > echo $PATH > > >
I had this issue as well. If you edit your ~/.bash\_profile it will permanently fix the issue. In terminal enter ``` nano ~/.bash_profile ``` It will then show something along the lines of ``` # Setting PATH for Python 2.7 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}" export PATH # Added by Canopy installer on 2017-03-28 # VIRTUAL_ENV_DISABLE_PROMPT can be set to '' to make the bash prompt show that Canopy is active, otherwise 1 alias activate_canopy="source '/Users/chrisdunstan/Library/Enthought/Canopy_64bit/User/bin/activate'" VIRTUAL_ENV_DISABLE_PROMPT=1 source '/Users/chrisdunstan/Library/Enthought/Canopy_64bit/User/bin/activate' ``` Delete everything added by the Canopy installer and press ^O to save and then ^X to close. Restart terminal and it should use the built-in python compiler. Another solution I found was to re-install Canopy and then go to Preferences and unselect Canopy as the default python compiler.
73,409,909
No matter what I install, it's either opencv-python, opencv-contrib-python or both at the same time, I keep getting the "No module named 'cv2'" error. I couldn't find an answer here. Some say that only opencv-python works, others say opencv-contrib-python works. I tried everything but nothing seems to work. I'm trying to use the aruco function and I know it belongs to the contrib module. Any tip? Thanks
2022/08/18
[ "https://Stackoverflow.com/questions/73409909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11672955/" ]
You need update your EAS to 0.60.0 npm install -g eas-cli I had the same problem. Work for me, friend
We fixed this issue by next steps 1: Upgrade your eas-cli running: `npm install -g eas-cli` 2: If you're publishing by first time your app, you need request access in to your App Store Connet, by this link, <https://appstoreconnect.apple.com/access/api> ``` Select Users and Access, and then select the API Keys tab. ``` Then, click in "Request access" blue button, and then, your api keys generated will appear there. Then download any key, open whit text editor and paste the path of file in eas terminal, by selecting "[Enter an App Specific Password]" Important: Is not necessary creare a new key if you has already downloaded your key We hope this works for you. And that's it.
73,409,909
No matter what I install, it's either opencv-python, opencv-contrib-python or both at the same time, I keep getting the "No module named 'cv2'" error. I couldn't find an answer here. Some say that only opencv-python works, others say opencv-contrib-python works. I tried everything but nothing seems to work. I'm trying to use the aruco function and I know it belongs to the contrib module. Any tip? Thanks
2022/08/18
[ "https://Stackoverflow.com/questions/73409909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11672955/" ]
You need update your EAS to 0.60.0 npm install -g eas-cli I had the same problem. Work for me, friend
There is a bug in Apple's infrastructure that does not propagate newly created objects for a long time (up to 14 seconds in my experiments). Apple responds saying the resource does not exist when the cli tries to download the key and it hasn't fully propagated. I just released a fix in `eas-cli` to retry in this scenario, it should be available in v1.1.1.
73,409,909
No matter what I install, it's either opencv-python, opencv-contrib-python or both at the same time, I keep getting the "No module named 'cv2'" error. I couldn't find an answer here. Some say that only opencv-python works, others say opencv-contrib-python works. I tried everything but nothing seems to work. I'm trying to use the aruco function and I know it belongs to the contrib module. Any tip? Thanks
2022/08/18
[ "https://Stackoverflow.com/questions/73409909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11672955/" ]
We fixed this issue by next steps 1: Upgrade your eas-cli running: `npm install -g eas-cli` 2: If you're publishing by first time your app, you need request access in to your App Store Connet, by this link, <https://appstoreconnect.apple.com/access/api> ``` Select Users and Access, and then select the API Keys tab. ``` Then, click in "Request access" blue button, and then, your api keys generated will appear there. Then download any key, open whit text editor and paste the path of file in eas terminal, by selecting "[Enter an App Specific Password]" Important: Is not necessary creare a new key if you has already downloaded your key We hope this works for you. And that's it.
There is a bug in Apple's infrastructure that does not propagate newly created objects for a long time (up to 14 seconds in my experiments). Apple responds saying the resource does not exist when the cli tries to download the key and it hasn't fully propagated. I just released a fix in `eas-cli` to retry in this scenario, it should be available in v1.1.1.
66,937,068
**Please help me fix my regex :).** Summary: How can I make a repeating group (tags) match greedily even if it means a preceding optional group (a label) is empty. For some reason, my regex is not acting as desired: ``` code: re.match("^foo(-.*?)?((?:-(?:a|b))*)$", "foo-a-b").groups() output: ('-a', '-b') expected: ('', '-a-b') # since "-a" and "-b" are both tags that should be greedily matched by the last pattern ``` Examples of expected behavior: | Input | Expected | Current Output | Notes | | --- | --- | --- | --- | | foo-a-b | ('', '-a-b') | ('-a', '-b') | everything after "foo" is a tag, so label should be empty | | foo-b-a | ('', '-b-a') | ('-b', '-a') | everything after "foo" is a tag, so label should be empty | | foo-c-a-b | ('-c', '-a-b') | as expected | has both a label and a tag | | foo-a-b-c | ('-a-b-c', '') | as expected | everything is a label because tags can only be at the end | My real-life problem has a much more complicated definition of tags, labels, and "foo", but the issue is reproducible even with this smaller contrived example. Ideally, I'd also prefer to avoid having to repeat the "a|b" part of the regex, since in my real system it is actually a really long and complex pattern. If repeating that part of the regex is unavoidable, that's okay though! Repeating it within a negative look-behind also throws an error because of variable-length strings: ``` r_tags_nonames = re.sub("\(\?P<.+?>", "(?:", r_tags) re.match(r_tags, example).groups() ``` ``` Traceback (most recent call last): File "foo.py", line 210, in <module> _main() File "foo.py", line 119, in _main format, match = firstMatch(fileRoot) File "foo.py", line 90, in firstMatch match = re.fullmatch(regex, path, flags=re.IGNORECASE) ... File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/sre_compile.py", line 182, in _compile raise error("look-behind requires fixed-width pattern") re.error: look-behind requires fixed-width pattern ``` An example of a more complex version of this where repeating is problematic (because of renaming) – imagine dozens of such tags where the tags themselves also have subtags with names and their own regexes: ``` "^foo(-.*?)?((?:-(?:(?P<tag1>hello)|(?P<tag2>world)))*)$" ``` Thanks in advance!
2021/04/04
[ "https://Stackoverflow.com/questions/66937068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4089332/" ]
This boils down to stylistic preferences. I personally don't have qualms with having some of the attributes defined outside of `__init__(...)`, and so would opt for something like: ``` class TriangleData(): def __init__(self, contour_data: np.ndarray): self.get_triangle_data(contour_data) def get_triangle_data(self, contour_data): # calculations self.vertices = vertices_final self.triangle_area = triangle_area self.contours = contours ``` and disable any linter warnings that didn't like it. You could also opt for something like: ``` class TriangleData(): def __init__(self, contour_data: np.ndarray): self.vertices, self.triangle_area, self.contours = self.get_triangle_data(contour_data) def get_triangle_data(self, contour_data): # calculations return vertices_final, triangle_area, contours ``` which I think should satify the linter as-is.
There is a wide spectrum of approaches and libraries to eliminate redundancy of a plain `__init__()`. Please take a look at the [dataclasses](https://docs.python.org/3/library/dataclasses.html), [attrs](https://www.attrs.org/en/stable/), [NamedTuple](https://docs.python.org/3/library/typing.html#typing.NamedTuple) and [Pydantic](https://pydantic-docs.helpmanual.io/). --- UPD: I'm agree with Randy: there's nothing wrong about setting attributes outside of `__init__`. Beside of that, you could update instance dict directly. This would be better in case when the final set of fields should be computed dynamically. ```py class TriangleData(): def __init__(self, contour_data: np.ndarray): self.contour_data = contour_data data = self.get_triangle_data() # That's strange, that you return that field from `get` method # with different name, than you need to bind. Could we avoid that? # data['poly_dp_contours'] = data.pop('contorous') self.set_triangle_data(**data) def set_triangle_data(self, vertices, triangle, contorous): self.vertices = vertices self.triangle = triangle self.contorous = contorous # or even like below def set_triangle_data(self, **data): valid_keys = ['vertices', 'triangle', 'contorous', <...>] vars(self).update({k: data[k] for k in valid_keys if k in data}) def get_triangle_data(self): # Run calculations from original contour dataetc etc ..... return { self.vertices_key: vertices_final, self.triangle_area_key: triangle_area, self.contours_key: contours, } ```
66,937,068
**Please help me fix my regex :).** Summary: How can I make a repeating group (tags) match greedily even if it means a preceding optional group (a label) is empty. For some reason, my regex is not acting as desired: ``` code: re.match("^foo(-.*?)?((?:-(?:a|b))*)$", "foo-a-b").groups() output: ('-a', '-b') expected: ('', '-a-b') # since "-a" and "-b" are both tags that should be greedily matched by the last pattern ``` Examples of expected behavior: | Input | Expected | Current Output | Notes | | --- | --- | --- | --- | | foo-a-b | ('', '-a-b') | ('-a', '-b') | everything after "foo" is a tag, so label should be empty | | foo-b-a | ('', '-b-a') | ('-b', '-a') | everything after "foo" is a tag, so label should be empty | | foo-c-a-b | ('-c', '-a-b') | as expected | has both a label and a tag | | foo-a-b-c | ('-a-b-c', '') | as expected | everything is a label because tags can only be at the end | My real-life problem has a much more complicated definition of tags, labels, and "foo", but the issue is reproducible even with this smaller contrived example. Ideally, I'd also prefer to avoid having to repeat the "a|b" part of the regex, since in my real system it is actually a really long and complex pattern. If repeating that part of the regex is unavoidable, that's okay though! Repeating it within a negative look-behind also throws an error because of variable-length strings: ``` r_tags_nonames = re.sub("\(\?P<.+?>", "(?:", r_tags) re.match(r_tags, example).groups() ``` ``` Traceback (most recent call last): File "foo.py", line 210, in <module> _main() File "foo.py", line 119, in _main format, match = firstMatch(fileRoot) File "foo.py", line 90, in firstMatch match = re.fullmatch(regex, path, flags=re.IGNORECASE) ... File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/sre_compile.py", line 182, in _compile raise error("look-behind requires fixed-width pattern") re.error: look-behind requires fixed-width pattern ``` An example of a more complex version of this where repeating is problematic (because of renaming) – imagine dozens of such tags where the tags themselves also have subtags with names and their own regexes: ``` "^foo(-.*?)?((?:-(?:(?P<tag1>hello)|(?P<tag2>world)))*)$" ``` Thanks in advance!
2021/04/04
[ "https://Stackoverflow.com/questions/66937068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4089332/" ]
There is a wide spectrum of approaches and libraries to eliminate redundancy of a plain `__init__()`. Please take a look at the [dataclasses](https://docs.python.org/3/library/dataclasses.html), [attrs](https://www.attrs.org/en/stable/), [NamedTuple](https://docs.python.org/3/library/typing.html#typing.NamedTuple) and [Pydantic](https://pydantic-docs.helpmanual.io/). --- UPD: I'm agree with Randy: there's nothing wrong about setting attributes outside of `__init__`. Beside of that, you could update instance dict directly. This would be better in case when the final set of fields should be computed dynamically. ```py class TriangleData(): def __init__(self, contour_data: np.ndarray): self.contour_data = contour_data data = self.get_triangle_data() # That's strange, that you return that field from `get` method # with different name, than you need to bind. Could we avoid that? # data['poly_dp_contours'] = data.pop('contorous') self.set_triangle_data(**data) def set_triangle_data(self, vertices, triangle, contorous): self.vertices = vertices self.triangle = triangle self.contorous = contorous # or even like below def set_triangle_data(self, **data): valid_keys = ['vertices', 'triangle', 'contorous', <...>] vars(self).update({k: data[k] for k in valid_keys if k in data}) def get_triangle_data(self): # Run calculations from original contour dataetc etc ..... return { self.vertices_key: vertices_final, self.triangle_area_key: triangle_area, self.contours_key: contours, } ```
To follow the pattern of setting/initializing variables in the constructor, from [Instance variables in methods outside the constructor (Python) -- why and how?](https://stackoverflow.com/questions/38377276/instance-variables-in-methods-outside-the-constructor-python-why-and-how/38378757#38378757) (see answer from BrianOakley and others) You can declare your object members as follows, and them set them in a method afterwards. ``` def __init__(self, contour_data: np.ndarray): self.contour_data = contour_data self.vertices: np.ndarray = np.asarray([]) self.triangle_area: float = float() self.contour_final: np.ndarray = np.asarray([]) self.set_triangle_data() def set_triangle_data(self): # Run calculations from original contour data etc ..... self.vertices = vertices_final, self.triangle_area = triangle_area self.contour_final = contours ```
66,937,068
**Please help me fix my regex :).** Summary: How can I make a repeating group (tags) match greedily even if it means a preceding optional group (a label) is empty. For some reason, my regex is not acting as desired: ``` code: re.match("^foo(-.*?)?((?:-(?:a|b))*)$", "foo-a-b").groups() output: ('-a', '-b') expected: ('', '-a-b') # since "-a" and "-b" are both tags that should be greedily matched by the last pattern ``` Examples of expected behavior: | Input | Expected | Current Output | Notes | | --- | --- | --- | --- | | foo-a-b | ('', '-a-b') | ('-a', '-b') | everything after "foo" is a tag, so label should be empty | | foo-b-a | ('', '-b-a') | ('-b', '-a') | everything after "foo" is a tag, so label should be empty | | foo-c-a-b | ('-c', '-a-b') | as expected | has both a label and a tag | | foo-a-b-c | ('-a-b-c', '') | as expected | everything is a label because tags can only be at the end | My real-life problem has a much more complicated definition of tags, labels, and "foo", but the issue is reproducible even with this smaller contrived example. Ideally, I'd also prefer to avoid having to repeat the "a|b" part of the regex, since in my real system it is actually a really long and complex pattern. If repeating that part of the regex is unavoidable, that's okay though! Repeating it within a negative look-behind also throws an error because of variable-length strings: ``` r_tags_nonames = re.sub("\(\?P<.+?>", "(?:", r_tags) re.match(r_tags, example).groups() ``` ``` Traceback (most recent call last): File "foo.py", line 210, in <module> _main() File "foo.py", line 119, in _main format, match = firstMatch(fileRoot) File "foo.py", line 90, in firstMatch match = re.fullmatch(regex, path, flags=re.IGNORECASE) ... File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/sre_compile.py", line 182, in _compile raise error("look-behind requires fixed-width pattern") re.error: look-behind requires fixed-width pattern ``` An example of a more complex version of this where repeating is problematic (because of renaming) – imagine dozens of such tags where the tags themselves also have subtags with names and their own regexes: ``` "^foo(-.*?)?((?:-(?:(?P<tag1>hello)|(?P<tag2>world)))*)$" ``` Thanks in advance!
2021/04/04
[ "https://Stackoverflow.com/questions/66937068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4089332/" ]
This boils down to stylistic preferences. I personally don't have qualms with having some of the attributes defined outside of `__init__(...)`, and so would opt for something like: ``` class TriangleData(): def __init__(self, contour_data: np.ndarray): self.get_triangle_data(contour_data) def get_triangle_data(self, contour_data): # calculations self.vertices = vertices_final self.triangle_area = triangle_area self.contours = contours ``` and disable any linter warnings that didn't like it. You could also opt for something like: ``` class TriangleData(): def __init__(self, contour_data: np.ndarray): self.vertices, self.triangle_area, self.contours = self.get_triangle_data(contour_data) def get_triangle_data(self, contour_data): # calculations return vertices_final, triangle_area, contours ``` which I think should satify the linter as-is.
To follow the pattern of setting/initializing variables in the constructor, from [Instance variables in methods outside the constructor (Python) -- why and how?](https://stackoverflow.com/questions/38377276/instance-variables-in-methods-outside-the-constructor-python-why-and-how/38378757#38378757) (see answer from BrianOakley and others) You can declare your object members as follows, and them set them in a method afterwards. ``` def __init__(self, contour_data: np.ndarray): self.contour_data = contour_data self.vertices: np.ndarray = np.asarray([]) self.triangle_area: float = float() self.contour_final: np.ndarray = np.asarray([]) self.set_triangle_data() def set_triangle_data(self): # Run calculations from original contour data etc ..... self.vertices = vertices_final, self.triangle_area = triangle_area self.contour_final = contours ```
1,038,907
> > **Possible Duplicate:** > > [Suggestions for a Cron like scheduler in Python?](https://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python) > > > What would be the most pythonic way to schedule a function to run periodically as a background task? There are some ideas [here](http://code.activestate.com/recipes/65222/), but they all seem rather ugly to me. And incomplete. The java [Timer](http://java.sun.com/javase/6/docs/api/java/util/Timer.html) class has a very complete solution. Anyone know of a similar python class?
2009/06/24
[ "https://Stackoverflow.com/questions/1038907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581/" ]
There is a handy event scheduler that might do what you need. Here's a link to the documentation: <http://docs.python.org/library/sched.html>
Many programmers try to avoid multi-threaded code, since it is highly bug-prone in imperative programming. If you want to a scheduled task in a single-threaded environment, then you probably need some kind of "[Reactor](http://en.wikipedia.org/wiki/Reactor_pattern)". You may want to use a ready-made one like [Twisted](http://twistedmatrix.com/trac/)'s. Then it would be a basic function provided by your reactor, for example (with pygame): > > pygame.time.set\_timer - repeatedly create an event on the event queue > > >
1,038,907
> > **Possible Duplicate:** > > [Suggestions for a Cron like scheduler in Python?](https://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python) > > > What would be the most pythonic way to schedule a function to run periodically as a background task? There are some ideas [here](http://code.activestate.com/recipes/65222/), but they all seem rather ugly to me. And incomplete. The java [Timer](http://java.sun.com/javase/6/docs/api/java/util/Timer.html) class has a very complete solution. Anyone know of a similar python class?
2009/06/24
[ "https://Stackoverflow.com/questions/1038907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581/" ]
There is a handy event scheduler that might do what you need. Here's a link to the documentation: <http://docs.python.org/library/sched.html>
Python has a Timer class in threading module but that is one-shot timer, so you would be better doing something as you have seen links. <http://code.activestate.com/recipes/65222/> Why do you think that is ugly, once you have written such a class usage will be as simple as in java. if you are using it inside some GUI e.g. wxPython than it has wx.Timer which you can directly use
1,038,907
> > **Possible Duplicate:** > > [Suggestions for a Cron like scheduler in Python?](https://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python) > > > What would be the most pythonic way to schedule a function to run periodically as a background task? There are some ideas [here](http://code.activestate.com/recipes/65222/), but they all seem rather ugly to me. And incomplete. The java [Timer](http://java.sun.com/javase/6/docs/api/java/util/Timer.html) class has a very complete solution. Anyone know of a similar python class?
2009/06/24
[ "https://Stackoverflow.com/questions/1038907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581/" ]
There is a handy event scheduler that might do what you need. Here's a link to the documentation: <http://docs.python.org/library/sched.html>
Not direct response to the question. On Linux/Unix operating system there are few ways to do so and usually I just write my program / script normally and then add it to cron or something similar (like [launchd](http://nb.nathanamy.org/2012/07/schedule-jobs-using-launchd/) on OS X) Response to the question starts here. Use standard python sched module - [standard library documentation](http://docs.python.org/library/sched.html) describes some nifty solutions.
1,038,907
> > **Possible Duplicate:** > > [Suggestions for a Cron like scheduler in Python?](https://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python) > > > What would be the most pythonic way to schedule a function to run periodically as a background task? There are some ideas [here](http://code.activestate.com/recipes/65222/), but they all seem rather ugly to me. And incomplete. The java [Timer](http://java.sun.com/javase/6/docs/api/java/util/Timer.html) class has a very complete solution. Anyone know of a similar python class?
2009/06/24
[ "https://Stackoverflow.com/questions/1038907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581/" ]
There is a handy event scheduler that might do what you need. Here's a link to the documentation: <http://docs.python.org/library/sched.html>
try the [multiprocessing](http://docs.python.org/library/multiprocessing.html) module. ``` from multiprocessing import Process import time def doWork(): while True: print "working...." time.sleep(10) if __name__ == "__main__": p = Process(target=doWork) p.start() while True: time.sleep(60) ```
1,038,907
> > **Possible Duplicate:** > > [Suggestions for a Cron like scheduler in Python?](https://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python) > > > What would be the most pythonic way to schedule a function to run periodically as a background task? There are some ideas [here](http://code.activestate.com/recipes/65222/), but they all seem rather ugly to me. And incomplete. The java [Timer](http://java.sun.com/javase/6/docs/api/java/util/Timer.html) class has a very complete solution. Anyone know of a similar python class?
2009/06/24
[ "https://Stackoverflow.com/questions/1038907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581/" ]
Many programmers try to avoid multi-threaded code, since it is highly bug-prone in imperative programming. If you want to a scheduled task in a single-threaded environment, then you probably need some kind of "[Reactor](http://en.wikipedia.org/wiki/Reactor_pattern)". You may want to use a ready-made one like [Twisted](http://twistedmatrix.com/trac/)'s. Then it would be a basic function provided by your reactor, for example (with pygame): > > pygame.time.set\_timer - repeatedly create an event on the event queue > > >
Python has a Timer class in threading module but that is one-shot timer, so you would be better doing something as you have seen links. <http://code.activestate.com/recipes/65222/> Why do you think that is ugly, once you have written such a class usage will be as simple as in java. if you are using it inside some GUI e.g. wxPython than it has wx.Timer which you can directly use
1,038,907
> > **Possible Duplicate:** > > [Suggestions for a Cron like scheduler in Python?](https://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python) > > > What would be the most pythonic way to schedule a function to run periodically as a background task? There are some ideas [here](http://code.activestate.com/recipes/65222/), but they all seem rather ugly to me. And incomplete. The java [Timer](http://java.sun.com/javase/6/docs/api/java/util/Timer.html) class has a very complete solution. Anyone know of a similar python class?
2009/06/24
[ "https://Stackoverflow.com/questions/1038907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581/" ]
Not direct response to the question. On Linux/Unix operating system there are few ways to do so and usually I just write my program / script normally and then add it to cron or something similar (like [launchd](http://nb.nathanamy.org/2012/07/schedule-jobs-using-launchd/) on OS X) Response to the question starts here. Use standard python sched module - [standard library documentation](http://docs.python.org/library/sched.html) describes some nifty solutions.
Python has a Timer class in threading module but that is one-shot timer, so you would be better doing something as you have seen links. <http://code.activestate.com/recipes/65222/> Why do you think that is ugly, once you have written such a class usage will be as simple as in java. if you are using it inside some GUI e.g. wxPython than it has wx.Timer which you can directly use
1,038,907
> > **Possible Duplicate:** > > [Suggestions for a Cron like scheduler in Python?](https://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python) > > > What would be the most pythonic way to schedule a function to run periodically as a background task? There are some ideas [here](http://code.activestate.com/recipes/65222/), but they all seem rather ugly to me. And incomplete. The java [Timer](http://java.sun.com/javase/6/docs/api/java/util/Timer.html) class has a very complete solution. Anyone know of a similar python class?
2009/06/24
[ "https://Stackoverflow.com/questions/1038907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581/" ]
try the [multiprocessing](http://docs.python.org/library/multiprocessing.html) module. ``` from multiprocessing import Process import time def doWork(): while True: print "working...." time.sleep(10) if __name__ == "__main__": p = Process(target=doWork) p.start() while True: time.sleep(60) ```
Python has a Timer class in threading module but that is one-shot timer, so you would be better doing something as you have seen links. <http://code.activestate.com/recipes/65222/> Why do you think that is ugly, once you have written such a class usage will be as simple as in java. if you are using it inside some GUI e.g. wxPython than it has wx.Timer which you can directly use
48,075,739
django version: 1.11, python version: 3.6.3 I found this stackoverflow question: [Unit Testing a Django Form with a FileField](https://stackoverflow.com/questions/2473392/unit-testing-a-django-form-with-a-filefield) and I like how there isn't an actual image/external file used for the unittest; however I tried these approaches: ``` from django.test import TestCase from io import BytesIO from PIL import Image from my_app.forms import MyForm from django.core.files.uploadedfile import InMemoryUploadedFile class MyModelTest(TestCase): def test_valid_form_data(self): im_io = BytesIO() # BytesIO has to be used, StrinIO isn't working im = Image.new(mode='RGB', size=(200, 200)) im.save(im_io, 'JPEG') form_data = { 'some_field': 'some_data' } image_data = { InMemoryUploadedFile(im_io, None, 'random.jpg', 'image/jpeg', len(im_io.getvalue()), None) } form = MyForm(data=form_data, files=image_data) self.assertTrue(form.is_valid()) ``` however, this always results in the following error message: ``` Traceback (most recent call last): File "/home/my_user/projects/my_app/products/tests/test_forms.py", line 44, in test_valid_form_data self.assertTrue(form.is_valid()) File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 183, in is_valid return self.is_bound and not self.errors File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 175, in errors self.full_clean() File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 384, in full_clean self._clean_fields() File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 396, in _clean_fields value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/widgets.py", line 423, in value_from_datadict upload = super(ClearableFileInput, self).value_from_datadict(data, files, name) File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/widgets.py", line 367, in value_from_datadict return files.get(name) AttributeError: 'set' object has no attribute 'get' ``` Why? I understand that `.get()` is a dictionary method, but I fail to see where it created a set.
2018/01/03
[ "https://Stackoverflow.com/questions/48075739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3329127/" ]
`image_data` should be dict, without providing key `{value}` will create set object. You need to define it like this `{key: value}`. Fix to this: ``` image_data = { 'image_field': InMemoryUploadedFile(im_io, None, 'random.jpg', 'image/jpeg', len(im_io.getvalue()), None) } ```
Without External File Code ``` from django.core.files.uploadedfile import SimpleUploadedFile testfile = ( b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04' b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02' b'\x02\x4c\x01\x00\x3b') avatar = SimpleUploadedFile('small.gif', testfile, content_type='image/gif') ```
3,319,788
I am trying to retrieve data in a sybase data base from python and I was wondering which would be the best way to do it. I found this module but may be you have some other suggestions: <http://python-sybase.sourceforge.net/> Thanks
2010/07/23
[ "https://Stackoverflow.com/questions/3319788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/400413/" ]
The sybase module you linked is by far the easiest way. You can get data like so: ``` import Sybase db = Sybase.connect('server','name','pass','database') c = db.cursor() c.execute("sql statement") list1 = c.fetchall() print list1 ``` You will have to use something like freetds to setup the interfaces for sybase, however.
you can also connect through [ODBC](http://tinyurl.com/255plm2).
3,319,788
I am trying to retrieve data in a sybase data base from python and I was wondering which would be the best way to do it. I found this module but may be you have some other suggestions: <http://python-sybase.sourceforge.net/> Thanks
2010/07/23
[ "https://Stackoverflow.com/questions/3319788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/400413/" ]
The sybase module you linked is by far the easiest way. You can get data like so: ``` import Sybase db = Sybase.connect('server','name','pass','database') c = db.cursor() c.execute("sql statement") list1 = c.fetchall() print list1 ``` You will have to use something like freetds to setup the interfaces for sybase, however.
There is also `python-pymssql` which is in Debian / Ubuntu. This can connect to MS-SQL-Server or Sybase using freetds. I'm not sure how it compares to the other options. <http://www.pymssql.org/> Example code, abridged from their website: ``` import pymssql conn = pymssql.connect('server','user','pass','database') cursor = conn.cursor() cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe') row = cursor.fetchone() while row: print("ID=%d, Name=%s" % (row[0], row[1])) row = cursor.fetchone() conn.close() ```
28,724,785
I am currently working on a project that makes use of Python 3.2.3 and thought to do some tests of my code in IPython but it seems that IPython does not support the version of python I am using. I get the following ImportError when trying to run Ipython on my Ubuntu machine. ``` ImportError: IPython requires Python version 2.7 or 3.3 or above. ```
2015/02/25
[ "https://Stackoverflow.com/questions/28724785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3166105/" ]
You can find some discussion about dropping 2.6 and 3.2 support [here](https://github.com/ipython/ipython/pull/4002). One of the main reasons was that 3.2 does not support 2.x-style unicode strings - `u"I love IPython!"`, while 3.3 and above do. This change made it possible to support 2.7 and 3.3+ in a single codebase.
[Quickstart](http://ipython.org/ipython-doc/2/install/install.html): IPython requires Python 2.7 or ≥ 3.3. If you need to use Python 2.6 or 3.2, you can find IPython 1.0 [here](http://archive.ipython.org/release/). PS: The deadsnakes PPA has packages for old and new python versions: ``` sudo apt-get install python-software-properties sudo add-apt-repository ppa:fkrull/deadsnakes sudo apt-get update sudo apt-get install python3.3 ```
68,081,171
This is a problem of the missing number in python. ``` class Missing: n = int(input()) arr = list(map(int,input().split(" "))) def __init__(self,arr,n): self.arr = arr self.n = n def MissingNumber(self): self.res = self.n*(self.n+1)/2 self.sum_array = sum(self.arr) return "Missing no. is ",self.res-self.sum_array Obj = Missing() Obj.MissingNumber() ``` I am getting this error. can anybody solve it? ``` Obj = Missing() TypeError: __init__() missing 2 required positional arguments: 'arr' and 'n' ```
2021/06/22
[ "https://Stackoverflow.com/questions/68081171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14643490/" ]
you need put the input outside class,and assign it when you create instance by `Obj = Missing(arr,n)` code: ``` class Missing: def __init__(self,arr,n): self.arr = arr self.n = n def MissingNumber(self): self.res = self.n*(self.n+1)/2 self.sum_array = sum(self.arr) return "Missing no. is ",self.res-self.sum_array n = int(input()) arr = list(map(int,input().split(" "))) Obj = Missing(arr,n) print(Obj.MissingNumber()) ``` result: ``` 5 1 2 3 4 5 ('Missing no. is ', 0.0) ```
your constructor need two parameter. You need to assign it before it run. you need to assign n and arr outside class object ``` class Missing: def __init__(self,arr,n): self.arr = arr self.n = n def MissingNumber(self): self.res = self.n*(self.n+1)/2 self.sum_array = sum(self.arr) return "Missing no. is ",self.res-self.sum_array if __name__ == '__main__': n = int(input()) arr = list(map(int,input().split(" "))) Obj = Missing(n,arr) Obj.MissingNumber() ```
6,715,486
So I am fairly new to python. But would like your help solving this minor issue I having removing similar duplicates out of a list. So I have a list of urls: `myList = ['http://www.mywebsite.com/shoes', 'http://wwww.yourwebsite.com/', 'http://www.mywebsite.com/shoes/']` I want to remove similar url's as you can see <http://www.mywebsite.com/shoes> and <http://www.mywebsite.com/shoes/> are pretty much the same. I would like to remove one of them (I don't care which one) But keep the other. Essentially removing the duplicate from the list. I would give an example. But I don't even know where to begin. Any insight would great help.
2011/07/16
[ "https://Stackoverflow.com/questions/6715486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/841342/" ]
If similarity for you is difference in '\' thab you can use sets[(read tutorial here)](http://docs.python.org/tutorial/datastructures.html#sets) [and here](http://docs.python.org/library/stdtypes.html?highlight=frozenset#set-types-set-frozenset) to remove duplicates from your list since: > > A set object is an unordered collection of distinct hashable objects. > Common uses include membership testing, removing duplicates from a > sequence, and computing mathematical operations such as intersection, > union, difference, and symmetric difference. > > > ``` myList = ['http://www.mywebsite.com/shoes', 'http://wwww.yourwebsite.com/', 'http://www.mywebsite.com/shoes/'] set(x.lstrip('\') for x in myList) # will return a set of unique urls # In case you need list myList = list(set(x.rstrip('\') for x in myList)) ```
The issue may be that you haven't figured out exactly what it means for two URLs to be similar. We can't help you with that because only you know what your requirements are. Once you do figure that out, though, the rest is simple enough. There are two ways to do it: * If your similarity relation is transitive - that is, if `similar(a,b) and similar(b,c)` implies that `similar(a,c)` for all URLs `a`, `b`, `c` - then it will be possible to convert each URL to a canonical form. Two URLs will be similar if and only if their canonical forms are equal. So the easiest thing to do in that case is to convert each URL to canonical form, then create a set out of the canonical URLs obtained in this way: ``` set(canonical(u) for u in myList) ``` * If your similarity relation is not transitive, then things get really tricky because you can have cases like A being similar to B and B being similar to C, but A is not similar to C. So then the question becomes, in this example, what would you like to include in your list with duplicates stripped? Would you include A and C because they are not similar to each other, or would you include only B because you'd consider both A and C similar duplicates of it? In this case, depending on how you want to handle "fuzzy" cases like this, there are various algorithms you can use - but again, we'd need to know your exact requirements to recommend anything.
6,715,486
So I am fairly new to python. But would like your help solving this minor issue I having removing similar duplicates out of a list. So I have a list of urls: `myList = ['http://www.mywebsite.com/shoes', 'http://wwww.yourwebsite.com/', 'http://www.mywebsite.com/shoes/']` I want to remove similar url's as you can see <http://www.mywebsite.com/shoes> and <http://www.mywebsite.com/shoes/> are pretty much the same. I would like to remove one of them (I don't care which one) But keep the other. Essentially removing the duplicate from the list. I would give an example. But I don't even know where to begin. Any insight would great help.
2011/07/16
[ "https://Stackoverflow.com/questions/6715486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/841342/" ]
You could do: 1. First, remove last slash 2. List item Remove duplicates: ``` set(map(lambda url: url.rstrip('/'), myList)) ```
The issue may be that you haven't figured out exactly what it means for two URLs to be similar. We can't help you with that because only you know what your requirements are. Once you do figure that out, though, the rest is simple enough. There are two ways to do it: * If your similarity relation is transitive - that is, if `similar(a,b) and similar(b,c)` implies that `similar(a,c)` for all URLs `a`, `b`, `c` - then it will be possible to convert each URL to a canonical form. Two URLs will be similar if and only if their canonical forms are equal. So the easiest thing to do in that case is to convert each URL to canonical form, then create a set out of the canonical URLs obtained in this way: ``` set(canonical(u) for u in myList) ``` * If your similarity relation is not transitive, then things get really tricky because you can have cases like A being similar to B and B being similar to C, but A is not similar to C. So then the question becomes, in this example, what would you like to include in your list with duplicates stripped? Would you include A and C because they are not similar to each other, or would you include only B because you'd consider both A and C similar duplicates of it? In this case, depending on how you want to handle "fuzzy" cases like this, there are various algorithms you can use - but again, we'd need to know your exact requirements to recommend anything.
15,848,156
I use the package named python-snappy. This package requires [snappy](https://code.google.com/p/snappy/) library. So, I download and install snappy successfully by the following commands such as: ``` ./configure make sudo make install ``` When I import snappy, I receive the errors: ``` from _snappy import CompressError, CompressedLengthError, \ ImportError: libsnappy.so.1 cannot open shared object file: No such file or directory ``` I'm using Python 2.7, snappy, python-snappy and Ubuntu 12.04 How can I fix this problem? Thanks
2013/04/06
[ "https://Stackoverflow.com/questions/15848156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875781/" ]
Traditionally you might have to run the `ldconfig` utility to update your */etc/ld.so.cache* (or equivalent as appropriate to your OS). Sometimes it might be necessary to add new entries (paths) to your */etc/ld.so.conf*. Basically the shared object (so) loaders on many versions of Unix (and probably other Unix-like operating systems) use a cache to help resolve their base filenames into actual files to be loaded (usually *mmap()'d*). This is roughly similar to the intermittent need to run *hash -r* or *rehash* in your shell after adding things to directories in your PATH. Usually you can just run `ldconfig` with no arguments (possibly after adding your new library's path to your */etc/ld.so.conf* text file). Good *Makefiles* will do this for you during `make install`. Here's a little bit more info: <http://linux.101hacks.com/unix/ldconfig/>
You can install the [python-snappy](http://packages.ubuntu.com/precise/python-snappy) and [libsnappy1](http://packages.ubuntu.com/precise/libsnappy1) from the ubuntu repos: ``` $ sudo apt-get install libsnappy1 python-snappy ``` You should not have to download anything.
15,848,156
I use the package named python-snappy. This package requires [snappy](https://code.google.com/p/snappy/) library. So, I download and install snappy successfully by the following commands such as: ``` ./configure make sudo make install ``` When I import snappy, I receive the errors: ``` from _snappy import CompressError, CompressedLengthError, \ ImportError: libsnappy.so.1 cannot open shared object file: No such file or directory ``` I'm using Python 2.7, snappy, python-snappy and Ubuntu 12.04 How can I fix this problem? Thanks
2013/04/06
[ "https://Stackoverflow.com/questions/15848156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875781/" ]
You can install the [python-snappy](http://packages.ubuntu.com/precise/python-snappy) and [libsnappy1](http://packages.ubuntu.com/precise/libsnappy1) from the ubuntu repos: ``` $ sudo apt-get install libsnappy1 python-snappy ``` You should not have to download anything.
Here for e.g. anaconda python 1. Download snappy from [github](http://google.github.io/snappy/) 2. also download the python file 3. extract both files 4. google-snappy folder `$ ./configure` `$ make` `$ sudo make install` 5. Then in python folder: `$ python setup.py build # here I get the same import _snappy error` `$ python setup.py install # after this import works`
15,848,156
I use the package named python-snappy. This package requires [snappy](https://code.google.com/p/snappy/) library. So, I download and install snappy successfully by the following commands such as: ``` ./configure make sudo make install ``` When I import snappy, I receive the errors: ``` from _snappy import CompressError, CompressedLengthError, \ ImportError: libsnappy.so.1 cannot open shared object file: No such file or directory ``` I'm using Python 2.7, snappy, python-snappy and Ubuntu 12.04 How can I fix this problem? Thanks
2013/04/06
[ "https://Stackoverflow.com/questions/15848156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875781/" ]
You can install the [python-snappy](http://packages.ubuntu.com/precise/python-snappy) and [libsnappy1](http://packages.ubuntu.com/precise/libsnappy1) from the ubuntu repos: ``` $ sudo apt-get install libsnappy1 python-snappy ``` You should not have to download anything.
the following worked for me: ``` $ conda install python-snappy ``` then in my code I used: ``` import snappy ```
15,848,156
I use the package named python-snappy. This package requires [snappy](https://code.google.com/p/snappy/) library. So, I download and install snappy successfully by the following commands such as: ``` ./configure make sudo make install ``` When I import snappy, I receive the errors: ``` from _snappy import CompressError, CompressedLengthError, \ ImportError: libsnappy.so.1 cannot open shared object file: No such file or directory ``` I'm using Python 2.7, snappy, python-snappy and Ubuntu 12.04 How can I fix this problem? Thanks
2013/04/06
[ "https://Stackoverflow.com/questions/15848156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875781/" ]
Traditionally you might have to run the `ldconfig` utility to update your */etc/ld.so.cache* (or equivalent as appropriate to your OS). Sometimes it might be necessary to add new entries (paths) to your */etc/ld.so.conf*. Basically the shared object (so) loaders on many versions of Unix (and probably other Unix-like operating systems) use a cache to help resolve their base filenames into actual files to be loaded (usually *mmap()'d*). This is roughly similar to the intermittent need to run *hash -r* or *rehash* in your shell after adding things to directories in your PATH. Usually you can just run `ldconfig` with no arguments (possibly after adding your new library's path to your */etc/ld.so.conf* text file). Good *Makefiles* will do this for you during `make install`. Here's a little bit more info: <http://linux.101hacks.com/unix/ldconfig/>
Here for e.g. anaconda python 1. Download snappy from [github](http://google.github.io/snappy/) 2. also download the python file 3. extract both files 4. google-snappy folder `$ ./configure` `$ make` `$ sudo make install` 5. Then in python folder: `$ python setup.py build # here I get the same import _snappy error` `$ python setup.py install # after this import works`
15,848,156
I use the package named python-snappy. This package requires [snappy](https://code.google.com/p/snappy/) library. So, I download and install snappy successfully by the following commands such as: ``` ./configure make sudo make install ``` When I import snappy, I receive the errors: ``` from _snappy import CompressError, CompressedLengthError, \ ImportError: libsnappy.so.1 cannot open shared object file: No such file or directory ``` I'm using Python 2.7, snappy, python-snappy and Ubuntu 12.04 How can I fix this problem? Thanks
2013/04/06
[ "https://Stackoverflow.com/questions/15848156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875781/" ]
Traditionally you might have to run the `ldconfig` utility to update your */etc/ld.so.cache* (or equivalent as appropriate to your OS). Sometimes it might be necessary to add new entries (paths) to your */etc/ld.so.conf*. Basically the shared object (so) loaders on many versions of Unix (and probably other Unix-like operating systems) use a cache to help resolve their base filenames into actual files to be loaded (usually *mmap()'d*). This is roughly similar to the intermittent need to run *hash -r* or *rehash* in your shell after adding things to directories in your PATH. Usually you can just run `ldconfig` with no arguments (possibly after adding your new library's path to your */etc/ld.so.conf* text file). Good *Makefiles* will do this for you during `make install`. Here's a little bit more info: <http://linux.101hacks.com/unix/ldconfig/>
the following worked for me: ``` $ conda install python-snappy ``` then in my code I used: ``` import snappy ```
15,848,156
I use the package named python-snappy. This package requires [snappy](https://code.google.com/p/snappy/) library. So, I download and install snappy successfully by the following commands such as: ``` ./configure make sudo make install ``` When I import snappy, I receive the errors: ``` from _snappy import CompressError, CompressedLengthError, \ ImportError: libsnappy.so.1 cannot open shared object file: No such file or directory ``` I'm using Python 2.7, snappy, python-snappy and Ubuntu 12.04 How can I fix this problem? Thanks
2013/04/06
[ "https://Stackoverflow.com/questions/15848156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875781/" ]
the following worked for me: ``` $ conda install python-snappy ``` then in my code I used: ``` import snappy ```
Here for e.g. anaconda python 1. Download snappy from [github](http://google.github.io/snappy/) 2. also download the python file 3. extract both files 4. google-snappy folder `$ ./configure` `$ make` `$ sudo make install` 5. Then in python folder: `$ python setup.py build # here I get the same import _snappy error` `$ python setup.py install # after this import works`
59,412,006
I am new to python and having a problem: my task was `"Given a sentence, return a sentence with the words reversed"` e.g. `Tea is hot --------> hot is Tea` my code was: ``` def funct1 (x): a,b,c = x.split() return c + " "+ b + " "+ a funct1 ("I am home") ``` It did solve the answer, but i have 2 questions: 1. how to give space without adding a space concatenation 2. is there any other way to reverse than splitting? thank you.
2019/12/19
[ "https://Stackoverflow.com/questions/59412006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12565719/" ]
Your code is heavily dependent on the assumption that the string will always contain **exactly** 2 spaces. The task description you provided does not say that this will always be the case. This assumption can be eliminated by using `str.join` and `[::-1]` to reverse the list: ``` def funct1(x): return ' '.join(x.split()[::-1]) print(funct1('short example')) print(funct1('example with more than 2 spaces')) ``` Outputs ``` example short spaces 2 than more with example ``` A micro-optimization can be the use of `reversed`, so an extra list does not need to be created: ``` return ' '.join(reversed(x.split())) ``` > > 2) is there any other way to reverse than spliting? > > > Since the requirement is to reverse the order of the words while maintaining the order of letters inside each word, the answer to this question is "not really". A regex can be used, but will that be much different than splitting on a whitespace? probably not. Using `split` is probably faster anyway. ``` import re def funct1(x): return ' '.join(reversed(re.findall(r'\b(\w+)\b', x))) ```
A pythonic way to do this would be: ``` def reverse_words(sentence): return " ".join(reversed(sentence.split())) ``` To answer the subquestions: 1. Yes, use [`str.join`](https://docs.python.org/3/library/stdtypes.html#str.join). 2. Yes, you can use a [slice](https://stackoverflow.com/questions/509211/understanding-slice-notation) with a negative step `"abc"[::-1] == "cba"`. You can also use the builtin function [`reversed`](https://docs.python.org/3/library/functions.html#reversed) like I've done above (to get a reversed copy of a sequence), which is marginally more readable.
32,780,946
I have this database layout ``` class Clinic(models.Model): class Menu(models.Model): ... menu = models.OneToOneField(Clinic, related_name='menu') class Item(models.Model): ... menu = models.ForeignKey('Menu') ``` and I would like to access my Menu model and the Items linked to that menu from my Clinic model. I have tried this ``` In [5]: clinic = Clinic.objects.get(pk=1) In [12]: clinic.menu Out[12]: <Menu: Menu object> In [13]: clinic.menu.objects.all() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-13-2aff8882b6ad> in <module>() ----> 1 clinic.menu.objects.all() /Users/gabriel/.virtualenvs/meed_waps/lib/python3.4/site-packages/django/db/models/manager.py in __get__(self, instance, type) 253 def __get__(self, instance, type=None): 254 if instance is not None: --> 255 raise AttributeError("Manager isn't accessible via %s instances" % type.__name__) 256 return self.manager 257 AttributeError: Manager isn't accessible via Menu instances ``` but it tells me that the manager can't access it. Conceptually it seems like I should be able to access the items and get a list by tracing the relationship down through the clinic model like this Clinic > Menu > Items. Is there another way I should be doing this?
2015/09/25
[ "https://Stackoverflow.com/questions/32780946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3282276/" ]
`clinic.menu.objects` is the `ModelManager` for the `Menu` model - note that it's an attribute of the `Menu` *class*, not of your `clinic.menu` instance. `ModelManager` classes are used to query the underlying table, and are not supposed to be called directly from instances (which wouldn't make much sense anyway), hence the error message. > > Conceptually it seems like I should be able to access the items and get a list by tracing the relationship down through the clinic model like this Clinic > Menu > Items > > > That's indeed possible (hopefully), but where are you mentionning `items` in `clinic.menu.objects` ? You want `clinic.menu.item_set.all()`.
Try this: ``` Clinic.objects.get(pk=1).menu.item_set.all() ```
8,264,569
I've got 32 SQLite (3.7.9) databases with 3 tables each that I'm trying to merge together using the idiom that I've found elsewhere (each db has the same schema): ``` attach db1.sqlite3 as toMerge; insert into tbl1 select * from toMerge.tbl1; insert into tbl2 select * from toMerge.tbl2; insert into tbl3 select * from toMerge.tbl3; detach toMerge; ``` and rinse-repeating for the entire set of databases. I do this using python and the sqlite3 module: ``` for fn in filelist: completedb = sqlite3.connect("complete.sqlite3") c = completedb.cursor() c.execute("pragma synchronous = off;") c.execute("pragma journal_mode=off;") print("Attempting to merge " + fn + ".") query = "attach '" + fn + "' as toMerge;" c.execute(query) try: c.execute("insert into tbl1 select * from toMerge.tbl1;") c.execute("insert into tbl2 select * from toMerge.tbl2;") c.execute("insert into tbl3 select * from toMerge.tbl3;") c.execute("detach toMerge;") completedb.commit() except sqlite3.Error as err: print "Error! ", type(err), " Error msg: ", err raise ``` 2 of the tables are fairly small, only 50K rows per db, while the third (tbl3) is larger, about 850 - 900K rows. Now, what happens is that the inserts progressively slow down until I get to about the fourth database when they grind to a near halt (on the order of a a megabyte or two in file size added every 1-3 minutes to the combined database). In case it was python, I've even tried dumping out the tables as INSERTs (.insert; .out foo; sqlite3 complete.db < foo is the skeleton, found [here](https://stackoverflow.com/questions/75675/how-do-i-dump-the-data-of-some-sqlite3-tables)) and combining them in a bash script using the sqlite3 CLI to do the work directly, but I get exactly the same problem. The table setup of tbl3 isn't too demanding - a text field containing a UUID, two integers, and four real values. My worry is that it's the number of rows, because I ran into exactly the same trouble at exactly the same spot (about four databases in) when the individual databases were an order of magnitude larger in terms of file size with the same number of rows (I trimmed the contents of tbl3 significantly by storing summary stats instead of raw data). Or maybe it's the way I'm performing the operation? Can anyone shed some light on this problem that I'm having before I throw something out the window?
2011/11/25
[ "https://Stackoverflow.com/questions/8264569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126321/" ]
You can do it somewhat with HTML5's new input types See: <http://www.456bereastreet.com/archive/201004/html5_input_types/>
Using HTML5, kind of yes. Link: <http://thereforei.am/2011/07/01/css-selectors-for-html5-input-validation/>
8,264,569
I've got 32 SQLite (3.7.9) databases with 3 tables each that I'm trying to merge together using the idiom that I've found elsewhere (each db has the same schema): ``` attach db1.sqlite3 as toMerge; insert into tbl1 select * from toMerge.tbl1; insert into tbl2 select * from toMerge.tbl2; insert into tbl3 select * from toMerge.tbl3; detach toMerge; ``` and rinse-repeating for the entire set of databases. I do this using python and the sqlite3 module: ``` for fn in filelist: completedb = sqlite3.connect("complete.sqlite3") c = completedb.cursor() c.execute("pragma synchronous = off;") c.execute("pragma journal_mode=off;") print("Attempting to merge " + fn + ".") query = "attach '" + fn + "' as toMerge;" c.execute(query) try: c.execute("insert into tbl1 select * from toMerge.tbl1;") c.execute("insert into tbl2 select * from toMerge.tbl2;") c.execute("insert into tbl3 select * from toMerge.tbl3;") c.execute("detach toMerge;") completedb.commit() except sqlite3.Error as err: print "Error! ", type(err), " Error msg: ", err raise ``` 2 of the tables are fairly small, only 50K rows per db, while the third (tbl3) is larger, about 850 - 900K rows. Now, what happens is that the inserts progressively slow down until I get to about the fourth database when they grind to a near halt (on the order of a a megabyte or two in file size added every 1-3 minutes to the combined database). In case it was python, I've even tried dumping out the tables as INSERTs (.insert; .out foo; sqlite3 complete.db < foo is the skeleton, found [here](https://stackoverflow.com/questions/75675/how-do-i-dump-the-data-of-some-sqlite3-tables)) and combining them in a bash script using the sqlite3 CLI to do the work directly, but I get exactly the same problem. The table setup of tbl3 isn't too demanding - a text field containing a UUID, two integers, and four real values. My worry is that it's the number of rows, because I ran into exactly the same trouble at exactly the same spot (about four databases in) when the individual databases were an order of magnitude larger in terms of file size with the same number of rows (I trimmed the contents of tbl3 significantly by storing summary stats instead of raw data). Or maybe it's the way I'm performing the operation? Can anyone shed some light on this problem that I'm having before I throw something out the window?
2011/11/25
[ "https://Stackoverflow.com/questions/8264569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126321/" ]
Using HTML5, kind of yes. Link: <http://thereforei.am/2011/07/01/css-selectors-for-html5-input-validation/>
As others writes: Yes, with HTML5. BUT HTML5 is NOT fully supported by most browsers. So don't use this approach yet. You can't do it with CSS, you have to use JavaScript until HTML5 is fully supported. But ALWAYS remember to validate server-side as well via ASP(.NET), PHP and such.. Doing both Client-side and Server-side will ensure the safety of your site even if JS are disabled :)
8,264,569
I've got 32 SQLite (3.7.9) databases with 3 tables each that I'm trying to merge together using the idiom that I've found elsewhere (each db has the same schema): ``` attach db1.sqlite3 as toMerge; insert into tbl1 select * from toMerge.tbl1; insert into tbl2 select * from toMerge.tbl2; insert into tbl3 select * from toMerge.tbl3; detach toMerge; ``` and rinse-repeating for the entire set of databases. I do this using python and the sqlite3 module: ``` for fn in filelist: completedb = sqlite3.connect("complete.sqlite3") c = completedb.cursor() c.execute("pragma synchronous = off;") c.execute("pragma journal_mode=off;") print("Attempting to merge " + fn + ".") query = "attach '" + fn + "' as toMerge;" c.execute(query) try: c.execute("insert into tbl1 select * from toMerge.tbl1;") c.execute("insert into tbl2 select * from toMerge.tbl2;") c.execute("insert into tbl3 select * from toMerge.tbl3;") c.execute("detach toMerge;") completedb.commit() except sqlite3.Error as err: print "Error! ", type(err), " Error msg: ", err raise ``` 2 of the tables are fairly small, only 50K rows per db, while the third (tbl3) is larger, about 850 - 900K rows. Now, what happens is that the inserts progressively slow down until I get to about the fourth database when they grind to a near halt (on the order of a a megabyte or two in file size added every 1-3 minutes to the combined database). In case it was python, I've even tried dumping out the tables as INSERTs (.insert; .out foo; sqlite3 complete.db < foo is the skeleton, found [here](https://stackoverflow.com/questions/75675/how-do-i-dump-the-data-of-some-sqlite3-tables)) and combining them in a bash script using the sqlite3 CLI to do the work directly, but I get exactly the same problem. The table setup of tbl3 isn't too demanding - a text field containing a UUID, two integers, and four real values. My worry is that it's the number of rows, because I ran into exactly the same trouble at exactly the same spot (about four databases in) when the individual databases were an order of magnitude larger in terms of file size with the same number of rows (I trimmed the contents of tbl3 significantly by storing summary stats instead of raw data). Or maybe it's the way I'm performing the operation? Can anyone shed some light on this problem that I'm having before I throw something out the window?
2011/11/25
[ "https://Stackoverflow.com/questions/8264569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126321/" ]
You can do it somewhat with HTML5's new input types See: <http://www.456bereastreet.com/archive/201004/html5_input_types/>
As others writes: Yes, with HTML5. BUT HTML5 is NOT fully supported by most browsers. So don't use this approach yet. You can't do it with CSS, you have to use JavaScript until HTML5 is fully supported. But ALWAYS remember to validate server-side as well via ASP(.NET), PHP and such.. Doing both Client-side and Server-side will ensure the safety of your site even if JS are disabled :)
49,461,537
Using pycharm community python3.6.2 Django 2.0.3 views.py ``` from django.http import HttpResponse def hello_world(request): return HttpResponse('Hello World') ``` urls.py ``` from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views, hello_world), ] ``` i Tried to figure it out but missing something. error while running on pycharm > > urls.py", line 8, in > url(r'^$', views, hello\_world), > > > NameError: name 'hello\_world' is not defined > > >
2018/03/24
[ "https://Stackoverflow.com/questions/49461537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9511012/" ]
The error is telling you that there is no variable such as `hello_world` defined. You need to change it to: ``` url(r'^$', views.hello_world) ``` Where `views` is the views module that you have imported at the top.
This line of code is wrong ``` url(r'^$', views, hello_world) ``` You just imported the `view` which is the file view.py. Now you need to call the function view, which it is going to be like: ``` url(r'^$', views.hello_world) ``` And you might think it is going to be useful to give that url a name so you can use it as a reference in your templates in the future. ``` url(r'^$', views.hello_world, name='hello-world') ``` Also, you can import your view.py as follow: ``` from .views import hello_world ``` The next is possible as well as suggested in the comments Niayesh Isky, but not encouraged. ``` from .views import * ```
36,937,305
I am running a shell script in cygwin where I am using python robot framework, but in that environment it's not getting 'pybot' as command. ``` $ pybot --version ``` Result- ``` -bash: pybot: command not found ``` However in cmd prompt the above command is working fine. PS- I have already set python interpreter path in environment variable. As the same command is working fine in cmd prompt. Is there any possible way to use pybot in cygwin shell?
2016/04/29
[ "https://Stackoverflow.com/questions/36937305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4637378/" ]
I have explored and get to know that, in Cygwin we need to specify the file type as well. So, if we say- ``` pybot.bat --version ``` this should work.
worked for me in cygwin: Adjetterpc@Pompina $ robot.bat --version Robot Framework 3.0.4 (Python 2.7.13 on win32) Adjetterpc@Pompina $ pybot.bat --version Robot Framework 3.0.4 (Python 2.7.13 on win32)
62,023,199
I have a little problem on making ecounter for fast food, the problems is at continuing order. I don't know how to use True and False in python.. I choose three food as a beginner. It's end up failing.. So I tried to use True by copying other people code. at first the code was success, but when i changed a little thing in code, it went wrong and I don't know how to fix it. so far this is my code: ``` hcount = 0 scount = 0 fcount = 0 y = True n = False cstm= input("Please enter your name: ") print(" ") print(" ") print("Hi MR/MS " + cstm) print("WELCOME TO MACDUNNO ECOUNTER") print("CHOOSE YOUR FOOD") while True: print(" ") print('MENU MAC DUNNO') print("1. HAMBURGER = $1.50") print("2. SODA = $1.15") print("3. FRIES = $1.25") choice = int(input('ENTER NUMBER 1-3: ')) if choice == 1: amount = int(input("ENTER THE AMOUNT: ")) hcount += amount elif choice == 2: amount = int(input("ENTER THE AMOUNT: ")) scount += amount elif choice == 3: amount = int(input("ENTER THE AMOUNT: ")) fcount += amount countinue = input("ARE YOU STILL WANT TO ORDER? (y/n)") if countinue == n: sub = (hcount * 1.50) + (scount * 1.15) + (fcount * 1.25) tax = sub * 0.09 total = sub + tax print(" ") print(" ") print("************") print("PAYMENT") print("************") print('TOTAL HAMBURGER: {0}'.format(hcount)) print('TOTAL SODA: {0}'.format(scount)) print('TOTAL FRIES: {0}'.format(fcount)) print(" ") print('SUBTOTAL: {:0.2f}'.format(sub)) print('TAX : {:0.2f}'.format(tax)) print(" ") print("__________________________________") print('TOTAL: {:0.2f}'.format(total)) print(" ") pay =int(input("INSERT PAYMENT:")) if pay > total : exchange = pay - total print(' ') print(' ') print('EXCHANGE : {:0.2f}'.format(exchange)) print("THANK YOU, PLEASE COME AGAIN") import time time.sleep(5) else: print(' ') print(' ') print("INSUFFICIENT AMOUNT") print("PLEASE INSERT THE RIGHT AMOUNT") scpay = int(input("INSERT PAYMENT : ")) if scpay > total : exchange = scpay - total print(' ') print(' ') print('EXCHANGE : {:0.2f}'.format(exchange)) print("THANK YOU, PLEASE COME AGAIN") import time time.sleep(5) else: print(" ") print("ORDER TERMINATED") import time time.sleep(5) ```
2020/05/26
[ "https://Stackoverflow.com/questions/62023199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13620217/" ]
Query is fairly self explanatory. I have added a should clause with a match on field c and no exists check on field c. Minimum\_should\_match is set as 1. A document which matches either of clause is returned i.e either it should not exist or should match the input string ``` { "query": { "bool": { "must": [ { "match": { "a": "norm" } }, { "match_phrase": { "b": "views" } } ], "should": [ { "match": { "c": "claims" } }, { "bool": { "must_not": [ { "exists": { "field": "c" } } ] } } ], "minimum_should_match": 1 } } } ``` **Data:** ``` "hits" : [ { "_source" : { "a" : "norm", "b" : "views", "c" : "claims" } }, { "_source" : { "a" : "norm", "b" : "views" } }, { "_source" : { "a" : "norm", "b" : "views", "c" : "ddd" } } ] ``` **Result:** ``` "hits" : [ { "_source" : { "a" : "norm", "b" : "views", "c" : "claims" } }, { "_source" : { "a" : "norm", "b" : "views" } } ] ``` Document where c="claims" or c not exists is returned
Use filter and exist. [exists](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html) [filter](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html) ``` { "query": { "filtered": { "filter": { "bool": { "must_not": [ { "missing": { "field": "your_field" } } ] } } } } } ```
48,886,423
I have a address list as : ``` addr = ['100 NORTH MAIN ROAD', '100 BROAD ROAD APT.', 'SAROJINI DEVI ROAD', 'BROAD AVENUE ROAD'] ``` I need to do my replacement work in a following function: ``` def subst(pattern, replace_str, string): ``` by defining a pattern outside of this function and passing it as an argument to subst. I need an output like: ``` addr = ['100 NORTH MAIN RD', '100 BROAD RD APT.', 'SAROJINI DEVI RD ', 'BROAD AVENUE RD'] ``` where all 'ROAD' strings are replaced with 'RD' --- ``` def subst(pattern, replace_str, string): #susbstitute pattern and return it new=[] for x in string: new.insert((re.sub(r'^(ROAD)','RD',x)),x) return new def main(): addr = ['100 NORTH MAIN ROAD', '100 BROAD ROAD APT.', 'SAROJINI DEVI ROAD', 'BROAD AVENUE ROAD'] #Create pattern Implementation here pattern=r'^(ROAD)' print (pattern) #Use subst function to replace 'ROAD' to 'RD.',Store as new_address new_address=subst(pattern,'RD',addr) return new_address ``` --- I have done this and getting below error Traceback (most recent call last): File "python", line 23, in File "python", line 20, in main File "python", line 7, in subst TypeError: 'str' object cannot be interpreted as an integer
2018/02/20
[ "https://Stackoverflow.com/questions/48886423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9385748/" ]
No need for regex, just use `replace`: ``` [x.replace('ROAD', 'RD') for x in addr] ``` If you only want to replace the `ROAD` as a word, no in the middle, use: ``` [re.sub(r'\bROAD\b', 'RD', x) for x in addr] ```
Using `re` ``` import re addr = ['100 NORTH MAIN ROAD', '100 BROAD ROAD APT.', 'SAROJINI DEVI ROAD', 'BROAD AVENUE ROAD'] for i, v in enumerate(addr): addr[i] = re.sub('ROAD', 'RD', v) #v.replace("ROAD", "RD") print addr ``` **Output**: ``` ['100 NORTH MAIN RD', '100 BRD RD APT.', 'SAROJINI DEVI RD', 'BRD AVENUE RD'] ```
48,886,423
I have a address list as : ``` addr = ['100 NORTH MAIN ROAD', '100 BROAD ROAD APT.', 'SAROJINI DEVI ROAD', 'BROAD AVENUE ROAD'] ``` I need to do my replacement work in a following function: ``` def subst(pattern, replace_str, string): ``` by defining a pattern outside of this function and passing it as an argument to subst. I need an output like: ``` addr = ['100 NORTH MAIN RD', '100 BROAD RD APT.', 'SAROJINI DEVI RD ', 'BROAD AVENUE RD'] ``` where all 'ROAD' strings are replaced with 'RD' --- ``` def subst(pattern, replace_str, string): #susbstitute pattern and return it new=[] for x in string: new.insert((re.sub(r'^(ROAD)','RD',x)),x) return new def main(): addr = ['100 NORTH MAIN ROAD', '100 BROAD ROAD APT.', 'SAROJINI DEVI ROAD', 'BROAD AVENUE ROAD'] #Create pattern Implementation here pattern=r'^(ROAD)' print (pattern) #Use subst function to replace 'ROAD' to 'RD.',Store as new_address new_address=subst(pattern,'RD',addr) return new_address ``` --- I have done this and getting below error Traceback (most recent call last): File "python", line 23, in File "python", line 20, in main File "python", line 7, in subst TypeError: 'str' object cannot be interpreted as an integer
2018/02/20
[ "https://Stackoverflow.com/questions/48886423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9385748/" ]
No need for regex, just use `replace`: ``` [x.replace('ROAD', 'RD') for x in addr] ``` If you only want to replace the `ROAD` as a word, no in the middle, use: ``` [re.sub(r'\bROAD\b', 'RD', x) for x in addr] ```
*Using* **RegEx**.. ``` import re count = 0 for x in addr: addr[count] = re.sub('ROAD', 'RD', x) count = count + 1 addr # just to print the result. ```
48,886,423
I have a address list as : ``` addr = ['100 NORTH MAIN ROAD', '100 BROAD ROAD APT.', 'SAROJINI DEVI ROAD', 'BROAD AVENUE ROAD'] ``` I need to do my replacement work in a following function: ``` def subst(pattern, replace_str, string): ``` by defining a pattern outside of this function and passing it as an argument to subst. I need an output like: ``` addr = ['100 NORTH MAIN RD', '100 BROAD RD APT.', 'SAROJINI DEVI RD ', 'BROAD AVENUE RD'] ``` where all 'ROAD' strings are replaced with 'RD' --- ``` def subst(pattern, replace_str, string): #susbstitute pattern and return it new=[] for x in string: new.insert((re.sub(r'^(ROAD)','RD',x)),x) return new def main(): addr = ['100 NORTH MAIN ROAD', '100 BROAD ROAD APT.', 'SAROJINI DEVI ROAD', 'BROAD AVENUE ROAD'] #Create pattern Implementation here pattern=r'^(ROAD)' print (pattern) #Use subst function to replace 'ROAD' to 'RD.',Store as new_address new_address=subst(pattern,'RD',addr) return new_address ``` --- I have done this and getting below error Traceback (most recent call last): File "python", line 23, in File "python", line 20, in main File "python", line 7, in subst TypeError: 'str' object cannot be interpreted as an integer
2018/02/20
[ "https://Stackoverflow.com/questions/48886423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9385748/" ]
No need for regex, just use `replace`: ``` [x.replace('ROAD', 'RD') for x in addr] ``` If you only want to replace the `ROAD` as a word, no in the middle, use: ``` [re.sub(r'\bROAD\b', 'RD', x) for x in addr] ```
I got the answer, ``` pattern=r'\bROAD\b' ``` passing this a parameter to ``` def subst(pattern, replace_str, string): #susbstitute pattern and return it new=[re.sub(pattern,'RD',x) for x in string] return new ``` we can get the op :)
70,332,822
I am receiving an image as bytes that I would like to store using specifically with open command due to library restrictions. Therefore I am unable to use libs like opencv2 and PIL ``` mport numpy as np import base64 import cv2 import io from os.path import dirname, join from com.chaquo.python import Python def main(data): decoded_data = base64.b64decode(data) files_dir = str(Python.getPlatform().getApplication().getFilesDir()) filename = join(dirname(files_dir), 'image.PNG') with open(filename, 'rb') as file: img = file.write(img) return img ``` What I would simply like to do is save the image file to the current directory that i am in. Currently when i try my code it gives me the following error: ``` com.chaquo.python.PyException: TypeError: write() argument must be str, not bytes ``` Which requires me to have a string. I'd like to know what do i need to do to save the image as a .PNG file to the directory
2021/12/13
[ "https://Stackoverflow.com/questions/70332822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As you wrote most Databricks clusters use 1.2.17 so it is different version and version affected by vulnerability is not used by Databricks. Only one problem is when you install different version by yourself on the cluster. Even when you installed affected version you can mitigate the problem by setting Spark config in cluster advanced config as below: ``` spark.driver.extraJavaOptions "-Dlog4j2.formatMsgNoLookups=true" spark.executor.extraJavaOptions "-Dlog4j2.formatMsgNoLookups=true" ```
you get complete e2e update on this here : <https://databricks.com/blog/2021/12/13/log4j2-vulnerability-cve-2021-44228-research-and-assessment.html>
13,788,114
Given the following Python (from <http://norvig.com/sudoku.html>) ``` def cross(A, B): "Cross product of elements in A and elements in B." return [a+b for a in A for b in B] cols = '123456789' rows = 'ABCDEFGHI' squares = cross(rows, cols) ``` This produces: ``` ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'B1', 'B2', 'B3', ...] ``` As an exercise, I want to do the same in C++. Currently I have: ``` #include <iostream> #include <map> #include <vector> using std::string; using std::vector; static vector<string> cross_string(const string &A, const string &B) { vector<string> result; for (string::const_iterator itA = A.begin(); itA != A.end(); ++itA) { for (string::const_iterator itB = B.begin(); itB != B.end(); ++itB) { char s[] = {*itA, *itB, 0}; result.push_back(string(s)); } } return result; } int main(int argc, char** argv) { const char digits[] = "123456789"; const char rows[] = "ABCDEFGHI"; vector<string> res = cross_string(rows, digits); for (vector<string>::const_iterator it = res.begin(); it != res.end(); ++it) { std::cout << *it << std::endl; } } ``` This works, but I was hoping there would be a better way. This also does only strings, whereas the python does any list... --- Edit: Thanks for all of the replies. I accepted the one that I understood best, but Alf's answer was a close second. I note that all used C++11 and wonder whether as a novice at C++ I should adopt that directly instead of the learning the older standard. But that is perhaps best for another question.
2012/12/09
[ "https://Stackoverflow.com/questions/13788114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1163625/" ]
Well it's shorter to just present the code than to explain: ``` #include <iostream> // std::wcout, std::endl #include <string> // std::string #include <utility> // std::begin, std::end #include <vector> using namespace std; string sum( char const a, char const b ) { return string() + a + b; } template< class Container > auto cross( Container const& a, Container const& b ) -> vector< decltype( sum( *begin( a ), *begin( b ) ) ) > { typedef decltype( sum( *begin( a ), *begin( b ) ) ) ResultItem; vector< ResultItem > result; for( auto&& itemA : a ) for( auto&& itemB : b ) { result.push_back( sum( itemA, itemB ) ); } return result; } wostream& operator<<( wostream& stream, string const& s ) { return (stream << s.c_str()); } template< class Item > wostream& operator<<( wostream& stream, vector<Item> const& v ) { stream << "["; bool isFirstItem = true; for( auto&& item : v ) { if( !isFirstItem ) { stream << ", "; } stream << item; isFirstItem = false; } stream << "]"; return stream; } int main() { string const cols = "123456789"; string const rows = "ABCDEFGHI"; auto const squares = cross( cols, rows ); wcout << squares << endl; } ```
templatize for classes A and B. then make pairs `std::pair<A, B>`
13,788,114
Given the following Python (from <http://norvig.com/sudoku.html>) ``` def cross(A, B): "Cross product of elements in A and elements in B." return [a+b for a in A for b in B] cols = '123456789' rows = 'ABCDEFGHI' squares = cross(rows, cols) ``` This produces: ``` ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'B1', 'B2', 'B3', ...] ``` As an exercise, I want to do the same in C++. Currently I have: ``` #include <iostream> #include <map> #include <vector> using std::string; using std::vector; static vector<string> cross_string(const string &A, const string &B) { vector<string> result; for (string::const_iterator itA = A.begin(); itA != A.end(); ++itA) { for (string::const_iterator itB = B.begin(); itB != B.end(); ++itB) { char s[] = {*itA, *itB, 0}; result.push_back(string(s)); } } return result; } int main(int argc, char** argv) { const char digits[] = "123456789"; const char rows[] = "ABCDEFGHI"; vector<string> res = cross_string(rows, digits); for (vector<string>::const_iterator it = res.begin(); it != res.end(); ++it) { std::cout << *it << std::endl; } } ``` This works, but I was hoping there would be a better way. This also does only strings, whereas the python does any list... --- Edit: Thanks for all of the replies. I accepted the one that I understood best, but Alf's answer was a close second. I note that all used C++11 and wonder whether as a novice at C++ I should adopt that directly instead of the learning the older standard. But that is perhaps best for another question.
2012/12/09
[ "https://Stackoverflow.com/questions/13788114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1163625/" ]
You could certainly make this generic: ``` template <class InIt1, class InIt2, class OutIt> void cross_product(InIt1 b1, InIt1 e1, InIt2 b2, InIt2 e2, OutIt out) { for (auto i=b1; i != e1; ++i) for (auto j=b2; j != e2; ++j) *out++ = std::make_pair(*i, *j); } ``` Note that you don't generally want the template parameters to be the types of the objects in the collections, but the types of iterators to the collections. For example, you could use this like this: ``` std::ostream &operator<<(std::ostream &os, std::pair<char, int> const &d) { return os << d.first << d.second; } int main() { std::vector<char> a{'A', 'B', 'C', 'D'}; std::vector<int> b{ 1, 2, 3, 4}; cross_product(a.begin(), a.end(), b.begin(), b.end(), infix_ostream_iterator<std::pair<char, int> >(std::cout, ", ")); return 0; } ``` ...which should produce output like this: ``` A1, A2, A3, A4, B1, B2, B3, B4, C1, C2, C3, C4, D1, D2, D3, D4 ``` Also note that I've used some C++11 features throughout most of this code. If you're using an older compiler (or one from Microsoft) it'll need a bit of editing.
templatize for classes A and B. then make pairs `std::pair<A, B>`
13,788,114
Given the following Python (from <http://norvig.com/sudoku.html>) ``` def cross(A, B): "Cross product of elements in A and elements in B." return [a+b for a in A for b in B] cols = '123456789' rows = 'ABCDEFGHI' squares = cross(rows, cols) ``` This produces: ``` ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'B1', 'B2', 'B3', ...] ``` As an exercise, I want to do the same in C++. Currently I have: ``` #include <iostream> #include <map> #include <vector> using std::string; using std::vector; static vector<string> cross_string(const string &A, const string &B) { vector<string> result; for (string::const_iterator itA = A.begin(); itA != A.end(); ++itA) { for (string::const_iterator itB = B.begin(); itB != B.end(); ++itB) { char s[] = {*itA, *itB, 0}; result.push_back(string(s)); } } return result; } int main(int argc, char** argv) { const char digits[] = "123456789"; const char rows[] = "ABCDEFGHI"; vector<string> res = cross_string(rows, digits); for (vector<string>::const_iterator it = res.begin(); it != res.end(); ++it) { std::cout << *it << std::endl; } } ``` This works, but I was hoping there would be a better way. This also does only strings, whereas the python does any list... --- Edit: Thanks for all of the replies. I accepted the one that I understood best, but Alf's answer was a close second. I note that all used C++11 and wonder whether as a novice at C++ I should adopt that directly instead of the learning the older standard. But that is perhaps best for another question.
2012/12/09
[ "https://Stackoverflow.com/questions/13788114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1163625/" ]
Weirdly enough, `cross_product` is missing from the C++ algorithms library. It can easily be added but as Jerry’s and Alf’s answers show, opinions differ on how to do it best. In fact, I’d do it different still. Jerry’s interface conforms to that of the other C++ algorithms but he didn’t abstract away the cross product operation, which I’d do thusly: ``` template <typename InputIt1, typename InputIt2, typename OutputIt, typename F> void cross_product(InputIt1 begin1, InputIt1 end1, InputIt2 begin2, InputIt2 end2, OutputIt out, F f) { for (auto i = begin1; i != end1; ++i) for (auto j = begin2; j != end2; ++j) *out++ = f(*i, *j); } ``` The call, in your example, would then look as follows: ``` auto digits = "1234546789"; auto chars = "ABCDEFGHI"; vector<string> result; cross_product(digits, digits + strlen(digits), chars, chars + strlen(chars), back_inserter(result), [](char a, char b) { return string() + a + b; }); ``` (Don’t I just love C++11? Yes, I do.) In a proper library I’d offer a second overload which supplies a default `f` operation which creates a tuple similar to what Jerry’s code does. It would even be thinkable to abstract this further to allow more than two ranges – after all, the Python list comprehension allows you to iterate over more than two ranges).
templatize for classes A and B. then make pairs `std::pair<A, B>`