text:
import random
import socket
import re

INVALID_KEY = re.compile(r'[\x00-\x1F]|\s|\x7F', re.IGNORECASE)
TERMINAL = '\r\n'
BUFSIZE = 4096
MAX_KEY_LEN = 250

class MemClientError(Exception):
    pass

class MemServerError(Exception):
    pass

class MemClient(object):

    def __init__(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def connect(self, host, port):
        self.socket.connect((host, port))

    def _check_key(self, key):
        '''
        length <= 250
        no control character or whitespace
        '''
        if not isinstance(key, basestring):
            raise MemClientError('key must be str or unicode')
        if isinstance(key, unicode):
            key = key.encode('utf-8')
        if len(key) > MAX_KEY_LEN:
            raise MemClientError('key is too long (less than 250 characters)')
        res = INVALID_KEY.search(key)
        if res is not None:
            raise MemClientError('key contains control characters or whitespace')
        return key

    def _check_value(self, value, value_type=basestring):
        if not isinstance(value, value_type):
            raise MemClientError('value must be %s' % (value_type,))
        if isinstance(value, unicode):
            value = value.encode('utf-8')
        return value

    # storage commands
    def _storage_command(self, command, key, value, expire, noreply, cas_unique=None):
        key = self._check_key(key)
        value = self._check_value(value)

        num_bytes = len(value)
        flags = random.randint(0, (1 << 16) - 1)

        meta = [command, key, str(flags), str(expire), str(num_bytes)]
        if cas_unique:
            meta.append(cas_unique)
        if noreply is True:
            meta.append('noreply')
        header = ' '.join(meta)
        padding = ''
        request = TERMINAL.join((header, value, padding))
        res = self.socket.sendall(request)
        if res is None and noreply is False:
            data = self.socket.recv(BUFSIZE)
        else:
            raise MemClientError('execute command %s failed' % command)

    def set(self, key, value, expire=0, noreply=True):
        return self._storage_command('set', key, value, expire, noreply)

    def add(self, key, value, expire=0, noreply=True):
        return self._storage_command('add', key, value, expire, noreply)

    def replace(self, key, value, expire=0, noreply=True):
        return self._storage_command('replace', key, value, expire, noreply)

    def append(self, key, value, noreply=True):
        return self._storage_command('append', key, value, 0, noreply)

    def prepend(self, key, value, noreply=True):
        return self._storage_command('prepend', key, value, 0, noreply)

    def cas(self, key, value, cas_unique, expire=0, noreply=True):
        raise NotImplemented

    # retrieval commands
    def _retrieval_command(self, command, keylist):
        keymap = {}
        for i in range(len(keylist)):
            keylist[i] = self._check_key(keylist[i])
            keymap[keylist[i]] = None

        keystr = ' '.join(keymap.keys())
        header = ' '.join((command, keystr))
        padding = ''
        request = TERMINAL.join((header, padding))
        res = self.socket.sendall(request)
        if res is None:
            data = self.socket.recv(BUFSIZE)
            while not data.endswith('END\r\n'):
                part = self.socket.recv(BUFSIZE)
                data = ''.join((data, part))
            blocks = data.split(TERMINAL)[:-2]
            for i in range(0, len(blocks), 2):
                header = blocks[i].split()
                raw = blocks[i + 1]
                if len(raw) != int(header[3]):
                    raise MemServerError('incomplete value for %s' % header[1])
                if len(header) == 5:
                    keymap[header[1]] = (raw, long(header[4]))
                else:
                    keymap[header[1]] = raw
            values = [keymap[key] for key in keylist]
            return values
        else:
            raise ClientError('execute command %s failed' % command)

    def get(self, key, *args):
        return self._retrieval_command('get', [key] + list(args))

    def gets(self, key, *args):
        return self._retrieval_command('gets', [key] + list(args))

    def _send_command(self, command, key, value=None, noreply=True):
        meta = [command, key]
        if value is not None:
            meta.append(value)
        if noreply  is True:
            meta.append('noreply')
        header = ' '.join(meta)
        padding = ''
        request = TERMINAL.join((header, padding))
        res = self.socket.sendall(request)
        if res is None and noreply is False:
            data = self.socket.recv(BUFSIZE)
        else:
            raise MemClientError('execute command %s failed' % command)

    # other commands
    def delete(self, key, noreply=True):
        key = self._check_key(key)
        self._send_command('delete', key, noreply=noreply)

    def incr(self, key, value, noreply=True):
        key = self._check_key(key)
        value = self._check_value(value, value_type=(int, long))
        self._send_command('incr', key, value, noreply)

    def decr(self, key, value, noreply=True):
        key = self._check_key(key)
        value = self._check_value(value, value_type=(int, long))
        self._send_command('decr', key, value, noreply)

    def touch(self, key, expire, noreply=True):
        key = self._check_key(key)
        self._send_command('touch', key, str(expire), noreply=noreply)

    def slabs_reassign(self, source, dest):
        raise NotImplemented

    def slabs_automove(self, indicator):
        raise NotImplemented

    def lru_crawler(self, enabled=True):
        raise NotImplemented

    def lru_crawler_sleep(self, ms):
        raise NotImplemented

    def lru_crawler_tocrawl(self, num):
        raise NotImplemented

    def lru_crawler_crawl(self, classid, *args, **kwargs):
        raise NotImplemented

    def stats(self):
        stat = {}
        header = 'stats'
        padding = ''
        request = TERMINAL.join((header, padding))
        res = self.socket.sendall(request)
        if res is None:
            data = self.socket.recv(BUFSIZE)
            while not data.endswith('END\r\n'):
                part = self.socket.recv(BUFSIZE)
                data = ''.join((data, part))
            blocks = data.split(TERMINAL)[:-2]
            for item in blocks:
                _, key, value = item.split(' ', 2)
                stat[key] = value
        else:
            raise MemClientError('execute command %s failed' % command)
        return stat

    def stats_settings(self):
        raise NotImplemented

    def stats_items(self):
        raise NotImplemented

    def stats_sizes(self):
        raise NotImplemented

    def stats_slabs(self):
        raise NotImplemented

    def stats_conns(self):
        raise NotImplemented

    def flush_all(self, delay=0, noreply=True):
        self._send_command('flush_all', str(delay), noreply=noreply)

    def version(self):
        header = 'version'
        padding = ''
        request = TERMINAL.join((header, padding))
        res = self.socket.sendall(request)
        if res is None:
            data = self.socket.recv(BUFSIZE)
            return data[8:-2]
        else:
            raise MemClientError('execute command %s failed' % command)

    def verbosity(self, log_level=3, noreply=True):
        self._send_command('verbosity', str(log_level), noreply=noreply)

    def quit(self):
        header = 'quit'
        padding = ''
        request = TERMINAL.join((header, padding))
        self.socket.sendall(request)
        self.socket.close()
        # self.socket.fileno() # socket.error: [Errno 9] Bad file descriptor

if __name__ == '__main__':
    client = MemClient()
    client.connect('127.0.0.1', 11211)
    client.set('foo', 'bar', noreply=False)
    print client.get('foo')
    print client.version()
    client.flush_all(delay=5, noreply=False)
    client.quit()


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/protobuf/unittest_drop_unknown_fields.proto

#ifndef PROTOBUF_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto__INCLUDED
#define PROTOBUF_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto__INCLUDED

#include <string>

#include <google/protobuf/stubs/common.h>

#if GOOGLE_PROTOBUF_VERSION < 3001000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please update
#error your headers.
#endif
#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please
#error regenerate this file with a newer version of protoc.
#endif

#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/generated_enum_reflection.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)

namespace unittest_drop_unknown_fields {

// Internal implementation detail -- do not call these.
void protobuf_AddDesc_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto();
void protobuf_InitDefaults_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto();

class Foo;
class FooWithExtraFields;

enum Foo_NestedEnum {
  Foo_NestedEnum_FOO = 0,
  Foo_NestedEnum_BAR = 1,
  Foo_NestedEnum_BAZ = 2,
  Foo_NestedEnum_Foo_NestedEnum_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min,
  Foo_NestedEnum_Foo_NestedEnum_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max
};
bool Foo_NestedEnum_IsValid(int value);
const Foo_NestedEnum Foo_NestedEnum_NestedEnum_MIN = Foo_NestedEnum_FOO;
const Foo_NestedEnum Foo_NestedEnum_NestedEnum_MAX = Foo_NestedEnum_BAZ;
const int Foo_NestedEnum_NestedEnum_ARRAYSIZE = Foo_NestedEnum_NestedEnum_MAX + 1;

const ::google::protobuf::EnumDescriptor* Foo_NestedEnum_descriptor();
inline const ::std::string& Foo_NestedEnum_Name(Foo_NestedEnum value) {
  return ::google::protobuf::internal::NameOfEnum(
    Foo_NestedEnum_descriptor(), value);
}
inline bool Foo_NestedEnum_Parse(
    const ::std::string& name, Foo_NestedEnum* value) {
  return ::google::protobuf::internal::ParseNamedEnum<Foo_NestedEnum>(
    Foo_NestedEnum_descriptor(), name, value);
}
enum FooWithExtraFields_NestedEnum {
  FooWithExtraFields_NestedEnum_FOO = 0,
  FooWithExtraFields_NestedEnum_BAR = 1,
  FooWithExtraFields_NestedEnum_BAZ = 2,
  FooWithExtraFields_NestedEnum_QUX = 3,
  FooWithExtraFields_NestedEnum_FooWithExtraFields_NestedEnum_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min,
  FooWithExtraFields_NestedEnum_FooWithExtraFields_NestedEnum_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max
};
bool FooWithExtraFields_NestedEnum_IsValid(int value);
const FooWithExtraFields_NestedEnum FooWithExtraFields_NestedEnum_NestedEnum_MIN = FooWithExtraFields_NestedEnum_FOO;
const FooWithExtraFields_NestedEnum FooWithExtraFields_NestedEnum_NestedEnum_MAX = FooWithExtraFields_NestedEnum_QUX;
const int FooWithExtraFields_NestedEnum_NestedEnum_ARRAYSIZE = FooWithExtraFields_NestedEnum_NestedEnum_MAX + 1;

const ::google::protobuf::EnumDescriptor* FooWithExtraFields_NestedEnum_descriptor();
inline const ::std::string& FooWithExtraFields_NestedEnum_Name(FooWithExtraFields_NestedEnum value) {
  return ::google::protobuf::internal::NameOfEnum(
    FooWithExtraFields_NestedEnum_descriptor(), value);
}
inline bool FooWithExtraFields_NestedEnum_Parse(
    const ::std::string& name, FooWithExtraFields_NestedEnum* value) {
  return ::google::protobuf::internal::ParseNamedEnum<FooWithExtraFields_NestedEnum>(
    FooWithExtraFields_NestedEnum_descriptor(), name, value);
}
// ===================================================================

class Foo : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:unittest_drop_unknown_fields.Foo) */ {
 public:
  Foo();
  virtual ~Foo();

  Foo(const Foo& from);

  inline Foo& operator=(const Foo& from) {
    CopyFrom(from);
    return *this;
  }

  static const ::google::protobuf::Descriptor* descriptor();
  static const Foo& default_instance();

  static const Foo* internal_default_instance();

  void Swap(Foo* other);

  // implements Message ----------------------------------------------

  inline Foo* New() const { return New(NULL); }

  Foo* New(::google::protobuf::Arena* arena) const;
  void CopyFrom(const ::google::protobuf::Message& from);
  void MergeFrom(const ::google::protobuf::Message& from);
  void CopyFrom(const Foo& from);
  void MergeFrom(const Foo& from);
  void Clear();
  bool IsInitialized() const;

  size_t ByteSizeLong() const;
  bool MergePartialFromCodedStream(
      ::google::protobuf::io::CodedInputStream* input);
  void SerializeWithCachedSizes(
      ::google::protobuf::io::CodedOutputStream* output) const;
  ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
      bool deterministic, ::google::protobuf::uint8* output) const;
  ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const {
    return InternalSerializeWithCachedSizesToArray(false, output);
  }
  int GetCachedSize() const { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const;
  void InternalSwap(Foo* other);
  void UnsafeMergeFrom(const Foo& from);
  private:
  inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
    return _internal_metadata_.arena();
  }
  inline void* MaybeArenaPtr() const {
    return _internal_metadata_.raw_arena_ptr();
  }
  public:

  ::google::protobuf::Metadata GetMetadata() const;

  // nested types ----------------------------------------------------

  typedef Foo_NestedEnum NestedEnum;
  static const NestedEnum FOO =
    Foo_NestedEnum_FOO;
  static const NestedEnum BAR =
    Foo_NestedEnum_BAR;
  static const NestedEnum BAZ =
    Foo_NestedEnum_BAZ;
  static inline bool NestedEnum_IsValid(int value) {
    return Foo_NestedEnum_IsValid(value);
  }
  static const NestedEnum NestedEnum_MIN =
    Foo_NestedEnum_NestedEnum_MIN;
  static const NestedEnum NestedEnum_MAX =
    Foo_NestedEnum_NestedEnum_MAX;
  static const int NestedEnum_ARRAYSIZE =
    Foo_NestedEnum_NestedEnum_ARRAYSIZE;
  static inline const ::google::protobuf::EnumDescriptor*
  NestedEnum_descriptor() {
    return Foo_NestedEnum_descriptor();
  }
  static inline const ::std::string& NestedEnum_Name(NestedEnum value) {
    return Foo_NestedEnum_Name(value);
  }
  static inline bool NestedEnum_Parse(const ::std::string& name,
      NestedEnum* value) {
    return Foo_NestedEnum_Parse(name, value);
  }

  // accessors -------------------------------------------------------

  // optional int32 int32_value = 1;
  void clear_int32_value();
  static const int kInt32ValueFieldNumber = 1;
  ::google::protobuf::int32 int32_value() const;
  void set_int32_value(::google::protobuf::int32 value);

  // optional .unittest_drop_unknown_fields.Foo.NestedEnum enum_value = 2;
  void clear_enum_value();
  static const int kEnumValueFieldNumber = 2;
  ::unittest_drop_unknown_fields::Foo_NestedEnum enum_value() const;
  void set_enum_value(::unittest_drop_unknown_fields::Foo_NestedEnum value);

  // @@protoc_insertion_point(class_scope:unittest_drop_unknown_fields.Foo)
 private:

  ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
  ::google::protobuf::int32 int32_value_;
  int enum_value_;
  mutable int _cached_size_;
  friend void  protobuf_InitDefaults_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto_impl();
  friend void  protobuf_AddDesc_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto_impl();
  friend void protobuf_AssignDesc_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto();
  friend void protobuf_ShutdownFile_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto();

  void InitAsDefaultInstance();
};
extern ::google::protobuf::internal::ExplicitlyConstructed<Foo> Foo_default_instance_;

