Thursday, December 26, 2013

Write to a prettified JSON file in Python (with least number of lines of code)

import json

jsonData = ['foo', {'bar': ('baz', None, 1.0, 2)}]
with open('sample.json', 'w') as outfile:
    json.dump(jsonData, outfile, sort_keys= True, indent=4)

Monday, December 23, 2013

Remove duplicates in an array in Javascript

If you follow this approach, you need to create another array and if you have performance limitations you need to consider that.

This algorithm will be o(n)complexity in which n is the length.

With jQuery:

 var newArray = []; 
 var array=["amir", "amir", "rahnama", 1, 1]; 
 var newArray = [];

 $.each(array, function(i, element) { 
   if ($.inArray(element, newArray) === -1) {
       newArray.push(region); 
   }
 });

 console.log(newArray); // ["amir", "rahnama", 1];

Vanila Javascript:

 var newArray = []; 
 var array=["amir", "amir", "rahnama", 1, 1]; 
 var newArray = [];

 array.forEach(function(i, element) { 
   if (newArray.indexOf(element) === -1) { 
      newArray.push(region); 
   }
 });
 console.log(newArray); // ["amir", "rahnama", 1];

Sunday, December 22, 2013

How to resolve XCode's “valid signing identity not found” error

Generally, this error is caused because of a mismatch between a provisioning profile and a private key. It can also be that you even do not own a private key that makes your identity identified to the provisioning profile which are you working with.


First Resolution
Double-check that the profile that you have got from Apple Developer Program is the correct one that you are supposed to have. Sometimes organizations have multiple profiles for each team and although you have a correct private key, you own the wrong provisioning profile.

Second Resolution
You do not own the private key of the provisioning profile and/or identity that you are using. You need to own a private key file with .p12 extension in order for your identity to be validated. Whoever have created your identity (in case you work in a  team of developers, it could be someone else), has it on his/her machine when he has created the profile and/or identity. you need to get this key from that person or reissue a new private key (which takes some time) in order to resolve the issue.


If this sounds too confusing and does not make any sense for you, follow my step-to-step guide to How to sign your MacOSX application code with codesign?

Saturday, December 21, 2013

How to sign your MacOSX application code with codesign?

A Brief Preface: I recently realized that the documentation for signing your Mac OSX applications with codesign is distributed across many documents which is extremely hard to find (You can find those documents in the "more to read" section of this post). Also, in the documentation it has been assumed that you will sign your code with XCode which is not always the case. As you may know, XCode is mainly used for development with Objective C for MacOSX and iPhone but a lot of Mac OSX applications are written in C/C++ and Java which XCode does not support any feature for those project types and makes the signing process extremely hard.

Now, let us start:

1. Go to Apple's Developer Program's Member Center. Go to member center. Write your credentials and enter.

NOTE: If you have not registered in Apple's Developer Program, you need to do so before you can sign your code.

2. Under Developer Program Resources, click on Certificates, Identifiers and Profiles. Under Mac Apps Click on Certificates. Then go to your certificate and then Click on Download. Now you have downloaded the Certificate.


3. Find the certificate file that you downloaded, and run it.
Keychain Access program will be opened by default and will put your Certificate under login keychains and certificates category:





4. Download your private key from the Apple's website: In the downloaded folder you will find a key file with .p12 extension which is Mac’s public key (PKCS12) format. Again, open the file and automatically it will be attached to the certificate you just downloaded.


Check whether it is already there as you expect it.

5. Next Step is to get Developer’s ID. Right click on the certificate of Mac developer profile which you want the code to be signed with and click on “Get info”. On the new windows, scroll down and get the SHA1 fingerprint of the certificate:


Remove the white-spaces and put it under $DEVELOPER_ID in your sign command or if you have one, in your build script. Also, you need to add the requirement for signing. Read about it on Mac Developer Documentation: Apple's Codesign Requirement Specification

