text:
title: LookUp
sidebar: flexberry-winforms_sidebar
keywords:  Flexberry Winforms, Controls, LookUp
summary: Внешний вид, множественный выбор, переопределение методов, возможные проблемы использования и пути их решения
toc: true
permalink: ru/fw_lookup.html
lang: ru
---

`LookUp` (действие) - выбор мастерового объекта (проставление ссылки на мастеровой объект).

`LookUp` (контрол) - контрол для выбора мастерового объекта, возвращающий ссылку на него.

## Возврат нескольких объектов

Существует возможность получать все объекты, выбранные на списке по Lookup.

Это используется в [редакторе ограничений](fw_limit-editor-advanced-view.html), где для вида ограничения `Среди значений` возвращаются все выбранные на списке по лукапу объекты.

Все выбранные объекты можно получить, обратившись к `DynamicProperties` стандартно возвращаемого объекта. А именно:

```csharp
o.DynamicProperties["retFromObjectListView"] as List<DataObject>
```

Полученный список не будет содержать первого выбранного объекта `o`.

__Замечание:__ на формах, имеющих несколько [ObjectListView](fw_objectlistview.html) или `ObjectHierarchicalView`, нужно убрать перегрузку `prv_EditData` и подписку на `OLV.ReturnData`.

## Переопределить метода Edited

На примере показано как можно переопределить метод __Edited__, чтобы использовать полученные  от LookUp данные.

```csharp
public override void Edited(ICSSoft.STORMNET.DataObject dataobject, string contpath, string propertyname)
    {
        base.Edited (dataobject, contpath, propertyname);

        if (propertyname == "Сотрудник")
        {
            Объекты.ДвижениеГруппыОтказнМатер Э = (Объекты.ДвижениеГруппыОтказнМатер)EditManager.DataObject;
            Объекты.Сотрудник р = (Объекты.Сотрудник)Э.Сотрудник;

            Э.ФИОСотрудника = Э.Сотрудник.ОпрПолноеФИО();
            if (р.Должность != null)
            {
                DataServiceProvider.DataService.LoadObject(р.Должность);
                Э.Должность = р.Должность.Наименование;
            }
            else Э.Должность = "";

            EditManager.Change("ФИОСотрудника");
            EditManager.Change("Должность");
        }

        if (propertyname == "Сотрудник")
        {
            Объекты.ДвижениеГруппыОтказнМатер Э = (Объекты.ДвижениеГруппыОтказнМатер)EditManager.DataObject;
            Объекты.ОтвЗаРешение р = (Объекты.ОтвЗаРешение)Э.УКогоНаходится;

            if (р != null)
            {
                extTextControl1.Text = р.Наименование;
            }
            else extTextControl1.Text = "";
        }
    }
```

## Кнопка отображения списка

Для того чтобы добавить кнопку отображения мастерового списка к Lookup, нужно:

* Создать плоский контрол __button__
* Добавить иконку из __ImageList__.
* На нажатие кнопки добавить __вызов__ следующей функции:

```csharp
public void ПоказатьСписок()
    {
        SQLWhereLanguageDef langdef = SQLWhereLanguageDef.LanguageDef;
        Function lf = null;

        // формируем lf
        LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Лицо), "ЛицоL");
        lcs.LimitFunction = lf;

        ICSSoft.STORMNET.DataObject[] objs = DataServiceProvider.DataService.LoadObjects(lcs);

        if (objs.Length == 0)
        {
            Tools.ShowInformation("Не найдено ни одного лица с заданными параметрами");
            return;
        }
        else // хоть кого-то нашли
        {
            string contpath = "STORMCASE.STORMNET.Generator.SerializeNewEditForm/EditPanel(Panel)/TabControl(Tab" + "Control)/panel(TabPage)/panel(GroupBox)/ctrlЛицо(LookUp)";
            base.OnEdit("Лицо", EditManager.DataObject, contpath, lf);
        }
    }
```

## Изменение внешнего вида

Существует два способа изменить изображения на кнопках LookUp.

1.В случае если требуется изменить изображения в рамках всего приложения, необходимо инициализировать _статический ImageList_ при запуске приложения. В этом списке должны присутствовать изображения с именами "LookUp", "Clear" и "Edit".

__Пример:__

```csharp
LookUp.UserImageList.Images.Add("LookUp", Properties.Resources.LookUpImage);
LookUp.UserImageList.Images.Add("Clear", Properties.Resources.ClearImage);
LookUp.UserImageList.Images.Add("Edit", Properties.Resources.EditImage);
```

2.Для конкретного экземпляра `LookUp` с помощью свойства `UserImageList` можно назначить _пользовательский ImageList_, в котором также должны быть изображения с именами "LookUp", "Clear" и "Edit".

### Размер и границы кнопок

Размер кнопок задается с помощью свойства `ButtonSize`, при изменении данного свойства должно выполнится перевычисление размера всего контрола.

За отображение границ кнопок отвечает свойство `ButtonBorder`.

## Запрет изменения в BeforeChangeProperty

Уставновка признака Cancel в методе BeforeChangeProperty при изменении мастерового поля не блокирует Lookup и последующее изменение свойства.

## Смена обработчика look_LookUpEvent

Для того чтобы заменить обработчик `look_LookUpEvent` на свой, нужно:

* создать контейнер-runner,
* подписаться на события сохранения (отказа от сохранения),
* задать свои действия при наступлении событий.

```csharp
private void look_LookUpEvent1(object sender, System.EventArgs e)
{
    Посетитель oПосетитель = (Посетитель)this.EditManager.DataObject;

    Function lf = FunctionBuilder.BuildTrue();

    //создадим контейнер-раннер
    ICSSoft.АдресноеБюро.ЛичностьL FormЛичностьL = (ICSSoft.АдресноеБюро.ЛичностьL)      ICSSoft.STORMNET.UI.ContRunner.RunForm(typeof(ICSSoft.АдресноеБюро.ЛичностьL));
    FormЛичностьL.Edit(oПосетитель, "Личность", "Личность",lf);

    //подпишемся на события
    FormЛичностьL.SaveEvent+=new ICSSoft.STORMNET.UI.SaveEventArgsHandler(FormЛичностьL_SaveEvent);FormЛичностьL.CancelEvent+=new ICSSoft.STORMNET.UI.CancelEventArgsHandler(FormЛичностьL_CancelEvent);
}

private void FormЛичностьL_SaveEvent(object sender, ICSSoft.STORMNET.UI.SaveEventArgs e)
{
    //наши действия
}

private void FormЛичностьL_CancelEvent(object sender, ICSSoft.STORMNET.UI.CancelEventArgs e)
{
    //наши действия
}
```

## Возможные проблемы использования

### Стандартно сгенерированный lookup

#### На форме

Если не срабатывает обработчик события `look_LookUpEvent` (в зависимой форме).

* Правильно указать путь на форме до `Lookup` в методе `prv_TuneLookupInformations` (в зависимой форме).
* Указать форму вызова в методе `GetEditor` независимой формы.
* На кнопку `LookUp` (например, для Гражданства это будет ctrlГражданство) навесить обработчик __события__ LookUp.

```csharp
this.ctrlГражданство.LookUpEvent += look_LookUpEvent
```

#### В GroupEdit

* Привязка [GropEdit](fw_group-edit.html) к EditManager формы
* Наличие обработчика `this.gr_SetupEditorEventHandler` типа `OnSetupEditorEventHandler` для события `SetupEditor`
* Упоминание `GroupEdit` в методе `prv_TuneLookupInformations` (в зависимой форме), _например_:

```csharp
m_arrGroupEditInformations.Add(
               new ICSSoft.STORMNET.UI.GroupEditInformation(this.ПредметыИзъятия,
               "ИтогиИзъятия.ПредметыИзъятия",
               "STORMCASE.STORMNET.Generator.SerializeNewEditForm/EditPanel(Panel)/TabControl(TabControl)/panel(TabPage)/ПредметыИзъятия(GroupEditBase)"));
```

### Нестандартные случаи использования Lookup

#### Не поднимается форма по Lookup

Нужно учесть особенности контрола:

* Если не существует свойство, имя которого передаётся в качестве `PropertyName`, то лучше указать пустую строку, иначе метод `Save` не будет вызываться.
* Нехранимые объекты, поднимаемые по Lookup, scriptizer обрабатываются нестандартно и событие необходимо прописывать вручную.

Также следует проверить:

* Хранимый ли объект, с которого поднимается LookUp.
* Какие формы поднимаются и с какой формы.
* Поднимается ли с формы по кнопке LookUp. Если да, то поднимается ли с формы LookUp. Если да, то _неправильно указываются параметры_. Если не поднимается ни по кнопке, ни из метода, то есть ошибка, скорее всего, носит системный характер.

#### Не выдаётся сообщение о сохранении объекта при закрытии формы

Необходимо проверить:

* Объект имеет статус _Altered_
* Объект изменил свои свойства с момента поднятия формы по Lookup. При поднятии по Lookup форма-инициатор в методе `PrepareDataObjectForEdit` создаёт копию данных, и при закрытии сравнивается эта копия с текущим на момент закрытия объектом. Сохранение произойдёт только в случае наличия разницы между объектом и его копией.
* Форма корректно поднята по Lookup:
  * передаётся объект формы-инициатора LookUp, а не тот, который надо редактировать
  * указано существующее свойство или пустая строка

## Изменение названия списка для Lookup

Изменить название списка для Lookup, находящегося на разных формах редактирования можно задать условия на форме редактирования, а на списковой форме добавить обработчик данного события. Например, на  форме редактирования при открытии Lookup в объект данных добавить необходимое название в `DynamicProperties`, а на списковой форме его вычитывать.

## Дополнительно

* [Лукап с предиктивным вводом](fw_extended-lookup.html)
* [Вызов независимого мастера](fw_lookup-another-object.html)


text:
\hypertarget{http__header__field__dispatcher__apply_8cpp}{\section{http\-\_\-header\-\_\-field\-\_\-dispatcher\-\_\-apply.\-cpp File Reference}
\label{http__header__field__dispatcher__apply_8cpp}\index{http\-\_\-header\-\_\-field\-\_\-dispatcher\-\_\-apply.\-cpp@{http\-\_\-header\-\_\-field\-\_\-dispatcher\-\_\-apply.\-cpp}}
}

applies the implementation of field to H\-T\-T\-P Header.

