Random PhantomJS Review

A well-designed video tutorial by Stefan Judis.

In Video Stefan has covered every scenarios where you want to programmatically capture web contents or want to access and manipulate webpages with the standard DOM APIs, or interested in monitoring page loading, PhantomJS is the tool you will look for.

 

Rapid PhantomJS video tutorial by Stefan Judis will prove an excellent guide in learning PhantomJS. Three sections in this video tutorial will teach you from basics of PhantomJS to automating your workflow with included tests based on PhantomJS.

 

Basics are covered in Section 1, PhantomJS – Introduction. In most video tutorials in the Internet, you will see that author will first install and then explain the topic. But here, Stefan has taken a different route. He first has run few examples to prove the usefulness of PhantomJS. I believe every reader will like this approach since it will help everyone in understanding the use cases of PhantomJS. Secondly, in introductory section only, he has covered basics of error handling, ‘phantom’, ‘system’ and ‘webpage’ APIs. For more detailed information about the APIs, you can visit http://phantomjs.org/api/.

 

Various aspects of frontend unit testing is covered in Section 2, Frontend Unit Testing using PhantomJS. I am a big fan of unit testing and therefore, this section can prove to be very useful and informative. Author has covered following topics in this section:

 

Using PhantomJS in Terms of Rendering

Using PhantomJS in Terms of Page Automation (Reading)

Using PhantomJS in Terms of Page Automation (Writing)

Using PhantomJS in Terms of Network Monitoring

Using PhantomJS in Terms of Testing

 

All the examples in the above sections are very practical and well explained. Also, every example is a continuation of the previous example which makes it easy for the reader to understand and implement the examples. Because this way, you can start thinking very easily how to use these concepts in your use cases.

 

Another note is that PhantomJS can be used with Karma, the JavaScript test runner for running your unit test cases in a headless browser.

 

Final aspect of the course is Section 3, Automating Your Workflow with Included Tests Based on PhantomJS. In any project as a developer you are not going to run your test scripts manually. You will look for options to automate your test cases/ scripts. This section will show you setting up of make, npm scripts, grunt and gulp scripts to run your PhantomJS scripts. This is a good ending of any course for any reader.

 

From above discussions, we can conclude that this is a well recommended course for anyone who wants to start PhantomJS from ground up.

C Programming Important notes

1) void *realloc(void *ptr, size_t size);
-> realloc changes the size of the allocated memory pointed to by the argument ptr
-> newly allocated memory will be uninitialized
-> you can pass a NULL ptr safely to realloc
-> realloc may move your data to a new pointer and free the memory at the old pointer. It will return the new pointer, or the old pointer if the data is not moved.

2) Calloc
-> allocates a region of memory large enough to hold “n elements” of “size” bytes each. Also initializes contents of memory to zeroes.
-> void *calloc (number_of_blocks, size_of_each_block_in_bytes);
-> The allocated region is initialized to zero.
-> void pointer (void *). If the allocation succeeds, a pointer to the block of memory is returned.
void *calloc(size_t nelements, size_t bytes);

Malloc:
-> allocates “size” bytes of memory.
-> void *malloc (size_in_bytes);
-> The contents of allocated memory are not changed. i.e., the memory contains unpredictable or garbage values. This presents a risk.
-> void pointer (void *). If the allocation succeeds, a pointer to the block of memory is returned.
void *malloc(size_t size);

3) In theory, which is faster, the call to strcpy or the call to memcpy?

#include <string.h>
#include <stdlib.h>
int main(){
        char msg[12] = "Hello World";
        char buffer1[12];
        char buffer2[12];

        strcpy(buffer1, msg);
        memcpy(buffer2, msg, sizeof(msg));
        return 0;
}

Answer:
memcpy should be faster because it does not need to check every byte for a NULL, it is copying a known size of data.

4)Variables declared outside of functions or with the static specifier are always initialized to zero. Therefore this program has deterministic behavior.

#include <stdlib.h>
#include <stdio.h>
int* ptrToData;
int main(){

    if (!ptrToData){
        ptrToData = (int*)malloc(sizeof(int) * 10);
        printf("%p\n", ptrToData);
    }
    free(ptrToData);
    return 0;
}

5) Fortunately, C/C++/Java makes this simple.

