In this post we will be covering the basic concepts in CSS3 along with some hands on examples. The topics that we will cover in this post are:

  • Structure of a CSS Style
  • Types of Stylesheets
  • Selector
    • Tag
    • Class
    • Id
  • Pseudo-Class

Structure of a CSS Style

Cascading Style Sheets are the way we usually style the elements on our web pages and CSS helps us define this style at one place which can be reused at multiple places later on.

When we write a CSS style it looks something like below. We have the name of the CSS class (or selector) followed by the opening and closing parenthesis. Inside these parentheses we define the property name and the value of those properties which are separated by colon (:). Each property value pair is separated by a semi colon (;). Sometime the vales can be placed inside quotes (“” or ‘’) depending on the value that we are adding.

CSS Structure

CSS Structure

 

Types of Stylesheets

External Stylesheet

External stylesheets are the ones which are used mostly as they allow us to make design changes to an entire site by simply changing one file.

  • External Stylesheet allows us to have better separation of concerns between the HTML and the style that we are writing. The HTML should be completely independent of the style that will be applied to it.
  • They are faster as they are cached and easily available for use.
  • We can include external stylesheet into a HTML page by simply adding it as a link. We need to specify the rel as stylesheet along with the type and path of the stylesheet.
<link href="~/Content/css/styles.css"  rel="stylesheet" type="text/css" />

Internal Stylesheet

Internal stylesheet reference styles within the page itself. Internal stylesheets are mainly use during development or prototyping because they are faster while development as they do not need to come from the cache every time we reload the application. These stylesheet should only be used at the time of development or prototyping and there is a good chance that these stylesheet will become obsolete in a few years.

To create an internal stylesheet we add the styled within the head tags of the webpage

<html>

<head>

<title>Learn CSS</title>

<style></style>

</head>

<body></body>

</html>

Section

Section is used to specify a particular area on the screen.

Aside

This section is generally used for the side panels. Sometimes it is also used to give additional information.

Footer

This is used for adding the footer to the website or the webpage.

Selectors

Tag

Tag selectors are page wide selectors like p (paragraph). This selector is the most wide as they have multiple elements with that tag.

Class

The Class attribute tells the browser that an HTML tag belongs to a certain group. We can have many selector with the same class and this allows us apply one style to multiple selectors across the web page or website. Class selectors allow us to select every element on the page with that specific class. The Class selector is a little less wide than the Tag selector but still there can be multiple elements that can be present with the same class selector. When declare class selector in the style then we specify dot (.) to indicate that this is a class selector. But when we use it just specify the class name.

Id

