Tuesday, November 5, 2019

Unknown failure (at android.os.Binder.execTransact(Binder.java:674)) Error while Installing APKs



I had this issue when I was trying to run the android application from android studio.

Unknown failure (at android.os.Binder.execTransact(Binder.java:674))
Error while Installing APKs


This issue occurs because of android's Instant run feature. You need to disable this feature to overcome this issue.

To disable Instant Run:


  1. Open the Settings or Preferences dialog. (For Mac, Android Studio -> Preferences)
  2. Navigate to Build, Execution, Deployment > Instant Run.
  3. Uncheck the box next to Enable Instant Run.


Saturday, November 2, 2019

Python AttributeError: 'module' object has no attribute 'strptime'

This type of error occurs when the strptime method called on module instead of class:

If your import statement is like below :

import datetime
Then you need to access strptime method like below:
datetime.datetime.strptime(date, "%Y-%m-%d")
to access the strptime method. Or, you could change the import statement to this:
from datetime import datetime
and access it as you are.
The people who made the datetime module also named their class datetime:
#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")
Ref: https://stackoverflow.com/questions/19480028/attributeerror-datetime-module-has-no-attribute-strptime

Wednesday, January 3, 2018

Android Open Phone Dialer from Code


There are Two ways to achieve it.

 1) Have to start the dialer via code, without user interaction. 

 You need Action_Dial, use below code it will open Dialer with number specified.

Intent intent = new Intent(Intent.ACTION_DIAL); 
intent.setData(Uri.parse("tel:0123456789")); 
startActivity(intent);

The 'tel:' prefix is required, otherwhise the following exception will be thrown:

java.lang.IllegalStateException: Could not execute method of the activity. Action_Dial doesn't require any permission. If you want to initiate the call directly without user's interaction , You can use action Intent.ACTION_CALL.

In this case, you must add the following permission in your AndroidManifest.xml:

<uses-permission android:name="android.permission.CALL_PHONE">
</uses-permission>

2) Have user to click on Phone_Number string and start the call. 

android:autoLink="phone" 

You need to use TextView with below property.
android:autoLink="phone" android:linksClickable="true"

This is how you can open EditText label assigned number on dialer directly.
<TextView
 android:id="@+id/phoneNumber"
 android:autoLink="phone"
 android:linksClickable="true"
 android:text="+91 22 2222 2222"
 />
Ref: https://stackoverflow.com/questions/11699819/how-do-i-get-the-dialer-to-open-with-phone-number-displayed

Saturday, December 23, 2017

Apply Border color to button on Android


Use the <stroke> element. Add this xml file in res/drawable folder as button_border.xml:



<?xml version="1.0" encoding="utf-8"?>
  <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:startColor="#FFFFFF" 
       android:endColor="#00FF00"
       android:angle="270" />
    <corners android:radius="3dp" />
    <stroke android:width="5px" android:color="#ffffff" />
 </shape>

then call this by in layout file

 
<Button
   android:id="@+id/button1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_margin="10dp"
   android:background="@drawable/button_border"
   android:text="Button" 
/>

Forcing “portrait” orientation mode for android application

Adding following code segment in AndroidManifest file for each activity, we can force the android application to work only in portrait mode.

Note: Don't apply the orientation to the application element, instead you should apply the attribute to the activity element, and you must also set configChanges as noted below.


<activity
   android:screenOrientation="portrait"
   android:configChanges="orientation|keyboardHidden">
</activity>

Monday, December 18, 2017

Java Interview Question: HashSet vs HashMap

HashSet

  1. HashSet class implements the Set interface
  2. In HashSet, we store objects(elements or values) e.g. If we have a HashSet of string elements then it could depict a set of HashSet elements: {“Hello”, “Hi”, “Bye”, “Run”}
  3. HashSet does not allow duplicate elements that mean you can not store duplicate values in HashSet.
  4. HashSet permits to have a single null value.
  5. HashSet is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly. 

