text:
using namespace v8;

#define LOCAL_STRING(s) Nan::New<String>(s).ToLocalChecked()
#define LOOKUP_CALLBACK(map, name) map->Has(LOCAL_STRING(name)) ? new Nan::Callback(map->Get(LOCAL_STRING(name)).As<Function>()) : NULL

enum bindings_ops_t {
  OP_INIT = 0,
  OP_ERROR,
  OP_ACCESS,
  OP_STATFS,
  OP_FGETATTR,
  OP_GETATTR,
  OP_FLUSH,
  OP_FSYNC,
  OP_FSYNCDIR,
  OP_READDIR,
  OP_TRUNCATE,
  OP_FTRUNCATE,
  OP_UTIMENS,
  OP_READLINK,
  OP_CHOWN,
  OP_CHMOD,
  OP_MKNOD,
  OP_SETXATTR,
  OP_GETXATTR,
  OP_LISTXATTR,
  OP_REMOVEXATTR,
  OP_OPEN,
  OP_OPENDIR,
  OP_READ,
  OP_WRITE,
  OP_RELEASE,
  OP_RELEASEDIR,
  OP_CREATE,
  OP_UNLINK,
  OP_RENAME,
  OP_LINK,
  OP_SYMLINK,
  OP_MKDIR,
  OP_RMDIR,
  OP_DESTROY
};

static Nan::Persistent<Function> buffer_constructor;
static Nan::Callback *callback_constructor;
static struct FUSE_STAT empty_stat;

struct bindings_t {
  int index;
  int gc;

  // fuse context
  int context_uid;
  int context_gid;
  int context_pid;

  // fuse data
  char mnt[1024];
  char mntopts[1024];
  abstr_thread_t thread;
  bindings_sem_t semaphore;
  bindings_sem_t semaphore_readdir;
  uv_async_t async;

  // methods
  Nan::Callback *ops_init;
  Nan::Callback *ops_error;
  Nan::Callback *ops_access;
  Nan::Callback *ops_statfs;
  Nan::Callback *ops_getattr;
  Nan::Callback *ops_fgetattr;
  Nan::Callback *ops_flush;
  Nan::Callback *ops_fsync;
  Nan::Callback *ops_fsyncdir;
  Nan::Callback *ops_readdir;
  Nan::Callback *ops_truncate;
  Nan::Callback *ops_ftruncate;
  Nan::Callback *ops_readlink;
  Nan::Callback *ops_chown;
  Nan::Callback *ops_chmod;
  Nan::Callback *ops_mknod;
  Nan::Callback *ops_setxattr;
  Nan::Callback *ops_getxattr;
  Nan::Callback *ops_listxattr;
  Nan::Callback *ops_removexattr;
  Nan::Callback *ops_open;
  Nan::Callback *ops_opendir;
  Nan::Callback *ops_read;
  Nan::Callback *ops_write;
  Nan::Callback *ops_release;
  Nan::Callback *ops_releasedir;
  Nan::Callback *ops_create;
  Nan::Callback *ops_utimens;
  Nan::Callback *ops_unlink;
  Nan::Callback *ops_rename;
  Nan::Callback *ops_link;
  Nan::Callback *ops_symlink;
  Nan::Callback *ops_mkdir;
  Nan::Callback *ops_rmdir;
  Nan::Callback *ops_destroy;

  Nan::Callback *callback;

  // method data
  bindings_ops_t op;
  fuse_fill_dir_t filler; // used in readdir
  struct fuse_file_info *info;
  char *path;
  char *name;
  FUSE_OFF_T offset;
  FUSE_OFF_T length;
  void *data; // various structs
  int mode;
  int dev;
  int uid;
  int gid;
  int result;
};

static bindings_t *bindings_mounted[1024];
static int bindings_mounted_count = 0;
static bindings_t *bindings_current = NULL;

static bindings_t *bindings_find_mounted (char *path) {
  for (int i = 0; i < bindings_mounted_count; i++) {
    bindings_t *b = bindings_mounted[i];
    if (b != NULL && !b->gc && !strcmp(b->mnt, path)) {
      return b;
    }
  }
  return NULL;
}

static int bindings_fusermount (char *path) {
  return fusermount(path);
}

static int bindings_unmount (char *path) {
  mutex_lock(&mutex);
  bindings_t *b = bindings_find_mounted(path);
  int result = bindings_fusermount(path);
  if (b != NULL && result == 0) b->gc = 1;
  mutex_unlock(&mutex);

  if (b != NULL && result == 0) thread_join(b->thread);

  return result;
}

#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION && NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION)
NAN_INLINE v8::Local<v8::Object> bindings_buffer (char *data, size_t length) {
  Local<Object> buf = Nan::New(buffer_constructor)->NewInstance(0, NULL);
  Local<String> k = LOCAL_STRING("length");
  Local<Number> v = Nan::New<Number>(length);
  buf->Set(k, v);
  buf->SetIndexedPropertiesToExternalArrayData((char *) data, kExternalUnsignedByteArray, length);
  return buf;
}
#else
void noop (char *data, void *hint) {}
NAN_INLINE v8::Local<v8::Object> bindings_buffer (char *data, size_t length) {
  return Nan::NewBuffer(data, length, noop, NULL).ToLocalChecked();
}
#endif

NAN_INLINE static int bindings_call_ex (bindings_t *b, bool isreaddir) {
  uv_async_send(&(b->async));
  if (isreaddir) {
    semaphore_wait(&(b->semaphore_readdir));
  } else {
    semaphore_wait(&(b->semaphore));
  }

  return b->result;
}

NAN_INLINE static int bindings_call (bindings_t *b) {
  return bindings_call_ex(b, false);
}

static bindings_t *bindings_get_context () {
  fuse_context *ctx = fuse_get_context();
  bindings_t *b = (bindings_t *) ctx->private_data;
  b->context_pid = ctx->pid;
  b->context_uid = ctx->uid;
  b->context_gid = ctx->gid;
  return b;
}

static int bindings_mknod (const char *path, mode_t mode, dev_t dev) {
  bindings_t *b = bindings_get_context();

  b->op = OP_MKNOD;
  b->path = (char *) path;
  b->mode = mode;
  b->dev = dev;

  return bindings_call(b);
}

static int bindings_truncate (const char *path, FUSE_OFF_T size) {
  bindings_t *b = bindings_get_context();

  b->op = OP_TRUNCATE;
  b->path = (char *) path;
  b->length = size;

  return bindings_call(b);
}

static int bindings_ftruncate (const char *path, FUSE_OFF_T size, struct fuse_file_info *info) {
  bindings_t *b = bindings_get_context();

  b->op = OP_FTRUNCATE;
  b->path = (char *) path;
  b->length = size;
  b->info = info;

  return bindings_call(b);
}

static int bindings_getattr (const char *path, struct FUSE_STAT *stat) {
  bindings_t *b = bindings_get_context();

  b->op = OP_GETATTR;
  b->path = (char *) path;
  b->data = stat;

  return bindings_call(b);
}

static int bindings_fgetattr (const char *path, struct FUSE_STAT *stat, struct fuse_file_info *info) {
  bindings_t *b = bindings_get_context();

  b->op = OP_FGETATTR;
  b->path = (char *) path;
  b->data = stat;
  b->info = info;

  return bindings_call(b);
}

static int bindings_flush (const char *path, struct fuse_file_info *info) {
  bindings_t *b = bindings_get_context();

  b->op = OP_FLUSH;
  b->path = (char *) path;
  b->info = info;

  return bindings_call(b);
}

static int bindings_fsync (const char *path, int datasync, struct fuse_file_info *info) {
  bindings_t *b = bindings_get_context();

  b->op = OP_FSYNC;
  b->path = (char *) path;
  b->mode = datasync;
  b->info = info;

  return bindings_call(b);
}

static int bindings_fsyncdir (const char *path, int datasync, struct fuse_file_info *info) {
  bindings_t *b = bindings_get_context();

  b->op = OP_FSYNCDIR;
  b->path = (char *) path;
  b->mode = datasync;
  b->info = info;

  return bindings_call(b);
}

static int bindings_readdir (const char *path, void *buf, fuse_fill_dir_t filler, FUSE_OFF_T offset, struct fuse_file_info *info) {
  bindings_t *b = bindings_get_context();

  b->op = OP_READDIR;
  b->path = (char *) path;
  b->data = buf;
  b->filler = filler;

  return bindings_call_ex(b, true);
}

static int bindings_readlink (const char *path, char *buf, size_t len) {
  bindings_t *b = bindings_get_context();

  b->op = OP_READLINK;
  b->path = (char *) path;
  b->data = (void *) buf;
  b->length = len;

  return bindings_call(b);
}

static int bindings_chown (const char *path, uid_t uid, gid_t gid) {
  bindings_t *b = bindings_get_context();

  b->op = OP_CHOWN;
  b->path = (char *) path;
  b->uid = uid;
  b->gid = gid;

  return bindings_call(b);
}

static int bindings_chmod (const char *path, mode_t mode) {
  bindings_t *b = bindings_get_context();

  b->op = OP_CHMOD;
  b->path = (char *) path;
  b->mode = mode;

  return bindings_call(b);
}

#ifdef __APPLE__
static int bindings_setxattr (const char *path, const char *name, const char *value, size_t size, int flags, uint32_t position) {
  bindings_t *b = bindings_get_context();

  b->op = OP_SETXATTR;
  b->path = (char *) path;
  b->name = (char *) name;
  b->data = (void *) value;
  b->length = size;
  b->offset = position;
  b->mode = flags;

  return bindings_call(b);
}

static int bindings_getxattr (const char *path, const char *name, char *value, size_t size, uint32_t position) {
  bindings_t *b = bindings_get_context();

  b->op = OP_GETXATTR;
  b->path = (char *) path;
  b->name = (char *) name;
  b->data = (void *) value;
  b->length = size;
  b->offset = position;

  return bindings_call(b);
}
#else
static int bindings_setxattr (const char *path, const char *name, const char *value, size_t size, int flags) {
  bindings_t *b = bindings_get_context();

  b->op = OP_SETXATTR;
  b->path = (char *) path;
  b->name = (char *) name;
  b->data = (void *) value;
  b->length = size;
  b->offset = 0;
  b->mode = flags;

  return bindings_call(b);
}

static int bindings_getxattr (const char *path, const char *name, char *value, size_t size) {
  bindings_t *b = bindings_get_context();

  b->op = OP_GETXATTR;
  b->path = (char *) path;
  b->name = (char *) name;
  b->data = (void *) value;
  b->length = size;
  b->offset = 0;

  return bindings_call(b);
}
#endif

static int bindings_listxattr (const char *path, char *list, size_t size) {
  bindings_t *b = bindings_get_context();

  b->op = OP_LISTXATTR;
  b->path = (char *) path;
  b->data = (void *) list;
  b->length = size;

  return bindings_call(b);
}

static int bindings_removexattr (const char *path, const char *name) {
  bindings_t *b = bindings_get_context();

  b->op = OP_REMOVEXATTR;
  b->path = (char *) path;
  b->name = (char *) name;

  return bindings_call(b);
}

static int bindings_statfs (const char *path, struct statvfs *statfs) {
  bindings_t *b = bindings_get_context();

  b->op = OP_STATFS;
  b->path = (char *) path;
  b->data = statfs;

  return bindings_call(b);
}

static int bindings_open (const char *path, struct fuse_file_info *info) {
  bindings_t *b = bindings_get_context();

  b->op = OP_OPEN;
  b->path = (char *) path;
  b->mode = info->flags;
  b->info = info;

  return bindings_call(b);
}

static int bindings_opendir (const char *path, struct fuse_file_info *info) {
  bindings_t *b = bindings_get_context();

  b->op = OP_OPENDIR;
  b->path = (char *) path;
  b->mode = info->flags;
  b->info = info;

  return bindings_call(b);
}

static int bindings_read (const char *path, char *buf, size_t len, FUSE_OFF_T offset, struct fuse_file_info *info) {
  bindings_t *b = bindings_get_context();

  b->op = OP_READ;
  b->path = (char *) path;
  b->data = (void *) buf;
  b->offset = offset;
  b->length = len;
  b->info = info;

  return bindings_call(b);
}