* To write numbers in octal, precede the value with a 0. Thus, 023 is 238 (which is 19 in base 10).
* To write numbers in hexadecimal, precede the value with a 0x or 0X. Thus, 0x23 is 2316 (which is 35 in base 10).

6)
How to Write a Negative Value
When you write 0x23, you might wonder how to negate it. Should you write the minus sign before the 0x, or after it? The answer is before. 0x indicates that the digits afterwards are written in hex. – is an operator, so it applies to a non-negative representation. Thus, you write -0x23. which is equivalent to -35

7) Structure Member Alignment, Padding and Data Packing

http://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/

8: C Bit Fields : http://msdn.microsoft.com/en-us/library/yszfawxh.aspx
struct-declarator:declarator
type-specifier declarator opt : constant-expression

The constant-expression specifies the width of the field in bits. The type-specifier for the declarator must be unsigned int, signed int, or int, and the constant-expression must be a nonnegative integer value. If the value is zero, the declaration has no declarator. Arrays of bit fields, pointers to bit fields, and functions returning bit fields are not allowed. The optional declarator names the bit field. Bit fields can only be declared as part of a structure. The address-of operator (&) cannot be applied to bit-field components.
Unnamed bit fields cannot be referenced, and their contents at run time are unpredictable. They can be used as “dummy” fields, for alignment purposes. An unnamed bit field whose width is specified as 0 guarantees that storage for the member following it in the struct-declaration-list begins on an int boundary.

Bit fields must also be long enough to contain the bit pattern. For example, these two statements are not legal:

short a:17; /* Illegal! */
int long y:33; /* Illegal! */

This example defines a two-dimensional array of structures named screen.
struct
{
unsigned short icon : 8;
unsigned short color : 4;
unsigned short underline : 1;
unsigned short blink : 1;
} screen[25][80];

7) C bit field storage question: stackoverflow.com/questions/21164939/unexpected-behaviour-of-bit-field-operator-in-c

8)

#include<stdio.h>
struct st
{
    int x;
    static int y;
};
 
int main()
{
    printf("%d", sizeof(struct st));
    return 0;
}

->In C, struct and union types cannot have static members. In C++, struct types are allowed to have static members, but union cannot have static members in C++ also.

9: A structure cannot contain a member of its own type because if this is allowed then it becomes impossible for compiler to know
sizeof such struct. Although a pointer of same type can be a member because pointers of all types are of same size and compiler cancalculate size of struct

10) Size of array can’t be constant

#include<stdio.h>
void main(){
    int const SIZE=5;
    int expr;
    double value[SIZE]={2.0,4.0,6.0,8.0,10.0};
    expr=1|2|3|4;
    printf("%f",value[expr]);
}

Give compiler error

11) strlen(“nishant”) = 7
sizeof(“nishant”) = 8
strlen(“nishant “) = 8
sizeof(“nishant “) = 10
strlen(“nishantkumar”) = 7
sizeof(“nishant kumar”) = 16

12) Hexadecimal : 0X, \x,
Octate : 0 Followed by number less then 7 ex: 01001 = 513 , ‘\111′ = 73 here \ representing octate

#include<stdio.h>
#define WWW -1
enum {cat,rat};
void main(){
    int Dhoni[]={2,'b',0x3,01001,'\x1d','\111',rat,WWW};
    int i;
    for(i=0;i<8;i++)
         printf(" %d",Dhoni[i]);
}
1
2 98 3 513 29 73 1 -1

In c any character is starting with character ‘\’ represents octal number in character. As we know octal digits are: 0, 1, 2, 3, 4, 5, 6, and 7. So 8 is not an octal digit. Hence ‘\08’ is invalid octal character constant.

13) 
1
#include<stdio.h>
void main(){
    int a;
    a= (3,4,5);
    printf("%d",a);
}

[/sourcecode ]
a= 5

1
 #include<stdio.h>
void main(){
    int a;
    a= 3,4,5;
    printf("%d",a);
}

a=3

14) What will be output if you will compile and execute the following c code?

void main(){
char c=125;
    c=c+10;
    printf("%d",c);
}

15:

 #include "stdio.h"