// -------------------------------------------------------------------

class FooWithExtraFields : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:unittest_drop_unknown_fields.FooWithExtraFields) */ {
 public:
  FooWithExtraFields();
  virtual ~FooWithExtraFields();

  FooWithExtraFields(const FooWithExtraFields& from);

  inline FooWithExtraFields& operator=(const FooWithExtraFields& from) {
    CopyFrom(from);
    return *this;
  }

  static const ::google::protobuf::Descriptor* descriptor();
  static const FooWithExtraFields& default_instance();

  static const FooWithExtraFields* internal_default_instance();

  void Swap(FooWithExtraFields* other);

  // implements Message ----------------------------------------------

  inline FooWithExtraFields* New() const { return New(NULL); }

  FooWithExtraFields* New(::google::protobuf::Arena* arena) const;
  void CopyFrom(const ::google::protobuf::Message& from);
  void MergeFrom(const ::google::protobuf::Message& from);
  void CopyFrom(const FooWithExtraFields& from);
  void MergeFrom(const FooWithExtraFields& from);
  void Clear();
  bool IsInitialized() const;

  size_t ByteSizeLong() const;
  bool MergePartialFromCodedStream(
      ::google::protobuf::io::CodedInputStream* input);
  void SerializeWithCachedSizes(
      ::google::protobuf::io::CodedOutputStream* output) const;
  ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
      bool deterministic, ::google::protobuf::uint8* output) const;
  ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const {
    return InternalSerializeWithCachedSizesToArray(false, output);
  }
  int GetCachedSize() const { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const;
  void InternalSwap(FooWithExtraFields* other);
  void UnsafeMergeFrom(const FooWithExtraFields& from);
  private:
  inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
    return _internal_metadata_.arena();
  }
  inline void* MaybeArenaPtr() const {
    return _internal_metadata_.raw_arena_ptr();
  }
  public:

  ::google::protobuf::Metadata GetMetadata() const;

  // nested types ----------------------------------------------------

  typedef FooWithExtraFields_NestedEnum NestedEnum;
  static const NestedEnum FOO =
    FooWithExtraFields_NestedEnum_FOO;
  static const NestedEnum BAR =
    FooWithExtraFields_NestedEnum_BAR;
  static const NestedEnum BAZ =
    FooWithExtraFields_NestedEnum_BAZ;
  static const NestedEnum QUX =
    FooWithExtraFields_NestedEnum_QUX;
  static inline bool NestedEnum_IsValid(int value) {
    return FooWithExtraFields_NestedEnum_IsValid(value);
  }
  static const NestedEnum NestedEnum_MIN =
    FooWithExtraFields_NestedEnum_NestedEnum_MIN;
  static const NestedEnum NestedEnum_MAX =
    FooWithExtraFields_NestedEnum_NestedEnum_MAX;
  static const int NestedEnum_ARRAYSIZE =
    FooWithExtraFields_NestedEnum_NestedEnum_ARRAYSIZE;
  static inline const ::google::protobuf::EnumDescriptor*
  NestedEnum_descriptor() {
    return FooWithExtraFields_NestedEnum_descriptor();
  }
  static inline const ::std::string& NestedEnum_Name(NestedEnum value) {
    return FooWithExtraFields_NestedEnum_Name(value);
  }
  static inline bool NestedEnum_Parse(const ::std::string& name,
      NestedEnum* value) {
    return FooWithExtraFields_NestedEnum_Parse(name, value);
  }

  // accessors -------------------------------------------------------

  // optional int32 int32_value = 1;
  void clear_int32_value();
  static const int kInt32ValueFieldNumber = 1;
  ::google::protobuf::int32 int32_value() const;
  void set_int32_value(::google::protobuf::int32 value);

  // optional .unittest_drop_unknown_fields.FooWithExtraFields.NestedEnum enum_value = 2;
  void clear_enum_value();
  static const int kEnumValueFieldNumber = 2;
  ::unittest_drop_unknown_fields::FooWithExtraFields_NestedEnum enum_value() const;
  void set_enum_value(::unittest_drop_unknown_fields::FooWithExtraFields_NestedEnum value);

  // optional int32 extra_int32_value = 3;
  void clear_extra_int32_value();
  static const int kExtraInt32ValueFieldNumber = 3;
  ::google::protobuf::int32 extra_int32_value() const;
  void set_extra_int32_value(::google::protobuf::int32 value);

  // @@protoc_insertion_point(class_scope:unittest_drop_unknown_fields.FooWithExtraFields)
 private:

  ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
  ::google::protobuf::int32 int32_value_;
  int enum_value_;
  ::google::protobuf::int32 extra_int32_value_;
  mutable int _cached_size_;
  friend void  protobuf_InitDefaults_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto_impl();
  friend void  protobuf_AddDesc_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto_impl();
  friend void protobuf_AssignDesc_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto();
  friend void protobuf_ShutdownFile_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto();

  void InitAsDefaultInstance();
};
extern ::google::protobuf::internal::ExplicitlyConstructed<FooWithExtraFields> FooWithExtraFields_default_instance_;

// ===================================================================

// ===================================================================

#if !PROTOBUF_INLINE_NOT_IN_HEADERS
// Foo

// optional int32 int32_value = 1;
inline void Foo::clear_int32_value() {
  int32_value_ = 0;
}
inline ::google::protobuf::int32 Foo::int32_value() const {
  // @@protoc_insertion_point(field_get:unittest_drop_unknown_fields.Foo.int32_value)
  return int32_value_;
}
inline void Foo::set_int32_value(::google::protobuf::int32 value) {

  int32_value_ = value;
  // @@protoc_insertion_point(field_set:unittest_drop_unknown_fields.Foo.int32_value)
}

// optional .unittest_drop_unknown_fields.Foo.NestedEnum enum_value = 2;
inline void Foo::clear_enum_value() {
  enum_value_ = 0;
}
inline ::unittest_drop_unknown_fields::Foo_NestedEnum Foo::enum_value() const {
  // @@protoc_insertion_point(field_get:unittest_drop_unknown_fields.Foo.enum_value)
  return static_cast< ::unittest_drop_unknown_fields::Foo_NestedEnum >(enum_value_);
}
inline void Foo::set_enum_value(::unittest_drop_unknown_fields::Foo_NestedEnum value) {

  enum_value_ = value;
  // @@protoc_insertion_point(field_set:unittest_drop_unknown_fields.Foo.enum_value)
}

inline const Foo* Foo::internal_default_instance() {
  return &Foo_default_instance_.get();
}
// -------------------------------------------------------------------

// FooWithExtraFields

// optional int32 int32_value = 1;
inline void FooWithExtraFields::clear_int32_value() {
  int32_value_ = 0;
}
inline ::google::protobuf::int32 FooWithExtraFields::int32_value() const {
  // @@protoc_insertion_point(field_get:unittest_drop_unknown_fields.FooWithExtraFields.int32_value)
  return int32_value_;
}
inline void FooWithExtraFields::set_int32_value(::google::protobuf::int32 value) {

  int32_value_ = value;
  // @@protoc_insertion_point(field_set:unittest_drop_unknown_fields.FooWithExtraFields.int32_value)
}

// optional .unittest_drop_unknown_fields.FooWithExtraFields.NestedEnum enum_value = 2;
inline void FooWithExtraFields::clear_enum_value() {
  enum_value_ = 0;
}
inline ::unittest_drop_unknown_fields::FooWithExtraFields_NestedEnum FooWithExtraFields::enum_value() const {
  // @@protoc_insertion_point(field_get:unittest_drop_unknown_fields.FooWithExtraFields.enum_value)
  return static_cast< ::unittest_drop_unknown_fields::FooWithExtraFields_NestedEnum >(enum_value_);
}
inline void FooWithExtraFields::set_enum_value(::unittest_drop_unknown_fields::FooWithExtraFields_NestedEnum value) {

  enum_value_ = value;
  // @@protoc_insertion_point(field_set:unittest_drop_unknown_fields.FooWithExtraFields.enum_value)
}

// optional int32 extra_int32_value = 3;
inline void FooWithExtraFields::clear_extra_int32_value() {
  extra_int32_value_ = 0;
}
inline ::google::protobuf::int32 FooWithExtraFields::extra_int32_value() const {
  // @@protoc_insertion_point(field_get:unittest_drop_unknown_fields.FooWithExtraFields.extra_int32_value)
  return extra_int32_value_;
}
inline void FooWithExtraFields::set_extra_int32_value(::google::protobuf::int32 value) {

  extra_int32_value_ = value;
  // @@protoc_insertion_point(field_set:unittest_drop_unknown_fields.FooWithExtraFields.extra_int32_value)
}

inline const FooWithExtraFields* FooWithExtraFields::internal_default_instance() {
  return &FooWithExtraFields_default_instance_.get();
}
#endif  // !PROTOBUF_INLINE_NOT_IN_HEADERS
// -------------------------------------------------------------------

// @@protoc_insertion_point(namespace_scope)

}  // namespace unittest_drop_unknown_fields

#ifndef SWIG
namespace google {
namespace protobuf {

template <> struct is_proto_enum< ::unittest_drop_unknown_fields::Foo_NestedEnum> : ::google::protobuf::internal::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::unittest_drop_unknown_fields::Foo_NestedEnum>() {
  return ::unittest_drop_unknown_fields::Foo_NestedEnum_descriptor();
}
template <> struct is_proto_enum< ::unittest_drop_unknown_fields::FooWithExtraFields_NestedEnum> : ::google::protobuf::internal::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::unittest_drop_unknown_fields::FooWithExtraFields_NestedEnum>() {
  return ::unittest_drop_unknown_fields::FooWithExtraFields_NestedEnum_descriptor();
}

}  // namespace protobuf
}  // namespace google
#endif  // SWIG

