Friday, October 30, 2020

Create a custom event listener in Java, Android Studio

We often face a problem that we need local/global variables accessible inside a listener class, let say OnClickListener, OnTouchListener. But, since the listener is an object of another class, even our global variables are not accessible inside its overriden methods such as onClick,onTouch etc. So, how to pass values into the listener methods?

We can implement our custom listener class that implements the default listener classes. The class should consists of all the variables/attributes and their variables can be passed using its constructor. Now, the variable values are accessible inside the listener methods since we set them local on creation. The variables may either be primitive or composite.

First, we need to add the class definition on the file itself where we need it or in a separate file. A sample custom event listener class will be like,
class CustomOnClickListener implements View.OnClickListener {
    int id;
    String name;
    
    public abstract boolean onTouch(View v, MotionEvent event);
    
    CustomOnClickListener(int id, String name){
        this.id = id;
        this.name = name;
    }
}

Since the class implement the default event listener, you can use the listener class within the appropriate set listener method, setOnClickListner, setOnTouchListner etc. You need to pass the arguments into the constructor when you instantiate objects of the custom listener.
myButton.setOnClickListener(new CustomOnClickListener(globalKey, globalName) {
                @Override
                public boolean onClick(View v, MotionEvent event) {
                    // your lister action code here
                    myButtonPressed(id, name);    //any  method in the main class
                }
            });

Thanks for reading. Please share if you find it useful !
Subscribe with your email to receive News updates
 

 

Sunday, July 26, 2020

How to setup Conda in Google Colabs to do GPU programming in Python?

  Conda is an open source package management and environment management system from Anaconda that would allow us to work across the platforms and languages. The conda also facilitates to programming GPUs in python using other modules from Anaconda such as numpy, scipy, numba etc. It uses the Cuda framework behind. Though the colabs notebooks are pre-built some of the above packages and python, it has not been pre-built with conda.
  Let us see how to install the conda in Colabs. I've made it simple for you. You only need to import an execute the following Jupyter Notebook available at Github.
  1. Download Jupyter Notebook ipynb file from the following Github link.
  2. Create an empty notebook in Colabs.
  3. Import the file into the notebook.
  4. Execute every code section in the notebook. Make sure the previous one has got success before move onto the next one. You may skip the sections that are used to check the versions after installations.
  5. Instructions are given there also.

Important: These installations are specific to notebooks. So, the Conda will only work within the notebook from where you install it. Don't forget to change the notebook to the GPU mode before executing any Cuda codes. It will not work otherwise.
  1. Runtime from the top menu
  2. Change runtime type
  3. Choose Hardware accelerator as GPU and save it.

Whola! you can now be experiencing the GPU python programming in Colabs.

Thanks for reading!
Please share if you find it useful!
Subscribe with your email to receive New updates

Tuesday, July 21, 2020

Validate dynamic form fields in Thymeleaf templates

How to validate the unknown  number of input fields dynamically generated and  attached to Thymeleaf scripts
   We have to write JavaScript validations for each field in the input form if we don't use a framework such as AngularJS. The jQuery validator script makes it easy that we can add it into the script and write small snippets for the validations. It is also flexible to use with the Thymeleaf scripts since the fields are validated by the HTML identifiers. The issue is, how to validate an unknown number of fields that are dynamically generated by a thyme script array. Thymeleaf allows us to give identifiers to the fields with the indexes of the array. Therefore, we can validate them if we can loop through the fields inside the validation script. Also, We can validate the fields individually or verify the sum of the fields equal to another field, not in the array.

  As usual, we must include the jQuery validator script in the Thymeleaf template. It can be included from a local server or a CDN.
<!--Validation framework on jQuery-->
<script th:src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js">
</script>
  There are so many tailored validation methods included in the jQuery validation script. We add our custom methods to the validation script using addMethod to the jQuery validator object.

  Let's say, we have some chickens in a basket and their weights are attached to a form of fields. There is another field, 'totalWeight' to take the sum of the chicken weights, in the basket. A sample custom validation method added is shown below.
