text:
Architecture
=============

## App Startup ##

The `App.main` entrypoint receives 2 input arguments:
* Source = simple | console | (cosmos | cosmosdb) | kafka
* Target = console | (cosmos | cosmosdb) | (mongo | mongodb) | kafka

The program initializes the following objects:
* DataSource
* DataTarget
* Storage

Then it calls the Connector object.

## Connector ##

Connector has 2 important methods:

* setup: receive the resources and create a job per source partition
* sync: start the synchronization using individual threads per job

## SyncJob ##

The syncJob implements the loop that retrieves message from the source and
send it to the target. It could be represented as:

```
while(true) {
    messages = source.readMessages();

    for (DataMessage msg : messages) {
        target.process(msg);
    }
}
```

## Data Flow ##

### Data Source ###

`DataSource` is the interface that abstract the resources that generate data.
If the resource has multiple partition, then it should return a corresponding list of partitions. This signals the connector to create multiple jobs to be
run in multiple threads.

``` java
public interface DataSource {
    void init();
    List<Partition> listPartition();
    List<DataMessage> readMessages(Partition partition);
    void close();
}
```

The main method is `readMessages`, which return a batch of messages.

Classes implementing DataSource:
* `SimpleSource`
* `ConsoleSource`
* `CosmosDBSource`
* `KafkaSource`

### Data Target ###

`DataTarget` is the interface that abstract the resources that consume data.

``` java
public interface DataTarget {
    void init();
    void process(DataMessage message);
    void close();
}
```

The main method is `process`, which receives a single message to be processed.

Classes implementing DataSource:
* `ConsoleTarget`
* `CosmosDBTarget`
* `MongoTarget`
* `KafkaTarget`

### Data Message ###

`DataMessage` is a simple interface that messages should implement.
This allows the message to be stored in different formats and at the same time
to provide a common `getContent` method for the consumers (data targets).

``` java
public interface DataMessage {
    String getContent();
}
```

### Transform ###
`Transform` is a simple interface that can be used when is necessary to transform the message before save it to the target.
A good sample of that is the transformation made for MongoDB in 'CosmosDBMessageTransform' where we change from Json to Bson.