// @@protoc_insertion_point(global_scope)

#endif  // PROTOBUF_google_2fprotobuf_2funittest_5fdrop_5funknown_5ffields_2eproto__INCLUDED

redpajama_set_name: RedPajamaGithub


text:
IMPORTANT NOTE:
These examples may not work with more recent versions of ANGSD.
We will update everything when a stable final version of ANGSD will be available.
In doubt, please contact the authors for questions on the usage of ngsTools with the current version of ANGSD.

# ngsPopGen

Several tools to perform population genetic analyses from NGS data:
 * ` ngsFst`  - Quantificate population genetic differentiation
 * ` ngsCovar`  - Population structure via PCA (principal components analysis)
 * ` ngs2dSFS`  - Estimate 2D-SFS from posterior probabilities of sample allele frequencies
 * ` ngsStat`  - Estimates number of segregating sites, expected average heterozygosity, and number of fixed differences and Dxy (if 2 populations provided).

NOTE: In all analisis involving 2 populations, input data must refer to the exact same sites. If they differ (e.g. because of different filtering), use `GetSubSfs` ([ngsUtils](https://github.com/mfumagalli/ngsUtils)) to get an overlapping subset of sites for both populations (you can use .mafs file from ANGSD to get the corresponding coordinates).
For instance you can get the overlapping sites with (using ANGSD +0.579):

    gunzip -c file1.saf.pos.gz > A.saf.pos
    gunzip -c file2.saf.pos.gz > B.saf.pos
    awk 'FNR==NR {x[$1"_"$2]=NR; next} x[$1"_"$2] {print x[$1"_"$2]; print FNR > "/dev/stderr"}' A.saf.pos B.saf.pos >A.pos 2>B.pos
    rm A.saf.pos B.saf.pos

and then use `GetSubSfs` as:

    ./ngsTools/ngsUtils/GetSubSfs -infile file1.sin.saf -posfile A.pos -nind 7 -nsites 733744 -len 717017 -outfile file1.sin.fix.saf

and so on for the second file.
A quick trick to check that everything went fine is to retrieve the dimension of each file (using "ls -l"), then divide this number by 8 and then by the double of the number of individuals plus 1. You should get the final number of sites.

### Installation

    % git clone https://github.com/mfumagalli/ngsPopGen.git

To install these tools just run:

    % cd ngsPopGen
    % make
    % make test

Executables are built into the main directory. If you wish to clean all binaries and intermediate files:

    % make clean

---

## ngsFST

Program to estimate FST from NGS data. It computes expected genetic variance components and estimate per-site FST from those using methods-of-moments estimator. See Fumagalli et al. Genetics 2013 for more details.
In input it receives posterior probabilities of sample allele frequencies for each population. It may receive also a 2D-SFS as a prior and in this case it receives as input posterior probabilities with uniform prior (ANGSD with -realSFS 1 only, and then set -islog 1). You can give also 2 marginal spectra as priors.

The output is a tab-separated text file. Each row represents a site. Columns are labelled: A, AB, f, FST, Pvar; where A is the expectation of genetic variance between populations, AB is the expectation of the total genetic variance, f is the correcting factor for the ratio of expectations, FST is the per-site FST value, Pvar is the probability for the site of being variable.

### Usage
#### Examples:

 * using a 2D-SFS as a prior, estimated using ngs2dSFS (recommended if data is unfolded):

#

    % ./ngsFST -postfiles pop1.sfs pop2.sfs -priorfile spectrum2D.txt -nind 20 20 -nsites 100000 -block_size 20000 -outfile pops.fst -islog 1

 * using marginal spectra as priors, estimated using optimSFS (ANGSD):

#

    % ./ngsFST -postfiles pop1.sfs pop2.sfs -priorfiles spectrum1.txt spectrum2.txt -nind 20 20 -nsites 100000 -block_size 20000 -outfile pops.fst -islog 1

 * instead of prior files, we can also directly provide the posterior probabilities:

#

    % ./ngsFST -postfiles pop1.sfs.ml.norm pop2.sfs.ml.norm -nind 20 20 -nsites 100000 -block_size 20000 -outfile pops.fst -islog 0

* use posterior probabilities of allele frequencies from a uniform prior:

#

    % ./ngsFST -postfiles pop1.sfs pop2.sfs -nind 20 20 -nsites 100000 -block_size 20000 -outfile pops.fst -islog 1

#### Parameters:

    -postfiles: files with posterior probabilities of sample allele frequencies (.sfs or .saf) for each population
    -priorfile: 2D-SFS to be used as a prior; you can use ngs2dSfs with parameter -relative set to 1
    -priorfiles: 2 marginal spectra to be used as priors
    -nind: number of individuals for each population
    -nsites: total number of sites; in case of a site subset this is the upper limit
    -firstbase: in case of a site subset, this is the lower limit
    -isfold: boolean, is your data folded? You SHOULD not use this option! This will be deprecated soon.
    -islog: boolean, are postfiles in -log?
    -outfile: name of the output file
    -block_size: number of sites in each chunk (for memory reasons)
    -verbose: level of verbosity

NOTE: Currently, it is not possible to estimate a joint-SFS from folded data. Also, one should check whether each site has the same minor allele for both populations (hardly met for many cases), so `isfold` option will be removed soon for safety. Therefore, for _Fst_ estimation, a solution would be to use posterior probabilities of allele frequencies using the non-reference site frequency spectrum if the ancestral-derived polarization is not available.

---

## ngsCovar

Program to compute the expected correlation matrix between individuals from genotype posterior probabilities. It receives as input genotype posterior probabilities. It can receive in input also posterior probabilities of sample allele frequencies for computing the probability of each site to be variant.

### Usage

#### Examples:

* not calling genotypes and weighting by each site's probability of being variable (recommended if no SNP calling is performed and coverage is low):

#

    % ./ngsCovar -probfile pop.geno -outfile pop.covar -nind 40 -nsites 100000 -block_size 20000 -call 0 -norm 0 -sfsfile pop.sfs.ml.norm

* not calling genotypes:

#

    % ./ngsCovar -probfile pop.geno -outfile pop.covar -nind 40 -nsites 100000 -block_size 20000 -call 1

* calling genotypes and filtering out rare variants:

#

    % ./ngsCovar -probfile pop.geno -outfile pop.covar -nind 40 -nsites 100000 -block_size 20000 -call 1 -minmaf 0.05

#### Parameters:

    -probfile: file with genotype posterior probabilities
    -sfsfile: file with sample allele frequency posterior probabilities
    -nind: number of individuals
    -nsites: total number of sites; in case of a site subset this is the upper limit
    -offset: in case of a site subset, this is the lower limit
    -genoquality: text file with 'nsites' lines stating whether to use (1) or ignore (0) the site
    -norm: 0 [no normalization, recommended if no SNP calling is performed]
           1 [matrix is normalized by p(1-p) as in Patterson et al (2006)]
           2 [normalized by 2p(1-p)]
    -minmaf: ignore sites below this threshold of minor allele frequency
    -call: call genotypes based on the maximum posterior probability
    -isfold: boolean, is your data folded?
    -islog: boolean, are postfiles in -log?
    -outfile: name of output file
    -block_size: number of sites in each chunk (for memory reasons)
    -verbose: level of verbosity

---

## ngs2dSFS

Program to estimate 2D-SFS from posterior probabilities of sample allele frequencies. Output file reports the occurrence of sites at distinct joint allele frequencies. This spectrum is a (2N1+1)x(2N2+2) matrix with N1 and N2 number of individuals at the two populations. Please note that cells are zero-based ordered. As an example, value reported in the cell [4,3] represents the frequency of sites with allele frequency 3 and 2 at population 1 and 2 respectively.

#### Example:

    % ./ngs2dSFS -postfiles pop.sfs.ml.norm pop.sfs.ml.norm -outfile spectrum.txt -relative 1 -nind 20 20 -nsites 100000 -block_size 20000

#### Parameters:

    -postfiles: file with sample allele frequency posterior probabilities for each population
    -nind: number of individuals
    -nsites: total number of sites; in case of a site subset this is the upper limit
    -offset: in case of a site subset, this is the lower limit
    -outfile: name of output file
    -maxlike: compute the MLE as the sum across sites' joint allele frequency (1) or as the sum of the products of likelihoods (0)
    -relative: boolean, whether input are absolute counts of sites with a specific joint allele frequency (0) or relative frequencies (1)
    -block_size: memory efficiency, number of sites for each chunk

---

## ngsStat

Program to compute estimates of the number of segregating sites, the expected average heterozygosity, and the number of fixed differences (if 2 populations data is provided). It receives as input sample allele frequency posterior probabilities (from ANGSD) from 1 or 2 populations. Output is a text file with columns: start, end, segregating sites (pop 1), heterozygosity (pop 1), segregating sites (pop 2), heterozygosity (pop 2), fixed differences, dxy.

#### Example:

* 2 populations, sliding windows of 100 sites (latter recommended only if no missing data is present):

#

    ./ngsStat -npop 2 -postfiles pop1.sfs.norm pop2.sfs.norm -nsites 1000 -iswin 1 -nind 10 50 -islog 0 -outfile pops.stat -isfold 0 -verbose 0 -block_size 100

* 1 populations, sliding windows of 100 sites (latter recommended only if no missing data is present):

#

    ./ngsStat -npop 1 -postfiles pop1.sfs.norm -nsites 1000 -iswin 1 -nind 10 -islog 0 -outfile pops.stat -isfold 0 -verbose 0 -block_size 100

* 1 population, values estimated at each site (recommended in case of missing data):

#

    ./ngsStat -npop 1 -postfiles pop1.sfs.norm -nsites 1000 -iswin 0 -nind 10 -islog 0 -outfile pops.stat -isfold 0 -verbose 0

#### Parameters:

    -npop: number of populations (should be the first one to be specified)
    -postfiles: file with sample allele frequency posterior probabilities for each population
    -nind: number of individuals
    -nsites: total number of sites; in case of a site subset this is the upper limit
    -firstbase: in case of a site subset, this is the lower limit
    -isfold: boolean, is your data folded?
    -islog: boolean, are postfiles in -log?
    -iswin: if set to 1, chuncks are considered non-overlapping sliding-windows
    -outfile: name of output file
    -block_size: number of sites in each chunk (for memory reasons)
    -verbose: level of verbosity


text:
#pragma once

/**
 * Ó¦ÓÃÉèÖöԻ°¿ò
 */
class CSettingDlg : public CDialogEx
{
	DECLARE_DYNAMIC(CSettingDlg)

public:
	CSettingDlg(CWnd* pParent = nullptr);
	virtual ~CSettingDlg();

	enum { IDD = IDD_SETTINGDLG };

protected:
	virtual BOOL OnInitDialog();
	virtual void DoDataExchange(CDataExchange* pDX);

public:
	CMFCEditBrowseCtrl m_tag_browser;
	CMFCEditBrowseCtrl m_book_browser;
	CMFCEditBrowseCtrl m_project_browser;

	DECLARE_MESSAGE_MAP()
protected:
	afx_msg void OnBnClickedOk();
};


text:
import * as _ from 'lodash';
import { ListItem } from './apListItemFactory';
import { User } from './apUserFactory';
import { FieldDefinition, FieldConfigurationObject } from './apFieldFactory';
import { IModelFactory } from './apModelFactory';

export interface ListItemVersions<T extends ListItem<any>> {
    [key: number]: ListItemVersion<T>;
}

export interface ListItemVersion<T extends ListItem<any>> {
    modified: Date;
    version: number;
    [key: string]: any;
}

export interface FieldVersion {
    editor: User;
    modified: Date;
    value: any;
    version: number;
}

/**
 * @ngdoc object
 * @name apListItemVersionFactory.FieldVersionCollection
 * @param {FieldDefinition} fieldDefinition Field definition of each version of the field added.
 * @description
 * Object that contains the entire version history for a given list item field/property.
 */
export class FieldVersionCollection {
    fieldDefinition: FieldDefinition;
    versions: { [key: number]: FieldVersion } = {};

    constructor(fieldDefinition: FieldDefinition) {
        this.fieldDefinition = fieldDefinition;
    }

    /**
     * @ngdoc object
     * @name apListItemVersionFactory.FieldVersionCollection.addVersion
     * @methodOf apListItemVersionFactory.FieldVersionCollection
     * @param {User} editor User who made the change.
     * @param {Date} modified Date modified.
     * @param {any} value Value of the field at this version.
     * @param {number} version The version number.
     * @description
     * Used to add a single version to the collection.
     */
    addVersion(editor: User, modified: Date, value: any, version: number): void {
        this.versions[version] = {
            editor,
            modified,
            value,
            version,
        };
    }

    get mappedName() {
        return this.fieldDefinition.mappedName;
    }

    get length() {
        return _.keys(this.versions).length;
    }
}

export class FieldChange {
    fieldName: string;
    newerVersion: ListItemVersion<any>;
    newValue: string;
    oldValue: string;
    previousVersion: ListItemVersion<any>;
    propertyName: string;

    constructor(
        propertyName: string,
        fieldDefinition: FieldConfigurationObject,
        newerVersion: ListItemVersion<any>,
        previousVersion: ListItemVersion<any> = <ListItemVersion<any>>{},
    ) {
        this.fieldName = fieldDefinition.displayName;
        this.newerVersion = newerVersion;
        /** Need to set property name before calling this.getFormattedValue */
        this.propertyName = propertyName;

        this.newValue = this.getFormattedValue(newerVersion);
        this.oldValue = this.getFormattedValue(previousVersion);
        this.previousVersion = previousVersion;
    }

    getFormattedValue(version: ListItemVersion<any> | any): string {
        let propertyValue = '';
        if (version.getFormattedValue) {
            propertyValue = version.getFormattedValue(this.propertyName);
        }
        return propertyValue;
    }
}

/**
 * @ngdoc object
 * @name apListItemVersionFactory.FieldChangeSummary
 * @param {ListItem<T>} newerVersion Updated version of list item.
 * @param {ListItem<T>} [previousVersion={}] Previous version of list item.
 * @description
 * Generates a snapshot between 2 versions of a list item and locates diferences.
 */
export class FieldChangeSummary<T extends ListItem<any>> {
    changeCount: number;
    fieldsChanged: { [key: string]: FieldChange } = {};

    constructor(newerVersion: ListItem<T> | any, previousVersion: ListItem<T> | Object | any = <ListItem<T>>{}) {
        /** Loop through each of the properties on the newer list item */
        _.each(newerVersion, (val, propertyName: string) => {
            const fieldDefinition = newerVersion.getFieldDefinition(propertyName);
            /** Only log non-readonly fields that aren't the same */
            if (
                fieldDefinition &&
                !fieldDefinition.readOnly &&
                JSON.stringify(newerVersion[propertyName]) !== JSON.stringify(previousVersion[propertyName])
            ) {
                let fieldChange = new FieldChange(propertyName, fieldDefinition, newerVersion, previousVersion);
                if (fieldChange.newValue !== fieldChange.oldValue) {
                    /** This field has changed */
                    this.fieldsChanged[propertyName] = fieldChange;
                }
            }
        });
        this.changeCount = _.keys(this.fieldsChanged).length;
    }

    get hasMajorChanges(): boolean {
        return _.isNumber(this.changeCount) && this.changeCount > 0;
    }
}

/**
 * @ngdoc object
 * @name apListItemVersionFactory.VersionSummary
 * @param {IListItemVersion<T>} newerVersion Updated version of list item.
 * @param {IListItemVersion<T>} [previousVersion={}] Previous version of list item.
 * @description
 * Used specifically to determine difference between 2 distinct versions of a list item using the
 * version history.  Extends FieldChangeSummary.
 */
export class VersionSummary<T extends ListItem<any>> extends FieldChangeSummary<T> {
    listItemVersion: ListItemVersion<any> | any;
    version: number;

    constructor(newerVersion: ListItemVersion<T>, previousVersion: ListItemVersion<T> | Object = {}) {
        super(newerVersion, previousVersion);
        this.listItemVersion = newerVersion;
        this.version = newerVersion.version;
    }

    get editor() {
        return this.listItemVersion.editor;
    }

    get modified() {
        return this.listItemVersion.modified;
    }
}

/**
 * @ngdoc object
 * @name apListItemVersionFactory.ChangeSummary
 * @param {IListItemVersions} versions Multiple versions of a list item.
 * @description
 * Used to summarize all changes for a given list item.
 */
export class ChangeSummary<T extends ListItem<any>> {
    /** The number of versions where list item data actually changed */
    significantVersionCount = 0;
    private versionSummaryCollection: { [key: number]: VersionSummary<T> } = {};

    constructor(versions: ListItemVersions<T>) {
        /** First version won't have a previous version */
        let previousVersion;
        _.each(versions, (version: ListItemVersion<T>) => {
            const versionSummary = new VersionSummary<T>(version, previousVersion);
            if (versionSummary.hasMajorChanges) {
                this.significantVersionCount++;
            }
            this.versionSummaryCollection[versionSummary.version] = versionSummary;
            /** Store this version so we can compare to the next version */
            previousVersion = version;
        });
    }

    // Use getter in case we need to alter the way we store this in future
    get changes() {
        return this.versionSummaryCollection;
    }

    count(): number {
        return _.keys(this.versionSummaryCollection).length;
    }

    toArray(): VersionSummary<T>[] {
        return _.toArray<any>(this.versionSummaryCollection);
    }
}

export class VersionHistoryCollection<T extends ListItem<any>> {
    [key: number]: ListItemVersion<T>;
    // getFactory: () => IModelFactory;
    constructor(fieldVersionCollections: FieldVersionCollection[], factory: IModelFactory) {
        /** Iterate through each of the field version collections */
        _.each(fieldVersionCollections, (fieldVersionCollection) => {
            this.addFieldCollection(fieldVersionCollection, factory);
        });
    }

    addFieldCollection(fieldVersionCollection: FieldVersionCollection, factory: IModelFactory): void {
        /** Iterate through each version of this field */
        _.each(fieldVersionCollection.versions, (fieldVersion: FieldVersion, versionNumberAsString: string) => {
            /** Create a new version object if it doesn't already exist */
            this[fieldVersion.modified.toUTCString()] =
                this[fieldVersion.modified.toUTCString()] ||
                new factory<T>({
                    editor: fieldVersion.editor,
                    modified: fieldVersion.modified,
                    /** Iterating over object properties which converts everything to string so convert back */
                    version: Number(versionNumberAsString),
                });
            /** Add field to the version history for this version with computed property name */
            this[fieldVersion.modified.toUTCString()][fieldVersionCollection.mappedName] = fieldVersion.value;
        });
    }

    count(): number {
        return _.keys(this).length;
    }

    generateChangeSummary(): ChangeSummary<T> {
        return new ChangeSummary<T>(<any>this);
    }

    toArray(): ListItemVersion<T>[] {
        return _.toArray<ListItemVersion<T>>(this);
    }
}

/**
 * @ngdoc function
 * @name apListItemVersionFactory
 * @description
 * Factory which handles parsing list item versions and identifying changes.
 *
 */
export class ListItemVersionFactory {
    ChangeSummary = ChangeSummary;
    FieldChangeSummary = FieldChangeSummary;
    FieldVersionCollection = FieldVersionCollection;
    VersionHistoryCollection = VersionHistoryCollection;
    VersionSummary = VersionSummary;
}


text:
package effects;

import conditions.etc.Cooldown;
import entities.characters.personas.Persona;
import entities.characters.Character;
import entities.particles.Particle;
import game.Engine;
import org.lwjgl.util.Point;
import org.newdawn.slick.Graphics;
import util.Constants;
import util.Images;
import util.Maths;

import java.util.ArrayList;

public class SmiteEffect extends Effect {

	private Character caster;
	private Persona tgt;
	private double damage;
	private Cooldown delay = new Cooldown(.3f * Constants.TICKS_PER_SECOND);
	private boolean hasReset = false;

	ArrayList<Particle> particles = new ArrayList<Particle>();

	int type = 0;

	ArrayList<Persona> hit = new ArrayList<Persona>();

	public SmiteEffect(Character caster, Persona tgt, double damage){
		this.caster = caster;
		this.tgt = tgt;
		this.setLoc(caster.getLoc());
		//setXY(caster.getX(), caster.getY());
		this.damage = damage;
		delay.reset();

		for(float theta = -180.0f; theta < 180.0f; theta += 3.0f){
			double x = Math.cos(Math.toRadians(theta)) * 16 * 3;
			double y = Math.sin(Math.toRadians(theta)) * 16 * 3;

			x += tgt.getCharacter().getX();
			y += tgt.getCharacter().getY();

			particles.add(Particle.newSmiteParticle(new Point((int)x,(int)y), tgt.getCharacter()));

		}
		this.setLoc(tgt.getCharacter().getLoc());

	}

	public void draw(float sY, float sy, Graphics g, float zoom) {
		for (Particle p : particles){
			p.draw(sY, sy, g, zoom);
		}

	}

    public Effect tick(){
		if(tgt == null || tgt.getCharacter() == null || tgt.getCharacter().getHP()<0)return this;
		delay.tick();

		//we're using the effect's x,y to track where the target was last tick

		float dx = tgt.getCharacter().getX() - this.getX();
		float dy = tgt.getCharacter().getY() - this.getY();
		for (Particle p : particles){
			p.setX(p.getX() + dx);
			p.setY(p.getY() + dy);
			//p.translate(dx, dy);

			//float dx = (float)(-((p.getX()-tgt.getCharacter().getX()) / Maths.dist(p.getLoc(), tgt.getCharacter().getLoc())));
			//float dy = (float)(-((p.getY()-tgt.getCharacter().getY()) / Maths.dist(p.getLoc(), tgt.getCharacter().getLoc())));
//
			//p.setDX(dx);
			//p.setDY(dy);
			p.tick();
		}
		this.setLoc(tgt.getCharacter().getLoc());
		if(delay.offCooldown() && !hasReset){

			//TODO: make deal true damage
			Character.dealTrueDamage(damage, caster, tgt.getCharacter(), false);
			if(tgt.getCharacter().getHP() < 0)
                Engine.addToBeRemoved(tgt);
			delay = new Cooldown(0.2f * Constants.TICKS_PER_SECOND);
			delay.reset();
			hasReset = true;
		}else if(delay.offCooldown() && hasReset)return this;
		return null;
	}

}


text:
<?php

namespace Maruamyu\Core\OAuth1;

class AuthorizationHeaderTest extends \PHPUnit\Framework\TestCase
{
    public function test_getScheme()
    {
        $authorizationHeader = new AuthorizationHeader();
        $this->assertEquals('OAuth', $authorizationHeader->getScheme());
    }

    public function test_fromHeaderValue()
    {
        $headerValue  = 'OAuth realm="http://example.jp/"';
        $headerValue .= ' , oauth_version="1.0"';
        $headerValue .= ' , oauth_signature_method="HMAC-SHA1"';
        $headerValue .= ' , oauth_consumer_key="consumer_key"';
        $headerValue .= ' , oauth_token="oauth_token"';
        $headerValue .= ' , oauth_nonce="nonce"';
        $headerValue .= ' , oauth_timestamp="1234567890"';
        $headerValue .= ' , oauth_signature="qBoVJCjYWRHEmXh5VRqzItHuA50="';

        $params = [
            'realm' => 'http://example.jp/',
            'oauth_version' => '1.0',
            'oauth_signature_method' => 'HMAC-SHA1',
            'oauth_consumer_key' => 'consumer_key',
            'oauth_token' => 'oauth_token',
            'oauth_nonce' => 'nonce',
            'oauth_timestamp' => '1234567890',
            'oauth_signature' => 'qBoVJCjYWRHEmXh5VRqzItHuA50=',
        ];
        $authorizationHeader = new AuthorizationHeader($headerValue);
        $this->assertEquals($params, $authorizationHeader->getParams());
    }

    public function test_fromAuthParams()
    {
        $params = [
            'realm' => 'http://example.jp/',
            'oauth_version' => '1.0',
            'oauth_signature_method' => 'HMAC-SHA1',
            'oauth_consumer_key' => 'consumer_key',
            'oauth_token' => 'oauth_token',
            'oauth_nonce' => 'nonce',
            'oauth_timestamp' => '1234567890',
            'oauth_signature' => 'qBoVJCjYWRHEmXh5VRqzItHuA50=',
        ];
        $authorizationHeader = new AuthorizationHeader($params);
        $this->assertEquals($params, $authorizationHeader->getParams());
    }
}


text:
#pragma once

#include "base/BackendTexture.h"
#include <stdint.h>

namespace three {

  class GLTexture : public BackendTexture
  {
    public:
      GLTexture(Texture * source);

    public:
      uint32_t id;
      uint32_t type;
  };

}


text:
const path = require('path')
const childProcess = require('child_process')
const fs = require('fs-extra')

const util = require(path.join(__dirname, 'util.js'))

const PRM = {
  getNameByURL: function (urlof) {
    // Get repository name (eg. Squeebot/squeebot-plugins)
    let s = urlof.split('/')
    let lName = s[s.length - 2]
    let sName = s[s.length - 1]

    if (sName.indexOf('.git') !== -1) {
      sName = sName.replace('.git', '')
    }

    return lName + '/' + sName
  },
  install: async function (core, repo) {
    // Install a git repository for plugin sources
    let repoId = PRM.getNameByURL(repo)

    if (core.settings.pluginRepositories[repoId]) {
      if (await fs.pathExists(core.settings.pluginRepositories[repoId].directory)) {
        console.warn('This repository has already been installed!')
        return
      }
    }

    let pluginsDir = core.pluginManager.repoPath

    await fs.ensureDir(pluginsDir)

    let target = repoId.replace(/\//g, '+')
    let clone = childProcess.spawn('git', ['clone', repo, target], {cwd: pluginsDir})

    clone.stderr.on('data', function (l) {
      let lines = l.toString().split('\n')
      for (let li in lines) {
        if (lines[li].trim() !== '') {
          console.log(lines[li])
        }
      }
    })

    clone.on('exit', function (c) {
      if (c !== 0) {
        console.error('Could not clone the git repository.')
        return
      }

      console.log('Successfully cloned the repository as', repoId)

      core.settings.pluginRepositories[repoId] = {remote: repo, directory: path.join(pluginsDir, target)}
      PRM.repopCache(core)
    })
  },
  uninstall: async function (core, repoName) {
    // Uninstall a git repository
    let repoId = PRM.getNameByURL(repoName)
    if (!core.settings.pluginRepositories[repoId]) {
      console.error('There is no such repository.')
      return
    }

    let repo = core.settings.pluginRepositories[repoId]

    if (!await fs.pathExists(repo.directory)) {
      console.warn('This repository has already been deleted!')
      return
    } else {
      await fs.remove(repo.directory)
    }

    let loaded = []
    for (let i in core.settings['_pluginCache'].installedList[repoId]) {
      let pl = core.settings['_pluginCache'].installedList[repoId][i]
      if (core.settings.pluginConfiguration[pl]) {
        loaded.push(pl)
      }
    }

    console.warn('WARNING! Removing this repository will render the following loaded plugins useless:')
    console.warn(loaded.join(', '))
    console.warn('You will have to delete them using `plugin remove %s`!', loaded.join(' '))

    delete core.settings['_pluginCache'].installedList[repoId]
    delete core.settings.pluginRepositories[repoId]

    console.log('Repository removed successfully.')

    await core.settingsManager.saveSettings()
  },
  update: async function (core, repoName) {
    let repoId = PRM.getNameByURL(repoName)
    if (!core.settings.pluginRepositories[repoId]) {
      console.error('There is no such repository.')
      return
    }

    let repo = core.settings.pluginRepositories[repoId]

    if (!await fs.pathExists(repo.directory)) {
      console.error('This repository has been deleted!')
      return
    }

    let pull = childProcess.spawn('git', ['pull'], {cwd: repo.directory})

    pull.stderr.on('data', function (l) {
      let lines = l.toString().split('\n')
      for (let li in lines) {
        if (lines[li].trim() !== '') {
          console.log(lines[li])
        }
      }
    })

    pull.on('exit', function (c) {
      if (c !== 0) {
        console.error('Could not pull the git repository.')
        return
      }

      console.log('Successfully updated the repository', repoId)

      PRM.repopCache(core)
    })
  },
  repopCache: async function (core) {
    core.settings['_pluginCache'].installedList = {}
    for (let rid in core.settings.pluginRepositories) {
      let rdata = core.settings.pluginRepositories[rid]
      let final = []
      let raw = await fs.readdir(rdata.directory)
      for (let i in raw) {
        let dir = raw[i]
        let stat = await fs.stat(path.join(rdata.directory, dir))
        if (!stat.isDirectory()) continue
        if (raw[i].indexOf('.') === 0) continue
        final.push(raw[i])
      }

      core.settings['_pluginCache'].installedList[rid] = final
    }
    await core.settingsManager.saveSettings()
  },
  installNpmModule: async function (module, version, cwd) {
    return new Promise(function (resolve, reject) {
      let npm = childProcess.spawn('npm', ['install', `${module}@${version}`], {cwd: cwd})

      npm.stderr.on('data', function (l) {
        let lines = l.toString().split('\n')
        for (let li in lines) {
          let line = lines[li]
          if (line.indexOf(' WARN') === 0) continue
          if (line.indexOf('npm') === 0) continue
          if (line.trim() !== '') {
            console.log(line)
          }
        }
      })

      npm.on('exit', function (c) {
        if (c !== 0) {
          return reject(new Error('Non-zero exit code'))
        }

        console.log(`Successfully installed ${module}@${version}`)
        resolve(module)
      })
    })
  },
  installDepsIfNecessary: async function (core, deplist) {
    console.log('Checking plugin dependencies...')
    let skipped = true

    for (let i in deplist) {
      if (core.settings['_pluginCache'].npmPackagesInstalled[i]) {
        if (core.settings['_pluginCache'].npmPackagesInstalled[i] === deplist[i]) {
          continue
        }
      }

      try {
        console.log(`Installing ${i}@${deplist[i]}...`)
        skipped = false
        await PRM.installNpmModule(i, deplist[i], core._root)
      } catch (e) {
        throw new Error(`Failed to install ${i}@${deplist[i]}`)
      }
      core.settings['_pluginCache'].npmPackagesInstalled[i] = deplist[i]
    }

    if (skipped) {
      console.log('There was nothing to do.')
      return
    }

    await core.settingsManager.saveSettings()
  }
}

class Plugin {
  constructor (core) {
    this.core = core

    this.plugins = {}
    this.repoPath = 'plugins/'

    this.bindPRM()
  }

  setDirectory (dirPath) {
    this.repoPath = dirPath
  }

  async findPluginByName (name) {
    let instancesFound = []

    if (name.indexOf('/') !== -1) {
      let spl = name.split('/')
      let resName = spl.splice(2).join()

      let repo = spl.join('/')
      let r = this.core.settings.pluginRepositories[repo]

      if (!r) {
        return null
      }

      if (!await fs.pathExists(path.join(r.directory, resName))) {
        return
      }

      instancesFound.push({repo: r, name: resName, path: path.join(repo.directory, resName)})
    } else {
      for (let repo in this.core.settings['_pluginCache'].installedList) {
        let rlist = this.core.settings['_pluginCache'].installedList[repo]
        let repoData = this.core.settings.pluginRepositories[repo]

        if (!repoData) continue

        for (let j in rlist) {
          if (rlist[j] === name) {
            instancesFound.push({repo: repo, name: name, path: path.join(repoData.directory, name)})
          }
        }
      }
    }

    if (!instancesFound.length) return null
    if (instancesFound.length > 1) {
      console.warn(`More than one instance of "${name}" was found in the installed repositories.`)
      console.warn('You either have to')
      console.warn(' * Uninstall one of the repositories (recommended)')
      console.warn(' * If you own one of these repositories, add a prefix to the plugin directory (eg. better-commands)')
      console.warn(' * Specify repository name when loading the plugin (eg. Squeebot/squeebot-plugins/commands)')
      let conflics = []
      for (let i in instancesFound) {
        conflics.push(instancesFound[i].repo)
      }
      console.warn('Conflicting repositories:', conflics.join(', '))
      return null
    }

    return instancesFound[0]
  }

  async loadPlugin (name, data) {
    let pluginData = await this.findPluginByName(name)
    if (!pluginData) throw new Error('Plugin not found: ' + name)

    let pluginMeta
    let pluginFile
    try {
      pluginMeta = await fs.readJson(path.join(pluginData.path, 'plugin.json'))
      pluginFile = path.join(pluginData.path, 'plugin.js')
      if (!await fs.pathExists(pluginFile)) {
        throw new Error()
      }
    } catch (e) {
      throw new Error('Invalid plugin!')
    }

    if (this.plugins[name]) return

    // Load dependency plugins
    try {
      if (pluginMeta.dependencies.length > 0) {
        for (let i in pluginMeta.dependencies) {
          let dep = pluginMeta.dependencies[i]

          if (this.plugins[dep]) continue

          let conf = {}

          if (this.core.settings.pluginConfiguration[dep]) {
            conf = this.core.settings.pluginConfiguration[dep]
          }

          await this.loadPlugin(dep, conf)
        }
      }
    } catch (e) {
      throw new Error('Failed to load plugin dependencies!')
    }

    // Install required modules
    try {
      if (pluginMeta['node-modules'] && Object.keys(pluginMeta['node-modules']).length) {
        await this.PRM.installDepsIfNecessary(pluginMeta['node-modules'])
      }
    } catch (e) {
      console.error(e.message)
      throw new Error('Failed to meet plugin dependencies!')
    }

    if (this.plugins[name]) return
    console.log('[plugin] %s initializing..', name)

    let Plugin = util.requireNoCache(pluginFile)
    if (!Plugin) throw new Error('Nothing got loaded from plugin file - double check your exports.')

    this.plugins[name] = new Plugin({
      pluginId: name,
      config: data,
      settings: this.core.settings,
      botF: this.core.compatLib
    }, this.core)

    this.plugins[name].initialize()
  }

  getPluginById (id) {
    if (!this.plugins[id]) return null
    return this.plugins[id]
  }

  bindPRM () {
    this.PRM = {}
    this.PRM.getNameByURL = PRM.getNameByURL

    // Bind Plugin Repository Manager functions to this
    this.PRM.install = async (repo) => { return PRM.install.apply(this, [this.core, repo]) }
    this.PRM.uninstall = async (repo) => { return PRM.uninstall.apply(this, [this.core, repo]) }
    this.PRM.update = async (repo) => { return PRM.update.apply(this, [this.core, repo]) }
    this.PRM.repopCache = async () => { return PRM.repopCache.apply(this, [this.core]) }
    this.PRM.installDepsIfNecessary = async (deplist) => { return PRM.installDepsIfNecessary.apply(this, [this.core, deplist]) }
  }
}

module.exports = Plugin


text:
import { fromJS } from 'immutable';

import {
    CHANGE_ITEM,
    HOME_ITEM
} from './constants';

const initialState = fromJS({
    activeItem: HOME_ITEM,
});

function NavBarReducer(state = initialState, action) {
  switch (action.type) {
    case CHANGE_ITEM:
      return state
        .set('activeItem', action.activeItem);
    default:
      return state;
  }
}

export default NavBarReducer;


text:
package cyclops.companion;

import java.util.Comparator;

public class Comparators {

    private final static Comparator IDENTITY_COMPARATOR_INSTANCE = (a, b)-> Comparator.<Integer>naturalOrder().compare(System.identityHashCode(a),System.identityHashCode(b));
    public static  <T extends Comparable<? super T>> Comparator<T> naturalComparator(){
        return Comparator.naturalOrder();
    }
    public static <T> Comparator<T> identityComparator(){
        return IDENTITY_COMPARATOR_INSTANCE;
    }
    public static <T> Comparator<T> naturalOrderIdentityComparator(){
        return (a,b)-> {
            if (a instanceof Comparable) {
                return Comparator.<Comparable>naturalOrder().compare((Comparable)a,(Comparable)b);
            }
            return identityComparator().compare(a,b);
        };
    }
}


text:
namespace v8 {
namespace internal {

class AstNumberingVisitor final : public AstVisitor {
 public:
  AstNumberingVisitor(Isolate* isolate, Zone* zone)
      : AstVisitor(),
        isolate_(isolate),
        zone_(zone),
        next_id_(BailoutId::FirstUsable().ToInt()),
        properties_(zone),
        slot_cache_(zone),
        dont_optimize_reason_(kNoReason) {
    InitializeAstVisitor(isolate);
  }

  bool Renumber(FunctionLiteral* node);

 private:
// AST node visitor interface.
#define DEFINE_VISIT(type) void Visit##type(type* node) override;
  AST_NODE_LIST(DEFINE_VISIT)
#undef DEFINE_VISIT

  bool Finish(FunctionLiteral* node);

  void VisitVariableProxyReference(VariableProxy* node);
  void VisitPropertyReference(Property* node);
  void VisitReference(Expression* expr);

  void VisitStatements(ZoneList<Statement*>* statements) override;
  void VisitDeclarations(ZoneList<Declaration*>* declarations) override;
  void VisitArguments(ZoneList<Expression*>* arguments);
  void VisitObjectLiteralProperty(ObjectLiteralProperty* property);

  int ReserveIdRange(int n) {
    int tmp = next_id_;
    next_id_ += n;
    return tmp;
  }

  void IncrementNodeCount() { properties_.add_node_count(1); }
  void DisableSelfOptimization() {
    properties_.flags() |= AstProperties::kDontSelfOptimize;
  }
  void DisableOptimization(BailoutReason reason) {
    dont_optimize_reason_ = reason;
    DisableSelfOptimization();
  }
  void DisableCrankshaft(BailoutReason reason) {
    if (FLAG_turbo_shipping) {
      properties_.flags() |= AstProperties::kDontCrankshaft;
    } else {
      dont_optimize_reason_ = reason;
      DisableSelfOptimization();
    }
  }

  template <typename Node>
  void ReserveFeedbackSlots(Node* node) {
    node->AssignFeedbackVectorSlots(isolate_, properties_.get_spec(),
                                    &slot_cache_);
  }

  BailoutReason dont_optimize_reason() const { return dont_optimize_reason_; }

  Isolate* isolate_;
  Zone* zone_;
  int next_id_;
  AstProperties properties_;
  // The slot cache allows us to reuse certain feedback vector slots.
  FeedbackVectorSlotCache slot_cache_;
  BailoutReason dont_optimize_reason_;

  DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
  DISALLOW_COPY_AND_ASSIGN(AstNumberingVisitor);
};

void AstNumberingVisitor::VisitVariableDeclaration(VariableDeclaration* node) {
  IncrementNodeCount();
  VisitVariableProxy(node->proxy());
}

void AstNumberingVisitor::VisitExportDeclaration(ExportDeclaration* node) {
  IncrementNodeCount();
  DisableOptimization(kExportDeclaration);
  VisitVariableProxy(node->proxy());
}

void AstNumberingVisitor::VisitEmptyStatement(EmptyStatement* node) {
  IncrementNodeCount();
}

void AstNumberingVisitor::VisitSloppyBlockFunctionStatement(
    SloppyBlockFunctionStatement* node) {
  IncrementNodeCount();
  Visit(node->statement());
}

void AstNumberingVisitor::VisitContinueStatement(ContinueStatement* node) {
  IncrementNodeCount();
}

void AstNumberingVisitor::VisitBreakStatement(BreakStatement* node) {
  IncrementNodeCount();
}

void AstNumberingVisitor::VisitDebuggerStatement(DebuggerStatement* node) {
  IncrementNodeCount();
  DisableOptimization(kDebuggerStatement);
  node->set_base_id(ReserveIdRange(DebuggerStatement::num_ids()));
}

void AstNumberingVisitor::VisitNativeFunctionLiteral(
    NativeFunctionLiteral* node) {
  IncrementNodeCount();
  DisableOptimization(kNativeFunctionLiteral);
  node->set_base_id(ReserveIdRange(NativeFunctionLiteral::num_ids()));
}

void AstNumberingVisitor::VisitDoExpression(DoExpression* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(DoExpression::num_ids()));
  Visit(node->block());
  Visit(node->result());
}

void AstNumberingVisitor::VisitLiteral(Literal* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(Literal::num_ids()));
}

void AstNumberingVisitor::VisitRegExpLiteral(RegExpLiteral* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(RegExpLiteral::num_ids()));
}

void AstNumberingVisitor::VisitVariableProxyReference(VariableProxy* node) {
  IncrementNodeCount();
  if (node->var()->IsLookupSlot()) {
    DisableCrankshaft(kReferenceToAVariableWhichRequiresDynamicLookup);
  }
  node->set_base_id(ReserveIdRange(VariableProxy::num_ids()));
}

void AstNumberingVisitor::VisitVariableProxy(VariableProxy* node) {
  VisitVariableProxyReference(node);
  ReserveFeedbackSlots(node);
}

void AstNumberingVisitor::VisitThisFunction(ThisFunction* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(ThisFunction::num_ids()));
}

void AstNumberingVisitor::VisitSuperPropertyReference(
    SuperPropertyReference* node) {
  IncrementNodeCount();
  DisableCrankshaft(kSuperReference);
  node->set_base_id(ReserveIdRange(SuperPropertyReference::num_ids()));
  Visit(node->this_var());
  Visit(node->home_object());
}

void AstNumberingVisitor::VisitSuperCallReference(SuperCallReference* node) {
  IncrementNodeCount();
  DisableCrankshaft(kSuperReference);
  node->set_base_id(ReserveIdRange(SuperCallReference::num_ids()));
  Visit(node->this_var());
  Visit(node->new_target_var());
  Visit(node->this_function_var());
}

void AstNumberingVisitor::VisitImportDeclaration(ImportDeclaration* node) {
  IncrementNodeCount();
  DisableOptimization(kImportDeclaration);
  VisitVariableProxy(node->proxy());
}

void AstNumberingVisitor::VisitExpressionStatement(ExpressionStatement* node) {
  IncrementNodeCount();
  Visit(node->expression());
}

void AstNumberingVisitor::VisitReturnStatement(ReturnStatement* node) {
  IncrementNodeCount();
  Visit(node->expression());
}

void AstNumberingVisitor::VisitYield(Yield* node) {
  IncrementNodeCount();
  DisableOptimization(kYield);
  ReserveFeedbackSlots(node);
  node->set_base_id(ReserveIdRange(Yield::num_ids()));
  Visit(node->generator_object());
  Visit(node->expression());
}

void AstNumberingVisitor::VisitThrow(Throw* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(Throw::num_ids()));
  Visit(node->exception());
}

