Monday, 9 October 2017

How to secure your Bitcoin Wallet?

A mobile bitcoin wallet is convenient to use, because it can be installed on either a tablet or smartphone. Either of these devices is more often than not in close proximity to everyday consumers and doesn’t require users to take additional items with them wherever they go.
Similar to how a desktop bitcoin wallet works, having access to an Internet connection — either through mobile data or WiFi — is a great plus when it comes to sending and receiving transactions. However, this is not a must, as most bitcoin wallets allow users to send and receive funds through NFC or Bluetooth Low Energy connection. In return, this makes mobile wallets more versatile compared to their computer counterparts, which is also part of the reason why bitcoin has received a lot of appreciation from its users.
In terms of security, the story with mobile bitcoin wallets is not all that different from a piece of software installed on your computer. The private key — which allows you to spend bitcoins from your wallet — is stored on your mobile device itself. As a security measure, this reduces the risk of the private key falling into the wrong hands.
However, there is a potential risk in doing so as well. Given the current rate at which technology — and consumer behavior — evolves, smartphones and tablets are being replaced at a rapid pace. Considering that your private key is stored on that mobile device, it is important to make a backup as soon as you install the mobile bitcoin wallet of your choice.
Depending on which type of mobile wallet you’re using, a backup feature is included in the software itself. A copy of your backup can then be exported to cloud services such as Dropbox or Google Drive, or even sent to yourself via e-mail. Any application you have installed on your mobile device with backup capabilities should be available to use.
All in all, mobile bitcoin wallets can provide the best solutions when balancing the needs of security and convenience, but it all depends on the individual user in the end. If users are careless with their device, or forget to back up their private key, there is no option to restore access to their mobile bitcoin wallet. Bitcoin allows users to take full control — and full responsibility — at every step, which includes responsibilities such as backing up their mobile wallet.

Secure online bitcoin wallets — or not

You could easily draw a parallel between online bitcoin wallet providers and financial institutions such as banks. Both services handle your personal funds, and you can check the balance, as well as send and receive funds at any time. But you are trusting a bank to keep your funds safe, and that’s not what bitcoin is about. Ever since bitcoin’s inception, trust has played an integral role in the development of this ideology.
Satoshi Nakamoto envisioned that the future development of bitcoin would eventually lead to a “trustless” society, where all interactions were done between people directly, without using any third-party service.
On top of that, you are responsible for protecting your personal mobile wallet service account. Most online bitcoin wallet platforms provide options such as two-factor authentication. And although that additional layer of security protects the user from harm — in most cases, as no system is truly perfect — it will not prevent your funds from being stolen if the online wallet service itself is hacked.

Secure paper bitcoin wallets

A bitcoin paper wallet can be best described as a document containing all the data necessary to generate private keys, effectively forming a “wallet of private keys.” But that is not its only purpose, because a paper wallet can also be used to store bitcoins safely and securely, in which case the paper itself also includes public keys and redeemable codes.
The main purpose of a redeemable code is to use it as a means of funding and “redeeming” funds associated with a certain bitcoin wallet address. However, it is important to note that paper wallets should only be used once, because a paper wallet is not a bitcoin wallet intended for daily use.
Paper wallets can serve many purposes. A bitcoin paper wallet makes for a great gift when introducing friends, family, and loved ones to bitcoin. Or you can give someone a paper wallet as a tip, to show your appreciation for something the other person has done. Redeeming a paper wallet as a gift or tip requires recipients to have a bitcoin wallet installed on their computer or mobile device, through which they can import the private key associated with that address.


How to store Bitcoin?


Bitcoin has grown considerably in popularity over the past several months, with prices almost tripling and more and more cryptocurrency followers joining the field. As this has taken place, so too have the number of publicized hacking events increased as well. With more money being invested in digital currencies now than ever before, and particularly given that many investors are new to the system and may not know how to keep their investments secure, hackers are coming up with ingenious ways of stealing funds. Some of the most prominent thefts have been those that have taken place in plain sight: a recent hack rerouted tokens bound for one wallet for another. The victims watched as their tokens were stolen away from them, with nothing they could do about it. Here are a few ways to store your Bitcoins that may be safer than others.

Desktop Wallet

A desktop wallet offers a number of advantages over an online wallet. While online wallets are easily accessed from anywhere in the world, they are also more vulnerable to potential hacking. Desktop wallets, on the other hand, are accessed only via your private computer, with personal security keys stored just on that machine. Thus, exposure of your security key online is reduced. Nonetheless, desktop wallets are still susceptible to hacks if your machine gets infected with malware designed to root out keys and steal Bitcoins.

Hardware Wallet

More secure than a desktop wallet is a hardware wallet. These wallets are bits of hardware, external devices like USB sticks which you can carry around on your person. An added benefit of a hardware wallet is the complete anonymity with which you can transact. There is no personal information linked to the hardware, so no identifying data which could be leaked. Hardware wallets are resilient to malware, and if you happen to lose the wallet you'll be able to recover the funds using a seed phrase.

Paper Wallet

A paper wallet is also a relatively safe way of storing Bitcoin, although it requires a bit more advanced understanding of how digital currencies work. Generate a paper wallet online using any number of dedicated websites, or generate the wallet offline for even greater security. Paper wallets are stored easily because they don't take up a great deal of space, and they also offer true anonymity: they are simply a Bitcoin seed written in some way on a piece of paper.