HashMap


  1. HashMap class implements the Map interface
  2. HashMap is used for storing key & value pairs. In short, it maintains the mapping of key & value (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This is how you could represent HashMap elements if it has integer key and value of String type: e.g. {1->”Hello”, 2->”Hi”, 3->”Bye”, 4->”Run”}
  3. HashMap does not allow duplicate keys however it allows having duplicate values.
  4. HashMap permits single null key and any number of null values.
  5. HashMap is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly. 

Friday, December 15, 2017

How to handle HTTP Header related issue in Apache


By following below steps you can suppress following HTTP Header related security issues in web applications those are hosted in apache web server.
  • Web Browser XSS Protection Not Enabled
  • X-Frame option Header not set
  • X-Content-Type-Options header missing  
  • Incomplete or No Cache-control and Pragma HTTP Header Set


These issues can be handled by placing following lines in httpd.conf of apache web server.

Header set X-XSS-Protection “1; mode=block”
Header set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
Header always append X-Frame-Options DENY
Header set X-Content-Type-Options nosniff
Header set Content-Security-Policy "default-src 'self';"



For this mod_hedaers module also need to be enabled. so uncomment the following Load Module line:

LoadModule headers_module modules/mod_headers.so


Now doing security audit test again, you can see these issues are handled properly. 

Handling HTTP Header related security issues in Tomcat 8 web applications


The following issues are the commonly occurs in security audit report of any java web applications

  • Web Browser XSS Protection Not Enabled
  • X-Frame option Header not set
  • X-Content-Type-Options header missing  
  • Incomplete or No Cache-control and Pragma HTTP Header Set

Tomcat 8 provides, support for following http header 


  • X-Frame-Options – to prevent clickjacking attack
  • X-XSS-Protection – to avoid cross-site scripting attack
  • X-Content-Type-Options – block content type sniffing
  • HSTS – add strict transport security

To utilize this option we need to follow simple steps. Just uncomment the following lines in Tomcat's web.xml files (\conf\web.xml).

<filter>
     <filter-name>HeaderSecurityFilter</filter-name> 
     <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
 </filter>
<filter-mapping>
      <filter-name>HeaderSecurityFilter</filter-name>
      <url-pattern>/*</url-pattern>
 </filter-mapping>

Remember it is not applications individual web.xml files. it is tomcat's web.xml. after uncommenting these lines. restart the tomcat and redo the security audit. you can see the issues are handled.

Friday, October 13, 2017

'gradle' is not recognized as an internal or external command

Following steps need to be followed for fixing: "'gradle' is not recognized as an internal or external command" error.

  1.  Download the zipped file of Gradle from https://services.gradle.org/distributions/gradle-2.8-all.zip. 
  2. Unzip them and place them in your Windows machine at any specific location. For e.g. “C:\Program Files\”. 
  3. Click on the Windows button at the left bottom of the desktop. 
  4. Right-click on “Computer” and click on “Properties”. This will open the Control Panel. 
  5. Click on “Advanced System settings” and then click on “Environment Variables” button. 
  6. Click on “New…” button under the “System Variables” section and enter Variable name as ‘GRADLE_HOME’. 
  7. Provide the path of the Gradle file as Variable value, i.e. C:\Program Files\gradle-2.8 
  8. Click OK. 
  9. Select “path” variable under the “System Variables” section and click on “Edit” button. 
  10. Go to the end of variable value and add “;%GRADLE_HOME%\bin” and click on “OK” button. 
  11. Press “Windows + R” and type ‘cmd’. Click OK. 
  12. Type the command “gradle –v” on the command prompt. 
  13. Now the screen displays the version of the Gradle. This means that the Gradle is successfully configured on the given Windows machine.

Saturday, March 26, 2011

Escape Special chracters in java

Following code escaps the special meaning of characters before showing in XML or in view

 public static String escapeText(String s) {
   
    if (s.indexOf('&') != -1 || s.indexOf('<') != -1
     || s.indexOf('>') != -1 || s.indexOf('"') != -1
     || s.indexOf('\'') != -1 ) {
      StringBuffer result = new StringBuffer(s.length() + 6);
      for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c == '&') result.append("&amp;");
        else if (c == '<') result.append("&lt;");
        else if (c == '"') result.append("&quot;");
        else if (c == '\'') result.append("&apos;");
        else if (c == '>') result.append("&gt;");
        else result.append(c);
      }
      return result.toString();  
    }
    else {
      return s;   
    }
        
  }

Tuesday, January 18, 2011

HTML 5 logo unveiled by W3C

HTML5Imagination, meet implementation. HTML5 is the cornerstone of the W3C's open web platform; a framework designed to support innovation and foster the full potential the web has to offer. Heralding this revolutionary collection of tools and standards, the HTML5 identity system provides the visual vocabulary to clearly classify and communicate our collective efforts.


W3C unveiled today an HTML5 logo, a striking visual identity for the open web platform. W3C encourages early adopters to use HTML5 and to provide feedback to the W3C HTML Working Group as part of the standardization process. Now there is a logo for those who have taken up parts of HTML5 into their sites, and for anyone who wishes to tell the world they are using or referring to HTML5, CSS, SVG, WOFF, and other technologies used to build modern Web applications. The logo home page includes a badge builder (which generates code for displaying the logo), a gallery of sites using the logo, links for buying an HTML5 T-shirt, instructions for getting free stickers, and more. The logo is available under "Creative Commons 3.0 By" so it can be adapted by designers to meet their needs.

Wednesday, January 5, 2011

Updating(Replace) anchor href values in a webpage

Using the jquery One can update attribute values of html elements in a simple steps .
The following jquery script will update the href value of all the anchor links those
 available in a web page to a static url http://www.tecrocks.com.

$('a[href]').attr('href', 'http://www.tecrocks.com');

This will be helpful for the situation like displaying the webpage content in a custom print preview page like so.
The following block will update all the href value in page without considering the element of the href value.

$('[href]').each(function () {
  $(this).attr('href', 'http://www.tecrocks.com');
});

Using *= filders with in [] we can filter the href url's.

Tuesday, January 4, 2011

Truncating(Clip) Excess text with Ellipsis in HTML5

      Text-overflow property in CSS gives the way to deal with the clipped text when the actual text content size is exceed the container box.
      'text-overflow' css attribute allows the text to be clipped when its exceed the allowed display area by setting text-overflow value as ellipsis, it will display ellipsis( three periods) following the clipped text.

.cliptext 
       {
            color: #eee;
            border: 1px solid #000000;
            overflow: hidden;
            width: 100%;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

To get this ellipsis effect when the content fall outside the box you may need to set the boxs overflow property to hidden or scroll and white-space  property to  'nowrap'.

If you have any comments or suggestions in setting ellipsis please leave a comment.

Wednesday, November 24, 2010

Generate a random alpha-numeric string in Java

By combinig use of Char array that having alphabets and numbers are an string of alphanumberic characters we can generate random alpha numberic strings in java.here is the exampls code that generate random alpha numberic string for the given length.

 /**
     * Generates alpha numeric random number for the given length.
     * for this it accounts lowercase alpha characters(a-z) and numbers(0-9)
     * @param length length of the alpha numeric random to be generated.
     * @return resulting random alpha numeric string for the given length.
     */
    public static String getAlphaNumbericRandom(int length) {
        //include lower case alpha(a-z) and numbers(0-9)
        String chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        int numberOfCodes = 0;//controls the length of alpha numberic string
        String code = "";
        while (numberOfCodes < length) {
            char c = chars.charAt((int) (Math.random() * chars.length()));
            code += c;
            numberOfCodes++;
        }
        System.out.println("Code is :" + code);
        return code;
    }

If we want to create 6 digit apha numberic random means we have call getAlphaNumbericRandom methods as

getAlphaNumbericRandom(6);

Wednesday, October 20, 2010

Format Source Code for Blogging


Here is the interface to change your source code for put in blogging environments. This escapes the html tags so you can display your source codes in blogs




Tab size: 2 4 8

Embed Stylesheet:

Copy the HTML below to your clipboard. Insert the HTML of your blog or wiki.

This is an example of what your text will look like.
    • Tabs are converted to spaces.
    • Quotes and other special characters are converted to HTML.
    • Everything is enclose in HTML's 'pre' and 'code' tags.
    • Style is set:
        • Fixed width font.
        • Shaded box.
        • Dotted line border.
 

Source :formatmysourcecode.blogspot.com

Wednesday, September 8, 2010

Disable Enter key in Form tag

Placing the following code in your page section will disable the enter key operation in text field



 <script type="text/javascript">   
 function stopRKey(evt) {   
  var evt = (evt) ? evt : ((event) ? event : null);   
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);   
  if ((evt.keyCode == 13) && (node.type=="text")) {return false;}   
 }   
 document.onkeypress = stopRKey;   
 </script>  
