All posts by admin

NSURLSession basics

ref – http://code.tutsplus.com/tutorials/networking-with-nsurlsession-part-1–mobile-21394

http://code.tutsplus.com/tutorials/networking-with-nsurlsession-part-2–mobile-21581

1) Simple GET of data

2) Downloading a file using NSURLSessionDownloadDelegate protocol

So we want to download a file. However, we want to see what percentage we are at, as well as when the file has finished downloading.

A session configuration object is nothing more than a dictionary of properties that defines how the session it is tied to behaves. A session has one session configuration object that dictates cookie, security, and cache policies, the maximum number of connections to a host, resource and network timeouts, etc.

Once a session is created and configured by a NSURLSessionConfiguration instance, the session’s configuration cannot be modified. If you need to modify a session’s configuration, you have to create a new session. Keep in mind that it is possible to copy a session’s configuration and modify it, but the changes have no effect on the session from which the configuration was copied.

Once a session is created and configured by a NSURLSessionConfiguration instance, the session’s configuration cannot be modified. A SessionConfiguration is immutable. If you need to modify a session’s configuration, you have to create a new session. Keep in mind that it is possible to copy a session’s configuration and modify it, but the changes have no effect on the session from which the configuration was copied.

  1. Use a private UIImageView to hold the image
  2. privately conform to NSURLSessionDownloadDelegate protocol
  3. Implement protocol methods
ViewController.m

Add the image holder to your view hierarchy

Then use a NSURLSession to get a task running

Notice that we first get a default Session Configuration object. Then we pass it into the session to be used.

Configuring a session configuration object is as simple as modifying its properties as shown in the example. We can then use the session configuration object to instantiate a session object. The session object serves as a factory for data, upload, and download tasks, with each task corresponding to a single request.

Finally, implement the protocol methods

Make sure you use the main queue, to update your image holder with the data you just downloaded.

Also, if you are to use a progress view to show updates on progress, make sure you dispatch a code block onto the main queue, so that the main thread can run the code and show it.

http://stackoverflow.com/questions/31254725/transport-security-has-blocked-a-cleartext-http

concurrency, asynchronous, parrallelism

ref – http://stackoverflow.com/questions/4844637/what-is-the-difference-between-concurrency-parallelism-and-asynchronous-methods

Concurrent and parallel are effectively the same principle as you correctly surmise, both are related to tasks being executes simultaneously although I would say that parallel tasks should be truly multitasking, executed at the same time whereas concurrent could mean that the tasks are sharing the execution thread while still appearing to be executing in parallel.

Asynchronous methods aren’t directly related to the previous two concepts, asynchrony is used to present the impression of concurrent or parallel tasking but effectively an asynchronous method call is normally used for a process that needs to do work away from the current application and we don’t want to wait and block our application awaiting the response.

For example, getting data from a database could take time but we don’t want to block our UI waiting for the data. The async call takes a call-back reference and returns execution back to your code as soon as the request has been placed with the remote system. Your UI can continue to respond to the user while the remote system does whatever processing is required, once it returns the data to your call-back method then that method can update the UI (or hand off that update) as appropriate.

From the User perspective it appears like multitasking but it may not be.

EDIT

It’s probably worth adding that in many implementations an asynchronous method call will cause a thread to be spun up but it’s not essential, it really depends on the operation being executed and how the response can be notified back to the system.

Concurrency vs Asynchronous

http://blog.stevenedouard.com/asynchronousness-vs-concurrency/

Concurrency

There are various different ways of accomplishing concurrency. One of them is parallelism–having multiple CPUs working on the different tasks at the same time. For example, its like having more than 1 chef working on 5 recipes AT THE SAME TIME.

But parallelism is not the only way to achieve concurrency. Another is by task switching, which works like this: Task A works up to a certain point, then the CPU working on it stops and switches over to task B, works on it for a while, and then switches back to task A. If the time slices are small enough, it may appear to the user that both things are being run in parallel, even though they’re actually being processed in serial by a multitasking CPU.