{\ttfamily \#include \char`\"{}precompiled.\-h\char`\"{}}\\*
{\ttfamily \#include \char`\"{}hryky/http/http\-\_\-header\-\_\-field\-\_\-dispatcher\-\_\-apply.\-h\char`\"{}}\\*
{\ttfamily \#include \char`\"{}hryky/reduction.\-h\char`\"{}}\\*
\subsection*{Namespaces}
\begin{DoxyCompactItemize}
\item
namespace \hyperlink{namespacehryky}{hryky}
\begin{DoxyCompactList}\small\item\em the root of all namespaces in hryky-\/codebase. \end{DoxyCompactList}\item
namespace \hyperlink{namespacehryky_1_1http}{hryky\-::http}
\begin{DoxyCompactList}\small\item\em modules to manage H\-T\-T\-P. \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Detailed Description}
applies the implementation of field to H\-T\-T\-P Header. \begin{DoxyAuthor}{Author}
H\-R\-Y\-K\-Y
\end{DoxyAuthor}
\begin{DoxyVersion}{Version}

\end{DoxyVersion}
\begin{DoxyParagraph}{Id\-:}
\hyperlink{http__header__field__dispatcher__apply_8cpp}{http\-\_\-header\-\_\-field\-\_\-dispatcher\-\_\-apply.\-cpp} 150 2013-\/02-\/10 10\-:08\-:03\-Z \href{mailto:hryky.private@gmail.com}{\tt hryky.\-private@gmail.\-com}
\end{DoxyParagraph}

redpajama_set_name: RedPajamaGithub


text:
package me.superkoh.kframework.lib.payment.wechat.sdk.common.report;

import me.superkoh.kframework.lib.payment.wechat.sdk.common.report.protocol.ReportReqData;
import me.superkoh.kframework.lib.payment.wechat.sdk.common.report.service.ReportService;

/**
 * User: rizenguo
 * Date: 2014/12/3
 * Time: 11:42
 */
public class Reporter {

    private ReportRunable r;
    private Thread t;
    private ReportService rs;

    /**
     * 请求统计上报API
     * @param reportReqData 这个数据对象里面包含了API要求提交的各种数据字段
     */
    public Reporter(ReportReqData reportReqData){
        rs = new ReportService(reportReqData);
    }

    public void run(){
        r = new ReportRunable(rs);
        t = new Thread(r);
        t.setDaemon(true);  //后台线程
        t.start();
    }
}


text:
body .b-form-radio__colorpicker .b-form-radio__button_color_00fd00 .b-form-radio__inner
{
    background: #00fd00;
}


text:
import * as spawn from 'cross-spawn';
import * as fs from 'fs';
import * as path from 'path';
import * as url from 'url';

// i would use home-path here but im not sure if the docker cli config file even
// exists in the user home dir in windows.
const defaultPath = path.join(
    process.env.HOME || process.env.USERPROFILE || '', '.docker',
    'config.json');

export class DockerCredentialHelpers {
  private dockerConfig: DockerCredsConfig = {};

  constructor(customPathOrConfig?: string|DockerCredsConfig) {
    if (typeof customPathOrConfig === 'string' || !customPathOrConfig) {
      this.readDockerConfig(customPathOrConfig);
    } else {
      this.dockerConfig = customPathOrConfig || {};
    }
  }

  auth(registry: string): Promise<DockerAuthResult> {
    const host = url.parse(registry).host || registry;
    // console.log('authing to registry ' + registry, ' with host ', host);
    return new Promise((resolve, reject) => {
      if (!this.dockerConfig.credHelpers ||
          !this.dockerConfig.credHelpers[host]) {
        reject(new Error('no auth handler for ' + host));
      }
      const helper =
          'docker-credential-' + this.dockerConfig.credHelpers![host];

      let endCount = 0;
      const bufs: Buffer[] = [];
      const ebufs: Buffer[] = [];

      let maybeEnd = (err?: Error) => {
        if (err) {
          maybeEnd = () => {};
          return reject(err);
        }

        endCount++;
        if (endCount === 2) {
          resolve((json(Buffer.concat(bufs)) || {}) as DockerAuthResult);
        }
      };
      const proc = spawn(helper, ['get']);
      proc.on('exit', (code) => {
        if (code) {
          return reject(new Error(
              'exit code ' + code + ' from docker credential helper ' + helper +
              '\nstderr: ' + Buffer.concat(ebufs) + ''));
        }
        maybeEnd();
      });

      proc.stdout.on('data', (b) => bufs.push(b))
          .on('end', maybeEnd)
          .on('error', maybeEnd);

      proc.stderr.on('data', (b) => ebufs.push(b)).on('error', maybeEnd);
      proc.stdin.end(host);
    });
  }

  readDockerConfig(customPath?: string) {
    try {
      this.dockerConfig =
          (JSON.parse(
               fs.readFileSync(
                   customPath ||
                   (process.env.DOCKER_CONFIG ?
                        path.join(process.env.DOCKER_CONFIG, 'config.json') :
                        false) ||
                   defaultPath) +
               '') ||
           {}) as DockerCredsConfig;
    } catch (e) {
    }
    return this.dockerConfig;
  }

  getDockerConfig() {
    return this.dockerConfig;
  }

  setDockerConfig(config: DockerCredsConfig) {
    this.dockerConfig = config || {};
  }
}

function json(s: string|Buffer) {
  try {
    return JSON.parse(s + '');
  } catch (e) {
  }
}

export type DockerAuthResult = {
  Username?: string,
  Secret?: string,
  token?: string
};

export type DockerCredsConfig = {
  credHelpers?: {[registryUrl: string]: string}
};


text:
var _excluded = ["url"];

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

import { createRequestConfig } from 'contentful-sdk-core';
import entities from './entities';

/**
 * @private
 */
export default function createClientApi(makeRequest) {
  var _entities$space = entities.space,
      wrapSpace = _entities$space.wrapSpace,
      wrapSpaceCollection = _entities$space.wrapSpaceCollection;
  var wrapUser = entities.user.wrapUser;
  var _entities$personalAcc = entities.personalAccessToken,
      wrapPersonalAccessToken = _entities$personalAcc.wrapPersonalAccessToken,
      wrapPersonalAccessTokenCollection = _entities$personalAcc.wrapPersonalAccessTokenCollection;
  var _entities$organizatio = entities.organization,
      wrapOrganization = _entities$organizatio.wrapOrganization,
      wrapOrganizationCollection = _entities$organizatio.wrapOrganizationCollection;
  var wrapUsageCollection = entities.usage.wrapUsageCollection;
  return {
    /**
     * Gets all spaces
     * @return Promise for a collection of Spaces
     * ```javascript
     * const contentful = require('contentful-management')
     *
     * const client = contentful.createClient({
     *   accessToken: '<content_management_api_key>'
     * })
     *
     * client.getSpaces()
     * .then((response) => console.log(response.items))
     * .catch(console.error)
     * ```
     */
    getSpaces: function getSpaces() {
      var query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return makeRequest({
        entityType: 'Space',
        action: 'getMany',
        params: {
          query: createRequestConfig({
            query: query
          }).params
        }
      }).then(function (data) {
        return wrapSpaceCollection(makeRequest, data);
      });
    },

    /**
     * Gets a space
     * @param spaceId - Space ID
     * @return Promise for a Space
     * ```javascript
     * const contentful = require('contentful-management')
     *
     * const client = contentful.createClient({
     *   accessToken: '<content_management_api_key>'
     * })
     *
     * client.getSpace('<space_id>')
     * .then((space) => console.log(space))
     * .catch(console.error)
     * ```
     */
    getSpace: function getSpace(spaceId) {
      return makeRequest({
        entityType: 'Space',
        action: 'get',
        params: {
          spaceId: spaceId
        }
      }).then(function (data) {
        return wrapSpace(makeRequest, data);
      });
    },

    /**
     * Creates a space
     * @param spaceData - Object representation of the Space to be created
     * @param organizationId - Organization ID, if the associated token can manage more than one organization.
     * @return Promise for the newly created Space
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const client = contentful.createClient({
     *   accessToken: '<content_management_api_key>'
     * })
     *
     * client.createSpace({
     *   name: 'Name of new space'
     * })
     * .then((space) => console.log(space))
     * .catch(console.error)
     * ```
     */
    createSpace: function createSpace(spaceData, organizationId) {
      return makeRequest({
        entityType: 'Space',
        action: 'create',
        params: {
          organizationId: organizationId
        },
        payload: spaceData
      }).then(function (data) {
        return wrapSpace(makeRequest, data);
      });
    },

    /**
     * Gets an organization
     * @param  id - Organization ID
     * @return Promise for a Organization
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const client = contentful.createClient({
     *   accessToken: '<content_management_api_key>'
     * })
     *
     * client.getOrganization('<org_id>')
     * .then((org) => console.log(org))
     * .catch(console.error)
     * ```
     */
    getOrganization: function getOrganization(id) {
      return makeRequest({
        entityType: 'Organization',
        action: 'get',
        params: {
          organizationId: id
        }
      }).then(function (data) {
        return wrapOrganization(makeRequest, data);
      });
    },

    /**
     * Gets a collection of Organizations
     * @return Promise for a collection of Organizations
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const client = contentful.createClient({
     *   accessToken: '<content_management_api_key>'
     * })
     *
     * client.getOrganizations()
     * .then(result => console.log(result.items))
     * .catch(console.error)
     * ```
     */
    getOrganizations: function getOrganizations() {
      var query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return makeRequest({
        entityType: 'Organization',
        action: 'getMany',
        params: {
          query: createRequestConfig({
            query: query
          }).params
        }
      }).then(function (data) {
        return wrapOrganizationCollection(makeRequest, data);
      });
    },

    /**
     * Gets the authenticated user
     * @return Promise for a User
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const client = contentful.createClient({
     *   accessToken: '<content_management_api_key>'
     * })
     *
     * client.getCurrentUser()
     * .then(user => console.log(user.firstName))
     * .catch(console.error)
     * ```
     */
    getCurrentUser: function getCurrentUser(params) {
      return makeRequest({
        entityType: 'User',
        action: 'getCurrent',
        params: params
      }).then(function (data) {
        return wrapUser(makeRequest, data);
      });
    },

    /**
     * Creates a personal access token
     * @param data - personal access token config
     * @return Promise for a Token
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const client = contentful.createClient({
     *   accessToken: '<content_management_api_key>'
     * })
     *
     * client.createPersonalAccessToken(
     *  {
     *    "name": "My Token",
     *    "scope": [
     *      "content_management_manage"
     *    ]
     *  }
     * )
     * .then(personalAccessToken => console.log(personalAccessToken.token))
     * .catch(console.error)
     * ```
     */
    createPersonalAccessToken: function createPersonalAccessToken(data) {
      return makeRequest({
        entityType: 'PersonalAccessToken',
        action: 'create',
        params: {},
        payload: data
      }).then(function (response) {
        return wrapPersonalAccessToken(makeRequest, response);
      });
    },

    /**
     * Gets a personal access token
     * @param data - personal access token config
     * @return Promise for a Token
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const client = contentful.createClient({
     *   accessToken: '<content_management_api_key>'
     * })
     *
     * client.getPersonalAccessToken(tokenId)
     * .then(token => console.log(token.token))
     * .catch(console.error)
     * ```
     */
    getPersonalAccessToken: function getPersonalAccessToken(tokenId) {
      return makeRequest({
        entityType: 'PersonalAccessToken',
        action: 'get',
        params: {
          tokenId: tokenId
        }
      }).then(function (data) {
        return wrapPersonalAccessToken(makeRequest, data);
      });
    },

    /**
     * Gets all personal access tokens
     * @return Promise for a Token
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const client = contentful.createClient({
     *   accessToken: '<content_management_api_key>'
     * })
     *
     * client.getPersonalAccessTokens()
     * .then(response => console.log(reponse.items))
     * .catch(console.error)
     * ```
     */
    getPersonalAccessTokens: function getPersonalAccessTokens() {
      return makeRequest({
        entityType: 'PersonalAccessToken',
        action: 'getMany',
        params: {}
      }).then(function (data) {
        return wrapPersonalAccessTokenCollection(makeRequest, data);
      });
    },

    /**
     * Get organization usage grouped by {@link UsageMetricEnum metric}
     *
     * @param organizationId - Id of an organization
     * @param query - Query parameters
     * @return Promise of a collection of usages
     * @example ```javascript
     *
     * const contentful = require('contentful-management')
     *
     * const client = contentful.createClient({
     *   accessToken: '<content_management_api_key>'
     * })
     *
     * client.getOrganizationUsage('<organizationId>', {
     *    'metric[in]': 'cma,gql',
     *    'dateRange.startAt': '2019-10-22',
     *    'dateRange.endAt': '2019-11-10'
     *    }
     * })
     * .then(result => console.log(result.items))
     * .catch(console.error)
     * ```
     */
    getOrganizationUsage: function getOrganizationUsage(organizationId) {
      var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      return makeRequest({
        entityType: 'Usage',
        action: 'getManyForOrganization',
        params: {
          organizationId: organizationId,
          query: query
        }
      }).then(function (data) {
        return wrapUsageCollection(makeRequest, data);
      });
    },

    /**
     * Get organization usage grouped by space and metric
     *
     * @param organizationId - Id of an organization
     * @param query - Query parameters
     * @return Promise of a collection of usages
     * ```javascript
     * const contentful = require('contentful-management')
     *
     * const client = contentful.createClient({
     *   accessToken: '<content_management_api_key>'
     * })
     *
     * client.getSpaceUsage('<organizationId>', {
     *    skip: 0,
     *    limit: 10,
     *    'metric[in]': 'cda,cpa,gql',
     *    'dateRange.startAt': '2019-10-22',
     *    'dateRange.endAt': '2020-11-30'
     *    }
     * })
     * .then(result => console.log(result.items))
     * .catch(console.error)
     * ```
     */
    getSpaceUsage: function getSpaceUsage(organizationId) {
      var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      return makeRequest({
        entityType: 'Usage',
        action: 'getManyForSpace',
        params: {
          organizationId: organizationId,
          query: query
        }
      }).then(function (data) {
        return wrapUsageCollection(makeRequest, data);
      });
    },

    /**
     * Make a custom request to the Contentful management API's /spaces endpoint
     * @param opts - axios request options (https://github.com/mzabriskie/axios)
     * @return Promise for the response data
     * ```javascript
     * const contentful = require('contentful-management')
     *
     * const client = contentful.createClient({
     *   accessToken: '<content_management_api_key>'
     * })
     *
     * client.rawRequest({
     *   method: 'GET',
     *   url: '/custom/path'
     * })
     * .then((responseData) => console.log(responseData))
     * .catch(console.error)
     * ```
     */
    rawRequest: function rawRequest(_ref) {
      var url = _ref.url,
          config = _objectWithoutProperties(_ref, _excluded);

      return makeRequest({
        entityType: 'Http',
        action: 'request',
        params: {
          url: url,
          config: config
        }
      });
    }
  };
}


text:
package io.aeron.agent;

import io.aeron.driver.EventLog;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.scaffold.TypeValidation;
import net.bytebuddy.utility.JavaModule;
import org.agrona.concurrent.AgentRunner;
import org.agrona.concurrent.SleepingIdleStrategy;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.util.concurrent.TimeUnit;

import static net.bytebuddy.asm.Advice.to;
import static net.bytebuddy.matcher.ElementMatchers.*;

public class EventLogAgent
{
    private static final long SLEEP_PERIOD_NS = TimeUnit.MILLISECONDS.toNanos(1);
    private static final EventLogReaderAgent EVENT_LOG_READER_AGENT = new EventLogReaderAgent();

    private static final AgentRunner EVENT_LOG_READER_AGENT_RUNNER =
        new AgentRunner(new SleepingIdleStrategy(SLEEP_PERIOD_NS), EventLogAgent::errorHandler, null, EVENT_LOG_READER_AGENT);

    private static final Thread EVENT_LOG_READER_THREAD = new Thread(EVENT_LOG_READER_AGENT_RUNNER);

    private static volatile ClassFileTransformer logTransformer;
    private static volatile Instrumentation instrumentation;

    private static final AgentBuilder.Listener LISTENER = new AgentBuilder.Listener()
    {
        public void onTransformation(
            final TypeDescription typeDescription,
            final ClassLoader classLoader,
            final JavaModule module,
            final DynamicType dynamicType)
        {
            System.out.format("TRANSFORM %s%n", typeDescription.getName());
        }

        public void onIgnored(final TypeDescription typeDescription, final ClassLoader classLoader, final JavaModule module)
        {
        }

        public void onError(
            final String typeName, final ClassLoader classLoader, final JavaModule module, final Throwable throwable)
        {
            System.out.format("ERROR %s%n", typeName);
            throwable.printStackTrace(System.out);
        }

        public void onComplete(final String typeName, final ClassLoader classLoader, final JavaModule module)
        {
        }
    };

    private static void errorHandler(final Throwable throwable)
    {
    }

    private static void agent(final boolean redefine, final Instrumentation instrumentation)
    {
        if (EventConfiguration.ENABLED_EVENT_CODES != 0)
        {
            /*
             * Intercept based on enabled events:
             *  SenderProxy
             *  ReceiverProxy
             *  ClientProxy
             *  DriverConductor (onClientCommand)
             *  SendChannelEndpoint
             *  ReceiveChannelEndpoint
             */

            EventLogAgent.instrumentation = instrumentation;

            logTransformer = new AgentBuilder.Default(new ByteBuddy().with(TypeValidation.DISABLED))
                .with(LISTENER)
                .disableClassFormatChanges()
                .with(redefine ? AgentBuilder.RedefinitionStrategy.RETRANSFORMATION : AgentBuilder.RedefinitionStrategy.DISABLED)
                .type(nameEndsWith("DriverConductor"))
                .transform((builder, typeDescription, classLoader) ->
                    builder
                        .visit(to(CmdInterceptor.class).on(named("onClientCommand")))
                        .visit(to(CleanupInterceptor.DriverConductorInterceptor.CleanupImage.class)
                            .on(named("cleanupImage")))
                        .visit(to(CleanupInterceptor.DriverConductorInterceptor.CleanupPublication.class)
                            .on(named("cleanupPublication")))
                        .visit(to(CleanupInterceptor.DriverConductorInterceptor.CleanupSubscriptionLink.class)
                            .on(named("cleanupSubscriptionLink"))))
                .type(nameEndsWith("ClientProxy"))
                .transform((builder, typeDescription, classLoader) ->
                    builder.visit(to(CmdInterceptor.class).on(named("transmit"))))
                .type(nameEndsWith("SenderProxy"))
                .transform((builder, typeDescription, classLoader) ->
                    builder
                        .visit(to(ChannelEndpointInterceptor.SenderProxyInterceptor.RegisterSendChannelEndpoint.class)
                            .on(named("registerSendChannelEndpoint")))
                        .visit(to(ChannelEndpointInterceptor.SenderProxyInterceptor.CloseSendChannelEndpoint.class)
                            .on(named("closeSendChannelEndpoint"))))
                .type(nameEndsWith("ReceiverProxy"))
                .transform((builder, typeDescription, classLoader) ->
                    builder
                        .visit(to(ChannelEndpointInterceptor.ReceiverProxyInterceptor.RegisterReceiveChannelEndpoint.class)
                            .on(named("registerReceiveChannelEndpoint")))
                        .visit(to(ChannelEndpointInterceptor.ReceiverProxyInterceptor.CloseReceiveChannelEndpoint.class)
                            .on(named("closeReceiveChannelEndpoint"))))
                .type(inheritsAnnotation(EventLog.class))
                .transform((builder, typeDescription, classLoader) ->
                    builder
                        .visit(to(ChannelEndpointInterceptor.SendChannelEndpointInterceptor.Presend.class)
                            .on(named("presend")))
                        .visit(to(ChannelEndpointInterceptor.ReceiveChannelEndpointInterceptor.SendTo.class)
                            .on(named("sendTo")))
                        .visit(to(ChannelEndpointInterceptor.ReceiveChannelEndpointInterceptor.Dispatch.class)
                            .on(named("dispatch"))))
                .installOn(instrumentation);

            EVENT_LOG_READER_THREAD.setName("event log reader");
            EVENT_LOG_READER_THREAD.setDaemon(true);
            EVENT_LOG_READER_THREAD.start();
        }
    }

    public static void premain(final String agentArgs, final Instrumentation instrumentation)
    {
        agent(false, instrumentation);
    }

    public static void agentmain(final String agentArgs, final Instrumentation instrumentation)
    {
        agent(true, instrumentation);
    }

    public static void removeTransformer()
    {
        if (logTransformer != null)
        {
            instrumentation.removeTransformer(logTransformer);

            instrumentation.removeTransformer(new AgentBuilder.Default()
                .type(nameEndsWith("DriverConductor")
                    .or(nameEndsWith("ClientProxy"))
                    .or(nameEndsWith("SenderProxy"))
                    .or(nameEndsWith("ReceiverProxy"))
                    .or(inheritsAnnotation(EventLog.class)))
                .transform(AgentBuilder.Transformer.NoOp.INSTANCE)
                .installOn(instrumentation));
        }
    }
}


text:
def _strip_unsafe_kubernetes_special_chars(string: str) -> str:
    """
    Kubernetes only supports lowercase alphanumeric characters, "-" and "." in
    the pod name.
    However, there are special rules about how "-" and "." can be used so let's
    only keep
    alphanumeric chars  see here for detail:
    https://kubernetes.io/docs/concepts/overview/working-with-objects/names/

    :param string: The requested Pod name
    :return: Pod name stripped of any unsafe characters
    """
    return ''.join(ch.lower() for ch in list(string) if ch.isalnum())

def create_pod_id(dag_id: str, task_id: str) -> str:
    """
    Generates the kubernetes safe pod_id. Note that this is
    NOT the full ID that will be launched to k8s. We will add a uuid
    to ensure uniqueness.

    :param dag_id: DAG ID
    :param task_id: Task ID
    :return: The non-unique pod_id for this task/DAG pairing
    """
    safe_dag_id = _strip_unsafe_kubernetes_special_chars(dag_id)
    safe_task_id = _strip_unsafe_kubernetes_special_chars(task_id)
    return safe_dag_id + safe_task_id


text:
package io.cucumber.messages;

import com.fasterxml.jackson.annotation.JsonCreator.Mode;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.cfg.ConstructorDetector;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

final class Jackson {
    public static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder()
            .addModule(new Jdk8Module())
            .addModule(new ParameterNamesModule(Mode.PROPERTIES))
            .serializationInclusion(Include.NON_ABSENT)
            .constructorDetector(ConstructorDetector.USE_PROPERTIES_BASED)
            .enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING)
            .enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING)
            .enable(DeserializationFeature.USE_LONG_FOR_INTS)
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET)
            .build();

    private Jackson() {
    }
}


