w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Template a python-like setattr function
You probably can use pointer to member for this but I am not sure if you are going to like that: struct XX { char c; int i; }; template<class T, class U, class N> void set_parameter(T &S, U val, N T::*n) { for(auto &x: S) { x.*n = val; } } set_parameter(..., ..., &XX::c); set_parameter(..., ..., &XX::i);

Categories : C++

Python recursive setattr()-like function for working with nested dictionaries
>>> class D(dict): ... def __missing__(self, k): ... ret = self[k] = D() ... return ret ... >>> x=D() >>> x['f'][0]['a'] = 'whatever' >>> x {'f': {0: {'a': 'whatever'}}}

Categories : Python

Does setattr() method creates a temporary object?
No, that's not how it works at all. Python objects are dynamic. You can define whatever attributes you like on them at any point. It doesn't matter whether you do setattr(d, "name", "foo") or d.name = foo, the result is exactly the same: the d instance gains an attribute name, whether or not it previously had one, and whether or not there is a definition in the class that mentions it. Django models add their own special syntax for defining the fields that they store in the database, but underneath that they're just Python objects, so you can dynamically define extra attributes on them as much as you like.

Categories : Python

Attribute error: function object has no attribute in python
Just to get this answered: def datapaths(ipaddress, testlogfile): # Unecessary code reomved (code, val) = datapaths.listDatapaths(mylib) # Unecessary code reomved You are trying to access an attribute of a function you've defined, but most likely not set. I think you need to rexamine your code.

Categories : Python

Simple image css attribute issue
Compare the following 2 img tags in this fiddle in your Chrome dev tools. <img src="http://i.imgur.com/GTUxoqj.png"> <img src="http://i.imgur.com/GTUxoqj.png" width="200" height"200"> The following style img[Attributes Style] { width: 200px; } only appears on the 2nd attribute and appears in the Chrome dev tools on a grey background because it's not coming from CSS styles in the document or from an external stylesheet. The second image has a width and height attribute set on it. The dev tools are showing you that for that image the width is being affected by the attribute value (as opposed to CSS style). The grey background means it's not a CSS property you can modify through the dev tools. Chrome has similar behavior for default styling it applies to certain otherwise

Categories : HTML

Perl regex to match alt attribute as mandatory but sometimes alt attribute comes before src attribute and sometimes after src attribute
Does it have to be just one regex only? use Data::Dumper; my $s = q{<img rel="relfoo" src="srcfoo">}; my @m; $s =~ m{ <img s+ ( ((w+)(?{push @m, $^N})) = "( ([^"]*) (?{push @m, $^N}) )" s* )+ > }x; my %h = @m; print Dumper \%h; die "alt is mandatory.. " if !exists $h{alt}; output $VAR1 = { 'rel' => 'relfoo', 'src' => 'srcfoo' }; alt is mandatory..

Categories : Regex

Django Admin Issue - 'NoneType' object has no attribute 'user'
Your swallowing the request. Here you take it: def formfield_for_dbfield(self, db_field, request, **kwargs): but then you don't pass it on: return super(PostAdmin, self).formfield_for_dbfield(db_field, **kwargs) However the original - https://github.com/django/django/blob/stable/1.5.x/django/contrib/admin/options.py#L88 is defined as: def formfield_for_dbfield(self, db_field, **kwargs): So you should keep the same signature when you override. Please note: the original will do: request = kwargs.pop("request", None) If you want to access the request, don't do the same, because "pop()" will remove it from kwargs. Just access without deleting: request = kwargs['request'] so your super call still passes the request through. It only came to light with the M2M field because that n

Categories : Django

AttributeError at /login/ 'bool' object has no attribute 'rindex' - Django 1.5 issue
The answer was in my urls.py Notice how in my views.py I am sending my correct login to return render_to_response('uc/portal/index.html', {'state':state, 'username':username}, context_instance=RequestContext(request)) Turns out that in my urls.py I had defined url(r'^portal/$', 'portal.views.portal'), but I had not defined uc/portal/index.html as it is above. adding url(r'^portal/$', 'portal.views.portal'), fixed my problem entirely Thank you so much to bouke for taking the time to help me out!!! :D