A characteristic of task switching is asynchronous. Asynchronous is when a task DOES NOT BLOCK the worker, and the worker is free to work on other parts of other tasks.

Asynchronous is when a chef is working on 5 dishes at the same time. Going through steps of each recipes one after another WITHOUT IT WAITING (or blocking in IT terms). The chef does not let the recipe step BLOCK HIM from moving on to other recipe tasks.

For example

He preps dish 1, apple pie. then puts it into the oven for a 1 hour bake. Now, the baking process DOES NOT BLOCK him from working on other recipes. So that he does not waste time waiting on the oven, he moves on to other recipe(s).

While dish 1 bakes, he moves on to dish 2, which to chop up some Potatoes and salt some beef chunks. After the potatoes are prepped, he throws them into a pot and starts simmering them with some beef chunks. The simmering process DOES NOT BLOCK HIM from moving on to other recipes. Thus, he is free to move on to other tasks of other recipes.

He then moves on to dish 3, which is to simply toss some salad. He is done with dish 3.

He then goes on to dish 4, which to boil some pasta. Fire on high and the water warms. The boiling process DOES NOT BLOCK him from working on other recipes, so he moves on.

For dish 5, he just chops some fruits and throws yogurt on top. Done!

Dish 4 (al dente pasta) water has now boiled and it DINGS our chef so he knows. He then comes back to Dish 4, salts the water, then throw in pasta. The pasta needs to cook for a few minutes. This cooking process DOES NOT BLOCK him, so he moves on to other dishes.

All Dishes are not processing in some way…so the chef now waits. After a few minutes, Dish 4 (pasta) finishes boiling. It DINGS the chef to let him know. The chef takes the pasta out and finishes preparing for it.

Now, the chef has nothing to do and waits for the next DING.

After an hour, dish 1 finishes baking and DINGS him. Letting him know that dish 1 needs attention. The chef goes to dish 1, takes out the apple pie..puts some vanilla ice cream on the side, and done.

He now has nothing to do and waits. Then after another hour, dish 2 finishes simmering and a timer DINGS him. He then slowly spoons out the morsels, chops some parsley, and finishes dish 2.

So as you can see, asynchronous means that there is one worker, one process, one chef…but its working on multiple tasks.

No task is holding on to him. Whenever he hits a point of a recipe where the recipe needs to take some time (bake, simmer, boil..etc), then he moves on to the next recipe’s task.

In IT term, asynchronous-ness is the ability to NOT stop on a task which depends on an external system (like reading a file from the file system, or loading data from the internet) and continue the processing of the application.

global queue and their priorities

http://stackoverflow.com/questions/25052629/ios-gcd-difference-between-any-global-queue-and-the-one-with-background-priorit

  • DISPATCH_QUEUE_PRIORITY_HIGH
  • DISPATCH_QUEUE_PRIORITY_DEFAULT
  • DISPATCH_QUEUE_PRIORITY_LOW

are priority queues with tasks in them.

These queues are performed according to their priority as evident by their names.

Let’s say you have the queue with HIGH priority; tasks in that queue will be executed first; you would do that if one specific task needs to be finished as quick as possible even if it means that other tasks are delayed.

DISPATCH_QUEUE_PRIORITY_LOW – Items dispatched to the queue will run at low priority, i.e. the queue will be scheduled for execution after ALL default priority and high priority queues have been scheduled.

DISPATCH_QUEUE_PRIORITY_BACKGROUND

Let’s say you may have a task A that takes a long time, but it is Ok for that task to wait for other tasks to finish. For example, if there is work to do at NORMAL priority, that work will be done first, and only when there is a spare CPU doing nothing else, then your task A will be performed.

You would give that task A BACKGROUND priority.

Meaning of Global Queue