text:
package org.coderswithoutborders.deglancer.bus.events;

/**
 * Created by Renier on 2016/05/06.
 */
public class DebugStageEvent {

}


text:
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_CPU_RUNTIME_FFT_IMPL_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_CPU_RUNTIME_FFT_IMPL_H_

#include <array>

#include "third_party/eigen3/Eigen/Core"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/framework/numeric_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/platform/types.h"

// 'tensorflow' namespace is used so that int64 and other types don't require
// qualification.
namespace tensorflow {
namespace xla {

namespace internal {

// Computes either a forward or reverse complex-to-complex FFT.
template <bool Forward, int FFTRank, typename EigenDevice>
void EigenFftC2C(const EigenDevice& device, complex64* out, complex64* operand,
                 int64 input_batch, int64 fft_length0, int64 fft_length1,
                 int64 fft_length2) {
  // Create the axes (which are always trailing).
  const auto axes = Eigen::ArrayXi::LinSpaced(FFTRank, 1, FFTRank);
  constexpr auto direction = Forward ? Eigen::FFT_FORWARD : Eigen::FFT_REVERSE;

  const std::array<int64, 3> fft_shape = {
      {fft_length0, fft_length1, fft_length2}};

  Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> dims;
  dims[0] = input_batch;
  for (int i = 0; i < FFTRank; i++) {
    dims[i + 1] = fft_shape[i];
  }
  const Eigen::TensorMap<Eigen::Tensor<complex64, FFTRank + 1, Eigen::RowMajor>,
                         Eigen::Aligned>
      input(operand, dims);
  Eigen::TensorMap<Eigen::Tensor<complex64, FFTRank + 1, Eigen::RowMajor>,
                   Eigen::Aligned>
      output(out, dims);
  output.device(device) = input.template fft<Eigen::BothParts, direction>(axes);
}

// Computes a forward real->complex FFT, slicing out redundant negative
// frequencies from the innermost dimension.
template <int FFTRank, typename EigenDevice>
void EigenFftR2C(const EigenDevice& device, complex64* out, float* operand,
                 int64 input_batch, int64 fft_length0, int64 fft_length1,
                 int64 fft_length2) {
  const std::array<int64, 3> fft_shape = {
      {fft_length0, fft_length1, fft_length2}};

  Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> in_dims;
  in_dims[0] = input_batch;
  Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> out_dims;
  out_dims[0] = input_batch;
  TensorShape temp_shape{input_batch};
  for (int i = 0; i < FFTRank; i++) {
    in_dims[i + 1] = fft_shape[i];
    out_dims[i + 1] = i == FFTRank - 1 ? fft_shape[i] / 2 + 1 : fft_shape[i];
    temp_shape.AddDim(fft_shape[i]);
  }
  const Eigen::TensorMap<Eigen::Tensor<float, FFTRank + 1, Eigen::RowMajor>,
                         Eigen::Aligned>
      input(operand, in_dims);
  Eigen::TensorMap<Eigen::Tensor<complex64, FFTRank + 1, Eigen::RowMajor>,
                   Eigen::Aligned>
      output(out, out_dims);

  // Create the axes (which are always trailing).
  const auto axes = Eigen::ArrayXi::LinSpaced(FFTRank, 1, FFTRank);

  // Compute the full FFT using a temporary tensor.
  Tensor temp(DataTypeToEnum<complex64>::v(), temp_shape);
  auto full_fft = temp.flat_inner_dims<complex64, FFTRank + 1>();
  const Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> zero_start_indices;
  full_fft.device(device) =
      input.template fft<Eigen::BothParts, Eigen::FFT_FORWARD>(axes);

  // Slice away the negative frequency components.
  output.device(device) = full_fft.slice(zero_start_indices, out_dims);
}

// Computes a reverse complex->real FFT, reconstructing redundant negative
// frequencies using reverse conjugate on innermost dimension after doing IFFT
// on outer dimensions.
template <int FFTRank, typename EigenDevice>
void EigenFftC2R(const EigenDevice& device, float* out, complex64* operand,
                 int64 input_batch, int64 fft_length0, int64 fft_length1,
                 int64 fft_length2) {
  const std::array<int64, 3> fft_shape = {
      {fft_length0, fft_length1, fft_length2}};

  Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> in_dims;
  in_dims[0] = input_batch;
  Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> out_dims;
  out_dims[0] = input_batch;
  TensorShape temp_shape{input_batch};
  for (int i = 0; i < FFTRank; i++) {
    in_dims[i + 1] = i == FFTRank - 1 ? fft_shape[i] / 2 + 1 : fft_shape[i];
    out_dims[i + 1] = fft_shape[i];
    temp_shape.AddDim(fft_shape[i]);
  }
  const Eigen::TensorMap<Eigen::Tensor<complex64, FFTRank + 1, Eigen::RowMajor>,
                         Eigen::Aligned>
      input(operand, in_dims);
  Eigen::TensorMap<Eigen::Tensor<float, FFTRank + 1, Eigen::RowMajor>,
                   Eigen::Aligned>
      output(out, out_dims);

  // Calculate the shape of the temporary tensor for the full FFT and the
  // region we will slice from input given fft_shape. We slice input to
  // fft_shape on its inner-most dimensions, except the last (which we
  // slice to fft_shape[-1] / 2 + 1).
  Tensor temp(DataTypeToEnum<complex64>::v(), temp_shape);
  auto full_fft = temp.flat_inner_dims<complex64, FFTRank + 1>();

  // Calculate the starting point and range of the source of
  // negative frequency part.
  auto neg_sizes = in_dims;
  neg_sizes[FFTRank] = fft_shape[FFTRank - 1] - in_dims[FFTRank];
  Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> neg_target_indices;
  neg_target_indices[FFTRank] = in_dims[FFTRank];

  const Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> zero_start_indices;
  Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> neg_start_indices;
  neg_start_indices[FFTRank] = 1;

  full_fft.slice(zero_start_indices, in_dims).device(device) = input;

  // First, conduct IFFTs on outer dimensions. We save computation (and
  // avoid touching uninitialized memory) by slicing full_fft to the
  // subregion we wrote input to.
  if (FFTRank > 1) {
    const auto outer_axes =
        Eigen::ArrayXi::LinSpaced(FFTRank - 1, 1, FFTRank - 1);
    full_fft.slice(zero_start_indices, in_dims).device(device) =
        full_fft.slice(zero_start_indices, in_dims)
            .template fft<Eigen::BothParts, Eigen::FFT_REVERSE>(outer_axes);
  }

  // Reconstruct the full FFT by appending reversed and conjugated
  // spectrum as the negative frequency part.
  Eigen::array<bool, FFTRank + 1> reverse_last_axis;
  for (auto i = 0; i <= FFTRank; i++) {
    reverse_last_axis[i] = i == FFTRank;
  }

  if (neg_sizes[FFTRank] != 0) {
    full_fft.slice(neg_target_indices, neg_sizes).device(device) =
        full_fft.slice(neg_start_indices, neg_sizes)
            .reverse(reverse_last_axis)
            .conjugate();
  }

  auto inner_axis = Eigen::array<int, 1>{FFTRank};
  output.device(device) =
      full_fft.template fft<Eigen::RealPart, Eigen::FFT_REVERSE>(inner_axis);
}

template <int FFTRank, typename EigenDevice>
void EigenFftWithRank(const EigenDevice& device, void* out, void* operand,
                      int32 fft_type, int64 input_batch, int64 fft_length0,
                      int64 fft_length1, int64 fft_length2) {
  CHECK(::xla::FftType_IsValid(fft_type)) << fft_type;
  switch (fft_type) {
    case ::xla::FftType::FFT:
      EigenFftC2C<true, FFTRank, EigenDevice>(
          device, static_cast<complex64*>(out),
          static_cast<complex64*>(operand), input_batch, fft_length0,
          fft_length1, fft_length2);
      break;
    case ::xla::FftType::IFFT:
      EigenFftC2C<false, FFTRank, EigenDevice>(
          device, static_cast<complex64*>(out),
          static_cast<complex64*>(operand), input_batch, fft_length0,
          fft_length1, fft_length2);
      break;
    case ::xla::FftType::RFFT:
      EigenFftR2C<FFTRank, EigenDevice>(
          device, static_cast<complex64*>(out), static_cast<float*>(operand),
          input_batch, fft_length0, fft_length1, fft_length2);
      break;
    case ::xla::FftType::IRFFT:
      EigenFftC2R<FFTRank, EigenDevice>(
          device, static_cast<float*>(out), static_cast<complex64*>(operand),
          input_batch, fft_length0, fft_length1, fft_length2);
      break;
    default:
      LOG(FATAL) << "Unsupported FFT type: " << fft_type;
  }
}

}  // namespace internal

template <typename EigenDevice>
void EigenFftImpl(const EigenDevice& device, void* out, void* operand,
                  int32 fft_type, int32 fft_rank, int64 input_batch,
                  int64 fft_length0, int64 fft_length1, int64 fft_length2) {
  switch (fft_rank) {
    case 1:
      internal::EigenFftWithRank<1, EigenDevice>(
          device, out, operand, fft_type, input_batch, fft_length0, 0, 0);
      break;
    case 2:
      internal::EigenFftWithRank<2, EigenDevice>(device, out, operand, fft_type,
                                                 input_batch, fft_length0,
                                                 fft_length1, 0);
      break;
    case 3:
      internal::EigenFftWithRank<3, EigenDevice>(device, out, operand, fft_type,
                                                 input_batch, fft_length0,
                                                 fft_length1, fft_length2);
      break;
    default:
      LOG(FATAL) << "Unsupported FFT rank " << fft_rank;
  }
}

}  // namespace xla
}  // namespace tensorflow