#include "string.h"
void main(){
   char *str=NULL;
   strcpy(str,"cquestionbank");
   printf("%s",str);
}

Note:

void strcpy(char *target, char *source){
   while(*source)
   {
      *target = *source;
      source++;
      target++;
   }
   *target = '\0';}
  ***Note: In strcpy function target should not be character pointer.

16)

void main(){
int i=10;
static int x=i;
if(x==i)
printf("Equal");
else if(x>i)
printf("Greater than");
else
printf("Less than");
}

Output: Compile time error
Explanation:
static variables are load time entity while auto variables are run time entity. We can not initialize any load time variable by the run time variable.
In this example i is run time variable while x is load time variable.

17)

#include<stdio.h>
int main(){
    printf("%c",*"abcde");
return 0;
}

18) Label of GOTO: scope is function block it is not visible outside of function.

19) Scope of variable

19)

#include<stdio.h>
int main(){
    int i=0;
    {
         auto int a=20;
         XYZ:;
         printf("%d",a);
         a++;
         i++;
    }
    if (i<3)
         goto xyz;
    return 0;
}

Explanation: Variable a which declared inside inner block has scope only within that block. Ones program control comes out of that block variable will be dead. If with the help of goto statement we will go to inside that inner block in the printf statement complier will not known about variable a because it has been destroyed already. Hence complier will show an error message: undefined symbol a. But if you will write goto statement label before the declaration of variable then there is not any problem because variable a will again declared and initialize.

20) We cannot initialize extern variable locally i.e. within any block either at the time of declaration or separately. We can only initialize extern variable globally. For example:

(a)

#include <stdio.h>
int main(){
extern int i=10; //Try to initialize extern variable
                 //locally.
    printf("%d",i);
    return 0;
}

Output: Compilation error: Cannot initialize extern variable.

(b)

#include <stdio.h>
int main(){
    extern int i; //Declaration of extern variable i.
    int i=10;     //Try to locally initialization of
                  //extern variable i.
    printf("%d",i);
    return 0;
}

Output: Compilation error: Multiple declaration of variable i.

#include <stdio.h>
extern int i;
int main(){
    i=25;       //Assignment statement
    printf("%d",i);
    return 0;
}
int i=10;   //Initialization statement

Output: 25

21) Typedef is a storage class : http://itee.uq.edu.au/~comp2303/Leslie_C_ref/C/SYNTAX/typedef.html

Javascript: How to convert string into XML Object in Javascript ?

In JavaScript we have string which format is equivalent to XML but In actual data is not in XML so we can’t enjoy predefine function and can’t manipulate string as XML so shoot out this issue we have to first convert string into XML object so that It allow to use manipulation of content inside node easily.

Cases Where we need to consider this conversion ( String into XML Object)

-> From server In response we get XML like formatted data but in actual data type of data  is string so we can’t apply manipulation on string by using XML manipulation function.

Let’s have example: First we have declare a var xmlString of type string if we want to see the type of xmlString we can use console.log( typeof xmlString); it will return string.


var xmlString = "<userInfo>
                    <name>Nishant</name>
                    <email>mindfiresolutions@gmail.com</email>
                </userInfo>";

So We will use XML Parser to parse string into XML object to enjoy feature of XML. As all modern browser have built
in XML Parser.

Below ParseXML function will take string val and return XML object


function ParseXML(val)
{
	if (window.DOMParser)
	  {
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(val,"text/xml");
	  }
	else // Internet Explorer
	  {
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.loadXML(val);
	  }
return xmlDoc ;
}

After converting string into XML object we can enjoy XML manipulation

var xmlDataObj = ParseXML(xmlString);
console.log(xmlDataObj.getElementsByTagName('name')[0].childNodes[0].nodeValue)

Output will be Nishant

How to calculate the Last Day of the month using Filemaker

Often we need to calculate the last Day or Date of the month of a year. Particularly useful to display on the report headers where we need to display the data from first of the month to the last. The calculation of last day of the month is a problem when we take into consideration the month february and the leap year. We will have to write some case statements to arrive the calculation. But there is simpler approach here. A pretty small calculation that will give you the last date and hence the day can be calculated from it.Here it goes like this below one.
 
Date((SuppliedMonth+ 1), 1, SuppliedYear) -1
 
