text:
package com.intellij.openapi.project;

import com.intellij.ide.caches.FileContent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.vfs.InvalidVirtualFileAccessException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

/**
* @author peter
*/
@SuppressWarnings({"SynchronizeOnThis"})
public class FileContentQueue {
  private static final Logger LOG = Logger.getInstance("#com.intellij.ide.startup.FileContentQueue");
  private static final long SIZE_THRESHOLD = 1024*1024;
  private long myTotalSize;

  private final ArrayBlockingQueue<FileContent> myQueue = new ArrayBlockingQueue<FileContent>(256);
  private Queue<FileContent> myPushbackBuffer = new ArrayDeque<FileContent>();

  public void queue(final Collection<VirtualFile> files, @Nullable final ProgressIndicator indicator) {
    final Runnable contentLoadingRunnable = new Runnable() {
      public void run() {
        try {
          for (VirtualFile file : files) {
            if (indicator != null) {
              indicator.checkCanceled();
            }
            put(file);
          }

          // put end-of-queue marker only if not canceled
          try {
            myQueue.put(new FileContent(null));
          }
          catch (InterruptedException e) {
            LOG.error(e);
          }
        }
        catch (ProcessCanceledException e) {
          // Do nothing, exit the thread.
        }
        catch (InterruptedException e) {
          LOG.error(e);
        }
      }
    };

    ApplicationManager.getApplication().executeOnPooledThread(contentLoadingRunnable);
  }

  private void put(VirtualFile file) throws InterruptedException {
    FileContent content = new FileContent(file);

    if (file.isValid() && !file.isDirectory()) {
      if (!doLoadContent(content)) {
        content.setEmptyContent();
      }
    }
    else {
      content.setEmptyContent();
    }

    myQueue.put(content);
  }

  private boolean doLoadContent(final FileContent content) throws InterruptedException {
    final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    final long contentLength = content.getLength();

    boolean counterUpdated = false;
    try {
      if (contentLength < PersistentFS.MAX_INTELLISENSE_FILESIZE) {
        synchronized (this) {
          while (myTotalSize > SIZE_THRESHOLD) {
            if (indicator != null) {
              indicator.checkCanceled();
            }
            wait(300);
          }
          myTotalSize += contentLength;
          counterUpdated = true;
        }

        content.getBytes(); // Reads the content bytes and caches them.
      }

      return true;
    }
    catch (Throwable e) {
      if (counterUpdated) {
        synchronized (this) {
          myTotalSize -= contentLength;   // revert size counter
          notifyAll();
        }
      }
      if (e instanceof ProcessCanceledException) throw (ProcessCanceledException)e;
      if (e instanceof InterruptedException) throw (InterruptedException)e;

      if (e instanceof IOException || e instanceof InvalidVirtualFileAccessException) LOG.info(e);
      else if (ApplicationManager.getApplication().isUnitTestMode()) {
        e.printStackTrace();
      }
      else {
        LOG.error(e);
      }

      return false;
    }
  }

  @Nullable
  public FileContent take() {
    FileContent result;
    synchronized (this) {
      result = myPushbackBuffer.poll();
      if (result != null) {
        return result;
      }
    }

    try {
      result = myQueue.take();
    }
    catch (InterruptedException e) {
      throw new RuntimeException(e);
    }

    final VirtualFile file = result.getVirtualFile();
    if (file == null) {
      try {
        myQueue.put(result); // put it back to notify the others
      }
      catch (InterruptedException ignore) {
        // should not happen
      }
      return null;
    }
    if (result.getLength() < PersistentFS.MAX_INTELLISENSE_FILESIZE) {
      synchronized (this) {
        try {
          myTotalSize -= result.getLength();
        }
        finally {
          notifyAll();
        }
      }
    }

    return result;
  }

  public synchronized void pushback(@NotNull FileContent content) {
    myPushbackBuffer.add(content);
  }
}


text:
require 'spec_helper'

describe DataMapper::State::Loaded, '#update_tracker' do
  let(:tracker)       { {} }

  let(:object)        { described_class.new(mapper, domain_object) }
  let(:mapper)        { DummyMapper.new                           }
  let(:domain_object) { DomainObject.new(:foo, :bar) }

  subject { object.update_tracker(tracker) }

  it_should_behave_like 'a command method'

  it 'should add object to tracker' do
    subject
    tracker.should == { domain_object => object }
  end

  it 'should return self' do
    should be(object)
  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace audio
{
namespace priv
{
void listener_impl::set_volume(float volume)
{
    al_check(alListenerf(AL_GAIN, volume));
}

void listener_impl::set_position(const float3& position)
{
    al_check(alListenerfv(AL_POSITION, position.data()));
}

void listener_impl::set_velocity(const float3& velocity)
{
    al_check(alListenerfv(AL_VELOCITY, velocity.data()));
}

void listener_impl::set_orientation(const float3& direction, const float3& up)
{
    // orientation { norm(at), norm(up) };
    float orientation6[] = {-direction[0], -direction[1], -direction[2], up[0], up[1], up[2]};
    al_check(alListenerfv(AL_ORIENTATION, orientation6));
}
}
}


text:
.. Tori documentation master file, created by
   sphinx-quickstart on Fri Feb 17 21:37:41 2012.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Tori Framework
==============

:Author: Juti Noppornpitak <jnopporn@shiroyuki.com>

Tori is a collection of libraries, micro web framework based on Facebook's
Tornado framework 2.x and the ORM for MongoDB and supports Python 2.7+ and
Python 3.3+. (Read more from the :doc:`manual/introduction`.)

How to Install?
---------------

See **Installation** from :doc:`manual/getting_started`.

What's next?
------------

Read:

- :doc:`manual/index` to get started and learn how to use it.
- :doc:`api/index` to get the reference on APIs and methods.
- :doc:`changes` to see what have been changed.

.. toctree::
   :maxdepth: 1
   :glob:
   :hidden:

   manual/index
   api/index
   changes

Not working after upgrade?
--------------------------

File a bug at `Tori on GitHub <https://github.com/shiroyuki/Tori>`_.

What if the documentation is suck or the code is buggy?
-------------------------------------------------------

If the document is unclear or missing or needs improvement, please help us by
contributing to the codebase of `Tori on GitHub <https://github.com/shiroyuki/Tori>`_.

Special Thanks
--------------

This project is not possible without helps and guidance from
`Guilherme Blanco <http://phpork.net/>`_ from
`Doctrine (PHP) <http://doctrine-project.org>`_.

Indices and Modules
-------------------

* :ref:`genindex`
* :ref:`modindex`

.. * :ref:`search`


text:
package members

import (
	"github.com/gophercloud/gophercloud"
	"github.com/gophercloud/gophercloud/pagination"
)

// ListOpts allows the filtering and sorting of paginated collections through
// the API. Filtering is achieved by passing in struct field values that map to
// the floating IP attributes you want to see returned. SortKey allows you to
// sort by a particular network attribute. SortDir sets the direction, and is
// either `asc' or `desc'. Marker and Limit are used for pagination.
type ListOpts struct {
	Status       string `q:"status"`
	Weight       int    `q:"weight"`
	AdminStateUp *bool  `q:"admin_state_up"`
	TenantID     string `q:"tenant_id"`
	PoolID       string `q:"pool_id"`
	Address      string `q:"address"`
	ProtocolPort int    `q:"protocol_port"`
	ID           string `q:"id"`
	Limit        int    `q:"limit"`
	Marker       string `q:"marker"`
	SortKey      string `q:"sort_key"`
	SortDir      string `q:"sort_dir"`
}

// List returns a Pager which allows you to iterate over a collection of
// members. It accepts a ListOpts struct, which allows you to filter and sort
// the returned collection for greater efficiency.
//
// Default policy settings return only those members that are owned by the
// tenant who submits the request, unless an admin user submits the request.
func List(c *gophercloud.ServiceClient, opts ListOpts) pagination.Pager {
	q, err := gophercloud.BuildQueryString(&opts)
	if err != nil {
		return pagination.Pager{Err: err}
	}
	u := rootURL(c) + q.String()
	return pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page {
		return MemberPage{pagination.LinkedPageBase{PageResult: r}}
	})
}

// CreateOptsBuilder allows extensions to add additional parameters to the
// Create request.
type CreateOptsBuilder interface {
	ToLBMemberCreateMap() (map[string]interface{}, error)
}

// CreateOpts contains all the values needed to create a new pool member.
type CreateOpts struct {
	// Address is the IP address of the member.
	Address string `json:"address" required:"true"`

	// ProtocolPort is the port on which the application is hosted.
	ProtocolPort int `json:"protocol_port" required:"true"`

	// PoolID is the pool to which this member will belong.
	PoolID string `json:"pool_id" required:"true"`

	// TenantID is only required if the caller has an admin role and wants
	// to create a pool for another tenant.
	TenantID string `json:"tenant_id,omitempty"`
}

// ToLBMemberCreateMap builds a request body from CreateOpts.
func (opts CreateOpts) ToLBMemberCreateMap() (map[string]interface{}, error) {
	return gophercloud.BuildRequestBody(opts, "member")
}

// Create accepts a CreateOpts struct and uses the values to create a new
// load balancer pool member.
func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {
	b, err := opts.ToLBMemberCreateMap()
	if err != nil {
		r.Err = err
		return
	}
	_, r.Err = c.Post(rootURL(c), b, &r.Body, nil)
	return
}

// Get retrieves a particular pool member based on its unique ID.
func Get(c *gophercloud.ServiceClient, id string) (r GetResult) {
	_, r.Err = c.Get(resourceURL(c, id), &r.Body, nil)
	return
}

// UpdateOptsBuilder allows extensions to add additional parameters to the
// Update request.
type UpdateOptsBuilder interface {
	ToLBMemberUpdateMap() (map[string]interface{}, error)
}

// UpdateOpts contains the values used when updating a pool member.
type UpdateOpts struct {
	// The administrative state of the member, which is up (true) or down (false).
	AdminStateUp *bool `json:"admin_state_up,omitempty"`
}

// ToLBMemberUpdateMap builds a request body from UpdateOpts.
func (opts UpdateOpts) ToLBMemberUpdateMap() (map[string]interface{}, error) {
	return gophercloud.BuildRequestBody(opts, "member")
}

// Update allows members to be updated.
func Update(c *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) (r UpdateResult) {
	b, err := opts.ToLBMemberUpdateMap()
	if err != nil {
		r.Err = err
		return
	}
	_, r.Err = c.Put(resourceURL(c, id), b, &r.Body, &gophercloud.RequestOpts{
		OkCodes: []int{200, 201, 202},
	})
	return
}