void AstNumberingVisitor::VisitUnaryOperation(UnaryOperation* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(UnaryOperation::num_ids()));
  Visit(node->expression());
}

void AstNumberingVisitor::VisitCountOperation(CountOperation* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(CountOperation::num_ids()));
  Visit(node->expression());
  ReserveFeedbackSlots(node);
}

void AstNumberingVisitor::VisitBlock(Block* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(Block::num_ids()));
  if (node->scope() != NULL) VisitDeclarations(node->scope()->declarations());
  VisitStatements(node->statements());
}

void AstNumberingVisitor::VisitFunctionDeclaration(FunctionDeclaration* node) {
  IncrementNodeCount();
  VisitVariableProxy(node->proxy());
  VisitFunctionLiteral(node->fun());
}

void AstNumberingVisitor::VisitCallRuntime(CallRuntime* node) {
  IncrementNodeCount();
  ReserveFeedbackSlots(node);
  node->set_base_id(ReserveIdRange(CallRuntime::num_ids()));
  VisitArguments(node->arguments());
}

void AstNumberingVisitor::VisitWithStatement(WithStatement* node) {
  IncrementNodeCount();
  DisableCrankshaft(kWithStatement);
  node->set_base_id(ReserveIdRange(WithStatement::num_ids()));
  Visit(node->expression());
  Visit(node->statement());
}

