Friday, November 30, 2018

Git : How to add an existing local folder into a git repository?

This is quite simple, in fact, this is one of the suggestions that bitbucket gives when new repo is created
 

if we have an existing repository, then that can be initialized to git by the below command

cd /
git init

git remote add origin https://myusername@bitbucket.org/myusername/mytestapp-ios.git
git push -u origin master

now when committing if getting the below error,

git push
No refs in common and none specified; doing nothing.
Perhaps you should specify a branch such as 'master'.

Everything up-to-date

Below to be done to set the upstream folder. 

git push --set-upstream origin master

Thursday, November 29, 2018

Flutter : Adding NetworkImage


To display the network image in a list leading row space, we need to actually specify a circle avatar

Widget _buildRow(int i) {
  return new Padding(
    padding: const EdgeInsets.all(16.0),
    child: new ListTile(
      title: new Text("${_members[i].login}", style: _biggerFont),
      leading: new CircleAvatar(
        backgroundColor: Colors.green,
        backgroundImage: new NetworkImage(_members[i].avatarUrl)
      ),
    )
  );
}



References:
https://www.raywenderlich.com/116-getting-started-with-flutter

ListViews in Flutter:

Dart provides a ListView widget that will let you show the data in a list. ListView acts like a RecyclerView on Android and a UITableView on iOS, recycling views as the user scrolls through the list to achieve smooth scrolling performance.

To build a list view, we need to provide raw builder like the below

  body: new ListView.builder(
  padding: const EdgeInsets.all(16.0),
  itemCount: _members.length,
  itemBuilder: (BuildContext context, int position) {
    return _buildRow(position);
  }),

_buildRow method returns an item builder which is like this below

Widget _buildRow(int i) {
  return new ListTile(
    title: new Text("${_members[i]["login"]}", style: _biggerFont)
  );
}

Adding divider is funny, which is like the below

body: new ListView.builder(
  itemCount: _members.length * 2,
  itemBuilder: (BuildContext context, int position) {
    if (position.isOdd) return new Divider();

    final index = position ~/ 2;

    return _buildRow(index);
  }),


The above is passing string list type. Now it is easy to pass int he customer types as well. Which is like below

Suppose _members array is now array of Member,

Widget _buildRow(int i) {
  return new ListTile(
    title: new Text("${_members[I].key}", style: _biggerFont)
  );
}

The member object can be something like below

class Member {

Final String login;
Member(this.login){

}

}

At the time of processing the response, below can be done to create the Member array.

setState((){
Var members  = JSON.decode(response.body);
for(var memberObj in members)}{
Final newMember = new Member(memberObj["login"])
_members.add(newMember);
}

});



References:
https://www.raywenderlich.com/116-getting-started-with-flutter

Flutter making network calls

For making network calls, the below package can be imported

import 'package:http/http.dart' as http;

Dart apps are single-threaded, but Dart provides support for running code on other threads as well as running asynchronous code that does not block the UI thread using an async/await pattern.

To keep the list of list of members at the class level, below to be done

var members = [];

The underscores at the beginning of the names make the members of the class private.
Below is how to make an asynchronous HTTP call

_loadData() async {

String dataURL = "https://urltoetchthedata.com";
http.response = await.http.get(dataURL);
setState((){
_members = JSON.decode(response.body);
});

}

The async keyword onto _loadData() to tell Dart that it’s asynchronous, and also the await keyword on the http.get() call that is blocking.
When the HTTP call completes, you pass a callback to setState() that runs synchronously on the UI thread. In this case, you are decoding the JSON response and assigning it to the _members list.


References:
https://www.raywenderlich.com/116-getting-started-with-flutter

Wednesday, November 28, 2018

Flutter: Widgets , Stateless and Stateful



Almost every element of your Flutter app is a widget. Widgets are designed to be immutable, since using immutable widgets helps keep the app UI lightweight.

There are two fundamental types of widgets you will use:

    Stateless: widgets that depend only upon their own configuration info, such as a static image in an image view.
    Stateful: widgets that need to maintain dynamic information and do so by interacting with a State object.

Both stateless and stateful widgets redraw in Flutter apps on every frame, the difference being that the stateful widgets delegate their configuration to a State object.

To get started with making your own widgets, create a new class at the bottom of main.dart:

class GHFlutter extends StatefulWidget {
  @override
  createState() => new GHFlutterState();
}

We need to make a StatefulWidget subclass and then overre the createState() method to create its state object. Now add a GHFlutterState class above GHFlutter:

class GHFlutterState extends State {
}

Now we need to fill in the build method

@override
Widget build(BuildContext context) {
  return new Scaffold (
    appBar: new AppBar(
      title: new Text(Strings.appTitle),
    ),
    body: new Text(Strings.appTitle),
  );
}

A Scaffold is a container for material design widgets. It acts as the root of a widget hierarchy. You’ve added an AppBar and a body to the scaffold, and each contains a Text widget.


To use the stateless widget, it should be given the state for the home.

class GHFlutterApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: Strings.appTitle,
      home: new GHFlutter(),
    );
  }
}


iOS Objective C Bridging header

There are two ways to create an Objective-C Bridging Header. The first one is to create a new Objective-C File and specify that it is used a header file. This will then create two files: .h and .m or Just create the Header File on its own.

Click the Next button. You will be then asked to name this new file. You can name it whatever you like. I have named mine: Objective-CBridgingHeader. You will then be asked to chose a location for the filed to be saved. Usually Xcode will detect the correct folder but double check and then click save. You will then be presented with another Dialogue that says: Would you like to configure an Objective-C bridging header?:

Second option is to create objective C header separately

Go to File > New > File and Select Header File:
Just like the above example, Chose a name and save it. This will then create Just one file: Objective-CBridgingHeader.h

Now, depending on what ever example you have chosen open the .h file and add the following line:

#import

References:
https://www.ios-blog.com/tutorials/objective-c/how-to-create-an-objective-c-bridging-header/

iOS Profiling with Instruments

On device profiling can be done in below steps

First need to declare the phone for development, which can be done from ORganizer
Now just hit record, which will let us see a real time graph of the activity on the device, along with bar graphs for % CPU, CPU Time,
Real Memory Usage, and then Real Memory Usage as a pie chart.

Thats all.

Practically, some of the issues one may face are

1. Error: Instruments could not acquire the necessary privileges to profile the target application.

https://www.podfeet.com/blog/tutorials-5/activity-monitor-for-ios-using-instruments-in-xcode/

Tuesday, November 27, 2018

What Can an Android Point-of-Sale System Do?

Android POS systems are tablet-based systems that run on the Android platform. Most systems have apps that you download to your Android tablet, though some companies sell the tablets or proprietary equipment with the POS software preloaded on them. The tablet connects to or is used alongside the card reader or terminal provided by your payment processor. The POS system records sales transactions and generates reports that help you analyze your business's performance. Many include additional features that help you run your business, such as inventory and customer management tools.

You can connect the tablets to POS hardware such as receipt printers, cash drawers and tablet stands to create a countertop checkout station. Many systems also allow you to add more tablets or phones as well as peripherals such as barcode scanners to the system.

Many POS systems are designed to be used by either retail businesses or restaurants; however, some companies offer solutions for multiple business types, including retail, restaurants, and service-based businesses like salons and spas. Some POS companies offer systems that cater to specific types of retail business, such as clothing stores, florists or jewelry boutiques. All of the Android POS systems we reviewed offer a retail solution; these are often also suitable for counter-serve restaurants. Half of the systems can also be used by full-service restaurants. If you want more options for restaurant POS systems, check out our review. If you're looking for a credit card processing company to use with your Android POS system, we've got a review for that as well. Our articles about POS systems and payment processing can help you learn more about these topics.

references:
https://www.business.com/categories/best-android-pos-systems/

Monday, November 26, 2018

Google Alerts API



$ npm i -S google-alerts-api
const alerts = require('google-alerts-api');

if using email and password, configure like below

alerts.configure({
    mail: 'your_mail@gmail.com',
    password: '**********'
});

if using cookies, to be configured like below