static int bindings_write (const char *path, const char *buf, size_t len, FUSE_OFF_T offset, struct fuse_file_info * info) {
  bindings_t *b = bindings_get_context();

  b->op = OP_WRITE;
  b->path = (char *) path;
  b->data = (void *) buf;
  b->offset = offset;
  b->length = len;
  b->info = info;

  return bindings_call(b);
}

static int bindings_release (const char *path, struct fuse_file_info *info) {
  bindings_t *b = bindings_get_context();

  b->op = OP_RELEASE;
  b->path = (char *) path;
  b->info = info;

  return bindings_call(b);
}

static int bindings_releasedir (const char *path, struct fuse_file_info *info) {
  bindings_t *b = bindings_get_context();

  b->op = OP_RELEASEDIR;
  b->path = (char *) path;
  b->info = info;

  return bindings_call(b);
}

static int bindings_access (const char *path, int mode) {
  bindings_t *b = bindings_get_context();

  b->op = OP_ACCESS;
  b->path = (char *) path;
  b->mode = mode;

  return bindings_call(b);
}

static int bindings_create (const char *path, mode_t mode, struct fuse_file_info *info) {
  bindings_t *b = bindings_get_context();

  b->op = OP_CREATE;
  b->path = (char *) path;
  b->mode = mode;
  b->info = info;

  return bindings_call(b);
}

static int bindings_utimens (const char *path, const struct timespec tv[2]) {
  bindings_t *b = bindings_get_context();

  b->op = OP_UTIMENS;
  b->path = (char *) path;
  b->data = (void *) tv;

  return bindings_call(b);
}

static int bindings_unlink (const char *path) {
  bindings_t *b = bindings_get_context();

  b->op = OP_UNLINK;
  b->path = (char *) path;

  return bindings_call(b);
}

static int bindings_rename (const char *src, const char *dest) {
  bindings_t *b = bindings_get_context();

  b->op = OP_RENAME;
  b->path = (char *) src;
  b->data = (void *) dest;

  return bindings_call(b);
}

static int bindings_link (const char *path, const char *dest) {
  bindings_t *b = bindings_get_context();

  b->op = OP_LINK;
  b->path = (char *) path;
  b->data = (void *) dest;

  return bindings_call(b);
}

static int bindings_symlink (const char *path, const char *dest) {
  bindings_t *b = bindings_get_context();

  b->op = OP_SYMLINK;
  b->path = (char *) path;
  b->data = (void *) dest;

  return bindings_call(b);
}

static int bindings_mkdir (const char *path, mode_t mode) {
  bindings_t *b = bindings_get_context();

  b->op = OP_MKDIR;
  b->path = (char *) path;
  b->mode = mode;

  return bindings_call(b);
}

static int bindings_rmdir (const char *path) {
  bindings_t *b = bindings_get_context();

  b->op = OP_RMDIR;
  b->path = (char *) path;

  return bindings_call(b);
}

static void* bindings_init (struct fuse_conn_info *conn) {
  bindings_t *b = bindings_get_context();

  b->op = OP_INIT;

  bindings_call(b);
  return b;
}

static void bindings_destroy (void *data) {
  bindings_t *b = bindings_get_context();

  b->op = OP_DESTROY;

  bindings_call(b);
}

static void bindings_free (bindings_t *b) {
  if (b->ops_access != NULL) delete b->ops_access;
  if (b->ops_truncate != NULL) delete b->ops_truncate;
  if (b->ops_ftruncate != NULL) delete b->ops_ftruncate;
  if (b->ops_getattr != NULL) delete b->ops_getattr;
  if (b->ops_fgetattr != NULL) delete b->ops_fgetattr;
  if (b->ops_flush != NULL) delete b->ops_flush;
  if (b->ops_fsync != NULL) delete b->ops_fsync;
  if (b->ops_fsyncdir != NULL) delete b->ops_fsyncdir;
  if (b->ops_readdir != NULL) delete b->ops_readdir;
  if (b->ops_readlink != NULL) delete b->ops_readlink;
  if (b->ops_chown != NULL) delete b->ops_chown;
  if (b->ops_chmod != NULL) delete b->ops_chmod;
  if (b->ops_mknod != NULL) delete b->ops_mknod;
  if (b->ops_setxattr != NULL) delete b->ops_setxattr;
  if (b->ops_getxattr != NULL) delete b->ops_getxattr;
  if (b->ops_listxattr != NULL) delete b->ops_listxattr;
  if (b->ops_removexattr != NULL) delete b->ops_removexattr;
  if (b->ops_statfs != NULL) delete b->ops_statfs;
  if (b->ops_open != NULL) delete b->ops_open;
  if (b->ops_opendir != NULL) delete b->ops_opendir;
  if (b->ops_read != NULL) delete b->ops_read;
  if (b->ops_write != NULL) delete b->ops_write;
  if (b->ops_release != NULL) delete b->ops_release;
  if (b->ops_releasedir != NULL) delete b->ops_releasedir;
  if (b->ops_create != NULL) delete b->ops_create;
  if (b->ops_utimens != NULL) delete b->ops_utimens;
  if (b->ops_unlink != NULL) delete b->ops_unlink;
  if (b->ops_rename != NULL) delete b->ops_rename;
  if (b->ops_link != NULL) delete b->ops_link;
  if (b->ops_symlink != NULL) delete b->ops_symlink;
  if (b->ops_mkdir != NULL) delete b->ops_mkdir;
  if (b->ops_rmdir != NULL) delete b->ops_rmdir;
  if (b->ops_init != NULL) delete b->ops_init;
  if (b->ops_destroy != NULL) delete b->ops_destroy;
  if (b->callback != NULL) delete b->callback;

  bindings_mounted[b->index] = NULL;
  while (bindings_mounted_count > 0 && bindings_mounted[bindings_mounted_count - 1] == NULL) {
    bindings_mounted_count--;
  }

  free(b);
}

static void bindings_on_close (uv_handle_t *handle) {
  mutex_lock(&mutex);
  bindings_free((bindings_t *) handle->data);
  mutex_unlock(&mutex);
}

static thread_fn_rtn_t bindings_thread (void *data) {
  bindings_t *b = (bindings_t *) data;

  struct fuse_operations ops = { };

  if (b->ops_access != NULL) ops.access = bindings_access;
  if (b->ops_truncate != NULL) ops.truncate = bindings_truncate;
  if (b->ops_ftruncate != NULL) ops.ftruncate = bindings_ftruncate;
  if (b->ops_getattr != NULL) ops.getattr = bindings_getattr;
  if (b->ops_fgetattr != NULL) ops.fgetattr = bindings_fgetattr;
  if (b->ops_flush != NULL) ops.flush = bindings_flush;
  if (b->ops_fsync != NULL) ops.fsync = bindings_fsync;
  if (b->ops_fsyncdir != NULL) ops.fsyncdir = bindings_fsyncdir;
  if (b->ops_readdir != NULL) ops.readdir = bindings_readdir;
  if (b->ops_readlink != NULL) ops.readlink = bindings_readlink;
  if (b->ops_chown != NULL) ops.chown = bindings_chown;
  if (b->ops_chmod != NULL) ops.chmod = bindings_chmod;
  if (b->ops_mknod != NULL) ops.mknod = bindings_mknod;
  if (b->ops_setxattr != NULL) ops.setxattr = bindings_setxattr;
  if (b->ops_getxattr != NULL) ops.getxattr = bindings_getxattr;
  if (b->ops_listxattr != NULL) ops.listxattr = bindings_listxattr;
  if (b->ops_removexattr != NULL) ops.removexattr = bindings_removexattr;
  if (b->ops_statfs != NULL) ops.statfs = bindings_statfs;
  if (b->ops_open != NULL) ops.open = bindings_open;
  if (b->ops_opendir != NULL) ops.opendir = bindings_opendir;
  if (b->ops_read != NULL) ops.read = bindings_read;
  if (b->ops_write != NULL) ops.write = bindings_write;
  if (b->ops_release != NULL) ops.release = bindings_release;
  if (b->ops_releasedir != NULL) ops.releasedir = bindings_releasedir;
  if (b->ops_create != NULL) ops.create = bindings_create;
  if (b->ops_utimens != NULL) ops.utimens = bindings_utimens;
  if (b->ops_unlink != NULL) ops.unlink = bindings_unlink;
  if (b->ops_rename != NULL) ops.rename = bindings_rename;
  if (b->ops_link != NULL) ops.link = bindings_link;
  if (b->ops_symlink != NULL) ops.symlink = bindings_symlink;
  if (b->ops_mkdir != NULL) ops.mkdir = bindings_mkdir;
  if (b->ops_rmdir != NULL) ops.rmdir = bindings_rmdir;
  if (b->ops_init != NULL) ops.init = bindings_init;
  if (b->ops_destroy != NULL) ops.destroy = bindings_destroy;

  int argc = !strcmp(b->mntopts, "-o") ? 1 : 2;
  char *argv[] = {
    (char *) "fuse_bindings_dummy",
    (char *) b->mntopts
  };

  struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
  struct fuse_chan *ch = fuse_mount(b->mnt, &args);

  if (ch == NULL) {
    b->op = OP_ERROR;
    bindings_call(b);
    uv_close((uv_handle_t*) &(b->async), &bindings_on_close);
    return NULL;
  }

  struct fuse *fuse = fuse_new(ch, &args, &ops, sizeof(struct fuse_operations), b);

  if (fuse == NULL) {
    b->op = OP_ERROR;
    bindings_call(b);
    uv_close((uv_handle_t*) &(b->async), &bindings_on_close);
    return NULL;
  }

  fuse_loop(fuse);

  fuse_unmount(b->mnt, ch);
  fuse_session_remove_chan(ch);
  fuse_destroy(fuse);

  uv_close((uv_handle_t*) &(b->async), &bindings_on_close);

  return 0;
}

NAN_INLINE static Local<Date> bindings_get_date (struct timespec *out) {
  int ms = (out->tv_nsec / 1000);
  return Nan::New<Date>(out->tv_sec * 1000 + ms).ToLocalChecked();
}

NAN_INLINE static void bindings_set_date (struct timespec *out, Local<Date> date) {
  double ms = date->NumberValue();
  time_t secs = (time_t)(ms / 1000.0);
  time_t rem = ms - (1000.0 * secs);
  time_t ns = rem * 1000000.0;
  out->tv_sec = secs;
  out->tv_nsec = ns;
}

NAN_INLINE static void bindings_set_stat (struct FUSE_STAT *stat, Local<Object> obj) {
  if (obj->Has(LOCAL_STRING("dev"))) stat->st_dev = obj->Get(LOCAL_STRING("dev"))->NumberValue();
  if (obj->Has(LOCAL_STRING("ino"))) stat->st_ino = obj->Get(LOCAL_STRING("ino"))->NumberValue();
  if (obj->Has(LOCAL_STRING("mode"))) stat->st_mode = obj->Get(LOCAL_STRING("mode"))->Uint32Value();
  if (obj->Has(LOCAL_STRING("nlink"))) stat->st_nlink = obj->Get(LOCAL_STRING("nlink"))->NumberValue();
  if (obj->Has(LOCAL_STRING("uid"))) stat->st_uid = obj->Get(LOCAL_STRING("uid"))->NumberValue();
  if (obj->Has(LOCAL_STRING("gid"))) stat->st_gid = obj->Get(LOCAL_STRING("gid"))->NumberValue();
  if (obj->Has(LOCAL_STRING("rdev"))) stat->st_rdev = obj->Get(LOCAL_STRING("rdev"))->NumberValue();
  if (obj->Has(LOCAL_STRING("size"))) stat->st_size = obj->Get(LOCAL_STRING("size"))->NumberValue();
  if (obj->Has(LOCAL_STRING("blocks"))) stat->st_blocks = obj->Get(LOCAL_STRING("blocks"))->NumberValue();
  if (obj->Has(LOCAL_STRING("blksize"))) stat->st_blksize = obj->Get(LOCAL_STRING("blksize"))->NumberValue();
#ifdef __APPLE__
  if (obj->Has(LOCAL_STRING("mtime"))) bindings_set_date(&stat->st_mtimespec, obj->Get(LOCAL_STRING("mtime")).As<Date>());
  if (obj->Has(LOCAL_STRING("ctime"))) bindings_set_date(&stat->st_ctimespec, obj->Get(LOCAL_STRING("ctime")).As<Date>());
  if (obj->Has(LOCAL_STRING("atime"))) bindings_set_date(&stat->st_atimespec, obj->Get(LOCAL_STRING("atime")).As<Date>());
#else
  if (obj->Has(LOCAL_STRING("mtime"))) bindings_set_date(&stat->st_mtim, obj->Get(LOCAL_STRING("mtime")).As<Date>());
  if (obj->Has(LOCAL_STRING("ctime"))) bindings_set_date(&stat->st_ctim, obj->Get(LOCAL_STRING("ctime")).As<Date>());
  if (obj->Has(LOCAL_STRING("atime"))) bindings_set_date(&stat->st_atim, obj->Get(LOCAL_STRING("atime")).As<Date>());
#endif
}

