text:
package io.atomix.protocols.raft.session.impl;

import io.atomix.primitive.session.SessionId;
import io.atomix.protocols.raft.TestPrimitiveType;
import io.atomix.protocols.raft.protocol.CommandResponse;
import io.atomix.protocols.raft.protocol.PublishRequest;
import io.atomix.protocols.raft.protocol.QueryResponse;
import io.atomix.protocols.raft.protocol.RaftResponse;
import org.junit.Test;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * Client sequencer test.
 *
 * @author Jordan Halterman
 */
public class RaftSessionSequencerTest {

  /**
   * Tests sequencing an event that arrives before a command response.
   */
  @Test
  public void testSequenceEventBeforeCommand() throws Throwable {
    RaftSessionSequencer sequencer = new RaftSessionSequencer(new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000));
    long sequence = sequencer.nextRequest();

    PublishRequest request = PublishRequest.builder()
        .withSession(1)
        .withEventIndex(1)
        .withPreviousIndex(0)
        .withEvents(Collections.emptyList())
        .build();

    CommandResponse response = CommandResponse.builder()
        .withStatus(RaftResponse.Status.OK)
        .withIndex(2)
        .withEventIndex(1)
        .build();

    AtomicInteger run = new AtomicInteger();
    sequencer.sequenceEvent(request, () -> assertEquals(0, run.getAndIncrement()));
    sequencer.sequenceResponse(sequence, response, () -> assertEquals(1, run.getAndIncrement()));
    assertEquals(2, run.get());
  }

  /**
   * Tests sequencing an event that arrives before a command response.
   */
  @Test
  public void testSequenceEventAfterCommand() throws Throwable {
    RaftSessionSequencer sequencer = new RaftSessionSequencer(new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000));
    long sequence = sequencer.nextRequest();

    PublishRequest request = PublishRequest.builder()
        .withSession(1)
        .withEventIndex(1)
        .withPreviousIndex(0)
        .withEvents(Collections.emptyList())
        .build();

    CommandResponse response = CommandResponse.builder()
        .withStatus(RaftResponse.Status.OK)
        .withIndex(2)
        .withEventIndex(1)
        .build();

    AtomicInteger run = new AtomicInteger();
    sequencer.sequenceResponse(sequence, response, () -> assertEquals(0, run.getAndIncrement()));
    sequencer.sequenceEvent(request, () -> assertEquals(1, run.getAndIncrement()));
    assertEquals(2, run.get());
  }

  /**
   * Tests sequencing an event that arrives before a command response.
   */
  @Test
  public void testSequenceEventAtCommand() throws Throwable {
    RaftSessionSequencer sequencer = new RaftSessionSequencer(new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000));
    long sequence = sequencer.nextRequest();

    PublishRequest request = PublishRequest.builder()
        .withSession(1)
        .withEventIndex(2)
        .withPreviousIndex(0)
        .withEvents(Collections.emptyList())
        .build();

    CommandResponse response = CommandResponse.builder()
        .withStatus(RaftResponse.Status.OK)
        .withIndex(2)
        .withEventIndex(2)
        .build();

    AtomicInteger run = new AtomicInteger();
    sequencer.sequenceResponse(sequence, response, () -> assertEquals(1, run.getAndIncrement()));
    sequencer.sequenceEvent(request, () -> assertEquals(0, run.getAndIncrement()));
    assertEquals(2, run.get());
  }

  /**
   * Tests sequencing an event that arrives before a command response.
   */
  @Test
  public void testSequenceEventAfterAllCommands() throws Throwable {
    RaftSessionSequencer sequencer = new RaftSessionSequencer(new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000));
    long sequence = sequencer.nextRequest();

    PublishRequest request1 = PublishRequest.builder()
        .withSession(1)
        .withEventIndex(2)
        .withPreviousIndex(0)
        .withEvents(Collections.emptyList())
        .build();

    PublishRequest request2 = PublishRequest.builder()
        .withSession(1)
        .withEventIndex(3)
        .withPreviousIndex(2)
        .withEvents(Collections.emptyList())
        .build();

    CommandResponse response = CommandResponse.builder()
        .withStatus(RaftResponse.Status.OK)
        .withIndex(2)
        .withEventIndex(2)
        .build();

    AtomicInteger run = new AtomicInteger();
    sequencer.sequenceEvent(request1, () -> assertEquals(0, run.getAndIncrement()));
    sequencer.sequenceEvent(request2, () -> assertEquals(2, run.getAndIncrement()));
    sequencer.sequenceResponse(sequence, response, () -> assertEquals(1, run.getAndIncrement()));
    assertEquals(3, run.get());
  }

  /**
   * Tests sequencing an event that arrives before a command response.
   */
  @Test
  public void testSequenceEventAbsentCommand() throws Throwable {
    RaftSessionSequencer sequencer = new RaftSessionSequencer(new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000));

    PublishRequest request1 = PublishRequest.builder()
        .withSession(1)
        .withEventIndex(2)
        .withPreviousIndex(0)
        .withEvents(Collections.emptyList())
        .build();

    PublishRequest request2 = PublishRequest.builder()
        .withSession(1)
        .withEventIndex(3)
        .withPreviousIndex(2)
        .withEvents(Collections.emptyList())
        .build();

    AtomicInteger run = new AtomicInteger();
    sequencer.sequenceEvent(request1, () -> assertEquals(0, run.getAndIncrement()));
    sequencer.sequenceEvent(request2, () -> assertEquals(1, run.getAndIncrement()));
    assertEquals(2, run.get());
  }

  /**
   * Tests sequencing callbacks with the sequencer.
   */
  @Test
  public void testSequenceResponses() throws Throwable {
    RaftSessionSequencer sequencer = new RaftSessionSequencer(new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000));
    long sequence1 = sequencer.nextRequest();
    long sequence2 = sequencer.nextRequest();
    assertTrue(sequence2 == sequence1 + 1);

    CommandResponse commandResponse = CommandResponse.builder()
        .withStatus(RaftResponse.Status.OK)
        .withIndex(2)
        .withEventIndex(0)
        .build();

    QueryResponse queryResponse = QueryResponse.builder()
        .withStatus(RaftResponse.Status.OK)
        .withIndex(2)
        .withEventIndex(0)
        .build();

    AtomicBoolean run = new AtomicBoolean();
    sequencer.sequenceResponse(sequence2, queryResponse, () -> run.set(true));
    sequencer.sequenceResponse(sequence1, commandResponse, () -> assertFalse(run.get()));
    assertTrue(run.get());
  }
}


text:
class AddSubscriptionIdToOrders < ActiveRecord::Migration
  def change
    add_column :spree_orders, :subscription_id, :integer
  end
end

redpajama_set_name: RedPajamaGithub


text:
module Rails
  class Conductor::ActionMailbox::InboundEmailsController < Rails::Conductor::BaseController
    def index
      @inbound_emails = ActionMailbox::InboundEmail.order(created_at: :desc)
    end

    def new
    end

    def show
      @inbound_email = ActionMailbox::InboundEmail.find(params[:id])
    end

    def create
      inbound_email = create_inbound_email(new_mail)
      redirect_to main_app.rails_conductor_inbound_email_url(inbound_email)
    end

    private
      def new_mail
        Mail.new(mail_params.except(:attachments).to_h).tap do |mail|
          mail[:bcc]&.include_in_headers = true
          mail_params[:attachments].to_a.each do |attachment|
            mail.add_file(filename: attachment.original_filename, content: attachment.read)
          end
        end
      end

      def mail_params
        params.require(:mail).permit(:from, :to, :cc, :bcc, :x_original_to, :in_reply_to, :subject, :body, attachments: [])
      end

      def create_inbound_email(mail)
        ActionMailbox::InboundEmail.create_and_extract_message_id!(mail.to_s)
      end
  end
end


text:
'use strict';

define(function(){
    return function Command (command, args, callback, call_on_write) {
        this.command = command;
        this.args = args;
        this.buffer_args = false;
        this.callback = callback;
        this.call_on_write = call_on_write;
    };
});


text:
package org.jetbrains.plugins.scala.lang.psi.api.statements

import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import org.jetbrains.plugins.scala.icons.Icons
import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes.kVAL
import org.jetbrains.plugins.scala.lang.psi.api.ScalaFile
import org.jetbrains.plugins.scala.lang.psi.api.expr.ScBlock
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.templates.ScExtendsBlock
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef._

import javax.swing.Icon

trait ScValue extends ScValueOrVariable {

  override protected def keywordElementType: IElementType = kVAL

  override protected def isSimilarMemberForNavigation(member: ScMember, isStrictCheck: Boolean): Boolean = member match {
    case other: ScValue => super.isSimilarMemberForNavigation(other, isStrictCheck)
    case _ => false
  }

  // TODO unify with ScFunction and ScVariable
  override protected final def baseIcon: Icon = {
    @scala.annotation.tailrec
    def basedOnParent(current: PsiElement): Icon = current match {
      case _: ScExtendsBlock         => if (isAbstract) Icons.ABSTRACT_FIELD_VAL else Icons.FIELD_VAL
      case _: ScBlock | _: ScalaFile => Icons.VAL
      case other if other != null    => basedOnParent(current.getParent)
      case _                         => Icons.VAL
    }
    basedOnParent(getParent)
  }
}


text:
from distutils.core import setup

setup(
    name='xmpp2',
    version='0.4',
    description='An XMPP client',
    long_description='An XMPP client',
    author='Alex Lee',
    author_email='xmpp2@thirdbeat.com',
    maintainer='Alex Lee',
    maintainer_email='xmpp2@thirdbeat.com',
    url='http://xmpp2.thirdbeat.com',
    license='MIT',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Topic :: Communications :: Chat',
        'Topic :: Software Development :: Libraries',
    ],
    packages=['xmpp2', 'xmpp2.handler']
)


text:
<template name="Diners_Page">

        Home

        Craving

        Cravings Available Today

        Rate

        Options

User Dashboard

Craving

            I'm craving:

                <input type="radio" name="craving" checked="" tabindex="0" class="hidden">
                Asian

                <input type="radio" name="craving" tabindex="0" class="hidden">
                Mexican

                <input type="radio" name="craving" tabindex="0" class="hidden">
                Indian

                <input type="radio" name="craving" tabindex="0" class="hidden">
                American

Cravings Available Today

Location: Campus Center, 1st floor

Accepts: Cash, Meal Swipes, Retail Points, Dining Dollars, Bonus Dollars and Credit Cards (Visa, MC, Amex, Discover & Diners)

Today's Menu

Poke Bowl $4.95

Noodles $6.89

Location: Hemenway Hall, 1st floor

Accepts: Cash, Retail Points, Dining Dollars, Meal Swipes and Credit Cards (Visa, MC, Amex, Discover & Diners)

Today's Menu

Pho $6.89

Rate

        <select class="ui search dropdown">
          <option value="">Restaurant</option>
          <option value="AL">Stir Fresh</option>
          <option value="AK">Campus Center</option>
          <option value="AZ">Fried Musubi</option>
          <option value="AZ">BaLe</option>
          </select>
        <select class="ui search dropdown">
          <option value="">Food</option>
          <option value="AL">Poke</option>
          <option value="AK">Noodles</option>
          <option value="AZ">Fried Musubi</option>
        </select>

            Rate

                <input type="radio" name="fruit" checked="" tabindex="0" class="hidden">
                1

                <input type="radio" name="fruit" tabindex="0" class="hidden">
                2

                <input type="radio" name="fruit" tabindex="0" class="hidden">
                3

                <input type="radio" name="fruit" tabindex="0" class="hidden">
                4

