EzDevInfo.com

nested interview questions

Top nested frequently asked interview questions

Can regular expressions be used to match nested patterns?

Is it possible to write a regular expression that matches a nested pattern that occurs an unknown number of times. For example, can a regular expression match an opening and closing brace when there are an unknown number of open closing braces nested within the outer braces.

For example:

public MyMethod()
{
  if (test)
  {
    // More { }
  }

  // More { }
} // End

Should match:

{
  if (test)
  {
    // More { }
  }

  // More { }
}

Source: (StackOverflow)

Nested function in C

Can we have a nested function in C? What is the use of nested functions? If they exist in C does their implementation differ from compiler to compiler?

Are nested functions allowed in any other language? If yes, then what is their significance?


Source: (StackOverflow)

Advertisements

Multiple levels of 'collection.defaultdict' in Python

Thanks to some great folks on SO, I discovered the possibilities offered by collections.defaultdict, notably in readability and speed. I have put them to use with success.

Now I would like to implement three levels of dictionaries, the two top ones being defaultdict and the lowest one being int. I don't find the appropriate way to do this. Here is my attempt:

from collections import defaultdict
d = defaultdict(defaultdict)
a = [("key1", {"a1":22, "a2":33}),
     ("key2", {"a1":32, "a2":55}),
     ("key3", {"a1":43, "a2":44})]
for i in a:
    d[i[0]] = i[1]

Now this works, but the following, which is the desired behavior, doesn't:

d["key4"]["a1"] + 1

I suspect that I should have declared somewhere that the second level defaultdict is of type int, but I didn't find where or how to do so.

The reason I am using defaultdict in the first place is to avoid having to initialize the dictionary for each new key.

Any more elegant suggestion?

Thanks pythoneers!


Source: (StackOverflow)

namespaces for enum types - best practices

Often, one needs several enumerated types together. Sometimes, one has a name clash. Two solutions to this come to mind: use a namespace, or use 'larger' enum element names. Still, the namespace solution has two possible implementations: a dummy class with nested enum, or a full blown namespace.

I'm looking for pros and cons of all three approaches.

Example:

// oft seen hand-crafted name clash solution
enum eColors { cRed, cColorBlue, cGreen, cYellow, cColorsEnd };
enum eFeelings { cAngry, cFeelingBlue, cHappy, cFeelingsEnd };
void setPenColor( const eColors c ) {
    switch (c) {
        default: assert(false);
        break; case cRed: //...
        break; case cColorBlue: //...
        //...
    }
 }


// (ab)using a class as a namespace
class Colors { enum e { cRed, cBlue, cGreen, cYellow, cEnd }; };
class Feelings { enum e { cAngry, cBlue, cHappy, cEnd }; };
void setPenColor( const Colors::e c ) {
    switch (c) {
        default: assert(false);
        break; case Colors::cRed: //...
        break; case Colors::cBlue: //...
        //...
    }
 }


 // a real namespace?
 namespace Colors { enum e { cRed, cBlue, cGreen, cYellow, cEnd }; };
 namespace Feelings { enum e { cAngry, cBlue, cHappy, cEnd }; };
 void setPenColor( const Colors::e c ) {
    switch (c) {
        default: assert(false);
        break; case Colors::cRed: //...
        break; case Colors::cBlue: //...
        //...
    }
  }

Source: (StackOverflow)

How do I setup nested views in AngularJS?

I have an application with various screens. Each screen is assigned a URL, such as #, mails, contacts, and so on.

In my main HTML file I have an ng-view element which updates according to the route the user selects. So far, so good.

Now some of these screens have a sub-navigation. E.g., #mails does have an inbox and a sent folder. They present themselfes with two columns: The sub-navigation on the left, the mails of the appropriate folder on the right.

When you navigate to #mails, it shall redirect you to #mails/inbox, so that basically inbox is the default sub-view for mails.

How could I set this up?

The only approach I can currently think of (I am quite new to AngularJS, hence forgive me if this question is a little bit naive) is to have two views, one for #mails/inbox, and the other for #mails/sent.