alerts.configure({
    cookies: 'W3sia2V5IjoiR0FQUyIsInZhbHVlIjoiMTpCRXRtZEpjc...saGRasC==',
});

This is how to fetch alerts

const alerts = require('google-alerts-api');
const { HOW_OFTEN, DELIVER_TO, HOW_MANY, SOURCE_TYPE } = alerts;

alerts.configure({
    mail: 'your_mail@gmail.com',
    password: '**********'
});

alerts.sync((err) => {
    if(err) return console.log(err);
    const alertList = alerts.getAlerts();
    alertList.forEach(alert => printAlertInfo);
});

function printAlertInfo(alert) {
    console.log('name:', alert.name);
    //'How Many' property information:
    if (alert.howMany === HOW_MANY.BEST) {
    console.log('How many: Only the best results');
    } else if (alert.howMany === HOW_MANY.ALL) {
    console.log('How many: All Results');
    }
}

a sample alert object is like below

{
    name: '"Donald Trump * ISIS"',
    id: '4f94515ec736ef62:ade5b03803caa237:com:en:PL:R',
    howOften: 2, //use HOW_OFTEN enum to find out proper meaning
    sources: '...', // some of SOURCE_TYPE enum property, SOURCE_TYPE.AUTOMATIC by default
    lang: 'en',
    region: 'PL',
    howMany: 3, //use HOW_MANY enum to find out proper meaning
    deliverTo: 2, //use DELIVER_TO enum to find out proper meaning
    deliverToData: '', //email address, available when deliverTo === DELIVER_TO.MAIL
    rss: 'https://google.com/alerts/feeds/00357582442749620569/11537740808718742679' //field available, when deliverTo === DELIVER_TO.RSS
}


references:
https://github.com/adasq/google-alerts-api

FIDL protocol

FIDL is a language for defining interprocess communication protocols. Although the syntax resembles a definition of an object-oriented interface, the design considerations are more akin to network protocols than to object systems. For example, to design a high-quality interface, you need to consider bandwidth, latency, and flow control. You should also consider that an interface is more than just a logical grouping of operations: an interface also imposes a FIFO ordering on requests and breaking an interface into two smaller interfaces means that requests made on the two different interfaces can be reordered with respect to each other.

Focus on the types

A good starting point for designing your FIDL protocol is to design the data structures your protocol will use. For example, a FIDL protocol about networking would likely contain data structures for various types of IP addresses and a FIDL protocol about graphics would likely contain data structures for various geometric concepts. You should be able to look at the type names and have some intuition about the concepts the protocol manipulates and how the interfaces for manipulating those concepts might be structured.

Language neutrality

There are FIDL backends for many different languages. You should avoid over-specializing your FIDL definitions for any particular target language. Over time, your FIDL protocol is likely to be used by many different languages, perhaps even some languages that are not even supported today. FIDL is the glue that holds the system together and lets Fuchsia support a wide variety of languages and runtimes. If you over-specialize for your favorite language, you undermine that core value proposition.

Names defined in FIDL are used to generate identifiers in each target language. Some languages attach semantic or conventional meaning to names of various forms. For example, in Go, whether the initial letter in an identifier is capitalized controls the visibility of the identifier. For this reason, many of the language backends transform the names in your library to make them more appropriate for their target language. The naming rules in this section are a balancing act between readability in the FIDL source, usability in each target language, and consistency across target languages.

Avoid commonly reserved words, such as goto. The language backends will transform reserved words into non-reserved identifiers, but these transforms reduce usability in those languages. Avoiding commonly reserved words reduces the frequency with which these transformations are applied.

While some FIDL keywords are also commonly reserved words in target languages, (such as struct in C and C++), and should thus be avoided, other FIDL keywords, particularly request and handle, are generally descriptive and can be used as appropriate.

Names must not contain leading or trailing underscores. Leading or trailing underscores have semantic meaning in some languages (e.g., leading underscores control visibility in Dart) and conventional meaning in other languages (e.g., trailing underscores are conventionally used for member variables in C++). Additionally, the FIDL compiler uses leading and trailing underscores to munge identifiers to avoid collisions.

References:
https://fuchsia.googlesource.com/docs/+/HEAD/development/api/fidl.md

A sweet introduction to Flutter

Flutter apps are written using the Dart programming language, also originally from Google and now an ECMA standard. Dart shares many of the same features as other modern languages such as Kotlin and Swift, and can be transcompiled into JavaScript code.

As a cross-platform framework, Flutter most closely resembles React Native, as Flutter allows for a reactive and declarative style of programming. Unlike React Native, however, Flutter does not need to use a Javascript bridge, which can improve app startup times and overall performance. Dart achieves this by using Ahead-Of-Time or AOT compilation.

Another unique aspect of Dart is that it can also use Just-In-Time or JIT compilation. JIT compilation with Flutter improves the development workflow by allowing hot reload capability to refresh the UI during development without the need for an entirely new build.

As you’ll see in this tutorial, the Flutter framework is heavily built around the idea of widgets. In Flutter, widgets are not used just for the views of your app, but also for entire screens and even for the app itself.

In addition to cross-platform iOS and Android development, learning Flutter will also give you a head start on developing for the Fuchsia platform, which is currently an experimental operating system in development at Google. Fuchsia is thought by many to be a potential future replacement for Android.


What is Fuchsia?

Fuchsia seems to be Assistant-first

From the ground up, Fuchsia seems designed to accommodate the Google Assistant. Everything on-screen, everything you’ve done and anything you can do is visible to the Google Assistant — or at least that’s how the current Fuchsia documents make it seem.

Assistant in Android can inspect your screen for information for its use if you hold the home button, but it seems Fuchsia will provide even deeper access. In Fuchsia, you can be in your browser looking at reviews for a restaurant, then you open your calendar to check a date, then say “Okay Google, invite Samantha to lunch” and it would have all that context.

Assistant will have access to all “entities” (“an identifiable person, place, thing, event, or concept which is represented within the Fuchsia platform”). And notably, the developers have specifically called out access to entities seen on-screen in the past: Entities will enable “the Assistant to inspect and manipulate entities present in the current context or seen in the past.”

Fuchsia is a cross-device OS

In today’s technological world, most people don’t have just one device, but multiple. Phone, tablet, desktop, laptop, wearables, and more. Based on the current state of the OS, Google seems to be working to make Fuchsia run on all of these seamlessly and in unison.

Traditionally, the problem with doing this is maintaining progress and context. That’s where something called Ledger comes in: once signed in with your Google Account, your applications automatically save their place across devices. Google describes Ledger as “a distributed storage system for Fuchsia.” Everything is stored in the cloud.

The idea is a futuristic but cool one: Close Chrome on your phone, then open it on your laptop and your tabs are right where you left them. The document you forgot to save before you left work? Just open Docs on your phone and save it. Your battery died right in the middle of a research project? Borrow a public computer and pick up where you left off.

Additionally, since there’s no difference between Fuchsia for laptop and desktop and Fuchsia for mobile, for some there may not be a need to carry both. Theoretically, you could just plug your phone into a dock (similar to Samsung’s DeX or Razer’s Project Linda, perhaps), and you can be up and running with a bigger screen and a desktop/laptop-like experience.


Architectural benefits over Android/Chrome OS?

Android and Chrome OS are both based on Linux, which has a solid 25-year foundation. One problem for Android is that before Treble, patching to the latest Linux kernel was reliant on device OEMs putting in the work, which few did (or at least not in a timely manner). Even now, after Treble has been available for a few months, some OEMs are reluctant to include it on their devices. This leaves Android users potentially vulnerable to new exploits that have already been patched upstream.

Fuchsia avoids these pitfalls by using its own custom kernel, Zircon, which is designed to be consistently upgradeable. To help make this possible, applications are isolated from having direct kernel access. This both gives an extra layer of security and prevents apps from being incompatible after a system upgrade, a problem that has plagued Android before.

Fuchsia for developers

Google is reaching out to developers of all backgrounds with this project. Most of the UI is written in Dart (a language that is designed to feel familiar to JavaScript and Java developers), through the Flutter framework. Support for Go, another Google-designed language is also included. Systems developers will find comfort in the availability of Rust. Google is also targeting Apple’s developer base by introducing Swift support.