Source : http://www.webcheatsheet.com

Saturday, September 4, 2010

Redirect Action result to another action in struts2

Using special result type in Struts-2 result we can forward one actions result to another action before forwarding it to view logic.
"redirect-action" result type is used to achieve this.here is the sample code snippet to show how to redirect one actions result to another action


 <action name="userInfo" class="UserAction">  
  <!-- Redirect to another namespace -->  
  <result type="redirect-action">  
   <param name="actionName">getDetails</param>  
   <param name="userId">${userId}</param>  
  </result>  
 </action>  

Here after finishing userInfo action getDetails action will be invoked.Here by using "Param" tags we can pass the values to the getDetails action.

Wednesday, August 25, 2010

Displaying Current Date using Javascript

We can get the current date using the javascript build-in functions. To get the current date we have to use

 var dt new Date()  

in javascript.This creates one date type variable which holds all the date related informations like date,moth,year,time etc,.
Displaying this in any component or in alert will give information like

 Wed Aug 25 2010 13:42:41 GMT+0530 (India Standard Time)  

There are various methods are available in javascript to get the details only what we needed from this .We can use these methods like

 dt.getMonth();  
 dt.getDate();  

First one(getMonth()) gives only current month(0-11),getDate() gives the current date.Here is the sample to get MM/DD/YYYY for the current date in javascript

   var curr_date=new Date();   
   var month=curr_date.getMonth()+1;  
   var day=curr_date.getDate();  
   var year=curr_date.getYear();  
   // Y2K compliant  
   if (year < 1000) year +=1900;  
   document.getElementById(component).value = month + "/" + day + "/" + year;  