Options

</template>


text:
package core.framework.mongo.impl;

import core.framework.mongo.MongoEnumValue;

/**
 * @author neo
 */
public enum TestEnum {
    @MongoEnumValue("I1")
    ITEM1,
    @MongoEnumValue("I2")
    ITEM2
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	  package="com.cbsb.wakelan"
	  android:versionCode="2"
	  android:versionName="1.2">

	<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="13"/>

	<uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

	<supports-screens android:resizeable="false"
					  android:smallScreens="true"
					  android:normalScreens="true"
					  android:largeScreens="true"
					  android:anyDensity="true" />

    <application android:label="@string/app_name"
				 android:icon="@drawable/icon"
				 android:debuggable="false"
				 android:description="@string/app_desc" android:theme="@android:style/Theme.Light">

		<activity android:name="WakeOnLanActivity"
				  android:label="@string/app_name"
				  android:launchMode="singleInstance">

			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>

		<provider android:name="com.cbsb.wakelan.HistoryProvider"
				  android:authorities="com.cbsb.wakelan.historyprovider" />

		  <activity            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode"
            android:name="com.google.ads.AdActivity" />
	</application>
</manifest>


text:
function fullNameBuilder (value, record) {
    return record.data.LastName + ', ' + record.data.FirstName;
}


text:
<?php
namespace Poirot\AuthSystem\Authorize\Interfaces;

use Poirot\AuthSystem\Authenticate\Interfaces\iIdentity;

interface iAuthorize
{
    /**
     * Is allowed to features?
     *
     * - we can use this method event if no user identified
     *   in case that all users has access on home route from
     *   resource object, but only authorized users has access
     *   on other route names, and only AdminUser has access on
     *   admin route
     *
     * @param iIdentity          $role
     * @param iResourceAuthorize $resource
     *
     * @return boolean
     */
    function isAllowed(iIdentity $role = null, iResourceAuthorize $resource = null);
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="60dp"
    tools:context="pma.ftn.weather.fragments.HourlyForecastFragment">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <pma.ftn.weather.utils.CTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:text="Next 12 hours"
            android:textColor="#FFFFFF"
            android:textSize="20sp"
            app:font="Roboto-Light.ttf" />
    </RelativeLayout>

    <ListView
        style="@style/ForecastListStyle"
        android:id="@+id/listview_hourly_forecast"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="40dp"
        android:paddingBottom="30dp"
        android:listSelector="@android:color/transparent"
        android:divider="@null" />
</FrameLayout>


text:
<?php

declare(strict_types=1);

namespace GrumPHP\Console;

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputOption;

class ApplicationConfigurator
{
    const APP_NAME = 'GrumPHP';
    const APP_VERSION = '1.8.0';

    public function configure(Application $application): void
    {
        $application->setVersion(self::APP_VERSION);
        $application->setName(self::APP_NAME);
        $this->registerInputDefinitions($application);
    }

    private function registerInputDefinitions(Application $application): void
    {
        $definition = $application->getDefinition();
        $definition->addOption(
            new InputOption(
                'config',
                'c',
                InputOption::VALUE_REQUIRED,
                'Path to config'
            )
        );
    }
}


text:
{% extends "dnd/languages/language_layout.html" %}

{% load custom_filters %}

{% block title %}{{ language.name }} – Language{% endblock %}

{% block breadcrumbs %}
    » Languages
    » {{ language.name }}
{% endblock %}

{% block admin_edit %}EDIT{% endblock %}

{% block content %}

{{ language.name }}

    {{ language.description_html|safe }}

Races speaking this language

{% include "dnd/races/race_table.html" %}

{% endblock %}


text:
__author__ = "Microsoft Corporation <ptvshelp@microsoft.com>"
__version__ = "3.0.0.0"

import datetime
import os
import sys
import traceback

if sys.version_info[0] == 3:
    def to_str(value):
        return value.decode(sys.getfilesystemencoding())

    def execfile(path, global_dict):
        """Execute a file"""
        with open(path, 'r') as f:
            code = f.read()
        code = code.replace('\r\n', '\n') + '\n'
        exec(code, global_dict)
else:
    def to_str(value):
        return value.encode(sys.getfilesystemencoding())

def log(txt):
    """Logs fatal errors to a log file if WSGI_LOG env var is defined"""
    log_file = os.environ.get('WSGI_LOG')
    if log_file:
        f = open(log_file, 'a+')
        try:
            f.write('%s: %s' % (datetime.datetime.now(), txt))
        finally:
            f.close()

ptvsd_secret = os.getenv('WSGI_PTVSD_SECRET')
if ptvsd_secret:
    log('Enabling ptvsd ...\n')
    try:
        import ptvsd
        try:
            ptvsd.enable_attach(ptvsd_secret)
            log('ptvsd enabled.\n')
        except:
            log('ptvsd.enable_attach failed\n')
    except ImportError:
        log('error importing ptvsd.\n');

def get_wsgi_handler(handler_name):
    if not handler_name:
        raise Exception('WSGI_ALT_VIRTUALENV_HANDLER env var must be set')

    if not isinstance(handler_name, str):
        handler_name = to_str(handler_name)

    module_name, _, callable_name = handler_name.rpartition('.')
    should_call = callable_name.endswith('()')
    callable_name = callable_name[:-2] if should_call else callable_name
    name_list = [(callable_name, should_call)]
    handler = None
    last_tb = ''

    while module_name:
        try:
            handler = __import__(module_name, fromlist=[name_list[0][0]])
            last_tb = ''
            for name, should_call in name_list:
                handler = getattr(handler, name)
                if should_call:
                    handler = handler()
            break
        except ImportError:
            module_name, _, callable_name = module_name.rpartition('.')
            should_call = callable_name.endswith('()')
            callable_name = callable_name[:-2] if should_call else callable_name
            name_list.insert(0, (callable_name, should_call))
            handler = None
            last_tb = ': ' + traceback.format_exc()

    if handler is None:
        raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb))

    return handler

activate_this = os.getenv('WSGI_ALT_VIRTUALENV_ACTIVATE_THIS')
if not activate_this:
    raise Exception('WSGI_ALT_VIRTUALENV_ACTIVATE_THIS is not set')

def get_virtualenv_handler():
    log('Activating virtualenv with %s\n' % activate_this)
    execfile(activate_this, dict(__file__=activate_this))

    log('Getting handler %s\n' % os.getenv('WSGI_ALT_VIRTUALENV_HANDLER'))
    handler = get_wsgi_handler(os.getenv('WSGI_ALT_VIRTUALENV_HANDLER'))
    log('Got handler: %r\n' % handler)
    return handler

def get_venv_handler():
    log('Activating venv with executable at %s\n' % activate_this)
    import site
    sys.executable = activate_this
    old_sys_path, sys.path = sys.path, []

    site.main()

    sys.path.insert(0, '')
    for item in old_sys_path:
        if item not in sys.path:
            sys.path.append(item)

    log('Getting handler %s\n' % os.getenv('WSGI_ALT_VIRTUALENV_HANDLER'))
    handler = get_wsgi_handler(os.getenv('WSGI_ALT_VIRTUALENV_HANDLER'))
    log('Got handler: %r\n' % handler)
    return handler


text:
name             "ossec"
maintainer       "Alexis Le-Quoc"
maintainer_email "alq@datadoghq.com"
license          "Apache 2.0"
description      "Installs/Configures ossec"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          "1.0.14"

%w{ build-essential apt }.each do |pkg|
  depends pkg
end

%w{ debian ubuntu arch redhat centos fedora }.each do |os|
  supports os
end


text:
namespace gfx {

// Base interface for WGL surfaces.
class GLSurfaceWGL : public GLSurface {
 public:
  GLSurfaceWGL();
  virtual ~GLSurfaceWGL();

  // Implement GLSurface.
  virtual void* GetDisplay();

  static bool InitializeOneOff();
  static HDC GetDisplayDC();

 private:
  DISALLOW_COPY_AND_ASSIGN(GLSurfaceWGL);
};

// A surface used to render to a view.
class NativeViewGLSurfaceWGL : public GLSurfaceWGL {
 public:
  explicit NativeViewGLSurfaceWGL(gfx::AcceleratedWidget window);
  virtual ~NativeViewGLSurfaceWGL();

  // Implement GLSurface.
  virtual bool Initialize();
  virtual void Destroy();
  virtual bool IsOffscreen();
  virtual bool SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  gfx::AcceleratedWidget window_;
  gfx::AcceleratedWidget child_window_;
  HDC device_context_;

  DISALLOW_COPY_AND_ASSIGN(NativeViewGLSurfaceWGL);
};

// A surface used to render to an offscreen pbuffer.
class PbufferGLSurfaceWGL : public GLSurfaceWGL {
 public:
  explicit PbufferGLSurfaceWGL(const gfx::Size& size);
  virtual ~PbufferGLSurfaceWGL();

  // Implement GLSurface.
  virtual bool Initialize();
  virtual void Destroy();
  virtual bool IsOffscreen();
  virtual bool SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  gfx::Size size_;
  HDC device_context_;
  void* pbuffer_;

  DISALLOW_COPY_AND_ASSIGN(PbufferGLSurfaceWGL);
};

}  // namespace gfx

#endif  // UI_GL_GL_SURFACE_WGL_H_


text:
package com.nortal.spring.cw.core.web.component.list;

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

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;

import com.nortal.spring.cw.core.web.annotation.component.EventHandler;
import com.nortal.spring.cw.core.web.component.ElementHandler;
import com.nortal.spring.cw.core.web.component.composite.ComponentType;
import com.nortal.spring.cw.core.web.component.composite.ControllerComponent;
import com.nortal.spring.cw.core.web.component.composite.complex.ComplexComponent;
import com.nortal.spring.cw.core.web.component.composite.simple.AbstractTypeComponent;
import com.nortal.spring.cw.core.web.component.element.ElementsGroup;
import com.nortal.spring.cw.core.web.component.element.EventElement;
import com.nortal.spring.cw.core.web.component.element.FormDataElement;
import com.nortal.spring.cw.core.web.component.element.FormElement;
import com.nortal.spring.cw.core.web.component.form.FormElementHolderMapItem;
import com.nortal.spring.cw.core.web.component.list.header.DefaultListHeaderBuilder;
import com.nortal.spring.cw.core.web.component.list.header.ListHeader;
import com.nortal.spring.cw.core.web.component.list.header.ListHeaderBuilder;
import com.nortal.spring.cw.core.web.component.list.holder.EpmPagedListHolder;
import com.nortal.spring.cw.core.web.component.list.row.DefaultListRowBuilder;
import com.nortal.spring.cw.core.web.component.list.row.ListRow;
import com.nortal.spring.cw.core.web.component.list.row.ListRowBuilder;
import com.nortal.spring.cw.core.web.component.list.row.ListRowButtons;
import com.nortal.spring.cw.core.web.component.modal.ModalDialogComponent;
import com.nortal.spring.cw.core.web.exception.FieldNotFoundException;
import com.nortal.spring.cw.core.web.helper.FieldHelper;
import com.nortal.spring.cw.core.web.util.BeanUtil;
import com.nortal.spring.cw.core.web.util.ElementUtil;