Physical Coins

Services are cropping up which allow Bitcoin investors to buy physical Bitcoins. The coin you purchase will have a tamper-proof sticker covering a predetermined amount of Bitcoin. In order to purchase the physical coin, you may need to pay a slight premium over the value of the Bitcoin that you're buying, owing to the cost of the manufacture and shipment of the coin itself.

Wednesday, 4 October 2017

A school where teachers don't 'teach'!

He was all of 33 when his friends, acquaintances, colleagues and the wider circle of people around him thought he’d taken leave of his senses. And who really could blame them?
The year was 2009.
An IIT-Kharagpur engineer and IIM-Ahmedabad MBA, Arghya Banerjee lived in Chennai with his wife and four-year-old daughter, worked at Irevna -- a Standard and Poor’s equity research outsourcing company that later got acquired by Crisil -- had built a career and reputation in his chosen field and had some savings to get by.
That’s when Banerjee decided to chuck it all, return to his native town, Suri, in West Bengal’s Birbhum district, and start a school.
He had no experience in running schools, had no degrees that teachers or school administrators typically acquired, he had no one chasing him to fund his “mad” idea and he really had no one patting his back, saying he was doing something noble.


Want to know more detail check the link
http://www.rediff.com/getahead/report/a-school-where-teachers-dont-teach/20171003.htm

Friday, 22 September 2017

Google Doodle for the day september23,2017

Google Doodle today celebrates the 100th birthday of Asima Chatterjee, a renowned Indian chemist who was the first female Doctorate of Science in India from an Indian university.  

Born on September 23, 1917, Dr Asima Chatterjee has made various contributions on the research of vinca alkaloids and the development of anti-epileptic and anti-malarial drugs.  

According to Google's blog, "Dr Chatterjee primarily studied the medicinal properties of plants native to India. Throughout her career, her research contributed to the development of drugs that treated epilepsy and malaria. Dr Chatterjee's most noted contribution to the field, however, was her work on vinca alkaloids. Alkaloids are compounds made from plants, often to treat medical ailments. Vinca alkaloids, which come from the Madagascar periwinkle plant, are used today in chemotherapy treatment because they help slow down or stall the multiplying of cancer cells." 

Asima joined the Lady Brabourne College in Calcutta Universtiy in 1940 and founded the department of chemistry in the college. 

Asima Chatterjee's work in the field of science opened the doors for millions of women to excel in the field and her research on vinca alkaloids which is now widely used in chemotherapy and helps to slow down the growth rate of cancer cells. 

Her phenomenal contributions have won Asima various awards and accolades from all over the world and she was also honoured with India's third highest civilian award, Padma Bhushan. In 1975 she became the first woman to be appointed general president of the Indian Science Congress.

Monday, 18 September 2017

Bitcoin- past,present and future

Bitcoin (ticker: BTC) has been around since late 2008 but it only started making the news in early 2013. It is a crypto currency and a payment system; its main advantage being that transactions are anonymous and peer-to-peer (i.e. made directly without an intermediary). Bitcoin’s unique architecture is set-up in such a way that their creation (or “mining”) gets progressively more resource-intensive and total production will be limited to 21 million Bitcoins.
It’s certainly an interesting concept with many advantages but also some important disadvantages. For example:
  1. Given its pseudonymous nature and that Bitcoin address owners are not explicitly identified, such transactions are effectively anonymous. However, this anonymity has been known to attract transactions from illegal activities, the best-known example being that of the Silk Road website. This has been a problem with regulators and officials, as they recognise it as a medium for illegal transactions.
  2. Bitcoin has been recognised as currency in many countries and as of today it’s the most liquid & widely accepted crypto currency in the world. However, there is a long list of alternate crypto currencies that are eager to grab market share and challenge Bitcoin’s dominance. And what about the 21 million Bitcoin limit? It’s possible that once that ceiling becomes severely limiting, users will turn to other crypto currencies, effectively increasing the global supply.
  3. Bitcoin trades continuously on exchanges around the world in a very quick and straightforward manner, and it is conveniently stored electronically in “wallets”. However, having online wallet providers introduces an extra risk factor that cannot be ignored. One such example is the security breach at Mt. Gox in 2011, which sent shockwaves in the crypto currency community. At the time, Mt. Gox was handling around 70% of all Bitcoin transactions and one day it declared that around 850,000 Bitcoins had been stolen. Soon after the exchange suspended trading and filed for bankruptcy. It’s this potential security vulnerability that makes many people sceptical when it comes to crypto currencies.

What does the future hold for Bitcoin?

So what’s next for Bitcoin? As outlined previously, it has many advantages and for this reason it will remain relevant as a currency. The vast majority of BTC transactions by volume are made in China so the two will remain interlinked.
We see the biggest risk to Bitcoin being its substitution and/or parallel use by other crypto currencies. Bitcoin die-hard fans claim that this is never going to be an issue since Bitcoin was the pioneer and as such enjoys first-mover privilege. This argument is probably flawed because although the BTC is used for payments, this is only a relatively small % of all Bitcoins. One of its primary uses is being a store of value and for this reason other crypto currencies can always step in and enjoy similar status if aggregate demand requires it.
Is Bitcoin simply a 21st century version of gold, only without the storage issues? Or is it just a short-lived popular fad that may soon evolve into something quite different? Only time will tell. The only certainty is that its price will remain very volatile in the future.