The icing on the cake, though, is the native interoperability support for most of these languages. Through the FIDL protocol, your Dart UI code can directly interface with your Go backend or any other combination. This gives developers the opportunity to be more expressive and use the best language for the job at hand. We’ll dive a bit more into this later.

Sunday, November 25, 2018

GCP vs AWS : Load balancing

Load balancing

Load balancers distribute incoming traffic across multiple instances. When configured appropriately, load balancers make applications fault-tolerant and increase application availability.

AWS's Elastic Load Balancing (ELB) service allows you to direct traffic to your instances within one or several availability zones in a given region. The ELB service performs regular health checks on each target instance, and redirects traffic if an instance becomes unhealthy. In addition, the ELB service can be integrated with AWS’s Auto Scaling service, adding and removing instances automatically when Auto Scaling scales them up or down.

When you create an Elastic Load Balancer, AWS provides a CNAME to which you can direct traffic. If you are using Amazon’s Route 53 service, you can use Elastic Load Balancer as a root domain. Otherwise, you have to use a CNAME for the Elastic Load Balancer.

Like ELB, Compute Engine's load balancer directs traffic to backend instances in one or many zones. Compute Engine's load balancer also has some additional unique features:

Compute Engine lets you choose between a network (Layer 4) load balancer, which balances both UDP and TCP traffic regionally, and an HTTP(S) (Layer 7) load balancer, which can balance traffic globally as well as regionally.
When you provision a Compute Engine load balancer, you're given a single, globally accessible IP address. This IP address can be used for the lifetime of the load balancer, so it can be used for DNS A Records, whitelists, or configurations in applications.
To summarize, AWS ELB and Compute Engine's load balancer compare as follows:


GCP vs AWS : IP addresses

Cloud Platform and Amazon VPC handle IP addresses in very similar ways. At launch, all instances have an internal IP. You can optionally request an external IP. By default, an external IP is ephemeral, meaning that it is tied to the life of the instance.

You can also request a permanent IP address—called an Elastic IP in Amazon VPC and a static IP in Cloud Platform—to attach an instance. In both services, a static IP address is yours until you choose to release it, and can be attached to and detached from instances as needed.

Amazon EC2-Classic takes a slightly different approach to IP addresses. When you create an instance in Amazon EC2-Classic, your instance is given an external, ephemeral IP address that is only valid as long as that machine is running. The instance is also given an internal network IP. You can create an Elastic IP and assign it to the instance at any time. This is much the same for Amazon VPC, except it is optional to have an external IP assigned to a new instance.

AWS's terminology for IP types maps to that of Cloud Platform as follows:



references:
https://cloud.google.com/docs/compare/aws/networking

GCP vs AWS : Networking comparison

Amazon Web Services

Because most of Amazon's web services are deployed on Amazon Elastic Compute Cloud (EC2) instances, Amazon's networking services are heavily tied to Amazon EC2. Amazon Web Services (AWS) has two different networking stacks, both of which center on Amazon EC2:

Elastic Compute Cloud-Classic (EC2-Classic), their original offering.
Amazon Virtual Private Cloud (VPC), their current offering.
Amazon EC2-Classic launches all instance types into a public, shared network, where each instance has access to the Internet and is assigned a public IP address. This offering has been deprecated since late 2013, and can only be used by accounts created before that date.

Amazon VPC is a newer model, with support for a wider array of networking features. For example, Amazon VPC offers the following upgrades:

Support for creating private RFC 1918 address spaces and subnetting
Network access control lists (NACLs)
Inbound and outbound firewall rules
Routing
VPN


Google Cloud Platform

In contrast, Google Cloud Platform treats networking as a global feature that spans all services. Cloud Platform's networking is based on Google’s Andromeda architecture, which can create networking elements at any level with software. This software-defined networking allows Cloud Platform's services to implement networking features that fit their exact needs, such as secure firewalls for virtual machines in Google Compute Engine, fast connections between database nodes in Cloud Bigtable, or fast query results in BigQuery.

When you create virtual machine instances in a Cloud Platform project, Compute Engine automatically connects them to a default internal network. If needed, you can create additional networks as well. As with Amazon VPC, each network is private, and each supports firewall rules, routing, VPNs, private RFC 1918 address spaces, and subnetting.

Most of the networking entities in Cloud Platform, such as load balancers, firewall rules, and routing tables, have global scope. More importantly, networks themselves have a global scope. This means that you can create a single private IP space that is global, without having to connect multiple private networks and manage those spaces separately. Due to this single, global network, your Compute Engine instances can be addressed within your network by both IP address and name.

references:
https://cloud.google.com/docs/compare/aws/networking

Android: How to show dialog with choice items

String[] linkedNames = {"One","Two","Three"};
        AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
        //alt_bld.setIcon(R.drawable.icon);
        alt_bld.setTitle("Select one");
        alt_bld.setSingleChoiceItems(linkedNames, 0, new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int item) {
                Log.v(LOG_TAG,"Selected one")
                dialog.dismiss();// dismiss the alertbox after chose option
            }
        });
        AlertDialog alert = alt_bld.create();
        alert.show();

Saturday, November 24, 2018

GCP vs AWS : Automatic instance scaling



Both Compute Engine and Amazon EC2 support autoscaling, in which instances are created and removed according to user-defined policies. Autoscaling can be used to maintain a specific number of instances at any given point, or to adjust capacity in response to certain conditions. Autoscaled instances are created from a user-defined template.

Compute Engine and Amazon EC2 implement autoscaling in similar ways:

Amazon's Auto Scaling scales instances within a group. The Auto Scaler creates and removes instances according to your chosen scaling plan. Each new instance within the group is created from a launch configuration.
Compute Engine's autoscaler scales instances within a managed instance group. The autoscaler creates and removes instances according to an autoscaling policy. Each new instance within the instance group is created from an instance template.
Amazon's Auto Scaling allows for three scaling plans:

Manual, in which you manually instruct Auto Scaling to scale up or down.
Scheduled, in which you configure Auto Scaling to scale up or down at scheduled times.
Dynamic, in which Auto Scaling scales based on a policy. You can create policies based on either Amazon CloudWatch metrics or Amazon Simple Queue Service (SQS) queues.
In contrast, Compute Engine's autoscaler supports only dynamic scaling. You can create policies based on average CPU utilization, HTTP load balancing serving capacity, or Stackdriver Monitoring metrics.

GCP vs AWS : Custom image import

Amazon EC2 and Compute Engine both provide ways to import existing machine images to their respective environments.

Amazon EC2 provides a service called VM Import/Export. This service supports a number of virtual machine image types—such as RAW, OVA, VMDK and VHD—as well as a number of operating systems, including varieties of Windows, Red Hat Enterprise Linux (RHEL), CentOS, Ubuntu, and Debian. To import a virtual machine, you use a command-line tool that bundles the virtual machine image and uploads it to Amazon Simple Storage Service (S3) as an AMI.

Similarly, Compute Engine provides the ability to import virtual machine images. This process allows you to import RAW image files from almost any platform. For example, you can convert AMI or VirtualBox VDI files to RAW format and then import them to Compute Engine. The import process is similar to Amazon's process, though less automated. While this process requires more manual effort than VM Import/Export, it does have the benefit of increased flexibility. After you convert your image, you upload the image to Cloud Storage, and then Compute Engine makes a private copy of the image to use. For more details about importing an existing image into Compute Engine, see Importing an Existing Image.

If you build your own custom operating systems and plan to run them on Compute Engine, ensure that they meet the hardware support and kernel requirements for custom images.

Apart from the cost of storing an image in Amazon S3 or Cloud Storage, neither AWS nor GCP charge for their respective import services.

references
https://cloud.google.com/docs/compare/aws/compute

GCP vs AWS : Machine Images

Compute Engine and Amazon EC2 both use machine images to create new instances. Amazon calls these images Amazon Machine Images (AMIs), and Compute Engine simply calls them images.

