text:
Form Validation
###############

CodeIgniter provides a comprehensive form validation and data prepping
class that helps minimize the amount of code you'll write.

.. contents:: Page Contents

********
Overview
********

Before explaining CodeIgniter's approach to data validation, let's
describe the ideal scenario:

#. A form is displayed.
#. You fill it in and submit it.
#. If you submitted something invalid, or perhaps missed a required
   item, the form is redisplayed containing your data along with an
   error message describing the problem.
#. This process continues until you have submitted a valid form.

On the receiving end, the script must:

#. Check for required data.
#. Verify that the data is of the correct type, and meets the correct
   criteria. For example, if a username is submitted it must be
   validated to contain only permitted characters. It must be of a
   minimum length, and not exceed a maximum length. The username can't
   be someone else's existing username, or perhaps even a reserved word.
   Etc.
#. Sanitize the data for security.
#. Pre-format the data if needed (Does the data need to be trimmed? HTML
   encoded? Etc.)
#. Prep the data for insertion in the database.

Although there is nothing terribly complex about the above process, it
usually requires a significant amount of code, and to display error
messages, various control structures are usually placed within the form
HTML. Form validation, while simple to create, is generally very messy
and tedious to implement.

************************
Form Validation Tutorial
************************

What follows is a "hands on" tutorial for implementing CodeIgniters Form
Validation.

In order to implement form validation you'll need three things:

#. A :doc:`View <../general/views>` file containing a form.
#. A View file containing a "success" message to be displayed upon
   successful submission.
#. A :doc:`controller <../general/controllers>` method to receive and
   process the submitted data.

Let's create those three things, using a member sign-up form as the
example.

The Form
========

Using a text editor, create a form called myform.php. In it, place this
code and save it to your application/views/ folder::

	<title>My Form</title>

	<?php echo validation_errors(); ?>

	<?php echo form_open('form'); ?>

Username

	<input type="text" name="username" value="" size="50" />

Password

	<input type="text" name="password" value="" size="50" />

Password Confirm

	<input type="text" name="passconf" value="" size="50" />

Email Address

	<input type="text" name="email" value="" size="50" />

<input type="submit" value="Submit" />

	</form>

The Success Page
================

Using a text editor, create a form called formsuccess.php. In it, place
this code and save it to your application/views/ folder::

	<title>My Form</title>

Your form was successfully submitted!

<?php echo anchor('form', 'Try it again!'); ?>

The Controller
==============

Using a text editor, create a controller called form.php. In it, place
this code and save it to your application/controllers/ folder::

	<?php

	class Form extends CI_Controller {

		public function index()
		{
			$this->load->helper(array('form', 'url'));

			$this->load->library('form_validation');

			if ($this->form_validation->run() == FALSE)
			{
				$this->load->view('myform');
			}
			else
			{
				$this->load->view('formsuccess');
			}
		}
	}

Try it!
=======

To try your form, visit your site using a URL similar to this one::

	example.com/index.php/form/

If you submit the form you should simply see the form reload. That's
because you haven't set up any validation rules yet.

**Since you haven't told the Form Validation class to validate anything
yet, it returns FALSE (boolean false) by default. ``The run()`` method
only returns TRUE if it has successfully applied your rules without any
of them failing.**

Explanation
===========

You'll notice several things about the above pages:

The form (myform.php) is a standard web form with a couple exceptions:

#. It uses a form helper to create the form opening. Technically, this
   isn't necessary. You could create the form using standard HTML.
   However, the benefit of using the helper is that it generates the
   action URL for you, based on the URL in your config file. This makes
   your application more portable in the event your URLs change.
#. At the top of the form you'll notice the following function call:
   ::

	<?php echo validation_errors(); ?>

   This function will return any error messages sent back by the
   validator. If there are no messages it returns an empty string.

The controller (form.php) has one method: ``index()``. This method
initializes the validation class and loads the form helper and URL
helper used by your view files. It also runs the validation routine.
Based on whether the validation was successful it either presents the
form or the success page.

.. _setting-validation-rules:

Setting Validation Rules
========================

CodeIgniter lets you set as many validation rules as you need for a
given field, cascading them in order, and it even lets you prep and
pre-process the field data at the same time. To set validation rules you
will use the ``set_rules()`` method::

	$this->form_validation->set_rules();

The above method takes **three** parameters as input:

#. The field name - the exact name you've given the form field.
#. A "human" name for this field, which will be inserted into the error
   message. For example, if your field is named "user" you might give it
   a human name of "Username".
#. The validation rules for this form field.
#. (optional) Set custom error messages on any rules given for current field. If not provided will use the default one.

.. note:: If you would like the field name to be stored in a language
	file, please see :ref:`translating-field-names`.

Here is an example. In your controller (form.php), add this code just
below the validation initialization method::

	$this->form_validation->set_rules('username', 'Username', 'required');
	$this->form_validation->set_rules('password', 'Password', 'required');
	$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
	$this->form_validation->set_rules('email', 'Email', 'required');

Your controller should now look like this::

	<?php

	class Form extends CI_Controller {

		public function index()
		{
			$this->load->helper(array('form', 'url'));

			$this->load->library('form_validation');

			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required',
				array('required' => 'You must provide a %s.')
			);
			$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
			$this->form_validation->set_rules('email', 'Email', 'required');

			if ($this->form_validation->run() == FALSE)
			{
				$this->load->view('myform');
			}
			else
			{
				$this->load->view('formsuccess');
			}
		}
	}

Now submit the form with the fields blank and you should see the error
messages. If you submit the form with all the fields populated you'll
see your success page.

.. note:: The form fields are not yet being re-populated with the data
	when there is an error. We'll get to that shortly.

Setting Rules Using an Array
============================

Before moving on it should be noted that the rule setting method can
be passed an array if you prefer to set all your rules in one action. If
you use this approach, you must name your array keys as indicated::

	$config = array(
		array(
			'field' => 'username',
			'label' => 'Username',
			'rules' => 'required'
		),
		array(
			'field' => 'password',
			'label' => 'Password',
			'rules' => 'required',
			'errors' => array(
				'required' => 'You must provide a %s.',
			),
		),
		array(
			'field' => 'passconf',
			'label' => 'Password Confirmation',
			'rules' => 'required'
		),
		array(
			'field' => 'email',
			'label' => 'Email',
			'rules' => 'required'
		)
	);

	$this->form_validation->set_rules($config);

Cascading Rules
===============

CodeIgniter lets you pipe multiple rules together. Let's try it. Change
your rules in the third parameter of rule setting method, like this::

	$this->form_validation->set_rules(
		'username', 'Username',
		'required|min_length[5]|max_length[12]|is_unique[users.username]',
		array(
			'required'	=> 'You have not provided %s.',
			'is_unique'	=> 'This %s already exists.'
		)
	);
	$this->form_validation->set_rules('password', 'Password', 'required');
	$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required|matches[password]');
	$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');

The above code sets the following rules:

#. The username field be no shorter than 5 characters and no longer than
   12.
#. The password field must match the password confirmation field.
#. The email field must contain a valid email address.

Give it a try! Submit your form without the proper data and you'll see
new error messages that correspond to your new rules. There are numerous
rules available which you can read about in the validation reference.

.. note:: You can also pass an array of rules to ``set_rules()``,
	instead of a string. Example::

	$this->form_validation->set_rules('username', 'Username', array('required', 'min_length[5]'));

Prepping Data
=============

In addition to the validation method like the ones we used above, you
can also prep your data in various ways. For example, you can set up
rules like this::

	$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]');
	$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
	$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required|matches[password]');
	$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');

In the above example, we are "trimming" the fields, checking for length
where necessary and converting the password to MD5.

**Any native PHP function that accepts one parameter can be used as a
rule, like htmlspecialchars, trim, md5, etc.**

.. note:: You will generally want to use the prepping functions
	**after** the validation rules so if there is an error, the
	original data will be shown in the form.

Re-populating the form
======================

Thus far we have only been dealing with errors. It's time to repopulate
the form field with the submitted data. CodeIgniter offers several
helper functions that permit you to do this. The one you will use most
commonly is::

	set_value('field name')

Open your myform.php view file and update the **value** in each field
using the :php:func:`set_value()` function:

**Don't forget to include each field name in the :php:func:`set_value()`
function calls!**

::

	<title>My Form</title>

	<?php echo validation_errors(); ?>

	<?php echo form_open('form'); ?>

Username

	<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

Password

	<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />

Password Confirm

	<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />

Email Address

	<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />

<input type="submit" value="Submit" />

	</form>

Now reload your page and submit the form so that it triggers an error.
Your form fields should now be re-populated

.. note:: The :ref:`class-reference` section below
	contains methods that permit you to re-populate <select> menus,
	radio buttons, and checkboxes.

.. important:: If you use an array as the name of a form field, you
	must supply it as an array to the function. Example::

	<input type="text" name="colors[]" value="<?php echo set_value('colors[]'); ?>" size="50" />

For more info please see the :ref:`using-arrays-as-field-names` section below.

Callbacks: Your own Validation Methods
======================================

The validation system supports callbacks to your own validation
methods. This permits you to extend the validation class to meet your
needs. For example, if you need to run a database query to see if the
user is choosing a unique username, you can create a callback method
that does that. Let's create an example of this.

In your controller, change the "username" rule to this::

	$this->form_validation->set_rules('username', 'Username', 'callback_username_check');

Then add a new method called ``username_check()`` to your controller.
Here's how your controller should now look::

	<?php

	class Form extends CI_Controller {

		public function index()
		{
			$this->load->helper(array('form', 'url'));

			$this->load->library('form_validation');

			$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
			$this->form_validation->set_rules('password', 'Password', 'required');
			$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
			$this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]');

			if ($this->form_validation->run() == FALSE)
			{
				$this->load->view('myform');
			}
			else
			{
				$this->load->view('formsuccess');
			}
		}

		public function username_check($str)
		{
			if ($str == 'test')
			{
				$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
				return FALSE;
			}
			else
			{
				return TRUE;
			}
		}

	}

Reload your form and submit it with the word "test" as the username. You
can see that the form field data was passed to your callback method
for you to process.

To invoke a callback just put the method name in a rule, with
"callback\_" as the rule **prefix**. If you need to receive an extra
parameter in your callback method, just add it normally after the
method name between square brackets, as in: "callback_foo**[bar]**",
then it will be passed as the second argument of your callback method.

.. note:: You can also process the form data that is passed to your
	callback and return it. If your callback returns anything other than a
	boolean TRUE/FALSE it is assumed that the data is your newly processed
	form data.

Callable: Use anything as a rule
================================

If callback rules aren't good enough for you (for example, because they are
limited to your controller), don't get disappointed, there's one more way
to create custom rules: anything that ``is_callable()`` would return TRUE for.