chickens - chicken array, Thymeleaf object.
<script>
       jQuery.validator.addMethod(
        "chickensWeightValidator",        // name of the validator to call within HTML input fields
        function(given_weight, element) {
            var cal_total = 0;
           
            /*<![CDATA[*/
            /*[# th:each="chicken, index : ${response?.data?.chickens}"]*/
                var weightX = parseInt($(/*[[|#chicken_${index.index}|]]*/).val());
                if(!isNaN(weightX)) cal_total = cal_total + weightX;
            /*[/]*/
            /*]]>*/
           
            var is_valid_total = (cal_total==0 || cal_total==given_weight);    // initilally cal_total=0
            return this.optional(element) || is_valid_total;
        },
        "Total weight must be equal to the sum of the chicken weights"        // a warning message if invalid
    );
</script>
  ThymeLeaf loop code is commented inside the JS but Java template engine is intelligent enough to process it and respond with pure JS code to the client requested the page.

  We can attach the validator method to the total_weight field either directly in the HTML as a class or using jQuery validate method in script separately. The latter method let us define custom highlighting methods if input value is invalid.
<form id="chickenForm" >
    <div class="invalid-feedback"></div>
    <input type="text" id="totalWeight" name="Total Weight" class="chickensWeightValidator" />
</form>
or
<script>
    $(function() {
        $("#chickenForm").validate({
            rules: {
                totalWeight:{
                    required:true,
                    chickensWeightValidator: true
                },
            },
            submitHandler: function(form) {
                form.submit(function() {
                    return true;
                });
            },
            highlight: function (element) {
                $(element).removeClass("is-valid");
                $(element).addClass("is-invalid");
            },
            unhighlight: function (element) {
                if (invalidFixed == true){
                    $(element).removeClass("is-invalid");
                    $(element).addClass("is-valid");
                }
            },
            errorElement: 'div',
            errorClass: 'invalid-feedback'
        });
    });
</script>
  That is not end there. We must validate each chicken's weight is valid. It can be done easily with min="0" tag in the HTML weight input field that is looped through the array by Thymeleaf.
<div th:each="chicken , index: ${response?.data?.chickens}">
    <input    th:id="|chicken_[__${index.index}__]|"
            th:name="|chicken_[__${index.index}__]|"
            th:value="${chicken.weight}"
            type="number"
            min = "0"
    />
</div>
or
by adding following custom validator method,
jQuery.validator.addMethod(
    "nonZeroWeight",
    function(weight, element) {
        var isValidWeight = /^[0-9]*(\.\d{0,2})?$/.test(weight) && parseFloat(weight)!=0;
        return this.optional(element) || isValidWeight;
    },
    "Enter a valid weight"
);
I have tried in several ways but could not find a way to attach the above method to the unknown number of, dynamically generated fields using the validate method in the jQuery validator. Finally, I added the method to the HTML field directly as a CSS class.

Thanks for reading!
Please share if you find it useful!
Subscribe with your email to receive New updates

Sunday, July 19, 2020

Things to know before buying a laptop or computer

Contents
When it is required to buy a computer, people are often confusing about specifications and the cues offered from sellers or in showrooms.
* dual-core, quad-core, octa-core, i3, i5, i7, i9
* 2GB, 4GB, 8GB, 16GB, 32GB
* 160GB, 320GB, 500GB, 1TB, 2TB
* VGA card or graphics card 1GB, 2GB, 4GB

What info should I know before buying a computer or laptop?
What are these numbers?
How it is related to the performance of a computer?
which one should I select for my need or afford my budget?

  It is confusing even after you have reached a selling center. Following are some important facts that relate the specs with their performance. The facts will get rid of your confusions and help to buy the most suitable computer for your purpose within your budget. I don't talk about brands here and you can buy any of your favorite brands.

