Wednesday, October 31, 2018

Flutter: Implementing Swipe to Dismiss

Below are the steps to do this:

1. Create List of items
2. Wrap each item in a dismissible widget
3. Provide "Lead Behind" indicators

To create a list of items, its as usual the code is like

Final items = List.generate(20,(i) => "Item ${I+1}")

Now this can be converted into a list like below

ListView.builder(itemCount:10,itemBuilder:(context, index){ return ListTitle(title:Text($itmes[index])})

The crux is that we should have list item wrapped inside a Dismissable object

Dismissable(key:Key(item)),
onDismissed:(direction){
setState(){
items.removeAt(index)
}
Scaffold.of(context).showSnackBar(SnackBar(content:Text(${item dismissed})))
}
Background:Container(color:Colors.red);
Child:ListTitle(title:Text('$item'))

References:
https://flutter.io/cookbook/gestures/dismissible/

Flutter: Navigating to new screen


In flutter world, everything is Widget!

1. Create new screen
2. Navigate to the new screen using Navigator.push
3. Return to the first screen using Navigator.pop.

Thats all mainly to be done.

class FirstScreen extends StatlessWidget {
@Override
Widget build(BuildContext context){
Return Scaffold(appBar:AppBar(title:Text('First Screen')))
}

}


References

Tuesday, October 30, 2018

iOS What is ReplayKit?

Using the ReplayKit framework, users can record video from the screen, and audio from the app and microphone. They can then share their recordings with other users through email, messages, and social media. You can build app extensions for live broadcasting your content to sharing services. ReplayKit is incompatible with AVPlayer content.

References:
https://www.appcoda.com/replaykit/

Monday, October 29, 2018

iOS Dual SIM some notes from Apple documentation



Phone XS, iPhone XS Max, and iPhone XR feature Dual SIM with a nano-SIM and an eSIM.1 An eSIM is a digital SIM that allows you to activate a cellular plan from your carrier without having to use a physical nano-SIM.

Some of the use cases are below


    Use one number for business and another number for personal calls.
    Add a local data plan when you travel outside of the country or region.
    Have separate voice and data plans.



Both of your phone numbers can make and receive voice calls and send and receive SMS and MMS.2 Your iPhone can use one cellular data network at a time.

Both of your phone numbers can make and receive voice calls and send and receive SMS and MMS.2 Your iPhone can use one cellular data network at a time.

1. eSIM on iPhone is not offered in mainland China. In Hong Kong and Macau, only iPhone XS features eSIM.
2. This uses Dual SIM Dual Standby technology, which means that both SIMs can make and receive calls. If one number is on a call, incoming calls on the other number will go to voicemail.

To use two different carriers, your iPhone must be unlocked. Otherwise, both plans must be from the same carrier. If a CDMA carrier provides your first SIM, your second SIM won't support CDMA. Contact your carrier for more information.

If you have an enterprise or corporate cellular service plan, check with your company administrator to see if they support this feature.


Below are the 3 options

Use Primary as your default line: If you select this option, Primary will be used by default for voice, SMS, Data, iMessage, and FaceTime. Secondary will be available just for voice and SMS.

Use Secondary as your default line: If you select this option, Secondary will be used for voice, SMS, Data, iMessage, and FaceTime. Primary will be available just for voice and SMS.

Use Secondary for cellular data only: You might want to select this option if you're traveling internationally and you want to keep Primary for voice, SMS, iMessage, and FaceTime. This will allow you to use Secondary for data.

References:
https://support.apple.com/en-us/HT209044

Flutter: Adding Material Touch Ripples

Below given some guidelines for adding ripple animation when something is touched on the screen.

1. Create a Widget to tap
2. Wrap it in an InkWell widget to manage tap callbacks and ripple animations

Class MyButtpn extends StatelessWidget {
    @override
    Widget build(BuildContext context){   
        return InkWell(
            onTap:() {
                Scaffold.of.(context).showSnackBar(SnackBar (content : Text('Tap')),
            }
            child:Container(padding:EdgeInsets.all(12.0)),child:Text('Flat Button')
        );
    }
}


References:
https://flutter.io/cookbook/gestures/ripples/

iOS Support for eSIM

Apple have added eSIM support to the latest version of their iOS 12.1 Public Beta 1. The LPA now includes an LUId that allows the subscriber to either scan a QR code or enter an activation code manually.  All that the subscriber has to do is purchase an appropriate activation code/QR code from an Operator and download the profile. This is effected by going into ‘Settings’, selecting ‘Mobile Data’ and then selecting ‘Add Data Plan’. It is curious that when UK English is set in the phone, Apple are referring to ‘Data Plan’ when there is no reason why a downloaded profile could not support Voice, SMS and Data. Although when the language in the phone is switched to US English the menu entry becomes ‘Add Cellular Plan’. It would appear that Apple will permit voice, SMS and data and that the UK English words are a bit misleading. Another point of note is that there does not yet seem to be any UI for searching for available plans using any form of Discovery Service.

References:
https://esim.net/category/all-the-latest-news-about-esims/

What is LUID?

An LUID is a 64-bit value guaranteed to be unique only on the system on which it was generated. The uniqueness of a locally unique identifier (LUID) is guaranteed only until the system is restarted. Applications must use functions and structures to manipulate LUID values.

references:
https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_luid

What is eSIM?




eSIM is a global specification by the GSMA which enables remote SIM provisioning of any mobile device. eSIM now allows consumers to store multiple operator profiles on a device simultaneously, and switch between them remotely, though only one can be used at a time.

Remote provisioning means much smaller devices can be supported. The first products have already come to market, and we can expect to see many further launches in 2018: it is now easier to extend mobile connectivity to devices such as tablets, smart watches, fitness bands, portable health systems and various other devices.

eSIM is the only globally-backed remote SIM specification for consumer devices. This universal approach will grow the Internet of Things by allowing manufacturers to build a new range of products for global deployment based on this common embedded SIM architecture.

Consumer benefits include:

    simpler device setup without the need to insert or replace a SIM card;
    devices that can operate independently of a tethered smartphone, with their own subscriptions;
    a range of new, enhanced mobile-connected devices.

references:
https://www.gsma.com/esim/

SendGrid send email using SMTP relay

Web API integration require the assistant packages from SendGrid to be used. If we have NodeMailer kind of package already in use
Below is the configuration for this

var transporter = nodemailer.createTransport({
            host: 'smtp.sendgrid.net',
            port: 465,
            secure: true, // true for 465, false for other ports
            auth: {
                user: "apikey", // generated ethereal user
                pass: ""  // generated ethereal password
            }
        });

references

SendGrid unable to receive email on certain domains


Likely you (SendGrid) have been blacklisted for spamming.
You can try filling out this form, submit, and wait for a response to get off their blacklist.
https://support.microsoft.com/en-us/getsupport?oaspworkflow=start_1.0.0.0&wfname=capsub&productkey=edfsmsbl3
If you get an error during submittal it is because you've put in too much info in one of the text fields. Correct before submitting again.


https://answers.microsoft.com/en-us/outlook_com/forum/all/sendgrid-says-emails-delivered-but-customers-with/62de80ab-c006-4507-86d1-708d255c996d

How to Integrate SendGrid with Node JS

- create an account with Send grid  and follow the below steps

1. Make sure you have the prerequisites
Our library requires Node.js version 0.10, 0.12, or 4.

2. Create an API key
This allows your application to authenticate to our API and send mail. You can enable or disable additional permissions on the

3. Install the package using below command
npm install --save @sendgrid/mail


4. Send your first email
The following is the minimum needed code to send an email:
// using SendGrid's v3 Node.js Library

// https://github.com/sendgrid/sendgrid-nodejs

const sgMail = require('@sendgrid/mail');

sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const msg = {

  to: 'test@example.com',

  from: 'test@example.com',

  subject: 'Sending with SendGrid is Fun',

  text: 'and easy to do anywhere, even with Node.js',

  html: 'and easy to do anywhere, even with Node.js',

};

sgMail.send(msg);

Node JS : Why Nodemailer work with Gmail on local but not on AWS ?

The nodemailer documentation has a good explanation for this!

Even though Gmail is the fastest way to get started with sending emails, it is by no means a preferable solution unless you are using OAuth2 authentication. Gmail expects the user to be an actual user not a robot so it runs a lot of heuristics for every login attempt and blocks anything that looks suspicious to defend the user from account hijacking attempts. For example you might run into trouble if your server is in another geographical location – everything works in your dev machine but messages are blocked in production.

Additionally Gmail has came up with the concept of “Less Secure” apps which is basically anyone who uses plain password to login to Gmail, so you might end up in a situation where one username can send mail (support for “less secure” apps is enabled) but other is blocked (support for “less secure” apps is disabled). You can configure your Gmail account to allow less secure apps here. When using this method make sure to also enable the required functionality by completing the “Captcha Enable” challenge. Without this, less secure connections probably would not work.

If you are using 2FA you would have to create an “Application Specific” password for Nodemailer to work.

Gmail also always sets authenticated username as the From: e-mail address. So if you authenticate as foo@example.com and set bar@example.com as the from: address, then Gmail reverts this and replaces the sender with the authenticated user.

To prevent having login issues you should either use XOAUTH2 (see details here) or use another provider and preferably a dedicated one like Mailgun or SendGrid or any other. Usually these providers have free plans available that are comparable to the daily sending limits of Gmail. Gmail has a limit of 500 recipients a day (a message with one To and one Cc address counts as two messages since it has two recipients) for @gmail.com addresses and 2000 for Google Apps customers, larger SMTP providers usually offer about 200-300 recipients a day for free.

references:
https://community.nodemailer.com/using-gmail/

Sunday, October 28, 2018

Node JS: Node mailer SMTP configuration

var smtpConfig = {
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL
    auth: {
        user: 'user@gmail.com',
        pass: 'pass'
    }
};

var poolConfig = {
    pool: true,
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL
    auth: {
        user: 'user@gmail.com',
        pass: 'pass'
    }
};

var directConfig = {
    name: 'hostname' // must be the same that can be reverse resolved by DNS for your IP
};


references:
https://community.nodemailer.com/2-0-0-beta/setup-smtp/

Node JS:Configuring NodeMailer with gmail

Gmail has some security rules that needs to be taken care before able to send mail using NodeMailer.
Below is how the configurations to be done.

1. Login gmail account.
2. Enable pop3 in settings tabs
3. Enable less secure apps at: https://myaccount.google.com/lesssecureapps
4. Display Unlock Captcha at: https://accounts.google.com/b/0/DisplayUnlockCaptcha
5. Defined email option and sending
var mailOptions = {
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL
    auth: {
        user: 'gmail_account@gmail.com',
        pass: 'password'
    }
}   

mailer = nodemailer.createTransport(mailOptions);

mailer.sendMail({
....
}, function(err, response) {
        if (err) {
             console.log(err);
        }
        console.log(response);
});


references:
https://stackoverflow.com/questions/14654736/nodemailer-econnrefused

Saturday, October 27, 2018

Swift : How to Drop a table?

Below is the code to do that

open func dropTable(tableName:String) -> Bool{
        let opened = openDatabase();
        if(!opened){
            return false
        }
        let query = "DROP TABLE IF EXISTS "+tableName
        if(sqlite3_exec(db,query,nil,nil,nil) != SQLITE_OK){
            let errMsg = String(cString:sqlite3_errmsg(db!))
            if errMsg.count > 0 {
                return false
            }
        }
        return true
    }

references:

HTML Creating Favorite icon

Below is one good web site which accept PNG , JPEG or any other format and give back the ico format file.

http://icoconvert.com/

references:
http://icoconvert.com/

Friday, October 26, 2018

SIP: What is the best Local ringing policy for SIP UAs'?


 With this in mind, a UAC should develop its local policy regarding local ringing generation.  For example, a POTS ("Plain Old Telephone Service")-li SIP User Agent (UA) could implement the following
   local policy:

      1. Unless a 180 (Ringing) response is received, never generate
         local ringing.

      2. If a 180 (Ringing) has been received but there are no incoming
         media packets, generate local ringing.

      3. If a 180 (Ringing) has been received and there are incoming
         media packets, play them and do not generate local ringing.

         Note that a 180 (Ringing) response means that the callee is
         being alerted, and a UAS should send such a response if the
         callee is being alerted, regardless of the status of the early
         media session.

   At first sight, such a policy may look difficult to implement in decomposed UAs (i.e., media gateway controller and media gateway), but this policy is the same as the one described in Section 2, which must be implemented by any UA.  That is, any UA should play incoming media packets (and stop local ringing tone generation if it was being performed) in order to avoid media clipping, even if the 200 (OK) response has not arrived.  So, the tools to implement this early media policy are already available to any UA that uses SIP.

Note that, while it is not desirable to standardize a common local policy to be followed by every SIP UA, a particular subset of more or less homogeneous SIP UAs could use the same local policy by convention.  Examples of such subsets of SIP UAs may be "all the PSTN/SIP gateways" or "every 3GPP IMS (Third Generation Partnership Project Internet Multimedia System) terminal".  However, defining the  particular common policy that such groups of SIP devices may use is  outside the scope of this document.

References:
https://www.ietf.org/rfc/rfc3960.txt

Flutter : Gesture Recognition

Class MyButton extends StatelessWidget {

@override
Widget build(BuildContext context) {
    return GestureDetector (
        onTap() {
        final snackbar = SnackBar (content:Text("Tap"))
        Scaffold.of(context).showSnackBar(snackBar)
    }
    child:Container(padding: EdgeInsets.all(12.0),decoration : BoxDecoration(color:Theme.of(context).buttonColor,borderRadius:BorderRadius.circular(8.0))),
    child:Text("My Button");
    )

}

}

References:
https://flutter.io/cookbook/gestures/handling-taps/

Flutter: Grid View

Class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context){
    return MaterialApp(title: "title", home : Scaffold(appBar:AppBar(title:Text(title),), body : GridView.count(
    crossAxisCount : 2,
    Children : List.generate(100, (index) {
    return Center( child : Text ("Item index $index", style : Theme.of(context.textTheme.headline)))

) ) )
}

}

References:
https://flutter.io/cookbook/lists/grid-lists/

Flutter: Creating Lists with Different type of Items

The basic design needed for creating list with Different type is

1. Create Data source with Different items
2. Convert the data source into List of widgets

The example here is a list with heading and message items

Abstract class ListItem{}

Class HeadingItem implementes ListItem{
Final String heading;
HeadingItem(this.heading);
}

Class MessageItem implements ListItem {

Final String sender;
Final String body;

MessageItem(this.sender, this.body)
}


Final items = List.generate(
1200,
(i) => I % 6 == 0 ? HeadingItem("Heading Item $I") : MessageItem("Sender $I","Message Body $I")
);
References:
https://flutter.io/cookbook/lists/mixed-list/

iOS encrypting App's files

We can specify the level of data protection that you want to apply on each of the files. There are four levels available, each of which determines when you one may access the file. If one do not specify a protection level when creating a file, iOS applies the default protection level automatically.

    No protection. The file is always accessible.

    Complete until first user authentication. (Default) The file is inaccessible until the first time the user unlocks the device. After the first unlocking of the device, the file remains accessible until the device shuts down or reboots.

    Complete unless open. You can open existing files only when the device is unlocked. If you have a file already open, you may continue to access that file even after the user locks the device. You can also create new files and access them while the device is locked or unlocked.

    Complete. The file is accessible only when the device is unlocked.

Below is how to encrypt

Do {
   Try data.write(to:fileURL, options:.completeFileProtection);
}
Catch {
// handle errors.
}

References:
https://developer.apple.com/documentation/uikit/core_app/protecting_the_user_s_privacy/encrypting_your_app_s_files

Thursday, October 25, 2018

SSL Handshake and SNI

When a web client and a web server talk to each other over HTTPS, the very first thing that needs to happen is the secure handshake.
Here is a simplified example of such a handshake:



If this were HTTP and not HTTPS, the first thing the client would have sent would have been something like this:

GET /index.html HTTP/1.1
Host: example.com
This made multiple virtual hosts on a single IP address possible, since the server knows exactly what domain the client wants to access, namely example.com.

HTTPS is different. Like I said earlier, the handshake comes before everything else. If you look at the third step of the handshake illustrated above (Certificate), the server needs to present a certificate to the client as part of the handshake, but has no clue what domain name the client is trying to access. The only option the server has is to send the same certificate every time, its default certificate.

You could still set up virtual hosts on your web server, but the server would always send the same certificate to each client. If you tried to host both the example.com and example.org websites on your server, the server would always send the certificate for example.com when a client requests a HTTPS connection. So when a client requests example.org over an established HTTPS connection, this would happen:



This problem effectively limits the number of domains you can server over HTTPS to one per IP address.

The solution:

The easiest way to solve this problem is for the client to tell the server which domain it wants to access during the handshake. This way the server can serve up the correct certificate.

This is exactly what SNI, or Server Name Indication does.

With SNI, the client sends the server name it wants to access as part of the first message, the "Client Hello" step in the handshake diagram above.

Some older web browsers do not support SNI. For instance, on Windows XP there isn't a single version of Internet Explorer that has support for SNI. When accessing a resource over HTTPS on a server that makes use of SNI virtual hosts, you will be presented with a generic certificate, which may cause the browser to display a warning or error.

references:
https://serverfault.com/questions/109800/multiple-ssl-domains-on-the-same-ip-address-and-same-port

iOS: How to remove unwanted architecture from the framework file

terminal command to do this is below

#!/bin/sh
## Strips unwanted architectures
lipo -remove i386 MyFramework.framework/MyFramework -output MyFramework.framework/MyFramework
lipo -remove x86_64 MyFramework.framework/MyFramework -output MyFramework.framework/MyFramework
rm MyFramework.framework/Modules/MyFramework.swiftmodule/i386.swiftdoc
rm MyFramework.framework/Modules/MyFramework.swiftmodule/i386.swiftmodule
rm MyFramework.framework/Modules/MyFramework.swiftmodule/x86_64.swiftdoc
rm MyFramework.framework/Modules/MyFramework.swiftmodule/x86_64.swiftmodule

references

AWS: How to install Apache httpd on AWS ?

To install Apache, below are the main commands.

sudo yum -y install httpd

to stop and start the server, below given the command

sudo service httpd start 
sudo service httpd stop
sudo service httpd restart   

once the server is installed, the files are in the folder
/var/www/html

the index html file can be replaced to get our own html file.

references:
https://docs.aws.amazon.com/efs/latest/ug/wt2-apache-web-server.html#wt2-apache-web-server-one-ec2-host

Running PHP locally on Mac

Its pretty simple. php installed by default on Mac.

$php -S 127.0.0.1:8080

this to be run on the folder where the index.html is present.
Once the php server is run, the http://127.0.0.1:8080

references:
https://www.youtube.com/watch?v=C_7nJHTdD5c

Flutter creating a horizontal list

Sample is like below

Class MyApp extends StatelessWidget {

@override
Widget build (BuildContext context)
{
  final title = 'MyApp';
  return MaterialApp( title: title, home : Scaffold (appBar: AppBar(title:Text(title)),
  Body : Container (margin: EdgeInsets.symmetric(vertical:20.0, height : 200.0, child:ListView(scrollDirection:Axis.horizontal, children:[Container(width:160.0,color:Color.red),Container(width:160,color:Color.blue)])
}

}

References:
https://flutter.io/cookbook/lists/horizontal-list/

Flutter Lists

A sample is like below

Class MyApp extends StatelessWidget {

@override
Widget build (BuildContext context){

Final title = 'ListTitle';

Return MaterialApp(
 Title : title,
 home : Scaffold(
  appBar : AppBar(title:Text(title)),
  Body : ListView(children : [ListTitle(leading:Icon(Icons.map),title:Text('Map')),ListTitle(title:Text('Album'),leading:Icon(Icons.map))])
 )
);
}
}

References:
https://flutter.io/cookbook/lists/basic-list/

Flutter: Display images from internet

Images.networks {} gives ability to load the image from internet

Also, the GIF format is supported out of the box.

Class MyApp extends StatelessWidget {

@override
Widget build (BuildContext context){
var title = 'Web Images';
return MaterialApp (title:title, home:Scafold(appbar:AppBar{title:Text(title);},body:Image.Network{}));
}
}

App can also fade in images with the below code

FadeInImage.memoryNetwork(
Placeholder:kTramsparentImage,
Image:''
)

This technique can be used for displaying loading bar as well.

For e.g.

FadeInImage.memoryNetwork(
Placeholder:'assets/loading.gif'),


References:
https://flutter.io/cookbook/images/network-image/

Tuesday, October 16, 2018

HTML how to prevent page from reloading on form submit?

Below is how to do that

the key is  e.preventDefault(); to be called

 $('#btn_login').click(function (e) {

        e.preventDefault();
        login();
      });

Flutter how to use custom fonts?

Below are the main steps in using the custom font in a flutter app


    Import the font files
    Declare the font in the pubspec.yaml
    Set a font as the default
    Use a font in a specific Widget

Place the custom font ttf files inside Fonts or assets folder

awesome_app/
  fonts/
    Raleway-Regular.ttf
    Raleway-Italic.ttf
    RobotoMono-Regular.ttf
    RobotoMono-Bold.ttf


In pubspec.yaml file, define the fonts

flutter:
  fonts:
    - family: Raleway
      fonts:
        - asset: fonts/Raleway-Regular.ttf
        - asset: fonts/Raleway-Italic.ttf
          style: italic
    - family: RobotoMono
      fonts:
        - asset: fonts/RobotoMono-Regular.ttf
        - asset: fonts/RobotoMono-Bold.ttf
          weight: 700


Below are the ways it can be used within the app

MaterialApp(
  title: 'Custom Fonts',
  // Set Raleway as the default app font
  theme: ThemeData(fontFamily: 'Raleway'),
  home: MyHomePage(),
);


Text(
  'Roboto Mono sample',
  style: TextStyle(fontFamily: 'RobotoMono'),
);



References:
https://flutter.io/cookbook/design/fonts/

Curl How to send Request with Basic Authorization?

curl --user name:password http://www.example.com 

If you use -u or --user, Curl will Encode the credentials into
Base64 and produce a header like this:
 -H Authorization: Basic

curl -H "Authorization: OAuth " http://www.example.com

If its bearer token, like below the request can be made.

curl -H "Authorization: Bearer " http://www.example.com

references:

https://stackoverflow.com/questions/3044315/how-to-set-the-authorization-header-using-curl

Monday, October 15, 2018

Google Fonts download

Any Official site for downloading some good fonts without much licensing issue?

https://fonts.google.com/

This allows to type in and see various font sizes and download and get small snippets for web etc. 

references:
https://fonts.google.com/

Flutter working with Tabs

Below steps are involved in creating tabs


    Create a TabController
    Create the tabs
    Create content for each tab


Inorder for the tabs to work, one to need to keep the selected tab and the content are in sync. The TabController takes care of this

Below is how one can do that

import 'package:flutter/material.dart';

void main() {
  runApp(TabBarDemo());
}

class TabBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.directions_car)),
                Tab(icon: Icon(Icons.directions_transit)),
                Tab(icon: Icon(Icons.directions_bike)),
              ],
            ),
            title: Text('Tabs Demo'),
          ),
          body: TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );
  }
}