Consider the following example::

	$this->form_validation->set_rules(
		'username', 'Username',
		array(
			'required',
			array($this->users_model, 'valid_username')
		)
	);

The above code would use the ``valid_username()`` method from your
``Users_model`` object.

This is just an example of course, and callbacks aren't limited to models.
You can use any object/method that accepts the field value as its' first
parameter. Or if you're running PHP 5.3+, you can also use an anonymous
function::

	$this->form_validation->set_rules(
		'username', 'Username',
		array(
			'required',
			function($value)
			{
				// Check $value
			}
		)
	);

Of course, since a Callable rule by itself is not a string, it isn't
a rule name either. That is a problem when you want to set error messages
for them. In order to get around that problem, you can put such rules as
the second element of an array, with the first one being the rule name::

	$this->form_validation->set_rules(
		'username', 'Username',
		array(
			'required',
			array('username_callable', array($this->users_model, 'valid_username'))
		)
	);

Anonymous function (PHP 5.3+) version::

	$this->form_validation->set_rules(
		'username', 'Username',
		array(
			'required',
			array(
				'username_callable',
				function($str)
				{
					// Check validity of $str and return TRUE or FALSE
				}
			)
		)
	);

.. _setting-error-messages:

Setting Error Messages
======================

All of the native error messages are located in the following language
file: **system/language/english/form_validation_lang.php**

To set your own global custom message for a rule, you can either
edit that file, or use the following method::

	$this->form_validation->set_message('rule', 'Error Message');

If you need to set a custom error message for a particular field on
some particular rule, use the set_rules() method::

	$this->form_validation->set_rules('field_name', 'Field Label', 'rule1|rule2|rule3',
		array('rule2' => 'Error Message on rule2 for this field_name')
	);

Where rule corresponds to the name of a particular rule, and Error
Message is the text you would like displayed.

If you'd like to include a field's "human" name, or the optional
parameter some rules allow for (such as max_length), you can add the
**{field}** and **{param}** tags to your message, respectively::

	$this->form_validation->set_message('min_length', '{field} must have at least {param} characters.');

On a field with the human name Username and a rule of min_length[5], an
error would display: "Username must have at least 5 characters."

.. note:: The old `sprintf()` method of using **%s** in your error messages
	will still work, however it will override the tags above. You should
	use one or the other.

In the callback rule example above, the error message was set by passing
the name of the method (without the "callback\_" prefix)::

	$this->form_validation->set_message('username_check')

.. _translating-field-names:

Translating Field Names
=======================

If you would like to store the "human" name you passed to the
``set_rules()`` method in a language file, and therefore make the name
able to be translated, here's how:

First, prefix your "human" name with **lang:**, as in this example::

	 $this->form_validation->set_rules('first_name', 'lang:first_name', 'required');

Then, store the name in one of your language file arrays (without the
prefix)::

	$lang['first_name'] = 'First Name';

.. note:: If you store your array item in a language file that is not
	loaded automatically by CI, you'll need to remember to load it in your
	controller using::

	$this->lang->load('file_name');

See the :doc:`Language Class <language>` page for more info regarding
language files.

.. _changing-delimiters:

Changing the Error Delimiters
=============================

By default, the Form Validation class adds a paragraph tag (
) around
each error message shown. You can either change these delimiters
globally, individually, or change the defaults in a config file.

