x This domain is for sale. If you intrested, Please contact : webspeckle@gmail.com

An Introduction To WebSockets

Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.

Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.

WebSocket Events

Following are the events associated with WebSocket object. Assuming we created Socket object as mentioned above −
open:
Socket.onopen
    This event occurs when socket connection is established.
message:
  Socket.onmessage
            This event occurs when client receives data from server.
error:
  Socket.onerror
            This event occurs when there is any error in communication.
close:
Socket.onclose
      This event occurs when connection is closed.

WebSocket Methods

Following are the methods associated with WebSocket object. Assuming we created Socket object as mentioned above −

Socket.send()
The send(data) method transmits data using the connection.

Socket.close()
The close() method would be used to terminate any existing connection.
if ("WebSocket" in window)
{
    WebSocket = new WebSocket("wss://echo.websocket.org");
    WebSocket.onopen = function (Event)
    {
        //Web Socket Connected Successfully";
        WebSocket.send("Message to send");
    };
    WebSocket.onmessage = function (Event)
    {
        //Message is received...
    };

    WebSocket.onclose = function (event)
    {
        //Web Socket Closed Successfully
    };

    WebSocket.onerror = function (Error)
    {
        //Web Socket Error
    };
}
else
{
    //Web Socket Error: NOT supported by your Browser!
}

Check whether form value is set or not in java?

In java a function getParameter() is used for check whether form value set or not.

getParameter()
Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.

You should only use this method when you are sure the parameter has only one value. If the parameter might have more than one value, use getParameterValues(java.lang.String).

If you use this method with a multivalued parameter, the value returned is equal to the first value in the array returned by getParameterValues.

If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the body directly via getInputStream() or getReader() can interfere with the execution of this method.
Eg:
if(request.getParameter("Submit") != null)
{
     /* Yes! submit field is set in the request */
}

How to close jquery modal dialog when click outside?

If jquery ui dialog is a modal, then this code is working fine. If the dialog is not a modal you will find out another method.

.ui-widget-overlay is dialog overlay class. So attach an event handler function for this element.

Eg:
<script type="text/javascript">
$(document).ready(function()
{
        $("#dialog").dialog();
        $('body').on("click", ".ui-widget-overlay", function()
       {
            $("#dialog").dialog("close");
       });
});
</script>

How to print java variable in jsp page

Print java variable in jsp by
<%=  JavaVariable %>

ternary operator usage
<input type="hidden" name="Name" value="<%= (session != null && session.getAttribute("Code") != null) ? session.getAttribute("Code").toString() : ""%>"/>

Reset a form elements using jquery/javascript

By using jquery
$('#formID')[0].reset();

By using Javascript
document.getElementById("myForm").reset(); 

The reset() method resets the values of all elements in a form (same as clicking the Reset button)
.

How to change jquery ui dialog overlay style

Jquery UI dialog which is useful for displaying information. You can fully customize this dialog. Here we explain how to change the style of dialog overlay style.

This is the css style. Add a new class 'overlayStyle' and apply the new styles within the brackets.
.ui-widget-overlay.overlayStyle
{
    background: repeat-x scroll 50% 50% #ff0000;
    opacity:0.3;
    filter:Alpha(Opacity=15);
}

Then use an addClass function for add the new style to the dialog
open: function (event, ui)
{
     $('.ui-widget-overlay').addClass('overlayStyle');
}

The final code is
$( "#dialog" ).dialog(
{
     open: function (event, ui)
     {
          $('.ui-widget-overlay').addClass('overlayStyle');
     }
});

How to solve structured data errors in blogger?

Structured Data Testing Tool

 The Structured Data Testing Tool (SDTT) provides a variety of ways to develop, test, and modify your structured markup.

You can load markup into the tool either directly or by supplying a URL. The editing environment for the tool provides these utilities to simplify markup testing:

Automatic highlighting
once you load your content in the editor, you can click on a validated field on the right of the editor to see which line in your markup produced that field. This is handy for isolating syntax errors.

Search & replace keyboard shortcuts
supports plain text and JavaScript regular expressions. The search and replace status line appears at the top of the Editor Panel.

Keyword completion of schema.org and JSON-LD keywords.

Structured data errors

  1. The property blogId is not recognized by Google for an object of type BlogPosting.
  2. The property postId is not recognized by Google for an object of type BlogPosting.
  3. The dateModified field is recommended. Please provide a value if available.
  4. A value for the headline field is required.
  5. A value for the image field is required.
  6. The property image_url is not recognized by Google for an object of type BlogPosting.
  7. The mainEntityOfPage field is recommended. Please provide a value if available.
  8. A value for the publisher field is required.
Log into your Blogger Dashboard.

2. Click Theme.

3. Click  Edit HTML.

1) The property blogId is not recognized by Google for an object of type BlogPosting.

