mercredi 31 août 2016

FieldInfo.SetValue fails under certain circumatances

I am working on a QA testing framework for hardware devices tested by C# test programs. Part of running a compiled test is to use reflection on the compiled.exe to find where the Device-under-test (DUT) is declared in each test case and plug in the actual Framework-assigned device object.

Here is the heart of the code:

                    if (device.GetType().FullName.Equals(fi.FieldType.FullName))
                    {
                        try
                        {
                            fi.SetValue(tc, device);
                        }
                        catch (ArgumentException ex)
                        {
                            TestLogger.Warning(ex.Message);
                        }
                    }

In this code we already know from the first line that the 'device' is the same type as the field ('fi') in the test case ('tc').

Now the strange part: If the test case is in the same assembly as this code, everything is fine. If, however this code is part of a testing platform that loads the compiled test as an assembly, the call to SetValue() throws an ArgumentException with the message "Object of type 'X' cannot be converted to type 'X'" where X is the full name ofthe type of the device.

I have repeatedly searched both here and other sites for problem where SetValue() complained about inability to change one type to itself and the only instance I found involved serialization which is not a factor here.

QUESTION: What kind of problem could cause FieldInfo.SetValue() to balk like this when no conversion seems to be necessary?





Catch calls to decimal.ToString at compile time

I would like to catch all calls to decimal.ToString() in my solution. At compile time.

Is there any trick for this? like overloading ToString and using ObsoleteAttribute?

I can resolve to running a scan (by reflection) once a week through code like this or install and configure some sort of program with static code checking. But this question is about compile time.

The reason for this is that decimal.ToString is culture aware and which in my case might be trouble; i.e. if someone installs the solution on a localised server output might change.
We have a rule not to call decimal.ToString without making it CultureInvariant but it is not always heeded.





Spigot/Bukkit 1.10.2 Field Reflection returns NullPointerException without clear reason

  • Spigot: v1_10_R1
  • Java: 1.8.0_25 x64

Hello Guys, First I hope I dont get trouble because I post original code from Spigots intern copy of Minecraft-Server.

Ok said that now to the problem: I'm writing a plugin that hooks into the network packet system of mc-server to overwatch some packet traffic for learning reasons. Now is the problem that mojang declares all the fields inside a outgoing packet to private, so the only way to access it is via reflection. It works mostly fine but especially in the PacketPlayOutScoreboardScore class there are 2 fields that should be setted but reflection dont like them it returns 2 times a NullPointerException. here the fields out of the class PacketPlayOutScoreboardScore.

   private int c;

   private EnumScoreboardAction d;

I traced the call hirachy down to the function handleScoreChanged in ScoreboardServer where we cleary see the used constructor.

   public void handleScoreChanged(ScoreboardScore scoreboardscore)
   {
    super.handleScoreChanged(scoreboardscore);
    if (this.b.contains(scoreboardscore.getObjective())) {
      sendAll(new PacketPlayOutScoreboardScore(scoreboardscore));
    }
    b();
   }

   private void sendAll(Packet packet)
   {
     for (EntityPlayer entityplayer : this.a.getPlayerList().players) {
       if (entityplayer.getBukkitEntity().getScoreboard().getHandle() == this) {
         entityplayer.playerConnection.sendPacket(packet);
       }
     }
   }

If we now look at the constructor in PacketPlayOutScoreboardScore we see that the both variables should be setted. we assume that the getScore() method should return 10 because minecraft client shows the score 10 correctly so the value has to be there.

  public PacketPlayOutScoreboardScore(ScoreboardScore paramScoreboardScore)
  {
    this.a = paramScoreboardScore.getPlayerName();
    this.b = paramScoreboardScore.getObjective().getName();
    this.c = paramScoreboardScore.getScore();
    this.d = EnumScoreboardAction.CHANGE;
  }

    public static enum EnumScoreboardAction {

        CHANGE, REMOVE;

        private EnumScoreboardAction() {}
    }

to hook in I use a Class that extends PlayerConnection and replace both via reflection on PlayerJoinEvent

Listener

@EventHandler(priority=EventPriority.NORMAL,ignoreCancelled=false)
public void onJoin(PlayerJoinEvent event)
{
    EntityPlayer nmsplayer = ((CraftPlayer)event.getPlayer()).getHandle();

    FieldReflection f = new FieldReflection();
    try
    {
        f.hook("playerConnection", nmsplayer.getClass(), nmsplayer);
        f.set(new ConnectionWatchdog(nmsplayer.playerConnection));          
    } catch (Exception e)
    {
        e.printStackTrace();
    }



    event.getPlayer().setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
    event.getPlayer().getScoreboard().registerNewObjective("test", "dummy");
    Objective o = event.getPlayer().getScoreboard().getObjective("test");
    o.setDisplaySlot(DisplaySlot.SIDEBAR);
    o.setDisplayName("TEST");
    o.getScore("test1").setScore(10);
    o.getScore(" ").setScore(9);
    o.getScore("  ").setScore(8);

}

FieldReflection

public class FieldReflection
{
    public Field f;
    public Object object;

    public void  hook (String name, Class<?> c, Object obj) throws Exception
    {
        f = c.getDeclaredField(name);
        f.setAccessible(true);
        this.object = obj;
    }

    public void set(Object val) throws Exception
    {
        f.set(object, val);
    }

    public Object get() throws Exception
    {
        return f.get(object);
    }

    public int getInt() throws Exception
    {
        return f.getInt(object);
    }

}

ConnectionWatchdog

public class ConnectionWatchdog extends PlayerConnection
{

    public PlayerConnection old;

    public ConnectionWatchdog(PlayerConnection pc)
    {
        super(((CraftServer)Bukkit.getServer()).getServer(), pc.networkManager, pc.player);
    }

    public void sendPacket(Packet<?> p)
    {
        try
        {
            if(p instanceof PacketPlayOutScoreboardDisplayObjective)
            {
                System.out.println("\n \n \n");
                System.out.println("DisplayObjective");
                FieldReflection f1 = new FieldReflection();
                f1.hook("a", p.getClass(), p);
                System.out.println(f1.get());
                FieldReflection f2 = new FieldReflection();
                f2.hook("b", p.getClass(), p);
                System.out.println(f2.get());
            }

            if(p instanceof PacketPlayOutScoreboardObjective)
            {
                System.out.println("\n \n \n");
                System.out.println("Objective");
                FieldReflection f1 = new FieldReflection();
                f1.hook("a", PacketPlayOutScoreboardObjective.class, p);
                System.out.println(f1.get());
                FieldReflection f2 = new FieldReflection();
                f2.hook("b", PacketPlayOutScoreboardObjective.class, p);
                System.out.println(f2.get());
                FieldReflection f3 = new FieldReflection();
                f2.hook("c", PacketPlayOutScoreboardObjective.class, p);
                System.out.println(f3.get());
                FieldReflection f4 = new FieldReflection();
                f2.hook("d", PacketPlayOutScoreboardObjective.class, p);
                System.out.println(f4.get());
            }

            if(p instanceof PacketPlayOutScoreboardScore)
            {
                System.out.println("\n \n \n");
                System.out.println("Score");

                FieldReflection f1 = new FieldReflection();
                f1.hook("a", PacketPlayOutScoreboardScore.class, p);
                System.out.println(f1.get());
                FieldReflection f2 = new FieldReflection();
                f2.hook("b", PacketPlayOutScoreboardScore.class, p);
                System.out.println(f2.get());
                FieldReflection f3 = new FieldReflection();
                f2.hook("c", PacketPlayOutScoreboardScore.class, p);
                System.out.println(f3.getInt());
                Field f = PacketPlayOutScoreboardScore.getDeclaredField("d");
                f.setAccessible(true);
                System.out.println(f.get(p));
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        super.sendPacket(p);
    }

}

If anyone has an Idea what I do wrong(except of not simply using ProtocolLib or the stupid normal bukkit-api)please tell me! If you need any more information please tell me.

Thanks in advance,

picatrix1899





Reflection how to pass values to parameters based on getparameters and cast return object

i have class library with class

    namespace ReflectionCALlingproject
{
    public class Class1
    {
        public House GetResultsByReflection(int HouseNumb,int pincode)
        {
            House house = new House ();
            House.currentDay=DateTime.Now;
            return house;
        }

    }
}

i have to call this class dynamically at runtime and need to get the currentDay.

 public string test()
        {
     int HouseNumb= 31231123;
     int pincode= 124124124;
    string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"bin\ReflectionCALlingproject.dll");         
               Assembly assembly = Assembly.LoadFile(path);
               Type type = assembly.GetType("ReflectionCALlingproject.Class1");
                if (type != null)
                {
                    MethodInfo methodInfo = type.GetMethod("GetResultsByReflection");
                    if (methodInfo != null)
                    {
                    ParameterInfo[] parameters = methodInfo.GetParameters();
                   object classInstance = Activator.CreateInstance(type, null);

        object[] parametersArray = new object[] { HouseNumb, pincode};   //need to pass this values based on the parameterinfo.       
                        result = methodInfo.Invoke(classInstance, parametersArray );


                    }
                }
                return result.ToString();
//result is House object how can i get the property from it.
}

i have to pass the parameters based on the parameterinfo.

if am changing the calling method parameters it should work properly.

how can i pass values based on the parameterinfo.

how can i cast the result to the specified house class?





Easy method to make deep copies without [serializable]

I have a class that I want to make a deep copy off, however it contains many attributes some of which contains other attributes. Now normally we can use either a clone or serialize method such as seen in How do you do a deep copy an object in .Net (C# specifically)? in order to get a good copy. However in my case several of these attributes come from a library which did not mark anything as either serializable or clonable.

Anybody know how to fix this? Something with reflection? Something efficient?





scala create dynamic factory based on trait inharitance

I have several classes which extends a trait. I created a factory method that uses pattern matching in order to instantiate the relevant class.

The problem is that whenever I create a new class that extend this trait I need to add it to the factory method manually. is there an option to create the list of classes dynamically from all the classes available?

Thanks





iOS: How to know that Self is RawConvertable and responds to rawValue function?

guys!

I'm trying to make a protocol extension that will go through struct/class/enum and convert its properties/rawValue to NSData using Mirror.

These types can contain another structs/enums/classes which are conforming to DataConvertable protocol too, or just Uint8 and Uint16, which can be converted to NSData by data() function.

It looks ok for me for structs and classes, but I still have some problems with enums.

protocol DataConvertable {
    func data() -> NSData?
}

extension DataConvertable {
    func data() -> NSData? {
        let resultData = NSMutableData(capacity: sizeofValue(self))!
        let mirror = Mirror(reflecting: self)
        guard let displayStyle = mirror.displayStyle else { return nil }

        switch displayStyle {
            case .Enum:
                if let enumValue = self as? RawRepresentable {
                   resultData.appendData(enumValue.rawValue.data())
                }
            case .Struct, .Class:
                for case let(_, value) in mirror.children {
                    if let uint16Value = value as? UInt16 {
                        resultData.appendData(uint16Value.data())
                    } else if let uint8Value = value as? UInt8 {
                        resultData.appendData(uint8Value.data())
                    } else if let subValue = value as? DataConvertable {
                        resultData.appendData(subValue.data())
                    }
                }
            default:
                break
            }
            return NSData(data: resultData)
        }
    }

This line is not working.

if let enumValue = self as? RawRepresentable

How can I manage it? Do you have any ideas?

Thanks!





Set value to model class properties swift

I know I can get the list of class properties using Mirror(reflecting:) but I can only print them. But what if I want to set properties to them and return the mirrored object.
Somwhat like this -

    let mirroredObj = Mirror(reflecting: User())
                for (index, property) in mirroredObj.children.enumerate() {
                        property.value = <SOME_VALUE>
                    }
    return mirroredObj  

Or maybe some totally different approach to do this?





How to find potential points of NullReferenceException in a static code analyzer utility?

We're developing a static code analysis tool that aims at improving code via some hints.

We want to find places where developer has forgotten to check nullability of a variable or property or method return and has accessed the members via Dot Notation, because it might encounter NullReferenceException.

For example this code:

class Program
{
    static void Main(string[] args)
    {
        var human = new Human();
        if (human.Name.Length > 10)
        {
            // Jeez! you have a long name;
        }
    }
}

public class Human
{
    public string Name { get; set; }
}

We use Mono.Cecil and we find the body of all methods of all types in a given assembly, and for each method body we find the Instructions of it, and then we check for Callvirt operations. Yet that doesn't support this example:

class Program
{
    static string name;

    static void Main(string[] args)
    {
        if (name.Length > 10)
        {
        }
    }
}

How can we find all of the accesses to members (variable, field, property, method) of a given nullable type?





Exclude interface implementation members through reflection

I have the following Interface, and implementation:

public interface INew
{
    string TestString { get; }
}

public class PurchaseOrder : INew
{
    public string OrderNo { get; set; }

    public string TestString
    {
        get { return "This is a test string"; }
    }
}

I am trying to reflect out the OrderNo part of the PurchaseOrder object, using the following code:

var props = p.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.FlattenHierarchy);
foreach (var prop in props)
{
    Console.WriteLine(prop.Name);
}

My output is returning the TestString property also. I have searched for ways to exclude implemented interface members but can only find items to include it. Can anybody show me how i can exclude such items?





mardi 30 août 2016

Get all properties of class using reflection

Wants to retrieve all properties of class using reflection. Please find below example. When I retentive properties of MainClass, I want to have list of all properties of Person and Employee class.

I am having multiple objects just like MainClass. there could be N number of properties inside this class and i want to have list of all properties of the class. If property is object, in that case object's properties are required. I want to have a function for this which will accept dynamic model and will return all properties.

Please help.

public class Person
{
 public string FirstName { get;set; }
 public string LastName { get;set; }
 public string City { get;set; }
}

public class Employee
{
 public string EmpCode { get;set; }
 public string CompanyName { get;set; }
 public string DepartmentName { get;set; }
}

public class MainClass
{
 public Person PersonInfo { get; set; }
 public Employee EmployeeInfo { get; set; }
}





Can a ConstructorInfo have no DeclaringType

I was browsing the System.Linq.Expressions source code on GitHub and found the following code

public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments)
{
    ContractUtils.RequiresNotNull(constructor, nameof(constructor));
    ContractUtils.RequiresNotNull(constructor.DeclaringType, nameof(constructor));

    // ...
}

