Recent Posts

Sunday 22 November 2015

Creating Views in android in loops ( Java )

Here goes a small code for looping in android using java.

Layout to which we add views

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent" android:layout_height="wrap_content"
  android:orientation="vertical" android:id="@+id/content">
</LinearLayout>



Lets create views in for loop and add to above layout

LinearLayout content=(LinearLayout)findViewById(R.id.content);

int[5] x={1,2,3,4,5};
for(int i:x)
{
  Button butn=new Button(getApplicationContext());
  butn.setTag(i);       // used for identifying individually each button 
 content.addView(butn);
}

Sunday 6 September 2015

Compressing images as like WhatsApp in Android



package com.smartapps.ImageResolution;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Details extends ActionBarActivity {
    File profile_pic_file;
    SharedPreferences pref;
    ImageView preview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        pref = getSharedPreferences("log_account", 0);
        String user_name = pref.getString("user_name", null);

        if (user_name == null)
            // Creating the profile pic file
            try {
                File dir = getExternalFilesDir(null);
                File _dir = new File(dir, "LocalStorage");
                if (!_dir.exists()) _dir.mkdir();

                profile_pic_file = new File(_dir, "profile.jpg");
                if (!profile_pic_file.exists()) profile_pic_file.createNewFile();
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }

        preview = (ImageView) findViewById(R.id.preview_image);
        ImageButton image_select = (ImageButton) findViewById(R.id.image_select);
        Button save_butn = (Button) findViewById(R.id.save_butn);

        image_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent image_select = new Intent();
                image_select.setAction(Intent.ACTION_PICK);
                image_select.setType("image/*");
                startActivityForResult(image_select, 1);
            }
        });// end of the select_image button

        save_butn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }); // end of the Save Button

    }

    private String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        cursor.moveToFirst();
        int column = cursor.getColumnIndex(projection[0]);
        String path = cursor.getString(column);
        cursor.close();
        return path;
    }

    @Override
    protected void onActivityResult(int req_code, int res_code, Intent data) {
        if (req_code == 1)
            if (res_code == RESULT_OK) {
                String path = getPath(data.getData());
                try {
                    File file = new File(path);
                    FileInputStream fis = new FileInputStream(file);
                    byte[] bytes_data = new byte[(int) file.length()];
                    fis.read(bytes_data);fis.close();
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;

                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes_data, 0, bytes_data.length, options);
                    int w = options.outWidth,h=options.outHeight, insampleSize = 1;

                    if(h>w){ insampleSize=getSample(h,false); }
                    else { insampleSize=getSample(w,true); }

                    if(insampleSize!=1){
                        options.inSampleSize=insampleSize;
                        options.inJustDecodeBounds = false;

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        bitmap = BitmapFactory.decodeByteArray(bytes_data, 0, bytes_data.length, options);
                        bitmap.compress(Bitmap.CompressFormat.JPEG,25,bos);

                        FileOutputStream fos = new FileOutputStream(profile_pic_file);
                        fos.write(bos.toByteArray());fos.flush();fos.close();
                    }
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

        if (req_code == 2)
            if (res_code == RESULT_OK) {
                ByteArrayOutputStream bos=new ByteArrayOutputStream();
                Bitmap bm=data.getExtras().getParcelable("data");
                bm.compress(Bitmap.CompressFormat.JPEG,25,bos);
                try {
                    FileOutputStream fos=new FileOutputStream(profile_pic_file);
                    fos.write(bos.toByteArray());fos.flush();fos.close();
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();}
                finally {
                    preview.setImageBitmap(bm);
                }
            }
    }

    private int getSample(int x,boolean isWidth){
        int u=1;
        if(isWidth)
        {
            if(x>1000) u=x/1000;
        }
        else{
            if(x>350) u=x/350;
        }
        return u;
    }
}

Tuesday 30 June 2015

Finding Factorial using the BigInteger in JAVA

Up to Schooling we may only find factorial up to 25 but in real engineering we may have to deal with the largest numbers where the usual datatypes may not work. In Java , BigInteger is the pre-defined class we use in order to deal with those numbers.