Categories : Python

Set attribute to Element in Python
You should be doing: ET.SubElement(root,'TextSummary').set('Status','Completed') The Etree documentation shows usage.

Categories : Python

Python CSV Has No Attribute 'Writer'
If you've set something that assigns to csv (looks like a string) then you're shadowing the module import. So, the simplest thing is to just change whatever's assigning to csv that isn't the module and call it something else... In effect what's happening is: import csv csv = 'bob' csvout = csv.writer(somefile) Remove the further assignment to csv and go from there...

Categories : Csv

How to know which next attribute is requested in python
No. c.someMethod is a self-contained expression; its evaluation cannot be influenced by the context in which the result will be used. If it were possible to achieve what you want, this would be the result: x = c.someMethod c.someMethod.getAttributes() # Works! x.getAttributes() # AttributeError! This would be confusing as hell. Don't try to make c.someMethod behave differently depending on what will be done with it, and if possible, don't make c.someMethod a method call at all. People will expect c.someMethod to return a bound method object that can then be called to execute the method; just define the method the usual way and call it with c.someMethod().

Categories : Python

Python - How to get the attribute behind @property
There's no general way to do this, since a property doesn't have to simply be a proxy for a private attribute. You could have any of the following: @property def foo(self): return 4 @property def bar(self): return self._bar**2 @property def baz(self): sys.exit(1) @property def spam(self): if self._spam is None: self._spam = self._lazily_compute_spam() return self._spam If you wanted to try it anyway, you could try to get the source code of the property method with the inspect module and parse it, or decompile the bytecode, but both are terribly fragile ideas.

Categories : Python

Getting Attribute error in Python
self.entbx is created by create_widget(). You are calling reveal() -- which requires self.entbx -- before you've called create_widget(): self.reveal() self.create_widget()

Categories : Python

get attribute with getattr from a object in python
The parentheses are almost certainly not part of the attribute name. Get rid of them when calling getattr(). Then you need to call the method: attr_name = pattr[letter] if not attr_name.endswith("()"): print getattr(p, attr_name) else: print getattr(p, attr_name[:-2])()

Categories : Python

Python: How do you call an attribute from one function into another?
Your current implementation declares it as a local variable, and hence in accessible outside. For that to work, the assignment needs to happen onto self.charinfo: When you want to access charinfo from other places - self.charinfo works from within the class definition, and - app.charinfo works outside class / from the instance for index in self.charbox.curselection(): charfilelocale = self.charbox.get(int(index)) charfile = open(app.chardir + app.charprefix + charfilelocale, 'r+') # notice the self.charinfo here self.charinfo = self.charfile.read().splitlines(0) Its better to ensure the attribute self.charinfo is available outside the loop to avoid errors in case it loops 0 times self.charinfo = None for index in self.charbox.curselection(): charfilelocale = self

Categories : Python

Python: Subsetting a list according to the attribute
For your specific example, you could use a list comprehension like so: return [x for x in a_list if x.smth == 2] For your general example, you could do a similar thing: if value_to_accept is not None: return [x for x in a_list if x.smth == value_to_accept] if value_to_reject is not None: return [x for x in a_list if x.smth != value_to_reject] return []

Categories : Python

Comparing two xml using python ignoring particular attribute
Something like this could work: root1 = etree.fromstring(xml1) root2 = etree.fromstring(xml2) for node1, node2 in zip(root1.iter(), root2.iter()): if node1.tag == node2.tag: a1 = node2.attrib a2 = node2.attrib if node1.tail != node2.tail: raise ValueError('XML differs') for ignored in ('ID',): try: del a1[ignored] except AttributeError: pass try: del a2[ignored] except AttributeError: pass if a1 != a2: raise ValueError('XML differs') else: raise ValueError('XML differs') Instead of izip() you might need to use itertools.izip_longest()

Categories : Python

