text:
Zulip, like many popular applications, is designed with
internationalization (i18n) in mind, which means users can fully use
the the Zulip UI in their preferred language.

This article aims to teach Zulip contributors enough about
internationalization and Zulip's tools for it so that they can make
correct decisions about how to tag strings for translation.  A few
principles are important in how we think about internationalization:

* Our goal is for **all end-user facing strings** in Zulip to be
  tagged for translation in both [HTML templates](#html-templates) and
  code, and our linters attempt to enforce this.  There are some
  exceptions: we don't tag strings in Zulip's landing pages
  (e.g. /features) and other documentation (e.g. /help) for
  translation at this time (though we do aim for those pages to be
  usable with tools like Google Translate).
* Translating all the strings in Zulip for a language and maintaining
  that translation is a lot of work, and that work scales with the
  number of strings tagged for translation in Zulip.  For this reason,
  we put significant effort into only tagging for translation content
  that will actually be displayed to users, and minimizing unnecessary
  user-facing strings in the product.
* In order for a translated user experience to be good, every UI
  element needs to be built in a way that supports i18n.
* This is more about string consistency in general, but we have a
  "Sentence case" [capitalization
  policy](../translating/translating.html#capitalization) that we enforce using linters
  that check all strings tagged for translation in Zulip.

This article aims to provide a brief introduction.  We recommend the
[EdX i18n guide][edx-i18n] as a great resource for learning more about
internationalization in general; we agree with essentially all of
their style guidelines.

[edx-i18n]: https://edx.readthedocs.io/projects/edx-developer-guide/en/latest/internationalization/i18n.html

## Key details about human language

There's a few critical details about human language that are important
to understand when implementing an internationalized application:

* **Punctuation** varies between languages (e.g. Japanese doesn't use
  `.`s at the end of sentences).  This means that you should always
  include end-of-sentence symbols like `.` and `?` inside the
  to-be-translated strings, so that translators can correctly
  translate the content.
* **Word order** varies between languages (e.g. some languages put
  subjects before verbs, others the other way around).  This means
  that **concatenating translateable strings** produces broken results
  (more details with examples are below).
* The **width of the string needed to express something** varies
  dramatically between languages; this means you can't just hardcode a
  button or widget to look great for English and expect it to work in
  all languages.  German is a good test case, as it has a lot of long
  words, as is Japanese (as character-based languages use a lot less
  width).
* This is more about how i18n tooling works, but in code, the
  translation function must be passed the string to translate, not a
  variable containing the target string.  Otherwise, the parsers that
  extract the strings in a project to send to translators will not
  find your string.

There's a lot of other interesting differences that are important for
i18n (e.g. Zulip has a "Full Name" field rather than "First Name" and
"Last Name" because different cultures order the surnames and given
names differently), but the above issues are likely to be relevant to
most people working on Zulip.

## Translation process

The end-to-end tooling process for translations in Zulip is as follows.

1. The strings are marked for translation (see sections for
   [backend](#backend-translations) and
   [frontend](#frontend-translations) translations for details on
   this).

2. Translation [resource][] files are created using the `./manage.py
   makemessages` command. This command will create, for each language,
   a resource file called `translations.json` for the frontend strings
   and `django.po` for the backend strings.

   The `makemessages` command is idempotent in that:

   - It will only delete singular keys in the resource file when they
     are no longer used in Zulip code.
   - It will only delete plural keys (see below for the documentation
     on plural translations) when the corresponding singular key is
     absent.
   - It will not override the value of a singular key if that value
     contains a translated text.

3. Those resource files are uploaded to Transifex by a maintainer using the
   `./tools/i18n/push-translations` command (which invokes a Transifex
   API tool, `tx push`, internally).

4. Translators translate the strings in the Transifex UI.  (In theory,
   it's possible to translate locally and then do `tx push`, but
   because our workflow is to sync translation data from Transifex to
   Zulip, making changes to translations in Zulip risks having the
   changes blown away by a data sync, so that's only a viable model
   for a language that has no translations yet).

5. The translations are downloaded back into the codebase by a
   maintainer, using `tools/i18n/sync-translations` (which invokes the
   Transifex API tool, `tx pull`, internally).

If you're interested, you may also want to check out the [translators'
workflow](../translating/translating.html#translators-workflow), just so you have a
sense of how everything fits together.

## Translation resource files

All the translation magic happens through resource files which hold
the translated text. Backend resource files are located at
`locale/<lang_code>/LC_MESSAGES/django.po`, while frontend
resource files are located at
`locale/<lang_code>/translations.json` (and mobile at
`mobile.json`).

These files are uploaded to [Transifex][], where they can be translated.

## HTML Templates

Zulip makes use of the [Jinja2][] templating system for the backend
and [Handlebars][] for the frontend. Our [HTML templates][html-templates]
documentation includes useful information on the syntax and
behavior of these systems.

## Backend translations

### Jinja2 templates

All user-facing text in the Zulip UI should be generated by an Jinja2 HTML
template so that it can be translated.

To mark a string for translation in a Jinja2 template, you
can use the `_()` function in the templates like this:

```
{{ _("English text") }}
```

If a piece of text contains both a literal string component and variables,
you can use a block translation, which makes use of placeholders to
help translators to translate an entire sentence.  To translate a
block, Jinja2 uses the [trans][] tag.  So rather than writing
something ugly and confusing for translators like this:

```
# Don't do this!
{{ _("This string will have") }} {{ value }} {{ _("inside") }}
```

You can instead use:

```
{% trans %}This string will have {{ value }} inside.{% endtrans %}
```

### Python

A string in Python can be marked for translation using the `_()` function,
which can be imported as follows:

```
from django.utils.translation import ugettext as _
```

Zulip expects all the error messages to be translatable as well.  To
ensure this, the error message passed to `json_error` and
`JsonableError` should always be a literal string enclosed by `_()`
function, e.g.:

```
json_error(_('English Text'))
JsonableError(_('English Text'))
```

If you're declaring a user-facing string at top level or in a class, you need to
use `ugettext_lazy` instead, to ensure that the translation happens at
request-processing time when Django knows what language to use, e.g.:

```python
from zproject.backends import check_password_strength, email_belongs_to_ldap

AVATAR_CHANGES_DISABLED_ERROR = ugettext_lazy("Avatar changes are disabled in this organization.")

def confirm_email_change(request: HttpRequest, confirmation_key: str) -> HttpResponse:
  ...
```

```python
class Realm(models.Model):
    MAX_REALM_NAME_LENGTH = 40
    MAX_REALM_SUBDOMAIN_LENGTH = 40

    ...
    ...

    STREAM_EVENTS_NOTIFICATION_TOPIC = ugettext_lazy('stream events')
```

To ensure we always internationalize our JSON errors messages, the
Zulip linter (`tools/lint`) attempts to verify correct usage.

## Frontend translations

We use the [i18next][] library for frontend translations when dealing
with [Handlebars][] templates or JavaScript.

To mark a string translatable in JavaScript files, pass it to the
`i18n.t` function.

```
i18n.t('English Text', context);
```

Variables in a translated frontend string are enclosed in
double-underscores, like `__variable__`:

```
i18n.t('English text with a __variable__', {'variable': 'Variable value'});
```

`i18next` also supports plural translations. To support plurals make
sure your resource file contains the related keys:

```
{
    "en": {
        "translation": {
            "key": "item",
            "key_plural": "items",
            "keyWithCount": "__count__ item",
            "keyWithCount_plural": "__count__ items"
        }
    }
}
```

With this resource you can show plurals like this:

```
i18n.t('key', {count: 0}); // output: 'items'
i18n.t('key', {count: 1}); // output: 'item'
i18n.t('key', {count: 5}); // output: 'items'
i18n.t('key', {count: 100}); // output: 'items'
i18n.t('keyWithCount', {count: 0}); // output: '0 items'
i18n.t('keyWithCount', {count: 1}); // output: '1 item'
i18n.t('keyWithCount', {count: 5}); // output: '5 items'
i18n.t('keyWithCount', {count: 100}); // output: '100 items'
```

For further reading on plurals, read the [official] documentation.

By default, all text is escaped by i18next. To unescape a text you can use
double-underscores followed by a dash `__-` like this:

```
i18n.t('English text with a __- variable__', {'variable': 'Variable value'});
```

For more information, you can read the official [unescape] documentation.

### Handlebars templates

For translations in Handlebars templates we also use `i18n.t`, through two
Handlebars [helpers][] that Zulip registers.  The syntax for simple strings is:

```
{{t 'English Text' }}
```

If you are passing a translated string to a Handlebars Partial, you can use:

```
{{> template_name
    variable_name=(t 'English Text')
    }}
```

The syntax for block strings or strings containing variables is:

```
{{#tr context}}
    Block of English text.
{{/tr}}

var context = {'variable': 'variable value'};
{{#tr context}}
    Block of English text with a __variable__.
{{/tr}}
```

Just like in JavaScript code, variables are enclosed in double
underscores `__`.

Handlebars expressions like `{{variable}}` or blocks like
`{{#if}}...{{/if}}` aren't permitted inside a `{{#tr}}...{{/tr}}`
translated block, because they don't work properly with translation.
The Handlebars expression would be evaluated before the string is
processed by `i18n.t`, so that the string to be translated wouldn't be
constant.  We have a linter to enforce that translated blocks don't
contain handlebars.

The rules for plurals are same as for JavaScript files. You just have
to declare the appropriate keys in the resource file and then include
the `count` in the context.

## Transifex config

The config file that maps the resources from Zulip to Transifex is
located at `.tx/config`.

## Transifex CLI setup

In order to be able to run `tx pull` (and `tx push` as well, if you're a
maintainer), you have to specify your Transifex credentials in a config
file, located at `~/.transifexrc`.

You can find details on how to set it up [here][transifexrc], but it should
look similar to this (with your credentials):

```
[https://www.transifex.com]
username = user
token =
password = p@ssw0rd
hostname = https://www.transifex.com
```

This basically identifies you as a Transifex user, so you can access your
organizations from the command line.

[Jinja2]: http://jinja.pocoo.org/
[Handlebars]: https://handlebarsjs.com/
[trans]: http://jinja.pocoo.org/docs/dev/templates/#i18n
[i18next]: https://www.i18next.com
[official]: https://www.i18next.com/plurals.html
[unescape]: https://www.i18next.com/interpolation.html#unescape
[helpers]: https://handlebarsjs.com/guide/block-helpers.html
[resource]: https://www.i18next.com/add-or-load-translations.html
[Transifex]: https://transifex.com
[transifexrc]: https://docs.transifex.com/client/client-configuration#transifexrc
[html-templates]: ../subsystems/html-css.html#html-templates


text:
<?php

sfLoader::loadHelpers(array('Tag'));

/**
 * Returns a link that will trigger a javascript function using the onclick
 * handler and return false after the fact.
 *
 * @param string $name Text to in the anchor tag
 * @param string $function Function to be called by clicking
 * @param mixed $html_options Set of options for the tag
 * @return string The completed anchor tag
 */
function dojo_link_to_function($name, $function, $html_options = array())
{
    $html_options = _parse_attributes($html_options);

    $html_options['href'] = isset($html_options['href']) ? $html_options['href'] : '#';
    if (isset($html_options['confirm']))
    { // add confirmation if desired
        $confirm = escape_javascript($html_options['confirm']);
        $html_options['onclick'] = "if(confirm('$confirm')){ $function;}; return false;";
    }
    else
    {
        $html_options['onclick'] = $function.'; return false;';
    }

    return content_tag('a', $name, $html_options);
}

/**
 * Creates a link that will execute a remote XMLHttpRequest.  Various options
 * can be sent to this function to control what gets changed or what happens
 * when the request is done.
 *
 * @param string $name Text for the link
 * @param mixed $options Set of options for the remote function
 * @param mixed $html_options Set
 * @return unknown
 */
function dojo_link_to_remote($name, $options = array(), $html_options = array())
{
    return dojo_link_to_function($name, remote_function($options), $html_options);
}

/**
 * Creates a Dojo button to a particular function in javascript.
 *
 * @param string $name Text for the button
 * @param string $function Javascript function to be executed
 * @param mixed $html_options Set of HTML options for the tag
 * @return DojoButton The created Dojo button
 */
function dojo_button_to_function($name, $function, $html_options = array())
{
    DojoManager::addJavascript();

    $html_options = _parse_attributes($html_options);

    $html_options['onclick'] = $function.'; return false;';

    return new DojoButton($name, array(), $html_options);
}

/**
 * Creates a Dojo Button that will execute an XMLHttpRequest when clicked.
 *
 * @param string $name The button text
 * @param mixed $options Set of options for the remote function
 * @param mixed $html_options Set of HTML options for the button
 * @return DojoButton The DojoButton object for the options
 */
function dojo_button_to_remote($name, $options = array(), $html_options = array())
{
    return dojo_button_to_function($name, dojo_remote_function($options), $html_options);
}

/**
 * Periodically calls a Javascript function.  The frequency option sets the
 * interval between executions and defaults to ten.  Its units are seconds.
 *
 * @param string $function Javascript function to be run
 * @param mixed $options Options for the Javascript
 * @return string A javascript tag with the Javascript to do the call
 */
function dojo_periodically_call_function($function, $options = array())
{
    // every 10 seconds by default
    $frequency = isset($options['frequency']) ? $options['frequency'] * 1000 : 10000;
    $code = 'setInterval(dojo.hitch(this, function() {'.$function.';}), '.$frequency.');';

    return javascript_tag($code);
}

/**
 * Periodically calls a remote site.  Acts just like the Dojo link to remote
 * and button to remote.
 *
 * @param mixed $options Options for the remote call and the interval
 * @return string The Javascript to do the calling
 */
function dojo_periodically_call_remote($options = array())
{
    return dojo_periodically_call_function(dojo_remote_function($options), $options);
}

/**
 * Returns an open form tag element for submitting data to a remote page using
 * XMLHttpRequests.
 *
 * @param mixed $options Set of options for the remote function
 * @param mixed $html_options Set of options for the HTML form tag
 * @return string The opening tag for a form
 */
function dojo_form_remote_tag($options = array(), $html_options = array())
{
    $options = _parse_attributes($options);
    $html_options = _parse_attributes($html_options);

    // can't use 'this' in the XHR function, so put the form element in a var
    // before the function call
    if (!isset($options['form']) && !isset($options['formElement']))
    {
        if (isset($html_options['id']))
            $options['form'] = $html_options['id'];
        else
        {
            $formElement = 'var formElement = this';
            if (isset($options['before']))
                $options['before'] = $options['before'].'; '.$formElement;
            else
                $options['before'] = $formElement;
            $options['formElement'] = 'formElement';
        }
    }

    $html_options['action'] = isset($html_options['action']) ? $html_options['action'] : url_for($options['url']);
    $html_options['method'] = isset($options['method']) ? $html_options['method'] : 'post';
    $options['method'] = $html_options['method'];
    $html_options['onsubmit'] = dojo_remote_function($options).' return false;';

    return tag('form', $html_options, true);
}

/**
 * Creates an input button that submits a form using XMLHttpRequests.  If you
 * do not specify the form, it will attempt to find it with using
 * 'this.parentNode' for the button.
 *
 * @param string $name Name of the input
 * @param string $value Value for the input button
 * @param mixed $options Set of options for the remote function
 * @param mixed $html_options Set of options for the created HTML tag
 * @return string The completed input with needed javascript
 */
function dojo_submit_to_remote($name, $value, $options = array(), $html_options = array())
{
    $options = _parse_attributes($options);
    $html_options = _parse_attributes($html_options);

    // can't use 'this' in the XHR function, so put the form element in a var
    // before the function call
    if (!isset($options['form']) && !isset($options['formElement']))
    {
        $formElement = 'var formElement = this.parentNode';
        if (isset($options['before']))
            $options['before'] = $options['before'].'; '.$formElement;
        else
            $options['before'] = $formElement;
        $options['formElement'] = 'formElement';
    }

    $options['method'] = (isset($options['method'])) ? $options['method'] : 'post';
    $html_options['type'] = 'button';
    $html_options['onclick'] = dojo_remote_function($options).' return false;';
    $html_options['name'] = $name;
    $html_options['value'] = $value;

    return tag('input', $html_options, false);
}

/**
 * Creates an input that is an image that submits a form or other data using an
 * XMLHttpRequest.  If you do not specify what form, this will guess it as
 * 'this.parentNode'.  The 'alt' option is also guessed if not set.
 *
 * @param string $name Name for the input
 * @param string $source Image source
 * @param mixed $options Options for the remote function
 * @param mixed $html_options Set of options for the input HTML tag
 * @return string The input tag with all the needed javascript
 */
function dojo_submit_image_to_remote($name, $source, $options = array(), $html_options = array())
{
    $options = _parse_attributes($options);
    $html_options = _parse_attributes($html_options);

    // can't use 'this' in the XHR function, so put the form element in a var
    // before the function call
    if (!isset($options['form']) && !isset($options['formElement']))
    {
        $formElement = 'var formElement = this.parentNode';
        if (isset($options['before']))
            $options['before'] = $options['before'].'; '.$formElement;
        else
            $options['before'] = $formElement;
        $options['formElement'] = 'formElement';
    }

    $options['method'] = (isset($options['method'])) ? $options['method'] : 'post';
    $html_options['type'] = 'image';
    $html_options['onclick'] = dojo_remote_function($options).' return false;';
    $html_options['name'] = $name;
    $html_options['src'] = image_path($source);

    if (!isset($html_options['alt']))
    {
      $path_pos = strrpos($source, '/');
      $dot_pos = strrpos($source, '.');
      $begin = $path_pos ? $path_pos + 1 : 0;
      $nb_str = ($dot_pos ? $dot_pos : strlen($source)) - $begin;
      $html_options['alt'] = ucfirst(substr($source, $begin, $nb_str));
    }

    return tag('input', $html_options, false);
}

/**
 * Updates a DOM node specified by the element ID.  You can either update the
 * node with content at a specific location, empty the node, or completely
 * remove the node from the page.
 *
 * @param string $element_id ID of the element being updated
 * @param mixed $options Options to specify what this function does
 * @return string The javascript to do the updates
 */
function dojo_update_element($element_id, $options = array())
{
    DojoManager::addJavascript();

    $content = escape_javascript(isset($options['content']) ? $options['content'] : '');

    $js_function = '';
    $value = isset($options['action']) ? strtolower($options['action']) : 'update';
    switch ($value)
    {
        case 'update':
            $js_function = _dojo_build_update($element_id, $options);
            break;
        case 'empty':
            $js_function = "dojo.byId('$element_id').innerHTML = '';";
            break;
        case 'remove':
            $js_function = "var removeNode = dojo.byId('$element_id');";
            $js_function .= "removeNode.parentNode.removeChild(removeNode);";
            break;
        default:
            throw new DojoHelperOptionException('Invalid action, choose one of update, remove, or empty.');
    }

    return $js_function;
}

/**
 * Creates Javascript to observe a form field for certain events.  The default
 * event is onchange.  It passes the value of the field on to the server as the
 * parameter 'value'.
 *
 * @param string $field_id ID of the field to be observed
 * @param mixed $options Set of options, majorly for the remove function
 * @return string The completed javascript to do the observing
 */
function dojo_observe_field($field_id, $options = array())
{
    DojoManager::addJavascript();

    if (isset($options['frequency']) && $options['frequency'] > 0)
    {
        if (isset($options['withj']))
            $options['withj'] .= " value=dojo.byId('$field_id').value";
        else
            $options['withj'] = "value=dojo.byId('$field_id').value";

        return dojo_periodically_call_remote($options);
    }
    else
    {
        $event = isset($options['event']) ? $options['event'] : 'onchange';
        if (isset($options['withj']) && is_array($options['withj']))
            $options['withj']['value'] = 'this.value';
        else if (isset($options['with']) && $options['with'])
            $options['withj'] .= ' value=this.value';
        else
            $options['withj'] = 'value=this.value';

        $function = dojo_remote_function($options);
        $script = "dojo.connect(dojo.byId('$field_id'), '$event', dojo.byId('$field_id'), function(event) { $function });";

        return javascript_tag($script);
    }
}

/**
 * Creates the Javascript to observe all fields in a form for a certain event.
 * The default event is 'onchange'.  The field that caused the event is sent
 * in the 'target' param and its new value is in the 'value' param.  The whole
 * form is still submitted to the action, though.
 *
 * @param string $form_id What form needs to be watched
 * @param mixed $options Options for the remote function
 * @return string The Javascript in a tag that sets up the observer
 */
function dojo_observe_form($form_id, $options = array())
{
    DojoManager::addJavascript();

    $options['form'] = $form_id;
    if (isset($options['frequency']) && $options['frequency'] > 0)
    {
        return dojo_periodically_call_remote($options);
    }
    else
    {
        $event = isset($options['event']) ? $options['event'] : 'onchange';
        if (isset($options['withj']) && is_array($options['withj']))
        {
            $options['withj']['target'] = 'event.target.name';
            $options['withj']['value'] = 'event.target.value';
        }
        else if (isset($options['withj']) && $options['withj'])
            $options['withj'] .= ' target=event.target.name value=event.target.value';
        else
            $options['withj'] = 'target=event.target.name value=event.target.value';

        $function = dojo_remote_function($options);
        // attach to event for each child node in the form, have to use jscript
        $script = "var children = dojo.byId('$form_id').childNodes;";
        $script .= "for (i=0; i < children.length; i++) {";
        $script .= "dojo.connect(children[i], '$event', dojo.byId('$form_id'), function(event) { $function });";
        $script .= '}';

        return javascript_tag($script);
    }
}

function dojo_remote_function($options)
{
    DojoManager::addJavascript();

    $javascript_options = _dojo_options_for_ajax($options);

    $method = 'GET';
    if (isset($options['method']))
    {
        $method = strtoupper($options['method']);
    }

    $function = 'dojo.xhr(';
    $function .= "'$method'";
    $function .= ", $javascript_options";

    if (isset($options['hasBody']))
    {
        $function .= ', '._dojo_boolean_for_javascript($options['hasBody']);
    }

    $function .= ');';

    if (isset($options['before']))
        $function = $options['before'].'; '.$function;
    if (isset($options['after']))
        $function = $function.' '.$options['after'].';';
    if (isset($options['condition']))
        $function = 'if ('.$options['condition'].') { '.$function.' }';
    if (isset($options['confirm']))
    {
        $function = 'if (confirm("'.escape_javascript($options['confirm']).'")) { '.$function.' }';
        if (isset($options['cancel']))
            $function .= ' else { '.$options['cancel'].' }';
    }

    return $function;
}

function _dojo_build_ajax_callbacks($options)
{
    $error_function = '';
    $handle_function = '';
    $load_function = '';

    if (isset($options['failure']['before']))
    {
        $error_function .= $options['failure']['before'];
    }

    if (isset($options['always']['before']))
    {
        $handle_function = $options['always']['before'];
    }

    if (isset($options['success']['before']))
    {
        $load_function .= $options['success']['before'];
    }

    if (isset($options['update']) && is_array($options['update']))
    {
        if (isset($options['update']['success']))
        {
            $load_function .= _dojo_build_update($options['update']['success'], $options);
        }

        if (isset($options['update']['always']))
        {
            $handle_function .= _dojo_build_update($options['update']['always'], $options);
        }

        if (isset($options['update']['failure']))
        {
            $error_function .= _dojo_build_update($options['update']['failure'], $options);
        }
    }
    else if (isset($options['update']))
    {
        $handle_function .= _dojo_build_update($options['update'], $options);;
    }

    if (isset($options['failure']['after']))
    {
        $error_function .= $options['failure']['after'];
    }

    if (isset($options['always']['after']))
    {
        $handle_function = $options['always']['after'];
    }

    if (isset($options['success']['after']))
    {
        $load_function .= $options['success']['after'];
    }

    $rval = array();
    if ($load_function)
        $rval['load'] = "function(response, ioArgs) { $load_function return response; }";
    if ($error_function)
        $rval['error'] = "function(response, ioArgs) { $error_function return response; }";
    if ($handle_function)
        $rval['handle'] = "function(response, ioArgs) { $handle_function return response; }";

    return $rval;
}

function _dojo_build_update($id, $options)
{
    $rval = '';
    if (isset($options['position']) && $options['position'])
    {
        $pos = strtolower($options['position']);
        if ($pos == 'top') $pos = 'first';
        if ($pos == 'bottom') $pos = 'last';

        $rval = "var theDiv = document.createElement('div');";
        $rval .= "dojo.place(theDiv, '$id', '$pos');";
        $rval .= "dojo.byId(theDiv).innerHTML = response;";
        if (isset($options['renderWidgets']) && ($options['renderWidgets'] == true))
            $rval .= "dojo.parser.parse(theDiv);";
    }
    else
    {
        $rval = "dojo.byId('$id').innerHTML = response;";
        if (isset($options['renderWidgets']) && ($options['renderWidgets'] == true))
            $rval .= "dojo.parser.parse('$id');";
    }

    return $rval;
}

function _dojo_options_for_ajax($options)
{
    $js_options = _dojo_build_ajax_callbacks($options);
    $js_options['url'] = '"'.url_for($options['url']).'"';

    $content = array();
    if (isset($options['with']))
    {
        $content = _parse_attributes($options['with']);
        foreach ($content as $key => $value)
            $content[$key] = "'$value'";
    }

    if (isset($options['withj']))
    {
        $content = array_merge(_parse_attributes($options['withj']), $content);
    }

    if (!empty($content))
    {
        $js_options['content'] = _dojo_options_for_javascript($content);
    }

    if (isset($options['form']))
    {
        $js_options['form'] = '"'.$options['form'].'"';
    }
    else if (isset($options['formElement']))
    {
        $js_options['form'] = $options['formElement'];
    }

    if (isset($options['handleAs']))
    {
        $js_options['handleAs'] = '"'.$options['handleAs'].'"';
    }

    if (isset($options['headers']))
    {
        $headers = _parse_attributes($options['headers']);
        $js_options['headers'] = _dojo_options_for_javascript($headers);
    }

    if (isset($options['noCache']))
    {
        $js_options['preventCache'] = $options['noCache'];
    }

    if (isset($options['type']) && ($options['type'] == 'synchronous'))
    {
        $js_options['sync'] = true;
    }

    if (isset($options['timeout']))
    {
        $js_options['timeout'] = intval($options['timeout']);
    }

    return _dojo_options_for_javascript($js_options);
}

function _dojo_options_for_javascript($options)
{
    $opts = array();
    foreach ($options as $key => $value)
    {
        $opts[] = $key.":"._dojo_boolean_for_javascript($value);
    }
    sort($opts);

    return '{'.join(', ', $opts).'}';
}

function _dojo_boolean_for_javascript($bool)
{
    if (is_bool($bool))
    {
        return ($bool === true ? 'true' : 'false');
    }
    return $bool;
}
?>

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * PNCAV
 *
 *

 *
 Redcom Ltda <www.redcom.com.co>

 *
 Proyecto PNCAV

 *

 */
/**
 * Modulo Compromisos
 * maneja el modulo COMPROMISOS en union con CCompromiso y CCompromisoData
 *
 * @see CPoliza
 * @see CPolizaData
 *
 * @package  modulos
 * @subpackage jurídico
 * @author Redcom Ltda
 * @version 2014.09.05
 * @copyright SERTIC - MINTICS
 */

defined('_VALID_PRY') or die('Restricted access');

$docData = new CPolizaData($db);

$task = $_REQUEST['task'];
if (empty($task))
    $task = 'list';

switch ($task){

    case 'list':

        if(isset($_REQUEST['txt_numerocontrato'])){
            $numero_contrato=$_REQUEST['txt_numerocontrato'];
            if($numero_contrato!=""){
                $consultaContrato=" AND pol_numero_contrato LIKE '$numero_contrato%'";
            }
        }else{
            $consultaContrato="";
        }
        if(isset($_REQUEST['txt_objeto'])){
            $objeto=$_REQUEST['txt_objeto'];
            if($objeto!=""){
                $consultaObjeto=" AND pol_objeto LIKE '$objeto%'";
            }
        }else{
            $consultaObjeto="";
        }
        if(isset($_REQUEST['txt_numero_poliza'])){
            $poliza=$_REQUEST['txt_numero_poliza'];
            if($poliza!=""){
                $consultaPoliza=" AND pol_numero_poliza LIKE '$poliza%'";
            }
        }else{
            $consultaPoliza="";
        }
        if(isset($_REQUEST['txt_tomador'])){
            $tomador=$_REQUEST['txt_tomador'];
            if($tomador!=""){
                $consultaTomador=" AND pol_tomador LIKE '$tomador%'";
            }
        }else{
            $consultaTomador="";
        }
        $criterio = "1".$consultaContrato.$consultaObjeto.$consultaPoliza.$consultaTomador;

        $form = new CHtmlForm();
        $form->setClassEtiquetas('td_label');
        $form->setTitle(TABLA_POLIZAS);
        $form->setId('frm_agregar_poliza');
        $form->setMethod('post');
        $form->setAction('?mod=' . $modulo . '&niv=' . $niv . '&task=list');

        $form->addEtiqueta(CAMPO_NUMERO_CONTRATO);
        $form->addInputText('text', 'txt_numerocontrato', 'txt_numerocontrato', 15, 19, $numero_contrato, '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" ');

        $form->addEtiqueta(CAMPO_OBJETO);
        $form->addInputText('text', 'txt_objeto', 'txt_objeto', 15, 19, $objeto, '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" ');

        $form->addEtiqueta(CAMPO_NUMERO_POLIZA);
        $form->addInputText('text', 'txt_numero_poliza', 'txt_numero_poliza', 15, 19, $poliza, '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" ');

        $form->addEtiqueta(CAMPO_TOMADOR);
        $form->addInputText('text', 'txt_tomador', 'txt_tomador', 15, 19, $tomador, '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_NUMEROS) . '" ');

        $form->addInputButton('submit', 'ok', 'ok', BTN_ACEPTAR, 'button', '');

        $form->writeForm();

        $elementos = $docData->getPolizas($criterio, "polizainterventoria");
        $dt = new CHtmlDataTable();
        $titulos = array(
                        CAMPO_NUMERO_CONTRATO,
                        CAMPO_OBJETO,
                        CAMPO_PLAZO,
                        CAMPO_FECHA_SUSCRIPCION,
                        CAMPO_CONTRATANTE,
                        CAMPO_CONTRATISTA,
                        CAMPO_NUMERO_POLIZA,
                        CAMPO_ASEGURADORA,
                        CAMPO_TOMADOR,
                        CAMPO_ASEGURADO,
                        CAMPO_BENEFICIARIO,
                        CAMPO_AMPARO,
                        CAMPO_PORCENTAJE,
                        CAMPO_VALOR_ASEGURADO,
                        CAMPO_VIGENCIA_INICIO,
                        CAMPO_VIGENCIA_FIN,
                        CAMPO_OBSERVACIONES,
                        CAMPO_ARCHIVO_INCIDENCIA);
        $dt->setDataRows($elementos);
        $dt->setTitleRow($titulos);

        $dt->setTitleTable(TABLA_POLIZAS);
		$dt->setFormatRow(array(null,null,null,null,null,null,null,null,null,null,null,null,null,array(0, ',', '.'),null,null,null,null));
        $dt->setSumColumns(array(14));

        $dt->setAddLink("?mod=" . $modulo . "&niv=" . $niv . "&task=add");
        $dt->setDeleteLink("?mod=" . $modulo . "&niv=" . $niv . "&task=delete");
        $dt->setEditLink("?mod=" . $modulo . "&niv=" . $niv . "&task=edit");
        $dt->setType(1);
        $dt->setPag(1);
        $dt->writeDataTable($niv);

        break;

    case 'add':
        $form = new CHtmlForm();
        $form->setClassEtiquetas('td_label');
        $form->setTitle(TITULO_AGREGAR_POLIZA);
        $form->setId('frm_agregar_poliza');
        $form->setMethod('post');
        $form->setAction('?mod=' . $modulo . '&niv=' . $niv . '&task=saveAdd');

        $form->addEtiqueta(CAMPO_NUMERO_CONTRATO);
        $form->addInputText('text', 'txt_numerocontrato', 'txt_numerocontrato', 15, 19, '', '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_OBJETO);
        $form->addTextArea('textarea', 'txt_objeto', 'txt_objeto', 15, 19, '', '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_PLAZO);
        $form->addInputText('text', 'txt_plazo', 'txt_plazo', 15, 19, '', '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_FECHA_SUSCRIPCION);
        $form->addInputDate('date', 'date_suscripcion', 'date_suscripcion', '', '%Y-%m-%d', '22', '22', '', 'pattern="' .
                PATTERN_FECHA . '" title="' . $html->traducirTildes(TITLE_FECHA) . '" required');

        $form->addEtiqueta(CAMPO_CONTRATANTE);
        $form->addInputText('text', 'txt_contratante', 'txt_contratante', 15, 19, '', '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_CONTRATISTA);
        $form->addInputText('text', 'txt_contratista', 'txt_contratista', 15, 19, '', '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_NUMERO_POLIZA);
        $form->addInputText('text', 'txt_numero_poliza', 'txt_numero_poliza', 15, 19, '', '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_ASEGURADORA);
        $form->addInputText('text', 'txt_aseguradora', 'txt_aseguradora', 15, 19, '', '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_TOMADOR);
        $form->addInputText('text', 'txt_tomador', 'txt_tomador', 15, 19, '', '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_ASEGURADO);
        $form->addInputText('text', 'txt_asegurado', 'txt_asegurado', 15, 19, '', '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_BENEFICIARIO);
        $form->addInputText('text', 'txt_beneficiario', 'txt_beneficiario', 15, 19, '', '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_AMPARO);
        $form->addInputText('text', 'txt_amparo', 'txt_amparo', 15, 19, '', '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_PORCENTAJE);
        $form->addInputText('text', 'txt_porcentaje', 'txt_porcentaje', 15, 19, '', '', 'pattern="' .
                PATTERN_NUMEROS_FINANCIEROS. '" title="' . $html->traducirTildes(TITLE_NUMEROS_FINANCIEROS) . '" required');
        //onkeyup="formatearNumero(this);"
        $form->addEtiqueta(CAMPO_VALOR_ASEGURADO);
        $form->addInputText('text', 'txt_valor_asegurado', 'txt_valor_asegurado', 15, 19, '', '', ' pattern="' .
                PATTERN_NUMEROS_FINANCIEROS . '" title="' . $html->traducirTildes(TITLE_NUMEROS) . '" required onkeyup="formatearNumero(this);"');

        $form->addEtiqueta(CAMPO_VIGENCIA_INICIO);
        $form->addInputDate('date', 'date_inicio', 'date_inicio', '', '%Y-%m-%d', '22', '22', '', 'pattern="' .
                PATTERN_FECHA . '" title="' . $html->traducirTildes(TITLE_FECHA) . '" required');

        $form->addEtiqueta(CAMPO_VIGENCIA_FIN);
        $form->addInputDate('date', 'date_fin', 'date_fin', '', '%Y-%m-%d', '22', '22', '', 'pattern="' .
                PATTERN_FECHA . '" title="' . $html->traducirTildes(TITLE_FECHA) . '" required');

        $form->addEtiqueta(CAMPO_OBSERVACIONES);
        $form->addTextArea('textarea', 'txt_observaciones', 'txt_observaciones', 15, 19, '', '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '"');

        $form->addEtiqueta(CAMPO_ARCHIVO_INCIDENCIA);
        $form->addInputFile('file', 'file_archivo', 'file_archivo', 15,'', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '"');

        $form->addInputButton('submit', 'ok', 'ok', BOTON_INSERTAR, 'button', '');
        $form->addInputButton('button', 'cancelar', 'cancelar', BOTON_CANCELAR, 'button', 'onClick=location.href="?mod=' . $modulo . '&niv=' . $niv . '"');
        $form->writeForm();

        break;

    case 'saveAdd':
        $numeroContrato     = $_REQUEST['txt_numerocontrato'];
        $objeto             = $_REQUEST['txt_objeto'];
        $plazo              = $_REQUEST['txt_plazo'];
        $fecha_suscripcion  = $_REQUEST['date_suscripcion'];
        $contratante        = $_REQUEST['txt_contratante'];
        $contratista        = $_REQUEST['txt_contratista'];
        $numero_poliza      = $_REQUEST['txt_numero_poliza'];
        $aseguradora        = $_REQUEST['txt_aseguradora'];
        $tomador            = $_REQUEST['txt_tomador'];
        $asegurado          = $_REQUEST['txt_asegurado'];
        $beneficiario       = $_REQUEST['txt_beneficiario'];
        $amparo             = $_REQUEST['txt_amparo'];
        $porcentaje         = $_REQUEST['txt_porcentaje']/100;
        $valor_asegurado    = $_REQUEST['txt_valor_asegurado'];
		$valor_asegurado 	= str_replace(".", "", $valor_asegurado);
        $inicio             = $_REQUEST['date_inicio'];
        $fin                = $_REQUEST['date_fin'];
        $observaciones      = $_REQUEST['txt_observaciones'];
        $archivo            = $_FILES['file_archivo'];

        $poliza = new CPoliza('',$docData);
        $poliza->setNumContrato($numeroContrato);
        $poliza->setObjeto($objeto);
        $poliza->setPlazo($plazo);
        $poliza->setFechaSuscripcion($fecha_suscripcion);
        $poliza->setContratante($contratante);
        $poliza->setContratista($contratista);
        $poliza->setNumeroPoliza($numero_poliza);
        $poliza->setAseguradora($aseguradora);
        $poliza->setTomador($tomador);
        $poliza->setAsegurado($asegurado);
        $poliza->setBeneficiario($beneficiario);
        $poliza->setAmparo($amparo);
        $poliza->setPorcentaje($porcentaje);
        $poliza->setValorAsegurado($valor_asegurado);
        $poliza->setVigenciaInicio($inicio);
        $poliza->setVigenciaFin($fin);
        $poliza->setObservacionesPoliza($observaciones);
        $poliza->setArchivoPoliza($archivo);
        $mesg=$poliza->saveNewPoliza("polizainterventoria");

        echo $html->generaAviso($mesg, "?mod=" . $modulo . "&niv=" . $niv . "&task=list");

        break;

    case 'edit':

        $id = $_REQUEST['id_element'];

        $poliza = new CPoliza($id, $docData);
        $poliza->loadPoliza("polizainterventoria");

        $numero_contrato=   $poliza->getNumContrato();
        $objeto=            $poliza->getObjeto();
        $plazo=             $poliza->getPlazo();
        $fecha_suscripcion= $poliza->getFechaSuscripcion();
        $contratante=       $poliza->getContratante();
        $contratista=       $poliza->getContratista();
        $numero_poliza=     $poliza->getNumeroPoliza();
        $aseguradora=       $poliza->getAseguradora();
        $tomador=           $poliza->getTomador();
        $asegurado=         $poliza->getAsegurado();
        $beneficiario=      $poliza->getBeneficiario();
        $amparo=            $poliza->getAmparo();
        $porcentaje=        $poliza->getPorcentajePoliza()*100;
        $valor_asegurado=   $poliza->getValorAsegurado();
        $inicio=            $poliza->getVigenciaInicio();
        $fin=               $poliza->getVigenciaFin();
        $observaciones=     $poliza->getObservacionesPoliza();

        $form = new CHtmlForm();
        $form->setClassEtiquetas('td_label');
        $form->setTitle(TITULO_EDITAR_POLIZA);
        $form->setId('frm_editar_poliza');
        $form->setMethod('post');
        $form->setAction('?mod=' . $modulo . '&niv=' . $niv . '&task=saveEdit');
        $form->addInputText('hidden', 'id_element', 'id_element', '', '', $id, '', '');
        $form->addEtiqueta(CAMPO_NUMERO_CONTRATO);
        $form->addInputText('text', 'txt_numerocontrato', 'txt_numerocontrato', 15, 19, $numero_contrato, '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_OBJETO);
        $form->addTextArea('textarea', 'txt_objeto', 'txt_objeto', 15, 19, $objeto, '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_PLAZO);
        $form->addInputText('text', 'txt_plazo', 'txt_plazo', 15, 19, $plazo, '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_FECHA_SUSCRIPCION);
        $form->addInputDate('date', 'date_suscripcion', 'date_suscripcion', $fecha_suscripcion, '%Y-%m-%d', '22', '22', '', 'pattern="' .
                PATTERN_FECHA . '" title="' . $html->traducirTildes(TITLE_FECHA) . '" required');

        $form->addEtiqueta(CAMPO_CONTRATANTE);
        $form->addInputText('text', 'txt_contratante', 'txt_contratante', 15, 19, $contratante, '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_CONTRATISTA);
        $form->addInputText('text', 'txt_contratista', 'txt_contratista', 15, 19, $contratista, '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_NUMERO_POLIZA);
        $form->addInputText('text', 'txt_numero_poliza', 'txt_numero_poliza', 15, 19, $numero_poliza, '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_ASEGURADORA);
        $form->addInputText('text', 'txt_aseguradora', 'txt_aseguradora', 15, 19, $aseguradora, '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_TOMADOR);
        $form->addInputText('text', 'txt_tomador', 'txt_tomador', 15, 19, $tomador, '', 'pattern="' .
                PATTERN_ALFANUMERICO. '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_ASEGURADO);
        $form->addInputText('text', 'txt_asegurado', 'txt_asegurado', 15, 19, $asegurado, '', 'pattern="' .
                PATTERN_ALFANUMERICO. '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_BENEFICIARIO);
        $form->addInputText('text', 'txt_beneficiario', 'txt_beneficiario', 15, 19, $beneficiario, '', 'pattern="' .
                PATTERN_ALFANUMERICO. '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_AMPARO);
        $form->addInputText('text', 'txt_amparo', 'txt_amparo', 15, 19, $amparo, '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '" required');

        $form->addEtiqueta(CAMPO_PORCENTAJE);
        $form->addInputText('text', 'txt_porcentaje', 'txt_porcentaje', 15, 19, $porcentaje, '', 'pattern="' .
                PATTERN_NUMEROS_FINANCIEROS. '" title="' . $html->traducirTildes(TITLE_NUMEROS_FINANCIEROS) . '" required');
        //onkeyup="formatearNumero(this);"
        $form->addEtiqueta(CAMPO_VALOR_ASEGURADO);
        $form->addInputText('text', 'txt_valor_asegurado', 'txt_valor_asegurado', 15, 19, $valor_asegurado, '', ' pattern="' .
                PATTERN_NUMEROS_FINANCIEROS . '" title="' . $html->traducirTildes(TITLE_NUMEROS_FINANCIEROS) . '" required onkeyup="formatearNumero(this);"');

        $form->addEtiqueta(CAMPO_VIGENCIA_INICIO);
        $form->addInputDate('date', 'date_inicio', 'date_inicio', $inicio, '%Y-%m-%d', '22', '22', '', 'pattern="' .
                PATTERN_FECHA . '" title="' . $html->traducirTildes(TITLE_FECHA) . '" required');

        $form->addEtiqueta(CAMPO_VIGENCIA_FIN);
        $form->addInputDate('date', 'date_fin', 'date_fin', $fin, '%Y-%m-%d', '22', '22', '', 'pattern="' .
                PATTERN_FECHA . '" title="' . $html->traducirTildes(TITLE_FECHA) . '" required');

        $form->addEtiqueta(CAMPO_OBSERVACIONES);
        $form->addTextArea('textarea', 'txt_observaciones', 'txt_observaciones', 15, 19, $observaciones, '', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '"');

        $form->addEtiqueta(CAMPO_ARCHIVO_INCIDENCIA);
        $form->addInputFile('file', 'file_archivo', 'file_archivo', 15,'', 'pattern="' .
                PATTERN_ALFANUMERICO . '" title="' . $html->traducirTildes(TITLE_ALFANUMERICO) . '"');

        $form->addInputButton('submit', 'ok', 'ok', BOTON_EDITAR, 'button', '');
        $form->addInputButton('button', 'cancelar', 'cancelar', BOTON_CANCELAR, 'button', 'onClick=location.href="?mod=' . $modulo . '&niv=' . $niv . '"');
        $form->writeForm();
        break;

    case 'saveEdit':
        $id                 = $_REQUEST['id_element'];
        $numeroContrato     = $_REQUEST['txt_numerocontrato'];
        $objeto             = $_REQUEST['txt_objeto'];
        $plazo              = $_REQUEST['txt_plazo'];
        $fecha_suscripcion  = $_REQUEST['date_suscripcion'];
        $contratante        = $_REQUEST['txt_contratante'];
        $contratista        = $_REQUEST['txt_contratista'];
        $numero_poliza      = $_REQUEST['txt_numero_poliza'];
        $aseguradora        = $_REQUEST['txt_aseguradora'];
        $tomador            = $_REQUEST['txt_tomador'];
        $asegurado          = $_REQUEST['txt_asegurado'];
        $beneficiario       = $_REQUEST['txt_beneficiario'];
        $amparo             = $_REQUEST['txt_amparo'];
        $porcentaje         = $_REQUEST['txt_porcentaje']/100;
        $valor_asegurado    = $_REQUEST['txt_valor_asegurado'];
		$valor_asegurado 	= str_replace(".", "", $valor_asegurado);
        $inicio             = $_REQUEST['date_inicio'];
        $fin                = $_REQUEST['date_fin'];
        $observaciones      = $_REQUEST['txt_observaciones'];
        $archivo            = $_FILES['file_archivo'];

        $poliza = new CPoliza($id,$docData);
        $poliza->setNumContrato($numeroContrato);
        $poliza->setObjeto($objeto);
        $poliza->setPlazo($plazo);
        $poliza->setFechaSuscripcion($fecha_suscripcion);
        $poliza->setContratante($contratante);
        $poliza->setContratista($contratista);
        $poliza->setNumeroPoliza($numero_poliza);
        $poliza->setAseguradora($aseguradora);
        $poliza->setTomador($tomador);
        $poliza->setAsegurado($asegurado);
        $poliza->setBeneficiario($beneficiario);
        $poliza->setAmparo($amparo);
        $poliza->setPorcentaje($porcentaje);
        $poliza->setValorAsegurado($valor_asegurado);
        $poliza->setVigenciaInicio($inicio);
        $poliza->setVigenciaFin($fin);
        $poliza->setObservacionesPoliza($observaciones);
        $poliza->setArchivoPoliza($archivo);
        $mesg=$poliza->updatePoliza("polizainterventoria");
        echo $html->generaAviso($mesg, "?mod=" . $modulo . "&niv=" . $niv . "&task=list");
        break;

    case 'delete':
        $id = $_REQUEST['id_element'];
        echo $html->generaAdvertencia(MENSAJE_ELIMINAR_POLIZA, '?mod=' . $modulo . '&niv='
                . $niv . '&task=confirmDelete&id_element=' . $id, '"onClick=location.href="?mod='.$modulo.'&niv='.$niv);
        break;

    case 'confirmDelete':
        $id = $_REQUEST['id_element'];
        $poliza = new CPoliza($id, $docData);
        $poliza->loadPoliza("polizainterventoria");
        $mens = $poliza->deletePoliza("polizainterventoria");
        echo $html->generaAviso($mens, "?mod=" . $modulo . "&niv=1&task=list");
        break;
    default:
        include('templates/html/under.html');

}

?>


text:
import numpy

from chainer import functions
from chainer import testing

@testing.parameterize(*testing.product({
    'shape': [(3, 2), ()],
    'dtype': [numpy.float16, numpy.float32, numpy.float64],
}))
@testing.fix_random()
@testing.inject_backend_tests(
    None,
    # CPU tests
    [
        {},
    ]
    # GPU tests
    + testing.product({
        'use_cuda': [True],
        'cuda_device': [0, 1],
    })
    # ChainerX tests
    + testing.product({
        'use_chainerx': [True],
        'chainerx_device': ['native:0', 'cuda:0', 'cuda:1'],
    })
)
class TestCeil(testing.FunctionTestCase):

    skip_backward_test = True
    skip_double_backward_test = True

    def generate_inputs(self):
        while True:
            x = numpy.random.uniform(
                -10.0, 10.0, self.shape).astype(self.dtype)
            if (numpy.abs(x - numpy.round(x)) > 1e-2).all():
                return x,

    def forward(self, inputs, device):
        x, = inputs
        y = functions.ceil(x)
        return y,

    def forward_expected(self, inputs):
        x, = inputs
        expected = numpy.ceil(x)
        expected = numpy.asarray(expected)
        return expected,

testing.run_module(__name__, __file__)


text:
Today

<<

<

>

>>

        Sunday
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
        Saturday


text:
<?php

namespace tests\entity;

use WebComplete\core\entity\AbstractEntityRepositoryMicro;

class UserRepositoryMicro extends AbstractEntityRepositoryMicro
{

    protected $collectionName = 'users';
}


text:
package com.google.ads.googleads.v12.services.stub;

import com.google.ads.googleads.lib.GrpcGoogleAdsCallableFactory;

public class GrpcCustomizerAttributeServiceCallableFactory extends GrpcGoogleAdsCallableFactory {
}


text:
import sys
import tensorflow as tf
import tools
import numpy as np
import vgg
import argparse
from skimage.transform import resize
from skimage.io import imread

G = tf.Graph()
with G.as_default():
    images = tf.placeholder("float", [1, 224, 224, 3])
    logits = vgg.build(images, n_classes=10, training=False)
    probs = tf.nn.softmax(logits)

def predict(im):
    labels = ['airplane', 'automobile', 'bird', 'cat', 'deer',
              'dog', 'frog', 'horse', 'ship', 'truck']
    if im.shape != (224, 224, 3):
        im = resize(im, (224, 224))
    im = np.expand_dims(im, 0)
    sess = tf.get_default_session()
    results = sess.run(probs, {images: im})
    return labels[np.argmax(results)]

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-w", "--weights", required=True, help="path to weights.npz file")
    parser.add_argument("image", help="path to jpg image")
    args = parser.parse_args()
    im = imread(args.image)
    sess = tf.Session(graph=G)
    with sess.as_default():
        tools.load_weights(G, args.weights)
        print predict(im)


text:
package leap.web.api.meta.model;

import java.util.Map;

public class MApiTag extends MApiNamedWithDesc {

    public MApiTag(String name) {
        super(name);
    }

    public MApiTag(String name, String title) {
        super(name, title);
    }

    public MApiTag(String name, String title, String summary, String description, Map<String, Object> attrs) {
        super(name, title, summary, description, attrs);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
    xmlns:android="http://schemas.android.com/apk/res/android"
    id="jp.wizcorp.phonegap.plugin.wizAssetsPlugin"
    version="6.1.1">

    <name>Wizard Asset Manager Plugin</name>
    <description>This plugin allows you easily download, lookup and delete files.</description>
    <author>Ally Ogilvie</author>
    <keywords>asset, manager, wizAssets, file, wizcorp, wizard</keywords>

    <engines>
        <engine name="cordova" version=">=3.0.0" />
    </engines>

    <license>MIT</license>

    <js-module src="www/phonegap/plugin/wizAssets/wizAssets.js" name="wizAssetsPlugin" target="phonegap/plugin/wizAssets/wizAssets.js">
        <clobbers target="window.wizAssets" />
    </js-module>
    <js-module src="www/phonegap/plugin/wizAssets/WizAssetsError.js" name="WizAssetsError" target="phonegap/plugin/wizAssets/WizAssetsError.js">
        <clobbers target="window.WizAssetsError" />
    </js-module>

    <!-- ios -->
    <platform name="ios">

        <config-file target="config.xml" parent="/*">
            <feature name="wizAssetsPlugin">
                <param name="ios-package" value="WizAssetsPlugin"/>
                <param name="onload" value="true" />
            </feature>
            <plugin name="WizAssetsPlugin" value="WizAssetsPlugin"/>
        </config-file>

        <!-- Plugin files -->
        <header-file src="platforms/ios/HelloCordova/Plugins/WizAssetsPlugin/WizAssetsPlugin.h" />
        <source-file src="platforms/ios/HelloCordova/Plugins/WizAssetsPlugin/WizAssetsPlugin.m" />

        <!-- Logger -->
        <source-file src="platforms/ios/HelloCordova/Plugins/WizAssetsPlugin/WizDebugLog.h" />

    </platform>

    <!-- android -->
    <platform name="android">

        <config-file target="res/xml/config.xml" parent="/*">
            <feature name="WizAssetsPlugin" >
                <param name="android-package" value="jp.wizcorp.phonegap.plugin.WizAssets.WizAssetsPlugin"/>
            </feature>
        </config-file>

        <source-file src="platforms/android/src/jp/wizcorp/phonegap/plugin/WizAssets/HttpToFile.java"
                     target-dir="src/jp/wizcorp/phonegap/plugin/WizAssets"/>

        <source-file src="platforms/android/src/jp/wizcorp/phonegap/plugin/WizAssets/WizAssetsPlugin.java"
                target-dir="src/jp/wizcorp/phonegap/plugin/WizAssets"/>

        <source-file src="platforms/android/src/jp/wizcorp/phonegap/plugin/WizAssets/AndroidLogger.java"
                     target-dir="src/jp/wizcorp/phonegap/plugin/WizAssets"/>

        <source-file src="platforms/android/src/jp/wizcorp/phonegap/plugin/WizAssets/ILogger.java"
                     target-dir="src/jp/wizcorp/phonegap/plugin/WizAssets"/>

    </platform>

</plugin>


text:
package net.roboconf.dm.rest.client.delegates;

import java.net.URI;

import javax.security.auth.login.LoginException;
import javax.ws.rs.core.UriBuilder;

import org.glassfish.grizzly.http.server.HttpServer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;

import net.roboconf.dm.rest.client.WsClient;
import net.roboconf.dm.rest.client.exceptions.DebugWsException;
import net.roboconf.dm.rest.commons.security.AuthenticationManager;
import net.roboconf.dm.rest.commons.security.AuthenticationManager.IAuthService;
import net.roboconf.dm.rest.services.internal.RestApplication;

/**
 * @author Vincent Zurczak - Linagora
 */
public class AuthenticationWsDelegateTest {

	private static final String REST_URI = "http://localhost:8090";

	private WsClient client;
	private HttpServer httpServer;
	private IAuthService authService;

	@After
	public void after() {

		if( this.httpServer != null )
			this.httpServer.stop();

		if( this.client != null )
			this.client.destroy();
	}

	@Before
	public void before() throws Exception {

		URI uri = UriBuilder.fromUri( REST_URI ).build();
		RestApplication restApp = new RestApplication( null );

		AuthenticationManager authenticationMngr = new AuthenticationManager( "whatever" );
		this.authService = Mockito.mock( IAuthService.class );
		authenticationMngr.setAuthService( this.authService );
		restApp.setAuthenticationManager( authenticationMngr );

		this.httpServer = GrizzlyServerFactory.createHttpServer( uri, restApp );
		this.client = new WsClient( REST_URI );
	}

	@Test( expected = DebugWsException.class )
	public void testLogin_failure() throws Exception {

		Mockito.doThrow( new LoginException( "for test" )).when( this.authService ).authenticate( "u", "p" );
		this.client.getAuthenticationWsDelegate().login( "u", "p" );
	}

	@Test
	public void testLogin_success() throws Exception {

		String sessionId = this.client.getAuthenticationWsDelegate().login( "u", "p" );
		Assert.assertNotNull( sessionId );
		this.client.getAuthenticationWsDelegate().logout( sessionId );

		// Log out twice does not result in any error
		this.client.getAuthenticationWsDelegate().logout( sessionId );
	}
}


text:
from django.conf.urls.defaults import *
from django.contrib.contenttypes.models import ContentType

user_contenttype_id = ContentType.objects.get(app_label='auth', name='user')

urlpatterns = patterns('offensivecontent.views',
    url(
        regex = r'^(?P<content_type_id>\d+)/(?P<object_id>\d+)/add/$',
        view = 'add',
        name = 'oc_add',
    ),
    url(
        regex = r'^(?P<content_type_id>\d+)/(?P<object_id>\d+)/add_ajax/$',
        view = 'add_ajax',
        name = 'oc_add_ajax',
    ),
    url(
        regex = r'^(?P<object_id>\d+)/disable/$',
        view = 'content_cotroller',
        kwargs = {'method': 'disable_content'},
        name = 'oc_disable_content'
    ),
    url(
        regex = r'^(?P<object_id>\d+)/enable/$',
        view = 'content_cotroller',
        kwargs = {'method': 'enable_content'},
        name = 'oc_enable_content',
    ),
    url(
        regex = r'^user/(?P<object_id>\d+)/disable/$',
        view = 'content_cotroller',
        kwargs = {
            'content_type_id': user_contenttype_id,
            'method': 'disable_user'},
        name = "oc_disable_user"
    ),
    url(
        regex = r'^user/(?P<object_id>\d+)/enable/$',
        view = 'content_cotroller',
        kwargs = {
            'content_type_id': user_contenttype_id,
            'method': 'enable_user'},
        name = "oc_enable_user"
    ),
    url(
        regex = r'^(?P<object_id>\d+)/mark_safe/$',
        view = 'mark_safe',
        kwargs = {'is_safe': True,},
        name = "oc_mark_safe",
    ),
)


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <committees>
      <billCommittees>
        <item>
          <type>Standing</type>
          <subcommittees />
          <systemCode>sseg00</systemCode>
          <activities>
            <item>
              <date>2017-06-08T21:46:02Z</date>
              <name>Reported by</name>
            </item>
            <item>
              <date>2017-03-30T13:30:00Z</date>
              <name>Markup by</name>
            </item>
            <item>
              <date>2017-02-13T23:15:48Z</date>
              <name>Referred to</name>
            </item>
          </activities>
          <chamber>Senate</chamber>
          <name>Energy and Natural Resources Committee</name>
        </item>
      </billCommittees>
    </committees>
    <originChamber>Senate</originChamber>
    <cosponsors>
      <item>
        <bioguideId>H001061</bioguideId>
        <sponsorshipDate>2017-02-13</sponsorshipDate>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <state>ND</state>
        <fullName>Sen. Hoeven, John [R-ND]</fullName>
        <party>R</party>
        <sponsorshipWithdrawnDate />
        <middleName />
        <firstName>John</firstName>
        <lastName>Hoeven</lastName>
        <identifiers>
          <lisID>2079</lisID>
          <bioguideId>H001061</bioguideId>
          <gpoId>8331</gpoId>
        </identifiers>
      </item>
      <item>
        <bioguideId>B001230</bioguideId>
        <sponsorshipDate>2017-02-13</sponsorshipDate>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <state>WI</state>
        <fullName>Sen. Baldwin, Tammy [D-WI]</fullName>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <middleName />
        <firstName>TAMMY</firstName>
        <lastName>BALDWIN</lastName>
        <identifiers>
          <lisID>1558</lisID>
          <gpoId>8215</gpoId>
          <bioguideId>B001230</bioguideId>
        </identifiers>
      </item>
      <item>
        <bioguideId>G000555</bioguideId>
        <sponsorshipDate>2017-02-13</sponsorshipDate>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <state>NY</state>
        <fullName>Sen. Gillibrand, Kirsten E. [D-NY]</fullName>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <middleName>E.</middleName>
        <firstName>Kirsten</firstName>
        <lastName>Gillibrand</lastName>
        <identifiers>
          <bioguideId>G000555</bioguideId>
          <lisID>1866</lisID>
          <gpoId>8336</gpoId>
        </identifiers>
      </item>
      <item>
        <bioguideId>H001069</bioguideId>
        <sponsorshipDate>2017-02-13</sponsorshipDate>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <state>ND</state>
        <fullName>Sen. Heitkamp, Heidi [D-ND]</fullName>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <middleName />
        <firstName>Heidi</firstName>
        <lastName>Heitkamp</lastName>
        <identifiers>
          <lisID>2174</lisID>
          <gpoId />
          <bioguideId>H001069</bioguideId>
        </identifiers>
      </item>
      <item>
        <bioguideId>F000457</bioguideId>
        <sponsorshipDate>2017-02-13</sponsorshipDate>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <state>MN</state>
        <fullName>Sen. Franken, Al [D-MN]</fullName>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <middleName />
        <firstName>Al</firstName>
        <lastName>Franken</lastName>
        <identifiers>
          <lisID>1969</lisID>
          <bioguideId>F000457</bioguideId>
          <gpoId>8339</gpoId>
        </identifiers>
      </item>
      <item>
        <bioguideId>L000174</bioguideId>
        <sponsorshipDate>2017-02-13</sponsorshipDate>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <state>VT</state>
        <fullName>Sen. Leahy, Patrick J. [D-VT]</fullName>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <middleName>JOSEPH</middleName>
        <firstName>PATRICK</firstName>
        <lastName>LEAHY</lastName>
        <identifiers>
          <bioguideId>L000174</bioguideId>
          <gpoId>8244</gpoId>
          <lisID>1383</lisID>
        </identifiers>
      </item>
      <item>
        <bioguideId>S000770</bioguideId>
        <sponsorshipDate>2017-02-13</sponsorshipDate>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <state>MI</state>
        <fullName>Sen. Stabenow, Debbie [D-MI]</fullName>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <middleName>ANN</middleName>
        <firstName>DEBORAH</firstName>
        <lastName>STABENOW</lastName>
        <identifiers>
          <bioguideId>S000770</bioguideId>
          <lisID>1531</lisID>
          <gpoId>8261</gpoId>
        </identifiers>
      </item>
      <item>
        <bioguideId>S000033</bioguideId>
        <sponsorshipDate>2017-02-13</sponsorshipDate>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <state>VT</state>
        <fullName>Sen. Sanders, Bernard [I-VT]</fullName>
        <party>I</party>
        <sponsorshipWithdrawnDate />
        <middleName />
        <firstName>BERNARD</firstName>
        <lastName>SANDERS</lastName>
        <identifiers>
          <gpoId>8270</gpoId>
          <lisID>1010</lisID>
          <bioguideId>S000033</bioguideId>
        </identifiers>
      </item>
      <item>
        <bioguideId>P000595</bioguideId>
        <sponsorshipDate>2017-02-13</sponsorshipDate>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <state>MI</state>
        <fullName>Sen. Peters, Gary C. [D-MI]</fullName>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <middleName>C.</middleName>
        <firstName>Gary</firstName>
        <lastName>Peters</lastName>
        <identifiers>
          <bioguideId>P000595</bioguideId>
          <gpoId>7994</gpoId>
          <lisID>1929</lisID>
        </identifiers>
      </item>
    </cosponsors>
    <notes />
    <introducedDate>2017-02-13</introducedDate>
    <committeeReports>
      <committeeReport>
        <citation>S. Rept. 115-99</citation>
      </committeeReport>
    </committeeReports>
    <createDate>2017-02-14T05:20:37Z</createDate>
    <actions>
      <item>
        <actionDate>2017-06-08</actionDate>
        <committee />
        <links />
        <sourceSystem>
          <name>Senate</name>
          0
        </sourceSystem>
        <text>Placed on Senate Legislative Calendar under General Orders. Calendar No. 129.</text>
        <type>Calendars</type>
      </item>
      <item>
        <actionDate>2017-06-08</actionDate>
        <committee>
          <name>Energy and Natural Resources Committee</name>
          <systemCode>sseg00</systemCode>
        </committee>
        <links>
          <link>
            <name>report No. 115-99</name>
            <url>https://www.congress.gov/congressional-report/115th-congress/senate-report/99</url>
          </link>
        </links>
        <sourceSystem>
          <name>Senate</name>
          0
        </sourceSystem>
        <text>Committee on Energy and Natural Resources. Reported by Senator Murkowski without amendment. With written report No. 115-99.</text>
        <type>Committee</type>
      </item>
      <item>
        <actionDate>2017-06-08</actionDate>
        <links>
          <link>
            <name>report No. 115-99</name>
            <url>https://www.congress.gov/congressional-report/115th-congress/senate-report/99</url>
          </link>
        </links>
        <sourceSystem>
          <name>Library of Congress</name>
          9
        </sourceSystem>
        <committee>
          <name>Energy and Natural Resources Committee</name>
          <systemCode>sseg00</systemCode>
        </committee>
        <text>Committee on Energy and Natural Resources. Reported by Senator Murkowski without amendment. With written report No. 115-99.</text>
        <actionCode>14000</actionCode>
        <type>Committee</type>
      </item>
      <item>
        <actionDate>2017-03-30</actionDate>
        <committee>
          <name>Energy and Natural Resources Committee</name>
          <systemCode>sseg00</systemCode>
        </committee>
        <links />
        <sourceSystem>
          <name>Senate</name>
          0
        </sourceSystem>
        <text>Committee on Energy and Natural Resources. Ordered to be reported without amendment favorably.</text>
        <type>Committee</type>
      </item>
      <item>
        <actionDate>2017-02-13</actionDate>
        <committee>
          <name>Energy and Natural Resources Committee</name>
          <systemCode>sseg00</systemCode>
        </committee>
        <links />
        <sourceSystem>
          <name>Senate</name>
          0
        </sourceSystem>
        <text>Read twice and referred to the Committee on Energy and Natural Resources.</text>
        <type>IntroReferral</type>
      </item>
      <item>
        <actionDate>2017-02-13</actionDate>
        <links />
        <sourceSystem>
          <name>Library of Congress</name>
          9
        </sourceSystem>
        <committee />
        <text>Introduced in Senate</text>
        <actionCode>10000</actionCode>
        <type>IntroReferral</type>
      </item>
      <actionByCounts>
        <senate>6</senate>
      </actionByCounts>
      <actionTypeCounts>
        <referredToCommittee>1</referredToCommittee>
        <introducedInSenate>1</introducedInSenate>
        <placedOnCalendarGeneralOrders>1</placedOnCalendarGeneralOrders>
        <reportedToSenate>2</reportedToSenate>
        <orderedReported>1</orderedReported>
      </actionTypeCounts>
    </actions>
    <updateDate>2017-08-10T13:24:03Z</updateDate>
    <billType>S</billType>
    <policyArea>
      <name>Public Lands and Natural Resources</name>
    </policyArea>
    <congress>115</congress>
    <sponsors>
      <item>
        <fullName>Sen. Klobuchar, Amy [D-MN]</fullName>
        <middleName />
        <identifiers>
          <gpoId>8249</gpoId>
          <lisID>1826</lisID>
          <bioguideId>K000367</bioguideId>
        </identifiers>
        <lastName>Klobuchar</lastName>
        <firstName>Amy</firstName>
        <bioguideId>K000367</bioguideId>
        <party>D</party>
        <byRequestType />
        <state>MN</state>
      </item>
    </sponsors>
    <recordedVotes />
    <calendarNumbers>
      <item>
        <number>0129</number>
        <calendar>Senate Calendar of Business</calendar>
      </item>
    </calendarNumbers>
    <billNumber>363</billNumber>
    <titles>
      <item>
        <titleType>(Extracted from GPO) Short Titles as Reported to Senate</titleType>
        <parentTitleType />
        <title>North Country National Scenic Trail Route Adjustment Act</title>
        <chamberCode>S</chamberCode>
        <chamberName>Senate</chamberName>
      </item>
      <item>
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <parentTitleType />
        <title>North Country National Scenic Trail Route Adjustment Act</title>
        <chamberCode />
        <chamberName />
      </item>
      <item>
        <titleType>Short Titles as Reported to Senate</titleType>
        <parentTitleType>Short Titles Senate</parentTitleType>
        <title>North Country National Scenic Trail Route Adjustment Act</title>
        <chamberCode>S</chamberCode>
        <chamberName>Senate</chamberName>
      </item>
      <item>
        <titleType>Short Titles as Introduced</titleType>
        <parentTitleType />
        <title>North Country National Scenic Trail Route Adjustment Act</title>
        <chamberCode />
        <chamberName />
      </item>
      <item>
        <titleType>Official Title as Introduced</titleType>
        <parentTitleType />
        <title>A bill to revise the authorized route of the North Country National Scenic Trail in northeastern Minnesota and to extend the trail into Vermont to connect with the Appalachian National Scenic Trail, and for other purposes.</title>
        <chamberCode />
        <chamberName />
      </item>
      <item>
        <titleType>Display Title</titleType>
        <parentTitleType />
        <title>North Country National Scenic Trail Route Adjustment Act</title>
        <chamberCode />
        <chamberName />
      </item>
    </titles>
    <title>North Country National Scenic Trail Route Adjustment Act</title>
    <version>1.0.0</version>
    <cboCostEstimates>
      <item>
        <pubDate>2017-04-17T20:01:47Z</pubDate>
        <url>https://www.cbo.gov/publication/52645</url>
        <title>S. 363, North Country National Scenic Trail Route Adjustment Act</title>
      </item>
    </cboCostEstimates>
    <summaries>
      <billSummaries>
        <item>
          <updateDate>2017-02-13T05:00:00Z</updateDate>
          <actionDesc>Introduced in Senate</actionDesc>
          <name>Introduced in Senate</name>
          <actionDate>2017-02-13</actionDate>
          <versionCode>00</versionCode>
          <text><![CDATA[
North Country National Scenic Trail Route Adjustment Act

 This bill amends the National Trails System Act to revise the authorized route of the North Country National Scenic Trail to extend it to the Appalachian Trail in Vermont and to modify the route in northeastern Minnesota.
]]></text>
          <lastSummaryUpdateDate>2017-03-03T22:21:40Z</lastSummaryUpdateDate>
        </item>
        <item>
          <updateDate>2017-06-08T14:10:33Z</updateDate>
          <actionDesc>Reported to Senate without amendment</actionDesc>
          <name>Reported to Senate without amendment</name>
          <actionDate>2017-06-08</actionDate>
          <versionCode>80</versionCode>
          <text><![CDATA[
(This measure has not been amended since it was introduced. The summary has been expanded because action occurred on the measure.)

North Country National Scenic Trail Route Adjustment Act

 (Sec. 2) This bill amends the National Trails System Act to revise the authorized route of the North Country National Scenic Trail to extend it to the Appalachian Trail in Vermont and to modify the route in northeastern Minnesota.
]]></text>
          <lastSummaryUpdateDate>2017-07-06T18:46:42Z</lastSummaryUpdateDate>
        </item>
      </billSummaries>
    </summaries>
    <relatedBills>
      <item>
        <number>1026</number>
        <latestTitle>North Country National Scenic Trail Route Adjustment Act</latestTitle>
        <congress>115</congress>
        <type>HR</type>
        <relationshipDetails>
          <item>
            <type>Identical bill</type>
            <identifiedBy>CRS</identifiedBy>
          </item>
        </relationshipDetails>
        <latestAction>
          <actionDate>2017-02-24</actionDate>
          <text>Referred to the Subcommittee on Federal Lands.</text>
        </latestAction>
      </item>
    </relatedBills>
    <subjects>
      <billSubjects>
        <policyArea>
          <name>Public Lands and Natural Resources</name>
        </policyArea>
        <legislativeSubjects>
          <item>
            <name>Minnesota</name>
          </item>
          <item>
            <name>Outdoor recreation</name>
          </item>
          <item>
            <name>Parks, recreation areas, trails</name>
          </item>
          <item>
            <name>Vermont</name>
          </item>
        </legislativeSubjects>
      </billSubjects>
    </subjects>
    <latestAction>
      <actionDate>2017-06-08</actionDate>
      <links />
      <text>Placed on Senate Legislative Calendar under General Orders. Calendar No. 129.</text>
    </latestAction>
    <laws />
    <amendments />
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Composition;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Shell.FindAllReferences;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudio.Language.Intellisense;

namespace Microsoft.VisualStudio.LanguageServices.FindReferences
{
    [Export(typeof(IStreamingFindReferencesPresenter)), Shared]
    internal partial class StreamingFindReferencesPresenter :
        ForegroundThreadAffinitizedObject, IStreamingFindReferencesPresenter
    {
        public const string RoslynFindReferencesTableDataSourceIdentifier =
            nameof(RoslynFindReferencesTableDataSourceIdentifier);

        public const string RoslynFindReferencesTableDataSourceSourceTypeIdentifier =
            nameof(RoslynFindReferencesTableDataSourceSourceTypeIdentifier);

        private readonly IServiceProvider _serviceProvider;
        private readonly IAsynchronousOperationListener _asyncListener;

        private readonly ITextBufferFactoryService _textBufferFactoryService;
        private readonly IProjectionBufferFactoryService _projectionBufferFactoryService;
        private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
        private readonly ITextEditorFactoryService _textEditorFactoryService;
        private readonly IContentTypeRegistryService _contentTypeRegistryService;

        private readonly ClassificationTypeMap _typeMap;
        private readonly IEditorFormatMapService _formatMapService;
        private readonly IFindAllReferencesService _vsFindAllReferencesService;

        [ImportingConstructor]
        public StreamingFindReferencesPresenter(
            Shell.SVsServiceProvider serviceProvider,
            ITextBufferFactoryService textBufferFactoryService,
            IProjectionBufferFactoryService projectionBufferFactoryService,
            IEditorOptionsFactoryService editorOptionsFactoryService,
            ITextEditorFactoryService textEditorFactoryService,
            IContentTypeRegistryService contentTypeRegistryService,
            ClassificationTypeMap typeMap,
            IEditorFormatMapService formatMapService,
            [ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners)
        {
            _serviceProvider = serviceProvider;
            _textBufferFactoryService = textBufferFactoryService;
            _projectionBufferFactoryService = projectionBufferFactoryService;
            _editorOptionsFactoryService = editorOptionsFactoryService;
            _contentTypeRegistryService = contentTypeRegistryService;

            _textEditorFactoryService = textEditorFactoryService;
            _typeMap = typeMap;
            _formatMapService = formatMapService;

            _asyncListener = new AggregateAsynchronousOperationListener(
                asyncListeners, FeatureAttribute.ReferenceHighlighting);

            _vsFindAllReferencesService = (IFindAllReferencesService)_serviceProvider.GetService(typeof(SVsFindAllReferences));
        }

        public FindReferencesContext StartSearch()
        {
            this.AssertIsForeground();

            // Get the appropriate window for FAR results to go into.
            var window = _vsFindAllReferencesService.StartSearch(label: null);

            // Make the data source that will feed data into this window.
            var dataSource = new TableDataSourceFindReferencesContext(this, window);

            // And return the data source so that the FindRefs engine can report results
            // which the data source can then create the appropriate presentation items for
            // for the window.
            return dataSource;
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gagravarr.speex;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.gagravarr.ogg.OggFile;
import org.gagravarr.ogg.OggPacket;
import org.gagravarr.ogg.OggPacketReader;
import org.gagravarr.ogg.OggPacketWriter;
import org.gagravarr.ogg.OggStreamIdentifier;
import org.gagravarr.ogg.OggStreamIdentifier.OggStreamType;
import org.gagravarr.ogg.audio.OggAudioHeaders;
import org.gagravarr.ogg.audio.OggAudioSetupHeader;
import org.gagravarr.ogg.audio.OggAudioStream;

/**
 * This is a wrapper around an OggFile that lets you
 *  get at all the interesting bits of a Speex file.
 */
public class SpeexFile implements OggAudioStream, OggAudioHeaders, Closeable {
    private OggFile ogg;
    private OggPacketReader r;
    private OggPacketWriter w;
    private int sid = -1;

    private SpeexInfo info;
    private SpeexTags tags;

    private List<SpeexAudioData> writtenPackets;

    /**
     * Opens the given file for reading
     */
    public SpeexFile(File f) throws IOException, FileNotFoundException {
        this(new OggFile(new FileInputStream(f)));
    }
    /**
     * Opens the given file for reading
     */
    public SpeexFile(OggFile ogg) throws IOException {
        this(ogg.getPacketReader());
        this.ogg = ogg;
    }
    /**
     * Loads a Speex File from the given packet reader.
     */
    public SpeexFile(OggPacketReader r) throws IOException {
        this.r = r;

        OggPacket p = null;
        while( (p = r.getNextPacket()) != null ) {
            if (p.isBeginningOfStream() && p.getData().length > 10) {
                if (SpeexPacketFactory.isSpeexStream(p)) {
                    sid = p.getSid();
                    break;
                }
            }
        }
        if (sid == -1) {
            throw new IllegalArgumentException("Supplied File is not Speex");
        }

        // First two packets are required to be info then tags
        info = (SpeexInfo)SpeexPacketFactory.create( p );
        tags = (SpeexTags)SpeexPacketFactory.create( r.getNextPacketWithSid(sid) );

        // Everything else should be audio data
    }

    /**
     * Opens for writing.
     */
    public SpeexFile(OutputStream out) {
        this(out, new SpeexInfo(), new SpeexTags());
    }
    /**
     * Opens for writing, based on the settings
     *  from a pre-read file. The Steam ID (SID) is
     *  automatically allocated for you.
     */
    public SpeexFile(OutputStream out, SpeexInfo info, SpeexTags tags) {
        this(out, -1, info, tags);
    }
    /**
     * Opens for writing, based on the settings
     *  from a pre-read file, with a specific
     *  Steam ID (SID). You should only set the SID
     *  when copying one file to another!
     */
    public SpeexFile(OutputStream out, int sid, SpeexInfo info, SpeexTags tags) {
        ogg = new OggFile(out);

        if(sid > 0) {
            w = ogg.getPacketWriter(sid);
            this.sid = sid;
        } else {
            w = ogg.getPacketWriter();
            this.sid = w.getSid();
        }

        writtenPackets = new ArrayList<SpeexAudioData>();

        this.info = info;
        this.tags = tags;
    }

    public SpeexAudioData getNextAudioPacket() throws IOException {
        OggPacket p = null;
        SpeexPacket sp = null;
        while( (p = r.getNextPacketWithSid(sid)) != null ) {
            sp = SpeexPacketFactory.create(p);
            if(sp instanceof SpeexAudioData) {
                return (SpeexAudioData)sp;
            } else {
                System.err.println("Skipping non audio packet " + sp + " mid audio stream");
            }
        }
        return null;
    }

    /**
     * Skips the audio data to the next packet with a granule
     *  of at least the given granule position.
     * Note that skipping backwards is not currently supported!
     */
    public void skipToGranule(long granulePosition) throws IOException {
        r.skipToGranulePosition(sid, granulePosition);
    }

    /**
     * Returns the Ogg Stream ID
     */
    public int getSid() {
        return sid;
    }

    /**
     * This is a Speex file
     */
    public OggStreamType getType() {
        return OggStreamIdentifier.SPEEX_AUDIO;
    }

    public SpeexInfo getInfo() {
        return info;
    }
    public SpeexTags getTags() {
        return tags;
    }
    /**
     * Speex doesn't have setup headers, so this is always null
     */
    public OggAudioSetupHeader getSetup() {
        return null;
    }

    /**
     * Buffers the given audio ready for writing
     *  out. Data won't be written out yet, you
     *  need to call {@link #close()} to do that,
     *  because we assume you'll still be populating
     *  the Info/Comment/Setup objects
     */
    public void writeAudioData(SpeexAudioData data) {
        writtenPackets.add(data);
    }

    /**
     * In Reading mode, will close the underlying ogg
     *  file and free its resources.
     * In Writing mode, will write out the Info and
     *  Tags objects, and then the audio data.
     */
    public void close() throws IOException {
        if(r != null) {
            r = null;
            ogg.close();
            ogg = null;
        }
        if(w != null) {
            w.bufferPacket(info.write(), true);
            w.bufferPacket(tags.write(), false);

            long lastGranule = 0;
            for(SpeexAudioData vd : writtenPackets) {
                // Update the granule position as we go
                if(vd.getGranulePosition() >= 0 &&
                        lastGranule != vd.getGranulePosition()) {
                    w.flush();
                    lastGranule = vd.getGranulePosition();
                    w.setGranulePosition(lastGranule);
                }

                // Write the data, flushing if needed
                w.bufferPacket(vd.write());
                if(w.getSizePendingFlush() > 16384) {
                    w.flush();
                }
            }

            w.close();
            w = null;
            ogg.close();
            ogg = null;
        }
    }

    /**
     * Returns the underlying Ogg File instance
     * @return
     */
    public OggFile getOggFile() {
        return ogg;
    }
}


text:
<?php

declare(strict_types=1);

namespace Application;

use Application\Auth;
use Bluz\Application\Application;
use Bluz\Auth\AuthException;
use Bluz\Controller\Controller;
use Bluz\Http\Exception\ForbiddenException;
use Bluz\Http\Exception\RedirectException;
use Bluz\Proxy\Auth as AuthProxy;
use Bluz\Proxy\Config;
use Bluz\Proxy\Layout;
use Bluz\Proxy\Logger;
use Bluz\Proxy\Messages;
use Bluz\Proxy\Request;
use Bluz\Proxy\Response;
use Bluz\Proxy\Router;
use Bluz\Proxy\Session;
use Bluz\Proxy\Translator;

/**
 * Bootstrap
 *
 * @category Application
 * @package  Bootstrap
 */
class Bootstrap extends Application
{
    /**
     * {@inheritdoc}
     */
    protected function initTranslator(): void
    {
        $translator = new \Bluz\Translator\Translator();
        $translator->setOptions(Config::get('translator'));

        // supported locales
        // en_US, ru_RU, uk_UA
        $locales = [
            'en' => 'en_US',
            'ru' => 'ru_RU',
            'uk' => 'uk_UA',
        ];

        // try to check locale from cookies
        $locale = Request::getCookie('locale');

        // try to get locale from browser
        if (!$locale) {
            $languages = Request::getAcceptLanguage();
            foreach ($languages as $language => $priority) {
                if (array_key_exists($language, $locales)) {
                    $locale = $language;
                    break;
                }
            }
        }

        // normalize locale
        if (array_key_exists($locale, $locales)) {
            $translator->setLocale($locales[$locale]);
        }

        $translator->init();

        Translator::setInstance($translator);
    }

    /**
     * {@inheritdoc}
     *
     * @param Controller $controller
     *
     * @return void
     * @throws AuthException
     * @throws Exception
     * @throws \Bluz\Db\Exception\DbException
     * @throws \Bluz\Db\Exception\InvalidPrimaryKeyException
     */
    protected function preDispatch($controller): void
    {
        // example of setup default title
        Layout::title('Bluz Skeleton');

        if (!AuthProxy::getIdentity() && $controller->getModule() !== Router::getErrorModule()) {
            if ($token = Request::getCookie('Auth-Token')) {
                // try to login by token from cookies
                try {
                    Auth\Provider\Cookie::authenticate($token);
                } catch (AuthException $e) {
                    $this->getResponse()->setCookie('Auth-Token', '', 1, '/');
                }
            } elseif ($token = Request::getHeader('Auth-Token')) {
                // try to login by token from headers
                Auth\Provider\Token::authenticate($token);
            }
        }
        parent::preDispatch($controller);
    }

    /**
     * Denied access
     *
     * @param ForbiddenException $exception
     *
     * @return \Bluz\Controller\Controller|null
     */
    public function forbidden(ForbiddenException $exception): ?Controller
    {
        // for AJAX and API calls (over JSON)
        $jsonOrApi = Request::isXmlHttpRequest()
            || (Request::checkAccept([Request::TYPE_HTML, Request::TYPE_JSON]) === Request::TYPE_JSON);

        // for guest, for requests
        if (!$jsonOrApi && !AuthProxy::getIdentity()) {
            // save URL to session and redirect make sense if presentation is null
            Session::set('rollback', Request::getUri()->__toString());
            // add error notice
            Messages::addError('You don\'t have permissions, please sign in');
            // redirect to Sign In page
            $redirect = new RedirectException();
            $redirect->setUrl(Router::getUrl('users', 'signin'));
            return $this->redirect($redirect);
        }
        return $this->error($exception);
    }

    /**
     * Render with debug headers
     *
     * @return void
     */
    public function render(): void
    {
        Logger::info('app:render');
        Logger::info('app:files:' . count(get_included_files()));
        parent::render();
    }

    /**
     * Finish it
     *
     * @return void
     */
    public function end(): void
    {
        if ($errors = Logger::get('error')) {
            $this->sendErrors($errors);
        }
    }

    /**
     * sendErrorBody
     *
     * @param array $errors
     *
     * @return void
     */
    protected function sendErrors($errors): void
    {
        foreach ($errors as $message) {
            errorLog(new \ErrorException($message, 0, E_USER_ERROR));
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<com.zhy.autolayout.AutoLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical">

    <com.zhy.autolayout.AutoLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="778px"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@drawable/back_dialog"
        android:gravity="center_horizontal"
        android:minWidth="778px"
        android:orientation="vertical"
        android:paddingTop="51px">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="温馨提示"
            android:textColor="@android:color/black"
            android:textSize="49px" />

        <TextView
            android:id="@+id/content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="51px"
            android:layout_marginTop="20px"
            android:paddingLeft="81px"
            android:paddingRight="81px"
            android:text="确定采纳夏天的风的回答作为最佳答案?"
            android:textColor="@android:color/black"
            android:textSize="37px" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1px"
            android:background="@color/color_dfdfdf" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="130px"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/cancle"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:text="取消"
                android:textColor="#007aff"
                android:textSize="49px" />

            <View
                android:layout_width="1px"
                android:layout_height="match_parent"
                android:background="@color/color_dfdfdf" />

            <TextView
                android:id="@+id/sure"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:text="确定"
                android:textColor="#007aff"
                android:textSize="49px" />

        </LinearLayout>
    </com.zhy.autolayout.AutoLinearLayout>
</com.zhy.autolayout.AutoLinearLayout>


text:
/**
 *
 */
package at.free23.billing.repository;

import org.springframework.data.repository.PagingAndSortingRepository;

import at.free23.billing.model.Position;
import at.free23.billing.model.PositionId;

/**
 * @author michael.vlasaty
 *
 */
public interface PositionRepository extends PagingAndSortingRepository<Position, PositionId> {
	// public Position findByLineItem_Uuid(String uuid);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<fileset-config file-format-version="1.2.0" simple-config="true" sync-formatter="false">
    <local-check-config name="ko" location="target/checkstyle-checker.xml" type="project" description="">
        <additional-data name="protect-config-file" value="false"/>
    </local-check-config>
    <fileset name="all" enabled="true" check-config-name="ko" local="true">
        <file-match-pattern match-pattern="^src[/\\]." include-pattern="true"/>
    </fileset>
    <filter name="FilesFromPackage" enabled="true">
        <filter-data value="src/com/google"/>
    </filter>
    <filter name="NonSrcDirs" enabled="true"/>
</fileset-config>