Other things, like system frameworks, may be scheduling in to it. It’s very easy to starve the priority bands – if there are a lot of DISPATCH_QUEUE_PRIORITY_HIGH tasks being scheduled, tasks at the default priority may have to wait quite a while before executing. And tasks in DISPATCH_QUEUE_PRIORITY_BACKGROUND may have to wait a very long time, as all other priorities above them must be empty.

Don’t abuse the global queue

A lot of developers abuse the global concurrent queue. They want a execute a block, need a queue, and just use that at the default priority. That kind of practice can lead to some very difficult to troubleshoot bugs. The global concurrent queue is a shared resource and should be treated with care. In most cases it makes more sense to create a private queue.

ref – http://stackoverflow.com/questions/9602042/whats-the-difference-between-the-global-queue-and-the-main-queue-in-gcd

thread priorities

-main- : 0.758065
DISPATCH_QUEUE_PRIORITY_HIGH : 0.532258
DISPATCH_QUEUE_PRIORITY_DEFAULT : 0.500000
DISPATCH_QUEUE_PRIORITY_LOW : 0.467742
DISPATCH_QUEUE_PRIORITY_BACKGROUND : 0.000000

Using Postman to query Node endpoints

start up your server


> node server.js

Then the output from the terminal would be like this:

Insert beer on port 3000
mongoose db connected

Use postman to send data

Make sure you select POST as your request verb.

type in the test url:
http://localhost:3000/api/

Select Body, because we are using POST data from a web form.

The body data comes from a x-www-form-urlencoded

For application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string — name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:

MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

This query string is stored in the BODY of the message packet.

So in POSTMAN, just put test as the key, and please work as the value.

postman-post

When you press “Send” in POSTMAN, you should see the output from your node terminal like so:


POST /api/
{ test: ‘please work’ }
{}
{}

As you can see, the results appear in req.body

Javascript Functions, scoping, and changing context

Since no inner function is declared, this function object is bound to the global scope.

In the above code:

  • global scope has one variable globalVariable.
  • However in globalFunction function object, notice notice we have a inner function, and thus, each function’s this scope is bound to itself.
  • the inner function cannot read the outer scope’s variable and thus both innerVariable and globalVariables are undefined.
  • In globalFunction’s globalVariable is undefined because it is not declared in its this scope

Thus, in the example, there are separate ‘this’ objects bound to each invoking function.

Unbeknownst to many Javascript developers, there is an arguments object created within a function. It is an Array-like object (only having the property length). Arguments has three main properties, namely, callee (the invoking method), length, and caller (the reference to invoked function).

Declaring a variable arguments inside a function replaces/overrides the primary arguments object.

Call, Apply

Both call and apply are used to invoke a method on an object.

Bind

The bind method is used to invoke methods while explicitly specifying this.

mongo dump

Say you want to do a dump of your mongo database onto your desktop.

You’d go:


mongodump -d DumpFolderName -o /location/of/your/directory

mongodump1

Once it makes a dump, you’ll see the DumpFolderName folder with various files in there. It contains the data of your database.

mongodump3

When you want to make the restore, copy the DumpFolderName to that machine. Make sure MongoDB is installed. Then just type


mongorestore DumpFolderName

mongodump2

Private methods in Objective C are semi private

ref – http://blog.akquinet.de/2013/03/28/clean-objective-c-private-methods-in-objective-c/
http://www.friday.com/bbum/2009/09/11/class-extensions-explained/

A word about usage

When implementing a class, it is common to have a set of methods that only appear in the class’s @implementation. Often, they are spread around the @implementation and generally appear just above whatever method first uses the private method (if they were to appear below, the compiler will warn).

Eventually, this becomes unwieldy and the developer will capture the private method’s declarations into a category declaration at the top of the implementation file. Something like:

The resulting problem is that the compiler will not check to make sure you have implemented all of the methods declared in that category. Nor will it catch, say, spelling errors in the method declarations in the implementation.