References:
https://flutter.io/cookbook/design/tabs/

Flutter Displaying Snackbars

Below are the three steps involved in providing a snacker UX


    Create a Scaffold
    Display a SnackBar
    Provide an additional action

Below is a complete example of a SnackBar

class SnackBarPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(
        onPressed: () {
          final snackBar = SnackBar(
            content: Text('Yay! A SnackBar!'),
            action: SnackBarAction(
              label: 'Undo',
              onPressed: () {
                // Some code to undo the change!
              },
            ),
          );

          // Find the Scaffold in the Widget tree and use it to show a SnackBar!
          Scaffold.of(context).showSnackBar(snackBar);
        },
        child: Text('Show SnackBar'),
      ),
    );
  }
}


References:
https://flutter.io/cookbook/design/snackbars/


Flutter using Themes

There are two ways to define themes: App-wide or using Theme Widgets that define the colors and font styles for a particular part of our application
n order to share a Theme containing colors and font styles across our entire app, we can provide ThemeData to the MaterialApp constructor.

MaterialApp(
  title: title,
  theme: ThemeData(
    brightness: Brightness.dark,
    primaryColor: Colors.lightBlue[800],
    accentColor: Colors.cyan[600],
  ),
);

Creating unique ThemeData
Theme(
  // Create a unique theme with "ThemeData"
  data: ThemeData(
    accentColor: Colors.yellow,
  ),
  child: FloatingActionButton(
    onPressed: () {},
    child: Icon(Icons.add),
  ),
);