Select a suitable computer (quick)

  Buying a high-performance computer since you can afford it means you are wasting your money. You are not going to utilize all of its resources and they will be wasted for life. So, you should buy what fits your needs. Following criteria will help you to choose the right machine. I've used 3 types of usages to select a computer that has appropriate values for some major specifications
  • Classical usages: browsing the internet, watching videos, light games, other ms office works such as word, excel, PowerPoint
  • Intermediate usages: programming in IDEs (Android Studio, IntelliJ Idea, Visual Studio), basic video editing, video games, academic engineering purposes such as MatLab, AutoCAD, machine learning etc. and all classical usages.
  • Extreme usages: video editing, 3D video and graphics processing, industrial engineering purposes, high-quality 3D games, to host servers and all Intermediate usages.

1. Processor or CPU
  1. Classical usages - an i3 computer or barely even a p4 dual-core/quad-core can do all those very well.
  2. Intermediate usages - i5 or i7 if you can afford
  3. Extreme usages - i7 or i9 if you can afford
  • The number of cores - the price afford your budget. No guarantee that all cores are utilized if your programs don't support.
  • Clock speed - You shouldn't worry too much about the clock rate since all modern CPUs has a significant clock rate. Even so, you should consider the basic clock rate but not the Turbo Boost. Maximize the GHz value and find one with turbo boost if you suppose, you will do data science or heavyweight computations.
  • Size of the cache - It improves performance and speed for high computational applications. Maximize the sum of L1 and L2/L3 caches if budget supports.

2. RAM or Memory
  1. Classical usages - 2GB enough
  2. Intermediate usages - 4GB required or 8GB
  3. Extreme usages - 8GB required or any your budget allows
  It is good to buy a laptop or computer that has the whole memory in a single slot. So, you can upgrade with additional memory later if it is required.

3. Hard Disk (HDD or SSD)
  1. Classical usages - 250GB enough or 500GB HDD
  2. Intermediate usages - 500GB or 1TB (1000GB) HDD and 64GB SSD if budget allows
  3. Extreme usages - more than 1TB(1000GB) HDD and at least 128GB SSD or more than 1TB SSD

4. VGA card or graphics card
  1. Classical usages - not necessary, 1GB or 2GB max
  2. Intermediate usages - 2GB at least shared (consider additional 2GB RAM size if it is shared)
  3. Extreme usages - at least 4GB at least shared (consider additional 4GB RAM size if it is shared)

5. Additional Utilities
  DVD or Bluray ROM, fingerprint, smart card, wifi will increase the price of the computer. You will select them based on your needs and budget. I suggest should not consider an inbuilt 3G or 4G modem which would increase the price but not efficient. You can use a wifi router for internet usage which is cheap and healthy.

6. Display

  Also, if it is a laptop, You will choose the right size of the display, suitable for you and afford your budget. There are many kinds of displays. LCD, LED, IPS, value increases in the same order and you should not buy LCD ever. you might consider a touch screen if only it is very useful for your career or work.

7. Software (Operating System e.g. Windows, Mac)
  It would cost less if you purchase the Operating System(OS) software installed along with a computer. If you've planned to buy a Mac computer, you don't need to worry about it since the Mac OS is coming with every Mac computer. There are computers in the market that don't carry any OS but named as DOS, Ubuntu or Linux which are freeware.

  If you prefer the Windows OS, you must be careful if it is the original windows installed. A sticker specifying the serial key should be on the computer but also sometimes the key is installed in a chip inside the computer and no sticker there. It will cost you around 100$ additionally for the OS but it is cheaper than you buy it externally. You can download the genuine validation tool and check whether your copy of windows is genuine or not.

Congratulations! to buy an amazing laptop or computer. Read further if you have time. You are welcomed to ask in comments if any questions.

Versions
  First, i7 does not mean a seven-core processor!. The "i" numbers are the versions of Intel processors to indicate their relative performance. But, their overall performance often increases with the "i" number. Performance of a processor is depending on the following,
  1. the number of cores,
  2. clock speed (in GHz),
  3. size of the cache (often increasing with the number i3, i5, i7),
  4. as well as Intel technologies like Turbo Boost and Hyper-Threading.