// Delete will permanently delete a particular member based on its unique ID.
func Delete(c *gophercloud.ServiceClient, id string) (r DeleteResult) {
	_, r.Err = c.Delete(resourceURL(c, id), nil)
	return
}


text:
<?php

use Project\Post\Agavi\View\BaseView;

class Post_Detail_DetailSuccessView extends BaseView
{
    public function executeHtml(AgaviRequestDataHolder $parameters)
    {
        $this->setupHtml($parameters);

        $post = $parameters->getParameter('post');

        $this->setAttribute('_title', $post->getTitle());
        $this->setAttribute('post', $post->toArray('detail'));
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Argentine Corn Chicken</title>
      <categories>
        <cat>Diabetic</cat>
        <cat>Poultry</cat>
        <cat>Main dish</cat></categories>
      <yield>4</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1</qty>
          <unit/></amt>
        <item>Broilier-fryer chicken; (about 2 1/2 lbs) cut-up</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Pepper to taste;</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>tablespoon</unit></amt>
        <item>Virgin olive oil;</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>cloves</unit></amt>
        <item>Garlic; minced</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit/></amt>
        <item>Tomatoes;</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit/></amt>
        <item>Bay leaf;</item></ing>
      <ing>
        <amt>
          <qty>1/4</qty>
          <unit>teaspoons</unit></amt>
        <item>Leaf marjoram;</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Frozen whole-kernel corn; thawed</item></ing></ingredients>
    <directions>
      <step>  Renove skin from chicken.  Season with salt and pepper.  In a large
  non-stick pan skillet, heat oil and cook chicken until tender,
  turning. 15 to 20 minutes.  Remove from skillet and keep warn.  Saute
  onion and garlic in skillet.  Add tomatoes, bay leaf and narhiran;
  simmer 10 minutes. Add corn and chicken; heat through, mix well with
  the sauce. Serve this dish with "Bell Pepper Salad" (also in this
  file)

  Food Exchange per serving: 3 LOW/FAT MEAT EXCHANGES + 1 STARCH/BREAD
  EXCHANGE + 1 VEGETABLE EXCHANGE  CAL: 246; CHO: 75mg; CAR: 18g; PRO:
       27 g  SOD: 138mg; FAT: 10g;

  Souce: Light & Easy Diabetes Cuisine by Betty Marks
  Brought to you and yours via Nancy O'Brion and her Meal-Master

  File ftp://ftp.idiscover.co.uk/pub/food/mealmaster/recipes/diabetic.zip

</step></directions></recipe></recipeml>


text:
package com.vmware.vim25;

/**
@author Steve Jin (sjin@vmware.com)
*/

public class DrsInvocationFailedEvent extends ClusterEvent
{
}


text:
layout: post
title: svn:externals und ein Umzug zu git
published: true
tags:
- entwicklung
- svn
- git
summary: Behandlung von svn:externals verlangen bei einem Umzug zu git nach kreativen Lösungsansätzen
---

## Der Hintergrund
Aufgrund der besseren Verfügbarkeit wollte ich einige meiner Projekte von einem lokal verwendeten Subversion Server in entsprechende Repositories auf Github umziehen. Dabei kam es zu einigen Problemchen, die ich so vorher nicht bedacht hatte. Diese möchte ich hier kurz darstellen. Natürlich hätte ich einiges davon umgehen können, wenn ich die betroffenen Projekte vor dem Umzug an die neuen Gegebenheiten angepasst hätte, aber das vorrangige Ziel war ein Umzug, der die Projekte erst einmal soweit wie möglich unangetastet lässt.


text:
local protobuf = require "protobuf"
module('BseLeaveHall_pb', package.seeall)

local BSELEAVEHALL = protobuf.Descriptor();
local BSELEAVEHALL_HALLSRVID_FIELD = protobuf.FieldDescriptor();

BSELEAVEHALL_HALLSRVID_FIELD.name = "hallsrvID"
BSELEAVEHALL_HALLSRVID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseLeaveHall.hallsrvID"
BSELEAVEHALL_HALLSRVID_FIELD.number = 1
BSELEAVEHALL_HALLSRVID_FIELD.index = 0
BSELEAVEHALL_HALLSRVID_FIELD.label = 2
BSELEAVEHALL_HALLSRVID_FIELD.has_default_value = true
BSELEAVEHALL_HALLSRVID_FIELD.default_value = 0
BSELEAVEHALL_HALLSRVID_FIELD.type = 5
BSELEAVEHALL_HALLSRVID_FIELD.cpp_type = 1

BSELEAVEHALL.name = "BseLeaveHall"
BSELEAVEHALL.full_name = ".com.xinqihd.sns.gameserver.proto.BseLeaveHall"
BSELEAVEHALL.nested_types = {}
BSELEAVEHALL.enum_types = {}
BSELEAVEHALL.fields = {BSELEAVEHALL_HALLSRVID_FIELD}
BSELEAVEHALL.is_extendable = false
BSELEAVEHALL.extensions = {}

BseLeaveHall = protobuf.Message(BSELEAVEHALL)
_G.BSELEAVEHALL_PB_BSELEAVEHALL = BSELEAVEHALL


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="8dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:background="@color/gsr_background_gray"
        android:layout_marginBottom="4dp">
        <TextView
            android:id="@+id/gsr_building_name"
            android:textColor="@color/black"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/gsr_availability_in_building"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        tools:list_item="gsr_room" />

</LinearLayout>


text:
import hashlib
from databaseutil import DatabaseUtility

def generate_hash(registration_id):
    return str(hashlib.sha256(registration_id.encode()).hexdigest());

def register(registration_id):
    hash = generate_hash(registration_id)
    dbutil = DatabaseUtility()
    if dbutil.is_present(hash, registration_id):
        return '{\"status\":\"Already Present\"}'
    dbutil.add_id(hash, registration_id)
    dbutil.close_connection()
    return '{\"status\":\"Added\"}'


text:
import { RegisterComponent } from './register.component';
export const REGISTER_ROUTER = [
    {
        path: '',
        component: RegisterComponent
    }
];


text:
__author__ = 'Dave Foster <dfoster@asascience.com>, Michael Meisinger'

import datetime
import time
import sys

from mock import Mock, sentinel, patch
from nose.plugins.attrib import attr
from gevent import event, queue
from unittest import SkipTest

from pyon.util.int_test import IonIntegrationTestCase
from pyon.util.unit_test import IonUnitTestCase

from pyon.core import bootstrap
from pyon.core.bootstrap import IonObject
from pyon.core.exception import BadRequest, FilesystemError, StreamingError, CorruptionError
from pyon.datastore.datastore import DatastoreManager, DataStore
from pyon.ion.event import EventPublisher, EventSubscriber, EventRepository, handle_stream_exception, EventQuery, DQ
from pyon.ion.identifier import create_unique_event_id
from pyon.ion.resource import OT
from pyon.util.containers import get_ion_ts, DotDict

from interface.objects import Event, ResourceLifecycleEvent, ResourceOperatorEvent, ResourceCommandEvent

@attr('UNIT', group='event')
class TestEvents(IonUnitTestCase):
    def test_event_subscriber_auto_delete(self):
        mocknode = Mock()
        ev = EventSubscriber(event_type="ProcessLifecycleEvent", callback=lambda *a,**kw: None, auto_delete=sentinel.auto_delete, node=mocknode)
        self.assertEquals(ev._auto_delete, sentinel.auto_delete)

        # we don't want to have to patch out everything here, so call initialize directly, which calls create_channel for us
        ev._setup_listener = Mock()
        ev.initialize(sentinel.binding)

        self.assertEquals(ev._chan.queue_auto_delete, sentinel.auto_delete)

@attr('INT', group='event')
class TestEventsInt(IonIntegrationTestCase):

    def setUp(self):
        self._listens = []
        self._start_container()

    def tearDown(self):
        for x in self._listens:
            x.stop()

    def _listen(self, sub):
        """
        Pass in a subscriber here, this will make it listen in a background greenlet.
        """
        sub.start()
        self._listens.append(sub)
        sub._ready_event.wait(timeout=5)

    def test_pub_and_sub(self):
        ar = event.AsyncResult()
        gq = queue.Queue()
        self.count = 0

        def cb(*args, **kwargs):
            self.count += 1
            gq.put(args[0])
            if self.count == 2:
                ar.set()

        sub = EventSubscriber(event_type="ResourceEvent", callback=cb, origin="specific")
        pub = EventPublisher(event_type="ResourceEvent")

        self._listen(sub)
        pub.publish_event(origin="specific", description="hello")

        event_obj = bootstrap.IonObject('ResourceEvent', origin='specific', description='more testing')
        self.assertEqual(event_obj, pub.publish_event_object(event_obj))

        with self.assertRaises(BadRequest) as cm:
            event_obj = bootstrap.IonObject('ResourceEvent', origin='specific', description='more testing', ts_created='2423')
            pub.publish_event_object(event_obj)
        self.assertIn( 'The ts_created value is not a valid timestamp',cm.exception.message)

        with self.assertRaises(BadRequest) as cm:
            event_obj = bootstrap.IonObject('ResourceEvent', origin='specific', description='more testing', ts_created='1000494978462')
            pub.publish_event_object(event_obj)
        self.assertIn( 'This ts_created value is too old',cm.exception.message)

        with self.assertRaises(BadRequest) as cm:
            event_obj = bootstrap.IonObject('ResourceEvent', origin='specific', description='more testing')
            event_obj._id = '343434'
            pub.publish_event_object(event_obj)
        self.assertIn( 'The event object cannot contain a _id field',cm.exception.message)

        ar.get(timeout=5)

        res = []
        for x in xrange(self.count):
            res.append(gq.get(timeout=5))

        self.assertEquals(len(res), self.count)
        self.assertEquals(res[0].description, "hello")
        self.assertAlmostEquals(int(res[0].ts_created), int(get_ion_ts()), delta=5000)

        self.assertEquals(res[1].description, "more testing")
        self.assertAlmostEquals(int(res[1].ts_created), int(get_ion_ts()), delta=5000)

    def test_pub_on_different_origins(self):
        ar = event.AsyncResult()
        gq = queue.Queue()
        self.count = 0

        def cb(*args, **kwargs):
            self.count += 1
            gq.put(args[0])
            if self.count == 3:
                ar.set()

        sub = EventSubscriber(event_type="ResourceEvent", callback=cb)
        pub = EventPublisher(event_type="ResourceEvent")

        self._listen(sub)

        pub.publish_event(origin="one", description="1")
        pub.publish_event(origin="two", description="2")
        pub.publish_event(origin="three", description="3")

        ar.get(timeout=5)

        res = []
        for x in xrange(self.count):
            res.append(gq.get(timeout=5))

        self.assertEquals(len(res), 3)
        self.assertEquals(res[0].description, "1")
        self.assertEquals(res[1].description, "2")
        self.assertEquals(res[2].description, "3")

    def test_pub_on_different_subtypes(self):
        ar = event.AsyncResult()
        gq = queue.Queue()
        self.count = 0

        def cb(event, *args, **kwargs):
            self.count += 1
            gq.put(event)
            if event.description == "end":
                ar.set()

        sub = EventSubscriber(event_type="ResourceModifiedEvent", sub_type="st1", callback=cb)
        sub.start()

        pub1 = EventPublisher(event_type="ResourceModifiedEvent")
        pub2 = EventPublisher(event_type="ContainerLifecycleEvent")

        pub1.publish_event(origin="two", sub_type="st2", description="2")
        pub2.publish_event(origin="three", sub_type="st1", description="3")
        pub1.publish_event(origin="one", sub_type="st1", description="1")
        pub1.publish_event(origin="four", sub_type="st1", description="end")

        ar.get(timeout=5)
        sub.stop()

        res = []
        for x in xrange(self.count):
            res.append(gq.get(timeout=5))

        self.assertEquals(len(res), 2)
        self.assertEquals(res[0].description, "1")

    def test_pub_on_different_subsubtypes(self):
        res_list = [DotDict(ar=event.AsyncResult(), gq=queue.Queue(), count=0) for i in xrange(4)]

        def cb_gen(num):
            def cb(event, *args, **kwargs):
                res_list[num].count += 1
                res_list[num].gq.put(event)
                if event.description == "end":
                    res_list[num].ar.set()
            return cb

        sub0 = EventSubscriber(event_type="ResourceModifiedEvent", sub_type="st1.*", callback=cb_gen(0))
        sub0.start()

        sub1 = EventSubscriber(event_type="ResourceModifiedEvent", sub_type="st1.a", callback=cb_gen(1))
        sub1.start()

        sub2 = EventSubscriber(event_type="ResourceModifiedEvent", sub_type="*.a", callback=cb_gen(2))
        sub2.start()

        sub3 = EventSubscriber(event_type="ResourceModifiedEvent", sub_type="st1", callback=cb_gen(3))
        sub3.start()

        pub1 = EventPublisher(event_type="ResourceModifiedEvent")

        pub1.publish_event(origin="one", sub_type="st1.a", description="1")
        pub1.publish_event(origin="two", sub_type="st1", description="2")
        pub1.publish_event(origin="three", sub_type="st1.b", description="3")

        pub1.publish_event(origin="four", sub_type="st2.a", description="4")
        pub1.publish_event(origin="five", sub_type="st2", description="5")

        pub1.publish_event(origin="six", sub_type="a", description="6")
        pub1.publish_event(origin="seven", sub_type="", description="7")

        pub1.publish_event(origin="end", sub_type="st1.a", description="end")
        pub1.publish_event(origin="end", sub_type="st1", description="end")

        [res_list[i].ar.get(timeout=5) for i in xrange(3)]

        sub0.stop()
        sub1.stop()
        sub2.stop()
        sub3.stop()

        for i in xrange(4):
            res_list[i].res = []
            for x in xrange(res_list[i].count):
                res_list[i].res.append(res_list[i].gq.get(timeout=5))

        self.assertEquals(len(res_list[0].res), 3)
        self.assertEquals(res_list[0].res[0].description, "1")

        self.assertEquals(len(res_list[1].res), 2)
        self.assertEquals(res_list[1].res[0].description, "1")

        self.assertEquals(len(res_list[2].res), 3)
        self.assertEquals(res_list[2].res[0].description, "1")

        self.assertEquals(len(res_list[3].res), 2)
        self.assertEquals(res_list[3].res[0].description, "2")

    def test_base_subscriber_as_catchall(self):
        ar = event.AsyncResult()
        gq = queue.Queue()
        self.count = 0

        def cb(*args, **kwargs):
            self.count += 1
            gq.put(args[0])
            if self.count == 2:
                ar.set()

        sub = EventSubscriber(callback=cb)
        pub1 = EventPublisher(event_type="ResourceEvent")
        pub2 = EventPublisher(event_type="ContainerLifecycleEvent")

        self._listen(sub)

        pub1.publish_event(origin="some", description="1")
        pub2.publish_event(origin="other", description="2")

        ar.get(timeout=5)

        res = []
        for x in xrange(self.count):
            res.append(gq.get(timeout=5))

        self.assertEquals(len(res), 2)
        self.assertEquals(res[0].description, "1")
        self.assertEquals(res[1].description, "2")

    def test_subscriber_listening_for_specific_origin(self):
        ar = event.AsyncResult()
        self.count = 0
        def cb(*args, **kwargs):
            self.count += 1
            ar.set(args[0])

        sub = EventSubscriber(event_type="ResourceEvent", origin="specific", callback=cb)
        pub = EventPublisher(event_type="ResourceEvent", node=self.container.node)

        self._listen(sub)

        pub.publish_event(origin="notspecific", description="1")
        pub.publish_event(origin="notspecific", description="2")
        pub.publish_event(origin="specific", description="3")
        pub.publish_event(origin="notspecific", description="4")

        evmsg = ar.get(timeout=5)
        self.assertEquals(self.count, 1)
        self.assertEquals(evmsg.description, "3")

    def test_pub_sub_exception_event(self):
        ar = event.AsyncResult()

        gq = queue.Queue()
        self.count = 0

        def cb(*args, **kwargs):
            self.count += 1
            gq.put(args[0])
            if self.count == 3:
                ar.set()

        #test file system error event
        sub = EventSubscriber(event_type="ExceptionEvent", callback=cb, origin="stream_exception")
        self._listen(sub)

        @handle_stream_exception()
        def _raise_filesystem_error():
            raise FilesystemError()
        _raise_filesystem_error()

        @handle_stream_exception()
        def _raise_streaming_error():
            raise StreamingError()
        _raise_streaming_error()

        @handle_stream_exception()
        def _raise_corruption_error():
            raise CorruptionError()
        _raise_corruption_error()

        ar.get(timeout=5)
        res = []
        for i in xrange(self.count):
            exception_event = gq.get(timeout=5)
            res.append(exception_event)

        self.assertEquals(res[0].exception_type, "<class 'pyon.core.exception.FilesystemError'>")
        self.assertEquals(res[1].exception_type, "<class 'pyon.core.exception.StreamingError'>")
        self.assertEquals(res[2].exception_type, "<class 'pyon.core.exception.CorruptionError'>")
        self.assertEquals(res[2].origin, "stream_exception")

    def test_pub_sub_exception_event_origin(self):
        #test origin
        ar = event.AsyncResult()

        self.count = 0
        def cb(*args, **kwargs):
            self.count = self.count + 1
            ar.set(args[0])

        sub = EventSubscriber(event_type="ExceptionEvent", callback=cb, origin="specific")
        self._listen(sub)

        @handle_stream_exception("specific")
        def _test_origin():
            raise CorruptionError()
        _test_origin()

        exception_event = ar.get(timeout=5)

        self.assertEquals(self.count, 1)
        self.assertEquals(exception_event.exception_type, "<class 'pyon.core.exception.CorruptionError'>")
        self.assertEquals(exception_event.origin, "specific")

@attr('UNIT', group='event')
class TestEventRepository(IonUnitTestCase):
    def test_event_repo(self):
        dsm = DatastoreManager()
        ds = dsm.get_datastore("events", "EVENTS")
        ds.delete_datastore()
        ds.create_datastore()

        event_repo = EventRepository(dsm)
        event_repo1 = EventRepository(dsm)

        event1 = Event(origin="resource1")
        event_id, _ = event_repo.put_event(event1)

        event1r = event_repo.get_event(event_id)
        self.assertEquals(event1.origin, event1r.origin)

        ts = 1328680477138
        events2 = []
        for i in xrange(5):
            ev = Event(origin="resource2", ts_created=str(ts + i))
            event_id, _ = event_repo.put_event(ev)
            events2.append((ev,event_id))

        events_r = event_repo.find_events(origin='resource2')
        self.assertEquals(len(events_r), 5)

        events_r = event_repo.find_events(origin='resource2', descending=True)
        self.assertEquals(len(events_r), 5)

        events_r = event_repo.find_events(origin='resource2', limit=3)
        self.assertEquals(len(events_r), 3)

        events_r = event_repo.find_events(origin='resource2', start_ts=str(ts+3))
        self.assertEquals(len(events_r), 2)

        events_r = event_repo.find_events(origin='resource2', end_ts=str(ts+2))
        self.assertEquals(len(events_r), 3)

        events_r = event_repo.find_events(origin='resource2', start_ts=str(ts+3), end_ts=str(ts+4))
        self.assertEquals(len(events_r), 2)

        events_r = event_repo.find_events(start_ts=str(ts+3), end_ts=str(ts+4))
        self.assertEquals(len(events_r), 2)

        event3 = ResourceLifecycleEvent(origin="resource3")
        event_id, _ = event_repo.put_event(event3)

        events_r = event_repo.find_events(event_type="ResourceLifecycleEvent")
        self.assertEquals(len(events_r), 1)

    def test_event_persist(self):
        events = [{'_id': '778dcc0811bd4b518ffd1ef873f3f457',
                   'base_types': ['Event'],
                   'description': 'Event to deliver the status of instrument.',
                   'origin': 'instrument_1',
                   'origin_type': 'PlatformDevice',
                   'status': 1,
                   'sub_type': 'input_voltage',
                   'time_stamps': [2.0, 2.0],
                   'ts_created': '1364121284585',
                   'type_': 'DeviceStatusEvent',
                   'valid_values': [-100, 100],
                   'values': [110.0, 111.0]},
                  {'_id': 'b40731684e41418082e1727f3cf61026',
                   'base_types': ['Event'],
                   'description': 'Event to deliver the status of instrument.',
                   'origin': 'instrument_1',
                   'origin_type': 'PlatformDevice',
                   'status': 1,
                   'sub_type': 'input_voltage',
                   'time_stamps': [2.0, 2.0],
                   'ts_created': '1364121284609',
                   'type_': 'DeviceStatusEvent',
                   'valid_values': [-100, 100],
                   'values': [110.0, 111.0]}]

        dsm = DatastoreManager()
        ds = dsm.get_datastore(DataStore.DS_EVENTS, DataStore.DS_PROFILE.EVENTS)
        ds.delete_datastore()
        ds.create_datastore()

        event_repo = EventRepository(dsm)

        # Store one event without ID
        event1_dict = events[0].copy()
        event1_dict.pop("_id")
        event1_type = event1_dict.pop("type_")
        event1 = IonObject(event1_type, **event1_dict)
        event_repo.put_event(event1)

        events_r = event_repo.find_events(origin=event1_dict["origin"])
        self.assertEquals(len(events_r), 1)
        event1_read = events_r[0][2]
        self.assertEquals(event1_read.time_stamps, event1_dict["time_stamps"])

        # Store one event with ID
        event2_dict = events[1].copy()
        event2_id = event2_dict.pop("_id")
        event2_type = event2_dict.pop("type_")
        event2_obj = IonObject(event2_type, **event2_dict)
        event2_obj._id = event2_id
        event_repo.put_event(event2_obj)

        # Store multiple new events with ID set and unset, non-existing
        event1_dict = events[0].copy()
        event1_id = event1_dict.pop("_id")
        event1_type = event1_dict.pop("type_")
        event1_obj = IonObject(event1_type, **event1_dict)
        event1_obj._id = create_unique_event_id()

        event2_dict = events[1].copy()
        event2_id = event2_dict.pop("_id")
        event2_type = event2_dict.pop("type_")
        event2_obj = IonObject(event2_type, **event2_dict)

        event_repo.put_events([event1_obj, event2_obj])
        events_r = event_repo.find_events(event_type='DeviceStatusEvent')
        self.assertEquals(len(events_r), 4)

@attr('INT', group='event')
class TestEventRepoInt(IonIntegrationTestCase):

    def setUp(self):
        self._start_container()
        self.er = self.container.event_repository

    def test_event_query(self):
        t0 = 136304640000
        events = [
            ("RME1", ResourceCommandEvent(origin="O1", origin_type="OT1", sub_type="ST1", ts_created=str(t0))),
            ("RME2", ResourceCommandEvent(origin="O2", origin_type="OT1", sub_type="ST2", ts_created=str(t0+1))),
            ("RME3", ResourceCommandEvent(origin="O2", origin_type="OT2", sub_type="ST3", ts_created=str(t0+2))),

            ("RLE1", ResourceOperatorEvent(origin="O1", origin_type="OT3", sub_type="ST4", ts_created=str(t0+3))),
            ("RLE2", ResourceOperatorEvent(origin="O3", origin_type="OT3", sub_type="ST5", ts_created=str(t0+4))),
            ("RLE3", ResourceOperatorEvent(origin="O3", origin_type="OT2", sub_type="ST6", ts_created=str(t0+5))),
        ]
        ev_by_alias = {}
        for (alias, event) in events:
            evid, _ = self.container.event_repository.put_event(event)
            ev_by_alias[alias] = evid

        # --- Basic event queries
        eq = EventQuery()
        eq.set_filter(eq.filter_type(OT.ResourceCommandEvent))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 3)

