How to know MRO in python2 - python-2.x

In python3, we can use '__mro__' to get the method-resolution-order like below:
>>> class a:
... pass
...
>>> a.__mro__
(<class '__main__.a'>, <class 'object'>)
>>>
Does python2 has an alternative method for this? I tried to find one but failed.
>>> class a:
... pass
...
>>> dir(a)
['__doc__', '__module__']
>>> class a(object):
... pass
...
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

mro() is available since Python 2.2 (https://www.python.org/download/releases/2.3/mro/)
However the class must be a new style class.
>>> class A: pass
>>> A.mro()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class A has no attribute 'mro'
>>> class A(object): pass
>>> A.mro()
[<class '__main__.A'>, <type 'object'>]

Related

AttributeError: DescribeData: Method shapeFieldName does not exist

skipFlds = [desc.shapeFieldName, desc.OIDFieldName]
Error: AtrributeError: DescribeData: Method shapeFieldName does not exist
That error is common when a shape/geometry field doesn't exist, like in a regular table. Double check you are describing a spatial dataset; if so, then the dataset may be corrupted and ArcPy isn't recognizing a spatial data type exists.
>>> import arcpy
>>>
>>> fc = # path to feature class
>>> tbl = # path to table
>>>
>>> desc_fc = arcpy.Describe(fc)
>>> desc_fc.shapeFieldName
'Shape'
>>>
>>> desc_tbl = arcpy.Describe(tbl)
>>> desc_tbl.shapeFieldName
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: DescribeData: Method shapeFieldName does not exist
>>>

h2o set_params() takes exactly 1 argument (2 given), even though only 1 given?

Getting error
TypeError: set_params() takes exactly 1 argument (2 given)
even though I only appear to be providing a single argument...
HYPARAMS = {
unicode(HYPER_PARAM): best_random_forest.params[unicode(HYPER_PARAM)][u'actual']
for HYPER_PARAM in list_of_hyperparams_names
}
assert isinstance(HYPARAMS, dict)
print 'Setting optimal params for full-train model...'
pp.pprint(HYPARAMS)
model = model.set_params(HYPARAMS)
#output
{ u'col_sample_rate_per_tree': 1.0,
u'max_depth': 3,
u'min_rows': 1024.0,
u'min_split_improvement': 0.001,
u'mtries': 5,
u'nbins': 3,
u'nbins_cats': 8,
u'ntrees': 8,
u'sample_rate': 0.25}
model = model.set_params(OPTIM_HYPARAMS)
TypeError: set_params() takes exactly 1 argument (2 given)
Looking at the source code,
def set_params(self, **parms):
"""Used by sklearn for updating parameters during grid search.
Parameters
----------
parms : dict
A dictionary of parameters that will be set on this model.
Returns
-------
Returns self, the current estimator object with the parameters all set as desired.
"""
self._parms.update(parms)
return self
there does not appear to be much going on that I see could go wrong. Anyone know what I'm missing here or what is happening to cause this error?
TLDR: Need to unpack the keys/values as **kwargs keywords in order to get the expected behavior of updating the _parms dict. So do
model = model.set_params(**HYPARAMS) #see https://stackoverflow.com/a/22384521/8236733
Example:
# here's a basic standin for the set_params method
>>> def kfunc(**parms):
... print parms
...
# what I was doing
>>> kfunc({1:2})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: kfunc() takes exactly 0 arguments (1 given)
# and also tried
>>> kfunc(parms={1:2})
{'parms': {1: 2}}
>>> kfunc({u'1':2, u'2':3})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: kfunc() takes exactly 0 arguments (1 given)
# what should have been done
>>> kfunc(**{'1':2})
{'1': 2}
>>> kfunc(**{u'1':2, u'2':3})
{u'1': 2, u'2': 3}
Can now see that this is not directly related to h2o, but keeping post up anyway so others with this problem may find, since did not immediately think to do this from just reading the popup docs for the method (and also since the other SE post commented in the example that I used to actually use variables as **kwarg keywords was not even on the first page of a Google search of "How to use python variable as keyword for kwargs parameter?" so would like to add more avenues to it).

'DataFrame' object has no attribute 'split_frame'

Unable to Split frame using split_frame(). The dataframe is able to show() but I cannot split it. Please help.
Below is a sample of the code I have used.
from h2o.estimators.random_forest import H2ORandomForestEstimator
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
from h2o.estimators.glm import H2OGeneralizedLinearEstimator
from h2o.estimators.stackedensemble import H2OStackedEnsembleEstimator
from __future__ import print_function
temp = spark.read.option("header","true").option("inferSchema","true").csv("hdfs://bda-ns/user/august_week2.csv")
train,test,valid = temp.split_frame(ratios=[.75, .15])
Expected: no error. Data split into test and train data frame.
Actual:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/cloudera/parcels/SPARK2-2.3.0.cloudera2-1.cdh5.13.3.p0.316101/lib/spark2/python/pyspark/sql/dataframe.py", line 1182, in __getattr__
"'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
AttributeError: 'DataFrame' object has no attribute 'split_frame'
>>> train,test,valid = temp.split_frame(ratios=[.75, .15])
Traceback (most recent call last):
File "/opt/cloudera/parcels/SPARK2-2.3.0.cloudera2-1.cdh5.13.3.p0.316101/lib/spark2/python/pyspark/context.py", line 234, in signal_handler
You could use randomsplit on your spark dataframe.
If you want to use the H2O-3 split_frame method, you would first have to convert your spark frame to an h2o frame. In which case you could use hc.as_h2o_frame(spark_df) where hc is your h2o_context (note: you would also need to create the h2o_context for this to work).

Create class in a different file in MicroPython

I'm trying to use the MPU6050 module for MicroPython in NodeMCU, using uPyCraft as an editor. (https://github.com/larsks/py-mpu6050/blob/master/mpu6050.py)
I've got some troubles and I tried to simplify the code to the point I just try to call a class defined in a different file and I cannot get it to work. This is what I've done so far:
I created a new file (myFile.py) and it looks like:
import machine
class myClass(object):
def __init__(self):
print("init method called")
Then in my main.py I do:
import myFile
myclass = myFile.myClass()
I run main.py and I get this error when doing myclass = myFile.myClass() line:
'module' has no method myClass
I have no experience with MicroPython (although I'm a C# coder) so I'm pretty sure there is some detail about the syntax I'm missing. Any help?
here some tests (file name is the real one, I simplified in the question):
>>> print(open('mpuController.py').read())
import machine
class myClass(object):
def __init__(self):
print("init method called")
other:
>>> print (open('testMPU.py','r').read())
import time
import mpuController
print("starting")
mpu = mpuController.myClass()
print("finished")
and then when running:
exec(open('./testMPU.py').read(),globals())
starting
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 5, in <module>
AttributeError: 'module' object has no attribute 'myClass'
Change
import myFile.py
to
import myFile
You're importing a module (myFile), not a file. Let Python sort it out.

PyQt5 Signals and Slots 'QObject has no attribute' error

I have been trying to find a way to update the GUI thread from a Python thread outside of main. The PyQt5 docs on sourceforge have good instructions on how to do this. But I still can't get things to work.
Is there a good way to explain the following output from an interactive session? Shouldn't there be a way to call the emit method on these objects?
>>> from PyQt5.QtCore import QObject, pyqtSignal
>>> obj = QObject()
>>> sig = pyqtSignal()
>>> obj.emit(sig)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'QObject' object has no attribute 'emit'
and
>>> obj.sig.emit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'QObject' object has no attribute 'sig'
and
>>> obj.sig = pyqtSignal()
>>> obj.sig.emit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'PyQt5.QtCore.pyqtSignal' object has no attribute 'emit'
Following words and codes are in PyQt5 docs.
New signals should only be defined in sub-classes of QObject.They must be part of the class definition and cannot be dynamically added as class attributes after the class has been defined.
from PyQt5.QtCore import QObject, pyqtSignal
class Foo(QObject):
# Define a new signal called 'trigger' that has no arguments.
trigger = pyqtSignal()
def connect_and_emit_trigger(self):
# Connect the trigger signal to a slot.
self.trigger.connect(self.handle_trigger)
# Emit the signal.
self.trigger.emit()
def handle_trigger(self):
# Show that the slot has been called.
print "trigger signal received"

Resources