Amazon EC2 and Compute Engine are similar enough that you can use the same workflow for image creation on both platforms. For example, both Amazon EC2 AMIs and Compute Engine images contain an operating system. They also can contain other software, such as web servers or databases. In addition, both services allow you to use images published by third-party vendors or custom images created for private use.

Amazon EC2 and Compute Engine store images in different ways. On AWS, you store images in either Amazon Simple Storage Service (S3) or Amazon Elastic Block Store (EBS). If you create an instance based on an image that is stored in Amazon S3, you will experience higher latency during the creation process than you would with Amazon EBS.

On GCP, images are stored within Compute Engine. To view available images or to create or import images, you can visit the Cloud Console Images page or use the gcloud command-line tool in the Cloud SDK.

Unlike Amazon EC2, Compute Engine does not have a mechanism for making an image publicly available, nor does it have a community repository of available images to draw from. However, you can share images informally by exporting your images to Cloud Storage and making them publicly available.

Amazon's machine images are available only within a specific region. In contrast, Compute Engine's machine images are globally available.


Public images

Amazon EC2 and Compute Engine both provide a variety of public images with commonly used operating systems. On both platforms, if you choose to install a premium image with an operating system that requires a license, you pay a license fee in addition to normal instance costs.

On both services, you can access machine images for most common operating systems. For the complete list of images that are available on Compute Engine, see the public images list.

Amazon EC2 provides support for some operating system images that are not available as public images on Compute Engine:

Amazon Linux
Windows Server 2003 (Premium)
Oracle Linux (Premium)

GCP vs AWS: Temporary instances

Amazon EC2 and Compute Engine both offer temporary instances that become available when resources aren't being fully utilized. These instances—called spot instances in Amazon EC2 and preemptible VMs in Compute Engine—are cheaper than standard instances, but can be reclaimed by their respective compute services with little notice. Due to their ephemeral nature, these instances are most useful when applications have tasks that can be interrupted or that can use, but don't need, increased compute power. Examples of such tasks might include batch processing, rendering, testing, simulation, or web crawling.

Spot instances and preemptible VMs are functionally similar, but have different cost models. Spot instances have two models:

Regular spot instances are auctioned via the Spot Market and launched when a bid is accepted. If a user's bid is the current highest bid, Amazon EC2 creates one or more instances. These instances run until the user terminates them or AWS interrupts them.
Spot blocks have a fixed priced that is less than the regular on-demand rate. However, they can only run for a maximum of six hours at that fixed rate.
Spot instances are restricted to a smaller set of available instance types and predefined machine images than standard EC2 instances. Aside from these limitations, spot instances behave similarly to on-demand Amazon EC2 instances. You have full control over the spot instance while it’s running.

As with Amazon EC2 spot instances, Compute Engine's preemptible VMs are similar to normal instances and have the same performance characteristics. Preemptible VMs contrast with Amazon EC2 spot instances as follows:

Pricing is fixed. Depending on machine type, preemptible VM prices can be discounted to nearly 80% of the on-demand rate.
Unlike Amazon EC2's regular spot instances, Compute Engine's preemptible VMs run for a maximum of 24 hours and then are terminated. However, Compute Engine can terminate preemptible VMs sooner depending on its resource needs.
If you use a premium operating system with a license fee, you will be charged the full cost of the license while using that preemptible VM.

references:
https://cloud.google.com/docs/compare/aws/compute

GCP vs AWS : Instance type comparison

Amazon EC2 and Compute Engine both offer a variety of predefined instance configurations with specific amounts of virtual CPU, RAM, and network. Amazon EC2 refers to these configurations as instance types, and Compute Engine refers to them as machine types. In addition, Compute Engine allows you to depart from the predefined configurations, customizing your instance's CPU and RAM resources to fit your workload.

Below image gives a good comparison.


references:
https://cloud.google.com/docs/compare/aws/compute

GCP vs AWS : Comute Servies

Compute services are typically offered under four service models:

Infrastructure as a service (IaaS), in which users have direct, on-demand access to virtual machines, as well as a suite of related services to automate common tasks.
Platform as a service (PaaS), in which the machine layer is abstracted away completely, and users interact with resources by using high-level services and APIs.
Functions as a service (FaaS), a serverless computing model that allows you to run individual functions in response to a variety of triggers.
Containers as a service (CaaS), an IaaS/PaaS hybrid that abstracts away the machine layer but retains much of the flexibility of the IaaS model.

For IaaS, AWS offers Amazon Elastic Compute Cloud (EC2), and GCP offers Compute Engine. Google and Amazon take similar approaches to their IaaS services. Both Amazon EC2 and Compute Engine are:

Fundamental components of their cloud environment.
Used to run almost every type of customer workload in their platform.

Virtual machine instances

Compute Engine and Amazon EC2 virtual machine instances share many of the same features. On both services, you can:

Create instances from stored disk images.
Launch and terminate instances on demand.
Manage your instances without restrictions.
Tag your instances.
Install a variety of available operating systems on your instance.


Machine access

Compute Engine and Amazon EC2 approach machine access in slightly different ways. With Amazon EC2, you must include your own SSH key if you want terminal access to the instance. In contrast, on Compute Engine, you can create the key when you need it, even if your instance is already running. If you choose to use Compute Engine's browser-based SSH terminal, which is available in the Google Cloud Platform Console, you can avoid storing keys on your local machine altogether.


references:
https://cloud.google.com/docs/compare/aws/compute

Friday, November 23, 2018

Android: how to set Activity view porgammatically

Here is how to do it


 @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      Log.d(TAG, "onCreate");

      puzzleView = new PuzzleView(this);
      setContentView(puzzleView);
      puzzleView.requestFocus();
   }

In the puzzle view, onSizeChanged can be implemented to get to know about the activity size changes.

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {

canvasHeight = Math.min(w,h);
canvasWidth = canvasHeight;
width = canvasWidth / 9f;
height = canvasHeight / 9f;

getRect(selX, selY, selRect);
Log.d(TAG, "onSizeChanged: width " + width + ", height " + height);
super.onSizeChanged(w, h, oldw, oldh);
}

override the draw method if need to paint something 

@Override
protected void onDraw(Canvas canvas) {

}

Sequence diagram in HTML

A base project for generating sequence diagram in HTML

The appearance of the diagram that is generated is good. Convenience is that this is in HTML and can be sent, if modify the HTML, can add the mouse overs and other features such as filters to say filter out provisional response in case of SIP.

references:
https://github.com/geraintluff/sequence-diagram-html

Thursday, November 22, 2018

Firebase : How to add a node without auto generated key

The trick is to use set instead of push, example is below

 String normalizedUserName = getNormalizedUserNameForDBPath(email);
        String enterpriseRoot = normalizedUserName;
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
        String pathName = APP_NAME + "/" + enterpriseRoot + "/users";
        final DatabaseReference messagesRef = databaseReference.child(pathName).child(normalizedUserName);
        messagesRef.setValue(userdetails); 

=> Dont use push 

GCP : Ways to interact with GCP services



There are basically three different ways to interact with GCP.

1. Google Cloud platform Console

One create a new project, or choose an existing project, and use the resources that you create in the context of that project. You can create multiple projects, so you can use projects to separate your work in whatever way makes sense for you. For example, you might start a new project if you want to make sure only certain team members can access the resources in that project, while all team members can continue to access resources in another project.

2. Command line interface
The Google Cloud SDK provided gcloud tool which gives the commands we need. This tool can be used for managing the development workflow and GCP resources.
GCP also provides cloudshell a browser based interactive shell environment for GCP. The cloud shell can be used from GCP console.

The cloud shell provides basically the below

1. A temporary compute engine
2. Command line access to the instance from a web browser
3. A built in code editor
4. Persistant disk storage upto 5 GB
5. Pre-installed Google SDK and and other tools
6. Language support for Java and, Go, Python, Node.js, PHP, Ruby, and .NET
7. Web Preview functionality
8. Built in authorization to access resources

3. Client libraries

