text:
namespace strongloop {
namespace agent {
namespace uvmon {

namespace C = ::compat;

using v8::Isolate;
using v8::Local;
using v8::Object;

uv_check_t check_handle;
uint32_t statistics[4];
uint32_t& min = statistics[0];
uint32_t& max = statistics[1];
uint32_t& num = statistics[2];
uint32_t& sum = statistics[3];

void OnCheck(uv_check_t* handle) {
  const uv_loop_t* const loop = handle->loop;
  const uint64_t now = uv_hrtime() / static_cast<uint64_t>(1e6);
  const uint32_t delta =
      static_cast<uint32_t>(now <= loop->time ? 0 : (now - loop->time));
  if (delta < min) {
    min = delta;
  }
  if (delta > max) {
    max = delta;
  }
  num += 1;
  sum += delta;
}

void Initialize(Isolate* isolate, Local<Object> binding) {
  uv_check_init(uv_default_loop(), &check_handle);
  uv_check_start(&check_handle, reinterpret_cast<uv_check_cb>(OnCheck));
  uv_unref(reinterpret_cast<uv_handle_t*>(&check_handle));
#if !NODE_VERSION_AT_LEAST(3, 0, 0)
  Local<Object> event_loop_statistics = C::Object::New(isolate);
  event_loop_statistics->SetIndexedPropertiesToExternalArrayData(
      statistics, v8::kExternalUnsignedIntArray, ArraySize(statistics));
#else
  Local<v8::ArrayBuffer> array_buffer =
      v8::ArrayBuffer::New(isolate, statistics, sizeof(statistics));
  Local<v8::Uint32Array> event_loop_statistics =
      v8::Uint32Array::New(array_buffer, 0, ArraySize(statistics));
#endif
  binding->Set(C::String::NewFromUtf8(isolate, "eventLoopStatistics"),
               event_loop_statistics);
}

}  // namespace uvmon
}  // namespace agent
}  // namespace strongloop

#endif  // SRC_UVMON_H_