        eq = EventQuery()
        eq.set_filter(eq.filter_type(OT.ResourceCommandEvent))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=True)
        self.assertEquals(len(ev_obj), 3)
        self.assertTrue(all([True for eo in ev_obj if isinstance(eo, basestring)]))

        eq = EventQuery()
        eq.set_filter(eq.filter_sub_type("ST", cmpop=DQ.TXT_CONTAINS))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 6)

        eq = EventQuery()
        eq.set_filter(eq.filter_sub_type("st", cmpop=DQ.TXT_ICONTAINS))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 6)

        eq = EventQuery()
        eq.set_filter(eq.filter_sub_type("^ST(1|2)", cmpop=DQ.TXT_REGEX))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 2)

        eq = EventQuery()
        eq.set_filter(eq.filter_sub_type("^st(1|2)", cmpop=DQ.TXT_IREGEX))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 2)

        eq = EventQuery()
        eq.set_filter(eq.not_(eq.filter_sub_type("^st(1|2)", cmpop=DQ.TXT_IREGEX)))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 4)

        eq = EventQuery()
        eq.set_filter(eq.filter_type([OT.ResourceCommandEvent, OT.ResourceOperatorEvent]))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 6)

        eq = EventQuery()
        eq.set_filter(eq.filter_type([OT.ResourceCommandEvent, OT.ResourceOperatorEvent]),
                      eq.filter_origin_type("OT2"))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 2)

        eq = EventQuery()
        eq.set_filter(eq.filter_type([OT.ResourceCommandEvent, OT.ResourceOperatorEvent]),
                      eq.filter_origin_type(["OT2", "OT1"]))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 4)

        eq = EventQuery()
        eq.set_filter(eq.filter_type([OT.ResourceCommandEvent, OT.ResourceOperatorEvent]),
                      eq.filter_sub_type("ST1"))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 1)

        eq = EventQuery()
        eq.set_filter(eq.filter_type([OT.ResourceCommandEvent, OT.ResourceOperatorEvent]),
                      eq.filter_sub_type(["ST2", "ST3"]))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 2)

        # --- Temporal range queries

        eq = EventQuery()
        eq.set_filter(eq.filter_ts_created(str(t0), str(t0)))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 1)

        eq = EventQuery()
        eq.set_filter(eq.filter_ts_created(str(t0), str(t0+1)))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 2)

        eq = EventQuery()
        eq.set_filter(eq.filter_ts_created(t0, t0+1))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 2)

        eq = EventQuery()
        eq.set_filter(eq.filter_ts_created(datetime.datetime.fromtimestamp(float(t0)/1000),
                                           datetime.datetime.fromtimestamp(float(t0)/1000)))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 1)

        eq = EventQuery()
        eq.set_filter(eq.filter_ts_created(str(t0-10), str(t0-1)))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 0)

        eq = EventQuery()
        eq.set_filter(eq.filter_ts_created(from_expr=str(t0+3)))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 3)

        eq = EventQuery()
        eq.set_filter(eq.filter_ts_created(to_expr=str(t0+2)))
        ev_obj = self.er.find_events_query(query=eq.get_query(), id_only=False)
        self.assertEquals(len(ev_obj), 3)