void AstNumberingVisitor::VisitDoWhileStatement(DoWhileStatement* node) {
  IncrementNodeCount();
  DisableSelfOptimization();
  node->set_base_id(ReserveIdRange(DoWhileStatement::num_ids()));
  Visit(node->body());
  Visit(node->cond());
}

void AstNumberingVisitor::VisitWhileStatement(WhileStatement* node) {
  IncrementNodeCount();
  DisableSelfOptimization();
  node->set_base_id(ReserveIdRange(WhileStatement::num_ids()));
  Visit(node->cond());
  Visit(node->body());
}

void AstNumberingVisitor::VisitTryCatchStatement(TryCatchStatement* node) {
  IncrementNodeCount();
  DisableOptimization(kTryCatchStatement);
  Visit(node->try_block());
  Visit(node->catch_block());
}

void AstNumberingVisitor::VisitTryFinallyStatement(TryFinallyStatement* node) {
  IncrementNodeCount();
  DisableOptimization(kTryFinallyStatement);
  Visit(node->try_block());
  Visit(node->finally_block());
}

void AstNumberingVisitor::VisitPropertyReference(Property* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(Property::num_ids()));
  Visit(node->key());
  Visit(node->obj());
}

void AstNumberingVisitor::VisitReference(Expression* expr) {
  DCHECK(expr->IsProperty() || expr->IsVariableProxy());
  if (expr->IsProperty()) {
    VisitPropertyReference(expr->AsProperty());
  } else {
    VisitVariableProxyReference(expr->AsVariableProxy());
  }
}

