lldb & synthetic provider: follow pointer - c++

I have a custom class called Values that is a wrapper of arrays. For a given object vFoo of class Values, which contains an array of objects of class Foo, the var format -T vFoocommand returns the following structure:
(MyNameSpace::Values) vFoo = {
(void *) p = 0x0000000100204378
(size_t) n = 2
(MyNameSpace::ValueType) type = FOO
}
where vFoo.p is a pointer to the array<Foo> that contains 2 elements. I can access the array elements with the following command in the lldb prompt:
expression ((MyNameSpace::Foo*)vFoo.p)[0]
which returns
(MyNameSpace::Foo) $0 = "foo"
according to my summary provider.
I would like to write a synthetic child provider that returns something like:
(MyNameSpace::Values) vFoo = {
(MyNameSpace::Foo) vFoo.p[0] = "foo"
(MyNameSpace::Foo) vFoo.p[1] = "bar"
}
Unfortunately, I have no idea how to do that. I read the lldb data formatters page and try to follow the structure given at the end of the page. I have also had a look at the bitfield and libcxx examples, but I can't find my way to the solution. Any help would be deeply appreciated!
Many thanks in advance

You need to get the internal representation of the type Foo. You can get this from the SBModule using self.valobj.GetFrame().GetModule().FindFirstType("Foo"). Something like this will work with some poking around.
class Values_SynthProvider:
def __init__(self, valobj, dict):
self.valobj = valobj
self.num_elements = None
def update(self):
self.num_elements = self.valobj.GetChildMemberWithName('n').GetValueAsUnsigned(0)
def num_children(self):
return self.num_elements
def get_child_at_index(self,index):
# Here you could switch on the value of Values::type to get the right type name to search for
foo_type = self.valobj.GetFrame().GetModule().FindFirstType("Foo")
return self.valobj.GetChildMemberWithName('p').Cast(foo_type.GetPointerType()).GetChildAtIndex(index,0,True)
def get_child_index(self,name):
return int(name.lstrip('[').rstrip(']'))

Related

grails - how do you pass non string variables to taglib attrs map using testing with applyTemplate?

grails 3.3.9, + tag libs
I create a new taglib like this
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class JavaDateTimeTagLib {
static defaultEncodeAs = [taglib:'html']
//static encodeAsForTags = [tagName: [taglib:'html'], otherTagName: [taglib:'none']]
static encodeAsForTags = [testCall: [taglib:'none']]
static namespace = "jdt" //java8 date time name space for tags
def testCall = { attrs ->
def p1 = attrs.p1
def p2 = attrs.p2
out << "p1:'$p1' with class ${p1.getClass()}"
out << "p2:'$p2' with class ${p2.getClass()}"
}
}
where i want to pass a non string variable to the attrs map.
i then setup the test like this
class JavaDateTimeTagLibSpec extends Specification implements TagLibUnitTest<JavaDateTimeTagLib> {
def setup() {
}
def cleanup() {
}
/**
* restriction params must be quoted values - esentially strings
* taglib has to take that and do any conversions in the taglib
* output by defaults is encoded html using std codec
*/
void "call displayDateTime tag "() {
given:
String result = applyTemplate('<jdt:testCall p1="p1-string" p2="$now" />' , [now:LocalDateTime.now()])
when :
println "$result "
then:
result
}
}
What i'm trying to do is pass a LocalDateTime variable to the attrs map.
if you use applyTemplate and pass p2=ldt, and test map [ldt:LocalDateTime.now()]
the test fails saying the variable must be 'quoted
[Byte array resource [test_1549319950845]:1] Attribute value must be quoted (p1="p1-string" p2=now).
if you quote the p2 variable using p2="$ldt" and test map the sname as [ldt:LocalDateTime.now()], then the test will work - However the type passed to the attrs map is GStringImpl
however reading the OCI guide oci tag lib guide
it implies on page 4 that you can pass attrs.employees as a list of domainobjects and use that in you markup
but theres no way to invoke this using the testing as everything has to be string quoted - which makes it GStringImpl
how do you pass non string variable to a taglibs attrs map from appyTemplate (.. i presume the same restiction applies in live gsp and not just the testing framework )
hah! its such a small thing
if you change the test and write this
String result = applyTemplate('<jdt:testCall p1="p1-string" p2="${now}" />' , [now:LocalDateTime.now()])
with braces round the variable key name from the map - then the actual value of the typed variable is passed into the taglib. so if you look in the attrs.p2 value it has the actual LocalDateTime instance.
now quite sure how applytemplate is working not sure, but expecting its trying to do soemthing like groovy shell evaluate the string - hence the need to use single '' like '
Hope that makes sense
blimey enough to make your head explode sometimes

