Working with Microsoft SQL Server


MS SQL Server


What is SQL Server Management Studio?

SQL Server Management Studio (SSMS) is the main administration console for SQL Server.


SSMS enables you to create database objects (such as databases, tables, stored procedures, views etc), view the data within your database, configure user accounts, perform backups, replication, transfer data between databases, and more.

Fig 3 : SSMS Console Window


User Login :


When creating a new user login, the administrator can assign that login to any number of roles and schemas. This will depend on what that particular login is entitled to.


Create a New Login

Step 1 :  Using SQL Server Management Studio, expand the Security option (at the
server level, not at the database level) and right click n Logins.

Step 2 :  Click on New Login.

Step 3 :   Complete the login properties in the General tab by providing a name for the login, choosing the Authentication method (providing a password if you choose SQL Server authentication), and selecting the database to use as a default.

Step 4 :   Click the Server Roles tab if you need to apply any server-wide security privileges.


Step 5 :
Click the User Mapping tab to specify which databases this user account is allowed to    access. By default, the login will be assigned to the Public role, which provides the login with basic access.
 If the login needs more access in one or more databases, it can be assigned to  another role with greater privileges. In this case, select Task Tracker database  and  db_owner role for that database.
Step 6 :  Click OK to create the login.


NOTE :
These roles are database roles and are different to the server roles in the previous tab. Server roles are for administering the SQL Server. Database roles are more limited. They are created within each database and specify what the login can do within that particular database.




Fig : Server Roles

Server Roles :


When we created a SQL Server login, we had the option of assigning the login one or more server roles. Server roles (not to be confused with database roles) are available to manage permissions on a server.


View the server roles in SSMS, from the Object Explorer, expand the Security folder







Database :

A database is a collection of information that is organized so that it can be easily accessed, managed and updated.
Creating a database can be done by running a SQL script or by “point and click”. 


System Databases

When you install SQL Server, the following four databases are created.
1.master
This database stores system level information such as user accounts, configuration settings, and info on all other databases.
2.model
This database is used as a template for all other databases that are created.
3.msdb
The msdb database is used by the SQL Server Agent for configuring alerts and scheduled jobs etc
4.tempdb


This one holds all temporary tables, temporary stored procedures, and any other temporary storage requirements generated by SQL Server.  


Create Database :

Fig 4 : Create DB 
The following steps demonstrate how to create a database in SQL Server 2014 using SQL Server Management Studio.

Step 1 : From the Object Explorer, right click on the Databases folder/icon and select New Database

Step 2 : 
Name your database and click OK:


Database with the Given Name will be created.

NOTE :
The new database is based on the Model database (System Database).
It already contains system functions, system views, system stored procedures, and (hidden) system tables. These are system objects which provide information about the database.


Create Table :

Fig 5 : Create Table
Steps to create a table in a database using SQL Server Management Studio (SSMS).

Step 1 :   Ensuring you have the correct database expanded (in our case, the TaskTracker database), right click on the Tables icon and select Table

Step 2 :   A new table will open in Design view. Fill in Column_name, Datatype & if(Null) checkbox for making column .
  ( for more options such as PRIMARY KEY, is Identity, etc. right click on left pane of  required tuple to add property )

Step 3 :   Save the table by selecting File > Save able_1 or by right-clicking on the Table’s  tab and selecting. 
Save Table_1  from the contextual menu:  





Insert Data :
There are many ways of getting data into your database. 



1.Manually: Type data directly into your table rows.


2.Copy/Paste: Similar to the previous option, but this one is where you copy data from another source, then paste it into a table in your database.

3.Import: You can use the Import and Export Wizard to import data from another source.

4.SQL Scripts: You can run a SQL script that contains all data to insert.

5.Application/Website: Users update the database via an application or website.





1. Manually


We can use the Edit Top 200 Rows option to manually type data directly into the table rows. Manually entering data is OK if you only have a little bit of data to enter.


Steps :
1. In the Object Explorer, right click on the table you wish to open, and select Edit Top 200 Rows:
2.You can now start entering the data directly into your table.


2. Copy/Paste


You could use a similar method to the above by copying from another datasource and pasting into your database table. This is OK for a small number of records but not for a lot of records.


Steps :

1. Select all required records from the datasource

2. In the destination database (i.e. the one you want to populate with data), right-click on the destination table and select Edit Top 200 Rows. 

3. Select an empty row by right-clicking in the left-most column (it’s more of a button to the left of your left-most column that allows you to select the whole row) and select Paste from the contextual menu:


3 (a). Import 
You can import data from another datasource. The end result is similar to the copy/paste method (i.e. data is copied across to the destination database), but importing the data is more flexible and could be more suitable on many occasions.

Steps :
To import data, right-click on the database and select Tasks > Import Data… and follow the Wizard from there.

The SQL Server Import and Export Wizard can copy data to and from any data source for which a managed .NET Framework data provider or a native OLE DB provider is available. These include:
•SQL Server
•Flat files
•Microsoft Office Access
•Microsoft Office Excel


Start the SQL Server Import and Export Wizard to import data from an Excel worksheet to a SQL Server database. Click Next to bypass the welcome screen. On the Choose a Data Source page (Figure 8), configure the following:

Fig 6: Import Wizard


Step 1 : (Data Source)
Choose Microsoft Excel from the drop-down menu.

Step 2 : (Excel File Path )
Specify the path of the Excel file from which you are importing data.

Step 3: (Excel Version)
Choose the Excel version where you created the Excel.

Click Next to go to the Choose a Destination page (Figure 9), and configure the following:



Step 4 : (Data Source)
Choose SQL Server Native Client 11.0 from the drop-down menu.

Step 5 : (Server Name )
Fig 7 : Import Wizard Client

Type the name of the destination database’s SQL Server instance.

Step 6 : (Authentication)
Choose the appropriate authentication mode for the data destination connection.

Step 7 : (Database )
Choose which database to copy the data into.








Fig 8 : Finish Import

Step 8 :
Click the Next button to go to the Save and Run Package page. Here, select the Run immediately option and click the Next button. 

This takes you to the Complete the Wizard page where you can view the choices you made.

Click Finish to run the package.




3 (b). Exporting data  (from a SQL Server DB to a Microsoft Excel worksheet) :

To export data, start the SQL Server Import and Export Wizard. Then, click the Next button to bypass the Welcome Screen. On the Choose a Data Source page configure the following:

Step 1 : (Data Source )
Fig 9 : Export Wizard

 Choose SQL Server Native Client 11. from the drop-downmenu.

Step 2 : ( Server Name)
Type the name of the SQL Server instance that contains the source data.

Step 3 : (Authentication)
Choose authentication mode for the data source connection.

Step 4 : (Database)
 Choose the database that contains the source data.
Click Next to go to the Choose a Destination page (Figure 2). On this page, configure the following:





Fig 10 : Export Wizard Target

Step 5 : (Destination)
Choose Microsoft Excel from the drop-down menu.

Step 6: (Excel File Path)
Type in the Microsoft Excel worksheet operating system path.

Step 7 : (Excel Version)
Select the version of the Microsoft Excel worksheet.





Step 8:
Fig 11 : Finish Export 

Click the Next button to go to Review Data Type Mapping page. 

This is where you’ll see how different data types are mapped between the source and the destination and how any conversions issues will be handled.

Follow the wizard ahead.




4. SQL Scripts :
In many cases, you will find it more efficient to run a SQL script that contains the data you need to insert. You can use the SQL INSERT statement to insert just the data you specify in the statement.

Eg :
USE [Database_Name] 
GO
INSERT INTO Table_Name (column_name1,column_name2,column_name3) VALUES (‘val1’, ‘val2’, ‘val3’)
5. Application / Website


Server databases are the backend data storage for a front-end application. Users of the application are responsible for adding data to the database (as well as editing it). 
The Difference between these scripts and above scripts is, these scripts are dynamic. i.e Parameters are passed dynamically to the database.

T-SQL Scripts :

1. Create Database :
Creates a user defined database which can hold n number of user defined tables.

Syntax :
Create database

Query :
CREATE DATABASE SCTPL


2. Create Table :
Creates a user defined table which can hold n number of column with their respective constraints defined by user.

Syntax :
USE [DatabaseName]
GO
CREATE TABLE table_name
(
column_name1 Datatype,
column_name2 Datatype,
column_name3 Datatype
)

Query :
USE [SCTPL]
GO
CREATE TABLE Testdb
(
PrimaryID  int PRIMARY KEY IDENTITY,
Year  varchar(255)
)

3. Drop Table :
The SQL Server DROP TABLE statement is used to remove a table definition and all data, indexes, triggers, constraints, and permission specifications for that table.

Syntax :
USE [Database_Name]
GO
DROP TABLE table_name

Query :
USE [SCTPL]
GO
DROP TABLETEST


4. Insert Into :

The SQL Server INSERT INTO statement is used to add new rows of data to a table in the database.

Syntax :
USE [Database_Name]
GO
INSERT INTO Table_Name (column_name1,column_name2,column_name3) VALUES(‘val1’, ‘val2’, ‘val3’)

Query :
USE [Database_Name]
GO
INSERT INTO Table_Name (Year, Country, Location)
VALUES (‘1996′,’Nigeria’,’Akwa Ibom’)
4. Select :
SQL Server SELECT statement is used to fetch the data from a database table which returns data in the form of result table. These result tables are called result-sets.
Syntax :
/*For selecting all entries*/
USE [Database_Name]
GO
SELECT * FROM TEST
/*For selecting Specific entries*/
USE [Database_Name]
GO

SELECT column_name1, column_name2 FROM Table_name


Query :
/*For selecting all entries*/
USE [Database_Name]
GO
SELECT * FROM TEST
/*For selecting Specific entries*/
USE [SUVEN]
GO
SELECT Year, Country FROM TEST
5. Update :
The SQL Server UPDATE Query is used to modify the existing records in a table.
You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows would be affected.

Syntax :
/* Type 1 */
Use [Database_Name]
GO
UPDATE table_name SET column1 = value1, column2 = value2…., columnN = value WHERE [condition]
/* Type 2 */
USE [Database_Name]
GO
UPDATE TABLE_NAME
SET COLUMN_NAME = ‘val1′, Column_name =val


Query :
/* Type 1 */
USE [SUVEN]
GO
UPDATE TEST
SET Location = ‘RenamedColumn Akwa-Ibom
WHERE Location = ‘Akwa Ibom
/* Type 2 */
UPDATE CUSTOMERS SET ADDRESS = Pune‘, SALARY = 1000.00



6. Delete :
The SQL Server DELETE Query is used to delete the existing records from a table.
You have to use WHERE clause with DELETE query to delete selected rows, otherwise all the records would be deleted.

Syntax :
/*For selecting specific entries*/
USE [Database_Name]
GO
DELETE FROM table_name WHERE [condition]
/*For selecting all entries*/
DELETE FROM column_name

Query :
/*For selecting specific entries*/
USE [SUVEN]
GO
DELETE FROM TEST
WHERE SALARY = 1000
/*For selecting all entries*/
DELETE FROM Location



Clauses

1. WHERE Clause:

The MS SQL Server WHERE clause is used to specify a condition while fetching the
data from single table or joining with multiple tables.

If the given condition is satisfied, only then it returns a specific value from the table. You will have to use WHERE clause to filter the records and fetch only necessary records.
The WHERE clause is not only used in SELECT statement, but it is also used in

UPDATE, DELETE statement, etc.


Syntax :
SELECT column1, column2, columnN FROM table_name WHERE [condition]

Query:
SELECT name FROM Stud WHERE id=1


2. LIKE  Clause:

The MS SQL Server LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator 
  1. The percent sign (%)
  2. The underscore (_)
The percent sign represents zero, one, or multiple characters. 
The underscore represents a single number or character. The symbols can be used in combinations.

Syntax:


/* Type 1 */
SELECT *column-list FROM table_name WHERE column LIKE ‘%XXXX%’
/* Type 2 */
SELECT *column-list FROM table_name WHERE column LIKE ‘_XXXX_’

Query:

/* Type 1 */
SELECT name from Stud
WHERE sid LIKE ‘200%’
(Finds any values that start with 200)
/* Type 2 */
SELECT name from Stud
WHERE SALARYLIKE ‘_00_’
Finds any values that have 00 in the second and third positions & is of four characters. 


3. ORDER BY


The MS SQL Server ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some database sort query results in ascending order by default.


Syntax :

Use DatabaseName
Go
SELECT columnlist FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]

Query :

/*TYPE 1*/
Use SUVEN
Go
SELECT * FROM Stud ORDER BY NAME