This is because a category with no corresponding implementation is an informal protocol in Objective-C. It is a set of method declarations that can optionally be implemented, often on a subclass of the class with the category declaration.

Because a class extension effectively extends the class’s primary interface, changing the above declaration to the following makes the declared methods have the same requirements as methods declared in the class’s oft public primary interface.

Background

One common complaint for many new to Objective-C is that the language lacks support for private methods within a class. There are compiler directives for instance variables: @private, @protected (the default) and @public. link

However, if you want to hide methods, there is no specific directives to help.

The Problem

Using private methods, we can generally hide the details or behaviors of a class from other classes. These other classes may be clients, Categories, or subclasses.

Compile-time private methods are supported; if a class doesn’t declare a method in its publicly available interface, then that method might as well not exist as far as your code is concerned.
In other words, you can achieve all of the various combinations of visibility desired at compilation time by organizing your project appropriately.

For example:

To avoid exposing a method as part of a class’s API, we do not declare it within the @interface section but within the @implementation section.

makeActivationSound is current exposed. Let’s say we want to make this private, and not let others access this method. We so by removing it from the interface Lightsaber, and put it either in the “private extension” of the Lightsaber class, or simply just declare it as a method within the implementation file.

Now, a private method like makeActivationSound can no longer be called by another class. A method call from a Jedi class like:

is no longer possible.


Compiler error: Method ‘makeActivationSound’ is defined in class
‘Lightsaber’ and is not visible.

Methods are semi private in Objective C

using performSelector to call private methods

Although if we use the performSelector method or the Objective-C Runtime library, we can still invoke private methods.
switchOn is the public method, which calls the private method makeActivationSound of the LightSaber class.
From ViewController, by using performSelector, we still able to manage the private method.

performSelector_callPrivateMethod

The result would be:

BB-ZSHOOOO
BB-ZSHOOOO

Hence there is no true private methods in Objective C.

Using subclasses to access private method

When child classes access the Lightsaber public method switchOn, it will access Lightsaber private method makeActivationSound.

Extending the base class

So say another developer comes in and want to extend the Lightsaber class into a child class called DoubleBladedLightsaber

The developer wants to over-ride the switchOn behavior, and therefore calls [super switchOn]. Then, he wants to add an additional functionality so he declares his own private method. And calls it right after using the base class’s switchOn.

UH OH! PROBLEM

[[DoubleBladedLightsaber new] switchOn];

What he gets is:

BB-ZSHUUUU
BB-ZSHUUUU

The 1st BB-ZSHUUUU is from [super swithcOn]. The switchOn in the base class then calls makeActivationSound. However, it sees that the child class have over-ridden its makeActivationSound, and thus, uses the child’s makeActivationSound method. This results in the output BB-ZSHUUUU, and not BB-ZSHOOOO.

The 2nd BB-ZSHUUUU is just a call to its own private method makeActivationSound. THEREFORE:

Private methods in Objective-C are not as private as in other modern object-oriented programming languages. They are semi-private and have polymorphic behavior.

In objective C, we can (accidentally) compromise the implementation of our extended class. The probability of unknowingly overriding a private method rises when we extend a framework or library class without having access to its source code.

To reduce the risk of accidental method overriding, we should add a prefix to the names of private methods that is as unique as possible.

For this reason, one should use an uppercase abbreviation of the company and/or the product name. In our example that could be the prefix AQN_LS_ for the company akquinet and the product Lightsaber:

After this modification, the [super switchOn] will access its own class’s private method.

So, the risk of accidentally overriding a private method depends on the uniqueness of its name.

  • As private methods can be overridden in Objective-C, there is a risk of compromising the implementation of an extended class.
  • Therefore, always use an application-specific unique prefix for the names of private methods.
  • A single underscore character (_) may not be used as a prefix, as this is reserved for Cocoa classes.