Generations
  Generations of the processors are different from the versions and they have their own architecture(s). With generations, CPUs have higher compatibility, high performance, reduced power consumption, durability etc. Also, the price of the computer increases with the generations. It is denoted as first few digits of its model number. The latest Intel CPU generation is 11, launched in September 2020.

Cores and Clock Rate
  Clock rate shows how many calculations a computer can do at a time and basically the speed of the computer. It is multiplied with the number of cores but limited to the ability of a program to be executed in parallel.

Turbo Boost and Hyper-Threading
  i5, i7, i9 generations have turbo boost and work at their peak frequency (clock rate) for some supported operations. Hyper-Threading provides some redundant calculations units that utilized often so programs/operating system would feel them as additional cores.

  Intel and AMD are the most popular processor brands in the market. To know more about specifications of different CPU versions and generations, summarized.

2. RAM or Memory
  The capacity of the RAM determines the amount of work you can handle simultaneously. The higher the number would allow you to run the more programs at a time parallelly. However, often more capacity RAM reduces chances a computer getting stuck and make it faster since it can load the program in advance. People who want to play high-quality games needs more memory at least 4GB to accommodate the game.

  The capacity of modern RAMs may vary between 1GB and 64GB or even more which you need not know. Since you are going to buy an assembled PC you shouldn't worry about frequencies(1600MHz, 2333MHz,..) and slot type (DDR3, DDR3,..).

3. Hard Disk
  Hard is the secondary storage where you will store your files and programs, also where the operating system is installed. It will take too long to boot up your computer if the hard disk is slow. That's why technical people often prefer the SSD (Solid State) which is faster than the traditional hard disk(HDD). But it costs more. You can have a small SSD and an HDD which makes its price affordable.

4. VGA card or graphics card
  It computes and renders graphical images into the display. Some computers don't have additional VGA card but sharing the memory of the RAM. High-quality video utilizations such as video games, video editing, architectural development i.e. AutoCAD, HD or 4K video etc require more graphical memory. Typically, it may range from 0 to 8GB.

5. Additional Utilities
  You may look for additional features such as DVD or Bluray ROM, fingerprint, smart card, wifi etc. Typically, all modern laptops come with wifi and webcam.

Thanks for reading!
Please share if you find it useful!
Subscribe with your email to receive New updates

Saturday, July 18, 2020

Intel and AMD processor versions and generations, summary

What is the difference between Intel Core i3, i5 and i7?
  You will get answers for these questions after you've read this article. First, i7 does not mean a seven-core processor!. The "i" numbers are the versions of Intel processors to indicate their relative performance. But, their overall performance often increases with the "i" number. Performance of a processor is depending on the following,
  1. Number of cores,
  2. Clock speed (in GHz),
  3. Size of the cache (often increasing with the number i3, i5, i7),
  4. Intel technologies like Turbo Boost and Hyper-Threading.

  There are two processor brands popular in the market, Intel and AMD.

Intel Processors

Versions
The popular versions are,
* Intel Core i3, dual-core, 3-4MB cache, 2.93-3.9GHz Clock Rate, no Turbo Boost, Hyper-Threading, DDR3 or DDR4 RAM (2008).

* Intel Core i5, dual-core or four-core, 2.4-3.5GHz Clock Rate, 3-6MB cache, Turbo Boost(up to 3.9GHz), no Hyper-Threading, DDR3 or DDR4 RAM (2008).

* Intel Core i7, dual-core or four-core, 1.6-4GHz Clock Rate, 4-25MB Cache, Turbo Boost(up to 4.2GHz), Hyper-Threading, DDR3 or DDR4 RAM (2008).

* Intel Core i9, 8-18 cores, 1.8-4GHz Clock Rate, 20-33MB cache, Turbo Boost(up to 5.3GHz), Hyper-Threading 6 per core, DDR4 RAM (2017).