Get values from onclick attribute using python bs4
You can use regex for getting the data out of onclick: properties = soup.findAll('a', title=re.compile('Bedroom')) for eachproperty in properties: print re.findall("'([a-zA-Z0-9,s]*)'", eachproperty['onclick']) prints: ['Y10765227', '9884877926, 9283183326', '', 'Dealer', 'Rgmuthu'] ['L10038779', '9551154555', ',', ','] ['R10831945', '9150000747, 9282109134, 9043728565', ',', ','] ['B10750123', '9952946340', '', 'Dealer', 'Bala'] ['R10763559', '9841280752, 9884797013', '', 'Dealer', 'Senthil'] ... Hope that helps.

Categories : Python

Call attribute method python
Just call it date.now() - you'll never be able to access the hour attribute of the function since it's an attribute of the object. Doing date.hour will allow you to see hour. >>> date.hour 'hour' What you should do though is set all of these properties in the __init__ function of your class. class Date(): def __init__(self, hour): self.hour = hour def now(self): print self.hour #if you will def __call__(self string): print string

Categories : Python

What is the maximum length for an attribute name in python?
2.3. Identifiers and keywords from The Python Language Reference: Identifiers are unlimited in length. But you'll be violating PEP-8 most likely, which is not really cool: Limit all lines to a maximum of 79 characters. Also you'll be violating PEP-20 (the Zen of Python): Readability counts.

Categories : Python

python: 'str' object has no attribute 'iteritems'
open('1.txt', 'r').read() returns a string not dict. >>> print file.read.__doc__ read([size]) -> read at most size bytes, returned as a string. If 1.txt contains: 'alba':'barba', 'raim':'uva' then you can use ast.literal_eval to get a dict: >>> from ast import literal_eval >>> with open("1.txt") as f: dic = literal_eval('{' + f.read() +'}') print dic ... {'alba': 'barba', 'raim': 'uva'} Instead of using str.replace you should use regex, as str.replace('alba','barba') will also replace words like 'albaa', 'balba', etc: import re def replace_all(text, dic): for i, j in dic.iteritems(): text = re.sub(r"'{}'".format(i), "'{}'".format(j), text) return text

Categories : Python

How do we get an optional class attribute in Python?
You can use hasattr and getattr. For example: hasattr(foo, 'bar') would return True if foo has an attribute named bar, otherwise False and getattr(foo, 'bar', 'quux') would return foo.bar if it exists, otherwise defaults to quux.

Categories : Python

Python class without attribute boilerplate
Here are some recipes you can try: override __setattr__, __dict__, __slots__ and/or init. Let us know what works for you.

Categories : Python

Set attribute on a python thread from traits
Ok, I got it: I was adding the attribute port_name before creating the instance. class Arduino(HasTraits): start_stop_capture = Button() display = Instance(TextDisplay) capture_angles = Instance(CaptureAngles) capture_angles.port_name = 'COM5' # <-- wrong: the object is not created yet ... instead of: def _start_stop_capture_fired(self): if self.capture_angles and self.capture_angles.isAlive(): self.capture_angles.wants_abort = True else: self.capture_angles = CaptureAngles() self.capture_angles.port_name = 'COM5' # <-- correct ...

Categories : Python

Regex in python that finds the attribute of some HTML tag?
Have you actually benchmarked it and found that BeautifulSoup was the bottleneck? content = soup.find('meta', property='og:image').get('content') You could also use lxml, which is much faster: import lxml.html root = lxml.html.fromstring(html) # Use .parse() on a file-like object instead content = root.xpath('/html/head/meta[@property="og:image"][1]/@content')

Categories : Python

python - AttributeError: 'module' object has no attribute
Edit After reading the stacktrace again, you can see that urllib3 tries to import something from the http module. Your file is called http.py and is thus imported instead of the expected one. The actual error happens because of the circular nature of the import. Since requests hasn't finished importing completely yet. The get function in requests isn't defined yet when the http import reaches import requests again. Note: You will also want to always guard your entry point with the if __name__ == '__main__' construct. This will often avoid nasty errors for unsuspecting future developers (including yourself).

Categories : Python