void AstNumberingVisitor::VisitProperty(Property* node) {
  VisitPropertyReference(node);
  ReserveFeedbackSlots(node);
}

void AstNumberingVisitor::VisitAssignment(Assignment* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(Assignment::num_ids()));

  if (node->is_compound()) VisitBinaryOperation(node->binary_operation());
  VisitReference(node->target());
  Visit(node->value());
  ReserveFeedbackSlots(node);
}

void AstNumberingVisitor::VisitBinaryOperation(BinaryOperation* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(BinaryOperation::num_ids()));
  Visit(node->left());
  Visit(node->right());
}

void AstNumberingVisitor::VisitCompareOperation(CompareOperation* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(CompareOperation::num_ids()));
  Visit(node->left());
  Visit(node->right());
}

void AstNumberingVisitor::VisitSpread(Spread* node) { UNREACHABLE(); }

void AstNumberingVisitor::VisitEmptyParentheses(EmptyParentheses* node) {
  UNREACHABLE();
}

void AstNumberingVisitor::VisitForInStatement(ForInStatement* node) {
  IncrementNodeCount();
  DisableSelfOptimization();
  node->set_base_id(ReserveIdRange(ForInStatement::num_ids()));
  Visit(node->each());
  Visit(node->enumerable());
  Visit(node->body());
  ReserveFeedbackSlots(node);
}

void AstNumberingVisitor::VisitForOfStatement(ForOfStatement* node) {
  IncrementNodeCount();
  DisableCrankshaft(kForOfStatement);
  node->set_base_id(ReserveIdRange(ForOfStatement::num_ids()));
  Visit(node->assign_iterator());
  Visit(node->next_result());
  Visit(node->result_done());
  Visit(node->assign_each());
  Visit(node->body());
  ReserveFeedbackSlots(node);
}

void AstNumberingVisitor::VisitConditional(Conditional* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(Conditional::num_ids()));
  Visit(node->condition());
  Visit(node->then_expression());
  Visit(node->else_expression());
}

void AstNumberingVisitor::VisitIfStatement(IfStatement* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(IfStatement::num_ids()));
  Visit(node->condition());
  Visit(node->then_statement());
  if (node->HasElseStatement()) {
    Visit(node->else_statement());
  }
}

void AstNumberingVisitor::VisitSwitchStatement(SwitchStatement* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(SwitchStatement::num_ids()));
  Visit(node->tag());
  ZoneList<CaseClause*>* cases = node->cases();
  for (int i = 0; i < cases->length(); i++) {
    VisitCaseClause(cases->at(i));
  }
}

void AstNumberingVisitor::VisitCaseClause(CaseClause* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(CaseClause::num_ids()));
  if (!node->is_default()) Visit(node->label());
  VisitStatements(node->statements());
}

void AstNumberingVisitor::VisitForStatement(ForStatement* node) {
  IncrementNodeCount();
  DisableSelfOptimization();
  node->set_base_id(ReserveIdRange(ForStatement::num_ids()));
  if (node->init() != NULL) Visit(node->init());
  if (node->cond() != NULL) Visit(node->cond());
  if (node->next() != NULL) Visit(node->next());
  Visit(node->body());
}