Search the word itemprop='blogId'.  And you will see the line
<meta expr:content='data:blog.blogId' itemprop='blogId'/>

Replace by the below code
<meta expr:content='data:blog.blogId'/>

2) The property postId is not recognized by Google for an object of type BlogPosting.

Search the word itemprop='postId'.  And you will see the line
<meta expr:content='data:post.id' itemprop='postId'/>

Replace by the below code
<meta expr:content='data:post.id'/>

3) The dateModified field is recommended. Please provide a value if available.

Search the word itemprop='datePublished'.  And you will see the line contains itemprop='datePublished'.

Paste the below line after the above line
<meta expr:content='data:post.lastUpdatedISO8601' itemprop='dateModified'/>

4) A value for the headline field is required.

Search the word entry-title.  And you will see the line
<h3 class='post-title entry-title' itemprop='name'>

Replace by the below code
<h3 class='post-title entry-title' itemprop='headline'>

5) A value for the image field is required.

Search the word data:post.firstImageUrl.  And you will see the line
<b:if cond='data:post.firstImageUrl'>
     <meta expr:content='data:post.firstImageUrl' itemprop='image_url'/>
</b:if>

Replace by the below code
<div itemprop='image' itemscope='itemscope' itemtype='https://schema.org/ImageObject'>
      <b:if cond='data:post.firstImageUrl'>
        <img style='display:none;' expr:src='data:post.firstImageUrl' alt='Textual description of firstImageUrl'/>
        <meta itemprop='image' expr:content='data:post.firstImageUrl'/>
      </b:if>
      <meta itemprop='width' content='800'/> <!--Images should be at least 696 pixels wide.-->
      <meta itemprop='height' content='800'/>
</div>

6) The property image_url is not recognized by Google for an object of type BlogPosting.

Search the word itemprop='image_url'.  And you will see the line
<b:if cond='data:post.thumbnailUrl'>
     <meta expr:content='data:post.thumbnailUrl' itemprop='image_url'/>
</b:if>

Replace by the below code
<b:if cond='data:post.thumbnailUrl'>
     <meta expr:content='data:post.thumbnailUrl' itemprop='url'/>
</b:if>

7) The mainEntityOfPage field is recommended. Please provide a value if available.

Find the below code
<b:includable id='post' var='post'>
<div class='post hentry uncustomized-post-template' itemprop='blogPost' itemscope='itemscope' itemtype='http://schema.org/BlogPosting'>

Changed to
<b:includable id='post' var='post'>
    <div class='post hentry uncustomized-post-template' itemscope='itemscope' itemtype='http://schema.org/BlogPosting'>
      <meta itemscope='itemscope' itemprop='mainEntityOfPage'  itemType='https://schema.org/WebPage' expr:itemid='data:post.link' content= 'data:post.link : data:post.url'/>

Find another one
<b:includable id='mobile-post' var='post'>
<div class='post hentry uncustomized-post-template' itemscope='itemscope' itemtype='http://schema.org/BlogPosting'>

Changed to
<b:includable id='mobile-post' var='post'>
   <div class='post hentry uncustomized-post-template' itemscope='itemscope' itemtype='http://schema.org/BlogPosting'>
     <meta expr:itemid='data:post.link' content= 'data:post.link : data:post.url' itemType='https://schema.org/WebPage' itemprop='mainEntityOfPage' itemscope='itemscope'/>

8) A value for the publisher field is required.

<div itemprop='publisher' itemscope='itemscope' itemtype='https://schema.org/Organization'>
      <div itemprop='logo' itemscope='itemscope' itemtype='https://schema.org/ImageObject'>
        <!-- Schema Mods: THE FOLLOWING URL WILL FAIL - CHANGE IT -->
        <meta itemprop='url' content='http://www.myOrganization.com/OrgImage.png'/>
        <meta itemprop='width' content='600'/> <!-- Logos should be no wider than 600px. -->
        <meta itemprop='height' content='60'/> <!-- and no taller than 60px.-->
      </div>
      <meta itemprop='name' expr:content='data:blog.title'/>
</div>

Insert the code within the schema.org/BlogPosting and schema.org/WebPage code blocks

After the save and upload, then test again with the Structured Data Testing Tool

Laravel file cache API

Laravel provides an expressive, unified API for various caching backends. By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the filesystem. For larger applications, it is recommended that you use a more robust driver such as Memcached or Redis. You may even configure multiple cache configurations for the same driver. Here we listing some file cache API using in laravel

array many(array $keys)

Retrieve multiple items from the cache by key.
Items not found in the cache will have a null value.
Parameters
     array $keys
Return Value
     array


void putMany(array $values, float|int $minutes)

Store multiple items in the cache for a given number of minutes.
Parameters
     array $values
     float|int $minutes
Return Value
     void

void __construct(Filesystem $files, string $directory)