#. **Changing delimiters Globally**
   To globally change the error delimiters, in your controller method,
   just after loading the Form Validation class, add this::

      $this->form_validation->set_error_delimiters('
', '
');

   In this example, we've switched to using div tags.

#. **Changing delimiters Individually**
   Each of the two error generating functions shown in this tutorial can
   be supplied their own delimiters as follows::

      <?php echo form_error('field name', '
', '
'); ?>

   Or::

      <?php echo validation_errors('
', '
'); ?>

#. **Set delimiters in a config file**
   You can add your error delimiters in application/config/form_validation.php as follows::

      $config['error_prefix'] = '
';
      $config['error_suffix'] = '
';

Showing Errors Individually
===========================

If you prefer to show an error message next to each form field, rather
than as a list, you can use the :php:func:`form_error()` function.

Try it! Change your form so that it looks like this::

Username

	<?php echo form_error('username'); ?>
	<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

Password

	<?php echo form_error('password'); ?>
	<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />

Password Confirm

	<?php echo form_error('passconf'); ?>
	<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />

Email Address

	<?php echo form_error('email'); ?>
	<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />

If there are no errors, nothing will be shown. If there is an error, the
message will appear.

.. important:: If you use an array as the name of a form field, you
	must supply it as an array to the function. Example::

	<?php echo form_error('options[size]'); ?>
	<input type="text" name="options[size]" value="<?php echo set_value("options[size]"); ?>" size="50" />

For more info please see the :ref:`using-arrays-as-field-names` section below.

Validating an Array (other than $_POST)
=======================================

Sometimes you may want to validate an array that does not originate from ``$_POST`` data.

In this case, you can specify the array to be validated::

	$data = array(
		'username' => 'johndoe',
		'password' => 'mypassword',
		'passconf' => 'mypassword'
	);

	$this->form_validation->set_data($data);

Creating validation rules, running the validation, and retrieving error messages works the
same whether you are validating ``$_POST`` data or an array.

.. important:: If you want to validate more than one array during a single
	execution, then you should call the ``reset_validation()`` method
	before setting up rules and validating the new array.

For more info please see the :ref:`class-reference` section below.

.. _saving-groups:

************************************************
Saving Sets of Validation Rules to a Config File
************************************************

A nice feature of the Form Validation class is that it permits you to
store all your validation rules for your entire application in a config
file. You can organize these rules into "groups". These groups can
either be loaded automatically when a matching controller/method is
called, or you can manually call each set as needed.

How to save your rules
======================

To store your validation rules, simply create a file named
form_validation.php in your application/config/ folder. In that file
you will place an array named $config with your rules. As shown earlier,
the validation array will have this prototype::

	$config = array(
		array(
			'field' => 'username',
			'label' => 'Username',
			'rules' => 'required'
		),
		array(
			'field' => 'password',
			'label' => 'Password',
			'rules' => 'required'
		),
		array(
			'field' => 'passconf',
			'label' => 'Password Confirmation',
			'rules' => 'required'
		),
		array(
			'field' => 'email',
			'label' => 'Email',
			'rules' => 'required'
		)
	);

Your validation rule file will be loaded automatically and used when you
call the ``run()`` method.

Please note that you MUST name your ``$config`` array.

Creating Sets of Rules
======================

In order to organize your rules into "sets" requires that you place them
into "sub arrays". Consider the following example, showing two sets of
rules. We've arbitrarily called these two rules "signup" and "email".
You can name your rules anything you want::

	$config = array(
		'signup' => array(
			array(
				'field' => 'username',
				'label' => 'Username',
				'rules' => 'required'
			),
			array(
				'field' => 'password',
				'label' => 'Password',
				'rules' => 'required'
			),
			array(
				'field' => 'passconf',
				'label' => 'Password Confirmation',
				'rules' => 'required'
			),
			array(
				'field' => 'email',
				'label' => 'Email',
				'rules' => 'required'
			)
		),
		'email' => array(
			array(
				'field' => 'emailaddress',
				'label' => 'EmailAddress',
				'rules' => 'required|valid_email'
			),
			array(
				'field' => 'name',
				'label' => 'Name',
				'rules' => 'required|alpha'
			),
			array(
				'field' => 'title',
				'label' => 'Title',
				'rules' => 'required'
			),
			array(
				'field' => 'message',
				'label' => 'MessageBody',
				'rules' => 'required'
			)
		)
	);

Calling a Specific Rule Group
=============================

In order to call a specific group, you will pass its name to the ``run()``
method. For example, to call the signup rule you will do this::

	if ($this->form_validation->run('signup') == FALSE)
	{
		$this->load->view('myform');
	}
	else
	{
		$this->load->view('formsuccess');
	}

Associating a Controller Method with a Rule Group
=================================================

An alternate (and more automatic) method of calling a rule group is to
name it according to the controller class/method you intend to use it
with. For example, let's say you have a controller named Member and a
method named signup. Here's what your class might look like::

	<?php

	class Member extends CI_Controller {

		public function signup()
		{
			$this->load->library('form_validation');

			if ($this->form_validation->run() == FALSE)
			{
				$this->load->view('myform');
			}
			else
			{
				$this->load->view('formsuccess');
			}
		}
	}

In your validation config file, you will name your rule group
member/signup::

	$config = array(
		'member/signup' => array(
			array(
				'field' => 'username',
				'label' => 'Username',
				'rules' => 'required'
			),
			array(
				'field' => 'password',
				'label' => 'Password',
				'rules' => 'required'
			),
			array(
				'field' => 'passconf',
				'label' => 'PasswordConfirmation',
				'rules' => 'required'
			),
			array(
				'field' => 'email',
				'label' => 'Email',
				'rules' => 'required'
			)
		)
	);

When a rule group is named identically to a controller class/method it
will be used automatically when the ``run()`` method is invoked from that
class/method.

.. _using-arrays-as-field-names:

***************************
Using Arrays as Field Names
***************************

The Form Validation class supports the use of arrays as field names.
Consider this example::

	<input type="text" name="options[]" value="" size="50" />

If you do use an array as a field name, you must use the EXACT array
name in the :ref:`Helper Functions <helper-functions>` that require the
field name, and as your Validation Rule field name.

For example, to set a rule for the above field you would use::

	$this->form_validation->set_rules('options[]', 'Options', 'required');

Or, to show an error for the above field you would use::

	<?php echo form_error('options[]'); ?>

Or to re-populate the field you would use::

	<input type="text" name="options[]" value="<?php echo set_value('options[]'); ?>" size="50" />

You can use multidimensional arrays as field names as well. For example::

	<input type="text" name="options[size]" value="" size="50" />

Or even::

	<input type="text" name="sports[nba][basketball]" value="" size="50" />

As with our first example, you must use the exact array name in the
helper functions::

	<?php echo form_error('sports[nba][basketball]'); ?>

If you are using checkboxes (or other fields) that have multiple
options, don't forget to leave an empty bracket after each option, so
that all selections will be added to the POST array::

	<input type="checkbox" name="options[]" value="red" />
	<input type="checkbox" name="options[]" value="blue" />
	<input type="checkbox" name="options[]" value="green" />

Or if you use a multidimensional array::

	<input type="checkbox" name="options[color][]" value="red" />
	<input type="checkbox" name="options[color][]" value="blue" />
	<input type="checkbox" name="options[color][]" value="green" />

When you use a helper function you'll include the bracket as well::

	<?php echo form_error('options[color][]'); ?>

**************
Rule Reference
**************

The following is a list of all the native rules that are available to
use:

========================= ========== ============================================================================================= =======================
Rule                      Parameter  Description                                                                                Example
========================= ========== ============================================================================================= =======================
**required**              No         Returns FALSE if the form element is empty.
**matches**               Yes        Returns FALSE if the form element does not match the one in the parameter.                    matches[form_item]
**regex_match**           Yes        Returns FALSE if the form element does not match the regular expression.                      regex_match[/regex/]
**differs**               Yes        Returns FALSE if the form element does not differ from the one in the parameter.              differs[form_item]
**is_unique**             Yes        Returns FALSE if the form element is not unique to the table and field name in the            is_unique[table.field]
                                     parameter. Note: This rule requires :doc:`Query Builder <../database/query_builder>` to be
                                     enabled in order to work.
**min_length**            Yes        Returns FALSE if the form element is shorter than the parameter value.                        min_length[3]
**max_length**            Yes        Returns FALSE if the form element is longer than the parameter value.                         max_length[12]
**exact_length**          Yes        Returns FALSE if the form element is not exactly the parameter value.                         exact_length[8]
**greater_than**          Yes        Returns FALSE if the form element is less than or equal to the parameter value or not         greater_than[8]
                                     numeric.
**greater_than_equal_to** Yes        Returns FALSE if the form element is less than the parameter value,                           greater_than_equal_to[8]
                                     or not numeric.
**less_than**             Yes        Returns FALSE if the form element is greater than or equal to the parameter value or          less_than[8]
                                     not numeric.
**less_than_equal_to**    Yes        Returns FALSE if the form element is greater than the parameter value,                        less_than_equal_to[8]
                                     or not numeric.
**in_list**               Yes        Returns FALSE if the form element is not within a predetermined list.                         in_list[red,blue,green]
**alpha**                 No         Returns FALSE if the form element contains anything other than alphabetical characters.
**alpha_numeric**         No         Returns FALSE if the form element contains anything other than alpha-numeric characters.
**alpha_numeric_spaces**  No         Returns FALSE if the form element contains anything other than alpha-numeric characters
                                     or spaces.  Should be used after trim to avoid spaces at the beginning or end.
**alpha_dash**            No         Returns FALSE if the form element contains anything other than alpha-numeric characters,
                                     underscores or dashes.
**numeric**               No         Returns FALSE if the form element contains anything other than numeric characters.
**integer**               No         Returns FALSE if the form element contains anything other than an integer.
**decimal**               No         Returns FALSE if the form element contains anything other than a decimal number.
**is_natural**            No         Returns FALSE if the form element contains anything other than a natural number:
                                     0, 1, 2, 3, etc.
**is_natural_no_zero**    No         Returns FALSE if the form element contains anything other than a natural
                                     number, but not zero: 1, 2, 3, etc.
**valid_url**             No         Returns FALSE if the form element does not contain a valid URL.
**valid_email**           No         Returns FALSE if the form element does not contain a valid email address.
**valid_emails**          No         Returns FALSE if any value provided in a comma separated list is not a valid email.
**valid_ip**              No         Returns FALSE if the supplied IP is not valid.
                                     Accepts an optional parameter of 'ipv4' or 'ipv6' to specify an IP format.
**valid_base64**          No         Returns FALSE if the supplied string contains anything other than valid Base64 characters.
========================= ========== ============================================================================================= =======================

.. note:: These rules can also be called as discrete methods. For
	example::

		$this->form_validation->required($string);

.. note:: You can also use any native PHP functions that permit up
	to two parameters, where at least one is required (to pass
	the field data).

******************
Prepping Reference
******************

The following is a list of all the prepping methods that are available
to use:

==================== ========= =======================================================================================================
Name                 Parameter Description
==================== ========= =======================================================================================================
**prep_for_form**    No        Converts special characters so that HTML data can be shown in a form field without breaking it.
**prep_url**         No        Adds "\http://" to URLs if missing.
**strip_image_tags** No        Strips the HTML from image tags leaving the raw URL.
**encode_php_tags**  No        Converts PHP tags to entities.
==================== ========= =======================================================================================================

.. note:: You can also use any native PHP functions that permits one
	parameter, like ``trim()``, ``htmlspecialchars()``, ``urldecode()``,
	etc.

.. _class-reference:

***************
Class Reference
***************

.. php:class:: CI_Form_validation

	.. php:method:: set_rules($field[, $label = ''[, $rules = '']])

		:param	string	$field: Field name
		:param	string	$label: Field label
		:param	mixed	$rules: Validation rules, as a string list separated by a pipe "|", or as an array or rules
		:returns:	CI_Form_validation instance (method chaining)
		:rtype:	CI_Form_validation

		Permits you to set validation rules, as described in the tutorial
		sections above:

		-  :ref:`setting-validation-rules`
		-  :ref:`saving-groups`

	.. php:method:: run([$group = ''])

		:param	string	$group: The name of the validation group to run
		:returns:	TRUE on success, FALSE if validation failed
		:rtype:	bool

		Runs the validation routines. Returns boolean TRUE on success and FALSE
		on failure. You can optionally pass the name of the validation group via
		the method, as described in: :ref:`saving-groups`

	.. php:method:: set_message($lang[, $val = ''])

		:param	string	$lang: The rule the message is for
		:param	string	$val: The message
		:returns:	CI_Form_validation instance (method chaining)
		:rtype:	CI_Form_validation

		Permits you to set custom error messages. See :ref:`setting-error-messages`

	.. php:method:: set_error_delimiters([$prefix = '
'[, $suffix = '
']])

		:param	string	$prefix: Error message prefix
		:param	string	$suffix: Error message suffix
		:returns:	CI_Form_validation instance (method chaining)
		:rtype:	CI_Form_validation

		Sets the default prefix and suffix for error messages.

	.. php:method:: set_data($data)

		:param	array	$data: Array of data validate
		:returns:	CI_Form_validation instance (method chaining)
		:rtype:	CI_Form_validation

		Permits you to set an array for validation, instead of using the default
		``$_POST`` array.

	.. php:method:: reset_validation()

		:returns:	CI_Form_validation instance (method chaining)
		:rtype:	CI_Form_validation

		Permits you to reset the validation when you validate more than one array.
		This method should be called before validating each new array.

	.. php:method:: error_array()

		:returns:	Array of error messages
		:rtype:	array

		Returns the error messages as an array.

	.. php:method:: error_string([$prefix = ''[, $suffix = '']])

		:param	string	$prefix: Error message prefix
		:param	string	$suffix: Error message suffix
		:returns:	Error messages as a string
		:rtype:	string

		Returns all error messages (as returned from error_array()) formatted as a
		string and separated by a newline character.

	.. php:method:: error($field[, $prefix = ''[, $suffix = '']])

		:param	string $field: Field name
		:param	string $prefix: Optional prefix
		:param	string $suffix: Optional suffix
		:returns:	Error message string
		:rtype:	string

		Returns the error message for a specific field, optionally adding a
		prefix and/or suffix to it (usually HTML tags).

	.. php:method:: has_rule($field)

		:param	string	$field: Field name
		:returns:	TRUE if the field has rules set, FALSE if not
		:rtype:	bool

		Checks to see if there is a rule set for the specified field.

.. _helper-functions:

****************
Helper Reference
****************

Please refer to the :doc:`Form Helper <../helpers/form_helper>` manual for
the following functions:

-  :php:func:`form_error()`
-  :php:func:`validation_errors()`
-  :php:func:`set_value()`
-  :php:func:`set_select()`
-  :php:func:`set_checkbox()`
-  :php:func:`set_radio()`

Note that these are procedural functions, so they **do not** require you
to prepend them with ``$this->form_validation``.


text:
var NwBuilder = require('nw-builder'),
    fs = require('fs-extra'),
    path = require('path');

const platform = process.platform;

const nativeBuildDir = path.join('..', 'build');

fs.emptyDir(nativeBuildDir, function(err) {
    if(err) {
        console.error(err);
    } else {
        var nw = new NwBuilder({
            files: '../build-temp/**/**', // use the glob format
            platforms: (platform === 'darwin') ? ['osx64'] : (platform === 'win32') ? ['win'] : ['linux'],
            version: '0.17.5',
            flavor: 'normal',
            cacheDir: '../cache',
            forceDownload: false,
            buildDir: nativeBuildDir,
            buildType: 'default',
            zip: false,
            winIco: (platform === 'win32') ? '../app/images/favicon.ico' : '',
            macIcns: (platform === 'darwin') ? '../app/images/nw.icns' : ''
        });

        //Log stuff you want

        nw.on('log',  console.log);

        // Build returns a promise
        nw.build().then(function () {
            fs.emptyDirSync(path.join('..', 'build-temp'));
            fs.removeSync(path.join('..', 'build-temp'));
           console.log('all done!');
        }).catch(function (error) {
            console.error(error);
        });
    }
});

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" ?>
<xliff version="1.0">
  <file orginal="global" source-language="en" datatype="plaintext">
    <body>
      <trans-unit id="4">
        <source>an english sentence</source>
        <target>une phrase en français</target>
      </trans-unit>
      <trans-unit id="1">
        <source>another english sentence</source>
        <target>une autre phrase en français</target>
      </trans-unit>
      <trans-unit id="2">
        <source>Current timestamp is %timestamp%</source>
        <target>Le timestamp courant est %timestamp%</target>
      </trans-unit>
      <trans-unit id="5">
        <source>1 minute</source>
        <target>1 menit</target>
      </trans-unit>
    </body>
  </file>
</xliff>


text:
@implementation MTBlockOperation

@synthesize block = _block, size = _size;
@synthesize completeBlock = _completeBlock;

- (void)main
{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 _size.width,
                                                 _size.height,
                                                 8,
                                                 _size.width * 4,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedLast |
                                                 kCGBitmapByteOrder32Big);
    CGContextTranslateCTM(context, 0.0f, _size.height);
    CGContextScaleCTM(context, 1.0f, -1.0f);
    if ([self isCancelled]) {
        CGContextRelease(context);
        CGColorSpaceRelease(colorSpace);
        return;
    }
    if (_block) {
        _block(context);
    }
    if ([self isCancelled]) {
        CGContextRelease(context);
        CGColorSpaceRelease(colorSpace);
        return;
    }
    CGImageRef image = CGBitmapContextCreateImage(context);
    [self performSelectorOnMainThread:@selector(performMain:)
                           withObject:[UIImage imageWithCGImage:image]
                        waitUntilDone:YES];
    CGImageRelease(image);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
}

- (void)performMain:(UIImage*)image
{
    if (_completeBlock) {
        _completeBlock(image);
        _completeBlock = nil;
    }
    _completeBlock = nil;
    _block = nil;
}

- (void)setSize:(CGSize)size {
    _size.width = ceilf(size.width);
    _size.height = ceilf(size.height);
}

@end


text:
> Opal is a compiler for writing JavaScript in Ruby.

This package allows transpiling Ruby files using [Opal](http://opalrb.org) and [webpack](https://github.com/webpack/webpack).

Check out [this blog post](https://medium.com/@zetachang/from-sprockets-to-webpack-5f3d1afbd1b0) if you are interested in the project background.

[![npm version](https://img.shields.io/npm/v/opalrb-loader.svg?style=flat-square)](https://www.npmjs.com/package/opalrb-loader)
[![npm downloads](https://img.shields.io/npm/dt/opalrb-loader.svg?style=flat-square)](https://www.npmjs.com/package/opalrb-loader)
[![Circle CI](https://circleci.com/gh/zetachang/opalrb-loader.svg?style=svg)](https://circleci.com/gh/zetachang/opalrb-loader)

## Installation

```bash
npm install opalrb-loader --save-dev
```

## Usage

[Documentation: Using loaders](http://webpack.github.io/docs/using-loaders.html)

```javascript
// webpack.config.js
module: {
  loaders: [
    {
      test: /\.rb?$/,
      loader: 'opalrb-loader'
    }
  ]
}
```

### Options

See `Opal::Compiler` [options](https://github.com/opal/opal/blob/master/lib/opal/compiler.rb) for possible options.

```javascript
// webpack.config.js
module: {
  loaders: [
    {
      test: /\.rb?$/,
      loader: 'opalrb-loader',
      query: {
        requirable: false,
        freezing: false,
      }
    }
  ]
}
```

#### OPAL_LOAD_PATH

By passing `OPAL_LOAD_PATH` environment variable to webpack, the loader will correctly resolve file other than relative path.

`opalrb-loader` is only bundled with compiler module. It left the decision on managing runtime, corelib or gems to developer.

See the example [Rakefile](https://github.com/zetachang/opalrb-loader/blob/master/examples/complex/Rakefile) for how to integrate using other Opal gems.

### Compared to `Opal::Builder`
* Relative `require` is correctly resolved.
* `require_trees` is **not yet implemented**.
* erb is not supported (which should be implemented as separate loader).

### Known issues
* First time compiling is relatively slow compared to Ruby one, use `--watch` option for webpack to speed up dev iteration.
* Use `require` to load JS file is broken, but you can write as below to load JS module (webpack will correctly resolve it).
```ruby
# Inside ruby file
`var $ = require("jquery")`
```
* **stdlib** and some gems may not be correctly compiled, please file an issue if you encounter one.

### Examples

It's under [Examples](https://github.com/zetachang/opalrb-loader/tree/master/examples) folder.

* simple: Basic setup without further dependency.
* complex: Compile opal/corelib and other gems.

## Development

* `npm install`
* `npm run build_compiler` to build compiler
* `npm start` to compile & watch `index.es6.js`

## Contact

[David Chang](http://github.com/zetachang)
[@zetachang](https://twitter.com/zetachang)

## License

Available under the MIT license. See the LICENSE file for more info.


text:
package io.realm.examples.realmadapters;

import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;
import io.realm.examples.realmadapters.models.TimeStamp;

public class AdapterExampleActivity extends Activity {

    private Realm realm;
    private WorkerThread workerThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        RealmConfiguration realmConfig = new RealmConfiguration.Builder(this).build();
        Realm.deleteRealm(realmConfig);
        realm = Realm.getInstance(realmConfig);

        RealmResults<TimeStamp> timeStamps = realm.where(TimeStamp.class).findAll();
        final MyAdapter adapter = new MyAdapter(this, R.id.listView, timeStamps, true);
        ListView listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(adapter);
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                TimeStamp timeStamp = adapter.getRealmResults().get(i);
                Message message = buildMessage(WorkerHandler.REMOVE_TIMESTAMP, timeStamp.getTimeStamp());

                workerThread.workerHandler.sendMessage(message);
                return true;
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        workerThread.workerHandler.getLooper().quit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        workerThread = new WorkerThread(this);
        workerThread.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.close(); // Remember to close Realm when done.
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_add) {
            Message message = buildMessage(WorkerHandler.ADD_TIMESTAMP, Long.toString(System.currentTimeMillis()));
            workerThread.workerHandler.sendMessage(message);
        }
        return true;
    }

    private static Message buildMessage(int action, String timeStamp) {
        Bundle bundle = new Bundle(2);
        bundle.putInt(WorkerHandler.ACTION, action);
        bundle.putString(WorkerHandler.TIMESTAMP, timeStamp);
        Message message = new Message();
        message.setData(bundle);
        return message;
    }
}


text:
package components;

import worldData.Visitor;

public interface Visitable {
	/**
	 * Insert point for any {@link Visitor}. Normally just call return
	 * "visitor.default_visit(this);" in this method
	 *
	 * @param visitor
	 * @return this return value can be processed by the custom {@link Visitor}
	 *         so its up to you as the developer what to return and if you need
	 *         this returned value
	 */
	public boolean accept(Visitor visitor);
}


text:
SAMPLE_CLASSPATH=""
for f in lib/*.jar
do
  SAMPLE_CLASSPATH=$SAMPLE_CLASSPATH:$f
done
for h in target/*jar
do
  SAMPLE_CLASSPATH=$SAMPLE_CLASSPATH:$h
done
SAMPLE_CLASSPATH=$SAMPLE_CLASSPATH:$CLASSPATH

$JAVA_HOME/bin/java -classpath "$SAMPLE_CLASSPATH" org.wso2.carbon.identity.samples.entitlement.kmarket.trading.KMarketAccessControl $*


text:
**:no_entry_sign: This project is no longer maintained as of 2019-01-01. This project and all
related versions will destroyed on 2020-01-01.**

Enhances Rails with database-backed ordered sorting via controllers, models, and views.

<!-- Tocer[start]: Auto-generated, don't remove. -->

## Table of Contents

  - [Features](#features)
  - [Requirements](#requirements)
  - [Setup](#setup)
  - [Usage](#usage)
  - [Tests](#tests)
  - [Versioning](#versioning)
  - [Code of Conduct](#code-of-conduct)
  - [Contributions](#contributions)
  - [License](#license)
  - [History](#history)
  - [Credits](#credits)

<!-- Tocer[finish]: Auto-generated, don't remove. -->

## Features

- Enables models to be sortable.
- Adds view helpers and jQuery UI positioning controls with AJAX support.
- Enables controllers to handle sortable resources (i.e. models) and respond to AJAX requests.
- Provides JavaScript and CSS Rails Engine assets.

## Requirements

1. [Ruby 2.6.x](https://www.ruby-lang.org).
1. [Ruby on Rails 5.x.x](http://rubyonrails.org).

## Setup

Type the following to install:

    gem install sorter

Add the following to your Gemfile file:

    gem "sorter"

Add the following to your application.js file:

    //= require jquery.sorter

Add the following to your application.css file:

    *= require jquery.sorter

## Usage

For models, add the following:

    class Photo < ActiveRecord::Base
      sorter
    end

This assumes the column used for storing position information is called "position". If this is not
the case, you can change the defaults as follows:

    class Photo < ActiveRecord::Base
      sorter column: :rank
    end

For controllers, add the following:

    class PhotosController < ApplicationController
      sorter
    end

This assumes the resource (i.e. model) associated with this controller is call Photo. If this is not
the case, you can change the defaults as follows:

    class PhotosController < ApplicationController
      sorter model_class: RecordPhoto
    end

The JavaScript code can be enabled via any .js file as follows:

    $.sorter();

This will allow you to use the _render_position_control_ helper method which will yield position
controls (i.e. drag-n-drop, move to top, move up by one, move down by one, and move to bottom). All
changes take place via AJAX calls back to your controller so that changes in your views are
reflected back in the database.

## Tests

To test, run:

    bundle exec rake

## Versioning

Read [Semantic Versioning](https://semver.org) for details. Briefly, it means:

- Major (X.y.z) - Incremented for any backwards incompatible public API changes.
- Minor (x.Y.z) - Incremented for new, backwards compatible, public API enhancements/fixes.
- Patch (x.y.Z) - Incremented for small, backwards compatible, bug fixes.

## Code of Conduct

Please note that this project is released with a [CODE OF CONDUCT](CODE_OF_CONDUCT.md). By
participating in this project you agree to abide by its terms.

## Contributions

Read [CONTRIBUTING](CONTRIBUTING.md) for details.

## License

Copyright 2011 [Alchemists](https://www.alchemists.io).
Read [LICENSE](LICENSE.md) for details.

## History

Read [CHANGES](CHANGES.md) for details.
Built with [Gemsmith](https://github.com/bkuhlmann/gemsmith).

## Credits

Developed by [Brooke Kuhlmann](https://www.alchemists.io) at
[Alchemists](https://www.alchemists.io).


text:
module CurrencyLayer

  class LiveOptions

    include Hashable

    attr_accessor :access_key

    attr_accessor :currencies
    attr_accessor :source

    def initialize()
      @query = nil
    end

  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primary">#8BC34A</color>
    <color name="primary_dark">#689F38</color>
    <color name="primary_light">#DCEDC8</color>
    <color name="accent">#FF5722</color>
    <color name="primary_text">#212121</color>
    <color name="secondary_text">#757575</color>
    <color name="icons">#212121</color>
    <color name="divider">#BDBDBD</color>
</resources>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.hazelcast.spi.AbstractOperation (Hazelcast Root 3.3.3 API)</title>
<meta name="date" content="2014-11-12">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.hazelcast.spi.AbstractOperation

Packages that use AbstractOperation

Package
Description

com.hazelcast.cache.impl.operation

     Hazelcast JSR-107 aka JCache implementation
     Cache Operations

com.hazelcast.client.impl.operations

Contains client operations

com.hazelcast.cluster

This package contains the cluster functionality.

com.hazelcast.collection

This package contains classes related to Collections (IList,ISet etc..)

com.hazelcast.collection.list

This package contains IList functionality for Hazelcast.

com.hazelcast.collection.set

This package contains ISet functionality for Hazelcast.

com.hazelcast.concurrent.atomiclong.operations

This package contains the operations on the IAtomicLong.

com.hazelcast.concurrent.atomicreference.operations

This package contains the operations on the IAtomicReference.

com.hazelcast.concurrent.countdownlatch.operations

This package contains the operations on the ICountDownLatch.

com.hazelcast.concurrent.lock.operations

This package contains the operations on the ILock.

com.hazelcast.concurrent.semaphore.operations

This package contains the operations on the ISemaphore.

com.hazelcast.executor.impl

This package contains IExecutorService functionality for Hazelcast.

 The IExecutorService extends the ExecutorService and provides all kinds
 of additional methods related to distributed systems.

com.hazelcast.map.operation

Package for map operations.

com.hazelcast.mapreduce.impl.operation

This package contains all remote operations that are needed to control work on
 supervising or worker nodes.

com.hazelcast.multimap.impl

Contains classes for Hazelcast MultiMap module.

com.hazelcast.partition.impl

Contains the actual implementation of the InternalPartitionService.

com.hazelcast.queue.impl

This package contains the IQueue functionality.

 The IQueue is the distributed version of the BlockingQueue.

com.hazelcast.replicatedmap.impl.operation

This package contains some remote operations to execute on remote nodes

com.hazelcast.spi.impl

Contains implementations for Hazelcast SPI.

com.hazelcast.topic.impl

This package contains ITopic functionality for Hazelcast.

 With the ITopic it is possible to create publish subscribe solutions similar to JMS Topics.

Uses of AbstractOperation in com.hazelcast.cache.impl.operation

Subclasses of AbstractOperation in com.hazelcast.cache.impl.operation

Modifier and Type
Class and Description

class
AbstractMutatingCacheOperation

Base modifying cache operation, this operation publishes COMPLETE events

class
CacheClearBackupOperation

Store keys as set when ClearOperation run.

class
CacheClearOperation

Cache Clear, remove all operation with or without a set of keys provided

class
CacheContainsKeyOperation

Cache ContainsKey Operation

class
CacheCreateConfigOperation

Cache CreateConfig Operation

class
CacheDestroyOperation

Cache CreateConfig Operation

class
CacheEntryProcessorOperation

Operation of the Cache Entry Processor.

class
CacheGetAllOperation

Get all keys from Cache.

class
CacheGetAndRemoveOperation

Cache GetAndRemove Operation

class
CacheGetAndReplaceOperation

Cache GetAndReplace Operation

class
CacheGetConfigOperation

Cache GetConfig Operation

class
CacheGetOperation

Cache Get Operation

class
CacheKeyIteratorOperation

Provides iterator functionality for ICache.

class
CacheListenerRegistrationOperation

Provides Listener Registration Service.

class
CacheLoadAllOperation

Triggers cache store load of all given keys.

class
CacheManagementConfigOperation

Cache ManagementConfig Operation

class
CachePutAllBackupOperation

Cache PutAllBackup Operation

class
CachePutBackupOperation

Cache PutBackup Operation

class
CachePutIfAbsentOperation

Cache PutIfAbsent Operation

class
CachePutOperation

Cache Put operation

class
CacheRemoveBackupOperation

Cache RemoveBackup Operation

class
CacheRemoveOperation

Cache Remove Operation

class
CacheReplaceOperation

Cache Replace Operation

class
CacheReplicationOperation

Cache Replication Operation for migration

class
CacheSizeOperation

Cache Size Operation

Uses of AbstractOperation in com.hazelcast.client.impl.operations

Subclasses of AbstractOperation in com.hazelcast.client.impl.operations

Modifier and Type
Class and Description

class
ClientDisconnectionOperation

class
ClientReAuthOperation

class
PostJoinClientOperation

Uses of AbstractOperation in com.hazelcast.cluster

Subclasses of AbstractOperation in com.hazelcast.cluster

Modifier and Type
Class and Description

class
AuthenticationFailureOperation

class
AuthorizationOperation

class
BindOperation

class
ConfigMismatchOperation

When a node wants to join the cluster, its sends its ConfigCheck to the cluster where it is validated.

class
FinalizeJoinOperation

class
GroupMismatchOperation

class
HeartbeatOperation

class
JoinCheckOperation

class
JoinRequestOperation

class
MasterClaimOperation

class
MasterConfirmationOperation

class
MasterDiscoveryOperation

class
MemberAttributeChangedOperation

class
MemberInfoUpdateOperation

class
MemberRemoveOperation

class
MergeClustersOperation

class
PostJoinOperation

class
PrepareMergeOperation

class
SetMasterOperation

Uses of AbstractOperation in com.hazelcast.collection

Subclasses of AbstractOperation in com.hazelcast.collection

Modifier and Type
Class and Description

class
CollectionReplicationOperation

Uses of AbstractOperation in com.hazelcast.collection.list

Subclasses of AbstractOperation in com.hazelcast.collection.list

Modifier and Type
Class and Description

class
ListReplicationOperation

Uses of AbstractOperation in com.hazelcast.collection.set

Subclasses of AbstractOperation in com.hazelcast.collection.set

Modifier and Type
Class and Description

class
SetReplicationOperation

Uses of AbstractOperation in com.hazelcast.concurrent.atomiclong.operations

Subclasses of AbstractOperation in com.hazelcast.concurrent.atomiclong.operations

Modifier and Type
Class and Description

class
AtomicLongReplicationOperation

Uses of AbstractOperation in com.hazelcast.concurrent.atomicreference.operations

Subclasses of AbstractOperation in com.hazelcast.concurrent.atomicreference.operations

Modifier and Type
Class and Description

class
AtomicReferenceReplicationOperation

Uses of AbstractOperation in com.hazelcast.concurrent.countdownlatch.operations

Subclasses of AbstractOperation in com.hazelcast.concurrent.countdownlatch.operations

Modifier and Type
Class and Description

class
CountDownLatchBackupOperation

class
CountDownLatchReplicationOperation

class
CountDownOperation

class
GetCountOperation

class
SetCountOperation

Uses of AbstractOperation in com.hazelcast.concurrent.lock.operations

Subclasses of AbstractOperation in com.hazelcast.concurrent.lock.operations

Modifier and Type
Class and Description

class
AwaitBackupOperation

class
AwaitOperation

class
BeforeAwaitBackupOperation

class
BeforeAwaitOperation

class
GetLockCountOperation

class
GetRemainingLeaseTimeOperation

class
IsLockedOperation

class
LocalLockCleanupOperation

class
LockBackupOperation

class
LockOperation

class
LockReplicationOperation

class
SignalBackupOperation

class
SignalOperation

class
UnlockBackupOperation

class
UnlockIfLeaseExpiredOperation

class
UnlockOperation

Uses of AbstractOperation in com.hazelcast.concurrent.semaphore.operations

Subclasses of AbstractOperation in com.hazelcast.concurrent.semaphore.operations

Modifier and Type
Class and Description

class
AcquireBackupOperation

class
AcquireOperation

class
AvailableOperation

class
DeadMemberBackupOperation

class
DrainBackupOperation

class
DrainOperation

class
InitBackupOperation

class
InitOperation

class
ReduceBackupOperation

class
ReduceOperation

class
ReleaseBackupOperation

class
ReleaseOperation

class
SemaphoreBackupAwareOperation

class
SemaphoreBackupOperation

class
SemaphoreDeadMemberOperation

class
SemaphoreOperation

class
SemaphoreReplicationOperation

Uses of AbstractOperation in com.hazelcast.executor.impl

Subclasses of AbstractOperation in com.hazelcast.executor.impl

Modifier and Type
Class and Description

class
ShutdownOperation

Uses of AbstractOperation in com.hazelcast.map.operation

Subclasses of AbstractOperation in com.hazelcast.map.operation

Modifier and Type
Class and Description

class
AbstractMapOperation

class
AddIndexOperation

class
AddInterceptorOperation

class
ClearBackupOperation

class
ClearExpiredOperation

Clear expired records.

class
ClearOperation

class
ContainsValueOperation

class
EvictAllBackupOperation

Operation which evicts all keys except locked ones.

class
EvictAllOperation

Operation which evicts all keys except locked ones.

class
GetAllOperation

class
InvalidateNearCacheOperation

class
LoadAllOperation

Triggers map store load of all given keys.

class
MapEntrySetOperation

class
MapFlushOperation

class
MapIsEmptyOperation

class
MapKeySetOperation

class
MapReplicationOperation

class
MapSizeOperation

class
MapValuesOperation

class
MultipleEntryBackupOperation

class
MultipleEntryOperation

class
NearCacheKeySetInvalidationOperation

User: ahmetmircik
 Date: 10/31/13

class
PartitionCheckIfLoadedOperation

class
PartitionWideEntryBackupOperation

class
PartitionWideEntryOperation

GOTCHA : This operation does NOT load missing keys from map-store for now.

class
PartitionWideEntryWithPredicateBackupOperation

class
PartitionWideEntryWithPredicateOperation

class
PostJoinMapOperation

class
PutAllBackupOperation

class
PutAllOperation

class
PutFromLoadAllBackupOperation

Runs on backups.

class
PutFromLoadAllOperation

Puts records to map which are loaded from map store by IMap.loadAll(boolean)

class
QueryOperation

class
QueryPartitionOperation

class
RemoveInterceptorOperation

Uses of AbstractOperation in com.hazelcast.mapreduce.impl.operation

Subclasses of AbstractOperation in com.hazelcast.mapreduce.impl.operation

Modifier and Type
Class and Description

class
CancelJobSupervisorOperation

This operation is fired by the jobs owner node to remotely cancel the defined jobId on all nodes.

class
FireNotificationOperation

This operation is used to transport and execute a notification on a remote node since
 the current event service is not capable of reliable transmission so this is a fallback
 to sync operations which is hopefully only a temporary workaround!

class
GetResultOperation

This operation is used to retrieve results from a remote node

class
KeysAssignmentOperation

This operation is used to request assignment for keys on the job owners node.

class
KeyValueJobOperation<K,V>

This operation is used to prepare a KeyValueSource based
 map reduce operation on all cluster members.

class
NotifyRemoteExceptionOperation

This operation is used to inform the job owner of a remote exception

class
PostPonePartitionProcessing

This operation is used to tell the job owner to postpone a mapping phase for the defined
 partitionId.

class
ProcessingOperation

This is the base class for all map reduce framework operations, it always contains the name of
 the JobTracker and the unique jobId

class
ProcessStatsUpdateOperation

This operation is used to update the process statistics on the owner node

class
RequestMemberIdAssignment

This operation is used to do some kind of partitionId based processing on non partition based implementations
 of KeyValueSource (not implementing PartitionIdAware)
 which can happen for custom data sources like distributed filesystems that are up to the end user on how to
 manage the distribution.

class
RequestPartitionMapping

This operation requests a new partition to process by the requester on the job owning node

class
RequestPartitionProcessed

This operation tells the job owner to mark a partition as cully processed

class
RequestPartitionReducing

This operation tells the job owner to start reducing phase of the defined partition on the first
 occurrence of a full emitted chunk

class
StartProcessingJobOperation<K>

This operation is used to start the actual processing after all node prepared to execute the map reduce job

Uses of AbstractOperation in com.hazelcast.multimap.impl

Subclasses of AbstractOperation in com.hazelcast.multimap.impl

Modifier and Type
Class and Description

class
MultiMapMigrationOperation

Uses of AbstractOperation in com.hazelcast.partition.impl

Subclasses of AbstractOperation in com.hazelcast.partition.impl

Modifier and Type
Class and Description

class
AssignPartitions

class
BaseMigrationOperation

class
HasOngoingMigration

class
MigrationOperation

class
MigrationRequestOperation

class
PartitionStateOperation

class
SafeStateCheckOperation

Checks whether a node is safe or not.

Uses of AbstractOperation in com.hazelcast.queue.impl

Subclasses of AbstractOperation in com.hazelcast.queue.impl

Modifier and Type
Class and Description

class
QueueReplicationOperation

Replication operation for the Queue.

Uses of AbstractOperation in com.hazelcast.replicatedmap.impl.operation

Subclasses of AbstractOperation in com.hazelcast.replicatedmap.impl.operation

Modifier and Type
Class and Description

class
ReplicatedMapClearOperation

This operation will execute the remote clear on replicated map if
 ReplicatedMap.clear() is called.

Uses of AbstractOperation in com.hazelcast.spi.impl

Subclasses of AbstractOperation in com.hazelcast.spi.impl

Modifier and Type
Class and Description

class
AbstractNamedOperation

static class
EventServiceImpl.DeregistrationOperation

static class
EventServiceImpl.PostJoinRegistrationOperation

static class
EventServiceImpl.RegistrationOperation

static class
EventServiceImpl.SendEventOperation

class
IsStillExecutingOperation

An operation that checks if another operation is still running.

class
PartitionIteratingOperation

static class
ProxyServiceImpl.DistributedObjectDestroyOperation

static class
ProxyServiceImpl.PostJoinProxyOperation

class
TraceableIsStillExecutingOperation

Uses of AbstractOperation in com.hazelcast.topic.impl

Subclasses of AbstractOperation in com.hazelcast.topic.impl

Modifier and Type
Class and Description

class
PublishOperation

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 Hazelcast, Inc.. All Rights Reserved.


text:
<?php
/**
 * Created by PhpStorm.
 * User: petrvohralik
 * Date: 25.09.17
 * Time: 14:26
 */

namespace App\Core;

use App\Controllers\Error;
use App\Controllers\Home;

class Application
{

    /**
     * @var null The Controller loaded by url
     */
    private $controller = null;

    /**
     * @var null Action loaded by url
     */
    private $action = null;

    /**
     * @var array URL parameters loaded by url
     */
    private $params = [];

    public function __construct()
    {

        $this->_getUrlWithoutModRewrite();

        // Check if controller is set
        if (!$this->controller) {
            $page = new Home();
            $page->index();
        } else{
            $page = new Error();
            $page->index();
        }
    }

    private function _getUrlWithoutModRewrite()
    {

        // TODO the "" is weird
        // get URL ($_SERVER['REQUEST_URI'] gets everything after domain and domain ending), something like
        // array(6) { [0]=> string(0) "" [1]=> string(9) "index.php" [2]=> string(10) "controller" [3]=> string(6) "action" [4]=> string(6) "param1" [5]=> string(6) "param2" }
        // split on "/"
        $url = explode('/', $_SERVER['REQUEST_URI']);
        // also remove everything that's empty or "index.php", so the result is a cleaned array of URL parts, like
        // array(4) { [2]=> string(10) "controller" [3]=> string(6) "action" [4]=> string(6) "param1" [5]=> string(6) "param2" }
        $url = array_diff($url, array('', 'index.php'));
        // to keep things clean we reset the array keys, so we get something like
        // array(4) { [0]=> string(10) "controller" [1]=> string(6) "action" [2]=> string(6) "param1" [3]=> string(6) "param2" }
        $url = array_values($url);

        // if first element of our URL is the sub-folder (defined in config/config.php), then remove it from URL
        if (defined('URL_SUB_FOLDER') && !empty($url[0]) && $url[0] === URL_SUB_FOLDER) {
            // remove first element (that's obviously the sub-folder)
            unset($url[0]);
            // reset keys again
            $url = array_values($url);
        }
        // Put URL parts into according properties
        // By the way, the syntax here is just a short form of if/else, called "Ternary Operators"
        // @see http://davidwalsh.name/php-shorthand-if-else-ternary-operators
        $this->url_controller = isset($url[0]) ? $url[0] : null;
        $this->url_action = isset($url[1]) ? $url[1] : null;
        // Remove controller and action from the split URL
        unset($url[0], $url[1]);
        // Rebase array keys and store the URL params
        $this->url_params = array_values($url);
    }

}


text:
/* eslint-disable @typescript-eslint/camelcase */
import React, { FC, useRef, useState, useEffect, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';
import {
  Button,
  CircleButton,
  Dropdown,
  MousePositionedTooltip,
} from '@keen.io/ui-core';
import { Icon } from '@keen.io/icons';
import { colors } from '@keen.io/colors';

import TooltipContent from '../TooltipContent';
import {
  Container,
  BasicActions,
  ActionsContainer,
  ContextActions,
} from './BrowserQueryMenu.styles';

import ActionsMenu from '../ActionsMenu';

import { getSavedQueryIsEditable } from '../../modules/savedQuery/selectors';
import { getQuerySettings } from '../../modules/queries';
import { appActions, SettingsModalSource } from '../../modules/app';

const actionsDropdownMotion = {
  initial: { opacity: 0, top: 20, left: 37, translateX: '-100%' },
  animate: { opacity: 1, top: 2, left: 37, translateX: '-100%' },
  exit: { opacity: 0, top: 30, left: 37 },
};

type Props = {
  /** Edit query event handler */
  onEditQuery: () => void;
  /** Remove query event handler */
  onRemoveQuery: () => void;
};

const menuTooltip = (text: string) => (
  <TooltipContent color={colors.black[500]}>{text}</TooltipContent>
);

const BrowserQueryMenu: FC<Props> = ({ onEditQuery, onRemoveQuery }) => {
  const dispatch = useDispatch();
  const { t } = useTranslation();
  const actionsContainer = useRef(null);
  const isSavedQueryEditable = useSelector(getSavedQueryIsEditable);
  const { analysis_type: analysisType }: any = useSelector(getQuerySettings);

  const isMultiAnalysisQuery = analysisType === 'multi_analysis';

  const [actionsMenu, setActionsMenuVisibility] = useState(false);

  const outsideActionsMenuClick = useCallback(
    (e) => {
      if (
        actionsMenu &&
        actionsContainer.current &&
        !actionsContainer.current.contains(e.target)
      ) {
        setActionsMenuVisibility(false);
      }
    },
    [actionsContainer, actionsMenu]
  );

  useEffect(() => {
    if (actionsMenu) {
      document.addEventListener('click', outsideActionsMenuClick);
    }

    return () => document.removeEventListener('click', outsideActionsMenuClick);
  }, [actionsMenu, actionsContainer]);

  return (
    <Container>
      <BasicActions>
        <MousePositionedTooltip
          isActive={!isSavedQueryEditable || isMultiAnalysisQuery}
          tooltipPinPlacement="bottom-left"
          renderContent={() =>
            isMultiAnalysisQuery
              ? t('browser_query_menu.multi_analysis_tootlip')
              : t('browser_query_menu.query_edition_not_possible')
          }
        >
          <Button
            variant="secondary"
            onClick={onEditQuery}
            isDisabled={!isSavedQueryEditable || isMultiAnalysisQuery}
          >
            {t('browser_query_menu.edit_query')}
          </Button>
        </MousePositionedTooltip>
      </BasicActions>
      <ContextActions data-testid="context-buttons">
        {isSavedQueryEditable && (
          <MousePositionedTooltip
            isActive={!actionsMenu}
            tooltipPinPlacement="bottom-left"
            renderContent={() =>
              menuTooltip(t('browser_query_menu.settings_tooltip'))
            }
          >
            <ActionsContainer data-testid="query-settings">
              <CircleButton
                variant="secondary"
                icon={<Icon type="settings" />}
                onClick={() => {
                  dispatch(
                    appActions.showQuerySettingsModal({
                      source: SettingsModalSource.QUERY_SETTINGS,
                    })
                  );
                }}
              />
            </ActionsContainer>
          </MousePositionedTooltip>
        )}
        {isSavedQueryEditable && !isMultiAnalysisQuery && (
          <MousePositionedTooltip
            isActive={!actionsMenu}
            tooltipPinPlacement="bottom-left"
            renderContent={() =>
              menuTooltip(t('browser_query_menu.share_tooltip'))
            }
          >
            <ActionsContainer data-testid="share-query" marginLeft={10}>
              <CircleButton
                variant="secondary"
                icon={<Icon type="share" />}
                onClick={() => {
                  dispatch(appActions.shareQueryUrl());
                }}
              />
            </ActionsContainer>
          </MousePositionedTooltip>
        )}
        <MousePositionedTooltip
          isActive={!actionsMenu}
          tooltipPinPlacement="bottom-left"
          renderContent={() =>
            menuTooltip(t('browser_query_menu.actions_tooltip'))
          }
        >
          <ActionsContainer ref={actionsContainer} marginLeft={10}>
            <CircleButton
              variant="secondary"
              icon={<Icon type="actions" />}
              onClick={() => {
                setActionsMenuVisibility(!actionsMenu);
              }}
            />
            <Dropdown
              isOpen={actionsMenu}
              fullWidth={false}
              motion={actionsDropdownMotion}
            >
              <ActionsMenu
                isNewQuery={false}
                isQueryEditable={isSavedQueryEditable}
                isVisible={actionsMenu}
                isMultiAnalysisQuery={isMultiAnalysisQuery}
                isInsideQueryBrowser
                onHideMenu={() => setActionsMenuVisibility(false)}
                onRemoveQuery={() => {
                  setActionsMenuVisibility(false);
                  onRemoveQuery();
                }}
              />
            </Dropdown>
          </ActionsContainer>
        </MousePositionedTooltip>
      </ContextActions>
    </Container>
  );
};

export default BrowserQueryMenu;


text:
package org.hisp.dhis.datastore;

import static java.util.stream.Collectors.toList;
import static org.hisp.dhis.utils.JavaToJson.toJson;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.List;
import java.util.Map;

import org.hisp.dhis.test.integration.IntegrationTestBase;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Tests the features of the {@link DatastoreService} that do require a postgres
 * database.
 *

 * The test dimensions are:
 *

 *
filter operator

 *
root path (.) or property path (name or a.b)

 *
type of JSON value: numeric, text, ...

 *

 *
 * @author Jan Bernitt
 */
class DatastoreIntegrationTest extends IntegrationTestBase
{
    @Autowired
    private DatastoreService datastore;

    @Override
    protected void setUpTest()
        throws Exception
    {
        datastore.deleteNamespace( "pets" );

        addEntry( "dog", toJson( false ) );
        addEntry( "bat", toJson( true ) );
        addEntry( "pidgin", toJson( 42 ) );
        addEntry( "horse", toJson( "Fury" ) );
        addEntry( "snake", toJson( (Object) null ) );

        addEntry( "mole", toJson( "" ) );
        addEntry( "duck", toJson( List.of() ) );
        addEntry( "eagle", toJson( Map.of() ) );

        addPet( "cat", "Miao", 9, List.of( "tuna", "mice", "birds" ) );
        addPet( "cow", "Muuhh", 5, List.of( "gras" ) );
        addPet( "hamster", "", 2, List.of() );
        addPet( "pig", "Oink", 6, List.of( "carrots", "potatoes" ) );
    }

    @Override
    protected void tearDownTest()
        throws Exception
    {
        datastore.deleteNamespace( "pets" );
    }

    private DatastoreEntry addEntry( String key, String value )
    {
        DatastoreEntry entry = new DatastoreEntry( "pets", key, value.replace( '\'', '"' ), false );
        datastore.addEntry( entry );
        return entry;
    }

    private DatastoreEntry addPet( String key, String name, int age, List<String> eats )
    {
        return addEntry( key,
            toJson( Map.of(
                "name", name,
                "age", age,
                "cute", true,
                "eats", eats == null ? List.of() : eats.stream().map( food -> Map.of( "name", food ) ) ) ) );
    }

    /*
     * Boolean Equality Filters
     */

    @Test
    void test_Filter_RootEq_Boolean()
    {
        assertEntries( ".:eq:true", "bat" );
    }

    @Test
    void test_Filter_RootNotEq_Boolean()
    {
        assertEntries( ".:!eq:true", "dog" );
    }

    /*
     * String Equality Filters
     */

    @Test
    void test_Filter_RootEq_String()
    {
        assertEntries( ".:eq:Fury", "horse" );
    }

    @Test
    void test_Filter_RootNotEq_String()
    {
        assertEntries( ".:!eq:Fury", "mole" );
    }

    @Test
    void test_Filter_PathEq_String()
    {
        assertEntries( "name:eq:Miao", "cat" );
    }

    @Test
    void test_Filter_PathNotEq_String()
    {
        assertEntries( "name:!eq:Miao", "cow", "hamster", "pig" );
    }

    /*
     * Numeric Filters (decided by value)
     */

    @Test
    void test_Filter_RootEq_Numeric()
    {
        assertEntries( ".:eq:42", "pidgin" );
    }

    @Test
    void test_Filter_RootNotEq_Numeric()
    {
        assertEntries( ".:!eq:13", "pidgin" );
    }

    @Test
    void test_Filter_RootLt_Numeric()
    {
        assertEntries( ".:lt:44", "pidgin" );
    }

    @Test
    void test_Filter_RootLe_Numeric()
    {
        assertEntries( ".:le:42", "pidgin" );
    }

    @Test
    void test_Filter_RootGt_Numeric()
    {
        assertEntries( ".:gt:41", "pidgin" );
    }

    @Test
    void test_Filter_RootGe_Numeric()
    {
        assertEntries( ".:ge:42", "pidgin" );
    }

    @Test
    void test_Filter_PathEq_Numeric()
    {
        assertEntries( "age:eq:9", "cat" );
    }

    @Test
    void test_Filter_PathNotEq_Numeric()
    {
        assertEntries( "age:!eq:9", "cow", "hamster", "pig" );
    }

    @Test
    void test_Filter_PathLt_Numeric()
    {
        assertEntries( "age:lt:6", "cow", "hamster" );
    }

    @Test
    void test_Filter_PathLe_Numeric()
    {
        assertEntries( "age:le:6", "cow", "hamster", "pig" );
    }

    @Test
    void test_Filter_PathGt_Numeric()
    {
        assertEntries( "age:gt:6", "cat" );
    }

    @Test
    void test_Filter_PathGe_Numeric()
    {
        assertEntries( "age:ge:6", "cat", "pig" );
    }

    /*
     * Emptiness Filters
     *
     * These match empty/non-empty objects or arrays or strings of length zero
     */

    @Test
    void test_Filter_RootEmpty()
    {
        assertEntries( ".:empty", "duck", "eagle", "mole" );
    }

    @Test
    void test_Filter_RootNotEmpty()
    {
        assertEntries( ".:!empty", "cat", "cow", "hamster", "horse", "pig" );
    }

    @Test
    void test_Filter_PathEmpty()
    {
        assertEntries( "eats:empty", "hamster" );
    }

    @Test
    void test_Filter_PathNotEmpty()
    {
        assertEntries( "eats:!empty", "cat", "cow", "pig" );
    }

    /*
     * String Pattern Filters
     *
     * We test ilike and !ilike since they represent the most complicated
     * combination. If those work it is very likely the other variants work as
     * well.
     */

    @Test
    void test_Filter_RootILike_String()
    {
        assertEntries( ".:ilike:uRy", "horse" );
    }

    @Test
    void test_Filter_RootNotILike_String()
    {
        assertEntries( ".:!ilike:ur", "mole" );
    }

    @Test
    void test_Filter_PathILike_String()
    {
        assertEntries( "name:ilike:IA", "cat" );
    }

    @Test
    void test_Filter_PathNotILike_String()
    {
        assertEntries( "name:!ilike:IA", "cow", "hamster", "pig" );
    }

    /*
     * Nullness Filters
     */

    @Test
    void test_Filter_RootNull()
    {
        assertEntries( ".:null", "snake" );
    }

    @Test
    void test_Filter_RootNotNull()
    {
        assertEntries( ".:!null",
            "bat", "cat", "cow", "dog", "duck", "eagle", "hamster", "horse", "mole", "pidgin", "pig" );
    }

    @Test
    void test_Filter_RootEqNull()
    {
        assertEntries( ".:eq:null", "snake" );
    }

    @Test
    void test_Filter_RootNotEqNull()
    {
        assertEntries( ".:!eq:null",
            "bat", "cat", "cow", "dog", "duck", "eagle", "hamster", "horse", "mole", "pidgin", "pig" );
    }

    private DatastoreQuery createQuery( String... filters )
    {
        return DatastoreQuery.builder()
            .namespace( "pets" )
            .fields( List.of() )
            .filters( DatastoreQuery.parseFilters( List.of( filters ) ) )
            .build();
    }

    private List<DatastoreFields> queryAsList( DatastoreQuery query )
    {
        return datastore.getFields( query, stream -> stream.collect( toList() ) );
    }

    private void assertEntries( String filter, String... expectedKeys )
    {
        assertEntries( List.of( expectedKeys ),
            queryAsList( createQuery( filter ) ) );
    }

    private static void assertEntries( List<String> expectedKeys, List<DatastoreFields> actual )
    {
        List<String> actualKeys = actual.stream().map( DatastoreFields::getKey ).collect( toList() );
        assertEquals( expectedKeys, actualKeys );
    }
}


text:
{generate_api_title(/mark_all_as_read:post)}

{generate_api_description(/mark_all_as_read:post)}

## Usage examples

{start_tabs}

{generate_code_example(python)|/mark_all_as_read:post|example}

{generate_code_example(javascript)|/mark_all_as_read:post|example}

{tab|curl}

{generate_code_example(curl)|/mark_all_as_read:post|example}

{end_tabs}

## Parameters

{generate_api_arguments_table|zulip.yaml|/mark_all_as_read:post}

{generate_parameter_description(/mark_all_as_read:post)}

## Response

{generate_response_description(/mark_all_as_read:post)}

#### Example response

{generate_code_example|/mark_all_as_read:post|fixture}

{generate_api_title(/mark_stream_as_read:post)}

{generate_api_description(/mark_stream_as_read:post)}

`POST {{ api_url }}/v1/mark_stream_as_read`

## Usage examples

{start_tabs}

{generate_code_example(python)|/mark_stream_as_read:post|example}

{generate_code_example(javascript)|/mark_all_as_read:post|example}

{tab|curl}

{generate_code_example(curl)|/mark_stream_as_read:post|example}

{end_tabs}

## Parameters

{generate_api_arguments_table|zulip.yaml|/mark_stream_as_read:post}

{generate_parameter_description(/mark_all_as_read:post)}

## Response

{generate_response_description(/mark_all_as_read:post)}

#### Example response

{generate_code_example|/mark_stream_as_read:post|fixture}

# Mark messages in a topic as read
{generate_api_title(/mark_topic_as_read:post)}

{generate_api_description(/mark_all_as_read:post)}

`POST {{ api_url }}/v1/mark_topic_as_read`

## Usage examples

{start_tabs}

{generate_code_example(python)|/mark_topic_as_read:post|example}

{generate_code_example(javascript)|/mark_all_as_read:post|example}

{tab|curl}

{generate_code_example(curl)|/mark_topic_as_read:post|example}

{end_tabs}

## Parameters

{generate_api_arguments_table|zulip.yaml|/mark_topic_as_read:post}

{generate_parameter_description(/mark_all_as_read:post)}

## Response

{generate_response_description(/mark_all_as_read:post)}

#### Example response

{generate_code_example|/mark_topic_as_read:post|fixture}


text:
// Ported from dom/src/json/test/unit/test_reviver.js

function doubler(k, v)
{
  assertEq(typeof k, "string");

  if (typeof v == "number")
    return 2 * v;

  return v;
}

var x = JSON.parse('{"a":5,"b":6}', doubler);
assertEq(x.hasOwnProperty('a'), true);
assertEq(x.hasOwnProperty('b'), true);
assertEq(x.a, 10);
assertEq(x.b, 12);

x = JSON.parse('[3, 4, 5]', doubler);
assertEq(x[0], 6);
assertEq(x[1], 8);
assertEq(x[2], 10);

// make sure reviver isn't called after a failed parse
var called = false;
function dontCallMe(k, v)
{
  called = true;
}

try
{
  JSON.parse('{{{{{{{}}}}', dontCallMe);
  throw new Error("didn't throw?");
}
catch (e)
{
  assertEq(e instanceof SyntaxError, true, "wrong exception: " + e);
}
assertEq(called, false);

/******************************************************************************/

if (typeof reportCompare === "function")
  reportCompare(true, true);

print("Tests complete");


text:
xsd.exe -c -l:c# -n:Spring.NmsQuickStart.Common.Data TradeResponse.xsd
xsd.exe -c -l:c# -n:Spring.NmsQuickStart.Common.Data TradeRequest.xsd


text:
{% extends "layout.html" %}

{% block phase%}
  {% include 'sprint12/partials/phase-banner.html'%}
{% endblock %}

{% block main %}

Landlord / Tenant

 <form method="post" action="abroad">

Tell us what you know?

      <fieldset>

          <textarea class="form-control form-control-3-4" rows="5" id="additional_info" name="additional_info">{{session.additional_info}}</textarea>

      </fieldset>

      <input id="submit" type="submit" class="button" value="Continue">
    </form>

{% endblock %}


text:
<?php if (isset($_SESSION['pesan'])) { ?>

    <button type="button" class="close" data-dismiss="alert">

    </button>
    <?php echo $this->session->flashdata('pesan'); ?>

<?php } ?>

Master Site

                <form class="form-horizontal" role="form" action="<?php echo base_url().'kota/tambah_ubah_kota'; ?>" method="post">

                             Provinsi

                                    <select id="provinsi" name="provinsi" class="col-xs-10 col-sm-5 form-control" required>
                                        <?php foreach ($provinsi as $p) { ?>
                                        <option value="<?php echo $p->id_provinsi; ?>"><?php echo $p->nama_provinsi; ?></option>
                                        <?php } ?>
                                    </select>

                                                    Tambah

                             Nama Kota

                                <input type="hidden" id="id_kota" name="id_kota" class="col-xs-10 col-sm-5 form-control" value="<?php echo $id_kota; ?>" />
                                <input type="text" id="nama_kota" name="nama_kota" placeholder="Nama Kota" class="col-xs-10 col-sm-5 form-control" />

                                <button class="btn btn-success" type="submit">

                                        Simpan
                                </button>

                                <button class="btn btn-danger" type="reset">

                                        Batal
                                </button>

                </form>

                        Tabel Kota

                                Provinsi
                                Kota
                                Status
                                Opsi

                            <?php foreach($kota as $k) { ?>

                                        <a class="green" href="#modal-provinsi" role="button" data-toggle="modal"
                                            onclick="fill_provinsi('<?php echo $k->id_provinsi; ?>', '<?php echo $k->nama_provinsi; ?>', '<?php echo $k->status_provinsi; ?>')">

                                        <a href="<?php echo base_url().'index.php/kota/activate_provinsi/'.$k->id_provinsi; ?>"
                                            onclick="return confirm('Anda yakin?\nInfo: Semua kota yang ada pada Provinsi <?php echo strtoupper($p->nama_provinsi); ?> juga akan dinon-aktifkan/diaktifkan.');">
                                            <?php if($k->status_provinsi == "Y") { ?>

                                            <?php } else { ?>

                                            <?php } ?>

                                    <span class="<?php echo $k->status_provinsi=="Y"?"green":"red"; ?>"><?php echo $k->nama_provinsi; ?>

                                <?php echo $k->nama_kota; ?>
                                <?php echo $k->status=="Y"?"Aktif":"Non-Aktiv"; ?>

                                        <a class="green" href="javascript:void(0);" onclick="fill('<?php echo $k->id_kota; ?>', '<?php echo $k->id_provinsi; ?>', '<?php echo $k->nama_kota; ?>')">

                                        <a href="<?php echo base_url().'index.php/kota/activate_kota/'.$k->id_kota; ?>" onclick="return confirm('Anda yakin?');">
                                            <?php if($k->status == "Y") { ?>

                                            <?php } else { ?>

                                            <?php } ?>

                            <?php } ?>

          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            ×
          </button>
          Tambah Provinsi

      <form class='form-horizontal' role='form' action='<?php echo base_url()."kota/tambah_provinsi"; ?>' method='post' enctype="multipart/form-data">

                     Nama Provinsi

                        <input type="text" id="nama_prov_new" name="nama_prov_new" placeholder="Nama Provinsi" class="col-xs-10 col-sm-5 form-control" />

                <button class='btn btn-success btn-sm pull-left' type='submit' id="btn-simpan">
                     Simpan
                </button>
                <button class='btn btn-sm btn-danger' data-dismiss='modal'>
                     Tutup
                </button>

      </form>

            <form class="form-horizontal" method="post" role="form" enctype="multipart/form-data" action="<?php echo base_url().'kota/ubah_provinsi'; ?>">

                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                            ×
                        </button>
                        Ubah Provinsi

                    <input type="hidden" id="id_provinsi-u" name="id_provinsi-u">
                    <input type="hidden" id="status-u" name="status-u">

                         Nama Provinsi

                            <input type="text" id="nama_provinsi-u" name="nama_provinsi-u" placeholder="Nama Provinsi" class="col-xs-10 col-sm-5 form-control" />

                    <button type="submit" class="btn btn-sm btn-success pull-left">

                        Simpan
                    </button>

                    <button type="button" class="btn btn-sm btn-danger" data-dismiss="modal">

                        Tutup
                    </button>

            </form>


text:
@CHARSET "ISO-8859-1";

/* Border around dialog */
.dialogBorder
{
	border-style: outset;
	border-width: 1px;
	border-color: #CCCCCC;
	background-color: gray;
}

/* Title bar background area */
.dialogTitleBar
{
	height: 20px;
	background-color: #4E6DA4;
	cursor: move;
}

.dTitleBar
{
	padding-left: 7px;
	padding-right: 7px;
	padding-top: 2px;
	padding-bottom: 2px;
	position: relative;
}

/* Title text */
.dialogTitleText
{
	font-size: 11px;
	font-weight: bold;
	font-family: tahoma, verdana, arial, sans-serif;
	color: white;
}

.dTitleText
{
	vertical-align: middle;
	white-space: nowrap;
	cursor: move;
}

.dTitleTextContainer
{
	float: left;
	position: relative;
	height: 100%;
	width: 1px;
}

/* Close button - width should match those of .dialogCloseBtnContainer */
.dialogCloseBtn
{
	background-image: url("../images/Close.gif");
	width: 14px;
	height: 14px;
	background-color: gray;
	cursor: pointer;
}

.dCloseBtn
{
	vertical-align: middle;
	background-repeat: no-repeat;
	background-position: center right;
}

/* Close button container - width should match those of .dialogCloseBtn */
.dialogCloseBtnContainer
{
	width: 14px;
}

.dCloseBtnContainer
{
	height: 100%;
	float: right;
	position: relative;
}

/* Background of dialog below title bar */
.dialogBackground
{
	background-color: #ECE9D8;
	margin-bottom: 1px;
}

.dBackground
{
	margin-left: 10px;
	margin-right: 10px;
	padding-top: 4px;
}

/* Border style of content area for individual dialog content */
.dialogContentContainer
{
}

/* Area from bottom of dialog content container to bottom border */
.dialogBtnBarContainer
{
	position: relative;
	text-align: center;
	padding-top: 4px; /* distance from bottom of content area to top of divider bar*/
	overflow: hidden;
}

/* Top divider line between dialog content area and button area */
.dBtnBarDividerTop
{
	height: 1px;
	background-color: gray;
	overflow: hidden;
}

/* Bottom divider line between dialog content area and button area */
.dBtnBarDividerBottom
{
	height: 1px;
	background-color: #fefefe;
	overflow: hidden;
}

/* Area that contains OK and CANCEL buttons - from bottom of divider bar to top of outer border */
.dialogBtnBar
{
	height: 36px;
	text-align: right;
}

/* Area holding both OK and CANCEL buttons */
.dialogBtnBarButtonContainer
{
	margin-left: auto;
	margin-right: 0px;
	margin-top: 6px;
	margin-bottom: 7px;
	width: 166px;
	height:24px;
}

/* Space between OK and CANCEL */
.dialogBtnBarDivider
{
	width: 6px;
	height: 1px;
	float: left;
}

.dialogBtnBarButtonEnabled
{
	float: left;
	cursor: pointer;
	height: 24px;
	width: 80px;
	overflow: hidden;
	color: black; /* Font color */
	/*background-color: #9C9C9C;
	background-repeat: repeat-x;
	background-position: top left;*/
}

.dialogBtnBarButtonDisabled
{
	float: left;
	cursor: default;
	height: 24px;
	width: 80px;
	overflow: hidden;
	color: #999999; /* Font color */
	/*background-color: #9C9C9C;
	background-repeat: repeat-x;
	background-position: top left;*/
}

/* Left background image for OK and CANCEL buttons */
.dialogBtnBarButtonLeftBackgroundEnabled
{
	background-color: #9C9C9C;
	background-repeat: no-repeat;
	background-position: top left;
	position: relative;
	width: 0px;
	height: 24px;
	float: left;
}

/* Left background image for OK and CANCEL buttons */
.dialogBtnBarButtonLeftBackgroundDisabled
{
	background-color: #9C9C9C;
	background-repeat: no-repeat;
	background-position: top left;
	position: relative;
	width: 0px;
	height: 24px;
	float: left;
}

/* Right background image for OK and CANCEL buttons */
.dialogBtnBarButtonRightBackgroundEnabled
{
	background-color: #9C9C9C;
	background-repeat: no-repeat;
	background-position: top right;
	position: relative;
	width: 0px;
	height: 24px;
	float: right;
}

/* Right background image for OK and CANCEL buttons */
.dialogBtnBarButtonRightBackgroundDisabled
{
	background-color: #9C9C9C;
	background-repeat: no-repeat;
	background-position: top right;
	position: relative;
	width: 0px;
	height: 24px;
	float: right;
}

/* Text for OK and CANCEL buttons */
.dialogBtnBarButtonText
{
	font-family: tahoma, verdana, arial, sans-serif;
	font-size: 11px;
	font-weight: 400;
	text-align: center;
	vertical-align: middle;
}


text:
using System;
namespace BeerDrinkin.DataObjects
{
    public class PerformanceEvent : BaseDataObject
    {
        public string UserId { get; set; }
        public string EventName { get; set;}
        public double Elapsed { get; set;}
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
  xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
  xmlns:camunda="http://camunda.org/schema/1.0/bpmn"
  targetNamespace="Examples">

  <process id="process" isExecutable="true">

    <startEvent id="theStart" />

    <sequenceFlow sourceRef="theStart" targetRef="serviceTask" />

    <serviceTask id="serviceTask"
      camunda:asyncBefore="true"
      camunda:asyncAfter="true"
      camunda:class="org.camunda.bpm.engine.test.api.runtime.FailingDelegate"
      camunda:jobPriority="15" />

    <sequenceFlow id="flow1" sourceRef="serviceTask" targetRef="theEnd" />

    <endEvent id="theEnd" />

  </process>
</definitions>


text:
<?xml version="1.0" encoding="UTF-8"?>
<Policy
      xmlns="urn:oasis:names:tc:xacml:2.0:policy:schema:os"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="urn:oasis:names:tc:xacml:2.0:policy:schema:os
        access_control-xacml-2.0-policy-schema-os.xsd"
      PolicyId="urn:oasis:names:tc:xacml:2.0:conformance-test:IIC185:policy"
      RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:deny-overrides">
    <Description>
        Policy for Conformance Test IIC185.
    </Description>
    <Target/>
    <Rule
          RuleId="urn:oasis:names:tc:xacml:2.0:conformance-test:IIC185:rule"
          Effect="Permit">
        <Condition>
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-set-equals">
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-bag">
                <AttributeValue
                      DataType="http://www.w3.org/2001/XMLSchema#integer">5</AttributeValue>
                <AttributeValue
                      DataType="http://www.w3.org/2001/XMLSchema#integer">-20</AttributeValue>
            </Apply>
            <SubjectAttributeDesignator
                  AttributeId="urn:oasis:names:tc:xacml:2.0:conformance-test:test-attr"
                  DataType="http://www.w3.org/2001/XMLSchema#integer"/>
            </Apply>
        </Condition>
    </Rule>
</Policy>