NAN_INLINE static void bindings_set_statfs (struct statvfs *statfs, Local<Object> obj) { // from http://linux.die.net/man/2/stat
  if (obj->Has(LOCAL_STRING("bsize"))) statfs->f_bsize = obj->Get(LOCAL_STRING("bsize"))->Uint32Value();
  if (obj->Has(LOCAL_STRING("frsize"))) statfs->f_frsize = obj->Get(LOCAL_STRING("frsize"))->Uint32Value();
  if (obj->Has(LOCAL_STRING("blocks"))) statfs->f_blocks = obj->Get(LOCAL_STRING("blocks"))->Uint32Value();
  if (obj->Has(LOCAL_STRING("bfree"))) statfs->f_bfree = obj->Get(LOCAL_STRING("bfree"))->Uint32Value();
  if (obj->Has(LOCAL_STRING("bavail"))) statfs->f_bavail = obj->Get(LOCAL_STRING("bavail"))->Uint32Value();
  if (obj->Has(LOCAL_STRING("files"))) statfs->f_files = obj->Get(LOCAL_STRING("files"))->Uint32Value();
  if (obj->Has(LOCAL_STRING("ffree"))) statfs->f_ffree = obj->Get(LOCAL_STRING("ffree"))->Uint32Value();
  if (obj->Has(LOCAL_STRING("favail"))) statfs->f_favail = obj->Get(LOCAL_STRING("favail"))->Uint32Value();
  if (obj->Has(LOCAL_STRING("fsid"))) statfs->f_fsid = obj->Get(LOCAL_STRING("fsid"))->Uint32Value();
  if (obj->Has(LOCAL_STRING("flag"))) statfs->f_flag = obj->Get(LOCAL_STRING("flag"))->Uint32Value();
  if (obj->Has(LOCAL_STRING("namemax"))) statfs->f_namemax = obj->Get(LOCAL_STRING("namemax"))->Uint32Value();
}

class SetDirWorker : public Nan::AsyncWorker {
 public:
  SetDirWorker(bindings_t *b, char **dirs, int dirs_length)
    : Nan::AsyncWorker(NULL), b(b), dirs(dirs), dirs_length(dirs_length) {}
  ~SetDirWorker() {}

  void Execute () {
    fuse_fill_dir_t fillerToCall = b->filler;
    void *data = b->data;
    for (int i = 0; i < dirs_length; i++) {
      fillerToCall(data, dirs[i], &empty_stat, 0);
    }
  }
  void WorkComplete(){
    semaphore_signal(&(b->semaphore_readdir));
    for (int i = 0; i < dirs_length; i++) {
      free(dirs[i]);
    }
    free(dirs);
  }
 private:
  bindings_t *b;
  char **dirs;
  int dirs_length;
};

NAN_METHOD(OpCallback) {
  bindings_t *b = bindings_mounted[info[0]->Uint32Value()];
  b->result = (info.Length() > 1 && info[1]->IsNumber()) ? info[1]->Uint32Value() : 0;
  bindings_current = NULL;

  if (!b->result) {
    switch (b->op) {
      case OP_STATFS: {
        if (info.Length() > 2 && info[2]->IsObject()) bindings_set_statfs((struct statvfs *) b->data, info[2].As<Object>());
      }
      break;

      case OP_GETATTR:
      case OP_FGETATTR: {
        if (info.Length() > 2 && info[2]->IsObject()) bindings_set_stat((struct FUSE_STAT *) b->data, info[2].As<Object>());
      }
      break;

      case OP_READDIR: {
        if (info.Length() > 2 && info[2]->IsArray()) {
          Local<Array> dirs = info[2].As<Array>();

          char **dirs_alloc = (char**)malloc(sizeof(char*)*dirs->Length());

          for (uint32_t i = 0; i < dirs->Length(); i++) {

            Nan::Utf8String dir(dirs->Get(i));

            dirs_alloc[i] = (char *) malloc(1024);
            strcpy(dirs_alloc[i], *dir);
          }

          Nan::AsyncQueueWorker(new SetDirWorker(b, dirs_alloc, dirs->Length()));
          return;
        }
      }
      break;

      case OP_CREATE:
      case OP_OPEN:
      case OP_OPENDIR: {
        if (info.Length() > 2 && info[2]->IsNumber()) {
          b->info->fh = info[2].As<Number>()->Uint32Value();
        }
      }
      break;

      case OP_READLINK: {
        if (info.Length() > 2 && info[2]->IsString()) {
          Nan::Utf8String path(info[2]);
          strcpy((char *) b->data, *path);
        }
      }
      break;

      case OP_INIT:
      case OP_ERROR:
      case OP_ACCESS:
      case OP_FLUSH:
      case OP_FSYNC:
      case OP_FSYNCDIR:
      case OP_TRUNCATE:
      case OP_FTRUNCATE:
      case OP_CHOWN:
      case OP_CHMOD:
      case OP_MKNOD:
      case OP_SETXATTR:
      case OP_GETXATTR:
      case OP_LISTXATTR:
      case OP_REMOVEXATTR:
      case OP_READ:
      case OP_UTIMENS:
      case OP_WRITE:
      case OP_RELEASE:
      case OP_RELEASEDIR:
      case OP_UNLINK:
      case OP_RENAME:
      case OP_LINK:
      case OP_SYMLINK:
      case OP_MKDIR:
      case OP_RMDIR:
      case OP_DESTROY:
      break;
    }
  }

  semaphore_signal(&(b->semaphore));
}

NAN_INLINE static void bindings_call_op_ex (bindings_t *b, Nan::Callback *fn, int argc, Local<Value> *argv, bool isreaddir) {
  if (fn == NULL){
    if (isreaddir) {
      semaphore_signal(&(b->semaphore_readdir));
    } else {
      semaphore_signal(&(b->semaphore));}
    }
  else {
    fn->Call(argc, argv);
  }
}

NAN_INLINE static void bindings_call_op (bindings_t *b, Nan::Callback *fn, int argc, Local<Value> *argv) {
  bindings_call_op_ex(b, fn, argc, argv, false);
}

static void bindings_dispatch (uv_async_t* handle, int status) {
  Nan::HandleScope scope;

  bindings_t *b = bindings_current = (bindings_t *) handle->data;
  Local<Function> callback = b->callback->GetFunction();
  b->result = -1;

  switch (b->op) {
    case OP_INIT: {
      Local<Value> tmp[] = {callback};
      bindings_call_op(b, b->ops_init, 1, tmp);
    }
    return;

    case OP_ERROR: {
      Local<Value> tmp[] = {callback};
      bindings_call_op(b, b->ops_error, 1, tmp);
    }
    return;

    case OP_STATFS: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), callback};
      bindings_call_op(b, b->ops_statfs, 2, tmp);
    }
    return;

    case OP_FGETATTR: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->info->fh), callback};
      bindings_call_op(b, b->ops_fgetattr, 3, tmp);
    }
    return;

    case OP_GETATTR: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), callback};
      bindings_call_op(b, b->ops_getattr, 2, tmp);
    }
    return;

    case OP_READDIR: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), callback};
      bindings_call_op_ex(b, b->ops_readdir, 2, tmp, true);
    }
    return;

    case OP_CREATE: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->mode), callback};
      bindings_call_op(b, b->ops_create, 3, tmp);
    }
    return;

    case OP_TRUNCATE: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->length), callback};
      bindings_call_op(b, b->ops_truncate, 3, tmp);
    }
    return;

    case OP_FTRUNCATE: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->info->fh), Nan::New<Number>(b->length), callback};
      bindings_call_op(b, b->ops_ftruncate, 4, tmp);
    }
    return;

    case OP_ACCESS: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->mode), callback};
      bindings_call_op(b, b->ops_access, 3, tmp);
    }
    return;

    case OP_OPEN: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->mode), callback};
      bindings_call_op(b, b->ops_open, 3, tmp);
    }
    return;

    case OP_OPENDIR: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->mode), callback};
      bindings_call_op(b, b->ops_opendir, 3, tmp);
    }
    return;

    case OP_WRITE: {
      Local<Value> tmp[] = {
        LOCAL_STRING(b->path),
        Nan::New<Number>(b->info->fh),
        bindings_buffer((char *) b->data, b->length),
        Nan::New<Number>(b->length), // TODO: remove me
        Nan::New<Number>(b->offset),
        callback
      };
      bindings_call_op(b, b->ops_write, 6, tmp);
    }
    return;

    case OP_READ: {
      Local<Value> tmp[] = {
        LOCAL_STRING(b->path),
        Nan::New<Number>(b->info->fh),
        bindings_buffer((char *) b->data, b->length),
        Nan::New<Number>(b->length), // TODO: remove me
        Nan::New<Number>(b->offset),
        callback
      };
      bindings_call_op(b, b->ops_read, 6, tmp);
    }
    return;

    case OP_RELEASE: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->info->fh), callback};
      bindings_call_op(b, b->ops_release, 3, tmp);
    }
    return;

    case OP_RELEASEDIR: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->info->fh), callback};
      bindings_call_op(b, b->ops_releasedir, 3, tmp);
    }
    return;

    case OP_UNLINK: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), callback};
      bindings_call_op(b, b->ops_unlink, 2, tmp);
    }
    return;

    case OP_RENAME: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), LOCAL_STRING((char *) b->data), callback};
      bindings_call_op(b, b->ops_rename, 3, tmp);
    }
    return;

    case OP_LINK: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), LOCAL_STRING((char *) b->data), callback};
      bindings_call_op(b, b->ops_link, 3, tmp);
    }
    return;

    case OP_SYMLINK: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), LOCAL_STRING((char *) b->data), callback};
      bindings_call_op(b, b->ops_symlink, 3, tmp);
    }
    return;

    case OP_CHMOD: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->mode), callback};
      bindings_call_op(b, b->ops_chmod, 3, tmp);
    }
    return;

    case OP_MKNOD: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->mode), Nan::New<Number>(b->dev), callback};
      bindings_call_op(b, b->ops_mknod, 4, tmp);
    }
    return;

    case OP_CHOWN: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->uid), Nan::New<Number>(b->gid), callback};
      bindings_call_op(b, b->ops_chown, 4, tmp);
    }
    return;

    case OP_READLINK: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), callback};
      bindings_call_op(b, b->ops_readlink, 2, tmp);
    }
    return;

    case OP_SETXATTR: {
      Local<Value> tmp[] = {
        LOCAL_STRING(b->path),
        LOCAL_STRING(b->name),
        bindings_buffer((char *) b->data, b->length),
        Nan::New<Number>(b->length),
        Nan::New<Number>(b->offset),
        Nan::New<Number>(b->mode),
        callback
      };
      bindings_call_op(b, b->ops_setxattr, 7, tmp);
    }
    return;

    case OP_GETXATTR: {
      Local<Value> tmp[] = {
        LOCAL_STRING(b->path),
        LOCAL_STRING(b->name),
        bindings_buffer((char *) b->data, b->length),
        Nan::New<Number>(b->length),
        Nan::New<Number>(b->offset),
        callback
      };
      bindings_call_op(b, b->ops_getxattr, 6, tmp);
    }
    return;

    case OP_LISTXATTR: {
      Local<Value> tmp[] = {
        LOCAL_STRING(b->path),
        bindings_buffer((char *) b->data, b->length),
        Nan::New<Number>(b->length),
        callback
      };
      bindings_call_op(b, b->ops_listxattr, 4, tmp);
    }
    return;

    case OP_REMOVEXATTR: {
      Local<Value> tmp[] = {
        LOCAL_STRING(b->path),
        LOCAL_STRING(b->name),
        callback
      };
      bindings_call_op(b, b->ops_removexattr, 3, tmp);
    }
    return;

    case OP_MKDIR: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->mode), callback};
      bindings_call_op(b, b->ops_mkdir, 3, tmp);
    }
    return;

    case OP_RMDIR: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), callback};
      bindings_call_op(b, b->ops_rmdir, 2, tmp);
    }
    return;

    case OP_DESTROY: {
      Local<Value> tmp[] = {callback};
      bindings_call_op(b, b->ops_destroy, 1, tmp);
    }
    return;

    case OP_UTIMENS: {
      struct timespec *tv = (struct timespec *) b->data;
      Local<Value> tmp[] = {LOCAL_STRING(b->path), bindings_get_date(tv), bindings_get_date(tv + 1), callback};
      bindings_call_op(b, b->ops_utimens, 4, tmp);
    }
    return;

    case OP_FLUSH: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->info->fh), callback};
      bindings_call_op(b, b->ops_flush, 3, tmp);
    }
    return;

    case OP_FSYNC: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->info->fh), Nan::New<Number>(b->mode), callback};
      bindings_call_op(b, b->ops_fsync, 4, tmp);
    }
    return;

    case OP_FSYNCDIR: {
      Local<Value> tmp[] = {LOCAL_STRING(b->path), Nan::New<Number>(b->info->fh), Nan::New<Number>(b->mode), callback};
      bindings_call_op(b, b->ops_fsyncdir, 4, tmp);
    }
    return;
  }

  semaphore_signal(&(b->semaphore));
}