Create a new file cache store instance.
Parameters
     Filesystem $files
     string $directory
Return Value
     void

mixed get(string|array $key)

Retrieve an item from the cache by key.
Parameters
     string|array $key
Return Value
     mixed

void put(string $key, mixed $value, float|int $minutes)

Store an item in the cache for a given number of minutes.
Parameters
     string $key
     mixed $value
     float|int $minutes
Return Value
     void

int|bool increment(string $key, mixed $value = 1)

Increment the value of an item in the cache.
Parameters
     string $key
     mixed $value
Return Value
     int|bool

int|bool decrement(string $key, mixed $value = 1)

Decrement the value of an item in the cache.
Parameters
     string $key
     mixed $value
Return Value
     int|bool

void forever(string $key, mixed $value)

Store an item in the cache indefinitely.
Parameters
     string $key
     mixed $value
Return Value
     void

bool forget(string $key)

Remove an item from the cache.
Parameters
     string $key
Return Value
     bool

bool flush()

Remove all items from the cache.
Return Value
     bool

Filesystem getFilesystem()

Get the Filesystem instance.
Return Value
     Filesystem

string getDirectory()

Get the working directory of the cache.
Return Value
     string

string getPrefix()

Get the cache key prefix.
Return Value
     string

How to delay an execution in jquery?

delay() method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show() or .hide() which do not use the effects queue.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

Using the standard effects queue, we can, for example, set an 800-millisecond delay between the .slideUp() and .fadeIn() of <div id="foo">:

$( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );

When this statement is executed, the element slides up for 300 milliseconds and then pauses for 800 milliseconds before fading in for 400 milliseconds.

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

How to set jquery ui dialog to fixed position

By default the jquery ui dialog will scroll with the page. Some time we need the dialog position as fixed.

Just add a style to solve this.

.ui-dialog
{
      position:fixed;
}

How to check TV remote is working by using mobile phone

In the TV remote an IR LED (Infrared LED) is used for send the signals to the receiver. An IR LED, also known as IR transmitter, is a special purpose LED that transmits infrared rays in the range of 760 nm wavelength. Such LEDs are usually made of gallium arsenide or aluminium gallium arsenide. They, along with IR receivers, are commonly used as sensors.

The appearance is same as a common LED. Since the human eye cannot see the infrared radiations, it is not possible for a person to identify whether the IR LED is working or not, unlike a common LED. To overcome this problem, the camera on a cellphone can be used. The camera can show us the IR rays being emanated from the IR LED in a circuit.
Through a digital camera display,the IR LED appears as a flashing, bright white light

How to add gadget section in blogger layout

Gadgets are simple HTML and JavaScript applications that can be embedded in web pages and other apps, including Blogger.
You can simply add a single line of code in blogger source code for Gadget section.

<b:section id='MyBloggerGadget'/>

The 'id' attribute is mandatory and a give a simple name like 'Header-Section'. 

Laravel Validation Rules

Laravel provides several different approaches to validate your application's incoming data. By default, Laravel's base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.

Available Validation Rules

Below is a list of all available validation rules and their function:

accepted

The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.

active_url

The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function.
after:date

The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function:

'start_date' => 'required|date|after:tomorrow'

Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date:

'finish_date' => 'required|date|after:start_date'

after_or_equal:date

The field under validation must be a value after or equal to the given date. For more information, see the after rule.

alpha

The field under validation must be entirely alphabetic characters.

alpha_dash

The field under validation may have alpha-numeric characters, as well as dashes and underscores.

alpha_num

The field under validation must be entirely alpha-numeric characters.

array

The field under validation must be a PHP array.

before:date

The field under validation must be a value preceding the given date. The dates will be passed into the PHP strtotime function.

before_or_equal:date

The field under validation must be a value preceding or equal to the given date. The dates will be passed into the PHP strtotime function.

between:min,max

The field under validation must have a size between the given min and max. Strings, numerics, and files are evaluated in the same fashion as the size rule.

boolean

The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".

confirmed

The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.

date

The field under validation must be a valid date according to the strtotime PHP function.

date_format:format

The field under validation must match the given format. You should use either date or date_format when validating a field, not both.

different:field

The field under validation must have a different value than field.

digits:value

The field under validation must be numeric and must have an exact length of value.

digits_between:min,max

The field under validation must have a length between the given min and max.

dimensions

The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters:

'avatar' => 'dimensions:min_width=100,min_height=200'

Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio.

A ratio constraint should be represented as width divided by height. This can be specified either by a statement like 3/2 or a float like 1.5:

'avatar' => 'dimensions:ratio=3/2'

Since this rule requires several arguments, you may use the Rule::dimensions method to fluently construct the rule:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'avatar' => [
        'required',
        Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2),
    ],
]);


distinct

When working with arrays, the field under validation must not have any duplicate values.

'foo.*.id' => 'distinct'

email