void AstNumberingVisitor::VisitClassLiteral(ClassLiteral* node) {
  IncrementNodeCount();
  DisableCrankshaft(kClassLiteral);
  node->set_base_id(ReserveIdRange(node->num_ids()));
  if (node->extends()) Visit(node->extends());
  if (node->constructor()) Visit(node->constructor());
  if (node->class_variable_proxy()) {
    VisitVariableProxy(node->class_variable_proxy());
  }
  for (int i = 0; i < node->properties()->length(); i++) {
    VisitObjectLiteralProperty(node->properties()->at(i));
  }
  ReserveFeedbackSlots(node);
}

void AstNumberingVisitor::VisitObjectLiteral(ObjectLiteral* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(node->num_ids()));
  for (int i = 0; i < node->properties()->length(); i++) {
    VisitObjectLiteralProperty(node->properties()->at(i));
  }
  node->BuildConstantProperties(isolate_);
  // Mark all computed expressions that are bound to a key that
  // is shadowed by a later occurrence of the same key. For the
  // marked expressions, no store code will be is emitted.
  node->CalculateEmitStore(zone_);
  ReserveFeedbackSlots(node);
}

void AstNumberingVisitor::VisitObjectLiteralProperty(
    ObjectLiteralProperty* node) {
  if (node->is_computed_name()) DisableCrankshaft(kComputedPropertyName);
  Visit(node->key());
  Visit(node->value());
}

void AstNumberingVisitor::VisitArrayLiteral(ArrayLiteral* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(node->num_ids()));
  for (int i = 0; i < node->values()->length(); i++) {
    Visit(node->values()->at(i));
  }
  node->BuildConstantElements(isolate_);
  ReserveFeedbackSlots(node);
}

void AstNumberingVisitor::VisitCall(Call* node) {
  IncrementNodeCount();
  ReserveFeedbackSlots(node);
  node->set_base_id(ReserveIdRange(Call::num_ids()));
  Visit(node->expression());
  VisitArguments(node->arguments());
}

void AstNumberingVisitor::VisitCallNew(CallNew* node) {
  IncrementNodeCount();
  ReserveFeedbackSlots(node);
  node->set_base_id(ReserveIdRange(CallNew::num_ids()));
  Visit(node->expression());
  VisitArguments(node->arguments());
}

void AstNumberingVisitor::VisitStatements(ZoneList<Statement*>* statements) {
  if (statements == NULL) return;
  for (int i = 0; i < statements->length(); i++) {
    Visit(statements->at(i));
  }
}

void AstNumberingVisitor::VisitDeclarations(
    ZoneList<Declaration*>* declarations) {
  for (int i = 0; i < declarations->length(); i++) {
    Visit(declarations->at(i));
  }
}

void AstNumberingVisitor::VisitArguments(ZoneList<Expression*>* arguments) {
  for (int i = 0; i < arguments->length(); i++) {
    Visit(arguments->at(i));
  }
}

void AstNumberingVisitor::VisitFunctionLiteral(FunctionLiteral* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(FunctionLiteral::num_ids()));
  // We don't recurse into the declarations or body of the function literal:
  // you have to separately Renumber() each FunctionLiteral that you compile.
}

void AstNumberingVisitor::VisitRewritableExpression(
    RewritableExpression* node) {
  IncrementNodeCount();
  node->set_base_id(ReserveIdRange(RewritableExpression::num_ids()));
  Visit(node->expression());
}

bool AstNumberingVisitor::Finish(FunctionLiteral* node) {
  node->set_ast_properties(&properties_);
  node->set_dont_optimize_reason(dont_optimize_reason());
  return !HasStackOverflow();
}

bool AstNumberingVisitor::Renumber(FunctionLiteral* node) {
  Scope* scope = node->scope();
  if (scope->new_target_var()) DisableCrankshaft(kSuperReference);
  if (scope->calls_eval()) DisableOptimization(kFunctionCallsEval);
  if (scope->arguments() != NULL && !scope->arguments()->IsStackAllocated()) {
    DisableCrankshaft(kContextAllocatedArguments);
  }

  int rest_index;
  if (scope->rest_parameter(&rest_index)) {
    DisableCrankshaft(kRestParameter);
  }

  VisitDeclarations(scope->declarations());
  VisitStatements(node->body());

  return Finish(node);
}

bool AstNumbering::Renumber(Isolate* isolate, Zone* zone,
                            FunctionLiteral* function) {
  AstNumberingVisitor visitor(isolate, zone);
  return visitor.Renumber(function);
}
}  // namespace internal
}  // namespace v8


text:
package org.camunda.bpm.cockpit.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.camunda.bpm.cockpit.CockpitRuntimeDelegate;
import org.camunda.bpm.cockpit.db.CommandExecutor;
import org.camunda.bpm.cockpit.db.QueryService;
import org.camunda.bpm.cockpit.impl.db.CommandExecutorImpl;
import org.camunda.bpm.cockpit.impl.db.QueryServiceImpl;
import org.camunda.bpm.cockpit.impl.plugin.DefaultPluginRegistry;
import org.camunda.bpm.cockpit.plugin.PluginRegistry;
import org.camunda.bpm.cockpit.plugin.spi.CockpitPlugin;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.impl.ProcessEngineImpl;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.webapp.impl.AbstractAppRuntimeDelegate;

/**
 *
This is the default {@link CockpitRuntimeDelegate} implementation that provides
 * the camunda cockpit plugin services (i.e. {@link QueryService} and
 * {@link CommandExecutor}).

 *
 * @author roman.smirnov
 * @author nico.rehwaldt
 */
public class DefaultCockpitRuntimeDelegate extends AbstractAppRuntimeDelegate<CockpitPlugin> implements CockpitRuntimeDelegate {

  private  Map<String, CommandExecutor> commandExecutors;

  public DefaultCockpitRuntimeDelegate() {
    super(CockpitPlugin.class);
    this.commandExecutors = new HashMap<String, CommandExecutor>();
  }

  @Override
  public QueryService getQueryService(String processEngineName) {
    CommandExecutor commandExecutor = getCommandExecutor(processEngineName);
    return new QueryServiceImpl(commandExecutor);
  }

  @Override
  public CommandExecutor getCommandExecutor(String processEngineName) {

    CommandExecutor commandExecutor = commandExecutors.get(processEngineName);
    if (commandExecutor == null) {
      commandExecutor = createCommandExecutor(processEngineName);
      commandExecutors.put(processEngineName, commandExecutor);
    }

    return commandExecutor;
  }

  /**
   * Deprecated: use {@link #getAppPluginRegistry()}
   */
  @Deprecated
  public PluginRegistry getPluginRegistry() {
    return new DefaultPluginRegistry(pluginRegistry);
  }

  /**
   * Returns the list of mapping files that should be used to create the
   * session factory for this runtime.
   *
   * @return
   */
  protected List<String> getMappingFiles() {
    List<CockpitPlugin> cockpitPlugins = pluginRegistry.getPlugins();

    List<String> mappingFiles = new ArrayList<String>();
    for (CockpitPlugin plugin: cockpitPlugins) {
      mappingFiles.addAll(plugin.getMappingFiles());
    }

    return mappingFiles;
  }

  /**
   * Create command executor for the engine with the given name
   *
   * @param processEngineName
   * @return
   */
  protected CommandExecutor createCommandExecutor(String processEngineName) {

    ProcessEngine processEngine = getProcessEngine(processEngineName);
    if (processEngine == null) {
      throw new ProcessEngineException("No process engine with name " + processEngineName + " found.");
    }

    ProcessEngineConfigurationImpl processEngineConfiguration = ((ProcessEngineImpl)processEngine).getProcessEngineConfiguration();
    List<String> mappingFiles = getMappingFiles();

    return new CommandExecutorImpl(processEngineConfiguration, mappingFiles);
  }

}


text:
.ui-toggle-button {
  cursor: pointer;
  display: flex;
  margin: 0;
  padding: 0;
}


text:
//
//  ViewController.m
//  IDPAuthoringWorkspace
//
//  Created by 能登 要 on 2014/10/23.
//  Copyright (c) 2014年 Irimasu Densan Planning. All rights reserved.
//

#import "ViewController.h"
#import "EditObjectView.h"
#import "NoTrackerObjectView.h"

static double degreesToRadians(double degrees);
static double degreesToRadians(double degrees) {return degrees * M_PI / 180;}

@interface ViewController () <UIScrollViewDelegate>
{
    BOOL _initialized;
    __weak IBOutlet UIView *_groundView;
    __weak IBOutlet UIScrollView *_scrollView;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self constructionAuthoringWorkspace];
        // 環境の構築

    self.toolbarItems = @[ [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:self action:@selector(onAdd:)]
                           ,[[UIBarButtonItem alloc] initWithTitle:@"Add(NoTracker)" style:UIBarButtonItemStylePlain target:self action:@selector(onAddNotracker:)]
                           ,[[UIBarButtonItem alloc] initWithTitle:@"Delete" style:UIBarButtonItemStylePlain target:self action:@selector(onDelete:)]
//#warning UNDO disabled
                           ,[[UIBarButtonItem alloc] initWithTitle:@"Undo" style:UIBarButtonItemStylePlain target:self action:@selector(onUndo:)]
                           ,[[UIBarButtonItem alloc] initWithTitle:@"Redo" style:UIBarButtonItemStylePlain target:self action:@selector(onRedo:)]
                           ];
    self.navigationController.toolbarHidden = NO;
}

- (void)onAdd:(id)sender
{
    EditObjectView *editObjectView = [[EditObjectView alloc] initWithFrame:(CGRect){CGPointZero,CGSizeMake(150, 120)}];
    editObjectView.center = self.groundView.center;
    editObjectView.backgroundColor = [UIColor clearColor]/*[UIColor lightGrayColor]*/;
    editObjectView.opaque = NO;
    editObjectView.clipsToBounds = NO;
    editObjectView.transform = CGAffineTransformMakeRotation(degreesToRadians(0.0f) );

    [self addObjectView:editObjectView];
    // オブジェクトを追加

    [self clearSelection];

    [self selectObjectViews:@[editObjectView]];
}

- (void)onAddNotracker:(id)sender
{
    NoTrackerObjectView *noTrackerObjectView = [[NoTrackerObjectView alloc] initWithFrame:(CGRect){CGPointZero,CGSizeMake(150, 120)}];
    noTrackerObjectView.center = self.groundView.center;
    noTrackerObjectView.backgroundColor = [UIColor clearColor]/*[UIColor lightGrayColor]*/;
    noTrackerObjectView.opaque = NO;
    noTrackerObjectView.clipsToBounds = NO;
    noTrackerObjectView.transform = CGAffineTransformMakeRotation(degreesToRadians(0.0f) );

    [self addObjectView:noTrackerObjectView];
    // オブジェクトを追加

    [self clearSelection];

    [self selectObjectViews:@[noTrackerObjectView]];
}

- (void)onDelete:(id)sender
{
    [self deleteSelectedObject];
}

- (void)onUndo:(id)sender
{
    [self popCommand];
}

- (void)onRedo:(id)sender
{
    [self popRedoCommand];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIStatusBarStyle) preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (UIView *) groundView
{
    return _groundView;
}

- (UIView *) viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _groundView;
}

- (void) viewWillLayoutSubviews
{
    [super viewDidLayoutSubviews];
    if( _initialized != YES ){
        _initialized = YES;

        // スクロールViewを設定
        _scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.view.frame),CGRectGetHeight(self.view.frame));
