EzDevInfo.com

dynamic interview questions

Top dynamic frequently asked interview questions

Dynamically add elements to a listView Android

Can anyone explain or suggest a tutorial to create a listView in android?

Here are my requirements:

  • I should be able to dynamically add new elements by pressing a button.
  • Should be simple enough to understand (possibly without any performance improvements or convertview, for instance)

I know there are quite a few questions on this topic, posted here on StackOverflow, but couldn't find any that would answer my question. Thanks!


Source: (StackOverflow)

How to detect if a property exists on an ExpandoObject?

In javascript you can detect if a property is defined by using the undefined keyword:

if( typeof data.myProperty == "undefined" ) ...

How would you do this in C# using the dynamic keyword with an ExpandoObject and without throwing an exception?


Source: (StackOverflow)

Advertisements

What's the difference between dynamic(C# 4) and var?

I had read a ton of articles about that new keyword that will ship with C# v4,but I couldn't make out the difference between a "dynamic" and "var".

This article made me think about it,but I still can't see any difference.

Is it that you can use "var" only as a local variable,but dynamic as both local and global?

I'm sorry for my ignorance,but could you show some code without dynamic keyword and then show the same code with dynamic keyword?


Source: (StackOverflow)

What is the difference between call and apply?

What is the difference between using call and apply to invoke a function?

var func = function(){
  alert('hello!');
};

func.apply();

vs

func.call();

Are there performance differences between the two methods? When is it best to use call over apply and vice versa?


Source: (StackOverflow)

Deserialize JSON into C# dynamic object?

Is there a way to deserialize JSON content into a C# 4 dynamic type? It would be nice to skip creating a bunch of classes in order to use the DataContractJsonSerializer.


Source: (StackOverflow)

What's the difference between eval, exec, and compile in Python?

I've been looking at dynamic evaluation of Python code, and come across the eval() and compile() functions, and the exec statement.

Can someone please explain the difference between eval and exec, and how the different modes of compile() fit in?


Source: (StackOverflow)

Are parameters in strings.xml possible?

In my Android app I'am going to implement my strings with internationalization. So currently I got a problem with the grammar and the way sentences build in different languages.

For example:

"5 minutes ago" - English

"vor 5 Minuten" - German

Can I do something like the following in strings.xml?

<string name="timeFormat">{0} minutes ago</string>

And then some magic like

getString(R.id.timeFormat, dynamicTimeValue)

This behaviour would solve the other problem with different word orders as well.


Source: (StackOverflow)

Test if a property is available on a dynamic variable

My situation is very simple. Somewhere in my code I have this:

dynamic myVariable = GetDataThatLooksVerySimilarButNotTheSame();

//How to do this?
if (myVariable.MyProperty.Exists)   
//Do stuff

So, basically my question is how to check (without throwing an exception) that a certain property is available on my dynamic variable. I could do GetType() but I'd rather avoid that since I don't really need to know the type of the object. All that I really want to know is whether a property (or method, if that makes life easier) is available. Any pointers?


Source: (StackOverflow)

javascript - change form action based on selection?

I'm trying to change the form action based on the selected value from a dropdown menu...

Basically, the html looks like this:

<form class="search-form" id="search-form" method="post" accept-charset="UTF-8" action="/search/user">
<select id="selectsearch" class="form-select" name="selectsearch">
<option value="people">Search people</option>
<option value="node">Search content</option>
</select>

<label>Enter your keywords: </label>
 <input type="text" class="form-text" value="" size="40" id="edit-keys" name="keys" maxlength="255" />

<input type="submit" class="form-submit" value="Search" id="edit-submit" name="search"/>
</form>

If "people" is selected, (which it is by default), the action should be "/search/user", and if content is selected, the action should be "/search/content"

I'm still searching around, but haven't been able to find out how to do this...


Source: (StackOverflow)

How to implement a rule engine?

I have a db table that stores the following:

RuleID  objectProperty ComparisonOperator  TargetValue
1       age            'greater_than'             15
2       username       'equal'             'some_name'
3       tags           'hasAtLeastOne'     'some_tag some_tag2'

Now say I have a collection of these rules:

List<Rule> rules = db.GetRules();

Now I have an instance of a user also:

User user = db.GetUser(....);

How would I loop through these rules, and apply the logic and perform the comparisons etc?

if(user.age > 15)

if(user.username == "some_name")

Since the object's property like 'age' or 'user_name' is stored in the table, along with the comparison operater 'great_than' and 'equal', how could I possible do this?

C# is a statically typed language, so not sure how to go forward.


Source: (StackOverflow)

Is there a best practice for generating html with javascript