Sending file from html to node server (multer)

node server download

ref – https://dzone.com/articles/upload-files-or-images-to-server-using-nodejs

client side

Server side – index.js

Make sure you create the folder Images at the the directory your index.js is at.

However, our solution always jumps to another page.
In order to do it without any jump, we do it without a form

non-form way

First, we create a file uploader, and button control

For the button, whenever we press it, we will run function uploadImage
In this function, we first get the file object via the files property. The files property is an array, and we simply get the first element.

Once we have this file, we create a FormData object, append our file to it. Make sure to call it “imgUploader” as that’s what our multer code from the server side is expecting.

Assign the form data object to body and that’s it.

Javascript Prototype

https://javascript.info/prototype-inheritance

Prototype, function, and New

https://scotch.io/tutorials/better-javascript-with-es6-pt-ii-a-deep-dive-into-classes

When you call a function with new, four things happen under the hood:

  • A new object gets created (let’s call it O)
  • O gets linked to another object, called its prototype
  • The function’s this value is set to refer to O
  • The function implicitly returns O

We can also rewrite our Food function to work without the new keyword:

Everything is straightforward, except the setPrototypeOf.

Prototype Inheritance

Under normal circumstances, all objects in JavaScript — including Functions — are linked to another object, called its prototype.

If you request a property on an object that the object doesn’t have, JavaScript checks the object’s prototype for that property. In other words, if you ask for a property on an object that the object doesn’t have, it says: “I don’t know. Ask my prototype.”

This process — referring lookups for nonexistent properties to another object — is called delegation.

The output from our toString calls is utterly useless, but note that this snippet doesn’t raise a single ReferenceError!
That’s because, while neither joe or sara has a toString property, their prototype does.

When we look for sara.toString(), sara says, I don’t have a toString property. Ask my prototype.
JavaScript, obligingly, does as told, and asks Object.prototype if it has a toString property. Since it does, it hands Object.prototype’s toString back to our program, which executes it.

It doesn’t matter that sara didn’t have the property herself — we just delegated the lookup to the prototype.

In other words, we can access non-existent properties on an object as long as that object’s prototype does have those properties. We can take advantage of this by assigning properties and methods to an object’s prototype, so that we can use them as if they existed on the object itself.

Even better, if several objects share the same prototype — as is the case with joe and sara above — they can all access that prototype’s properties, immediately after we assign them, without our having to copy those properties or methods to each individual object.

This is what people generally refer to as prototypical/prototypal inheritance — if my object doesn’t have it, but my object’s prototype does, my object inherits the property.

In reality, there’s no “inheritance” going on, here.

In class-oriented languages, inheritance implies behavior is copied from a parent to a child.

In JavaScript, no such copying takes place — which is, in fact, one of the major benefits of prototypes over classes because we can dynamically switch to different prototypes and the prototype would “delegate” properties to those objects.

Setting an Object’s Prototype

The function, Object, has a property, called .prototype, which points to any object Object.prototype that you want.

The object, Object.prototype, has a property, called .constructor, which points to a function (Object). Keep in mind that this Object.prototype.constructor property is just a public property of Object.prototype. It is not used in any way in the construction of new objects or resolution of property names.

basic_prototype

You can also change the property to reference other objects. Rabbit.Property references an object. Any object created with new will now have their [[Prototype]] reference object {eats: true}. When we change Rabbit.Property to an empty object {}, further new objects created will then have their [[Prototype]] reference the new prototype object.

changing_properties

Prototype properties will over shadow objects that delegate from them

When both your object and its prototype has the same property, the prototype will have precedence.

Now we add the function “cook” to our prototype, in which we can then use.

Further Reading – Prototype Chain Details

In programming, we often want to take something and extend it.

In JavaScript, objects have a special hidden property [[Prototype]] (as named in the specification), that is either:
– null
– references another object. (all properties/methods of that object will be inherited)