/*TYPE 2*/

SELECT * FROM Stud ORDER BY NAME DES

4. GROUP BY Clause :

The SQL Server GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.

The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.

Syntax :

UseSUVEN
Go

SELECT column1, column2 FROM table_name WHERE [ conditions ] GROUP BY column1, column2 ORDER BY column1, column2

Query: 

UseSUVEN
Go
SELECT NAME, SUM(SALARY) as [sum of salary] FROM Stud GROUP BY NAME

6. DISTINCT

The MS SQL Server DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only unique records.


There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records.


Syntax :

Use Suven
Go

SELECT DISTINCTcolumn1, column2,…..columnN FROM table_nameWHERE [condition]

Query :
Use SUVEN
Go
SELECT DISTINCT SALARY FROM CUSTOMERS ORDER BY SALARY 


Joins :

The MS SQL Server Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each.

MS SQL Server Join Types −

There are different types of joins available in MS SQL Server −

INNER JOIN         −  Returns rows when there is a match in both tables.

LEFT JOIN            −  Returns all rows from the left table, even if there are no matches in the  
                                  right table.

RIGHT JOIN         −  Returns all rows from the right table, even if there are no matches in the 
                                  left  table.

FULL JOIN            −  Returns rows when there is a match in one of the tables.

SELF JOIN             − This is used to join a table to itself as if the table were two tables, 
                                 temporarily renaming at least one table in the MS SQL Server statement.

CARTESIAN JOIN − Returns the Cartesian product of the sets of records from the two or 
                                  more joined tables.

NOTE :

The join is performed in the WHERE clause. Several operators can be used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join tables. However, the most common operator is the equal symbol.


Query Designer :

The query designer is a graphical user interface that assists in building queries for your SQL Server database. This can be particularly useful when building complex queries that involves many tables, views etc.

The Query Designer can also be beneficial for those who are learning how to write SQL. By using the Query Designer to generate the SQL, you can study the SQL and learn the syntax as you go.

Step 1 :  Open a new query by clicking New Query on the toolbar


Step 2 :  Open the Query Designer by selecting Query > Design Query in Editor. from the top menu:

Step 3 : Select the tables you want to run the query against (in this case, we will add both tables), click Add, and close the box by clicking Close:


Step 4 :  
Select the column/s you want to display in your query by checking the checkbox next to the column name. In the middle pane, you can deselect an Output checkbox to hide that field from being displayed when the query is run (but the field will still be involved in the query).

 Add a value under Filter to narrow the results down to only those you’re interested in (in this example, it is creating a WHERE clause to select only those records with a StatusId of “1” – which is “To Do”):

Step 5 :
Click OK once you’re happy with your query. Query will be automatically  Generated by query designer. Execute it using f5 key.


Views :

In SQL Server, a view is a pre-written query that is stored on the database. A view consists of a SELECT statement, and when you run the view, you see the results of it like you would when opening a table. 

Some people like to think of a view as a virtual table. This is because a view can pull together data from multiple tables, as well as aggregate data, and present it as though it is a single table.
Syntax :

CREATE VIEW ViewName AS
SELECT …

Query :

CREATE VIEW ToDoList AS
SELECT  Tasks.TaskName, Tasks.Description
FROM  Status INNER JOIN
Tasks ON
Status.StatusId = Tasks.StatusId
WHERE  (Status.StatusId = 1)
NOTE : Tasks & Status are two different Tables in a single database.


To execute a View  : 

Syntax : select * from View_name


NOTE :
The view will return upto date data. If the data in the table changes, the results of the view will change too. So if you were to add a new task with a status of “To Do”, next time you run the view, it will include the new record in the result set.


Stored Procedures :

A stored procedure will typically contain some business logic. For example, a stored procedure can accept parameters that are passed to it and test against those parameters using IF statements. Eg, if the parameter is one value, do this, if it’s another value, do that.

Benefits of Stored Procedures :

1. Modular programming
You can write a stored procedure once, then call it again and again, from different parts of an application (and even from multiple applications).

2. Performance
Stored procedures provide faster code execution and reduce network traffic.

3. Security
Users can execute a stored procedure without needing to execute any of the statements directly. Therefore, a stored procedure can provide advanced database functionality for users who wouldn’t normally have access to these tasks, but this functionality is made available in a tightly controlled way.

Create a Stored Procedure :

To create a stored procedure, you need to use the CREATE PROCEDURE statement, followed by the code that makes up the stored procedure. If your stored procedure is going to accept parameters, they need to be included after the name.

Syntax :

CREATE PROCEDURE myStoredProcedure AS
OR
CREATE PROCEDURE myStoredProcedure @{Parameter Name} {data type} AS

Query :

CREATE PROCEDURE
LatestTasks @Count int
AS
SET ROWCOUNT @Count
SELECT TaskName AS LatestTasks, DateCreated
FROM Tasks

ORDER BY DateCreated DESC


Execute a Stored Procedure

1. T-Sql Script :

Now that you’ve created your stored procedure, any time you want to execute it, you need to call it using either EXECUTE or EXEC. If the stored procedure requires parameters you provide those after the procedure name. 


Syntax :
EXECUTE LatestTasks
EXEC LatestTasks
OR
EXEC LatestTasks @Count = 5





2. Using The GUI

Step 1 : Using the Object Explorer, navigate to the stored procedure.

Step 2 : Right click on the stored procedure and select Execute Stored Procedure.

Step 3 : A dialog will appear. Enter your parameter values.

Step 4 : Click OK. SQL Server will generate the SQL code and execute the stored 




System Stored Procedures :

SQL Server includes a large number of system stored procedures to assist in database administration tasks. Many of the tasks you can perform via the GUI can be done via a system stored procedure. For example, some of the things you can do with system stored procedures include:
  • Configure security accounts
  • Set up linked servers
  • Create a database maintenance plan
  • Create full text search catalogs
  • Add remote login
  • Configure replication
  • Set up scheduled jobs
  • and much more…
NOTE :
System Stored Procedure has a prefix sp_ as naming convention.
It is a good idea to develop a consistent naming convention for your stored procedures, like usp_,  select_ , etc.

Android WiFi: Android – LeaVe my baThRoom at-least !

android wifi