This gives you the last date of the month. Now to calculate the day just use the day function.
 
Day(Date((SuppliedMonth+ 1), 1, SuppliedYear) -1)

Optimized way for Counting total no of record in Portal in Filemaker.

As we know that we generally we use count () function for counting total no of record in related table, but it’s take time when we have large number of data. So there is a function called Get(FoundCount) which calculate total no of record in portal in fastest way.

Put a Field Called Found_Record_Count  in Related table on wich Portal is displayed and make it Unstored Calculation field with Get ( FoundCount ) function and mark calculation result as Number.

What are P, NP, NP-complete, and NP-hard ?

P (Polynomial time decidable problems) is a class of problems which can be decided in polynomial time i.e., there’s an algorithm for such a problem which tells whether the solution of a given instance of a problem is true/false in O(n^k) time for some constant k.
For example, deciding whether there exists a path of at most k links between two vertices u and v is in P.

NP (Non-deterministic polynomial time decidable problems) is a class of problems which have short accepting certificates and efficient verification algorithms i.e., given a certificate of a solution, it is easy to check if the problem is satisfied.
Accepting certificate is information which can be used to decide if the answer is true or false.
Formally, a problem is in NP if there exists a verification algorithm A such that for any input x for which the answer is “true”, there is a certificate c such that |c| is polynomial and A(x,c) = true. For any x for which the answer is true, there is no certificate c such that |c| is polynomial and A(x,c) is true.
For example, given a graph G and a number k, deciding whether there exists a clique (complete subgraph) of size k, is in NP.

P is a subset of NP i.e., any problem that is in P is also in NP. It is easy to see that for any problem that can be decided in polynomial time, there exists a verification algorithm that given any certificate just ignores the certificate and returns the result of the polynomial-time algorithm.

Whether NP is also a subset of P (i.e., P = NP) is an open question. No one knows yet.

NP-hard is a class of problems which are hardest of all problems in NP. These are the problems such that if we can solve them fast, then we can solve all problems in NP fast and P would equal NP. NP-hard problems may be of any type: decision problems, search problems, or optimization problems so they may not even be in NP.
For example, the clique problem discussed above is NP-hard.

NP-complete is a class of problems which are in NP and are NP-hard. NP-complete problems transform to each-other by polynomial-time many-one reductions so if a polynomial-time algorithm exists for any one of them, then polynomial algorithms exist for all of them. However, no polynomial algorithm for any NP-complete problem has yet been found.
For example, the clique problem discussed above is NP-complete.

How to add JavaScript file dynamically from JavaScript on client Side

We can add java script file on client side under head tag by JavaScript dynamically. Below is working code

            var filename = 'http://code.jquery.com/jquery-2.0.0.js';
            var fileref = document.createElement('script');
                fileref.setAttribute("type", "text/javascript");
                fileref.setAttribute("src", filename);
                fileref.setAttribute("ID", "jsScript");
                document.getElementsByTagName("head")[0].appendChild(fileref);

Let’s Understand the above code We have to put script under head tag in below format

<script src="http://code.jquery.com/jquery-2.0.0.js" type="text/javascript"></script>


So for doing this have to define filename = which can be file name and absolute and relative JS file path name.Now we have to create script element which can be done using document.createElement(‘script’) method. And for adding attribute can be used setAttribute method.


Note: Here I have also set ID property fileref.setAttribute(“ID”, “jsScript”); which is optional. It will be helpfull when you want to check whether already page contains script with this ID or not.

Below code is used for check whether already have included Js file if yes then don’t include So It can be used to Check to see if script is present before adding one.

        var jsSelector = document.getElementById("jsScript");

        if (!jsSelector) {

            var filename = 'http://code.jquery.com/jquery-2.0.0.js';
            var fileref = document.createElement('script');
            fileref.setAttribute("type", "text/javascript");
            fileref.setAttribute("src", filename);
            fileref.setAttribute("ID", "jsScript");
            document.getElementsByTagName("head")[0].appendChild(fileref);
        }
 

Page Keyword: How to check js file already loaded or not, add js file dynamically, add java script file by java script

umbraco : How to retrieve drop down value and drop down text in umbraco using c#.

