SQL PRIMARY KEY on CREATE TABLE

The following SQL creates a PRIMARY KEY on the “ID” column when the “Persons” table is created:

MySQL:

CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

SQL Server / Oracle / MS Access:

CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255NOT NULL,
FirstName varchar(255),
Age int
);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
Note: In the example above there is only ONE PRIMARY KEY (PK_Person). However, the VALUE of the primary key is made up of TWO COLUMNS (ID + LastName).
[mai mult...]

Sending Email using Ruby – SMTP

Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers. Ruby provides Net::SMTP class for Simple Mail Transfer Protocol (SMTP) client-side connection and provides two class methods new and start.

  • The new takes two parameters −
    • The server name defaulting to localhost.
    • The port number defaulting to the well-known port 25.
  • The start method takes these parameters −
    • The server − IP name of the SMTP server, defaulting to localhost.
    • The port − Port number, defaulting to 25.
    • The domain − Domain of the mail sender, defaulting to ENV[“HOSTNAME”].
    • The account − Username, default is nil.
    • The password − User password, defaulting to nil.
    • The authtype − Authorization type, defaulting to cram_md5.

An SMTP object has an instance method called sendmail, which will typically be used to do the work of mailing a message. It takes three parameters −

  • The source − A string or array or anything with an each iterator returning one string at a time.
  • The sender − A string that will appear in the from field of the email.
  • The recipients − A string or an array of strings representing the recipients’ addressee(s).
Example

Here is a simple way to send one email using Ruby script. Try it once −

require 'net/smtp'

message = <<MESSAGE_END
From: Private Person <me@fromdomain.com>
To: A Test User <test@todomain.com>
Subject: SMTP e-mail test

This is a test e-mail message.
MESSAGE_END

Net::SMTP.start('localhost') do |smtp|
  smtp.send_message message, 'me@fromdomain.com', 'test@todomain.com'
end

Here, you have placed a basic e-mail in message, using a document, taking care to format the headers correctly. E-mails require a FromTo, and Subject header, separated from the body of the e-mail with a blank line.

To send the mail you use Net::SMTP to connect to the SMTP server on the local machine and then use the send_message method along with the message, the from address, and the destination address as parameters (even though the from and to addresses are within the e-mail itself, these aren’t always used to route mail).

If you’re not running an SMTP server on your machine, you can use the Net::SMTP to communicate with a remote SMTP server. Unless you’re using a webmail service (such as Hotmail or Yahoo! Mail), your e-mail provider will have provided you with outgoing mail server details that you can supply to Net::SMTP, as follows −

Net::SMTP.start('mail.your-domain.com')

This line of code connects to the SMTP server on port 25 of mail.your-domain.com without using any username or password. If you need to, though, you can specify port number and other details. For example −

Net::SMTP.start('mail.your-domain.com', 
                25, 
                'localhost', 
                'username', 'password' :plain)

This example connects to the SMTP server at mail.your-domain.com using a username and password in plain text format. It identifies the client’s hostname as localhost.

[mai mult...]

Ruby – Classes and Objects

Ruby is a perfect Object Oriented Programming Language. The features of the object-oriented programming language include −

  • Data Encapsulation
  • Data Abstraction
  • Polymorphism
  • Inheritance

An object-oriented program involves classes and objects. A class is the blueprint from which individual objects are created. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles.

Take the example of any vehicle. It comprises wheels, horsepower, and fuel or gas tank capacity. These characteristics form the data members of the class Vehicle. You can differentiate one vehicle from the other with the help of these characteristics. A vehicle can also have certain functions, such as halting, driving, and speeding. Even these functions form the data members of the class Vehicle. You can, therefore, define a class as a combination of characteristics and functions.

A class Vehicle can be defined as −

Class Vehicle {

   Number no_of_wheels
   Number horsepower
   Characters type_of_tank
   Number Capacity
   Function speeding {
   }
   
   Function driving {
   }
   
   Function halting {
   }
}

By assigning different values to these data members, you can form several instances of the class Vehicle. For example, an airplane has three wheels, horsepower of 1,000, fuel as the type of tank, and a capacity of 100 liters. In the same way, a car has four wheels, horsepower of 200, gas as the type of tank, and a capacity of 25 liters.

Defining a Class in Ruby

To implement object-oriented programming by using Ruby, you need to first learn how to create objects and classes in Ruby. A class in Ruby always starts with the keyword class followed by the name of the class. The name should always be in initial capitals. The class Customer can be displayed as −

class Customer
end

You terminate a class by using the keyword end. All the data members in the class are between the class definition and the end keyword.

Variables in a Ruby Class

Ruby provides four types of variables −

  • Local Variables − Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more details about method in subsequent chapter. Local variables begin with a lowercase letter or _.
  • Instance Variables − Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (@) followed by the variable name.
  • Class Variables − Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign @@ and are followed by the variable name.
  • Global Variables − Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign ($).