Here in our example, using BigInteger we are finding factorial for larger Numbers.

import java.lang.*;
import java.util.Scanner;
import java.math.BigInteger;

public class HelloWorld {
    @ SuppressWarnings ("deprication")
    /*  The above line suppress the deprication warnings */
    public static void main(String[] args) {
    try{
        Scanner sc=new Scanner(System.in);
        int tests=Integer.parseInt(sc.next());
        BigInteger num,sum;
        String res;
        while(tests--!=0)
        {
        sum=new BigInteger("1");
        num=new BigInteger(sc.next());
        while(num.compareTo(new BigInteger("0"))!=0){
        sum=sum.multiply(num);
        num=num.subtract(new BigInteger("1"));
        }
        res+=sum+"\n";
        }
        System.out.println(res);
    }
    catch(Exception e){ System.out.println(e.getMessage()); }
    }
}

Converting Numbers to Different Numerical Systems in JAVA

You may have to change the numbers from one format to other format, as like from decimal to hexagon . Here i have tried the different approach where you can convert from one numerical system to other numerical system using the digits in that numerical system.

For Example , if i want to convert the 10 from decimal to hexagon. I will provide the input in the following format along with the number of Test Cases.
1
# input1: 10 0123456789 0123456789abcdef
# output: a

Here is the logic for that written in JAVA language.

import java.lang.*; import java.util.*; public class Numbers{ @ SuppressWarnings ("deprication") public static void main(String[] args) { String result=""; Scanner sc=new Scanner(System.in); int i=0,tests=Integer.parseInt(sc.next()); while(i++<tests){ String numbr=sc.next(); String source_pattern=sc.next(); String target_pattern=sc.next(); Number_System source=new Number_System(source_pattern); Number_System target=new Number_System(target_pattern); result=result+"Case #"+i+": "+target.genValue(source.genDeciValue(numbr))+"\n"; } System.out.print(result); } } class Number_System{ int len=0; String pattern; public Number_System(String seq){ len=seq.length(); pattern=seq; } public int genDeciValue(String x){ int i=0,v,str_len=x.length(); Double value=new Double(0.0); while(i<str_len){ v=pattern.indexOf(x.charAt(str_len-i-1)); value=v*Math.pow(len,i)+value; i++; } return value.intValue(); } public String genValue(int x){ String res=""; while(x!=0) { if(x<len){ res=pattern.charAt(x)+""+res; break; } res=pattern.charAt(x%len)+""+res; x=x/len; } return res; } }

Sunday 7 June 2015

Validating IPAddress in Java

This is the part of the java Regular Expressions, Validating,searching the data using the matches function This is mostly used in analyzing the data. To know further about it read about JAVA Regex  

import java.io.*;

public class ValidIP{

     public static void main(String []args){
       String IP="000.12.12.034";
       String pat="(([01]?(\\d)?(\\d))|([2]?([012345])?([012345])))";
       String pattern=pat+"."+pat+"."+pat+"."+pat;
       System.out.println(IP.matches(pattern));
     }
}

Sunday 31 May 2015

Basic Steps to Create your WebSite

WebServer: The computer which serves the requests from the client (webbrowser) is called webserver.

 WebClient: The computer from which the clients request the services (webpage) is called webClient. The application used in webclient to access the webserver is called WebServer.

 To make the business, internet is the best market place. Setting up the website is the basic step for online business.

Today we are going to learn about How to setup the website ? We can setup the website in 3 steps.

1.) Register your domain :Domain name is the virtual address to your website. Generally to access the webserver we use ipaddress of the server, but for humans it was difficult to remember numbers than alphabets . So we register our static ipaddress with the corresponding alphabatics. Those are called Domain Names.
                               Eg: www.google.com   www.blogger.com  

2.) Prepare your hosting area : Hosting means storing your files in the system whose ipaddress is registered for Domain Name. This can be done in two ways :
  1. Creating your server
  2. Buying Hosting area ( www.godaddy.com )