/**
 * Üldine listi komponent. Vastavalt vajadusele on võimalik sisse ja välja lülitada tabeli filtreerimine ja sorteerimine
 *
 * @author Margus Hanni
 * @author Alrik Peets
 */
public class EpmListComponent<T> extends AbstractTypeComponent<T> implements ListComponent {

   private static final long serialVersionUID = 1L;
   private static final boolean DEFAULT_SORT_ORDER_ASC = true;
   private final ListRowButtons listRowButtons = new ListRowButtons();

   private List<ListHeader> headers = new ArrayList<>();
   private ElementsGroup<FormElement> formElementsGroup = new ElementsGroup<FormElement>();
   private int cellCount = 0;

   private ElementsGroup<FormElement> newDefaultFormElements;
   private NewRow newRow;

   private ListProperties properties = new ListProperties();
   private ListHeaderBuilder listHeaderBuilder = new DefaultListHeaderBuilder();
   private ListRowBuilder<T> listRowBuilder = new DefaultListRowBuilder<T>();
   private final EpmPagedListHolder<T> pagedListHolder = new EpmPagedListHolder<>(this);

   private ElementHandler addNewRowHandler;
   private ElementHandler deleteRowHandler;
   private ElementHandler editRowHandler;

   private FormElement activeFormElement;
   private ListRow activeListRow;
   private Object activeObject;

   public EpmListComponent(String componentName, Class<T> objectClass, String orderedField, boolean sortOrderAsc) {
      super(componentName, objectClass);

      pagedListHolder.getOrder().setOrderedField(orderedField);
      pagedListHolder.getOrder().setDesc(!sortOrderAsc);
   }

   public EpmListComponent(String componentName, Class<T> objectClass) {
      this(componentName, objectClass, null, DEFAULT_SORT_ORDER_ASC);
   }

   @Override
   @SuppressWarnings("unchecked")
   public <K extends FormElement> K add(String elementFieldPath) {
      return (K) add(elementFieldPath, properties.isSortable(), properties.isFilterable());
   }

   @Override
   @SuppressWarnings("unchecked")
   public <K extends FormElement> K add(FormElement element) {
      return (K) add(element, properties);
   }

   @Override
   public void remove(FormElement element) {
      formElementsGroup.removeByPath(element.getId());
   }

   @SuppressWarnings("unchecked")
   public <K extends FormElement> K add(String elementFieldPath, boolean sortable, boolean filterable) {
      FormElement element = FieldHelper.createElement(getObjectClass(), elementFieldPath);

      return (K) add(element, sortable, filterable);
   }

   @SuppressWarnings("unchecked")
   public <K extends FormElement> K add(FormElement element, boolean sortable, boolean filterable) {

      Assert.isTrue(!isInitialized(), "List is already initialized");

      formElementsGroup.add(element);
      headers.add(new ListHeader(this, element, sortable, filterable, cellCount));

      cellCount++;

      return (K) element;
   }

   private <K extends FormElement> K add(FormElement element, ListProperties properties) {
      return add(element, properties.isSortable(), properties.isFilterable());
   }

   /**
    * Kasutatakse JSP ridade joonistamisel
    *
    * @return
    */
   public List<ListRow> getListRow() {
      Assert.isTrue(pagedListHolder.getDataProvider() != null, "DataSource is not initialized");
      return pagedListHolder.getPageListHolder();
   }

   @SuppressWarnings("unchecked")
   public T getListRowEntity(int rowId) {
      return (T) pagedListHolder.getPageListHolder().get(rowId).getEntity();
   }

   public FormElement getFormElement(int rowId, int cellId) {
      return pagedListHolder.getPageListHolder().get(rowId).getElementsGroup().getByIndex(cellId).getElement();
   }

   public List<FormElement> getFormElements() {
      return Collections.unmodifiableList(formElementsGroup.getList());
   }

   @SuppressWarnings("unchecked")
   public EpmPagedListHolder<T> getPagedListHolder() {
      return pagedListHolder;
   }

   @SuppressWarnings("unchecked")
   public List<T> getActivePageDataList() {
      List<ListRow> dataList = pagedListHolder.getPageListHolder();
      List<T> list = new ArrayList<>(dataList.size());
      for (ListRow row : dataList) {
         if (!row.isDeleted()) {
            list.add((T) row.getEntity());
         }
      }
      return list;
   }

   @SuppressWarnings("unchecked")
   public List<T> getDataList() {
      List<ListRow> dataList = pagedListHolder.getSource();
      List<T> list = new ArrayList<>(dataList.size());
      for (ListRow row : dataList) {
         if (!row.isDeleted()) {
            list.add((T) row.getEntity());
         }
      }
      return list;
   }

   @SuppressWarnings("unchecked")
   public List<T> getNewRowDataList() {
      List<ListRow> allRows = getPagedListHolder().getAllDataRows();
      List<T> list = new ArrayList<>(allRows.size());
      for (ListRow row : allRows) {
         if (!row.isDeleted() && row.isNewRow()) {
            list.add((T) row.getEntity());
         }
      }
      return list;
   }

   public void setDataProvider(ListDataProvider<T> dataProvider) {
      this.pagedListHolder.setDataProvider(dataProvider);
   }

   public List<ListHeader> getListHeader() {
      return headers;
   }

   public ListHeader getHeaderByPath(String fieldPath) {
      for (ListHeader listHeader : headers) {
         if (StringUtils.equals(listHeader.getElement().getId(), fieldPath)) {
            return listHeader;
         }
      }

      throw new FieldNotFoundException(fieldPath);
   }

   @Override
   public boolean validateAndConvert() {
      if (!this.validate()) {
         return false;
      }
      convert();
      return !getBindingResult().hasErrors();
   }

   @Override
   public void convert() {
      for (Iterator<ListRow> iter = pagedListHolder.getPageListHolder().iterator(); iter.hasNext();) {

         ListRow row = iter.next();

         if (row.isDeleted()) {
            continue;
         }
         row.convert();
      }
   }

   @Override
   public boolean validate() {
      for (ListRow row : pagedListHolder.getPageListHolder()) {
         if (!row.isDeleted()) {
            this.setActiveListRow(row);
            row.validate();
         }
      }
      this.setActiveListRow(null);
      return !getBindingResult().hasErrors();
   }

   @SuppressWarnings("unchecked")
   public List<ListRow> getNewRows() {
      return (List<ListRow>) CollectionUtils.select(getPagedListHolder().getAllDataRows(), new Predicate() {

         @Override
         public boolean evaluate(Object object) {
            ListRow listRow = (ListRow) object;
            return listRow.isNewRow();
         }
      });
   }

   public ListProperties getProperties() {
      return properties;
   }

   public int getCellCount() {
      return this.cellCount;
   }

   @Override
   public void refresh() {
      if (getProperties().isAllowAdd() && newRow != null) {
         createNewRow();
      }
      pagedListHolder.setMaxLinkedPages(properties.getMaxLinkedPages());
      pagedListHolder.refresh();
   }

   @Override
   public void refreshData() {
      pagedListHolder.markedToRefreshData();
      refresh();
   }

   public NewRow getNewRow() {
      if (getProperties().isAllowAdd() && newRow == null) {
         createNewRow();
      }

      return newRow;
   }

   public void setEditable(boolean editable) {
      super.setEditable(editable);
      properties.setAllowDeleteButton(editable);
      properties.setAllowEditButton(editable);
   }

   public ElementHandler getAddNewRowHandler() {
      return addNewRowHandler;
   }

   public void setAddNewRowHandler(ElementHandler addNewRowHandler) {
      this.addNewRowHandler = addNewRowHandler;
   }

   public ElementHandler getDeleteRowHandler() {
      return deleteRowHandler;
   }

   public void setDeleteRowHandler(ElementHandler deleteRowHandler) {
      this.deleteRowHandler = deleteRowHandler;
   }

   @Override
   public void initComponent() {
      int lCellCount = 0;

      for (ListHeader header : headers) {
         this.listHeaderBuilder.init(DefaultListHeaderBuilder.listHeaderBuildStrategy, header, lCellCount);
         lCellCount++;
      }

      refresh();

      super.initComponent();
   }

   @EventHandler(eventName = ListComponent.SUBMIT_LIST_SORT)
   public void listSort(ControllerComponent comp, Map<String, String> params) {

      String listComponentName = params.get(ListComponent.SUBMIT_LIST_COMPONENT);
      refreshListComponent(listComponentName);
   }

   /**
    * Kutsutakse välja listi filtreerimisel
    *
    */
   @EventHandler(eventName = ListComponent.SUBMIT_LIST_FILTER)
   public void listFilter(ControllerComponent comp, Map<String, String> params) {

      String listComponentName = params.get(ListComponent.SUBMIT_LIST_COMPONENT);
      refreshListComponent(listComponentName);
   }

   @EventHandler(eventName = ListComponent.SUBMIT_LIST_PAGINATION)
   public void listPagination(ControllerComponent comp, Map<String, String> params) {

      String listComponentName = params.get(ListComponent.SUBMIT_LIST_COMPONENT);

      refreshListComponent(listComponentName);
   }

   /**
    * Uuendame tabeliobjekti
    *
    */
   private void refreshListComponent(String listComponentName) {
      ComplexComponent component = (ComplexComponent) getParent();

      ListComponent listComponent = component.getComponentByKey(listComponentName);
      listComponent.validateAndConvert();

      if (component instanceof ModalDialogComponent) {
         ((ModalDialogComponent) component).show();
      }

      if (!getBindingResult().hasErrors()) {
         listComponent.refresh();
      }
   }

   public ElementHandler getEditRowHandler() {
      return editRowHandler;
   }

   public void setEditRowHandler(ElementHandler editRowHandler) {
      this.editRowHandler = editRowHandler;
   }

   /**
    * Meetod tagastab tabeli päise elemendi, leides elemendi veeru elemendi raha alusel. Elemendi mitte leidmisel on tulemuseks NULL
    *
    */
   public ListHeader getHeaderByElementFieldPath(String elementFieldPath) {
      for (ListHeader header : headers) {
         if (StringUtils.equals(header.getElement().getId(), elementFieldPath)) {
            return header;
         }
      }

      return null;
   }

   /**
    * This has to be called before setDataSource to function
    *
    */
   public EventElement addRowActionButton(EventElement eventElement) {
      listRowButtons.addEventButton(eventElement);
      return eventElement;
   }

   public Map<String, FormElementHolderMapItem> getRowCustomActionButtonsMap() {
      return Collections.unmodifiableMap(listRowButtons.getElementHolder());
   }

   public boolean isHasActionButtons() {
      if (properties.isAllowDeleteButton() || properties.isAllowEditButton()) {
         return true;
      }

      for (ListRow row : getListRow()) {
         if (row.getListRowButtons().isHasActionButtons()) {
            return true;
         }
      }

      return false;
   }

   @Override
   public FormElement getActiveFormElement() {
      return activeFormElement;
   }

   @Override
   public void setActiveFormElement(FormElement activeFormElement) {
      this.activeFormElement = activeFormElement;
   }

   @SuppressWarnings({ "unchecked", "hiding" })
   @Override
   public <T> T getActiveEntity() {
      return (T) activeObject;
   }