When you select a route, these views are loaded. When you select #mails it simply redirects you to #mails/inbox.

But this means that both views must use an ng-include for the sub-navigation. Somehow this feels wrong to me.

What I'd like more is to have nested views: The top one switches between screens such as mails, contacts, and so on, and the bottom one changes between sub-views such as inbox, sent, and so on.

How would I solve this?


Source: (StackOverflow)

Ruby accessing outer variables in nested function

I'm sure there's a simple answer for this; I just can't seem to find it. I made a nested function in Ruby, and I was having trouble accessing variables from the outer function inside the inner function:

def foo(x)
  def bar
    puts x
  end
  bar
  42
end

foo(5)

I get: NameError: undefined local variable or method x' for main:Object`

The analogous Python code works:

def foo(x):
  def bar():
    print x
  bar()
  return 42

foo(5)

So how do I do the same thing in Ruby?


Source: (StackOverflow)

Why/when should you use nested classes in .net? Or shouldn't you?

In Kathleen Dollard's recent blog post, she presents an interesting reason to use nested classes in .net. However, she also mentions that FxCop doesn't like nested classes. I'm assuming that the people writing FxCop rules aren't stupid, so there must be reasoning behind that position, but I haven't been able to find it.


Source: (StackOverflow)

How to steal touches from UIScrollView?

Today on my creative time I did some quite comprehensive research on how to steal touches from a UIScrollView and send them instantly to a specific subview, while maintaining the default behavior for the rest of the scroll view. Consider having a UIPickerView inside of a UITableView. The default behavior is that if you drag your finger over the picker view, the scroll view will scroll and the picker view will remain unchanged.

The first thing I tried was to override

- (BOOL)touchesShouldCancelInContentView:(UIView *)view

and simply not allow the UIScrollView to cancel touches inside the picker view. This works, but it has an unpleasant side effect. You would like the picker view to respond immediately and thus you will have to set delaysContentTouches to NO. The problem is that you don't want the rest of the table view to respond immediately, because if it does the table view cell will always get highlighted for a few milliseconds before the scrolling starts.

The second thing I tried was to override

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event

because I had read that the scroll view always returns itself, so that it will "steal" the touches from its subviews and later send them to the subview if they weren't of interest to the scroll view. However, this isn't true anymore. UIScrollView's default implementation of hitTest:withEvent: actually returns the subview that should receive the touch. Instead it uses gesture recognizers to intercept the touches.

So the third thing I attempted was to implement my own gesture recognizer and cause it to fail if the touch was outside of the picker view and otherwise succeed. Then I set all the scroll view's gesture recognizers to fail unless my gesture recognizer failed using the following code:

for (UIGestureRecognizer * gestureRecognizer in self.tableView.gestureRecognizers)
{
    [gestureRecognizer requireGestureRecognizerToFail:myRecognizer];
}

This does in fact steal the touches from the scroll view, but the picker view never receives them. So I though maybe I could just send all the touches that my gesture recognizer receives using this code:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (UITouch *touch in touches)
        [touch.view touchesBegan:touches withEvent:event];
}