Extending the parent theme
Rather than overriding everything, it often makes sense to extend the parent theme. We can achieve this by using the copyWith method.

Theme(
  // Find and Extend the parent theme using "copyWith". Please see the next
  // section for more info on `Theme.of`.
  data: Theme.of(context).copyWith(accentColor: Colors.yellow),
  child: FloatingActionButton(
    onPressed: null,
    child: Icon(Icons.add),
  ),
);


References:
https://flutter.io/cookbook/design/themes/

Apache Comet

With usage of APR or NIO APIs as the basis of its connectors, Tomcat is able to provide a number of extensions over the regular blocking IO as provided with support for the Servlet API.


Comet support allows a servlet to process IO asynchronously, receiving events when data is available for reading on the connection (rather than always using a blocking read), and writing data back on connections asynchronously (most likely responding to some event raised from some other source).

The section contains the sample code for this https://tomcat.apache.org/tomcat-6.0-doc/aio.html#Example_code

When some event occurs, the event() method is called back. There are multiple event types

CometEvent.EventType.BEGIN => Beginning of the session
CometEvent.EventType.ERROR => If there is any error in the session
CometEvent.EventType.END => end of the Event
CometEvent.EventType.READ => READ event

When the READ event is called back, application can read the stream by using the Input stream method. 

