text:
<?php

namespace Drupal\Core\Entity;

use Drupal\Core\Entity\Exception\UnsupportedEntityTypeDefinitionException;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\user\UserInterface;

/**
 * Provides a trait for accessing revision logging and ownership information.
 *
 * @ingroup entity_api
 */
trait RevisionLogEntityTrait {

  /**
   * Provides revision-related base field definitions for an entity type.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   *
   * @return \Drupal\Core\Field\FieldDefinitionInterface[]
   *   An array of base field definitions for the entity type, keyed by field
   *   name.
   *
   * @see \Drupal\Core\Entity\FieldableEntityInterface::baseFieldDefinitions()
   */
  public static function revisionLogBaseFieldDefinitions(EntityTypeInterface $entity_type) {

    if (!($entity_type instanceof ContentEntityTypeInterface)) {
      throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type->id() . ' is not a content entity type.');
    }
    foreach (['revision_created', 'revision_user', 'revision_log_message'] as $revision_metadata_key) {
      if (!$entity_type->hasRevisionMetadataKey($revision_metadata_key)) {
        throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type->id() . ' does not have an "' . $revision_metadata_key . '" entity revision metadata key.');
      }
    }

    $fields[$entity_type->getRevisionMetadataKey('revision_created')] = BaseFieldDefinition::create('created')
      ->setLabel(t('Revision create time'))
      ->setDescription(t('The time that the current revision was created.'))
      ->setRevisionable(TRUE);

    $fields[$entity_type->getRevisionMetadataKey('revision_user')] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Revision user'))
      ->setDescription(t('The user ID of the author of the current revision.'))
      ->setSetting('target_type', 'user')
      ->setRevisionable(TRUE);

    $fields[$entity_type->getRevisionMetadataKey('revision_log_message')] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Revision log message'))
      ->setDescription(t('Briefly describe the changes you have made.'))
      ->setRevisionable(TRUE)
      ->setDefaultValue('')
      ->setDisplayOptions('form', [
        'type' => 'string_textarea',
        'weight' => 25,
        'settings' => [
          'rows' => 4,
        ],
      ]);

    return $fields;
  }

  /**
   * Implements \Drupal\Core\Entity\RevisionLogInterface::getRevisionCreationTime().
   */
  public function getRevisionCreationTime() {
    return $this->{$this->getEntityType()->getRevisionMetadataKey('revision_created')}->value;
  }

  /**
   * Implements \Drupal\Core\Entity\RevisionLogInterface::setRevisionCreationTime().
   */
  public function setRevisionCreationTime($timestamp) {
    $this->{$this->getEntityType()->getRevisionMetadataKey('revision_created')}->value = $timestamp;
    return $this;
  }

  /**
   * Implements \Drupal\Core\Entity\RevisionLogInterface::getRevisionUser().
   */
  public function getRevisionUser() {
    return $this->{$this->getEntityType()->getRevisionMetadataKey('revision_user')}->entity;
  }

  /**
   * Implements \Drupal\Core\Entity\RevisionLogInterface::setRevisionUser().
   */
  public function setRevisionUser(UserInterface $account) {
    $this->{$this->getEntityType()->getRevisionMetadataKey('revision_user')}->entity = $account;
    return $this;
  }

  /**
   * Implements \Drupal\Core\Entity\RevisionLogInterface::getRevisionUserId().
   */
  public function getRevisionUserId() {
    return $this->{$this->getEntityType()->getRevisionMetadataKey('revision_user')}->target_id;
  }

  /**
   * Implements \Drupal\Core\Entity\RevisionLogInterface::setRevisionUserId().
   */
  public function setRevisionUserId($user_id) {
    $this->{$this->getEntityType()->getRevisionMetadataKey('revision_user')}->target_id = $user_id;
    return $this;
  }

  /**
   * Implements \Drupal\Core\Entity\RevisionLogInterface::getRevisionLogMessage().
   */
  public function getRevisionLogMessage() {
    return $this->{$this->getEntityType()->getRevisionMetadataKey('revision_log_message')}->value;
  }

  /**
   * Implements \Drupal\Core\Entity\RevisionLogInterface::setRevisionLogMessage().
   */
  public function setRevisionLogMessage($revision_log_message) {
    $this->{$this->getEntityType()->getRevisionMetadataKey('revision_log_message')}->value = $revision_log_message;
    return $this;
  }

  /**
   * Gets the name of a revision metadata field.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   A content entity type definition.
   * @param string $key
   *   The revision metadata key to get, must be one of 'revision_created',
   *   'revision_user' or 'revision_log_message'.
   *
   * @return string
   *   The name of the field for the specified $key.
   */
  protected static function getRevisionMetadataKey(EntityTypeInterface $entity_type, $key) {
    @trigger_error(static::class . 'getRevisionMetadataKey() is deprecated in drupal:9.0.0 and is removed from drupal:10.0.0. Use $entity_type->getRevisionMetadataKey() instead. See: https://www.drupal.org/node/2831499', E_USER_DEPRECATED);
    /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */
    return $entity_type->getRevisionMetadataKey($key);
  }

  /**
   * Gets the entity type definition.
   *
   * @return \Drupal\Core\Entity\ContentEntityTypeInterface
   *   The content entity type definition.
   */
  abstract public function getEntityType();

}