text:
declare namespace java {
  namespace nio {
    namespace channels {

      abstract class AsynchronousFileChannel implements java.nio.channels.AsynchronousChannel {
        protected constructor()
        public static open(arg0: java.nio.file.Path, arg1: java.util.Set<java.nio.file.OpenOption>, arg2: java.util.concurrent.ExecutorService, ...vargs: (java.nio.file.attribute.FileAttribute<unknown>)[]): java.nio.channels.AsynchronousFileChannel
        public static open(arg0: java.nio.file.Path, ...vargs: (java.nio.file.OpenOption)[]): java.nio.channels.AsynchronousFileChannel
        public abstract size(): number
        public abstract truncate(arg0: number | java.lang.Long): java.nio.channels.AsynchronousFileChannel
        public abstract force(arg0: boolean | java.lang.Boolean): void
        public abstract lock<A>(arg0: number | java.lang.Long, arg1: number | java.lang.Long, arg2: boolean | java.lang.Boolean, arg3: A, arg4: java.nio.channels.CompletionHandler<java.nio.channels.FileLock,unknown>): void
        public lock<A>(arg0: A, arg1: java.nio.channels.CompletionHandler<java.nio.channels.FileLock,unknown>): void
        public abstract lock(arg0: number | java.lang.Long, arg1: number | java.lang.Long, arg2: boolean | java.lang.Boolean): java.util.concurrent.Future<java.nio.channels.FileLock>
        public lock(): java.util.concurrent.Future<java.nio.channels.FileLock>
        public abstract tryLock(arg0: number | java.lang.Long, arg1: number | java.lang.Long, arg2: boolean | java.lang.Boolean): java.nio.channels.FileLock
        public tryLock(): java.nio.channels.FileLock
        public abstract read<A>(arg0: java.nio.ByteBuffer, arg1: number | java.lang.Long, arg2: A, arg3: java.nio.channels.CompletionHandler<java.lang.Integer,unknown>): void
        public abstract read(arg0: java.nio.ByteBuffer, arg1: number | java.lang.Long): java.util.concurrent.Future<java.lang.Integer>
        public abstract write<A>(arg0: java.nio.ByteBuffer, arg1: number | java.lang.Long, arg2: A, arg3: java.nio.channels.CompletionHandler<java.lang.Integer,unknown>): void
        public abstract write(arg0: java.nio.ByteBuffer, arg1: number | java.lang.Long): java.util.concurrent.Future<java.lang.Integer>
      }

    }
  }
}


text:
<?php

class UserMapper extends Agileo_Mapper_Db
{
    // @formatter:off
    public static $prefix = 'usr';
    public static $tableName = 'ag_users';
    public static $tableFields = array('usr_id', 'usr_email', 'usr_pass', 'usr_status', 'usr_type', 'usr_create_date', 'usr_update_date', 'usr_nick', 'usr_name', 'usr_surname', 'usr_avatar', 'usr_description', 'usr_auth_token'
        ,'usr_soc_update_date','usr_soc_facebook','usr_soc_googleplus','usr_soc_tweeter','usr_soc_linkedin', 'usr_contact', 'usr_bg'
        ,'usr_geo_address','usr_geo_lat','usr_geo_lng','usr_geo_zoom');

    public static $fieldsList = array('usr_id', 'usr_email', 'usr_pass', 'usr_status', 'usr_type', 'usr_create_date', 'usr_update_date', 'usr_nick', 'usr_name', 'usr_surname', 'usr_avatar',
        'usr_soc_update_date','usr_soc_facebook','usr_soc_googleplus','usr_soc_tweeter','usr_soc_linkedin',
        'usr_stat_blogit_count',
        'usr_geo_address','usr_geo_lat','usr_geo_lng','usr_geo_zoom');

    const STATUS_ACTIVE = 'ACTIVE';
    const STATUS_NEW = 'NEW';
    const STATUS_BLOCKED = 'BLOCKED';
    const STATUS_DELETED = 'DELETED';

    const TYPE_STANDARD = 'STANDARD';
    const TYPE_SOCIAL = 'SOCIAL';
    const TYPE_MIXED = 'MIXED';

    const ROLE_STANDARD = 'STANDARD';
    const ROLE_POLITICIAN = 'POLITICIAN';

    // @formatter:on

    public function login($email, $pass)
    {

        if(!empty($email) && !empty($pass)) {
            $select = $this->_db->select()
                            ->from(self::$tableName)
                            ->where('usr_email = ?', $email)
                            ->where('usr_pass = ?', $this->_hashPassword($pass));

            if($data = $this->_db->query($select)->fetch()) {
                return new User($data);
            }
        }

        return null;
    }

    public function getByToken($token)
    {
        $select = $this->_db->select()
                        ->from(self::$tableName)
                        ->where('usr_auth_token = ?', $token);

        if($data = $this->_db->query($select)->fetch()) {
            return new User($data);
        }

        return null;
    }