The following are outdated versions and you shouldn't worry about them.
  • (1993) Intel Pentium, Pentium Pro
  • (1997) Intel Pentium 2, Pentium 2 Celeron, Pentium 2 Xeon
  • (1999) The Intel Pentium 3, Pentium 3 Xeon, Pentium 3 Celeron
  • (2000) The Intel Pentium 4, Pentium 4 Celeron, Pentium 4 Xeon, Pentium 4 Core, Pentium 4 Dual Core, Pentium M, Pentium M Celeron, Pentium M Core, Pentium M Core 2 Dual, Pentium M Xeon, Pentium D, Pentium D Xeon, Pentium 4 Quad Core, Pentium 4 Core 2 Dual, Pentium 4 Core 2 Quad
  All these are outdated now. You may refer through following Wikipedia article if you need more information.

  Generation of a processor is different from the version and different generations have their own architecture(s). With generations, CPUs have higher compatibility, high performance, reduced power consumption, durability etc. It is denoted as first few digits of a CPU's model number. The latest generation of Intel CPU is 10 and 11th generation is going to be launched September 2020.
  • 1st generation - Nehalem
  • 2nd generation - Sandy Bridge
  • 3rd generation - Ivy Bridge
  • 4th generation - Haswell
  • 5th generation - Broadwell
  • 6th generation - Sky lake
  • 7th generation - kaby lake
  • 8th generation - kaby lake, Coffee lake, Amber lake, Whiskey lake, Cannon lake,
  • 9th generation - Sky lake, Coffee lake
  • 10th generation - Cascade lake, Ice lake, Comet lake, Amber lake
To read more about generations of Intel processors, Intel Processor Generations

AMD Processors

Versions, generations and the architectures are treated analogously in AMD brand.

The popular architectures are,
* (2007) AMD K10, dual/tri/quad/octa-cores, 1.7-3.7 GHz Clock Rate, 2-8MB cache.

* (2011) AMD K10 APUs, dual/tri/quad/octa-cores, 3-3 GHz Clock Rate, 2-8MB cache.

* (2017) AMD Zen core, Ryzen/Athlon Brand, up to 64 cores, 1.7-3.7 GHz Clock Rate, 4-64MB cache, Precision boost(up to 4.7 GHz).
* (2018) AMD K10 Zen+.
* (2019) AMD K10 Zen 2.

The following are outdated and you shouldn't worry about them.
  • (1996) AMD K5, 133 MHz max Clock Rate
  • (1997) AMD K6, 300 MHz max Clock Rate
  • (1999) AMD K7, 2.33 GHz max Clock Rate, 256-512KB cache
  • (2003) AMD K8, 1.6-3.2 GHz Clock Rate, 512-1024KB cache
Information collected By J Jeyakeethan
Please share if you find it useful!

Thursday, July 16, 2020

Are blogs still making money?


  With growing technologies and cheap data rates, people want to learn with some fast mediums such as YouTube and other video channels, web tutorial etc. Is it possible to earning income with blogs containing text which are boring visitors to read? Of course, it has been possible yet. But you should thrive to bring a regular crowd visiting your blog first rather looking for a paycheck in the beginning. That does only matter and nothing else. If you could achieve a certain number of visitors to your blog or set of blogs regularly, you are succeeded. But, I suggest working on a single blog if you are a beginner.

How much visitors should my blog get per day?
  You should not target for 10k per day. Because new blogs will not often have that number of visits initially since it would take some time for your blog to be indexed by Google and your blog would have no subscribers at the beginning. You can also index your blogs and their posts manually to Google. Every blogger should set up a subscription box in his or her blog, e.g. RSS. Because subscribers are the ones who will generate you a passive income even if you make posts less frequently or with less quality. 1000 visitors/day is an affordable count and it can be achieved within 3 months if you add content to your blog at least twice a day.