We have some scenario where we want to fetch custom umbraco dropdown list field value and text. For Instance consider situation where you have defined prevalue A, B, C, D in umbraco dropdown list data types and you want to retrieve user selected value from code behind.

See Below Image

CustomDrop-downList

demodropdownlist used in demoDropdown document type as property data type.

documentType

Now In code Behind file we can retrieve user selected value. In content section it look like

content-section

In code behind file we can retrieve user selected value text I mean A, B, C, D or it’s value.

 // Define content node ID in which dropdown data type has been used
 int contentNodeID = 1200;
 Document docDropDown = new Document(contentNodeID);

// Retrive Prevalue of selected value
 int selectedPreVal = Convert.ToInt32(docDropDown.getProperty("dropdownabcd").Value);
 [/sourcecode ]

// Retrive corresponding Text value corrospond to prevalue
 string selectedTextVal = umbraco.library.GetPreValueAsString(selectedPreVal);

Important aspects to consider while designing the website

Knowing Audience(User): Clarifying this early on as it may affect theme, design, content, search engine optimization, usability and networking efforts. In short, everything revolves around target market or audience.

Search Engine Optimization (SEO): It is the process of improving the quality and volume of web traffic to a website by employing a series of proven SEO techniques that help a website achieve a higher ranking with the major search engines when certain keywords and phrases are put in the search field.

Responsive theming: The basic idea behind responsive web design is to avoid having to build unique websites for different devices — such as smartphones, tablets, and desktop browsers. Instead, responsive design allows us to have one site that reflows its layout in response to the size of the screen it’s displayed on.

Honing content/messages: For stronger marketing impact, content should be consistent and touch the hearts and minds of potential customers. By working on content that reach out to viewers but also inspire them to convert into clients.

Engaging in social networking: Social networking sites have won the hearts of not just individuals, but businesses as well. Leveraging website by being seen on the top sites, such as Facebook, Twitter, LinkedIn etc.

Starting a blog on website: Company blogs are partners of websites these days. If websites tell about the product or service, blogs tell about the people behind company and the issues in the industry.

Lightweight Components: Something that many people do not consider is the weight of the website. As computers are most powerful, and the internet is faster, but when we are working with web design, we still have one major goal to make our website as small as possible. The larger our website is, the longer it will take to load, and many people will simple move on if they find that website takes too long to appear.

Typography matters: Understand what audience’s purpose is, like reading, learning, or getting technical advice, hence using the proper typography.

Color Palette: Can be define using brand’s logo, an image, or by finding a color swatch. Every color has its own properties and signs. Proper shades combinations required for grabbing the attention.

Keeping it Coherent: The website should behave in a way that makes sense. It should be logical and consistent. For example if one part of the website uses a pop up menu, then it might be expected that other parts of the website would do the same.

Keeping changes noticeable: When a user makes a change in the program it should be reflected within the website accordingly. For example, when a user is trying to select an item it might be helpful to gray out the other choices and only highlight what they are selecting so that they are confident in what they are picking.

Shortcuts are key: Giving the user a way to complete a task by using a shortcut can be important. Once a user has experience with a program and feels comfortable with the results that they are having its nice for them to be able to get the same task completed, but with a shortcut.

The human eye is drawn to motion: The eye is drawn to movement more than static objects. An animated object is usually going to be noticed quicker than an object that is not moving. Anything that we want to stand out can often be benefited by adding a little movement to it.

The User needs to feel safe: A new user does not want to feel stupid. So, it might be important to make them feel comfortable and keep them from feeling overwhelmed with the program. In this case, we might want to consider having a tip menu or FAQs section.

Help: The user may at some point in time need help, and when they do it is important to understand the type of help that they might need. There can be five basic type of helps:
Goal oriented- what can I do with this program?
Descriptive- What is this?
procedural- How do I do this?
Interpretive- Why did this just happen?
Navigational- Where am I?

Non-Standard Links: Few things needs to be considered regarding links.
Make obvious what’s click able.
Differentiating visited and unvisited links.
Little description can be shown while hovering on link.

Forms: Few things regarding forms:
Cutting questions that are not needed.
Not making fields mandatory which are not required.
Supporting auto fill for fields like Gender, Country etc..
Taking input of phone numbers, credit card numbers etc. in a flexible way.