text:
[![Circle CI](https://circleci.com/gh/planningcenter/pco_api_ruby/tree/master.svg?style=svg)](https://circleci.com/gh/planningcenter/pco_api_ruby/tree/master)

`pco_api` is a Rubygem that provides a simple wrapper around our RESTful JSON API at https://api.planningcenteronline.com.

## Installation

```
gem install pco_api
```

## Usage

1. Create a new API object, passing in your credentials (either HTTP Basic or OAuth2 access token):

    ```ruby
    # authenticate with HTTP Basic:
    api = PCO::API.new(basic_auth_token: 'token', basic_auth_secret: 'secret')
    # ...or authenticate with an OAuth2 access token (use the 'oauth2' gem to obtain the token)
    api = PCO::API.new(oauth_access_token: 'token')
    ```

2. Chain path elements together as method calls.

    ```ruby
    api.people.v2.households
    # /people/v2/households
    ```

3. For IDs, treat the object like a hash (use square brackets).

    ```ruby
    api.people.v2.households[1]
    # /people/v2/households/1
    ```

4. To execute the request, use `get`, `post`, `patch`, or `delete`, optionally passing arguments.

    ```ruby
    api.people.v2.households.get(order: 'name')
    # GET /people/v2/households?order=name
    ```

5. To query dataset according to `can_query_by` variables:

    ```ruby
    api.people.v2.people.get('where[membership]': 'Member')
    # GET /people/v2/people?where[membership]=Member
    ```

## Example

```ruby
require 'pco_api'

api = PCO::API.new(basic_auth_token: 'token', basic_auth_secret: 'secret')
api.people.v2.people.get(order: 'last_name')
```

...which returns something like:

```ruby
{
  "links" => {
    "self" => "https://api.planningcenteronline.com/people/v2/people?order=last_name",
    "next" => "https://api.planningcenteronline.com/people/v2/people?offset=25&order=last_name"
  },
  "data"=> [
    {
      "type" => "Person",
      "id" => "271",
      "attributes" => {
        "first_name" => "Jean",
        "middle_name" => nil,
        "last_name" => "Abernathy",
        "birthdate" => "1885-01-01",
        "anniversary" => nil,
        "gender" => "F",
        "grade" => -1,
        "child" => false,
        "status" => "active",
        "school_type" => nil,
        "graduation_year" => nil,
        "site_administrator" => false,
        "people_permissions" => nil,
        "created_at" => "2015-04-01T20:18:22Z",
        "updated_at" => "2015-04-10T18:59:51Z",
        "avatar" => nil,
      },
      "links" => {
        "self" => "https://api.planningcenteronline.com/people/v2/people/271"
      }
    },
    # ...
  ],
  "meta" => {
    "total_count" => 409,
    "count" => 25,
    "next" => {
      "offset" => 25
    },
    "can_order_by" => [
      "first_name",
      "middle_name",
      "last_name",
      "birthdate",
      "anniversary",
      "gender",
      "grade",
      "child",
      "status",
      "school_type",
      "graduation_year",
      "site_administrator",
      "people_permissions",
      "created_at",
      "updated_at"
    ],
    "can_query_by" => [
      "first_name",
      "middle_name",
      "last_name",
      "birthdate",
      "anniversary",
      "gender",
      "grade",
      "child",
      "status",
      "school_type",
      "graduation_year",
      "site_administrator",
      "people_permissions",
      "created_at",
      "updated_at"
    ],
    "can_include" => [
      "emails",
      "addresses",
      "phone_numbers",
      "households",
      "school",
      "inactive_reason",
      "marital_status",
      "name_prefix",
      "name_suffix",
      "field_data",
      "apps"
    ],
    "parent" => {
      "id" => "1",
      "type" => "Organization"
    }
  }
}
```

## get()

`get()` works for a collection (index) and a single resource (show).

```ruby
# collection
api.people.v2.people.get(order: 'last_name')
# => { data: array_of_resources }

# single resource
api.people.v2.people[1].get
# => { data: resource_hash }
```

## post()

`post()` sends a POST request to create a new resource. You *must* wrap your resource with
a `{ data: { ... } }` hash.

```ruby
api.people.v2.people.post(data: { type: 'Person', attributes: { first_name: 'Tim', last_name: 'Morgan' } })
# => { data: resource_hash }
```

## patch()

`patch()` sends a PATCH request to update an existing resource. You *must* wrap your resource with
a `{ data: { ... } }` hash.

```ruby
api.people.v2.people[1].patch(data: { type: 'Person', id: 1, attributes: { first_name: 'Tim', last_name: 'Morgan' } })
# => { data: resource_hash }
```

## delete()

`delete()` sends a DELETE request to delete an existing resource. This method returns `true` if the delete was successful.

```ruby
api.people.v2.people[1].delete
# => true
```

## Errors

The following errors may be raised by the library, depending on the API response status code.

| HTTP Status Codes   | Error Class                                                               |
| ------------------- | ------------------------------------------------------------------------- |
| 400                 | `PCO::API::Errors::BadRequest` < `PCO::API::Errors::ClientError`          |
| 401                 | `PCO::API::Errors::Unauthorized` < `PCO::API::Errors::ClientError`        |
| 403                 | `PCO::API::Errors::Forbidden` < `PCO::API::Errors::ClientError`           |
| 404                 | `PCO::API::Errors::NotFound` < `PCO::API::Errors::ClientError`            |
| 405                 | `PCO::API::Errors::MethodNotAllowed` < `PCO::API::Errors::ClientError`    |
| 422                 | `PCO::API::Errors::UnprocessableEntity` < `PCO::API::Errors::ClientError` |
| 429                 | `PCO::API::Errors::TooManyRequests` < `PCO::API::Errors::ClientError`     |
| other 4xx errors    | `PCO::API::Errors::ClientError`                                           |
| 500                 | `PCO::API::Errors::InternalServerError` < `PCO::API::Errors::ServerError` |
| other 5xx errors    | `PCO::API::Errors::ServerError`                                           |

The exception object has the following methods:

| Method  | Content                                     |
| ------- | ------------------------------------------- |
| status  | HTTP status code returned by the server     |
| message | the message returned by the API             |
| detail  | the full error response returned by the API |
| headers | hash of HTTP headers returned by the API    |

The `message` should be a simple string given by the API, e.g. "Resource Not Found".

In the case of validation errors, the `message` is a summary string built from the raw `detail`.

Alternatively, you may rescue `PCO::API::Errors::BaseError` and branch your code based on
the status code returned by calling `error.status`.

### TooManyRequests Error

By default, PCO::API::Endpoint will sleep and retry a request that fails with TooManyRequests due
to rate limiting. If you would rather catch and handle such errors yourself, you can disable this
behavior like this:

```ruby
api = PCO::API.new(...)
api.retry_when_rate_limited = false
```

## Copyright & License

Copyright Ministry Centered Technologies. Licensed MIT.

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Grav\Plugin\VideoEmbed\Tests\VideoEmbed\Service;

use Grav\Plugin\VideoEmbed\Service\VideoJS;

class VideoJSTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var VideoJS
     */
    protected $service;

    protected function setUp()
    {
        $this->service = new VideoJS([
            'embed_html_attr' => [
                'id' => 'test'
            ]
        ]);
    }

    /**
     * @param $url string
     * @param $isMatch bool
     * @param $format string
     * @dataProvider dpGetRegExpression
     */
    public function testGetRegExpression($url, $isMatch, $format = null)
    {
        $this->assertEquals(
            $isMatch,
            preg_match('/'.$this->service->getRegExpression().'/', $url, $matches)
        );

        if ($isMatch) {
            $this->assertEquals($format, $matches[7]);
        }
    }

    /**
     * @param array $matches
     * @dataProvider dpGetEmbedNodes
     */
    public function testGetEmbedNodes(array $matches)
    {
        $embed = $this->service->getEmbedNodes($matches);

        $this->assertEquals('video', $embed->nodeName);
        $this->assertEquals(
            'test',
            $embed->attributes->getNamedItem('id')->nodeValue
        );

        $dSetup = $embed->attributes->getNamedItem('data-setup');
        $dSetup = json_decode($dSetup->nodeValue, true);

        parse_str(trim($matches[8], '?& '), $expectedSettings);
        foreach ($expectedSettings as $setting => $settingVal) {
            $this->assertEquals(
                $settingVal,
                $dSetup[$setting]
            );
        }

        $source = $embed->childNodes->item(0);
        $this->assertEquals('source', $source->nodeName);
        $this->assertEquals(
            $this->service->getSupportedExt()[$matches[7]],
            $source->attributes->getNamedItem('type')->nodeValue
        );
        $this->assertEquals(
            $matches[1],
            $source->attributes->getNamedItem('src')->nodeValue
        );
    }

    public function dpGetEmbedNodes()
    {
        return [
            [[
                1 => 'http://test/vid1.mp4',
                7 => 'mp4',
                8 => ''
            ]],
            [[
                1 => 'http://test2/vid2.mov',
                7 => 'mp4',
                8 => '?poster=test.jpg&test=ok'
            ]]
        ];
    }

    public function dpGetRegExpression()
    {
        return [
            [
                'http://localhost/vid1.mp4',
                true,
                'mp4'
            ],
            [
                '.mp4',
                false
            ],
            [
                'https://google.com/video/vid1.mp3',
                false
            ],
            [
                'https://google.com/video/vid1.mov',
                true,
                'mov'
            ]
        ];
    }
}


text:
#ifndef YAMC_TESTUTIL_HPP_
#define YAMC_TESTUTIL_HPP_

#include <cassert>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>

// platform
#if defined(_WIN32)
#define TEST_PLATFORM_LINUX 0
#define TEST_PLATFORM_OSX 0
#define TEST_PLATFORM_WINDOWS 1
#elif defined(__APPLE__)
#define TEST_PLATFORM_LINUX 0
#define TEST_PLATFORM_OSX 1
#define TEST_PLATFORM_WINDOWS 0
#elif defined(__linux)
#define TEST_PLATFORM_LINUX 1
#define TEST_PLATFORM_OSX 0
#define TEST_PLATFORM_WINDOWS 0
#endif

// C++ compiler
#if defined(__clang__)
#define TEST_COMPILER_CLANG 1
#define TEST_COMPILER_GCC 0
#define TEST_COMPILER_MSVC 0
#elif defined(__GNUC__)
#define TEST_COMPILER_CLANG 0
#define TEST_COMPILER_GCC 1
#define TEST_COMPILER_MSVC
#elif defined(_MSC_VER)
#define TEST_COMPILER_CLANG 0
#define TEST_COMPILER_GCC 0
#define TEST_COMPILER_MSVC 1
#endif

namespace yamc {
namespace test {

/// auto join thread
class join_thread {
  std::thread thd_;

public:
  template<typename F>
  explicit join_thread(F&& f)
    : thd_(std::forward<F>(f)) {}

  ~join_thread() noexcept(false)
  {
    thd_.join();
  }

  join_thread(const join_thread&) = delete;
  join_thread& operator=(const join_thread&) = delete;
  join_thread(join_thread&&) = default;
  join_thread& operator=(join_thread&&) = default;
};

/// rendezvous point primitive
class barrier {
  std::size_t nthread_;
  std::size_t count_;
  std::size_t step_ = 0;
  std::condition_variable cv_;
  std::mutex mtx_;

public:
  explicit barrier(std::size_t n)
    : nthread_(n), count_(n) {}

  barrier(const barrier&) = delete;
  barrier& operator=(const barrier&) = delete;

  bool await()
  {
    std::unique_lock<std::mutex> lk(mtx_);
    std::size_t step = step_;
    if (--count_ == 0) {
      count_ = nthread_;
      ++step_;
      cv_.notify_all();
      return true;
    }
    while (step == step_) {
      cv_.wait(lk);
    }
    return false;
  }
};

/// phase control primitive
class phaser {
  std::size_t sentinel_ = 0;
  std::vector<std::size_t> phase_;
  std::condition_variable cv_;
  std::mutex mtx_;

  void do_advance(std::size_t id, std::size_t n)
  {
    std::lock_guard<std::mutex> lk(mtx_);
    phase_[id] += n;
    sentinel_ = *std::min_element(phase_.begin(), phase_.end());
    cv_.notify_all();
  }

  void do_await(std::size_t id)
  {
    std::unique_lock<std::mutex> lk(mtx_);
    phase_[id] += 1;
    sentinel_ = *std::min_element(phase_.begin(), phase_.end());
    while (sentinel_ != phase_[id]) {
      cv_.wait(lk);
    }
    cv_.notify_all();
  }

public:
  explicit phaser(std::size_t n)
    : phase_(n, 0u) {}

  class proxy {
    phaser* phaser_;
    std::size_t id_;

    friend class phaser;
    proxy(phaser* p, std::size_t id)
      : phaser_(p), id_(id) {}

  public:
    void advance(std::size_t n)
      { phaser_->do_advance(id_, n); }
    void await()
      { phaser_->do_await(id_); }
  };

  proxy get(std::size_t id)
  {
    assert(id < phase_.size());
    return {this, id};
  }
};

/// parallel task runner
template<typename F>
void task_runner(std::size_t nthread, F f)
{
  barrier gate(1 + nthread);
  std::vector<std::thread> thds;
  for (std::size_t n = 0; n < nthread; ++n) {
    thds.emplace_back([f,n,&gate]{
      gate.await();
      f(n);
    });
  }
  gate.await();  // start
  for (auto& t: thds) {
    t.join();
  }
}

/// stopwatch
template <typename Clock = std::chrono::system_clock, typename Duration = std::chrono::microseconds>
class stopwatch {
  typename Clock::time_point start_;

public:
  stopwatch()
    : start_(Clock::now()) {}

  stopwatch(const stopwatch&) = delete;
  stopwatch& operator=(const stopwatch&) = delete;

  Duration elapsed()
  {
    auto end = Clock::now();
    return std::chrono::duration_cast<Duration>(end - start_);
  }
};

} // namespace test

namespace cxx {

/// C++14 std::make_unique()
template <typename T, typename... Args>
inline
std::unique_ptr<T> make_unique(Args&&... args)
{
  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

/// C++17 std::void_t<Ts...>
template <typename... Ts>
struct make_void { using type = void; };
template <typename... Ts>
using void_t = typename make_void<Ts...>::type;

} // namespace cxx

// mock classes of mutex types
namespace mock {

struct mutex {
  bool locked = false;
  bool retval_on_trylock = true;

  mutex() = default;
  ~mutex() = default;

  mutex(const mutex&) = delete;
  mutex& operator=(const mutex&) = delete;

  void lock() { locked = true; }
  bool try_lock() { return (locked = retval_on_trylock); }
  void unlock() { locked = false; }
};

struct recursive_mutex {
  bool retval_on_trylock = true;

  recursive_mutex() = default;
  ~recursive_mutex() = default;

  recursive_mutex(const recursive_mutex&) = delete;
  recursive_mutex& operator=(const recursive_mutex&) = delete;

  void lock() {}
  bool try_lock() { return retval_on_trylock; }
  void unlock() {}
};

struct timed_mutex {
  bool retval_on_trylock = true;

  timed_mutex() = default;
  ~timed_mutex() = default;

  timed_mutex(const timed_mutex&) = delete;
  timed_mutex& operator=(const timed_mutex&) = delete;

  void lock() {}
  bool try_lock() { return retval_on_trylock; }
  void unlock() {}

  template<typename Rep, typename Period>
  bool try_lock_for(const std::chrono::duration<Rep, Period>&)
    { return retval_on_trylock; }

  template<typename Clock, typename Duration>
  bool try_lock_until(const std::chrono::time_point<Clock, Duration>&)
    { return retval_on_trylock; }
};

struct recursive_timed_mutex {
  bool retval_on_trylock = true;

  recursive_timed_mutex() = default;
  ~recursive_timed_mutex() = default;

  recursive_timed_mutex(const recursive_timed_mutex&) = delete;
  recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete;

  void lock() {}
  bool try_lock() { return retval_on_trylock; }
  void unlock() {}

  template<typename Rep, typename Period>
  bool try_lock_for(const std::chrono::duration<Rep, Period>&)
    { return retval_on_trylock; }

  template<typename Clock, typename Duration>
  bool try_lock_until(const std::chrono::time_point<Clock, Duration>&)
    { return retval_on_trylock; }
};

struct shared_mutex {
  bool retval_on_trylock = true;

  shared_mutex() = default;
  ~shared_mutex() = default;

  shared_mutex(const shared_mutex&) = delete;
  shared_mutex& operator=(const shared_mutex&) = delete;

  void lock() {}
  bool try_lock() { return retval_on_trylock; }
  void unlock() {}

  void lock_shared() {}
  bool try_lock_shared() { return retval_on_trylock; }
  void unlock_shared() {}
};

struct shared_timed_mutex {
  bool retval_on_trylock = true;

  shared_timed_mutex() = default;
  ~shared_timed_mutex() = default;

  shared_timed_mutex(const shared_timed_mutex&) = delete;
  shared_timed_mutex& operator=(const shared_timed_mutex&) = delete;

  void lock() {}
  bool try_lock() { return retval_on_trylock; }
  void unlock() {}

  template<typename Rep, typename Period>
  bool try_lock_for(const std::chrono::duration<Rep, Period>&)
    { return retval_on_trylock; }

  template<typename Clock, typename Duration>
  bool try_lock_until(const std::chrono::time_point<Clock, Duration>&)
    { return retval_on_trylock; }

  void lock_shared() {}
  bool try_lock_shared() { return retval_on_trylock; }
  void unlock_shared() {}

  template<typename Rep, typename Period>
  bool try_lock_shared_for(const std::chrono::duration<Rep, Period>&)
    { return retval_on_trylock; }

  template<typename Clock, typename Duration>
  bool try_lock_shared_until(const std::chrono::time_point<Clock, Duration>&)
    { return retval_on_trylock; }
};

} // namespace mock

} // namespace yamc

#define TEST_TICKS std::chrono::milliseconds(200)
#define WAIT_TICKS std::this_thread::sleep_for(TEST_TICKS)

// stepping test
#if 0
namespace {
std::mutex g_guard;
#define TRACE(msg_) \
  (std::unique_lock<std::mutex>(g_guard),\
   std::cout << std::this_thread::get_id() << ':' << (msg_) << std::endl)
}
#else
#define TRACE(msg_)
#endif

// declare stepping counter
#define SETUP_STEPTEST  std::atomic<int> step = {0}

// expect n-th step
#define EXPECT_STEP(n_) \
  do {                                                         \
    TRACE("STEP"#n_);                                          \
    int s = step.fetch_add(1, std::memory_order_relaxed) + 1;  \
    EXPECT_EQ(n_, s);                                          \
    WAIT_TICKS;                                                \
  } while (0)

// expect between step#r0 and step#r1
#define EXPECT_STEP_RANGE(r0_, r1_) \
  do {                                                         \
    TRACE("STEP"#r0_"-"#r1_);                                  \
    int s = step.fetch_add(1, std::memory_order_relaxed) + 1;  \
    EXPECT_TRUE(r0_ <= s && s <= r1_);                         \
    WAIT_TICKS;                                                \
  } while(0)

// advance step counter (w/o wait ticks)
#define ADVANCE_STEP(msg_, inc_) \
  do {                                                \
    TRACE(msg_);                                      \
    step.fetch_add(inc_, std::memory_order_relaxed);  \
  } while(0)

#endif


text:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>

#include <Weave/Support/CodeUtils.h>
#include <Weave/Support/logging/WeaveLogging.h>

#include "MockTimeSyncUtil.h"

#if WEAVE_CONFIG_TIME

using namespace nl::Weave::Profiles::Time;

void Abort()
{
    abort();
}

void TestError(WEAVE_ERROR err, const char *msg)
{
    if (err != WEAVE_NO_ERROR)
    {
        printf("%s: %s\n", msg, nl::ErrorStr(err));
        Abort();
    }
}

void TestAssert(bool assert, const char *msg)
{
    if (!assert)
    {
        printf("%s\n", msg);
        Abort();
    }
}

void TestCase1(void)
{
    WEAVE_ERROR err = WEAVE_NO_ERROR;

    WeaveLogProgress(TimeService, "------------------------------------------------------------");
    // test case 1, size == 4, PDT
    {
        uint8_t buffer[TimeZoneUtcOffset::BufferSizeForEncoding] = { 0 };
        TimeZoneUtcOffset utc_offset_enc;
        TimeZoneUtcOffset utc_offset_dec;
        uint32_t size = sizeof(buffer);
        utc_offset_enc.mSize = 4;
        utc_offset_enc.mUtcOffsetRecord[0].mBeginAt_usec = 1394355600000000LL; // 3/9/2014 2AM PST
        utc_offset_enc.mUtcOffsetRecord[0].mUtcOffset_sec = -3600 * 7;
        utc_offset_enc.mUtcOffsetRecord[1].mBeginAt_usec = 1414922400000000LL; // 11/2/2014 2AM PDT
        utc_offset_enc.mUtcOffsetRecord[1].mUtcOffset_sec = -3600 * 8;
        utc_offset_enc.mUtcOffsetRecord[2].mBeginAt_usec = 1425805200000000LL; // 3/8/2015 2AM PST
        utc_offset_enc.mUtcOffsetRecord[2].mUtcOffset_sec = -3600 * 7;
        utc_offset_enc.mUtcOffsetRecord[3].mBeginAt_usec = 1446372000000000LL; // 11/2/2015 2AM PDT
        utc_offset_enc.mUtcOffsetRecord[3].mUtcOffset_sec = -3600 * 8;

        WeaveLogProgress(TimeService, "TimeZone Unit Test Case 1: normal case");
        WeaveLogProgress(TimeService, "Encoding buffer size %u, Number of records: %u", size, utc_offset_enc.mSize);
        err = utc_offset_enc.Encode(buffer, &size);
        SuccessOrExit(err);
        WeaveLogProgress(TimeService, "Encoding buffer size used %u");
        err = utc_offset_dec.Decode(buffer, size);
        SuccessOrExit(err);
        WeaveLogProgress(TimeService, "Decoded number of records: %u", utc_offset_dec.mSize);

        for (int i = 0; i < utc_offset_dec.mSize; ++i)
        {
            WeaveLogProgress(TimeService, "[%d] timestamp usec: %ld, offset sec %d", i,
                utc_offset_dec.mUtcOffsetRecord[i].mBeginAt_usec, utc_offset_dec.mUtcOffsetRecord[i].mUtcOffset_sec);
        }

        {
            timesync_t utc_time = 1403303320000000LL; // Fri Jun 20 15:28:40 2014, PDT
            timesync_t local_time;
            time_t temp;

            temp = time_t(utc_time / 1000000);
            // we use 'local time' to convert the utc to local time
            WeaveLogProgress(TimeService, "Sample time: %s", asctime(localtime(&temp)));

            // this time we use GetCurrentLocalTime to convert utc to local time
            err = utc_offset_dec.GetCurrentLocalTime(&local_time, utc_time);
            SuccessOrExit(err);
            temp = time_t(local_time / 1000000);
            // since it's already converted, we use gmtime to process it (as there is no further tz/dst correction applied)
            WeaveLogProgress(TimeService, "Local time: %s", asctime(gmtime(&temp)));
        }

        WeaveLogProgress(TimeService, "TimeZone Unit Test Case 1: succeeded");
    }

    WeaveLogProgress(TimeService, "------------------------------------------------------------");

exit:
    TestError(err, "Test Case 1 Failed");
}

void TestCase2(void)
{
    WEAVE_ERROR err = WEAVE_NO_ERROR;

    WeaveLogProgress(TimeService, "------------------------------------------------------------");
    // test case 2, size == 4, very large offsets and changes
    // Samoa, timezone Pacific/Apia, in the middle of Pacific ocean, changed their timezone from UTC-11 to UTC+13 in 2012,
    // essentially advanced one full day
    {
        uint8_t buffer[TimeZoneUtcOffset::BufferSizeForEncoding] = { 0 };
        TimeZoneUtcOffset utc_offset_enc;
        TimeZoneUtcOffset utc_offset_dec;
        uint32_t size = sizeof(buffer);
        utc_offset_enc.mSize = 4;
        utc_offset_enc.mUtcOffsetRecord[0].mBeginAt_usec = 1394355600000000LL; //
        utc_offset_enc.mUtcOffsetRecord[0].mUtcOffset_sec = -3600 * 11;
        utc_offset_enc.mUtcOffsetRecord[1].mBeginAt_usec = 1414922400000000LL; //
        utc_offset_enc.mUtcOffsetRecord[1].mUtcOffset_sec = +3600 * 13;
        utc_offset_enc.mUtcOffsetRecord[2].mBeginAt_usec = 1425805200000000LL; //
        utc_offset_enc.mUtcOffsetRecord[2].mUtcOffset_sec = +3600 * 14;
        utc_offset_enc.mUtcOffsetRecord[3].mBeginAt_usec = 1446372000000000LL; //
        utc_offset_enc.mUtcOffsetRecord[3].mUtcOffset_sec = +3600 * 13;

        WeaveLogProgress(TimeService, "TimeZone Unit Test Case 2: huge offset changes");
        WeaveLogProgress(TimeService, "Encoding buffer size %u, Number of records: %u", size, utc_offset_enc.mSize);
        err = utc_offset_enc.Encode(buffer, &size);
        SuccessOrExit(err);
        WeaveLogProgress(TimeService, "Encoding buffer size used %u");
        err = utc_offset_dec.Decode(buffer, size);
        SuccessOrExit(err);
        WeaveLogProgress(TimeService, "Decoded number of records: %u", utc_offset_dec.mSize);

        for (int i = 0; i < utc_offset_dec.mSize; ++i)
        {
            WeaveLogProgress(TimeService, "[%d] timestamp usec: %ld, offset sec %d", i,
                utc_offset_dec.mUtcOffsetRecord[i].mBeginAt_usec, utc_offset_dec.mUtcOffsetRecord[i].mUtcOffset_sec);
        }

        WeaveLogProgress(TimeService, "TimeZone Unit Test Case 2: succeeded");
    }

    WeaveLogProgress(TimeService, "------------------------------------------------------------");

exit:
    TestError(err, "Test Case 2 Failed");
}

void TestCase3(void)
{
    WEAVE_ERROR err = WEAVE_NO_ERROR;

    WeaveLogProgress(TimeService, "------------------------------------------------------------");
    // test case 2, size == 4, very large offsets and changes
    // Samoa, timezone Pacific/Apia, in the middle of Pacific ocean, changed their timezone from UTC-11 to UTC+13 in 2012,
    // essentially advanced one full day
    {
        uint8_t buffer[TimeZoneUtcOffset::BufferSizeForEncoding] = { 0 };
        TimeZoneUtcOffset utc_offset_enc;
        TimeZoneUtcOffset utc_offset_dec;
        uint32_t size = sizeof(buffer);
        utc_offset_enc.mSize = 1;
        utc_offset_enc.mUtcOffsetRecord[0].mBeginAt_usec = 0; //
        utc_offset_enc.mUtcOffsetRecord[0].mUtcOffset_sec = +3600 * 7;

        WeaveLogProgress(TimeService, "TimeZone Unit Test Case 3: no DST case, single UTC offset");
        WeaveLogProgress(TimeService, "Encoding buffer size %u, Number of records: %u", size, utc_offset_enc.mSize);
        err = utc_offset_enc.Encode(buffer, &size);
        SuccessOrExit(err);
        WeaveLogProgress(TimeService, "Encoding buffer size used %u");
        err = utc_offset_dec.Decode(buffer, size);
        SuccessOrExit(err);
        WeaveLogProgress(TimeService, "Decoded number of records: %u", utc_offset_dec.mSize);

        for (int i = 0; i < utc_offset_dec.mSize; ++i)
        {
            WeaveLogProgress(TimeService, "[%d] timestamp usec: %ld, offset sec %d", i,
                utc_offset_dec.mUtcOffsetRecord[i].mBeginAt_usec, utc_offset_dec.mUtcOffsetRecord[i].mUtcOffset_sec);
        }

        {
            timesync_t utc_time = 1403303320000000LL; // Fri Jun 20 15:28:40 2014, PDT
            timesync_t local_time;
            time_t temp;

            temp = time_t(utc_time / 1000000);
            // we use 'asctime/gmtime' to convert the time to string, with UTC offset 0
            WeaveLogProgress(TimeService, "Sample time: %s", asctime(gmtime(&temp)));

            // this time we use GetCurrentLocalTime to convert utc to local time
            err = utc_offset_dec.GetCurrentLocalTime(&local_time, utc_time);
            SuccessOrExit(err);
            temp = time_t(local_time / 1000000);
            // fixed offset shall be applied here
            WeaveLogProgress(TimeService, "Local time: %s", asctime(gmtime(&temp)));
        }

        WeaveLogProgress(TimeService, "TimeZone Unit Test Case 3: succeeded");
    }

    WeaveLogProgress(TimeService, "------------------------------------------------------------");

exit:
    TestError(err, "Test Case 3 Failed");
}

int main()
{
    TestCase1();
    TestCase2();
    TestCase3();

    printf("All tests passed\n");
    return 0;
}

#else // WEAVE_CONFIG_TIME

int main()
{
    printf("Weave Time is NOT ENABLED. Test Skipped\n");
    return -1;
}

#endif // WEAVE_CONFIG_TIME


text:
import attr
import sqlite3
import logging

@attr.s
class ContactsProcessor:
    """
    The processor of contacts data.

    :param sakia.data.repositories.ContactsRepo _contacts_repo: the repository of the contacts
    """
    _contacts_repo = attr.ib()
    _logger = attr.ib(default=attr.Factory(lambda: logging.getLogger('sakia')))

    @classmethod
    def instanciate(cls, app):
        """
        Instanciate a blockchain processor
        :param sakia.app.Application app: the app
        """
        return cls(app.db.contacts_repo)

    def contacts(self):
        return self._contacts_repo.get_all()

    def contact(self, contact_id):
        return self._contacts_repo.get_one(contact_id=contact_id)

    def commit(self, contact):
        try:
            self._contacts_repo.insert(contact)
        except sqlite3.IntegrityError:
            self._contacts_repo.update(contact)

    def delete(self, contact):
        self._contacts_repo.drop(contact)

    def get_one(self, **search):
        return self._contacts_repo.get_one(**search)


text:
'''
Created on 24.02.2012

@author: rack

TODO: - limit .delquote to admin only?
'''
import logging

from interaction.irc.module import InteractiveModule, InteractiveModuleCommand, InteractiveModuleResponse
from components.quote import NoQuoteAvailable, NoAffectedRows

#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
MAX_LENGTH_QUOTE = 375
#-------------------------------------------------------------------------------
# Module 'Logic'
#-------------------------------------------------------------------------------
class Quote(InteractiveModule):
    """
    This module provides quote functions
    """
    def initialize(self):
        self.me = self.client.me
        self.logger = logging.getLogger('interaction.irc.quote')
        self.component = self.client.bot.get_subsystem('quote-component')

    def module_identifier(self):
        """
        Declare the module identifier.
        """
        return 'QuoteMod'

    def init_commands(self):
        """
        Declare all commands of the module.
        """
        return [
                InteractiveModuleCommand(
                                         keyword='addquote',
                                         callback=self.add_new_quote,
                                         pattern=r'^(.+)$',
                                         syntaxhint='<text>'
                                         ),
                InteractiveModuleCommand(
                                         keyword='delquote',
                                         callback=self.del_quote,
                                         pattern=r'^(\d+)$',
                                         syntaxhint='<id>'
                                         ),
                InteractiveModuleCommand(
                                         keyword='quote',
                                         callback=self.display_quote,
                                         pattern=r'^(.+)$|^$',
                                         syntaxhint='<id|text>'
                                         ),
                InteractiveModuleCommand(
                                         keyword='searchquote',
                                         callback=self.search_quotes,
                                         pattern=r'^(.+)$',
                                         syntaxhint='<text>'
                                         )
                ]

    def display_quote(self, request):
        """
        Select a quote from database and post it to a channel.

        Usage: .quote [<text>|<id>]

        @param request: A runtime request of an InteractiveModule command.

        @return InteractiveModuleResponse
        """
        response = InteractiveModuleResponse()

        try:
            text = request.parameter[0]
            if (len(text) > 0):
                try:
                    id = int(text)
                    quote = self.component.get_quote_by_id(id)
                except ValueError:
                    quote = self.component.get_random_quote_by_string(request.parameter[0])
            else:
                quote = self.component.get_random_quote()

            response.add_line("{0} ({1})".format(quote.text,quote.id))
        except NoQuoteAvailable:
            response.add_line("No quotes in database.")

        return response

    def add_new_quote(self, request):
        """
        Add a new quote to database.
        Max length of the quote is 375 letters.

        Usage: .addquote <text>

        @param request: A runtime request of an InteractiveModule command.

        @return InteractiveModuleResponse
        """
        response = InteractiveModuleResponse()

        text = request.parameter[0]
        if len(text) <= MAX_LENGTH_QUOTE:
            self.component.insert_quote(text,request.source.nickname)
            response.add_line("The process was successful.")
        else:
            response.add_line("Max length of a quote is {0} letters. Yours is {1}."
                              .format(MAX_LENGTH_QUOTE,str(len(text))))

        return response

    def del_quote(self,request):
        """
        Delete a quote with the given id from database.

        Usage: .delquote <id>

        @param request: A runtime request of an InteractiveModule command.

        @return InteractiveModuleResponse
        """
        response = InteractiveModuleResponse()
        try:
            id = int(request.parameter[0])
            self.component.delete_quote_by_id(id)
            response.add_line("Delete was successful.")
        except ValueError:
            response.add_line("If you like to delete a quote, you'll have to declare an ID instead of a string.")
        except NoAffectedRows:
            response.add_line("Delete didn't work. Maybe, there isn't a quote with the given ID.")

        return response

    def search_quotes(self,request):
        """
        Search in database for quote with the given string.
        It will display all IDs of the founded quotes

        Usage: .searchquote <text>

        @param request: A runtime request of an InteractiveModule command.

        @return InteractiveModuleResponse
        """
        response = InteractiveModuleResponse()

        ids = self.component.get_ids_by_string(request.parameter[0])
        if len(ids) > 0:
            response.add_line("Found the string in following quotes: {0}".format(" ".join(str(ids))))
        else:
            response.add_line("There isn't a quote with the given id.")

        return response


text:
package org.smartdata.server.engine.rule;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.smartdata.conf.SmartConf;
import org.smartdata.metastore.MetaStore;
import org.smartdata.metastore.TestDaoUtil;
import org.smartdata.model.FileInfo;
import org.smartdata.model.RuleInfo;
import org.smartdata.model.RuleState;
import org.smartdata.server.engine.RuleManager;
import org.smartdata.server.engine.ServerContext;

import java.io.IOException;
import java.util.List;
import java.util.Random;

/**
 * Testing RuleManager service.
 */
public class TestRuleManager extends TestDaoUtil {
  private RuleManager ruleManager;
  private MetaStore metaStore;
  private SmartConf smartConf;

  @Before
  public void init() throws Exception {
    initDao();
    smartConf = new SmartConf();
    metaStore = new MetaStore(druidPool);
    ServerContext serverContext = new ServerContext(smartConf, metaStore);
    ruleManager = new RuleManager(serverContext, null, null);
    ruleManager.init();
    ruleManager.start();
  }

  @After
  public void close() throws Exception {
    ruleManager.stop();
    ruleManager = null;
    metaStore = null;
    closeDao();
  }

  @Test
  public void testSubmitNewActiveRule() throws Exception {
    String rule = "file: every 1s \n | accessCount(5s) > 3 | cache";
    long id = ruleManager.submitRule(rule, RuleState.ACTIVE);
    RuleInfo ruleInfo = ruleManager.getRuleInfo(id);
    Assert.assertTrue(ruleInfo.getRuleText().equals(rule));
    RuleInfo info = ruleInfo;
    for (int i = 0; i < 5; i++) {
      Thread.sleep(1000);
      info = ruleManager.getRuleInfo(id);
      System.out.println(info);
    }

    Assert.assertTrue(info.getNumChecked()
        - ruleInfo.getNumChecked() > 3);
  }

  @Test
  public void testSubmitDeletedRule() throws Exception {
    String rule = "file: every 1s \n | length > 300 | cache";
    try {
      long id = ruleManager.submitRule(rule, RuleState.DELETED);
    } catch (IOException e) {
      Assert.assertTrue(e.getMessage().contains("Invalid initState"));
    }
  }

  @Test
  public void testSubmitNewDisabledRule() throws Exception {
    String rule = "file: every 1s \n | length > 300 | cache";
    long id = ruleManager.submitRule(rule, RuleState.DISABLED);
    RuleInfo ruleInfo = ruleManager.getRuleInfo(id);
    Assert.assertTrue(ruleInfo.getRuleText().equals(rule));
    RuleInfo info = ruleInfo;
    for (int i = 0; i < 5; i++) {
      Thread.sleep(1000);
      info = ruleManager.getRuleInfo(id);
      System.out.println(info);
    }

    Assert.assertTrue(info.getNumChecked()
        - ruleInfo.getNumChecked() == 0);
  }

  @Test
  public void testSubmitAutoEndsRule() throws Exception {
    String rule = "file: every 1s from now to now + 2s \n | "
        + "length > 300 | cache";

    long id = ruleManager.submitRule(rule, RuleState.ACTIVE);
    RuleInfo ruleInfo = ruleManager.getRuleInfo(id);
    Assert.assertTrue(ruleInfo.getRuleText().equals(rule));
    RuleInfo info = ruleInfo;
    for (int i = 0; i < 5; i++) {
      Thread.sleep(1000);
      info = ruleManager.getRuleInfo(id);
      System.out.println(info);
    }

    Assert.assertTrue(info.getState() == RuleState.FINISHED);
    Assert.assertTrue(info.getNumChecked()
        - ruleInfo.getNumChecked() <= 3);
  }

  @Test
  public void testStopRule() throws Exception {
    String rule = "file: every 1s from now to now + 100s \n | "
        + "length > 300 | cache";

    long id = ruleManager.submitRule(rule, RuleState.ACTIVE);
    RuleInfo ruleInfo = ruleManager.getRuleInfo(id);
    Assert.assertTrue(ruleInfo.getRuleText().equals(rule));
    RuleInfo info = ruleInfo;
    for (int i = 0; i < 2; i++) {
      Thread.sleep(1000);
      info = ruleManager.getRuleInfo(id);
      System.out.println(info);
    }

    ruleManager.deleteRule(ruleInfo.getId(), true);
    Thread.sleep(3000);

    RuleInfo endInfo = ruleManager.getRuleInfo(info.getId());
    System.out.println(endInfo);

    Assert.assertTrue(endInfo.getState() == RuleState.DELETED);
    Assert.assertTrue(endInfo.getNumChecked()
        - info.getNumChecked() <= 1);
  }

  @Test
  public void testResumeRule() throws Exception {
    String rule = "file: every 1s from now to now + 100s \n | "
        + "length > 300 | cache";

    long id = ruleManager.submitRule(rule, RuleState.ACTIVE);
    RuleInfo ruleInfo = ruleManager.getRuleInfo(id);
    Assert.assertTrue(ruleInfo.getRuleText().equals(rule));
    RuleInfo info = ruleInfo;
    for (int i = 0; i < 2; i++) {
      Thread.sleep(1000);
      info = ruleManager.getRuleInfo(id);
      System.out.println(info);
    }
    Assert.assertTrue(info.getNumChecked()
        > ruleInfo.getNumChecked());

    ruleManager.disableRule(ruleInfo.getId(), true);
    Thread.sleep(1000);
    RuleInfo info2 = ruleManager.getRuleInfo(id);
    for (int i = 0; i < 3; i++) {
      Thread.sleep(1000);
      info = ruleManager.getRuleInfo(id);
      System.out.println(info);
    }
    Assert.assertTrue(info.getNumChecked()
        == info2.getNumChecked());

    RuleInfo info3 = info;
    ruleManager.activateRule(ruleInfo.getId());
    for (int i = 0; i < 3; i++) {
      Thread.sleep(1000);
      info = ruleManager.getRuleInfo(id);
      System.out.println(info);
    }
    Assert.assertTrue(info.getNumChecked()
        > info3.getNumChecked());
  }

  @Test
  public void testSubmitNewMultiRules() throws Exception {
    String rule = "file: every 1s \n | length > 300 | cache";

    // id increasing
    int nRules =  3;
    long[] ids = new long[nRules];
    for (int i = 0; i < nRules; i++) {
      ids[i] = ruleManager.submitRule(rule, RuleState.DISABLED);
      System.out.println(ruleManager.getRuleInfo(ids[i]));
      if (i > 0) {
        Assert.assertTrue(ids[i] - ids[i - 1] == 1);
      }
    }

    for (int i = 0; i < nRules; i++) {
      ruleManager.deleteRule(ids[i], true);
      RuleInfo info = ruleManager.getRuleInfo(ids[i]);
      Assert.assertTrue(info.getState() == RuleState.DELETED);
    }

    long[] ids2 = new long[nRules];
    for (int i = 0; i < nRules; i++) {
      ids2[i] = ruleManager.submitRule(rule, RuleState.DISABLED);
      System.out.println(ruleManager.getRuleInfo(ids2[i]));
      if (i > 0) {
        Assert.assertTrue(ids2[i] - ids2[i - 1] == 1);
      }
      Assert.assertTrue(ids2[i] > ids[nRules - 1]);
    }

    System.out.println("\nFinal state:");
    List<RuleInfo> allRules = ruleManager.listRulesInfo();
    // Deleted rules are not included in the list
    Assert.assertTrue(allRules.size() == nRules);
    for (RuleInfo info : allRules) {
      System.out.println(info);
    }
  }

  @Test
  public void testMultiThreadUpdate() throws Exception {
    String rule = "file: every 1s \n | length > 10 | cache";

    long now = System.currentTimeMillis();

    long rid = ruleManager.submitRule(rule, RuleState.DISABLED);
    ruleManager.updateRuleInfo(rid, null, now, 1, 1);

    long start = System.currentTimeMillis();

    Thread[] threads = new Thread[] {
        new Thread(new RuleInfoUpdater(rid, 3)),
//        new Thread(new RuleInfoUpdater(rid, 7)),
//        new Thread(new RuleInfoUpdater(rid, 11)),
        new Thread(new RuleInfoUpdater(rid, 17))};

    for (Thread t : threads) {
      t.start();
    }

    for (Thread t : threads) {
      t.join();
    }

    long end = System.currentTimeMillis();
    System.out.println("Time used = " + (end - start) + " ms");

    RuleInfo res = ruleManager.getRuleInfo(rid);
    System.out.println(res);
  }

  private class RuleInfoUpdater implements Runnable {
    private long ruleid;
    private int index;

    public RuleInfoUpdater(long ruleid, int index) {
      this.ruleid = ruleid;
      this.index = index;
    }

    @Override
    public void run() {
      long lastCheckTime;
      long checkedCount;
      int cmdletsGen;
      try {
        for (int i = 0; i < 200; i++) {
          RuleInfo info = ruleManager.getRuleInfo(ruleid);
          lastCheckTime = System.currentTimeMillis();
          checkedCount = info.getNumChecked();
          cmdletsGen = (int) info.getNumCmdsGen();
          //System.out.println("" + index + ": " + lastCheckTime + " "
          // + checkedCount + " " + cmdletsGen);
          Assert.assertTrue(checkedCount == cmdletsGen);
          ruleManager.updateRuleInfo(ruleid, null,
              lastCheckTime, index, index);
        }
      } catch (Exception e) {
        Assert.fail("Can not have exception here.");
      }
    }
  }

  @Test
  public void testMultiThreadChangeState() throws Exception {
    String rule = "file: every 1s \n | length > 10 | cache";

    long now = System.currentTimeMillis();

    long length = 100;
    long fid = 10000;
    FileInfo[] files = { new FileInfo("/tmp/testfile", fid,  length, false, (short) 3,
        1024, now, now, (short) 1, null, null, (byte) 3) };

    metaStore.insertFiles(files);
    long rid = ruleManager.submitRule(rule, RuleState.ACTIVE);

    long start = System.currentTimeMillis();

    int nThreads = 2;
    Thread[] threads = new Thread[nThreads];
    for (int i = 0; i < nThreads; i++) {
      threads[i] = new Thread(new StateChangeWorker(rid));
    }

    for (Thread t : threads) {
      t.start();
    }

    for (Thread t : threads) {
      t.join();
    }

    long end = System.currentTimeMillis();
    System.out.println("Time used = " + (end - start) + " ms");
    Thread.sleep(1000); // This is needed due to async threads

    RuleInfo res = ruleManager.getRuleInfo(rid);
    System.out.println(res);
    Thread.sleep(5000);
    RuleInfo after = ruleManager.getRuleInfo(rid);
    System.out.println(after);
    if (res.getState() == RuleState.ACTIVE) {
      Assert.assertTrue(after.getNumCmdsGen() - res.getNumCmdsGen() <= 6);
    } else {
      Assert.assertTrue(after.getNumCmdsGen() == res.getNumCmdsGen());
    }
  }

  private class StateChangeWorker implements Runnable {
    private long ruleId;

    public StateChangeWorker(long ruleId) {
      this.ruleId = ruleId;
    }

    @Override
    public void run() {
      Random r = new Random();
      try {
        for (int i = 0; i < 200; i++) {
          int rand = r.nextInt() % 2;
          //System.out.println(rand == 0 ? "Active" : "Disable");
          switch (rand) {
            case 0:
              ruleManager.activateRule(ruleId);
              break;
            case 1:
              ruleManager.disableRule(ruleId, true);
              break;
          }
        }
      } catch (Exception e) {
        Assert.fail("Should not happen!");
      }
    }
  }
}


text:
<?php

//base head content on every page

echo '
	<meta name="author" content="John Ink" />
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta charset="UTF-8" />
	<link rel="stylesheet" type="style/css" href="style/normalize.css" />
	<link rel="stylesheet" type="style/css" href="style/base.css" />

		<!--temp nofollow -->
		<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
		<!--temp nofollow -->

'
?>


text:
FROM biocontainers/biocontainers:vdebian-buster-backports_cv1
MAINTAINER biocontainers <biodocker@gmail.com>
LABEL    software="typed-ast" \
    base_image="biocontainers/biocontainers:vdebian-buster-backports_cv1" \
    container="typed-ast" \
    about.summary="AST with PEP 484 type comments support" \
    about.home="http://www.mypy-lang.org/" \
    software.version="1.3.1-1-deb-py3" \
    upstream.version="1.3.1" \
    version="1" \
    about.copyright=" 2016 David Fisher <ddfisher@dropbox.com>" \
    about.license="Apache-2.0" \
    about.license_file="/usr/share/doc/typed-ast/copyright" \
    about.tags=""

USER root
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && (apt-get install -t buster-backports -y python3-typed-ast || apt-get install -y python3-typed-ast) && apt-get clean && apt-get purge && rm -rf /var/lib/apt/lists/* /tmp/*
USER biodocker


text:
/*
 * DungeonConfiguration.cpp
 *
 *  Created on: May 27, 2013
 *      Author: CresCoJeff
 */

#include "DungeonConfiguration.h"
/*
DungeonConfiguration::DungeonConfiguration() {
	// TODO Auto-generated constructor stub

}

DungeonConfiguration::~DungeonConfiguration() {
	// TODO Auto-generated destructor stub
}

*/


text:
@extends('theme::layout.master')

@section('title') Dodawanie tekstu @stop

@section('content')

            Dodawanie nowej aktualności

 Home

Dodaj tekst

                    {{ Form::open(array('route' => 'admin.post.store', 'files'=> true)) }}
                    {{ Form::token() }}

                        Wróć do listy

informacje na temat dodawania nowego tekstu

has('title')) has-error @endif">
                            {{ Form::label('title', 'Tytuł') }}
                            {{ Form::text('title', Input::old('title'), array('class' => 'form-control', 'id' => 'title', 'placeholder' => 'Tytuł') ) }}
                            @if ($errors->has('title'))
{{ $errors->first('title') }}
 @endif

                            {{ Form::label('photo', 'Zdjęcie') }}
                            <input type="file" name="photo" />

has('category_id')) has-error @endif">
                            {{ Form::label('category_id', 'Kategoria') }}
                            {{ Form::select('category_id', $select, Input::old('category_id'), array('class' => 'form-control', 'id' => 'select2')) }}
                            @if ($errors->has('category_id'))
{{ $errors->first('category_id') }}
 @endif

has('content')) has-error @endif">
                            {{ Form::label('content', 'Tresc') }}
                            {{ Form::textarea('content', Input::old('content'), array('class' => 'form-control', 'id' => 'wysihtml5', 'placeholder' => 'Tresc') ) }}
                            @if ($errors->has('content'))
{{ $errors->first('content') }}
 @endif

has('tags')) has-error @endif">
                            {{ Form::label('tags', 'Tagi') }}
                            {{ Form::textarea('tags', Input::old('tags'), array('class' => 'form-control', 'placeholder' => 'Tagi') ) }}
                            @if ($errors->has('tags'))
{{ $errors->first('tags') }}
 @endif