Python using .find to search an XML (Attribute Error)
After parsing, the XML document is a Document (DOM) object, not a string. Document objects indeed do not have a find() method because you can't just search and replace text in them. If you know the ID or tag of the element that contains the text you wish to change, you could use getElementById or getElementsByTagName and then search the children of the returned elements for the text. Otherwise, you can recursively walk all the nodes in the document and search each text node for the text you wish to change. See the DOM documentation for more information on working with the Document Object Model.

Categories : Python

Python 2.7 assertin gets error object has no attribute
There seems to be an issue with assertIn in some versions of Python. Here's an alternative that should work: a = 'a' apple = 'apple' self.assertTrue(a in apple, '{} not in {}'.format(a, apple))

Categories : Misc

Attempting to use python Enchant but I'm getting an Attribute Error
Had the same error, because I was naming the file "enchant.py". And then I did import enchant I think then he tried to import the file I was editing, so I simply changed the name and enchant was working properly.

Categories : Python

how to get or set object's attribute from a list in maya python?
Unless there is a Maya specific issue that I don't know about, there are a couple of ways to do this in Python: for myObject in myList: # directly getting and setting attribute myObject.translateY = 30.0 # set a = myObject.translateY # get # alternatively, via setattr and getattr built-in functions. setattr(myObject, "translateY", 40.0) # getter which Raises exception if myObject has no "translateY" attr: a = getattr(myObject, "translateY") # getter which supplies defaultVal if myObject has no "translateY" attr a = getattr(myObject, "translateY", defaultVal) As an aside, it is bad form to call your variable "list", as this name will shadow Python's built-in list function. Better to use something like "myList" instead.

Categories : Python

Extracting XML Element and Attribute Data with Python 3
http://docs.python.org/3/library/xml.etree.elementtree.html >>> from xml.etree import ElementTree as ET >>> elem = ET.fromstring('''<Atom3d ID="18" Mapping="43" Parent="2" Name="C7" ... XYZ="0.0148299997672439,0.283699989318848,1.0291999578476" Connections="33,39" ... TemperatureType="Isotropic" IsotropicTemperature="0.0677" ... AnisotropicTemperature="0,0,0,0,0,0,0,0,0" Occupancy="0.708" Components="C"/> ... ''') get attribute using get('attribute-name'): >>> elem.get('XYZ') '0.0148299997672439,0.283699989318848,1.0291999578476' split string by ',': >>> elem.get('XYZ').split(',') ['0.0148299997672439', '0.283699989318848', '1.0291999578476']

Categories : Python

python- Feature class attribute manipulation
Short of writing your code for you, use arcpy.ListFields() to loop over the fields of each featureclass. Be careful not to totally denude the target class of identifying info; use an if/then w/in that loop. You haven't really specified the common key/relate field but you'll want to keep that around, at least, in order to transfer information to relevant features in target. P.S. why 2.6? Time to update both ArcGIS & Python!

Categories : Python

Weird python list syntax with an attribute
The author of the underlying blocks class has replaced the normal semantics of various Python expressions to implement a mini query language. Most likely, the blocks class overrides the __setitem__ and __eq__ hooks. The temp.blocks == 14 expression is handled by the __eq__ hook and returns some kind of specialized object that is then passed to the __setitem__ hook via the [...] syntax. The __setitem__ hook then uses that specialised object to determine what indices in the sequence to alter. The == operator looks for a __eq__ method on either operand, and if present, that method is called and the return value (normally True or False) is returned as the result for that equality test. However, the __eq__ method on temp.blocks returns something else; and that 'something' could also implemen

Categories : Python