Sunday, 17 September 2017

Bitcoin Price Might Exceed $1 Million

While sources differ on the number of millionaires in the world, Credit Suisse estimates the number at about 35 million. This figure accounts for all “financial and nonfinancial wealth,” including assets, collectibles, and homes.
This is a remarkable number when compared to the total number of Bitcoins that will ever exist. While there are roughly 35 million millionaires in the world, there will only ever be a maximum of 21 million Bitcoins. That’s right--there will never be enough Bitcoins in existence for every millionaire in the world to own even a single one.

Why is Bitcoin valuable?

While you let that thought sink in, let’s consider what gives Bitcoin its value. Granted that there are numerous features we could cite, including a global network, an immutable Blockchain and a means to transfer wealth from one person to another without ever involving a middleman.
These are all fine features, to be sure. But what really makes Bitcoin valuable are two properties: scarcity and authenticity.

Digital scarcity

Bitcoin has value for the same reason gold has value: people want it and there isn’t enough to go around. New gold can’t merely be created; one has to find a gold mine and go through the difficult, capital-intensive and expensive process of mining and refining the gold. Because neither governments nor factories can create more of it, gold is scarce. This scarcity imparts value.
Many unusual items have been used as currencies or stores of value in earlier societies. One of the more famous is wampum, a necklace made from a certain kind of seashell that was rare in the Americas. A currency doesn’t necessarily have to be inherently useful in order to function, but it absolutely must be scarce.
This requirement for scarcity is the reason counterfeiting has such severe penalties. In fact, in earlier times, counterfeiting was punishable by death. Counterfeiters undermined confidence in a currency by making it less scarce. Doing so, at scale, could wreck an entire economy.

Authenticity

Gold has another feature that’s extremely important for any store of value or currency: authenticity. For millennia, gold has been used as both a currency and as a store of value. It has been prized throughout its history because of its scarcity. Gold has been used in money, in jewelry, in crowns and in palaces. Gold is universally associated with wealth.
Since Bitcoin lacks the thousands of years of history, culture and tradition that impart so much value and mystique to gold, it's easy to write the currency off as inauthentic.
But in a world that's rapidly moving from analog to digital, even a "new" technology like Bitcoin can be authentic. When it comes to digital money, Bitcoin certainly fits the bill. Of the thousands of different tokens that label themselves “digital currency,” Bitcoin is the very first. That grants it an important claim to the property of authenticity.
There are many great altcoins, but none of them were first. None of them can reasonably claim to be the best. None have a higher market capitalization. Bitcoin is the first, has the largest network effect, is the most universally recognized and is authentic.

Asset or currency?

As Bitcoin inches toward mainstream adoption, economists and finance experts debate whether it’s an asset or a currency. In terms of valuing Bitcoin, that argument couldn’t be more irrelevant. It doesn’t matter how people use Bitcoin; what matters is why people choose to own it.

Bitcoin’s future

The future of Bitcoin is almost certainly a bright one. Various analysts and traders have tried to guess the value of Bitcoin in the future, with some saying it might even reach $15,000 in the near term.
But forget about the near term. If Bitcoin is digital gold, then its long term value is what really matters. Bitcoin is rare. Bitcoin is scarce. The vast majority of people don’t own even a fraction of one.
What’s Bitcoin’s long-term potential? Bitcoin could easily become so valuable that even millionaires can’t afford an entire coin.

Friday, 15 September 2017

Bitcoin freefall in India




The Bitcoin has gone on a tailspin in India, falling much faster that elsewhere in the globe, after a China crackdown on crypto-currencies and public remark by an Reserve Bank of India (RBI) official, trashing the digital currency.

According to the data available with Zebpay, the value of the currency in India has declined from Rs 3,40,116 per unit on September 2 to hit a low of Rs 2,29,417 on September 15, indicating a fall of 48 per cent in less than two weeks.

Zebpay is an app-enabled Bitcoin wallet provider headquartered in Singapore with IT offices in Mumbai, Maharashtra and Ahmedabad. Zebpay is involved in sale and purchase of bitcoins since 2011. It started India’s first bitcoin exchange in 2012.

Till recently, Bitcoin and other crypto-currencies were hailed as something that would usher in a new world order for the monetary system and challenge the establishment, including global central banks.

But in recent times, these new-age currencies have been losing the battle against regulators. Bitcoin, the biggest names among such non-fiat currencies, is going through one of its toughest phases in 2017, plunging some 27 per cent since September 7 in global markets.

Earlier this week, a Reserve Bank of India official virtually trashed the crypto-currencies. "As regards non-fiat crypto-currencies, I think we are not comfortable,” Sudharshan Sen, RBI's Executive Director, said at a Mumbai event.

RBI has been repeatedly cautioning people about the usage of crypto-currencies, flagging a slew of concerns.

Crypto-currencies, also called virtual currencies, are created and held electronically. Bitcoin, invented by Satoshi Nakamoto in 2009, is commonly known as a decentralised digital currency.

These new-age currencies have been the talk of the town and are garnering a lot of publicity. However, of late all that is being said about Bitcoin in globally has not been too positive.

The currency came under severe pressure after BTCChina, one of the biggest Bitcoin exchanges in the world, on Thursday announced that it would shut down all trading activities on its platform from September 30, after the regulators clamped down on crypto-currencies.