has('badges')) has-error @endif">
                            {{ Form::label('badges', 'Parametry obrazki') }}
                            {{ Form::textarea('badges', Input::old('badges'), array('class' => 'form-control', 'placeholder' => 'Parametry obrazki') ) }}
                            @if ($errors->has('badges'))
{{ $errors->first('badges') }}
 @endif

has('parameters')) has-error @endif">
                            {{ Form::label('parameters', 'Parametry tabela') }}
                            {{ Form::textarea('parameters', Input::old('parameters'), array('class' => 'form-control', 'id' => 'wysihtml6', 'placeholder' => 'Parametry tabela') ) }}
                            @if ($errors->has('parameters'))
{{ $errors->first('parameters') }}
 @endif

                        {{ Form::button('Dodaj', array('class' => 'btn btn-success btn-flat', 'type' => 'submit') ) }}

                    {{ Form::close() }}

@stop

@section('extrascripts')

@stop


text:
module.exports = {
  root: true,
  parser: 'babel-eslint',
  parserOptions: {
    sourceType: 'module'
  },
  // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
  extends: 'standard',
  // required to lint *.vue files
  plugins: [
    'html'
  ],
  // add your custom rules here
  'rules': {
    'arrow-parens': 0,
    'generator-star-spacing': 0,
    'no-debugger': 0
  }
}