Client libraries are part of Google cloud SDK and it enable one to easily create and manage resources. GCP client libraries expose APIs for two main purposes:

 a. App APIs provide access to services. App APIs are optimized for supported languages, such as Node.js and Python. The libraries are designed around service metaphors, so one can work with the services more naturally and write less boilerplate code. The libraries also provide helpers for authentication and authorization.

 b. Admin APIs offer functionality for resource management. For example, you can use admin APIs if you want to build your own automated tools.

One also can use the Google API client libraries to access APIs for products such as Google Maps, Google Drive, and YouTube.

References:
https://cloud.google.com/docs/overview/

GCP : projects



Any GCP resources that you allocate and use must belong to a project. You can think of a project as the organizing entity for what you're building. A project is made up of the settings, permissions, and other metadata that describe your applications. Resources within a single project can work together easily, for example by communicating through an internal network, subject to the regions-and-zones rules. The resources that each project contains remain separate across project boundaries; you can only interconnect them through an external network connection.

Each GCP project has:

    A project name, which you provide.
    A project ID, which you can provide or GCP can provide for you.
    A project number, which GCP provides.

As you work with GCP, you'll use these identifiers in certain command lines and API calls. The following screenshot shows a project name, its ID, and number:

Each project ID is unique across GCP. Once you have created a project, you can delete the project but its ID can never be used again.

When billing is enabled, each project is associated with one billing account. Multiple projects can have their resource usage billed to the same account.

A project serves as a namespace. This means every resource within each project must have a unique name, but you can usually reuse resource names if they are in separate projects. Some resource names must be globally unique. Refer to the documentation for the resource for details.

References:
https://cloud.google.com/docs/overview/

GCP : Global, regional, and zonal resources



Some resources can be accessed by any other resource, across regions and zones. These global resources include preconfigured disk images, disk snapshots, and networks. Some resources can be accessed only by resources that are located in the same region. These regional resources include static external IP addresses. Other resources can be accessed only by resources that are located in the same zone. These zonal resources include VM instances, their types, and disks.

The scope of an operation varies depending on what kind of resources you're working with. For example, creating a network is a global operation because a network is a global resource, while reserving an IP address is a regional operation because the address is a regional resource.

As you start to optimize your GCP applications, it's important to understand how these regions and zones interact. For example, even if you could, you wouldn't want to attach a disk in one region to a computer in a different region because the latency you'd introduce would make for very poor performance. Thankfully, GCP won't let you do that; disks can only be attached to computers in the same zone.

References:
https://cloud.google.com/docs/overview/

Wednesday, November 21, 2018

GCP vs AWS : Service Types

At a high level, cloud platforms begin by providing a set of baseline services: compute, storage, networking, and database services. AWS's baseline services include:

    Compute: Amazon Elastic Compute Cloud (EC2)
    Storage: Amazon Simple Storage Service (S3) and Amazon Elastic Block Store (EBS)
    Networking: Amazon Virtual Private Cloud (VPC)
    Databases: Amazon Relational Database Service (RDS) and Amazon DynamoDB

GCP's baseline services include:

    Compute: Google Compute Engine and Google App Engine
    Storage: Google Cloud Storage
    Networking: Google Virtual Private Cloud
    Databases: Google Cloud SQL, Google Cloud Datastore, and Google Cloud Bigtable

Each platform then builds other higher-level services on top of these services. Typically, these higher-level services can be categorized as one of four types:

    Application services: Services designed to help optimize applications in the cloud. Examples include Amazon SNS and Google Cloud Pub/Sub.
    Big data and analytics services: Services designed to help process large amounts of data, such as Amazon Kinesis and Google Cloud Dataflow.
    Management services: Services designed to help you track the performance of an application. Examples include Amazon CloudWatch and Google Stackdriver Monitoring.
    Machine learning services: Services designed to help you incorporate perceptual AI such as image or speech recognition, or to train and deploy your own machine learning models. Examples include Amazon SageMaker and Google Cloud Machine Learning Engine.

References:
https://cloud.google.com/docs/compare/aws/

What is Enrolling for App Signing in the Google Play?

Until recently, losing your key would make it impossible to update your app with a new version. A compromised key would be a serious issue too: a third-party could maliciously replace an authentic app or corrupt it. Unfortunately in such cases, the only solution was to publish a new app, with a new package name and key, and ask all of your users to install it.

App signing in the Play Console allows us to offer help in such circumstances. For existing apps, it requires transferring your app signing key to Google Play. For new apps, we can generate your app signing key. Once enrolled in app signing, you sign your APK with an upload key, which we use to authenticate your identity. We'll then strip that signature and re-sign your app with the app signing key.

The app signing key is now securely managed by Google Play meaning that you are only responsible for managing your upload key. If your upload key is compromised or lost, our developer operations team can assist by verifying your identity and resetting your upload key. We'll still re-sign with the same app signing key, allowing the app to update as usual.

Rest assured, your key will be fully protected by Google's robust cloud security infrastructure and will benefit from the ongoing investment we're making to our security systems. In the future, we plan to offer developers who sign with Google Play automatic optimizations to enhance their app distribution. Stay tuned for more news in this area!


References:
https://android-developers.googleblog.com/2017/09/enroll-for-app-signing-in-google-play.html

GCP vs AWS : Resource management interfaces

AWS and GCP each provide a command-line interface (CLI) for interacting with the services and resources. AWS provides the Amazon CLI, and GCP provides the Cloud SDK. Each is a unified CLI for all services, and each is cross-platform, with binaries available for Windows, Linux, and macOS. In addition, in GCP, you can use the Cloud SDK in your web browser by using Google Cloud Shell.

AWS and GCP also provide web-based consoles. Each console allows users to create, manage, and monitor their resources. The console for GCP is located at https://console.cloud.google.com/.
Service types

At a high level, cloud platforms begin by providing a set of baseline services: compute, storage, networking, and database services. AWS's baseline services include:

    Compute: Amazon Elastic Compute Cloud (EC2)
    Storage: Amazon Simple Storage Service (S3) and Amazon Elastic Block Store (EBS)
    Networking: Amazon Virtual Private Cloud (VPC)
    Databases: Amazon Relational Database Service (RDS) and Amazon DynamoDB

GCP's baseline services include:

    Compute: Google Compute Engine and Google App Engine
    Storage: Google Cloud Storage
    Networking: Google Virtual Private Cloud
    Databases: Google Cloud SQL, Google Cloud Datastore, and Google Cloud Bigtable

Each platform then builds other higher-level services on top of these services. Typically, these higher-level services can be categorized as one of four types:

    Application services: Services designed to help optimize applications in the cloud. Examples include Amazon SNS and Google Cloud Pub/Sub.
    Big data and analytics services: Services designed to help process large amounts of data, such as Amazon Kinesis and Google Cloud Dataflow.
    Management services: Services designed to help you track the performance of an application. Examples include Amazon CloudWatch and Google Stackdriver Monitoring.
    Machine learning services: Services designed to help you incorporate perceptual AI such as image or speech recognition, or to train and deploy your own machine learning models. Examples include Amazon SageMaker and Google Cloud Machine Learning Engine.

references:
https://cloud.google.com/docs/compare/aws/

Tuesday, November 20, 2018

GCP vs AWS : Pricing differences

To use an AWS service, you must sign up for an AWS account. After you have completed this process, you can launch any service under your account within Amazon's stated limits, and these services are billed to your specific account. If needed, you can create billing accounts, and then create sub-accounts that roll up to them. In this way, organizations can emulate a standard organizational billing structure.

Similarly, GCP requires you to set up a Google account to use its services. However, GCP groups your service usage by project rather than by account. In this model, you can create multiple, wholly separate projects under the same account. In an organizational setting, this model can be advantageous, allowing you to create project spaces for separate divisions or groups within your company. This model can also be useful for testing purposes: once you're done with a project, you can delete the project, and all of the resources created by that project will be deleted as well.

AWS and GCP both have default soft limits on their services for new accounts. These soft limits are not tied to technical limitations for a given service—instead, they are in place to help prevent fraudulent accounts from using excessive resources, and to limit risk for new users, keeping them from spending more than intended as they explore the platform. If you find that your application has outgrown these limits, AWS and GCP provide straightforward ways to get in touch with the appropriate internal teams to raise the limits on their services.