   @Override
   public void setActiveEntity(Object activeObject) {
      this.activeObject = activeObject;
   }

   @SuppressWarnings("unchecked")
   public <E> void setListRowBuilder(ListRowBuilder<E> listRowBuilder) {
      this.listRowBuilder = (ListRowBuilder<T>) listRowBuilder;
   }

   public void setListHeaderBuilder(ListHeaderBuilder listHeaderBuilder) {
      this.listHeaderBuilder = listHeaderBuilder;
   }

   public boolean isShowActionColumn() {
      return isHasActionButtons() || properties.isFilterable() || properties.isAllowAdd();
   }

   public boolean getHasData() {
      for (ListRow row : getListRow()) {
         // piisab ühest reast, mis ei ole kustutatud
         if (!row.isDeleted()) {
            return true;
         }
      }

      return false;
   }

   public boolean isShowFilter() {
      return properties.isFilterable() && (getHasData() || !isFilterEmpty());
   }

   public boolean isFilterEmpty() {

      for (ListHeader header : getListHeader()) {

         if (header.getElement() instanceof FormDataElement) {
            FormDataElement dataElement = (FormDataElement) header.getElement();

            if (!ElementUtil.isEmpty(dataElement)) {
               return false;
            }

            // kontrollime üle ka vahemiku
            if (header.isAllowFilterRange()
                  && (!ElementUtil.isEmpty((FormDataElement) header.getBetween().getRight().getElement()) || !ElementUtil
                        .isEmpty((FormDataElement) header.getBetween().getRight().getElement()))) {
               return false;
            }
         }
      }

      return true;
   }

   @Override
   public boolean isEmpty() {
      return CollectionUtils.isEmpty(getDataList()) && CollectionUtils.isEmpty(getNewRows());
   }

   public ListRowBuilder<T> getListRowBuilder() {
      return listRowBuilder;
   }

   @Override
   public ComponentType getComponentType() {
      return ComponentType.LIST;
   }

   public void setActiveListRow(ListRow listRow) {
      this.activeListRow = listRow;
   }

   public ListRow getActiveListRow() {
      return activeListRow;
   }

   public ListRow refreshRow(ListRow listRow, int rowNumber) {
      listRow.setParentElementPath(this);
      return getListRowBuilder().refreshRow(DefaultListRowBuilder.normalElementBuildStrategy, listRow, rowNumber);
   }

   public ListRow buildRow(Object data, int rowNumber) {
      return getListRowBuilder().buildRow(data, this, DefaultListRowBuilder.normalElementBuildStrategy, rowNumber);
   }

   /**
    * Meetod mis tagastab elemendid, koos algsätetega.
    *
    * @return {@link ElementsGroup}
    */
   public ElementsGroup<FormElement> getNewDefaultFormElements() {
      if (newDefaultFormElements == null) {
         newDefaultFormElements = new ElementsGroup<FormElement>();

         for (FormElement element : getFormElements()) {
            FormElement elementClone = (FormElement) BeanUtil.clone(element);
            newDefaultFormElements.add(elementClone);
         }
      }

      return newDefaultFormElements;
   }

   private void createNewRow() {
      ListRow row = listRowBuilder.buildRow(BeanUtils.instantiateClass(getObjectClass()), this,
            DefaultListRowBuilder.newElementBuildStrategy, 0);
      modifyNewRow(row);

      this.newRow = new NewRow(row, this);
   }

   private void modifyNewRow(ListRow newRow) {
      newRow.setNewRow(true);
      newRow.setEditable(true);
   }

   @Override
   public void afterInitComponent() {
      // Nothing to do here
   }
}


text:
ACCEPTED

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

#### Published in
Persoonia 7(4): 555 (1974)

#### Original name
Hydnum informe Rick, 1932

### Remarks
null


text:
namespace ALinq
{
    public interface IAsyncGrouping<out TKey,out TElement> : IAsyncEnumerable<TElement>
    {
        TKey Key { get; }
    }
}


text:
namespace verilog {
namespace analysis {

// ExplicitFunctionTaskParameterTypeRule checks that every function and task
// parameter have explicitly defined a storage type.
class ExplicitFunctionTaskParameterTypeRule
    : public verible::SyntaxTreeLintRule {
 public:
  using rule_type = verible::SyntaxTreeLintRule;

  static const LintRuleDescriptor& GetDescriptor();

  void HandleSymbol(const verible::Symbol& symbol,
                    const verible::SyntaxTreeContext& context) final;

  verible::LintRuleStatus Report() const final;

 private:
  std::set<verible::LintViolation> violations_;
};

}  // namespace analysis
}  // namespace verilog

#endif  // VERIBLE_VERILOG_ANALYSIS_CHECKERS_EXPLICIT_FUNCTION_TASK_PARAMETER_TYPE_RULE_H_


text:
package wb.app.seek.widgets;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import wb.app.seek.R;

/**
 * 列表底部 loading
 * <p>
 * Created by W.b on 05/05/2017.
 */
public class LoadingFooterView {

    public static final int STATE_INIT = 1;
    public static final int STATE_IDLE = 2;
    public static final int STATE_LOADING = 3;
    public static final int STATE_END = 4;

    private final View mView;
    private final ProgressBar mProgressBar;
    private final TextView mTextView;

    protected int mCurrentState = STATE_IDLE;

    private long mAnimDuration;

    public LoadingFooterView(Context context) {
        mView = LayoutInflater.from(context).inflate(R.layout.item_footer, null);
        mProgressBar = (ProgressBar) mView.findViewById(R.id.item_loading_pb);
        mTextView = (TextView) mView.findViewById(R.id.item_loading_status_tv);

        mView.setVisibility(View.GONE);
        mAnimDuration = context.getResources().getInteger(android.R.integer.config_mediumAnimTime);
    }

    public void setState(int state) {

        if (mCurrentState == state)
            return;

        mCurrentState = state;

        mView.setVisibility(View.VISIBLE);

        switch (state) {
            case STATE_LOADING:
                mTextView.setText("加载中...");
                mTextView.setVisibility(View.VISIBLE);
                mTextView.animate().withLayer().alpha(1).setDuration(mAnimDuration);
                mProgressBar.setVisibility(View.VISIBLE);
                break;
            case STATE_END:
                mTextView.setText("没有更多了");
                mTextView.setVisibility(View.VISIBLE);
                mTextView.animate().withLayer().alpha(1).setDuration(mAnimDuration);
                mProgressBar.setVisibility(View.GONE);
                break;
            default:
                mView.setVisibility(View.GONE);
                break;
        }
    }

    public View getView() {
        return mView;
    }
}


text:
namespace blink {

struct WebIDBValue {
  WebIDBValue() {}
  explicit WebIDBValue(const WebData& data) : data(data) {}
  WebIDBValue(const WebData& data, const WebVector<WebBlobInfo>& blobInfo)
      : data(data), webBlobInfo(blobInfo) {}
  WebIDBValue(const WebData& data,
              const WebVector<WebBlobInfo>& blobInfo,
              const WebIDBKey& primaryKey,
              const WebIDBKeyPath& keyPath)
      : data(data),
        webBlobInfo(blobInfo),
        primaryKey(primaryKey),
        keyPath(keyPath) {}

  // The serialized JavaScript bits (ignoring blob data) for this IDB Value.
  // Required value.
  WebData data;
  // Collection of blob info referenced by [[data]]. Optional and empty for
  // values without blobs.
  WebVector<WebBlobInfo> webBlobInfo;
  // The auto-generated primary key and key path. Both are set when IDB is
  // generating keys (and not JavaScript).  Optional; If set then a property
  // named [[keyPath]] will be set to [[primaryKey]] on the deserialized
  // [[data]] object before calling the event handler.
  WebIDBKey primaryKey;
  WebIDBKeyPath keyPath;
};

}  // namespace blink

#endif


text:
package org.arengine.engine;

import java.util.Arrays;

import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.location.Location;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

/**
 * @author Atef Haouari
 *
 *         This view draws the projection of the poi. The method on draw is
 *         called when sensors values changed.
 */
public final class AREngineView extends View implements OnTouchListener {

	/**
	 * Indicates if the view is touched.
	 */
	private boolean touched = false;

	/**
	 * The x of the touched point.
	 */
	private float touchedX = 0;

	/**
	 * The y of the touched point.
	 */
	private float touchedY = 0;

	/**
	 * The projector
	 */
	private Projector projector;

	/**
	 * Gets the projector
	 *
	 * @return The projector
	 */
	protected Projector getProjector() {
		return projector;
	}

	/**
	 * Sets the projector
	 *
	 * @param projector
	 *            The projector
	 */
	protected void setProjector(Projector projector) {
		this.projector = projector;
	}

	/**
	 * the AREngineActivity
	 */
	private AREngineActivity arEngineActivity;

	/**
	 * Constructor of the AREngineView
	 *
	 * @param aREngineActivity
	 *            the AREngineActivity
	 */
	protected AREngineView(AREngineActivity arEngineActivity) {
		super(arEngineActivity, null);
		this.arEngineActivity = arEngineActivity;
		setOnTouchListener(this);

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.view.View#onDraw(android.graphics.Canvas)
	 */
	@Override
	public void onDraw(Canvas canvas) {
		if (projector != null) {
			// Refresh first the projection values
			projector.refresh(Arrays.asList(arEngineActivity.getPoiList()),
					getWidth(), getHeight(),
					arEngineActivity.isFilterDistanceEnabled(),
					arEngineActivity.getMaxDistanceFilter());

			// Draw the custom overlays
			for (CustomOverlay overlay : arEngineActivity.getOverlays()) {
				int savedCount = canvas.save();
				overlay.draw(canvas, projector);
				canvas.restoreToCount(savedCount);
			}

			// Do translation an rotation calculated by the projector
			canvas.rotate((float) projector.getRotation());
			canvas.translate((float) projector.getTranslationX(),
					(float) projector.getTranslationY());

			// Draw the poi projections
			Location curLocation = projector.getCurLocation();
			PoiPainter poiPainter = arEngineActivity.getPoiPainter();

			if (poiPainter == null) {
				poiPainter = arEngineActivity.getDefaultPoiPainter();
			}

			if (curLocation != null && poiPainter != null) {
				for (Poi poi : projector.getPoiList()) {
					int count = canvas.save();

					// Go to the projection point and call the PoiPainter to
					// draw
					// it.
					canvas.translate(poi.getProjectionPoint().x,
							poi.getProjectionPoint().y);
					int countLocal = canvas.save();
					RectF touchableRect = poiPainter.draw(poi, canvas);

					canvas.restoreToCount(countLocal);
					// When the event is touched
					if (touched && touchableRect != null) {
						Matrix matrix = canvas.getMatrix();
						RectF touchableRectMapped = new RectF();
						matrix.mapRect(touchableRectMapped, touchableRect);
						// call the action onTouch if a poi is touched
						if (touchableRectMapped.contains(touchedX, touchedY)) {
							if (arEngineActivity.getPoiTouchListener() != null) {
								arEngineActivity.getPoiTouchListener().onTouch(
										poi);
							}
							touched = false;
						}
					}

					canvas.restoreToCount(count);

				}
			}

		}
		touched = false;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.view.View.OnTouchListener#onTouch(android.view.View,
	 * android.view.MotionEvent)
	 */
	public boolean onTouch(View v, MotionEvent event) {

		touchedX = event.getRawX();
		touchedY = event.getRawY();
		this.touched = true;
		// redraw the force the PoiTouchListener verification
		this.invalidate();
		return false;
	}

}


text:
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">