//        [_scrollView.panGestureRecognizer requireGestureRecognizerToFail:self.authoringWorkspacePanGestureRecognizer];

        // レイアウトが決定してからテストオブジェクトを追加
        NSArray *centers = @[  [NSValue valueWithCGPoint:CGPointMake(CGRectGetMidX(self.groundView.frame),CGRectGetMidY(self.groundView.frame))]
                               ,[NSValue valueWithCGPoint:CGPointMake(CGRectGetMidX(self.groundView.frame) + 20.0f ,CGRectGetMidY(self.groundView.frame) + 20.0f)]
                               ];

        NSArray *bounds = @[ [NSValue valueWithCGRect:CGRectMake(0, 0, 120, 80)]
                             ,[NSValue valueWithCGRect:CGRectMake(0, 0, 120, 80)]
                             ];

        [centers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            CGRect lineBounds = [bounds[idx] CGRectValue];;
            CGPoint center = [obj CGPointValue] /*CGPointMake(CGRectGetMidX(self.groundView.frame),CGRectGetMidY(self.groundView.frame))*/;

            EditObjectView *editObjectView = [[EditObjectView alloc] initWithFrame:lineBounds];
            editObjectView.center = center;
            editObjectView.backgroundColor = [UIColor clearColor]/*[UIColor lightGrayColor]*/;
            editObjectView.opaque = NO;
            editObjectView.clipsToBounds = NO;
            editObjectView.transform = CGAffineTransformMakeRotation(degreesToRadians(0.0f) );

            [self addObjectView:editObjectView];
                // オブジェクトを追加
        }];

        while ([self commandNumber] > 0) {
            [self popFrontCommand];
        }

    }
}

@end


text:
package com.auth0.lock.event;

import com.auth0.lock.R;

public class ChangePasswordEvent extends AlertDialogEvent {

    public ChangePasswordEvent() {
        super(R.string.com_auth0_db_change_password_title_success, R.string.com_auth0_db_change_password_message_success);
    }

}


text:
"""This module contains the SQLAlchemy user class definition."""
from flask_login import UserMixin
from sqlalchemy.ext.associationproxy import association_proxy
from server.models.db import db
from server.models.event import Event

class User(db.Model, UserMixin):

    """SQLAlchemy user class definition."""

    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column('username', db.String(50), unique=True)
    password = db.Column('password', db.String(50))
    is_admin = db.Column('is_admin', db.Boolean)
    uuid = db.Column('uuid', db.Text)

    subscriptions = association_proxy('event_subscriptions', 'event')

    def __init__(self, username, password, is_admin, uuid=None):
        """Constructor for user."""
        self.username = username
        self.password = password
        self.is_admin = is_admin
        self.uuid = uuid

    def owns_event_with_id(self, instance_id: int) -> bool:
        """Tell whether user owns event with a given id."""
        query = Event.query.filter_by(created_by=self.id, id=instance_id)
        event = query.first()
        if event is None:
            return False
        return True

    def is_subscribed_to_event(self, event_id: int) -> bool:
        """Tell whether user is subscribed to event with a given id."""
        filtered = list(filter(
            lambda x: x.id == event_id, self.subscriptions
        ))
        return (len(filtered) > 0)


text:
define(['backbone', 'mps', 'compare/presenters/PresenterClass'], function(
  Backbone,
  mps,
  PresenterClass
) {
  'use strict';

  var CountryGridButtonBoxPresenter = PresenterClass.extend({
    init: function(view) {
      this._super();
      this.open = false;
      this.view = view;
    },

    _subscriptions: [
      {
        'CountryWidgetsModal/hide': function() {
          this.open = false;
        }
      }
    ],

    showIndicatorModal: function() {
      if (!this.open) {
        // mps publish an event that makes the indicator modal show
        mps.publish('CountryWidgetsModal/show');
        this.open = true;
      }
    }
  });

  return CountryGridButtonBoxPresenter;
});


text:
#include "sleepGenerator.h"

#include <generatorBase/generatorCustomizer.h>

#include "ev3GeneratorBase/ev3GeneratorFactory.h"

using namespace ev3::simple::lineLeader;
using namespace generatorBase::simple;
using namespace qReal;

SleepGenerator::SleepGenerator(const qrRepo::RepoApi &repo
		, generatorBase::GeneratorCustomizer &customizer
		, const Id &id
		, QObject *parent)
	: BindingGenerator(repo, customizer, id, "sensors/lineLeader/sleep.t", QList<Binding *>()
			<< Binding::createConverting("@@PORT@@", "Port"
					, static_cast<Ev3GeneratorFactory *>(customizer.factory())->portNameConverter())
			, parent)
{
}


text:
package com.techhounds.commands.shooter;

import com.techhounds.subsystems.ShooterSubsystem;

import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

/**
 *
 */
public class SetShooterSpeedFromVision extends Command {

	ShooterSubsystem shooter;
    public SetShooterSpeedFromVision() {
    	shooter = ShooterSubsystem.getInstance();//Doesn't require, just calls a new setShooterSpeed
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	double setSpeed = SmartDashboard.getNumber("Vision_Shoot_Speed");
    	new SetShooterSpeed(setSpeed).start();

    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return true;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
package com.sibilantsolutions.grison.client;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import com.sibilantsolutions.grison.driver.foscam.dto.CommandDto;
import com.sibilantsolutions.grison.rx.State;
import com.sibilantsolutions.grison.rx.event.action.AbstractAction;
import com.sibilantsolutions.grison.rx.event.result.AbstractResult;
import com.sibilantsolutions.grison.rx.event.result.AudioVideoReceiveResult;
import com.sibilantsolutions.grison.rx.event.result.OperationReceiveResult;
import com.sibilantsolutions.grison.rx.event.ui.ConnectUiEvent;
import com.sibilantsolutions.grison.rx.event.ui.UiEvent;
import com.sibilantsolutions.grison.rx.event.xform.AbstractActionToAbstractResult;
import com.sibilantsolutions.grison.rx.event.xform.CommandToAudioVideoReceiveResult;
import com.sibilantsolutions.grison.rx.event.xform.CommandToOperationReceiveResult;
import com.sibilantsolutions.grison.rx.event.xform.StateAndResultToStateBiFunction;
import com.sibilantsolutions.grison.rx.event.xform.UiEventToAbstractAction;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.processors.FlowableProcessor;
import io.reactivex.rxjava3.processors.PublishProcessor;
import io.reactivex.rxjava3.schedulers.Schedulers;

@Service
@EnableConfigurationProperties(CameraConnectionProperties.class)
public class AudioVideoClient {

    private final CameraConnectionProperties cameraConnectionProperties;

    public AudioVideoClient(CameraConnectionProperties cameraConnectionProperties) {
        this.cameraConnectionProperties = cameraConnectionProperties;
    }

    public Flowable<State> stream() {

        Flowable<UiEvent> events = Flowable.just(new ConnectUiEvent(cameraConnectionProperties.getHost(), cameraConnectionProperties.getPort()));

        //TODO: Handle upstream socket disconnect.

        Flowable<AbstractAction> uiEventsToActions = events
                .compose(new UiEventToAbstractAction());

        final FlowableProcessor<AbstractAction> dynamicActions = PublishProcessor.<AbstractAction>create().toSerialized();

        Flowable<AbstractAction> actions = Flowable
                .merge(
                        uiEventsToActions,
                        dynamicActions);

        final FlowableProcessor<CommandDto> operationDatastream = PublishProcessor.<CommandDto>create().toSerialized();
        final FlowableProcessor<CommandDto> audioVideoDatastream = PublishProcessor.<CommandDto>create().toSerialized();

        final Flowable<OperationReceiveResult> operationReceiveResults = operationDatastream
                .observeOn(Schedulers.io())
                .compose(new CommandToOperationReceiveResult());

        final Flowable<AudioVideoReceiveResult> audioVideoReceiveResults = audioVideoDatastream
                .onBackpressureLatest()
                .observeOn(Schedulers.io())
                .compose(new CommandToAudioVideoReceiveResult());

        final Flowable<AbstractResult> actionResults = actions
                .compose(new AbstractActionToAbstractResult(operationDatastream, audioVideoDatastream));

        final Flowable<AbstractResult> results = Flowable.merge(
                actionResults,
                operationReceiveResults,
                audioVideoReceiveResults);

        return results
                .scanWith(
                        State::init,
                        new StateAndResultToStateBiFunction(dynamicActions, cameraConnectionProperties.getUsername(), cameraConnectionProperties.getPassword()));
    }

}


text:
/*
 * file:	SR-EELS_CreateCharacterisationOverview.ijm
 * author:	Michael Entrup b. Epping (michael.entrup@wwu.de)
 * version:	20150126
 * info:	This script generates a HTML file to show the results of the SR-EELS characterisation.
 * 			The first of the calibration images is displayed (JPEG version with overlay).
 * 			'head.html' and 'foot.html' must be present at the output directory.
 *
 * 			This scrfipt is part of the Fiji plugin EFTEMj (https://github.com/EFTEMj/EFTEMj).
 */

importClass(Packages.java.io.File);
importClass(Packages.java.io.FileReader);
importClass(Packages.java.io.FileWriter);
importClass(Packages.ij.IJ);

IJ.log(arguments.length);

var input = "Q:/Aktuell/SR-EELS Calibration measurements/";
var output = "Q:/Aktuell/SR-EELS Calibration measurements/HTML-Overview/";

var found = new Array();

var skip = false;
if (!new File(input).isDirectory()) {
	exit("Please set the input path.");
	skip = true;
}
if (!new File(output).isDirectory()) {
	exit("Please set the output path.");
	skip = true;
}
if (!new File(output + "head.html").exists()) {
	IJ.showMessage("Please place the file 'head.html' at\n" + output);
	skip = true;
}
if (!new File(output + "foot.html").exists()) {
	IJ.showMessage("Please place the file 'foot.html' at\n" + output);
	skip = true;
}

if (skip == false) {
	processFolder(input);

	IJ.log(found.length + " data sets found.");
	var headReader = new FileReader(new File(output + "head.html"));
	var footReader = new FileReader(new File(output + "foot.html"));

	var indexWriter = new FileWriter(new File(output + "index.html"));

	for (var c; ( c = headReader.read() ) != -1; ) {
		indexWriter.append(c);
	}

	for (var i = 0; i < found.length; i++) {
		var divStart = "

\n";
		indexWriter.append(divStart);
		var img = "\n";
		indexWriter.append(img);
		var desc = "

specMag = " + found[i].specMag + "

QSinK7 = " + found[i].qSinK7 + "%

Date: " + found[i].date + "

Parameters: " + found[i].paras + "

\n";
		indexWriter.append(desc);
		var divEnd = "

\n";
		indexWriter.append(divEnd);
	}

	for (var c; ( c = footReader.read() ) != -1; ) {
		indexWriter.append(c);
	}
	headReader.close();
	footReader.close();
	indexWriter.close();
	IJ.showMessage("Finished!");
} else IJ.showMessage("Aborted!");

function processFolder(path) {
	var pattern = /(\d{8})\WSM(\d+)\W(-?\d+)%/;
	var pattern2 = /results_(\d+\w+)/;
	var folder = new File(path);
	var list = folder.list();
	for (var i = 0; i < list.length; i++) {
		if (pattern.test(list[i])) {
			var result = pattern.exec(list[i]);
			var folder2 = new File(path + list[i]);
			var list2 = folder2.list();
			for (var j = 0; j < list2.length; j++) {
				if (pattern2.test(list2[j])) {
					var result2 = pattern2.exec(list2[j]);
					var folder3 = new File(path + list[i] + "/" + list2[j]);
					if (folder3.isDirectory()) {
						var list3 = folder3.list();
						var images = new Array();
						for (var k = 0; k < list3.length; k++) {
							if (list3[k].indexOf(".jpg") >= 0) {
								images.push("../" + list[i] + "/" + list2[j] + "/" + list3[k]);
							}
						}
						found.push(new Data(result[2], result[3], result[1], result2[1], images[0]));
					}
				}
			}
		}
	}
}

function Data(specMag, qSinK7, date, paras, img) {
	this.specMag = specMag;
	this.qSinK7 = qSinK7;
	this.date = date;
	this.paras = paras;
	this.img = img;
}


text:
<!--
  Generated template for the CardDetail page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar>
    <ion-title>Easy Detail Page</ion-title>
  </ion-navbar>

</ion-header>

<ion-content padding>

    <ion-item>
    <ion-label fixed>Question</ion-label>
    <ion-input  [(ngModel)]="newEasyCard.easyThemeQuestion" ></ion-input>
    </ion-item>

    <ion-item>
    <ion-label fixed>Answer</ion-label>
    <ion-input  [(ngModel)]="newEasyCard.easyThemeAnswer" ></ion-input>
    </ion-item>

  <button ion-button class="Button"  (click)="addEasyCard()" block>Sign In</button>

</ion-content>