WiFi is a technology for wireless local area networking with devices based on the IEEE 802.11 standards. Devices that can use Wi-Fi technology include personal computers, video-game consoles, smartphones, digital cameras, tablet computers, digital audio players and modern printers. Wi-Fi compatible devices can connect to the Internet via a WLAN and a wireless access point. Such an access point (or hotspot) has a range of about 20 meters (66 feet) indoors and a greater range outdoors. Hotspot coverage can be as small as a single room with walls that block radio waves, or as large as many square kilometers achieved by using multiple overlapping access points.

Android allows applications to access to view the access the state of the wireless connections at very low level. Android provides WiFi API through which applications can communicate with the lower-level wireless stack that provides WiFi network access. Almost all information from the device supplicant is available, including the connected network’s link speed, IP address, negotiation state, and more, plus information about other networks that are available. Some other API features include the ability to scan, add, save, terminate and initiate WiFi connections.

WifiManager is the primary API for managing all aspects of WiFi connectivity. Get an instance of this class by calling Context.getSystemService(Context.WIFI_SERVICE). It’s Syntax is given below:-

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);


WifiManager class provides different methods to control WiFi activities:-

  • int addNetwork(WifiConfiguration config): Add a new network description to the set of configured networks.
  • WifiManager.MulticastLock createMulticastLock(String tag): Create a new MulticastLock
  • WifiManager.WifiLock createWifiLock(String tag): This method creates a new WifiLock.
  • boolean disconnect(): This method disassociate from the currently active access point.
  • boolean enableNetwork(int netId, boolean disableOthers): This method allow a previously configured network to be associated with.
  • int getWifiState(): This method gets the Wi-Fi enabled state
  • boolean isWifiEnabled(): This method return whether Wi-Fi is enabled or disabled.
  • boolean setWifiEnabled(boolean enabled): This method enable or disable Wi-Fi.
  • int updateNetwork(WifiConfiguration config): This method update the network description of an existing configured network.
  • boolean disableNetwork (int netId): Disable a configured network.

In order to scan a list of wireless networks, you also need to register your BroadcastReceiver. It can be registered using registerReceiver method with argument of your receiver class object. Its syntax is given below −

class WifiScanReceiver extends BroadcastReceiver {

   public void onReceive(Context c, Intent intent) {
   }
}
WifiScanReceiver wifiReciever = new WifiScanReceiver();
registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

The wifi scan can be start by calling the startScan method of the WifiManager class. This method returns a list of ScanResult objects. You can access any object by calling the get method of list. Its syntax is given below :-


List wifiScanList = mainWifiObj.getScanResults();

String data = wifiScanList.get(0).toString();

Example

Let’s see the simple example of wifi to enable and disable the wifi service.
To run this example you need actual Android device.
  • You will use Android studio to create an Android application under a package net.suven.android.androidwifi.
  • Modify src/MainActivity.java file to add necessary code.
  • Modify the res/layout/activity_main to add respective XML components.
  • Modify the AndroidManifest.xml to add the necessary permissions
  • Run the application and choose a running android device and install the application on it and verify the results.
Following is the content of src/MainActivity.java

package net.suven.android.androidwifi;

import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends Activity {
Button enableButton,disableButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

enableButton=(Button)findViewById(R.id.button);
disableButton=(Button)findViewById(R.id.button1);

enableButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
Toast.makeText(getBaseContext(), "WiFI Enabled",
Toast.LENGTH_LONG).show();

}
});

disableButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
Toast.makeText(getBaseContext(), "WiFI Disabled",
Toast.LENGTH_LONG).show();
}
});
}
}
Following is the content of activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:textSize="30dp"
android:text="ANDROID WIFI"
android:layout_above="@+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginBottom="11dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SCTPL"
android:id="@+id/textView2"
android:textSize="35dp"
android:textColor="#ff16ff01"
android:layout_above="@+id/imageView"
android:layout_centerHorizontal="true" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/suvenlogo"
android:layout_centerVertical="true"
android:layout_alignEnd="@+id/textView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enable WiFi"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_toStartOf="@+id/textView2"
android:layout_marginEnd="14dp"
android:layout_marginBottom="56dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="76dp"
android:text="Disable WiFI"
android:layout_alignBaseline="@+id/button"
android:layout_alignBottom="@+id/button"
android:layout_alignParentEnd="true"
android:layout_marginEnd="20dp" />

</RelativeLayout>
Following is the content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.suven.android.androidwifi">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
Following is the output of Application

android wifi enabled

android wifi disabled
Click here to download Source Code and APK

 Learn Android Programming?


How abundance makes us poorer

Maybe it was to be expected with an offer that involves charity, but it turns out that for me the Humble Bundle Monthly is mostly an investment in a source for philosophical thoughts. When I initially bought the bundle in order to get Civ VI for cheap, I went for the three-month plan. So even if I since unsubscribed I just got my second months worth of games. And compared to the first month, there are even less games in there which I can see me playing. That is not to say that the offer is a bad one, or the games on offer are bad. Rather it reflects upon how my interests got narrower over time.

I am old enough to remember a time before video games. The first video game I played was Pong on a console that couldn’t play anything else, in black and white on a TV screen. When people got the first consoles with cartridges and computers, kids typically had just a handful of games, not necessarily chosen by themselves. If you only have 3 game cartridges, you will play the hell out of each of those games, whether those are your favorite games or not. Fast forward to 2017, where 7,672 games were released on Steam alone, again nearly doubling the number of Steam games available for a fourth year in a row.

Everybody has favorite games and favorite genres. If you are limited by the number of games available to you, you play what you got regardless of genre. If you have an abundance of choice, you get more and more picky and only play your favorite genres. The bottleneck becomes the amount of time available to play, so why should you play let’s say a platformer if you prefer role-playing games? Of course the consequence of that is that you end up with a much narrower experience. You only play a handful of favorite genres and don’t have the time for a bunch of other genres, which might offer a very different experience of gaming.

I see a parallel to the world of news and politics. Back in the day where your only source of news was one paper you and everybody in your street was subscribed to, you all got the same variety of news and opinions. Today there are so many sources of news and opinions that you can choose one which aligns well with your own opinions. If you are a fan of Trump, you watch Fox News and read Breitbart, if you are on the other side you watch CNN and read Huffington Post. But the result is that you end up in an echo chamber which doesn’t allow for a variety of opinions. This has gone so far that the echo chambers of today don’t even agree on the same set of facts. A news source that reports something uncomfortable to you is “fake news”, truth has become subservient to opinion.