text:
namespace System
{
    namespace Runtime
    {
        namespace CompilerServices
        {
            // Generated from `System.Runtime.CompilerServices.Unsafe` in `System.Runtime.CompilerServices.Unsafe, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`
            public static class Unsafe
            {
                unsafe public static void* Add<T>(void* source, int elementOffset) => throw null;
                public static T Add<T>(ref T source, System.IntPtr elementOffset) => throw null;
                public static T Add<T>(ref T source, System.UIntPtr elementOffset) => throw null;
                public static T Add<T>(ref T source, int elementOffset) => throw null;
                public static T AddByteOffset<T>(ref T source, System.IntPtr byteOffset) => throw null;
                public static T AddByteOffset<T>(ref T source, System.UIntPtr byteOffset) => throw null;
                public static bool AreSame<T>(ref T left, ref T right) => throw null;
                public static T As<T>(object o) where T : class => throw null;
                public static TTo As<TFrom, TTo>(ref TFrom source) => throw null;
                unsafe public static void* AsPointer<T>(ref T value) => throw null;
                public static T AsRef<T>(T source) => throw null;
                unsafe public static T AsRef<T>(void* source) => throw null;
                public static System.IntPtr ByteOffset<T>(ref T origin, ref T target) => throw null;
                unsafe public static void Copy<T>(void* destination, ref T source) => throw null;
                unsafe public static void Copy<T>(ref T destination, void* source) => throw null;
                unsafe public static void CopyBlock(void* destination, void* source, System.UInt32 byteCount) => throw null;
                public static void CopyBlock(ref System.Byte destination, ref System.Byte source, System.UInt32 byteCount) => throw null;
                unsafe public static void CopyBlockUnaligned(void* destination, void* source, System.UInt32 byteCount) => throw null;
                public static void CopyBlockUnaligned(ref System.Byte destination, ref System.Byte source, System.UInt32 byteCount) => throw null;
                unsafe public static void InitBlock(void* startAddress, System.Byte value, System.UInt32 byteCount) => throw null;
                public static void InitBlock(ref System.Byte startAddress, System.Byte value, System.UInt32 byteCount) => throw null;
                unsafe public static void InitBlockUnaligned(void* startAddress, System.Byte value, System.UInt32 byteCount) => throw null;
                public static void InitBlockUnaligned(ref System.Byte startAddress, System.Byte value, System.UInt32 byteCount) => throw null;
                public static bool IsAddressGreaterThan<T>(ref T left, ref T right) => throw null;
                public static bool IsAddressLessThan<T>(ref T left, ref T right) => throw null;
                public static bool IsNullRef<T>(ref T source) => throw null;
                public static T NullRef<T>() => throw null;
                unsafe public static T Read<T>(void* source) => throw null;
                unsafe public static T ReadUnaligned<T>(void* source) => throw null;
                public static T ReadUnaligned<T>(ref System.Byte source) => throw null;
                public static int SizeOf<T>() => throw null;
                public static void SkipInit<T>(out T value) => throw null;
                unsafe public static void* Subtract<T>(void* source, int elementOffset) => throw null;
                public static T Subtract<T>(ref T source, System.IntPtr elementOffset) => throw null;
                public static T Subtract<T>(ref T source, System.UIntPtr elementOffset) => throw null;
                public static T Subtract<T>(ref T source, int elementOffset) => throw null;
                public static T SubtractByteOffset<T>(ref T source, System.IntPtr byteOffset) => throw null;
                public static T SubtractByteOffset<T>(ref T source, System.UIntPtr byteOffset) => throw null;
                public static T Unbox<T>(object box) where T : struct => throw null;
                unsafe public static void Write<T>(void* destination, T value) => throw null;
                unsafe public static void WriteUnaligned<T>(void* destination, T value) => throw null;
                public static void WriteUnaligned<T>(ref System.Byte destination, T value) => throw null;
            }

        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * This code is generated using [[https://www.scala-sbt.org/contraband/ sbt-contraband]].
 */

// DO NOT EDIT MANUALLY
package sbt.protocol.testing
/** Called for each class or equivalent grouping. */
final class StartTestGroupEvent private (
  val name: String) extends sbt.protocol.testing.TestMessage() with Serializable {

  override def equals(o: Any): Boolean = this.eq(o.asInstanceOf[AnyRef]) || (o match {
    case x: StartTestGroupEvent => (this.name == x.name)
    case _ => false
  })
  override def hashCode: Int = {
    37 * (37 * (17 + "sbt.protocol.testing.StartTestGroupEvent".##) + name.##)
  }
  override def toString: String = {
    "StartTestGroupEvent(" + name + ")"
  }
  private[this] def copy(name: String = name): StartTestGroupEvent = {
    new StartTestGroupEvent(name)
  }
  def withName(name: String): StartTestGroupEvent = {
    copy(name = name)
  }
}
object StartTestGroupEvent {

  def apply(name: String): StartTestGroupEvent = new StartTestGroupEvent(name)
}


text:
<?php

namespace JildertMiedema\Commander;

interface ExecutorInterface
{
    /**
     * @param string $command
     * @param array $input
     * @param array $decorators
     *
     * @return mixed
     */
    public function execute(
        $command,
        array $input = null,
        array $decorators = []
    );
}


text:
```bash
make doc
```

#### Run tests
```bash
make
make test
```

#### Run benchmarks

Build target `all`, go to subdirectory `benchmarks` and run executable.

## Dependencies

### Doxygen

Tool for generating documentation.

#### Installation
```bash
sudo apt-get install doxygen
```

### Boost unit test framework

See Boost unit test framework [documentation](http://www.boost.org/doc/libs/1_58_0/libs/test/doc/html/utf.html).

#### Installation
```bash
sudo apt-get install libboost-test-dev
```

### Celero benchmark framework

See Celero project on [GitHub](https://github.com/DigitalInBlue/Celero).

#### Installation
```bash
cd ~/
mkdir celero && cd celero
git clone https://github.com/DigitalInBlue/Celero.git
mkdir build
cd build
cmake ../Celero
make -j
sudo make install
cd ..
sudo cp -R Celero/include/celero /usr/local/include/
```

### Regex python package

#### Installation
```bash
pip install regex
```


text:
CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS
---------------------------------------

The maximum number of warnings in a single build step which will be detected.
After this, the :command:`ctest_test` command will truncate the output.
Defaults to 50.

.. include:: CTEST_CUSTOM_XXX.txt


text:
/**
 * Created by clemenspfister on 31/03/2017.
 */

public class Main {

    public static void main(String[] args) {
        // Two professor objects
        Professor professor1 = new Professor("John", "Doe");
        Professor professor2 = new Professor(5430.0, "Richard", "Wagner");

        // room1 with capacity of 25
        Room room1 = new Room(365, 25);
        Course course1 = new Course(1, room1, professor1);

        // Add 30 students to this room
        for (int i = 0; i < 30; i++) {
            course1.addStudent(new Student(i));
        }

        // If John Doe teaches a course give him an unfair amount of money
        if (professor1.isTeaching) {
            professor1.currentSalary *= 1.252;
        }

        // 25 = Magic number
        if ((course1.professor.equals(professor1)) && (course1.students.size() > 25)) {
            professor1.currentSalary *= 1.11;
        }

        // Add three more students
        Student sameIdStudent1 = new Student(100, "Mat", "Hematik");
        Student sameIdStudent2 = new Student(100, "Ham", "Burger");
        Student sameNameStudent3 = new Student(101, "Mat", "Hematik");

        // Print number of students in course
        System.out.println("There are " + course1.students.size() + " students in this course.");

        // Add one more student
        course1.addStudent(sameIdStudent1);

        // Print NoS again
        System.out.println("There are " + course1.students.size() + " students in this course.");

        // Print professor with currentSalary using toString
        // If we want to print out n professors, we need a datastructure like an array or a list.
        System.out.println("Current salary of " + professor1.toString() + ": " + professor1.currentSalary);
        System.out.println("Current salary of " + professor2.toString() + ": " + professor2.currentSalary);

        // Test if sameId students are the same (use devtools)
        // This returns true because in the equals method, we specified that if
        // two IDs are identical, the students are, too.
        System.out.println(sameIdStudent1.equals(sameIdStudent2));

        // Are two students without same IDs equal?
        // returns false because neither are these student objects the same
        // (e.g. have the same internal value) nor do they have the same IDs.
        System.out.println(sameIdStudent1.equals(sameNameStudent3));

        // Print a student without toString();
        // prints Student@5cad8086 on my machine (this is
        // the internal identifier for this student object).
        System.out.println(sameIdStudent1);
    }
}


text:
<?php

namespace MediaMonks\MssqlBundle\PDO;

use MediaMonks\MssqlBundle\Helper\ConnectionHelper;
use MediaMonks\MssqlBundle\Doctrine\DBAL\Driver\PDODblib\Driver;

class PDO extends \PDO
{
    /**
     * PDO constructor.
     * @param $host
     * @param $port
     * @param $dbname
     * @param $username
     * @param $passwd
     * @param $options
     */
    public function __construct($host, $port, $dbname, $username, $passwd, $options)
    {
        $driver = new Driver();
        $dsn = $driver->constructPdoDsn([
            'host'   => $host,
            'port'   => $port,
            'dbname' => $dbname
        ]);

        parent::__construct($dsn, $username, $passwd, $options);

        ConnectionHelper::setConnectionOptions($this);
    }
}


text:
using System;
using System.Reflection.Emit;

namespace ILReaderLibrary.ILReader
{
    public class ShortInlineIInstruction : ILInstruction
    {
        private Byte m_int8;

        public Byte Byte
        {
            get
            {
                return m_int8;
            }
        }

        internal ShortInlineIInstruction(Int32 offset, OpCode opCode, Byte value)
            : base(offset, opCode)
        {
            m_int8 = value;
        }

        public override void Accept(ILInstructionVisitor vistor)
        {
            vistor.VisitShortInlineIInstruction(this);
        }
    }
}


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

#include "node_dtrace.h"

#ifdef HAVE_DTRACE
#include "node_provider.h"
#elif HAVE_ETW
#include "node_win32_etw_provider-inl.h"
#else
#define NODE_HTTP_SERVER_REQUEST(arg0, arg1)
#define NODE_HTTP_SERVER_REQUEST_ENABLED() (0)
#define NODE_HTTP_SERVER_RESPONSE(arg0)
#define NODE_HTTP_SERVER_RESPONSE_ENABLED() (0)
#define NODE_HTTP_CLIENT_REQUEST(arg0, arg1)
#define NODE_HTTP_CLIENT_REQUEST_ENABLED() (0)
#define NODE_HTTP_CLIENT_RESPONSE(arg0)
#define NODE_HTTP_CLIENT_RESPONSE_ENABLED() (0)
#define NODE_NET_SERVER_CONNECTION(arg0)
#define NODE_NET_SERVER_CONNECTION_ENABLED() (0)
#define NODE_NET_STREAM_END(arg0)
#define NODE_NET_STREAM_END_ENABLED() (0)
#define NODE_GC_START(arg0, arg1, arg2)
#define NODE_GC_DONE(arg0, arg1, arg2)
#endif

#include "node_errors.h"
#include "node_internals.h"

#include <string.h>

namespace node {

using v8::FunctionCallbackInfo;
using v8::GCCallbackFlags;
using v8::GCType;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

#define SLURP_STRING(obj, member, valp)                                    \
  if (!(obj)->IsObject()) {                                                \
    return node::THROW_ERR_INVALID_ARG_TYPE(env,                           \
        "expected object for " #obj " to contain string member " #member); \
  }                                                                        \
  node::Utf8Value _##member(env->isolate(),                                \
      obj->Get(OneByteString(env->isolate(), #member)));                   \
  if ((*(const char **)valp = *_##member) == nullptr)                      \
    *(const char **)valp = "<unknown>";

#define SLURP_INT(obj, member, valp)                                       \
  if (!(obj)->IsObject()) {                                                \
    return node::THROW_ERR_INVALID_ARG_TYPE(env,                           \
        "expected object for " #obj " to contain integer member " #member);\
  }                                                                        \
  *valp = obj->Get(OneByteString(env->isolate(), #member))                 \
      ->Int32Value();

#define SLURP_OBJECT(obj, member, valp)                                    \
  if (!(obj)->IsObject()) {                                                \
    return node::THROW_ERR_INVALID_ARG_TYPE(env,                           \
        "expected object for " #obj " to contain object member " #member); \
  }                                                                        \
  *valp = Local<Object>::Cast(obj->Get(OneByteString(env->isolate(), #member)));

#define SLURP_CONNECTION(arg, conn)                                        \
  if (!(arg)->IsObject()) {                                                \
    return node::THROW_ERR_INVALID_ARG_TYPE(env,                           \
        "expected argument " #arg " to be a connection object");           \
  }                                                                        \
  node_dtrace_connection_t conn;                                           \
  Local<Object> _##conn = Local<Object>::Cast(arg);                        \
  Local<Value> _handle =                                                   \
      (_##conn)->Get(FIXED_ONE_BYTE_STRING(env->isolate(), "_handle"));    \
  if (_handle->IsObject()) {                                               \
    SLURP_INT(_handle.As<Object>(), fd, &conn.fd);                         \
  } else {                                                                 \
    conn.fd = -1;                                                          \
  }                                                                        \
  SLURP_STRING(_##conn, remoteAddress, &conn.remote);                      \
  SLURP_INT(_##conn, remotePort, &conn.port);                              \
  SLURP_INT(_##conn, bufferSize, &conn.buffered);

#define SLURP_CONNECTION_HTTP_CLIENT(arg, conn)                            \
  if (!(arg)->IsObject()) {                                                \
    return node::THROW_ERR_INVALID_ARG_TYPE(env,                           \
        "expected argument " #arg " to be a connection object");           \
  }                                                                        \
  node_dtrace_connection_t conn;                                           \
  Local<Object> _##conn = Local<Object>::Cast(arg);                        \
  SLURP_INT(_##conn, fd, &conn.fd);                                        \
  SLURP_STRING(_##conn, host, &conn.remote);                               \
  SLURP_INT(_##conn, port, &conn.port);                                    \
  SLURP_INT(_##conn, bufferSize, &conn.buffered);

#define SLURP_CONNECTION_HTTP_CLIENT_RESPONSE(arg0, arg1, conn)            \
  if (!(arg0)->IsObject()) {                                               \
    return node::THROW_ERR_INVALID_ARG_TYPE(env,                           \
        "expected argument " #arg0 " to be a connection object");          \
  }                                                                        \
  if (!(arg1)->IsObject()) {                                               \
    return node::THROW_ERR_INVALID_ARG_TYPE(env,                           \
        "expected argument " #arg1 " to be a connection object");          \
  }                                                                        \
  node_dtrace_connection_t conn;                                           \
  Local<Object> _##conn = Local<Object>::Cast(arg0);                       \
  SLURP_INT(_##conn, fd, &conn.fd);                                        \
  SLURP_INT(_##conn, bufferSize, &conn.buffered);                          \
  _##conn = Local<Object>::Cast(arg1);                                     \
  SLURP_STRING(_##conn, host, &conn.remote);                               \
  SLURP_INT(_##conn, port, &conn.port);

void DTRACE_NET_SERVER_CONNECTION(const FunctionCallbackInfo<Value>& args) {
  if (!NODE_NET_SERVER_CONNECTION_ENABLED())
    return;
  Environment* env = Environment::GetCurrent(args);
  SLURP_CONNECTION(args[0], conn);
  NODE_NET_SERVER_CONNECTION(&conn, conn.remote, conn.port, conn.fd);
}

void DTRACE_NET_STREAM_END(const FunctionCallbackInfo<Value>& args) {
  if (!NODE_NET_STREAM_END_ENABLED())
    return;
  Environment* env = Environment::GetCurrent(args);
  SLURP_CONNECTION(args[0], conn);
  NODE_NET_STREAM_END(&conn, conn.remote, conn.port, conn.fd);
}

void DTRACE_HTTP_SERVER_REQUEST(const FunctionCallbackInfo<Value>& args) {
  node_dtrace_http_server_request_t req;

  if (!NODE_HTTP_SERVER_REQUEST_ENABLED())
    return;

  Environment* env = Environment::GetCurrent(args);
  HandleScope scope(env->isolate());
  Local<Object> arg0 = Local<Object>::Cast(args[0]);
  Local<Object> headers;

  memset(&req, 0, sizeof(req));
  req._un.version = 1;
  SLURP_STRING(arg0, url, &req.url);
  SLURP_STRING(arg0, method, &req.method);
  SLURP_OBJECT(arg0, headers, &headers);

  if (!(headers)->IsObject()) {
    return node::THROW_ERR_INVALID_ARG_TYPE(env,
        "expected object for request to contain string member headers");
  }

  Local<Value> strfwdfor = headers->Get(env->x_forwarded_string());
  node::Utf8Value fwdfor(env->isolate(), strfwdfor);

  if (!strfwdfor->IsString() || (req.forwardedFor = *fwdfor) == nullptr)
    req.forwardedFor = const_cast<char*>("");

  SLURP_CONNECTION(args[1], conn);
  NODE_HTTP_SERVER_REQUEST(&req, &conn, conn.remote, conn.port, req.method, \
                           req.url, conn.fd);
}

void DTRACE_HTTP_SERVER_RESPONSE(const FunctionCallbackInfo<Value>& args) {
  if (!NODE_HTTP_SERVER_RESPONSE_ENABLED())
    return;
  Environment* env = Environment::GetCurrent(args);
  SLURP_CONNECTION(args[0], conn);
  NODE_HTTP_SERVER_RESPONSE(&conn, conn.remote, conn.port, conn.fd);
}

void DTRACE_HTTP_CLIENT_REQUEST(const FunctionCallbackInfo<Value>& args) {
  node_dtrace_http_client_request_t req;
  char *header;

  if (!NODE_HTTP_CLIENT_REQUEST_ENABLED())
    return;

  Environment* env = Environment::GetCurrent(args);
  HandleScope scope(env->isolate());

  /*
   * For the method and URL, we're going to dig them out of the header.  This
   * is not as efficient as it could be, but we would rather not force the
   * caller here to retain their method and URL until the time at which
   * DTRACE_HTTP_CLIENT_REQUEST can be called.
   */
  Local<Object> arg0 = Local<Object>::Cast(args[0]);
  SLURP_STRING(arg0, _header, &header);

  req.method = header;

  while (*header != '\0' && *header != ' ')
    header++;

  if (*header != '\0')
    *header++ = '\0';

  req.url = header;

  while (*header != '\0' && *header != ' ')
    header++;

  *header = '\0';

  SLURP_CONNECTION_HTTP_CLIENT(args[1], conn);
  NODE_HTTP_CLIENT_REQUEST(&req, &conn, conn.remote, conn.port, req.method, \
                           req.url, conn.fd);
}

void DTRACE_HTTP_CLIENT_RESPONSE(const FunctionCallbackInfo<Value>& args) {
  if (!NODE_HTTP_CLIENT_RESPONSE_ENABLED())
    return;
  Environment* env = Environment::GetCurrent(args);
  SLURP_CONNECTION_HTTP_CLIENT_RESPONSE(args[0], args[1], conn);
  NODE_HTTP_CLIENT_RESPONSE(&conn, conn.remote, conn.port, conn.fd);
}

void dtrace_gc_start(Isolate* isolate, GCType type, GCCallbackFlags flags) {
  // Previous versions of this probe point only logged type and flags.
  // That's why for reasons of backwards compatibility the isolate goes last.
  NODE_GC_START(type, flags, isolate);
}

void dtrace_gc_done(Isolate* isolate, GCType type, GCCallbackFlags flags) {
  // Previous versions of this probe point only logged type and flags.
  // That's why for reasons of backwards compatibility the isolate goes last.
  NODE_GC_DONE(type, flags, isolate);
}

void InitDTrace(Environment* env, Local<Object> target) {
  HandleScope scope(env->isolate());

  static struct {
    const char *name;
    void (*func)(const FunctionCallbackInfo<Value>&);
  } tab[] = {
#define NODE_PROBE(name) #name, name
    { NODE_PROBE(DTRACE_NET_SERVER_CONNECTION) },
    { NODE_PROBE(DTRACE_NET_STREAM_END) },
    { NODE_PROBE(DTRACE_HTTP_SERVER_REQUEST) },
    { NODE_PROBE(DTRACE_HTTP_SERVER_RESPONSE) },
    { NODE_PROBE(DTRACE_HTTP_CLIENT_REQUEST) },
    { NODE_PROBE(DTRACE_HTTP_CLIENT_RESPONSE) }
#undef NODE_PROBE
  };

  for (size_t i = 0; i < arraysize(tab); i++) {
    Local<String> key = OneByteString(env->isolate(), tab[i].name);
    Local<Value> val = env->NewFunctionTemplate(tab[i].func)->GetFunction();
    target->Set(key, val);
  }

#ifdef HAVE_ETW
  init_etw();
#endif

#if defined HAVE_DTRACE || defined HAVE_ETW
  env->isolate()->AddGCPrologueCallback(dtrace_gc_start);
  env->isolate()->AddGCEpilogueCallback(dtrace_gc_done);
#endif
}

}  // namespace node


text:
import pytest

from fudge.index import read_index, write_index
from fudge.utils import FudgeException, read_file

from conftest import get_destination_path

@pytest.mark.fudgefiles(['index/invalid_checksum', 'index'])
def test_read_index_with_an_invalid_checksum(repo):
    with pytest.raises(FudgeException) as exception:
        read_index()
    assert 'bad index file checksum' in str(exception.value)

@pytest.mark.fudgefiles(['index/invalid_magic', 'index'])
def test_read_index_with_an_invalid_magic(repo):
    with pytest.raises(FudgeException) as exception:
        read_index()
    assert 'invalid index file magic' in str(exception.value)

@pytest.mark.fudgefiles(['index/invalid_version', 'index'])
def test_read_index_with_an_invalid_version(repo):
    with pytest.raises(FudgeException) as exception:
        read_index()
    assert 'unsupported index file version' in str(exception.value)

@pytest.mark.fudgefiles(['index/valid', 'index'])
def test_read_index_successfully(repo):
    expected = [
        '.gitignore',
        'README.md',
        'fudge/__init__.py',
        'tests/data/index',
        'tests/test_fudge.py',
    ]
    index = read_index()
    assert [entry.path for entry in index] == expected

@pytest.mark.fudgefiles(['index/valid', 'index'])
def test_read_and_write_index_successfully(repo):
    path = get_destination_path('index')
    before = read_file(path)

    index = read_index()
    write_index(index)

    after = read_file(path)
    assert before == after


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

namespace Avoid_The_Blocks {
    public class ScoreEntry {

        private string name;
        private int level;

        public ScoreEntry(string n, int l) {
            this.name = n;
            this.level = l;
        }

        public string getName() {
            return this.name;
        }

        public void setName(string s) {
            this.name = s;
        }

        public int getLevel() {
            return this.level;
        }

        public void setLevel(int l) {
            this.level = l;
        }

    }
}


text:
clojure-language-server
=======================
Clojure的vscode的language server,实现language server protocol,暂时没空做,等有空或者有人一起做的时候改描述

# References

* see Wiki


text:
CelestialModel::CelestialModel(CelestialObject *root, QObject *parent)
	: QAbstractListModel(parent)
	, _rootObject(root)
{ }

int CelestialModel::indexById(const QString &id) const
{
	if (!_rootObject)
		return -1;
	if (_rootObject->equalIds(id))
		return 0;
	for (size_t i = 0; i < _rootObject->children().size(); ++i) {
		if (_rootObject->childObject(i)->equalIds(id))
			return i + 1;
	}
	return -1;
}

int CelestialModel::rowCount(const QModelIndex &parent) const
{
	Q_UNUSED(parent);
	return _rootObject ? _rootObject->childrenSize() + 1 : 0;
}

QVariant CelestialModel::data(const QModelIndex &index, int role) const
{
	if (!_rootObject || index.row() < 0 || index.row() >= _rootObject->childrenSize() + 1)
		return QVariant();

	CelestialObject *body = index.row() == 0 ? _rootObject : _rootObject->childObject(index.row() - 1);
	if (!body)
		return QVariant();
	switch (role) {
		case Name: return body->name();
		case HasChildren: return body->childrenSize() != 0;
		case HasParent:
			return body == _rootObject
				&& _rootObject->parent()->typeId() == bluedot::TypeInfo<CelestialObject>::id;
		default: return QVariant();
	}
}

QHash<int, QByteArray> CelestialModel::roleNames() const
{
	QHash<int, QByteArray> roles;
	roles[Name] = "name";
	roles[HasChildren] = "hasChildren";
	roles[HasParent] = "hasParent";
	return roles;
}

CelestialObject *CelestialModel::rootObject() const
{
	return _rootObject;
}

void CelestialModel::setRootObject(CelestialObject *rootObject)
{
	beginResetModel();
	_rootObject = rootObject;
	endResetModel();
}


text:
A ByteOffset represents the byte offset between successive elements of a Field.
It is returned when creating a raw_rect_ptr to a PhysicalRegion.


text:
'use strict';

angular.module('av001App')
    .controller('ProductDetailController', function ($scope, $rootScope, $stateParams, entity, Product, Lineitem) {
        $scope.product = entity;
        $scope.load = function (id) {
            Product.get({id: id}, function(result) {
                $scope.product = result;
            });
        };
        var unsubscribe = $rootScope.$on('av001App:productUpdate', function(event, result) {
            $scope.product = result;
        });
        $scope.$on('$destroy', unsubscribe);

    });


text:
/**
 * Created by julia on 23.01.2017.
 */
let Manager = require('../../structures/manager');
class UtilityManager extends Manager {

}
module.exports = {
    class: UtilityManager,
    deps: [],
    async: false,
    shortcode: 'utm'
};


text:
module Gitlab
  module GoogleCodeImport
    class Client
      attr_reader :raw_data

      def self.mask_email(author)
        parts = author.split("@", 2)
        parts[0] = "#{parts[0][0...-3]}..."
        parts.join("@")
      end

      def initialize(raw_data)
        @raw_data = raw_data
      end

      def valid?
        raw_data.is_a?(Hash) && raw_data["kind"] == "projecthosting#user" && raw_data.key?("projects")
      end

      def repos
        @repos ||= raw_data["projects"].map { |raw_repo| GoogleCodeImport::Repository.new(raw_repo) }.select(&:git?)
      end

      def incompatible_repos
        @incompatible_repos ||= raw_data["projects"].map { |raw_repo| GoogleCodeImport::Repository.new(raw_repo) }.reject(&:git?)
      end

      def repo(id)
        repos.find { |repo| repo.id == id }
      end

      def user_map
        user_map = Hash.new { |hash, user| hash[user] = self.class.mask_email(user) }

        repos.each do |repo|
          next unless repo.valid? && repo.issues

          repo.issues.each do |raw_issue|
            # Touching is enough to add the entry and masked email.
            user_map[raw_issue["author"]["name"]]

            raw_issue["comments"]["items"].each do |raw_comment|
              user_map[raw_comment["author"]["name"]]
            end
          end
        end

        Hash[user_map.sort]
      end
    end
  end
end


text:
        <form id="form-clear" class="navbar-form form-inline navbar-right">
            <button id="toggle-edit" type="button" class="btn btn-danger">Not Editing</button>
            <button id="undo" type="button" class="btn btn-info">Undo</button>
            <button id="redo" type="button" class="btn btn-info">Redo</button>
            <button id="clear" type="button" class="btn btn-info">Clear</button>
        </form>

<video id="videoInput" autoplay muted loop poster="images/fiware-logo.png"></video>
<video id="videoOutput" class="hide" autoplay muted loop poster ="images/fiware-logo.png"></video>


text:
using Consolas.Core;

namespace Consolas.Razor
{
    public class RazorView : IView
    {
        private readonly string _view;

        public RazorView(string view)
        {
            _view = view;
        }

        public string Render<T>(T model)
        {
            return RazorEngine.Razor.Parse(_view, model);
        }
    }
}


text:
Multiple environments are supported through the use of environment specific configuration files, which are stored in the `/config` directory.

The environment is determined in 2 ways:
* In the `/config/environment.php` file, you can explicitly set the environment by providing a value for the `APP_ENVIRONMENT` constant
* If you leave the `APP_ENVIRONMENT` constant as a null value, then the auto-detector will take over from and try to determine if you are in a development or testing environment.  The `$_SERVER` superglobal array elements `HTTP_HOST, SERVER_NAME, SERVER_ADDRESS, and REMOTE_ADDR` will be searched for a match to anything containing:
    * 127.0.0.1
    * localhost
    * any domain ending in *.dev
    * any domain ending in *.local

If a match is found, the environment will be set to `development`.  If no match is found, the environment will be set to testing.  The auto detect script will not put the application into the production environment under any circumstances, this must be done manually.

> The superglobal values and the values that trigger a positive response to go into development mode can be adjusted in the `/core/global_functions.php` file.

Other custom environments like `staging` can be deployed by adding a `staging.php` file in the `/config` directory, but it will be necessary to explicitly set the environment from the `environment.php` file.


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_randomize"
        android:orderInCategory="10"
        android:showAsAction="ifRoom"
        android:title="@string/action_randomize"/>
    <item
        android:id="@+id/action_reroll"
        android:orderInCategory="15"
        android:showAsAction="ifRoom"
        android:title="@string/action_reroll"/>
    <item
        android:id="@+id/action_reset"
        android:orderInCategory="25"
        android:showAsAction="ifRoom"
        android:title="@string/action_reset"/>

</menu>


text:
While using Injector\Container or any other dependency injection container, there are a few patterns of usage to be wary of. These patterns are listed below.

## Container Dependency or, the glorified Service Locator

When classes other than Factory classes start to depend on Injector\Container, you should think about your application's design again. Chances are that you're using the DiC as a glorified Service Locator. Imagine the following case:
```php
use Injector\Container;

class UserRepository {
    protected $container;
    public function __construct(Container $container) {
        $this->container = $container;
    }

    public function fetch($id) {
        $query = 'SELECT * FROM users WHERE id = :id';
        return $this->container->get('DbAdapter')->query($query, ['id' => $id]);
    }
}
```

The solution to this anti-pattern is keeping stuff simple: denote concrete dependencies, rather than the container. Consider the corrected code:

```php
use Injector\Container;

class UserRepository {
    protected $adapter;

    public function __construct(DbAdapter $adapter) {
        $this->adapter = $adapter;
    }

    public function fetch($id) {
        return $this->adapter->query('SELECT * FROM users WHERE id = :id', ['id' => $id]);
    }
}
```

## Propagated dependency

In cases a Dependency exists only to pass it on to another class, this might become an issue.

```php
class UserHandler {
    protected $userRepository;

    public function __construct(DbAdapter $adapter) {
        $this->userRepository = new UserRepository($adapter);
    }
}
```

The solution, again, is simple: move the dependency to where it belongs.

```php
class UserHandler {
    protected $userRepository;

    public function __construct(UserRepository $repository) {
        $this->userRepository = $repository;
    }
}
```

## Long constructor definition

This becomes an issue quite easily, and it's one of the harder anti-patterns to battle.

```php
class UserHandler {
    public function __construct(UserRepository $repository, GroupRepository $groups, Logger $logger, Config $config, Application $application) {
    }
}
```

The issue is generally remedied by determining what your class is actually doing. It might be doing too much (as in violating the Single Responsibility Principle). You could probably refactor your application to minimize what classes do, and with that, the dependencies.

## Testing with Container

If you're using a Container object in your tests, there's probably something wrong, and it's probably caused by Container Dependency. This shouldn't be the case, and it's solved by listing concrete dependencies instead of only the Container. It would also make mocking dependencies a lot easier.


text:
import logging
from collections import OrderedDict
from time import sleep
from decimal import Decimal
from random import random

from django.conf import settings
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from localflavor.se.forms import SEPersonalIdentityNumberField
import stripe
from rest_framework import serializers
from rest_framework.reverse import reverse
from rest_framework_expandable import ExpandableSerializerMixin
from rest_framework_jwt.utils import jwt_payload_handler as original_jwt_payload_handler

from . import exceptions, models

logger = logging.getLogger(__name__)

def jwt_payload_handler(user):
    payload = original_jwt_payload_handler(user)
    payload['name'] = user.get_full_name()
    payload['nin'] = user.nin
    return payload

class EventSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Event
        fields = [
            'url',
            'id',
            'slug',
            'name',
            'description',
            'organization'
        ]

class OrganizationSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Organization
        fields = [
            'url',
            'id',
            'name',
            'organization_number',
            'address',
            'email'
        ]

class PurchasePaymentSerializer(serializers.Serializer):
    # Hard coded to Stripe for the time being.
    type = serializers.ChoiceField(choices=(('stripe', _('Stripe')),))
    payload = serializers.CharField()
    amount = serializers.DecimalField(max_digits=9, decimal_places=2)

class PurchaseTicketSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Ticket
        fields = (
            'url',
            'id',
            'ticket_type',
            'variation_choices'
        )
        extra_kwargs = {
            'ticket_type': {
                # Don't filter on general availability! We might have access
                # codes.
                'queryset': models.TicketType.objects.published()
            }
        }

    def validate(self, attrs):
        if (list(models.Variation.objects.filter(choices__in=attrs['variation_choices']).distinct()) != list(attrs['ticket_type'].variations.all()) or len(attrs['variation_choices']) != attrs['ticket_type'].variations.count()):
            raise exceptions.InvalidVariationChoices(_('Invalid variation choices.'))

        return attrs

class PurchaseTransactionSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Transaction
        fields = (
            'amount',
        )

class PurchaseMessageSerializer(serializers.Serializer):
    code = serializers.CharField()
    text = serializers.CharField()
    entity = serializers.CharField()

class PurchaseUserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.User
        fields = (
            'nin',
        )
        extra_kwargs = {
            'nin': {'max_length': 13}  # Allow YYYYMMDD-XXXX
        }

    def validate_nin(self, value):
        return SEPersonalIdentityNumberField(required=False, coordination_number=False).clean(value=value)

class PurchaseSerializer(serializers.Serializer):
    tickets = PurchaseTicketSerializer(
        many=True,
        allow_empty=False)

    # Request only
    access_codes = serializers.SlugRelatedField(
        write_only=True,
        many=True,
        slug_field='token',
        queryset=models.AccessCode.objects.utilizable(),
        allow_empty=True)
    payment = PurchasePaymentSerializer(
        write_only=True)
    user = PurchaseUserSerializer(
        write_only=True)

    # Response only
    messages = PurchaseMessageSerializer(
        read_only=True,
        many=True,
        allow_empty=True)
    transactions = PurchaseTransactionSerializer(
        read_only=True,
        many=True,
        allow_null=True)

    def validate_tickets(self, value):
        used_ticket_type_ids = [t.get('ticket_type').id for t in value]

        # We only want exactly one organization. Many organizations *can* be
        # handled but implicates troubles if payment to one organization
        # succeeds but not to another.
        if models.Organization.objects.filter(
            events__ticket_types__id__in=used_ticket_type_ids
        ).distinct().count() != 1:
            raise exceptions.MultipleOrganizations()

        if models.TicketType.objects.filter(
            id__in=used_ticket_type_ids,
            conflicts_with__id__in=used_ticket_type_ids
        ).exists():
            raise exceptions.ConflictingTicketTypes()

        return value

    def create(self, validated_data):
        # * Validate ticket types according to general avail. and access code
        # * Create ticket objects
        # * Charge with Stripe
        # * Rollback transaction if Stripe fails

        response_data = OrderedDict((
            ('tickets', []),
            ('transactions', []),
            ('messages', [])
        ))

        request = self.context['request']
        user = request.user

        tickets_data = validated_data.get('tickets')
        # We've already validated there is only one organization in play here.
        organization = tickets_data[0]['ticket_type'].event.organization

        unclear_tickets = set()
        safe_tickets = set()
        lost_tickets = set()

        with transaction.atomic():
            for ticket_data in tickets_data:
                for access_code in validated_data.get('access_codes'):
                    if access_code and access_code.ticket_type == ticket_data['ticket_type']:
                        ticket_data['access_code'] = access_code
                # Keeping M2M until we have saved
                variation_choices = ticket_data.pop('variation_choices')
                ticket = models.Ticket.objects.create(pending=True, **ticket_data)
                ticket.variation_choices.set(variation_choices)
                models.TicketOwnership.objects.create(ticket=ticket, user=user)
                unclear_tickets.add(ticket)
        try:
            while True:
                for ticket in unclear_tickets:
                    if not ticket.ticket_type.is_generally_available:
                        # Ticket type not available for purchase
                        if not ticket.access_code:
                            lost_tickets.add(ticket)
                            response_data['messages'].append(dict(
                                code='ticket_type_unavailable',
                                text=_("The ticket type '{}' is not available for purchase.".format(
                                        ticket.ticket_type.name)),
                                entity=reverse('tickettype-detail', kwargs={
                                    'pk': ticket.ticket_type_id}, request=request)))
                            continue

                        # Access code is supplied, has an impact on availability
                        # and is utilized by a ticket before this one.
                        if ticket.access_code and ticket.access_code.tickets.before_in_queue(ticket=ticket).exists():
                            lost_tickets.add(ticket)
                            response_data['messages'].append(OrderedDict((
                                ('code', 'access_code_utilized'),
                                ('text', _("The access code is already utilized."))
                            )))
                            continue

                    if models.Ticket.objects.filter(ticket_type__conflicts_with=ticket.ticket_type).before_in_queue(ticket=ticket).owned_by(user).exists():
                        lost_tickets.add(ticket)
                        response_data['messages'].append(dict(
                            code='ticket_type_conflicting',
                            text=_('The ticket type conflicts with another ticket of yours.'),
                            entity=reverse('tickettype-detail', kwargs={'pk': ticket.ticket_type_id}, request=request)
                        ))
                        continue

                    # No tickets left
                    if not ticket.ticket_type.within_max_total_quantity:
                        lost_tickets.add(ticket)
                        response_data['messages'].append(OrderedDict((
                            ('code', 'ticket_type_max_total_quantity_exceeded'),
                            ('text', _("There are no tickets of the type '{}' left.".format(ticket.ticket_type.name))),
                            ('entity', reverse('tickettype-detail', kwargs={'pk': ticket.ticket_type_id}, request=request))
                        )))
                        continue

                    if ticket.ticket_type.max_personal_quantity and ticket.ticket_type.tickets.before_in_queue(ticket=ticket).owned_by(user).count() >= ticket.ticket_type.max_personal_quantity:
                        lost_tickets.add(ticket)
                        response_data['messages'].append(OrderedDict((
                            ('code', 'ticket_type_max_personal_quantity_exceeded'),
                            ('text', _(
                                "You have reached your personal limit for the ticket type '{}'.".format(
                                    ticket.ticket_type.name))),
                            ('entity', reverse('tickettype-detail', kwargs={
                                'pk': ticket.ticket_type_id}, request=request))
                        )))
                        continue

                    max_total_quantity = ticket.ticket_type.max_total_quantity
                    position = ticket.ticket_type.tickets.before_in_queue(ticket=ticket).count()

                    # position is zero-indexed
                    if not max_total_quantity or position < max_total_quantity:
                        # Since the position never gets higher, we now know that
                        # this ticket is safe. Great!
                        safe_tickets.add(ticket)
                        continue

                    # Everything above this position will be discarded.
                    cutoff_position = 2 * max_total_quantity - ticket.ticket_type.tickets.unpending().count()

                    # Cutting off randomly (although weighted) up to the point
                    # where there are as many pending over the maximum quantity
                    # as under it. (Beneath this point all are discarded)
                    if random() <= (
                            (position - max_total_quantity) /
                            (cutoff_position - max_total_quantity or 0.001)  # Save us from ZeroDivisionError
                            ) ** 3:  # Make it much harder near the cutoff
                        lost_tickets.add(ticket)
                        response_data['messages'].append(OrderedDict((
                            ('code', 'bad_queue_position'),
                            ('text', _(
                                "You didn't get a good enough queue position to get the ticket '{}'.".format(
                                    ticket.ticket_type.name))),
                            ('entity', reverse('tickettype-detail', kwargs={
                                'pk': ticket.ticket_type_id}, request=request))
                        )))
                        continue

                unclear_tickets = unclear_tickets.difference(safe_tickets,
                                                             lost_tickets)

                # Delete all lost tickets so we release the positions to
                # concurrent buyers
                for ticket in lost_tickets:
                    ticket.delete()
                lost_tickets.clear()

                if unclear_tickets:
                    # Wait for a while and retry.
                    sleep(0.5)
                    continue
                else:
                    # We know every ticket's destiny.
                    break

        except Exception as exc:
            # Something went really wrong and we must clean up the mess before
            # raising the exception.
            for ticket in unclear_tickets | safe_tickets | lost_tickets:
                ticket.delete()

            raise exc

        if safe_tickets:
            charge_amount = Decimal(0)

            for ticket in safe_tickets:
                # There should be one ownership per ticket, hence get()
                charge_amount += ticket.ownerships.get().price

            try:
                assert charge_amount <= validated_data['payment']['amount']

                charge = stripe.Charge.create(
                    stripe_account=organization.stripe_account_id,
                    source=validated_data['payment']['payload'],
                    amount=int(charge_amount * 100),
                    currency=settings.CURRENCY,
                    receipt_email=user.email,
                    metadata=dict(
                        bitket_ticket_ownerships=','.join(map(lambda x: str(x.ownerships.get().pk), safe_tickets))
                    )
                )
            except Exception as exc:
                # Something went wrong and we must clean up the mess.
                for ticket in safe_tickets:
                    ticket.delete()

                if isinstance(exc, stripe.error.CardError):
                    # See https://stripe.com/docs/api#errors
                    error = exc.json_body['error']
                    raise exceptions.PaymentFailed(error['message'])

                raise exc

            purchase_transaction = models.Transaction.objects.create(
                amount=charge_amount,
                stripe_charge=charge.id
            )
            response_data['transactions'].append(purchase_transaction)

            # Must be done before sending the confirmation emails
            user.nin = validated_data['user']['nin']
            user.save()

            for ticket in safe_tickets:
                ticket.pending = False
                ticket_ownership = ticket.ownerships.latest()
                purchase_transaction.ticket_ownerships.add(ticket_ownership)
                ticket.save()
                response_data['tickets'].append(ticket)
                try:
                    ticket_ownership.email_confirmation()
                except Exception as exc:
                    # This should not stop us.
                    logger.exception('Exception during mail send')

        return response_data

class TicketSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Ticket
        fields = [
            'url',
            'id',
            'ticket_type',
            'variation_choices',
            'utilized'
        ]

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.User
        fields = [
            'url',
            'id',
            'name',
            'email'
        ]

class PrivilegedUserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.User
        fields = [
            'url',
            'id',
            'name',
            'nin',
            'email'
        ]

class TicketOwnershipSerializer(ExpandableSerializerMixin,
                                serializers.HyperlinkedModelSerializer):
    resell_token = serializers.SerializerMethodField()
    qr = serializers.SerializerMethodField()
    price = serializers.DecimalField(max_digits=9, decimal_places=2)
    utilized = serializers.SerializerMethodField()

    class Meta:
        model = models.TicketOwnership
        fields = [
            'url',
            'id',
            'ticket',
            'user',
            'code',
            'qr',
            'price',
            'resell_token',
            'is_current',
            'utilized'
        ]
        expandable_fields = {
            'ticket': (TicketSerializer, list(), dict()),
            'user': (PrivilegedUserSerializer, list(), dict())
        }

    def get_qr(self, obj):
        if obj.is_current:
            return b'data:image/png;base64,' + obj.get_qr()
        return None

    def get_resell_token(self, obj):
        if self.context['request'].user != obj.user:
            return None
        return obj.resell_token

    def get_utilized(self, obj):
        return obj.ticket.utilized

class VariationChoiceSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.VariationChoice
        fields = [
            'url',
            'id',
            'variation',
            'name',
            'delta',
            'index'
        ]

class VariationSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Variation
        fields = [
            'url',
            'id',
            'ticket_type',
            'name',
            'index'
        ]

class _VariationSerializer(VariationSerializer):
    choices = VariationChoiceSerializer(many=True)

    class Meta:
        model = models.Variation
        fields = [
            'url',
            'id',
            'name',
            'choices'
        ]

class AccessCodeSerializer(serializers.HyperlinkedModelSerializer):
    token = serializers.SerializerMethodField()

    class Meta:
        model = models.AccessCode
        fields = [
            'token',
            'ticket_type',
        ]

    def get_token(self, obj):
        return self.context['view'].kwargs.get('token', obj.token)

class TicketTypeSerializer(serializers.HyperlinkedModelSerializer):
    modifiers = serializers.SerializerMethodField()
    availability = serializers.SerializerMethodField()

    class Meta:
        model = models.TicketType
        fields = [
            'url',
            'id',
            'event',
            'name',
            'description',
            'price',
            'modifiers',
            'availability',
            'conflicts_with',
            'index'
        ]

    def get_availability(self, obj):
        return OrderedDict((
            ('general', obj.is_generally_available),
            ('total_quantity', obj.within_max_total_quantity)
        ))

    def get_modifiers(self, obj):
        class _ModifierSerializer(serializers.ModelSerializer):
            condition = serializers.SerializerMethodField()

            class Meta:
                model = models.Modifier
                fields = [
                    'condition',
                    'delta'
                ]

            def get_condition(self, obj):
                return '{}'.format(obj.condition_subclass)

        user = self.context['request'].user
        modifiers = obj.modifiers.eligible(user).select_related('condition')
        serializer = _ModifierSerializer(modifiers, read_only=True, many=True)
        return serializer.data


text:
using System.Linq;
using NUnit.Framework;
using SevenDigital.Api.Schema;
using SevenDigital.Api.Schema.Tags;

namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.TagsEndpoint
{
	[TestFixture]
	public class ReleaseByTagNewTests
	{
		[Test]
		public void Can_hit_endpoint()
		{

			ReleaseByTagNew tags = Api<ReleaseByTagNew>.Create
				.WithParameter("tags", "rock")
				.Please();

			Assert.That(tags, Is.Not.Null);
			Assert.That(tags.TaggedReleases.Count, Is.GreaterThan(0));
			Assert.That(tags.Type, Is.EqualTo(ItemType.release));
			Assert.That(tags.TaggedReleases.FirstOrDefault().Release.Title, Is.Not.Empty);
		}

		[Test]
		public void Can_hit_endpoint_with_paging()
		{

			ReleaseByTagNew artistBrowse = Api<ReleaseByTagNew>.Create
				.WithParameter("tags", "rock")
				.WithParameter("page", "2")
				.WithParameter("pageSize", "20")
				.Please();

			Assert.That(artistBrowse, Is.Not.Null);
			Assert.That(artistBrowse.Page, Is.EqualTo(2));
			Assert.That(artistBrowse.PageSize, Is.EqualTo(20));
		}
	}
}


text:
<?php

namespace SelectOptionTree\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class SelectOptionTreeController extends AbstractActionController
{
    public function indexAction()
    {
        return array();
    }

    public function fooAction()
    {
        // This shows the :controller and :action parameters in default route
        // are working when you browse to /selectOptionTree/select-option-tree/foo
        return array();
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.container.model;

/**
 * AcceleratorConfig represents a Hardware Accelerator request.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Kubernetes Engine API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class AcceleratorConfig extends com.google.api.client.json.GenericJson {

  /**
   * The number of the accelerator cards exposed to an instance.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long acceleratorCount;

  /**
   * The accelerator type resource name. List of supported accelerators [here](/compute/docs/gpus)
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String acceleratorType;

  /**
   * The number of the accelerator cards exposed to an instance.
   * @return value or {@code null} for none
   */
  public java.lang.Long getAcceleratorCount() {
    return acceleratorCount;
  }

  /**
   * The number of the accelerator cards exposed to an instance.
   * @param acceleratorCount acceleratorCount or {@code null} for none
   */
  public AcceleratorConfig setAcceleratorCount(java.lang.Long acceleratorCount) {
    this.acceleratorCount = acceleratorCount;
    return this;
  }

  /**
   * The accelerator type resource name. List of supported accelerators [here](/compute/docs/gpus)
   * @return value or {@code null} for none
   */
  public java.lang.String getAcceleratorType() {
    return acceleratorType;
  }

  /**
   * The accelerator type resource name. List of supported accelerators [here](/compute/docs/gpus)
   * @param acceleratorType acceleratorType or {@code null} for none
   */
  public AcceleratorConfig setAcceleratorType(java.lang.String acceleratorType) {
    this.acceleratorType = acceleratorType;
    return this;
  }

  @Override
  public AcceleratorConfig set(String fieldName, Object value) {
    return (AcceleratorConfig) super.set(fieldName, value);
  }

  @Override
  public AcceleratorConfig clone() {
    return (AcceleratorConfig) super.clone();
  }

}


text:
========
Usage
========

To use pystamps in a project::

    import pystamps


text:
/*

 CEUtils.h

 CotEditor
 http://coteditor.com

 Created by nakamuxu on 2014-04-20.

 ------------------------------------------------------------------------------

 © 2004-2007 nakamuxu
 © 2014-2015 1024jp

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 */

@import Foundation;

@interface CEUtils : NSObject

/// returns substitute character for invisible space to display
+ (unichar)invisibleSpaceChar:(NSUInteger)index;

/// returns substitute character for invisible tab character to display
+ (unichar)invisibleTabChar:(NSUInteger)index;

/// returns substitute character for invisible new line character to display
+ (unichar)invisibleNewLineChar:(NSUInteger)index;

/// returns substitute character for invisible full-width to display
+ (unichar)invisibleFullwidthSpaceChar:(NSUInteger)index;

/// returns corresponding NSStringEncoding from a encoding name
+ (NSStringEncoding)encodingFromName:(nonnull NSString *)encodingName;

/// whether Yen sign (U+00A5) can be converted to the given encoding
+ (BOOL)isInvalidYenEncoding:(NSStringEncoding)encoding;

/// returns string form keyEquivalent (keyboard shortcut) for menu item
+ (nonnull NSString *)keyEquivalentAndModifierMask:(nonnull NSUInteger *)modifierMask
                                        fromString:(nonnull NSString *)string
                               includingCommandKey:(BOOL)needsIncludingCommandKey;

@end


text:
package org.kairosdb.core;

/**
 Created by bhawkins on 5/19/17.
 */
public class PluginException extends Exception
{
	public PluginException()
	{
	}

	public PluginException(String pluginName, String message)
	{
		super("Exception in "+pluginName+": "+message);
	}

	public PluginException(String pluginName, String message, Throwable cause)
	{
		super("Exception in "+pluginName+": "+message, cause);
	}
}


text:
package com.ledpixelart.pixelesque;

import android.graphics.Color;

public class PixelArtState {
	public final static int PENCIL = 1;
	public final static int ERASER = 2;
	public final static int LINE = 3;
	public final static int RECTANGLE = 4;
	public final static int RECTANGLE_FILL = 40;
	public final static int CIRCLE = 6;
	public final static int CIRCLE_FILL = 60;
	public final static int BUCKET = 7;
	public final static int DRAW = 5;

	public int mode = DRAW;

	public int selectedColor = Color.CYAN;

}


text:
#include "SocketsBaseDialog.h"
#include <eikbtgpc.h>
#include <eikseced.h>
#include <eikmfne.h>
#include <eikedwin.h>

CSocketsBaseDialog::CSocketsBaseDialog(CMessageHandler& aAppUi)
: iAppUi(aAppUi)
    {
    }

void CSocketsBaseDialog::SetTextL(TInt aControl, const TDesC& aText)
    {
    // Copy text into an edwin type control
    static_cast<CEikEdwin*>(Control(aControl))->SetTextL(&aText);
    Control(aControl)->DrawNow();
    }

void CSocketsBaseDialog::SetSecretText(TInt aControl, const TDesC& aText)
    {
    // Copy text into a secret editor type control
    static_cast<CEikSecretEditor*>(Control(aControl))->SetText(aText);
    Control(aControl)->DrawNow();
    }

void CSocketsBaseDialog::SetNumber(TInt aControl, TInt aNumber)
    {
    // Copy number into a number editor type control
    static_cast<CEikNumberEditor*>(Control(aControl))->SetNumber(aNumber);
    Control(aControl)->DrawNow();
    }

void CSocketsBaseDialog::GetText(TInt aControl, TDes& aText)
    {
    // Copy text out of an edwin type control
    static_cast<CEikEdwin*>(Control(aControl))->GetText(aText);
    }

void CSocketsBaseDialog::GetSecretText(TInt aControl, TDes& aText)
    {
    // Copy text out of a secret editor type control
    static_cast<CEikSecretEditor*>(Control(aControl))->GetText(aText);
    }

TInt CSocketsBaseDialog::GetNumber(TInt aControl)
    {
    // Copy number out of a number editor type control
    return static_cast<CEikNumberEditor*>(Control(aControl))->Number();
    }

CMessageHandler& CSocketsBaseDialog::AppUi() const
    {
    return(iAppUi);
    }


text:
from BisApp import app, db, models
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView

admin = Admin(app, name='BiSTeca', template_mode='bootstrap3')
admin.add_view(ModelView(models.Usuario, db.session))
admin.add_view(ModelView(models.Emprestimo, db.session))
admin.add_view(ModelView(models.Exemplar, db.session))
admin.add_view(ModelView(models.Autor, db.session))
admin.add_view(ModelView(models.Contato, db.session))

if __name__ == '__main__':
    app.run()


text:
import React, { ReactNode, useState } from 'react';

import styles from '../index.module.css';
import { useTabs } from '../lib/tabs';
import { TabsHeader, TabsItem } from './Tabs';
import { TogglerHeader, TogglerItem } from './Toggler';

export type TogglerTabsProps<T extends TabsItem, U extends TogglerItem> = {
  children: (args: { tab: T; toggle: U }) => ReactNode;
  group: string;
  tabsItems: T[];
  togglerItems: U[];
};

export function TogglerTabs<T extends TabsItem, U extends TogglerItem>({
  children,
  group,
  tabsItems,
  togglerItems,
}: TogglerTabsProps<T, U>) {
  const { activeTab, onTab } = useTabs(group);
  const [activeToggle, setStateToggler] = useState(0);

  const handleTogglerClick = (toggle: number) => () => {
    setStateToggler(toggle);
  };

  return (

        <TabsHeader items={tabsItems} onTab={onTab} activeTab={activeTab} />
        <TogglerHeader
          items={togglerItems}
          onClick={handleTogglerClick}
          activeToggle={activeToggle}
        />

      {children({
        tab: tabsItems[activeTab],
        toggle: togglerItems[activeToggle],
      })}

  );
}


text:
/**
 * Created by Edward Luna Noriega on 02/10/17.
 */

"use strict";

const connection = require('../services/connection');

module.exports = name => {

    const sequelize = connection[name];

    return {
        today: () => {

            return sequelize.query(
                'EXEC [SP].[ruta] @fecha = :fecha',
                {
                    nest: true,
                    replacements: {fecha: new Date()},
                    type: sequelize.QueryTypes.SELECT
                });

        },
        reporte: (fecha, fletero) => {

            return sequelize.query(
                'EXEC [SP].[rutas] @fecha = :fecha, @fletero = :fletero',
                {
                    nest: true,
                    replacements: {fecha: fecha, fletero: fletero},
                    type: sequelize.QueryTypes.SELECT
                });

        },
        despacho_generico: (fecha_inicial = new Date(), fecha_final = new Date(),ruta = null) => {
            return sequelize.query(
                'EXEC [RR].[despacho_generico] @fecha_inicial = :fecha_inicial, @fecha_final = :fecha_final, @ruta = :ruta',
                {
                    nest: true,
                    replacements: {fecha_inicial: fecha_inicial, fecha_final: fecha_final, ruta: ruta},
                    type: sequelize.QueryTypes.SELECT
                });
        },
        despacho_linea: (fecha_inicial = new Date(), fecha_final = new Date(),ruta = null) => {
            return sequelize.query(
                'EXEC [RR].[despacho_linea] @fecha_inicial = :fecha_inicial, @fecha_final = :fecha_final, @ruta = :ruta',
                {
                    nest: true,
                    replacements: {fecha_inicial: fecha_inicial, fecha_final: fecha_final, ruta: ruta},
                    type: sequelize.QueryTypes.SELECT
                });
        },
        despacho_proveedor: (fecha_inicial = new Date(), fecha_final = new Date(),ruta = null) => {
            return sequelize.query(
                'EXEC [RR].[despacho_proveedor] @fecha_inicial = :fecha_inicial, @fecha_final = :fecha_final, @ruta = :ruta',
                {
                    nest: true,
                    replacements: {fecha_inicial: fecha_inicial, fecha_final: fecha_final, ruta: ruta},
                    type: sequelize.QueryTypes.SELECT
                });
        }
    };
};


text:
package com.marklogic.client.test.example.handle;

import static org.junit.Assert.assertTrue;

import java.io.IOException;

import org.junit.Test;

import com.marklogic.client.example.handle.URIHandleExample;

public class URIHandleTest {
  @Test
  public void testMain() {
    boolean succeeded = false;
    try {
      URIHandleExample.main(new String[0]);
      succeeded = true;
    } catch (IOException e) {
      e.printStackTrace();
    }
    assertTrue("URIHandleExample failed", succeeded);
  }
}


text:
<?php

namespace Symfony\Component\Form;

use Symfony\Component\Form\ValueTransformer\BooleanToStringTransformer;

/**
 * An input field for selecting boolean values.
 *
 * @author Bernhard Schussek <bernhard.schussek@symfony.com>
 */
abstract class ToggleField extends Field
{
    /**
     * {@inheritDoc}
     */
    protected function configure()
    {
        $this->addOption('value');

        parent::configure();

        $this->setValueTransformer(new BooleanToStringTransformer());
    }

    public function isChecked()
    {
        return $this->getData();
    }

    public function getValue()
    {
        return $this->getOption('value');
    }

    public function hasValue()
    {
        return $this->getValue() !== null;
    }
}


text:
namespace Lipisha.Response
{
    public class SMSReport : BaseResponse
    {
        private const string RECIPIENT_KEY = "recipient";
        private const string COST_KEY = "cost";
        private const string MESSAGE_KEY = "message";

        public string getMessage ()
        {
            string message = "";
            contentResponse.TryGetValue(MESSAGE_KEY, out message);
            return message;
        }

        public string getRecipient ()
        {
            string recipient = "";
            contentResponse.TryGetValue(RECIPIENT_KEY, out recipient);
            return recipient;
        }

        public double getCost()
        {
            string cost = "0.00";
            contentResponse.TryGetValue(COST_KEY, out cost);
            if (string.IsNullOrEmpty(cost)) {
                cost = "0.00";
            }
            return double.Parse(cost);
        }
    }
}


text:
ACCEPTED

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

#### Published in
null

#### Original name
Hedyotis yapensis Kaneh.

### Remarks
null


text:
package assembly.data.loader;

import assembly.data.peptide.DenovoPeptide;

import java.io.File;
import java.util.List;

public interface ResultLoader {
    List<DenovoPeptide> load(File[] files);
}


text:
package net.sf.microlog.core;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;

import net.sf.microlog.core.appender.ConsoleAppender;
import net.sf.microlog.core.format.PatternFormatter;

/**
 * The Logger class is used for logging.
 *
 * This is similar to the Log4j Logger class. The method names are
 * the same, but we do not claim that they are 100% compatible.
 *
 * You have the ability to use named loggers as in Log4j. If you want to save
 * memory, you could use unnamed loggers.
 *
 * @author Johan Karlsson (johan.karlsson@jayway.se)
 * @author Darius Katz
 * @author Karsten Ohme
 * @since 0.1
 */
public final class Logger {

	public static final Level DEFAULT_LOG_LEVEL = Level.DEBUG;

	private String clientID;

	private String name;

	private Level level;

	private static final StopWatch stopWatch = new StopWatch();

	private final static Vector appenderList = new Vector(4);

	private static boolean firstLogEvent = true;

	/**
	 * Create a logger with the specified name. The
	 * LoggerFactory should be used for creating
	 * Logger objects.
	 *
	 * @param name
	 *            the name of the logger.
	 */
	Logger(String name) {
		this.name = name;
	}

	/**
	 * Get the log level.
	 *
	 * @return the log Level.
	 */
	public Level getLevel() {
		return level;
	}

	/**
	 * Set the log level.
	 *
	 * @param level
	 *            The logLevel to set.
	 * @throws IllegalArgumentException
	 *             if the level is null.
	 */
	public void setLevel(Level level) throws IllegalArgumentException {
		if (level == null) {
			throw new IllegalArgumentException("The level must not be null.");
		}
		this.level = level;
	}

	/**
	 * Get the effective log level. If we have a hierarchy of loggers, this is
	 * searched to get the effective level.
	 *
	 * @return the effective logger level.
	 */
	public Level getEffectiveLevel() {
		Level effectiveLevel = this.level;

		if (effectiveLevel == null && !name.equals("")) {
			effectiveLevel = DefaultLoggerRepository.getInstance()
					.getEffectiveLevel(this);
		}

		return effectiveLevel;
	}

	/**
	 * Get the client ID.
	 *
	 * @return the clientID
	 */
	public String getClientID() {
		return clientID;
	}

	/**
	 * Set the client ID.
	 *
	 * @param clientID
	 *            the clientID to set
	 */
	public void setClientID(String clientID) {
		this.clientID = clientID;
	}

	/**
	 * Get the name of the Logger.
	 *
	 * @return the name of the Logger.
	 */
	public String getName() {
		return name;
	}

	/**
	 * Add the specified appender to the output appenders.
	 *
	 * @param appender
	 *            the Appender to add.
	 * @throws IllegalArgumentException
	 *             if the appender is null.
	 */
	public void addAppender(Appender appender) throws IllegalArgumentException {
		if (appender == null) {
			throw new IllegalArgumentException(
					"Appender not allowed to be null");
		}

		if (!appenderList.contains(appender)) {
			appenderList.addElement(appender);
		}
	}

	/**
	 * Remove the specified appender from the appender list.
	 *
	 * @param appender
	 *            the Appender to remove.
	 */
	public void removeAppender(Appender appender)
			throws IllegalArgumentException {
		if (appender == null) {
			throw new IllegalArgumentException("The appender must not be null.");
		}

		if (appender.isLogOpen()) {
			try {
				appender.close();
			} catch (IOException e) {
				System.err.println("Failed to close appender. " + e);
			}
		}
		appenderList.removeElement(appender);
	}

	/**
	 * Remove all the appenders.
	 *
	 */
	public void removeAllAppenders() {
		for (Enumeration enumeration = appenderList.elements(); enumeration
				.hasMoreElements();) {
			Appender appender = (Appender) enumeration.nextElement();
			if (appender.isLogOpen()) {
				try {
					appender.close();
				} catch (IOException e) {
					System.err.println("Failed to close appender. " + e);
				}
			}
		}
		appenderList.removeAllElements();
	}

	/**
	 * Get the number of appenders.
	 *
	 * @return the number of appenders.
	 */
	public int getNumberOfAppenders() {
		return appenderList.size();
	}

	/**
	 * Get the specified appender, starting at index = 0.
	 *
	 * @param index
	 *            the index of the appender.
	 * @return the appender.
	 */
	public Appender getAppender(int index) {
		return (Appender) appenderList.elementAt(index);
	}

	/**
	 * Log the message at the specified level.
	 *
	 * @param level
	 *            the Level to log at.
	 * @param message
	 *            the message to log.
	 * @throws IllegalArgumentException
	 *             if the level is null.
	 */
	public void log(Level level, Object message)
			throws IllegalArgumentException {
		this.log(level, message, null);
	}

	/**
	 * Log the message and the Throwable object at the specified level.
	 *
	 * @param level
	 *            the log level
	 * @param message
	 *            the message to log.
	 * @param t
	 *            the Throwable object.
	 * @throws IllegalArgumentException
	 *             if the level is null.
	 */
	public void log(Level level, Object message, Throwable t)
			throws IllegalArgumentException {
		if (level == null) {
			throw new IllegalArgumentException("The level must not be null.");
		}

		if (getEffectiveLevel().levelValue <= level.levelValue) {
			int nofAppenders = appenderList.size();

			if (firstLogEvent == true) {
				if (nofAppenders == 0) {
					System.err
							.println("Warning! No appender is set, using ConsoleAppender with PatternFormatter");
					Appender appender = new ConsoleAppender();
					appender.setFormatter(new PatternFormatter());
					addAppender(appender);
					nofAppenders++;
				}

				try {
					open();
				} catch (IOException e) {
					System.err.println("Failed to open the log. " + e);
				}

				stopWatch.start();
				firstLogEvent = false;
			}

			for (int index = 0; index < nofAppenders; index++) {
				Appender appender = (Appender) appenderList.elementAt(index);
				appender.doLog(clientID, name, stopWatch.getCurrentTime(),
						level, message, t);
			}
		}
	}

	/**
	 * Is this Logger enabled for TRACE level?
	 *
	 * @return true if logging is enabled.
	 */
	public boolean isTraceEnabled() {
		Level effectiveLevel = getEffectiveLevel();
		return effectiveLevel.levelValue <= Level.TRACE_INT;
	}

	/**
	 * Log the message at Level.TRACE level.
	 *
	 * @param message
	 *            the message to log.
	 */
	public void trace(Object message) {
		log(Level.TRACE, message, null);
	}

	/**
	 * Log the message and the Throwable object at
	 * Level.TRACE.
	 *
	 * @param message
	 *            the message to log.
	 * @param t
	 *            the Throwable object to log.
	 */
	public void trace(Object message, Throwable t) {
		log(Level.TRACE, message, t);
	}

	/**
	 * Is this Logger enabled for DEBUG level?
	 *
	 * @return true if logging is enabled.
	 */
	public boolean isDebugEnabled() {
		Level effectiveLevel = getEffectiveLevel();
		return effectiveLevel.levelValue <= Level.DEBUG_INT;
	}

	/**
	 * Log the message at Level.DEBUG level.
	 *
	 * @param message
	 *            the message to log.
	 */
	public void debug(Object message) {
		log(Level.DEBUG, message, null);
	}

	/**
	 * Log the message and the Throwable object at
	 * Level.DEBUG level.
	 *
	 * @param message
	 *            the message to log.
	 * @param t
	 *            the Throwable object to log.
	 */
	public void debug(Object message, Throwable t) {
		log(Level.DEBUG, message, t);
	}

	/**
	 * Is this Logger enabled for INFO level?
	 *
	 * @return true if the Level.INFO level is enabled.
	 */
	public boolean isInfoEnabled() {
		Level effectiveLevel = getEffectiveLevel();
		return effectiveLevel.levelValue <= Level.INFO_INT;
	}

	/**
	 * Log the specified message at Level.INFO level.
	 *
	 * @param message
	 *            the message to log.
	 */
	public void info(Object message) {
		log(Level.INFO, message, null);
	}

	/**
	 * Log the specified message and the Throwable at
	 * Level.INFO level.
	 *
	 * @param message
	 *            the message to log.
	 * @param t
	 *            the Throwable to log.
	 */
	public void info(Object message, Throwable t) {
		log(Level.INFO, message, t);
	}

	/**
	 * Is this Logger enabled for Level.WARN level?
	 *
	 * @return true if WARN level is enabled.
	 */
	public boolean isWarnEnabled() {
		Level effectiveLevel = getEffectiveLevel();
		return effectiveLevel.levelValue <= Level.WARN_INT;
	}

	/**
	 * Log the specified message at Level.WARN level.
	 *
	 * @param message
	 *            the message to log.
	 */
	public void warn(Object message) {
		log(Level.WARN, message, null);
	}

	/**
	 * Log the specified message and Throwable object at
	 * Level.WARN level.
	 *
	 * @param message
	 *            the object to log.
	 * @param t
	 *            the Throwable to log.
	 */
	public void warn(Object message, Throwable t) {
		log(Level.WARN, message, t);
	}

	/**
	 * Is this LOGGER enabled for ERROR level?
	 *
	 * @return true if the ERROR level is enabled.
	 */
	public boolean isErrorEnabled() {
		Level effectiveLevel = getEffectiveLevel();
		return effectiveLevel.levelValue <= Level.ERROR_INT;
	}

	/**
	 * Log the specified message at ERROR level.
	 *
	 * @param message
	 *            the object to log.
	 */
	public void error(Object message) {
		log(Level.ERROR, message, null);
	}

	/**
	 * Log the specified message and Throwable object at ERROR level.
	 *
	 * @param message
	 *            the object to log.
	 * @param t
	 *            the Throwable to log.
	 */
	public void error(Object message, Throwable t) {
		log(Level.ERROR, message, t);
	}

	/**
	 * Is this LOGGER enabled for FATAL level?
	 *
	 * @return true if the FATAL level is enabled.
	 */
	public boolean isFatalEnabled() {
		Level effectiveLevel = getEffectiveLevel();
		return effectiveLevel.levelValue <= Level.FATAL_INT;
	}

	/**
	 * Log the specified message at FATAL level.
	 *
	 * @param message
	 *            the object to log.
	 */
	public void fatal(Object message) {
		log(Level.FATAL, message, null);
	}

	/**
	 * Log the specified message and Throwable object at FATAL level.
	 *
	 * @param message
	 *            the object to log.
	 * @param t
	 *            the Throwable to log.
	 */
	public void fatal(Object message, Throwable t) {
		log(Level.FATAL, message, t);
	}

	/**
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(super.toString());
		stringBuffer.append('[');

		int nofAppenders = appenderList.size();
		for (int index = 0; index < nofAppenders; index++) {
			Appender appender = (Appender) appenderList.elementAt(index);
			stringBuffer.append(appender);
			stringBuffer.append(';');
		}
		stringBuffer.append(']');
		return stringBuffer.toString();
	}

	/**
	 * Reset the Logger, i.e. remove all appenders and set the log level to the
	 * default level.
	 */
	synchronized void resetLogger() {
		Logger.appenderList.removeAllElements();
		Logger.stopWatch.stop();
		Logger.stopWatch.reset();
		firstLogEvent = true;
	}

	/**
	 * Open the log. The logging is now turned on.
	 */
	void open() throws IOException {

		int nofAppenders = appenderList.size();
		for (int index = 0; index < nofAppenders; index++) {
			Appender appender = (Appender) appenderList.elementAt(index);
			appender.open();
		}

	}

	/**
	 * Close the log. From this point on, no logging is done.
	 *
	 * @throws IOException
	 *             if the Logger failed to close.
	 */
	void close() throws IOException {
		int nofAppenders = appenderList.size();
		for (int index = 0; index < nofAppenders; index++) {
			Appender appender = (Appender) appenderList.elementAt(index);
			appender.close();
		}
		stopWatch.stop();
		Logger.firstLogEvent = true;
	}
}


text: Testbed repository for various odds and ends


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Torrey bot. Club 70: 579 (1943)

#### Original name
Aecidium rutideae Cummins

### Remarks
null


text:
package com.siyeh.ig.threading;

import javax.annotation.Nonnull;

import com.intellij.psi.*;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.psiutils.SynchronizationUtil;

public class PublicFieldAccessedInSynchronizedContextInspection extends BaseInspection {

  @Nonnull
  public String getDisplayName() {
    return InspectionGadgetsBundle.message("public.field.accessed.in.synchronized.context.display.name");
  }

  @Nonnull
  public String getID() {
    return "NonPrivateFieldAccessedInSynchronizedContext";
  }

  @Nonnull
  protected String buildErrorString(Object... infos) {
    return InspectionGadgetsBundle.message("public.field.accessed.in.synchronized.context.problem.descriptor");
  }

  public BaseInspectionVisitor buildVisitor() {
    return new PublicFieldAccessedInSynchronizedContextVisitor();
  }

  private static class PublicFieldAccessedInSynchronizedContextVisitor extends BaseInspectionVisitor {

    @Override
    public void visitReferenceExpression(@Nonnull PsiReferenceExpression expression) {
      final PsiExpression qualifier = expression.getQualifierExpression();
      if (qualifier != null && !(qualifier instanceof PsiThisExpression) && !(qualifier instanceof PsiSuperExpression)) {
        return;
      }
      final PsiElement element = expression.resolve();
      if (!(element instanceof PsiField)) {
        return;
      }
      final PsiField field = (PsiField)element;
      if (field.hasModifierProperty(PsiModifier.PRIVATE) || field.hasModifierProperty(PsiModifier.FINAL)) {
        return;
      }
      if (!SynchronizationUtil.isInSynchronizedContext(expression)) {
        return;
      }
      final PsiClass containingClass = field.getContainingClass();
      if (containingClass == null || containingClass.hasModifierProperty(PsiModifier.PRIVATE)) {
        return;
      }
      registerError(expression);
    }
  }
}


text:
@class Model;

@interface ViewController : UIViewController

//pod trunk push --use-libraries

@end

@interface Model : NSObject

@property (nonatomic, assign) NSInteger age;
@property (nonatomic, assign) NSInteger userId;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *nickname;

@end


text:
---
title: Analytics
---

ExoPlayer supports a wide range of playback analytics needs. Ultimately,
analytics is about collecting, interpreting, aggregating and summarizing data
from playbacks. This data can be used either on the device, for example for
logging, debugging, or to inform future playback decisions, or reported to a
server to monitor playbacks across all devices.

An analytics system usually needs to collect events first, and then process them
further to make them meaningful:

* **Event collection**:
  This can be done by registering an `AnalyticsListener` on an `ExoPlayer`
  instance. Registered analytics listeners receive events as they occur during
  usage of the player. Each event is associated with the corresponding media
  item in the playlist, as well as playback position and timestamp metadata.
* **Event processing**:
  Some analytics systems upload raw events to a server, with all event
  processing performed server-side. It's also possible to process events on the
  device, and doing so may be simpler or reduce the amount of information that
  needs to be uploaded. ExoPlayer provides `PlaybackStatsListener`, which
  allows you to perform the following processing steps:
  1. **Event interpretation**: To be useful for analytics purposes, events need
     to be interpreted in the context of a single playback. For example the raw
     event of a player state change to `STATE_BUFFERING` may correspond to
     initial buffering, a rebuffer, or buffering that happens after a seek.
  1. **State tracking**: This step converts events to counters. For example,
     state change events can be converted to counters tracking how much time is
     spent in each playback state. The result is a basic set of analytics data
     values for a single playback.
  1. **Aggregation**: This step combines the analytics data across multiple
     playbacks, typically by adding up counters.
  1. **Calculation of summary metrics**: Many of the most useful metrics are
     those that compute averages or combine the basic analytics data values in
     other ways. Summary metrics can be calculated for single or multiple
     playbacks.

## Event collection with AnalyticsListener ##

Raw playback events from the player are reported to `AnalyticsListener`
implementations. You can easily add your own listener and override only the
methods you are interested in:

~~~
exoPlayer.addAnalyticsListener(new AnalyticsListener() {
    @Override
    public void onPlaybackStateChanged(
        EventTime eventTime, @Player.State int state) {
    }

    @Override
    public void onDroppedVideoFrames(
        EventTime eventTime, int droppedFrames, long elapsedMs) {
    }
});
~~~
{: .language-java}

The `EventTime` that's passed to each callback associates the event to a media
item in the playlist, as well as playback position and timestamp metadata:

* `realtimeMs`: The wall clock time of the event.
* `timeline`, `windowIndex` and `mediaPeriodId`: Defines the playlist and the
  item within the playlist to which the event belongs. The `mediaPeriodId`
  contains optional additional information, for example indicating whether the
  event belongs to an ad within the item.
* `eventPlaybackPositionMs`: The playback position in the item when the event
  occurred.
* `currentTimeline`, `currentWindowIndex`, `currentMediaPeriodId` and
  `currentPlaybackPositionMs`: As above but for the currently playing item. The
  currently playing item may be different from the item to which the event
  belongs, for example if the event corresponds to pre-buffering of the next
  item to be played.

## Event processing with PlaybackStatsListener ##

`PlaybackStatsListener` is an `AnalyticsListener` that implements on device
event processing. It calculates `PlaybackStats`, with counters and derived
metrics including:

* Summary metrics, for example the total playback time.
* Adaptive playback quality metrics, for example the average video resolution.
* Rendering quality metrics, for example the rate of dropped frames.
* Resource usage metrics, for example the number of bytes read over the network.

You will find a complete list of the available counts and derived metrics in the
[`PlaybackStats` Javadoc][].

`PlaybackStatsListener` calculates separate `PlaybackStats` for each media item
in the playlist, and also each client-side ad inserted within these items. You
can provide a callback to `PlaybackStatsListener` to be informed about finished
playbacks, and use the `EventTime` passed to the callback to identify which
playback finished. It's possible to [aggregate the analytics data][] for
multiple playbacks. It's also possible to query the `PlaybackStats` for the
current playback session at any time using
`PlaybackStatsListener.getPlaybackStats()`.

~~~
exoPlayer.addAnalyticsListener(
    new PlaybackStatsListener(
        /* keepHistory= */ true, (eventTime, playbackStats) -> {
          // Analytics data for the session started at `eventTime` is ready.
        }));
~~~
{: .language-java}

The constructor of `PlaybackStatsListener` gives the option to keep the full
history of processed events. Note that this may incur an unknown memory overhead
depending on the length of the playback and the number of events. Therefore you
should only turn it on if you need access to the full history of processed
events, rather than just to the final analytics data.

Note that `PlaybackStats` uses an extended set of states to indicate not only
the state of the media, but also the user intention to play and more detailed
information such as why playback was interrupted or ended:

| Playback state | User intention to play  | No intention to play |
|:---|:---|:---|
| Before playback | `JOINING_FOREGROUND` | `NOT_STARTED`, `JOINING_BACKGROUND` |
| Active playback | `PLAYING` | |
| Interrupted playback | `BUFFERING`, `SEEKING` | `PAUSED`, `PAUSED_BUFFERING`, `SUPPRESSED`, `SUPPRESSED_BUFFERING`, `INTERRUPTED_BY_AD` |
| End states | | `ENDED`, `STOPPED`, `FAILED`, `ABANDONED` |

The user intention to play is important to distinguish times when the user was
actively waiting for playback to continue from passive wait times. For example,
`PlaybackStats.getTotalWaitTimeMs` returns the total time spent in the
`JOINING_FOREGROUND`, `BUFFERING` and `SEEKING` states, but not the time when
playback was paused. Similarly, `PlaybackStats.getTotalPlayAndWaitTimeMs` will
return the total time with a user intention to play, that is the total active
wait time and the total time spent in the `PLAYING` state.

### Processed and interpreted events ###

You can record processed and interpreted events by using `PlaybackStatsListener`
with `keepHistory=true`. The resulting `PlaybackStats` will contain the
following event lists:

* `playbackStateHistory`: An ordered list of extended playback states with
  the `EventTime` at which they started to apply. You can also use
  `PlaybackStats.getPlaybackStateAtTime` to look up the state at a given wall
  clock time.
* `mediaTimeHistory`: A history of wall clock time and media time pairs allowing
  you to reconstruct which parts of the media were played at which time. You can
  also use `PlaybackStats.getMediaTimeMsAtRealtimeMs` to look up the playback
  position at a given wall clock time.
* `videoFormatHistory` and `audioFormatHistory`: Ordered lists of video and
  audio formats used during playback with the `EventTime` at which they started
  to be used.
* `fatalErrorHistory` and `nonFatalErrorHistory`: Ordered lists of fatal and
  non-fatal errors with the `EventTime` at which they occurred. Fatal errors are
  those that ended playback, whereas non-fatal errors may have been recoverable.

### Single-playback analytics data ###

This data is automatically collected if you use `PlaybackStatsListener`, even
with `keepHistory=false`. The final values are the public fields that you can
find in the [`PlaybackStats` Javadoc][] and the playback state durations
returned by `getPlaybackStateDurationMs`. For convenience, you'll also find
methods like `getTotalPlayTimeMs` and `getTotalWaitTimeMs` that return the
duration of specific playback state combinations.

~~~
Log.d("DEBUG", "Playback summary: "
    + "play time = " + playbackStats.getTotalPlayTimeMs()
    + ", rebuffers = " + playbackStats.totalRebufferCount);
~~~
{: .language-java}

Some values like `totalVideoFormatHeightTimeProduct` are only useful when
calculating derived summary metrics like the average video height, but are
required to correctly combine multiple `PlaybackStats` together.
{:.info}

### Aggregate analytics data of multiple playbacks ###

You can combine multiple `PlaybackStats` together by calling
`PlaybackStats.merge`. The resulting `PlaybackStats` will contain the aggregated
data of all merged playbacks. Note that it won't contain the history of
individual playback events, since these cannot be aggregated.

`PlaybackStatsListener.getCombinedPlaybackStats` can be used to get an
aggregated view of all analytics data collected in the lifetime of a
`PlaybackStatsListener`.

### Calculated summary metrics ###

In addition to the basic analytics data, `PlaybackStats` provides many methods
to calculate summary metrics.

~~~
Log.d("DEBUG", "Additional calculated summary metrics: "
    + "average video bitrate = " + playbackStats.getMeanVideoFormatBitrate()
    + ", mean time between rebuffers = "
        + playbackStats.getMeanTimeBetweenRebuffers());
~~~
{: .language-java}

## Advanced topics ##

### Associating analytics data with playback metadata ###

When collecting analytics data for individual playbacks, you may wish to
associate the playback analytics data with metadata about the media being
played.

It's advisable to set media-specific metadata with `MediaItem.Builder.setTag`.
The media tag is part of the `EventTime` reported for raw events and when
`PlaybackStats` are finished, so it can be easily retrieved when handling the
corresponding analytics data:

~~~
new PlaybackStatsListener(
    /* keepHistory= */ false, (eventTime, playbackStats) -> {
      Object mediaTag =
          eventTime.timeline.getWindow(eventTime.windowIndex, new Window())
              .mediaItem.localConfiguration.tag;
      // Report playbackStats with mediaTag metadata.
    });
~~~
{: .language-java}

### Reporting custom analytics events ###

In case you need to add custom events to the analytics data, you need to save
these events in your own data structure and combine them with the reported
`PlaybackStats` later. If it helps, you can extend `AnalyticsCollector` to be
able to generate `EventTime` instances for your custom events and send them to
the already registered listeners as shown in the following example.

~~~
interface ExtendedListener extends AnalyticsListener {
  void onCustomEvent(EventTime eventTime);
}

class ExtendedCollector extends AnalyticsCollector {
 public void customEvent() {
   EventTime eventTime = generateCurrentPlayerMediaPeriodEventTime();
   sendEvent(eventTime, CUSTOM_EVENT_ID, listener -> {
     if (listener instanceof ExtendedListener) {
       ((ExtendedListener) listener).onCustomEvent(eventTime);
     }
   });
 }
}

// Usage - Setup and listener registration.
ExoPlayer player = new ExoPlayer.Builder(context)
    .setAnalyticsCollector(new ExtendedCollector())
    .build();
player.addAnalyticsListener(new ExtendedListener() {
  @Override
  public void onCustomEvent(EventTime eventTime) {
    // Save custom event for analytics data.
  }
});
// Usage - Triggering the custom event.
((ExtendedCollector) player.getAnalyticsCollector()).customEvent();
~~~
{: .language-java}

[`PlaybackStats` Javadoc]: {{ site.exo_sdk }}/analytics/PlaybackStats.html
[aggregate the analytics data]: {{ site.baseurl }}/analytics.html#aggregate-analytics-data-of-multiple-playbacks


text:
class FvVersionComparatorTest : public QObject
{
	Q_OBJECT

public slots:

	void runAll();

	void testNumbers();
	void testPrereleases();
	void testVersionsWithBuildNumbers();

};

#endif // FVVERSIONCOMPARATORTEST_H


text:
module UserInfo
  extend ActiveSupport::Concern

  def display_name
    name.presence || username.presence || "Someone"
  end

  def github_path
    if username
      "https://github.com/#{username}"
    end
  end

  def update_me!(params)
    raise "Name is required!" unless params[:name].present?
    self.name = params[:name]
    self.email = params[:email]

    if really_admin?
      if params[:incognito] == "true" && !(role =~ /\Aincognito_/)
        self.role = "incognito_#{role}"
      elsif params[:incognito].blank? && role =~ /\Aincognito_/
        self.role[/\Aincognito_/] = ""
      end
    end

    save!
  end

  # Common methods
  def admin?
    super_admin? || role == "admin"
  end

  def anonymous?
    role == "anonymous"
  end

  def incognito_admin?
    role == "incognito_admin" || role == "incognito_super_admin"
  end

  def really_admin?
    incognito_admin? || admin?
  end

  def super_admin?
    role == "super_admin"
  end

  module Anonymous
    extend ActiveSupport::Concern
    include UserInfo

    def id
      nil
    end

    def display_name
      "anonymous"
    end

    def github_path
      nil
    end

    def role
      "anonymous"
    end

    def update_me!(params)
      raise PermissionError.new
    end
  end
end