The move confirmed earlier reports of Chinese officials mulling a closure of domestic exchanges for virtual currency trading, which sent the price of Bitcoin tumbling.

JPMorgan Chase Chief Executive Officer Jamie Dimon earlier this week said he would fire any employee trading in Bitcoin for being ‘stupid’. “The crypto-currency won’t end well,” he told an investor conference in New York on Tuesday, predicting that it will eventually blow up.

Tuesday, 22 August 2017

Floating point number storage-The IEEE-754 floating-point standard

The IEEE-754 floating-point standard


The IEEE-754 floating-point standard is a standard for representing and manipulating floating-point quantities that is followed by all modern computer systems. It defines several standard representations of floating-point numbers, all of which have the following basic pattern (the specific layout here is for 32-bit floats):
bit  31 30    23 22                    0
     S  EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM

The bit numbers are counting from the least-significant bit. The first bit is the sign (0 for positive, 1 for negative). The following 8 bits are the exponent in excess-127 binary notation; this means that the binary pattern 01111111 = 127 represents an exponent of 0, 1000000 = 128, represents 1, 01111110 = 126 represents -1, and so forth. The mantissa fits in the remaining 24 bits, with its leading 1 stripped off as described above.
Certain numbers have a special representation. Because 0 cannot be represented in the standard form (there is no 1 before the decimal point), it is given the special representation 0 00000000 00000000000000000000000. (There is also a -0 = 1 00000000 00000000000000000000000, which looks equal to +0 but prints differently.) Numbers with exponents of 11111111 = 255 = 2128 represent non-numeric quantities such as "not a number" (NaN), returned by operations like (0.0/0.0) and positive or negative infinity. A table of some typical floating-point numbers (generated by the program float.c) is given below:
         0 =                        0 = 0 00000000 00000000000000000000000
        -0 =                       -0 = 1 00000000 00000000000000000000000
     0.125 =                    0.125 = 0 01111100 00000000000000000000000
      0.25 =                     0.25 = 0 01111101 00000000000000000000000
       0.5 =                      0.5 = 0 01111110 00000000000000000000000
         1 =                        1 = 0 01111111 00000000000000000000000
         2 =                        2 = 0 10000000 00000000000000000000000
         4 =                        4 = 0 10000001 00000000000000000000000
         8 =                        8 = 0 10000010 00000000000000000000000
     0.375 =                    0.375 = 0 01111101 10000000000000000000000
      0.75 =                     0.75 = 0 01111110 10000000000000000000000
       1.5 =                      1.5 = 0 01111111 10000000000000000000000
         3 =                        3 = 0 10000000 10000000000000000000000
         6 =                        6 = 0 10000001 10000000000000000000000
       0.1 =      0.10000000149011612 = 0 01111011 10011001100110011001101
       0.2 =      0.20000000298023224 = 0 01111100 10011001100110011001101
       0.4 =      0.40000000596046448 = 0 01111101 10011001100110011001101
       0.8 =      0.80000001192092896 = 0 01111110 10011001100110011001101
     1e+12 =             999999995904 = 0 10100110 11010001101010010100101
     1e+24 =   1.0000000138484279e+24 = 0 11001110 10100111100001000011100
     1e+36 =   9.9999996169031625e+35 = 0 11110110 10000001001011111001110
       inf =                      inf = 0 11111111 00000000000000000000000
      -inf =                     -inf = 1 11111111 00000000000000000000000
       nan =                      nan = 0 11111111 10000000000000000000000

What this means in practice is that a 32-bit floating-point value (e.g. a float) can represent any number between 1.17549435e-38 and 3.40282347e+38, where the e separates the (base 10) exponent. Operations that would create a smaller value will underflow to 0 (slowly—IEEE 754 allows "denormalized" floating point numbers with reduced precision for very small values) and operations that would create a larger value will produce inf or -inf instead.
For a 64-bit double, the size of both the exponent and mantissa are larger; this gives a range from 1.7976931348623157e+308 to 2.2250738585072014e-308, with similar behavior on underflow and overflow.
Intel processors internally use an even larger 80-bit floating-point format for all operations. Unless you declare your variables as long double, this should not be visible to you from C except that some operations that might otherwise produce overflow errors will not do so, provided all the variables involved sit in registers (typically the case only for local variables and function parameters).

Error