In this the getYear() method will return non Y2K compliant year(110 for 2010 ! ) to make this Y2K complian ,we need to add 1900 with that.

Wednesday, August 18, 2010

Creating a ZIP file in JAVA

Using ZipOutputStream and  Class in java.util.zip package we can craete an zip entry for the list of files.
The following gives the sample to create an zip file "outfile.zip" .This zip whill be created using the contents those given in the 'filenames' array.

1:  // These are the files to include in the ZIP file  
2:  String[] filenames = new String[]{"filename1", "filename2"};  
3:  // Create a buffer for reading the files  
4:  byte[] buf = new byte[1024];  
5:  try {  
6:    // Create the ZIP file  
7:    String outFilename = "outfile.zip";  
8:    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));  
9:    // Compress the files  
10:    for (int i=0; i<filenames.length; i++) {  
11:      FileInputStream in = new FileInputStream(filenames[i]);  
12:      // Add ZIP entry to output stream.  
13:      out.putNextEntry(new ZipEntry(filenames[i]));  
14:      // Transfer bytes from the file to the ZIP file  
15:      int len;  
16:      while ((len = in.read(buf)) > 0) {  
17:        out.write(buf, 0, len);  
18:      }  
19:      // Complete the entry  
20:      out.closeEntry();  
21:      in.close();  
22:    }  
23:    // Complete the ZIP file  
24:    out.close();  
25:  } catch (IOException e) {  
26:  }  

Source : http://www.exampledepot.com