How much do bloggers earn a month with Adsense?
  There is no guaranteed amount that you could earn with a blog. If your blog has 1000 visitors/day, it might be somewhere between 150$ to 500$. However, some bloggers are earning more than 1000$ a day (30k per month). Also, the highest Adsense revenue is earned by www.mashable.com 1,000,000$ per month. It depends on some other factors such as the number of visitors, the number of clicks received within the month, from which part of the world the visitors were from, what you are writing about (decides what type of ads to show which determines the value of the ads). Sometimes placements of ads also influence the revenue you earned since some places are more likely to be clicked.

  Advertisements are shown by fetching some keywords from your blog content so that they would reach the right people. The keywords decide what ads to show and then determine the revenue from the ads. So you may want to take little care about it. Though some niche words pay the most, you should write what you know and should not worry about the earning rate. If you start a blog with such a niche which you rarely knows, it will end up with a failure that you don't have content to write. Anyway, you should not aim for the money in starting days. Your earning would be even low if your blog is not an English blog since Google rarely has related ads for such sites.

How can I get AdSense approval?
  Eligibility: Your content must comply with Google Adsense policies and you must be older than 18 years. Also, you must not forget to add a Privacy Policy page to your site which is a must for approval. Those are the difficult criteria. It was required previously that a blog must be 3 months old. Fortunately, the rule has been removed now. However, I would suggest you to applying only after you had the descent traffic of 1000 visits/day. For more about terms and conditions and eligibility criteria, look here.

  If your blog is hosted in blogger, you must apply through the blogger and you will have higher chances to get approval if the blog has high quality and indexed content. It is less likely to be approved if your blog is not in English or just contains a few posts. If your blog has its original content and generating enough traffic, you need not worry about the approval very much. You can re-apply if the application is rejected due to less traffic or poor quality content after you have fixed them.

Can I use blogger or does other domain sites have anything special?
  You can blog on any platform which best fits you. Google doesn't treat the blogger blog and other blogs differently. It only expects quality and original content, and decent visitors who will actually benefit the advertisers and themselves. You can also use a custom domain for your blogger blog if you wish it to be short. You need to fill the application externally in Adsense site with the blog details if it is not a blogger blog.

If I copy content from internet and synthetically modify sentences into my style, would it work?
  Sometimes yes. However, search engines rank redundant contents based on their posted date priority and then your blog will be listed last. But, you may do research in a specific topic or compose information from other sites if it would be useful collectively for some purposes. You must be passionate and make your content interesting rather blindly targeting for the traffic generated through search engines. It would work at the beginning but will receive negative feedback and ranked below by search engines. A passionate blogger would like to have regular readers and fans for his or her blog.

What topic to write today? I have no idea to blog
  This is the typical issue that every new blogger who has not really been passionate but wants to earn money is complaining. I have said already that you should not write for money or high paying keywords at the beginning. If you do so, you would not like to continue blogging and hate it eventually. You must write what is related to you. Your blog is to help and teach others on which you are expert. You might have motivated to write or tell something to others when you were doing your other duties. You have to jot them down, do research on them if it is needed to elaborate and make it as a post. Sometimes, it is better to start with one post a day if you are a beginner.

  You might not have such other duties and wanted to do blogging as a full-time job. If so, you have to read a lot, keep a notebook and write down important points and topic ideas raised when you are reading, analyze to add your opinion and finally make them into attracting posts. You may do brainstorming in your field or blog title will give you better topics and titles to make content. A few months later, you can check the stats of your posts and write on related to the topics that had been reached more people.

  It is better to write posts blog-specific and related which would make the blog richer. It will not be an issue, if it doesn't but may take some time to generate expected traffic. Also, you have to post regularly to have a good rank in search engines. Beginners often want to decorate their blog but not interested in adding content. The fact is, theme and decoration are never related to traffic and earning. A simple and clean template is okay and Don't waste your too much of time on it.

Congratulations!, to start a content-rich blog that is useful to everyone I might also visit your blog in future.
Thanks for reading!
Please share if you find it useful

Whats New

How redundant uploads can be avoided in social media apps?

People spend more time on social media, and it influences the most and changes to societies. They want to share photos and videos often when...

You may also like to read

x

emailSubscribe to our mailing list to get the updates to your email inbox...

Delivered by FeedBurner