In general, floating-point numbers are not exact: they are likely to contain round-off error because of the truncation of the mantissa to a fixed number of bits. This is particularly noticeable for large values (e.g. 1e+12 in the table above), but can also be seen in fractions with values that aren't powers of 2 in the denominator (e.g. 0.1). Round-off error is often invisible with the default float output formats, since they produce fewer digits than are stored internally, but can accumulate over time, particularly if you subtract floating-point quantities with values that are close (this wipes out the mantissa without wiping out the error, making the error much larger relative to the number that remains).
The easiest way to avoid accumulating error is to use high-precision floating-point numbers (this means using double instead of float). On modern CPUs there is little or no time penalty for doing so, although storing doubles instead of floats will take twice as much space in memory.
Note that a consequence of the internal structure of IEEE 754 floating-point numbers is that small integers and fractions with small numerators and power-of-2 denominators can be represented exactly—indeed, the IEEE 754 standard carefully defines floating-point operations so that arithmetic on such exact integers will give the same answers as integer arithmetic would (except, of course, for division that produces a remainder). This fact can sometimes be exploited to get higher precision on integer values than is available from the standard integer types; for example, a double can represent any integer between -253 and 253 exactly, which is a much wider range than the values from 2^-31^ to 2^31^-1 that fit in a 32-bit int or long.  (A 64-bit long long does better.)  So double` should be considered for applications where large precise integers are needed (such as calculating the net worth in pennies of a billionaire.)
One consequence of round-off error is that it is very difficult to test floating-point numbers for equality, unless you are sure you have an exact value as described above. It is generally not the case, for example, that (0.1+0.1+0.1) == 0.3 in C. This can produce odd results if you try writing something like for(f = 0.0; f <= 0.3; f += 0.1): it will be hard to predict in advance whether the loop body will be executed with f = 0.3 or not. (Even more hilarity ensues if you write for(f = 0.0; f != 0.3; f += 0.1), which after not quite hitting 0.3 exactly keeps looping for much longer than I am willing to wait to see it stop, but which I suspect will eventually converge to some constant value of f large enough that adding 0.1 to it has no effect.) Most of the time when you are tempted to test floats for equality, you are better off testing if one lies within a small distance from the other, e.g. by testing fabs(x-y) <= fabs(EPSILON * y), where EPSILON is usually some application-dependent tolerance. This isn't quite the same as equality (for example, it isn't transitive), but it usually closer to what you want.

for more details check the link


http://www.cprogramming.com/tutorial/floating_point/understanding_floating_point_representation.html
 

Tuesday, 15 August 2017

Wednesday, 26 July 2017

Ways to make money out of YouTube

Video is the new content style, we are all running out of attention spans and focus levels. Videos keep two of our five senses occupied and need lesser time to get the point across. YouTube has catered to our changing kind just right. Right from learning how to make a simple dish to understanding international politics, watching the iconic scenes from classic movies to simple advice with regards to teenage relationships. YouTube is the answer.
Videos are not only about shooting and viewing, but the money in there is a huge. It is possible to have a YouTube channel and actually make a lot of money out of it. Here is how:

  • Be organised from the start

If you have an existing Google ID, like a gmail one then you can just use that to sign in to Youtube. But we’d advise you to maybe create a new one, which will be for professional purposes as well, so it doesn’t get mixed up with your everyday Ola and Twitter promoting mails. Try and make it short and snappy, for you and your viewers to remember easily. (You could just be getting some fan mail…)
  • Be careful with the name of the channel

No pressure, but this pretty much determines everything. Well, most of it anyway. Be sure to make a relevant, catchy name for your Youtube Channel, a three-four word liner that sums up and most importantly, represents everything you want to show. That makes it more credible, than calling it something like ‘Joe Andrew’s channel’. You don’t want people to forget the name of your channel, you want them to keep clicking on it instead. You are assisted by the fact that you can add relevant keywords in your settings in the Advance section. Also, you can add a catchy colourful image to go with your channel, which will be featured at the top of your page.
  • CONTENT IS KING

It’s time to paint the canvas. The Internet world is truly yours for the taking, so be sure to make your content stand out. We’d strongly advise you to use high quality original content, which does not contain anything ‘adult’, ‘violent’ and ‘hateful’ and ‘copyrighted’. Challenging these set rules by Youtube, will subject you to losing your partnership with it. So, play it safe boys and girls
  • Define your videos

Since most content is often subjective, we would advise you to give a strong title and description to whatever you upload, to get the clear-cut point of the video across to your viewers. So we implore you, do not play Guess-Master with them!
  • Keep up with the Uploads, don’t slack

Not too many people become ground-breaking Youtube sensations on one good video. You need to keep up the quality of the content you are uploading, so that people are offered a variety of your work to choose best from. That’s what will get the views, that’s what will get the likes and the subscriptions.
  • Like, subscribe and share

Sound familiar? That’s right, the mantra to increasing viewership is to posting it on all the Social Media pages- Facebook, Twitter, LinkedIn, Instagram, Snapchat– fill these up with your work. Make your friends and family share it and recommend it more people. That’s how anything goes viral in this digital age, so pick your audience wisely. You can also embed it in different websites and blogs. Just make sure it’s out there and it’s doing the rounds.
  • M for Monetization

If you’re looking to make money out of your Youtube channel, the next step calls for ‘monetization’ of your channel. This feature allows Youtube to display ads in or on your video and you acknowledge that your video has no unmentioned copyright issues. This can be activated, by going to the ‘channel setting tab’ and clicking on the option of ‘Monetize with Ads’. And if you put out good content, then Youtube will send you a private message offering you the chance to “Apply for revenue sharing for You Video”. So remember, make haste while the sun shines!
  • AdSense is what you need

The next step is to set up a Google AdSense account and link it to your Youtube account. This is the most important step, as it allows you to collect your revenue. How it works, is that Youtube will pay for per ad click and per view. This works well for you when your video gets more and more views, because this leads to more potential of ad clicks and this further leads to more revenue. Although AdSense can be downloaded for free, the revenue can only be received if you have a bank or PayPal account and a valid, physical mailing address.
  • Promote, gain traffic and analyse

The final step to making money out of your Youtube Channel, involves promoting your channel on all the social media platforms, gaining more viewership and traffic through ads and shares to your channel and the final step, which includes checking out your video analytics to see the number of views, ad performance, minutes watched, age-group of people who’ve watched it etc. so that you know if your content is reaching your target audience and further, if you need to change anything.
But at the end of the day, content is king and you need to have some really good videos for the people to watch and love.

Friday, 23 June 2017

First Web Service in java using Eclipse

Let us start writing the actual RESTful web services with Jersey Framework. Before you start writing your first example using the Jersey Framework, you have to make sure that you have setup your Jersey environment properly as explained in the RESTful Web Services - Environment Setup chapter. Here, I am also assuming that you have a little working knowledge of Eclipse IDE.
So, let us proceed to write a simple Jersey Application which will expose a web service method to display the list of users.

Creating a Java Project

The first step is to create a Dynamic Web Project using Eclipse IDE. Follow the option File → New → Project and finally select the Dynamic Web Project wizard from the wizard list. Now name your project as UserManagement using the wizard window as shown in the following screenshot −
Dynamic Web Project Wizard Once your project is created successfully, you will have the following content in your Project Explorer
Usermanagement Directories

Adding the Required Libraries

As a second step let us add Jersey Framework and its dependencies (libraries) in our project. Copy all jars from following directories of download jersey zip folder in WEB-INF/lib directory of the project.
  • \jaxrs-ri-2.17\jaxrs-ri\api
  • \jaxrs-ri-2.17\jaxrs-ri\ext
  • \jaxrs-ri-2.17\jaxrs-ri\lib
Now, right click on your project name UserManagement and then follow the option available in context menu − Build Path → Configure Build Path to display the Java Build Path window.
Now use Add JARs button available under Libraries tab to add the JARs present in WEBINF/lib directory.

Creating the Source Files

Now let us create the actual source files under the UserManagement project. First we need to create a package called com.tutorialspoint. To do this, right click on src in package explorer section and follow the option − New → Package.
Next we will create UserService.java, User.java,UserDao.java files under the com.tutorialspoint package.
User.java
  

import java.io.Serializable;  
import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 
@XmlRootElement(name = "user") 

public class User implements Serializable {  
   private static final long serialVersionUID = 1L; 
   private int id; 
   private String name; 
   private String profession;  
   public User(){} 
    
   public User(int id, String name, String profession){  
      this.id = id; 
      this.name = name; 
      this.profession = profession; 
   }  
   public int getId() { 
      return id; 
   }  
   @XmlElement 
   public void setId(int id) { 
      this.id = id; 
   } 
   public String getName() { 
      return name; 
   } 
   @XmlElement
   public void setName(String name) { 
      this.name = name; 
   } 
   public String getProfession() { 
      return profession; 
   } 
   @XmlElement 
   public void setProfession(String profession) { 
      this.profession = profession; 
   }   
} 
UserDao.java


import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException;  
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.util.ArrayList; 
import java.util.List;  

public class UserDao { 
   public List<User> getAllUsers(){ 
      
      List<User> userList = null; 
      try { 
         File file = new File("Users.dat"); 
         if (!file.exists()) { 
            User user = new User(1, "Mahesh", "Teacher"); 
            userList = new ArrayList<User>(); 
            userList.add(user); 
            saveUserList(userList); 
         } 
         else{ 
            FileInputStream fis = new FileInputStream(file); 
            ObjectInputStream ois = new ObjectInputStream(fis); 
            userList = (List<User>) ois.readObject(); 
            ois.close(); 
         } 
      } catch (IOException e) { 
         e.printStackTrace(); 
      } catch (ClassNotFoundException e) { 
         e.printStackTrace(); 
      }   
      return userList; 
   } 
   private void saveUserList(List<User> userList){ 
      try { 
         File file = new File("Users.dat"); 
         FileOutputStream fos;  
         fos = new FileOutputStream(file); 
         ObjectOutputStream oos = new ObjectOutputStream(fos); 
         oos.writeObject(userList); 
         oos.close(); 
      } catch (FileNotFoundException e) { 
         e.printStackTrace(); 
      } catch (IOException e) { 
         e.printStackTrace(); 
      } 
   }    
}
UserService.java
package com.tutorialspoint;  

import java.util.List; 
import javax.ws.rs.GET; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType;  
@Path("/UserService") 

public class UserService {  
   UserDao userDao = new UserDao();  
   @GET 
   @Path("/users") 
   @Produces(MediaType.APPLICATION_XML) 
   public List<User> getUsers(){ 
      return userDao.getAllUsers(); 
   }  
}
There are two important points to be noted about the main program,

UserService.java

  • The first step is to specify a path for the web service using @Path annotation to the UserService.
  • The second step is to specify a path for the particular web service method using @Path annotation to method of UserService.

Creating the Web.xml configuration File

You need to create a Web xml Configuration file which is an XML file and is used to specify Jersey framework servlet for our application.
web.xml
<?xml version = "1.0" encoding = "UTF-8"?> 
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"  
   xmlns = "http://java.sun.com/xml/ns/javaee"  
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
   id = "WebApp_ID" version = "3.0"> 
   <display-name>User Management</display-name> 
   <servlet> 
      <servlet-name>Jersey RESTful Application</servlet-name> 
      <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servletclass> 
      <init-param> 
         <param-name>jersey.config.server.provider.packages</param-name> 
         <param-value>com.tutorialspoint</param-value> 
      </init-param> 
   </servlet> 
   <servlet-mapping> 
      <servlet-name>Jersey RESTful Application</servlet-name> 
      <url-pattern>/rest/*</url-pattern> 
   </servlet-mapping>   
</web-app>

Deploying the Program

Once you are done with creating source and web configuration files, you are ready for this step which is compiling and running your program. To do this, using Eclipse, export your application as a war file and deploy the same in tomcat.
To create a WAR file using eclipse, follow the option File → export → Web → War File and finally select project UserManagement and destination folder. To deploy a war file in Tomcat, place the UserManagement.war in the Tomcat Installation Directory → webapps directory and start the Tomcat.

Running the Program

We are using Postman, a Chrome extension, to test our webservices.
Make a request to UserManagement to get list of all the users. Put http://localhost:8080/UserManagement/rest/UserService/users in POSTMAN with GET request and see the following result.
RESTful API, All users Congratulations, you have created your first RESTful Application successfully.

Web Services in java

Web services are one of the most successful implementations of a Service Oriented Architecture, and they usually are presented as a public Api you can use to expand the capabilities of your applications. There's a web service for everything from obtaining songs lyrics to detect faces in an image, to the point that they can be considered the modern version of libraries.
Every application can count on a (moderately fast) internet connection, so the network bottleneck is not a problem like it was 10 years ago, especially when the interchanged data consist of text. But there are a few issues you should be aware of.
First, web services commonly do not present a standard Api: vendor lock-ins are the norm. What if a service is discontinued, or it changes its API? A Facade-like pattern can help here. Another issues is how to test an application which involves web services? Every test that involves a web service uses the network and when you have plenty of tests the suite becomes slower and slower.

Define what you want

When choosing to use a web service in your application, the first task to accomplish is writing an abstraction over it, in a way similar to wrapping an external library. Like libraries, web services APIs are catch-all so wrapping them is useful for hiding everything you won't need: often an interface composed of one or two methods captures any communication towards the service.
For example, if you want to use Google Translate, an interface with the single method:
String translate(String from, String to, String text)
will often suffice. You want to use it for detection instead?
String detect(String text)
You want to find out the lyrics of a song? I did it in my thesis project:
String getLyrics(String artist, String title)
To see if you're segregating interfaces right, try writing a stub which uses an internal prepopulated Map to satisfy requests, and see if it's too difficult because there are tons of methods.
When the abstraction over the web service is defined, you should build a Facade or a Bridge that implements this interface, so that you can swap in an implementation of a different service that does the same thing at will. Note that swapping in an implementation does not happen only if the web service dies: it happens every day in the testing environment (and ease of testing is the sign of good old loose coupling.)
You will usually write integration tests for the Facade, and isolate internal classes that uses it with unit tests that employ mocks and stubs. JUnit satisfies the requirements for both these types of tests, but you may want to define your base test case or helpers.

Throw away SOAP for REST-like (not RESTful)

SOAP and the plethora of WS-* specification are heavy, semantically poor and difficult to use without supporting libraries. Nearly every public web service offers a REST-like API, which is by far simpler to integrate. You can use the REST-like interface to do exploratory manual testing with Curl or even in your browser. Or you can access it from JavaScript other than from Java if you have a web-based interface.
Why the term REST-like? Because many services proclaim to be RESTful but they do not adhere to all six REST principles. But the simplicity is there at least, so we may call them REST-like like Solr does with itself.
REST-like interfaces return native representations instead of XML envelopes which replicate the HTTP semantics with their own headers (we have alreayd 4 TCP/IP levels; why do you think we need another one on top?)
Web services APIs are also resource-oriented instead of being based on Remote Procedure Call, and this paradigm is something the web has employed for twenty years (a proof that it can work.) You're retrieving information in the form of resources, like a list of tweets, a text, facebook status updates, links... Not calling a method.
Web services talk in XML or JSON; you usually can choose between them.

XML

XML as a format is natively supported in Java, by the SAX and DOM APIs (or even XSLT). If you have a JDK, you already have SAX and DOM available.
But please, do not try to define wrapper classes from the XML Schema (JAXB). The idea is generating a bunch of classes from the schema definition (.xsd files) that let you unmarshal XML documents in objects. Why shouldn't we do it?
  • most web services do not define a schema. Pretty good point.
  • Moreover, even if a schema is available you add 10, 20 or 30 classes to your codebase for nothing. Remember, if we have an abstraction the webservice-specific information cannot escape from the particular driver (Bridge implementation) or implementation (Facade). So either you use all the classes defined by JAXB in your implementation for this particular web service, or the majority of them will sit there rolling their thumbs in a nice gen/ folder.
To parse XML returned from a web service you'll probably just need DOM to extract what you want from the response document and throw away the rest:
public class XMLLyricWikiParser implements LyricWikiParser {

 /* (non-Javadoc)
  * @see it.polimi.chansonnier.driver.lyricwiki.LyricWikiParser#getLyrics(java.lang.String)
  */
 public String getLyrics(String xmlContent) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xmlContent.trim()));
            Document doc = db.parse(is);
            doc.getDocumentElement().normalize();
            NodeList lyricsNodes = doc.getElementsByTagName("lyrics");
            Node lyricsNode = lyricsNodes.item(0);
            Element lyricsElement = (Element) lyricsNode;
            return _getTextValue(lyricsElement);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Malformed document.");
        }
    }

    private static String _getTextValue(Element element)
    {
        return ((Node) element.getChildNodes().item(0)).getNodeValue();
    }

}
For the response string, you can use URL and URLConnection to send HTTP requests without further intermiediate layers:
public class HttpLyricWikiBackend implements LyricWikiBackend {
 private static final String LYRICWIKI_REST_API = "http://lyrics.wikia.com/api.php";

 @Override
 public String getSong(String title, String artist) {
  try {
   URL apiEndPoint = new URL(LYRICWIKI_REST_API 
                                  + "?func=getSong&artist="
                                  + _escape(artist)
                                  + "&song=" 
                                  + _escape(title)
                                  + "&fmt=xml");
         URLConnection connection = apiEndPoint.openConnection();
         BufferedReader in = new BufferedReader(
                                 new InputStreamReader(
                                 connection.getInputStream()));
 
         StringBuilder builder = new StringBuilder();
         String inputLine;
         while ((inputLine = in.readLine()) != null) {
          builder.append(inputLine);
          builder.append("\n");
         }
         in.close();
 
   return builder.toString();
  } catch (MalformedURLException e) {
   throw new RuntimeException("Url of the API is not correct.");
  } catch (IOException e) {
   throw new RuntimeException("Cannot communicate with the server.");
  }
 }

 private String _escape(String phrase) {
  return phrase.replaceAll(" ", "%20");
 }
}
Unfortunately, this is very verbose with regard to dynamic languages. Try XPath if you need more concise code.

JSON

json.org has all you need for JSON parsing in Java. Six classes (six!) which do everything. You download them, put the code in a org/json folder in your class path and you can start parsing responses. Native types are welcome in this small library (like String or Boolean), but JSONObject or JSONArray are also included.

Conclusion

So accessing web services from a Java app, being it web-based or not, it's very simple if you isolate the service, hide everything you don't need and avoid slowing down your test suite by testing in isolation (separating integration tests from unit ones).
Formats are standard and well-supported, with quite long code snippets attached (DOM examples are twenty-lines to extract a field value) but all the wiring code is in the abstraction you create. Web services are just adapters for the ports of your application, but there are so many of them that they are worth considering for inclusion. In this article I presented the simplest approach which you can start with, but that can already take you to great results.

Wednesday, 21 June 2017

RecyclerView with different layouts


One of the new concepts introduced in RecyclerView is the Layout managers. This class basically defines the type of layout which RecyclerView should use. In RecyclerView you can define three types of LayoutManager (s).
  1. LinearLayoutManager – This LayoutManager can be used to display linear lists, they could be vertical or horizontal.
  2. GridLayoutManager – Earlier in android GridView was the only widget to display grids, but now with RecyclerView, GridLayoutManager can be used to display grids.
  3. StaggeredGridLayoutManager – Another great customization is StaggeredGridLayoutManager, this is used to display a staggered grid.
In this Android RecyclerView Tutorial for simplicity I will be using a LinearLayoutManager for displaying a vertical list of items.
Android RecyclerView ViewHolder
The concept of RecyclerView.ViewHolder is same as it was in the ListView. Simply said: when a view goes out of visible area it is kept for recycling. Earlier this was done through the custom view holder pattern. But now with RecyclerView a ViewHolder class is included in the adapter by default. Therefore now its a compulsion for everyone to implement this class. There are many advantages to this approach, like it keeps references to the views in your items, which in turn decreases the overhead of creating new references every time an item is displayed.
Have a look at the object, that I will be using to supply data to ViewHolder:
Also have please have look at the layout where RecyclerView needs to be added:
Android RecyclerView Adapter
In general ListView implementations, the adapters were used to bind views with positions, usually in the getView() method. As developers we used to bind data into it. Here in RecyclerView the concept is same. But now the difference is, that new view holders are placed inside the adapter and the adapter now binds with ViewHolder, instead of views, as in previous adapters. In a way a direct binding between ViewHolder and position is made. To understand the concept mode deeply have a look at my custom implementation of RecyclerView.Adapter :
Android RecyclerView onItemClick Event
Sadly the standard implementation of RecyclerView does not have an onItemClick implementation. Instead they support touch events by adding an OnItemTouchListener through the addOnItemTouchListener method of RecyclerView class.
But I believe the suggested implementation is a little lengthy to implement. Also you may need to detect click events on the views in a RecyclerView item. Which may be a little difficult to implement through the standard OnItemTouchListener. Therefore I have implemented a custom recyclerview onitemclick event.
Here in the above code sample, I defined a custom interface MyClickListener with a method onItemClick, which is used for detecting clicks on the activity. The only drawback of this approach is, that I had to make a static reference to MyClickListener, inside the adapter. Although it may not create any problems, but still to avoid them I suggest you to initialize this interface in onResume() method of your activity.
The above code implementation will detect clicks on the item. If you need to detect clicks on particular views. It can be done simply by modifying the code in DataObjectHolder constructor. The layout for RecyclerView item:
To display visual responses like ripples on screen when a click event is detected add selectableItemBackground resource in the layout (highlighted above). Next have a look at the main activity where all of this code would come into play:
In the above code sample I have defined a basic Android RecyclerView. Where I have also shown, how to add and remove items at run time from the adapter. The good part here is, you need not to worry about animation. They are added and removed with default animation. But the most annoying thing is how to add dividers and spaces between items in RecyclerView?