The field under validation must be formatted as an e-mail address.

exists:table,column

The field under validation must exist on a given database table.
Basic Usage Of Exists Rule

'state' => 'exists:states'

Specifying A Custom Column Name

'state' => 'exists:states,abbreviation'

Occasionally, you may need to specify a specific database connection to be used for the exists query. You can accomplish this by prepending the connection name to the table name using "dot" syntax:

'email' => 'exists:connection.staff,email'

If you would like to customize the query executed by the validation rule, you may use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit them:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::exists('staff')->where(function ($query) {
            $query->where('account_id', 1);
        }),
    ],
]);


file

The field under validation must be a successfully uploaded file.

filled

The field under validation must not be empty when it is present.

image

The file under validation must be an image (jpeg, png, bmp, gif, or svg)

in:foo,bar,...

The field under validation must be included in the given list of values. Since this rule often requires you to implode an array, the Rule::in method may be used to fluently construct the rule:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'zones' => [
        'required',
        Rule::in(['first-zone', 'second-zone']),
    ],
]);


in_array:anotherfield

The field under validation must exist in anotherfield's values.

integer

The field under validation must be an integer.

ip

The field under validation must be an IP address.

ipv4

The field under validation must be an IPv4 address.

ipv6

The field under validation must be an IPv6 address.

json

The field under validation must be a valid JSON string.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

mimetypes:text/plain,...

The file under validation must match one of the given MIME types:

'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'

To determine the MIME type of the uploaded file, the file's contents will be read and the framework will attempt to guess the MIME type, which may be different from the client provided MIME type.

mimes:foo,bar,...

The file under validation must have a MIME type corresponding to one of the listed extensions.

Basic Usage Of MIME Rule

'photo' => 'mimes:jpeg,bmp,png'

Even though you only need to specify the extensions, this rule actually validates against the MIME type of the file by reading the file's contents and guessing its MIME type.

A full listing of MIME types and their corresponding extensions may be found at the following location: https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

min:value

The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

nullable

The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values.

not_in:foo,bar,...

The field under validation must not be included in the given list of values.

numeric

The field under validation must be numeric.

present

The field under validation must be present in the input data but can be empty.

regex:pattern

The field under validation must match the given regular expression.

Note: When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

required

The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true:

    The value is null.
    The value is an empty string.
    The value is an empty array or empty Countable object.
    The value is an uploaded file with no path.

required_if:anotherfield,value,...

The field under validation must be present and not empty if the anotherfield field is equal to any value.

required_unless:anotherfield,value,...

The field under validation must be present and not empty unless the anotherfield field is equal to any value.

required_with:foo,bar,...

The field under validation must be present and not empty only if any of the other specified fields are present.

required_with_all:foo,bar,...

The field under validation must be present and not empty only if all of the other specified fields are present.

required_without:foo,bar,...

The field under validation must be present and not empty only when any of the other specified fields are not present.

required_without_all:foo,bar,...

The field under validation must be present and not empty only when all of the other specified fields are not present.

same:field

The given field must match the field under validation.

size:value

The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes.

string

The field under validation must be a string. If you would like to allow the field to also be null, you should assign the nullable rule to the field.

timezone

The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

unique:table,column,except,idColumn

The field under validation must be unique in a given database table. If the column option is not specified, the field name will be used.

Specifying A Custom Column Name:

'email' => 'unique:users,email_address'

Custom Database Connection

Occasionally, you may need to set a custom connection for database queries made by the Validator. As seen above, setting unique:users as a validation rule will use the default database connection to query the database. To override this, specify the connection and the table name using "dot" syntax:

'email' => 'unique:connection.users,email_address'

Forcing A Unique Rule To Ignore A Given ID:

Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.

To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit the rules:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);


If your table uses a primary key column name other than id, you may specify the name of the column when calling the ignore method:

'email' => Rule::unique('users')->ignore($user->id, 'user_id')

Adding Additional Where Clauses:

You may also specify additional query constraints by customizing the query using the where method. For example, let's add a constraint that verifies the account_id is 1:

'email' => Rule::unique('users')->where(function ($query) {
    $query->where('account_id', 1);
})

url

The field under validation must be a valid URL.

What is KERMIT?

Kermit is a robust transport-independent file-transfer protocol and a large collection of software programs that implement it on a wide variety of platforms. In addition to file transfer, many of these programs also make network, dialed, and/or serial-port connections and also offer features such as terminal emulation, character-set conversion, and scripting for automation of any communication or file-management task. The Kermit Project originated at Columbia University in New York City in 1981 and remained there for 30 years. Since 2011 it is independent.