The above code is a simplified version. I also make sure that the view is a picker view (or one of it's subviews) and set the appropriate state for the gesture recognizer as I mentioned above. I also did the same for canceled, ended and moved. However, the picker view was still not responding.

I also tried one last thing before returning to my regular work. During my extensive googling I read that nested UIScrollViews just magically worked since 3.x, so I tried putting my picker view inside a nested UIScrollView and set the following properties on it:

scrollView.delaysContentTouches = NO;
scrollView.canCancelContentTouches = NO;

As one would expect the outer scroll view didn't treat the inner scroll view any different than it treated the picker view, so the inner scroll view did not receive the touches. I thought that it was a long shot, but it was simple enough to implement, so I thought it was worth to give it a shot.

What I know is that UIScrollView has a gesture recognizer named UIScrollViewDelayedTouchesBeganGestureRecognizer that intercepts the touches and sends them to the appropriate subview after 150 (?) ms. I'm thinking that I should be able to write a similar recognizer that causes the scroll view's default recognizers to fail and instead of delaying the touches immediately sends them to the picker view. So if anyone knows how to write such a recognizer please let me know and if you have any other solution to the problem, you're very welcome share that as well.

Thank you for reading through the whole question and even if you don't know the answer you could still upvote the question so that it gets more attention (hopefully from someone that can answer it). Thanks! :)


Source: (StackOverflow)

Rails: How to modify tests for a nested resource?

While learning Rails I've created an application with a Domains controller nested below a Customers controller. I'm using Rails 2.3.4 and it's been a learning experience. I managed to get the below routing set up:

    customer_domains GET    /customers/:customer_id/domains(.:format)          {:controller=>"domains", :action=>"index"}
                     POST   /customers/:customer_id/domains(.:format)          {:controller=>"domains", :action=>"create"}
 new_customer_domain GET    /customers/:customer_id/domains/new(.:format)      {:controller=>"domains", :action=>"new"}
edit_customer_domain GET    /customers/:customer_id/domains/:id/edit(.:format) {:controller=>"domains", :action=>"edit"}
     customer_domain GET    /customers/:customer_id/domains/:id(.:format)      {:controller=>"domains", :action=>"show"}
                     PUT    /customers/:customer_id/domains/:id(.:format)      {:controller=>"domains", :action=>"update"}
                     DELETE /customers/:customer_id/domains/:id(.:format)      {:controller=>"domains", :action=>"destroy"}
           customers GET    /customers(.:format)                               {:controller=>"customers", :action=>"index"}
                     POST   /customers(.:format)                               {:controller=>"customers", :action=>"create"}
        new_customer GET    /customers/new(.:format)                           {:controller=>"customers", :action=>"new"}
       edit_customer GET    /customers/:id/edit(.:format)                      {:controller=>"customers", :action=>"edit"}
            customer GET    /customers/:id(.:format)                           {:controller=>"customers", :action=>"show"}
                     PUT    /customers/:id(.:format)                           {:controller=>"customers", :action=>"update"}
                     DELETE /customers/:id(.:format)                           {:controller=>"customers", :action=>"destroy"}
                root        /                                                  {:controller=>"customers", :action=>"index"}

However, all tests for the Domains controller are failing due to routing errors.

For example the following test (generated by Rails' resource generator) fails, as do all other tests in the DomainsControllerTest class.

class DomainsControllerTest < ActionController::TestCase
  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:domains)
  end
end

It fails with the error:

No route matches {:action => "index", :controller => "domains"}

This makes sense since the default routes no longer exist and the Domains controller requires a @customer to be set. I've spent an afternoon looking for the needed change, but almost every site talks about Rspec tests instead of regular Rails tests.

How do I modify the domains_controller_test.rb so it will understand the nested resource?


Source: (StackOverflow)

Updating nested arrays in mongodb

I have a document in mongodb with 2 level deep nested array of objects that I need to update, something like this:

{
    id: 1,
    items: [
        {
            id: 2,
            blocks: [
                {
                    id: 3
                    txt: 'hello'
                }
            ]
        }
    ] 
}

If there was only one level deep array I could use positional operator to update objects in it but for second level the only option I've came up is to use positional operator with nested object's index, like this:

db.objects.update({'items.id': 2}, {'$set': {'items.$.blocks.0.txt': 'hi'}})

This approach works but it seems dangerous to me since I'm building a web service and index number should come from client which can send say 100000 as index and this will force mongodb to create an array with 100000 indexes with null value.

Are there any other ways to update such nested objects where I can refer to object's ID instead of it's position or maybe ways to check if supplied index is out of bounds before using it in query?


Source: (StackOverflow)

Understanding nested list comprehension

I want to understand nested list comprehension. Below, I listed a list comprehension expression and their for loop equivalent.
I wonder if my understanding is correct on those.

For example,

[(min([row[i] for row in rows]),max([row[i] for row in rows])) 
for i in range(len(rows[0]))]

is equivalent to

result=[]
for i in range(len(rows[0])):
  innerResult=[]
  for row in rows:
    innerResult.append(row[i])
  innerResult2=[]
  for row in rows:
    innerResult2.append(row[i])
  tuple=(min(innerResult), max(innerResult2))
  result.append(tuple)

If I may generalize, I guess

[exp2([exp1 for x in xSet]) for y in ySet]

form can be translated to the following. (I hope I'm correct on this)

result=[]
for y in ySet:
  innerResult =[]
  for x in xSet:
    innerResult.append(exp1)
  exp2Result = exp2(innerResult)
  result.append(exp2Result)

For simpler case,

[exp1 for x in xSet for y in ySet] 

is equal to

result=[] 
for x in xSet:
  for y in ySet: 
    result.append(exp1)

whereas,

[[exp1 for x in xSet] for y in ySet]

is equal to

result=[]
for y in ySet:
  innerResult=[]
  for x in xSet:
    innerResult.append(exp1)
  result.append(innerResult)

I asked a similar question on equivalent for loop expression for complex list comprehension
The answers given there reconstruct the form after understanding what it does internally.
I'd like to know how it works systematically so I can apply the concept to other slightly varying examples.


Source: (StackOverflow)

Nested or Inner Class in PHP

I'm building a User Class for my new website, however this time I was thinking to build it little bit differently...

I know that C++, Java and even Ruby (and probably other programming languages) allows nested/inner classes inside the main class which allows to make the code more Object-Oriented and organized.

In PHP, I would like to do something like so:

<?php
    public class User {
        public $userid;
        public $username;
        private $password;

        public class UserProfile {
            // Some code here
        }

        private class UserHistory {
            // Some code here
        }
    }
?>

Is that possible in PHP? How can I achieve it?


UPDATE

If it's impossible, will future PHP versions might support nested classes?


Source: (StackOverflow)

Pros and cons of using nested C++ classes and enumerations?

What are the pros and cons of using nested public C++ classes and enumerations? For example, suppose you have a class called printer, and this class also stores information on output trays, you could have:

class printer
{
public:
    std::string name_;

    enum TYPE
    {
        TYPE_LOCAL,
        TYPE_NETWORK,
    };

    class output_tray
    {
        ...
    };
    ...
};

printer prn;
printer::TYPE type;
printer::output_tray tray;

Alternatively:

class printer
{
public:
    std::string name_;
    ...
};

enum PRINTER_TYPE
{
    PRINTER_TYPE_LOCAL,
    PRINTER_TYPE_NETWORK,
};

class output_tray
{
    ...
};

printer prn;
PRINTER_TYPE type;
output_tray tray;

I can see the benefits of nesting private enums/classes, but when it comes to public ones, the office is split - it seems to be more of a style choice.

So, which do you prefer and why?


Source: (StackOverflow)

Why can't I create an enum in an inner class in Java?

What I try to do is this:

public class History {
    public class State {
        public enum StateType {

Eclipse gives me this compile error on StateType: The member enum StateType must be defined inside a static member type.

The error disappears when I make the State class static. I could make State static, but I don't understand why I cannot declare an enum in an inner class.


Source: (StackOverflow)

Angular ui-router - how to access parameters in nested, named view, passed from the parent template?

Hi I am trying to access a parameter in the controller "ViewWorklogCrtl" while using ui-router and running into difficulty.

Basically, my parent template contains:

a(ui-sref="instance-ticket.worklog({id:{{ticket.testnum}}})") show

and then further down the page:

section(ui-view="top-section")

Then in my app.js, containing client-side routing info in short I have:

 $stateProvider
.state('instance-ticket', {
  url: '/ticket/:instanceID',
  templateUrl: 'partials/instance-ticket',
  controller: 'ViewTicketCrtl'
})
.state('instance-ticket.worklog', {
  views:{
    'top-section':{
      templateUrl:'/partials/ticket.worklog.jade',
      controller: 'ViewWorklogCrtl'
      }
  }
  })

The template loading is working correctly, the issue and question I can't find an answer to is - how to access "testnum" being passed through the ui-sref link, to and within the ViewWorkLogCtrl... Is there a better approach to this?

Much thanks!!!


Source: (StackOverflow)