    public function getByEmail($email)
    {
        $select = $this->_db->select()
                        ->from(self::$tableName)
                        ->where('usr_email = ?', $email);

        if($data = $this->_db->query($select)->fetch()) {
            return new User($data);
        }

        return null;
    }

    private function _hashPassword($pass)
    {
        return md5(Zend_Registry::get('config')->model->user->passwordSecretKey . $pass);
    }

    public function getListPager($filter, $page, $limit)
    {

        $select = $this->_db->select()
            ->from(self::$tableName, self::$fieldsList)
            ;
        ;

        $this->_listRestrict($select, $filter);

        $cSelect = clone $select;
        $cSelect->reset(Zend_Db_Select::COLUMNS)
            ->reset(Zend_Db_Select::ORDER)
            ->columns(new Zend_Db_Expr('COUNT(*) AS ' . Zend_Paginator_Adapter_DbSelect::ROW_COUNT_COLUMN));

        $adapter = new Zend_Paginator_Adapter_DbSelect($select);
        $adapter->setRowCount($cSelect);

        $paginator = new Agileo_Paginator($adapter, 'User');
        $paginator->setCurrentPageNumber($page);
        $paginator->setItemCountPerPage($limit);

        return $paginator;
    }

    public function getList($filter, $limit = 10)
    {
        $select = $this->_db->select()
            ->from(self::$tableName, self::$fieldsList)
            ;
        ;

        $this->_listRestrict($select, $filter);

        $select->limit($limit);

        return Agileo_Collection::create('User', $this->_db->query($select)->fetchAll());
    }

    protected function _listRestrict($select, $filter)
    {
        if(!empty($filter['available'])) {
            $select->where("usr_status= ?", self::STATUS_ACTIVE);
        } else {
            if(!empty($filter['status'])) {
                $select->where("usr_status = ?", $filter['status']);
            } else {
                $select->where("usr_status <> ?", UserMapper::STATUS_DELETED);
            }
        }

        if(!empty($filter['nick'])) {
            $select->where("usr_nick like ?", '%'.$filter['nick'].'%');
        }

        if(!empty($filter['search'])) {

            $term = '%'.$filter['search'].'%';

            $select->where("usr_nick like '{$term}' or usr_name like '{$term}' or usr_surname like '{$term}' or usr_email like '{$term}'");
        }

        if (!empty($filter['order'])){

            switch($filter['order']) {
                case 'mostActive' : $select->order('usr_most_active desc');break;
                case 'mostPopular' : $select->order('usr_most_popular desc');break;
                case 'lastActivity' : $select->order('usr_last_activity desc');break;
                case 'createDate' : $select->order('usr_create_date desc');break;
                case 'alphabetically' : $select->order('usr_nick asc');break;
                default : $select->order($filter['order']);
            }
        } else {
            $select->order('usr_id desc');
        }

    }

    public function save(User $user)
    {

        if(!empty($user->pass)) {
            $user->pass = $this->_hashPassword($user->pass);
        }
        if(empty($user->id)) {
            $user->create_date = date('Y-m-d H:i:s');
        }

        $user->update_date = date('Y-m-d H:i:s');

        return $this->_save($user);
    }

    public function checkPass($id, $pass)
    {
        if(!empty($id) && !empty($pass)) {

            $select = $this->_db->select()
                            ->from(self::$tableName)
                            ->where('usr_id = ?', $id)
                            ->where('usr_pass = ?', $this->_hashPassword($pass));

            if($data = $this->_db->query($select)->fetch()) {
                return true;
            }

        }

        return false;
    }

    public function delete(User $user)
    {
        $oldObject = clone $user;

        $user->status = self::STATUS_DELETED;
        // TOTO zmienić dane osobowe

        $startTransaction = $this->beginTransaction();
        try {

            if($this->_save($user)) {
                ChangeLogMapper::getMasterInstance()->saveLog($user, $oldObject);
            }

            $this->commit($startTransaction);

            return true;

        } catch (Exception $e) {
            $this->rollBack($startTransaction);
            throw $e;
        }

        return false;
    }

    public function getBySocFacebook($fbId)
    {
        $select = $this->_db->select()
                        ->from(self::$tableName)
                        ->where('usr_soc_facebook = ?', $fbId);

        if($data = $this->_db->query($select)->fetch()) {
            return new User($data);
        }

        return null;
    }

    public function getSearchFulltextForObject(User $user)
    {
        $fulltext = ''.$user.' '.$user->nick.' '.$user->description;
        return trim(strip_tags($fulltext));
    }

}


text:
void init_getkey(void);
void close_getkey(void);

enum confirmation_t {confirmation_y, confirmation_n, confirmation_esc};

POE_ERR get_insertable_key(char* pchr);
enum confirmation_t get_confirmation(const char* prompt);
const char* ui_get_key();


text:
package atc

import (
	"encoding/json"
	"errors"
	"regexp"
)

type Worker struct {
	// not garden_addr, for backwards-compatibility
	GardenAddr      string `json:"addr"`
	BaggageclaimURL string `json:"baggageclaim_url"`

	CertsPath *string `json:"certs_path,omitempty"`

	HTTPProxyURL  string `json:"http_proxy_url,omitempty"`
	HTTPSProxyURL string `json:"https_proxy_url,omitempty"`
	NoProxy       string `json:"no_proxy,omitempty"`

	ActiveContainers int `json:"active_containers"`
	ActiveVolumes    int `json:"active_volumes"`
	ActiveTasks      int `json:"active_tasks"`

	ResourceTypes []WorkerResourceType `json:"resource_types"`

	Platform  string `json:"platform"`
	Tags      Tags   `json:"tags"`
	Team      string `json:"team"`
	Name      string `json:"name"`
	Version   string `json:"version"`
	StartTime int64  `json:"start_time"`
	Ephemeral bool   `json:"ephemeral"`
	State     string `json:"state"`
}

type Tags []string

// UnmarshalJSON unmarshals as a []string, removing any empty elements. Empty
// tags are treated as unset.
func (t *Tags) UnmarshalJSON(data []byte) error {
	var dst []string
	if err := json.Unmarshal(data, &dst); err != nil {
		return err
	}

	if dst == nil {
		return nil
	}

	*t = make(Tags, 0, len(dst))
	for _, s := range dst {
		if s != "" {
			*t = append(*t, s)
		}
	}

	return nil
}

var ErrInvalidWorkerVersion = errors.New("invalid worker version, only numeric characters are allowed")
var ErrMissingWorkerGardenAddress = errors.New("missing garden address")
var ErrNoWorkers = errors.New("no workers available for checking")

func (w Worker) Validate() error {
	if w.Version != "" && !regexp.MustCompile(`^[0-9\.]+$`).MatchString(w.Version) {
		return ErrInvalidWorkerVersion
	}

	if len(w.GardenAddr) == 0 {
		return ErrMissingWorkerGardenAddress
	}

	return nil
}

type WorkerResourceType struct {
	Type                 string `json:"type"`
	Image                string `json:"image"`
	Version              string `json:"version"`
	Privileged           bool   `json:"privileged"`
	UniqueVersionHistory bool   `json:"unique_version_history"`
}

type PruneWorkerResponseBody struct {
	Stderr string `json:"stderr"`
}


text:
package com.amazonaws.services.cloudfront.model;

import java.io.Serializable;

/**
 * The returned result of the corresponding request.
 */
public class ListDistributionsResult implements Serializable, Cloneable {

    /** The DistributionList type. */
    private DistributionList distributionList;

    /**
     * The DistributionList type.
     *
     * @param distributionList
     *        The DistributionList type.
     */

    public void setDistributionList(DistributionList distributionList) {
        this.distributionList = distributionList;
    }

    /**
     * The DistributionList type.
     *
     * @return The DistributionList type.
     */

    public DistributionList getDistributionList() {
        return this.distributionList;
    }

    /**
     * The DistributionList type.
     *
     * @param distributionList
     *        The DistributionList type.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListDistributionsResult withDistributionList(
            DistributionList distributionList) {
        setDistributionList(distributionList);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDistributionList() != null)
            sb.append("DistributionList: " + getDistributionList());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListDistributionsResult == false)
            return false;
        ListDistributionsResult other = (ListDistributionsResult) obj;
        if (other.getDistributionList() == null
                ^ this.getDistributionList() == null)
            return false;
        if (other.getDistributionList() != null
                && other.getDistributionList().equals(
                        this.getDistributionList()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime
                * hashCode
                + ((getDistributionList() == null) ? 0 : getDistributionList()
                        .hashCode());
        return hashCode;
    }

    @Override
    public ListDistributionsResult clone() {
        try {
            return (ListDistributionsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
require_relative '../../test_helper'

class Aggregate::Attribute::BitfieldTest < ActiveSupport::TestCase

  setup do
    @ad = Aggregate::AttributeHandler.factory("testme", :bitfield, limit: 4)
    @default_bitfield_options = { mapping: { 't' => true, 'f' => false, ' ' => nil }, default: nil }
  end

  should "handle bitfields as booleans by default" do
    result = @ad.from_value("tf t")
    assert_equal Aggregate::Bitfield.with_options(@default_bitfield_options.merge(limit: 4)).new("tf t"), result
    assert_equal true, result[0]
    assert_equal false, result[1]
    assert_nil result[2]
    assert_equal true, result[3]

    assert_equal Aggregate::Bitfield.with_options(@default_bitfield_options.merge(limit: 4)).new("tf t"), @ad.from_store("tf t")
    assert_equal "tf t", @ad.to_store(Aggregate::Bitfield.with_options(@default_bitfield_options.merge(limit: 4)).new("tf t"))
  end

  should "convert array of values to mapped string" do
    result = @ad.from_value([true, false, nil, true])
    assert_equal Aggregate::Bitfield.with_options(@default_bitfield_options.merge(limit: 4)).new("tf t"), result
  end

  should "allow custom mapping and default values" do
    options = {
      mapping: { 'a' => :awesome, 'p' => :pizza },
      default: :pizza,
      limit:   4
    }
    ad = Aggregate::AttributeHandler.factory("testme", :bitfield, options)

    bitfield = ad.default
    bitfield[2] = :awesome
    assert_equal "ppa", bitfield.to_s
    assert_equal Aggregate::Bitfield.with_options(options).new("ppa"), bitfield
  end

  should "provide a default" do
    expected_default = Aggregate::Bitfield.with_options(@default_bitfield_options.merge(limit: 4)).new("")
    assert_equal expected_default, @ad.default
  end

  should "be valid" do
    assert_equal [], @ad.validation_errors("")
  end

  context ".available_options" do
    should "support limit, mapping, and default" do
      available_options = @ad.class.available_options
      assert([:limit, :mapping, :default].all? { |option| option.in?(available_options) })
    end
  end

  should "raise ArgumentError if default value is not included in mapping" do
    assert_raises ArgumentError, "default value not provided in mapping" do
      Aggregate::AttributeHandler.factory("testme", :bitfield, limit: 4, default: :default)
    end
  end

  should "raise ArgumentError if mapping provided is not a hash" do
    assert_raises ArgumentError, "mapping must be provided as a Hash" do
      Aggregate::AttributeHandler.factory("testme", :bitfield, limit: 4, mapping: [])
    end
  end

  should "raise ArgumentError if mapping values are not unique" do
    assert_raises ArgumentError, "mapping must have unique values" do
      Aggregate::AttributeHandler.factory("testme", :bitfield, limit: 4, mapping: { 't' => true, 'f' => true, ' ' => nil })
    end
  end
end


text:
require('./debounce');

var MODULE_NAME = 'ui.bootstrap.module.debounce';

angular.module(MODULE_NAME, ['ui.bootstrap.debounce']);

module.exports = MODULE_NAME;


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@mipmap/switch_on" />
    <item android:state_selected="false" android:drawable="@mipmap/switch_off" />
</selector>


text:
<?php

namespace GotChosen\Util;

class Strings
{
    public static function base64EncodeUrl($text)
    {
        $enc = base64_encode($text);
        $enc = strtr($enc, '+/=', '._-');
        return $enc;
    }

    public static function base64DecodeUrl($enc)
    {
        $enc = strtr($enc, '._-', '+/=');
        $text = base64_decode($enc);
        return $text;
    }

    /**
     * Slugify a string - There's no reason this shouldn't work since we're
     * using PHP 5.4+ everywhere?
     *
     * @param string $string
     * @return string
     */
    public static function slugify($string)
    {
        $string = transliterator_transliterate("Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC; [:Punctuation:] Remove; Lower();", $string);
        $string = preg_replace('/[-\s]+/', '-', $string);
        return trim($string, '-');
    }
}


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