Kermit is the name of a file-transfer and -management protocol and a suite of computer programs for many types of computers that implements that protocol as well as other communication functions ranging from terminal emulation to automation of communications tasks through a high-level cross-platform scripting language. The software is transport-independent, operating over TCP/IP connections in traditional clear-text mode or secured by SSH, SSL/TLS, or Kerberos IV or V, as well as over serial-port connections, modems, and other communication methods (X.25, DECnet, various LAN protocols such as NETBIOS and LAT, parallel ports, etc, on particular platforms).
The Kermit Project was founded at the Columbia University Computer Center (now CUIT) in 1981.

The major features of the most popular Kermit programs are:

  1. Connection establishment and maintenance for a wide variety of connection methods (TCP/IP, X.25, LAN, serial port, modem, etc).
  2. Terminal emulation.
  3. Error-free file transfer.
  4. Internet protocols including Telnet, Rlogin, FTP, and HTTP.
  5. Internet security methods including Kerberos, SSL/TLS, SSH, and SRP.
  6. Character-set conversion during both terminal emulation and file transfer – a unique feature of Kermit software.
  7. Numeric and alphanumeric paging.
  8. Script programming to automate complicated or repetitive tasks. 

 Our premiere Kermit software implementations are:

Kermit 95 for Windows 95/98/ME, Windows NT/2000/XP/Vista/7/8/10, and OS/2;
C-Kermit for UNIX, VMS, VOS, and several other operating system families;
E-Kermit for embedding.
MS-DOS Kermit for DOS and Windows 3.x;
IBM Mainframe Kermit for VM/CMS, MVS/TSO, and CICS. 
Kermit protocol has developed into a sophisticated, powerful, and extensible transport-independent tool for file transfer and management, incorporating, among other things:

  • Transmission of multiple files in a single operation.
  • File attribute transmission (size, date, permissions, etc)
  • File name, record-format, and character-set conversion
  • File collision options, including an "update" feature
  • File transfer recovery (resumption of an interrupted binary-mode transfer from the point of failure)
  • Auto upload and download
  • Client/Server file transfer and management
  • Automatic per-file text/binary mode switching during file-group transmission
  • Recursive directory-tree transfer, even between unlike platforms
  • Uniform services on serial and network connections
  • An Internet Kermit Service Daemon 

Customize Blogger Contact Form

Customize blogger contact form, ie. change the default form to fully responsive contact form by using bootstrap. This tutorial helps you to customize all the elements in the contact form, such as input box, textarea, buttons, error and success messages.

Most of the tutorials doesn't touch the error and success message styling. But we will explain how to change the default style of  the error and success messages.

Our contact form was created by using this method. Take a look at the following link

Demo

1: Include the bootstrap CDN

Go to Theme -> Edit Html -> paste the following code just before the </head> tag.
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

2: Add the default contact form through the Gadget.

3: Hide the default contact form

Go to Theme -> Edit Html -> paste the following code just before the ]]></b:skin> tag.
div#ContactForm1
{
     display:none;
}

4: Create a new page

Go to Pages -> New Page
Type the title like "Contact"
copy paste the follwing code to the new page
<div class="ContactForm"><br><div style='text-align: center; width: 100%' class="ContactFormMessages"><p class='contact-form-error-message' id='ContactForm1_contact-form-error-message'></p><p class='contact-form-success-message' id='ContactForm1_contact-form-success-message'></p></div><form name='contact-form' class="form-horizontal"><div class="form-group"><label class="control-label col-sm-3">Name:</label><div class="col-sm-7"><input type="text" class="form-control" id='ContactForm1_contact-form-name' placeholder="Enter name..." name="name"></div></div><div class="form-group"><label class="control-label col-sm-3" for="email">Email Address:</label><div class="col-sm-7"><input type="email" class="form-control" id='ContactForm1_contact-form-email' placeholder="Enter email address..." name="email"></div></div><div class="form-group"><label class="control-label col-sm-3" for="email">Message:</label><div class="col-sm-7"><textarea class="form-control" id='ContactForm1_contact-form-email-message' rows="5" name='email-message' placeholder="Enter message..."></textarea></div></div><div class="form-group"><div class="col-sm-offset-3 col-sm-7"><button type="button" class="contact-form-button contact-form-button-submit" id='ContactForm1_contact-form-submit'>Send</button><button type='reset' class="contact-form-button contact-form-button-submit">Clear</button></div></div></form></div>

5: Add styling to the contact form