I was confused by the second null check, so went to MSDN. It had the following to say about ConstructorInfo.DeclaringType:

The DeclaringType property retrieves a reference to the Type object for the type that declares this member. A member of a type is either declared by the type or inherited from a base type, so the Type object returned by the DeclaringType property might not be the same as the Type object used to obtain the current MemberInfo object.

If the Type object from which this MemberInfo object was obtained did not declare this member, the DeclaringType property will represent one of its base types.

If the MemberInfo object is a global member (that is, if it was obtained from the Module.GetMethods method, which returns global methods on a module), the returned DeclaringType will be null.

So it seems that DeclaringType can be null for a MemberInfo (the class from which ConstructorInfo derives). But I am uncertain whether it can be null or not for ConstructorInfo.

So to my questions:

  1. Can ConstructorInfo.DeclaringType ever be null? Why is the System.Linq.Expressions code checking for it?

  2. If DeclaringType can be null, can you provide an example?

  3. If DeclaringType can be null, does this imply that the CLR supports global constructors? (I've tried researching this but can't find anything)





Java custom method annotation to access the runtime processed field inside the annotated method [duplicate]

This question already has an answer here:

I want to fire method foo(x) every time method bar(y) is called.

bar(y){
    x = 1 + y  
    return x*2
} 

foo(x) {
    httpPost(x)
}

My strategy is to:

@fireX
bar(y){
    x = 1 + y  
    return x*2
}

some how in runtime access x using reflections (may be) and then fire foo(x).

Possible? or is there is any other better way to do this differently than

bar(y){
    x = 1 + y 
    foo(x) 
    return x*2
}

Thanks in advance





Capture all runtime calls a wrapper library makes to an inner library in Python

I'm using a closed-source Python library that is mostly wrappers around objects from an open-source Python library. I want to capture the calls the closed-source wrapper is making into the open-source library as my program runs.

(I'm using Python 2.7 on Windows.)

The vendor distributes the conglomeration as *.pyd files, so there is no source code to read or modify. However the inner library objects are reachable at runtime by exposed wrapper object implementation details and Python reflection.

My basic idea is to monkey patch the module as it loads, and capture all method calls. However I'm not familiar enough with Python to know what details I should consider and what other techniques may be available to me.

  • Is there a Python library that does exactly this?
  • What about patching the Python interpreter (would that even have any effect on a pyd file?)
  • Does there exist something that runs a Python program and spits out a smaller/less depencies version of the program with just the code and data used during the run? (Something like Code Data and Environment for Python.)
  • Would a profiling tool or library help with this?
  • What about dumping the (runtime, Python) disassembly of the methods?




How to set property name using reflection in anonymous list?

So I have this query:

using (APContext _context = new APContext(null)) {
                var q = from inv in _context.Invoices
                        where inv.Sys_InvoiceID == 1276291
                        join cust in _context.InvoiceCustomFields
                        on inv.Sys_InvoiceID equals cust.FK_SysInvoiceID

                        select new {
                                inv.Sys_InvoiceID,
                                inv.AccountNumber,
                                cust.FK_CustomFieldHeader,
                                cust.Value
                        };
            }

Which returns something like so { 1, 50, "Badger", "Is Great"}

I would like to use the value of FK_customFieldHeader to set a property name in an anonymous list like so:

      var x = q.Select(r => new{
                    ID = r.Sys_InvoiceID,
                    AccountNum = r.AccountNumber,
                    //Reflection here to set CustomFieldHeader value as the property name and cust.Value to be the value for the property
                    r.FK_CustomFieldHeader = r.Value //Like this
        });

How do I do this?





FieldInfo.GetValue returns null

I have this piece of code:

FieldInfo fi = this.GetType().GetField(StringConstants.UNDERSCORE + phase, BindingFlags.Instance | BindingFlags.NonPublic);

    if (fi != null)
    {
        itemPhase = fi.GetValue(this) as IItemPhase;
    }

    if (itemPhase != null) 
    {
        _currentPhase = phase;
        _itemVo.Phase = phase;
        itemPhase.PreparePhase();
    }

FieldInfo fi gets correct value, so the field was found.

enter image description here

But FieldInfo.GetValue returns always null:

enter image description here

... and the Type matches:

enter image description here

Anyone knows why?





lundi 29 août 2016

Reflection: invoke method inside static field

Type type_class_a = ....;
Type type_class_b = type_class.GetField("name_b").FieldType;
MethodInfo method = type_nameb.GetMethod("method");
method.Invoke(type_class_b,new object[] {"test_string"});

in dll

public class class_a
{
    public static class_b name_b = new class_b();
}
public class class_b
{
    public void method(string data)
    {
    }
}

but i got error

An unhandled exception of type 'System.Reflection.TargetException' occurred in mscorlib.dll Additional information: Object does not match target type.

Then how to invoke it? Thankyou.





C# Read Summary Function

there is a way to read the summary of function automatically from another CS file? I explain - I have the method

void foo(int x); with Reflection I read the function name and his parameters but I also need to read his summary. The summary is XML style.

Thanks.





c# get property with specific attribute from list objects

Having List of objects:

List<ConfigurationObjectBase> ObjectRegistry;

Having below Attribute and some of the above objects' decorated with that Attribute:

[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
public sealed class PropertyCanHaveReference : Attribute
{
    public PropertyCanHaveReference(Type valueType)
    {
        this.ValueType = valueType;
    }

    public Type ValueType { get; set; }
}

Now, I want to find all objects whose property is decorated with that Attribute.

Trying below code, seems I am doing wrong:

List<ConfigurationObjectBase> tmplist = ObjectRegistry.Where(o => (o.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(PropertyCanHaveReference), true).Length > 0)));

Thanks for your time.





How to call static field method in static class using reflection

I gave this static class with Specifications:

public static class OperationSpecs
{