namespace Baud.Deployment.BusinessLogic.Contracts
{
    public interface IAgentAdapter
    {
        Task<Agents.Models.Deployment> DeployPackageAsync(string siteID, byte[] package);

        Task<IDictionary<string, string>> GetSharedParameters();

        Task<string> GetSharedParameter(string parameterName);

        Task SetSharedParameters(IDictionary<string, string> parameters);

        Task SetSharedParameter(string parameterName, string stringValue);

        Task DeleteSharedParameter(string parameterName);

        Task<IDictionary<string, string>> GetSiteParameters(string siteID);

        Task<string> GetSiteParameter(string siteID, string parameterName);

        Task SetSiteParameters(string siteID, IDictionary<string, string> parameters);

        Task SetSiteParameter(string siteID, string parameterName, string stringValue);

        Task DeleteSiteParameter(string siteID, string parameterName);
    }
}


text:
set -e
set -x

mvnSettings="$1"
taggedVersion="$2"
newVersion="$3"

rootDir="$(pwd)"

./src/build/sh/mvn-versions-set.sh "$mvnSettings" "${taggedVersion}"
tag="${taggedVersion}"
msg="Tagged ${tag}"
git commit -a -m "${msg}"
git tag -a "${tag}" -m "${msg}"
./src/build/sh/mvn-versions-set.sh "$mvnSettings" "${newVersion}"
git commit -a -m "Prepare for next development iteration"
git checkout "${tag}"


text:
<!DOCTYPE html>

    <title>Gentoo Tyrian Template</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="theme-color" content="#54487a">
    <meta name="description" content="">
    <link href="assets/bootstrap.css" rel="stylesheet" media="screen">
    <link href="assets/tyrian.css" rel="stylesheet" media="screen">

                 Get Gentoo!

                     gentoo.org sites

 gentoo.org

 Wiki

 Bugs

 Forums

 Packages

 Planet

 Archives

 Sources

 Infra Status

                <object data="assets/site-logo.svg" type="image/svg+xml">

                </object>

              Site Title

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
                Toggle navigation

              </button>

Home

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Home

Install, Customize, Love

We produce Gentoo Linux, a special flavor of Linux that can be automatically optimized and customized for just about any application or need. Extreme performance, configurability and a top-notch user and developer community are all hallmarks of the Gentoo experience.

Learn more »

News

Google Summer of Code applications close April 6 posted on April 7, 2012 by Donnie Berkholz

Students, only a few days remain to apply for Gentoo's 7th year in the Google Summer of Code! GSoC pays college students $5000 to work full-time on an open-source project for a summer. Check out our GSoC 2012 homepage if you are interested in this year's GSoC for Gentoo. We particularly encourage applications from students who are new to Gentoo development—many of our students become Gentoo developers after a successful summer.

Interested students can browse Gentoo's project ideas. Student applications will be accepted until 1900 UTC April 6, so start now if you haven't already!

Developers, if you'd like to apply to be a mentor, you can do so on the webapp. Please read the mentoring guide before applying.

Gentoo Linux releases 12.1 LiveDVD posted on April 1, 2012 by Robin H. Johnson

Gentoo Linux is proud to announce the availability of a new LiveDVD to celebrate the continued collaboration between Gentoo users and developers. The LiveDVD features a superb list of packages, some of which are listed below.

A special thanks to the Gentoo Infrastructure Team. Their hard work behind the scenes provide the resources, services and technology necessary to support the Gentoo Linux project.

Packages included in this release: Linux Kernel 3.3.0, Xorg 1.12.0, KDE 4.8.1, Gnome 3.2.1, XFCE 4.8, Fluxbox 1.3.2, Firefox 11.0, LibreOffice 3.5.1.2, Gimp 2.6.12, Blender 2.60, Amarok 2.5 , VLC 2.0.1 and much more ... If you want to see if your package is included we have generated both the x86 package list, and amd64 package list. You may also be interested in checking out the FAQ. There is no new artwork for the 12.1 release, but you can still get the 12.0 artwork plus DVD cases and covers for the 12.0 release.

Special Features:

ZFSOnLinux

Writable file systems using AUFS so you can emerge new packages!

Persistence for $HOME is available; press F9 for more info!

More news »

Developer Blogs (Planet Gentoo)

              Andreas K. Hüttel
              Please test cups-1.5

              Diego E. Pettenò
              Back to Cinnamon!

              Eray Aslan
              Upgrading to Postfix-2.9

              Sebastian Pipping
              overlint: Static analysis for your Gentoo overlay

              Tomáš Chvátal
              Stabilisation of libreoffice-3.5

Sponsors

Gentoo is proudly sponsored by:

New Packages

              dev-lang/ruby
              The Ruby interpreter

              dev-vcs/git
              The stupid content tracker

              kde-misc/ktwitter
              KDE Twitter client

Security Updates

              GLSA 2012-02-02
              critical
              GNOME: Execution of arbitrary code

              GLSA 2012-02-01
              moderate
              KDE: Denial of Service

              GLSA 2012-01-34
              minor
              Xfce: Information disclosure

Questions or comments?

            Please feel free to contact us.

            © 2001–2016 Gentoo Foundation, Inc.

              Gentoo is a trademark of the Gentoo Foundation, Inc.
              The contents of this document, unless otherwise expressly stated, are licensed under the
              CC-BY-SA-3.0 license.
              The Gentoo Name and Logo Usage Guidelines apply.


text:
package Opengl

import "strconv"

const (
	NO_TEXTURE float32 = 0.1
	TEXTURED   float32 = 1.1
)

func samplerIdx(idx int) string {
	strIdx := strconv.Itoa(idx)
	return `
    if (int(samplerIdxOut) == ` + strIdx + `) {
        tex = texture2D( myTextureSampler[` + strIdx + `], UV );
    }`
}

func VertexShader() string {
	return `

#version ` + OGL_VERSION + `

// Input vertex data, different for all executions of this shader.
in vec3 vertexPosition_modelspace;
out vec3 fragPos;

// model view normal
in vec3 mNorm;

// world normal
in vec3 wNorm;
out vec3 wNormFrag;

in vec4 diffuse;

in vec2 vertexUV;

// mode set
in float mode;
out float modeOut;

//sampleridx set
in float samplerIdx;
out float samplerIdxOut;

// Output data ; will be interpolated for each fragment.
out vec2 UV;

// Output data ; will be interpolated for each fragment.
out vec4 diffuseFragment;

// Values that stay constant for the whole mesh.
uniform mat4 MVP;

void main(){

    gl_Position = MVP * vec4 (vertexPosition_modelspace,1); //* MVP;

    // The color of each vertex will be interpolated
    // to produce the color of each fragment
    diffuseFragment = diffuse;

    // display uv textures?
    modeOut = mode;

    // which sampler to use
    samplerIdxOut = samplerIdx;

		// pass the pos to fragment shader
		fragPos = vertexPosition_modelspace;

		// pass the world normal to fragment shader
		wNormFrag = wNorm;

    // UV of the vertex. No special space for this one.
    UV = vertexUV;

}
` + "\x00"

}