Go to Theme -> Edit Html -> paste the following code just before the ]]></b:skin> tag.
.ContactForm .contact-form-button.contact-form-button-submit { margin:0px; padding: 3px 15px 3px 15px; height:auto; } .ContactForm .ContactFormMessages p { font-size:14px; font-family:Arial, Helvetica, sans-serif; font-weight:normal; box-shadow:none; } .ContactForm .ContactFormMessages p.contact-form-success-message-with-border { color:#005200; border:1px solid #81e181; background-color: #e2f4c6; padding:10px; } .ContactForm .ContactFormMessages p.contact-form-error-message-with-border { color: #dd0000; border:1px solid #e8b7b7; background-color: #fff1f1; padding:10px; } div#ContactForm1 { display:none; } .FollowByEmail .follow-by-email-inner .follow-by-email-address { height:30px; }


Done!


Word highlighting in Qt using QRegExp


Highlight a searched word using QRegExp.

The QRegExp class provides pattern matching using regular expressions.QRegExp is modeled on Perl's regexp language. It fully supports Unicode. QRegExp can also be used in a simpler, wildcard mode that is similar to the functionality found in command shells. The syntax rules used by QRegExp can be changed with setPatternSyntax(). In particular, the pattern syntax can be set to QRegExp::FixedString, which means the pattern to be matched is interpreted as a plain string, i.e., special characters (e.g., backslash) are not escaped.

Example 1:

QString text = "A <i>bon mot</i>.";
text.replace(QRegExp("<i>([^<]*)</i>"), "<b>\\1</b>");

Output:
A <b>bon mot</b>.


Example 2:

QString text1 = "This is a sample text.";
text1.replace(QRegExp("(s)"), "<b>\\1</b>");

Output:
Thi<b>s</b> i<b>s</b> a <b>s</b>ample text.


Remove all matching characters from a string using C language

Here i writing a function named void_RemoveAllChars() and is used for removing
all matching characters from the given string.

void RemoveAllChars(char*,char)

First argument is a string
Second argument is a character

Eg:
In the below example shows how to removing all the 'l' characters from the
string "llHello, world!ll".

#include <stdio.h>

void RemoveAllChars(char* String,char CharForRemoval)
{
    char *Read = String, *Write = String;
    while (*Read)
    {
        *Write = *Read++;
        Write += (*Write != CharForRemoval);
    }
    *Write = '\0';
}

int main(int argc, char *argv[])
{
    char str[]="llHello, world!ll";
    RemoveAllChars(str,"l");
    printf("Output is %s",str);
    return 0;
}

Output:
"Heo, word!"

Get the last occurrence of a string using C language


char * strrstr ( const char *, const char * );

str1     The input string
str2     This string containing the sequence of characters to match.

Return Value
A pointer to the last occurrence in str1 of the entire sequence of characters specified in str2, or a null pointer if the sequence is not present in str1.

Eg:
#include <stdio.h>
char *strrstr(char *MainString,char *SubString)
{
    char *Read,*CharPos;
    int SubStringLength=strlen(SubString);
    CharPos=strrchr(MainString,*SubString);
    if(CharPos != NULL)
    {
        for(Read=CharPos; Read >= MainString; Read--)
        {
            if (strncmp(Read, SubString, SubStringLength) == 0)
            {
                return Read;
            }
        }
    }
    return NULL;
}
int main(int argc, char *argv[])
{
    char * ptr;
    ptr= strrstr("webspecklelearnandshareknowledge","know");
    printf ("%s",ptr);
    return 0;
}

Output :
knowledge

How to initialize QStringList as Empty

QStringList list;
In the above code will generate an empty list.

list=QStringLIst();
This is used for initializing the QStringList as Empty.

Eg:
    QStringList list;
    list << "Web" << "Speckle";

    if(list.isEmpty())
    {
         qDebug("empty");
    }
    else
    {
         qDebug("not empty");
    }


//initializing the QStringList as Empty.
    list=QStringList();
    if(list.isEmpty())
    {
         qDebug("empty");
    }
    else
    {
         qDebug("not empty");
    }


Output of the above code is
not empty
empty

How can i check the request is AJAX in laravel

How can i check the request is ajax in laravel framework.

You can easily check the request is ajax or not. First you paste the below line into the top of the controller page.

use Illuminate\Http\Request;

This is the sample code
public function SomeFunction(Request $HTTPRequest)
{
      if($HTTPRequest->ajax())
      {
            //Yes it is an ajax request
      }
      else
     {
          //It is not an ajax request
     }
}

What is Laravel

Laravel is a free, open-source PHP web framework, created by Taylor Otwell and intended for the development of web applications following the model–view–controller (MVC) architectural pattern. Some of the features of Laravel are a modular packaging system with a dedicated dependency manager, different ways for accessing relational databases, utilities that aid in application deployment and maintenance, and its orientation toward syntactic sugar.

Laravel is regarded as one of the most popular PHP frameworks, together with Symfony, Nette, CodeIgniter, Yii2 and other frameworks.

The following features serve as Laravel's key design points

  • Bundles provide a modular packaging system since the release of Laravel 3, with bundled features already available for easy addition to applications. Furthermore, Laravel 4 uses Composer as a dependency manager to add framework-agnostic and Laravel-specific PHP packages available from the Packagist repository.
  • Eloquent ORM (object-relational mapping) is an advanced PHP implementation of the active record pattern, providing at the same time internal methods for enforcing constraints on the relationships between database objects. Following the active record pattern, Eloquent ORM presents database tables as classes, with their object instances tied to single table rows.
  • Query builder, available since Laravel 4, provides a more direct database access alternative to the Eloquent ORM. Instead of requiring SQL queries to be written directly, Laravel's query builder provides a set of classes and methods capable of building queries programmatically. It also allows selectable caching of the results of executed queries.
  • Application logic is an integral part of developed applications, implemented either by using controllers or as part of the route declarations. The syntax used to define application logic is similar to the one used by Sinatra framework.
  • Reverse routing defines a relationship between the links and routes, making it possible for later changes to routes to be automatically propagated into relevant links. When the links are created by using names of existing routes, the appropriate uniform resource identifiers (URIs) are automatically created by Laravel.
  • Restful controllers provide an optional way for separating the logic behind serving HTTP GET and POST requests.
  • Class auto loading provides automated loading of PHP classes without the need for manual maintenance of inclusion paths. On-demand loading prevents inclusion of unnecessary components, so only the actually used components are loaded.
  • View composers serve as customizable logical code units that can be executed when a view is loaded.
  • Blade templating engine combines one or more templates with a data model to produce resulting views, doing that by transpiling the templates into cached PHP code for improved performance. Blade also provides a set of its own control structures such as conditional statements and loops, which are internally mapped to their PHP counterparts. Furthermore, Laravel services may be called from Blade templates, and the templating engine itself can be extended with custom directives.
  • IoC containers make it possible for new objects to be generated by following the inversion of control (IoC) principle, in which the framework calls into the application- or task-specific code, with optional instantiating and referencing of new objects as singletons.
  • Migrations provide a version control system for database schemas, making it possible to associate changes in the application's codebase and required changes in the database layout. As a result, this feature simplifies the deployment and updating of Laravel-based applications.
  • Database seeding provides a way to populate database tables with selected default data that can be used for application testing or be performed as part of the initial application setup.
  • Unit testing is provided as an integral part of Laravel, which itself contains unit tests that detect and prevent regressions in the framework. Unit tests can be run through the provided artisan command-line utility.
  • Automatic pagination simplifies the task of implementing pagination, replacing the usual manual implementation approaches with automated methods integrated into Laravel.
  • Form request is a feature of Laravel 5 that serves as the base for form input validation by internally binding event listeners, resulting in automated invoking of the form validation methods and generation of the actual form.
  • Homestead - a Vagrant virtual machine that provides Laravel developers with all the tools nessessary to develop Laravel straight out of the box, including, Ubuntu, Gulp , Bower and other development tools that are useful in developing full scale web applications.


What is Qt

Qt is a cross-platform application framework that is used for developing application software that can be run on various software and hardware platforms with little or no change in the underlying codebase, while still being a native application with native capabilities and speed.

Qt is used for developing multi-platform applications and graphical user interfaces (GUIs); however, programs without a GUI can be developed, such as command-line tools and consoles for servers. An example of a non-GUI program using Qt is the Cutelyst web framework. GUI programs created with Qt can have a native-looking interface, in which case Qt is classified as a widget toolkit.

Qt uses standard C++ with extensions including signals and slots that simplify handling of events, and this helps in development of both GUI and server applications which receive their own set of event information and should process them accordingly. Qt supports many compilers, including the GCC C++ compiler and the Visual Studio suite. Qt also provides Qt Quick, that includes a declarative scripting language called QML that allows using JavaScript to provide the logic. With Qt Quick, rapid application development for mobile devices became possible, although logic can be written with native code as well to achieve the best possible performance. Qt can be used in several other programming languages via language bindings. It runs on the major desktop platforms and some of the mobile platforms. It has extensive internationalization support. Non-GUI features include SQL database access, XML parsing, JSON parsing, thread management and network support.

A language construct introduced in Qt for communication between objects which makes it easy to implement the observer pattern while avoiding boilerplate code. The concept is that GUI widgets can send signals containing event information which can be received by other controls using special functions known as slots.

Qt works on many different platforms.

Get file extension from filename using PHP

pathinfo — Returns information about a file path

Description
pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )

pathinfo() returns information about path: either an associative array or a string, depending on options.

Parameters
path - The path to be parsed.

options
If present, specifies a specific element to be returned; one of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME.
If options is not specified, returns all available elements.

Return Value:
If the options parameter is not passed, an associative array containing the following elements is returned: dirname, basename, extension (if any), and filename.

Example:

<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0?>


The above example will output:

/www/htdocs/inc
lib.inc.php
php
lib.inc

 Other method

The below function returns the extension of the given file name. Argument is the File name

function GetExtension($Filename)
{
   $Filename = strtolower($Filename) ;
   $Extension = explode(".", $Filename) ;
   $ExtensionNo = count($Extension)-1;
   $Extension = $Extension[$ExtensionNo];
   return $Extension;
}


Eg: GetExtension("feshers-2013-apply-1132.jpeg");

it return jpeg

CSRF security token in spring boot

CSRF security token setting in spring boot is approximate same as spring.
Please read the post CSRF implementation in spring and setup the configuration as per the document.
After the configuration please check is application.properties or application.yml file exists under the resources folder.

If not exists create application.properties or application.yml file under the resources folder. And then add the following code into that file.

security.enable-csrf=true

Done!

CSRF implementation in spring

In this section discusses Spring boot Security’s Cross Site Request Forgery (CSRF) support.