References:
https://tomcat.apache.org/tomcat-6.0-doc/aio.html#Example_code

Sunday, October 14, 2018

jQuery - How to parse the server response as JSON?

Pretty simple.

For dictionaries, below given

var obj = jQuery.parseJSON( '{ "name": "John" }' );
 $.each( appointments, function( key, val ) {
 }

for arrays, it is

var appointments = jQuery.parseJSON( response);
 $.each( appointments, function( index, val ) {
 }

references:
http://api.jquery.com/jquery.parsejson/

jQuery - How to dynamically display table view from JSON response?

function displayAppointmentsInTable(response) {
var table = document.createElement("table");
table.align = 'center';
table.className = 'table table-striped';
table.border = '1px';
var items = [];
var tr = table.insertRow(-1);
//Add Titles for colums
var col = ["Title 1","Title 2","Title 3","Title 4"];
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");      // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
var tr = table.insertRow(-1);
var appointments = jQuery.parseJSON( response);
$.each( appointments, function( index, val ) {
tr = table.insertRow(-1);
var tabCell = tr.insertCell(-1);
tabCell.width = '10%';
var appointmentID = val.bookingID;
tabCell.innerHTML = appointmentID;
tabCell = tr.insertCell(-1);
tabCell.width = '10%';
var displayName = val.fields.name;
tabCell.innerHTML = displayName;
tabCell = tr.insertCell(-1);
tabCell.width = '10%';
var startTime = val.fields.startTime;
tabCell.innerHTML = startTime;
tabCell = tr.insertCell(-1);
tabCell.width = '10%';
var displayName = val.fields.name;
tabCell.innerHTML = "";

});
var divContainer = document.getElementById("appointmentlistingTable");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}

Saturday, October 13, 2018

iOS Swift How to clone a dictionary?

let serverDict =  Dictionary()
var combinedDict = serverDict.merging(rawJSON!) { $1 }

references:

Friday, October 12, 2018

TWilio Integration - High level steps

- Signup with Twilio using email and phone number
- Verification code will be sent to the given phone number
- Once the signup is complete, login to see the project template
- for e.g. if interested in the video conferencing, select the video conferencing from the template page
- This will take to programmable video. Now select on the Settings from the right top menu
- under the tools section, there are there are 3 options
- Testing tools will allow to create access token if needed one to test
- API keys is needed for calling REST apis and as well can be used for signing access tokens
- Credentials - Credentials allow you to upload and manage third-party provided and self-issued credentials.


How to Install CPanel on AWS

The steps are

sudo curl -o latest https://securedownloads.cpanel.net/latest

This downloads the channel package on to the machine. Now just run it to install
sudo sh latest

1. Open your preferred browser
2. Type https://ipaddress:2087 in the address bar
3. Enter the word root in the Username text box
4. Enter your root password in the Password text box
5. Click the Login button

Visit https://go.cpanel.net/whminit for more information about first-time configuration of your server

this may require the root password to be changed. the detail to how to do it is given in the video.


references:
https://www.youtube.com/watch?v=DVwm5Y6eO9c

How to launch an EC2 Instance?

This is pretty easy. Just follow the link contents in references:

Couple of things to note are:

- Remember to select the instance which is most suitable, for e.g. if need php environment, there is an instance which is coming preloaded with it. Although it is possible to install post the instance is launched

- The Security rules to be updated to make sure the port to be publicaly available is exposed.


references:
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Tutorials.WebServerDB.CreateWebServer.html

AnyDesk - Another remote sharing software

This is an awesome tool for any practical desk sharing purposes. the download size is just under 5MB and quick to share the desk contents.


references:
https://anydesk.com/remote-desktop

iOS what is UITextFieldInput view?

The custom input view to display when the receiver becomes the first responder.

This property is typically used to provide a view to replace the system-supplied keyboard that is presented for UITextField and UITextView objects.
The value of this read-only property is nil. A responder object that requires a custom view to gather input from the user should redeclare this property as read-write and use it to manage its custom input view. When the receiver becomes the first responder, the responder infrastructure presents the specified input view automatically. Similarly, when the receiver resigns its first responder status, the responder infrastructure automatically dismisses the specified input view.

references:
https://developer.apple.com/documentation/uikit/uiresponder/1621092-inputview

Thursday, October 11, 2018

Node JS, How to decode base64 data?

Base64 encoding is a way to convert data (typically binary) into the ASCII character set. It is important to mention here that Base64 is not an encryption or compression technique, although it can sometimes be confused as encryption due to the way it seems to obscure data. In fact, size of a Base64 encoded piece of information is 1.3333 times the actual size of your original data.

Base64 is the most widely used base encoding technique with Base16 and Base32 being the other two commonly used encoding schemes.


Encoding Base64 Strings with Node.j

The easiest way to encode Base64 strings in Node.js is via the Buffer object. In Node.js, Buffer is a global object which means that you do not need to use require statement in order to use Buffer object in your applications.

Internally Buffer is an immutable array of integers that is also capable of performing many different encodings/decodings. These include to/from UTF-8, UCS2, Base64 or even Hex encodings. As you write code that deals with and manipulates data, you'll likely be using the Buffer object at some point.
The code is seen in the previous post. Below section explain how to decode


Decoding Base64 Strings with Node.js

Decoding Base64 string is quite similar to encoding it. You have to create a new buffer object and pass two parameters to its constructor. The first parameter is the data in Base64 and second parameter is "base64". Then you simply have to call "toString" on the buffer object but this time the parameter passed to the method will be "ascii" because this is the data type that you want your Base64 data to convert to. Take a look at the following code snippet for reference.


'use strict';

let data = 'c3RhY2thYnVzZS5jb20='; 
let buff = new Buffer(data, 'base64'); 
let text = buff.toString('ascii');

console.log('"' + data + '" converted from Base64 to ASCII is "' + text + '"'); 


Decoding Base64 Strings to Binary Data

The reverse process here is very similar to how we decode Base64 strings, as we saw in an earlier section. The biggest difference is the output destination and how data is written there. Let's see the example:

'use strict';

const fs = require('fs');

let data = 'iVBORw0KGgoAAAANSUhEUgAAABkAAAATCAYAAABlcqYFAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAA' + 
'CA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAACXBIWXMAAAsTAAALEwEAmpwYAAABWWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0' + 
'YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly' +

let buff = new Buffer(data, 'base64'); 
fs.writeFileSync('stack-abuse-logo-out.png', buff);

console.log('Base64 image data converted to file: stack-abuse-logo-out.png');


References:
https://stackabuse.com/encoding-and-decoding-base64-strings-in-node-js/

Wednesday, October 10, 2018

How do we add Digest Authentication to the http requests in Node JS?

Here’s an easy way to use basic authentication while using the request library for Node.js.

Unfortunately request doesn’t come with an easy convenience parameter you can use, so you need to provide it by yourself. The common way is to add it as an extra HTTP header.

Let’s say you need to login to example.com using user and pass as your username/password.

var request = require('request'),
    username = "john",
    password = "1234",
    url = "http://www.example.com",
    auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

request(
    {
        url : url,
        headers : {
            "Authorization" : auth
        }
    },
    function (error, response, body) {
        // Do more stuff with 'body' here
    }
);

References:
https://www.haykranen.nl/2011/06/21/basic-http-authentication-in-node-js-using-the-request-module/

What are the X-Forwarded-Proto and X-Forwarded-For headers?

The X-Forwarded-Proto (XFP) header is a de-facto standard header for identifying the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer. Your server access logs contain the protocol used between the server and the load balancer, but not the protocol used between the client and the load balancer. To determine the protocol used between the client and the load balancer, the X-Forwarded-Proto request header can be used.

The X-Forwarded-For (XFF) header is a de-facto standard header for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or a load balancer. When traffic is intercepted between clients and servers, server access logs contain the IP address of the proxy or load balancer only. To see the original IP address of the client, the X-Forwarded-For request header is used.

This header is used for debugging, statistics, and generating location-dependent content and by design it exposes privacy sensitive information, such as the IP address of the client. Therefore the user's privacy must be kept in mind when deploying this header.

A standardized version of this header is the HTTP Forwarded header.

X-Forwarded-For is also an email-header indicating that an email-message was forwarded from another account.

references:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For

Tuesday, October 9, 2018

Node JS. How to append to file instead of overwriting?

below is the code snippet for it

const fs = require('fs');
fs.appendFile('messages.txt', 'data to append', function(error) {
  if(!err) {
     console.log('Appended to file');  
   }
});

references:
https://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node

What is Port Forwarding?

Port forwarding is a process of configuring a router to make a computer or other network device that is connected to it accessible from other computers and network devices from outside of the local network. Port forwarding uses IP address + Port number to route the network requests to the specific devices.

references:
https://www.youtube.com/watch?v=-K6jMYBfuIY

What is Ngrok?

Ngrok is a multiplatform tunneling, reverse proxy software that establishes secure tunnels from a public end point such as internet to a locally running service capturing all the traffic for detailed inspection and replay.

Before using ngrok, when we needed to expose a localhost application to web (internet) all we were doing is deploying the application in a server running a DMZ or we used to relocate the host to DMZ and configure NATing in the firewall. We also used to make DNS configuration in External DNS where the domain is hosted. In general, DMZ (De-Militarized Zone) is a computer host or small network inserted as a “neutral zone” between a company’s private network and the outside public network. It prevents outside users from getting direct access to a server that has company data. The following are the issues that we were facing before Ngrok deployment:

    Unable to expose localhost application directly to internet without DMZ & other network configuration
    Unable to demonstrate an application to Client on urgent basis
    Unable to share websites for testing purpose
    Develop any services which consume Webhooks (HTTP CallBacks)
    Can’t share a website temporarily that is running only on our developer machine
    Time Consuming on network and DNS configurations
    Can’t debug or inspect HTTP Traffic in a precise manner
    Can’t run networked services on machines that are firewalled off from the internet
    Unable to expose application behind http proxy
    Unable to forward non-http and non-local network services

references:
https://vmokshagroup.com/blog/expose-your-localhost-to-web-in-50-seconds-using-ngrok/

Http POST request in NodeJS

To make http POST request in NodeJS, below can be done

var https = reqiuire('https');

 function makePOSTRequest() {
   var postData = {'key' : 'value'}
   var postOptions = {'host' : 'testserver.com','port' : '8080','path' : '/testpath','method' : 'POST',
   headers : {
      'Content-Type' : 'application/json',
      'Content-Length' : Buffer.byteLength(postData);
    } }

   var post_req = https.request(postOptions,function(res) {
       res.setEncoding('utf8');
       res.on('data', function(chunk) {
          console.log('chunk is '+chunk)
       })

   })

}

references:
https://stackoverflow.com/questions/6158933/how-to-make-an-http-post-request-in-node-js

Monday, October 8, 2018

Java static Method import

this was interesting to see the method is directly imported. This is possible for variables and functions those are static.

import static com.github.florent37.materialviewpager.Utils.canScroll;
import static com.github.florent37.materialviewpager.Utils.colorWithAlpha;
import static com.github.florent37.materialviewpager.Utils.dpToPx;
import static com.github.florent37.materialviewpager.Utils.getTheVisibileView;
import static com.github.florent37.materialviewpager.Utils.minMax;

However, there seems to be no performance impact or advantage due to this

references:
https://stackoverflow.com/questions/18825640/are-there-any-advantages-of-using-static-import-over-import

Sunday, October 7, 2018

Android How to give slide up/down animation with Activity

 Define an animation in res/anim/slide_in_up.xml:


    android:fromYDelta="100%p" android:toYDelta="0%p"
    android:duration="@android:integer/config_longAnimTime"/>
and another at res/anim/slide_out_up.xml:


    android:fromYDelta="0%p" android:toYDelta="-100%p"
    android:duration="@android:integer/config_longAnimTime"/>
Then apply these after to call startActivity:

Intent i2 = new Intent(main.this, test.class);
startActivity(i2);
overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );

references:
https://blog.stylingandroid.com/simple-animation-part-1/

What is CPanel?

cPanel is an online Linux-based web hosting control panel that provides a graphical interface and automation tools designed to simplify the process of hosting a web site. cPanel utilizes a three-tier structure that provides capabilities for administrators, resellers, and end-user website owners to control the various aspects of website and server administration through a standard web browser.

In addition to the GUI, cPanel also has command line and API-based access that allows third-party software vendors, web hosting organizations, and developers to automate standard system administration processes.[4]

cPanel is designed to function either as a dedicated server or virtual private server. The latest cPanel version supports installation on CentOS, Red Hat Enterprise Linux (RHEL), and CloudLinux OS.[5] cPanel 11.30 is the last major version to support FreeBSD.[6][7]

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

Thursday, October 4, 2018

How to get preview image from Youtube link?

This below one should be good enough

https://img.youtube.com/vi/f1qz8vn3XbY/0.jpg

However, there are also links upto 4
https://img.youtube.com/vi/f1qz8vn3XbY/1.jpg
https://img.youtube.com/vi/f1qz8vn3XbY/2.jpg
https://img.youtube.com/vi/f1qz8vn3XbY/3.jpg


references:
https://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api

How to edit cloud functions online?

the quickest way is to login to the account and use the below link. This gives a way to list all the cloud functions on the account and let us edit quickly.

https://console.cloud.google.com/functions/list


references:
https://firebase.google.com/docs/functions/

Picasso Android Some tips

To invalidate a particular image cache
Picasso.with(getApplicationContext()).invalidate(getProfileImageURL());

To clear all cache contents
Picasso.with(context).cache.clear()

To explicitly set the cache policy
Picasso.with(context).load(uri).networkPolicy(NetworkPolicy.NO_CACHE)
        .memoryPolicy(MemoryPolicy.NO_CACHE)
        .placeholder(R.drawable.bv_logo_default).stableKey(id)
        .into(viewImage_imageView);

Monday, October 1, 2018

Whats the easiest way to detect links on Android text view and launch web browser?

Just have the below !

    android:text="www.google..com"
    android:id="@+id/tv_linkable"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:autoLink="web"
    android:linksClickable="true">



references:
https://stackoverflow.com/questions/6910703/android-active-link-of-url-in-textview