3.) Linking your hosting and domain : Login to your domain name provider website, select your domain name and now activate it by updating the name servers provided by the hosting website / update name servers with your hosting system in case of own hosting system.

  Testing the system : After linking the domain, it takes minimum 15 min and max 1 day for activate your system. Create the file with name "index.html" and in that file write "Its working" and place it in public_html folder.

 Now enter your domain in the browser and click enter to see "Its working".


    I hope you understand the basic steps. If any doubts please comment it.

Tuesday 26 May 2015

Executing C program in android mobile using terminal IDE

While studying about the android software stack . I got to know that the base is linux terminal . So I got one idea doubt if we can run the C program .
Yes of course we can execute the C program in android mobile using the app Terminal IDE ,which lets us to access the Linux terminal in our android mobile.

Here are the steps to download, install the terminal IDE in your mobile and executing C program.
First Step : Install the Terminal IDE app in your android mobile phone, which lets you to access your linux terminal in android mobile.

Second Step : Open the terminal IDE and select the option Install System.



Third Step : Now press back and select the Terminal IDE option to access your terminal IDE.Now navigate to the system folder and then to src folder, where this app is having the permissions to execute the file. To navigate to that directory type the command cd system/src . And also create the directory code where we are going to store our code using the command mkdir code


Fourth Step : Its now time to create the C program file, here i am creating the file test.c file and placing the code for "Hello World" program .Before that navigate to code folder using cd code . Commands to create and write the code are cat>test.c.

Fifth Step : Now in the terminal list select the another terminal other than Terminal 1 .


Sixth Step : We have to install the terminal GCC for compiling and executing the C Program. To install the terminal GCC type the command install_gcc .


Seventh Step : Its time for us to compile and execute the C program. Lets do that in three steps.
  1. terminal-gcc -c test.c
  2. terminal-gcc test.o -o test
  3. ./test

Tuesday 19 May 2015

Fetching the data from MYSQL server using PHP prepared Statements

Generally developers use the prepared statement in order to connect to the MYSQL server in order to prevent the SQL Injections from the hackers from the user forms.

Here is the code for connecting to the server and selecting the database.
Here i am using the database "newsonspot". Place the bellow code in connect.php

//connect.php
<?php
$con=new mysqli(host_name,username,password,"newsonspot");
?>

//Code for retriving the data using PHP prepare statements.Here i am getting the email ID of the person whose username is "smartsiva" (Select.php)

<?php
require("connect.php");
if($u_data=$con->prepare("SELECT email FROM users WHERE uname=? "))
{
 $u_data->bind_param("s","smartsiva");
 $u_data->bind_result($ema);
 $u_data->execute();
 while($row=$u_data->fetch()){
 echo $ema;
 }
}

In bind_param() function first parameter is the datatypes of the data we are sending to the MYSQL server ,
they may be one of the following :
s-string
i-integer
b-blob
d-double
Here "smartsiva" is string so i used "s" there. 

Sunday 17 May 2015

Buttons styling using CSS


In order to have good look for the website Cascading Style Sheets(CSS) plays very important role. Let us now discuss about the styling of the "buttons" using CSS.

First, create the html file and place the following code.
//index.html
<html><head><title>Styling buttons using CSS</title></head>
<link rel='stylesheet' href='style.css' type='text/css'/>
<body><!-- button -->
<button id='butn'>LetsScript</button>
</body>
</html>

Now its time for writing CSS and javascript . Assuming that you know the basics and syntax of CSS.

//place this code in style.css
#butn{
padding:10px 22px;background:#10c878;
margin:20px;color:#fff;font-weight:bold;letter-spacing:1px;
box-shadow:0px 1px 1px #10e878;border:1px solid #10d878;
cursor:pointer;font-family:arial;}
#butn:hover{ box-shadow:inset 0px 5px 14px #10a878; }

Friday 15 May 2015

Network commands in Windows Command Prompt


netstat :   This is the command which lets you to get the active networks.
netstat_command
ipconfig :   This is the command which lets you to know about your ip address for each network adapter.
ipconfig_command
getmac :   This is the network windows command which is used to know the physical address also called Medium Access Control (MAC address) .

Dealing with cookies using javascript