Remark: One example of requirements can be of following (This example uses Mozilla's XULWrapper platform):

CODESIGN_REQUIREMENTS="=designated => anchor apple generic  and identifier \"org.webapp.xulwrapper\" and ((cert leaf[field.1.2.840.113635.100.6.1.9] exists) or ( certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists  and certificate leaf[subject.OU] = \"FOO123BAR1\" ))"

/usr/bin/codesign -s "$DEVELOPER_ID" -v \
   --requirements "$CODESIGN_REQUIREMENTS" \
   "$APPDIR"

6. You can sign the code now. Run the above command and you should be good to go.

Further References:

Friday, November 1, 2013

Merge two object literals into one another in Javascript

I faced this issue a while back that I wanted to achieve something like
var a,b,c;
a = b + c;
for object literals in Javascript. Moreover to that, I wanted to have an option to extend (merge, add or whatever you might want to call it) in a loop, something like the following for the string type:
var result = "",
    j = 0,
    array = ["Amir", "Rahnama"];

    for (; j< array.length;j++) {
       result += array[j] + " ";

}

console.log(result); //Amir Rahnama
I first tried to write my own code and then suddenly found a better solution: jQuery's extend method. In short, jQuery's extend method extends N objects into a target object:

jQuery.extend( target [, object1 ] [, objectN ] )

The target is an object that will receive the new properties, Object1 is an object containing additional properties to merge in and finally, objectN is the additional objects containing properties to merge in. One way of using the function is like following:
var personObject = {person: {name: "Amir", familyName: "Rahnama"}};
var workObject = { work: {workplace: "Stockholm", companyName: "Gapminder"}};
var personWorkObject = {};
    
personWorkObject = $.extend(personObject,workObject);
You could also use the method to extend an object recursively, within a loop for example and that is why I highly recommend you to use this method. If you want to extend the objects recursively, make target the return value of the method, like the code below:
personWorkObject = $.extend(personWorkObject, personObject,workObject);

How to Check if one array is a subset of another array in Javascript?

I encountered this question in my code today. Although there are a lot of messy ways to do it which it will definitely lead to unmaintainable code, I guess I found the best answer.

Just to remind you, this solution will work if your supported browsers are of ECMA-262 standard. Therefore, for some of you guys out there, this might not work.

The key idea is to use every function in Javascript arrays. According MDN, "Tests whether all elements in the array pass the test implemented by the provided function."

Here is the signature of the method:

array.every(callback[, thisObject])

where callback is a function to test for each element, and thisObject refers to the object that we are testing array against (Remember that in Javascript, arrays are object. Right?)

Here is the snippet:

var arrayOfChildrenNames = ["Amir Rahnama", "Mahshid Rahnama"];
var arrayOfFamilyMemberNames = ["Davood Rahnama", "Maryam Toloo", "Amir Rahnama", "Mahshid Rahnama"];

var isarrayOfNamesSubsetOfFamily = arrayOfChildrenNames.every(function(val) { return arrayOfFamilyMemberNames.indexOf(val) >= 0; }));
console.log(isarrayOfNamesSubsetOfFamily); // true

If you are interested to know more about the function, check out MDN Documentation on Array every method

Wednesday, August 28, 2013

Javascript Namespacing: Object Literal Namespace (OLN) in Javascript

Javascript, unlike many other programming languages does not come with its built-in namespace or class pattern. In many other languages such as Java or C#, the code comes with built-in name-spacing and class patterns. Have a look at C#'s namespace pattern below:
namespace Project
{
    class MyClass
    {

    }
}
You may first ask why do we need a namespace to begin with in a language like Javascript?! As a reply, one can simply say that namespaces avoid the global namespace of your application to become polluted by dividing the global namespace into several manageable chunks of code, calling one another. It is very obvious that if you are writing an application you cannot just continues writing it like this, can you?
var getUserInput = function () {

};

var thenSortIt = function() {

};
If you think you can, you are right! But then you lose track of your functions as it becomes so hard to find your functions in thousands of lines of code and newly added functions. Even if you divide them in separate script files, you still are polluting the global namespace, i.e. as the application starts, you are injecting all the code suddenly inside the browser in one big scope. Do you think that is desirable?! If so, think twice.

The Object Literal Namespace (OLN) pattern, comes with a very easy idea. Wrap your namespace inside a very big object literal:
var myNamespace = {
 instanceVariable: undefined,

 setter: function (element) {
  this.instanceVariable = element; 
 },

 getter: function() {
  return this.instanceVariable;
 },

 randomFunctions: function (message) {
  return "Hello, " + message;
 } 
};
In the following script, that is how you call and interact with you OLN in Javascript:
myNamespace.setter(1000); 

console.log(myNamespace.getter()); //Output: 1000

console.log(myNamespace.randomFunctions("Amir Rahnama!")); //Output: Hello, Amir Rahnama!
One fact to remember here, is that by using OLN as your namespace pattern, there is no level of information hiding in your namespace. You are exposing your whole namespace to the caller's code. Meaning that, you can replace the second line of above with the following line, keeping the output still the same:
console.log(myNamespace.instanceVariable); //Output: 1000
Actually, that is one of the main reasons that many developer dislike OLN namespaces, because they believe in a namespace with public and private values at the same time.

One last thing to note is that you can dynamically extend your OLN Namespace by the following code:
//Dynamically add instance variables to myNamespace
myNamespace.newInstanceVariable = "I am new";

//Dynamically add newFunction to myNamespace
myNamespace.newFunction = function (newMessage) {
 return "Hello Again," + newMessage;
};

And you can guess that you can use them as soon as they are declared:

console.log(myNamespace.newInstanceVariable); //Output: I am new
console.log(myNamespace.newRandomFunction("Mr, Amir Rahnama!")); //Output: Hello Again, Mr. Amir Rahnama!