Keyword

Result: 265 questions

What is the output of the program below? Explain your answer.

class Program {
  private static string result;
 
  static void Main() {
    SaySomething();
    Console.WriteLine(result);
  }
 
  static async Task<string> SaySomething() {
    await Task.Delay(5);
    result = "Hello world!";
    return “Something”;
  }
}

Also, would the answer change if we were to replace await Task.Delay(5); with Thread.Sleep(5)? Why or why not?

Answer:

The answer to the first part of the question (i.e., the version of the code with await Task.Delay(5);) is that the program will just output a blank line (not “Hello world!”). This is because result will still be uninitialized when Console.WriteLine is called.

Most procedural and object-oriented programmers expect a function to execute from beginning to end, or to a return statement, before returning to the calling function. This is not the case with C# async functions. They only execute up until the first await statement, then return to the caller. The function called by await (in this case Task.Delay) is executed asynchronously, and the line after the await statement isn’t signaled to execute until Task.Delay completes (in 5 milliseconds). However, within that time, control has already returned to the caller, which executes the Console.WriteLine statement on a string that hasn’t yet been initialized.

Calling await Task.Delay(5) lets the current thread continue what it is doing, and if it’s done (pending any awaits), returns it to the thread pool. This is the primary benefit of the async/await mechanism. It allows the CLR to service more requests with less threads in the thread pool.

Asynchronous programming has become a lot more common, with the prevalence of devices which perform over-the-network service requests or database requests for many activities. C# has some excellent programming constructs which greatly ease the task of programming asynchronous methods, and a programmer who is aware of them will produce better programs.

With regard to the second part of the question, if await Task.Delay(5); was replaced with Thread.Sleep(5), the program would output Hello world!. An async method without at least one await statement in it operates just like a synchronous method; that is, it will execute from beginning to end, or until it encounters a return statement. Calling Thread.Sleep() simply blocks the currently running thread, so the Thread.Sleep(5) call just adds 5 milliseconds to the execution time of the SaySomething() method.

View

Why would you prefer to use an empty struct{}? Provide some examples of the good use of the empty struct{}.

Answer:

You would use an empty struct when you would want to save some memory. Empty structs do not take any memory for its value.

a := struct{}{}
println(unsafe.Sizeof(a))
// Output: 0

This saving is usually insignificant and is dependent on the size of the slice or a map. Although, more important use of an empty struct is to show a reader you do not need a value at all. Its purpose in most cases is mainly informational. Here are a few examples where it can be useful:

  • When implementing a data set:
set := make(map[string]struct{})
for _, value := range []string{"apple", "orange", "apple"} {
   set[value] = struct{}{}
}
fmt.Println(set)
// Output: map[orange:{} apple:{}]
  • With the seen hash, like when traversing a graph:
seen := make(map[string]struct{})
for _, ok := seen[v]; ok {
    // First time visiting a vertex.
    seen[v] = struct{}{}
}
  • When building an object, and only being interested in a grouping of methods and no intermediary data, or when you do not plan to retain the object state. In the example below it does not make a difference whether the method is called on the same (case #1) or on two different objects (case #2):
type Lamp struct{}

func (l Lamp) On() {
        println("On")

}
func (l Lamp) Off() {
        println("Off")
}

func main() {
       	// Case #1.
       	var lamp Lamp
       	lamp.On()
       	lamp.Off()
       	// Output:
       	// on
       	// off
	
       	// Case #2.
       	Lamp{}.On()
       	Lamp{}.Off()
       	// Output: 
       	// on
       	// off
}
  • When you need a channel to signal an event, but do not really need to send any data. This event is also not the last one in the sequence, in which case you would use the close(ch) built-in function.
func worker(ch chan struct{}) {
	// Receive a message from the main program.
	<-ch
	println("roger")
	
	// Send a message to the main program.
	close(ch)
}

func main() {
	ch := make(chan struct{})
	go worker(ch)
	
	// Send a message to a worker.
	ch <- struct{}{}
	
	// Receive a message from the worker.
	<-ch
	println(“roger")
	// Output:
	// roger
	// roger
}
View

How do you compare two structs? What about two interfaces? Provide examples.

Answer:

You can compare two structs with the == operator, as you would do with other simple types. Just make sure they do not contain any slices, maps, or functions, in which case the code will not be compiled.

type Foo struct {
	A int
	B string
	C interface{}
}
a := Foo{A: 1, B: "one", C: "two"}
b := Foo{A: 1, B: "one", C: "two"}

println(a == b)
// Output: true

type Bar struct {
	A []int
}
a := Bar{A: []int{1}}
b := Bar{A: []int{1}}

println(a == b)
// Output: invalid operation: a == b (struct containing []int cannot be compared)

You can compare two interfaces with the == operator as long as the underlying types are “simple” and identical. Otherwise the code will panic at runtime:

var a interface{}
var b interface{}

a = 10
b = 10
println(a == b)
// Output: true

a = []int{1}
b = []int{2}
println(a == b)
// Output: panic: runtime error: comparing uncomparable type []int

Both structs and interfaces which contain maps, slices (but not functions) can be compared with the reflect.DeepEqual() function:

var a interface{}
var b interface{}

a = []int{1}
b = []int{1}
println(reflect.DeepEqual(a, b))
// Output: true

a = map[string]string{"A": "B"}
b = map[string]string{"A": "B"}
println(reflect.DeepEqual(a, b))
// Output: true

temp := func() {}
a = temp
b = temp
println(reflect.DeepEqual(a, b))
// Output: false

For comparing byte slices, there are nice helper functions in the bytes package: bytes.Equal()bytes.Compare(), and bytes.EqualFold(). The latter is for comparing text strings disregarding the case, which are much faster than the reflect.DeepEqual().

View

What is wrong with the following code snippet?

type Orange struct {
	Quantity int
}

func (o *Orange) Increase(n int) {
	o.Quantity += n
}

func (o *Orange) Decrease(n int) {
	o.Quantity -= n
}

func (o *Orange) String() string {
	return fmt.Sprintf("%v", o.Quantity)
}

func main() {
	var orange Orange
	orange.Increase(10)
	orange.Decrease(5)
	fmt.Println(orange)
}

Provide the proper code solution.

Answer:

This is a trick question because you might think this has something to do with the member variable Quantity being set incorrectly, but actually, it will be set to 5 as expected. The real problem here, which is easy to overlook, is that the String() method that implements the fmt.Stringer() interface will not be invoked when the object orange is being printed with fmt.Println() function, because the method String() is not being defined on a value but only on a pointer:

var orange Orange
orange.Increase(10)
orange.Decrease(5)
fmt.Println(orange)
// Output: {5}

orange := &Orange{}
orange.Increase(10)
orange.Decrease(5)
fmt.Println(orange)
// Output: 5

That is a subtle one, but the fix is simple. You need to redefine the String() method on a value instead of a pointer, and in that case, it will work for both pointers and values:

func (o Orange) String() string {
	return fmt.Sprintf("%v", o.Quantity)
}
View

How would you implement a stack and a queue in Go? Explain and provide code examples.

Answer:

You use slices to implement a stack or queue by yourself:

type Stack []int
func (s Stack) Empty() bool { return len(s) == 0 }
func (s *Stack) Push(v int) { (*s) = append((*s), v) }
func (s *Stack) Pop() int {
	v := (*s)[len(*s)-1]
	(*s) = (*s)[:len(*s)-1]
	return v
}

type Queue []int
func (q Queue) Empty() bool    { return len(q) == 0 }
func (q *Queue) Enqueue(v int) { (*q) = append((*q), v) }
func (q *Queue) Dequeue() int {
	v := (*q)[0]
	(*q) = (*q)[1:len(*q)]
	return v
}

func main() {
	s := Stack{}
	s.Push(1)
	s.Push(2)
	fmt.Println(s.Pop())
	fmt.Println(s.Pop())
	fmt.Println(s.Empty())
	// Output:
	// 2
	// 1
	// true

	q := Queue{}
	q.Enqueue(1)
	q.Enqueue(2)
	fmt.Println(q.Dequeue())
	fmt.Println(q.Dequeue())
	fmt.Println(q.Empty())
	// Output:
	// 1
	// 2
	// true
}

The queue implementation above is correct, but it is suboptimal. There are better but lengthier implementations, like this one.

Occasionally, you would prefer the Go standard library’s container/list to implement them for their conciseness, genericity, and extra list data structure related operations:

stack := list.New()
stack.PushBack(1)
stack.PushBack(2)
fmt.Println(stack.Remove(stack.Back()))
fmt.Println(stack.Remove(stack.Back()))
fmt.Println(stack.Len() == 0)
// Output:
// 2
// 1
// true

queue := list.New()
queue.PushBack(1)
queue.PushBack(2)
fmt.Println(queue.Remove(queue.Front()))
fmt.Println(queue.Remove(queue.Front()))
fmt.Println(queue.Len() == 0)
// Output:
// 1
// 2
// true

Although, their usage is generally discouraged for their slower performance, compared to slices iteration pattern. Let’s compare the two following examples:

// Iterate through a list and print its contents.
for e := queue.Front(); e != nil; e = e.Next() {
    fmt.Println(e.Value)
}
for _, e := range queue {
    fmt.Println(e)
}

“Always use a slice.”, Dave Cheney

Another possibility to implement a queue is to use buffered channels, but this is never a good idea, because:

  1. The buffer size is determined at the channel creation and cannot be increased.
  2. It is impossible to peek at the next queue element without retrieving it from the queue.
  3. There is a risk of deadlock: “Novices are sometimes tempted to use buffered channels within a single goroutine as a queue, lured by their pleasingly simple syntax, but this is a mistake. Channels are deeply connected to goroutine scheduling, and without another goroutine receiving from the channel, a sender—and perhaps the whole program—risks becoming blocked forever. If all you need is a simple queue, make one using a slice.”, Brian Kernighan.
View

Explain the architecture of Django?

Answer:

Django is based on MVC architecture. It contains the following layers:

Models: It describes the database schema and data structure.

Views: The view layer is a user interface. It controls what a user sees, the view retrieves data from appropriate models and execute any calculation made to the data and pass it to the template.

Templates: It determines how the user sees it. It describes how the data received from the views should be changed or formatted for display on the page.

Controller: Controller is the heart of the system. It handles requests and responses, setting up database connections and loading add-ons. It specifies the Django framework and URL parsing.

View

What is Python really? You can (and are encouraged) make comparisons to other technologies in your answer

Answer:

Here are a few key points:

  • Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby.

  • Python is dynamically typed, this means that you don't need to state the types of variables when you declare them or anything like that. You can do things like x=111and then x="I'm a string" without error

  • Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++'s publicprivate), the justification for this point is given as "we are all adults here"

  • In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects

  • Writing Python code is quick but running it is often slower than compiled languages. Fortunately, Python allows the inclusion of C based extensions so bottlenecks can be optimised away and often are. The numpy package is a good example of this, it's really quite quick because a lot of the number crunching it does isn't actually done by Python

  • Python finds use in many spheres - web applications, automation, scientific modelling, big data applications and many more. It's also often used as "glue" code to get other languages and components to play nice.

  • Python makes difficult things easy so programmers can focus on overriding algorithms and structures rather than nitty-gritty low level details.

View

Fill in the missing code:

def print_directory_contents(sPath):
    """
    This function takes the name of a directory 
    and prints out the paths files within that 
    directory as well as any files contained in 
    contained directories. 

    This function is similar to os.walk. Please don't
    use os.walk in your answer. We are interested in your 
    ability to work with nested structures. 
    """
    fill_this_in

Answer:

def print_directory_contents(sPath):
    import os                                       
    for sChild in os.listdir(sPath):                
        sChildPath = os.path.join(sPath,sChild)
        if os.path.isdir(sChildPath):
            print_directory_contents(sChildPath)
        else:
            print(sChildPath)

Pay Special Attention

  • Be consistent with your naming conventions. If there is a naming convention evident in any sample code, stick to it. Even if it is not the naming convention you usually use
  • Recursive functions need to recurse and terminate. Make sure you understand how this happens so that you avoid bottomless callstacks
  • We use the os module for interacting with the operating system in a way that is cross platform. You could say sChildPath = sPath + '/' + sChild but that wouldn't work on windows
  • Familiarity with base packages is really worthwhile, but don't break your head trying to memorize everything, Google is your friend in the workplace!
  • Ask questions if you don't understand what the code is supposed to do
  • KISS! Keep it Simple, Stupid!
View

Python and multi-threading. Is it a good idea? List some ways to get some Python code to run in a parallel way.

Answer:

Python doesn't allow multi-threading in the truest sense of the word. It has a multi-threading package but if you want to multi-thread to speed your code up, then it's usually not a good idea to use it. Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your 'threads' can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core. All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn't a good idea.

There are reasons to use Python's threading package. If you want to run some things simultaneously, and efficiency is not a concern, then it's totally fine and convenient. Or if you are running code that needs to wait for something (like some IO) then it could make a lot of sense. But the threading library won't let you use extra CPU cores.

Multi-threading can be outsourced to the operating system (by doing multi-processing), some external application that calls your Python code (eg, Spark or Hadoop), or some code that your Python code calls (eg: you could have your Python code call a C function that does the expensive multi-threaded stuff).

View

Explain how to overload constructors or methods in Python.

Answer:

Python’s constructor – _init__ () is a first method of a class. Whenever we try to instantiate a object __init__() is automatically invoked by python to initialize members of an object.

View

What is JSON? How would convert JSON data into Python data?

Answer:

JSON – stands for JavaScript Object Notation. It is a popular data format for storing data in NoSQL
databases. Generally JSON is built on 2 structures.
1. A collection of <name, value> pairs.
2. An ordered list of values.
As Python supports JSON parsers, JSON-based data is actually represented as a dictionary in Python. You can convert json data into python using load() of json module.

View

Name and explain the three magic methods of Python that are used in the construction and initialization of custom Objects.

Answer:

The 3 magic methods of Python that are used in the construction and initialization of custom Objects are: init__, new , and del__.
new – this method can be considered as a “constructor”. It is invoked to create an instance of a class with the statement say, myObj = MyClass()
init__ — It is an “initializer”/ “constructor” method. It is invoked whenever any arguments are passed at the time of creating an object. myObj = MyClass(‘Pizza’,25)
del- this method is a “destructor” of the class. Whenever an object is deleted,
invocation of del__ takes place and it defines behaviour during the garbage collection. Note: new , del are rarely used explicitly.

View

What Code Can We Put At The Third Line Of The Definition Of Class B To Invoke Its Superclass’s Constructor?

class A:
    def __init__(self, i = 1):
        self.i = i
 
class B(A):
    def __init__(self, j = 2):
        ___________________
        self.j = j
 
def main():
    b = B()
    print(b.i, b.j)
 
main()

 

Quiz

What is the output when the following instruction is executed?

print  ('+55'.zfill(5))
Quiz

Which of the following is the output of the following Python instruction?

print  ('am'.zfill(5))
Quiz

Which of the following is the output of the instructions mentioned below?

def test1(param):
 return str(param)

def test2(param):
 return str(2 * param)

result = test1(1) + test2(2)
print(result)
Quiz

Which of the following is the output of the instructions given below?

mylist=[1, 5, 9, int('0')]
print(sum(mylist))
Quiz

What is REPL in context of Node?

Answer:

REPL stands for Read Eval Print Loop and it represents a computer environment like a window console or unix/linux shell where a command is entered and system responds with an output. Node.js or Node comes bundled with a REPL environment. It performs the following desired tasks.

  • Read - Reads user's input, parse the input into JavaScript data-structure and stores in memory.

  • Eval - Takes and evaluates the data structure

  • Print - Prints the result

  • Loop - Loops the above command until user press ctrl-c twice.

View

What is Callback?

Answer:

Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is such a way that they supports callbacks. For example, a function to read a file may start reading file and return the control to execution environment immidiately so that next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process high number of request without waiting for any function to return result.

View

Name some of the flags used in read/write operation on files.

Answer:

flags for read/write operations are following:

  • r - Open file for reading. An exception occurs if the file does not exist.

  • r+ - Open file for reading and writing. An exception occurs if the file does not exist.

  • rs - Open file for reading in synchronous mode. Instructs the operating system to bypass the local file system cache. This is primarily useful for opening files on NFS mounts as it allows you to skip the potentially stale local cache. It has a very real impact on I/O performance so don't use this flag unless you need it. Note that this doesn't turn fs.open() into a synchronous blocking call. If that's what you want then you should be using fs.openSync()

  • rs+ - Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about using this with caution.

  • w - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

  • wx - Like 'w' but fails if path exists.

  • w+ - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).

  • wx+ - Like 'w+' but fails if path exists.

  • a - Open file for appending. The file is created if it does not exist.

  • ax - Like 'a' but fails if path exists.

  • a+ - Open file for reading and appending. The file is created if it does not exist.

  • ax+' - Like 'a+' but fails if path exists.

View

© 2017 QuizBucket.org