The future is one in which we lead comfortable lives in which we play only our favorite games, see only our favorite genre of movies and TV shows, hear only news that please us. Until we have become so isolated from another group of people (which might well be our neighbors) that the two groups don’t consider each other of being of the same kind any more, and start killing each other off. The internet, which had a promise of offering us a much wider offer of everything from information to entertainment, ends up making us all poorer and more narrow-minded.

NY Times Frets About Russian Propaganda, Ignores the Massive Troll Farms Run By America and Its Allies

Social media manipulation is a major problem in urgent need of robust discussion

An op-ed by the president of the right-wing human rights group Freedom House, published in the New York Times Monday (12/11/17)—later boosted by New York Times chief White House correspondent Peter Baker—warned of the menace of “commentators, trolls, bots, false news sites and propaganda,” and their negative effects on democracy. Missing from its analysis was any account of how the government that funds their organization—86 percent of Freedom House’s budget comes from the US government, primarily the State Department and USAID—uses social media to stir unrest and undermine governments worldwide.

What the reader was left with was a very selective, curated impression that online social media manipulation is something done exclusively by brown and black people and those dastardly Slavs. The column condemns “surreptitious techniques pioneered in Moscow and Beijing to use the internet to drown out dissent and undermine free elections,” going on to cite online skullduggery in the Philippines, Kenya, Turkey, Mexico and Iran.

Missing from the piece by Freedom House’s Michael Abramowitz is any mention—much less discussion—of numerous reports detailing online manipulation by US and allied governments and Western PR firms.

No mention of the Defense Department’s $100 million program Operation Earnest Voice software that “creates fake online identities to spread pro-American propaganda.” No mention of the US Air Force’s 2010 solicitation of “persona management” software designed to create hundreds of sock puppets, “replete with background, history, supporting details and cyber presences that are technically, culturally and geographically consistent.” No mention of USAID (the same government agency, incidentally, that funds Freedom House) secretly creating an entire social media platform to “stir unrest” in Cuba. No mention of the US State Department’s newly-created $160 million Global Engagement Center, targeting English-language audiences with unattributed Facebookvideos combating, in part, “Russia propaganda.”

Nor was there mention of the UK’s “team of Facebook warriors,” “skilled in psychological operations and use of social media to engage in unconventional warfare in the information age.” Or reference to the half-dozen reports of Israeli troll farms promoting pro-Israel propaganda online.

Though the op-ed had a particular focus on “governing parties” using covert online tools to “inflate their popular support and essentially endorse themselves”—warning that this “devastating new threat to democracy” is used to “undermine elections, political debate and virtually every other aspect of governing”—there was no acknowledgement of the fact that the Hillary Clinton campaign spent $1 million in the 2016 primary to promote its candidate using unattributed social media personas. Nor was there mention of a torrent of pro-Trump bots that infected the 2016 campaign on social media.

None of this merits mention, much less investigation. Instead, the piece primarily consists of little insight or larger discussion as to the scope of the problem. “The United States and other democracies” are positioned as the victims of online manipulation, never its author. Amidst platitudes about “the future of democracy” and “malevolent actors,” the West’s place as noble defenders of Real Information online is simply taken for granted, with, by implication, their ideological satellites—like Freedom House—as neutral arbiters of what is and isn’t propaganda, never practitioners of propaganda themselves.

The US Department of Defense admitted in 2011 that it runs fake social media accounts in Farsi; the vast majority of Farsi speakers live in Iran. What were these accounts doing? Did they influence any elections there? Does Freedom House ask the question, much less attempt to answer it? Of course not; Iran can only be guilty of “[manipulating] discussions…on social media,” never the victim of it.

Should the New York Times have disclosed that the author of a piece about government propaganda runs a group overwhelmingly funded by the US government? The reader could theoretically do research on their own time to find out who backs the benign-sounding “Freedom House” (who doesn’t love freedom?), but this is a fairly tall order for the average media consumer, doubly so when one considers the whole point of the piece is criticizing unattributed propaganda.

Also missing from Freedom House’s cartoon narrative of Good Western Democracies vs. Bad Governments in the Global South is the issue of sophistication. One of the reasons groups like Freedom House know about clandestine attempts by these governments and affiliated parties to influence online messaging is they’re mostly bad at it. Hacky, easily identifiable bots, sloppy knock-off websites, transparent “fake news.” The software solicited by the US Air Force in 2010, which would allow each user to control up to ten social media personas at once “without fear of being discovered by sophisticated adversaries,” would presumably be much more difficult to detect.

Social media manipulation is a major problem in urgent need of robust discussion. But outlets like the New York Times—and others, such as Buzzfeed—that focus only on attempts by Official US Enemies, and never direct any criticism inwards, aren’t concerned with having an earnest discussion of the problem. They are, instead, using the specter of online manipulation to smear those in bad standing with the US State Department while deflecting any conversation about what the most powerful country in the history of the world may be up to online.

 

Related Stories

  • How the Saudis Escalated Yemen Struggle Beyond All Control
  • How NATO Set the Stage for Open-Air Slave Markets in Libya
  • Michael Flynn’s Indictment Exposes Trump Team’s Collusion With Israel, Not Russia

JSON – PHP : work BeaUtifuLLy




JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc.

  • JSON stands for JavaScript Object Notation.
  • The format was specified by Douglas Crockford.
  • It was designed for human-readable data interchange.
  • It has been extended from the JavaScript scripting language.
  • The filename extension is .json.
  • JSON Internet Media type is application/json.
  • The Uniform Type Identifier is public.json.

Uses of JSON

  • It is used while writing JavaScript based applications that includes browser extensions and websites.
  • JSON format is used for serializing and transmitting structured data over network connection.
  • It is primarily used to transmit data between a server and web applications.
  • Web services and APIs use JSON format to provide public data.
  • It can be used with modern programming languages.

Characteristics of JSON

  • JSON is easy to read and write.
  • It is a lightweight text-based interchange format.
  • JSON is language independent.

Why use JSON?

Since the JSON format is text only, it can easily be sent to and from a server, and used as a data format by any programming language.
JavaScript has a built in function to convert a string, written in JSON format, into native JavaScript objects:
JSON.parse()
So, if you receive data from a server, in JSON format, you can use it like any other JavaScript object.

JSON Syntax:

JSON syntax is derived from JavaScript object notation syntax:
  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays
Below is a simple example −
{
"book": [

{
"language": "Java",
"creator": "James Gosling"
},

{
"language": "PHP",
"creatoR": "Rasmus Lerdorf"
}
]
}


JSON with PHP

Let’s see how to encode and decode JSON objects using PHP programming language.

JSON Functions

PHP has some built-in functions to handle JSON.

Encoding JSON in PHP (json_encode)

PHP json_encode() function is used for encoding JSON in PHP. This function returns the JSON representation of a value on success or FALSE on failure.
Syntax:
string json_encode ( $value [, $options = 0 ] )
Parameters
value − The value being encoded. This function only works with UTF-8 encoded data.
options − This optional value is a bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG,         JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT.
Example

The following example shows how to convert an array into JSON with PHP −
php
$myObj->course = "Rocky Jagtiani";
$myObj->age = 39;
$myObj->city = "Chembur";

$Suven = json_encode($myObj);

echo $Suven;

?>
While executing, this will produce the following result −

{"name":"Rocky Jagtiani","age":39,"city":"Chembur"}

PHP Array:
Arrays in PHP will also be converted into JSON when using the PHP function json_encode():
php
$myArr = array("Java", "Web Technology", "Android", "Digital Marketing");

$myJSON = json_encode($myArr);

echo $myJSON;

?>
this will produce the following result −

["Java","Web Technology","Android","Digital Marketing"]

Decoding JSON in PHP (json_decode)
PHP json_decode() function is used for decoding JSON in PHP. This function returns the value decoded from json to appropriate PHP type.
Syntax
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

Paramaters
json_string − It is an encoded string which must be UTF-8 encoded data.
assoc − It is a boolean type parameter, when set to TRUE, returned objects will be converted into associative arrays.
depth − It is an integer type parameter which specifies recursion depth
options − It is an integer type bitmask of JSON decode, JSON_BIGINT_AS_STRING is supported.
Example:
The following example shows how PHP can be used to decode JSON objects −
php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>
While executing, it will produce the following result −
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}

array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}

Error-Handling and Testing

If the JSON value could not be parsed or a nesting level deeper than the given (or default) depth is found, NULL is returned from json_decode. This means that no exception is raised by json_encode/json_deocde directly.
So how can we identify the cause of the error? The json_last_error function helps here. json_last_error returns an integer error code that can be one of the following constants (taken from here):
JSON_ERROR_NONE: No error has occurred.
JSON_ERROR_DEPTH: The maximum stack depth has been exceeded.
JSON_ERROR_STATE_MISMATCH: Invalid or malformed JSON.
JSON_ERROR_CTRL_CHAR: Control character error, possibly incorrectly encoded.
JSON_ERROR_SYNTAX: Syntax error.
JSON_ERROR_UTF8: Malformed UTF-8 characters, possibly incorrectly encoded (since PHP 5.3.3).

Want to Learn Web Technologies?

Understanding Synchronous and Asynchronous JavaScript – paRt_1 : JavaScript – its DiFFereNt

Javascript logo
In JavaScript Synchronous and Asynchronous are very important concepts. Beginners might find them difficult to learn.
When two or more things happen at same time then it is Synchronous and when they don’t that’s Asynchronous. These definitions are easy to understand but it’s complicated than it looks from here. So let’s dig a little deeper. 
You’d probably call a normal function in JavaScript synchronous, right? And if it’s something like setTimeout() or AJAX that you’re working with, you will refer to it as being asynchronous, yes? What if I tell you that both are asynchronous in a way?
Let’s understand with an example. We’ll get help from Mr. K,

Scenario 1:-> Mr. K is trying Synchronicity 

Here’s the setup:
  1. Mr K is someone who can answer tough questions, and carry out any requested task.
  2. The only way to contact him is through a phone call.
  3. Whatever question or task you got, in order to ask Mr K’s help to carry it out; you call him.
  4. Mr K gives you the answer or completes the task right away, and lets you know it’s done.
  5. You put down the receiver feeling content and go out on a date.
What you’ve just carried out was a synchronous (back and forth) communication with Mr K. He listened as you were asking him your question, and you listened when he was answering it.

client calling server

Scenario 2:-> Mr. K isn’t happy with Synchronicity 

Since Mr K is so efficient, he starts receiving many more calls. So what happens when you call him but he’s already busy talking to someone else? You won’t be able to ask him your question – not till he is free to receive your call. All you will hear is a busy tone.

So what can Mr K do to combat this?
Instead of taking calls directly:
  1. Mr K hires a new guy, Mr J and gives him an answering machine for the callers to leave messages.
  2. Mr J’s job is to pass on a message from the answering machine to Mr K once he knows Mr K has completely finished processing all previous messages and is already free to take a new one.
  3. So now when you call him, instead of getting a busy tone, you get to leave a message for Mr K, then wait for him to call you back (no date time yet).
  4. Once Mr K is done with all the queued up messages he received before yours, he will look into your issue, and call you back to give you an answer.
Now here lies the question: were the actions so far synchronous or asynchronous?
It’s mixed. When you left your message, Mr K wasn’t listening in to it, so the forth communication was asynchronous.
But, when he replied, you were there listening, which makes the return communication synchronous.
Until now you must have understand synchronicity in communication. It’s time to bring in JavaScript in the picture.

JavaScript An Asynchronous Language

When someone labels JavaScript asynchronous, what they are referring to in general is how you can leave a message for it, and not have your call blocked with a busy tone.
The function calls are never direct in JavaScript, they’re usually done via messages
JavaScript uses a message queue where incoming messages (or events) are held. An event-loop (a message dispatcher) sequentially dispatches those messages to a call stack where the corresponding functions of the messages are stacked as frames (function arguments & variables) for execution.
The call stack holds the frame of the initial function being called, and any other frames for functions called via nested calls on top of it .

JavaScript Call Stack
JavaScript Call Stack

When a message joins the queue, it waits until the call stack is empty of all frames from the previous message, and when it is, the event-loop de-queues the previous message, and adds the corresponding frames of the current message to the call stack.
The message waits again until the call stack becomes empty of its own corresponding frames (i.e. the executions of all the stacked functions are over), then is de-queued.
Consider the following code:

function foo(){}
function
bar(){
foo();
}
function
baz(){
bar();
}
baz();

The function being run is baz() (at the last row of the code snippet), for which a message is added to the queue, and when the event-loop picks it up, the call stack starts stacking frames for baz(), bar(), and foo() at the relevant points of execution.