The Id attribute should only be used in one tag on your HTML page, so that whatever is in that one tag look different. The motive of using an Id attribute is to uniquely identify a selector so whenever we are using an Id it should be unique. The Id selector is even more specific than the class selector as Id assigned to an element on the page should be unique for that page. When we specify the Id in the style we use the hash (#) symbol to indicate that this is an Id. Two major uses of Id because of its uniqueness on the page are –

  • Id can be used by JavaScript code to find a specific element.
  • Id can be used for linking to a specific part if the page.

In the code below we see all the things that we have talked about till now.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8" />

<title>Learn CSS3</title>

</head>

<body>

<article id="first-article">

<section id="header-section">

<h1>Learn everything about CSS</h1>

<div>

<span>Posted on 12th Sep 2013</span>

<span>by</span>

<span>Abhishek Shukla</span>

</div>

</section>

<section>

<p>&nbsp;</p>

<p>In this section we will learn enough about CSS3 to get a good foundation for working on it.

<img alt="CSS3" title="CSS3" src="https://www.abhishekshukla.com/wp-content/uploads/2013/09/CSS3Logo.jpg" /></p>

<p>CSS 3 came along with HTML5 and has enhanced the capabilities that are available in HTML5.

In this course we will have a look at the various basics of CSS3.

We will also get our hands dirty with some practical examples.</p>

</section>
             <aside>
                <section>
                    <h2>About CSS3</h2>
                </section>

                <section>
                    This section is generally used for the side panels. Somethime it is also used to give additional information.
                </section>
            </aside>

</article>

<footer>

<p>Copyright 2013 Abhishek Shukla</p>

</footer>

</body>

</html>

 

When run the above webpage we will see something like below. The browser has different font style for the headings. It has a picked up a default font for the text as we did not specify any font family.

Only HTML

Only HTML

Now we will style this page to do that we will create an inline style. To create an inline style we need to add the style tag within the head tag. We will start off with styling the paragraph in our webpage. So let us add a few property and values for the paragraph style.

p
{
    color:  #24981f;
    font-family: Calibri;
    font-size: medium;
}

Let us also specify the style for the h1 and h2. Notice the font size for h2 is smaller that h1

h1
{
    color: #0f769d;
    font-family: Calibri;
    font-size: larger;
}
h2
{
    color: #1197c9;
    font-family: Calibri;
    font-size: large;
}

Let us also style the footer as well to show small text. You will see that we have specified the style name as footer p, this means that this style applies to any paragraph which is inside the footer.

footer p
{
    color: #000000;
    font-family: Calibri;
    font-size: x-small;
}

Now our webpage looks something like below.

Style By CSS Tag

Style By CSS Tag 

Style by Tag

We have already seen how to specify style by Tag in the previous section where we have specified styles based on tags like p, h1, h2, footer, etc.

p
{
    color:  #24981f;
    font-family: Calibri;
    font-size: medium;
}
h1
{
    color: #0f769d;
    font-family: Calibri;
    font-size: larger;
}
h2
{
    color: #1197c9;
    font-family: Calibri;
    font-size: large;
}
footer p
{
    color: #000000;
    font-family: Calibri;
    font-size: x-small;
}

You could see that we have specified the styles based on the element tags. So we have specified the style for all the paragraphs using p, for all heading1 using h1 and for all heading2 using h2. All of these styles apply to all the elements on the page with no exception. However if we notice the style that we have specified by footer p means that this style will apply only to the paragraph present inside the footer. This type of style specification opens up a lot of capabilities of defining styles for different elements inside different tags.

Style by Class

In the code that we have written before we saw that the h1 that we were using had a class named article-title.

<h1>Learn everything about CSS</h1>
Style By CSS Class

Style By CSS Class

We will define a style specific to this class. To that we need to go to the style section in the head tag and specify .article-title as the style name and then add a background color property to the style.

.article-title
{
    background-color: #c4c4c4;
}

Now if go back and refresh the page we will see that the h1 text has a background now. The same will happen for any element that is using the same class.

Now let us add the same class that we have added to h1 to h2 as well.

<h2>About CSS3</h2>

We will see that h2 will also get the same background. This will verify the principle that one class can be used at multiple places.

Style By CSS Class

Style By CSS Class

Now let us add style for the article metadata as well. The class that we are using for that is meta-article.

<div>
    <span>Posted on 12th Sep 2013</span>
    <span>by</span>
    <span>Abhishek Shukla</span>
</div>

So we will go back to the styles section and add a new style named .meta-article and assign the font-style for that class to be oblique.

.meta-article
{
    font-style: oblique;
}

And then the text for this div with meta-article class will become oblique.

Style By CSS Class

Style By CSS Class

Now say I want my name to not to be oblique but in normal font style so I will add a new style for the meta-author class and set the font-style to be normal.

.meta-author
{
    font-style: normal;
}

And then we will see the author name in normal font style.

Style by Id

To specify a style by Id we need to prefix a # before the Id while specifying the style. In this case will use the Id of the article section named as first-article and specify a background color.

#first-article
{
    background-color: #e8dede
}

This will make the background of the whole article as light gray.

Style By CSS Id

Style By CSS Id

Pseudo-class

These work just like the normal classes to find the elements. These pseudo-classes work on the relative basis. So in a class we can access the first child, last child, nth child, first child of a type, nth child of a type, etc. Below is the list of pseudo classes available in CSS3.

:focus

The :focus CSS pseudo-class is applied when a element has received focus, either from the user selecting it with the use of a keyboard or by activating with the mouse (e.g. a form input).

:active

The :active CSS pseudo-class matches when an element is being activated by the user. It allows the page to give a feedback that the activation has been detected by the browser. For mouse event this active behavior represents the time between mouse buttons down and then up. This is generally used

:hover

The :hover CSS pseudo-class matches when the user designates an element with a pointing device, but does not necessarily activate it. This style may be overridden by any other link-related pseudo-classes, that is :link, :visited, and :active, appearing in subsequent rules.

:link

The :link CSS pseudo-class lets you select links inside elements. This will select any link, even those already styled using selector with other link-related pseudo-classes like :hover, :active or

:visited

In order to style only non-visited links, you need to put the :link rule before the other ones, as defined by the LVHA-order: :link — :visited — :hover — :active. The :focus pseudo-class is usually placed right before or right after :hover, depending of the expected effect.

:visited

The :visited CSS pseudo-class lets you select only links that have been visited. This style may be overridden by any other link-related pseudo-classes, that is :link, :hover, and :active, appearing in subsequent rules. In order to style appropriately links, you need to put the :visited rule after the :link rule but before the other ones, defined in the LVHA-order: :link — :visited — :hover —

:active

Below is the use of all these 4 pseudo classes. We have specified these classes inside a (anchor tag)

<head>
    <meta charset="utf-8" />
    <title>Pseudo Selectors</title>
    <style>
        a:link { color:#0094ff; }
        a:visited { color: #ff006e; }
        a:hover { color: #ff6a00; }
        a:active { color: #60a941; }
    </style>
</head>
<body>
    <a href="#">This link will change color on hover becuase of style that is based on active pseudo class</a>
</body>
Pseudo Class

Pseudo Class

:checked

The :checked CSS pseudo-class selector works for any radio (input type=”radio”), checkbox (input type=”checkbox”) or option (option in a select) component that is checked or toggled to an on state. The client can transform this state by clicking on the component, or selecting an alternate worth, in which case the :checked pseudo-class no more applies to this component.

In the code below as soon as the checkbox or the radio button is checked the checkbox and radio button part disappears.

<style>
    input:checked
    {
        display: none;
    }
</style>

<body>
    <input type="checkbox" >CheckBox</input>
    <input type="radio" >RadioBox</input>
</body>

:default

The :default CSS pseudo-class represents any user interface element that is the default among a group of similar elements.

:disabled

The :disabled CSS pseudo-class represents any disabled element. An element is disabled if it can’t be activated (e.g. selected, clicked on or accept text input) or accept focus. The element also has an enabled state, in which it can be activated or accept focus.

:empty

The :empty pseudo-class represents any element that has no children at all. Only element nodes and text (including whitespace) are considered. Comments or processing instructions do not affect whether an element is considered empty or not.

:enabled

The :enabled CSS pseudo-class represents any enabled element. An element is enabled if it can be activated (e.g. selected, clicked on or accept text input) or accept focus. The element also has an disabled state, in which it can’t be activated or accept focus.

:first-child

The :first-child CSS pseudo-class represents any element that is the first child element of its parent.

:first-of-type

The :first-of-type CSS pseudo-class represents the first sibling of its type in the list of children of its parent element.

:last-child

The :last-child CSS pseudo-class represents any element that is the last child element of its parent.

:last-of-type

The :last-of-type CSS pseudo-class represents the last sibling of its type in the list of children of its parent element.

:nth-child()

The :nth-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings before it in the document tree, for a given positive or zero value for n, and has a parent element.

:nth-last-child()

The :nth-last-child CSS pseudo-class matches an element that has an+b-1 siblings after it in the document tree, for a given positive or zero value for n, and has a parent element. See :nth-child for a more thorough description of the syntax of its argument.

:nth-last-of-type()

The :nth-last-of-type CSS pseudo-class matches an element that has an+b-1 siblings with the same element name after it in the document tree, for a given positive or zero value for n, and has a parent element. See :nth-child for a more thorough description of the syntax of its argument.

:nth-of-type()

The :nth-of-type CSS pseudo-class matches an element that has an+b-1 siblings with the same element name before it in the document tree, for a given positive or zero value for n, and has a parent element. See :nth-child for a more thorough description of the syntax of its argument. This is a more flexible and useful pseudo selector if you want to ensure you’re selecting the same type of tag no matter where it is inside the parent element, or what other different tags appear before it.

: only-child

The : only-child CSS pseudo-class represents any element which is the only child of its parent. This is the same as :first-child:last-child or :nth-child(1):nth-last-child(1), but with a lower specificity.

: only-of-type

The : only-of-type CSS pseudo-class represents any element that has no siblings of the given type.

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Pseudo Selectors</title>
        <style>
            span:nth-of-type(2n+1)
            {
                 background-color: #ffd800;
            }
            span:nth-of-type(2n)
            {
                background-color: #ff006e;
            }
            div :first-of-type
            {
                background-color: #0094ff;
            }
            span:last-child
            {
                background-color: lime;
            }
        </style>
    </head>
    <body>
        <div dir="rtl">
            <span>This is child number 1</span>
            <span>This is child number 2</span>
            <span>This is child number 3</span>
            <span>This is child number 4</span>
            <span>This is child number 5</span>
            <span>This is child number 6</span>
            <span>This is child number 7</span>
            <span>This is child number 8</span>
            <span>This is child number 9</span>
            <span>This is child number 10</span>
        </div>
    </body>
</html>
Pseudo Class

Pseudo Class

:lang()

The :lang CSS pseudo-class matches elements based on the language the element is determined to be in. In HTML, the language is determined by a combination of the lang attribute, the <meta> element, and possibly by information from the protocol (such as HTTP headers). For other document types there may be other document methods for determining the language.

element:lang(language-code) { style properties }

:not()

The negation CSS pseudo-class, :not(X), is a functional notation taking a simple selector X as an argument. It matches an element that is not represented by the argument. X must not contain another negation selector, or any pseudo-elements.

:not(selector) { style properties }

:root

The :root CSS pseudo-class matches the root element of a tree representing the document. Applied to HTML, :root represents the <html> element and is identical to the selector html, except that its specifity is higher.

:target

The :target pseudo-class represents the unique element, if any, with an id matching the fragment identifier of the URI of the document.

 

The code for this post can be downloaded @ here or @ mirror

Any questions, comments or feedback are most welcome.

Microsoft will purchase Nokia’s Devices & Services business

Nokia CEO Stephen Elop and Microsoft CEO Steve Ballmer announce plans for a broad strategic partnership to build a new global mobile ecosystem at a press conference in London, UK February 11, 2011. Nokia and Microsoft plan to form a broad strategic partne

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Steve Ballmer and Stephen Elop in their open letter said that this step is being taken to deliver more choices, faster innovation, and even more exciting devices and services to our customers.

Read more @ Microsoft Press News

 

 

Git does not take care of the access control so we need to additional software for that and that’s where hosted solutions like GitHub and BitBucket come in and also self-managed solutions like Gitosis and Gitorious come in.

Help

git help –  provides help on all commands

git help commandName –  provides help on specific command

Config

git config - - global user.name “username”

git config  - - global user.email abc@xyz.com

git config - - global color.ui true –  Get pretty colors on the output of our command line

git config - - global core.editpr emacs –  use emacs for interactive commands

git config - - global merge.tool opendiff –  uses opendiff for merging conflicts

git config user.email “email” –  sets the email for the current repository

 

Starting a Repository

mkdir store –  create directory

cd store –  change to directory

git init –  Initialize the empty repository in the local system

or 

we could directly create a repository in the current folder
git init sample-dev-proj

and then navigate to the repository
cd sample-dev-proj

Never need to go in the directory but that’s where the data is stored.

Git Workflow

Creating a file – It will be untracked initially

Add file to staging area – Is getting ready for taking the snapshot of the file.

Commit – Taking a snapshot of the files that we have put on stage

git status – tells you what has changed since the last commit. It also tells the branch we are on as of now.

git add filename1 filename2 – will add the specific file to staging area

git add - - all – will add all the files to the staging area

git commit -m “Describe the changes done” – will add the snapshot at the top of the timeline and adds the commit message which describes the work that has been done.

This takes the snapshot of the stage and this gets added to our timeline

git log – lists the commits that we have had with details

Keep commit messages in present tense and not the past tense

Different ways to add files

git add <list of files> – adds the list of files

git add - - all – add all files

git add *.txt –  adds all text file in current directory

git add docs/*.txt –  adds all txt file sin the docs directory

git add docs/ –  adds all the files in the docs directory

git add “*.txt” –  adds all text files in the entire project

Git Diff

git diff –  Shows the unstaged differences since the last commit.

Red color shows the removed line and green color shows the line that was added.

git diff - - staged –  shows the differences between the staged files.

Unstaging files

git reset HEAD <filename> –  unstages the particular file

HEAD – refers to the last commit in the current branch

Discard modifications

git checkout - - <filename> –  blows all the changes since the last commit

Skip staging and Commit

git commit –a –m <filename> –  This will add changes of the file and commit it.

However this will not add the untracked files.

Undoing a commit

 

git reset - - soft HEAD^ –  resets into staging. ^ sign indicates that it moves to the commit one before the current one. Now I can make changes and re-commit.

git reset - - hard HEAD –  blows away the last commit and all changes

git reset - - hard HEAD^ –  blows away the last commit

Should not be used after the push

Adding to a commit

git add <filename>

git commit - - amend –m “Commit message” –  Adds the file to the last commit

This new commit message overrides the previous commit messages

Sharing the repository

Adding a Remote

git remote add <remote name> <repository address> –  Adds a new remote repository with name origin. It’s a convention to name it as origin as this is place where most of the people will be working from.

git remote –v –  shows the repositories

Remotes are like bookmarks

Pushing to Remote

git push <remote name> <branch name> –  push the local branch master to the remote repository origin.

We could password cashing to avoid typing the user name and password again and again.

https://help.github.com/articles/set-up-git

github.com has history and commit options which provide the info similar to git log

git pull –  will go to github and get the current changes and get it down to the local system and then sync it up with the local repository

Remove a remote

git remote rm <remote name>

Cloning and Branching

Cloning a Repository

git clone <repository address> –  creates a local repository with the same name as the actual repository

git clone <repository address> <local repository name> –  creates a local repository with specified name

Steps

  1. Downloads the entire repository to a new gir repository
  2. Adds the remote pointing it to the clone url
  3. Checks out the initial branch likely master and set the head
git remote –v lists all the remote branches

Branching Out

git branch <branch name> –  will create a new branch from master

git checkout <branch name> –  To move to that specified branch

git branch → See local branches

git branch --all → See all branches including remote

Working on a branch

echo “Schrodinger” > cat.txt –  creates a text file and inside it puts the word Schrodinger

Now when add this file and commit it then this file is added to our current branch and not the master branch.

ls –  Lists all the files in the current directory

Merge a Branch

Move to the branch you want to merge it with.

git checkout master

then

git merge <branch name to merge>

* Fast forward merge means that when we merge a branch there is no file merge required as the master branch did not change in the time while we made the changes.

Delete a branch

git branch –d <branch name>

NON Fast Forward Merge

git checkout –b <branch name> –  Creates a branch and then checks it out

Some commit done on both master and feature branch

Now when we move back to master from the feature branch and try to merge we are taken into the Vi editor and it asks us to do a merge commit.

Vi Commands

j –  down             k–  up                    Esc –  leave mode                            :wq –  save and quit

h–  left                  l –  right                i –  insert mode                 :q! –  cancel and quit

We can modify the message

When git does a merge commit then there a commit a commit at the top. If we see the git log it says that there has been a merge commit. At this point the 2 branches became one branch

Collaboration

Someone already pushed a new version of source code after you pulled but before you push. So now if you try to push your code it will be reject as you are behind the commit at this point of time.

Understanding Pull

git pull
  1. Fetch (or sync) our local repository with the remote one –  git fetch
  2. Merges the origin/master(repository on the server) with master –  git merge origin/master

So this has merged the local master branch with the code from branch but the origin/master is not aware of this merge commit

So we need to do a Push

git push

Updates origin/master be at the same state as our local repository

Merge commits are not considered to be good as they pollute the repository
We have 2 people editing the same file and one of them has committed the file back to github and other person now wants to commit the same file.

git pull

Pull will sync the repository and then tries to merge but the merge will not be successful. So we need to edit the file and do a merge commit.

When we jump into the file we will see something like a diff of the local version and the server version

So we need to manually edit the file to fix it.

The

git commit –a –  Leave off the message as we do not want to go back to the editor and list the commit message and will even list the committed files that we fixed.

Then

git push –  To sync the origin/master to the local master

Remote Branches

  • When you need other people to work on your branch
  • You might want to back up a branch if it’s going to there for long
git checkout –b <branch name>–  creates and switches to a new local branch

git push origin <branch name> –  links the local branch to the remote branch for tracking.

We make some changes on the branch and when we do a commit and a push the also pushes the changes from the local branch to the remote branch

We can see the list of all the branches in github

Now when someone else does a pull from remote then it will show that a new branch is be added to the remote.

But if check the local branches it will still not be available

git branch

but we see the remote branches we will be able to see the new remote branch

git branch –r

so we could do the

git checkout <remote branch name> –  Sets up the tracking for the remote branch from origin

So now you could make the changes and push it.

git remote show

Shows

  • All the remote branches whether they are tracked or not.
  • Shows all the local branches and what remote branches they merge with.
  • Local branches configured for git push. Also shows the local branches that are out of date.

Removing a Branch

git push origin :<branch name> –  Deletes the remote branch

git branch –d <branch name> –  Deletes the local branch

If there are commits on this branch that have not been merged it will ask to either commit those changes

git branch –D <branch name> –  force delete branch

Push on Deleted Remote Branch

git commit –m –a “Commit message”

git push –  Message comes up saying everything up to date because there is no remote to push to.

git remote show origin  –  shows the branches available and stale/deleted remote branches

git remote prune origin –  clean up the deleted remote branches references

Prune

We would have 2 copies of a remote branch locally. One is brach that we work with and the other one is a read-only copy of the remote branch. We could check that by running

git branch --all

Once we are done working with a brach we delete the branch but we might also want to remove the read-only copy of the branch maintained by git as well. We could do that by using the Prune command which removes all unreachable objects from the database.

git pull —prune

We could also use gc which automatically calls prune

git gc

Tags

A tag is a reference to commit. It is mostly used for the release versioning.

git tag –  list all the tags

git checkout tagname –  checks out the code at commit

git tag –a <tagname> -m “Tag description”

git push –tags –  Pushes the tags otherwise the tags will stay local

Rebase

Merge commits are not so great so we want to skip them. So Someone already pushed a new version of source code after you pulled but before you push. So now if you try to push your code it will be reject as you are behind the commit at this point of time.
So instead of git pull and git push we could do git fetch and git rebase

git fetch –  Goes to github and pulls down any changes but does not merge them

Rebase does the following steps.

  • Moves the changes form master which are not in origin/master to a temporary area.
  • Then it runs all the origin master commits one by one
  • Then it runs all the commits in the temporary area onto the master one by one.

So the merge happens without any merge commit.

Local Branch Rebase

git checkout admin –  switches to admin branch

git rebase master –  First runs the master commits and then it runs the additional admin commits onto the admin branch

git checkout master –  move to the master branch

git merge admin –  does a fast forward commit as the changes have been taken care of

We have 2 people editing the same file and one of them has committed the file back to github and other person now wants to commit the same file.

git fetch – fetches the commits of the branch in the repository

git rebase –  Takes the commits from master and moves them to a temporary area. Then it runs all the origin master commits. Then it runs the temporary area commits one at a time. And this will lead to a conflict

So need to fix the merge conflict and then run git rebase – – continue

git rebase - - skip –  Skips the patch

git rebase  - - abort –  Checkout the original branch and stop rebasing

once we are done with the editing of the file we do a

git add filename

git rebase - - continue –  continues applying the commits

History

git log –  Shows the list of the logs of the recent commits.

It shows

  • SHA
  • Author
  • Date Commit message
git config - - global color.ui true –  Emphasis the commit hash

git log - - pretty=oneline –  Displays one commit per line starting with SHA and then the commit message

git log - - pretty=formt: “%h %ad- %s [%an]” –  You can have specific format for the log

%ad – author date

%an – author name

%h – SHA hash

%s – subject

%d – ref names

* Run git help log for more options

Aliases for log output formats

git log  - - global alias.mylog \ “log - - pretty=format: %h %s [%an] - - graph”

To use this log formatting just use

git mylog

git config - - global alias.lol \ “log - - graph - - decorate - - pretty=oneline - - abbrev-commit - - all”

Shows the graphical output

git log - - online –p  –  provides the information of what was added and what was deleted.

git log - - online - - stat –  Shows how many insertions and deletions were made in each file in each commit.

git log - - online - - graph –  Shows visual representation of branch merging into master

Date and Time Ranges for Log

git log - - until=1.minute.ago –  Show log until 1 minute ago

git log - - since=1.day.ago –  shows log since days specified

git log - - since=1.hour.ago

git log - - since=1.month.ago - - until=2.weeks.ago –  Since and until

git log - - since=2000-01-01 - - until=2012-12-21 –  since an until

Uncommited Changes

git diff HEAD –  Does the same thing as git diff i.e. compares with the last commit

Comparing with earlier commits

git diff HEAD^ –  compares with parent of last commit

git diff HEAD^^ –  compares with grandparent of last commit

git diff HEAD~5 –  compares with the code 5 commits ago

git diff HEAD^ . . HEAD –  compares the second most recent to the most recent

git diff sha1 . . sha2 –  compares between different SHA’s

We could also use abbreviated sha’s available in github

git diff master <branch name> –  diff between two branches

* Can use time based diff just like logs

Blame

git blame <file name> - - date short –  shows the SHA’s and the commit ids and the difference between the various commits

Excluding files and folder

To exclude a folder we need to put the folder name inside the .git/info/exclude file and then we will not that folder anymore.

So we can exclude

Specific file –  tutorial.mp4

Specific file type –  *.mp4

Specific directory –  experiments/

.log files in log directory –  logs/*.log

Excluding From All Copies

.getignore –  To ignore the file not only from the local repository but also from the all the repositories

Removing a File from the repository

git rm filename –  removes the file from the local file system and is untracked

and then we commit

git commit –m “Removed file” –  The file finally removed

Untracking File

git rm - - cached filename –  stops watching for the changes of the file. It is deleted  only from the repository and not from the file system.

Aliases

git config - - global alias.st status –  git st = git status

git config - - global alias.co checkout –  git.co = git.checkout

git config - - global alias.br branch –  git br = git branch

git config - - global alias.ci commit –  git ci = git checkout

 

Data types in git

blob, tree commit, tag

git checkout <commitid> –  used to go to the history in any time.

Git takes snapshot and not the diff. So it takes the snapshot of the database at any point in time.

Difference Since some date

git diff "@{yesterday}"

git whatchanged --since="2 weeks ago"

 

Reset author on previous commit

git commit --amend --author "New Author Name <newmail@example.com>"

Reset author on all commits

$ git filter-branch --commit-filter 'if [ "$GIT_AUTHOR_NAME" = "Old Author Name" ];then export GIT_AUTHOR_NAME="New Author Name";export GIT_AUTHOR
_EMAIL=test@example.com; fi; git commit-tree "$@"'

Any questions, comments and feedback are most welcome.

 

An array is a collection of objects and these objects may be of different types. The difference between both these types of initialization is that JavaScript engine interprets the literals every time the array is accessed.

Initialization

We can also initialize the array to a specific size. We could also assign values particular elements of the array and when we do this the other elements will be undefined. You can see the same in the sample below where we have used for loop to show the elements of the array.

The elements of an array can be assessed directly by the 0 based index. We can use this 0 based index to get or set the value at a particular index.

function arrayDeclaration() {

var arrayObj = new Array("Item 1", 2, true);

var arrayObjWLiterals = ["Item 1", 2, false];

var arrayWithSize10 = new Array(10); // initializes array with size 10

var arrayWithUndefinedElements = ["Item 1", , "Item 3", , "Item 5"];

console.log(arrayObj); // ["Item 1", 2, true]

console.log(arrayObjWLiterals); // ["Item 1", 2, false]

console.log(arrayWithSize10); // [ ]

for (var i = 0; i < 5; i++) {

console.log("Element number " + (i+1) + " in array is " + arrayWithUndefinedElements[i]);

//Element number 1 in array is Item 1

//Element number 2 in array is undefined

//Element number 3 in array is Item 3

//Element number 4 in array is undefined

//Element number 5 in array is Item 5

}

}

When we pass an array in a function then it is a passed as a reference. This means if we change the values in the function then the value of the actual array are also modified. So we have modified the value of the 1st element of the array using array index of 0.

function passArrayInFunc() {

var arrayObj = ["Initial Value 1", "Initial Value 2"];

console.log("Array value before passing to function --- " + arrayObj); // Initial Value 1,Initial Value 2

modifyArrayFirstElement(arrayObj);

console.log("Array value after passing to function --- " + arrayObj); // Modified Value 1,Initial Value 2

}

function modifyArrayFirstElement(arrayObj) {

arrayObj[0] = "Modified Value 1";

}

Multidimensional

Multidimensional arrays have array as the elements of an array. In the previous section we saw we can access the element of an array by doing something like arrayObj[1] and this would return the element present at this index however if we do the same for a multidimensional array we will get back an array instead of an element.

var multidimArray = new Array(3);

multidimArray[0] = ["Item 0.1", "Item 0.2", "Item 0.3"];

multidimArray[1] = ["Item 1.1", "Item 1.2", "Item 1.3"];

multidimArray[2] = ["Item 2.1", "Item 2.2", "Item 2.3"];

console.log(multidimArray[0]); // ["Item 0.1", "Item 0.2", "Item 0.3"]

console.log(multidimArray[1]); // ["Item 1.1", "Item 1.2", "Item 1.3"]

console.log(multidimArray[2]); // ["Item 2.1", "Item 2.2", "Item 2.3"]

console.log(multidimArray[0][0]); // Item 0.1

console.log(multidimArray[0][1]); // Item 0.2

console.log(multidimArray[0][2]); // Item 0.3

We can use the concat method available on the multidimensional array to put all the arrays in the multidimensional array into a single array. This method takes one or more arrays and appends its elements to the new array.

var arrayObj = multidimArray[0].concat(multidimArray[1], multidimArray[2]);

console.log("Single dimensional array from multidimensional array -- " + arrayObj);

Array to string

We can convert an array into a string by simply using the join function on the array. We could simply pass nothing and comma (,) will become the delimiter for the array items or we can pass a parameter to the string function and that will act as a delimiter for each item of the string.

function arrayToString() {

var arrayObj = new Array("Item 1", "Item 2", "Item 3", "Item 4", "Item 5");

console.log("array join with no parameters - " + arrayObj.join()); // Item 1,Item 2,Item 3,Item 4,Item 5

console.log("array join with '||' as parameter - " + arrayObj.join("||")); // Item 1||Item 2||Item 3||Item 4||Item 5

}

It does not matter what types of objects does the array contains when we call the join methods it converts all the elements into its string equivalents and concatenates all the items of the array.

Sort and reverse sort an array

To sort an array of strings simply use sort method available for the array. We can see in the code below that we have sorted the list of months alphabetically.

function sortstringArray() {

var unsortedStringArray = new Array("jan", "feb", "mar", "apr", "may", "june");

console.log("sorted array --- " + unsortedStringArray.sort()); // apr,feb,jan,june,mar,may

}

Now let us try this sort function on an integer array.

function sortIntegerArray() {

var unsortedIntegerArray = new Array(5, 8, 9, 2, 6, 1, 0, 5, 6, 8, 7, 4);

console.log(unsortedIntegerArray.sort()); // [0, 1, 2, 4, 5, 5, 6, 6, 7, 8, 8, 9]

}

So it works perfectly find with single digit numbers. Now let’s try sorting with a combination of single and double digit numbers.

unsortedIntegerArray = new Array(5, 23, 13, 9, 8, 59);

console.log(unsortedIntegerArray.sort()); // [13, 23, 5, 59, 8, 9]

We get an improperly sorted array. The reason is that sort does not compare numbers but it compares the elements of the array lexically. So to fix this we need to implement our custom compare function which will return the difference of two numbers which we can use in sorting.

console.log(unsortedIntegerArray.sort(compare)); // [5, 8, 9, 13, 23, 59]

function compare(a, b) {

return a - b;

}

Now we get a properly sorted array because for each sort we are using the return value form compare method which is either +ve, -ve or 0. This same function will also work if we have numbers in form of strings. The reason is that the sort method is intelligent enough to convert these strings into numbers automatically and convert them back to string as well.

unsortedIntegerArray = new Array("5", "23", "13", "9", "8", "59");

console.log(unsortedIntegerArray.sort(compare)); // ["5", "8", "9", "13", "23", "59"]

We can achieve a reverse sort array by simply sorting the array and then reversing it as the sort function sorts the elements in the ascending order.

function reverseSortArray() {

var unsortedStringArray = new Array("jan", "feb", "mar", "apr", "may", "june", "july", "aug", "sep", "oct", "nov", "dec");

console.log("reverse sorted array --- " + unsortedStringArray.sort().reverse()); // sep,oct,nov,may,mar,june,july,jan,feb,dec,aug,apr

}

Array as a Stack and Queue

A stack is an object which adds the items in the linear order and when we retrieve the object we can access only the object that was added at the last and then the object that was added before that.

We can use the array object as a stack. We can use the push method of the array to add elements to the array and when we want to access the last added object we can use the pop method available in the array object.

function arrayAsStack() {

var arrayStack = new Array();

arrayStack.push("Item 1");

arrayStack.push("Item 2");

arrayStack.push("Item 3");

arrayStack.push("Item 4");

// This is equivalent to the code above

//arrayStack = new Array("Item 1", "Item 2","Item 3","Item 4" );

console.log(arrayStack.pop()); // Item 4

console.log(arrayStack.pop()); // Item 3

console.log(arrayStack.pop()); // Item 2

console.log(arrayStack.pop()); // Item 1

console.log(arrayStack.pop()); // undefined

}

 

A queue is a structure that allows us to enter the items into the queue in a linear way and access the item in the same order as they were added to the queue.

We can have the same behavior by using an array. We can use the push method of the array to add elements to the array and when we want to access the item in the same order they were added we can use the shift method available in the array object.

function arrayAsQueue() {

var arrayQueue = new Array();

arrayQueue.push("Item 1");

arrayQueue.push("Item 2");

arrayQueue.push("Item 3");

arrayQueue.push("Item 4");

console.log(arrayQueue.shift()); // Item 1

console.log(arrayQueue.shift()); // Item 2

console.log(arrayQueue.shift()); // Item 3

console.log(arrayQueue.shift()); // Item 4

console.log(arrayQueue.shift()); // undefined

}

Create an array from another array

We can create an array from another array by using the slice method available in the array. The slice method accepts two parameters: the start index of the array being sliced and the end index of the array being sliced.

function arraySlicing() {

var firstArray = new Array("Item 1", "Item 2", "Item 3", "Item 4", "Item 5");

var secondArray = firstArray.slice(2, 5);

console.log(secondArray); // ["Item 3", "Item 4", "Item 5"]

}

Now let us check whether the values that we copied into the array were copied as values or as references. We could check it by modifying the value of the array items and see if the changes were reflected in the array.

secondArray[2] = "modified item 5";

console.log(firstArray); // ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]

console.log(secondArray); // ["Item 3", "Item 4", "modified item 5"]

We saw that slice copied the items into the list by copying the values. The reason was because we were copying a primitive type. Now let us create an array which has objects instead of values.

function objectArraySlicing() {

var objectArray = new Array(3);

objectArray[0] = ["Item01", "Item02", "Item03"];

objectArray[1] = ["Item11", "Item12", "Item13"];

objectArray[2] = ["Item21", "Item22", "Item23"];

var newObjectArray = objectArray.slice(1, 3);

console.log(newObjectArray.toString()); // Item11,Item12,Item13,Item21,Item22,Item23

newObjectArray[1][2] = "Modified Item 23";

console.log(objectArray.toString()); // Item01,Item02,Item03,Item11,Item12,Item13,Item21,Item22,Modified Item 23

console.log(newObjectArray.toString()); // Item11,Item12,Item13,Item21,Item22,Modified Item 23

}

So we see that when we slice the array with objects as items we see that the items are copied by references and when we change the value in any of the arrays then the value is changed in both of them.

Search in array

The array object provides us with two methods to search for items in an array. These two methods are indexOf and lastIndexOf. If the item has only one occurrence then both the methods will return the same index of the element and if there are multiple occurrences of the element then the indexOf will return the index of the first occurrence of the element and lastIndexOf will return the index of the last occurrence of the element.

function searchInArray() {

var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"];

console.log(arrayToSearch.indexOf("june")); // 3

console.log(arrayToSearch.lastIndexOf("june")); // 7

}

//In both of these methods we can optionally specify the starting index of the search and will start searching for the element from that index.

console.log(arrayToSearch.indexOf("june", 4)); // 7

console.log(arrayToSearch.lastIndexOf("june", 4)); // 3

Now we specified the starting index in both our methods a 4 and we see that indexOf return 7 as the first occurrence of june which seems correct. But the lastIndexOf returns 3 which seem strange. Its correct because we said that the starting index of search is 4 and that’s where the search starts from but interestingly the lastIndexOf searches the whole array and then tells the last index and when we specified the start point of search as 4 we made the last index of array as 3 instead of 7.

Insert, replace and remove elements from array

The splice method is used to remove the elements form the array. So in the code below we have passed 3 and this will remove all the elements from the array but first three.

In the next block of code we have passed -3 and this will remove the last 3 elements from the array.

function removeFromArray() {

var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"];

console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june

arrayToSearch.splice(3);

console.log("Array after -- " + arrayToSearch); // jan,mar,may

var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"];

console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june

arrayToSearch.splice(-3);

console.log("Array after -- " + arrayToSearch); // jan,mar,may

}

We can insert an element at any index in the array. We can use the splice method to do that.

function insertInArray() {

var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"];

console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june

arrayToSearch.splice(3, 0, "july");

console.log("Array after -- " + arrayToSearch); // jan,mar,may,july,june,dec,apr,may,june

}

Here we have passed 3 parameters to the splice method:

  • Index: We have passed 3 as the index where we insert the new element.
  • Element count to remove: We have passed 0 as number of elements we want to replace.
  • Element to add: We have passed “july” as the element we want to insert.

We can use a combination of splice and indexOf methods to remove and replace elements within an array.

function replaceInArray() {

var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"];

console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june

arrayToSearch.splice(arrayToSearch.indexOf("june"), 1, "july");

console.log("Array after -- " + arrayToSearch); // jan,mar,may,july,dec,apr,may,june

}

We see here that we have passed 3 parameters to the splice method.

  • Index: We have passed the index by using the indexof method. This index is the place where we want to insert the new element.
  • Element count to remove: We have passed 1 as number of elements because I want to replace june.
  • Element to add: We have passed “july” as the element we want to insert.

Till now we have just passed one element that we want to add to the array. We can pass a list of elements we want to add to the array.

function addMultipleElements() {

var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"];

console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june

arrayToSearch.splice(1, 7, "feb", "mar", "apr", "may", "june", "july", "aug");

console.log("Array after -- " + arrayToSearch); // jan,feb,mar,apr,may,june,july,aug

}

The code for this post can be found here.

Any questions, comments or feedback is really appreciated.

 

 

The math object in JavaScript does not have constructor so we cannot instantiate it. All the methods and properties can be assessed directly from the math object.

Math Object Properties

The following properties are available on the math object

E Returns Euler’s number (approx. 2.718)
LN2 Returns the natural logarithm of 2 (approx. 0.693)
LN10 Returns the natural logarithm of 10 (approx. 2.302)
LOG2E Returns the base-2 logarithm of E (approx. 1.442)
LOG10E Returns the base-10 logarithm of E (approx. 0.434)
PI Returns PI (approx. 3.14)
SQRT1_2 Returns the square root of 1/2 (approx. 0.707)
SQRT2 Returns the square root of 2 (approx. 1.414)

 

Math object methods

The following methods are available on the math object.

abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,…,n) Returns the number with the highest value
min(x,y,z,…,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle

Generating random number

We have a random method available in the Math class which can be used for the random number generation. The only restriction with this approach is that that the random method outputs a value between 0 and 1 which is not suitable with most of our needs.

function randomBetween0and1() {

console.log("Random number - " + Math.random()); // 0.6579966396093369

console.log("Another random number - " + Math.random()); // 0.5774516856763512

console.log("Yet another random number - " + Math.random()); // 0.7963233035989106

}

To increase the range of our randoms we can simply multiply then every time by the maximum value that we want for our random number. Let’s say we want random number between 0 and 999, so will multiply the output of random function by 999.

function randomBetween0and999Float() {

console.log("a random between 0 and 999 is " + (Math.random() * 999)); // 541.2334246176761

console.log("a random between 0 and 999 is " + (Math.random() * 999)); // 56.533659977372736

console.log("a random between 0 and 999 is " + (Math.random() * 999)); // 889.5993133583106

}

As you can see we got random numbers between 0 and 999 but these random number are not whole numbers to fix that all we need to do is use the floor function available in the math class which rounds of the decimals to nearest value.

function randomBetween0and999() {

console.log("a random between 0 and 999 is " + Math.floor((Math.random() * 999))); // 541

console.log("a random between 0 and 999 is " + Math.floor((Math.random() * 999))); // 56

console.log("a random between 0 and 999 is " + Math.floor((Math.random() * 999))); // 889

}

Now say we want to generate the random number between 99 and 999. We will use the same way but now instead of just multiplying the random number by upper range but we will multiply by upper range – (lower range – 1) and then multiply by lower range.

function randomBetween99and999() {

console.log("a random between 99 and 999 is " + (Math.floor((Math.random() * 901)) + 99)); // 541

console.log("a random between 99 and 999 is " + (Math.floor((Math.random() * 901)) + 99)); // 156

console.log("a random between 99 and 999 is " + (Math.floor((Math.random() * 901)) + 99)); // 889

}

The code for this post can be found here.

Any questions, comments or feedback is really appreciated.