references

GCP vs AWS : Regions and zones

Nearly all AWS products are deployed within regions located around the world. Each AWS Region is a separate geographic area and comprises a group of data centers that are in relatively close proximity to each other. Each AWS Region has multiple, isolated locations known as Availability Zones. Amazon RDS provides the ability to place resources, such as instances, and data in multiple locations.

Similarly, GCP divides service availability into regions and zones that are located around the world. In addition, some GCP services are located at a multi-regional level rather than the more granular regional or zonal levels. These services include Google App Engine and Google Cloud Storage. Currently, the available multi-regional locations are United States, Europe, and Asia.

By design, each AWS region is isolated and independent from other AWS regions. This design helps ensure that the availability of one region doesn’t affect the availability of other regions, and that services within regions remain independent of each other. Similarly, GCP's regions are isolated from each other for availability reasons. However, GCP has built-in functionality that enables regions to synchronize data across regions according to the needs of a given GCP service.

AWS and GCP both have points of presence (POPs) located in many more locations around the world. These POP locations help cache content closer to end users. However, each platform uses their respective POP locations in different ways:

    AWS uses POPs to provide a content delivery network (CDN) service, Amazon CloudFront.
    GCP uses POPs to provide Google Cloud Content Delivery Network (Cloud CDN) and to deliver built-in edge caching for services such as Google App Engine and Google Cloud Storage.

GCP's POPs connect to data centers through Google-owned fiber. This unimpeded connection means that GCP-based applications have fast, reliable access to all of the services on GCP.

To summarize, AWS's location terms and concepts map to those of GCP as follows:
Concept                             AWS term             GCP term
Cluster of data centers and services     Region              Region
Abstracted data center     Availabilit.    Zone.                   Zone
Edge caching                             POP (just CloudFront)     POP (multiple services)

references:
https://cloud.google.com/docs/compare/aws/

Saturday, November 17, 2018

Android : Marker with outer border and pointing triangle.

For something like below, the code is given


import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Shader;

import sample.R;

public class BubbleTransformation implements com.squareup.picasso.Transformation {
    private static final int outerMargin = 5;
    private final int margin;  // dp

    // margin is the board in dp
    public BubbleTransformation(final int margin) {
        this.margin = margin;
    }

    @Override
    public Bitmap transform(final Bitmap source) {
        Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        Paint paintBorder = new Paint();
        paintBorder.setColor(Color.DKGRAY);
        paintBorder.setStrokeWidth(margin);
        canvas.drawRoundRect(new RectF(outerMargin, outerMargin, source.getWidth() - outerMargin, source.getHeight() - outerMargin), 0, 0, paintBorder);

        Paint trianglePaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        trianglePaint.setStrokeWidth(2);
        trianglePaint.setColor(Color.DKGRAY);
        trianglePaint.setStyle(Paint.Style.FILL_AND_STROKE);
        trianglePaint.setAntiAlias(true);

        Path triangle = new Path();
        triangle.setFillType(Path.FillType.EVEN_ODD);
        triangle.moveTo(outerMargin, source.getHeight() / 2);
        triangle.lineTo(source.getWidth()/2,source.getHeight());
        triangle.lineTo(source.getWidth()-outerMargin,source.getHeight()/2);
        triangle.close();

        canvas.drawPath(triangle, trianglePaint);

        final Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
        canvas.drawRoundRect(new RectF(margin+outerMargin, margin+outerMargin, source.getWidth() - (margin + outerMargin), source.getHeight() - (margin + outerMargin)), 0, 0, paint);

        if (source != output) {
            source.recycle();
        }

        return output;
    }

    @Override
    public String key() {
        return "rounded";
    }
}


String user_photo_url = "https://s3-ap-southeast-2.amazonaws.com/testuser.com/test_img.png";
        Picasso.with(this)
                .load(user_photo_url)
                .resize(100,100)
                .centerCrop()
                .transform(new BubbleTransformation(5))
                .into(mTarget);


Target mTarget = new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            Marker driver_marker = mMap.addMarker(new MarkerOptions()
                    .position(new LatLng(12.841747, 77.651758))
                    .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                    .title("test")
                    .snippet("test address")
            );
            mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(12.841747, 77.651758)));
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
            Log.d("picasso", "onBitmapFailed");
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    };


Android : Map Marker bitmap based drawing

In the Google Maps API v2 Demo there is a MarkerDemoActivity class in which you can see how a custom Image is set to a GoogleMap.

// Uses a custom icon.
mSydney = mMap.addMarker(new MarkerOptions()
    .position(SYDNEY)
    .title("Sydney")
    .snippet("Population: 4,627,300")
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
As this just replaces the marker with an image you might want to use a Canvas to draw more complex and fancier stuff:

Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(80, 80, conf);
Canvas canvas1 = new Canvas(bmp);

// paint defines the text color, stroke width and size
Paint color = new Paint();
color.setTextSize(35);
color.setColor(Color.BLACK);

// modify canvas
canvas1.drawBitmap(BitmapFactory.decodeResource(getResources(),
    R.drawable.user_picture_image), 0,0, color);
canvas1.drawText("User Name!", 30, 40, color);

// add marker to Map
mMap.addMarker(new MarkerOptions()
    .position(USER_POSITION)
    .icon(BitmapDescriptorFactory.fromBitmap(bmp))
    // Specifies the anchor to be at a particular point in the marker image.
    .anchor(0.5f, 1));
This draws the Canvas canvas1 onto the GoogleMap mMap. The code should (mostly) speak for itself, there are many tutorials out there how to draw a Canvas. You can start by looking at the Canvas and Drawables from the Android Developer page.

Now you also want to download a picture from an URL.

URL url = new URL(user_image_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
conn.setDoInput(true); 
conn.connect();   
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
You must download the image from an background thread (you could use AsyncTask or Volley or RxJava for that).

After that you can replace the BitmapFactory.decodeResource(getResources(), R.drawable.user_picture_image) with your downloaded image bmImg.

references:
https://stackoverflow.com/questions/14811579/how-to-create-a-custom-shaped-bitmap-marker-with-android-map-api-v2

Android: Marker with an image

Below is how to display a marker with a custom image. But this is going to just display the image as is given. Not with any marker like pointed.

public void updateMapWithUserLocations(){
        mSydney = mMap.addMarker(new MarkerOptions()
                .position(new LatLng(12.841747, 77.651758))
                .title("Sydney")
                .snippet("Population: 4,627,300")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.dummy_profile_img)));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(12.841747, 77.651758)));
    }

Friday, November 16, 2018

Protecting Data Using On-Disk Encryption

Data protection uses built-in hardware to store files in an encrypted format on disk and to decrypt them on demand. While the user’s device is locked, protected files are inaccessible, even to the app that created them. The user must unlock the device (by entering the appropriate passcode) before an app can access one of its protected files.

Data protection is available on most iOS devices and is subject to the following requirements:

    The file system on the user’s device must support data protection. Most devices support this behavior.

    The user must have an active passcode lock set for the device.

To protect a file, you add an attribute to the file indicating the desired level of protection. Add this attribute using either the NSData class or the NSFileManager class. When writing new files, you can use the writeToFile:options:error: method of NSData with the appropriate protection value as one of the write options. For existing files, you can use the setAttributes:ofItemAtPath:error: method of NSFileManager to set or change the value of the NSFileProtectionKey. When using these methods, specify one of the following protection levels for the file:

    No protection—The file is encrypted but is not protected by the passcode and is available when the device is locked. Specify the NSDataWritingFileProtectionNone option (NSData) or the NSFileProtectionNone attribute (NSFileManager).

    Complete—The file is encrypted and inaccessible while the device is locked. Specify the NSDataWritingFileProtectionComplete option (NSData) or the NSFileProtectionComplete attribute (NSFileManager).

    Complete unless already open—The file is encrypted. A closed file is inaccessible while the device is locked. After the user unlocks the device, your app can open the file and use it. If the user locks the device while the file is open, though, your app can continue to access it. Specify the NSDataWritingFileProtectionCompleteUnlessOpen option (NSData) or the NSFileProtectionCompleteUnlessOpen attribute (NSFileManager).

    Complete until first login—The file is encrypted and inaccessible until after the device has booted and the user has unlocked it once. Specify the NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication option (NSData) or the NSFileProtectionCompleteUntilFirstUserAuthentication attribute (NSFileManager).