    <module name="FileTabCharacter"/>
    <module name="SuppressionCommentFilter"/>
    <module name="TreeWalker">
        <property name="cacheFile" value="target/cachefile"/>
        <module name="FileContentsHolder"/>

        <!-- Block Checks -->
        <!-- See http://checkstyle.sf.net/config_blocks.html -->
        <module name="AvoidNestedBlocks"/>
        <module name="EmptyBlock"/>

        <!-- Class Design -->
        <!-- See http://checkstyle.sf.net/config_design.html -->
        <module name="FinalClass"/>
        <module name="HideUtilityClassConstructor"/>
        <module name="InterfaceIsType"/>

        <!-- Coding -->
        <!-- See http://checkstyle.sf.net/config_coding.html -->
        <module name="CovariantEquals"/>
        <module name="DeclarationOrder"/>
        <module name="DefaultComesLast"/>
        <module name="EmptyStatement"/>
        <module name="EqualsAvoidNull"/>
        <module name="EqualsHashCode"/>
        <module name="FallThrough"/>
        <module name="InnerAssignment"/>
        <module name="MissingSwitchDefault"/>
        <module name="ModifiedControlVariable"/>
        <module name="NoFinalizer"/>
        <module name="ParameterAssignment"/>
        <module name="SimplifyBooleanExpression"/>
        <module name="SimplifyBooleanReturn"/>
        <module name="StringLiteralEquality"/>
        <!--<module name="MagicNumber" />-->

        <!-- Imports -->
        <!-- See http://checkstyle.sf.net/config_import.html -->
        <module name="AvoidStarImport"/>
        <module name="IllegalImport"/>
        <module name="RedundantImport"/>
        <module name="UnusedImports"/>

        <!-- Metrics -->
        <!-- See http://checkstyle.sourceforge.net/config_metrics.html -->
        <module name="BooleanExpressionComplexity">
            <property name="max" value="5"/>
        </module>

        <!-- Miscellaneous -->
        <!-- See http://checkstyle.sf.net/config_misc.html -->
        <module name="ArrayTypeStyle"/>
        <module name="UpperEll"/>

        <!-- Modifiers -->
        <!-- See http://checkstyle.sf.net/config_modifiers.html -->
        <module name="RedundantModifier"/>

        <!-- Naming Conventions -->
        <!-- See http://checkstyle.sf.net/config_naming.html -->
        <module name="ConstantName"/>
        <module name="MemberName"/>
        <module name="MethodName"/>
        <module name="MethodTypeParameterName"/>
        <module name="PackageName"/>
        <module name="ParameterName"/>
        <module name="StaticVariableName"/>
        <module name="TypeName">
            <property name="format"
                      value="^[a-zA-Z0-9]*$"/>
            <property name="tokens"
                      value="CLASS_DEF, INTERFACE_DEF, ANNOTATION_DEF"/>
        </module>
        <module name="TypeName">
            <property name="format"
                      value="^[a-zA-Z0-9_]*$"/>
            <property name="tokens"
                      value="ENUM_DEF"/>
        </module>

        <!-- Size Violations -->
        <!-- See http://checkstyle.sf.net/config_sizes.html -->
        <module name="LineLength">
            <property name="max" value="160"/>
        </module>
        <module name="MethodLength"/>
        <module name="ParameterNumber"/>

        <!-- Whitespace -->
        <!-- See http://checkstyle.sf.net/config_whitespace.html -->
        <module name="GenericWhitespace"/>
        <module name="MethodParamPad">
            <property name="allowLineBreaks" value="true"/>
        </module>
        <module name="NoWhitespaceBefore">
            <property name="allowLineBreaks" value="true"/>
        </module>
        <module name="WhitespaceAfter"/>
        <module name="WhitespaceAround">
            <!-- All but RCURLY, to allow e.g. @ComponentScan(basePackages = {"com.auction"}) -->
            <property name="tokens" value="ASSIGN, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, EQUAL, GE, GT, LAND, LCURLY, LE, LITERAL_ASSERT, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, LITERAL_RETURN, LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, SL, SLIST, SL_ASSIGN, SR, SR_ASSIGN, STAR"/>
        </module>

    </module>
</module>


text:
Storage Handler that allows user to Connect/Analyse/Transform Kafka topics.
The workflow is as follow,  first the user will create an external table that is a view over one Kafka topic,
then the user will be able to run any SQL query including write back to the same table or different kafka backed table.

## Usage

### Create Table
Use following statement to create table:
```sql
CREATE EXTERNAL TABLE kafka_table
(`timestamp` timestamp , `page` string,  `newPage` boolean,
 added int, deleted bigint, delta double)
STORED BY 'org.apache.hadoop.hive.kafka.KafkaStorageHandler'
TBLPROPERTIES
("kafka.topic" = "test-topic", "kafka.bootstrap.servers"="localhost:9092");
```
Table property `kafka.topic` is the Kafka Topic to connect to and `kafka.bootstrap.servers` is the Broker connection string.
Both properties are mandatory.
On the write path if such a topic does not exists the topic will be created if Kafka broker admin policy allow such operation.

By default the serializer and deserializer is Json `org.apache.hadoop.hive.serde2.JsonSerDe`.
If you want to switch serializer/deserializer classes you can use alter table.
```sql
ALTER TABLE kafka_table SET TBLPROPERTIES ("kafka.serde.class"="org.apache.hadoop.hive.serde2.avro.AvroSerDe");
```
List of supported Serializer Deserializer:

|Supported Serializer Deserializer|
|-----|
|org.apache.hadoop.hive.serde2.JsonSerDe|
|org.apache.hadoop.hive.serde2.OpenCSVSerde|
|org.apache.hadoop.hive.serde2.avro.AvroSerDe|
|org.apache.hadoop.hive.serde2.lazybinary.LazyBinarySerDe|
|org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe|

#### Table definition
In addition to the user defined payload schema Kafka Storage Handler will append additional columns allowing user to query the Kafka metadata fields:
- `__key` Kafka record key (byte array)
- `__partition` Kafka record partition identifier (int 32)
- `__offset` Kafka record offset (int 64)
- `__timestamp` Kafka record timestamp (int 64)

### Query Table

List the table properties and all the partition/offsets information for the topic.
```sql
Describe extended kafka_table;
```

Count the number of records with Kafka record timestamp within the last 10 minutes interval.

```sql
SELECT count(*) from kafka_table
where `__timestamp` >  1000 * to_unix_timestamp(CURRENT_TIMESTAMP - interval '10' MINUTES);
```
The storage handler allow filter push-down read optimization,
for instance the query above will only read the records with timestamp satisfying the filter predicate.
Please note that such time based seek is only viable if the Kafka broker allow time based lookup (Kafka 0.11 or later versions)

In addition to **time based seek**, the storage handler reader is able to seek to a particular partition offset using the SQL WHERE clause.
Currently only support OR/AND with (<, <=, >=, >)

```sql
SELECT count(*)  from kafka_table
where (`__offset` < 10 and `__offset`>3 and `__partition` = 0)
or (`__partition` = 0 and `__offset` < 105 and `__offset` > 99)
or (`__offset` = 109);
```

User can define a view to take of the last 15 minutes and mask what ever column as follow:

```sql
CREATE VIEW last_15_minutes_of_kafka_table as select  `timestamp`, `user`, delta, added from kafka_table
where `__timestamp` >  1000 * to_unix_timestamp(CURRENT_TIMESTAMP - interval '15' MINUTES);
```

Join the Kafka Stream to Hive table. For instance assume you want to join the last 15 minutes of stream to dimension table like the following.
```sql
CREATE TABLE user_table (`user` string, `first_name` string , age int, gender string, comments string) STORED as ORC ;
```

Join the view of the last 15 minutes to `user_table`, group by user gender column and compute aggregates
over metrics from fact table and dimension table.

```sql
SELECT sum(added) as added, sum(deleted) as deleted, avg(delta) as delta, avg(age) as avg_age , gender
FROM last_15_minutes_of_kafka_table  join user_table on `last_15_minutes_of_kafka_table`.`user` = `user_table`.`user`
GROUP BY gender limit 10;
```

Join the Stream to the Stream it self. In cases where you want to perform some Ad-Hoc query over the last 15 minutes view.
In the following example we show how you can perform classical user retention analysis over the Kafka Stream.
```sql
-- Steam join over the view it self
-- The example is adapted from https://www.periscopedata.com/blog/how-to-calculate-cohort-retention-in-sql
-- Assuming l15min_wiki is a view of the last 15 minutes
select  count( distinct activity.`user`) as active_users, count(distinct future_activity.`user`) as retained_users
from l15min_wiki as activity
left join l15min_wiki as future_activity on
  activity.`user` = future_activity.`user`
  and activity.`timestamp` = future_activity.`timestamp` - interval '5' minutes ;

--  Stream to stream join
-- Assuming wiki_kafka_hive is the entire stream.
select floor_hour(activity.`timestamp`), count( distinct activity.`user`) as active_users, count(distinct future_activity.`user`) as retained_users
from wiki_kafka_hive as activity
left join wiki_kafka_hive as future_activity on
  activity.`user` = future_activity.`user`
  and activity.`timestamp` = future_activity.`timestamp` - interval '1' hour group by floor_hour(activity.`timestamp`);

```

# Configuration

## Table Properties

| Property                            | Description                                                                                | Mandatory | Default                                 |
|-------------------------------------|------------------------------------------------------------------------------------------------------------------------------------|-----------|-----------------------------------------|
| kafka.topic                         | Kafka topic name to map the table to.                                                                                | Yes       | null                                    |
| kafka.bootstrap.servers             | Table property indicating Kafka broker(s) connection string.                                                                       | Yes       | null                                    |
| kafka.serde.class                   | Serializer and Deserializer class implementation.                                                                                | No        | org.apache.hadoop.hive.serde2.JsonSerDe |
| hive.kafka.poll.timeout.ms          | Parameter indicating Kafka Consumer poll timeout period in millis.  FYI this is independent from internal Kafka consumer timeouts. | No        | 5000 (5 Seconds)                        |
| hive.kafka.max.retries              | Number of retries for Kafka metadata fetch operations.                                                                             | No        | 6                                       |
| hive.kafka.metadata.poll.timeout.ms | Number of milliseconds before consumer timeout on fetching Kafka metadata.                                                         | No        | 30000 (30 Seconds)                      |
| kafka.write.semantic                | Writer semantics, allowed values (AT_LEAST_ONCE, EXACTLY_ONCE)                                                         | No        | AT_LEAST_ONCE                           |

### Setting Extra Consumer/Producer properties.
User can inject custom Kafka consumer/producer properties via the Table properties.
To do so user can add any key/value pair of Kafka config to the Hive table property
by prefixing the key with `kafka.consumer` for consumer configs and `kafka.producer` for producer configs.
For instance the following alter table query adds the table property `"kafka.consumer.max.poll.records" = "5000"`
and will inject `max.poll.records=5000` to the Kafka Consumer.
```sql
ALTER TABLE kafka_table SET TBLPROPERTIES ("kafka.consumer.max.poll.records"="5000");
```

# Kafka to Hive ETL PIPE LINE

load form Kafka every Record exactly once
Goal is to read data and commit both data and its offsets in a single Transaction

First create the offset table.
```sql
Drop table kafka_table_offsets;
create table kafka_table_offsets(partition_id int, max_offset bigint, insert_time timestamp);
```

Initialize the table
```sql
insert overwrite table kafka_table_offsets select `__partition`, min(`__offset`) - 1, CURRENT_TIMESTAMP
from wiki_kafka_hive group by `__partition`, CURRENT_TIMESTAMP ;
```
Create the end target table on the Hive warehouse.
```sql
Drop table orc_kafka_table;
Create table orc_kafka_table (partition_id int, koffset bigint, ktimestamp bigint,
 `timestamp` timestamp , `page` string, `user` string, `diffurl` string,
 `isrobot` boolean, added int, deleted int, delta bigint
) stored as ORC;
```
This an example tp insert up to offset = 2 only

```sql
From wiki_kafka_hive ktable JOIN kafka_table_offsets offset_table
on (ktable.`__partition` = offset_table.partition_id
and ktable.`__offset` > offset_table.max_offset and  ktable.`__offset` < 3 )
insert into table orc_kafka_table select `__partition`, `__offset`, `__timestamp`,
`timestamp`, `page`, `user`, `diffurl`, `isrobot`, added , deleted , delta
Insert overwrite table kafka_table_offsets select
`__partition`, max(`__offset`), CURRENT_TIMESTAMP group by `__partition`, CURRENT_TIMESTAMP;
```

Double check the insert
```sql
select max(`koffset`) from orc_kafka_table limit 10;
select count(*) as c  from orc_kafka_table group by partition_id, koffset having c > 1;
```

Repeat this periodically to insert all data.

```sql
From wiki_kafka_hive ktable JOIN kafka_table_offsets offset_table
on (ktable.`__partition` = offset_table.partition_id
and ktable.`__offset` > offset_table.max_offset )
insert into table orc_kafka_table select `__partition`, `__offset`, `__timestamp`,
`timestamp`, `page`, `user`, `diffurl`, `isrobot`, added , deleted , delta
Insert overwrite table kafka_table_offsets select
`__partition`, max(`__offset`), CURRENT_TIMESTAMP group by `__partition`, CURRENT_TIMESTAMP;
```

# ETL from Hive to Kafka

## INSERT INTO
First create the table in have that will be the target table. Now all the inserts will go to the topic mapped by this Table.

```sql
CREATE EXTERNAL TABLE moving_avg_wiki_kafka_hive
(`channel` string, `namespace` string,`page` string, `timestamp` timestamp , avg_delta double )
STORED BY 'org.apache.hadoop.hive.kafka.KafkaStorageHandler'
TBLPROPERTIES
("kafka.topic" = "moving_avg_wiki_kafka_hive_2",
"kafka.bootstrap.servers"="cn105-10.l42scl.hortonworks.com:9092",
-- STORE AS AVRO IN KAFKA
"kafka.serde.class"="org.apache.hadoop.hive.serde2.avro.AvroSerDe");
```

Then insert data into the table. Keep in mind that Kafka is an append only, thus you can not use insert overwrite.
```sql
insert into table moving_avg_wiki_kafka_hive select `channel`, `namespace`, `page`, `timestamp`,
avg(delta) over (order by `timestamp` asc rows between  60 preceding and current row) as avg_delta,
null as `__key`, null as `__partition`, -1, -1 from l15min_wiki;
```


text:
package de.th.wildau.webapp.buchladen.entities;

import de.th.wildau.webapp.buchladen.validator.BICValidator;
import de.th.wildau.webapp.buchladen.validator.IBANValidator;
import de.th.wildau.webapp.buchladen.validator.NameValidator;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 * @author Jan Gabler
 * @author Malte Schwering
 * @version 0.3
 */
@Entity
@Table(name = "PAYMENT_TRANSFER")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "PaymentTransferEntity.findAll", query = "SELECT p FROM PaymentTransferEntity p"),
    @NamedQuery(name = "PaymentTransferEntity.findById", query = "SELECT p FROM PaymentTransferEntity p WHERE p.id = :id"),
    @NamedQuery(name = "PaymentTransferEntity.findByIban", query = "SELECT p FROM PaymentTransferEntity p WHERE p.iban = :iban"),
    @NamedQuery(name = "PaymentTransferEntity.findByBic", query = "SELECT p FROM PaymentTransferEntity p WHERE p.bic = :bic"),
    @NamedQuery(name = "PaymentTransferEntity.findByAccountHolder", query = "SELECT p FROM PaymentTransferEntity p WHERE p.accountHolder = :accountHolder")})
