Dry Stuff

#Interview Key Words Original from posts

#Python

##Important Concepts

###Data Models ###Descriptor Another paper PPT

####Definition If any of __get__(), __set__(), and __delete__() these methods are defined for an object, it is said to be a descriptor.

####Descriptor Protocol

descr.__get__(self, obj, type=None) --> value
descr.__set__(self, obj, value) --> None
descr.__delete__(self, obj) --> None

####Invoking

####Use Case 感觉看了这里才稍微有点点知道这东西是干吗用的

####Property property(fget=None, fset=None, fdel=None, doc=None) -> property attribute 我觉得这个才讲的比较清楚

x = property(getx, setx, delx, "I'm the 'x' property.")

If then c is an instance of C, c.x will invoke the getter, c.x = value will invoke the setter and del c.x the deleter.

####Bound vs Unbound

感觉Unbound method主要就是没有绑定instance的method. 一般来说是不能运行的, 但是如果用了decorator @staticmethod, 就可以tell metaclass type not to create a bound method.

####Static Methods and Class Methods

###Decorator Decorators allow you to inject or modify code in functions or classes”. In other words decorators allow you to wrap a function or class method call and execute some code before or after the execution of the original code. And also you can nest them e.g. to use more than one decorator for a specific function. Usage examples include – logging the calls to specific method, checking for permission(s), checking and/or modifying the arguments passed to the method etc.

A implement of decorator is classmethod() and staticmethod()

@f1(arg)
@f2
class Foo: pass

is equivalent to

class Foo: pass
Foo = f1(arg)(f2(Foo))

######The decorator is solving problems by avoid doing closure way

###Closure and nonlocal (说到closure就应该想到nonlocal)

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. 太长了的解释, 但是挺好.

###dir

###Classmethod vs Staticmethod First of all, both of @classmethod and @staticmethod are decorators.

###Magic Methods

###New Class vs Old Class

###Metaclass

<class ‘main.MyShinyClass’>

print(MyShinyClass()) # create an instance with the class

<main.MyShinyClass object at 0x8997cec>


#####Usage
* intercept a class creation
* modify the class
* return the modified class

#####Why metaclass over function?
* The intention is clear. When you read UpperAttrMetaclass(type), you know what's going to follow
* You can use OOP. Metaclass can inherit from metaclass, override parent methods. Metaclasses can even use metaclasses.
* You can structure your code better. You never use metaclasses for something as trivial as the above example. It's usually for something complicated. Having the ability to make several methods and group them in one class is very useful to make the code easier to read.
* You can hook on ```__new__```, ```__init__``` and ```__call__```. Which will allow you to do different stuff. Even if usually you can do it all in ```__new__```, some people are just more comfortable using __init__.
* These are called metaclasses, damn it! It must mean something!

#####Use Case
The main use case for a metaclass is creating an API. A typical example of this is the Django ORM.

classes are themselves instances. Of metaclasses.

###[Abstract Class](http://pymotw.com/2/abc/)

Abstract base classes are a form of interface checking more strict than individual hasattr() checks for particular methods.

#####Why?
Define a set of subclasses, so for large project, you won't forget to miss one of the method.

#####Work