static int bindings_alloc () {
  int free_index = -1;
  size_t size = sizeof(bindings_t);

  for (int i = 0; i < bindings_mounted_count; i++) {
    if (bindings_mounted[i] == NULL) {
      free_index = i;
      break;
    }
  }

  if (free_index == -1 && bindings_mounted_count < 1024) free_index = bindings_mounted_count++;
  if (free_index != -1) {
    bindings_t *b = bindings_mounted[free_index] = (bindings_t *) malloc(size);
    memset(b, 0, size);
    b->index = free_index;
  }

  return free_index;
}

NAN_METHOD(Mount) {
  if (!info[0]->IsString()) return Nan::ThrowError("mnt must be a string");

  mutex_lock(&mutex);
  int index = bindings_alloc();
  mutex_unlock(&mutex);

  if (index == -1) return Nan::ThrowError("You cannot mount more than 1024 filesystem in one process");

  mutex_lock(&mutex);
  bindings_t *b = bindings_mounted[index];
  mutex_unlock(&mutex);

  memset(&empty_stat, 0, sizeof(empty_stat));

  Nan::Utf8String path(info[0]);
  Local<Object> ops = info[1].As<Object>();

  b->ops_init = LOOKUP_CALLBACK(ops, "init");
  b->ops_error = LOOKUP_CALLBACK(ops, "error");
  b->ops_access = LOOKUP_CALLBACK(ops, "access");
  b->ops_statfs = LOOKUP_CALLBACK(ops, "statfs");
  b->ops_getattr = LOOKUP_CALLBACK(ops, "getattr");
  b->ops_fgetattr = LOOKUP_CALLBACK(ops, "fgetattr");
  b->ops_flush = LOOKUP_CALLBACK(ops, "flush");
  b->ops_fsync = LOOKUP_CALLBACK(ops, "fsync");
  b->ops_fsyncdir = LOOKUP_CALLBACK(ops, "fsyncdir");
  b->ops_readdir = LOOKUP_CALLBACK(ops, "readdir");
  b->ops_truncate = LOOKUP_CALLBACK(ops, "truncate");
  b->ops_ftruncate = LOOKUP_CALLBACK(ops, "ftruncate");
  b->ops_readlink = LOOKUP_CALLBACK(ops, "readlink");
  b->ops_chown = LOOKUP_CALLBACK(ops, "chown");
  b->ops_chmod = LOOKUP_CALLBACK(ops, "chmod");
  b->ops_mknod = LOOKUP_CALLBACK(ops, "mknod");
  b->ops_setxattr = LOOKUP_CALLBACK(ops, "setxattr");
  b->ops_getxattr = LOOKUP_CALLBACK(ops, "getxattr");
  b->ops_listxattr = LOOKUP_CALLBACK(ops, "listxattr");
  b->ops_removexattr = LOOKUP_CALLBACK(ops, "removexattr");
  b->ops_open = LOOKUP_CALLBACK(ops, "open");
  b->ops_opendir = LOOKUP_CALLBACK(ops, "opendir");
  b->ops_read = LOOKUP_CALLBACK(ops, "read");
  b->ops_write = LOOKUP_CALLBACK(ops, "write");
  b->ops_release = LOOKUP_CALLBACK(ops, "release");
  b->ops_releasedir = LOOKUP_CALLBACK(ops, "releasedir");
  b->ops_create = LOOKUP_CALLBACK(ops, "create");
  b->ops_utimens = LOOKUP_CALLBACK(ops, "utimens");
  b->ops_unlink = LOOKUP_CALLBACK(ops, "unlink");
  b->ops_rename = LOOKUP_CALLBACK(ops, "rename");
  b->ops_link = LOOKUP_CALLBACK(ops, "link");
  b->ops_symlink = LOOKUP_CALLBACK(ops, "symlink");
  b->ops_mkdir = LOOKUP_CALLBACK(ops, "mkdir");
  b->ops_rmdir = LOOKUP_CALLBACK(ops, "rmdir");
  b->ops_destroy = LOOKUP_CALLBACK(ops, "destroy");

  Local<Value> tmp[] = {Nan::New<Number>(index), Nan::New<FunctionTemplate>(OpCallback)->GetFunction()};
  b->callback = new Nan::Callback(callback_constructor->Call(2, tmp).As<Function>());

  strcpy(b->mnt, *path);
  strcpy(b->mntopts, "-o");

  Local<Array> options = ops->Get(LOCAL_STRING("options")).As<Array>();
  if (options->IsArray()) {
    for (uint32_t i = 0; i < options->Length(); i++) {
      Nan::Utf8String option(options->Get(i));
      if (strcmp(b->mntopts, "-o")) strcat(b->mntopts, ",");
      strcat(b->mntopts, *option);
    }
  }

  semaphore_init(&(b->semaphore));
  semaphore_init(&(b->semaphore_readdir));
  uv_async_init(uv_default_loop(), &(b->async), (uv_async_cb) bindings_dispatch);
  b->async.data = b;

  thread_create(&(b->thread), bindings_thread, b);
}

class UnmountWorker : public Nan::AsyncWorker {
 public:
  UnmountWorker(Nan::Callback *callback, char *path)
    : Nan::AsyncWorker(callback), path(path), result(0) {}
  ~UnmountWorker() {}

  void Execute () {
    result = bindings_unmount(path);
    free(path);

    if (result != 0) {
      SetErrorMessage("Error");
    }
  }

  void HandleOKCallback () {
    Nan::HandleScope scope;
    callback->Call(0, NULL);
  }

 private:
  char *path;
  int result;
};

NAN_METHOD(SetCallback) {
  callback_constructor = new Nan::Callback(info[0].As<Function>());
}

NAN_METHOD(SetBuffer) {
  buffer_constructor.Reset(info[0].As<Function>());
}

NAN_METHOD(PopulateContext) {
  if (bindings_current == NULL) return Nan::ThrowError("You have to call this inside a fuse operation");

  Local<Object> ctx = info[0].As<Object>();
  ctx->Set(LOCAL_STRING("uid"), Nan::New(bindings_current->context_uid));
  ctx->Set(LOCAL_STRING("gid"), Nan::New(bindings_current->context_gid));
  ctx->Set(LOCAL_STRING("pid"), Nan::New(bindings_current->context_pid));
}

NAN_METHOD(Unmount) {
  if (!info[0]->IsString()) return Nan::ThrowError("mnt must be a string");
  Nan::Utf8String path(info[0]);
  Local<Function> callback = info[1].As<Function>();

  char *path_alloc = (char *) malloc(1024);
  strcpy(path_alloc, *path);

  Nan::AsyncQueueWorker(new UnmountWorker(new Nan::Callback(callback), path_alloc));
}

void Init(Handle<Object> exports) {
  exports->Set(LOCAL_STRING("setCallback"), Nan::New<FunctionTemplate>(SetCallback)->GetFunction());
  exports->Set(LOCAL_STRING("setBuffer"), Nan::New<FunctionTemplate>(SetBuffer)->GetFunction());
  exports->Set(LOCAL_STRING("mount"), Nan::New<FunctionTemplate>(Mount)->GetFunction());
  exports->Set(LOCAL_STRING("unmount"), Nan::New<FunctionTemplate>(Unmount)->GetFunction());
  exports->Set(LOCAL_STRING("populateContext"), Nan::New<FunctionTemplate>(PopulateContext)->GetFunction());
}

NODE_MODULE(fuse_bindings, Init)


text:
package item_49;

import java.util.Comparator;

public class BrokenComparator {
	public static void main(String[] args) {
		//Comparator<Integer> naturalOrder = new Comparator<Integer>() {
		//	public int compare(Integer first, Integer second) {
		//		return first < second ? -1 : (first == second ? 0 : 1);
		//	}
		//};

		Comparator<Integer> naturalOrder = new Comparator<Integer>() {
			 public int compare(Integer first, Integer second) {
				 int f = first; // Auto-unboxing
				 int s = second; // Auto-unboxing
				 return f < s ? -1 : (f == s ? 0 : 1); // No unboxing
			 	}
			 };

		int result = naturalOrder.compare(new Integer(42), new Integer(42));
		System.out.println(result);
	}
}

redpajama_set_name: RedPajamaGithub


text:
var STARTING_HEALTH = 100;

var game = new DungeonQuest({
    tileset: {
        coin: {
            attributes: {
                type: 'coin',
                points: 5
            },
            methods: {
                register: function (state, player) {
                    state.set('coin', {
                        value: 1
                    });
                    player.set('coin', 0);
                },
                doRemove: function (state, player) {
                    player.increment('coin', state.get('coin').value);

                    return true;
                }
            }
        },
        potion: {
            attributes: {
                type: 'potion',
                points: 1
            },
            methods: {
                register: function (state, player) {
                    state.set('potion', {
                        value: 1
                    });
                    player.set('health', STARTING_HEALTH);
                    player.set('max_health', STARTING_HEALTH);
                },
                doRemove: function (state, player) {
                    var max = player.get('max_health'),
                        newTotal = player.get('health') + this.get('value');
                    if (newTotal > max) {
                        newTotal = max;
                    }

                    player.set('health', newTotal);

                    return true;
                }
            }
        },
        skull: {
            attributes: {
                type: 'skull',
                matches: ['sword'],
                points: 10
            },
            methods: {
                register: function (state, player) {
                    state.set('skull', {
                        level: 1,
                        attack: 1,
                        health: 1,
                        xp: 1
                    });
                },
                doRemove: function (state, player) {
                    this.increment('health', 0 - player.get('attack'));

                    if (this.get('health') <= 0) {
                        player.increment('xp', this.get('xp'));
                        return true;
                    }

                    return false;
                },
                doTurn: function (state, player) {
                    player.increment('health', 0 - this.get('attack'));
                }
            }
        },
        sword: {
            attributes: {
                type: 'sword',
                matches: ['skull'],
                points: 1
            },
            methods: {
                register: function (state, player) {
                    state.set('sword', {
                        attack: 1
                    });
                    player.set('attack', 1);
                },
                preRemove: function (state, player) {
                    player.increment('attack', this.get('attack'));
                },
                postRemove: function (state, player) {
                    player.increment('attack', 0 - this.get('attack'));
                }
            }
        }
    },
    assetRoot: '../assets',
    selection: d3.select('.field').append('svg:svg').append('svg:g')
});