Push action in Call Stack

Once the execution of the functions is complete one by one, their frames are removed from the call stack, while the message is still waiting in the queue, until baz() is popped from the stack.

Pop Action in Call Stack


Remember, the function calls are never direct in JavaScript, they’re done via messages. So whenever you hear someone say that JavaScript itself is an asynchronous programming language, assume that they are talking about its built-in “answering machine”, and how you’re free to leave messages.

But what about the specific asynchronous methods?

So far I’ve not touched on APIs such as setTimeout() and AJAX, those are the ones that are specifically referred to as asynchronous. Why is that?
It’s important to understand what exactly is being synchronous or asynchronous. JavaScript, with the help of events and the event-loop, may practice asynchronous processing of messages, but that doesn’t mean everything in JavaScript is asynchronous.
Remember, I told you the message didn’t leave until the call stack was empty of its corresponding frames, just like you didn’t leave on a date until you got your answer — that’s being synchronous, you are there waiting until the task is complete, and you get the answer.
Waiting isn’t ideal in all scenarios. What if after leaving a message, instead of waiting, you can leave on the date? What if a function can retire (emptying the call stack), and its message can be de-queued even before the task of the function is complete? What if you can have code executed asynchronously?
This is where APIs such as setTimeout() and AJAX come into the picture, and what they do is… hold on, I can’t explain this without going back to Mr K, which we’ll see in the second part of this article. Stay tuned…

Mueller Russia Investigation Will Continue Through 2018: Report

The president has long believed, without evidence, he’d be cleared by the end of the year.

Refuting President Donald Trump’s “arrogant” assumption that the Russia investigation will be over at the end of the year, members of special counsel Robert Mueller’s team confirmed they would continue their probe until at least 2018.

As The Washington Post reported Monday, “the special counsel’s office has continued to request new documents related to the [Trump] campaign, and members of Mueller’s team have told others they expect to be working through much of 2018, at a minimum.”

The possibility of the probe ending by the year’s close becomes even narrower considering that multiple witnesses, including former Trump aides George Papadopoulos and Mike Flynn, are continuing to cooperate with the investigation, the report continues.

Nevertheless, CNN reported Monday that Trump believes he’s going to receive an exonerating “letter” from Mueller — and those close to him fear he’ll have a “meltdown” if that letter doesn’t come soon.

 

Related Stories

  • Former CIA Official Suggests Trump Campaign Team May Have ‘Welcomed’ Russian Election Interference
  • If Trump Fires Mueller, Is a Watergate Rerun Coming?
  • Robert Mueller Has the Trump Team Panicked, No Matter What the President Says

Gardmore Abbey 5E rerun – Session 4

This session started with an interesting fight in a wizard’s tower. It turned out the wizard was both undead and quite mad, wanting to preserve everything for eternity by freezing it. So the group was hit with a lot of ice magic which hindered their movement, while battling the wizard and his 4 icy mummies. But the group prevailed and scored another card from the deck of many things, which had been frozen in a block of ice together with a Barlgura demon. That caused quite some concern on how to get to the card without being attacked by the demon, however it turned out that the demon didn’t wake up at all and just got banished back to the abyss by defrosting him.

So the group moved on to the garrison, having found both possible ways to open the door there, a scroll from the wizard’s tower and the sword of the lost paladin. But there was another Barlgura demon in the garrison, together with some specters, and this time the demon was alive. I had the demon use his disguise spell to assume the same form as the specters, so the group didn’t immediately know where the main threat was. But otherwise the combat went without major events, and the group found the brazier, one of the three objects they were searching for Sir Oakley.

So they returned to Sir Oakley and rested in the temple. Then they decided to take the stairs in the temple leading down to a dungeon, where they encountered a band of gnolls. The group attacked immediately, while the gnolls tried to retreat. Most of the gnolls made it to the next room and barred the door, but the barbarian just crashed through that door with an exceptional strength check. So the group fought the gnolls from both rooms at once, which was a tough fight. After the fight we decided to stop for this session.

The #1 Reason the GOP Tax Plan Is an Economic Catastrophe: It Will Send Health Care Costs Through the Roof

The bill is poised to cause real pain and suffering to people who struggle to pay for health care.

Of all the reasons the Republican tax bill will be a mugging of the majority of non-wealthy Americans, one reason stands out above all else—the bill will seriously set back everyone who has struggled to pay for health insurance and medical expenses.

Repealing the Obamacare coverage mandate is likely to prompt insurers to raise premiums by an estimated 10 percent annually into the foreseeable future, according to the nonpartisan Congressional Budget Office. Why? Because as up to 13 million people drop their policies—CBO’s estimate—the remaining policy holders will end up paying more. (Those dropping coverage will revert to pre-Obamacare days of postponing treatments and hoping for the best.)

That’s just the start of the dire news affecting health care costs, as anticipated increases will more than offset any tax break. Not that most Americans were going to see tax cuts anyway—the bottom 50 percent of wage earners will see their after-tax incomes shrink by 2 percent; the middle 40 percent’s after-tax incomes will shrink by 0.6 percent; while the top 10 percent will see their incomes grow by 1.5 percent or more, the New York Times noted Monday.

There’s more bad health care news. The tax bill’s $1.5 trillion cost also preys on seniors, triggering spending cuts of 4 percent annually for Medicare, the federal health program for those 65 and older.

Currently, before Congress has its final votes on the bill, there’s no shortage of physicians who do not accept Medicare, due to  reimbursement rates. The result is people needing to see some physicians have to pay cash up front, if they can, and then fight with supplemental insurance providers to be reimbursed. This downward spiral will only worsen as Congress cuts Medicare.

The GOP bill also trashes preventive health care for the poorest households, a majority of which are single mothers with children. The same budget pressures that trigger automatic cuts for Medicare will also apply to the food and nutritional assistance programs. Additionally, the bill’s authors have swapped in a stingier formula for cost-of-living index increases—the so-called chained CPI. That new metric translates into less assistance, not more, for the needy in coming years.

The punishment of the poor and vulnerable doesn’t stop there. The tax bill’s changes in the earned income tax credit will divert an estimated $19 billion from poor families. The bill’s new requirement that families seeking child tax credit provide a Social Security number will translate into higher taxes for undocumented immigrants, who work and pay taxes but lack that paperwork.