text:
this isn't anything serious -- just a bunch of little examples and notes to
myself as i learn d3. chris was interested in this, so now it's somewhere
other than just my laptop. `:D`

it's hard to resist the awesomeness of good d3 galleries like
[this](http://d3js.org/), and also
[this](https://github.com/mbostock/d3/wiki/Gallery).

## links

* [thinking with joins](http://bost.ocks.org/mike/join/) explains the data
  join, which is the core concept in d3. as expected, there are a ton of
  interesting links from here, all of which are interesting.

* [how selections work](http://bost.ocks.org/mike/selection/) explains how
  selections are *implemented*; this turns out to be surprisingly useful for
  understanding how to think about them.

* andrew montalenti gave a nice [pydata talk](http://vimeo.com/79580138) about
  "rapid data viz", and there's a corresponding
  [set of slides](http://pixelmonkey.org/pub/dataviz-elements/notes/). it's a
  little more focused on easy ways to get to vaious js/viz bits from python
  (which makes sense, given the venue), but there's a lot of interesting stuff
  there.

* cynthia brewer did a bunch of work on better
  [default color combinations](http://colorbrewer2.org/), specifically focused
  around maps. of course, mike bostock has a
  [post pulling that info into d3](http://bl.ocks.org/mbostock/5577023). i
  definitely think the colorbrewer stuff is prettier, and my partly-colorblind
  officemate heartily agrees.

* [d3 for HTML](http://www.macwright.org/2013/07/07/d3-for-html.html) is this
  great post by tom macwright where he points out that the pattern used for
  mapping data -> svg elements in d3 works just as well when you want to do
  data -> divs/list items in pure html. then he builds out an awesome address
  book app on d3.

## podcasts/videos

there were two really nice interviews on data stories:

* [jeff heer](http://datastori.es/episode-8-interview-jeff-heer/) gave a
  really nice perspective on the history of the projects leading up to d3. in
  particular, he really highlights why not being a system-unto-itself is a big
  win.

*
  [mike bostock and shan carter](http://datastori.es/data-stories-22-nyt-graphics-and-d3-with-mike-bostock-and-shan-carter/)
  showed up and talked d3 and what they do at the NYT. super interesting.

* [mike bostock at eyeo](http://vimeo.com/69448223) is also fantastic -- but
  maybe i'm biased because i've always loved examples, too. (this makes my
  particular choice of advisor quite curious.)

## other frameworks

* [vega](https://github.com/trifacta/vega) is a higher-level description
  language built with d3 as basically
  [its primary implementation](https://github.com/trifacta/vega/wiki/Vega-and-D3).

* [nvd3](http://nvd3.org/) builds a common set of components on top of d3;
  looks nice, but i haven't used it at all.

* [dygraphs](http://dygraphs.com/) is a completely independent library -- like
  nvd3 with no d3 underneath. in particular, though, it seems to be focused on
  "really good defaults" -- it's hard to overstate what a good idea that is.

* [mpld3](https://github.com/jakevdp/mpld3) is trying to render matplotlib
  graphics on top of d3; i've got a slew of mpl graphics i'm stuck with
  elsewhere, i'm planning on use this as a shim from the 1990s into modern
  times.

  for me at least, this one's a transition tool, not an end in itself. i think
  i differ from the crowd on that part -- some people *like* mpl. (i think
  that's called stockholm syndrome?)

## random stuff/notes


text:
package ch.sourcepond.maven.release.pom;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
import org.apache.maven.plugin.logging.Log;

import com.ximpleware.ModifyException;
import com.ximpleware.NavException;
import com.ximpleware.TranscodeException;

import ch.sourcepond.maven.release.scm.SCMException;
import ch.sourcepond.maven.release.scm.SCMRepository;

/**
 * Default implementation of the {@link ChangeSet} interface.
 *
 */
class DefaultChangeSet implements ChangeSet {
	static final String EXCEPTION_MESSAGE = "Unexpected exception while setting the release versions in the pom";
	static final String REVERT_ERROR_MESSAGE = "Could not revert modelsToBeReleased - working directory is no longer clean. Please revert modelsToBeReleased manually";
	static final String IO_EXCEPTION_FORMAT = "Updated project %s could not be written!";
	private final Log log;
	private final SCMRepository repository;
	private final Map<File, Model> modelsToBeReleased = new LinkedHashMap<>();
	private final Map<File, Model> modelsToBeIncremented = new LinkedHashMap<>();
	private final Set<Model> needOwnVersion = new HashSet<>();
	private final MavenXpp3Writer writer;
	private ChangeSetCloseException failure;

	DefaultChangeSet(final Log pLog, final SCMRepository pRepository, final MavenXpp3Writer pWriter) {
		log = pLog;
		repository = pRepository;
		writer = pWriter;
	}

	Map<File, Model> getModelsToBeReleased() {
		return modelsToBeReleased;
	}

	private void registerModel(final Map<File, Model> models, final File file, final Model model,
			final boolean needsOwnVersion) throws POMUpdateException {
		try {
			models.put(file.getCanonicalFile(), model);

			if (needsOwnVersion) {
				needOwnVersion.add(model);
			}
		} catch (final IOException e) {
			throw new POMUpdateException(e, "Canonical path could be determined for file %s", file);
		}
	}

	void markRelease(final File file, final Model model, final boolean needsOwnVersion) throws POMUpdateException {
		registerModel(modelsToBeReleased, file, model, needsOwnVersion);
	}

	void markSnapshotVersionIncrement(final File file, final Model model, final boolean needsOwnVersion)
			throws POMUpdateException {
		registerModel(modelsToBeIncremented, file, model, needsOwnVersion);
	}

	DefaultChangeSet writeChanges() throws POMUpdateException {
		for (final Map.Entry<File, Model> entry : modelsToBeReleased.entrySet()) {
			try (final Writer fileWriter = new FileWriter(entry.getKey())) {
				writer.write(fileWriter, entry.getValue());
			} catch (final IOException e) {
				setFailure(EXCEPTION_MESSAGE, e);
				close();
			}
		}
		return this;
	}

	private String getOwnVersionOrNull(final Model model) {
		if (needOwnVersion.contains(model)) {
			return model.getVersion();
		}
		return null;
	}

	@Override
	public void close() throws ChangeSetCloseException {
		try {
			repository.revertChanges(modelsToBeReleased.keySet());
		} catch (final SCMException e) {
			if (failure == null) {
				// throw if you can't revert as that is the root problem
				throw new ChangeSetCloseException(e, REVERT_ERROR_MESSAGE);
			} else {
				// warn if you can't revert but keep throwing the original
				// exception so the root cause isn't lost
				log.warn(REVERT_ERROR_MESSAGE, e);
			}
		}

		if (failure != null) {
			log.info("Reverted changes because there was an error.");
			throw failure;
		}

		if (!modelsToBeIncremented.isEmpty()) {
			for (final Map.Entry<File, Model> entry : modelsToBeIncremented.entrySet()) {
				try (final Writer fileWriter = new VersionTransferWriter(entry.getKey(),
						getOwnVersionOrNull(entry.getValue()))) {
					writer.write(fileWriter, entry.getValue());
				} catch (final IOException | ModifyException | NavException | TranscodeException e) {
					try {
						repository.revertChanges(modelsToBeIncremented.keySet());
					} catch (final SCMException revertException) {
						// warn if you can't revert but keep throwing the
						// original
						// exception so the root cause isn't lost
						log.warn(REVERT_ERROR_MESSAGE, e);
					}
					throw new ChangeSetCloseException(e, IO_EXCEPTION_FORMAT, entry.getValue());
				}
			}

			try {
				repository.pushChanges(modelsToBeIncremented.keySet());
			} catch (final SCMException e) {
				throw new ChangeSetCloseException(e, IO_EXCEPTION_FORMAT, modelsToBeIncremented.keySet());
			}
		}
	}

	@Override
	public void setFailure(final String message, final Exception failure) {
		this.failure = new ChangeSetCloseException(failure, message);
	}
}


text:
@interface UIScrollView(_UIWebViewScrollView_Swizzling)
@property BOOL enableChangeFrame;
//-(void) hookSetFrame;
-(void) setFrameSwizzling:(CGRect) frame;
@end


text:
list servers
============

syntax

	list servers [columns] [where ...] [limit ...]

List servers in a SiriDB Cluster. This command can be useful to view status
information about a server.

columns
-------
Valid columns are:

- active_handles: Returns the active handles which can be used as an indicator on how busy a server is.
- active_tasks: Returns the active tasks for the current database.
- address: Server address.
- buffer_path: Path where this server keeps the buffer file.
- buffer_size: Size the server uses for one series in the buffer.
- dbpath: Path where the server stores the database.
- fifo_files: Number of fifo files which are used to update the replica server. This value is 0 if the server has no replica. A value greater than 1 could be an indication that replication is not working.
- idle_percentage: Returns percentage of idle time since the database was loaded.
- idle_time: Returns the idle time in seconds since the database was loaded.
- ip_support: IP Support setting on the server. (ALL/ IPV4ONLY/ IPV6ONLY)
- libuv: Version of libuv library.
- log_level: Current loglevel for the server.
- max\_open\_files: Returns the maximum open files value used for sharding on *this* server. (If this value is lower than expected, please check the log files for SiriDB as startup time)
- mem_usage: Shows memory usage for the server in MB's.
- name: Server name.
- online: True when the server is online.
- open_files: Number of open files for *this* database on the server.
- pool: Returns the pool ID for the server.
- port: Server port.
- received_points: Returns the number of received points by the server. On each restart of the SiriDB Server the counter will reset to 0. This value is only incremented when the server is receiving points from a client.
- reindex_progress: Returns the re-index status. Only available when the database is re-indexing series over pools.
- selected_points: Returns the selected points on the server. On each restart of the SiriDB Server the counter will reset to 0. This value includes all points which are read from the local shards and the points received from other servers to respond to a select query. The value is only incremented when the server received the select query from a client.
- startup_time: Time it takes to start the server.
- status: Current server status.
- sync_progress: Return synchronization status while creating a new replica server.
- uptime: Uptime in seconds.
- uuid: Server UUID (unique ID)
- version: SiriDB version

When no columns are provided the default is used. (name, pool, version, online, status)

examples
--------

	# list all servers in a SiriDB cluster.
	list servers

	# list all offline servers
	list servers where online == false

	# view memory usage and open files on all servers.
	list servers name, mem_usage, open_files

	# sample output (list servers)
	{
		"columns": ["name", "pool", "version", "online", "status"],
		"servers": [
			["siri1:9010", 0, "2.0.10", true, "running"],
			["siri2:9010", 1, "2.0.10", true, "running"]
		]
	}


text:
module Cucumber
  module Formatter
    # This formatter keeps track of all failing features and print out their location.
    # Example:
    #
    #   features/foo.feature:34 features/bar.feature:11:76:81
    #
    # This formatter is used by AutoTest - it will use the output to decide what
    # to run the next time, simply passing the output string on the command line.
    #
    class Rerun < Ast::Visitor
      def initialize(step_mother, io, options)
        super(step_mother)
        @io = io
        @file_names = []
        @file_colon_lines = Hash.new{|h,k| h[k] = []}
      end

      def visit_features(features)
        super
        files = @file_names.uniq.map do |file|
          lines = @file_colon_lines[file]
          "#{file}:#{lines.join(':')}"
        end
        @io.puts files.join(' ')
      end

      def visit_feature_element(feature_element)
        @rerun = false
        super
        if @rerun
          file, line = *feature_element.file_colon_line.split(':')
          @file_colon_lines[file] << line
          @file_names << file
        end
      end

      def visit_step_name(keyword, step_match, status, source_indent, background)
        @rerun = true if [:failed].index(status)
      end
    end
  end
end


text:
<?php

namespace frontend\controllers;

use Yii;
use app\models\RecetaDetalle;
use frontend\models\RecetaDetalleSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use \yii\web\Response;
use yii\helpers\Html;
use kartik\mpdf\Pdf;

/**
 * RecetaDetalleController implements the CRUD actions for RecetaDetalle model.
 */
class RecetaDetalleController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                    'bulk-delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all RecetaDetalle models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new RecetaDetalleSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single RecetaDetalle model.
     * @param integer $id_cita
     * @param integer $id_medicamento
     * @return mixed
     */
    public function actionView($id_cita, $id_medicamento) {
        $request = Yii::$app->request;
        if ($request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return [
                'title' => "RecetaDetalle #" . $id_cita, $id_medicamento,
                'content' => $this->renderAjax('view', [
                    'model' => $this->findModel($id_cita, $id_medicamento),
                ]),
                'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                Html::a('Edit', ['update', 'id_cita, $id_medicamento' => $id_cita, $id_medicamento], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
            ];
        } else {
            return $this->render('view', [
                        'model' => $this->findModel($id_cita, $id_medicamento),
            ]);
        }
    }

    /**
     * Creates a new RecetaDetalle model.
     * For ajax request will return json object
     * and for non-ajax request if creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $request = Yii::$app->request;
        $model = new RecetaDetalle();
        $id_cita = $_GET['id_cita'];
        $searchModel = new RecetaDetalleSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        if ($request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            if ($request->isGet) {
                return [
                    'title' => "Create new RecetaDetalle",
                    'content' => $this->renderAjax('create', [
                        'model' => $model,
                        'id_cita' => $id_cita,
                        'searchModel' => $searchModel,
                        'dataProvider' => $dataProvider,
                    ]),
                    'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                    Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
                ];
            } else if ($model->load($request->post()) && $model->save()) {
                return [
                    'forceReload' => '#crud-datatable-pjax',
                    'title' => "Create new RecetaDetalle",
                    'content' => 'Create RecetaDetalle success',
                    'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                    Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
                ];
            } else {
                return [
                    'title' => "Create new RecetaDetalle",
                    'content' => $this->renderAjax('create', [
                        'model' => $model,
                        'id_cita' => $id_cita,
                        'searchModel' => $searchModel,
                        'dataProvider' => $dataProvider,
                    ]),
                    'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                    Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
                ];
            }
        } else {
            /*
             *   Process for non-ajax request
             */
            if ($model->load($request->post()) && $model->save()) {
            return $this->redirect(['create', 'id_cita' => $model->id_cita, 'id_medicamento'=>$model->id_medicamento]);
            } else {
                return $this->render('create', [
                            'model' => $model,
                            'id_cita' => $id_cita,
                            'searchModel' => $searchModel,
                            'dataProvider' => $dataProvider,
                ]);
            }
        }
    }

    /**
     * Updates an existing RecetaDetalle model.
     * For ajax request will return json object
     * and for non-ajax request if update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id_cita
     * @param integer $id_medicamento
     * @return mixed
     */
    public function actionUpdate($id_cita, $id_medicamento) {
        $request = Yii::$app->request;
        $model = $this->findModel($id_cita, $id_medicamento);

        if ($request->isAjax) {
            /*
             *   Process for ajax request
             */
            Yii::$app->response->format = Response::FORMAT_JSON;
            if ($request->isGet) {
                return [
                    'title' => "Update RecetaDetalle #" . $id_cita, $id_medicamento,
                    'content' => $this->renderAjax('update', [
                        'model' => $model,
                    ]),
                    'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                    Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
                ];
            } else if ($model->load($request->post()) && $model->save()) {
                return [
                    'forceReload' => '#crud-datatable-pjax',
                    'title' => "RecetaDetalle #" . $id_cita, $id_medicamento,
                    'content' => $this->renderAjax('view', [
                        'model' => $model,
                    ]),
                    'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                    Html::a('Edit', ['update', 'id_cita, $id_medicamento' => $id_cita, $id_medicamento], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
                ];
            } else {
                return [
                    'title' => "Update RecetaDetalle #" . $id_cita, $id_medicamento,
                    'content' => $this->renderAjax('update', [
                        'model' => $model,
                    ]),
                    'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                    Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
                ];
            }
        } else {
            /*
             *   Process for non-ajax request
             */
            if ($model->load($request->post()) && $model->save()) {
                return $this->redirect(['view', 'id_cita' => $model->id_cita]);
            } else {
                return $this->render('update', [
                            'model' => $model,
                ]);
            }
        }
    }

    /**
     * Delete an existing RecetaDetalle model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id_cita
     * @param integer $id_medicamento
     * @return mixed
     */
    public function actionDelete($id_cita, $id_medicamento) {
        $request = Yii::$app->request;
        $this->findModel($id_cita, $id_medicamento)->delete();

        if ($request->isAjax) {
            /*
             *   Process for ajax request
             */
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ['forceClose' => true, 'forceReload' => '#crud-datatable-pjax'];
        } else {
            /*
             *   Process for non-ajax request
             */
            return $this->redirect(['/receta-detalle/create', 'id_cita'=>$id_cita]);
        }
    }

    /**
     * Delete multiple existing RecetaDetalle model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id_cita
     * @param integer $id_medicamento
     * @return mixed
     */
    public function actionBulkDelete() {
        $request = Yii::$app->request;
        $pks = explode(',', $request->post('pks')); // Array or selected records primary keys
        foreach ($pks as $pk) {
            $model = $this->findModel($pk);
            $model->delete();
        }

        if ($request->isAjax) {
            /*
             *   Process for ajax request
             */
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ['forceClose' => true, 'forceReload' => '#crud-datatable-pjax'];
        } else {
            /*
             *   Process for non-ajax request
             */
            return $this->redirect(['index']);
        }
    }

    public function actionReportes($id_cita) {
        $pdf = new Pdf([
            'mode' => Pdf::MODE_CORE, // leaner size using standard fonts
            'content' => $this->renderPartial('receta_pdf', ['model' => $this->findModel1($id_cita)]),
            'options' => [
                'title' => 'Receta',
                'subject' => 'Receta PUCESE'
            ],
            'methods' => [
                'SetHeader' => ['Generado Por PUCESE||Fecha : ' . date("r")],
                'SetFooter' => ['|Pagina {PAGENO}|'],
            ]
        ]);
        return $pdf->render();
    }

    /**
     * Finds the RecetaDetalle model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id_cita
     * @param integer $id_medicamento
     * @return RecetaDetalle the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */

    protected function findModel1($id_cita) {
        if (($model = RecetaDetalle::findOne(['id_cita' => $id_cita])) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    protected function findModel($id_cita, $id_medicamento) {
        if (($model = RecetaDetalle::findOne(['id_cita' => $id_cita, 'id_medicamento' => $id_medicamento])) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import json
import logging
import os
from collections import namedtuple

from pants.pantsd.process_manager import ProcessManager
from pants.pantsd.watchman_client import StreamableWatchmanClient
from pants.util.dirutil import safe_mkdir

class Watchman(ProcessManager):
  """Watchman process manager and helper class."""

  SOCKET_TIMEOUT_SECONDS = 1

  EventHandler = namedtuple('EventHandler', ['name', 'metadata', 'callback'])

  def __init__(self, work_dir, log_level=1, watchman_path=None):
    super(Watchman, self).__init__(name='watchman', process_name='watchman', socket_type=str)
    self._logger = logging.getLogger(__name__)
    self._log_level = log_level
    self.watchman_path = self._resolve_watchman_path(watchman_path)

    # TODO(kwlzn): should these live in .pids or .pants.d? i.e. should watchman survive clean-all?
    self._work_dir = os.path.join(work_dir, self.name)
    self._state_file = os.path.join(self._work_dir, '{}.state'.format(self.name))
    self._log_file = os.path.join(self._work_dir, '{}.log'.format(self.name))
    self._sock_file = os.path.join(self._work_dir, '{}.sock'.format(self.name))

    self._watchman_client = None

  @property
  def client(self):
    if not self._watchman_client:
      self._watchman_client = self._make_client()
    return self._watchman_client

  def _make_client(self, timeout=SOCKET_TIMEOUT_SECONDS):
    """Create a new watchman client using the BSER protocol over a UNIX socket."""
    return StreamableWatchmanClient(sockpath=self.socket, transport='local', timeout=timeout)

  def _is_valid_executable(self, binary_path):
    return os.path.isfile(binary_path) and os.access(binary_path, os.X_OK)

  def _find_watchman_in_path(self):
    for path in os.environ['PATH'].split(os.pathsep):
      binary_path = os.path.join(path, self.process_name)
      if self._is_valid_executable(binary_path):
        return binary_path

  def _resolve_watchman_path(self, watchman_path=None):
    if watchman_path is not None:
      if not self._is_valid_executable(watchman_path):
        raise self.ExecutionError('invalid watchman binary at {}!'.format(watchman_path))
    else:
      watchman_path = self._find_watchman_in_path()
      if not watchman_path:
        raise self.ExecutionError('could not locate watchman in $PATH!')

    return os.path.abspath(watchman_path)

  def _maybe_init_metadata(self):
    safe_mkdir(self._work_dir)
    # Initialize watchman with an empty, but valid statefile so it doesn't complain on startup.
    self._write_file(self._state_file, '{}')

  def _construct_cmd(self, cmd_parts, state_file, sock_file, log_file, log_level):
    return [part for part in cmd_parts] + ['--no-save-state',
                                           '--statefile={}'.format(state_file),
                                           '--sockname={}'.format(sock_file),
                                           '--logfile={}'.format(log_file),
                                           '--log-level', log_level]

  def _parse_pid_from_output(self, output):
    try:
      # Parse the watchman pidfile from the cli output (in JSON).
      return json.loads(output)['pid']
    except ValueError:
      # JSON parse failure.
      self._logger.critical('invalid output from watchman!\n{output!s}'.format(output=output))
      raise self.InvalidCommandOutput(output)
    except KeyError:
      # Key access error on 'pid' - bad output from watchman.
      self._logger.critical('no pid from watchman!')
      raise self.InvalidCommandOutput(output)

  def launch(self):
    """Launch and synchronously write metadata.

    This is possible due to watchman's built-in async server startup - no double-forking required.
    """
    cmd = self._construct_cmd((self.watchman_path, 'get-pid'),
                              state_file=self._state_file,
                              sock_file=self._sock_file,
                              log_file=self._log_file,
                              log_level=str(self._log_level))
    self._logger.debug('watchman cmd is: {}'.format(' '.join(cmd)))
    self._maybe_init_metadata()

    # Spawn the watchman server (if not already running). Raise ExecutionError on failure.
    output = self.get_subprocess_output(cmd)

    # Parse the watchman PID from the cli output.
    pid = self._parse_pid_from_output(output)

    # Write the process metadata to disk.
    self.write_pid(pid)
    self.write_socket(self._sock_file)

  def watch_project(self, path):
    """Issues the watch-project command to watchman to begin watching the buildroot.

       :param string path: the path to the watchman project root/pants build root.
    """
    # TODO(kwlzn): this can fail with SocketTimeout - add retry.
    return self.client.query('watch-project', os.path.realpath(path))

  def subscribed(self, build_root, handlers):
    """Bulk subscribe generator for StreamableWatchmanClient.

       :param str build_root: the build_root for all subscriptions.
       :param iterable handlers: a sequence of Watchman.EventHandler namedtuple objects.
       :yields: a stream of tuples in the form (subscription_name: str, subscription_event: dict).
    """
    command_list = [['subscribe',
                     build_root,
                     handler.name,
                     handler.metadata] for handler in handlers]

    self._logger.debug('watchman command_list is: {}'.format(command_list))

    for event in self.client.stream_query(command_list):
      if event is None:
        yield None, None
      elif 'subscribe' in event:
        self._logger.info('confirmed watchman subscription: {}'.format(event))
        yield None, None
      elif 'subscription' in event:
        yield event.get('subscription'), event
      else:
        self._logger.warning('encountered non-subscription event: {}'.format(event))


text:
module RailsAdmin
  class ModelGenerator < Rails::Generators::NamedBase
    source_root File.expand_path('../templates', __FILE__)

    desc "Creates a RailsAdmin model"

    class_option :list, type: :array, default: []
    class_option :edit, type: :array, default: []
    class_option :only, type: :array, default: []
    class_option :except, type: :array, default: []
    class_option :nav, type: :string, default: ""

    def create_model_file
      template "model.rb.tt", File.join("app/admin", "#{file_name}_admin.rb")
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bruno.maromba" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SeriesScreen"
            android:label="series"
            android:theme="@style/AppTheme"/>
        <activity
            android:name=".ExerciseActivity"
            android:label="exercise"
            android:theme="@style/AppTheme"/>
        <activity
            android:name=".ExerciseInformationActivity"
            android:label="exercise"
            android:theme="@style/AppTheme"/>
        <activity
            android:name=".AddSerieActivity"
            android:label="exercise"
            android:theme="@style/AppTheme"/>
        <activity
            android:name=".AddExerciseActivity"
            android:label="exercise"
            android:theme="@style/AppTheme"/>

    </application>

</manifest>


text:
var Mocha;
if(module.parent){
  Mocha = module.parent.require('mocha');
}else{
  Mocha = window.Mocha;
}

/**
 * Module dependencies.
 */
var Suite = Mocha.Suite
  , Test = Mocha.Test
  , utils = Mocha.utils
  , Args = require('vargs').Constructor;

/**
 * BDD-style interface:
 *
 *      describe('Array', function() {
 *        describe('#indexOf()', function() {
 *          it('should return -1 when not present', function() {
 *            // ...
 *          });
 *
 *          it('should return the index when present', function() {
 *            // ...
 *          });
 *        });
 *      });
 *
 * @param {Suite} suite Root suite.
 */
module.exports = function(suite) {
  var suites = [suite];

  suite.on('pre-require', function(context, file, mocha) {
    var common = require('./common')(suites, context, mocha);

    context.before = common.before;
    context.after = common.after;
    context.beforeEach = common.beforeEach;
    context.afterEach = common.afterEach;
    context.run = mocha.options.delay && common.runWithSuite(suite);
    /**
     * Describe a "suite" with the given `title`
     * and callback `fn` containing nested suites
     * and/or tests.
     */

    context.describe = context.context = function() {
      var args = new Args(arguments);
      var title = args.all[0];
      var opts = args.all[1] || {};
      var fn = args.callback;
      suite = common.suite.create({
        title: title,
        file: file,
        pending: opts.pending ? true : false,
        fn: fn
      });
      return suite
    };

    /**
     * Pending describe.
     */

    context.xdescribe = context.xcontext = context.describe.skip = function() {
      var args = new Args(arguments);
      var title = args.all[0];
      var fn = args.callback;
      return common.suite.skip({
        title: title,
        file: file,
        fn: fn
      });
    };

    /**
     * Exclusive suite.
     */

    context.describe.only = function(title, fn) {
      var args = new Args(arguments);
      var title = args.all[0];
      var opts = args.all[1] || {};
      var fn = args.callback;
      suite = common.suite.only({
        title: title,
        file: file,
        fn: fn
      });
      return suite
    };

    /**
     * Describe a specification or test-case
     * with the given `title` and callback `fn`
     * acting as a thunk.
     */

    context.it = context.specify = function(title, fn) {
      var args = new Args(arguments);
      var title = args.all[0];
      var opts = args.all[1] || {};
      var fn = args.callback;
      var suite = suites[0];
      if (suite.isPending() || opts.pending) {
        fn = null;
      }
      var test = new Test(title, fn);
      test.file = file;
      suite.addTest(test);
      return test;
    };

    /**
     * Exclusive test-case.
     */

    context.it.only = function(title, fn) {
      var args = new Args(arguments);
      var title = args.all[0];
      var opts = args.all[1] || {};
      var fn = args.callback;
      suite = common.test.only(mocha, context.it(title, fn));
      suite.pending = opts.pending ? true : false;
      return suite
    };

    /**
     * Pending test case.
     */

    context.xit = context.xspecify = context.it.skip = function(title) {
      context.it(title);
    };

    /**
     * Number of attempts to retry.
     */
    context.it.retries = function(n) {
      context.retries(n);
    };
  });
};
Mocha.interfaces['bdd-with-opts'] = module.exports;


text:
Template Manager
================

Renderize HTML Documents with **zTag©** and/or **Razor©** engines.

It has a compressor and manager scripts (JavaScript) and Style Sheets (CSS) files.


text:
const five     = require('johnny-five');
const Tessel   = require('tessel-io');
const board    = new five.Board({
  io: new Tessel()
});
const keypress = require('keypress');
const Rover    = require('./Rover');

board.on('ready', function () {
  const motors = new five.Motors([
    { pins: { dir: 'A4', pwm: 'A5' }, invertPWM: true },
    { pins: { dir: 'B4', pwm: 'B5' }, invertPWM: true }
  ]);
  const rover = new Rover(motors);

  keypress(process.stdin);
  process.stdin.setEncoding('utf8');

  process.stdin.on('keypress', function (ch, key) {

    if (!key) { return; }

    switch (key.name) {
      case 'q':
        rover.stop();
        console.log('Bye-bye!');
        process.exit();
        break;
      case 'up':
        rover.forward();
        break;
      case 'down':
        rover.backward();
        break;
      case 'left':
        rover.left();
        break;
      case 'right':
        rover.right();
        break;
      case 'space':
        rover.stop();
        break;
      default:
        return;
    }
  });
});


text:
require "stringio"
require "formula"

module Homebrew
  module UnpackPatch
    def patch
      super if ARGV.flag?("--patch")
    end
  end

  def unpack
    formulae = ARGV.formulae
    raise FormulaUnspecifiedError if formulae.empty?

    if dir = ARGV.value("destdir")
      unpack_dir = Pathname.new(dir)
      unpack_dir.mkpath
    else
      unpack_dir = Pathname.pwd
    end

    raise "Cannot write to #{unpack_dir}" unless unpack_dir.writable_real?

    formulae.each do |f|
      f.extend(UnpackPatch)
      stage_dir = unpack_dir.join("#{f.name}-#{f.version}")

      if stage_dir.exist?
        raise "Destination #{stage_dir} already exists!" unless ARGV.force?
        rm_rf stage_dir
      end

      oh1 "Unpacking #{f.name} to: #{stage_dir}"

      ENV['VERBOSE'] = '1' # show messages about tar
      f.brew { cp_r getwd, stage_dir }
      ENV['VERBOSE'] = nil

      if ARGV.flag? "--git"
        ohai "Setting up git repository"
        cd stage_dir
        system "git", "init", "-q"
        system "git", "add", "-A"
        system "git", "commit", "-q", "-m", "brew-unpack"
      end
    end
  end
end


text:
package geconfsql

import (
	"database/sql"
	"log"
	"strings"

	"github.com/gimpldo/ba-prototype-go/geconf"
	"github.com/pkg/errors"
)

// InsertEntriesIntoDB writes the given configuration entries into a database
// using the given SQL INSERT statement.
//
// Any configuration entries already in the database remain unchanged.
//
// Neither the table name nor the column names are hardcoded, but
// this means that the caller is responsible to specify the columns
// in the right order: first the Element name, then Property, Value last.
//
func InsertEntriesIntoDB(db *sql.DB, insertSQL string, confEntries []geconf.Entry) error {
	stmt, err := db.Prepare(insertSQL)
	if err != nil {
		return err
	}
	defer stmt.Close()

	for i, entry := range confEntries {
		elem := strings.TrimSpace(entry.ConfElement) // may be empty

		prop := strings.TrimSpace(entry.ConfProperty)
		if prop == "" {
			log.Printf("Skipping entry %d/%d (empty ConfProperty): %#v",
				i, len(confEntries), entry)
			continue
		}

		val := strings.TrimSpace(entry.ConfValue)
		if val == "" {
			log.Printf("Skipping entry %d/%d (empty ConfValue): %#v",
				i, len(confEntries), entry)
			continue
		}

		result, insErr := stmt.Exec(elem, prop, val)
		if insErr != nil {
			return errors.Wrapf(insErr,
				"failed to insert conf entry %d/%d (%#v)",
				i, len(confEntries), entry)
		}

		nAffected, err := result.RowsAffected()
		if err != nil {
			return errors.Wrapf(err,
				"Cannot get affected count after inserting conf entry %d/%d (%#v)",
				i, len(confEntries), entry)
		}
		if nAffected != 1 {
			return errors.Wrapf(err,
				"Affected count is %d != 1 after inserting conf entry %d/%d (%#v)",
				nAffected, i, len(confEntries), entry)
		}
	}

	return nil
}


text:
<!--
  ~ Copyright 2020 Google LLC
  ~
  ~ 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
  ~
  ~     https://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.
  -->

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal"
    tools:ignore="VectorRaster">
  <path
      android:fillColor="#FFFFFF"
      android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM4,12c0,-4.42 3.58,-8 8,-8 1.85,0 3.55,0.63 4.9,1.69L5.69,16.9C4.63,15.55 4,13.85 4,12zM12,20c-1.85,0 -3.55,-0.63 -4.9,-1.69L18.31,7.1C19.37,8.45 20,10.15 20,12c0,4.42 -3.58,8 -8,8z"/>
</vector>