game.start();


text:
import SocketServer
import traceback
import sys
import threading
import json

import sister
import helpers
import sisterexceptions

class ThreadedSisterRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        """
        Main handle method.
        """

        # receive JSON from other machine (tracker/client)
        everything = ''

        self.request.settimeout(3)
        while True:
            data = self.request.recv(4096)
            everything += data
            if helpers.containsValidJSON(everything):
                break

        # debug
        print 'Request from %s:%d :' % self.request.getpeername()
        print everything
        mJSON = json.loads(everything)

        # process the request
        toSend = {}
        method = mJSON['method']

        try:
            if method == 'serverStatus':
                serverLogic.serverStatus(mJSON['server'])
            elif method == 'signup':
                serverLogic.signup(mJSON['username'], mJSON['password'])
            elif method == 'login':
                token, x, y, actionTime, serverTime = serverLogic.login(mJSON['username'], mJSON['password'])
                toSend['token'] = token
                toSend['x'] = x
                toSend['y'] = y
                toSend['time'] = actionTime
                toSend['serverTime'] = serverTime

            elif method == 'inventory':
                res = serverLogic.getInventory(mJSON['token'])
                toSend['inventory'] = res

            elif method == 'mixitem':
                res = serverLogic.mixItem(mJSON['token'], mJSON['item1'], mJSON['item2'])
                toSend['item'] = res

            elif method == 'map':
                name, width, height = serverLogic.getMap(mJSON['token'])
                toSend['name'] = name
                toSend['width'] = width
                toSend['height'] = height

            elif method == 'move':
                actionTime = serverLogic.move(mJSON['token'], mJSON['x'], mJSON['y'])
                toSend['time'] = actionTime

            elif method == 'field':
                item = serverLogic.field(mJSON['token'])
                toSend['item'] = item

            elif method == 'offer':
                serverLogic.putOffer(mJSON['token'], mJSON['offered_item'], mJSON['n1'],
                                     mJSON['demanded_item'], mJSON['n2'])

            elif method == 'tradebox':
                offers = serverLogic.tradebox(mJSON['token'])
                toSend['offers'] = offers

            elif method == 'sendfind':
                res = serverLogic.sendFind(mJSON['token'], mJSON['item'])
                toSend['offers'] = res

            elif method == 'findoffer':
                offers = serverLogic.findOffer(mJSON['item'])
                toSend['offers'] = offers

            elif method == 'sendaccept':
                serverLogic.sendAccept(mJSON['token'], mJSON['offer_token'])
            elif method == 'accept':
                serverLogic.accept(mJSON['offer_token'])
            elif method == 'fetchitem':
                serverLogic.fetchItem(mJSON['token'], mJSON['offer_token'])
            elif method == 'canceloffer':
                serverLogic.cancelOffer(mJSON['token'], mJSON['offer_token'])

            toSend['status'] = 'ok'

        except (sisterexceptions.OfferException, sisterexceptions.IndexItemException, sisterexceptions.MixtureException,
                sisterexceptions.TokenException, sisterexceptions.UsernameException,
                sisterexceptions.ActionException) as e:
            # any custom exceptions is a failure
            toSend['status'] = 'fail'
            toSend['description'] = str(e)

        except Exception as e:
            print "ERROR:"
            print '-'*60
            traceback.print_exc(file=sys.stdout)
            print '-'*60
            toSend['status'] = 'error'
            toSend['description'] = str(e)

        serverLogic.closeConnection()

        # send response to client
        sToSend = json.dumps(toSend)

        # debug mode
        print 'Response to %s:%d :' % self.request.getpeername()
        print sToSend
        self.request.sendall(sToSend)

if __name__ == '__main__':
    if len(sys.argv) > 4:
        # tracker mode
        myIP = sys.argv[1]
        port = int(sys.argv[2])
        trackerAddress = (sys.argv[3], int(sys.argv[4]))
        serverLogic = sister.SisterServerLogic((myIP, port), trackerAddress)

    elif len(sys.argv) == 2:
        # local mode
        port = int(sys.argv[1])
        serverLogic = sister.SisterServerLogic()

    elif len(sys.argv) == 1:
        # local mode with auto port
        port = 0
        serverLogic = sister.SisterServerLogic()

    else:
        print 'Usage: python %s <serverPort>' % sys.argv[0]
        print '  -or- python %s' % sys.argv[0]
        print '  -or- python %s <serverIP> <serverPort> <trackerIP> <trackerPort>' % sys.argv[0]
        sys.exit()

    address = ('', port)
    server = SocketServer.ThreadingTCPServer(address, ThreadedSisterRequestHandler)
    # find out what port we were given
    ip, port = server.server_address

    t = threading.Thread(target=server.serve_forever)
    t.start()

    print 'Server up on %s:%s' % (ip, port)

    t.join()
    print 'Server down'


text:
Originally published: 2006-02-24 05:23:36
Last updated: 2006-02-24 05:23:36
Author: Jitender Cheema

# 1. sys.arg has the script name
# 2. Although there can be many ways, e.g.  os.cwd() but, there is another
# trick to
# obtain the Complete URI or Location of the current script.
# You can argue,  os.getcwd()
# import can give you working directory of the current script
# Third party Java code calling your script.... ;)
#


text:
package fr.sii.atlantique.siistem.event.service;

import java.io.UnsupportedEncodingException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.commons.lang.SerializationUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import fr.sii.atlantique.siistem.event.model.Event;
import fr.sii.atlantique.siistem.event.model.EventType;
import fr.sii.atlantique.siistem.event.model.Person;

import me.xdrop.fuzzywuzzy.FuzzySearch;
import serilogj.Log;
import serilogj.LoggerConfiguration;
import serilogj.core.LoggingLevelSwitch;
import serilogj.events.LogEventLevel;
import serilogj.sinks.seq.SeqSink;

/**
 * Controller of the Event Service
 * @author Dorian Coqueron & Pierre Gaultier
 * @version 1.0
 */

@RestController
@Component
public class EventController {

	@Autowired
	private EventRepository repository;
	@Autowired
	private EventTypeRepository eventTypeRepository;
	private static final String ENCODE = "UTF-8";
	@Value("${spring.application.name}")
	private String appName;

	public EventController(){
		LoggingLevelSwitch levelswitch = new LoggingLevelSwitch(LogEventLevel.Verbose);
		Log.setLogger(new LoggerConfiguration()
		.writeTo(new SeqSink(Constants.getINSTANCE().getLogserverAddr(), Constants.getINSTANCE().getLogserverApikey(), null, Duration.ofSeconds(2), null, levelswitch))
		.createLogger());
	}

	/**
	 * method to save an event in the DB
	 * @param data
	 * @return
	 * @throws JsonProcessingException
	 */
	@RabbitListener(queues = "#{saveEventQueue.name}")
	public String saveEvent(byte[] data){
		String res = null;
		Event e = (Event)SerializationUtils.deserialize(data);
		Event event = null;
		if (e.checkEvent()){
			 event = repository.save(e);
		}
		else{
			Log
			.forContext("MemberName", "saveEvent")
			.forContext("Service", appName)
			.error(new IllegalArgumentException(),"IllegalArgumentException");
		}
		ObjectMapper mapper = new ObjectMapper();
		Log
		.forContext("MemberName", "saveEvent")
		.forContext("Service", appName)
		.information("RabbitMQ : saveEvent");
		try {
			res =  mapper.writeValueAsString(event);
		} catch (JsonProcessingException e1) {
			Log
			.forContext("MemberName", "saveEvent")
			.forContext("Service", appName)
			.error(e1,"JsonProcessingException");
		}
		return res;
	}

	/**
	 * method to find all events by  owner
	 * @param owner
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RabbitListener(queues = "#{findByOwnerQueue.name}")
	public String findByOwner(byte[] owner){

		Log
		.forContext("MemberName", "findByOwner")
		.forContext("Service", appName)
		.information("RabbitMQ : findByOwner");
		return repository.findByOwner((Person)SerializationUtils.deserialize(owner)).toString();
	}

	/**
	 * method to find all event of a person
	 * @param owner
	 * @return
	 * @throws JsonProcessingException
	 * @throws UnsupportedEncodingException
	 */
	@RabbitListener(queues = "#{getEventsByPersonQueue.name}")
	public String getEventsByPerson(byte[] person) throws JsonProcessingException{
		List<Event> res;
		Log
		.forContext("MemberName", "getEventsByPerson")
		.forContext("Service", appName)
		.information("RabbitMQ : getEventsByPerson");
		res = repository.getEventsByPerson((Person)SerializationUtils.deserialize(person));
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(res);
	}

	/**
	 * method to get an event by his place
	 * @param place
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RabbitListener(queues = "#{getEventByPlaceQueue.name}")
	public String getEventByPlace(byte[] place){
		String res = "";
		Log
		.forContext("MemberName", "getEventByPlace")
		.forContext("Service", appName)
		.information("RabbitMQ : getEventByPlace");
		try {
			res = repository.getEventFromPlace(new String(place, ENCODE), new Date()).toString();
		} catch (UnsupportedEncodingException e1) {
			Log
			.forContext("MemberName", "getEventByPlace")
			.forContext("Service", appName)
			.error(e1,"UnsupportedEncodingException");
		}
		return res;
	}

	/**
	 * method to get all the events
	 * @param id
	 * @return
	 * @throws JsonProcessingException
	 */
	@RabbitListener(queues = "#{getAllEventQueue.name}")
	public String getAllEvent(byte[] id){
		String res = "";
		List<Event> events = repository.findAll();
		ObjectMapper mapper = new ObjectMapper();
		Log
		.forContext("MemberName", "getAllEvent")
		.forContext("Service", appName)
		.information("RabbitMQ : getAllEvent");
		try {
			res = mapper.writeValueAsString(events);
		} catch (JsonProcessingException e1) {
			Log
			.forContext("MemberName", "getAllEvent")
			.forContext("Service", appName)
			.error(e1,"JsonProcessingException");
		}
		return res;
	}

	/**
	 * method to get all the events type
	 * @param id
	 * @return
	 * @throws JsonProcessingException
	 */
	@RabbitListener(queues = "#{getAllEventTypeQueue.name}")
	public String getAllEventType(byte[] id){
		String res = "";
		List<EventType> eventsType = eventTypeRepository.findAll();
		ObjectMapper mapper = new ObjectMapper();
		Log
		.forContext("MemberName", "getAllEventType")
		.forContext("Service", appName)
		.information("RabbitMQ : getAllEventType");
		try {
			res = mapper.writeValueAsString(eventsType);
		} catch (JsonProcessingException e1) {
			Log
			.forContext("MemberName", "getAllEventType")
			.forContext("Service", appName)
			.error(e1,"JsonProcessingException");
		}
		return res;
	}