public class PaymentTransferEntity implements Serializable {

    /**
     * Versionsnummer der Serialisierung.
     */
    private static final long serialVersionUID = 1L;

    /**
     * Auto increment ID der Tabelle 'payment_transfer'.
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "ID")
    private Integer id;

    /**
     * IBAN der Tabelle 'payment_transfer'.
     */
    @Size(max = 22)
    @Column(name = "IBAN")
    @NotNull
    @Pattern(regexp = IBANValidator.IBAN_REGEX)
    private String iban;

    /**
     * BIC der Tabelle 'payment_transfer'.
     */
    @Size(max = 11)
    @Column(name = "BIC")
    @NotNull
    @Pattern(regexp = BICValidator.BIC_REGEX)
    private String bic;

    /**
     * Kontoinhaber der Tabelle 'payment_transfer'.
     */
    @Size(max = 255)
    @Column(name = "ACCOUNT_HOLDER")
    @NotNull
    @Pattern(regexp = NameValidator.NAME_REGEX)
    private String accountHolder;

    /**
     * Referenz der 'BookingOrderEntity' zur 'PaymentTransferEntity'.
     */
    @OneToMany(mappedBy = "fkPaymentTransfer")
    private Collection<BookingOrderEntity> bookingOrderEntityCollection;

    /**
     * Referenz der 'PaymentTransferEntity' zur 'RegistredUserEntity'.
     */
    @JoinColumn(name = "FK_REGISTERED_USER_ID", referencedColumnName = "ID")
    @ManyToOne
    private RegisteredUserEntity fkRegisteredUserId;

    /**
     * Konstruktor der Entitäten-Klasse.
     */
    public PaymentTransferEntity() {
    }

    /**
     * Konstruktor der Entitäten-Klasse.
     * @param id ID einer Kontoüberweisungs-Entität
     */
    public PaymentTransferEntity(Integer id) {
        this.id = id;
    }

    /**
     * Liefert die ID zurück.
     * @return ID der Kontoüberweisung
     */
    public Integer getId() {
        return id;
    }

    /**
     * Setzt die ID.
     * @param id ID der Kontoüberweisung
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * Liefert die IBAN zurück.
     * @return IBAN der Kontoüberweisung
     */
    public String getIban() {
        return iban;
    }

    /**
     * Setzt die IBAN.
     * @param iban IBAN der Kontoüberweisung
     */
    public void setIban(String iban) {
        this.iban = iban;
    }

    /**
     * Liefert die BIC zurück.
     * @return BIC der Kontoüberweisung
     */
    public String getBic() {
        return bic;
    }

    /**
     * Setzt die BIC.
     * @param bic BIC der Kontoüberweisung
     */
    public void setBic(String bic) {
        this.bic = bic;
    }

    /**
     * Liefert den Kontoinhaber zurück.
     * @return Kontoinhaber der Kontoüberweisung
     */
    public String getAccountHolder() {
        return accountHolder;
    }

    /**
     * Setzt den Kontoinhaber.
     * @param accountHolder Kontoinhaber der Kontoüberweisung
     */
    public void setAccountHolder(String accountHolder) {
        this.accountHolder = accountHolder;
    }

    /**
     * Liefert Buchungs-Entitäten zurück.
     * @return Buchungen der Kontoüberweisung
     */
    @XmlTransient
    public Collection<BookingOrderEntity> getBookingOrderEntityCollection() {
        return bookingOrderEntityCollection;
    }

    /**
     * Setzt Buchungs-Entitäten.
     * @param bookingOrderEntityCollection Buchungen der Kontoüberweisung
     */
    public void setBookingOrderEntityCollection(Collection<BookingOrderEntity> bookingOrderEntityCollection) {
        this.bookingOrderEntityCollection = bookingOrderEntityCollection;
    }

    /**
     * Liefert Benutzer-Entitäten zurück.
     * @return Benutzer der Kontoüberweisung
     */
    public RegisteredUserEntity getFkRegisteredUserId() {
        return fkRegisteredUserId;
    }

    /**
     * Setzt die Benutzer-Entitäten.
     * @param fkRegisteredUserId Benutzer der Kontoüberweisung
     */
    public void setFkRegisteredUserId(RegisteredUserEntity fkRegisteredUserId) {
        this.fkRegisteredUserId = fkRegisteredUserId;
    }

    /**
     * Generiert einen ID basierten Hashwert.
     * @return Hashwert der ID
     */
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    /**
     * Vergleicht 2 Kontoüberweisungs-Entitäten miteinander.
     * @param object Kontoüberweisung-Entität
     * @return true für gleich, false für ungleich
     */
    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof PaymentTransferEntity)) {
            return false;
        }
        PaymentTransferEntity other = (PaymentTransferEntity) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    /**
     * Liefert einen String mit der ID der Entität zurück.
     * @return String mit der ID der Entität
     */
    @Override
    public String toString() {
        return "de.th.wildau.webapp.buchladen.entities.PaymentTransferEntity[ id=" + id + " ]";
    }

}


text:
package demo.reactive.stream.simple;

import java.util.function.Consumer;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

public class SimpleSubscriber<T> implements Subscriber<T> {
	private final Consumer<T> onNext;
	private final Consumer<Throwable> onError;
	private final Runnable onComplete;
	private SimpleSubscription<T> subscription;
	private volatile boolean completed = false;

	private SimpleSubscriber(Consumer<T> onNext) {
		this.onNext = onNext;
		this.onComplete = null;
		this.onError = null;
	}

	private SimpleSubscriber(Consumer<T> onNext, Consumer<Throwable> onError,
			Runnable onComplete) {
		this.onNext = onNext;
		this.onComplete = onComplete;
		this.onError = onError;
	}

	public static <T> SimpleSubscriber<T> of(Consumer<T> onNext) {
		return new SimpleSubscriber<T>(onNext);
	}

	public static <T> SimpleSubscriber<T> of(Consumer<T> onNext,
			Consumer<Throwable> onError, Runnable onComplete) {
		return new SimpleSubscriber<T>(onNext, onError, onComplete);
	}

	@Override
	@SuppressWarnings("unchecked")
	public void onSubscribe(Subscription subscription) {
		this.subscription = (SimpleSubscription<T>) subscription;
		subscription.request(1);
	}

	@Override
	public void onNext(T t) {
		if (onNext != null)
			onNext.accept(t);
		if (!completed)
			subscription.request(1);
	}

	@Override
	public void onError(Throwable t) {
		if (onError != null)
			onError.accept(t);
	}

	@Override
	public void onComplete() {
		completed = true;
		if (onComplete != null)
			onComplete.run();

	}

}


text:
layout: post
title: Tweets
date: 2018-12-21
summary: These are the tweets for December 21, 2018.
categories:
---