#endif  // TENSORFLOW_COMPILER_XLA_SERVICE_CPU_RUNTIME_FFT_IMPL_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="PMD Test RuleSet"
         xmlns="http://pmd.sf.net/ruleset/1.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
         xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">

    <description>First description...</description>

    <rule ref="rulesets/codesize.xml/CyclomaticComplexity" />
    <rule ref="rulesets/codesize.xml/NPathComplexity">
        <properties>
            <property name="minimum" value="50" />
        </properties>
    </rule>
</ruleset>


text:
package cn.scau.edu.ssm.showdoc.mapper;

import cn.scau.edu.ssm.showdoc.po.Voucher;
import cn.scau.edu.ssm.showdoc.po.VoucherExtendClass;

/**
 * 创建用户账号和密码的拓展类
 * @author Administrator
 *
 */
public interface VoucherExtendMapper {
	public void insertSelectiveExtend(Voucher voucher) throws Exception;

	public Integer selectVoucherExtend(VoucherExtendClass voucher) throws Exception;

	public void updateVoucherExtend(VoucherExtendClass voucher) throws Exception;

	public String queryPictureById(Integer id) throws Exception;
}


text:
using System;

namespace SimpleStates
{

	public class SimpleStateTransition
	{
		string nextState;
		Func<bool> criteria;