Summing Attribute in a list of Python Objects
You can do this using a defaultdict: from collections import defaultdict indexed_sums = defaultdict(int) for o in xbs: indexed_sums[(o.W, o.X, o.Y)] += o.Z For instance, if you start with (using your class definition of xb): xbs = [xb(1, 2, 3, 4, 5), xb(1, 2, 3, 4, 5), xb(1, 2, 3, 4, 5), xb(1, 4, 3, 4, 5), xb(1, 4, 3, 4, 3), xb(1, 2, 3, 9, 3)] You end up with: print dict(indexed_sums) # {(4, 3, 4): 8, (2, 3, 4): 15, (2, 3, 9): 3} Thus, you could get the sum for W, X, Y being 2, 3, 4 as: indexed_sums[(2, 3, 4)] # 15 Note that the defaultdict is doing very little work here (it's just a dictionary of counts that starts at 0 by default): the main thing is that you are indexing the (o.W, o.X, o.Y) tuples in a dictionary. You could have done t

Categories : Python

exceptions.AttributeError: Python instance has no attribute 'name'
Well the error is quite logical if command == "iam": self.name = content msg = self.name + "has joined" elif command == "msg": msg = self.name + ": " + content print msg In the first if clause you assign a value to self.name which may either rely on assumption that self.name exists somewhere, or on assumption that it is new and needs to be declared, but in elif you seem to assume with certainty that self.name already exists, it turns out it doesn't so you get an error. I guess your safest option consists of simply adding self.name at the beginning of dataReceived method: def dataReceived(self, data): self.name = "" this will get rid of the error. As an alternative you could also add self.name to init method of IphoneChat.If you need self.name in other functions

Categories : Python

Grab LDAP Attribute from stdin in Python
line_dict for line in sys.stdin: parts = line.split(",") line_dict = dict(map(str.strip,part.split("=")) for part in parts) print line_dict['protocol'] to be fair I didnt test it so there may be some minor syntax errors but something like that is probably what you want. however if you just wanted protocol import re for line in sys.stdin: if 'protocol' in line: print re.findall("protocols*=([^,]*)",line)

Categories : Python

Python import behaviour and 'NoneType' object has no attribute
The line "UMD has deleted ..." is the hint. You are likely using the Spyder IDE, and this non-standard behavior is described here: Spyder - UMD has deleted: module Now the additional issue is that the module untitled0.py has been unloaded (and reloaded). However, your pre-existing instance a has a class that is the one that existed in the old copy of the module. So its method f() invokes the old version of the code. The problem here is that the old copy of the module was garbage-collected: this means (strangely enough) that Python has replaced all global names with None. This is why you end up with looking up np.diag() --- but crashing because np is None at this point. Why does it replace all global variables with None??? It's a very old reason: because it creates cycles of referen

Categories : Python

Creating a __version__ attribute for python packages without getting into trouble
You haven't said how you get the version number into setup.py, but don't try to import it with the usual import my_package approach. You package hasn't been installed when you run setup.py! My usual approach is to define the version number in setup.py and have setup.py (re)generate the package's top level __init__.py file when the version number changes. This is easy to do if the __init__.py file contains no other code.

Categories : Python

python-magic module' object has no attribute 'open'
There is no magic.open() function. If you check out the python-magic documentation you can see that it has magic.from_file() and magic.from_buffer() functions. Use magic.from_file() to test against a path name; the module opens that file for you and and determines the type. Use magic.from_buffer() to test a byte sequence (str in Python 2, bytes in Python 3). There is also a magic.Magic() class that you can instantiate (per thread!) to alter how it operates: Magic(mime=False, magic_file=None, mime_encoding=False) documented as: Create a new libmagic wrapper. mime - if True, mimetypes are returned instead of textual descriptions mime_encoding - if True, codec is returned magic_file - use a mime database other than the system default and according to the README, that is

Categories : Python

Determine if given class attribute is a property or not, Python object
I once asked a similar question. The trouble you'll run into, of course, is that you can't access the property through the instance to determine its type without calling the getter, which gets you the type of whatever the getter returns. So you have to access the property through its class rather than through the instance. property is already a type, so you can just compare directly to that. (I originally had some superfluous code here that got the property type out of a class that had a property. I thought this was necessary due to a typo when I was testing things.) obj_type = type(obj) for attr in dir(obj): if isinstance(getattr(type(obj), attr, None), property): print attr, "is a property" Don't worry about having an instance attribute with the same name. It's ignored

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.