Hello guys, I am designing a website for project NEWSONSPOT, there i am going to use the cookies. I planned to write two default functions to set the cookies and get the cookies.

Here is the two functions setCookie and readCookie.
 
Assuming you know the basics of JavaScript.Place the below two functions in the js file and link that file in your html file to use the functions .

//getting the cookies in the form of string
var cok=document.cookie;


//function for reading the cookie value
function readCookie(str){ var cokee=cok.split(";");var coki;
var index=cok.indexOf(str);
for(coki=0;coki<cokee.length;coki++) {
 if(coke[coki].indexOf(str)!=-1 && cok[index-2]==";")
   { var len=cokee[coki].length;
   var eq=cokee[coki].indexOf("=");
   return cokee[coki].substr(eq+1,len);
   }
   }
   return null;
}


//function for setting the cookie value valid upto 1 hour and path is "/"
function setCookie(cname,cvalue){ var d=new Date(); d.setTime(d.getTime()+1000*60*60);
    document.cookie=cname+"="+cvalue+";expires="+d.toUTCString()+";path=/";
}

//function for deleting the cookie
function delCookie(name){ document.cookie=name+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/"; }


Thursday 14 May 2015

Getting the Locaiton in the web browser using JavaScript (GeoLocation)


we can get the location of the user only with the permission of the user. So when you execute the code in the browser . The browser asks the permission of the user to access his location.
OK, Lets start the code !
First create the html file with the following code. { Assuming that you know the basics of html. }

<!DOCTYPE html PUBLIC><html><head><title></title>
<script>
 //here goes our javascript code
</script>
</head>
<body onload='getLocation()'> <div id='result'></div></body>
</html>

 Now its time for the javascript.Assuming that you know the syntax of Javascript.

 //function to get the location
function getLocation() {
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(showLocation); }
else{ document.getElementById("result").innerHTML='Please update your browser !';}}

//function to show the location
function showLocation(position){ document.getElementById("result").innerHTML="Latitude="+position.coords.Latitude+"<br>Longitude="+position.coords.Longitude; }

Place the above javascript code in the script tag (<script>) of the html file. Now run the html file and accept the permission to get the latitude and longitude of your browser.

Removing ShortCut Virus in USB ( pendrive )


You may observe that there is a shortcut virus in the USB in Windows OS. To remove that first mount the USB ( put the pendrive to laptop or PC ). Next run the command prompt (shortcut : windows-key + R and type cmd in the run) . Now type the following command in the command prompt . Replace the h in h:\ with your USB drive letter
attrib -h -r -s /d /s h:\"*"
Now backup all your necessary data to the desired location and format your USB. Now again scan the USB drive with anti-virus you are using and restore your data. This removes the shortcut virus in your USB.

Wednesday 13 May 2015

#define

#define is the preprocessor used to define the constants and macro definitions.

#define MAX 50

This says that compiler that where ever there is MAX , the compiler replaces it with 50

Tuesday 12 May 2015

C Preprocessor #include


Pre-Processor as the name saying these are the actions occurs before compilation. Some possible actions are including the file, defining the symbolic constant, macros.
All preprocessor directives begin with #

Let us first study about #include

 #include is used to include the files, generally header files.

#include<studio.h> is the statement which includes standard input/output header library named as studio.h 

Factorial of the number

#include<studio.h>

void main()
{
int num,sum=1;
Printf ("Enter the number:");
scanf("%d",&num);
While(num--!=0)
  sum*=num;
printf("factorial is %d",sum);
}

Monday 11 May 2015

Reverse of a Number

Reversing of the number

#include<stdio.h>
#include<conio.h>

void main()
{
int a,r,sum=1;
printf("enter the number");
scanf("%d",&a);
while(a!=0)
{
r=a%10;
sum=sum*10+r;
a=a/10;
}
printf("the reverse number is %d ",sum);
getch();
}

Sunday 10 May 2015

Hello World C Program


Here goes my first post, letting you to know about C basics. Let's write the basic C programm to print "hello world"

#include<studio. h> /* includes standard input/output library */

void main()
{
Printf("hello world");
}

 
biz.