Example

Using the class variable @@no_of_customers, you can determine the number of objects that are being created. This enables in deriving the number of customers.

class Customer
   @@no_of_customers = 0
end
[mai mult...]

jQuery Effects – Animation

With jQuery, you can create custom animations.

jQuery Animations – The animate() Method

The jQuery animate() method is used to create custom animations.

Syntax:

$(selector).animate({params},speed,callback);

The required params parameter defines the CSS properties to be animated.

The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds.

The optional callback parameter is a function to be executed after the animation completes.

The following example demonstrates a simple use of the animate() method; it moves a <div> element to the right, until it has reached a left property of 250px:

[mai mult...]

Java Wrapper Classes

Java Wrapper Classes
  • Wrapper classes provide a way to use primitive data types (intboolean, etc..) as objects.
  • The table below shows the primitive type and the equivalent wrapper class:
Primitive Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character

 

Sometimes you must use wrapper classes, for example when working with Collection objects, such as ArrayList, where primitive types cannot be used (the list can only store objects):

Example
ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid
ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid
[mai mult...]

Java Regular Expressions

What is a Regular Expression?
  • A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.
  • A regular expression can be a single character, or a more complicated pattern.
  • Regular expressions can be used to perform all types of text search and text replace operations.
  • Java does not have a built-in Regular Expression class, but we can import the java.util.regex package to work with regular expressions. The package includes the following classes:
  • Pattern Class – Defines a pattern (to be used in a search)
  • Matcher Class – Used to search for the pattern
  • PatternSyntaxException Class – Indicates syntax error in a regular expression pattern
Example

Find out if there are any occurrences of the word “w3schools” in a sentence:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) {
    Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher("Visit W3Schools!");
    boolean matchFound = matcher.find();
    if(matchFound) {
      System.out.println("Match found");
    } else {
      System.out.println("Match not found");
    }
  }
}
// Outputs Match found
Example Explained

In this example, The word “w3schools” is being searched for in a sentence.

First, the pattern is created using the Pattern.compile() method. The first parameter indicates which pattern is being searched for and the second parameter has a flag to indicates that the search should be case-insensitive. The second parameter is optional.

The matcher() method is used to search for the pattern in a string. It returns a Matcher object which contains information about the search that was performed.

The find() method returns true if the pattern was found in the string and false if it was not found.

Flags

Flags in the compile() method change how the search is performed. Here are a few of them:

  • Pattern.CASE_INSENSITIVE – The case of letters will be ignored when performing a search.
  • Pattern.LITERAL – Special characters in the pattern will not have any special meaning and will be treated as ordinary characters when performing a search.
  • Pattern.UNICODE_CASE – Use it together with the CASE_INSENSITIVE flag to also ignore the case of letters outside of the English alphabet
[mai mult...]

C++ Function Overloading

With function overloading, multiple functions can have the same name with different parameters:

Example
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
Consider the following example, which have two functions that add numbers of different type:
Example
int plusFuncInt(int x, int y) {
return x + y;
}
double plusFuncDouble(double x, double y) {
return x + y;
}

int main() {
int myNum1 = plusFuncInt(85);
double myNum2 = plusFuncDouble(4.36.26);
cout << “Int: “ << myNum1 << “\n”;
cout << “Double: “ << myNum2;
return 0;
}

[mai mult...]

C++ Syntax

Let’s break up the following code to understand it better:

Example
#include <iostream>
using namespace std;
int main() {
cout << “Hello World!”;
return 0;
}

Example explained

Line 1: #include <iostream> is a header file library that lets us work with input and output objects, such as cout (used in line 5). Header files add functionality to C++ programs.

Line 2: using namespace std means that we can use names for objects and variables from the standard library.

Don’t worry if you don’t understand how #include <iostream> and using namespace std works. Just think of it as something that (almost) always appears in your program.

Line 3: A blank line. C++ ignores white space.

Line 4: Another thing that always appear in a C++ program, is int main(). This is called a function. Any code inside its curly brackets {} will be executed.

Line 5: cout (pronounced “see-out”) is an object used together with the insertion operator (<<) to output/print text. In our example it will output “Hello World”.

Note: Every C++ statement ends with a semicolon ;.

Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }

Remember: The compiler ignores white spaces. However, multiple lines makes the code more readable.

Line 6: return 0 ends the main function.

Line 7: Do not forget to add the closing curly bracket } to actually end the main function.

[mai mult...]

C++ References

Creating References

A reference variable is a “reference” to an existing variable, and it is created with the & operator:

string food = “Pizza”;  // food variable
string &meal = food;    // reference to food
[mai mult...]

C++ Exceptions

  • When executing C++ code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.
  • When an error occurs, C++ will normally stop and generate an error message. The technical term for this is: C++ will throw an exception.
[mai mult...]