text:
<?php sfLoader::loadHelpers('I18N') ?>
<div class="navmn">
			<?php if($sf_context->getModuleName() == 'instruction'): ?>
				<?php echo link_to(__('Instructions',null,'common'),'instruction/home','class="active"'); ?>
			<?php else: ?>
				<?php echo link_to(__('Instructions',null,'common'),'instruction/home'); ?>
			<?php endif; ?>
			<?php if($sf_context->getModuleName() == 'product'): ?>
				<?php echo link_to(__('Product',null,'common'),'product/list','class=active'); ?>
			<?php else: ?>
				<?php echo link_to(__('Product',null,'common'),'product/list'); ?>
			<?php endif; ?>
			<?php if($sf_context->getModuleName() == 'gallery'): ?>
				<?php echo link_to(__('Gallery',null,'common'),'gallery/list','class=active'); ?>
			<?php else: ?>
				<?php echo link_to(__('Gallery',null,'common'),'gallery/list'); ?>
			<?php endif; ?>
			<?php echo link_to(__('Sign Out',null,'common'),'default/signOut'); ?>
</div>


text:
<?php
/**
 * Checks for Plugin Territory Guidelines.
 *
 * See http://make.wordpress.org/themes/guidelines/guidelines-plugin-territory/
 */

class Plugin_Territory implements themecheck {
	protected $error = array();

	function check( $php_files, $css_files, $other_files ) {
		$ret = true;
		$php = implode( ' ', $php_files );

		// Functions that are required to be removed from the theme.
		$forbidden_functions = array(
			'register_post_type',
			'register_taxonomy',
		);

		foreach ( $forbidden_functions as $function ) {
			checkcount();
			if ( preg_match( '/[\s?]' . $function . '\(/', $php ) ) {
				$this->error[] = '' . __( 'REQUIRED', 'theme-check').': ' . sprintf( __( 'The theme uses the %s function, which is plugin-territory functionality.', 'theme-check' ), '' . esc_html( $function ) . '()' ) ;
				$ret = false;
			}
		}

		// Shortcodes can't be used in the post content, so warn about them.
		if ( false !== strpos( $php, 'add_shortcode' ) ) {
			checkcount();
			$this->error[] = '' . __( 'WARNING', 'theme-check').': ' . sprintf( __( 'The theme uses the %s function. Custom post-content shortcodes are plugin-territory functionality.', 'theme-check' ), 'add_shortcode()' ) ;
			$ret = false;
		}

		return $ret;
	}

	function getError() { return $this->error; }
}
$themechecks[] = new Plugin_Territory;


text:
using System;
using NServiceBus;

public partial class CoreSagaMetadataTests
{
    public class DelegateCallingSaga : Saga<DelegateCallingSaga.SagaData>
    {
        public class SagaData : ContainSagaData
        {
            public string Correlation { get; set; }
        }

        protected override void ConfigureHowToFindSaga(SagaPropertyMapper<SagaData> mapper)
        {
            Action action = () => mapper.ConfigureMapping<MessageA>(msg => msg.Correlation).ToSaga(saga => saga.Correlation);
            action();
        }
    }
}
/* IL:
DelegateCallingSaga.ConfigureHowToFindSaga:
IL_0000:  newobj      UserQuery+DelegateCallingSaga+<>c__DisplayClass1_0..ctor
IL_0005:  dup
IL_0006:  ldarg.1
IL_0007:  stfld       UserQuery+DelegateCallingSaga+<>c__DisplayClass1_0.mapper
IL_000C:  ldftn       UserQuery+DelegateCallingSaga+<>c__DisplayClass1_0.<ConfigureHowToFindSaga>b__0
IL_0012:  newobj      System.Action..ctor
IL_0017:  callvirt    System.Action.Invoke
IL_001C:  ret
*/


text:
class CefFindHandlerCToCpp
    : public CefCToCpp<CefFindHandlerCToCpp, CefFindHandler,
        cef_find_handler_t> {
 public:
  explicit CefFindHandlerCToCpp(cef_find_handler_t* str)
      : CefCToCpp<CefFindHandlerCToCpp, CefFindHandler, cef_find_handler_t>(
          str) {}
  virtual ~CefFindHandlerCToCpp() {}

  // CefFindHandler methods
  virtual void OnFindResult(CefRefPtr<CefBrowser> browser, int identifier,
      int count, const CefRect& selectionRect, int activeMatchOrdinal,
      bool finalUpdate) OVERRIDE;
};

#endif  // BUILDING_CEF_SHARED
#endif  // CEF_LIBCEF_DLL_CTOCPP_FIND_HANDLER_CTOCPP_H_


text:
namespace {

constexpr float kDefaultAspectRatio = 16.0 / 9.0f;
constexpr gfx::Size kMinimumEcheSize(240, 240);

}  // namespace

std::unique_ptr<WebAppInstallInfo> CreateWebAppInfoForEcheApp() {
  std::unique_ptr<WebAppInstallInfo> info =
      std::make_unique<WebAppInstallInfo>();
  info->start_url = GURL(ash::eche_app::kChromeUIEcheAppURL);
  info->scope = GURL(ash::eche_app::kChromeUIEcheAppURL);
  // |title| should come from a resource string, but this is the Eche app, and
  // doesn't have one.
  info->title = u"Eche App";
  web_app::CreateIconInfoForSystemWebApp(
      info->start_url,
      {{"app_icon_256.png", 256, IDR_ASH_ECHE_APP_ICON_256_PNG}}, *info);
  info->theme_color = 0xFFFFFFFF;
  info->background_color = 0xFFFFFFFF;
  info->display_mode = blink::mojom::DisplayMode::kMinimalUi;
  info->user_display_mode = web_app::UserDisplayMode::kStandalone;

  return info;
}

EcheSystemAppDelegate::EcheSystemAppDelegate(Profile* profile)
    : ash::SystemWebAppDelegate(ash::SystemWebAppType::ECHE,
                                "Eche",
                                GURL("chrome://eche-app"),
                                profile) {}

std::unique_ptr<WebAppInstallInfo> EcheSystemAppDelegate::GetWebAppInfo()
    const {
  return CreateWebAppInfoForEcheApp();
}
bool EcheSystemAppDelegate::ShouldCaptureNavigations() const {
  return true;
}
bool EcheSystemAppDelegate::ShouldShowInLauncher() const {
  return false;
}
bool EcheSystemAppDelegate::ShouldShowInSearch() const {
  return false;
}

bool EcheSystemAppDelegate::ShouldAllowResize() const {
  return false;
}

bool EcheSystemAppDelegate::ShouldAllowMaximize() const {
  return false;
}

bool EcheSystemAppDelegate::ShouldHaveReloadButtonInMinimalUi() const {
  return false;
}

bool EcheSystemAppDelegate::ShouldAllowScriptsToCloseWindows() const {
  // For debug purposes, we do not allow closing windows via script under the
  // debug mode.
  return !base::FeatureList::IsEnabled(chromeos::features::kEcheSWADebugMode);
}

gfx::Rect EcheSystemAppDelegate::GetDefaultBounds(Browser* browser) const {
  return GetDefaultBoundsForEche();
}

bool EcheSystemAppDelegate::IsAppEnabled() const {
  return base::FeatureList::IsEnabled(chromeos::features::kEcheSWA);
}

// TODO(nayebi): Remove this after migrating completely from SWA to bubble.
gfx::Rect EcheSystemAppDelegate::GetDefaultBoundsForEche() const {
  // Ensures the Eche bounds is always 16:9 portrait aspect ratio and not more
  // than half of the windows.
  gfx::Rect bounds =
      display::Screen::GetScreen()->GetDisplayForNewWindows().work_area();
  const float bounds_aspect_ratio =
      static_cast<float>(bounds.width()) / bounds.height();
  const bool is_landscape = (bounds_aspect_ratio >= 1);
  auto new_width = is_landscape ? (bounds.height() / 2) : bounds.width() / 2;
  if (kMinimumEcheSize.width() > new_width) {
    new_width = kMinimumEcheSize.width();
  }
  bounds.ClampToCenteredSize(
      gfx::Size(new_width, new_width * kDefaultAspectRatio));
  return bounds;
}


text:
title: The Workspace
layout: tutorial
prev: 100-prerequisites.html
next: 300-application.html
summary: Setup a bnd(tools) workspace
---

## What you will learn in this section
We will setup a bnd(tools) workspace for enRoute so we can build an application in the next section.

Before you start this section, make sure you've checked the [prerequisites](100-prerequisites.html) for enRoute on your platform.

## The Workspace

A workspace is a directory that has a specific layout so that bnd(tools) knows how to treat your projects. Since we will work in Eclipse we actually have 2 workspaces. The Eclipse workspace is a directory where Eclipse keeps its metadata and we keep that separated from the bnd(tools) workspace.