	/**
	 * method to search events by name/description/owner using fuzzi distance
	 * @param name
	 * @return
	 */
	@RabbitListener(queues = "#{searchEventByNameQueue.name}")
	public String searchEventByName(byte[] name){
		String res = null;
		List<Event> events = null;
		List<Event> resEvents = new ArrayList<>() ;
		SortedMap<Integer, ArrayList<Event>> indexedEvents = new TreeMap<Integer,  ArrayList<Event>>();
		try {
			Log
			.forContext("MemberName", "searchEventByName")
			.forContext("Service", appName)
			.forContext("name",new String(name, ENCODE))
			.information("RabbitMQ : searchEventByName");
		} catch (UnsupportedEncodingException e2) {
			Log
			.forContext("MemberName", "searchEventByName")
			.forContext("Service", appName)
			.error(e2,"UnsupportedEncodingException");
		}
		events = repository.findAll();

		for (Event e : events){
			try {
				int fuzzyName =FuzzySearch.tokenSetPartialRatio(e.getName(),new String(name, ENCODE));
				int fuzzyDescr =FuzzySearch.tokenSetPartialRatio(e.getDescription(),new String(name, ENCODE));
				int fuzzyOwner =FuzzySearch.tokenSetPartialRatio(e.getOwner().getPseudo(),new String(name, ENCODE));
				if (fuzzyName>70 || fuzzyDescr>80 || fuzzyOwner>90){
					int key = Math.max(Math.max(fuzzyName,fuzzyDescr),fuzzyOwner);
					List<Event> itemsList = indexedEvents.get(key);
					if(itemsList == null) {
					      itemsList = new ArrayList<>();
					      itemsList.add(e);
					      indexedEvents.put(key, (ArrayList<Event>) itemsList);
					}
					else{
						 itemsList.add(e);
					 }
				}
			} catch (UnsupportedEncodingException e1) {
				Log
				.forContext("MemberName", "searchEventByName")
				.forContext("Service", appName)
				.error(e1,"UnsupportedEncodingException");
			}
		}
		for(int i : indexedEvents.keySet()){
			for( Event eventToSend : indexedEvents.get(i)){
				resEvents.add(eventToSend);
			}
		}
		Collections.reverse(resEvents);
		ObjectMapper mapper = new ObjectMapper();
		Log
		.forContext("MemberName", "searchEventByName")
		.forContext("Service", appName)
		.information("RabbitMQ : searchEventByName");
		try {
			res = mapper.writeValueAsString(resEvents);
		} catch (JsonProcessingException e1) {
			Log
			.forContext("MemberName", "searchEventByName")
			.forContext("Service", appName)
			.error(e1,"JsonProcessingException");
		}
		return res;
	}

	/**
	 * method to get all upcomming events
	 * @param id
	 * @return
	 * @throws JsonProcessingException
	 * @throws UnsupportedEncodingException
	 * @throws NumberFormatException
	 */
	@RabbitListener(queues = "#{getUpcommingEventsQueue.name}")
	public String getUpcommingEvents(byte[] id){
		String res = "";
		int num = -1;
		try {
			num = Integer.parseInt(new String(id, ENCODE));
		} catch (NumberFormatException | UnsupportedEncodingException e) {
			Log
			.forContext("MemberName", "getUpcommingEvents")
			.forContext("Service", appName)
			.error(e,"Exception");
		}
		Pageable p = new PageRequest(0,num);
		List<Event> events = repository.getUpcommingEvents(new Date(), p);
		Log
		.forContext("MemberName", "getUpcommingEvents")
		.forContext("Service", appName)
		.information("RabbitMQ : getUpcommingEvents");
		ObjectMapper mapper = new ObjectMapper();
		try {
			res = mapper.writeValueAsString(events);
		} catch (JsonProcessingException e) {
			Log
			.forContext("MemberName", "getUpcommingEvents")
			.forContext("Service", appName)
			.error(e,"JsonProcessingException");
		}
		return res;
	}

}


text:
Apprity
=======

For jenkins git integration


text:
using Foundation;

namespace Dirigent.iOS.UI {
	[Register("SecondViewController")]
	partial class SecondViewController {
		void ReleaseDesignerOutlets() {
		}
	}
}


text: This is the ==ABOUT== page's content (included).


text:
/* NOTE: This file is autogenerated, do not edit this file directly.*/

#ifndef TRChartsJNI_Support_AxisLayoutInterfaceMarshaller_hpp
#define TRChartsJNI_Support_AxisLayoutInterfaceMarshaller_hpp

#include <TRChartsJNI/Support/BasicObjectMarshaller.hpp>
#include <TRCharts/AxisLayout.hpp>

namespace TRChartsJNI
{

	class AxisLayoutInterfaceMarshaller : public BasicObjectMarshaller<std::shared_ptr<Charts::AxisLayout>, jobject>
	{
	public:
		virtual std::shared_ptr<Charts::AxisLayout> marshall(JNIEnv * env, const jobject & in) const;

		virtual jobject unmarshall(JNIEnv * env, const std::shared_ptr<Charts::AxisLayout> & in) const;

	private:

		static bool inited;
		static jclass cls;
		static jmethodID midCalculateTransform;

		static void checkInited(JNIEnv * env);

		class Proxy;
	};
}

#endif


text:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import RegexValidator

def user_directory_path(instance, filename):
    return 'user_{0}/{1}'.format(instance.user.pk, filename)

class CustomUser(AbstractUser):
    username = models.CharField(
        'username',
        max_length=16,
        primary_key=True,
        help_text='Required. ID number.',
        validators=[RegexValidator(regex='^[0-9]{9}$',
                    message='Enter a valid ID number.')],
        error_messages={
            'unique': 'A user with that username already exists.',
        },
    )
    first_name = models.CharField('first name', max_length=30)
    last_name = models.CharField('last name', max_length=30)
    email = models.EmailField('email address')

    REQUIRED_FIELDS = ['first_name', 'last_name', 'email']

class Student(models.Model):
    user = models.OneToOneField(CustomUser,
                                verbose_name='ID number',
                                on_delete=models.CASCADE)
    bio = models.TextField(verbose_name='bio')
    cv = models.TextField(verbose_name='CV')
    pic = models.ImageField(verbose_name='profile picture',
                            upload_to='uploads')

    def __str__(self):
        return '{}'.format(self.user.get_username())


text:
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using OpenLiveWriter.Interop.Windows;

namespace OpenLiveWriter.CoreServices
{
    /// <summary>
    /// KeyboardHook used for monitoring (and optionally handling) key events for
    /// a window. You must always call the Remove() method to uninstall the hook when
    ///	you no longer need it or when the process or thread is terminating.
    ///	Failing to do this will result in an "orphaned" hook procedure which
    ///	may cause crashes and system instability!
    /// </summary>
    public abstract class KeyboardHook
    {
        /// <summary>
        /// Install a Keyboard hook on the thread of the passed hWnd
        /// </summary>
        /// <param name="hIEFrame">Handle to window to hook</param>
        public void Install(IntPtr hWnd)
        {
            // verify that Install is not called twice
            if (m_hHook != IntPtr.Zero)
            {
                // don't install redundantly in release, but warn in debug
                Debug.Assert(false, "Hook already installed");
                return;
            }

            // get the thread-id for the passed window
            uint dwThreadId = User32.GetWindowThreadProcessId(hWnd, IntPtr.Zero);

            // verify that the hook's thread and the current thread are the same
            Debug.Assert(dwThreadId == Kernel32.GetCurrentThreadId(),
                "Keyboard Hook not running on the same thread as hooked window!");

            Install(dwThreadId);
        }

        /// <summary>
        /// Install on the specified thread
        /// </summary>
        /// <param name="dwThreadId"></param>
        public void Install(uint dwThreadId)
        {
            // create the hook delegate and save a reference to it so that
            // it isn't garbage collected
            m_hookDelegate = new User32.HookDelegate(this.KeyboardProc);

            // install the hook for this thread
            m_hHook = User32.SetWindowsHookEx(
                WH.KEYBOARD, m_hookDelegate, IntPtr.Zero, dwThreadId);
            Trace.Assert(m_hHook != IntPtr.Zero, "Failed to install keyboard-hook!");
        }

        /// <summary>
        /// Determines whether the hook is currently installed
        /// </summary>
        public bool IsInstalled { get { return m_hHook != IntPtr.Zero; } }

        /// <summary>
        /// Remove the keyboard hook
        /// </summary>
        public void Remove()
        {
            // release hook if necessary (cleanly handle multiple remove calls)
            if (m_hHook != IntPtr.Zero)
            {
                // remove hook
                bool unhooked = User32.UnhookWindowsHookEx(m_hHook);

                // verify success in debug mode (ignore in release)
                Debug.Assert(unhooked, String.Format(CultureInfo.InvariantCulture,
                    "Win32 error number {0} occurred when attempting to " +
                    "remove keyboard hook.", Marshal.GetLastWin32Error()));

                // set handle to zero to prevent unhooking twice
                m_hHook = IntPtr.Zero;
            }

            // set hook delegate to null (allow it to be garbage collected)
            m_hookDelegate = null;
        }

        /// <summary>
        /// call the next hook in the chain
        /// </summary>
        protected IntPtr CallNextHook(int nCode, UIntPtr wParam, IntPtr lParam)
        {
            return User32.CallNextHookEx(m_hHook, nCode, wParam, lParam);
        }

        /// <summary>
        /// Keyboard hook handler (must be implemented by subclasses)
        /// </summary>
        /// <param name="nCode">HC_ACTION or HC_NOREMOVE</param>
        /// <param name="wParam">Virtual key code</param>
        /// <param name="lParam">Key state flags</param>
        /// <returns>1 to indicate key handled, otherwise next hook</returns>
        protected abstract IntPtr OnKeyHooked(int nCode, UIntPtr wParam, IntPtr lParam);

        /// <summary>
        /// Keyboard hook handler.
        /// </summary>
        /// <param name="nCode">HC_ACTION or HC_NOREMOVE</param>
        /// <param name="wParam">Virtual key code</param>
        /// <param name="lParam">Key state flags</param>
        /// <returns>1 to indicate key handled, otherwise next hook</returns>
        private IntPtr KeyboardProc(int nCode, UIntPtr wParam, IntPtr lParam)
        {
            try
            {
                return OnKeyHooked(nCode, wParam, lParam);
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Caught exception while handling keyboard hook: " + ex.ToString());
                return new IntPtr(1); // supress key from editor
            }
        }

        /// <summary>
        /// handle to keyboard hook
        /// </summary>
        private IntPtr m_hHook = IntPtr.Zero;

        /// <summary>
        /// Delegate for KeyboardProc (hold on to a reference to it so that it
        /// isn't garbarge collected)
        /// </summary>
        private User32.HookDelegate m_hookDelegate;
    }
}


text:
// ========================================================================
// $Id: Server.java,v 1.40 2005/10/21 13:52:11 gregwilkins Exp $
// Copyright 2002-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================

package net.lightbody.bmp.proxy.jetty.jetty;

import net.lightbody.bmp.proxy.jetty.http.HttpContext;
import net.lightbody.bmp.proxy.jetty.http.HttpServer;
import net.lightbody.bmp.proxy.jetty.jetty.servlet.ServletHttpContext;
import net.lightbody.bmp.proxy.jetty.jetty.servlet.WebApplicationContext;
import net.lightbody.bmp.proxy.jetty.log.LogFactory;
import net.lightbody.bmp.proxy.jetty.util.LogSupport;
import net.lightbody.bmp.proxy.jetty.util.Resource;
import net.lightbody.bmp.proxy.jetty.xml.XmlConfiguration;
import org.apache.commons.logging.Log;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/* ------------------------------------------------------------ */
/** The Jetty HttpServer.
 *
 * This specialization of org.mortbay.http.HttpServer adds knowledge
 * about servlets and their specialized contexts.   It also included
 * support for initialization from xml configuration files
 * that follow the XmlConfiguration dtd.
 *
 * HttpContexts created by Server are of the type
 * org.mortbay.jetty.servlet.ServletHttpContext unless otherwise
 * specified.
 *
 * This class also provides a main() method which starts a server for
 * each config file passed on the command line.  If the system
 * property JETTY_NO_SHUTDOWN_HOOK is not set to true, then a shutdown
 * hook is thread is registered to stop these servers.
 *
 * @see net.lightbody.bmp.proxy.jetty.xml.XmlConfiguration
 * @see net.lightbody.bmp.proxy.jetty.jetty.servlet.ServletHttpContext
 * @version $Revision: 1.40 $
 * @author Greg Wilkins (gregw)
 */
public class Server extends HttpServer
{
    static Log log = LogFactory.getLog(Server.class);
    private String[] _webAppConfigurationClassNames =
        new String[]{"XMLConfiguration", "JettyWebConfiguration"};
    private String _configuration;
    private String _rootWebApp;
    private static ShutdownHookThread hookThread = new ShutdownHookThread();

    /* ------------------------------------------------------------ */
    /** Constructor.
     */
    public Server()
    {
    }

    /* ------------------------------------------------------------ */
    /** Constructor.
     * @param configuration The filename or URL of the XML
     * configuration file.
     */
    public Server(String configuration)
        throws IOException
    {
        this(Resource.newResource(configuration).getURL());
    }