Before we discuss how Spring Security can protect applications from CSRF attacks, we will explain what a CSRF attack is. Let’s take a look at a concrete example to get a better understanding.
Assume that your bank’s website provides a form that allows transferring money from the currently logged in user to another bank account.

For example, the HTTP request might look like:
Now pretend you authenticate to your bank’s website and then, without logging out, visit an evil website.
The evil website contains an HTML page with the following form:

<form action="https://bank.example.com/transfer" method="post">
<input type="hidden"
name="amount"
value="100.00"/>
<input type="hidden"
name="routingNumber"
value="evilsRoutingNumber"/>
<input type="hidden"
name="account"
value="evilsAccountNumber"/>
<input type="submit"
value="Win Money!"/>
</form>

You like to win money, so you click on the submit button. In the process, you have unintentionally transferred $100 to a malicious user. This happens because, while the evil website cannot see your cookies, the cookies associated with your bank are still sent along with the request.

Worst yet, this whole process could have been automated using JavaScript. This means you didn’t even need to click on the button.

So how do we protect ourselves from such attacks?


The issue is that the HTTP request from the bank’s website and the request from the evil website are exactly the same. This means there is no way to reject requests coming from the evil website and allow requests coming from the bank’s website. To protect against CSRF attacks we need to ensure there is something in the request that the evil site is unable to provide.

One solution is to use the Synchronizer Token Pattern. This solution is to ensure that each request requires, in addition to our session cookie, a randomly generated token as an HTTP parameter. When a request is submitted, the server must look up the expected value for the parameter and compare it against the actual value in the request. If the values do not match, the request should fail.

We can relax the expectations to only require the token for each HTTP request that updates state. This can be safely done since the same origin policy ensures the evil site cannot read the response. Additionally, we do not want to include the random token in HTTP GET as this can cause the tokens to be leaked.

How to solve this? 


You will notice that we added the _csrf parameter with a random value. Now the evil website will not be able to guess the correct value for the _csrf parameter (which must be explicitly provided on the evil website) and the transfer will fail when the server compares the actual token to the expected token.

Using Spring Security CSRF Protection

  • Use proper HTTP verbs
  • Configure CSRF Protection
  • Include the CSRF Token 

Use proper HTTP verbs

The first step to protecting against CSRF attacks is to ensure your website uses proper HTTP verbs. Specifically, before Spring Security’s CSRF support can be of use, you need to be certain that your application is using PATCH, POST, PUT, and/or DELETE for anything that modifies state.

Configure CSRF Protection

The next step is to include Spring Security’s CSRF protection within your application. Some frameworks handle invalid CSRF tokens by invaliding the user’s session, but this causes its own problems. Instead by default Spring Security’s CSRF protection will produce an HTTP 403 access denied. This can be customized by configuring the AccessDeniedHandler to process InvalidCsrfTokenException differently.

As of Spring Security 4.0, CSRF protection is enabled by default with XML configuration. If you would like to disable CSRF protection, the corresponding XML configuration can be seen below.

<http>
<!-- ... -->
<csrf disabled="true"/>
</http>

CSRF protection is enabled by default with Java Configuration.

@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
}
}

If you would like to disable CSRF, the corresponding Java configuration can be seen below. Refer to the Javadoc of csrf() for additional customizations in how CSRF protection is configured.

@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable();
}
}

Include the CSRF Token

The last step is to ensure that you include the CSRF token in all PATCH, POST, PUT, and DELETE methods. One way to approach this is to use the _csrf request attribute to obtain the current CsrfToken. An example of doing this with a JSP is shown below:

<c:url var="logoutUrl" value="/logout"/>
<form action="${logoutUrl}"
method="post">
<input type="submit"
value="Log out" />
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
</form>

Ajax and JSON Requests


If you are using JSON, then it is not possible to submit the CSRF token within an HTTP parameter. Instead you can submit the token within a HTTP header. A typical pattern would be to include the CSRF token within your meta tags. An example with a JSP is shown below:

<html>
<head>
<meta name="_csrf" content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<!-- ... -->
</head>
<!-- ... -->

You can then include the token within all your Ajax requests. If you were using jQuery, this could be done with the following:

$(function () {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
});

Maven Dependency

<dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-security</artifactid>
</dependency>