I'm calling a web service that returns an array of objects in JSON. I want to take those objects and populate a div with HTML. Let's say each object contains a url and a name.

If I wanted to generate the following HTML for each object:

    <div><img src="the url" />the name</div>

Is there a best practice for this? I can see a few ways of doing it:

  1. Concatenate strings
  2. Create elements
  3. Use a templating plugin
  4. Generate the html on the server, then serve up via JSON.

Source: (StackOverflow)

Differences between ExpandoObject, DynamicObject and dynamic

What are the differences between System.Dynamic.ExpandoObject, System.Dynamic.DynamicObject and dynamic?

In which situations do you use these types?


Source: (StackOverflow)

Get value of c# dynamic property via string

I'd like to access the value of a dynamic c# property with a string:

dynamic d = new { value1 = "some", value2 = "random", value3 = "value" };

How can I get the value of d.value2 ("random") if I only have "value2" as a string? In javascript, I could do d["value2"] to access the value ("random"), but I'm not sure how to do this with c# and reflection. The closest I've come is this:

d.GetType().GetProperty("value2") ... but I don't know how to get the actual value from that.

As always, thanks for your help!


Source: (StackOverflow)

Django dynamic model fields

I'm working on a multi-tenanted application in which some users can define their own data fields (via the admin) to collect additional data in forms and report on the data. The latter bit makes JSONField not a great option, so instead I have the following solution:

class CustomDataField(models.Model):
    """
    Abstract specification for arbitrary data fields.
    Not used for holding data itself, but metadata about the fields.
    """
    site = models.ForeignKey(Site, default=settings.SITE_ID)
    name = models.CharField(max_length=64)

    class Meta:
        abstract = True

class CustomDataValue(models.Model):
    """
    Abstract specification for arbitrary data.
    """
    value = models.CharField(max_length=1024)

    class Meta:
        abstract = True

Note how CustomDataField has a ForeignKey to Site - each Site will have a different set of custom data fields, but use the same database. Then the various concrete data fields can be defined as:

class UserCustomDataField(CustomDataField):
    pass

class UserCustomDataValue(CustomDataValue):
    custom_field = models.ForeignKey(UserCustomDataField)
    user = models.ForeignKey(User, related_name='custom_data')

    class Meta:
        unique_together=(('user','custom_field'),)

This leads to the following use:

custom_field = UserCustomDataField.objects.create(name='zodiac', site=my_site) #probably created in the admin
user = User.objects.create(username='foo')
user_sign = UserCustomDataValue(custom_field=custom_field, user=user, data='Libra')
user.custom_data.add(user_sign) #actually, what does this even do?

But this feels very clunky, particularly with the need to manually create the related data and associate it with the concrete model. Is there a better approach?

Options that have been pre-emptively discarded:

  • Custom SQL to modify tables on-the-fly. Partly because this won't scale and partly because it's too much of a hack.
  • Schema-less solutions like NoSQL. I have nothing against them, but they're still not a good fit. Ultimately this data is typed, and the possibility exists of using a third-party reporting application.
  • JSONField, as listed above, as it's not going to work well with queries.

Source: (StackOverflow)

Why does this (null || !TryParse) conditional result in "use of unassigned local variable"?

The following code results in use of unassigned local variable "numberOfGroups":

int numberOfGroups;
if(options.NumberOfGroups == null || !int.TryParse(options.NumberOfGroups, out numberOfGroups))
{
    numberOfGroups = 10;
}

However, this code works fine (though, ReSharper says the = 10 is redundant):

int numberOfGroups = 10;
if(options.NumberOfGroups == null || !int.TryParse(options.NumberOfGroups, out numberOfGroups))
{
    numberOfGroups = 10;
}

Am I missing something, or is the compiler not liking my ||?

I've narrowed this down to dynamic causing the issues (options was a dynamic variable in my above code). The question still remains, why can't I do this?

This code doesn't compile:

internal class Program
{
    #region Static Methods

    private static void Main(string[] args)
    {
        dynamic myString = args[0];

        int myInt;
        if(myString == null || !int.TryParse(myString, out myInt))
        {
            myInt = 10;
        }

        Console.WriteLine(myInt);
    }

    #endregion
}

However, this code does:

internal class Program
{
    #region Static Methods

    private static void Main(string[] args)
    {
        var myString = args[0]; // var would be string

        int myInt;
        if(myString == null || !int.TryParse(myString, out myInt))
        {
            myInt = 10;
        }

        Console.WriteLine(myInt);
    }

    #endregion
}

I didn't realize dynamic would be a factor in this.


Source: (StackOverflow)