    /* ------------------------------------------------------------ */
    /** Constructor.
     * @param configuration The filename or URL of the XML
     * configuration file.
     */
    public Server(Resource configuration)
        throws IOException
    {
        this(configuration.getURL());
    }

    /* ------------------------------------------------------------ */
    /** Constructor.
     * @param configuration The filename or URL of the XML
     * configuration file.
     */
    public Server(URL configuration)
        throws IOException
    {
        _configuration=configuration.toString();
        Server.hookThread.add(this);
        try
        {
            XmlConfiguration config=new XmlConfiguration(configuration);
            config.configure(this);
        }
        catch(IOException e)
        {
            throw e;
        }
        catch(InvocationTargetException e)
        {
            log.warn(LogSupport.EXCEPTION,e.getTargetException());
            throw new IOException("Jetty configuration problem: "+e.getTargetException());
        }
        catch(Exception e)
        {
            log.warn(LogSupport.EXCEPTION,e);
            throw new IOException("Jetty configuration problem: "+e);
        }
    }

    /* ------------------------------------------------------------ */
    public boolean getStopAtShutdown()
    {
        return hookThread.contains(this);
    }

    /* ------------------------------------------------------------ */
    public void setStopAtShutdown(boolean stop)
    {
        if (stop)
            hookThread.add(this);
        else
            hookThread.remove(this);
    }

    /* ------------------------------------------------------------ */
    /** Get the root webapp name.
     * @return The name of the root webapp (eg. "root" for root.war).
     */
    public String getRootWebApp()
    {
        return _rootWebApp;
    }

    /* ------------------------------------------------------------ */
    /** Set the root webapp name.
     * @param rootWebApp The name of the root webapp (eg. "root" for root.war).
     */
    public void setRootWebApp(String rootWebApp)
    {
        _rootWebApp = rootWebApp;
    }

    /* ------------------------------------------------------------ */
    /**  Configure the server from an XML file.
     * @param configuration The filename or URL of the XML
     * configuration file.
     */
    public void configure(String configuration)
        throws IOException
    {

        URL url=Resource.newResource(configuration).getURL();
        if (_configuration!=null && _configuration.equals(url.toString()))
            return;
        if (_configuration!=null)
            throw new IllegalStateException("Already configured with "+_configuration);
        try
        {
            XmlConfiguration config=new XmlConfiguration(url);
            _configuration=url.toString();
            config.configure(this);
        }
        catch(IOException e)
        {
            throw e;
        }
        catch(Exception e)
        {
            log.warn(LogSupport.EXCEPTION,e);
            throw new IOException("Jetty configuration problem: "+e);
        }
    }

    /* ------------------------------------------------------------ */
    public String getConfiguration()
    {
        return _configuration;
    }

    /* ------------------------------------------------------------ */
    /** Create a new ServletHttpContext.
     * Ths method is called by HttpServer to creat new contexts.  Thus
     * calls to addContext or getContext that result in a new Context
     * being created will return an
     * org.mortbay.jetty.servlet.ServletHttpContext instance.
     * @return ServletHttpContext
     */
    protected HttpContext newHttpContext()
    {
        return new ServletHttpContext();
    }

    /* ------------------------------------------------------------ */
    /** Create a new WebApplicationContext.
     * Ths method is called by Server to creat new contexts for web
     * applications.  Thus calls to addWebApplication that result in
     * a new Context being created will return an correct class instance.
     * Derived class can override this method to create instance of its
     * own class derived from WebApplicationContext in case it needs more
     * functionality.
     * @param webApp The Web application directory or WAR file.
     * @return WebApplicationContext
     */
    protected WebApplicationContext newWebApplicationContext(
       String webApp
    )
    {
        return new WebApplicationContext(webApp);
    }

    /* ------------------------------------------------------------ */
    /** Add Web Application.
     * @param contextPathSpec The context path spec. Which must be of
     * the form / or /path/*
     * @param webApp The Web application directory or WAR file.
     * @return The WebApplicationContext
     * @exception IOException
     */
    public WebApplicationContext addWebApplication(String contextPathSpec,
                                                   String webApp)
        throws IOException
    {
        return addWebApplication(null,contextPathSpec,webApp);
    }

    /* ------------------------------------------------------------ */
    /** Add Web Application.
     * @param virtualHost Virtual host name or null
     * @param contextPathSpec The context path spec. Which must be of
     * the form / or /path/*
     * @param webApp The Web application directory or WAR file.
     * @return The WebApplicationContext
     * @exception IOException
     */
    public WebApplicationContext addWebApplication(String virtualHost,
                                                   String contextPathSpec,
                                                   String webApp)
        throws IOException
    {
        WebApplicationContext appContext =
            newWebApplicationContext(webApp);
        appContext.setContextPath(contextPathSpec);
        addContext(virtualHost,appContext);
        if(log.isDebugEnabled())log.debug("Web Application "+appContext+" added");
        return appContext;
    }

    /* ------------------------------------------------------------ */
    /**  Add Web Applications.
     * Add auto webapplications to the server.  The name of the
     * webapp directory or war is used as the context name. If a
     * webapp is called "root" it is added at "/".
     * @param webapps Directory file name or URL to look for auto webapplication.
     * @exception IOException
     */
    public WebApplicationContext[] addWebApplications(String webapps)
        throws IOException
    {
        return addWebApplications(null,webapps,null,false);
    }

    /* ------------------------------------------------------------ */
    /**  Add Web Applications.
     * Add auto webapplications to the server.  The name of the
     * webapp directory or war is used as the context name. If the
     * webapp matches the rootWebApp it is added as the "/" context.
     * @param host Virtual host name or null
     * @param webapps Directory file name or URL to look for auto webapplication.
     * @exception IOException
     */
    public WebApplicationContext[] addWebApplications(String host,
                                                      String webapps)
        throws IOException
    {
        return addWebApplications(host,webapps,null,false);
    }

    /* ------------------------------------------------------------ */
    /**  Add Web Applications.
     * Add auto webapplications to the server.  The name of the
     * webapp directory or war is used as the context name. If the
     * webapp matches the rootWebApp it is added as the "/" context.
     * @param host Virtual host name or null
     * @param webapps Directory file name or URL to look for auto
     * webapplication.
     * @param extract If true, extract war files
     * @exception IOException
     */
    public WebApplicationContext[] addWebApplications(String host,
                                                      String webapps,
                                                      boolean extract)
        throws IOException
    {
        return addWebApplications(host,webapps,null,extract);
    }

    /* ------------------------------------------------------------ */
    /**  Add Web Applications.
     * Add auto webapplications to the server.  The name of the
     * webapp directory or war is used as the context name. If the
     * webapp matches the rootWebApp it is added as the "/" context.
     * @param host Virtual host name or null
     * @param webapps Directory file name or URL to look for auto
     * webapplication.
     * @param defaults The defaults xml filename or URL which is
     * loaded before any in the web app. Must respect the web.dtd.
     * If null the default defaults file is used. If the empty string, then
     * no defaults file is used.
     * @param extract If true, extract war files
     * @exception IOException
     */
    public WebApplicationContext[] addWebApplications(String host,
                                                      String webapps,
                                                      String defaults,
                                                      boolean extract)
        throws IOException
    {
        return addWebApplications(host,webapps,defaults,extract,true);
    }

    /* ------------------------------------------------------------ */
    /**  Add Web Applications.
     * Add auto webapplications to the server.  The name of the
     * webapp directory or war is used as the context name. If the
     * webapp matches the rootWebApp it is added as the "/" context.
     * @param host Virtual host name or null
     * @param webapps Directory file name or URL to look for auto
     * webapplication.
     * @param defaults The defaults xml filename or URL which is
     * loaded before any in the web app. Must respect the web.dtd.
     * If null the default defaults file is used. If the empty string, then
     * no defaults file is used.
     * @param extract If true, extract war files
     * @param java2CompliantClassLoader True if java2 compliance is applied to all webapplications
     * @exception IOException
     */
    public WebApplicationContext[] addWebApplications(String host,
                                                      String webapps,
                                                      String defaults,
                                                      boolean extract,
						      boolean java2CompliantClassLoader)
        throws IOException
    {
        ArrayList wacs = new ArrayList();
        Resource r=Resource.newResource(webapps);
        if (!r.exists())
            throw new IllegalArgumentException("No such webapps resource "+r);

        if (!r.isDirectory())
            throw new IllegalArgumentException("Not directory webapps resource "+r);

        String[] files=r.list();

        for (int f=0;files!=null && f<files.length;f++)
        {
            String context=files[f];

            if (context.equalsIgnoreCase("CVS/") ||
                context.equalsIgnoreCase("CVS") ||
                context.startsWith("."))
                continue;

            String app = r.addPath(r.encode(files[f])).toString();
            if (context.toLowerCase().endsWith(".war") ||
                context.toLowerCase().endsWith(".jar"))
            {
                context=context.substring(0,context.length()-4);
                Resource unpacked=r.addPath(context);
                if (unpacked!=null && unpacked.exists() && unpacked.isDirectory())
                    continue;
            }

            if (_rootWebApp!=null && (context.equals(_rootWebApp)||context.equals(_rootWebApp+"/")))
                context="/";
            else
                context="/"+context;

            WebApplicationContext wac= addWebApplication(host,
                                                         context,
                                                         app);
            wac.setExtractWAR(extract);
	    wac.setClassLoaderJava2Compliant(java2CompliantClassLoader);
            if (defaults!=null)
            {
                if (defaults.length()==0)
                    wac.setDefaultsDescriptor(null);
                else
                    wac.setDefaultsDescriptor(defaults);
            }
            wacs.add(wac);
        }

        return (WebApplicationContext[])wacs.toArray(new WebApplicationContext[wacs.size()]);
    }

    /* ------------------------------------------------------------ */
    /** setWebApplicationConfigurationClasses
     * Set up the list of classnames of WebApplicationContext.Configuration
     * implementations that will be applied to configure every webapp.
     * The list can be overridden by individual WebApplicationContexts.
     * @param configurationClasses
     */
    public void setWebApplicationConfigurationClassNames (String[] configurationClassNames)
    {
        if (configurationClassNames != null)
        {
            _webAppConfigurationClassNames = new String[configurationClassNames.length];
            System.arraycopy(configurationClassNames, 0, _webAppConfigurationClassNames, 0, configurationClassNames.length);
        }
    }

    public String[] getWebApplicationConfigurationClassNames ()
    {
        return _webAppConfigurationClassNames;
    }

    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    public static void main(String[] arg)
    {
        String[] dftConfig={"etc/jetty.xml"};

        if (arg.length==0)
        {
            log.info("Using default configuration: etc/jetty.xml");
            arg=dftConfig;
        }

        final Server[] servers=new Server[arg.length];

        // create and start the servers.
        for (int i=0;i<arg.length;i++)
        {
            try
            {
                servers[i] = new Server(arg[i]);
                servers[i].setStopAtShutdown(true);
                servers[i].start();

            }
            catch(Exception e)
            {
                log.warn(LogSupport.EXCEPTION,e);
            }
        }

        // create and start the servers.
        for (int i=0;i<arg.length;i++)
        {
            try{servers[i].join();}
            catch (Exception e){LogSupport.ignore(log,e);}
        }
    }

   /**
    * ShutdownHook thread for stopping all servers.
    *
    * Thread is hooked first time list of servers is changed.
    */
  private static class ShutdownHookThread extends Thread {
    private boolean hooked = false;
    private ArrayList servers = new ArrayList();

    /**
     * Hooks this thread for shutdown.
     * @see java.lang.Runtime#addShutdownHook(java.lang.Thread)
     */
    private void createShutdownHook() {
      if (!Boolean.getBoolean("JETTY_NO_SHUTDOWN_HOOK") && !hooked) {
        try {
          Method shutdownHook = java.lang.Runtime.class.getMethod("addShutdownHook",
              new Class[] { java.lang.Thread.class });
          shutdownHook.invoke(Runtime.getRuntime(), new Object[] { this });
          this.hooked = true;
        } catch (Exception e) {
          if (log.isDebugEnabled()) log.debug("No shutdown hook in JVM ", e);
        }
      }
    }