That object is called “a prototype”:

When we want to read a property from object, and it’s missing, JavaScript automatically takes it from the prototype.

The property [[Prototype]] is internal and hidden, but there are many ways to set it.
One of them is to use __proto__, like this:

// So if animal has a lot of useful properties and methods,
// then they become automatically available in rabbit.
// Such properties are called “inherited”.

__proto__ IS NOT the same as [[Prototype]].

[[Prototype]]’s getter/setter is __proto__

If the subclass does not have the property/method, then JavaScript automatically takes it from the parent class.

Then, when console.log tries to read property rabbit.eats (**), it’s not exist in rabbit, so JavaScript follows the [[Prototype]] reference and finds it in animal (look from the bottom up).

Here we can say that animal is the prototype of rabbit or rabbit prototypally inherits from animal.

So if animal has a lot of useful properties and methods, then they become automatically available in rabbit. Such properties are called “inherited”.

Inherited Method

If we have a method in animal, it can be called on rabbit:

Longer Prototype Chain

getter setter in prototype inheritance

An interesting question may arise in the example above: what’s the value of this inside set fullName(value)?
Where the properties this.name and this.surname are written: user or admin?
The answer is simple: this is not affected by prototypes at all.
No matter where the method is found: in an object or its prototype. In a method call, this is always the object before the dot.
So, the setter actually uses admin as this, not user.

That is actually a super-important thing, because we may have a big object with many methods and inherit from it.
Then we can run its methods on inherited objects and they will modify the state of these objects, not the big one.

For instance, here animal represents a “method storage”, and rabbit makes use of it.
The call rabbit.sleep() sets this.isSleeping on the rabbit object:

If we had other objects like bird, snake etc inheriting from animal, they would also gain access to methods of animal. But this in each method would be the corresponding object, evaluated at the call-time (before dot), not animal. So when we write data into this, it is stored into these objects.

As a result, methods are shared, but the object state is not.

In JavaScript, all objects have a hidden [[Prototype]] property that’s either another object or null.

We can use obj.__proto__ to access it (there are other ways too, to be covered soon).

The object referenced by [[Prototype]] is called a “prototype”.

If we want to read a property of obj or call a method, and it doesn’t exist, then JavaScript tries to find it in the prototype list, from its immediate parent, and on up.

Write/delete operations work directly on the object, they don’t use the prototype (unless the property is actually a setter).

If we call obj.method(), and the method is taken from the prototype, the obj’s “this” still references the obj. So methods always work with the current object even if they are inherited.

Special

rabbit.jumps overrides its prototype reference’s jumps. Thus we get true.
Then we delete rabbit.jumps. This deletes the rabbit’s jumps (the one that overrides the prototype’s jumps).
Since the jump that overrides the prototype’s jump is now deleted, “rabbit.jumps” then refers to its prototype’s jumps, which comes out to be null.
We delete animal.jumps.
Since rabbit has no jumps, and then it goes to its prototype and sees no jumps, then jumps would be undefined, because undefined is assigned to anything that is undeclared.

Including Prototype, properties that describe the state of a particular object, is written into the object

Speedy derives from hamster.
lazy derives from hamster.
Stomach, since it is a property that describes the state of an object, is written into itself.
Thus, that’s why when Speedy calls stomach, it does this:

1) accesses this.stomach, stomach here belongs to hamster.
2) calls push on this.stomach. It pushes a string into array stomach.

When Lazy calls stomach, it does the same thing as above.

Thus, that’s when a parent class has a property that describes the state of an object, all its deriving objects will share that property.

In order to fix this you can do 2 things:

1)
Essentially, we work on “this”, the child object that is deriving.
Then, we create a new array with the food name, and references the child object’s property to it.

2) Instead of working on “this” in the parent object, we simply put all methods to be shared by “this” in the parent object, and leave the stomach property for its children like so:

__proto__ and prototype usage

http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/