		public SimpleStateTransition(Func<bool> pCriteria, string pNextState)
		{
			nextState = pNextState;
			criteria = pCriteria;
		}

		public bool CheckCriteria()
		{
			return criteria.Invoke();
		}

		public string Next()
		{
			return nextState;
		}
	}

}


text:
![Build Status](https://travis-ci.org/DarkmatterVale/regex4dummies.svg?branch=master)
[![Code Climate](https://codeclimate.com/github/DarkmatterVale/regex4dummies/badges/gpa.svg)](https://codeclimate.com/github/DarkmatterVale/regex4dummies)
[![Issue Count](https://codeclimate.com/github/DarkmatterVale/regex4dummies/badges/issue_count.svg)](https://codeclimate.com/github/DarkmatterVale/regex4dummies)

Simple pattern finding in strings and natural language processing.

Are you looking for the homepage of the project? Go to https://darkmattervale.github.io/regex4dummies if so.

If you are interested in maintaining this library, please let me know. I do not have time to maintain this at the moment.

###

## Features:

- Automatic pattern detection ( semantic and literal )
- Multiple parsers ( implementations of nltk, pattern, and nlpnet )
- Keyword searching to find specific phrases
- Topic analysis
- Important information extraction
- Tokenizer and sentence dependency identifier

## Roadmap

Please see the issues page for the project if you would like to see all of the features that are planned to be implemented.

## Usage

To see how to use this library, please see the new homepage for regex4dummies. Once at the homepage, proceed to the documentation section.

## Installation

To install this library, you can use pip, or download the repository from Github.

```
pip install regex4dummies
```

## Contributing

If you would like to contribute, please fork the repository and create a PR with whatever you've changed. Thanks for the help!

## License

Please see LICENSE.txt for information about the MIT license

Copyright (c) 2015 Vale Tolpegin. All rights reserved.

## Citations

Citations for nlpnet:

- Fonseca, E. R. and Rosa, J.L.G. Mac-Morpho Revisited: Towards Robust Part-of-Speech Tagging. Proceedings of the 9th Brazilian Symposium in Information and Human Language Technology, 2013. p. 98-107 [PDF]


text:
using System;

namespace RedBit.CCAdmin
{
    public class ServerErrorException : Exception
    {
		public ServerErrorException() { }
		public ServerErrorException(string message) : base(message) { }
		public ServerErrorException(string message, Exception inner) : base(message, inner) { }
    }
}


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

{% block head %}

<link rel="stylesheet" href="{{ MEDIA_URL }}css/download_installers.css" />
{% endblock %}

{% block content %}

  {% if user_built %}

Your installers are ready!

Bookmark this page to come back later, or share this URL with others:

{{ share_url }} Right click on the URL to copy the address.

  {% else %}

Thanks for contributing!

The installers below have been customized by a Seattle user. By running these installers, 10% of your computing resources will be donated to an experiment being run by that user.

  {% endif %}

Download installers

Installers are provided for Android, Linux, Mac OS X, and Windows.

Install via
Google Play

Android instructions

On your Android device, tap the icon to the left to download Seattle Testbed via Google Play. (If that doesn't work, please try this alternative link.)

In the Google Play app, tap Install and review the requested permissions.

Start the app and follow the on-screen instructions to complete the installation. Depending on the speed of your device, the process can take a few minutes to finish.

To check that Seattle is running, look at the Seattle on Android application window.

Download installer
for Linux

Linux instructions

Download the Seattle tarball to your computer.

Extract the tarball to the directory in which you would like to install Seattle.

Navigate to that directory and run ./install.sh

To check that Seattle is running, try running:
ps -ef | grep nmmain.py | grep -v grep

Note: You must have Python 2.5 installed.

Download installer
for Mac

Mac instructions

Download the Seattle tarball to your computer.

Extract the tarball to the directory in which you would like to install Seattle.

Navigate to that directory and run ./install.sh

To check that Seattle is running, try running:
ps Aww | grep nmmain.py | grep -v grep

Note: You must have Python 2.5 installed.

Download installer
for Windows

Windows instructions

Download the Seattle ZIP file to your computer.

Extract the ZIP file to the directory in which you would like to install Seattle.

Double-click install.bat or run it from the command line.

To check that Seattle is running, look in Task Manager for the process pythonw.exe.

{% endblock %}


text:
module Dota
  module API
    class Match
      class Side < BasicSide
        def name
          raw["name"]
        end

        def logo_id
          raw["logo"]
        end

        def complete?
          raw["team_complete"] == 1
        end

        def tower_status
          format_status raw["tower_status"], :towers
        end

        def barracks_status
          format_status raw["barracks_status"], :barracks
        end

        def captain_id
          raw["captain"]
        end

        def players
          raw["players"].map do |raw_player|
            Player.new(raw_player)
          end
        end
      end
    end
  end
end


text:
package com.qrra.spring.employee.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.util.CollectionUtils;

public class Page<T> {

    public static final int PAGE_SIZE = 10;

    private final int number; // Page number start from 1

    private final long total;

    private final List<T> content = new ArrayList<T>();

    public Page(int number, List<T> content, long total) {
        this.number = number;
        this.total = total;
        if (!CollectionUtils.isEmpty(content)) {
            this.content.addAll(content);
        }
    }

    public List<T> getContent() {
        return Collections.unmodifiableList(content);
    }

    public int getSize() {
        return PAGE_SIZE;
    }

    public long getTotal() {
        return total;
    }

    public int getCurrentPage() {
        return number;
    }

    public int getTotalPages() {
        return (int) Math.ceil((double) total / (double) PAGE_SIZE);
    }

    public boolean isFirst() {
        return number <= 1;
    }

    public boolean isLast() {
        return number >= getTotalPages();
    }

    public boolean isEmpty() {
        return content.isEmpty();
    }
}


text:
package com.ulyseo.model;

import java.util.Date;
import java.util.Map;

import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MapKeyColumn;
import javax.persistence.Table;

import org.springframework.format.annotation.DateTimeFormat;

@Entity
@Table(name = "stats")
public class Stats {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private long id;

	@Column(unique = true)
	@DateTimeFormat(pattern = "MM/yyyy")
	private Date monthAndYear;

	@ElementCollection
	@CollectionTable(name = "listenCount")
	@MapKeyColumn(name = "audioElement")
	private Map<AudioElement, Integer> listenCountByAudioElements;

	public Map<AudioElement, Integer> getListenCountByAudioElements() {
		return listenCountByAudioElements;
	}

	public void setListenCountByAudioElements(Map<AudioElement, Integer> listenCountByAudioElements) {
		this.listenCountByAudioElements = listenCountByAudioElements;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public Date getMonthAndYear() {
		return monthAndYear;
	}

	public void setMonthAndYear(Date monthAndYear) {
		this.monthAndYear = monthAndYear;
	}

}


text:
%% Eigenvalues of the Fox-Li integral operator
% Toby Driscoll and Nick Trefethen, 7 October 2010

%%
% (Chebfun example integro/FoxLi.m)
% [Tags: #eigenvalues, #fredholm]

%%
% In the field of optics, integral operators arise that have a complex
% symmetric (but not Hermitian) oscillatory kernel.  An example is the
% following linear Fredholm operator L associated with the names of Fox
% and Li (also Fresnel and H. J. Landau):
%
%    v(x) = sqrt(i*F/pi) int_{-1}^1 K(x,s) u(s) ds.
%
% L maps a function u defined on [-1,1] to another function v = Lu defined
% on [-1,1].  The number F is a positive real parameter, the Fresnel number,
% and the kernel function K(x,s) is
%
%    K(x,s) = exp(-i*F*(x-s)^2).
%

%%
% To create the operator in Chebfun, we define the kernel anduse the FRED
% function to build L:
F = 64*pi;                                     % Fresnel number
K = @(x,s) exp(-1i*F*(x-s).^2 );               % kernel
L = sqrt(1i*F/pi) * chebop(@(u) fred(K,u));    % Fredholm integral operator

%%
% Computing the 80 eigenvalues of largest complex magnitude requires just a call
% to EIGS with the 'lm' option:
tic
lam = eigs(L,80,'lm');
toc

%%
% Finally, a wonderful (and not fully understood) pattern emerges when we
% plot the results:
x = chebfun('x');
clf, plot(exp(1i*pi*x),'--r','linewidth',1.5)
hold on, plot(lam,'k.','markersize',12)
title('largest 80 eigenvalues of Fox-Li operator','fontsize',16)
axis equal, axis(1.05*[-1 1 -1 1]), hold off

%%
% References:
%
% T. A. Driscoll, <http://dx.doi.org/10.1016/j.jcp.2010.04.029 Automatic
% spectral collocation for integral, integro-differential, and integrally
% reformulated differential equations>, J. Comput. Phys. 229 (2010),
% 5980-5998.
%
% A. G. Fox and T. Li, Resonant modes in a maser interferometer,
% Bell System Technical Journal 40 (1961), 453-488.
%
% L. N. Trefethen and M. Embree, Spectra and Pseudospectra,
% Princeton University Press, 2005 (Chapter 60).


text:
<!DOCTYPE html >

          <title>NNDataScale - nounou documentation - nounou.elements.traits.NNDataScale</title>
          <meta name="description" content="NNDataScale - nounou documentation - nounou.elements.traits.NNDataScale" />
          <meta name="keywords" content="NNDataScale nounou documentation nounou.elements.traits.NNDataScale" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

nounou.elements.traits

NNDataScale

        class

        NNDataScale extends NNElement

This trait of XData and XDataChannel objects encapsulates scaling and unit information for
electrophysiological and imaging recordings.

Created by Kenta on 12/15/13.

          Linear Supertypes

NNElement, LoggingExt, LazyLogging, Logging, AnyRef, Any

<input id="mbrsel-input" type="text" accesskey="/" />

              Ordering

Alphabetic

By inheritance

                Inherited

NNDataScale

NNElement

LoggingExt

LazyLogging

Logging

AnyRef

Any

Hide All

Show all

            Learn more about member selection

            Visibility

Public

All

Instance Constructors

        new

        NNDataScale(minValue: Int, maxValue: Int, absGain: Double, absOffset: Double, absUnit: String, xBits: Int = 1024)

Value Members

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        val

        absGain: Double

        val

        absOffset: Double

        val

        absUnit: String

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        val

        className: String

[NNElement] getCanonicalName, buffered for serialization with GSON.

[NNElement] getCanonicalName, buffered for serialization with GSON.

Definition Classes

NNElement

        def

        clone(): AnyRef

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        final
        def

        convertAbsoluteToInt(dataAbs: Array[Double]): Array[Int]

        final
        def

        convertAbsoluteToInt(dataAbs: DenseVector[Double]): DenseVector[Int]

Converts data in the internal representation (Int) to absolute units (Double), with unit of
absUnit (e.g.

Converts data in the internal representation (Int) to absolute units (Double), with unit of
absUnit (e.g. "mV")

        final
        def

        convertAbsoluteToInt(dataAbs: Double): Int

Converts data in the internal representation (Int) to absolute units (Double), with unit of
absUnit (e.g.

Converts data in the internal representation (Int) to absolute units (Double), with unit of
absUnit (e.g. "mV")

        final
        def

        convertIntToAbsolute(data: Array[Int]): Array[Double]

        final
        def

        convertIntToAbsolute(data: DenseVector[Int]): DenseVector[Double]

Converts data in the internal representation (Int) to absolute units (Double), with unit of
absUnit (e.g.

Converts data in the internal representation (Int) to absolute units (Double), with unit of
absUnit (e.g. "mV")

        final
        def

        convertIntToAbsolute(data: Int): Double

Converts data in the internal representation (Int) to absolute units (Double), with unit of
absUnit (e.g.

Converts data in the internal representation (Int) to absolute units (Double), with unit of
absUnit (e.g. "mV")

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        def

        finalize(): Unit

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      classOf[java.lang.Throwable]
    )

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

        lazy val

        gitHead: String

[NNElement] Git HEAD of the current revision, buffered for serialization with GSON.

[NNElement] Git HEAD of the current revision, buffered for serialization with GSON.

Definition Classes

NNElement

        lazy val

        gitHeadShort: String

[NNElement] Git HEAD shortened to first 10 characters.

[NNElement] Git HEAD shortened to first 10 characters.

Definition Classes

NNElement

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

        def

        isCompatible(that: NNElement): Boolean

SHOULD OVERRIDE Whether an NNElement is compatible with another for merging, etc.

SHOULD OVERRIDE Whether an NNElement is compatible with another for merging, etc.

Definition Classes

NNDataScale → NNElement

        final
        def

        isCompatible(that: Seq[NNElement]): Boolean

SHOULD OVERRIDE Whether NNElements are compatible with another for merging, etc.

SHOULD OVERRIDE Whether NNElements are compatible with another for merging, etc.

Definition Classes

NNElement

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        lazy val

        logger: Logger

Attributes

protected

Definition Classes

LazyLogging → Logging

        def

        loggerError(message: String, params: AnyRef*): IllegalArgumentException

[LoggingExt] Logs a message using slf4j, and returns a new scala.IllegalArgumentException.

[LoggingExt] Logs a message using slf4j, and returns a new scala.IllegalArgumentException.
Use as follows:

throw loggerError("This is an error with params {}", param1.toString)

Definition Classes

LoggingExt

        def

        loggerRequire(boolean: Boolean, message: String, params: AnyRef*): Unit

[LoggingExt] If input 'boolean' is false, logs a message using slf4j and throws an error.

[LoggingExt] If input 'boolean' is false, logs a message using slf4j and throws an error.

Definition Classes

LoggingExt

Annotations

                @throws(

      ...
    )

        val

        maxValue: Int

        val

        minValue: Int

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        val

        nnGitObj: NNGit.type

Definition Classes

NNElement

        final
        def

        notify(): Unit

Definition Classes

AnyRef

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        def

        toJsonString: String

[NNElement]

[NNElement]

Definition Classes

NNElement

        def

        toString(): String

Definition Classes

AnyRef → Any

        def

        toStringFull(): String

Output string with short git head.

Output string with short git head. Each implementation (eg nounou.elements.data.filters.NNDataFilter
objects should update this to provide information specific to the specific filter, etc.

Definition Classes

NNElement

        val

        version: Double

[NNElement] Reads global nounou version number, buffered for serialization with GSON.

[NNElement] Reads global nounou version number, buffered for serialization with GSON.

Definition Classes

NNElement

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        val

        xBits: Int

        final
        lazy val

        xBitsD: Double

(xBits:Int).toDouble

Inherited from NNElement

Inherited from LoggingExt

Inherited from LazyLogging

Inherited from Logging

Inherited from AnyRef

Inherited from Any

Ungrouped


text:
#include "AspUtil.h"
#include "AspRegionList.h"
#include <float.h>
#include <math.h>

AspRegionList::AspRegionList() {
   regionMap = new AspRegionMap;
}

AspRegionList::~AspRegionList() {
   delete regionMap;
}

void AspRegionList::clearList() {
   regionMap->clear();
}

void AspRegionList::addRegion(int ind, spAspRegion_t region) {
   region->index=ind;
   regionMap->erase(region->sCoord[0].x);
   regionMap->insert(AspRegionMap::value_type(region->sCoord[0].x,region));

}

spAspRegion_t AspRegionList::getFirstRegion(AspRegionMap::iterator& regionItr) {
    if (regionMap && regionMap->size() > 0) {
        regionItr = regionMap->begin();
        if (regionItr != regionMap->end()) {
            return regionItr->second;
        }
    }
    return (spAspRegion_t)NULL;
}

spAspRegion_t AspRegionList::getNextRegion(AspRegionMap::iterator& regionItr) {
    if (++regionItr == regionMap->end()) {
        return (spAspRegion_t)NULL;
    }
    return regionItr->second;
}

spAspRegion_t AspRegionList::getSelRegion() {
   AspRegionMap::iterator itr;
   spAspRegion_t region;
   for (region= getFirstRegion(itr); region != nullAspRegion; region= getNextRegion(itr)) {
        if(region->selected != 0) return region;
   }
   return nullAspRegion;
}

// called by regionList. Note, region->index may be different than map ind.
spAspRegion_t AspRegionList::getRegion(int ind) {
   AspRegionMap::iterator itr;
   spAspRegion_t region;
   for (region= getFirstRegion(itr); region != nullAspRegion; region= getNextRegion(itr)) {
        if(region->index == ind) return region;
   }
   return nullAspRegion;
}

void AspRegionList::deleteRegion(int ind) {
   AspRegionMap::iterator itr;
   spAspRegion_t region;
   for (itr = regionMap->begin(); itr != regionMap->end(); ++itr) {
        if(itr->second->index == ind) {
	  regionMap->erase(itr->first);
	  return;
	}
   }
}

void AspRegionList::deleteRegion() {
   AspRegionMap::iterator itr;
   spAspRegion_t region;
   for (itr = regionMap->begin(); itr != regionMap->end(); ++itr) {
        if(itr->second->selected != 0) {
	  regionMap->erase(itr->first);
	}
   }
}

void AspRegionList::display(spAspCell_t cell, AspTraceList *selTraceList, spAspDataInfo_t dataInfo) {

   double px,py,pw,ph;
   cell->getPixCell(px,py,pw,ph);
   double vx,vy,vw,vh;
   cell->getValCell(vx,vy,vw,vh);

   set_clip_region((int)px-1,(int)(py+2*(cell->getCali(VERT))),(int)pw,(int)ph);

   AspRegionMap::iterator itr;
   spAspRegion_t region;

   for (itr = regionMap->begin(); itr != regionMap->end(); ++itr) {
        region = itr->second;
	if(region->dataID != "") {
	   spAspTrace_t trace = selTraceList->getTraceByKey(region->dataID);
	   if(trace != nullAspTrace) {
		region->display(cell,trace,dataInfo);
	   }
        }
   }
   selTraceList->showBCModel(cell); // shown only if model exist and BC not applied

   set_clip_region(0,0,0,0);
}

spAspRegion_t AspRegionList::selectRegion(spAspCell_t cell, int x, int y, bool &changeFlag) {
   spAspRegion_t prevRegion = getSelRegion();
   int selected = 0;
   if(prevRegion != nullAspRegion) {
      selected = prevRegion->selected;
   }
   spAspRegion_t region = nullAspRegion;;
   AspRegionMap::iterator itr;
   for (itr = regionMap->begin(); itr != regionMap->end(); ++itr) {
	itr->second->selected=0;
        if(region == nullAspRegion) {
           if(itr->second->select(cell,x,y)) region = itr->second;
	}
   }
   if(prevRegion == nullAspRegion && region == nullAspRegion) changeFlag = false;
   else if(prevRegion == nullAspRegion || region == nullAspRegion) changeFlag = true;
   else if(prevRegion == region) {
       if(region->selected == selected) changeFlag = false;
       else changeFlag = true;
   } else changeFlag = true;

   return region;
}

void AspRegionList::getBCMask(spAspTrace_t trace, float *baseData, float *mask, int npts) {

   for(int i=0; i<npts; i++) {
	mask[i]=0;
	baseData[i]=0;
   }

   if(trace->getTotalpts() != npts) return;
   if(trace == nullAspTrace) return;

   AspRegionMap::iterator itr;
   spAspRegion_t region;
   for (itr = regionMap->begin(); itr != regionMap->end(); ++itr) {
        region = itr->second;
	int i = trace->val2dpt(region->sCoord[0].x);
	mask[i]=1;
	baseData[i]=region->sCoord[0].y;
   }
}


text:
require 'rails_helper'

class CustomLogger
  def log(_message); end

  def unknown(_message, _opts = {}); end

  def debug(_message, _opts = {}); end

  def info(_message, _opts = {}); end

  def warn(_message, _opts = {}); end

  def error(_message, _opts = {}); end
end

describe Cangaroo::Logger do
  let(:cangaroo_logger) { Cangaroo::Logger.send(:new) }
  before { Rails.configuration.cangaroo.logger = logger }

  describe '#logger' do
    subject { cangaroo_logger.logger }

    context 'when Rails.configuration.cangaroo.logger is set' do
      let(:logger) { CustomLogger.new }

      it { is_expected.to eq(logger) }
    end

    context 'when Rails.configuration.cangaroo.logger is not set' do
      let(:logger) { nil }

      it { is_expected.to eq(Rails.logger) }
    end
  end

  context 'log methods' do
    let(:message) { 'message' }
    let(:opts) { { opt1: 1, opt2: 2 } }

    describe '#log' do
      after { cangaroo_logger.log(message, opts) }

      context 'when logger can receive given parameters' do
        let(:logger) { nil }

        it 'calls the logger log method with the given params' do
          expect(Rails.logger).to receive(:log).with(message, opts)
        end
      end

      context 'when logger can not receive given parameters' do
        let(:logger) { CustomLogger.new }

        it 'calls the logger log method with an array of message and params' do
          expect(logger).to receive(:log).with([message, opts])
        end
      end
    end

    %i(unknown debug info warn error).each do |log_method|
      describe "##{log_method}" do
        after { cangaroo_logger.send(log_method, message, opts) }

        context 'when logger can receive given parameters' do
          let(:logger) { CustomLogger.new }

          it "calls the logger #{log_method} method with the given params" do
            expect(logger).to receive(log_method).with(message, opts)
          end
        end

        context 'when logger can not receive given parameters' do
          let(:logger) { nil }

          it "calls the logger #{log_method} method with an array of message and params" do
            expect(Rails.logger).to receive(log_method).with([message, opts])
          end
        end
      end
    end
  end
end


text:
{-# LANGUAGE CPP #-}

-- |
-- Module      : Criterion.Main.Options.Internal
-- Copyright   : (c) 2022 Ryan Scott
--
-- License     : BSD-style
-- Maintainer  : bos@serpentine.com
-- Stability   : experimental
-- Portability : GHC
--
-- Provides a shim on top of @optparse-applicative@'s 'Options.tabulate'
-- function that is backwards-compatible with pre-@0.17.*@ versions of
-- @optparse-applicative@. This is deliberately kept separate from the rest of
-- "Criterion.Main.Options" because this function requires CPP to define, and
-- there is a Haddock comment in "Criterion.Main.Options" that will cause the
-- CPP preprocessor to trigger an \"unterminated comment\" error. Ugh.
--
-- TODO: When we support @optparse-applicative-0.17@ as the minimum, remove
-- this module and simply inline the definition of 'tabulate' in
-- "Criterion.Main.Options".
module Criterion.Main.Options.Internal (tabulate) where

import qualified Options.Applicative.Help as Options
import Options.Applicative.Help (Chunk, Doc)

#if MIN_VERSION_optparse_applicative(0,17,0)
import Options.Applicative (ParserPrefs(..), defaultPrefs)
#endif

-- | A shim on top of 'Options.tabulate' from @optparse-applicative@ that is
-- backwards-compatible with pre-@0.17.*@ versions of @optparse-applicative@.
tabulate :: [(Doc, Doc)] -> Chunk Doc
#if MIN_VERSION_optparse_applicative(0,17,0)
tabulate = Options.tabulate (prefTabulateFill defaultPrefs)
#else
tabulate = Options.tabulate
#endif


text:
BABL is a declarative langage designed for expressing simple transformations from models (PORO, ActiveRecord, ...) to JSON, by combining navigation & construction operators.

## Navigation

In a real world project, model objects are typically related to many others. This is especially true for ActiveRecords, which are often linked together via associations. By the mean of **navigation operators**, BABL can explore the object graph in order to fetch the data it needs.

At template's root, the **current object** is set to the model you want to serialize. It changes after a navigation operator is used (such as `#nav`, `#with`, ...). Multiple navigation operators can be chained.

In BABL world, *navigating* is almost always a synonym for *calling a method* ([except for `Hash`](operators.md#nav)).

Example template (`self` is written explicitly for demonstration purpose):
```ruby
    self.nav(:document).nav(:author)
```

- `self`: The **current object** is the model to serialize
- `self.nav(:document)`: Navigate to `document` and update the **current object** for the rest of the chain.
- `self.nav(:document).nav(:author)`: Navigate again to `author` starting from the **current object** (which was pointing on the document).
- Et cætera...

Semantically, this BABL template is ~ equivalent to this Ruby code:
```ruby
model.document.author
```

## Construction

Construction operators are necessary to produce JSON. They do not affect the **current object**, but they always terminate the chaining.

Additionally, when a chain is not terminated by a construction operator, the **current object** is implicitly dumped into the JSON output at the current position. For instance, the (minimal) template `self` will dump the input model without any transformation, assuming it is serializable.

The most useful construction operator is [`#object`](operators.md#object): it constructs a JSON object.

Example:
```ruby
object(
    document: nav(:document).object(
        id: nav(:id),
        content: nav(:content),
        author: nav(:author).object(
            id: nav(:id),
            name: nav(:name)
        )
    )
)
```

Semantically, this BABL template is ~ equivalent to this Ruby code:
```ruby
    {
        document: {
            id: model.document.id,
            content: model.document.content,
            author: {
                id: model.document.author.id,
                name: model.document.author.name
            }
        }
    }
```

### Side node: few words about `_` (`enter`)

The pattern `object(xxx: nav(:xxx))` tends to appear a lot if the keys are named after the properties on the model. To alleviate this, there is a macro `_`. See [`#enter`](operators.md#enter) for more details.

```ruby
object(
    document: _.object(
        id: _,
        content: _,
        author: _.object(
            id: _,
            name: _
        )
    )
)
```

## Templates

Like most Ruby DSLs, a BABL template is just Ruby code executed in a special context (where Ruby's `self` is a `Babl::Template` instance).
The last statement of a BABL template is expected to return another `Babl::Template`, or any value that can be interpreted as a template. See implicit forms in [Operators](operators.md) for more details.

It is important to know that an instance of `Babl::Template`:
- Is an immutable object.
- Doesn't depend on the context it is defined in.
- Can be re-used in different contexts.

```ruby
# This inline template is defined at top-level, but properties will
# be fetched starting from 'checkin' and 'checkout', depending on
# where it is used.
checkinout = _.nullable.object(
    id: _,
    time: _
)

object(
    mission: object(
        id: _,
        starts_at: _,
        ends_at: _,
        # Re-using 'checkinout' structure twice is okay
        # Each one will have a different replacement for '_'
        checkin: checkinout,
        checkout: checkinout
    )
)
```

----

Learn more about [Babl::Template](templates.md).


text:
var owner = owner || {

};

owner.init = function(){

}

/* ----- Tables ----- */
/* ------------------- */
owner.initTableDatatablesResponsive = function () {
    var table = $('#owner_table');

    if(!owner.tableObject){
        owner.tableObject = table.dataTable({
            // Internationalisation. For more info refer to http://datatables.net/manual/i18n
            "language": {
                "aria": {
                    "sortAscending": ": activate to sort column ascending",
                    "sortDescending": ": activate to sort column descending"
                },
                "emptyTable": "No data available in table",
                "info": "",
                "infoEmpty": "No entries found",
                "infoFiltered": "",
                "lengthMenu": "_MENU_ ",
                "search": translate('key_word'),
                "zeroRecords": "No matching records found",
            },
            searching:true,

            bShowAll: false,
             // setup buttons extentension: http://datatables.net/extensions/buttons/
            buttons: [
                {
                    extend: 'print',
                    className: 'btn dark btn-outline',
                    orientation: 'landscape',
                    exportOptions: {
                        columns: [ 0, 1, 2, 3, 5]
                    },
                    action  : function(e, dt, button, config) {
                        $.fn.dataTable.ext.buttons.print.action(e, dt, button, config);
                    }

                },{
                    extend: 'pdf',
                    className: 'btn green btn-outline',
                    orientation: 'landscape',
                    exportOptions: {
                        columns: [ 0, 1, 2, 3, 5]
                    },
                    action  : function(e, dt, button, config) {
                        $.fn.dataTable.ext.buttons.pdfHtml5.action(e, dt, button, config);
                    }
                },{
                    extend: 'csv',
                    text: 'Excel 1',
                    className: 'btn purple btn-outline ',
                    orientation: 'landscape',
                    fieldSeparator: ',',
                    exportOptions: {
                        columns: [ 0, 1, 2, 3,  5]
                    },
                    action  : function(e, dt, button, config) {
                        $.fn.dataTable.ext.buttons.csvHtml5.action(e, dt, button, config);
                    }
                },{
                    extend: 'csv',
                    text: 'Excel 2',
                    className: 'btn purple btn-outline ',
                    orientation: 'landscape',
                    fieldSeparator: ';',
                    exportOptions: {
                        columns: [ 0, 1, 2, 3, 5]
                    },
                    action  : function(e, dt, button, config) {
                        $.fn.dataTable.ext.buttons.csvHtml5.action(e, dt, button, config);
                    }
                }

            ],

            "order": [
                [1, 'desc']
            ],

            "lengthMenu": [
                [5, 10, 15, 20, -1],
                [5, 10, 15, 20, "All"] // change per page values here
            ],
            // set the initial value
            "pageLength": 20,

            "dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'f><'col-md-6 col-sm-12'p>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'l><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
        });
    }

};
/*********************************
*   @name : (window).load
*   params : /
*   Call init method on windows load
*********************************/
$(document).ready(function() {
    owner.init();
    owner.initTableDatatablesResponsive();
});


text: export * from "./SoundSwitch";


text:
import React from 'react'
import PropTypes from 'prop-types'
import { injectIntl } from 'react-intl'
import { intlShape } from '@zap/i18n'
import { Form, SearchInput } from 'components/Form'
import messages from './messages'

const AutopaySearch = ({ intl, searchQuery, updateAutopaySearchQuery, ...rest }) => (
  <Form width={1} {...rest}>
    <SearchInput
      field="channel-search"
      highlightOnValid={false}
      id="channel-search"
      initialValue={searchQuery}
      onValueChange={updateAutopaySearchQuery}
      placeholder={intl.formatMessage({ ...messages.search_placeholder })}
    />
  </Form>
)

AutopaySearch.propTypes = {
  intl: intlShape.isRequired,
  searchQuery: PropTypes.string,
  updateAutopaySearchQuery: PropTypes.func.isRequired,
}

export default injectIntl(AutopaySearch)


text:
package ca.corefacility.bioinformatics.irida.ria.web.ajax.dto;

import java.util.List;

/**
 * UI Request to update an existing sample
 */
public class UpdateSampleRequest extends CreateSampleRequest {
	public UpdateSampleRequest(String name, String organism, String description, List<FieldUpdate> metadata) {
		super(name, organism, description, metadata);
	}
}


text:
using System;
using System.Collections.Concurrent;
using Common.Logging;

namespace _S_LibraryProjectName_S_.Infrastructure.ContainerExtensions
{
    public class LogFactory : ILogFactory
    {
        private ConcurrentDictionary<Type, ILog> LoggersDictionary
        {
            get
            {
                if (_loggersDictionary == null)
                {
                    lock (_sync)
                    {
                        if (_loggersDictionary == null)
                        {
                            _loggersDictionary = new ConcurrentDictionary<Type, ILog>();
                        }
                    }
                }
                return _loggersDictionary;
            }
        }
        private ConcurrentDictionary<Type, ILog> _loggersDictionary;
        private readonly object _sync = new object();

        public ILog GetLogger(Type type)
        {
            if (!LoggersDictionary.ContainsKey(type))
            {
                var logger = LogManager.GetLogger(type);
                LoggersDictionary.AddOrUpdate(type, logger, (type1, log) => logger);
            }
            return LoggersDictionary[type];
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ceská Mykol. 31(2): 70 (1977)

#### Original name
Peziza labessiana (Boud.) Sacc. & Traverso, 1911

### Remarks
null


text:
Binding Tracks

        <select></select>
        <button id="remove" class="btn btn-default btn-xs glyphicon glyphicon-remove"></button>

    <button id="add" class="add-track btn btn-default btn-xs glyphicon glyphicon-plus"></button>

Chromosome

    <select></select>

Start Coordinate

    <button class="btn btn-default glyphicon glyphicon-refresh btn-update"></button>
    <input class="form-control input-with-update">

End Coordinate

    <button class="btn btn-default glyphicon glyphicon-refresh btn-update"></button>
    <input class="form-control input-with-update">

Find Gene Locus

    <button class="btn btn-default glyphicon glyphicon-refresh btn-update"></button>
    <input class="form-control input-with-update">

      <colgroup>
        <col>
        <col width="70px">
      </colgroup>

        Overviews
        <input type="checkbox" id="overview" title="show binding data overview" checked>

        Bed
        <input type="checkbox" id="bed" title="show bed track" checked>

        Bed Labels
        <input type="checkbox" id="bed-labels" title="show bed track" checked>

        Exons
        <input type="checkbox" id="exons" title="show exons track" checked>

        Auto-Scale
        <input type="checkbox" id="auto-scale" title="auto adjust the vertical plot maximum to the maximum data value in range" checked>


text:
A spring boot application with OpenAPI 3.0 api documentation enabled
 - Demonstrates using the default swagger group

```
./gradlew boot-webflux:bootRun
```

## Paths
- All Swagger Resources(groups) `http://localhost:8080/documentation/swagger-resources`
- Swagger UI endpoint: `http://localhost:8080/documentation/swagger-ui/`
- Swagger docs endpoint: `http://localhost:8080/v3/api-docs`


text:
<?php
////////////////////////////////////////////////////////
// Do not edit this file. It is automatically generated

//________________(SYSTEM)____________________

// Default currency
define('DEFAULT_CURRENCY_SYMBOL', '$');

// Application name
define('CONFIG_APPLICATION_NAME', 'Extreme Framework');

// CSV separator
define('CSV_SEPARATOR', ',');

// Date format
define('DATE_FORMAT', 'mm-dd-yy');

// Date format (in Smarty)
define('SMARTY_DATE_FORMAT', '%m-%d-%Y');

// Copyright notice
define('COPYRIGHT_NOTICE', 'Copyright © 2011-2015 Extreme Framework. All rights reserved.');

// Default user group
define('DEFAULT_USER_GROUP', '2');

// Positive currency format
define('POSITIVE_CURRENCY_FORMAT', '%s%n');

// Negative currency format
define('NEGATIVE_CURRENCY_FORMAT', '(%s%n)');

// Organization name
define('ORGANIZATION_NAME', 'Extreme Framework');

// Organization name (short)
define('ORGANIZATION_NAME_SHORT', 'Extreme Framework');

// Support name
define('SUPPORT_NAME', 'Extreme Framework');

// Support email
define('SUPPORT_EMAIL', '');

// Default public dashboard
define('DEFAULT_PUBLIC_DASHBOARD', '3');

// GetResponse API key
define('GETRESPONSE_API_KEY', '');

// Use SMTP for sending emails?
define('MAILER_USE_SMTP', '1');

// SMTP host
define('MAILER_SMTP_HOST', 'smtp.gmail.com');

// SMTP port
define('MAILER_SMTP_PORT', '465');

// SMTP username
define('MAILER_SMTP_USERNAME', '');

// SMTP password
define('MAILER_SMTP_PASSWORD', '******');

// Save draft interval (seconds)
define('SAVE_DRAFT_INTERVAL', '10');

// SMTP encryption (tls|ssl)
define('MAILER_SMTP_ENCRYPTION', 'ssl');

//________________(SYNC)____________________

// Cloud sync option
define('CLOUD_SYNC_ENABLED', '1');


text: The original source for these materials is https://github.com/Unidata/unidata-python-workshop


text:
/**
 * Autogenerated by Thrift Compiler (0.9.2)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package com.navercorp.pinpoint.thrift.dto.command;

import java.util.Map;
import java.util.HashMap;
import org.apache.thrift.TEnum;

public enum TRouteResult implements org.apache.thrift.TEnum {
  OK(0),
  BAD_REQUEST(200),
  EMPTY_REQUEST(201),
  NOT_SUPPORTED_REQUEST(202),
  BAD_RESPONSE(210),
  EMPTY_RESPONSE(211),
  NOT_SUPPORTED_RESPONSE(212),
  TIMEOUT(220),
  NOT_FOUND(230),
  NOT_ACCEPTABLE(240),
  NOT_SUPPORTED_SERVICE(241),
  UNKNOWN(-1);

  private final int value;

  private TRouteResult(int value) {
    this.value = value;
  }

  /**
   * Get the integer value of this enum value, as defined in the Thrift IDL.
   */
  public int getValue() {
    return value;
  }

  /**
   * Find a the enum type by its integer value, as defined in the Thrift IDL.
   * @return null if the value is not found.
   */
  public static TRouteResult findByValue(int value) {
    switch (value) {
      case 0:
        return OK;
      case 200:
        return BAD_REQUEST;
      case 201:
        return EMPTY_REQUEST;
      case 202:
        return NOT_SUPPORTED_REQUEST;
      case 210:
        return BAD_RESPONSE;
      case 211:
        return EMPTY_RESPONSE;
      case 212:
        return NOT_SUPPORTED_RESPONSE;
      case 220:
        return TIMEOUT;
      case 230:
        return NOT_FOUND;
      case 240:
        return NOT_ACCEPTABLE;
      case 241:
        return NOT_SUPPORTED_SERVICE;
      case -1:
        return UNKNOWN;
      default:
        return UNKNOWN;
    }
  }
}


text:
import sys
from time import time
import numpy as np
import matplotlib.pyplot as plt

def condense_file(filename,columnsKeep):
	with open(filename) as f:
		data = f.read()
	data = data.split('\n') # parse based on newLines
	newData = ''
	for d in data:
		i = 0
		newLine = ''
		currLine = d.split()

		for curr in currLine:
			i += 1
			if i in columnsKeep:
				newLine = newLine+curr+'\t'
		newData += newLine+'\n'

	with open(filename,'w') as f:
		f.write(newData)

def mesytec_parse(filename,columns):
	c = ','
	FILEEXTENSIONLENGTH = 4
	outfilename = filename[:-FILEEXTENSIONLENGTH]+'_parsed.txt'

	initialTime = time()

	parsedData = []
	for i in range(len(columns)):
		parsedData.append('')

	with open(filename) as f:
		with open(outfilename,'w') as of:
			previousLine = 'FFFF\n'
			while True:

				dataLine = previousLine
				dataidLine = f.readline()
				# print(dataidLine)

				if dataLine == '' or dataidLine == '':
					break

				data = int(dataLine.split()[0],16)
				dataid = int(dataidLine.split()[0][-2:],16)

				if not dataid in columns:
					continue

				parsedData[columns.index(dataid)] += str(data)+c

				previousLine = dataLine

			for pd in parsedData:
				of.write(pd+'\n')

	elapsedTime = time() - initialTime
	print('File written to',outfilename)
	print(round(elapsedTime,3),'seconds taken to parse.')
	# input('check parsed file')
	return outfilename

# -----------------------------------------------------------------
# create 2D histogram, where histogram height is displayed as color

def readParsedFile(filename,xcol,ycol):
	numSTDs = 4
	with open(filename) as f:
		for i in range(xcol):
			trash = f.readline()

		xList = f.readline().split(',')[:-1]
		yList = f.readline().split(',')[:-1]

		xList = [int(x) for x in xList]
		yList = [int(x) for x in yList]

	return xList, yList

def histogram_2d(inputfilename,nbins,figureTitle,stds,xcol,ycol,detector):

	FILEEXTENSIONLENGTH = 4
	DEFAULTSTDS = 5

	figureName = inputfilename[:-FILEEXTENSIONLENGTH]+'_'+detector+'_plot.png'

	x, y = readParsedFile(inputfilename,xcol,ycol)

	stdX = np.std(x)
	meanX = np.mean(x)
	maxX = meanX + (stdX * stds)
	minX = meanX - (stdX * stds)
	# maxX = 3000
	# minX = 0

	stdY = np.std(y)
	meanY = np.mean(y)
	maxY = meanY + (stdY * stds)
	minY = meanY - (stdY * stds)
	# maxY = 3000
	# minY = 0

	trimmedX = []
	trimmedY = []
	for i, j in zip(x,y):
		if i < minX or i > maxX or j < minY or j > maxY:
			continue
		trimmedX.append(i)
		trimmedY.append(j)

	H, xedges, yedges = np.histogram2d(trimmedX, trimmedY, bins = nbins)

	H = np.rot90(H)
	H = np.flipud(H)

	Hmasked = np.ma.masked_where(H==0,H)

	fig = plt.figure()
	plt.set_cmap("spectral")
	plt.pcolormesh(xedges,yedges,Hmasked)
	plt.ylabel('TAC')
	plt.xlabel('Amplitude')
	plt.title(figureTitle)
	cbar = plt.colorbar()

	plt.savefig(figureName)
	plt.close(fig)
	print('Figure saved as', figureName)