If you protect a file, your app must be prepared to lose access to that file. When complete file protection is enabled, your app loses the ability to read and write the file’s contents when the user locks the device. You can track changes to the state of protected files using one of the following techniques:

    The app delegate can implement the applicationProtectedDataWillBecomeUnavailable: and applicationProtectedDataDidBecomeAvailable: methods.

    Any object can register for the UIApplicationProtectedDataWillBecomeUnavailable and UIApplicationProtectedDataDidBecomeAvailable notifications.

    Any object can check the value of the protectedDataAvailable property of the shared UIApplication object to determine whether files are currently accessible.

For new files, it is recommended that you enable data protection before writing any data to them. If you are using the writeToFile:options:error: method to write the contents of an NSData object to disk, this happens automatically. For existing files, adding data protection replaces an unprotected file with a new protected version.

Thursday, November 15, 2018

Java Calendar one important note that may get easily missed

Calendar.HOUR value range is from 0 - 11. This means that
calendar.set(Calendar.HOUR,12) will switch the date to next day 0. If we want to get 12pm current day

calendar.set(Calendar.HOUR,0);
calendar.set(Calendar.AM_PM,Calendar.PM) 

Tuesday, November 13, 2018

Javascript : How to convert time to local time zone










references:
https://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/

HIPAA : How to determine if entity is a covered entity

the Guide below from cms.gov has an interactive flow chart that determines whether the entity is covered under HIPAA. This is quite useful tool. 

references:
 https://www.cms.gov/Regulations-and-Guidance/Administrative-Simplification/HIPAA-ACA/Downloads/CoveredEntitiesChart20160617.pdf

HIPAA Basics

Statutory and Regulatory Background

    The Administrative Simplification provisions of the Health Insurance Portability and Accountability Act of 1996 (HIPAA, Title II) required the Secretary of HHS to publish national standards for the security of electronic protected health information (e-PHI), electronic exchange, and the privacy and security of health information.

    HIPAA called on the Secretary to issue security regulations regarding measures for protecting the integrity, confidentiality, and availability of e-PHI that is held or transmitted by covered entities. HHS developed a proposed rule and released it for public comment on August 12, 1998. The Department received approximately 2,350 public comments. The final regulation, the Security Rule, was published February 20, 2003.2 The Rule specifies a series of administrative, technical, and physical security procedures for covered entities to use to assure the confidentiality, integrity, and availability of e-PHI.

    The text of the final regulation can be found at 45 CFR Part 160 and Part 164, Subparts A and C.

Who is Covered by the Security Rule

    The Security Rule applies to health plans, health care clearinghouses, and to any health care provider who transmits health information in electronic form in connection with a transaction for which the Secretary of HHS has adopted standards under HIPAA (the “covered entities”) and to their business associates. For help in determining whether you are covered, use CMS's decision tool.

    Read more about covered entities in the Summary of the HIPAA Privacy Rule - PDF - PDF.

Business Associates

    The HITECH Act of 2009 expanded the responsibilities of business associates under the HIPAA Security Rule. HHS developed regulations to implement and clarify these changes.

    See additional guidance on business associates.

What Information is Protected

    Electronic Protected Health Information. The HIPAA Privacy Rule protects the privacy of individually identifiable health information, called protected health information (PHI), as explained in the Privacy Rule and here - PDF - PDF. The Security Rule protects a subset of information covered by the Privacy Rule, which is all individually identifiable health information a covered entity creates, receives, maintains or transmits in electronic form. The Security Rule calls this information “electronic protected health information” (e-PHI).3 The Security Rule does not apply to PHI transmitted orally or in writing.






references
https://www.hhs.gov/hipaa/for-professionals/security/laws-regulations/index.html

Sunday, November 11, 2018

H.265 advantages

- Offers a 35,4% average reduction in the compression compared to its predecessor H.264. Although there are some studies indicating a possible reduction up to a 60%.

- The codec offers more compatibility with parallel processing systems more improved that actual ones.

This codec is specifically oriented to permit new video resolution supports like Full 3D or the 4K res.

Regardless of it has been admitted by the ITU-T, it finds itself in an early development stage and narrow-spread. Some new solutions start to implement it, like Cisco people, that have not been spending their time regarding this topic.

references:
https://www.voipelia.com/en/video-systems-evolution-h-265/

Thursday, November 8, 2018

Android : How to show HTML in AlertDialog?

Below code will help for it.

public static void showAlertMessageWithHTML(Context context, String title, String message, String positiveAction, String negativeAction, String neutralAction, boolean cancellable, final AlertActionListener actionListener)
    {
        TextView msg = new TextView(context);
        msg.setText(Html.fromHtml(message));
        msg.setPadding(30,20,30,10);
       

        final SpannableString s = new SpannableString(message);
        Linkify.addLinks(s, Linkify.ALL);
        AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
        builder1.setTitle(title);

        builder1.setView(msg);
        builder1.setCancelable(cancellable);
        if(positiveAction != null)
        {
            builder1.setPositiveButton(positiveAction, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if(actionListener != null)
                    {
                        actionListener.onPositiveAction();
                    }
                }
            });
        }
        if(negativeAction != null)
        {
            builder1.setNegativeButton(negativeAction, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if(actionListener != null) {
                        actionListener.onNegativeAction();
                    }
                }
            });
        }
        builder1.setNeutralButton(neutralAction, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(actionListener != null)
                {
                    actionListener.onNeutralAction();
                }
            }
        });

        AlertDialog alert11 = builder1.create();
        alert11.show();
    }

Wednesday, November 7, 2018

iOS How to do quick email validation

func isValidEmail(testStr:String) -> Bool {       
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"

    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    return emailTest.evaluate(with: testStr)
}

Android : Dismiss the keyboard programmatically

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

references:
https://stackoverflow.com/questions/3553779/android-dismiss-keyboard

Tuesday, November 6, 2018

W3C Push-API

The Push API allows a webapp to communicate with a user agent asynchronously. This allows an application server to provide the user agent with time-sensitive information whenever that information becomes known, rather than waiting for a user to open the webapp.

As defined here, push services support delivery of push messages at any time.

In particular, a push message will be delivered to the webapp even if that webapp is not currently active in a browser window: this relates to use cases in which the user may close the webapp, but still benefits from the webapp being able to be restarted when a push message is received. For example, a push message might be used to inform the user of an incoming WebRTC call.

A push message can also be sent when the user agent is temporarily offline. In support of this, the push service stores messages for the user agent until the user agent becomes available. This supports use cases where a webapp learns of changes that occur while a user is offline and ensures that the user agent can be provided with relevant information in a timely fashion. Push messages are stored by the push service until the user agent becomes reachable and the message can be delivered.

The Push API will also ensure reliable delivery of push messages while a user agent is actively using a webapp, for instance if a user is actively using the webapp or the webapp is in active communication with an application server through an active worker, frame, or background window. This is not the primary use case for the Push API. A webapp might choose to use the Push API for infrequent messages to avoid having to maintain constant communications with the application server.

Push messaging is best suited to occasions where there is not already an active communications channel established between user agent and webapp. Sending push messages requires considerably more resources when compared with more direct methods of communication such as fetch() or websockets. Push messages usually have higher latency than direct communications and they can also be subject to restrictions on use. Most push services limit the size and quantity of push messages that can be sent.

references:
https://www.w3.org/TR/push-api/


Firebase Scenarios and suitable notification methods.

Topic messaging is best suited for content such as news, weather, or other publicly available information.
Topic messages are optimized for throughput rather than latency. For fast, secure delivery to single devices or small groups of devices, target messages to registration tokens, not topics.
If you need to send messages to multiple devices per user, consider device group messaging for those use cases.

references:
https://firebase.google.com/docs/cloud-messaging/js/topic-messaging

iOS Swift : Compute mins and seconds from TimeInterval