```python
import abc

class PluginBase(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def load(self, input):
        """Retrieve data from the input source and return an object."""
        return

    @abc.abstractmethod
    def save(self, output, data):
        """Save the data object to the output."""
        return

#####Two ways to make this work:

###Some Words


###Yield

###Itertool

import itertools
horses = [1,2,3,4]
races = itertools.permutations(horses)
print list(races)

###Iterables, Iterators, Generators, Itertool

####Generator

#####Generator Expression Compare to list comprehension

  1. Generator doesn’t support indexing or slicing. Also can’t add anything.
  2. But save memory

#####Conclusion

  1. 必须包含yield语句的函数。
  2. 在调用时不会运行。
  3. 调用生成器时生成的生成器对象只能被使用一次(遍历)。
  4. 返回迭代器,但是不用关心迭代协议。

#####Why use Generator If you have infinite loops, or it may make inefficient use of memory when you have a really long list.

####Iterable

####Sequence定义

  1. Iterable
  2. Supports efficient element access using integer indices via the __getitem__() special method and defines a __len__() method that returns the length of the sequence. 也就是必须要支持下标搜索, 所以dict是一个iterable, 但是不是sequence.

####Iterator

Iterator Protocol就是implement以上两个method.

####关系

#####Generator vs Iterator All Generators must be Iterator, but no vise versa.

####For循环过程

for x in mylist:
    ...loop body...
  1. Gets an iterator for mylist: Call iter(mylist) -> this returns an object with a next() method (or __next__() in Python 3).
  2. Uses the iterator to loop over items: Keep calling the next() method on the iterator returned from step 1. The return value from next() is assigned to x and the loop body is executed. If an exception StopIteration is raised from within next(), it means there are no more values in the iterator and the loop is exited.

##Interview ###__new__() and __init__() __new__ is static class method, while __init__ is instance method. __new__ has to create the instance first, so __init__ can initialize it. Note that __init__ takes self as parameter. Until you create instance there is no self.

###isinstance(inst, class) Use this function to check if an object is an instance of a given class or of a subclass of it.

With Statement

In a few words the with statement allows you to executed code before and/or after a specific set of operations. For example if you open a file for reading and parsing no matter what happens during the parsing you want to be sure that at the end the file is closed. This is normally achieved using the try… finally construction but the with statement simplifies it usin the so called “context management protocol”. To use it with your own objects you just have to define __enter__ and __exit__ methods. Some standard objects like the file object automatically support this protocol. For more information you may check Understanding Python’s “with” statement.

###Underscore and Double Underscore

Private class/method/var are same since everything is object in python.

###PEP8 PEP 8 is a coding convention(a set of recommendations) how to write your Python code in order to make it more readable and useful for those after you.

###Python 2.x to 3.x

###xrange and range

###Pickling and unpickling pickle module accepts any python object converts it into a string representation & dumps it into a file(by using dump() function) which can be used later, process is called pickling. Whereas unpickling is process of retrieving original python object from the stored string representation for use.

###__repr__vs __str__ machine-headable vs human-readable

###Explain how python is interpreted. Python program runs directly from the source code. Each type Python programs are executed code is required. Python converts source code written by the programmer into intermediate language which is again translated it into the native language / machine language that is executed. So Python is an Interpreted language.

###How is memory managed in python?

###What is delegation? Delegation is an object oriented technique (also called a design pattern). Let’s say you have an object x and want to change the behaviour of just one of its methods. You can create a new class that provides a new implementation of the method you’re interested in changing and delegates all other methods to the corresponding method of x.

Need to see the example from the above link.

###Write a sample program to print the complete contents of a file, with a way to catch a missing file.

try:
    with open('filename','r') as file:
    print file.read()
except IOError:
    print 'no such file exists'

###Write a sample program to print the length of each line in a particular file, not counting whitespace at the ends.

with open('filename.txt', 'r') as file:
    print len(file.readline().rstrip())

###Remove Duplicates

list(set(dup_list))

###Random

###Python vs Other Languages

  1. Python is script language, Java C++ compiling language.
  2. Simpler

###Python数字精度问题 Flexible精度, you can test it by doing

import sys
sys.getsizeof(x)

where x is the number. You can get 24 or 36.

print sys.maxint

Also

>>> print type(1<<62)
<type 'int'>
>>> print type(1<<63)
<type 'long'>

But note this depends on the system is 32bit or 64bit


##My Search ###Lambda

###List/Dict Comprehension:

###Python Pros and Cons

#####Pros

#####Cons

###Python’s Thread

#####Cause Operations that read a variable or attribute, modifies it, and then writes it back are not thread-safe. Another thread may update the variable after it’s been read by the current thread, but before it’s been updated.

#####Example

# An very basic example
import threading

def worker(num):
    """thread worker function"""
    print 'Worker: %s' % num
    return

threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

#####Current Thread

threading.currentThread().getName()

#####Daemon vs. Non-Daemon Threads 意思就是daeomon thread will run wihtout blocking main program from exiting 如果不设的话主程序会等待所有thread运行完毕

#####Subclass 应该用

class MyThread(threading.Thread):
    def run(self):
      logging.debug('running')
      return

重写run()函数

#####Signaling Between Threads 用threading.Event()在thread之间传递信号

#####Lock Python’s built-in data structures (lists, dictionaries, etc.) are thread-safe as a side-effect of having atomic byte-codes for manipulating them (the GIL is not released in the middle of an update). Other data structures implemented in Python, or simpler types like integers and floats, don’t have that protection. To guard against simultaneous access to an object, use a Lock object.

#####Re-Entrant Locks The RLock class is a version of simple locking that only blocks if the lock is held by another thread.

lock = threading.Lock()
lock.acquire()
lock.release()

注意如果是普通的lock.acquire()就会一直等着lock release,程序就sb了 但是可以用

lock.acquire(0)
# or
lock = threading.RLock()

这样只会try一下,如果锁死就干别的去了

#####Semaphore Allow more than one worker access to a resource at a time(其实就是一个带counter的lock)

threading.Semaphore(2)

#####Synchronization Between Threads ######Event ######Condition 其实Condition就是Event + Lock.

event = threading.Event()

# a client thread can wait for the flag to be set
event.wait()

# a server thread can set or reset it
event.set()
event.clear()

# represents the addition of an item to a resource
condition = threading.Condition()

condition.acquire()
condition.notify() # signal that a new item is available
condition.release()

condition.wait

#####GIL Global Interpreter Lock Cpython use OS threads. Only one thread at a time is allowed to run Python code.

#####Reasons for GIL

#####Multi-threading vs Multi-processing

#####Other Choices (see slides 153)

#####总结

###Class Attributes

###Override and Overload

###Import

  1. import SomeModule 可以用import SomeModule.SomeName 调用时用 SomeModule.SomeName()
  2. from SomeModule import SomeName 可以直接用 SomeName()
  3. from SomeModule import * 可能mess up with your namespaces

###Self Used by method or anything inside a class to access method or varibles inside To use a reference of itself

###Namespace

###args, kargs

###Pass by Assignment

  1. If passing a mutable object, the method got an reference of the object and you can change it. But if you rebind the reference, outer scope wouldn’t know
  2. Immutable object is changed by rebind, so outer scope wouldn’t know.

Assignment Creates References, Not Copies

This is a core Python concept, which can cause problems when its behavior isn’t expected. In the following example, the list object assigned to the name L is referenced both from L and from inside of the list assigned to name M. Changing L in place changes what M references, too, because there are two references to the same object:

>>> L = [1, 2, 3]        # A shared list object
>>> M = ['X', L, 'Y']    # Embed a reference to L
>>> M
['X', [1, 2, 3], 'Y']

>>> L[1] = 0             # Changes M too
>>> M
['X', [1, 0, 3], 'Y']

This effect usually becomes important only in larger programs, and shared references are normally exactly what you want. If they’re not, you can avoid sharing objects by copying them explicitly; for lists, you can make a top-level copy by using an empty-limits slice:

>>> L = [1, 2, 3]
>>> M = ['X', L[:], 'Y']   # Embed a copy of L

>>> L[1] = 0               # Change only L, not M
>>> L
[1, 0, 3]
>>> M
['X', [1, 2, 3], 'Y']

Slice limits default to 0 and the length of the sequence being sliced. If both are omitted, the slice extracts every item in the sequence, and so makes a top-level copy (a new, unshared object). For dictionaries, use the dict.copy() method.

###Basic Immutable types Numbers, Strings, Tuples

Immutable Types Can’t Be Changed in Place. Remember that you can’t change an immutable object.

###Exception and Error

####Common Errors

######Why are Python exceptions named “Error”? 因为名字命名要有意义…

try:
    int('100+5')
except ValueError:
    print "Oh I can't"


class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return "WRONG %d" % self.value
# 基本就是重写这两个函数

###Special Data Structures

###Special function


##Just Interesting

###“Sticky” Method Problem:

>>> def function(data=[]):
...     data.append(1)
...     return data
...
>>> function()
[1]
>>> function()
[1, 1]
>>> function()
[1, 1, 1]

So when def is called, it creates a function object, and it also evaluates the default values. It will always be the same object when you call function, unless you def a new one.

###Cyclic Datastructures Cyclic Datastructures Can Cause Loops

Although fairly rare in practice, if a collection object contains a reference to itself, it’s called a cyclic object. Python prints a […] whenever it detects a cycle in the object, rather than getting stuck in an infinite loop:

>>> L = ['grail']  # Append reference back to L
>>> L.append(L)    # Generates cycle in object
>>> L
['grail', [...]]

###Reference Reference


System Design Data Structure

##Bloom Filter ###特点

###适用范围 数据字典,数据判重,数据求交集

##Heap

###适用范围 海量数据前n大,并且n比较小,堆可以放入内存

###特点

##双层桶划分

###适用范围

##Hashtable ###Using hash function is two steps

  1. Map the key to an integer
  2. Map the integer to a bucket

###Hash的两个特性:

常见的Hash方法是MD5 and SHA1

###简单的Hash Functions:

This seems to be the method that the theoreticians like.(可能永远都不需要知道)

###Collision

最重要的一点是Mod by something

class KeyValue:
    def __init__(self,key,value):
        self.key=key
        self.value=value
    def __str__(self):
        return self.key+":"+str(self.value)
class HashTable:
    SIZE=10
    def __init__(self):
        i=0
        self.list=[]
        while i<self.SIZE:
            self.list.append([])
            i=i+1

    def getValue(self,key):
        h = self.hash (key)
        bucket = self.list[h]
        for kv in bucket:
            if kv.key==key:
                return kv.value
    def setValue(self,key,value):
        h = self.hash(key)
        # should search first so we don't put key in twice, but for now ignore
        self.list[h].append(KeyValue(key,value))
    def hash(self,key):
        i=0
        total=0
        while i<len(key):
            total = total+ord(key[i])
            i=i+1
        return total % self.SIZE

htable= HashTable()
htable.setValue("wolber","359-4787")
htable.setValue("reblow","akfj-askf")
print htable.getValue("wolber")
print htable.getValue("reblow")

#Javascript

###Javascript types Number, String, Boolean, Function, Object, Null, and Undefined

In JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as:

var TestVar;
alert(TestVar); //shows undefined
alert(typeof TestVar); //shows undefined

null is an assignment value. It can be assigned to a variable as a representation of no value:

var TestVar = null;
alert(TestVar); //shows null
alert(typeof TestVar); //shows object

From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

###Var If you’re in the global scope then there’s no difference.

If you’re in a function then “var” will create a local variable, “no var” will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):

// These are both globals
var foo = 1;
bar = 2;

function()
{
    var foo = 1; // Local
    bar = 2;     // Global

    // Execute an anonymous function
    (function()
    {
        var wibble = 1; // Local
        foo = 2; // Inherits from scope above (creating a closure)
        moo = 3; // Global
    }())
}

If you’re not doing an assignment then you need to use var:

var x; // Declare x

###Javascript Inheritance

function Animal() {};

Animal.prototype.eat = function(){
    alert("I'm eating");
}

function Bird(){}

Bird.prototype = new Animal();

Bird.prototype.fly = function(){
    alert("I believe I can fly");
}

var aBird = new Bird();
aBird.fly(); // Should fly now
aBird.eat(); // Should eat now


###this Javascript’s this keyword normally refers to the object that owns the method, but it depends on how a function is called. Basically, it points to the currently in scope object that owns where you are in the code. When working within a Web page, this usually refers to the Window object. If you are in an object created with the new keyword, the this keyword refers to the object being created. When working with event handlers, JavaScript’s this keyword will point to the object that generated the event.

###Keep on mind this thing.

var elements = [...];
for (var i = 0, n = elements.length; i < n; i++) {
  var el = elements[i];
  el.addEventListener('click', function() {
    doAllOfMayasThingsQuickly(i, el);
  });
}

###JavaScript is an object-based language based on prototypes, rather than being class-based.

###CSS Box Model From outer to inner: Margin, Border, Padding and Content

###document.

document.getElementById
document.getElementsByTagName
document.getElementsByName
document.getElementsByClassName

$('#ID')
$('.Class')

###Latency

###HTML <!DOCTYPE> Declaration

###DOM Document Object Model

####涵盖了一切的神物


###In JavaScript, what is the difference between var x = 1 and x = 1? Answer in as much or as little detail as you feel comfortable. Novice JS programmers might have a basic answer about locals vs globals. Intermediate JS guys should definitely have that answer, and should probably mention function-level scope. Anyone calling themselves an “advanced” JS programmer should be prepared to talk about locals, implied globals, the window object, function-scope, declaration hoisting, and scope chains. Furthermore, I’d love to hear about [[DontDelete]], hoisting precedence (parameters vs var vs function), and undefined.

###Basic JS programmming Scope of variable What is Associative Array? How do we use it?

###OOPS JS Difference between Classic Inheritance and Prototypical Inheritance

What is difference between private variable, public variable and static variable? How we achieve this in JS? How to add/remove properties to object in run time? How to achieve inheritance ? How to extend built-in objects? Why extending array is bad idea?

###DOM and JS Difference between browser detection and feature detection DOM Event Propagation Event Delegation Event bubbling V/s Event Capturing

###Misc Graceful Degradation V/s Progressive Enhancement

###What is the difference between “==” and “===”?

###What are Javascript closures? When would you use them? Two one sentence summaries:

A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned. A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created.

The following code returns a reference to a function:

function sayHello2(name) {var text = 'Hello' + name; // local variable
var sayAlert = function() { alert(text); }
return sayAlert;
}

Closures reduce the need to pass state around the application. The inner function has access to the variables in the outer function so there is no need to store the information somewhere that the inner function can get it.

This is important when the inner function will be called after the outer function has exited. The most common example of this is when the inner function is being used to handle an event. In this case you get no control over the arguments that are passed to the function so using a closure to keep track of state can be very convenient.

###Closure

#Linux

###Compiled Language vs Scripting Language

#SQL ###ORM Object-relational mapping Like SQLAlchemy

###Language #####Inner Join Inner Join

#####Left Join Left Join

Right Join

Right Join

#####Full Join Full Join

#OS Knowledge

###REST vs SOAP

###Encoding #####Unicode, Ascii, UTF-8

#####hex and integer

###Big O

#####Master Method T(n) = aT(n/b) + f(n)

####Duke大法 #####步骤

  1. 写出Master Method方程
  2. 写出base case T(1) = ??
  3. 将递推式转化为通项式
Recurrence Algorithm Big-O Solution
T(n) = T(n/2) + O(1) Binary Search O(log n)
T(n) = T(n-1) + O(1) Sequential Search O(n)
T(n) = 2 T(n/2) + O(1) tree traversal O(n)
T(n) = T(n-1) + O(n) Selection Sort (other n2 sorts) O(n^2)
T(n) = 2 T(n/2) + O(n) Mergesort (average case Quicksort) O(n log n)
T(n) = n * T(n-1) + O(n)   O(n!)

####手算递归 以Subset/Combination为例,主要是主动递推然后尝试找规律,最后化简为T(1)的然后带入计算

T(n) = T(n-1) + T(n-2) + T(n-3) + ... + T(1) + O(1)
     = 2T(n-2) + 2T(n-3) + ... + 2T(1) + 2O(1)
     = 4T(n-3) +4T(n-4) + 4(T1) + 4O(1)
     = 2^(3-1)T(n-3) + ... + 2^(3-1)O(1)
     = 2^(n-1-1) * T(n-n+1) + ... + 2^(n-1-1)O(1)
     = 1/4 * 2^n * T(1) + 1/4 * 2^n * O(1)
     = O(2^n)

###Lock Lock: at most one thread can hold the lock, and therefore only on thread can access the shared resource.

Deadlock:

Or:

###Monitor & Semaphore

A Monitor is an object designed to be accessed from multiple threads. The member functions or methods of a monitor object will enforce mutual exclusion, so only one thread may be performing any action on the object at a given time. If one thread is currently executing a member function of the object then any other thread that tries to call a member function of that object will have to wait until the first has finished. Just a lock

A Semaphore is a lower-level object. You might well use a semaphore to implement a monitor. A semaphore essentially is just a counter. When the counter is positive, if a thread tries to acquire the semaphore then it is allowed, and the counter is decremented. When a thread is done then it releases the semaphore, and increments the counter. A counter. One example Mutex, hold and wait.

###Prevention:

  1. Mutual Exclusion: Limited access to a resource. Free the limited quantity of resource.增大循环数量或者resource数量
  2. Hold and wait: release the lock before request for another resource.
  3. No preemption: force other process to release the lock.
  4. Circular wait: 减少循环发生的可能性 reduce the occurrence to circular access for a resource.s

###Thread and Process A process can be thought of as an instance of a program in execution Each process is an in- dependent entity to which system resources (CPU time, memory, etc ) are allocated and each process is executed in a separate address space One process cannot access the variables and data structures of another process If you wish to access another process’ resources, inter-process communications have to be used such as pipes, files, sockets etc

A thread uses the same stack space of a process A process can have multiple threads A key difference between processes and threads is that multiple threads share parts of their state Typically, one allows multiple threads to read and write the same memory (no processes can directly access the memory of another process) However, each thread still has its own registers and its own stack, but other threads can read and write the stack memory

A thread is a particular execution path of a process; when one thread modifies a process resource, the change is immediately visible to sibling threads

###Big vs Little Endian: In big endian, the most significant byte is stored at the memory address location with the lowest address This is akin to left-to-right reading order Little endian is the reverse: the most significant byte is stored at the address with the highest address

###Memory

But Basically,

#####Compare | Stack | Heap | | — | — | | Stored in computer RAM just like the heap. | Stored in computer RAM just like the stack. | | Variables created on the stack will go out of scope and automatically deallocate. | Variables on the heap must be destroyed manually and never fall out of scope. The data is freed with delete, delete[] or free | | Much faster to allocate in comparison to variables on the heap. | Slower to allocate in comparison to variables on the stack. | | Implemented with an actual stack data structure. | Used on demand to allocate a block of data for use by the program. | | Stores local data, return addresses, used for parameter passing | Can have fragmentation when there are a lot of allocations and deallocations | | Can have a stack overflow when too much of the stack is used. (mostly from infinite (or too much) recursion, very large allocations) | In C++ data created on the heap will be pointed to by pointers and allocated with new or malloc | | Data created on the stack can be used without pointers. | Can have allocation failures if too big of a buffer is requested to be allocated. | | You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big. | You would use the heap if you don’t know exactly how much data you will need at runtime or if you need to allocate a lot of data.| | Usually has a maximum size already determined when your program starts | Responsible for memory leaks |

#####Memory Leak A memory leak may happen when an object is stored in memory but cannot be accessed by the running code.

######Cause of Memory Leak

#####Stack (Memory) When a function calls another function which calls another function, this memory goes onto the stack An int (not a pointer to an int) that is created in a function is stored on the stack #####Heap (Memory) When you allocate data with new() or malloc(), this data gets stored on the heap

The JVM divided the memory into following sections:

This division of memory is required for its effective management.

Of all of the above 4 sections, you need to understand the allocation of memory in Stack & Heap the most, since it will affect your programming efforts

###External Sort 20GB file, one String per line, how to sort them. Divide the file into x megabytes each, where x is the available memory that we have. Sort each chunk separately and save back to the file system. Once all sorted, we then merge the chunk, one by one. At the end, we will have a fully sorted file.

###what happens when you type in a URL in browser

  1. browser checks cache; if requested object is in cache and is fresh, skip to #9
  2. browser asks OS for server’s IP address
  3. OS makes a DNS lookup and replies the IP address to the browser(host/dig)
  4. browser opens a TCP connection to server (this step is much more complex with HTTPS)
  5. browser sends the HTTP request through TCP connection
  6. browser receives HTTP response and may close the TCP connection, or reuse it for another request
  7. browser checks if the response is a redirect (3xx result status codes), authorization request (401), error (4xx and 5xx), etc.; these are handled differently from normal responses (2xx)
  8. if cacheable, response is stored in cache
  9. browser decodes response (e.g. if it’s gzipped)
  10. browser determines what to do with response (e.g. is it a HTML page, is it an image, is it a sound clip?)
  11. browser renders response, or offers a download dialog for unrecognized types

###Transmission Control Protocol (TCP)

  1. Transmission Control Protocol (TCP) is a connection oriented protocol, which means the devices should open a connection before transmitting data and should close the connection gracefully after transmitting the data.
  2. Transmission Control Protocol (TCP) assure reliable delivery of data to the destination.
  3. Transmission Control Protocol (TCP) protocol provides extensive error checking mechanisms such as flow control and acknowledgment of data.
  4. Sequencing of data is a feature of Transmission Control Protocol (TCP).
  5. Delivery of data is guaranteed if you are using Transmission Control Protocol (TCP).
  6. Transmission Control Protocol (TCP) is comparatively slow because of these extensive error checking mechanisms
  7. Multiplexing and Demultiplexing is possible in Transmission Control Protocol (TCP) using TCP port numbers.
  8. Retransmission of lost packets is possible in Transmission Control Protocol (TCP).

###User Datagram Protocol (UDP)

  1. User Datagram Protocol (UDP) is Datagram oriented protocol with no overhead for opening, maintaining, and closing a connection.
  2. User Datagram Protocol (UDP) is efficient for broadcast/multicast transmission.
  3. User Datagram protocol (UDP) has only the basic error checking mechanism using checksums.
  4. There is no sequencing of data in User Datagram protocol (UDP) .
  5. The delivery of data cannot be guaranteed in User Datagram protocol (UDP) .
  6. User Datagram protocol (UDP) is faster, simpler and more efficient than TCP. However, User Datagram protocol (UDP) it is less robust then TCP
  7. Multiplexing and Demultiplexing is possible in User Datagram Protcol (UDP) using UDP port numbers.

There is no retransmission of lost packets in User Datagram Protcol (UDP).

###Serialization Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

#Java & C

###Garbage Collection

两种方法:

System.gc() method may be used to call it explicitly.

###Private Constructor no one outside class can directly instantiate this class. (or provide a static public method). class cannot be inherited

###Executed finally

  1. Virtual machine exits.
  2. Thread get killed.

###Final, Finally, Finalize

####Final variable(primitive):value cannot change

variable(reference): reference variable cannot point to any other object on the heap

method: method cannot be overridden

class: class cannot be subclassed.

####Finally used after try-catch block which will always be executed.

####Finalize() callled by the garbage collector when it determinesthat no more references exist.

###C++ vs Java A very common question in an interview is “describe the differences between C++ and Java ” If you aren’t comfortable with any of these concepts, we recommend reading up on them

  1. Java runs in a virtual machine
  2. C++ natively supports unsigned arithmetic
  3. In Java, parameters are always passed by value (or, with objects, their references are passed by value) In C++, parameters can be passed by value, pointer, or by reference
  4. Java has built-in garbage collection
  5. C++ allows operator overloading
  6. C++ allows multiple inheritance of classes

###Static

###Abstract

###Primitive Types: byte, short, int, long, float, double, boolean, char

###Three Principles

###Three kinds of Polymorphism:

###Class, Constructor, Casting Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform.

Constructor is a special kind of method that determines how an object is initialized when created.

Constructor and Method Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.

Casting is used to convert the value of one type to another.

##Missing Package Access Here

A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.

###Difference between abstract class and interface?(略傻逼)

  1. All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract.
  2. In abstract class, key word abstract must be used for the methods whereas interface we need not use that keyword for the methods.
  3. Abstract class must have subclasses whereas interface can’t have subclasses.

###Thread:

  1. Implementing the java.lang.Runnable interface
  public interface Runnable{
      void run();
  }

  RunnableThreadExample instance = new RunnableThreadExample();
  Thread thread = new Thread(instance);
  thread.start();
  1. Extending the java.lang.Thread class
  ThreadExample instance = new ThreadExample();
  instance.start();

Runnable interface 好在:

  1. No multiple inheritance
  2. Inheriting the full thread class would be excessive.

###Abstract Tips 抽象类中不一定包含抽象方法,但是包含抽象方法的类一定要被声明为抽象类。抽象类本身不具备实际的功能,只能用于派生其子类。抽象类中可以包含构造方法,但是构造方法不能被声明为抽象。

调用抽象类中的方法(抽象方法和非抽象方法),如果方法是static的,直接 抽象类.方法 就可以了;如果是非static的则必须需要一个继承的非抽象类,然后用这个非抽象类的实例来调用方法。

  1. 抽象类可以有实例变量,而接口不能拥有实例变量,接口中的变量都是静态(static)的常量(final)
  2. 抽象类可以有非抽象方法,而接口只能有抽象方法。 接口中的所有方法都是抽象方法

###Malloc Memory allocated using malloc is persistent—i e , it will exist until either the programmer frees the memory or the program is terminated void *malloc(size_t sz) Malloc takes as input sz bytes of memory and, if it is successful, returns a void pointer which indicates that it is a pointer to an unknown data type void free(void * p) Free releases a block of memory previously allocated with malloc, calloc, or realloc

###HashMap & Hashtable

Map(K,V) is an interface which Hashtable and HashMap implement it. Priority Queue 可以选择ordered or unordered 反正insert 和extract一个是O(n)一个是O(1) Heap insert和extract都是O(logn)

Nested Class
class OuterClass {
    ...
    static class StaticNestedClass {
        ...
    }
    class InnerClass {
        ...
    }
}

###Logical grouping of classes If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such “helper classes” makes their package more streamlined.

###Increased encapsulation Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A’s members can be declared private and B can access them. In addition, B itself can be hidden from the outside world. More readable, maintainable code Nesting small classes within top-level classes places the code closer to where it is used.

###Static Nested Class OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.

###Inner Class An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. The next figure illustrates this idea. OuterClass.InnerClass innerObject = outerObject.new InnerClass();

###Java: Difference between implementing Comparable and Comparator?

####Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

####Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.


Comparable lets a class implement its own comparison:

By comparison, Comparator is an external comparison:


###NodeJS Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Reference