func FragmentShader() string {
	strTexUnits := strconv.Itoa(texUnits)

	samplerIdxStr := ""

	// texNum := int(Probe().MaxTextureImageUnits)

	for i := 0; i < texUnits; i++ {
		samplerIdxStr += samplerIdx(i)
	}

	return `
#version ` + OGL_VERSION + `

struct Light {
   vec3 position;
   vec3 intensities; //a.k.a the color of the light
   float attenuation;
   float ambientCoefficient;
} ;

uniform Light light;
uniform vec3 cameraPosition;

// Interpolated values from the vertex shaders
in mediump vec4 diffuseFragment;

// fragment position passed vertex position.. transformed already
in mediump vec3 fragPos;

// fragment world normal
in mediump vec3 wNormFrag;

// Display uv?
in mediump float modeOut;

// which sampler to use
in mediump float samplerIdxOut;

// Interpolated values from the vertex shaders
in mediump vec2 UV;

// Ouput data
out mediump vec4 color;

// Values that stay constant for the whole mesh.
uniform sampler2D myTextureSampler[` + strTexUnits + `];

vec3 linearLight(in vec4 surfaceColor) {
	vec3 normal = wNormFrag;
	vec3 surfacePos = fragPos;

	vec3 surfaceToLight = normalize(light.position - surfacePos);
	vec3 surfaceToCamera = normalize(cameraPosition - surfacePos);

	//ambient
	vec3 ambient = .2 * surfaceColor.rgb * light.intensities;

	//diffuse
	float diffuseCoefficient = max(0.0, dot(normal, surfaceToLight));
	vec3 diffuse = diffuseCoefficient * surfaceColor.rgb * light.intensities;

	//specular
	float specularCoefficient = 0.0;
	if(diffuseCoefficient > 0.0)
			specularCoefficient = pow(max(0.0, dot(surfaceToCamera, reflect(-surfaceToLight, normal))), .5);
	vec3 specular = specularCoefficient * vec3(.2,1,.2) * light.intensities;

	//attenuation
  float distanceToLight = length(light.position - surfacePos);
  float attenuation = 1.0 / (1.0 + light.attenuation * pow(distanceToLight, 2));

	return ambient + attenuation*(diffuse + specular);
}

void main()
{
    // // Output color = red
    // color = vec4(fragmentColor,1.0);

    // Output color = color of the texture at the specified UV
    //color = texture2D( myTextureSampler, UV ).rgba;

    mediump vec4 tex ;

   ` + samplerIdxStr + `

    // Do we display textures or not?
    if (int(modeOut) == 0) {
			tex = vec4(0.0);
			tex.a = 1.0;
		}
    // mediump vec4 tex = texture2D( myTextureSampler[0], UV );

    tex.a *= diffuseFragment[3];
    // color = tex.rgba;
		vec4 surfaceColor = vec4(diffuseFragment[0], diffuseFragment[1], diffuseFragment[2], 1);
    color =  tex + surfaceColor*tex.a;

		vec3 gamma = vec3(1.0/2.2);
		// color = vec4(pow(linearLight(tex),gamma),tex.a);
}

` + "\x00"
}

var (
	OGL_VERSION string = "130"
)


text:
namespace tsp
{

    RouletteWheelSelector::RouletteWheelSelector()
    {
    }

    RouletteWheelSelector::~RouletteWheelSelector()
    {
    }

    void RouletteWheelSelector::select(const Population &population,
                                       std::vector<int> &parents)
    {
        unsigned int parentCount = 0;
        while(parentCount < parents.size()) {
            // generate target fitness value
            double selectFitness = Random::nextDouble();
            double accumFitness = 0;
            for(unsigned int i = 0; i < population.getIndividuals().size(); ++i) {
                // calculated accumulated fitness
                accumFitness += population.getIndividuals()[i].getNormalizedFitness();
                // check if random fitness is in interval
                if(accumFitness >= selectFitness) {
                    // check if previous parent was same
                    if(parentCount % 2 == 1 && parents[parentCount - 1] == static_cast<int>(i))
                        continue;
                    parents[parentCount] = i;
                    ++parentCount;
                    break;
                }
            }
        }
    }

}


text:
package filodb.akkabootstrapper.multijvm

import akka.remote.testkit.MultiNodeSpec
import com.typesafe.config.{Config, ConfigFactory}

object WhitelistBootstrapperMultiNodeConfig extends AkkaBootstrapperMultiNodeConfig {

  override def baseConfig: Config = ConfigFactory.parseString(
    s"""
       |akka-bootstrapper {
       |  seed-discovery.class = "filodb.akkabootstrapper.WhitelistClusterSeedDiscovery"
       |  whitelist.seeds = [
       |                          "akka.tcp://WhitelistBootstrapperSpec@127.0.0.1:2552"
       |                          "akka.tcp://WhitelistBootstrapperSpec@127.0.0.1:2562"
       |                          "akka.tcp://WhitelistBootstrapperSpec@127.0.0.1:2572"
       |                    ]
       |}
     """.stripMargin).withFallback(super.baseConfig)

  commonConfig(baseConfig)

  nodeConfig(node1)(ConfigFactory.parseString(
    s"""
       |akka.remote.netty.tcp.port = 2552
       |multijvmtest.http.port = 8070
     """.stripMargin))

  nodeConfig(node2)(ConfigFactory.parseString(
    s"""
       |akka.remote.netty.tcp.port = 2562
       |multijvmtest.http.port = 8080
     """.stripMargin))

  nodeConfig(node3)(ConfigFactory.parseString(
    s"""
       |akka.remote.netty.tcp.port = 2572
       |multijvmtest.http.port = 8090
     """.stripMargin))

}

/**
  * Run test as follows.
  *
  * Create consul dev config:
  * {{{
  *  > cat /usr/local/etc/consul/config/basic_config.json
  *  {
  *    "data_dir": "/usr/local/var/consul",
  *    "ui" : true,
  *    "dns_config" : {
  *        "enable_truncate" : true
  *     }
  *  }
  * }}}
  *
  * Then start consul: `consul agent -dev -config-dir=/usr/local/etc/consul/config/`
  *
  * Run test: `sbt "multi-jvm:test-only filodb.akkabootstrapper.multijvm.WhitelistBootstrapperSpec"`
  */
class WhitelistBootstrapperSpec extends MultiNodeSpec(WhitelistBootstrapperMultiNodeConfig)
  with BaseAkkaBootstrapperSpec {
  override val akkaBootstrapperMultiNodeConfig = WhitelistBootstrapperMultiNodeConfig
}
class WhitelistBootstrapperSpecMultiJvmNode1 extends WhitelistBootstrapperSpec
class WhitelistBootstrapperSpecMultiJvmNode2 extends WhitelistBootstrapperSpec
class WhitelistBootstrapperSpecMultiJvmNode3 extends WhitelistBootstrapperSpec


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Here we put strings that doesn't have to go to localization -->
<resources>
    <string name="preference_key_read_me">preference_key_read_me</string>
</resources>


text:
package it.itsoftware.chartx.kafka.tests.connect.influxdb;

import java.util.Collection;
import java.util.Map;

import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.connect.sink.SinkRecord;
import org.apache.kafka.connect.sink.SinkTask;

public class InfluxDBSinkTask extends SinkTask {