Here is the logic

let diff : TimeInterval = Date().timeIntervalSince1970 - capturedStartTimeSecs
let remaining : TimeInterval = capturedStartTimeSecs - diff;
let minutes : TimeInterval = remaining  / 60;
var mins : String = String(Int(minutes)) + "";
if(Int(minutes) < 10){
      mins = "0" + String(Int(minutes));
}
               
var seconds = remaining
seconds.formTruncatingRemainder(dividingBy:60) ;
var secs : String = String(Int(seconds)) + "";
if(Int(seconds) < 10){
      secs = "0" + String(Int(seconds))
}

iOS Swift: Trying to use a mutating function like a function that returns.

You need to understand the difference between a non-mutating function that returns a value, and a void mutating function. The one you wrote, is a mutating function:
mutating func parent(_ word:String){

    self = self+" "+word

}
Mutating functions like this can be used like this:
var string = "Hello"
string.parent("World")
print(string)

As you can see, the call to parent changes the value that is stored in the variable string.
Function that returns is another matter. This is the same parent function, rewritten to return a value:

func parent(_ word: String) -> String {
    return self + " " + word
}

You can use this function that returns like this:

print("Apple".parent("Tree"))
print("Tomato".parent("Plant"))

In this case, nothing is being changed. Values are just being "computed" and returned to the caller.
What you are doing wrong is basically trying to use a mutating function like a function that returns.
To fix this, either change the function to return a value, or use the mutating function properly, as I've showed you.

references:
https://stackoverflow.com/questions/45451133/cannot-use-mutating-member-on-immutable-value-of-type-string/45451230

Monday, November 5, 2018

iOS Swift allow optional delegate methods possible?

Swift protocols on their side do not allow optional methods. But if you are making an app for macOS, iOS, tvOS or watchOS you can add the @objc keyword at the beginning of the implementation of your protocol and add @objc follow by optional keyword before each methods you want to be optional.

@objc protocol MyProtocol {
    @objc optional func anOptionalMethod()
}

A swiftier way
The problem with @objc is that you can not use it in pure Swift. For example, imagine that you make a library that can be used on linux to do some Back-end app with Swift. The @objc will not be available. But let’s remember why we would like to declare a protocol method as optional? It is because we we don’t want to write the implementation if that method will not be used. So Swift has a feature called extension that allow us to provide a default implementation for those methods that we want to be optional.

protocol MyProtocol {
    func anOptionalMethod()
    func aNotOptionalMethod()
}

extension MyProtocol {

    func anOptionalMethod() {
        //this is a empty implementation to allow this method to be optional
    }
}

references:
https://medium.com/@ant_one/how-to-have-optional-methods-in-protocol-in-pure-swift-without-using-objc-53151cddf4ce

iOS App Submission screenshot requirements

the must screen size requirements are for 6.5, 5.5 and 12.9 inches.
 which are the ones below,


6.5 inch (iPhone XS Max, iPhone XR)
1242 x 2688 pixels (portrait)

2688 x 1242 pixels (landscape)
Optional
Upload 6.5-inch screenshots

5.5 inch (iPhone 6s Plus, iPhone 7 Plus, iPhone 8 Plus)
1242 x 2208 pixels (portrait)

2208 x 1242 pixels (landscape)
Required if app runs on iPhone
Upload 5.5-inch screenshots

12.9 inch (iPad Pro (3rd generation))
2048 x 2732 pixels (portrait)

2732 x 2048 pixels (landscape)
Optional
Upload 12.9-inch iPad Pro (3rd generation) screenshots

references:
https://help.apple.com/app-store-connect/#/devd274dd925

iOS Single point reference for screenshot requirements

the must screensize requirements are for 6.5, 5.5 and 12.9 inches.
 which are the ones below,


6.5 inch (iPhone XS Max, iPhone XR)
1242 x 2688 pixels (portrait)

2688 x 1242 pixels (landscape)
Optional
Upload 6.5-inch screenshots

5.5 inch (iPhone 6s Plus, iPhone 7 Plus, iPhone 8 Plus)
1242 x 2208 pixels (portrait)

2208 x 1242 pixels (landscape)
Required if app runs on iPhone
Upload 5.5-inch screenshots

12.9 inch (iPad Pro (3rd generation))
2048 x 2732 pixels (portrait)

2732 x 2048 pixels (landscape)
Optional
Upload 12.9-inch iPad Pro (3rd generation) screenshots

references:
https://help.apple.com/app-store-connect/#/devd274dd925

Sunday, November 4, 2018

iOS UICollectionView using horizontal and vertical scrolling with sticky rows and columns

Below is the visual effect of this


This can be done using the Collection layout like described in the link below in references

references:
https://www.brightec.co.uk/ideas/uicollectionview-using-horizontal-and-vertical-scrolling-sticky-rows-and-columns

iOS Paralax View using UICollectionViewlayout

Such effect is called parallax. The algorithm is actually pretty simple. The problem is how you can implement in a UICollectionView. You could in theory register the scroll event and move the visible cells around to achieve this. However, this is not what we are going to do today. We’ll instead create a UICollectionViewLayout subclass to handle this for us. Below effects are possible with this approach.




references:
https://medium.com/@uthoft.jin/how-to-animate-uicollectionview-using-a-custom-uicollectionviewlayout-a7513add25b2

What is MNG ?

Multiple-image Network Graphics (MNG) is a graphics file format, published in 2001, for animated images. Its specification is publicly documented and there are free software reference implementations available.

MNG is closely related to the PNG image format. When PNG development started in early 1995, developers decided not to incorporate support for animation, because the majority of the PNG developers felt that overloading a single file type with both still and animation features is a bad design, both for users (who have no simple way of determining to which class a given image file belongs) and for web servers (which should use a MIME type starting with image/ for stills and video/ for animations—GIF notwithstanding).[1] However, work soon started on MNG as an animation-supporting version of PNG. Version 1.0 of the MNG specification was released on 31 January 2001.The structure of MNG files is essentially the same as that of PNG files, differing only in the slightly different signature (8A 4D 4E 47 0D 0A 1A 0A in hexadecimal, where 4D 4E 47 is ASCII for "MNG" – see Portable Network Graphics: File header) and the use of a much greater variety of chunks to support all the animation features that it provides. Images to be used in the animation are stored in the MNG file as encapsulated PNG or JNG images.

Two versions of MNG of reduced complexity are also defined: MNG-LC (low complexity) and MNG-VLC (very low complexity). These allow applications to include some level of MNG support without having to implement the entire MNG specification, just as the SVG standard offers the "SVG Basic" and "SVG Tiny" subsets.

MNG does not have a registered MIME media type, but video/x-mng or image/x-mng can be used. MNG animations may be included in HTML pages using the or tag.

MNG can either be lossy or lossless, depending whether the frames are encoded in PNG (lossless) or JNG (lossy).

references:
https://en.wikipedia.org/wiki/Multiple-image_Network_Graphics

What is APNG?

The Animated Portable Network Graphics (APNG) file format is an extension to the Portable Network Graphics (PNG) specification. It allows for animated PNG files that work similarly to animated GIF files, while supporting 24-bit images and 8-bit transparency not available for GIFs. It also retains backward compatibility with non-animated PNG files.

The first frame of an APNG file is stored as a normal PNG stream, so most standard PNG decoders are able to display the first frame of an APNG file. The frame speed data and extra animation frames are stored in extra chunks (as provided for by the original PNG specification).

APNG competes with Multiple-image Network Graphics (MNG), a comprehensive format for bitmapped animations created by the same team as PNG. APNG's advantage is the smaller library size and compatibility with older PNG implementations.

Mozilla's role in extending the PNG format to APNG echoes Netscape's much earlier role in popularizing animated GIFs.[citation needed]

In 2016, Apple adopted the APNG format as the preferred format for animated stickers in iOS 10 iMessage apps.[10]

On March 15, 2017 APNG support was added to Chromium.[11] This leaves Microsoft Edge's EdgeHTML rendering engine as the only engine to not support the format.


references:
https://en.wikipedia.org/wiki/APNG