Modifying an object inside a class leads to an error

I am a beginner in Python and I am trying to understand trees better. Why can't I add nodes inside the function f below? I would expect that the final print returns the value 2 instead of an error that f(test) in None.
class Testcls(object):
def __init__(self,data):
self.data= data
self.children = []
def add_child(self,obj):
self.children.append(obj)
def f(test):
data1 = test.data+1
test.add_child(Testcls(data1))
test = Testcls(1)
print f(test).data
Final print in your case should actually return an error. Function f doesn't return anything (hence the None if you type print f(test). To add children using f you can add a return statement:
def f(test):
data1 = test.data+1
test.add_child(Testcls(data1))
return test
Which now returns the object test which you can further access and process,
f(test)
print test.children[0].data
Since it actually returns the test object you can also call it and use it directly:
print (f(test).children)[0].data
You don't have to have a return statement either - f will still change the object you're sending to it. In case you don't want to return the object, you just need to call the function separately and only then use test like shown in the second code snippet.

how to check if a variable is of type enum in python

I have an enum like this
#enum.unique
class TransactionTypes(enum.IntEnum):
authorisation = 1
balance_adjustment = 2
chargeback = 3
auth_reversal = 4
Now i am assigning a variable with this enum like this
a = TransactionTypes
I want to check for the type of 'a' and do something if its an enum and something else, if its not an enum
I tried something like this
if type(a) == enum:
print "do enum related stuff"
else:
print "do something else"
The problem is it is not working fine.
Now i am assigning a variable with this enum like this
a = TransactionTypes
I hope you aren't, because what you just assigned to a is the entire enumeration, not one of its members (such as TransactionTypes.chargeback) If that is really what you wanted to do, then the correct test would be:
if issubclass(a, enum.Enum)
However, if you actually meant something like:
a = TransactionTypes.authorisation
then the test you need is:
# for any Enum member
if isinstance(a, Enum):
or
# for a TransactionTypes Enum
if isinstance(a, TransactionTypes):
reliable solution:
from enum import IntEnum
from collections import Iterable
def is_IntEnum(obj):
try:
return isinstance(obj, Iterable) and isinstance (next(iter(obj)), IntEnum)
except:
return False # Handle StopIteration, if obj has no elements
I thought I`ve got a ugly way. eg:
print(o.__class__.__class__)
Output:
<enum.EnumMeta>
as mentioned use isinstance method to check weather an instance is of enum.Enum type or not.
A small working code for demonstration of its usage:
import enum
class STATUS(enum.Enum):
FINISHED = enum.auto()
DELETED = enum.auto()
CANCELLED = enum.auto()
PENDING = enum.auto()
if __name__ == "__main__":
instance = STATUS.CANCELLED
if isinstance(instance, enum.Enum):
print('name : ', instance.name, ' value : ', instance.value)
else:
print(str(instance))
Output:
name : CANCELLED value : 3
There are already good answers here but in case of it might be useful for some people out there
I wanted to stretch the question a little further and created a simple example
to propose a humble solution to help caller function who does maybe little knowledge about Enum
solve problem of sending arguments to functions that take only Enum
as a parameter by proposing a converter just below the file that Enum was created.
from enum import Enum
from typing import Union
class Polygon(Enum):
triangle: 3
quadrilateral: 4
pentagon: 5
hexagon: 6
heptagon: 7
octagon: 8
nonagon: 9
decagon: 10
def display(polygon: Polygon):
print(f"{polygon.name} : {polygon.value} ")
def do_something_with_polygon(polygon: Polygon):
"""This one is not flexible cause it only accepts a Polygon Enum it does not convert"""
""" if parameter is really a Polygon Enum we are ready to do stuff or We get error """
display(polygon)
def do_something_with_polygon_more_flexible(maybe_polygon_maybe_not: Union[Polygon, int, str]):
""" it will be more convenient function by taking extra parameters and converting"""
if isinstance(maybe_polygon_maybe_not, Enum):
real_polygon = maybe_polygon_maybe_not
else:
real_polygon = get_enum_with_value(int(maybe_polygon_maybe_not), Polygon, Polygon.quadrilateral)
""" now we are ready to do stuff """
display(real_polygon)
def get_enum_with_value(key: int, enum_: any, default_value: Enum):
""" this function will convert int value to Enum that corresponds checking parameter key """
# create a dict with all values and name of Enum
dict_temp = {x.value: x for x in
enum_} # { 3 : Polygon.triangle , 4 :Polygon.quadrilateral , 5 : Polygon.pentagon , ... }
# if key exists for example 6 or '6' that comes to do_something_with_polygon_more_flexible
# returns Polygon.hexagon
enum_value = dict_temp.get(key, None)
# if key does not exist we get None
if not enum_value:
... # if key does not exist we return default value (Polygon.quadrilateral)
enum_value = default_value # Polygon.quadrilateral
return enum_value

Python Dynamic Subclassing

Possible duplicates:
Is there a way to create subclasses on-the-fly?
Dynamically creating classes - Python
I would like to create a subclass where the only difference is some class variable, but I would like everything else to stay the same. I need to do this dynamically, because I only know the class variable value at run time.
Here is some example code so far. I would like FooBase.foo_var to be "default" but FooBar.foo_var to be "bar." No attempt so far has been successful.
class FooBase(object):
foo_var = "default"
def __init__(self, name="anon"):
self.name = name
def speak(self):
print self.name, "reporting for duty"
print "my foovar is '" + FooBase.foo_var + "'"
if __name__ == "__main__":
#FooBase.foo_var = "foo"
f = FooBase()
f.speak()
foobarname = "bar"
#FooBar = type("FooBar", (FooBase,), {'foo_var': "bar"})
class FooBar(FooBase): pass
FooBar.foo_var = "bar"
fb = FooBar()
fb.speak()
Many thanks
EDIT so I obviously have a problem with this line:
print "my foovar is '" + FooBase.foo_var + "'"
The accepted answer has self.foo_var in the code. That's what I should be doing. I feel ridiculous now.
What about this:
def make_class(value):
class Foo(object):
foo_var = value
def speak(self):
print self.foo_var
return Foo
FooBar = make_class("bar")
FooQux = make_class("qux")
FooBar().speak()
FooQux().speak()
That said, can't you make the value of foo_var be a instance variable of your class? So that the same class instantiated with different input behaves in different ways, instead of creating a different class for each of those different behaviours.

Covariance and Scala Collections

I'm trying to get my head around the covariance of Scala's collections. I have the following:
abstract class MediaFormat{
def name:String
def status:String
}
case class H264_high(status:String="on") extends MediaFormat {
def name = "h264_high"
}
case class H264_med(status:String="on") extends MediaFormat {
def name = "h264_med"
}
case class H264_low(status:String="on") extends MediaFormat {
def name = "h264_low"
}
case class H264_syndication(status:String="off") extends MediaFormat {
def name = "h264_syndication"
}
What I wanted to do was have a set of all of these formats because I need a collection where each format only occurs once, so I tried:
object MediaFormat {
val allFormats:Set[MediaFormat] = Set(H264_high,H264_low)
}
This gave me a compile time exception because, as I now understand, Set is invariant.
So I think, well I guess I'll just have to use a List and manage the repeated values myself
but then I try this:
object MediaFormat {
val allFormats:List[MediaFormat] = List(H264_high,H264_low)
}
because as I understand it, List is covariant, but that still doesn't compile.
Can someone help me understand what I should do to get a collection of my formats?
It doesn't compile because you are referencing the companion object (module), not the case classes! The compile error (which you should have posted) is nothing to do with variance. It will work, with Set if you do this:
val allFormats: Set[MediaFormat] = Set(H264_high(), H264_low())
^^ ^^
Or alternatively;
val allFormats = Set[MediaFormat](H264_high(), H264_low())
However, it makes no sense for these to be case classes given your description of the problem; I would just make them modules, i.e.
case object H264_syndication extends MediaFormat {
def status = "off"
def name = "h264_syndication"
}
Then your original code will work just fine. Or I would make them vals as follows:
case class MediaFormat(status: String, name: String)
val H264_syndication = MediaFormat(status ="off", name = "h264_syndication")
I think this would be my preference; I rarely use abstract classes any more to be honest (normally, I am dishonest).
Explanation: Covariance means the following:
G[S] <: G[T] iff S <: T
The fact that Set is invariant, means that a Set[S] is not a subtype of Set[T] (for S <: T), but it does not mean that such a Set[T] may not contain elements of type S.