But the bill’s biggest negative impact is that it will take bigger bites from paychecks and savings for health care spending. The bill’s GOP authors will counter that they lowered the threshold for deducting medical expenses from 10 percent of annual income to 7.5 percent. However, like many GOP tax breaks, it can only be claimed after spending the money in the first place—if you have it.

The coming shocks to the health care system have prompted industry experts and insiders to beseech Congress to vote no on the bill this week.

“In the wealthiest country on earth, 40 million people live in poverty,” tweeted Andy Slavitt, who ran the Medicaid and Medicare programs for the Obama administration. “The GOP tax bill would dramatically increase the wealth of the very wealthy & begin a cycle of cuts to poverty & health programs… Uneasy Rs have one last chance.”

“This is a horrid bill,” John Baackes, chief executive of L.A. Care, a public plan covering 2 million mostly poor residents of Los Angeles County, told the L.A. Times. “They haven’t been able to repeal and replace [Obamacare], so they’ll attack it through the budget by looking for ways knock down the money that’s needed to cover people.”

But high-ranking Republicans, like House Speaker Paul Ryan, have told conservative radio that cutting health care programs is their top federal budget priority—with Ryan saying he will be targeting welfare, Medicare and Medicaid (state-run care for those under 65) in 2018.

Meanwhile, neither Ryan nor his Senate counterparts have taken action to continue funding CHIP, the federal health care program that covers 9 million poor children. (On Monday, Alabama announced it was freezing 2018 CHIP enrollment.)

The GOP bill is poised to cause real pain and suffering to people who struggle to pay for health care. 

As Slavitt wrote late Monday, “BREAKING: Trump Administration announced it is ending program to pay differently to improve quality in Medicaid, as happens in Medicare & everywhere else. I’ve run these programs. This is tragic bigotry.”

Yes, more bigotry against the middle class and working poor. Despite GOP campaign trail rhetoric, there’s no tax simplification, fairness, economic growth or fiscal discipline in the Republicans’ tax bill. It transfers money up the ladder to those already making six-figures and into corporate profits. Almost everyone else pays more—starting with their health care (or lack of it).   

 

Related Stories

  • Trump Led American Politics Is Swamped by Epidemic of Unprecedented Lying
  • American Politics Is Swamped by Unprecedented Lies, Lying Politicians and Partisans Blaming Critics
  • Republican Tax Plan Is Only The Start of GOP Effort To Spread Inequality and Economic Anxieties by Shredding Safety Nets

Learn the Bootstrap Grid in 15 Minutes : BootStrap – ResponSive Designing

Bootstrap grid system

Bootstrap is a free and open-source front-end web framework for designing websites and web applications. Unlike many web frameworks, it concerns itself with front-end development only. Anybody who knows HTML, CSS and a bit of Java Script can learn Bootstrap in no time. Responsive page layout is the layout which can change and adapt depending on the screen size of the device the user is on.

The grid consists of rows and columns. This allows us to freely position elements vertically and horizontally. Rows are block level. This means, that when we create a row, it takes up the entire width of the element it is in. You can think of rows as new lines in your layout. The horizontal alignment in the grid is done via columns. Only columns can be the direct children of a row and all content should go inside them. Placing content directly within a row will break the layout.
        
Syntax for the Bootstrap grid system:


<div class="row">


<div class="col-md-12">Content Goes Here</div>

</div>      
Rows are divided horizontally into 12 equal parts. When we place a column inside a row, we have to specify the number of parts it is going to take up. 
        
This is done by using special class .col-md-NUMBER , here Number can be 1 to 12 depending on the width of the element getting placed in that column.

components of the grid system
 
In the class name .col-md-NUMBER  md stands for medium display size. To make the page responsive we use different classes because bootstrap uses the screen resolution and dpi into account when deciding which classes are active. This is a powerful way how to control how layouts render on different devices. 


classes used in bootstrap


To make it responsive according to screen size we use :


<div class="row"> <div class="col-xs-12 col-md-6"><p> To learn Angular JS and BootStrap visit http://monster.suvenconsultants.com/#section-angularJs-Bootsrtap . </p></div>


<div class="col-xs-12 col-md-6">Content</div>

output for the code where desktop will show elements horizontally and in mobile it will view vertical



Clearfix :
In some scenarios, when a column has much more content and a bigger height then the ones after it, the layout will break. The columns will all pile up under each other, instead of moving to the next line as they should. To make the page look perfectly aligned we use clearifix.

syntax to use clearfix:

<div class="row">
<div class="col-xs-6 tall-column">A column much taller than the rest.</div>
<div class="col-xs-6"></div>
<div class="clearfix"></div>
<div class="col-xs-6"></div>
</div>

even if the height is different next element will display on the next row


Offsets :
By default, columns stick to each other without leaving any space, floating to the left. Any excess space remaining in that row stays empty on the right. to leave space on the left side we use offsets
classes used in offsets


Example for offsets:

<div class="container">
<div class="row">
<div class="col-xs-5 col-xs-offset-4">col-xs-5 col-xs-offset-4</div>
<div class="col-xs-9 col-xs-offset-2">col-xs-9 col-xs-offset-2</div>
<div class="col-xs-6 col-xs-offset-1">col-xs-6 col-xs-offset-1</div>
<div class="col-xs-4 col-xs-offset-1">col-xs-4 col-xs-offset-1</div>
<div class="col-xs-11 col-xs-offset-1">col-xs-11 col-xs-offset-1</div>
<div class="col-xs-10">col-xs-10</div>
<div class="col-xs-7">col-xs-7</div> </div>
<div class="row"> <div class="col-xs-5">col-xs-5</div> </div>
<div class="row">
<div class="col-xs-7">col-xs-7</div>
<div class="col-xs-10">col-xs-10</div>
<div class="col-xs-11 col-xs-offset-1">col-xs-11 col-xs-offset-1</div>
<div class="col-xs-11 col-xs-offset-1">col-xs-11 col-xs-offset-1</div>
<div class="col-xs-9 col-xs-offset-2">col-xs-9 col-xs-offset-2</div>
<div class="col-xs-5 col-xs-offset-4">col-xs-5 col-xs-offset-4</div>
</div> </div>


   


offset will keep the blank space on left side


To make it more clear:


CONCLUSION:
Great job! You now know the most important part of the Bootstrap framework, and you’re ready to build your next responsive design. Interested in learning bootstrap ?  .