	@Override
	public String version() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void flush(Map<TopicPartition, OffsetAndMetadata> arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void put(Collection<SinkRecord> arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void start(Map<String, String> arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub

	}

}


text:
const Mocha = require('mocha')
const path = require('path')

module.exports = class {
  constructor(app, container, log, config) {
    this.container = container
    this.log = log
    this.app = app
    this.config = config

    this.mocha = new Mocha(this.getMochaOptions())
      .ui('tdd')
      .reporter('spec')
      .useColors(true)
  }

  getMochaOptions() {
    let options = {
      timeout: this.config.get('quadro.test.timeout', 2000)
    }

    return options
  }

  async addTestFiles() {
    let files = await this.app.glob('test/**/*_test.js')
    files.forEach(_ => this.mocha.addFile(_))
  }

  async run() {
    this.mocha.addFile(path.join(__dirname, './initialize_tests.js'))
    await this.addTestFiles()

    let runner = this.mocha.run((failures) => {
      if (global.coverage) global.coverage.report()
      process.exit(failures > 0 ? 1 : 0)
    })
    runner.on('fail', function(test, err) {
      let extra = err.extra
      if (extra) Q.log.error({ extra, test: test.title }, 'Extra error details')
    })
  }
}


text:
package com.example.junit5.hello;

import java.util.Objects;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import com.example.junit5.hello.impl.DefaultHello;
import com.example.junit5.hello.impl.MessageFormatter;

@Configuration
@ComponentScan
public class HelloConfiguration {

	private final MessageFormatter messageFormatter;

	public HelloConfiguration(final MessageFormatter messageFormatter) {
		this.messageFormatter = Objects.requireNonNull(messageFormatter);
	}

	@Bean
	public Hello hello() {
		return new DefaultHello(messageFormatter, "world");
	}
}


text:
"""
wego.settings

default setting
"""

from .exceptions import InitError
import wego
import logging

def init(**kwargs):
    """
    Init settings, get wechat config at https://mp.weixin.qq.com

    :param APP_ID: Wechat AppID get it at basic configuration(基本配置).
    :param APP_SECRET: Wechat AppSecret get it at basic configuration(基本配置).
    :param REGISTER_URL: As same as you set at interface permissions(接口权限)
            >> authorized users obtain basic information page(网页授权获取用户基本信息).
    :param HELPER: Official helper 'wego.helpers.DjangoHelper' and 'wego.helpers.TornadoHelper' or you can customized
            yourself helper with http://wego.quseit.com/customized/helper(building).

    :param MCH_ID: (optional) Mac ID get it at https://pay.weixin.qq.com/ (商户号).
    :param MCH_SECRET: (optional) MCH SECRET As same as you set at https://pay.weixin.qq.com/ (API 密钥).
    :param CERT_PEM_PATH: (optional) Path to apiclient_cert.pem.
    :param KEY_PEM_PATH: (optional) Path to apiclient_key.pem.
    :param PAY_NOTIFY_PATH: (optional) Default notify url for wechat pay callback.

    :param PUSH_TOKEN: (optional) Set at basic configuration(基本配置).
    :param PUSH_ENCODING_AES_KEY: (optional) Set at basic configuration(基本配置).

    :param GET_GLOBAL_ACCESS_TOKEN: (optional) A function that return a global access token, if your application run at
            multiple servers it required. How to customized your GET_GLOBAL_ACCESS_TOKEN:
            http://wego.quseit.com/customized/GET_GLOBAL_ACCESS_TOKEN(building).

    :param USERINFO_EXPIRE: (optional) Set number of seconds expired, default is 0. subscribe,
            language, remark and groupid still is real time.

    :param REDIRECT_PATH: (optional) Default redirect path, redirect when we get user`s authorize.
    :param REDIRECT_STATE: (optional) Default redirect state, redirect when we get user`s authorize.
    :param DEBUG: (optional) Default is True,
            When Debug equal True it will log all information and wechat payment only spend a penny(0.01 yuan).
    :return: :class:`WegoApi <wego.api.WegoApi>` object.
    :rtype: WegoApi.
    """

    default_settings = {
        'GET_GLOBAL_ACCESS_TOKEN': wego.api.official_get_global_access_token,
        'USERINFO_EXPIRE': 0,
        'DEBUG': False
    }
    kwargs = dict(default_settings, **kwargs)

    check_settings(kwargs)

    if 'REDIRECT_STATE' not in kwargs:
        kwargs['REDIRECT_STATE'] = False
    if 'REDIRECT_PATH' not in kwargs:
        kwargs['REDIRECT_PATH'] = False

    if 'PAY_NOTIFY_PATH' in kwargs:
        kwargs['PAY_NOTIFY_URL'] = kwargs['REGISTER_URL'] + kwargs['PAY_NOTIFY_PATH'][1:]

    logger = logging.getLogger('wego')
    formatter = logging.Formatter('%(asctime)s WEGO %(levelname)s: %(message)s', datefmt='%Y/%m/%d %I:%M:%S')
    ch = logging.StreamHandler()
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    logger.setLevel(logging.INFO)
    logger.warn = lambda x: logging.Logger.warn(logger, u'\033[1;31m%s\033[0m' % x)
    if kwargs['DEBUG']:
        logger.setLevel(logging.DEBUG)
        logger.warn(u'WEGO 运行在 DEBUG 模式, 微信支付付款金额将固定在 1 分钱.')
    kwargs['LOGGER'] = logger

    return wego.WegoApi(WegoSettings(kwargs))

def check_settings(settings):
    """
    check if settings is available

    :param settings: a dict.
    :return: None
    """

    required_list = [
        'APP_ID',
        'APP_SECRET',
        'REGISTER_URL',
        'HELPER'
    ]

    # optional_couple
    optional_couple_list = [
        ['MCH_ID', 'MCH_SECRET', 'PAY_NOTIFY_PATH', 'CERT_PEM_PATH', 'KEY_PEM_PATH'],
        ['PUSH_TOKEN', 'PUSH_ENCODING_AES_KEY'],
    ]

    for i in optional_couple_list:
        for j in i:
            if j in settings:
                required_list += i
                break

    for i in required_list:
        if i not in settings or not settings[i]:
            raise InitError('Missing required parameters "{param}"(缺少必须的参数 "{param}")'.format(param=i))

    if not settings['REGISTER_URL'].endswith('/'):
        raise InitError('REGISTER_URL has to ends with "/"(REGISTER_URL 需以 "/" 结尾)')

    if 'REDIRECT_PATH' in settings and not settings['REDIRECT_PATH'].startswith('/'):
        raise InitError('REDIRECT_PATH have to starts with "/"(REDIRECT_PATH 需以 "/" 开始)')

    if 'PAY_NOTIFY_PATH' in settings and not settings['PAY_NOTIFY_PATH'].startswith('/'):
        raise InitError('PAY_NOTIFY_PATH have to starts with "/"(PAY_NOTIFY_PATH 需以 "/" 开始)')

    if type(settings['HELPER']) is str:
        modules = settings['HELPER'].split('.')
        settings['HELPER'] = getattr(__import__('.'.join(modules[:-1]), fromlist=['']), modules[-1])

    if not issubclass(settings['HELPER'], wego.helpers.BaseHelper):
        raise InitError('Helper have to inherit the wego.helper.BaseHelper(Helper 必须继承至 wego.helper.BaseHelper)')

    if not hasattr(settings['GET_GLOBAL_ACCESS_TOKEN'], '__call__'):
        raise InitError('GET_GLOBAL_ACCESS_TOKEN is not a function(GET_ACCESS_TOKEN 不是一个函数)')

    # TODO 检查推送消息加解密所需依赖是否安装 PUSH_TOKEN PUSH_ENCODING_AES_KEY

    settings['DEBUG'] = not not settings['DEBUG']

class WegoSettings(object):
    """
    Wego settings
    """

    def __init__(self, data):
        self.data = data

    def __getattr__(self, key):
        if key in self.data:
            return self.data[key]
        return ''


text:
<?php

/**
 * @namespace
 */
namespace Bluz\Tests\Fixtures\Models\Auth;

use Bluz\Application;
use Bluz\Auth\AbstractTable;

/**
 * Auth Table
 *
 * @package  Bluz\Tests\Fixtures\Models\Auth
 *
 * @method   static Row findRow($primaryKey)
 * @method   static Row findRowWhere($whereList)
 */
class Table extends AbstractTable
{
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
		"http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>doh.robot MultiSelect Test</title>

		<style>
			@import "../../../../util/doh/robot/robot.css";
		</style>

		<!-- required: dojo.js -->
		<script type="text/javascript" src="../../../../dojo/dojo.js"></script>

		<script type="text/javascript">
			dojo.require("dui.robotx");
			dojo.require("dui.tests.helpers");	// functions to help test

			function testInverted(allOptions, selected, newSelected){
				doh.is(allOptions.length, selected.length+newSelected.length); //newSelected + the no longer selected list size should be the same as the length of the whole list
				dojo.forEach(allOptions, function(option){ //verify the selections were inverted
					var found;
					if(option.selected){
						//it must be in the newSelectedList
						found=false;
						dojo.forEach(newSelected, function(ns){
							if(option.value===ns){
								found=true;
							}
						});
						doh.t(found);
					}else{
						//it better be in the origional selected list
						found=false;
						dojo.forEach(selected, function(s){
							if(option.value===s){
								found=true;
							}
						});
						doh.t(found);
					}
				});
			}

			dojo.ready(function(){
				doh.robot.initRobot('../test_MultiSelect.html');

				doh.register("dui.form.MultiSelect", [
					{
						name: "tabInSelect",
						timeout: 6000,
						runTest: function(){
							var d = new doh.Deferred();

							var changed = false;
							dui.byId("select").set("onChange", function(e){changed = true; });

							dojo.global.scrollTo(0,0);
							doh.robot.mouseMove(30,30);
							doh.robot.mouseClick({left:true}, 1000); //tabbing in doesn't work in FF unless we first click on the page first

							doh.robot.keyPress(dojo.keys.TAB, 1000, {});
							doh.robot.keyPress(dojo.keys.DOWN_ARROW, 1000, {}); //Arrowing down will select the element for IE, FF, Safari, & chrome
							doh.robot.keyPress(dojo.keys.SPACE, 1000, {}); //Space is needed to select the element in opera

							doh.robot.sequence(d.getTestCallback(function(){
								doh.t(changed);
							}), 1000);
							return d;
						}
					},
					{
						name: "switchRight",
						timeout: 5000,
						runTest: function(){
							var d = new doh.Deferred();

							doh.robot.sequence(function(){
								dui.byId('select').set('value', ['16']);
							}, 500);

							doh.robot.mouseMoveAt("right", 1000);
							doh.robot.mouseClick({left:true}, 500);

							var selectedValue2 = "";
							doh.robot.sequence(function(){ selectedValue2 = dui.byId('select2').get('value');}, 1000);

							doh.robot.sequence(d.getTestCallback(function(){
								doh.is("16", dui.byId('select2').value.toString());
								doh.is("16", selectedValue2[0]);
							}), 1000);
							return d;
						}
					},
					{
						name: "switchLeft",
						timeout: 5000,
						runTest: function(){
							var d = new doh.Deferred();

							doh.robot.sequence(function(){
								dui.byId('select2').set('value', ['3','7','19','47']);
							}, 500);

							doh.robot.mouseMoveAt("left", 1000);
							doh.robot.mouseClick({left:true}, 500);

							var selectedValue = "";
							doh.robot.sequence(function(){ selectedValue = dui.byId('select').get('value');}, 1000);

							doh.robot.sequence(d.getTestCallback(function(){
								doh.is("3", selectedValue[0]);
								doh.is("7", selectedValue[1]);
								doh.is("19", selectedValue[2]);
								doh.is("47", selectedValue[3]);
								doh.is("3 7 19 47", dui.byId('select').value.join(' '));
							}), 1000);
							return d;
						}
					},
					{
						name: "invertSelected",
						timeout: 8000,
						runTest: function(){
							var d = new doh.Deferred();

							//select a block in the first list
							doh.robot.sequence(function(){
								dui.byId('select').set('value', ['18','14','12','10']);
							}, 500);

							//get the selected list
							var allOptions = "";
							var selected = "";
							var newSelected = "";
							doh.robot.sequence(function(){
								selected = dui.byId('select').get('value');
								allOptions = dui.byId('select').domNode.options;
							}, 1000);

							doh.robot.mouseMoveAt("i1", 1000);
							doh.robot.mouseClick({left:true}, 500);

							doh.robot.sequence(function(){
								newSelected = dui.byId('select').get('value');
							}, 1000);

							doh.robot.sequence(d.getTestCallback(function(){
								testInverted(allOptions, selected, newSelected);
							}), 1000);
							return d;
						}
					},
					{
						name: "invertSelected2",
						timeout: 8000,
						runTest: function(){
							var d = new doh.Deferred();

							//select random options
							doh.robot.sequence(function(){
								dui.byId('select').set('value', ['2','8','14','20','22','32']);
							}, 500);

							//get the selected list
							var allOptions = "";
							var selected = "";
							var newSelected = "";
							doh.robot.sequence(function(){
								selected = dui.byId('select').get('value');
								allOptions = dui.byId('select').domNode.options;
							}, 1000);

							doh.robot.mouseMoveAt("i1", 1000);
							doh.robot.mouseClick({left:true}, 500);

							doh.robot.sequence(function(){
								newSelected = dui.byId('select').get('value');
							}, 1000);

							doh.robot.sequence(d.getTestCallback(function(){
								testInverted(allOptions, selected, newSelected);
							}), 1000);
							return d;
						}
					},
					{
						name: "invertSelected3",
						timeout: 8000,
						runTest: function(){
							var d = new doh.Deferred();

							//Select the first thing in the list and then invert it
							//select random options
							doh.robot.sequence(function(){
								dui.byId('select3').set('value', ['TN']);
							}, 500);

							//get the selected list
							var allOptions = "";
							var selected = "";
							var newSelected = "";
							doh.robot.sequence(function(){
								selected = dui.byId('select3').get('value');
								allOptions = dui.byId('select3').domNode.options;
							}, 1000);

							doh.robot.mouseMoveAt("i3", 1000);
							doh.robot.mouseClick({left:true}, 500);

							doh.robot.sequence(function(){
								newSelected = dui.byId('select3').get('value');
							}, 1000);

							doh.robot.sequence(d.getTestCallback(function(){
								testInverted(allOptions, selected, newSelected);
							}), 1000);
							return d;
						}
					},
					{
						name: "setValue",
						timeout: 5000,
						runTest: function(){
							var d = new doh.Deferred();

							//Select only one thing in the list to make sure we don't start with the values that we are going to select
							doh.robot.sequence(function(){
								dui.byId('select3').set('value', ['CA']);
							}, 500);

							doh.robot.mouseMoveAt("s1", 1000);
							doh.robot.mouseClick({left:true}, 500);

							doh.robot.sequence(d.getTestCallback(function(){
								var selected = dui.byId('select3').get('value');
								doh.is(2, selected.length);
								doh.is(selected[0], 'VA');
								doh.is(selected[1], 'WA');
								doh.is("VA WA", dui.byId('select3').value.join(' '));
							}), 1000);
							return d;
						}
					}

				]);

				doh.run();
			});
		</script>
	</head>
</html>


text:
<html>
<body>
Changes attribute value.
</body>
</html>