Since a bnd workspace for enRoute has some specific setup, we clone the workspace from a Github project, [osgi/workspace](https://github.com/osgi/workspace).

So start an Eclipse Luna session and select a workspace. For our tutorials in OSGi enRoute we use the com.acme.prime workspace name, which is also the directory name. Let's place this test workspace in our home directory at `~/eclipse/com.acme.prime`.

Select `File/Switch Workspace/Other ...`. This gives you the following dialog:

![Switch Workspace]({{ site.baseurl }}/img/qs/qs-switch-0.png)

After filling in the proper path and then closing the dialog by clicking `OK`, we get an Eclipse restart and should finally get:

![Start Screen]({{ site.baseurl }}/img/qs/qs-switch-1.png)

### Import the Archetype Workspace

We can ignore the welcome screen. The next step is to link this Eclipse workspace to a bnd workspace. We therefore need to clone the [osgi/workspace](https://github.com/osgi/workspace). This process uses EGit, it is a tad cumbersome, quite a few steps.

Select `File/Import`.

![Import archetype]({{ site.baseurl }}/img/qs/git-import-0.png)

Then select the `Projects from Git`.

![Import archetype]({{ site.baseurl }}/img/qs/git-import-1.png)

If you click `Next` you should be see the following:

![Import archetype]({{ site.baseurl }}/img/qs/git-import-2.png)

Select `Clone URI`, then `Next`, which gives us the window where we should enter the URI to the repository.

![Import archetype]({{ site.baseurl }}/img/qs/git-import-3.png)

You should then enter the URI; the URI that we should use is

> `https://github.com/osgi/workspace.git`

Select `Next` and then select the `master` branch.

![Import archetype]({{ site.baseurl }}/img/qs/git-import-4.png)

Then select `Next` to go to the page where we will tell EGit to store our Git/bnd workspace in your file system.

![Import archetype]({{ site.baseurl }}/img/qs/git-import-5.png)

By default Git places the projects in a sub directory `git` of your home directory (`~/git/...`). (This is an Eclipse preference.) We will follow this rather sane convention. However, the default name of the workspace is 'workspace' so we want to rename this to `com.acme.prime`.

So click `Next`, which will bring us to a page asking us if we should import the projects in this workspace. A resounding yes! (Even if there is only a single `cnf` project.)

![Import archetype]({{ site.baseurl }}/img/qs/git-import-6.png)

When you click `Next` you get on a bit deja vu page but there is probably some reason we don't get.

![Import archetype]({{ site.baseurl }}/img/qs/git-import-7.png)

So just click `Finish`. Which should give you a fresh new workspace, only beaten by the smell of freshly baked bread!

![Import archetype]({{ site.baseurl }}/img/qs/git-import-8.png)

We've now created a workspace that will allow us to play with enRoute. Maybe a bit cumbersome with all the EGit steps but once you've mastered it is quite fast since most pages are just clicking `Next` to accept the defaults.

You have to restart Eclipse since there is a small chance that Eclipse will by default place new projects in the Eclipse workspace and not, as is absolutely required, in the Git/bnd workspace.
{: .bug}

Now, select the `Bndtools` perspective with `Window/Open Perspective .../Other ...'. This opens a selection dialog:

![Perspective Selection Dialog]({{ site.baseurl }}/img/qs/workspace-bndtools-0.png)

Selecting `Bndtools` and clicking `OK` ensures that you are in the proper perspective. Your Eclipse should look similar to (at least after you refresh the repository view at the left bottom):

![Perspective Selection Dialog]({{ site.baseurl }}/img/qs/workspace-bndtools-1.png)

### File System

Since we made changes to your file system, a short summary of where we placed what.

The Eclipse workspace was placed in a special place for Eclipse workspaces, the `~/eclipse` directory. We named this workspace `com.acme.prime`, which is a good name. The bnd workspace was placed also in your home directory, in the `~/git` directory, also under the name `com.acme.prime`; keeping the related Eclipse and Git/bnd workspace named identical is a a good practice.

	~/
		git/
			com.acme.prime/
				cnf/
					ext/
					build.bnd
					...
		eclipse/
			com.acme.prime/
				.metadata/
					...

## Next

In the next section of this quick start tutorial we will create a sample application.


text:
/*
 * (C) 2007-2012 Alibaba Group Holding Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * Authors:
 *   wuhua <wq163@163.com> , boyan <killme2008@gmail.com>
 */
package com.taobao.metamorphosis.client.extension;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.taobao.metamorphosis.client.consumer.ConsumerConfig;

/**
 *
 * @author ÎÞ»¨
 * @since 2011-6-13 ÏÂÎç06:41:33
 */

public class MetaBroadcastMessageSessionFactoryTest {

    @Test
    public void testUpdateGroupForBroadcast() throws Exception {
        final ConsumerConfig consumerConfig = new ConsumerConfig("test");
        MetaBroadcastMessageSessionFactory.updateGroupForBroadcast(consumerConfig);
        assertFalse("test".equals(consumerConfig.getGroup()));
        assertTrue(consumerConfig.getGroup().startsWith("test"));
        assertFalse(consumerConfig.getGroup().contains("."));
        System.out.println(consumerConfig.getGroup());
    }
}


text:
class RepositoryController < Repository::BaseController

  # /repository
  def index
    repos = Repo.for_org(current_user.org_id)
    bootstrap repos, :type => Repo

    commands = Command.for_repos(repos)
    bootstrap commands, :type => Command
  end

  def show
    repo = Repo.find(_id)
    bootstrap repo
    bootstrap Command.for_repos([repo]), :type => Command
  end

  def new
  end

end


text:
BOOL WINAPI DllMain(
	_In_ HINSTANCE hinstDLL,
	_In_ DWORD     fdwReason,
	_In_ LPVOID    lpvReserved
) {

	switch (fdwReason) {
	case DLL_PROCESS_ATTACH:

		CreateDirectoryA("Recv", NULL);
		CreateDirectoryA("Send", NULL);
		PutJMP(Get_Recv(), Hook_Recv);
		PutJMP(Get_Send(), Hook_Send);
		break;
	default:
		break;
	}
	return 1;
}


text:
{% extends "miniblog/blog_note.html" %}
{% block comment %}

{% endblock comment %}


text:
package org.mockito.internal.junit;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.mockito.mock.MockCreationSettings;
import org.mockito.plugins.MockitoLogger;

/**
 * Reports stubbing argument mismatches to the supplied logger
 */
public class MismatchReportingTestListener implements MockitoTestListener {

    private final MockitoLogger logger;
    private List<Object> mocks = new LinkedList<>();

    public MismatchReportingTestListener(MockitoLogger logger) {
        this.logger = logger;
    }

    @Override
    public void testFinished(TestFinishedEvent event) {
        Collection<Object> createdMocks = mocks;
        // At this point, we don't need the mocks any more and we can mark all collected mocks for
        // gc
        // TODO make it better, it's easy to forget to clean up mocks and we still create new
        // instance of list that nobody will read, it's also duplicated
        mocks = new LinkedList<>();

        if (event.getFailure() != null) {
            // print unused stubbings only when test succeeds to avoid reporting multiple problems
            // and confusing users
            new ArgMismatchFinder()
                    .getStubbingArgMismatches(createdMocks)
                    .format(event.getTestName(), logger);
        }
    }

    @Override
    public void onMockCreated(Object mock, MockCreationSettings settings) {
        this.mocks.add(mock);
    }
}


text:
namespace WebKit {
class WebLayerImpl;

class WebScrollbarLayerImpl : public WebScrollbarLayer {
public:
    WEBKIT_COMPOSITOR_BINDINGS_EXPORT WebScrollbarLayerImpl(
        WebScrollbar*, WebScrollbarThemePainter, WebScrollbarThemeGeometry*);
    virtual ~WebScrollbarLayerImpl();

    // WebScrollbarLayer implementation.
    virtual WebLayer* layer() OVERRIDE;
    virtual void setScrollLayer(WebLayer*) OVERRIDE;

private:
    scoped_ptr<WebLayerImpl> m_layer;
};

}

#endif // WebScrollbarLayerImpl_h


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mn.NewsCms.Web.WebLogic
{
    public class ManualActionCacheAttribute : ActionFilterAttribute
    {
        public ManualActionCacheAttribute()
        {
        }

        public int Duration { get; set; }

        private string cachedKey = null;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string key = filterContext.HttpContext.Request.Url.PathAndQuery;
            this.cachedKey = "CustomResultCache-" + key.ToLower();
            if (filterContext.HttpContext.Cache[this.cachedKey] != null)
            {
                filterContext.Result = (ActionResult)filterContext.HttpContext.Cache[this.cachedKey];
            }
            else
            {
                base.OnActionExecuting(filterContext);
            }
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.HttpContext.Cache.Add(this.cachedKey, filterContext.Result, null, DateTime.Now.AddSeconds(Duration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
            base.OnActionExecuted(filterContext);
        }
    }
}


text:
struct Foo<T>;

impl<T> Foo<T> {
    fn shadow_in_method<T>(&self) {}
    //~^ ERROR type parameter `T` shadows another type parameter

    fn not_shadow_in_item<U>(&self) {
        struct Bar<T, U>; // not a shadow, separate item
        fn foo<T, U>() {} // same
    }
}

trait Bar<T> {
    fn shadow_in_required<T>(&self);
    //~^ ERROR type parameter `T` shadows another type parameter

    fn shadow_in_provided<T>(&self) {}
    //~^ ERROR type parameter `T` shadows another type parameter

    fn not_shadow_in_required<U>(&self);
    fn not_shadow_in_provided<U>(&self) {}
}

fn main() {}


text:
from numpy.testing import Tester
test = Tester().test
del Tester


text:
package com.globallogic.mykolaiv.campustrainees.simplewebapp.messaging;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ErrorHandler;

@Service
public class EmailErrorHandler implements ErrorHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void handleError(Throwable t) {
        logger.error("Exception during sending email", t.getMessage());
    }
}


text:
require "spec_helper"

describe Contactmailer do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
namespace FCT.EPS.DataEntities
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    [Table("tblPaymentNotification")]
    public partial class tblPaymentNotification
    {
        [Key]
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
        public int NotificationID { get; set; }

        public int? PaymentTransactionID { get; set; }

        [Required]
        [StringLength(50)]
        public string PaymentReferenceNumber { get; set; }

        [StringLength(50)]
        public string FCTTrustAccountNumber { get; set; }

        public decimal Amount { get; set; }

        public DateTime? PaymentDateTime { get; set; }

        [StringLength(50)]
        public string OriginatorName { get; set; }

        [StringLength(50)]
        public string OriginalorAccountNumber { get; set; }

        [Required]
        [StringLength(20)]
        public string NotificationType { get; set; }

        public int StatusID { get; set; }

        [StringLength(400)]
        public string AdditionalInfo { get; set; }

        [StringLength(16)]
        public string PaymentBatchID { get; set; }

        public int NumberRetried { get; set; }

        public DateTime LastModifyDate { get; set; }

        [StringLength(100)]
        public string PaymentBatchDescription { get; set; }

        public int? PaymentStatusCode { get; set; }

        [ForeignKey("StatusID")]
        public virtual tblEPSStatus tblEPSStatus { get; set; }

        [ForeignKey("NotificationType,PaymentStatusCode")]
        public virtual tblPaymentStatus tblPaymentStatus { get; set; }

        [ForeignKey("PaymentTransactionID")]
        public virtual tblPaymentTransaction tblPaymentTransaction { get; set; }

    }
}


text:
namespace asio {
namespace detail {

template <typename T>
inline T& global()
{
#if !defined(ASIO_HAS_THREADS)
  return null_global<T>();
#elif defined(ASIO_WINDOWS)
  return win_global<T>();
#elif defined(ASIO_HAS_PTHREADS)
  return posix_global<T>();
#elif defined(ASIO_HAS_STD_CALL_ONCE)
  return std_global<T>();
#endif
}

} // namespace detail
} // namespace asio

#endif // ASIO_DETAIL_GLOBAL_HPP


text:
<?php $this->load->view('header_nav'); ?>

Registro de Asistencia

                    Grupo

                    <select name="COD_GRUPO" class="selectpicker form-control tablaDatos" data-live-search = "true" id="COD_GRUPO">
                        <option value="NADA">--SELECCIONE--</option>
                            <?php
                                foreach ($grupo as $fila) {
                                ?>
                                <option value="<?= $fila->COD_GRUPO ?>"><?= $fila->NOM_GRADO, " ",$fila->NUM_GRUPO?></option>
                                <?php
                                 }
                            ?>
                        </select>

                    <button class="btn btn-info form-control" id="btnBuscar"> Buscar</button>

                    <button class="btn btn-success form-control" id="btnRegistrar"> Registrar
                    </button>

Consultar Excusa

                            Estudiante *

                                <select name="DOC_EST" id="DOC_EST" class="selectpicker form-control" data-live-search="true">
                                    <option value="">--SELECCIONAR--</option>
                                    <?php
                                      foreach ($estudiante as $filas)
                                      {
                                   ?>
                                   <option value="<?= $filas->DOC_EST ?>" data-subtext="<?= $filas->DOC_EST ?>">
                                   <?=$filas->NOM1_EST," ",$filas->NOM2_EST," ",$filas->APE1_EST ?></option>
                                   <?php
                                        }
                                    ?>
                                </select>

                                <button class="btn btn-primary form-control" id="btnConsultar"> Consultar
                                </button>

                                N°
                                Documento
                                Estudiante
                                No Asistió

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

                <form action="#" id="form" class="form-horizontal">

El estudiante  con documento de identidad N°,
                             presenta las siguientes excusas.

                                    Fecha de la falta
                                    Excusa

                </form>

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

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

                <form action="#" id="form" class="form-horizontal">

                </form>

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