    public static ISpecification<TestEntity> TestSpec = new Specification<TestEntity>(
        o =>
        {

            return (o.Param1== 1 &&
                    o.Param2== 3 
                );
        }
    );

Specification implementation:

public class Specification<T> : ISpecification<T>
{
    private Func<T, bool> expression;
    public Specification(Func<T, bool> expression)
    {
        if (expression == null)
            throw new ArgumentNullException();
        else
            this.expression = expression;
    }

    public bool IsSatisfiedBy(T o)
    {
        return this.expression(o);
    }
}

How can I call TestSpec.IsSatisfiedBy(someType) using reflection ? I tried this:

            var specAttr = op.GetCustomAttribute<OperationSpecificationAttribute>();
            var specType = specAttr.SpecificationType;
            var specTypeMethodName = specAttr.SpecificationMethodName;
            var specField = specType.GetField(specTypeMethodName, BindingFlags.Public | BindingFlags.Static);

            if (specField != null)
            {
                var specFieldType = specField.FieldType;
                var result2 = specField.GetValue(null).GetType().GetMethod("IsSatisfiedBy").Invoke(null, new object[] { entity });
            }

I got ERROR when call Invoke Non-static method requires a target ... I need to get boolean result.. Thanks for Help!





Test if a property is an ICollection in Portable class library

iam trying to test if a property of my object is a collection or not but encounter problem since in portable class library many method are not avaible

this is my method:

public virtual bool Equals(TObject other) // where TObject : class
{
    if (other == null)
        return false;

    Type t = GetType();
    Type otherType = other.GetType();

    TypeInfo typeInfo = t.GetTypeInfo();            

    if (t != otherType)
        return false;

    IEnumerable<FieldInfo> fields = typeInfo.DeclaredFields; 
    foreach (FieldInfo field in fields)
    { ...

now i have to test if field is an Icollection or not but

  • ImplementedInterfaces is not avaible
  • IsAssignableFrom is not avaible
  • GetInterfaces() is not avaible
  • GetGenericTypeDefinition() is not avaible

maybe this is because i have FieldInfo and not TypeInfo?

is there something i can do?





Cast FieldInfo to list in C#

I have string array like this:

namespace DynamicCore
    {
        public class DynamicCode
        {
            List<Variable> variableList = new List<Variable>();
            public DynamicCode()
            {
                Variable Variable = new Variable();                    
                Variable.ID = "Variable_26545789";
                Variable.Type = 1;

                variableList.Add(Variable);

                Variable = new Variable();
                Variable.ID = "Variable_vdvd3679";
                Variable.Type = 2;

                variableList.Add(Variable);
            }
        }
    }

I compiled this array and store it to memory. I get variableList by this code:

string name = "DynamicCore.DynamicCode";
Type type = results.CompiledAssembly.GetType(name, true);
object instance = Activator.CreateInstance(type);    
FieldInfo filed = type.GetField("variableList", 
                                 BindingFlags.Instance | 
                                 BindingFlags.NonPublic);

I try to cast filed(variableList) to List<Variable> like this:

List<Variable> Variables = (List<Variable>)filed;

But I got this error:

Cannot convert type 'System.Reflection.FieldInfo' to 'System.Collections.Generic.List<Variable>'    

It would be very helpful if someone could explain solution for this problem.





C# find generic Interface implemented classes and create objects

I have a message handler class.

public interface IMessageHandler<in TMessage> where TMessage: IMessage
{
    void Handle(TMessage message);
}

And I want to select all classes that implements IMessageHandler<> interface and create instance of that class. Then I will call the handle method.





c# - Get all properties marked with [JsonIgnore] attribute

I have a class MyClass with a list of properties.

public class MyClass
{
    [Attribute1]
    [Attribute2]
    [JsonIgnore]
    public int? Prop1 { get; set; }

    [Attribute1]
    [Attribute8]
    public int? Prop2 { get; set; }

    [JsonIgnore]
    [Attribute2]
    public int Prop3 { get; set; }
}

I would like retrieve properties that are no marked with [JsonIgnore] attribute.

JsonIgnore is an attribute by http://ift.tt/1JSZVlU

So, in this example, I would like to have the property "Prop2".

I tried with

var props = t.GetProperties().Where(
                prop => Attribute.IsDefined(prop, typeof(JsonIgnore)));

or

var props = t.GetProperties().Where(
                    prop => Attribute.IsDefined(prop, typeof(Newtonsoft.Json.JsonIgnoreAttribute)));

where t is the type of MyClass but the method return 0 elements.

can you help me, please? Thanks





Is it possible to get the reflection of the recursive private static method?

I have some class

class Test {
    static private function someFunc(&$item) {
        $order = 0;
        foreach($item as &$folder) {
            $_folder['order'] = $order;
            $order += 1;
            if (isset($folder['value'])) {
                 static::someFunc($folder['value']);
            }
        }
    }
}

and I need to get reflection of this class for unit test

$func = new ReflectionMethod('Test', 'someFunc');
$func->setAccessible(true);

But what to do with the recursion? Is this possible change this line:

static::someFunc($folder['value']);





dimanche 28 août 2016

How to reflect.New a slice and reflect.AppendSlice it to a source slice

I want to reflect.New an []interface like []int and append it into another slice.

My code must have an error, but I don't know how to make it right and how to understand deeply the reflect.New and reflect.AppendSlice usage.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var a []int
    var value reflect.Value = reflect.ValueOf(&a)


    if !value.CanSet() {
        fmt.Println("go here", value.CanSet())
        value = value.Elem() 
        fmt.Println("go here", value.CanSet())  
    }
    fmt.Println("go here", value.Type())    
    s := reflect.New(value.Type())
    fmt.Println("go here", s.Elem())
    value = reflect.AppendSlice(value, reflect.ValueOf(s.Elem()))
    value = reflect.AppendSlice(value, reflect.ValueOf([]int{1, 2}))                
    value = reflect.AppendSlice(value, reflect.ValueOf([]int{3, 4, 5, 6, 7, 8, 9})) 

    fmt.Println(value.Kind(), value.Slice(0, value.Len()).Interface())
    //>>slice [1 2 3 4 5 6 7 8 9]
}

But it gives an error:

panic: reflect: call of reflect.AppendSlice on struct Value

goroutine 1 [running]:
panic(0x100a60, 0x1040e1a0)
    /usr/local/go/src/runtime/panic.go:500 +0x720
reflect.flag.mustBe(0x99, 0x17)
    /usr/local/go/src/reflect/value.go:201 +0xe0
reflect.AppendSlice(0xfa7e0, 0x1040e130, 0x197, 0x1116a0, 0x1040e190, 0x99, 0x0, 0x0, 0x0, 0x2)
    /usr/local/go/src/reflect/value.go:1825 +0x60
main.main()
    /tmp/sandbox476529744/main.go:21 +0x800

golang playground





get field of constructor by reflection in C#

I have a string array like this:

namespace DynamicCore
    {
        public class DynamicCode
        {
            public string ProcessName { get; set; }
            public DynamicCode()
            {
                List<Variable> variableList = new List<Variable>();
                Variable Variable = new Variable();

                Variable.ID = "Variable_26545789";
                Variable.Name = "var1";
                variableList_Process_1.Add(Variable);

                Variable = new Variable();

                Variable.ID = "Variable_vdvd3679";
                Variable.Name = "var2";    

                variableList_Process_1.Add(Variable);
            }
        }
    }

I compiled it using CompileAssemblyFromSource like this (GetCode gets string array) and store class in Memory:

CompilerResults results = provider.CompileAssemblyFromSource(parameters, GetCode());

I need to get variableList and show Variable.Name items in a listbox. I tested GetFields and GetProperty but none was not working properly.

It would be very helpful if someone could explain solution for this problem.

Thanks.





C# Reflection inconsistency with COM objects

Having spent the last few days reading everything I can find about C# reflection on COM objects, trying many experiments in code, and analyzing sample code to try and improve my understanding, I am now forced to admit that I just don't know enough, so I am requesting help from the Community.

I need to be able to access and update the properties of a late bound COM object that is wrapped as System._COMObject. I tried all the standard refection stuff without success and I looked through using IDispatch, but I'm not comfortable with using the pointers involved, so I'm hoping I have missed something pretty simple in the normal interface. I found papers on MSDN that DO show how to do what I need, but all the examples are in C++ and it is over my head.

It would be really helpful if someone could explain why the following simple C# code just doesn't work as expected:

            try
        {
            // late binding:
            // localCB is a COM object (System._COMObject) created by Activator.CreateInstance() from 
            // the ProgID of a registered COM .DLL. 
            // 
            // The original .DLL has a string PROPERTY called 
            // "TESTEXTERNAL1". localCB has an IDispatch Interface.  The original COM .DLL has a separate Typelib,
            // and, although I did not register the typelib separately, I can see from OLEView on the COM object
            // that  the GUID for the typelib is included in it.

            // Here's the code that is puzzling me...
             var vv = localCB.GetType().InvokeMember("TESTEXTERNAL1", BindingFlags.GetProperty, 
                  null, localCB, null);
            string rt = vv.ToString();
            // works exactly as expected and returns the value of TESTEXTERNAL1 -  OK.

            // now try and update the SAME PROPERTY, on the SAME COM object...
            Parameters = new Object[1];
            Parameters[0] = "Hello, World!";
            localCB.GetType().InvokeMember("TESTEXTERNAL1", BindingFlags.SetProperty, 
                  null, localCB, Parameters);
            // throws an (inner) exception: HRESULT 0x8002003 DISP_E_MEMBERNOTFOUND !!!

        }
        catch (Exception xa)
        {
            string xam = xa.Message;
        }

Is it unreasonable to expect an object that has already found and provided a property, to be able to update the same property? Is there some "alternative update" strategy that I am not aware of?

Many thanks for any help,

Pete.





samedi 27 août 2016

How to get closure argument names from function body?

How to get closure argument names in function body?

function Closure($id, $name)
{
    //I want get 'id' and 'name' here.
}





How can i use images from my drawable folder in my .java file in andriod studio?

I would like to use the images from my drawable file in my .java file. do i need to make a new file instance or something? if so, how do you do that?





Can a line of Python code know its indentation nesting level?

From something like this:

print(get_indentation_level())

    print(get_indentation_level())

        print(get_indentation_level())

I would like to get something like this:

1
2
3

Can the code read itself in this way?





Overview of quasiquotation in Idris

I hadn't realised that Idris has a quasiquotes until I came across some tests in the test suite.

Here's a short example in the REPL:

Idris> :module Language.Reflection
Idris> `(S Z)
App (P (DCon 1 1)
       (NS (UN "S") ["Nat", "Prelude"])
       (Bind (MN 0 "_t")
             (Pi (P (TCon 0 0) (NS (UN "Nat") ["Nat", "Prelude"]) Erased)
                 (TType (UVar "./Prelude/Nat.idr" 22)))
             (P (TCon 0 0) (NS (UN "Nat") ["Nat", "Prelude"]) Erased)))
    (P (DCon 0 0)
       (NS (UN "Z") ["Nat", "Prelude"])
       (P (TCon 0 0) (NS (UN "Nat") ["Nat", "Prelude"]) Erased)) : TT

I'd like to understand what that's all about. A brief overview and/or some references would be appreciated!





Get the method name and class of the callee's previous call

I am working on generating profiling data at various points in my code. For this purpose I have written a profiler like this :

public static void startProfiler() {
    startLineNumber = getCallersLineNumber();
    start = System.currentTimeMillis();
}

public static void endProfiler() {
    end = System.currentTimeMillis();
    endLineNumber = getCallersLineNumber();
    int startPoint = Integer.parseInt(startLineNumber.split(":")[1]);
    long secs = (end - start) / 1000;
        LOG.info(startLineNumber.split(":")[0] + ":" + (startPoint + 1) + " " + secs);
    start = 0;
    end = 0;
}

public static String getCallersLineNumber() {
    StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
    String fullClassName = stacktrace[3].getClassName();
    String[] packageName = fullClassName.split("\\.");
    String className = packageName[packageName.length - 1];
    String methodName = stacktrace[3].getMethodName();
    int lineNumber = stacktrace[3].getLineNumber();
    return className + ":" + lineNumber;
}

This prints the name of the caller method's class and the lineNumber of the call.

Eg : For method in class

import xyz.abc;
class foo {
     public static foo() {
           abc a = new abc();
           startProfiler();
           a.getData();
           endProfiler();
     }
}

The output would be :

foo:6 10

I instead want it to print :

xyz.abc.getData() 10

This would mean I want the method name of the callee (class foo)'s call before the endProfiler was called (which is the method call a.getData()). Is this possible to get this using stacktraces/reflection or other means?





What is the difference between Proxy constructor and Reflect?

Is there any significant difference between Reflect and Proxy?

From what is documented, it seems that they have pretty much the same capabilities, apart from:

If list above sums up all the differences, the what is the rationale for having both?





Get the methodName and className from a line of code

I am writing a parser that takes as an input a file like :

Testabc:10 20
Testxyz:100 30

This file is the format ClassName:LineNumber TimeTakenToExecute it. My parser takes a bunch of these files and gets the method called at ClassName:LineNumber and outputs another file of the format :

Say line 9 and 10 of Testabc looks like :

Utils utils = new Utils();
utils.getName()

then the output of my parser should be :

Utils.getName() 20
Manager.getPassword() 30

I can get the string attached to the line in a class (i.e from Testabc:10 I can get utils.getName()).

I can also get a list of methods in my code directory and map it to a class (Eg map : getName:Utils). But it will not work for duplicate method names/overridden methods/classes that extend interfaces (In this case I want the method to show the implemented class name and not the interface name).

Is there any way I can get this information through reflection? i.e., get the class name and method name from a line of code?





vendredi 26 août 2016

call a java method using runtime.exec()

In my java code there is class A that has the following line:

Process localProcess = Runtime.getRuntime().exec(myString);

where myString is user supplied input and is passed to exec() at runtime.

Also there is a public method doSomething() in class A.

Can I somehow invoke doSomething() (through reflection, jdwp etc.) using exec() at runtime ?





How do I find objects of a certain type in a Class in C#?

I am going to assume that I have to use System.Reflection. However when I want to build an list of type A that have been defined before, how would I build that list?

public TypeA foo;
System.Attribute.GetCustomAttributes?

I'm not really sure how to better phrase the question. I'm just looking to build a list of all the TypeA occurrences in my class.

Thanks!





How check if type is class?

In .Net we have Type.IsClass to check if a type is a class using System.Reflection.

But in .Net Core no. So, how can I check?





IsGenericType missing from .Net Core?

I have this code in .Net 4.6.2 and now trying to convert into .Net core however I am getting error

Error CS1061 'Type' does not contain a definition for 'IsGenericType' and no extension method 'IsGenericType' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)

public static class StringExtensions
{
    public static TDest ConvertStringTo<TDest>(this string src)
    {
        if (src == null)
        {
            return default(TDest);
        }           

        return ChangeType<TDest>(src);
    }

    private static T ChangeType<T>(string value)
    {
        var t = typeof(T);

        // getting error here at t.IsGenericType
        if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            if (value == null)
            {
                return default(T);
            }

            t = Nullable.GetUnderlyingType(t);
        }

        return (T)Convert.ChangeType(value, t);
    }
}

What is equivalent in .Net Core?





Converting between struct types in Go

So I have a question that I've been trying to figure out for a while and hopefully someone has some insight. Basically, I have two similar, but different structs in Go and I would like to convert between them.

Something like the following:

type A struct {
    Name string
}

type B struct {
    Name NameStruct
}

type NameStruct struct {
    Firstname string
    Lastname string
}

In this example,

B.Name == NameStruct{
              Firstname: strings.Split(A.Name, " ")[0],
              Lastname:  strings.Split(A.Name, " ")[1],
          }

Basically I would like to be able to define a mapping of fields from one struct to the other as well as a conversion function, so that I can do this without writing all of the code to do the conversion manually.

What I'm imagining is that there might be some sort of Go generator out there that could do something like this. I don't think it is possible using reflection because of the nested structs (although I'm open to suggestions).

Basically, does anyone know of a way to do this that is better than either writing conversion code manually or creating my own generator?





Getting a property just by providing a string name [duplicate]

This question already has an answer here:

looking for hours now on this particular question, I hope you can help. Following class hierachy is given:

public class Toon 
{
 public Skillset skillset;

 public Toon()
 {

    skillset = new Skillset();
 }
}

public class Skillset 
{
    public Skill Fight;
    public Skill Trade;
    public Skill Talk;


   public Skillset()
   {
        Fight = new Skill() { name = "Fight", value = 10 };
        Trade = new Skill() { name = "Trade", value = 12 };
        Talk = new Skill() { name = "Talk", value = 15 };
   }

}

public class Skill
{ 
    public string Name;
    public int Value;
    public int Rank

} 

This is to provide the Syntax of Toon.Skillset.Fight etc.

Now the question: I want to be able to randomly increase Skills, if they are in the favorites list, which is a List.

So basicly:

public void setSkill(string skillname, Toon toon, int value)
{
  => get property and set it to value
}

so that

setSkill("Fight", NewToon, 30); would set Toon.Skillset.Fight to 30.

I hope I could explain clear enough, and I'm thankful for any input. I heard of Reflection to solve this problem nicely, but I found no answer yet.

PS: just getting a List in Toon wouldn't help, it destroys the syntax.





PropertyInfo.GetProperty returns null when it shouldn't

I'm trying to get the value of a private property of a WPF WebBrowser object. I can see in the debugger that it has a non-null value.

PropertyInfo activeXProp = Browser.GetType().GetProperty("ActiveXInstance", BindingFlags.Instance | BindingFlags.NonPublic);
object activeX = activeXProp.GetValue(Browser, null); // here I get null for the activeX value
activeX.GetType().GetProperty("Silent").SetValue(activeX, true); // and here it crashes for calling a method on a null reference...

My guess is I'm not using reflection in a proper way, but what is the proper way to do it in this case?





Initialize a POJO dynamically from another method

Let's say I have these set of POJO class that implement an interface but there are no common attributes here.

public interface MainIfc {}

class Ifc1 implements MainIfc {
    private String a1;
    public String getA1() {
        return a1;
    }
    public void setA1(String a1) {
        this.a1 = a1;
    }
}

class Ifc2 implements MainIfc {
    private String x1;
    private String x2;
    public String getX1() {
        return x1;
    }
    public void setX1(String x1) {
        this.x1 = x1;
    }
    public String getX2() {
        return x2;
    }
    public void setX2(String x2) {
        this.x2 = x2;
    }
}

And in conjunction with these POJO classes I have a couple of methods which I can use to retrieve the type of POJO being returned based on another value and the actual POJO with values.

public class GetIfc {
    public Class getIfcType(int code) {
        if (code==1)
            return Ifc1.class;
        else
            return Ifc2.class;
    }
    public MainIfc getIfc(int code) {
        if (code==1) {
            Ifc1 thisIfc = new Ifc1();
            thisIfc.setA1("Ifc1");
            return thisIfc;
        } else {
            Ifc2 thisIfc = new Ifc2();
            thisIfc.setX1("Ifc2");
            thisIfc.setX2("Ifc2");
            return thisIfc;
        }
    }
}

Is there a way using which I can read the concrete POJO safely in my code and use the getters/setters? I have gone through quite a few questions which provide answers based on Reflection but that isn't working for me. The getters/setters aren't visible and when I call .getClass() on the returned Object I see it is the MainIfc interface.





PHP: ReflectionMethod::invokeArgs() - Incomplete exception trace

I use PHP's ReflectionMethod::invokeArgs() to call a static class method.

The called method may throw exceptions at different positions in the code.

When an exception is thrown, the trace of the exception object ends with the name of the called method and I don't know at which line the exception was actually thrown.

Example:

class A
{
    public static function methA()
    {
        $RC = new ReflectionClass('A');
        $M  = $RC->getMethod('methB');

        return $M->invokeArgs(null, ['arg']);
    }

    public static function methB($arg)
    {
        //some code
        throw new Exception('Exception thrown');
    }
}

try
{
    A::methA();
}
catch(Exception $e)
{
    print_r($e->getTraceAsString()[0]);
}

Output:

Array
(
    [function] => methB
    [class] => A
    [type] => ::
    [args] => Array
        (
            [0] => arg
        )

)

What I miss is the file / line where the Exception was thrown. Instead the last entry contains just the name of the method.

Is there any other way to get that information without providing it via the exception message?





How to add an object to a generic list property of an instance of a class using reflection

I have a class structure below. I am getting this error. Am i missing something here?

Object does not match target type.

Class Structure

public class Schedule
{
    public Schedule() { Name = ""; StartDate = DateTime.MinValue; LectureList = new List<Lecture>(); }
    public string Name { get; set; }
    public DateTime StartDate { get; set; }
    public List<Lecture> LectureList { get; set; }
}

public class Lecture
{
    public string Name { get; set; }
    public string Credit { get; set; }
}

What i am trying:

Schedule s = new Schedule();
Type t = Type.GetType("Lecture");
object obj = Activator.CreateInstance(t);
obj.GetType().GetProperty("Name").SetValue(obj, "Math");
obj.GetType().GetProperty("Credit").SetValue(obj, 1);
PropertyInfo pi = s.GetType().GetProperty("LectureList");
Type ti = Type.GetType(pi.PropertyType.AssemblyQualifiedName);
ti.GetMethod("Add").Invoke(pi, new object[] { obj });





jeudi 25 août 2016

my Class.forName is giving som issue in java 8

package designpattern.Singelton;

import java.lang.reflect.Constructor;

public class ReflectionIssueSingelton {

    public static void main(String[] args) throws Exception {
        Singelton s1 = Singelton.getInstance();
        Singelton s2 = Singelton.getInstance();

        print("s1", s1);
        print("s2", s2);
    }

    //Reflection

    //Load the class to be reflect
    @SuppressWarnings("unchecked")
    Class clazz =  Class.forName("designpattern.Singelton.Singelton");

    //getting degault declared constructor i.e default constructor
    Constructor<Singelton> ctor = clazz.getDeclaredConstructor();
    ctor.setAccessible(true);
    Singelton s3 = ctor.newInstance();


    private static void print(String name, Singelton object) {
        System.out.println(String.format("Object: %s, Hashcode: %d", name, object.hashCode()));

    }

}

enter image description here





Casting Using a Variable of Type 'Type' Instead of Type Name

First I should mention it seems like this will be a duplicate, but I can't seem to find the question pertaining to this specific problem. I only found close ones that don't address this specific approach and are thus not useful.

Consider this scenario where I'd like to cast something to a type. I might do something like one of these:

var foo = GetInstanceOfSomeUnknownType();
var cast1 = (MyCustomType)foo;
var cast2 = foo as MyCustomType;

Not let's consider what to do if, for whatever reason, we can't directly cast using the name MyCustomType. The below doesn't work:

var foo = GetInstanceOfSomeUnknownType();
var bar = "Whatever.";
Type someType = foo.GetType();
var cast1 = (someType)bar;
var cast2 = bar as someType;

In essence, you can do these sorts of casts using the type name, but not with a Type variable representing that type. I'd like to cast something using a Type object of the type I want to cast to instead of its name. Is there a way around this?





Return value of property from object and property name

Given an object and the name of a property, I'm trying to use reflection to get the value of that property. I've seen several threads here that are getting me close, but I'm not nailing it just yet. I happen to know that the value will be of type string.

public string GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(????);
}





Insert record to the table using entity framework

I have an Entity DbContext object which has a table called 'Employees'. I have employee object which I want to insert to Employees tables. I cannot use the Employees directly from the context. Want to access with the table name. is this possible ?

 MyContext _ctx;
 Type employee = a.GetType("SC.Employee"));
 object employee =Newtonsoft.Json.JsonConvert.DeserializeObject(emp, employee);
 using (_ctx=new MyContext())
 {
     //I am trying to insert the employee object to my entity. But this doesn't work
     //_customCtx.Employees.add(employee)
 }





reflect call MediaScanner.scanDirectories() throw InvocationTargetException

all my code is like below:

public void mediaScan(View source) {
    String[] path = new String[]{"/storage/F0E9-334E/Wildlife.wmv"};
    try {
        Button button = (Button) findViewById(R.id.my_btn);
        Class<?> mediaScannerClass = Class.forName("android.media.MediaScanner");
        Object mediaScanner = mediaScannerClass.getConstructor(Context.class).newInstance(this);
        Method scanDirectoryMethod = mediaScannerClass.getMethod("scanDirectories",
            path.getClass(), String.class);
        scanDirectoryMethod.invoke(mediaScanner, path, "external");//this line throw a InvocationTargetException everytime***
    } catch (Exception e) {
        e.printStackTrace();
        if (e instanceof InvocationTargetException) {
            Throwable targetEx = ((InvocationTargetException) e).getTargetException();
            if (targetEx != null) {}
        }else{}
    }

Every time call scanDirectoryMethod.invoke(mediaScanner, path, "external") will catch a InvocationTargetException like

java.lang.SecurityException: Permission Denial: 
reading com.android.providers.media.MediaProvider uri content://media/external/file?limit=1000 from pid=6587, uid=10105 
requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()

I've add the permission in AndroidManifest.xml like below,but it help nothing.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

Anyone could help me out ? Thanks





Design pattern to use for Null check through Reflection

What we are doing - Annotation driven null and empty values check for Object.

How we are doing - Creating one annotation and putting that annotation on the variable declaration.

I am not sure what design pattern i need to use to make it work best. Please suggest.





mercredi 24 août 2016

Java Reflection: Can't get to reach a class method

This is my first post here and I'll try to be short and specific.

I have the class Neuron, which contains a private field Class<? extends ActFunction> function; Whenever I create one of these Neurons, I pass to the constructor a subclass of ActFunction to be assigned to that field, all of the ActFunction subclasses have the method activate(double[] values), but when I try to invoke the method inside my Neuron by doing this:

Method activate = this.function.getClass().getMethod("activate");
return (double) activate.invoke(this, inputs);

it says that the method couldn't be found.

What am I doing wrong here? I'm not really an expert of reflection so I guess I'm missing some basic knowledge here.





How to convert json object to QObject?

Json structure is C++ struct-like (struct or array of sturcts, arrays and basic types). I need to convert JSON object to specified QObject with specified properties (by QObject fields).

For example, the json:

{
  "name": "Andrew",
  "age" 33,
  "identifiers": [32, 45, 67, 78],
  "more": {
     "gps": "44.9064', W073° 59.0735'",
     "valid": true
  }
}

QObjects:

class FMoreInfo : public QObject {
   Q_OBJECT

   Q_PROPERTY( QString gps );
   Q_PROPERTY( bool valid );
}

class FPersonInfo : public QObject {
   Q_OBJECT

   Q_PROPERTY( QString name );
   Q_PROPERTY( int32 age );
   Q_PROPERTY( QVector<int32> identifiers );
   Q_PROPERTY( FMoreInfo more );

}

JSON is a string and I need convert it by one template function to FPersonInfo. Is there known algorithms?





Invocation Handler does not modify object array?

I have used Invocation handler for reflection. and in findApiKeys method, I am trying to modify the value of args array. but its not changing the value. its giving me same value.

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String apiKey = findApiKey(args);
            if (cache.get(method.getName()) != null) {
                ServicesCacheKey cacheKey = new ServicesCacheKey();
                Map<String, Object> parameters = new HashMap<>();
                cacheKey.setApiKey(apiKey);
                parameters.put(PARAMETERS_KEY, args[0]);
                cacheKey.setParameters(parameters);
                return cache.get(method.getName()).get(cacheKey);
            } else if (multiMap.get(method.getName()) != null) {
                Set<ServicesCacheKey> servicesCacheKeys = getCacheKeySetFromArgList((Set<Object>) args[0], apiKey);
                Map<ServicesCacheKey, Object> result = multiMap.get(method.getName()).getAll(servicesCacheKeys);
                return getResultMapFromCacheKeyMap(result);
            } else {
                return i1.invoke(proxy, method, args);    // **problem here**
            }
        }

private String findApiKey(Object[] args) {
    for (int i = 0; i < args.length; i++) {
        Object arg = args[i];
        if (arg instanceof String) {
            String k = (String) arg;
            int index = k.indexOf("apiKey~~");
            if (index != -1) {
                String apiKey = k.substring(index + "apiKey~~".length());
                args[i] = apiKey;
                return apiKey;
            }
        }
    }
    throw new IllegalArgumentException("Api Key must not be empty");
}

stacktrace :

2016-08-24 03:54:33,849 [vli13:39922] [P7000] ERROR arch.service.thrift.SearchImpl - Invalid Request to dependencies services: null, Reason: Provided API key {apiKey~~solr} is not authorized to access experiment service. Please talk to service administrator to obtain a valid api key

Same code is working without reflection api

example:

public static void main(String[] args) throws InterruptedException {
    Object[] argss = new Object[] {"Pankaj", "api~~solr"};
    findApiKey(args);
    System.out.println(argss[0] + " " + argss[1]);
}

output : pankaj solr





LIbSVM of Weka in C# with IKVM

I am using the weka machine learning library in C# with IKVM. So far it worked very well, however, I am having problem using the libSVM package.

The problem appears when I want to instantiate the libsvm classifier in C# (the class is not found), as it is advised:

AbstractClassifier classifier = (AbstractClassifier)java.lang.Class.forName("weka.classifiers.functions.LibSVM").newInstance();     

What I tried:

  • Add the the libsvm.dll and weka.dll to the project (converted from libsvm.jar and weka.jar)
  • Merge libsvm.jar and weka.jar into one dll and add it to the project (using ikvm or ilmerge)

Note that the package is installed since it appears in the result of

WekaPackageManager.getInstalledPackages();

Has anyone every succeeded using Weka with LibSVM in C# using IKVM?

Thanks, Botond





mardi 23 août 2016

How to find field annotations for a MethodSymbol

Suppose that have a found a set of methods for a Type:

case class X()

object A{
   @someannotation
   val x=X()
}

def toType[T](a:T)(implicit tag: TypeTag[T]): Type = tag.tpe

val typ = toType(A)

// Get the public methods that return an X
val intMethods = typ.members.collect{ case m: ru.MethodSymbol if 
   m.isGetter && m.isPublic && m.returnType <:< typeOf[X]  => m }

How would I efficiently find the corresponding annotations for each element of intMethods?

intMethods.head.annotations

is empty because there are two entries in typ.decls for x. One is the found method and the other is the non-method field that holds the annotations. I can search by matching on:

getAnnotations(intMethods.head.toTerm.name.toString.trim)

def getAnnotations( name: String) ={
  typ.decls.filter{ s=>s.name.toString.trim==name.trim && !s.isMethod}.flatMap(_.annotations)
}

but all that toStringing and trimming is extremely slow (the trim is required because, one of the decls contains a trailing space, and the other not). Is there a better way to directly lookup a corresponding class field from a MethodSymbol?





Check if an object is an instance of class meta type in Swift

I have an array of objects of various types and an array of types. For each object, I'd like to iterate over the array of types and see if the object is that type. Something like this:

class Parent {}
class ChildA: Parent {}
class ChildB: Parent {}
class GrandChildA: ChildA {}

var objects: [Any] = ["foo", ChildA(), ChildA(), ChildB(), GrandChildA()]
var classes = [Parent, ChildA, ChildB] // This line doesn't compile!!

for obj in objects {
    for cls in classes {
        if obj is cls {
            NSLog("obj matches type!")
        }
    }
}

This doesn't work because you can't store classes in an array. As I understand, you can store class types such as ChildA.self:

ChildA().dynamicType == ChildA.self // true

But this doesn't handle subclasses:

ChildA().dynamicType == Parent.self // false

Obviously the is operator solves the subclass case:

ChildA() is Parent // true

But if I want to use is, I don't know how to store the class types in an array.

Can I accomplish what I want somehow using Swift and some reflection voodoo?

Sorry if the title is misleading -- I don't understand this well enough to form a proper question.





Set DependncyProperty from reflection in wpf - type convertion

I have some fun with WPF and I decided to build a library with custom implementation of attached triggers (similar to System.Windows.Interactivity.dll), but my own. I have a class TriggerAction which represents an action invoked by Trigger. I want to begin with something really easy like setting the background of the button while the user click it. I have already written some working code for example EventTrigger class, but I have one problem with my SetterTriggerAction. I have two dependency properties PropertyName which represents the name of property which should be set an a Value property. In the Invoke method I try to set property with a defined value. Here is the code:

internal override void Invoke(DependencyObject obj)
    {
        if (obj == null) return;
        if (string.IsNullOrEmpty(PropertyName)) return;
        PropertyInfo property = obj.GetType().GetProperty(PropertyName, BindingFlags.Public | BindingFlags.Instance);
        if (property == null)
        {
            Debug.WriteLine("Cannot find property {0} for type {1}.", PropertyName, obj.GetType());
            return;
        }
        MethodInfo setMethod = property.GetSetMethod();
        if (setMethod == null)
        {
            Debug.WriteLine("The property {0} does not have set method.", PropertyName);
            return;
        }
        try
        {
            setMethod.Invoke(obj, new object[] { Value });
        }
        catch(Exception ex)
        {
            Debug.WriteLine("Exception caught {0} with message {1}", ex.GetType(), ex.Message);
        }
    }

My second attempt:

internal override void Invoke(DependencyObject obj)
    {
        if (obj == null) return;
        if (string.IsNullOrEmpty(PropertyName)) return;
        FieldInfo property = obj.GetType().GetField(PropertyName+"Property", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
        if (property == null)
        {
            Debug.WriteLine("Cannot find dependency property {0} for type {1}.", PropertyName+"Property", obj.GetType());
            return;
        }
        try
        {
            DependencyProperty dp = property.GetValue(obj) as DependencyProperty;
            if(dp == null)
            {
                Debug.WriteLine("Cannot get DependencyProperty {0}", PropertyName + "Property");
                return;
            }
            obj.SetValue(dp, Value);
        }
        catch(Exception ex)
        {
            Debug.WriteLine("Exception caught {0} with message {1}", ex.GetType(), ex.Message);
        }
    }

In xaml I wrote:

<Button HorizontalAlignment="Center" VerticalAlignment="Center" Content="Click">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <i:SetterTriggerAction PropertyName="Background" Value="Red"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </Button>

So when I click the button I want to make its background red. However both versions of Invoke method suffers from convertion issue and in my output window I get a message that "Red" is not valid value for property Background (because it is treated like string not a Brush!). Is there any way to convert a value from xaml (string "Red") to a valid Brush value? I would like to have as general way of converting properties as possible.

I consider that something similar to what I want to achieve is done when xaml is parsed and properties of controls are set.

Any help would be appreciated.





IBM Reflection programming- MoveCursor function issue

In IBM Reflection host, i am trying to run a VBA macro for traversing through different screens and fill required information (in a predefined template kind of a screen) to create orders in the system.

In the process, i am trying to utilise the functions- "Session.MoveCursor" and "Session.CursorRow", "Session.CursorColumn" for moving the cursor to a desired position and then reading the cursor position information (to verify the position before writing data on HOST screen)

Code:

Dim currRowPos as Integer
Dim currColPos as Integer
Session.MoveCursor targetRowPos, targetColPos ' move cursor position
DoEvents ' custom logic to wait or inlcude delay 1 sec or more, mentioned only single code statement here 
currRowPos = Session.CursorRow 'get cursor current row position
currColPos = Session.CursorColumn 'get cursor current column position
'check current cursor position and write data onto HOST screen
If targetRowPos = currRowPos And targetColPos = currColPos Then
    Session.TransmitANSI "xyz" 'write xyz on HOST screen
End If

I am trying to write some information on to Host at the desired cursor position and traverse to next screen. In the due process, i am going going back and forth to fill information for multiple items (one at a time).

Sometimes I am facing an issue where the above logic (code) is executed and the cursor is still in old position (not in the desired new row, column position) and the program started writing data in the old position rather than the desired/ target position resulting in a programming error (i.e. 'Session.CursorRow' and 'Session.CursorColumn' are outputting new desired cursor position, when in real time the cursor in its old position on HOST screen).

If anyone has encountered this issue before and/ or have any solution in mind, can you please share the same . Thank you.

IBM HOST Programming Reference: http://ift.tt/2beETXC





Sum up all the properties of a collection and dynamically assigned it to another object

I have a collection of object in lst of type DataResponse and what I would like to do is sum up all the properties that are int and decimal of this collection and assign the result of each property to another object DataContainerResponse that has the same exact property names(and types) as the those that are being summed up.

I can do this manually by typing out each property by hand and do a .Sum(s=>s.<propertyname>. But that so 90s. Below is my fruitless attempt to juice it out. Frankly, I never assigned a var to a lambda expression before and I don't even know if it's possible .Sum(s=><var name>);

 public DataAggragationResponse doAggregation(List<DataResponse> lst)
    {
        if (lst.Count == 0)
            return null;
        DataContainerResponse rd = new DataContainerResponse();

        //If I do it manually typing each prop by hand.
        rd.VIOL = lst.Sum(s => s.VIOL);


        //Automation!!!
        foreach (PropertyInfo propertyInfo in typeof(DataResponse).GetProperties())
        {

                rd.GetType().GetProperties().SetValue(lst.Sum(s => propertyInfo.Name[0]));

        }
    }





How to get Polymorphic factor of classes using Java Reflection API?

I recently started trying out some exercises for Java Reflection API and found the tool pretty fascinating.I know that it is possible to obtain Polymorphism factor using the Java Reflection API.PF is about measuring the coupling based on the amount of overriden methods,How would be possible to obtain the Polymorphism Factor using Java Reflection?





Creating object from a given Class object in Java

quick question about creating objects when given a Class object. Or maybe I need to go about this differently. First off my plan, I am writing a method that will take an array of File objects, and read each one into a Set, where each set is then appended to a list and the list returned. Below is what I have:

private static List<Set<String>> loadFiles(File[] files, Class whatType, Charset charSet){
    List<Set<String>> setList = new ArrayList<Set<String>>(files.length);

    try {
        for(File f : files){
            BufferedInputStream bs = new BufferedInputStream(new FileInputStream(f));
            InputStreamReader r = new InputStreamReader(bs, charSet);
            BufferedReader br = new BufferedReader(r);

            Set<String> set = new HashSet<>(); //This is the problem line
            String line = null;

            while( (line = br.readLine()) != null){
                set.add(line.trim());

            }

            br.close();
            setList.add(set);
        }

        return setList;
    } catch (FileNotFoundException e) {
        //Just return the empty setlist
        return setList;
    } catch (IOException e) {
        //return a new empty list
        return new ArrayList<Set<String>>();
    }
}

But what I want is to allow the user of the method to specify the type of Set to instantiate (as long as it contains Strings of course). That is what the 'whatType' param is for.

All my research has lead me to how to instantiate an object given the class name, but that is not really what I am after here...

Maybe I need to go about this a different way? Any help is really appreciated!





Get the list of fields and subfields of a java class trough reflection

I am trying to get a list of all fields, be it a primitive or not of an object given as an argument to the method getFieldz. I've been trying to figure this out for a while now, the following code is the result. I keep getting stackoverflow error and have no clue why is this happening. Any pointers? Or perhaps I am doing something incorrectly?

Here's the logic: Get all of object's fields, if its a primitive or string add it to the list, otherwise check if the field has any subfields, if not then add it to the list if yes then recursively perform the check for the field.

public List<String> getFieldz(Object object) {
    List<String> fieldList = new ArrayList<String>();

    Field[] fields = object.getClass().getDeclaredFields();

    for (int i = 0; i < fields.length; i++) {

        if (fields[i].getType().isPrimitive() || fields[i].getType().toString().equals("class java.lang.String")) {
            fieldList.add(fields[i].getName());

        }

        else {
            Field[] subFields = fields[i].getClass().getDeclaredFields();

            if (subFields.length > 0) {
                System.out.println(subFields.length);
                getFieldz((Object)fields[i].getClass());
            } else {
                fieldList.add(fields[i].getName());
            }

        }

    }

    return addParrentName(fieldList, object.getClass().getSimpleName());
}

public List<String> addParrentName(List<String> list, String parrentName) {
    if (parrentName.equals("Field")) {
        return list;
    }

    List<String> listWithParrentNames = new ArrayList<String>();

    for (String name : list) {

        listWithParrentNames.add(parrentName + "." + name);

    }

    return listWithParrentNames;

}

EDIT: It's not that I don't know what stackoverflow error is, I just don't know why am I getting it: which part of the code is causing the infinite loop;





java.lang.reflect.Field getType() result cannot compare with type using equals() [duplicate]

This question already has an answer here:

Most probably I oversee something in this trivial use case. My code iterates over annotated fields in a class and the for every field I'd like to run some code dependent on the type. The simplest is just to set a value:

field.setAccessible(true);
final Class<?> type = field.getType();
if (type.equals(Boolean.class)) {
    field.set(this, Boolean.parseBoolean(property));
} else if (type.equals(Integer.class)) {
    field.set(this, Integer.parseInt(property));
} else if (type.equals(String.class)) {
    field.set(this, property);
} else {
    LOGGER.warn("Cannot parse property -{}{}. Unknown type defined.", option.getOpt(),
            field.getName());
}

However this check:

if (type.equals(Boolean.class))

dosn't work as expected e.g. for a field defined as private boolean isVerbose;. After inspection of type I got the property name as just only "boolean" where the Boolean.class property name was filled with "java.lang.Boolean". These object were different.

What would be the right implementation of this scenario?





lundi 22 août 2016

C# - Copying UnityEvent information using reflection

I need to copy the events from one UnityEvent to another, as once I figure this out I will be switching out the target at runtime to another object, what I have so far is:

MethodInfo info = UnityEventBase.GetValidMethodInfo (event1.GetPersistentTarget (i), event1.GetPersistentMethodName (i), Type.EmptyTypes);
UnityAction action = Delegate.CreateDelegate (typeof (UnityAction), info) as UnityAction;

event2.AddListener (action);

I get ArgumentNullException: Argument cannot be null., and if I change Type.EmptyTypes to new Type[] { typeof (float) }, I get ArgumentException: method argument length mismatch.

The problem being that I don't know what to put in there since I don't know what the type is (since Unity Events can send a bool, float, etc.)

Unity Docs don't cover this, so hopefully someone else has had success in the past.





Getting only Scala StaticAnnotation annotated classes at runtime

I am trying to find all the classes that have been annotated with the "Annotated" class, which I create below as a Scala StaticAnnotation class.

import scala.reflect.runtime.universe._

sealed trait Foo {}
class Annotated() extends scala.annotation.StaticAnnotation
@Annotated() case class AnnotatedFooCase() extends Foo
case class NotAnnotatedFooCase() extends Foo

val annotatedClasses = typeTag[Annotated].tpe.typeSymbol.owner.typeSignature.
  decls.filter(_.isPublic).filter(_.isClass).map(_.asClass).filter(_.isCaseClass)

I feel like this code should be working, but checking it out in a worksheet, I see this list is the result

annotatedClasses: Iterable[reflect.runtime.universe.ClassSymbol] = List(class AnnotatedFooCase, class NotAnnotatedFooCase)

I want a list that only includes the correctly annotated classes.





Why is my reflection method failing?

When I try to invoke this it isn't working. Null doesn't work as for other methods that are being called in this fashion, but for this particular one, it's causing problems.

The methods this is attempting to call are static, so I used null. I then tried creating an instance in the manner below, then I attempted removing static from the methods. I have been looking at msdn documentation on method.Invoke() and can't see any other way to do this. And break points are not being hit anywhere inside the methods, so the invocation is failing, not the methods I am trying to invoke

As it is, this is throwing a generic exception, otherwise I would include the details of the error.

//somewhere in code   


 getLoginInfo.Get("bob", "JobSeeker");     
 public object Get(string userName, string userType)
 {
      object data = null;
      try
      {
      using (var db = new dbEntities())
                {
                    ReflectionHelpers rh = new ReflectionHelpers();
                    data = rh.CallMethodIfExists(new GetLogin(), userType, new object[] { db, userName });

                }
            }
            catch (Exception e)
            {
                return e;
            }
        }
        public static object JobSeeker(aos_activeEntities aos, string userName)
        {
            return aos.Logins.Select(login => login.Login1.Equals(userName));
        }



//meanwhile
public object CallMethodIfExists(Object obj, string methodName, object[] args)
{

     if (HasMethod(obj, methodName))
     {
         MethodInfo methodInfo = obj.GetType().GetMethod(methodName);
         return methodInfo.Invoke(Activator.CreateInstance(obj.GetType()), args);

     }
}





C# Variable Expression Func Parameter

I'm writing a dynamic model binder that binds functions to api calls.

This is my test controller with 2 functions. They have different functions with different parameter types.

public class MyTestController : System.Web.Mvc.Controller {

    public ActionResult MyFunction() {
        // Do awesome stuff
        return result;
    }

    public ActionResult MyOtherFunction(int i) {
        // Do other awesome stuff
        return result;
    }
}

With this model binder I want to to be able to select the specific functions and create my api call name.

public static class ModelBinder {
    public static string GetApiCall<T>( Expression<Func<T, Func<ActionResult>>> expression ) {
        var unaryExpression = (UnaryExpression)expression.Body;
        var methodCallExpression = (MethodCallExpression)unaryExpression.Operand;
        var methodInfoExpression = (ConstantExpression)methodCallExpression.Arguments.Last();
        var methodInfo = (MemberInfo)methodInfoExpression.Value;

        var controllerName = typeof( T ).Name.Replace( "Controller", "" );
        var methodName = methodInfo.Name;

        var myApiCallName = string.Format( "{0}_{1}", controllerName, methodName ).ToLower();
        return myApiCallName;
    }
}

Using the ModelBinder works with functions in the controller class without parameters. But not with the parameterized function.

var apiCallName1 = ModelBinder.GetApiCall<MyTestController>( x => x.MyFunction );
var apiCallName2 = ModelBinder.GetApiCall<MyTestController>( x => x.MyOtherFunction ); // Compiler Says no!

It's not possible to compile because the function definition does not match. In this case I would need to define another GetApiCall Method with another parameter type of Expression>>.

So here's the actual question:

Is there any type in C# that accepts all kinds of delegate types, but it bound to a specific return type? So only functions that return a results of type of ActionResult.

public static string GetApiCall<T>( Expression<Func<T, MagicDelegateTypeThatTakesAllFunctionsWithAllParameterTypes>> expression ) {
    // do awesome stuff
}





How to get value of a grandchild in an expression in C#?

I am building a helper method that would take a model expression and do something with its value, just as in:

Html.EditorFor(expression)

(that I can use as: Html.EditorFor(m => m.Name)

I've implemented such method as:

public static MvcHtmlString MyMethod<TModel, TProperty>(this HtmlHelper<TModel> html,
    Expression<Func<TModel, TProperty>> expression)
{
    TModel dataModel = html.ViewData.Model;
    MemberExpression mexp = expression.Body as MemberExpression;
    PropertyInfo pinfo = mexp.Member as PropertyInfo;
    string currentValue = dataModel != null ? pinfo.GetValue(dataModel) as string : null; //exception on this line
    [do something with the value...]
}

This works for getting values of direct children of the model such as model.Name, but for higher degree references, trying to get value such as model.SomeChild.Name is throwing an exception:

Object does not match target type.

After some investigation, it turns that member expression is referencing SomeChild, where property info holds info on Name. When I try to get value, it tries to get model.Name in that sense, and crashes.

How do I get value of a grandchildren using expressions in C#?





Is Reflection is supported in .Net Core?

I've read that Reflection is not supported in .Net Core. Is Reflection totally not supported in .Net Core? Or it would be added soon or even the only thing is needed is to use an specific namespace, extension method or a library?

Many .Net Framework applications relies on Reflection. If it is not supported in .Net Core in long term, which alternative may be used?





Java Reflection in Scala

I am trying to get a simple java reflection program working in Scala, and seem to be missing something ...

scala> val cl = new URLClassLoader(Array(new File("Hi.jar").toURI.toURL), getClass.getClassLoader)
cl: java.net.URLClassLoader = java.net.URLClassLoader@3c7b137a

scala> val c = cl.loadClass("Hi")
c: Class[_] = class Hi

scala> val m = c.getMethod("run")
m: java.lang.reflect.Method = public void Hi.run()

scala> m.invoke()
<console>:21: error: not enough arguments for method invoke: (x$1: Any, x$2: Object*)Object.
Unspecified value parameters x$1, x$2.
       m.invoke()
               ^

What am I missing, as the prior line has indicated -

public void Hi.run()

What exactly is it expecting for the two arguments?





dimanche 21 août 2016

how to rotate reflection from Imageview?

My question concerns rotating the reflection of imageview. Is it possible or not? my code is shown below:

    Group root = new Group();
    File file = new File("c://Users/Garm/Downloads/AnimGif.gif");
    Image image1 = new Image(file.toURI().toString()); 
    ImageView view = new ImageView(image1);
    view.setFitHeight(image1.getHeight()/2);
    view.setFitWidth(image1.getWidth()/2);
    root.getChildren().add(view);
    view.setOnMouseClicked(new EventHandler<MouseEvent>()
    {
        @Override
        public void handle(MouseEvent t)
        {
            System.exit(0);
        }
    });

    Reflection reflection = new Reflection();
    reflection.setFraction(1.0);
    reflection.setTopOffset(55.5);
    reflection.setTopOpacity(0.600);
    reflection.setBottomOpacity(0.001); 
    view.setEffect(reflection);

    Scene scene = new Scene(root, image1.getWidth(), image1.getHeight());
    stage.setTitle("Animated GIF");
    stage.setScene(scene);
    stage.initStyle(StageStyle.TRANSPARENT);
    stage.show();

In my code, I would like to object reflection was rotated 90 degrees. Whether it is feasible, and if not, can anyone give an idea to solve this problem. Thank you for all your help and guidance on this topic.





Changing Class name, method name and exporting it

Hello I was hoping someone here can help me accomplish this task. I want to change the name of all my field, methods and class in a package (doing it one class at a time will also be fine). I know that even with Java Reflection I won't be able to change it outside the class.

My sample java class :

public class Foo {

    private final Object foo = ...
    private Object foo1 = ...

    private void foo(){
       Object foo;
    }

}

The generated class should become :

public class A{

    private final Object a= ...
    private Object b = ...

    private void a(){
       Object a; //if possible
    }

}

It would be great if someone can tell me or give me the code to achieve this, if this can be done on any other language it will also be great. This will obviously be done at the last resort and will only be done to classes that are not activity or, service or any other android file which are referenced outside the package.





Simple way to find method 'parents' at runtime?

I'm trying to find a simple way to retrieve 'parents' of a method at runtime. (Possibly using reflection) By 'parents' of a method, I mean the 'super' methods of said method, the ones said method is overriding or implementing. This would ideally also work with Generics.

Example:

public interface Class1<O> {
    void doSomething(O s);
}

public interface Class2 {
    void doSomething(String s);
}

public class Class3 implements Class1<String>, Class2 {
    public void doSomething(String s) {
        // Something
    }
}

Here it should retrieve Class1#doSomething and Class2#doSomething if I wanted to get the 'parents' of Class3#doSomething. Does any such method exist in Java or is it even possible?





Pass method as param via expression

I need to have the ability to pass a method of my class (or base-class) to be passed to a base-class method (as it will have to do some more stuff there).

I known about the following posibility: In my base-class I have the method public void Call(Action action) which will simply call action() and do other stuff.

But I wan't some more restrictive as by now I can put everything in this method, e.g. Call(() => string.Format("Some {0}, "text)); But I only want to allow methods of own type or base-type.

I think about something like public void Call(Expression<Func<MyClassType, Action>> expressionToAction) but I don't get the right point here.

Is this even possible? With the expression-param I get the error that the method must return Action which is totally not what I want.





samedi 20 août 2016

Using System.type as Type paramater

I'm trying to create a database that has a generic use for everything table filler based on the object passed. This object passed in is a reference object with just public variables and sub classes that are filled by a inheritance export on my main Object class. The DB tabled are created and updated a similar way to how i want to fill the tables but each class is hard coded into the method. At the moment i have this:

#region insert / object Creation

    private static void AddObject(ObjectReference or)
    {
        Dictionary<string, System.Type> classes = GetSubClassList<ObjectReference>();

        foreach(KeyValuePair<string, System.Type> kv in classes)
        {
            AddOrUpdateObjectToDB<kv.Value>(or);
        }
    }

    private static void AddOrUpdateObjectToDB<T>(ObjectReference or)
    {
        Dictionary<string, System.Type> properties = GetPropertyList<T>();

        foreach(KeyValuePair<string, System.Type> kv in properties)
        {
            Debug.LogWarning(kv.Key); // Warning for visability
        }
    }

    #endregion

But "AddOrUpdateObjectToDB<kv.Value>(or);" is not allowed.

GetSubClassList is using reflection to get the system.types of all public sub classes. I want to use this type to pass into AddOrUpdateObjectToDB, where reflection then gets the properties (Properties are the same name in the DB) for that class for the object reference to then use to add to the DB. This is so I don't have to keep adding case statements for each sub class that may exist to pass into the AddOrUpdate. Is this possible?

Example of ObjectReference if needed:

public class ObjectReference
{
    public string DatabaseID;
    public bool HoverDetails;
    public bool ReceivesWind;
    public string ItemModel;

    public Transform transform;

    //
    [System.Serializable]
    public class Transform
    {
        public Vector3 Scale;
    }
}





How to get current class name/object inside PowerShell static class method?

I need $this to work inside static class! How to achieve that? Any workaround? I have analyzed return of Get-PSCallStack in class context and found nothing useful.

I need this for (a) logging and for (b) calling other static methods of same class without mentioning its name again and again.

Sample code (PowerShell v5):

class foo {
    static [void]DoSomething() {
        [foo]::DoAnything()  #works

        #$this.DoAnything   #not working

        $static_this = [foo]
        $static_this::DoAnything() #works

    }
    static [void]DoAnything() {
        echo "Done"
    }
}

[foo]::DoSomething()





Workaround for PHP memory leak when using Reflection class in a loop

I have a loop like this

    foreach ($classes as $class)
    {
        $reflectionClass = new \ReflectionClass($class);
        ... //code that doesn't matter - commenting it out leaves the memory consumption all the same
    }

Which gives the Fatal error: Allowed memory size of 134217728 bytes exhausted result in case of a big number of classes to loop through and relatively small allowed memory size in php.ini (for me that's around 4000 classes and 128 MB memory setting).

Memory usage right before the loop start is around 1.6 MB.

As you might guess, leaving unset($reflectionClass) at the end of the loop body doesn't help at all.

Upon some googling my guess is that PHP doesn't free the memory taken by the object in case it has some internal references to other objects. Now, these posts (one, two, three) made me try using the garbage collector expicitly:

    gc_enable();
    foreach ($classes as $class)
    {
        $reflectionClass = new \ReflectionClass($class);
        ...
        unset($reflectionClass);
        gc_collect_cycles();
    }

Which still leads to the same result.

The solutions I see: 1) Increase allowed memory setting - which is ugly and sad. 2) Separate classes into portions and get the needed result from each portion separately via forking or executing some other PHP script - but this sounds like a tough way to go.

Is there a simple workaround for the memory leak? Am I missing something here?





How to find the access modifier of a member using java reflection

Find the access modifier of a member using java reflection

private final static long serialId = 1L;
protected String title;
public String FirstName;

I need to know which variable is private, protected and public?





Using String/int for referencing ImageView? [duplicate]

This question already has an answer here:

I am new to programming and I have been struggling on something.
If you take a look at the attached image and help me, it would be so nice.

enter image description here





vendredi 19 août 2016

Go: Dynamic type cast/assertion of struct's with interface (to call methods and use struct commons)

I cracked my brain trying to make my code shorter and cleaner. The problem is in one function, that is working with different structs, that implements one interface.

In some cases I need the model variable to implement the structure (slice of rowModel's) ([]rowModel) and some times I need to use methods from interface. The code is not short, sorry for that. So I put main comments in the code below.

Here is interface:

type StatModel interface {
    FilterData(Filter)
    ClusterData(Filter)
    CountDataForChart(string)[]ChartElement
    GroupByTreeGroups(Filter)[]OrgPack
}

type StatRow interface {
    Count( name string) float64
}

This interfaces are created for methods calls, and to make code shorter. But Interface cannot have fields or structure as Abstruct class in OOP. One of the models is here:

 type NoaggModel []NoaggRow

 type NoaggRow struct {
    Date             string
    Hour             int
    Id_user          int
    Id_line          float64
    Id_region        int
    Id_tree_devision int
    N_inb            float64
    N_out            float64
    N_hold           float64
    N_abandon        float64
    N_transfer       float64
    T_inb            float64
    T_out           float64
    T_hold           float64
    T_ring           float64
    T_acw            float64
    T_wait           float64
}

type FcrModel  []FcrRow

type FcrRow struct {
    Date             string
    Hour             int
    Id_user          int
    Id_line          float64
    Id_region        int
    Id_tree_devision int
    N_irr            float64
    N_inb            float64
}

So , I'm reading from channel, and getting different structures, and trying to calculate everything correctly. How to make type assertion and method calls correctly in this case?

func receiveLightWork(org <-chan models.OrgPack, request ChartOptions) interface{} {

    modelClusters := make(map[string][]models.OrgPack)

    for orgPack := range org {
        _, ok := modelClusters[orgPack.ModelName]
        if ok {
            model := modelClusters[orgPack.ModelName]
            model = append(model, orgPack)
            modelClusters[orgPack.ModelName] = model

        }else {
            var modelSlice []models.OrgPack
            modelSlice = append(modelSlice, orgPack)
            modelClusters[orgPack.ModelName] = modelSlice
        }
    }

    output := make(map[string][]OrgStat)

    for modelName, slice := range modelClusters {

        //here I can't choose what to write
        // model must be convertable to NoaggModel, that is []NoaggRow{}
        // as others AcsiModel, FcrModel ...etc. 
        // Also model.ClusterData(customFilter) must be callable as it is in interface of common model

        var model []interface{} 

        var rowModel interface{}

        switch modelName {

        case "noagg":
            model = model.(models.NoaggModel)
            rowModel = rowModel.(models.NoaggRow{})
        case "acsi":
            model = model.(models.AcsiModel)
            rowModel = rowModel.(models.AcsiRow)
        case "fcr24":
            model = model.(models.FcrModel)
            rowModel = rowModel.(models.FcrRow)
        case "aic":
            model = model.(models.AicModel)
            rowModel = rowModel.(models.AicRow)
        }

        for _, el := range slice {


            modelFields := reflect.ValueOf(&rowModel).Elem()
            sliceFields := reflect.ValueOf(&el.SummorisedData).Elem()

            fieldsTypes := modelFields.Type()

            for i := 6; i < modelFields.NumField(); i++ {
                fmt.Println(" model_field ", fieldsTypes.Field(i).Name )
                modelField := modelFields.Field(i);
                sliceField := sliceFields.Index(i-6) ;

                modelField.Set(reflect.Value(sliceField));
            }

            id_line := sliceFields.Index(len(el.SummorisedData) - 1) ;
            date := sliceFields.FieldByName("PackName");

            modelFields.FieldByName("Id_line").Set(id_line)
            modelFields.FieldByName("Date").Set(date)

     // here append not works, because model is []interface{} and not []NoaggRow or others.
     // Writes [non-interface type []interface {} on left]
            model = append(model, rowModel)
        }

        customFilter := request.Filters
        customFilter.Cluster = "clusterDay"

        model.ClusterData(customFilter) // now here is unresolved Reference 'ClusterData'

        for _, mod := range model {
            for _, charts := range request.Charts {
                    var stats []OrgStat
                    for _, chart := range charts {

                        // now here is unresolved Reference 'Count'
                        stats = append(stats, OrgStat{Name:chart.Name, Value: mod.Count(mod, chart.Name)}) 
                    }

                    _, group_exist := output[mod.Date]
                    if group_exist {
                        inserted_stat := output[mod.Date]
                        output[mod.Date] = append(stats, inserted_stat...)
                    }else {
                        output[mod.Date] = stats                        }

                }
        }
    }

    return output
}

All help is very highly appreciated. I'll answer to each question on this topic if necessary. Thanks in advance!