```
 public Document transform(DataMessage message) {

        String content = message.getContent();

        DBObject obj = (DBObject) BasicDBObject.parse(content);

        Document doc = (Document)navigateObject(obj);

        return doc;
    }
```


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TwitterLikeSystem.Models
{

    public class Comment
    {
        public int Id { get; set; }

        public string AuthorId { get; set; }

        public ApplicationUser Author { get; set; }

        public string Content { get; set; }

        public int TwitId { get; set; }

        public virtual Twit Twit { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class produccion_model extends CI_Model
{
    const categoria = 'sys_categoria_producto';
    const enviosTable = 'sys_envios_materiales';
    const catalogoMateriales = 'sys_catalogo_inventario_sucursal';
    const intEmpleados = 'sys_sucursal_int_usuarios';

    public function __construct()
    {
        parent::__construct();

    }

	public function getCentroProduccion()
    {
         $query = $this->db->query('Select * from sys_sucursal s
			where s.centro_produccion = 1');
         //echo $this->db->queries[0];
        return $query->result();

    }

    public function getAllSucursales()
    {
         $query = $this->db->query('Select * from sys_sucursal s where s.centro_produccion = 0');
         //echo $this->db->queries[0];
        return $query->result();

    }

    public function getAllUnidadMedida()
    {
         $query = $this->db->query('select * from  sys_unidad_medida');
         //echo $this->db->queries[0];
        return $query->result();

    }

    public function listEmpleadosCP($cpID)
    {
         $query = $this->db->query('Select su.id, u.id_usuario, u.nombres, u.apellidos, u.telefono, u.celular, u.direccion
          from sr_usuarios u
        inner join sys_sucursal_int_usuarios su ON su.id_usuario = u.id_usuario
        inner join sys_sucursal s ON s.id_sucursal = su.id_sucursal
        where s.id_sucursal ='.$cpID);
         //echo $this->db->queries[0];
        return $query->result();

    }

    public function getCentroProducion()
    {
         $query = $this->db->query('Select * from sys_sucursal s
		 where s.centro_produccion = 1');
         //echo $this->db->queries[0];
        return $query->result();

    }

     public function inventarioBySucursalDetall($cpID)
    {
        $query = $this->db->query('Select * from sys_catalogo_inventario_sucursal cis
        Inner join sys_catalogo_materiales cm ON cis.codigo_meterial = cm.codigo_material
        inner join sys_categoria_materia_prima cmp ON cmp.id_categoria_materia = cm.id_categoria_material
        inner join sys_sucursal s ON cis.id_sucursal = s.id_sucursal
        inner join sys_unidad_medida u ON u.id_unidad_medida = cm.id_unidad_medida
        inner join sys_tipo_unidad_medida tum ON tum.id_tipo_unidad_medida = u.id_tipo_unidad_medida
        where cis.id_sucursal ='.@$cpID.' group by cis.id_inventario_sucursal');
         //echo $this->db->queries[0];
        return $query->result();

    }

    public function getListaEviosByCP($cpID)
    {
         $query = $this->db->query('SELECT em.id_envio_materiales, em.codigo_envio, em.sucursal_enviado_id, em.cantidad, em.estatus, s.id_sucursal, s.nombre_sucursal, um.nombre_unidad_medida, cm.nombre_matarial,em.fecha_registro
          FROM sys_envios_materiales em
          inner join sys_catalogo_materiales cm ON cm.codigo_material = em.codigo_material
          INNER JOIN sys_sucursal s ON s.id_sucursal = em.sucursal_enviado_id
          INNER JOIN sys_unidad_medida um ON um.id_unidad_medida = em.unidad_medida
          WHERE em.cproduccion_id = '.$cpID.'
          group by em.codigo_envio');
         //echo $this->db->queries[3];
        return $query->result();

    }

    public function getSucursales($codigoMaterial)
    {
         $query = $this->db->query('Select s.id_sucursal, s.nombre_sucursal
          from sys_sucursal s
          inner join sys_catalogo_inventario_sucursal cis ON cis.id_sucursal = s.id_sucursal
          where s.centro_produccion = 0 and cis.codigo_meterial = "'.$codigoMaterial.'"
          group by s.id_sucursal');
         //echo $this->db->queries[0];
        return $query->result();

    }
    public function getUnidadMedida($tipoUnidad)
    {
         $query = $this->db->query('Select u.id_unidad_medida, u.nombre_unidad_medida
          from sys_unidad_medida u
          where  u.id_tipo_unidad_medida ='.@$tipoUnidad);
         //echo $this->db->queries[0];
        return $query->result();

    }

    public function getDataMaterial($idSucursalMaterial)
    {
         $query = $this->db->query('Select cis.id_inventario_sucursal, cis.id_sucursal, cis.codigo_meterial, s.nombre_sucursal, cis.total_existencia, um.nombre_unidad_medida, um.id_unidad_medida
          from sys_catalogo_inventario_sucursal cis
            inner join sys_catalogo_materiales cm on cm.codigo_material = cis.codigo_meterial
            inner join sys_unidad_medida um ON um.id_unidad_medida = cm.id_unidad_medida
                inner join sys_sucursal s ON s.id_sucursal =cis.id_sucursal
            where cis.id_inventario_sucursal ='.$idSucursalMaterial);
         //echo $this->db->queries[0];
        return $query->result_array();

    }

    public function saveEnvio($envio)
    {
        $dateNow = date("Y-m-d h:i:s");

        $envios = array(
            'codigo_material'    => $envio['codigoMaterial'],
            'sucursal_enviado_id'    => $envio['sucursalId'],
            'cproduccion_id'    => $envio['idCproduccion'],
            'cantidad'=> $envio['catindadEnvio'],
            'unidad_medida'    => $envio['unidadMedida'],
            'usuario_registro_envio'    => $envio['userID'],
            'estatus'    => 3,
            'fecha_registro'    => $dateNow
             );

        $dataInsert = $this->db->insert(self::enviosTable,$envios);
        if($dataInsert)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public function saveEnvioDos($envio)
    {
        $dateNow = date("Y-m-d h:i:s");
        $codigoEnvio = date("Y-mdhi");

       $envio = json_decode($_POST['data']);
       //var_dump($envio);
       foreach ($envio as $data)
       {
         $envios = array(
            'codigo_envio'    => $codigoEnvio,
            'codigo_material'    => $data->material,
            'sucursal_enviado_id'    => $data->sucursalEnvio,
            'cproduccion_id'    => $data->cproduccionID,
            'cantidad'=> $data->cantidadPorcion,
            'cantidad_medida_porcion'=> $data->medidaPorcion,
            'unidad_medida'    => $data->unidaMedida,
            'usuario_registro_envio'    => $data->userID,
            'estatus'    => 1,
            'fecha_envio'    => $data->fechaEnvio,
            'fecha_vencimiento_material'    => $data->vencimiento,
            'fecha_registro'    => $dateNow
             );

        $dataInsert = $this->db->insert(self::enviosTable,$envios);
       }

    }

    public function UpdateExistencia($envio)
    {
        //var_dump($envio);
        $datoSave = $envio['maximo'] - $envio['catindadEnvio'];
        $data = array(
            'total_existencia'   => $datoSave,

        );
        $this->db->where('id_inventario_sucursal', $envio['idInventarioMaterial']);
        $this->db->update(self::catalogoMateriales,$data);
    }

    public function getEmpleadoById($empleadoID)
    {
         $query = $this->db->query('Select * from sr_usuarios  u where u.id_usuario ='.$empleadoID);
         //echo $this->db->queries[0];
        return $query->result();

    }

    public function getEnvioById($envioID)
    {
         $query = $this->db->query('select em.id_envio_materiales, em.codigo_material, em.sucursal_enviado_id, em.cproduccion_id, em.cantidad, em.unidad_medida, em.usuario_registro_envio, em.comentario_envio, em.estatus, em.fecha_registro, cm.nombre_matarial, s.nombre_sucursal, sem.nombre_estatus, um.nombre_unidad_medida
            from sys_envios_materiales em
            inner join sys_catalogo_materiales cm ON cm.codigo_material = em.codigo_material
            inner join sys_sucursal s ON s.id_sucursal = em.sucursal_enviado_id
            inner join sys_estatus_meteriales sem ON sem.id_estatus = em.estatus
            inner join sys_unidad_medida um ON um.id_unidad_medida = em.unidad_medida
            where em.id_envio_materiales ='.@$envioID);
         //echo $this->db->queries[0];
        return $query->result();

    }

    public function delete_empleado($datos)
    {
         $data = array(
            'id' => $datos['empleadoID']
        );
        $this->db->delete(self::intEmpleados, $data);
    }

    public function getCatalogoMateriales()
    {
        $searchTerm = $_GET['term'];
        //echo $_GET;
        $query = $this->db->query("Select  cm.nombre_matarial, cm.codigo_material
        from sys_catalogo_materiales cm
        inner join sys_catalogo_inventario_sucursal cis ON cis.codigo_meterial = cm.codigo_material
        where cm.nombre_matarial LIKE '%".$searchTerm."%' and cis.id_sucursal =1");
         //echo $this->db->queries[0];
         return $query->result_array();

    }

}
/*
 * end of application/models/consultas_model.php
 */


text:
using System;
using System.Diagnostics;
using System.Resources;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using StrawhatNet.Samples.LongListSelectorPaging.Resources;

namespace StrawhatNet.Samples.LongListSelectorPaging
{
    public partial class App : Application
    {
        /// <summary>
        /// Phone アプリケーションのルート フレームへの容易なアクセスを提供します。
        /// </summary>
        /// <returns>Phone アプリケーションのルート フレームです。</returns>
        public static PhoneApplicationFrame RootFrame { get; private set; }

        /// <summary>
        /// Application オブジェクトのコンストラクターです。
        /// </summary>
        public App()
        {
            // キャッチできない例外のグローバル ハンドラーです。
            UnhandledException += Application_UnhandledException;

            // 標準 XAML の初期化
            InitializeComponent();

            // Phone 固有の初期化
            InitializePhoneApplication();

            // 言語表示の初期化
            InitializeLanguage();

            // デバッグ中にグラフィックスのプロファイル情報を表示します。
            if (Debugger.IsAttached)
            {
                // 現在のフレーム レート カウンターを表示します。
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // 各フレームで再描画されているアプリケーションの領域を表示します。
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // 試験的な分析視覚化モードを有効にします。
                // これにより、色付きのオーバーレイを使用して、GPU に渡されるページの領域が表示されます。
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // アプリケーションのアイドル状態の検出を無効にして、デバッガーの実行中に画面が
                // オフにならないようにします。
                // 注意: これはデバッグ モードのみで使用してください。ユーザーが電話を使用していないときに、ユーザーのアイドル状態の検出を無効にする
                // アプリケーションが引き続き実行され、バッテリ電源が消耗します。
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }

        }

        // (たとえば、[スタート] メニューから) アプリケーションが起動するときに実行されるコード
        // このコードは、アプリケーションが再アクティブ化済みの場合には実行されません
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
        }

        // アプリケーションがアクティブになった (前面に表示された) ときに実行されるコード
        // このコードは、アプリケーションの初回起動時には実行されません
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
        }

        // アプリケーションが非アクティブになった (バックグラウンドに送信された) ときに実行されるコード
        // このコードは、アプリケーションの終了時には実行されません
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
        }

        // (たとえば、ユーザーが戻るボタンを押して) アプリケーションが終了するときに実行されるコード
        // このコードは、アプリケーションが非アクティブになっているときには実行されません
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
        }

        // ナビゲーションに失敗した場合に実行されるコード
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // ナビゲーションに失敗しました。デバッガーで中断します。
                Debugger.Break();
            }
        }

        // ハンドルされない例外の発生時に実行されるコード
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // ハンドルされない例外が発生しました。デバッガーで中断します。
                Debugger.Break();
            }
        }

        #region Phone アプリケーションの初期化

        // 初期化の重複を回避します
        private bool phoneApplicationInitialized = false;

        // このメソッドに新たなコードを追加しないでください
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;

            // フレームを作成しますが、まだ RootVisual に設定しないでください。これによって、アプリケーションがレンダリングできる状態になるまで、
            // スプラッシュ スクリーンをアクティブなままにすることができます。
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // ナビゲーション エラーを処理します
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // 次のナビゲーションでバックスタックをクリアして、
            RootFrame.Navigated += CheckForResetNavigation;

            // 再初期化しないようにします
            phoneApplicationInitialized = true;
        }

        // このメソッドに新たなコードを追加しないでください
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // ルート visual を設定してアプリケーションをレンダリングできるようにします
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // このハンドラーは必要なくなったため、削除します
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        private void CheckForResetNavigation(object sender, NavigationEventArgs e)
        {
            // アプリが 'リセット' ナビゲーションを受け取った場合、チェックする必要があります
            // ページ スタックをリセットする必要があるかどうかを確認するためのリセット要求を処理します
            if (e.NavigationMode == NavigationMode.Reset)
                RootFrame.Navigated += ClearBackStackAfterReset;
        }

        private void ClearBackStackAfterReset(object sender, NavigationEventArgs e)
        {
            // もう一度呼び出されないようにイベントの登録を解除します
            RootFrame.Navigated -= ClearBackStackAfterReset;

            // '新しい' (次の) ナビゲーションおよび '更新' ナビゲーションのスタックのみをクリアします
            if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh)
                return;

            // UI の一貫性を維持するため、ページ スタック全体をクリアします
            while (RootFrame.RemoveBackEntry() != null)
            {
                ; // 何も実行しません
            }
        }

        #endregion

        // アプリのフォントと方向をそのローカライズされたリソース文字列で定義されたように初期化します。
        //
        // アプリケーションのフォントがそのサポートされる言語と一致し、各言語の FlowDirection がその従来の
        // 方向に従うようにするには、各 resx ファイルで ResourceLanguage と ResourceFlowDirection を
        // 初期化して、これらの値をそのファイルのカルチャと一致させる
        // 必要があります。例:
        //
        // AppResources.es-ES.resx
        //    ResourceLanguage の値は "es-ES" にする必要があります
        //    ResourceFlowDirection の値は "LeftToRight" にする必要があります
        //
        // AppResources.ar-SA.resx
        //     ResourceLanguage の値は "ar-SA" にする必要があります
        //     ResourceFlowDirection の値は "RightToLeft" にする必要があります
        //
        // Windows Phone アプリのローカライズの詳細については、http://go.microsoft.com/fwlink/?LinkId=262072 を参照してください。
        //
        private void InitializeLanguage()
        {
            try
            {
                // サポートされている各言語の ResourceLanguage リソース文字列で定義された
                // 表示言語と一致するようにフォントを設定します。
                //
                // 電話の表示言語がサポートされていない場合は、ニュートラル
                // 言語のフォントにフォールバックします。
                //
                // コンパイラ エラーが発生すると、ResourceLanguage がリソース ファイル
                // からなくなります。
                RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage);

                // サポートされる各言語の ResourceFlowDirection リソース文字列に基づいて、
                // ルート フレームのすべての要素の FlowDirection を
                // 設定します。
                //
                // コンパイラ エラーが発生すると、ResourceFlowDirection がリソース ファイル
                // からなくなります。
                FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection);
                RootFrame.FlowDirection = flow;
            }
            catch
            {
                // ここで例外が発生した場合、その原因は、
                // ResourceLangauge がサポートされている言語コードに正しく設定されていないこと、
                // または ResourceFlowDirection が LeftToRight または RightToLeft 以外の
                // 値に設定されていることである可能性があります。

                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                throw;
            }
        }
    }
}


text:
from django.template import Context, Template
from django.utils.safestring import SafeData

from djangocms_helper.base_test import BaseTestCase

from djangocms_text_ckeditor.fields import HTMLFormField
from djangocms_text_ckeditor.test_app.forms import SimpleTextForm
from djangocms_text_ckeditor.test_app.models import SimpleText

class HtmlFieldTestCase(BaseTestCase):

    def test_html_form_field(self):
        html_field = HTMLFormField()
        self.assertTrue(isinstance(html_field.clean("some text"), SafeData))

class FieldTestCase(BaseTestCase):

    text_normal = '
some non malicious text
'
    text_with_iframe = ('
some non malicious text
'
                        '')
    text_with_iframe_escaped = ('
some non malicious text
<iframe '
                                'src="http://www.w3schools.com"></iframe>')
    text_with_script = ('
some non malicious text
 '
                        '')
    text_with_script_escaped = (u'
some non malicious text
 <script>'
                                u'alert("Hello! I am an alert box!");</script>')

    def test_model_field_text_is_safe(self):
        original = 'Hello
There
'
        template = Template("{{ obj.text }}")
        text = SimpleText.objects.create(text='Hello
There
')
        # Fetching a new instance should now have the string marked
        # as safe.
        text = SimpleText.objects.get(pk=text.pk)
        rendered = template.render(Context({'obj': text}))
        self.assertEqual(original, rendered)

    def test_model_field_sanitized(self):
        obj = SimpleText(text=self.text_normal)
        obj.full_clean()
        obj.save()

        obj = SimpleText.objects.get(pk=obj.pk)

        self.assertEqual(obj.text, self.text_normal)

        obj = SimpleText(text=self.text_with_iframe)
        obj.full_clean()
        obj.save()

        self.assertEqual(obj.text, self.text_with_iframe_escaped)

        obj = SimpleText(text=self.text_with_script)
        obj.full_clean()
        obj.save()

        self.assertEqual(obj.text, self.text_with_script_escaped)

    def test_form_field_sanitized(self):
        form = SimpleTextForm(data={'text': self.text_normal})
        self.assertTrue(form.is_valid())

        self.assertEqual(form.cleaned_data['text'], self.text_normal)

        form = SimpleTextForm(data={'text': self.text_with_iframe})
        self.assertTrue(form.is_valid())

        self.assertEqual(form.cleaned_data['text'], self.text_with_iframe_escaped)

        form = SimpleTextForm(data={'text': self.text_with_script})
        self.assertTrue(form.is_valid())

        self.assertEqual(form.cleaned_data['text'], self.text_with_script_escaped)


text:
package org.kie.workbench.common.widgets.metadata.client;

import javax.inject.Inject;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.IsWidget;
import org.jboss.errai.ui.client.local.spi.TranslationService;
import org.kie.workbench.common.widgets.client.resources.i18n.CommonConstants;
import org.kie.workbench.common.widgets.client.source.ViewDRLSourceWidget;
import org.kie.workbench.common.widgets.metadata.client.resources.i18n.KieEditorConstants;
import org.kie.workbench.common.widgets.metadata.client.widget.OverviewWidgetPresenter;
import org.uberfire.client.views.pfly.multipage.MultiPageEditorImpl;
import org.uberfire.client.views.pfly.multipage.PageImpl;
import org.uberfire.client.workbench.widgets.multipage.MultiPageEditor;
import org.uberfire.ext.editor.commons.client.BaseEditorView;

public class KieEditorWrapperViewImpl
        extends MultiPageEditorImpl
        implements KieEditorWrapperView {

    protected static final int EDITOR_TAB_INDEX = 0;
    protected static final int OVERVIEW_TAB_INDEX = 1;

    private KieEditorWrapperPresenter presenter;

    @Inject
    private TranslationService translationService;

    @Override
    public void setPresenter(KieEditorWrapperPresenter presenter) {

        this.presenter = presenter;
    }

    @Override
    public MultiPageEditor getMultiPage() {
        return this;
    }

    @Override
    public void addMainEditorPage(IsWidget baseView) {
        addPage(new PageImpl(baseView,
                             CommonConstants.INSTANCE.EditTabTitle()) {
            @Override
            public void onFocus() {
                presenter.onEditTabSelected();
            }

            @Override
            public void onLostFocus() {
                presenter.onEditTabUnselected();
            }
        });
    }

    @Override
    public void addOverviewPage(final OverviewWidgetPresenter overviewWidget,
                                final Command onFocus) {
        addPage(new PageImpl(overviewWidget,
                             CommonConstants.INSTANCE.Overview()) {
            @Override
            public void onFocus() {
                onFocus.execute();
                presenter.onOverviewSelected();
            }

            @Override
            public void onLostFocus() {

            }
        });
    }

    @Override
    public void addSourcePage(ViewDRLSourceWidget sourceWidget) {
        addPage(new PageImpl(sourceWidget,
                             CommonConstants.INSTANCE.SourceTabTitle()) {
            @Override
            public void onFocus() {
                presenter.onSourceTabSelected();
            }

            @Override
            public void onLostFocus() {

            }
        });
    }

    @Override
    public String getNotAllowedSavingMessage() {
        return translationService.format(KieEditorConstants.NotAllowedSaving);
    }

    @Override
    public String getUnexpectedErrorWhileSavingMessage() {
        return translationService.format(KieEditorConstants.UnexpectedErrorWhileSaving);
    }

    @Override
    public void addImportsTab(IsWidget importsWidget) {
        addWidget(importsWidget,
                  CommonConstants.INSTANCE.DataObjectsTabTitle());
    }

    @Override
    public boolean isEditorTabSelected() {
        return selectedPage() == EDITOR_TAB_INDEX;
    }

    @Override
    public boolean isOverviewTabSelected() {
        return selectedPage() == OVERVIEW_TAB_INDEX;
    }

    @Override
    public int getSelectedTabIndex() {
        return selectedPage();
    }

    @Override
    public void selectOverviewTab() {
        setSelectedTab(OVERVIEW_TAB_INDEX);
    }

    @Override
    public void selectEditorTab() {
        setSelectedTab(EDITOR_TAB_INDEX);
    }

    @Override
    public void setSelectedTab(int tabIndex) {
        selectPage(tabIndex);
    }
}


text:
module.exports = require('/application/base/class').extend(function() {
	/* Require
	-------------------------------*/
	var $ = jQuery;

	/* Constants
	-------------------------------*/
	/* Public.Properties
	-------------------------------*/
	/* Protected Properties
	-------------------------------*/
	/* Private Properties
	-------------------------------*/
	/* Magic
	-------------------------------*/
	/* Public.Methods
	-------------------------------*/
	this.response = function(request) {
		//if no ID
		if(!request.variables[0]) {
			//setup an error
			this.Controller().notify('Error', 'No ID set', 'error');
			window.history.back();
			return this;
		}

		var id 	= request.variables[0];
		this.Controller().trigger('{{name}}-remove', id, request, this);
		return this;
	};

	/* Protected Methods
	-------------------------------*/
	/* Private Methods
	-------------------------------*/
}).singleton();


text:
import { Component } from '@angular/core';
import { MD_BUTTON_DIRECTIVES } from '@angular2-material/button';
import { MD_GRID_LIST_DIRECTIVES } from '@angular2-material/grid-list';
import { MdToolbar } from '@angular2-material/toolbar';
import { MdCheckbox } from '@angular2-material/checkbox';
import { CQRSApiService } from './cqrsng2.service';
import { Tweet } from './cqrsng2.tweet';

@Component({
  moduleId: module.id,
  selector: 'cqrsng2-app',
  templateUrl: 'cqrsng2.component.html',
  styleUrls: ['cqrsng2.component.css'],
  directives: [MD_BUTTON_DIRECTIVES, MD_GRID_LIST_DIRECTIVES, MdToolbar, MdCheckbox],
  providers: [CQRSApiService]
})

export class CQRSng2AppComponent {

  title = 'CQRS Demo';
  tiles: any[] = [];
  errorMessage: string;
  autoRefreshEnabled: any;

  constructor(private _service: CQRSApiService) {
    this.autoRefresh();
  }

  getTweets() {
    this._service.getTweets()
                    .subscribe(
                     tweets => {

                       tweets.forEach(tweet => {

                          var tweetExists: boolean = false;

                          for (var index = 0; index < this.tiles.length; index++) {
                              var element = this.tiles[index];

                              if (element.url === tweet.media_url) {
                                tweetExists = true;
                              }
                          }

                          if (!tweetExists) {
                            var tile: any = { url: tweet.media_url };
                            this.tiles.unshift(tile);
                          }

                       });

                      },
                     error =>  this.errorMessage = <any>error);
  }

 refresh() {
    this.getTweets();
  }

  autoRefresh() {
    setInterval(() => {
        if (this.autoRefreshEnabled && this.autoRefreshEnabled.checked) {
          this.refresh();
        }
      }, 3000);
  }

  ngOnInit() {
    this.getTweets();
  }
}


text:
namespace {

// Predicator for sorting ImageSkiaRep by scale factor.
bool ImageRepScaleFactorCompare(const gfx::ImageSkiaRep& rep1,
                                const gfx::ImageSkiaRep& rep2) {
  return rep1.scale_factor() < rep2.scale_factor();
}

// Gets cache key based on |image| contents and desired |size|.
std::string GetKey(const gfx::ImageSkia& image, const gfx::Size& size) {
  gfx::ImageSkia::ImageSkiaReps image_reps = image.image_reps();
  DCHECK_GT(image_reps.size(), 0u);

  std::sort(image_reps.begin(), image_reps.end(), &ImageRepScaleFactorCompare);

  base::MD5Context ctx;
  base::MD5Init(&ctx);
  for (gfx::ImageSkia::ImageSkiaReps::const_iterator it = image_reps.begin();
       it != image_reps.end(); ++it) {
    const SkBitmap& bitmap = it->sk_bitmap();
    SkAutoLockPixels image_lock(bitmap);

    base::MD5Update(
        &ctx,
        base::StringPiece(reinterpret_cast<const char*>(bitmap.getPixels()),
                          bitmap.getSize()));
  }

  base::MD5Digest digest;
  base::MD5Final(&digest, &ctx);

  return MD5DigestToBase16(digest) + "." + size.ToString();
}

}  // namespace

namespace app_list {

// static
IconCache* IconCache::instance_ = NULL;

// static
void IconCache::CreateInstance() {
  DCHECK(!instance_);
  instance_ = new IconCache;
}

// static
void IconCache::DeleteInstance() {
  DCHECK(instance_);
  delete instance_;
  instance_ = NULL;
}

// static
IconCache* IconCache::GetInstance() {
  DCHECK(instance_);
  return instance_;
}

void IconCache::MarkAllEntryUnused() {
  for (Cache::iterator i = cache_.begin(); i != cache_.end(); ++i)
    i->second.used = false;
}

void IconCache::PurgeAllUnused() {
  for (Cache::iterator i = cache_.begin(); i != cache_.end();) {
    Cache::iterator current(i);
    ++i;
    if (!current->second.used)
      cache_.erase(current);
  }
}

bool IconCache::Get(const gfx::ImageSkia& src,
                    const gfx::Size& size,
                    gfx::ImageSkia* processed) {
  Cache::iterator it = cache_.find(GetKey(src, size));
  if (it == cache_.end())
    return false;

  it->second.used = true;

  if (processed)
    *processed = it->second.image;
  return true;
}

void IconCache::Put(const gfx::ImageSkia& src,
                    const gfx::Size& size,
                    const gfx::ImageSkia& processed) {
  const std::string key = GetKey(src, size);
  cache_[key].image = processed;
  cache_[key].used = true;
}

IconCache::IconCache() {
}

IconCache::~IconCache() {
}

}  // namespace app_list


text:
.class Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;
.super Landroid/app/AlertDialog;
.source "ClippedDataPickerDialog.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/sec/ClippedDataPickerDialog;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = "ClearConfirmDialog"
.end annotation

# instance fields
.field private mContext:Landroid/content/Context;

.field private mListener:Landroid/content/DialogInterface$OnClickListener;

.field final synthetic this$0:Lcom/android/server/sec/ClippedDataPickerDialog;

# direct methods
.method public constructor <init>(Lcom/android/server/sec/ClippedDataPickerDialog;Landroid/content/Context;)V
    .locals 1
    .parameter
    .parameter "context"

    .prologue
    .line 229
    iput-object p1, p0, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->this$0:Lcom/android/server/sec/ClippedDataPickerDialog;

    .line 230
    const/4 v0, 0x4

    invoke-direct {p0, p2, v0}, Landroid/app/AlertDialog;-><init>(Landroid/content/Context;I)V

    .line 231
    iput-object p2, p0, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->mContext:Landroid/content/Context;

    .line 232
    return-void
.end method

.method static synthetic access$400(Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;)Landroid/content/Context;
    .locals 1
    .parameter "x0"

    .prologue
    .line 224
    iget-object v0, p0, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->mContext:Landroid/content/Context;

    return-object v0
.end method

# virtual methods
.method protected onCreate(Landroid/os/Bundle;)V
    .locals 5
    .parameter "savedInstanceState"

    .prologue
    .line 236
    new-instance v2, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog$1;

    invoke-direct {v2, p0}, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog$1;-><init>(Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;)V

    iput-object v2, p0, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->mListener:Landroid/content/DialogInterface$OnClickListener;

    .line 298
    const v2, 0x1040748

    invoke-virtual {p0, v2}, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->setTitle(I)V

    .line 299
    iget-object v2, p0, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->mContext:Landroid/content/Context;

    const v3, 0x104074e

    invoke-virtual {v2, v3}, Landroid/content/Context;->getString(I)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {p0, v2}, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->setMessage(Ljava/lang/CharSequence;)V

    .line 301
    const/4 v2, -0x1

    iget-object v3, p0, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->mContext:Landroid/content/Context;

    const v4, 0x104000a

    invoke-virtual {v3, v4}, Landroid/content/Context;->getString(I)Ljava/lang/String;

    move-result-object v3

    iget-object v4, p0, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->mListener:Landroid/content/DialogInterface$OnClickListener;

    invoke-virtual {p0, v2, v3, v4}, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->setButton(ILjava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)V

    .line 302
    const/4 v2, -0x2

    iget-object v3, p0, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->mContext:Landroid/content/Context;

    const/high16 v4, 0x104

    invoke-virtual {v3, v4}, Landroid/content/Context;->getString(I)Ljava/lang/String;

    move-result-object v3

    iget-object v4, p0, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->mListener:Landroid/content/DialogInterface$OnClickListener;

    invoke-virtual {p0, v2, v3, v4}, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->setButton(ILjava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)V

    .line 304
    invoke-virtual {p0}, Lcom/android/server/sec/ClippedDataPickerDialog$ClearConfirmDialog;->getWindow()Landroid/view/Window;

    move-result-object v1

    .line 305
    .local v1, theWindow:Landroid/view/Window;
    invoke-virtual {v1}, Landroid/view/Window;->getAttributes()Landroid/view/WindowManager$LayoutParams;

    move-result-object v0

    .line 306
    .local v0, lp:Landroid/view/WindowManager$LayoutParams;
    const/16 v2, 0x7d8

    iput v2, v0, Landroid/view/WindowManager$LayoutParams;->type:I

    .line 307
    invoke-virtual {v1, v0}, Landroid/view/Window;->setAttributes(Landroid/view/WindowManager$LayoutParams;)V

    .line 309
    invoke-super {p0, p1}, Landroid/app/AlertDialog;->onCreate(Landroid/os/Bundle;)V

    .line 310
    return-void
.end method


text:
import { NgModule } from '@angular/core';
import { SharedModule } from 'app/shared';
import { TransactionSearchComponent } from './transaction-search.component';
import { TransactionSearchContainerComponent } from './transaction-search-container.component';
import { TransactionSearchInteractionService } from './transaction-search-interaction.service';

@NgModule({
    declarations: [
        TransactionSearchComponent,
        TransactionSearchContainerComponent
    ],
    imports: [
        SharedModule
    ],
    exports: [
        TransactionSearchContainerComponent
    ],
    providers: [
        TransactionSearchInteractionService
    ]
})
export class TransactionSearchModule { }


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.placement;

import org.apache.commons.collections.IteratorUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.yarn.api.records.ResourceRequest;
import org.apache.hadoop.yarn.api.records.SchedulingRequest;
import org.apache.hadoop.yarn.exceptions.SchedulerInvalidResoureRequestException;
import org.apache.hadoop.yarn.server.resourcemanager.RMContext;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AppSchedulingInfo;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNode;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.SchedulingMode;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.ApplicationSchedulingConfig;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.ContainerRequest;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.PendingAsk;
import org.apache.hadoop.yarn.server.scheduler.SchedulerRequestKey;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * This is an implementation of the {@link AppPlacementAllocator} that takes
 * into account locality preferences (node, rack, any) when allocating
 * containers.
 */
public class LocalityAppPlacementAllocator <N extends SchedulerNode>
    extends AppPlacementAllocator<N> {
  private static final Log LOG =
      LogFactory.getLog(LocalityAppPlacementAllocator.class);

  private final Map<String, ResourceRequest> resourceRequestMap =
      new ConcurrentHashMap<>();
  private volatile String primaryRequestedPartition =
      RMNodeLabelsManager.NO_LABEL;
  private MultiNodeSortingManager<N> multiNodeSortingManager = null;
  private String multiNodeSortPolicyName;

  private final ReentrantReadWriteLock.ReadLock readLock;
  private final ReentrantReadWriteLock.WriteLock writeLock;

  public LocalityAppPlacementAllocator() {
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    readLock = lock.readLock();
    writeLock = lock.writeLock();
  }

  @SuppressWarnings("unchecked")
  @Override
  public void initialize(AppSchedulingInfo appSchedulingInfo,
      SchedulerRequestKey schedulerRequestKey, RMContext rmContext) {
    super.initialize(appSchedulingInfo, schedulerRequestKey, rmContext);
    multiNodeSortPolicyName = appSchedulingInfo
        .getApplicationSchedulingEnvs().get(
            ApplicationSchedulingConfig.ENV_MULTI_NODE_SORTING_POLICY_CLASS);
    multiNodeSortingManager = (MultiNodeSortingManager<N>) rmContext
        .getMultiNodeSortingManager();
    if (LOG.isDebugEnabled()) {
      LOG.debug(
          "nodeLookupPolicy used for " + appSchedulingInfo
              .getApplicationId()
              + " is " + ((multiNodeSortPolicyName != null) ?
              multiNodeSortPolicyName :
              ""));
    }
  }

  @Override
  @SuppressWarnings("unchecked")
  public Iterator<N> getPreferredNodeIterator(
      CandidateNodeSet<N> candidateNodeSet) {
    // Now only handle the case that single node in the candidateNodeSet
    // TODO, Add support to multi-hosts inside candidateNodeSet which is passed
    // in.

    N singleNode = CandidateNodeSetUtils.getSingleNode(candidateNodeSet);
    if (singleNode != null) {
      return IteratorUtils.singletonIterator(singleNode);
    }

    // singleNode will be null if Multi-node placement lookup is enabled, and
    // hence could consider sorting policies.
    return multiNodeSortingManager.getMultiNodeSortIterator(
        candidateNodeSet.getAllNodes().values(),
        candidateNodeSet.getPartition(),
        multiNodeSortPolicyName);
  }

  private boolean hasRequestLabelChanged(ResourceRequest requestOne,
      ResourceRequest requestTwo) {
    String requestOneLabelExp = requestOne.getNodeLabelExpression();
    String requestTwoLabelExp = requestTwo.getNodeLabelExpression();
    // First request label expression can be null and second request
    // is not null then we have to consider it as changed.
    if ((null == requestOneLabelExp) && (null != requestTwoLabelExp)) {
      return true;
    }
    // If the label is not matching between both request when
    // requestOneLabelExp is not null.
    return ((null != requestOneLabelExp) && !(requestOneLabelExp
        .equals(requestTwoLabelExp)));
  }

  private void updateNodeLabels(ResourceRequest request) {
    String resourceName = request.getResourceName();
    if (resourceName.equals(ResourceRequest.ANY)) {
      ResourceRequest previousAnyRequest =
          getResourceRequest(resourceName);

      // When there is change in ANY request label expression, we should
      // update label for all resource requests already added of same
      // priority as ANY resource request.
      if ((null == previousAnyRequest) || hasRequestLabelChanged(
          previousAnyRequest, request)) {
        for (ResourceRequest r : resourceRequestMap.values()) {
          if (!r.getResourceName().equals(ResourceRequest.ANY)) {
            r.setNodeLabelExpression(request.getNodeLabelExpression());
          }
        }
      }
    } else{
      ResourceRequest anyRequest = getResourceRequest(ResourceRequest.ANY);
      if (anyRequest != null) {
        request.setNodeLabelExpression(anyRequest.getNodeLabelExpression());
      }
    }
  }

  @Override
  public PendingAskUpdateResult updatePendingAsk(
      Collection<ResourceRequest> requests,
      boolean recoverPreemptedRequestForAContainer) {
    try {
      this.writeLock.lock();

      PendingAskUpdateResult updateResult = null;

      // Update resource requests
      for (ResourceRequest request : requests) {
        String resourceName = request.getResourceName();

        // Update node labels if required
        updateNodeLabels(request);

        // Increment number of containers if recovering preempted resources
        ResourceRequest lastRequest = resourceRequestMap.get(resourceName);
        if (recoverPreemptedRequestForAContainer && lastRequest != null) {
          request.setNumContainers(lastRequest.getNumContainers() + 1);
        }

        // Update asks
        resourceRequestMap.put(resourceName, request);

        if (resourceName.equals(ResourceRequest.ANY)) {
          String partition = request.getNodeLabelExpression() == null ?
              RMNodeLabelsManager.NO_LABEL :
              request.getNodeLabelExpression();

          this.primaryRequestedPartition = partition;

          //update the applications requested labels set
          appSchedulingInfo.addRequestedPartition(partition);

          PendingAsk lastPendingAsk =
              lastRequest == null ? null : new PendingAsk(
                  lastRequest.getCapability(), lastRequest.getNumContainers());
          String lastRequestedNodePartition =
              lastRequest == null ? null : lastRequest.getNodeLabelExpression();

          updateResult = new PendingAskUpdateResult(lastPendingAsk,
              new PendingAsk(request.getCapability(),
                  request.getNumContainers()), lastRequestedNodePartition,
              request.getNodeLabelExpression());
        }
      }
      return updateResult;
    } finally {
      this.writeLock.unlock();
    }
  }

  @Override
  public PendingAskUpdateResult updatePendingAsk(
      SchedulerRequestKey schedulerRequestKey,
      SchedulingRequest schedulingRequest,
      boolean recoverPreemptedRequestForAContainer)
      throws SchedulerInvalidResoureRequestException {
    throw new SchedulerInvalidResoureRequestException(this.getClass().getName()
        + " not be able to handle SchedulingRequest, there exists a "
        + "ResourceRequest with the same scheduler key=" + schedulerRequestKey
        + ", please send SchedulingRequest with a different allocationId and "
        + "priority");
  }

  @Override
  public Map<String, ResourceRequest> getResourceRequests() {
    return resourceRequestMap;
  }

  private ResourceRequest getResourceRequest(String resourceName) {
    return resourceRequestMap.get(resourceName);
  }

  @Override
  public PendingAsk getPendingAsk(String resourceName) {
    try {
      readLock.lock();
      ResourceRequest request = getResourceRequest(resourceName);
      if (null == request) {
        return PendingAsk.ZERO;
      } else{
        return new PendingAsk(request.getCapability(),
            request.getNumContainers());
      }
    } finally {
      readLock.unlock();
    }

  }

  @Override
  public int getOutstandingAsksCount(String resourceName) {
    try {
      readLock.lock();
      ResourceRequest request = getResourceRequest(resourceName);
      if (null == request) {
        return 0;
      } else{
        return request.getNumContainers();
      }
    } finally {
      readLock.unlock();
    }

  }

  private void decrementOutstanding(SchedulerRequestKey schedulerRequestKey,
      ResourceRequest offSwitchRequest) {
    int numOffSwitchContainers = offSwitchRequest.getNumContainers() - 1;
    offSwitchRequest.setNumContainers(numOffSwitchContainers);

    // Do we have any outstanding requests?
    // If there is nothing, we need to deactivate this application
    if (numOffSwitchContainers == 0) {
      appSchedulingInfo.getSchedulerKeys().remove(schedulerRequestKey);
      appSchedulingInfo.checkForDeactivation();
      resourceRequestMap.remove(ResourceRequest.ANY);
      if (resourceRequestMap.isEmpty()) {
        appSchedulingInfo.removeAppPlacement(schedulerRequestKey);
      }
    }

    appSchedulingInfo.decPendingResource(
        offSwitchRequest.getNodeLabelExpression(),
        offSwitchRequest.getCapability());
  }

  public ResourceRequest cloneResourceRequest(ResourceRequest request) {
    ResourceRequest newRequest = ResourceRequest.clone(request);
    newRequest.setNumContainers(1);
    return newRequest;
  }

  /**
   * The {@link ResourceScheduler} is allocating data-local resources to the
   * application.
   */
  private void allocateRackLocal(SchedulerRequestKey schedulerKey,
      SchedulerNode node, ResourceRequest rackLocalRequest,
      List<ResourceRequest> resourceRequests) {
    // Update future requirements
    decResourceRequest(node.getRackName(), rackLocalRequest);

    ResourceRequest offRackRequest = resourceRequestMap.get(
        ResourceRequest.ANY);
    decrementOutstanding(schedulerKey, offRackRequest);

    // Update cloned RackLocal and OffRack requests for recovery
    resourceRequests.add(cloneResourceRequest(rackLocalRequest));
    resourceRequests.add(cloneResourceRequest(offRackRequest));
  }

  /**
   * The {@link ResourceScheduler} is allocating data-local resources to the
   * application.
   */
  private void allocateOffSwitch(SchedulerRequestKey schedulerKey,
      ResourceRequest offSwitchRequest,
      List<ResourceRequest> resourceRequests) {
    // Update future requirements
    decrementOutstanding(schedulerKey, offSwitchRequest);
    // Update cloned OffRack requests for recovery
    resourceRequests.add(cloneResourceRequest(offSwitchRequest));
  }

  /**
   * The {@link ResourceScheduler} is allocating data-local resources to the
   * application.
   */
  private void allocateNodeLocal(SchedulerRequestKey schedulerKey,
      SchedulerNode node, ResourceRequest nodeLocalRequest,
      List<ResourceRequest> resourceRequests) {
    // Update future requirements
    decResourceRequest(node.getNodeName(), nodeLocalRequest);

    ResourceRequest rackLocalRequest = resourceRequestMap.get(
        node.getRackName());
    decResourceRequest(node.getRackName(), rackLocalRequest);

    ResourceRequest offRackRequest = resourceRequestMap.get(
        ResourceRequest.ANY);
    decrementOutstanding(schedulerKey, offRackRequest);

    // Update cloned NodeLocal, RackLocal and OffRack requests for recovery
    resourceRequests.add(cloneResourceRequest(nodeLocalRequest));
    resourceRequests.add(cloneResourceRequest(rackLocalRequest));
    resourceRequests.add(cloneResourceRequest(offRackRequest));
  }

  private void decResourceRequest(String resourceName,
      ResourceRequest request) {
    request.setNumContainers(request.getNumContainers() - 1);
    if (request.getNumContainers() == 0) {
      resourceRequestMap.remove(resourceName);
    }
  }

  @Override
  public boolean canAllocate(NodeType type, SchedulerNode node) {
    try {
      readLock.lock();
      ResourceRequest r = resourceRequestMap.get(
          ResourceRequest.ANY);
      if (r == null || r.getNumContainers() <= 0) {
        return false;
      }
      if (type == NodeType.RACK_LOCAL || type == NodeType.NODE_LOCAL) {
        r = resourceRequestMap.get(node.getRackName());
        if (r == null || r.getNumContainers() <= 0) {
          return false;
        }
        if (type == NodeType.NODE_LOCAL) {
          r = resourceRequestMap.get(node.getNodeName());
          if (r == null || r.getNumContainers() <= 0) {
            return false;
          }
        }
      }

      return true;
    } finally {
      readLock.unlock();
    }
  }

  @Override
  public boolean canDelayTo(String resourceName) {
    try {
      readLock.lock();
      ResourceRequest request = getResourceRequest(resourceName);
      return request == null || request.getRelaxLocality();
    } finally {
      readLock.unlock();
    }

  }

  @Override
  public boolean precheckNode(SchedulerNode schedulerNode,
      SchedulingMode schedulingMode) {
    // We will only look at node label = nodeLabelToLookAt according to
    // schedulingMode and partition of node.
    String nodePartitionToLookAt;
    if (schedulingMode == SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY) {
      nodePartitionToLookAt = schedulerNode.getPartition();
    } else {
      nodePartitionToLookAt = RMNodeLabelsManager.NO_LABEL;
    }

    return primaryRequestedPartition.equals(nodePartitionToLookAt);
  }

  @Override
  public String getPrimaryRequestedNodePartition() {
    return primaryRequestedPartition;
  }

  @Override
  public int getUniqueLocationAsks() {
    return resourceRequestMap.size();
  }

  @Override
  public void showRequests() {
    for (ResourceRequest request : resourceRequestMap.values()) {
      if (request.getNumContainers() > 0) {
        LOG.debug("\tRequest=" + request);
      }
    }
  }

  @Override
  public ContainerRequest allocate(SchedulerRequestKey schedulerKey,
      NodeType type, SchedulerNode node) {
    try {
      writeLock.lock();

      List<ResourceRequest> resourceRequests = new ArrayList<>();

      ResourceRequest request;
      if (type == NodeType.NODE_LOCAL) {
        request = resourceRequestMap.get(node.getNodeName());
      } else if (type == NodeType.RACK_LOCAL) {
        request = resourceRequestMap.get(node.getRackName());
      } else{
        request = resourceRequestMap.get(ResourceRequest.ANY);
      }

      if (type == NodeType.NODE_LOCAL) {
        allocateNodeLocal(schedulerKey, node, request, resourceRequests);
      } else if (type == NodeType.RACK_LOCAL) {
        allocateRackLocal(schedulerKey, node, request, resourceRequests);
      } else{
        allocateOffSwitch(schedulerKey, request, resourceRequests);
      }

      return new ContainerRequest(resourceRequests);
    } finally {
      writeLock.unlock();
    }
  }

  @Override
  public SchedulingRequest getSchedulingRequest() {
    return null;
  }
}


text:
/*
 * This file is subject to the license found in LICENCE.TXT in the root directory of the project.
 *
 * #SNAPSHOT#
 */
package fr.jayasoft.ivy.url;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import fr.jayasoft.ivy.util.CopyProgressListener;

/**
 * This interface is responsible for handling some URL manipulation
 * (stream opening, downloading, check reachability, ...).
 *
 * @author Xavier Hanin
 *
 */
public interface URLHandler {
    public static class URLInfo {
        private long _contentLength;
        private long _lastModified;
        private boolean _available;

        protected URLInfo(boolean available, long contentLength, long lastModified) {
            _available = available;
            _contentLength = contentLength;
            _lastModified = lastModified;
        }
        public boolean isReachable() {
            return _available;
        }
        public long getContentLength() {
            return _contentLength;
        }
        public long getLastModified() {
            return _lastModified;
        }
    }
    public static final URLInfo UNAVAILABLE = new URLInfo(false, 0,0);

    /**
     * Please prefer getURLInfo when several infos are needed.
     * @param url the url to check
     * @return true if the target is reachable
     */
    public boolean isReachable(URL url);
    /**
     * Please prefer getURLInfo when several infos are needed.
     * @param url the url to check
     * @return true if the target is reachable
     */
    public boolean isReachable(URL url, int timeout);
    /**
     * Returns the length of the target if the given url is reachable, and without
     * error code in case of http urls.
     * Please prefer getURLInfo when several infos are needed.
     * @param url the url to check
     * @return the length of the target if available, 0 if not reachable
     */
    public long getContentLength(URL url);
    /**
     * Returns the length of the target if the given url is reachable, and without
     * error code in case of http urls.
     * @param url the url to check
     * @param timeout the maximum time before considering an url is not reachable
     *        a timeout of zero indicates no timeout
     * @return the length of the target if available, 0 if not reachable
     */
    public long getContentLength(URL url, int timeout);

    /**
     * Please prefer getURLInfo when several infos are needed.
     * @param url the url to check
     * @return last modified timestamp of the given url
     */
    public long getLastModified(URL url);
    /**
     * Please prefer getURLInfo when several infos are needed.
     * @param url the url to check
     * @return last modified timestamp of the given url
     */
    public long getLastModified(URL url, int timeout);

    /**
     * never returns null, return UNAVAILABLE when url is not reachable
     * @param url
     * @return
     */
    public URLInfo getURLInfo(URL url);
    /**
     * never returns null, return UNAVAILABLE when url is not reachable
     * @param url
     * @return
     */
    public URLInfo getURLInfo(URL url, int timeout);

    public InputStream openStream(URL url) throws IOException;
    public void download(URL src, File dest, CopyProgressListener l) throws IOException;
}


text:
'use strict';
/*jshint bitwise: false*/
var _ = _ || {}, APP = APP || {};

angular.module('app.directives', []);
angular.module('app.directives')
  .directive('showAttrs', function() {
    return function(scope, el, attrs) {
      var pre = document.createElement('pre');
      el.after(pre);
      scope.$watch(function() {
        var attrs = {};
        Array.prototype.slice.call(el[0].attributes, 0).forEach(function(item) {
          if (item.name !== 'show-attrs') {
            attrs[item.name] = item.value;
          }
        });
        return attrs;
      }, function(newAttrs, oldAttrs) {
        pre.innerText = JSON.stringify(newAttrs, null, 2);
      }, true);
    };
  });


text:
@extends('layout.default')

@section('title', $__t('Barcode scanner testing'))

@section('viewJsName', 'barcodescannertesting')

@push('pageScripts')
<link href="{{ $U('/node_modules/animate.css/animate.min.css?v=', true) }}{{ $version }}"
	rel="stylesheet">
@endpush

@section('content')

@yield('title')

		<form id="barcodescannertesting-form"
			novalidate>

				{{ $__t('Expected barcode') }}
				<input type="text"
					class="form-control"
					required
					id="expected_barcode"
					name="expected_barcode"
					value="">

				{{ $__t('Scan field') }}

					<input type="text"
						class="form-control barcodescanner-input"
						id="scanned_barcode"
						name="scanned_barcode"
						value=""
						disabled
						data-target="#scanned_barcode">

				{{ $__t('Scanned barcodes') }}

					{{ $__t('Hit') }}: 0 //
					{{ $__t('Miss') }}: 0

				<select class="custom-control custom-select"
					id="scanned_codes"
					name="scanned_codes"
					multiple
					size="30"></select>

		</form>

@include('components.barcodescanner')
@stop


text:
package com.ss.editor.ui.event.impl;

import static com.ss.rlib.common.util.ObjectUtils.notNull;
import com.ss.editor.ui.event.SceneEvent;
import javafx.event.Event;
import javafx.event.EventType;
import org.jetbrains.annotations.NotNull;

import java.nio.file.Path;

/**
 * The event about deleted a file.
 *
 * @author JavaSaBr
 */
public class DeletedFileEvent extends SceneEvent {

    public static final EventType<DeletedFileEvent> EVENT_TYPE;

    static {
        synchronized (Event.class) {
            EVENT_TYPE = new EventType<>(SceneEvent.EVENT_TYPE, DeletedFileEvent.class.getSimpleName());
        }
    }

    private static final String FILE = "file";
    private static final String IS_DIRECTORY = "is_directory";

    public DeletedFileEvent() {
        super(EVENT_TYPE);
    }

    /**
     * Get the file.
     *
     * @return the file.
     */
    public @NotNull Path getFile() {
        return notNull(get(FILE), "Can't find a file");
    }

    /**
     * Return true if the file is directory.
     *
     * @return true if the file is directory.
     */
    public boolean isDirectory() {
        return get(IS_DIRECTORY) == Boolean.TRUE;
    }

    /**
     * Set the file.
     *
     * @param file the file.
     */
    public void setFile(@NotNull Path file) {
        set(FILE, file);
    }

    /**
     * Return true if it is a directory.
     *
     * @param directory true if it is a directory.
     */
    public void setDirectory(boolean directory) {
        set(IS_DIRECTORY, directory);
    }
}


text:
FactoryGirl.define do
  factory :user do
    email { Forgery(:internet).email_address }
    password "secret password"
  end
end


text:
package memory;

import nes.Cartridge;
import io.Joypad;
import operations.Utilities;

/**
 * This object manages all reads and writes into main main.java.memory. It acts similarly to virtual main.java.memory and as a layer
 * between the various independent components PPU, CPU, APU, Cartidge ROM/RAM, and I/O (controllers).
 *
 * There are three contiguous main.java.memory spaces in total:
 * 1. CPU Memory (0x10000 addressable bytes, with RAM, I/O registers, and Cartridge PRG-ROM, SRAM, and WRAM space)
 * 2. PPU Memory (0x10000 addressable bytes with Cartridge CHR-ROM, Name Table, and Sprite/Image pallete space)
 * 3. Sprite Memory (A dedicated 256 bytes for the PPU that contains sprite data).
 *
 * There are also two latches that are written to and read from that are technically separate: the ppuAddressLatch
 * and ppuScrollLatch.
 *
 * This class redirects reads/writes and offsets addresses.
 */
public class ConsoleMemory extends MemoryMap {
    private CPURAM cpuram = new CPURAM();
    private VRAM vram = new VRAM();
    private SPRAM sram = new SPRAM();
    private IORegisterMemory ioRegisterMemory = new IORegisterMemory(this);
    private Cartridge cartridge;
    private Joypad joypadOne;
    private Joypad joypadTwo;

    private static final int addressableMemorySize = 0x10000;

    public ConsoleMemory(final Cartridge cartridge, final Joypad joypadOne, final Joypad joypadTwo) {
        super(0);
        this.cartridge = cartridge;
        this.joypadOne = joypadOne;
        this.joypadTwo = joypadTwo;
        this.vram.setMirroringMode(cartridge.getMirroringMode());
    }

    /**
     * Read a byte from the CPU Memory Map. The provided address will be modded with 0x10000.
     *
     * @param address
     * @return
     */
    @Override
    public byte read(int address) {
        address = address % addressableMemorySize;

        // address: [0x0 -> 0xFFFF]
        if (address < cpuram.size()) {
            // address: [0x0 -> 0x1FFF]
            return this.cpuram.read(address);
        } else if (address < 0x4020) {
            // address: [0x2000 -> 0x401F]
            return ioRegisterMemory.read(address - 0x2000);
        }
        // address: [0x4020 -> 0xFFFF]
        return this.cartridge.readCPUROM(address - 0x4020);
    }

    /**
     * Write a byte into the CPU Memory map
     *
     * @param address
     * @param value
     */
    @Override
    public void write(int address, byte value) {
        address %= addressableMemorySize;
        if (address < cpuram.size()) {
            this.cpuram.write(address, value);
        } else if (address < 0x4020) {
            ioRegisterMemory.write(address - 0x2000, value);
        } else {
            this.cartridge.writeCPUROM(address - 0x4020, value);
        }
    }

    /**
     * Read a byte from the PPU main.java.memory space.
     *
     * @param address
     * @return
     */
    public byte readFromPPU(int address) {
        address %= 0x4000;
        if (address < this.cartridge.CHR_ROM_BANK_SIZE) {
            return this.cartridge.readCHRROM(address);
        }
        return this.vram.read(address);
    }

    /**
     * Write a byte into the PPU main.java.memory space.
     *
     * @param address
     * @param value
     */
    public void writeToPPU(int address, byte value) {
        address %= 0x4000;
        if (address < this.cartridge.CHR_ROM_BANK_SIZE) {
            this.cartridge.writeCHRROM(address, value);
        } else {
            this.vram.write(address, value);
        }
    }

    /**
     * Write a byte to SPR-RAM
     *
     * @param address
     * @param value
     */
    public void writeToSPRData(int address, byte value) {
        this.sram.write(address, value);
    }

    public byte readFromSPRData(int address) {
        return this.sram.read(address);
    }

    /**
     * Gets bubbled back up to the CPU
     *
     * @return
     */
    public boolean dma() {
        return this.ioRegisterMemory.dmaFlag;
    }

    /**
     * Execute a DMA. This means we take 512 cycles from the CPU to transfer 256 bytes from the address in 0x4014 x 100
     * directly to sprite RAM.
     */
    public void executeDma() {
        int startingAddress = Utilities.toUnsignedValue(this.read(0x4014)) * 0x100;
        this.sram.dmaWrite(this.read(startingAddress, 256));
        this.ioRegisterMemory.resetDmaFlag();
    }

    /**
     * Return the VRAM address maintained by I/O register main.java.memory
     *
     * @return
     */
    public int getVramAddress() {
        return this.ioRegisterMemory.vramAddress;
    }

    public int getFineYScroll() {
        return this.ioRegisterMemory.fineYScroll();
    }

    public int getFineXScroll() {
        return this.ioRegisterMemory.fineXScroll();
    }

    public void copyHorizontal() {
        this.ioRegisterMemory.copyHorizontal();
    }

    public void copyVertical() {
        this.ioRegisterMemory.copyVertical();
    }

    public void incrementVertical() {
        this.ioRegisterMemory.incrementVertical();
    }

    public void incrementHorizontal() {
        this.ioRegisterMemory.incrementHorizontal();
    }

    public void setSpriteOverflow() {
        this.ioRegisterMemory.setSpriteOverflow();
    }

    public void setSpriteZeroHit() {
        this.ioRegisterMemory.setSpriteZeroHit();
    }

    public void setVblank() {
        this.ioRegisterMemory.setVblank();
    }

    public void clearSpriteOverflow() {
        this.ioRegisterMemory.clearSpriteOverflow();
    }

    public void clearSpriteZeroHit() {
        this.ioRegisterMemory.clearSpriteZeroHit();
    }

    public void clearVblank() {
        this.ioRegisterMemory.clearVblank();
    }

    /**
     * Fetch all relevant sprites for a line number and fill sprites. We return true if the sprites array is completely
     * filled
     *
     * @param lineNumber
     * @return
     */
    public boolean fetchSprites(final Sprite[] sprites, int lineNumber) {
        return this.sram.fetchSprites(sprites, lineNumber);
    }

    public void writeToJoypadOne(byte value) {
        this.joypadOne.write(value);
    }

    public byte readFromJoypadOne() {
        return this.joypadOne.read();
    }

    public void setJoypadOne(final Joypad joypad) {
        this.joypadOne = joypad;
    }

    public void writeToJoypadTwo(byte value) {
        this.joypadTwo.write(value);
    }

    public byte readFromJoypadTwo() {
        return this.joypadTwo.read();
    }

    public void setJoypadTwo(final Joypad joypad) {
        this.joypadTwo = joypad;
    }
}


text:
// Copyright (c) 2015 RAMBLER&Co
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <Foundation/Foundation.h>

#pragma mark - Error domains

extern NSString * const ErrorDomain;

#pragma mark - Error codes

typedef NS_ENUM(NSInteger, ErrorCode) {

    /**
     @author Artem Karpushin

     Event is already stored in the calendar
     */
    ErrorEventAlreadyStoredInCalendar = 102,

    /**
     @author Konstantin Zinovyev

     Error downloading video
     */
    ErrorDownloadingVideo = 103
};


text:
package org.eigenbase.oj.util;

import java.util.Enumeration;

import openjava.mop.*;

import openjava.ptree.*;
import openjava.ptree.util.*;

import org.eigenbase.util.*;

/**
 * An OJSyntheticClass is a {@link OJClass class declaration} for
 * intermediate results in expressions. It is created implicitly while
 * expressions are being compiled.
 *
 *
Two synthetic classes are identical if their attributes are of the same
 * number, type, and order.
 *
 *
Synthetic classes are created in two ways: {@link
 * OJClassMap#createProject(OJClass, OJClass[], String[])} creates the type of a
 * select clause, and {@link OJClassMap#createJoin(OJClass, OJClass[])} creates
 * the type of a join. The semantics are slightly different: projection classes
 * have field names, but join classes do not; two join classes with the same
 * member types are equivalent, but two distinct projection classes may have the
 * same set of attributes.
 */
public class OJSyntheticClass
    extends OJClass
{
    //~ Static fields/initializers ---------------------------------------------

    public static final String JOIN_CLASS_PREFIX = "Oj_";
    public static final String PROJECT_CLASS_PREFIX = "Ojp_";
    public static final String FIELD_PREFIX = "$f";

    //~ Instance fields --------------------------------------------------------

    /* -- Data Members -- */

    String description; // for debug
    OJClass [] classes;
    ClassDeclaration decl;

    //~ Constructors -----------------------------------------------------------

    /**
     * Called only from {@link OJClassMap} methods.
     */
    OJSyntheticClass(
        Environment env,
        OJClass declarer,
        OJClass [] classes,
        String [] fieldNames,
        ClassDeclaration decl,
        String description,
        boolean defineValueConstructor)
    {
        super(env, declarer, decl);
        this.classes = classes;
        this.decl = decl;
        this.description = description;

        // default constructor
        ConstructorDeclaration constructor =
            new ConstructorDeclaration(
                new ModifierList(ModifierList.PUBLIC),
                decl.getName(),
                null,
                null,
                new StatementList());
        decl.getBody().add(constructor);

        // create value constructor (unless it is the same as the default
        // constructor, or we've been asked not to)
        if ((classes.length > 0) && defineValueConstructor) {
            ParameterList parameterList = new ParameterList();
            StatementList statementList = new StatementList();
            for (int i = 0; i < classes.length; i++) {
                String varName = fieldNames[i];
                parameterList.add(
                    new Parameter(
                        TypeName.forOJClass(classes[i]),
                        varName));
                statementList.add(
                    new ExpressionStatement(
                        new AssignmentExpression(
                            new FieldAccess(
                                SelfAccess.makeThis(),
                                varName),
                            AssignmentExpression.EQUALS,
                            new Variable(varName))));
            }
            ConstructorDeclaration constructor2 =
                new ConstructorDeclaration(
                    new ModifierList(ModifierList.PUBLIC),
                    decl.getName(),
                    parameterList,
                    null,
                    statementList);
            decl.getBody().add(constructor2);
        }
    }

    //~ Methods ----------------------------------------------------------------

    /* -- Methods -- */

    public String toString()
    {
        return super.toString() + " " + description;
    }

    // override Object
    public boolean equals(Object o)
    {
        return (o instanceof OJSyntheticClass)
            && this.description.equals(((OJSyntheticClass) o).description);
    }

    // override Object
    public int hashCode()
    {
        return HashableArray.arrayHashCode(classes);
    }

    /**
     * Adds declarations of a set of classes classes as inner
     * classes of a class declaration outerClassDecl. Declarations
     * which are already present are not added again.
     */
    public static void addMembers(
        ClassDeclaration outerClassDecl,
        OJClass [] classes)
    {
        MemberDeclarationList memberDecls = outerClassDecl.getBody();
outer:
        for (int i = 0; i < classes.length; i++) {
            if (classes[i] instanceof OJSyntheticClass) {
                ClassDeclaration innerClassDecl =
                    ((OJSyntheticClass) classes[i]).decl;
                for (
                    Enumeration existingDecls = memberDecls.elements();
                    existingDecls.hasMoreElements();)
                {
                    if (existingDecls.nextElement() == innerClassDecl) {
                        continue outer;
                    }
                }
                memberDecls.add(innerClassDecl);
            }
        }
    }

    /**
     * Creates a method in a class.
     */
    public static void addMethod(
        ClassDeclaration classDecl,
        StatementList statementList,
        String name,
        String [] parameterNames,
        OJClass [] parameterTypes,
        OJClass returnType)
    {
        ParameterList parameterList = new ParameterList();
        if (parameterNames.length != parameterTypes.length) {
            throw Util.newInternal(
                "must have same number & type of parameters");
        }
        ModifierList modifierList;
        for (int i = 0; i < parameterNames.length; i++) {
            parameterList.add(
                new Parameter(
                    new ModifierList(),
                    TypeName.forOJClass(parameterTypes[i]),
                    parameterNames[i]));
        }
        MethodDeclaration methodDecl =
            new MethodDeclaration(
                new ModifierList(ModifierList.STATIC | ModifierList.PUBLIC),
                TypeName.forOJClass(returnType),
                name,
                parameterList,
                new TypeName[] {
                    TypeName.forOJClass(OJUtil.clazzSQLException)
                },
                statementList);
        MethodDeclaration oldMethodDecl = null;
        MemberDeclarationList body = classDecl.getBody();
        for (int i = 0, count = body.size(); i < count; i++) {
            MemberDeclaration memberDecl = body.get(i);
            if (memberDecl instanceof MethodDeclaration) {
                MethodDeclaration existingMethodDecl =
                    (MethodDeclaration) memberDecl;
                if (existingMethodDecl.getName().equals(name)
                    && existingMethodDecl.getParameters().equals(
                        parameterList))
                {
                    oldMethodDecl = existingMethodDecl;
                }
            }
        }
        if (oldMethodDecl == null) {
            body.add(methodDecl);
        } else {
            try {
                oldMethodDecl.replace(methodDecl);
            } catch (ParseTreeException e) {
                throw Util.newInternal(
                    e,
                    "while replacing method " + oldMethodDecl);
            }
        }
    }

    /**
     * Converts a field name back to an ordinal. For example,
     * getOrdinal("$f2") returns 2. If fieldName is not valid, throws an
     * error if "fail" is true, otherwise returns -1.
     */
    public static int getOrdinal(String fieldName, boolean fail)
    {
        if (fieldName.startsWith(FIELD_PREFIX)) {
            String s = fieldName.substring(FIELD_PREFIX.length());
            try {
                return Integer.parseInt(s);
            } catch (NumberFormatException e) {
                // fall through
            }
        }
        if (fail) {
            throw Util.newInternal(
                "bad field in synthetic class [" + fieldName + "]");
        } else {
            return -1;
        }
    }

    public static String makeField(int ordinal)
    {
        return FIELD_PREFIX + ordinal;
    }

    public static boolean isJoinClass(OJClass clazz)
    {
        final String name = clazz.getName(); // null for the "null class"
        return (name != null) && (name.indexOf(JOIN_CLASS_PREFIX) >= 0);
    }
}

// End OJSyntheticClass.java


text:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  after_action :store_location

  def store_location
    # store last url as long as it isn't a /users path
    session[:previous_url] = request.fullpath unless request.fullpath =~ %r{/users}
  end

  rescue_from CanCan::AccessDenied do |exception|
    flash[:error] = exception.message
    redirect_to root_path
  end

  def after_sign_in_path_for(_resource)
    session[:previous_url] || root_path
  end

  def current_ability
    @current_ability ||= Ability.new(current_partner || current_user)
  end
end


text:
package com.spectralogic.ds3autogen.net.generators.parsers.element;

@FunctionalInterface
public interface NullableElement {
    String printParseElement();
}


text:
import LoginService from "./login.service";
import AlertModalService from "../common/alert-modal.service";
import {ILocationService} from "angular";

export default class SignUpCtrl {

    static $inject: string[] = ["$location", "LoginService", "AlertModalService"];
    email: string;
    groupName: string;
    validPassword: string;
    isSubmitted: boolean;

    constructor(private $location: ILocationService, private loginService: LoginService, private alertModalService: AlertModalService) {
        this.email = "";
        this.groupName = "";
        this.validPassword = undefined;
        this.isSubmitted = false;
    }

    signUp(): void {
        this.isSubmitted = true;
        const username: string = LoginService.formatUsername(this.email);
        const email: string = LoginService.formatEmail(this.email);
        this.loginService
            .attemptRegistration(username, email, this.groupName, this.validPassword, this.validPassword)
            .then(data => {
                    this.$location
                        .path("/page/login");
                    this.alertModalService.show({
                        style: "info",
                        title: "Information",
                        message: data.message
                    });
                },
                errData => {
                    this.alertModalService.show({
                        style: "warning",
                        title: "Warning",
                        message: errData.data.message});
                })
            .finally(() => this.isSubmitted = false);
    }
}


text:
sr-rd-theme-engwrite{display:none;}

/**
 * EngWrite style
 */

/**
 * Common style, include: h1 ~ h6; ol ul; code pre; table; sr-blockquote
 */

sr-rd-content h1,sr-rd-content h2,sr-rd-content h3,sr-rd-content h4,sr-rd-content h5,sr-rd-content h6{margin:20px 0 10px;padding:0;font-weight:500;-webkit-font-smoothing:antialiased}sr-rd-content h1{font-weight:300;text-align:center;font-size:2.8rem;color:#933d3f}sr-rd-content h2{font-size:2.4rem;border-bottom:1px solid #ccc;color:#000}sr-rd-content h3{font-size:1.8rem}sr-rd-content h4,sr-rd-content h5{font-size:1.6rem}sr-rd-content h6{color:#777;font-size:1.6rem}
sr-rd-content ul,sr-rd-content ol{padding-left:30px}sr-rd-content ul li>:first-child,sr-rd-content ol li>:first-child,sr-rd-content ul li ul:first-of-type,sr-rd-content ol li ol:first-of-type,sr-rd-content ul li ol:first-of-type,sr-rd-content ol li ul:first-of-type{margin-top:0}sr-rd-content ul ul,sr-rd-content ul ol,sr-rd-content ol ol,sr-rd-content ol ul{margin-bottom:0}
sr-rd-content table th{font-weight:bold}sr-rd-content table th,sr-rd-content table td{border:1px solid #ccc;padding:6px 13px}sr-rd-content table tr{border-top:1px solid #ccc;background-color:#fff}sr-rd-content table tr:nth-child(2n){background-color:#f8f8f8}
sr-rd-content sr-blockquote {
    text-align: left;
    border-top: 1px dotted #cdc7bc;
    border-bottom: 1px dotted #cdc7bc;
    background-color: #f8edda;
    color: #777
}

sr-blockquote >:first-child {
    margin-top: 0
}

sr-blockquote >:last-child {
    margin-bottom: 0
}

/**
 * Custom style, include: background; title; desc; sr-rd-content; p,div; a; pre
 */

.simpread-theme-root {
    background-color: rgb(252, 245, 237);
    color: rgb(51, 51, 51);
}

sr-rd-title {
    font-weight: 300;
    text-align: center;
    font-size: 2.8rem;
    color: rgb(147, 61, 63);
}

sr-rd-desc {
    padding: 10px;
    background-color: rgb(248, 237, 218);
    color: rgb(119, 119, 119);
    font-size: 2rem;
    text-align: center;
    border-top: 1px dotted rgb(205, 199, 188);
    border-bottom: 1px dotted rgb(205, 199, 188);
}

sr-rd-content {
    color: rgb(51, 51, 51);
    padding: 20px 0;
    margin: 0px auto;
    line-height: 1.8;
}

sr-rd-content *,
sr-rd-content p,
sr-rd-content div {
    color: rgb(51, 51, 51);
    line-height: 1.8;
}

sr-rd-content a,
sr-rd-content a:link {
    color: rgb(174, 55, 55);
    text-decoration: none;
}

sr-rd-content a:hover,
sr-rd-content a:focus,
sr-rd-content a:active {
    text-decoration: underline;
}

sr-rd-content pre {
    background-color: transparent;
    border: 1px solid rgb(204, 204, 204);
    border-radius: 3px;
}

sr-rd-content li code,
sr-rd-content p code {
    border: 1px solid rgb(234, 234, 234);
    background-color: rgb(244, 236, 227);
    border-radius: 3px;
}


text:
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import

import mock
import novaclient

from congress.datasources import nova_driver
from congress import exception
from congress.tests import base
from congress.tests.datasources import fakes
from congress.tests import helper

class TestNovaDriver(base.TestCase):

    def setUp(self):
        super(TestNovaDriver, self).setUp()
        nova_client = mock.MagicMock()
        self.nova = fakes.NovaFakeClient()
        with mock.patch.object(novaclient.client.Client, '__init__',
                               return_value=nova_client):
            self.driver = nova_driver.NovaDriver(
                name='nova',
                args=helper.datasource_openstack_args())

    def test_driver_called(self):
        self.assertIsNotNone(self.driver.nova_client)

    def test_servers(self):
        servers_raw = self.nova.servers.list(detailed=True)
        self.driver._translate_servers(servers_raw)
        server_tuples = self.driver.state[self.driver.SERVERS]

        self.assertEqual(3, len(server_tuples))
        #  tuple = (s.id, s.name, s.hostId, s.status, s.tenant_id,
        #   s.user_id, image, flavor)
        for t in server_tuples:
            id = t[0]
            name = t[1]
            host_id = t[2]
            status = t[3]
            tenant_id = t[4]
            user_id = t[5]
            image_id = t[6]
            flavor_id = t[7]
            zone = t[8]
            host_name = t[9]
            created_at = t[10]
            self.assertIn(id, ['1234', '5678', '9012'])
            # see congress.datasources.tests.unit.fakes for actual values
            if id == '1234':
                self.assertEqual("sample-server", name)
                self.assertEqual("e4d909c290d0fb1ca068ffaddf22cbd0", host_id)
                self.assertEqual("BUILD", status)
                self.assertEqual("33ea0494-2bdf-4382-a445-9068997430b9",
                                 user_id)
                self.assertEqual("50e14867-7c64-4ec9-be8d-ed2470ca1d24",
                                 tenant_id)
                self.assertEqual('2', image_id)
                self.assertEqual('1', flavor_id)
                self.assertEqual('2019-02-26T08:48:15Z', created_at)
                self.assertEqual('default', zone)
                self.assertEqual('host1', host_name)

            elif id == '5678':
                self.assertEqual("sample-server2", name)
                self.assertEqual("9e107d9d372bb6826bd81d3542a419d6", host_id)
                self.assertEqual("ACTIVE", status)
                self.assertEqual("33ea0494-2bdf-4382-a445-9068997430b9",
                                 user_id)
                self.assertEqual("50e14867-7c64-4ec9-be8d-ed2470ca1d24",
                                 tenant_id)
                self.assertEqual('2', image_id)
                self.assertEqual('1', flavor_id)
                self.assertEqual('2019-02-26T08:48:15Z', created_at)
                self.assertEqual(None, zone)
                self.assertEqual(None, host_name)

            elif id == '9012':
                self.assertEqual("sample-server3", name)
                self.assertEqual("9e107d9d372bb6826bd81d3542a419d6", host_id)
                self.assertEqual("ACTIVE", status)
                self.assertEqual("33ea0494-2bdf-4382-a445-9068997430b9",
                                 user_id)
                self.assertEqual("50e14867-7c64-4ec9-be8d-ed2470ca1d24",
                                 tenant_id)
                self.assertEqual('2', image_id)
                self.assertEqual('1', flavor_id)
                self.assertEqual('2019-02-26T08:48:15Z', created_at)
                self.assertEqual('foo', zone)
                self.assertEqual('host2', host_name)

        server_tag_tuples = self.driver.state[self.driver.TAGS]

        self.assertEqual(len(server_tag_tuples), 5)

        self.assertIn(('5678', 'tag1'), server_tag_tuples)
        self.assertIn(('5678', 'tag2'), server_tag_tuples)

        self.assertIn(('9012', 'tag1'), server_tag_tuples)
        self.assertIn(('9012', 'tag2'), server_tag_tuples)
        self.assertIn(('9012', 'tag3'), server_tag_tuples)

        server_addresses_tuples = self.driver.state[self.driver.ADDRESSES]
        self.assertEqual(len(server_addresses_tuples), 1)
        self.assertIn(('1234', 'net_mgmt', '192.168.0.60', 4, '11:11:11:11',
                       'fixed'),
                      server_addresses_tuples)

    def test_flavors(self):
        flavor_raw = self.nova.flavors.list(detailed=True)
        self.driver._translate_flavors(flavor_raw)

        flavor_tuples = self.driver.state[self.driver.FLAVORS]

        self.assertEqual(4, len(flavor_tuples))
        # "id", "name", "vcpus", "ram", "disk", "ephemeral",
        #            "rxtx_factor")
        for f in flavor_tuples:
            id = f[0]
            name = f[1]
            vcpus = f[2]
            ram = f[3]
            disk = f[4]
            ephemeral = f[5]
            rxtx_factor = f[6]

            self.assertIn(id, ['1', '2', '3', '4'])

            # {'id': 1, 'name': '256 MB Server', 'ram': 256, 'disk': 10,
            # 'vcpus' : 1, 'OS-FLV-EXT-DATA:ephemeral': 10,
            # 'os-flavor-access:is_public': True, 'rxtx_factor' : 1.0,
            # 'links': {}},
            if id == '1':
                self.assertEqual('256 MB Server', name)
                self.assertEqual(256, ram)
                self.assertEqual(10, disk)
                self.assertEqual(1, vcpus)
                self.assertEqual(10, ephemeral)
                self.assertEqual(1.0, rxtx_factor)
            # {'id': 2, 'name': '512 MB Server', 'ram': 512, 'disk': 20,
            #  'vcpus' :2, 'OS-FLV-EXT-DATA:ephemeral': 20,
            #  'os-flavor-access:is_public': False, 'rxtx_factor' : 1.0,
            #  'links': {}},
            elif id == '2':
                self.assertEqual('512 MB Server', name)
                self.assertEqual(512, ram)
                self.assertEqual(20, disk)
                self.assertEqual(2, vcpus)
                self.assertEqual(20, ephemeral)
                self.assertEqual(1.0, rxtx_factor)
            # {'id': 3, 'name': '128 MB Server', 'ram': 128, 'disk': 0,
            #  'vcpus' : 4, 'OS-FLV-EXT-DATA:ephemeral': 0,
            #  'os-flavor-access:is_public': True, 'rxtx_factor' : 3.0,
            #  'links': {}}
            elif id == '3':
                self.assertEqual('128 MB Server', name)
                self.assertEqual(128, ram)
                self.assertEqual(0, disk)
                self.assertEqual(4, vcpus)
                self.assertEqual(0, ephemeral)
                self.assertEqual(3.0, rxtx_factor)
            # {'id': 4, 'name': '1024 MB Server', 'ram': 1024, 'disk': 10,
            #  'vcpus' : 3, 'OS-FLV-EXT-DATA:ephemeral': 10,
            #  'os-flavor-access:is_public': True, 'rxtx_factor' : 2.0,
            #  'links': {}},
            elif id == '4':
                self.assertEqual('1024 MB Server', name)
                self.assertEqual(1024, ram)
                self.assertEqual(10, disk)
                self.assertEqual(3, vcpus)
                self.assertEqual(10, ephemeral)
                self.assertEqual(2.0, rxtx_factor)
                self.assertEqual('1024 MB Server', name)

#    def test_hosts(self):
#        host_list = self.nova.hosts.list()
#        self.driver._translate_hosts(host_list)
#        host_tuples = self.driver.state[self.driver.HOSTS]
#        self.assertEqual(2, len(host_tuples))
#        for host in host_tuples:
#            host_name = host[0]
#            service = host[1]
#            zone = host[2]
#
#            if host_name == 'host1':
#                self.assertEqual('nova-compute', service)
#                self.assertEqual('nova1', str(zone))
#            elif host_name == 'host2':
#                self.assertEqual('nova-cert', service)
#                self.assertEqual('nova1', str(zone))

    def test_hypervisors(self):
        hypervisors = self.nova.hypervisors.list()
        self.driver._translate_hypervisors(hypervisors)
        hypervisor_tuples = self.driver.state[self.driver.HYPERVISORS]
        self.assertEqual(2, len(hypervisor_tuples))
        for host in hypervisor_tuples:
            host_name = host[0]
            id = host[1]
            state = host[2]
            status = host[3]

            if host_name == 'host1':
                self.assertEqual(2, id)
                self.assertEqual('up', state)
                self.assertEqual('enabled', status)
            elif host_name == 'host2':
                self.assertEqual(3, id)
                self.assertEqual('down', state)
                self.assertEqual('enabled', status)

    def test_services(self):
        service_list = self.nova.services.list()
        self.driver._translate_services(service_list)
        expected_ret = {
            1: [1, 'nova-compute', 'nova', 'nova1', 'enabled', 'up',
                '2015-07-28T08:28:37.000000', None],
            2: [2, 'nova-schedule', 'nova', 'nova1', 'disabled', 'up',
                '2015-07-28T08:28:38.000000', 'daily maintenance']
        }
        service_tuples = self.driver.state[self.driver.SERVICES]

        self.assertEqual(2, len(service_tuples))

        for s in service_tuples:
            map(self.assertEqual, expected_ret[s[0]], s)

    def test_availability_zones(self):
        az_list = self.nova.availability_zones.list()
        self.driver._translate_availability_zones(az_list)
        expected_ret = {
            'AZ1': ['AZ1', 'available'],
            'AZ2': ['AZ2', 'not available']
        }
        az_tuples = self.driver.state[self.driver.AVAILABILITY_ZONES]

        self.assertEqual(2, len(az_tuples))

        for az in az_tuples:
            map(self.assertEqual, expected_ret[az[0]], az)

    # TODO(dse2): port or not.  Unclear why we're doing this with Nova.
    # def test_communication(self):
    #     """Test for communication.

    #     Test the module's ability to be loaded into the DSE
    #     by checking its ability to communicate on the message bus.
    #     """
    #     cage = d6cage.d6Cage()

    #     # Create modules.
    #     # Turn off polling so we don't need to deal with real data.
    #     args = helper.datasource_openstack_args()
    #     args['poll_time'] = 0
    #     cage.loadModule("NovaDriver",
    #                     helper.data_module_path("nova_driver.py"))
    #     cage.loadModule("PolicyDriver", helper.policy_module_path())
    #     cage.createservice(name="policy", moduleName="PolicyDriver",
    #                        args={'d6cage': cage,
    #                              'rootdir': helper.data_module_path(''),
    #                              'log_actions_only': True})
    #     cage.createservice(name="nova", moduleName="NovaDriver", args=args)

    #     # Check that data gets sent from nova to policy as expected
    #     nova = cage.service_object('nova')
    #     policy = cage.service_object('policy')
    #     policy.debug_mode()
    #     policy.create_policy('nova')
    #     policy.set_schema('nova', compile.Schema({'server': (1,)}))
    #     policy.subscribe('nova', 'server',
    #                      callback=policy.receive_data)

    #     # publishing is slightly convoluted b/c deltas are computed
    #     #  automatically.  (Not just convenient--useful so that DSE
    #     #  properly handles the initial state problem.)
    #     # Need to set nova.state and nova.prior_state and then publish
    #     #  anything.

    #     # publish server(1), server(2), server(3)
    #     helper.retry_check_subscribers(nova, [(policy.name, 'server')])
    #     nova.prior_state = {}
    #     nova.state['server'] = set([(1,), (2,), (3,)])
    #     nova.publish('server', None)
    #     helper.retry_check_db_equal(
    #         policy, 'nova:server(x)',
    #         'nova:server(1) nova:server(2) nova:server(3)')

    #     # publish server(1), server(4), server(5)
    #     nova.prior_state['server'] = nova.state['server']
    #     nova.state['server'] = set([(1,), (4,), (5,)])
    #     nova.publish('server', None)
    #     helper.retry_check_db_equal(
    #         policy, 'nova:server(x)',
    #         'nova:server(1) nova:server(4) nova:server(5)')

    # TODO(thinrichs): test that Nova's polling functionality
    #   works properly.  Or perhaps could bundle this into the
    #   tests above if we check self.state results.
    #   See Neutron's test_polling

    def test_execute(self):
        class NovaClient(object):
            def __init__(self):
                self.testkey = None

            def connectNetwork(self, arg1):
                self.testkey = 'arg1=%s' % arg1

        nova_client = NovaClient()
        self.driver.nova_client = nova_client
        api_args = {
            'positional': ['1']
        }
        expected_ans = 'arg1=1'

        self.driver.execute('connectNetwork', api_args)

        self.assertEqual(expected_ans, nova_client.testkey)

    def test_execute_servers_set_meta(self):
        args = {'positional': ['1', 'meta-key1', 'meta-value1']}
        action_args = {'named': {'server': '1',
                                 'metadata': {'meta-key1': 'meta-value1'}}}
        with mock.patch.object(self.driver, '_execute_api') as mock_ea:
            self.driver.servers_set_meta(args)
            mock_ea.assert_called_with(self.driver.nova_client,
                                       'servers.set_meta',
                                       action_args)

    def test_execute_with_non_executable_method(self):
        action_args = {'positional': ['1', 'meta-key1', 'meta-value1']}
        self.assertRaises(exception.CongressException,
                          self.driver.execute,
                          'get_nova_credentials_v2', action_args)


text:
Use [Natural Language Classifier][natural_language_classifier] service to create a classifier instance by providing a set of representative strings and a set of one or more correct classes for each as training. Then use the trained classifier to classify your new question for best matching answers or to retrieve next actions for your application.

## Usage
Classify intents in natural language.

### Instantiating and authenticating the service
Before you can send requests to the service it must be instantiated and credentials must be set.
```cs
using IBM.Watson.DeveloperCloud.Services.NaturalLanguageClassifier.v2;
using IBM.Watson.DeveloperCloud.Utilities;

void Start()
{
    Credentials credentials = new Credentials(<username>, <password>, <url>);
    NaturalLanguageClassifier _naturalLanguageClassifier = new NaturalLanguageClassifier(credentials);
}
```

### Fail handler
These examples use a common fail handler.
```cs
private void OnFail(RESTConnector.Error error, Dictionary<string, object> customData)
{
    Log.Error("ExampleNaturalLanguageClassifier.OnFail()", "Error received: {0}", error.ToString());
}
```

### Listing Classifiers
Returns an empty array if no classifiers are available.
```cs
private void GetClassifiers()
{
  if (!naturalLanguageClassifier.GetClassifiers(OnGetClassifiers, OnFail))
    Log.Debug("ExampleNaturalLanguageClassifier.GetClassifiers()", "Failed to get classifiers!");
}

private void OnGetClassifiers(Classifiers classifiers, Dictionary<string, object> customData)
{
  Log.Debug("ExampleNaturalLanguageClassifier.OnGetClassifiers()", "Natural Language Classifier - GetClassifiers  Response: {0}", customData["json"].ToString());
}
```

### Classifying Text
The status must be Available before you can use the classifier to classify calls. Use GET /classifiers/{classifier_id} to retrieve the status.
```cs
private void Classify()
{
  if (!naturalLanguageClassifier.Classify(OnClassify, OnFail, <classifier-id>, <input>))
    Log.Debug("ExampleNaturalLanguageClassifier.Classify()", "Failed to classify!");
}

private void OnClassify(ClassifyResult result, Dictionary<string, object> customData)
{
    Log.Debug("ExampleNaturalLanguageClassifier.OnClassify()", "Natural Language Classifier - Classify Response: {0}", customData["json"].ToString());
}
```

### Training A New Classifier
Sends data to create and train a classifier and returns information about the new classifier.
```cs
private void TrainClassifier()
{
  if (!naturalLanguageClassifier.TrainClassifier(<classifier-name>, <classifier-language>, <training-data>, OnTrainClassifier))
    Log.Debug("ExampleNaturalLanguageClassifier.TrainClassifier()", "Failed to train clasifier!");
}

private void OnTrainClassifier(Classifier classifier, Dictionary<string, object> customData)
{
    Log.Debug("ExampleNaturalLanguageClassifier.OnTrainClassifier()", "Natural Language Classifier - Train Classifier: {0}", customData["json"].ToString());
}
```

### Getting Information About A Classifier
Returns status and other information about a classifier
```cs
private void GetClassifier()
{
  if (!naturalLanguageClassifier.GetClassifier(<classifier-id>, OnGetClassifier))
    Log.Debug("ExampleNaturalLanguageClassifier.GetClassifier()", "Failed to get classifier {0}!", classifierId);
}

private void OnGetClassifier(Classifier classifier, Dictionary<string, object> customData)
{
    Log.Debug("ExampleNaturalLanguageClassifier.OnGetClassifier()", "Natural Language Classifier - Get Classifier {0}: {1}", classifier.classifier_id, data);
}
```

### Deleting A Classifier
Deletes a classifier
```cs
private void DeleteClassifier()
{
  if (!naturalLanguageClassifier.DeleteClassifer(<classifier-id>, OnDeleteTrainedClassifier))
    Log.Debug("ExampleNaturalLanguageClassifier.DeleteClassifier()", "Failed to delete clasifier {0}!", <classifier-id>);
}

private void OnDeleteTrainedClassifier(bool success, Dictionary<string, object> customData)
{
    Log.Debug("ExampleNaturalLanguageClassifier.OnDeleteTrainedClassifier()", "Natural Language Classifier - Delete Trained Classifier {0} | success: {1} {2}", <classifier-id>, success, data);
}
```

[natural_language_classifier]: https://www.ibm.com/watson/services/natural-language-classifier/