    /**
     * Add Server to servers list.
     */
    public boolean add(Server server) {
      createShutdownHook();
      return this.servers.add(server);
    }

    /**
     * Contains Server in servers list?
     */
    public boolean contains(Server server) {
      return this.servers.contains(server);
    }

    /**
     * Append all Servers from Collection
     */
    public boolean addAll(Collection c) {
      createShutdownHook();
      return this.servers.addAll(c);
    }

    /**
     * Clear list of Servers.
     */
    public void clear() {
      createShutdownHook();
      this.servers.clear();
    }

    /**
     * Remove Server from list.
     */
    public boolean remove(Server server) {
      createShutdownHook();
      return this.servers.remove(server);
    }

    /**
     * Remove all Servers in Collection from list.
     */
    public boolean removeAll(Collection c) {
      createShutdownHook();
      return this.servers.removeAll(c);
    }

    /**
     * Stop all Servers in list.
     */
    public void run() {
      setName("Shutdown");
      log.info("Shutdown hook executing");
      Iterator it = servers.iterator();
      while (it.hasNext()) {
        Server svr = (Server) it.next();
        if (svr == null) continue;
        try {
          svr.stop();
        } catch (Exception e) {
          log.warn(LogSupport.EXCEPTION, e);
        }
        log.info("Shutdown hook complete");

        // Try to avoid JVM crash
        try {
          Thread.sleep(1000);
        } catch (Exception e) {
          log.warn(LogSupport.EXCEPTION, e);
        }
      }
    }
  }
}


text:
ACCEPTED

#### According to
World Register of Marine Species

#### Published in
J. Phycol. 45: 933

#### Original name
null

### Remarks
null


text:
require 'nba_stats/resources/box_score_misc'

module NbaStats

  module BoxScoreMisc

    # The path of the boxscoremisc API
    BOX_SCORE_MISC_PATH   = '/stats/boxscoremisc'

    # Calls the boxscoremisc API and returns a BoxScoreMisc resource.
    #
    # @param game_id [String]
    # @param range_type [Integer]
    # @param start_period [Integer]
    # @param end_period [Integer]
    # @param start_range [Integer]
    # @param end_range [Integer]
    # @return [NbaStats::Resources::BoxScoreMisc]
    def box_score_misc(
        game_id,
        range_type=0,
        start_period=0,
        end_period=0,
        start_range=0,
        end_range=0
    )
      NbaStats::Resources::BoxScoreMisc.new(
          get(BOX_SCORE_MISC_PATH, {
              :GameID => game_id,
              :RangeType => range_type,
              :StartPeriod => start_period,
              :EndPeriod => end_period,
              :StartRange => start_range,
              :EndRange => end_range
          })
      )
    end

  end # BoxScoreMisc

end


text:
<?php
namespace Cheetahmail\Data\Ssis;

class GetLastMappingStatusResponse
{

    /**
     * @var EnumStepStatus $GetLastMappingStatusResult
     */
    protected $GetLastMappingStatusResult = null;

    /**
     * @param EnumStepStatus $GetLastMappingStatusResult
     */
    public function __construct($GetLastMappingStatusResult)
    {
        $this->GetLastMappingStatusResult = $GetLastMappingStatusResult;
    }

    /**
     * @return EnumStepStatus
     */
    public function getGetLastMappingStatusResult()
    {
        return $this->GetLastMappingStatusResult;
    }

    /**
     * @param EnumStepStatus $GetLastMappingStatusResult
     * @return \Cheetahmail\Data\Ssis\GetLastMappingStatusResponse
     */
    public function setGetLastMappingStatusResult($GetLastMappingStatusResult)
    {
        $this->GetLastMappingStatusResult = $GetLastMappingStatusResult;
        return $this;
    }
}


text:
/* http://keith-wood.name/calendars.html
   Swedish localisation for Gregorian/Julian calendars for jQuery.
   Written by Anders Ekdahl (anders@nomadiz.se). */
(function($) {
	$.calendars.calendars.gregorian.prototype.regionalOptions['sv'] = {
		name: 'Gregorian',
		epochs: ['BCE', 'CE'],
        monthNames: ['Januari','Februari','Mars','April','Maj','Juni',
        'Juli','Augusti','September','Oktober','November','December'],
        monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
        'Jul','Aug','Sep','Okt','Nov','Dec'],
		dayNames: ['Söndag','Måndag','Tisdag','Onsdag','Torsdag','Fredag','Lördag'],
		dayNamesShort: ['Sön','Mån','Tis','Ons','Tor','Fre','Lör'],
		dayNamesMin: ['Sö','Må','Ti','On','To','Fr','Lö'],
        dateFormat: 'yyyy-mm-dd',
		firstDay: 1,
		isRTL: false
	};
	if ($.calendars.calendars.julian) {
		$.calendars.calendars.julian.prototype.regionalOptions['sv'] =
			$.calendars.calendars.gregorian.prototype.regionalOptions['sv'];
	}
})(jQuery);


text:
package com.amb_it_ion.refocus.view;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import rx.Observable;

public class DevScoreLogic {
	public static Observable<Double> scores(Observable<String> coverages,
			Observable<Set<String>> agilities,
			Observable<String> teamSizeStrings,
			Observable<String> pMTechnicalities, Observable<Boolean> vaadinUses) {
		Observable<Inputs> inputs = Observable.combineLatest(coverages,
				agilities, teamSizeStrings, pMTechnicalities, vaadinUses,
				DevScoreLogic::combineInputs);

		return inputs.filter(DevScoreLogic::areInputsValid).map(
				DevScoreLogic::inputsToScore);
	}

	public static Observable<List<String>> faults(Observable<String> coverages,
			Observable<Set<String>> agilities,
			Observable<String> teamSizeStrings,
			Observable<String> pMTechnicalities, Observable<Boolean> vaadinUses) {
		Observable<Inputs> inputs = Observable.combineLatest(coverages,
				agilities, teamSizeStrings, pMTechnicalities, vaadinUses,
				DevScoreLogic::combineInputs);

		return inputs.map(DevScoreLogic::invalidInputs).filter(
				invalidInputs -> {
					return !invalidInputs.isEmpty();
				});
	}

	private static boolean areInputsValid(Inputs inputs) {
		return invalidInputs(inputs).isEmpty();
	}

	private static List<String> invalidInputs(Inputs inputs) {
		List<String> result = new ArrayList<>();
		if (inputs.coverage == null)
			result.add("coverage");

		if (inputs.teamSize == 0)
			result.add("team size");

		if (inputs.PMTechnicality == null)
			result.add("PM technicality");

		return result;
	}

	private static Double inputsToScore(Inputs inputs) {
		Double result = 0.0;
		if (areInputsValid(inputs)) {
			// Each input is converted to a number between 0..1
			result += DevScorePresenter.coverages.get(inputs.coverage);

			result += (double) inputs.agility
					/ DevScorePresenter.agilities.size();

			result += Math.min(1.0, 3.0 / inputs.teamSize);

			result += DevScorePresenter.PMTechnicalities
					.get(inputs.PMTechnicality);

			result += inputs.vaadinUsed ? 1.0 : 0.5;

			result *= 20; // Map to range 0..100
		}

		return result;
	}

	private static Inputs combineInputs(String coverage, Set<String> agility,
			String teamSize, String PMTechnicality, Boolean vaadinUsed) {
		return new DevScoreLogic().new Inputs(coverage, agility, teamSize,
				PMTechnicality, vaadinUsed);
	}

	/**
	 * This class would be unneccessary if only Java 8 had tuples, like Scala or
	 * Groovy.
	 */
	private class Inputs {
		public String coverage;
		public int teamSize;
		public String PMTechnicality;
		public int agility;
		public boolean vaadinUsed;

		public Inputs(String coverage, Set<String> agilities,
				String teamSizeStr, String PMTechnicality, Boolean vaadinUsed) {
			this.coverage = coverage;

			this.agility = agilities != null ? agilities.size() : 0;

			try {
				teamSize = Integer.parseInt(teamSizeStr);
			} catch (NumberFormatException nfe) {
				teamSize = 0;
			}

			this.PMTechnicality = PMTechnicality;

			this.vaadinUsed = vaadinUsed != null ? vaadinUsed.booleanValue()
					: false;
		}
	}
}


text:
module RuboCop
  module Cop
    module Lint
      # This cop checks for setter call to local variable as the final
      # expression of a function definition.
      #
      # @example
      #
      #   # bad
      #
      #   def something
      #     x = Something.new
      #     x.attr = 5
      #   end
      #
      # @example
      #
      #   # good
      #
      #   def something
      #     x = Something.new
      #     x.attr = 5
      #     x
      #   end
      class UselessSetterCall < Cop
        include OnMethodDef

        MSG = 'Useless setter call to local variable `%s`.'.freeze
        ASSIGNMENT_TYPES = %i(lvasgn ivasgn cvasgn gvasgn).freeze

        private

        def on_method_def(_node, _method_name, _args, body)
          return unless body

          last_expr = last_expression(body)
          return unless setter_call_to_local_variable?(last_expr)

          tracker = MethodVariableTracker.new(body)
          receiver, = *last_expr
          variable_name, = *receiver
          return unless tracker.contain_local_object?(variable_name)

          add_offense(receiver, :name, format(MSG, receiver.loc.name.source))
        end

        def last_expression(body)
          expression = body.begin_type? ? body.children : body

          expression.is_a?(Array) ? expression.last : expression
        end

        def setter_call_to_local_variable?(node)
          return unless node && node.send_type?
          receiver, method, _args = *node
          return unless receiver && receiver.lvar_type?
          method =~ /(?:\w|\[\])=$/
        end

        # This class tracks variable assignments in a method body
        # and if a variable contains object passed as argument at the end of
        # the method.
        class MethodVariableTracker
          def initialize(body_node)
            @body_node = body_node
            @local = nil
          end

          def contain_local_object?(variable_name)
            return @local[variable_name] if @local

            @local = {}

            scan(@body_node) { |node| process_assignment_node(node) }

            @local[variable_name]
          end

          def scan(node, &block)
            catch(:skip_children) do
              yield node

              node.each_child_node do |child_node|
                scan(child_node, &block)
              end
            end
          end

          def process_assignment_node(node)
            case node.type
            when :masgn
              process_multiple_assignment(node)
            when :or_asgn, :and_asgn
              process_logical_operator_assignment(node)
            when :op_asgn
              process_binary_operator_assignment(node)
            when *ASSIGNMENT_TYPES
              _, rhs_node = *node
              process_assignment(node, rhs_node) if rhs_node
            end
          end

          def process_multiple_assignment(masgn_node)
            mlhs_node, mrhs_node = *masgn_node

            mlhs_node.children.each_with_index do |lhs_node, index|
              next unless ASSIGNMENT_TYPES.include?(lhs_node.type)

              lhs_variable_name, = *lhs_node
              rhs_node = mrhs_node.children[index]

              if mrhs_node.array_type? && rhs_node
                process_assignment(lhs_variable_name, rhs_node)
              else
                @local[lhs_variable_name] = true
              end
            end

            throw :skip_children
          end

          def process_logical_operator_assignment(asgn_node)
            lhs_node, rhs_node = *asgn_node
            return unless ASSIGNMENT_TYPES.include?(lhs_node.type)
            process_assignment(lhs_node, rhs_node)

            throw :skip_children
          end

          def process_binary_operator_assignment(op_asgn_node)
            lhs_node, = *op_asgn_node
            return unless ASSIGNMENT_TYPES.include?(lhs_node.type)
            lhs_variable_name, = *lhs_node
            @local[lhs_variable_name] = true

            throw :skip_children
          end

          def process_assignment(asgn_node, rhs_node)
            lhs_variable_name, = *asgn_node

            @local[lhs_variable_name] = if rhs_node.variable?
                                          rhs_variable_name, = *rhs_node
                                          @local[rhs_variable_name]
                                        else
                                          constructor?(rhs_node)
                                        end
          end

          def constructor?(node)
            return true if node.literal?
            return false unless node.send_type?
            _receiver, method = *node
            method == :new
          end
        end
      end
    end
  end
end