I am using python to read the shapefile, however I meet some problems, this is the core code:
value="#code"
print 'value:',value
if '#' in value:
v=value.replace('#','');
print 'replaced:',v
fixed_value=str(feature.GetFieldAsString(v))
It worked as expected if I run the script directly, but it will throw error once I run it in a web environment, I will get error like this:
File "/home/kk/gis/codes/tilestache/map/__init__.py", line 162, in _get_features
fixed_value=str(feature.GetFieldAsString(v))
File "/usr/local/lib/python2.7/dist-packages/GDAL-1.10.1-py2.7-linux-x86_64.egg/osgeo/ogr.py", line 2233, in GetFieldAsString
return _ogr.Feature_GetFieldAsString(self, *args)
NotImplementedError: Wrong number of arguments for overloaded function 'Feature_GetFieldAsString'.
And if I change the line to :
fixed_value=str(feature.GetFieldAsString('code'))
It worked.
What's going on?
It seems that the replace function in python make things strange.
UPDATE
Seems I get the point,this is caused by the replace function in python which return a different rather than str:
value='#code'
type(value) ==> str
v=value.replace('#','')
type(v) ==>unicode
Then I use:
fixed_value=str(feature.GetFieldAsString(str(v)))
It worked.
But I am not sure why it work in a shell environment but not in a web environment. I hope someone can explain this.
Related
So here I am asking My first question related to python script. While I am running my python script i am facing an issue. So the complete error is
'''[E966] nlp.add_pipe now takes the string name of the registered component factory, not a callable component. Expected string, but got <spacy.pipeline.sentencizer.Sentencizer object at 0x000001D4C1831F80> (name: 'None').'''
So below is my code snippet. Please let me know where I am going rong.
if not isinstance(factory_name, str):
bad_val = repr(factory_name)
err = Errors.E966.format(component=bad_val, name=name)
raise ValueError(err)
So please let me know where I am doing wrong
I was faced with a very strange problem.
With print() this code works.
def max_pairwise_product(numbers):
max_1 = max(numbers)
numbers.remove(max_1)
max_2 = max(numbers)
return max_1 * max_2
if __name__ == '__main__':
input_n = int(input())
print() # <- comment of this line breaks the code
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product(input_numbers))
If I comment or delete the 10-th line with print() I got an error:
Traceback (most recent call last):
File "C:\Users\...\maximum_pairwise_product_fast.py", line 12, in <module>
print(max_pairwise_product(input_numbers))
File "C:\Users\...\maximum_pairwise_product_fast.py", line 2, in max_pairwise_product
max_1 = max(numbers)
ValueError: max() arg is an empty sequence*
Process finished with exit code 1
I use Python 3.9. PyCharm.
I tried to launch with different virtual environments with Python 3.8 and 3.10 – the same error.
When I launch in Jupyter and Colab – it is fane – no error.
There are no issues with any other Python script. I used the installation for several months and there was nothing strange.
It is so strange that I have no idea. Could you please help me?
Try checking if your python interpreter is working correctly and is the latest python
It might fix it or there's probably a problem with your ide.
Thank you all for helping to refer me in the right direction.
The reason for the error was a bug in PyCharm. It sent not was typed. The issue disappeared after the PyCharm update from version 2022.1.1 to 2022.1.2.
Back in 2018 or so, I found a similar strange issue in a Python program I downloaded that solved Rubik's cubes. Basically, the program ran just fine under Linux, but under Windows it was erroring out at a certain line that looked fine.
I ran "pyflakes" on that program, but pyflakes reported that nothing was wrong. Odd.
The line that supposedly contained the error was a list comprehension, much like your line here:
input_numbers = [int(x) for x in input().split()]
I replaced the list comprehension with a normal for-loop, and then the code ran fine with no errors. Basically, if I were to rewrite your line, I would replace it with the following four lines:
input_numbers = []
for x in input().split():
input_numbers.append(int(x))
assert input_numbers, "input_numbers is empty!"
I have no idea why the error was happening in the first place, and only on Windows. (The version of Python3 I was using certainly supported list comprehensions; I checked.) But once I replaced the list comprehensions with a for-loop, the code worked.
So my advice is to replace your list-comprehension with a for-loop and see if that solves anything.
I don't know if that will work, but it's worth a shot, as it seems that your input_numbers list is not actually being populated before it's passed to max_pairwise_product().
You might even try putting the assert statement:
assert input_numbers, "input_numbers is empty!"
after the list comprehension to verify that input_numbers is truly being populated. If it's not, then you at least have narrowed down your problem, and will now have to figure out why it's not being populated.
P.S. I'm curious: Which operating system(s) does the error happen on?
P.P.S. I recommend adding input text to your input() calls (such as input("Type some space-separated numbers: "), even if just for posting here. Otherwise, when stackoverflow users run your code, it looks like your code is hanging.
I'm getting used to VSCode in my daily Data Science remote workflow due to LiveShare feature.
So, upon executing functions it just executes the first line of code; if I mark the whole region then it does work, but it's cumbersome way of dealing with the issue.
I tried number of extensions, but none of them seem to solve the problem.
def gini_normalized(test, pred):
"""Simple normalized Gini based on Scikit-Learn's roc_auc_score"""
gini = lambda a, p: 2 * roc_auc_score(a, p) - 1
return gini(test, pred)
Executing the beginning of the function results in error:
def gini_normalized(test, pred):...
File "", line 1
def gini_normalized(test, pred):
^
SyntaxError: unexpected EOF while parsing
There's a solution for PyCharm: Python Smart Execute - https://plugins.jetbrains.com/plugin/11945-python-smart-execute. Also Atom's Hydrogen doesn't have such issue either.
Any ideas regarding VSCode?
Thanks!
I'm a developer on the VSCode DataScience features. Just to make sure that I'm understanding correctly. You would like the shift-enter command to send the entire function to the Interactive Window if you run it on the definition of the function?
If so, then yes, we don't currently support that. Shift-enter can run line by line or run a section of code that you manually highlight. If you want, you can use #%% lines in your code to put functions into code cells. Then when you are in a cell shift-enter will run that entire cell, might be the best current approach for you.
That smart execute does look interesting, if you would like to file that as a suggestion you can use our GitHub here to get it on our backlog to look at.
https://github.com/Microsoft/vscode-python
Hi you could click the symbol before each line and turn it into > (the indented codes of the function was hidden now). Then if you select the whole line and the next line, shift+enter could run them together.
enter image description here
I need to write an optimization file for Gurobi (Python) that is a modified version of a classic TSP. I tried to run the example file from their website:
examples.gurobi.com/traveling-salesman-problem/
I always get the following error:
TypeError: object of type 'NoneType' has no len()
What do I need to change?
Thx
Full code: https://www.dropbox.com/s/ewisx805b3o2wq5/beispiel_opt.py?dl=0
I can confirm the error with the example code from Gurobi's website. At the first look the problem seems to be inside the subtour function, that returns None if sum(lengths) == n and the missing check for if tour is None inside the subtourlim function.
Instead of providing a fix for the specific code, I first checked the examples that Gurobi installs inside the specific installation directory:
Mac: /Library/gurobi810/mac64/examples/python/
Linux: /opt/gurobi800/linux64/examples/python/
Windows: c:\gurobi800\win64\examples\python\
And surprisingly the tsp.py from there runs without any errors. Note also that the two mentioned functions are revised. So I guess the example from the website is just a old version of the code.
I have written this function in a package of mine.
def partitionIntoDays(ls, number, lookupKey=None):
''' Partitions the location measurements into days.
#ls: The list of measurements you want to partition
#return: A dictionary in the format {'Number of partition':
'List of measurements'}'''
if len(ls) == 0:
return {0: []}
firstMidnight = TimeAux.localTimeToEpoch(Delorean(TimeAux.epochToLocalTime(ls[0].time, TIMEZONE)).midnight())
return splitByTimedelta(ls, delta=number*24*3600, lowerBound=firstMidnight, lookupKey=lookupKey)
But whenever I try to call the function from a script I get the following error:
TypeError: partitionIntoDays() got an unexpected keyword argument 'lookupKey'
However if I import the function somewhere manually, I can check that the function has the argument. For example, I can even do this while I am debugging the above error in pdb.
import geogps.Partition as pt
pt.partitionIntoDays.func_code.co_varnames
>>>>('ls', 'number', 'lookupKey', 'firstMidnight')
Also the above code works fine in Python 3.4.
I am in short completely flabbergasted.
So I figured it out: While there were no lingering pyc files, my package structure was messed up and I had an extraneous file in a nested folder.
Thanks #bruno-desthuilliers for pointing me the right way.