text:
/*
 * evdev: event device infrastructure
 *
 * Heavily based on FreeBSD's code in `sys/dev/evdev/`.
 */

#include <dev/evdev.h>
#include <sys/devfs.h>
#include <sys/queue.h>
#include <sys/mutex.h>
#include <sys/devfs.h>
#include <sys/vnode.h>
#include <sys/malloc.h>
#include <sys/device.h>
#include <bitstring.h>
#include <sys/event.h>
#include <sys/libkern.h>

/* Maximum length of an evdev device */
#define EVDEV_NAMELEN 80

/* Default parameters for a software emulation of key repetition. */
#define DEFAULT_REP_DELAY 250
#define DEFAULT_REP_PERIOD 33

/* The size of client's event queue (counted in the number of events) */
#define CLIENT_QUEUE_SIZE 32

/* evdev clock IDs in Linux semantic */
typedef enum {
  EV_CLOCK_REALTIME = 0, /* UTC clock */
  EV_CLOCK_MONOTONIC,    /* monotonic, stops on suspend */
  EV_CLOCK_BOOTTIME      /* monotonic, suspend-aware */
} evdev_clock_id_t;

/* Type definitions to abbreviate types used in the code below. */
typedef struct evdev_client evdev_client_t;
typedef LIST_HEAD(, evdev_client) evdev_client_list_t;
typedef struct input_id input_id_t;

/* The vnode of the /dev/input directory. */
static devfs_node_t *evdev_input_dir;

/*
 * `evdev_dev_t` is the main structure of every input device. It contains both
 * general informations about the device and its state. A name, device ID and
 * supported features flags are only used by user-space.
 *
 * `evdev_client_t` is created whenever the evdev file is opened. Its jobs is to
 * handle an interaction with the user-space. Every client has its private event
 * buffer. Every time an input event is issued, it firstly goes through
 * `evdev_dev_t` and then it is propagated to clients. This allows us to have
 * multiple, non-interfering readers of a single evdev device. Hence, every
 * input device has exactly one `evdev_dev_t`, but possibly can have many
 * `evdev_client_t` structures linked to it.
 *
 * Field markings and the corresponding locks:
 * (!) - read-only access
 * (s) - evdev_dev::ev_lock
 * (c) - evdev_client::ec_lock
 */
typedef struct evdev_dev {
  char ev_name[EVDEV_NAMELEN]; /* (!) name of the device */
  input_id_t ev_id;            /* (!) device ID */

  /* Supported features: */
  bitstr_t bit_decl(ev_type_flags, EV_CNT);    /* (!) supported event types */
  bitstr_t bit_decl(ev_key_flags, KEY_CNT);    /* (!) supported key codes */
  bitstr_t bit_decl(ev_rel_flags, REL_CNT);    /* (!) supported relative axes */
  bitstr_t bit_decl(ev_flags, EVDEV_FLAG_CNT); /* (!) supported features */

  /* Protects the data that is changed by incoming evdev events
   * and some ioctls. */
  mtx_t ev_lock;

  /* Repeat parameters & callout: */
  int ev_rep[REP_CNT]; /* (s) key repetition parameters (period and delay) */
  callout_t ev_rep_callout; /* (s) callout used for scheduling repetition */
  uint16_t ev_rep_key;      /* (s) currently repeated key */

  /* State: */
  bitstr_t bit_decl(ev_key_states, KEY_CNT); /* (s) state of all keys */
  evdev_client_list_t ev_clients; /* (s) clients associated with this device */
  evdev_client_t *ev_grabber;     /* (s) grabber pointer */
} evdev_dev_t;

/*
 * Events in an evdev client are stored in a ring buffer.
 *
 * Evdev client (e.g. user-space) is allowed to read events up to last EV_SYN,
 * which may not be the last element in the ring buffer. Thus we need to keep
 * track of last EV_SYN position in `ec_buffer_ready`.
 */
struct evdev_client {
  devnode_t ev_dev;                 /* (!) device node of this client */
  evdev_dev_t *ec_evdev;            /* (!) associated evdev device */
  LIST_ENTRY(evdev_client) ec_link; /* (s) link on client list */

  mtx_t ec_lock;      /* Protects various fields in evdev_client struct. */
  knlist_t ec_knlist; /* (c) knotes attached to this evdev client. */

  /* Event ring buffer implementation: */
  evdev_clock_id_t ec_clock_id; /* (c) clock used to timestamp events */
  condvar_t ec_buffer_cv;       /* (c) wait here for state change to happen */
  size_t ec_buffer_size;        /* (c) ring buffer capacity */
  size_t ec_buffer_ready;       /* (c) read limit (see note above) */
  size_t ec_buffer_head;        /* (c) read end */
  size_t ec_buffer_tail;        /* (c) write end */
  input_event_t ec_buffer[];    /* (c) stored events */
};

/*
 * Event client functions.
 */

static bool evdev_client_empty(evdev_client_t *client) {
  return client->ec_buffer_head == client->ec_buffer_ready;
}

/* Returns the number of events that are ready to read. */
static int evdev_client_queue_size(evdev_client_t *client) {
  size_t size = client->ec_buffer_size;
  size_t ready = client->ec_buffer_ready;
  size_t head = client->ec_buffer_head;
  if (ready < head)
    return ready + size - head;
  return ready - head;
}

/* Get time depending on the client clock id */
static timeval_t evdev_client_gettime(evdev_client_t *client) {
  bintime_t btnow;

  switch (client->ec_clock_id) {
    case EV_CLOCK_BOOTTIME:
      __fallthrough;
    case EV_CLOCK_MONOTONIC:
      btnow = binuptime();
      break;
    case EV_CLOCK_REALTIME:
      __fallthrough;
    default:
      btnow = bintime();
      break;
  }

  timeval_t now;
  bt2tv(&btnow, &now);
  return now;
}

/* Push a single event to client's queue */
static void evdev_client_push(evdev_client_t *client, uint16_t type,
                              uint16_t code, int32_t value) {
  assert(mtx_owned(&client->ec_lock));

  size_t head = client->ec_buffer_head;
  size_t tail = client->ec_buffer_tail;
  size_t ready = client->ec_buffer_ready;
  size_t count = client->ec_buffer_size;

  /* If queue is full drop its content and place SYN_DROPPED event */
  if (tail + 1 == head || (tail + 1 - count) == head) {
    head = ready = 0;
    client->ec_buffer[head] =
      (input_event_t){.type = EV_SYN, .code = SYN_DROPPED, .value = 0};
    client->ec_buffer_head = head;
    client->ec_buffer_ready = head;
    tail = 1;
  }

  client->ec_buffer[tail].type = type;
  client->ec_buffer[tail].code = code;
  client->ec_buffer[tail].value = value;
  client->ec_buffer_tail = (tail == count - 1) ? 0 : (tail + 1);
}

/* Call this function only if EV_SYN arrived and reporting was turned on. */
static void evdev_client_notify(evdev_client_t *client) {
  assert(mtx_owned(&client->ec_lock));

  size_t ready = client->ec_buffer_ready;
  size_t count = client->ec_buffer_size;
  timeval_t tv = evdev_client_gettime(client);

  /* give all reported events the same timestamp */
  while (ready != client->ec_buffer_tail) {
    client->ec_buffer[ready].time = tv;
    ready = (ready == count - 1) ? 0 : (ready + 1);
  }

  /* move `ready` pointer and notify readers */
  client->ec_buffer_ready = client->ec_buffer_tail;
  cv_broadcast(&client->ec_buffer_cv);

  knote(&client->ec_knlist, 0);
}

/* Pop one event from the client's queue. Assumes the queue is nonempty! */
static void evdev_client_pop(evdev_client_t *client, input_event_t *event) {
  assert(mtx_owned(&client->ec_lock));
  assert(!evdev_client_empty(client));

  input_event_t *head = client->ec_buffer + client->ec_buffer_head;
  bcopy(head, event, sizeof(input_event_t));
  client->ec_buffer_head = client->ec_buffer_head + 1;
  if (client->ec_buffer_head == client->ec_buffer_size)
    client->ec_buffer_head = 0;
}

/*
 * Event device functions.
 */

static bool evdev_event_supported(struct evdev_dev *evdev, uint16_t type) {
  assert(type < EV_CNT);
  return bit_test(evdev->ev_type_flags, type);
}

static void evdev_set_repeat_params(struct evdev_dev *evdev, uint16_t property,
                                    int value) {
  assert(property < REP_CNT);
  evdev->ev_rep[property] = value;
}

static bool evdev_handle_event_key(evdev_dev_t *evdev, uint16_t type,
                                   uint16_t code, int32_t value) {
  switch (value) {
    case KEY_EVENT_UP:
    case KEY_EVENT_DOWN:
      if (bit_test(evdev->ev_key_states, code) == (uint32_t)value)
        return false;

      if (value)
        bit_set(evdev->ev_key_states, code);
      else
        bit_clear(evdev->ev_key_states, code);
      break;

    case KEY_EVENT_REPEAT:
      if (!bit_test(evdev->ev_key_states, code) ||
          !evdev_event_supported(evdev, EV_REP))
        return false;
      break;
  }

  return true;
}

static bool evdev_handle_event_rep(evdev_dev_t *evdev, uint16_t type,
                                   uint16_t code, int32_t value) {
  if (evdev->ev_rep[code] == value)
    return false;
  evdev_set_repeat_params(evdev, code, value);
  return true;
}

/* Handle incoming event. Returns false if the event should be skipped. */
static bool evdev_handle_event(evdev_dev_t *evdev, uint16_t type, uint16_t code,
                               int32_t value) {
  assert(mtx_owned(&evdev->ev_lock));

  if (type == EV_KEY)
    return evdev_handle_event_key(evdev, type, code, value);
  if (type == EV_REP)
    return evdev_handle_event_rep(evdev, type, code, value);
  return true;
}

/* Send an event to evdev. */
static void evdev_send_event(evdev_dev_t *evdev, uint16_t type, uint16_t code,
                             int32_t value) {
  assert(mtx_owned(&evdev->ev_lock));

  if (!evdev_handle_event(evdev, type, code, value))
    return;

  /* Propagate one event to all clients
   * and notify them if it is the end of the event batch. */
  evdev_client_t *client;
  LIST_FOREACH (client, &evdev->ev_clients, ec_link) {
    if (evdev->ev_grabber && evdev->ev_grabber != client)
      continue;

    WITH_MTX_LOCK (&client->ec_lock) {
      evdev_client_push(client, type, code, value);
      /* Allow users to read events only after report has been completed */
      if (type == EV_SYN && code == SYN_REPORT)
        evdev_client_notify(client);
    }
  }
}

/* Callout function called every key repetition. */
static void evdev_repeat_callout(void *arg) {
  evdev_dev_t *evdev = (evdev_dev_t *)arg;

  SCOPED_MTX_LOCK(&evdev->ev_lock);

  evdev_send_event(evdev, EV_KEY, evdev->ev_rep_key, KEY_EVENT_REPEAT);
  evdev_send_event(evdev, EV_SYN, SYN_REPORT, 1);

  if (evdev->ev_rep[REP_PERIOD])
    callout_reschedule(&evdev->ev_rep_callout,
                       evdev->ev_rep[REP_PERIOD] * CLK_TCK / 1000);
  else
    evdev->ev_rep_key = KEY_RESERVED;
}

static void evdev_start_repeat(evdev_dev_t *evdev, uint16_t key) {
  assert(mtx_owned(&evdev->ev_lock));

  if (evdev->ev_rep[REP_DELAY]) {
    evdev->ev_rep_key = key;
    callout_schedule(&evdev->ev_rep_callout,
                     evdev->ev_rep[REP_DELAY] * CLK_TCK / 1000);
  }
}

static void evdev_stop_repeat(evdev_dev_t *evdev) {
  assert(mtx_owned(&evdev->ev_lock));

  if (evdev->ev_rep_key != KEY_RESERVED) {
    callout_stop(&evdev->ev_rep_callout);
    evdev->ev_rep_key = KEY_RESERVED;
  }
}

/* Start/stop the key repetition callout depending on the key and its state. */
static void evdev_soft_repeat(evdev_dev_t *evdev, uint16_t key, int32_t state) {
  assert(mtx_owned(&evdev->ev_lock));

  /* Don't start the callout when there are no clients */
  if (LIST_EMPTY(&evdev->ev_clients))
    return;

  if (bit_test(evdev->ev_key_states, key) == (unsigned)state)
    return;

  if (state == KEY_EVENT_DOWN)
    evdev_start_repeat(evdev, key);
  else
    evdev_stop_repeat(evdev);
}

/*
 * Device file interface implementation.
 */

static void evdev_kq_detach(knote_t *kn) {
  evdev_client_t *client = kn->kn_hook;

  WITH_MTX_LOCK (&client->ec_lock) {
    SLIST_REMOVE(&client->ec_knlist, kn, knote, kn_objlink);
  }
}

static int evdev_kq_read(knote_t *kn, long hint) {
  evdev_client_t *client = kn->kn_hook;
  assert(mtx_owned(&client->ec_lock));

  kn->kn_kevent.data = evdev_client_queue_size(client) * sizeof(input_event_t);
  return !evdev_client_empty(client);
}

static filterops_t evdev_filterops = {
  .filt_attach = NULL,
  .filt_detach = evdev_kq_detach,
  .filt_event = evdev_kq_read,
};

static int evdev_open(devnode_t *dev, file_t *fp, int oflags);
static int evdev_close(devnode_t *dev, file_t *fp);
static int evdev_read(devnode_t *dev, uio_t *uio);
static int evdev_ioctl(devnode_t *dev, u_long cmd, void *data, int fflags);
static int evdev_kqfilter(devnode_t *dev, knote_t *kn);

static devops_t evdev_devops = {
  .d_type = DT_OTHER,
  .d_open = evdev_open,
  .d_close = evdev_close,
  .d_read = evdev_read,
  .d_ioctl = evdev_ioctl,
  .d_kqfilter = evdev_kqfilter,
};

static int evdev_read(devnode_t *dev, uio_t *uio) {
  evdev_client_t *client = dev->data;
  int error = 0;

  uio->uio_offset = 0; /* This device does not support offsets. */

  /* Zero-sized reads are allowed for error checking */
  if (uio->uio_resid != 0 && uio->uio_resid < sizeof(input_event_t))
    return EINVAL;

  WITH_MTX_LOCK (&client->ec_lock) {
    int remaining = uio->uio_resid / sizeof(input_event_t);

    if (evdev_client_empty(client) && remaining) {
      error = cv_wait_intr(&client->ec_buffer_cv, &client->ec_lock);
      error = (error == EINTR) ? ERESTARTSYS : error;
    }

    while (!error && remaining && !evdev_client_empty(client)) {
      input_event_t event;
      evdev_client_pop(client, &event);

      mtx_unlock(&client->ec_lock);
      error = uiomove(&event, sizeof(input_event_t), uio);
      mtx_lock(&client->ec_lock);

      remaining--;
    }
  }

  return error;
}

static int evdev_grab_client(evdev_dev_t *evdev, evdev_client_t *client) {
  assert(mtx_owned(&evdev->ev_lock));

  if (evdev->ev_grabber)
    return EBUSY;

  evdev->ev_grabber = client;
  return 0;
}

static int evdev_release_client(evdev_dev_t *evdev, evdev_client_t *client) {
  assert(mtx_owned(&evdev->ev_lock));

  if (!evdev->ev_grabber)
    return EINVAL;

  evdev->ev_grabber = NULL;
  return 0;
}

/* Handle EVIOCGBIT ioctl, which returns the bitmaps of supported features. */
static int evdev_ioctl_eviocgbit(evdev_dev_t *evdev, int type, int len,
                                 caddr_t data) {
  bitstr_t *bitmap;
  int limit;

  switch (type) {
    case 0:
      bitmap = evdev->ev_type_flags;
      limit = bitstr_size(EV_CNT);
      break;
    case EV_KEY:
      bitmap = evdev->ev_key_flags;
      limit = bitstr_size(KEY_CNT);
      break;
    default:
      return EINVAL;
  }

  /* Clear ioctl data buffer in case it's bigger than bitmap size. */
  bzero(data, len);
  memcpy(data, bitmap, min(limit, len));
  return 0;
}

static int evdev_ioctl(devnode_t *dev, u_long cmd, void *data, int fflags) {
  evdev_client_t *client = dev->data;
  evdev_dev_t *evdev = client->ec_evdev;
  int err = 0;

  /* evdev fixed-length ioctls handling */
  switch (cmd) {
    case EVIOCGVERSION:
      *(int *)data = EV_VERSION;
      return 0;
    case EVIOCGID:
      memcpy(data, &evdev->ev_id, sizeof(struct input_id));
      return 0;
    case EVIOCGREP:
      if (!evdev_event_supported(evdev, EV_REP))
        return ENOTSUP;

      WITH_MTX_LOCK (&evdev->ev_lock)
        memcpy(data, evdev->ev_rep, sizeof(evdev->ev_rep));
      return 0;
    case EVIOCSCLOCKID:
      WITH_MTX_LOCK (&client->ec_lock) {
        switch (*(int *)data) {
          case CLOCK_REALTIME:
            client->ec_clock_id = EV_CLOCK_REALTIME;
            break;
          case CLOCK_MONOTONIC:
            client->ec_clock_id = EV_CLOCK_MONOTONIC;
            break;
          default:
            err = EINVAL;
        }
      }
      return err;
    case EVIOCGRAB:
      WITH_MTX_LOCK (&evdev->ev_lock) {
        if (*(int *)data)
          err = evdev_grab_client(evdev, client);
        else
          err = evdev_release_client(evdev, client);
      }
      return err;
  }

  /* evdev variable-length ioctls handling */
  size_t len = IOCPARM_LEN(cmd);
  int limit, type_num;

  switch (IOCBASECMD(cmd)) {
    case EVIOCGNAME(0):
      /* Linux evdev does not terminate truncated strings with 0 */
      limit = min(strlen(evdev->ev_name) + 1, len);
      memcpy(data, evdev->ev_name, limit);
      return 0;

    case EVIOCGKEY(0):
      limit = min(len, bitstr_size(KEY_CNT));
      WITH_MTX_LOCK (&evdev->ev_lock)
        memcpy(data, evdev->ev_key_states, limit);
      return 0;

    case EVIOCGBIT(0, 0)... EVIOCGBIT(EV_MAX, 0):
      type_num = IOCBASECMD(cmd) - EVIOCGBIT(0, 0);
      return evdev_ioctl_eviocgbit(evdev, type_num, len, data);
  }

  return EINVAL;
}

/* Called whenever a new knote is attached to this file. */
static int evdev_kqfilter(devnode_t *dev, knote_t *kn) {
  evdev_client_t *client = dev->data;

  if (kn->kn_kevent.filter != EVFILT_READ)
    return EINVAL;

  kn->kn_filtops = &evdev_filterops;
  kn->kn_hook = client;
  kn->kn_objlock = &client->ec_lock;

  WITH_MTX_LOCK (&client->ec_lock) {
    SLIST_INSERT_HEAD(&client->ec_knlist, kn, kn_objlink);
  }

  return 0;
}

static int evdev_open(devnode_t *master_dev, file_t *fp, int oflags) {
  evdev_dev_t *evdev = master_dev->data;

  if ((oflags & O_ACCMODE) != O_RDONLY)
    return EACCES;

  size_t client_size =
    sizeof(evdev_client_t) + sizeof(input_event_t) * CLIENT_QUEUE_SIZE;
  evdev_client_t *client = kmalloc(M_DEV, client_size, M_WAITOK | M_ZERO);

  devnode_t *dev = &client->ev_dev;
  dev->data = client;
  dev->ops = &evdev_devops;
  refcnt_acquire(&dev->refcnt);

  client->ec_buffer_size = CLIENT_QUEUE_SIZE;

  client->ec_evdev = evdev;
  mtx_init(&client->ec_lock, 0);
  cv_init(&client->ec_buffer_cv, "ec_buffer_cv");
  SLIST_INIT(&client->ec_knlist);

  WITH_MTX_LOCK (&evdev->ev_lock)
    LIST_INSERT_HEAD(&evdev->ev_clients, client, ec_link);

  fp->f_data = dev;

  return 0;
}

static void evdev_dispose_client(evdev_dev_t *evdev, evdev_client_t *client) {
  assert(mtx_owned(&evdev->ev_lock));

  LIST_REMOVE(client, ec_link);
  if (!LIST_EMPTY(&evdev->ev_clients))
    return;

  /* If there are no active clients left, stop the callout. */
  if (evdev_event_supported(evdev, EV_REP) &&
      bit_test(evdev->ev_flags, EVDEV_FLAG_SOFTREPEAT)) {
    evdev_stop_repeat(evdev);
  }
}

static int evdev_close(devnode_t *dev, file_t *fp) {
  evdev_client_t *client = dev->data;

  /* Unlink and free a `evdev_client_t` structure. */
  WITH_MTX_LOCK (&client->ec_evdev->ev_lock)
    evdev_dispose_client(client->ec_evdev, client);

  mtx_destroy(&client->ec_mtx);
  cv_destroy(&client->ec_buffer_cv);
  kfree(M_DEV, client);
  return 0;
}

/* Create a devfs device for a given evdev. */
static int evdev_dev_create(evdev_dev_t *evdev) {
  char buf[16];
  int ret, unit = 0;

  /* Find the first free number for that device.
   * FIXME Not the best solution, but will do for now. */
  do {
    snprintf(buf, sizeof(buf), "event%d", unit);
    ret = devfs_makedev_new(evdev_input_dir, buf, &evdev_devops, evdev, NULL);
    unit++;
  } while (ret == EEXIST);

  return ret;
}

/*
 * Evdev public interface (described in the header file).
 */

evdev_dev_t *evdev_alloc(void) {
  return kmalloc(M_DEV, sizeof(evdev_dev_t), M_WAITOK | M_ZERO);
}

void evdev_free(evdev_dev_t *evdev) {
  kfree(M_DEV, evdev);
}

void evdev_set_name(evdev_dev_t *evdev, const char *name) {
  snprintf(evdev->ev_name, EVDEV_NAMELEN, "%s", name);
}

void evdev_set_id(evdev_dev_t *evdev, uint16_t bustype, uint16_t vendor,
                  uint16_t product, uint16_t version) {
  evdev->ev_id = (input_id_t){.bustype = bustype,
                              .vendor = vendor,
                              .product = product,
                              .version = version};
}

void evdev_support_event(evdev_dev_t *evdev, uint16_t type) {
  assert(type < EV_CNT);
  bit_set(evdev->ev_type_flags, type);
}

void evdev_support_key(evdev_dev_t *evdev, uint16_t code) {
  assert(code < KEY_CNT);
  bit_set(evdev->ev_key_flags, code);
}

void evdev_support_all_keys(evdev_dev_t *evdev, uint16_t *keyset,
                            size_t nitems) {
  for (size_t i = 0; i < nitems; i++) {
    uint16_t keycode = keyset[i];
    if (keycode != KEY_RESERVED)
      evdev_support_key(evdev, keycode);
  }
}

void evdev_support_rel(evdev_dev_t *evdev, uint16_t code) {
  assert(code < REL_CNT);
  bit_set(evdev->ev_rel_flags, code);
}

void evdev_set_flag(evdev_dev_t *evdev, uint16_t flag) {
  assert(flag < EVDEV_FLAG_CNT);
  bit_set(evdev->ev_flags, flag);
}

int evdev_register(evdev_dev_t *evdev) {
  mtx_init(&evdev->ev_lock, 0);
  LIST_INIT(&evdev->ev_clients);

  /* Initialize callout */
  callout_setup(&evdev->ev_rep_callout, evdev_repeat_callout, evdev);
  if (evdev->ev_rep[REP_DELAY] == 0 && evdev->ev_rep[REP_PERIOD] == 0) {
    /* Supply default values */
    evdev_set_repeat_params(evdev, REP_DELAY, DEFAULT_REP_DELAY);
    evdev_set_repeat_params(evdev, REP_PERIOD, DEFAULT_REP_PERIOD);
  }

  return evdev_dev_create(evdev);
}

void evdev_push_event(evdev_dev_t *evdev, uint16_t type, uint16_t code,
                      int32_t value) {
  SCOPED_MTX_LOCK(&evdev->ev_lock);

  if (type == EV_KEY && evdev_event_supported(evdev, EV_REP)) {
    if (bit_test(evdev->ev_flags, EVDEV_FLAG_SOFTREPEAT)) {
      /* Start/stop callout for evdev repeats */
      evdev_soft_repeat(evdev, code, value);
    } else {
      /* Detect driver key repeats. */
      if (bit_test(evdev->ev_key_states, code) && value == KEY_EVENT_DOWN)
        value = KEY_EVENT_REPEAT;
    }
  }

  evdev_send_event(evdev, type, code, value);
}

static void init_evdev(void) {
  if (devfs_makedir(NULL, "input", &evdev_input_dir) != 0)
    panic("failed to create /dev/input directory");
}

SET_ENTRY(devfs_init, init_evdev);


text:
from __future__ import print_function, division
import os
import sys
import subprocess

def class_process(dir_path, dst_dir_path, class_name):
  class_path = os.path.join(dir_path, class_name)
  if not os.path.isdir(class_path):
    return

  dst_class_path = os.path.join(dst_dir_path, class_name)
  if not os.path.exists(dst_class_path):
    os.mkdir(dst_class_path)

  for file_name in os.listdir(class_path):
    if '.mp4' not in file_name:
      continue
    name, ext = os.path.splitext(file_name)
    dst_directory_path = os.path.join(dst_class_path, name)

    video_file_path = os.path.join(class_path, file_name)
    try:
      if os.path.exists(dst_directory_path):
        if not os.path.exists(os.path.join(dst_directory_path, 'image_00001.jpg')):
          subprocess.call('rm -r \"{}\"'.format(dst_directory_path), shell=True)
          print('remove {}'.format(dst_directory_path))
          os.mkdir(dst_directory_path)
        else:
          continue
      else:
        os.mkdir(dst_directory_path)
    except:
      print(dst_directory_path)
      continue
    cmd = 'ffmpeg -i \"{}\" -vf scale=-1:240 \"{}/image_%05d.jpg\"'.format(video_file_path, dst_directory_path)
    print(cmd)
    subprocess.call(cmd, shell=True)
    print('\n')

if __name__=="__main__":
  dir_path = sys.argv[1]
  dst_dir_path = sys.argv[2]

  for class_name in os.listdir(dir_path):
    class_process(dir_path, dst_dir_path, class_name)

  class_name = 'test'
  class_process(dir_path, dst_dir_path, class_name)

redpajama_set_name: RedPajamaGithub


text:
package org.netbeans.lib.cvsclient.command.checkout;

import org.netbeans.lib.cvsclient.event.ICvsListener;
import org.netbeans.lib.cvsclient.event.ICvsListenerRegistry;
import org.netbeans.lib.cvsclient.event.IModuleExpansionListener;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Thomas Singer
 */
final class ExpandedModules implements ICvsListener, IModuleExpansionListener {

  // Fields =================================================================

  private final List<String> modules = new LinkedList<String>();

  // Setup ==================================================================

  public ExpandedModules() {
  }

  // Implemented ============================================================

  public void moduleExpanded(String module) {
    modules.add(module);
  }

  public void registerListeners(ICvsListenerRegistry listenerRegistry) {
    listenerRegistry.addModuleExpansionListener(this);
  }

  public void unregisterListeners(ICvsListenerRegistry listenerRegistry) {
    listenerRegistry.removeModuleExpansionListener(this);
  }

  // Accessing ==============================================================

  public List<String> getModules() {
    return Collections.unmodifiableList(modules);
  }
}


text:
package com.github.cchao.touchnews.util;

import android.content.Context;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.github.cchao.touchnews.BaseApplication;

import org.json.JSONObject;

import java.util.Map;

/**
 * Created by cchao on 2016/4/5.
 * E-mail:   cchao1024@163.com
 * Description: Volley 网络请求util
 */
public class NetRequestUtil {
    public final String TAG = this.getClass().getSimpleName();
    Context mContext = BaseApplication.getContext();
    public static RequestQueue mRequestQueue = Volley.newRequestQueue(BaseApplication.getContext());
    private static NetRequestUtil netRequestUtil;

    private NetRequestUtil() {
    }

    public static NetRequestUtil getInstance() {
        if (netRequestUtil == null) {
            synchronized (NetRequestUtil.class) {
                if (netRequestUtil == null)
                    netRequestUtil = new NetRequestUtil();
            }
        }
        return netRequestUtil;
    }

    /**
     * get请求获取JsonObject
     *
     * @param url      url
     * @param param    param
     * @param listener callback
     */
    public void getJson(String url, Map<String, String> param, final RequestListener listener) {
        url += prepareParam(param);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                listener.onResponse(response);
                Log.i(TAG, response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listener.onError(error);
                Log.i(TAG, error.getMessage(), error);
            }
        });
        mRequestQueue.add(jsonObjectRequest);
    }

    /**
     * get请求获取JsonObject 带Headers参数
     *
     * @param url      url
     * @param param    param
     * @param listener callback
     */
    public void getJsonWithHeaders(String url, final Map<String, String> param, final Map<String, String> headers, final RequestListener listener) {
        url += prepareParam(param);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                listener.onResponse(response);
//                                Log.i ( TAG, response.toString ( ) );
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listener.onError(error);
//                                Log.i ( TAG, error.getMessage ( ), error );
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                if (headers == null) {
                    return super.getHeaders();
                } else {
                    return headers;
                }

            }

        };
        mRequestQueue.add(jsonObjectRequest);

    }

    public void post(String url, final Map<String, String> param, final NetRequestUtil.RequestListener listener) {
        final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                listener.onResponse(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listener.onError(error);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return param;
            }
        };
        mRequestQueue.add(jsonObjectRequest);
    }

    private String prepareParam(Map<String, String> paramMap) {

        if (paramMap == null || paramMap.isEmpty()) {
            return "";
        } else {
            StringBuffer sb = new StringBuffer();
            sb.append("?");
            for (String key : paramMap.keySet()) {
                String value = (String) paramMap.get(key);
                if (sb.length() < 1) {
                    sb.append(key).append("=").append(value);
                } else {
                    sb.append("&").append(key).append("=").append(value);
                }
            }
            return sb.toString();
        }
    }

    public void cancelAll(Object tag) {
        mRequestQueue.cancelAll(tag);
    }

    public interface RequestListener {
        public void onResponse(JSONObject response);

        public void onError(VolleyError error);
    }
}


text:
require 'thread'
require 'timeout'

require 'aerospike/atomic/atomic'

module Aerospike

  private

  class Cluster

    attr_reader :connection_timeout, :connection_queue_size, :user, :password

    def initialize(policy, *hosts)
      @cluster_seeds = hosts
      @connection_queue_size = policy.connection_queue_size
      @connection_timeout = policy.timeout
      @aliases = {}
      @cluster_nodes = []
      @partition_write_map = {}
      @node_index = Atomic.new(0)
      @closed = Atomic.new(true)
      @mutex = Mutex.new

      # setup auth info for cluster
      if policy.requires_authentication
        @user = policy.user
        @password = AdminCommand.hash_password(policy.password)
      end

      wait_till_stablized

      if policy.fail_if_not_connected && !connected?
        raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::SERVER_NOT_AVAILABLE)
      end

      launch_tend_thread

      Aerospike.logger.info('New cluster initialized and ready to be used...')

      self
    end

    def add_seeds(hosts)
      @mutex.synchronize do
        @cluster_seeds.concat(hosts)
      end
    end

    def seeds
      @mutex.synchronize do
        @cluster_seeds.dup
      end
    end

    def connected?
      # Must copy array reference for copy on write semantics to work.
      node_array = nodes
      (node_array.length > 0) && !@closed.value
    end

    def get_node(partition)
      # Must copy hashmap reference for copy on write semantics to work.
      nmap = partitions
      if node_array = nmap[partition.namespace]
        node = node_array.value[partition.partition_id]

        if node && node.active?
          return node
        end
      end

      return random_node
    end

    # Returns a random node on the cluster
    def random_node
      # Must copy array reference for copy on write semantics to work.
      node_array = nodes
      length = node_array.length
      i = 0
      while i < length
        # Must handle concurrency with other non-tending threads, so node_index is consistent.
        index = (@node_index.update{|v| v+1} % node_array.length).abs
        node = node_array[index]

        if node.active?
          return node
        end

        i = i.succ
      end
      raise Aerospike::Exceptions::InvalidNode.new
    end

    # Returns a list of all nodes in the cluster
    def nodes
      @mutex.synchronize do
        # Must copy array reference for copy on write semantics to work.
        @cluster_nodes.dup
      end
    end

    # Find a node by name and returns an error if not found
    def get_node_by_name(node_name)
      node = find_node_by_name(node_name)

      raise Aerospike::Exceptions::InvalidNode.new unless node

      node
    end

    # Closes all cached connections to the cluster nodes and stops the tend thread
    def close
      unless @closed.value
        # send close signal to maintenance channel
        @closed.value = true
        @tend_thread.kill

        nodes.each do |node|
          node.close
        end
      end

    end

    def find_alias(aliass)
      @mutex.synchronize do
        @aliases[aliass]
      end
    end

    def update_partitions(conn, node)
      # TODO: Cluster should not care about version of tokenizer
      # decouple clstr interface
      nmap = {}
      if node.use_new_info?
        Aerospike.logger.info("Updating partitions using new protocol...")

        tokens = PartitionTokenizerNew.new(conn)
        nmap = tokens.update_partition(partitions, node)
      else
        Aerospike.logger.info("Updating partitions using old protocol...")
        tokens = PartitionTokenizerOld.new(conn)
        nmap = tokens.update_partition(partitions, node)
      end

      # update partition write map
      set_partitions(nmap) if nmap

      Aerospike.logger.info("Partitions updated...")
    end

    def request_info(policy, *commands)
      node = random_node
      conn = node.get_connection(policy.timeout)
      Info.request(conn, *commands).tap do
        node.put_connection(conn)
      end
    end

    def change_password(user, password)
     # change password ONLY if the user is the same
     @password = password if @user == user
    end

    private

    def launch_tend_thread
      @tend_thread = Thread.new do
        abort_on_exception = false
        while true
          begin
            tend
            sleep 1 # 1 second
          rescue => e
            Aerospike.logger.error("Exception occured during tend: #{e}")
          end
        end
      end
    end

    def tend
      nodes = self.nodes

      # All node additions/deletions are performed in tend thread.
      # If active nodes don't exist, seed cluster.
      if nodes.empty?
        Aerospike.logger.info("No connections available; seeding...")
        seed_nodes

        # refresh nodes list after seeding
        nodes = self.nodes
      end

      # Refresh all known nodes.
      friend_list = []
      refresh_count = 0

      # Clear node reference counts.
      nodes.each do |node|
        node.reference_count.value = 0
        node.responded.value = false

        if node.active?
          begin
            friends = node.refresh
            refresh_count += 1
            friend_list.concat(friends) if friends
          rescue => e
            Aerospike.logger.error("Node `#{node}` refresh failed: #{e.backtrace.join("\n")}")
          end
        end
      end

      # Add nodes in a batch.
      add_list = find_nodes_to_add(friend_list)
      add_nodes(add_list) unless add_list.empty?

      # Handle nodes changes determined from refreshes.
      # Remove nodes in a batch.
      remove_list = find_nodes_to_remove(refresh_count)
      remove_nodes(remove_list) unless remove_list.empty?

      # Guard clause to prevent show tend_info because is disabled by config.
      # See documentation
      return unless Aerospike.tend_info
      Aerospike.logger.info("Tend finished. Live node count: #{nodes.length}")
    end

    def wait_till_stablized
      count = -1

      # will run until the cluster is stablized
      thr = Thread.new do
        abort_on_exception=true
        while true
          tend

          # Check to see if cluster has changed since the last Tend.
          # If not, assume cluster has stabilized and return.
          if count == nodes.length
            break
          end

          sleep(0.001) # sleep for a miliseconds

          count = nodes.length
        end
      end

      # wait for the thread to finish or timeout
      begin
        Timeout.timeout(1) do
          thr.join
        end
      rescue Timeout::Error
        thr.kill if thr.alive?
      end

      @closed.value = false if @cluster_nodes.length > 0

    end

    def set_partitions(part_map)
      @mutex.synchronize do
        @partition_write_map = part_map
      end
    end

    def partitions
      res = nil
      @mutex.synchronize do
        res = @partition_write_map
      end

      res
    end

    def seed_nodes
      seed_array = seeds

      Aerospike.logger.info("Seeding the cluster. Seeds count: #{seed_array.length}")

      list = []

      seed_array.each do |seed|
        begin
          seed_node_validator = NodeValidator.new(self, seed, @connection_timeout)
        rescue => e
          Aerospike.logger.error("Seed #{seed.to_s} failed: #{e.backtrace.join("\n")}")
          next
        end

        nv = nil
        # Seed host may have multiple aliases in the case of round-robin dns configurations.
        seed_node_validator.aliases.each do |aliass|

          if aliass == seed
            nv = seed_node_validator
          else
            begin
              nv = NodeValidator.new(self, aliass, @connection_timeout)
            rescue Exection => e
              Aerospike.logger.error("Seed #{seed.to_s} failed: #{e}")
              next
            end
          end

          if !find_node_name(list, nv.name)
            node = create_node(nv)
            add_aliases(node)
            list << node
          end
        end

      end

      if list.length > 0
        add_nodes_copy(list)
      end

    end

    # Finds a node by name in a list of nodes
    def find_node_name(list, name)
      list.any?{|node| node.name == name}
    end

    def add_alias(host, node)
      if host && node
        @mutex.synchronize do
          @aliases[host] = node
        end
      end
    end

    def remove_alias(aliass)
      if aliass
        @mutex.synchronize do
          @aliases.delete(aliass)
        end
      end
    end

    def find_nodes_to_add(hosts)
      list = []

      hosts.each do |host|
        begin
          nv = NodeValidator.new(self, host, @connection_timeout)

          # if node is already in cluster's node list,
          # or already included in the list to be added, we should skip it
          node = find_node_by_name(nv.name)
          node ||= list.detect{|n| n.name == nv.name}

          # make sure node is not already in the list to add
          if node
            # Duplicate node name found.  This usually occurs when the server
            # services list contains both internal and external IP addresses
            # for the same node.  Add new host to list of alias filters
            # and do not add new node.
            node.reference_count.update{|v| v + 1}
            node.add_alias(host)
            add_alias(host, node)
            next
          end

          node = create_node(nv)
          list << node

        rescue => e
          Aerospike.logger.error("Add node #{node.to_s} failed: #{e}")
        end
      end

      list
    end

    def create_node(nv)
      Node.new(self, nv)
    end

    def find_nodes_to_remove(refresh_count)
      node_list = nodes

      remove_list = []

      node_list.each do |node|
        if !node.active?
          # Inactive nodes must be removed.
          remove_list << node
          next
        end

        case node_list.length
        when 1
          # Single node clusters rely solely on node health.
          remove_list << node if node.unhealthy?

        when 2
          # Two node clusters require at least one successful refresh before removing.
          if refresh_count == 2 && node.reference_count.value == 0 && !node.responded.value
            # Node is not referenced nor did it respond.
            remove_list << node
          end

        else
          # Multi-node clusters require two successful node refreshes before removing.
          if refresh_count >= 2 && node.reference_count.value == 0
            # Node is not referenced by other nodes.
            # Check if node responded to info request.
            if node.responded.value
              # Node is alive, but not referenced by other nodes.  Check if mapped.
              if !find_node_in_partition_map(node)
                # Node doesn't have any partitions mapped to it.
                # There is not point in keeping it in the cluster.
                remove_list << node
              end
            else
              # Node not responding. Remove it.
              remove_list << node
            end
          end
        end
      end

      remove_list
    end

    def find_node_in_partition_map(filter)
      partitions_list = partitions

      partitions_list.each do |node_array|
        max = node_array.length

        i = 0
        while i < max
          node = node_array[i]
          # Use reference equality for performance.
          if node == filter
            return true
          end

          i = i.succ
        end
      end
      false
    end

    def add_nodes(nodes_to_add)
      # Add all nodes at once to avoid copying entire array multiple times.
      nodes_to_add.each do |node|
        add_aliases(node)
      end

      add_nodes_copy(nodes_to_add)
    end

    def add_aliases(node)
      # Add node's aliases to global alias set.
      # Aliases are only used in tend thread, so synchronization is not necessary.
      node.get_aliases.each do |aliass|
        @aliases[aliass] = node
      end
    end

    def add_nodes_copy(nodes_to_add)
      @mutex.synchronize do
        @cluster_nodes.concat(nodes_to_add)
      end
    end

    def remove_nodes(nodes_to_remove)
      # There is no need to delete nodes from partition_write_map because the nodes
      # have already been set to inactive. Further connection requests will result
      # in an exception and a different node will be tried.

      # Cleanup node resources.
      nodes_to_remove.each do |node|
        # Remove node's aliases from cluster alias set.
        # Aliases are only used in tend thread, so synchronization is not necessary.
        node.get_aliases.each do |aliass|
          Aerospike.logger.debug("Removing alias #{aliass}")
          remove_alias(aliass)
        end

        node.close
      end

      # Remove all nodes at once to avoid copying entire array multiple times.
      remove_nodes_copy(nodes_to_remove)
    end

    def set_nodes(nodes)
      @mutex.synchronize do
        # Replace nodes with copy.
        @cluster_nodes = nodes
      end
    end

    def remove_nodes_copy(nodes_to_remove)
      # Create temporary nodes array.
      # Since nodes are only marked for deletion using node references in the nodes array,
      # and the tend thread is the only thread modifying nodes, we are guaranteed that nodes
      # in nodes_to_remove exist.  Therefore, we know the final array size.
      nodes_list = nodes
      node_array = []
      count = 0

      # Add nodes that are not in remove list.
      nodes_list.each do |node|
        if node_exists(node, nodes_to_remove)
          Aerospike.logger.info("Removed node `#{node}`")
        else
          node_array[count] = node
          count += 1
        end
      end

      # Do sanity check to make sure assumptions are correct.
      if count < node_array.length
        Aerospike.logger.warn("Node remove mismatch. Expected #{node_array.length}, Received #{count}")

        # Resize array.
        node_array = node_array.dup[0..count-1]
      end

      set_nodes(node_array)
    end

    def node_exists(search, node_list)
      node_list.any? {|node| node == search }
    end

    def find_node_by_name(node_name)
      nodes.detect{|node| node.name == node_name }
    end

  end

end


text: Requirements editor eclipse plugin


text:
var port = 34236;
var serverUrl = "http://pushapi.eval.blackberry.com";
var appId = "4363-875258kB87i6580O39c346m7h9e4a512ei2";
var max = 100;
var wakeUpPage = "index.html";
function openBISPushListener() {
	try {
		var bisRegistered = localStorage.getItem("bisRegistered");

		if (bisRegistered != null && bisRegistered)
		{
			onRegister(0);
		}
		else
		{
			showMessage("Open BIS push listener...");

			var ops = {port : port, appId : appId, serverUrl : serverUrl, wakeUpPage : wakeUpPage, maxQueueCap : max};
			blackberry.push.openBISPushListener(ops, onData, onRegister, onSimChange);
		}
	}
	catch (err) {
		showMessage("Open BIS push listener error: " + err);
	}
}

function onRegister(status) {
	if (status == 0) {
		localStorage.setItem("bisRegistered", true);

		var pushwooshRegistered = localStorage.getItem("pushwooshRegistered");
		if (pushwooshRegistered != null && pushwooshRegistered)
		{
			onPushwooshRegisterSuccess();
		}
		else
		{
			showMessage("Register on Pushwoosh...");
			PushWoosh.register(function(data) {
					localStorage.setItem("pushwooshRegistered", true);

					onPushwooshRegisterSuccess();
		        }, function(errorregistration) {
		            showMessage("Register on Pushwoosh error: " + errorregistration);
		        });
		}
	}
	else if (status == 1) {
		showMessage("push register status network error: " + status);
	}
	else if (status == 2) {
		showMessage("push register status rejected by server");
	}
	else if (status == 3) {
		showMessage("push register status invalid parameters");
	}
	else if (status == -1) {
		showMessage("push register status general error");
	}
	else {
		showMessage("push register status unknown");
	}
}

function onPushwooshRegisterSuccess() {
	showMessage("Register on Pushwoosh success.");
}

function onData(data) {
	localStorage.setItem("push", JSON.parse(blackberry.utils.blobToString(data.payload)).m);

	blackberry.app.showBannerIndicator("img/banner.png");

	showPush();

	return 0;
}

function onSimChange() {
	showMessage("SIM changed");
}


text:
using Azure.Core.TestFramework;

namespace Azure.ResourceManager.Cdn.Tests
{
    public class CdnManagementTestEnvironment : TestEnvironment
    {
    }
}


text:
namespace swift {

/// An implementation of Clang's AbstractBasicReader interface for a Swift
/// datastream-based reader.  This is paired with the AbstractBasicWriter
/// implementation in SwiftAbstractBasicWriter.h.  Note that the general
/// expectation is that the types and declarations involved will have passed
/// a serializability check when this is used for actual deserialization.
///
/// The subclass must implement:
///   uint64_t readUInt64();
///   clang::IdentifierInfo *readIdentifier();
///   clang::Stmt *readStmtRef();
///   clang::Decl *readDeclRef();
template <class Impl>
class DataStreamBasicReader
       : public clang::serialization::DataStreamBasicReader<Impl> {
  using super = clang::serialization::DataStreamBasicReader<Impl>;
public:
  using super::asImpl;
  using super::getASTContext;

  DataStreamBasicReader(clang::ASTContext &ctx) : super(ctx) {}

  /// Perform all the calls necessary to write out the given type.
  clang::QualType readTypeRef() {
    auto kind = clang::Type::TypeClass(asImpl().readUInt64());
    return clang::serialization::AbstractTypeReader<Impl>(asImpl()).read(kind);
  }

  bool readBool() {
    return asImpl().readUInt64() != 0;
  }

  uint32_t readUInt32() {
    return uint32_t(asImpl().readUInt64());
  }

  clang::Selector readSelector() {
    uint64_t numArgsPlusOne = asImpl().readUInt64();

    // The null case.
    if (numArgsPlusOne == 0)
      return clang::Selector();

    unsigned numArgs = unsigned(numArgsPlusOne - 1);
    SmallVector<clang::IdentifierInfo *, 4> chunks;
    for (unsigned i = 0, e = std::max(numArgs, 1U); i != e; ++i)
      chunks.push_back(asImpl().readIdentifier());

    return getASTContext().Selectors.getSelector(numArgs, chunks.data());
  }

  clang::SourceLocation readSourceLocation() {
    // Always read null.
    return clang::SourceLocation();
  }

  clang::QualType readQualType() {
    clang::Qualifiers quals = asImpl().readQualifiers();
    clang::QualType type = asImpl().readTypeRef();
    return getASTContext().getQualifiedType(type, quals);
  }

  const clang::BTFTypeTagAttr *readBTFTypeTagAttr() {
    llvm::report_fatal_error("Read BTFTypeTagAttr that should never have been"
                             " serialized");
  }
};

}

#endif


text:
"""
================================
Gradient Boosting regularization
================================

Illustration of the effect of different regularization strategies
for Gradient Boosting. The example is taken from Hastie et al 2009.

The loss function used is binomial deviance. Regularization via
shrinkage (``learning_rate < 1.0``) improves performance considerably.
In combination with shrinkage, stochastic gradient boosting
(``subsample < 1.0``) can produce more accurate models by reducing the
variance via bagging.
Subsampling without shrinkage usually does poorly.
Another strategy to reduce the variance is by subsampling the features
analogous to the random splits in Random Forests
(via the ``max_features`` parameter).

.. [1] T. Hastie, R. Tibshirani and J. Friedman, "Elements of Statistical
    Learning Ed. 2", Springer, 2009.
"""
print __doc__

# Author: Peter Prettenhofer <peter.prettenhofer@gmail.com>
#
# License: BSD

import numpy as np
import pylab as pl
from sklearn import ensemble
from sklearn import datasets

X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1)
X = X.astype(np.float32)

X_train, X_test = X[:2000], X[2000:]
y_train, y_test = y[:2000], y[2000:]

original_params = {'n_estimators': 1000, 'max_depth': 2, 'random_state': 1,
                   'min_samples_split': 5}

pl.figure()

for label, color, setting in [('No shrinkage', 'orange',
                               {'learning_rate': 1.0, 'subsample': 1.0}),
                              ('learning_rate=0.1', 'turquoise',
                               {'learning_rate': 0.1, 'subsample': 1.0}),
                              ('subsample=0.5', 'blue',
                               {'learning_rate': 1.0, 'subsample': 0.5}),
                              ('learning_rate=0.1, subsample=0.5', 'gray',
                               {'learning_rate': 0.1, 'subsample': 0.5}),
                              ('learning_rate=0.1, max_features=2', 'magenta',
                               {'learning_rate': 0.1, 'max_features': 2})]:
    params = dict(original_params)
    params.update(setting)

    clf = ensemble.GradientBoostingClassifier(**params)
    clf.fit(X_train, y_train)

    # compute test set deviance
    test_deviance = np.zeros((params['n_estimators'],), dtype=np.float64)

    for i, y_pred in enumerate(clf.staged_decision_function(X_test)):
        test_deviance[i] = clf.loss_(y_test, y_pred)

    pl.plot((np.arange(test_deviance.shape[0]) + 1)[::5], test_deviance[::5],
            '-', color=color, label=label)

pl.legend(loc='upper left')
pl.xlabel('Boosting Iterations')
pl.ylabel('Test Set Deviance')

pl.show()


text:
type: posts
layout: post
lang: en
id: en-segwit-testnet
name: segwit-testnet
title: Launch of Segregated Witness Testnet
permalink: /en/2016/01/21/launch_segwit_testnet/
version: 1
excerpt: We are extremely pleased and excited to announce the release of the Segregated Witness Testnet
---

We are extremely pleased and excited to announce the [Segregated Witness Testnet](https://github.com/sipa/bitcoin/commits/segwit)! All developers are encouraged to help begin testing and integration right away.

This represents one of the most hotly anticipated and exciting developments to date that is an important foundation for many future improvements and innovations. Segregated Witness frees up space on the Bitcoin blockchain by securely moving transaction signature data to a specially delegated "Segregated Witness" data structure outside of the transaction block.

This significant innovation leads to dramatically more efficient use of the Bitcoin blockchain, while simultaneously opening up exciting new possibilities and opportunities for the broader Bitcoin ecosystem, particularly around smart contract applications and dramatically faster transactions, while also providing the groundwork for more advanced features and possibilities in the future.

This development began with a research effort by Bitcoin Core developer, Dr. Pieter Wuille, initially focused on addressing transaction malleability, a longstanding and well-known concern and priority. However, in the process of this research, and in the narrowing toward a solution, additional properties of the solution were discovered that allow for increasing the block size while also simultaneously opening up some incredibly exciting secondary benefits.

This effort was initiated by Dr. Pieter Wuille, but included contributions from many others, with particular thanks to Eric Lombrozo, Johnson Lau, Alex Morcos, Nicolas Dorier, Bryan Bishop, Gregory Maxwell, Peter Todd, Cory Fields, Suhas Daftuar, and Luke-Jr.

## Bitcoin Core Ecosystem

There is broad excitement and anticipation as far as what providers and other exchange operators will create with the fundamental developments and innovations included in this release. So far, the [most popular wallets][segwit_adoption] and supporting libraries have stated they will support segwit including Ledger, Trezor, Electrum, and Bitgo. Additionally, work on numerous other libraries such as bitcoinj, bitcoinjs, pycoin and bitcore has already begun.

A faucet is available for "segnet" coins [here](https://segwit.greenaddress.it/faucet/).

Early previews of third party wallet support are available at:

- [mSIGNA](https://github.com/ciphrex/mSIGNA/tree/segwit) (wallet source-code)
- [Green Address](https://segwit.greenaddress.it/) (web wallet)

## How to get involved

Please join the `segwit-dev` IRC channel on irc.freenode.net.

Wallet providers should read the [migration guide](/en/segwit_wallet_dev).

If you are a wallet user interested in following the status of your wallet's implementation, please [follow their progress][segwit_adoption] which will be regularly updated.

## Testing

Finally and most importantly, please help test the Segwit Testnet!

The source-code can be located [here](https://github.com/sipa/bitcoin/tree/segwit) checkout the `segwit` branch.

Once compiled, add `-segnet` to the standard `bitcoind` and `bitcoin-cli` command line.

## Additional Background and History

- [Scaling Bitcoins Hong Kong Presentation](https://prezi.com/lyghixkrguao/segregated-witness-and-deploying-it-for-bitcoin/)
- [Extended Video](https://bitcoincore.org/en/2015/12/14/segregated-witness)
- [Transcript](http://diyhpl.us/wiki/transcripts/scalingbitcoin/hong-kong/segregated-witness-and-its-impact-on-scalability/)

## Technical References

### SegWit BIPs

- [BIP141](https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki): An overview of the segregated witness soft fork, and a discussion on its benefits, backwards compatibility, consensus limits, and deployment.
- [BIP143](https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki): The definition of a new digest algorithm for signature verification used in segregated witness transactions.
- [BIP144](https://github.com/bitcoin/bips/blob/master/bip-0144.mediawiki): The new message types and serialization formats for segregated witness transactions.

### References

- [Analysis of segwit benefits](http://lists.linuxfoundation.org/pipermail/bitcoin-dev/2016-January/012248.html)
- [Hard Forks vs. Soft Forks](https://petertodd.org/2016/soft-forks-are-safer-than-hard-forks)
- [Early Exploration of "Non-contentious" Hard Fork Research](https://scalingbitcoin.org/hongkong2015/presentations/DAY1/1_overview_1_timon.pdf)

[FAQ]: https://bitcoincore.org/en/2015/12/23/capacity-increases-faq
[roadmap]: http://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-December/011865.html
[segwit_adoption]: /en/segwit_adoption


text:
FROM ubuntu:precise

RUN apt-get -y update
RUN apt-get -y upgrade
RUN apt-get -y update

RUN apt-get -y --force-yes install \
        git \
        gunicorn \
        nginx-light \
        nodejs \
        npm \
        python-cairo \
        python-django \
        python-django-tagging \
        python-ldap \
        python-memcache \
        python-pip \
        python-pysqlite2 \
        python-simplejson \
        python-support \
        python-twisted \
        supervisor \
        build-essential \
        python-dev \
        wget

RUN ln -s `which nodejs` /usr/bin/node

RUN pip install --upgrade pip
RUN pip install whisper daemonize
RUN pip install django==1.4
RUN pip install --install-option="--prefix=/opt/graphite" --install-option="--install-lib=/opt/graphite/lib" carbon
RUN pip install --install-option="--prefix=/opt/graphite" --install-option="--install-lib=/opt/graphite/webapp" graphite-web==0.9.12

RUN sed -i -e's/from twisted.scripts._twistd_unix import daemonize/import daemonize/g' /opt/graphite/lib/carbon/util.py

ADD ./configs/nginx.conf /etc/nginx/nginx.conf
ADD ./configs/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
ADD ./configs/initial_data.json /opt/graphite/webapp/graphite/initial_data.json
ADD ./configs/local_settings.py /opt/graphite/webapp/graphite/local_settings.py
ADD ./configs/carbon.conf /opt/graphite/conf/carbon.conf
ADD ./configs/storage-schemas.conf /opt/graphite/conf/storage-schemas.conf
ADD ./configs/storage-aggregation.conf /opt/graphite/conf/storage-aggregation.conf

RUN mkdir -p /opt/graphite/storage/whisper
RUN touch /opt/graphite/storage/graphite.db /opt/graphite/storage/index
RUN chown -R www-data /opt/graphite/storage
RUN chmod 0775 /opt/graphite/storage /opt/graphite/storage/whisper
RUN chmod 0664 /opt/graphite/storage/graphite.db
RUN cd /opt/graphite/webapp/graphite && python manage.py syncdb --noinput

ADD ./copy_storage.sh /opt/graphite/bin/copy_storage.sh
RUN chmod a+x /opt/graphite/bin/copy_storage.sh

RUN mv /opt/graphite/storage /opt/graphite/storage.bak

RUN mkdir -p /opt/statsd
WORKDIR /opt/statsd
RUN git clone -b metric-toggles https://github.com/akgill/statsd.git
ADD config.js /opt/statsd/config.js

# install diamond
WORKDIR /tmp
RUN wget https://github.com/BrightcoveOS/Diamond/archive/v3.4.tar.gz
RUN tar xvfz v3.4.tar.gz
RUN pip install diamond==3.4.421 python-statsd==1.7.2
ADD ./diamond/diamond.conf /etc/diamond/diamond.conf
RUN mkdir -p /usr/share/diamond/collectors
RUN cp ./Diamond-3.4/src/collectors/diskspace/diskspace.py /usr/share/diamond/collectors/diskspace.py
ADD ./diamond/collectors/DiskSpaceCollector.conf /etc/diamond/collectors/DiskSpaceCollector.conf
RUN cp ./Diamond-3.4/src/collectors/diskusage/diskusage.py /usr/share/diamond/collectors/diskusage.py
ADD ./diamond/collectors/DiskUsageCollector.conf /etc/diamond/collectors/DiskUsageCollector.conf

# Make sure to expose these ports in the run command
#graphite web
EXPOSE  80
#graphite cache input
EXPOSE  2003
EXPOSE  2004
EXPOSE  7002

#statsd
EXPOSE  8125/udp
#statsd admin
EXPOSE  8126

CMD ["/usr/bin/supervisord", "-n"]


text:
/**
 *
 */
package br.com.dlp.framework.security;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * Classe helper para pesquisa sobre segurança. Pode ser utilizada em qualquer contexto. Trabalha com springSecurity
 *
 * @author darcio
 */
public class SecurityHelper {

	private static SecurityHelper securityHelper;

	private SecurityHelper(){}

	/**
	 * Singleton method
	 * @return
	 */
	public static SecurityHelper getInstance(){
		if(securityHelper==null){
			securityHelper = new SecurityHelper();
		}
		return securityHelper;
	}

	/**
	 * Testa se algum dos roles informados está presente nas authorities do usuários logado no momento
	 * @param roles
	 * @return
	 */
  public boolean ifAnyGranted(List<String> roles){

   	Collection<String> authorities = getAuthorities();

   	for (String auth : authorities) {
   		for (String role : roles) {

   			if(auth.equals(role)){
   				return true;
   			}

			}
		}
   	return false;
  }

	/**
	 * Recupera o login name, priorizando o principal do spring. Caso não encontre pega o loginName do principal informado.
	 * @param principal
	 * @return
	 */
	public String getLoginName(Principal principal) {
		Object principal2 = getSpringPrincipal();

		String loginName="";

		if(principal2!=null){

			if (principal2 instanceof UserDetails) {
				loginName = ((UserDetails)principal2).getUsername();
			} else {
				loginName = principal2.toString();
			}

		}else if (principal != null) {
			loginName = principal.getName();
		}else{
			return null;
		}
		return loginName;
	}

	/**
	 * Recupera o login name, priorizando o principal do spring. Caso não encontre pega o loginName do principal informado.
	 * @param principal
	 * @return
	 */
	public Collection<String> getAuthorities() {
		Object springPrincipal = getSpringPrincipal();

		Collection<String> authorities = null;

		if(springPrincipal!=null && springPrincipal instanceof UserDetails) {

			UserDetails userDetails = (UserDetails)springPrincipal;

			 Collection<? extends GrantedAuthority> springAuthorities = userDetails.getAuthorities();
			authorities = new ArrayList<String>(springAuthorities.size());

			for (GrantedAuthority grantedAuthority : springAuthorities) {
				authorities.add(grantedAuthority.getAuthority());
			}

		}else{
			authorities = new ArrayList<String>(0);
		}

		return authorities;
	}

	/**
	 * Recupera o login name, priorizando o principal do spring. Caso não encontre pega o loginName do principal informado.
	 * @param principal
	 * @return
	 */
	public String getLoginName() {
		return getLoginName(null);
	}

	/**
	 * Recupera o principal do SpringSecurity
	 * @return
	 */
	public Object getSpringPrincipal() {
		SecurityContext context = SecurityContextHolder.getContext();
		if(context==null){
			return null;
		}

		Authentication authentication = context.getAuthentication();
		if(authentication==null){
			return null;
		}

		Object principal = authentication.getPrincipal();
		return principal;
	}

}


text:
import mmap
import socket as SOCKET
from struct import pack, unpack
from collections import deque
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3

SIGNAL_REQUEST_BUFFER = b"\x00\x00\x00\x00"
SIGNAL_REQUEST_BUFFER_G0 = b"\xFF\xFF\xFF\xFD"
SIGNAL_REQUEST_BUFFER_G1 = b"\xFF\xFF\xFF\xFC"
SIGNAL_FINISHED = b"\xFF\xFF\xFF\xFF"

if PY2:
    SIGNAL_WAS_LAST = "\x20"
else:
    SIGNAL_WAS_LAST = 32

def recv_all(socket, toread):
    initial = socket.recv(toread)
    bytes_read = len(initial)
    if bytes_read == toread:
        return initial
    else:
        bits = [initial]
        toread = toread - bytes_read
        while toread:
            bit = socket.recv(toread)
            bits.append(bit)
            toread = toread - len(bit)
        return b"".join(bits)

class PureTCPConnection(object):
    def __init__(self, port):
        self._socket = SOCKET.socket(family=SOCKET.AF_INET, type=SOCKET.SOCK_STREAM)
        self._socket.connect((SOCKET.gethostbyname("localhost"), port))

    def write(self, msg):
        self._socket.send(msg)

    def read(self, size):
        return recv_all(self._socket, size)

    def close(self):
        self._socket.close()

class BufferingTCPMappedFileConnection(object):
    def __init__(self, input_file, output_file, mmap_size, port):
        self._input_file = open(input_file, "rb+")
        self._output_file = open(output_file, "rb+")
        self._mmap_size = mmap_size
        if hasattr(mmap, 'MAP_SHARED'):
            self._file_input_buffer = mmap.mmap(self._input_file.fileno(), mmap_size, mmap.MAP_SHARED, mmap.ACCESS_READ)
            self._file_output_buffer = mmap.mmap(self._output_file.fileno(), mmap_size, mmap.MAP_SHARED, mmap.ACCESS_WRITE)
        else:
            self._file_input_buffer = mmap.mmap(self._input_file.fileno(), mmap_size, None, mmap.ACCESS_READ)
            self._file_output_buffer = mmap.mmap(self._output_file.fileno(), mmap_size, None, mmap.ACCESS_WRITE)
        self._socket = SOCKET.socket(family=SOCKET.AF_INET, type=SOCKET.SOCK_STREAM)
        self._socket.connect((SOCKET.gethostbyname("localhost"), port))

        self._out = deque()
        self._out_size = 0

        self._input = b""
        self._input_offset = 0
        self._input_size = 0
        self._was_last = False

    def close(self):
        self._socket.close()

    def write(self, msg):
        length = len(msg)
        if length > self._mmap_size:
            raise Exception("Serialized object does not fit into a single buffer.")
        tmp = self._out_size + length
        if tmp > self._mmap_size:
            self._write_buffer()
            self.write(msg)
        else:
            self._out.append(msg)
            self._out_size = tmp

    def _write_buffer(self):
        self._file_output_buffer.seek(0, 0)
        self._file_output_buffer.write(b"".join(self._out))
        self._socket.send(pack(">i", self._out_size))
        self._out.clear()
        self._out_size = 0
        recv_all(self._socket, 1)

    def read(self, des_size, ignored=None):
        if self._input_size == self._input_offset:
            self._read_buffer()
        old_offset = self._input_offset
        self._input_offset += des_size
        if self._input_offset > self._input_size:
            raise Exception("BufferUnderFlowException")
        return self._input[old_offset:self._input_offset]

    def _read_buffer(self):
        self._socket.send(SIGNAL_REQUEST_BUFFER)
        self._file_input_buffer.seek(0, 0)
        self._input_offset = 0
        meta_size = recv_all(self._socket, 5)
        self._input_size = unpack(">I", meta_size[:4])[0]
        self._was_last = meta_size[4] == SIGNAL_WAS_LAST
        self._input = self._file_input_buffer.read(self._input_size)

    def send_end_signal(self):
        if self._out_size:
            self._write_buffer()
        self._socket.send(SIGNAL_FINISHED)

    def has_next(self, ignored=None):
        return not self._was_last or not self._input_size == self._input_offset

    def reset(self):
        self._was_last = False
        self._input_size = 0
        self._input_offset = 0
        self._input = b""

    def read_secondary(self, des_size):
        return recv_all(self._socket, des_size)

    def write_secondary(self, data):
        self._socket.send(data)

class TwinBufferingTCPMappedFileConnection(BufferingTCPMappedFileConnection):
    def __init__(self, input_file, output_file, mmap_size, port):
        super(TwinBufferingTCPMappedFileConnection, self).__init__(input_file, output_file, mmap_size, port)
        self._input = [b"", b""]
        self._input_offset = [0, 0]
        self._input_size = [0, 0]
        self._was_last = [False, False]

    def read(self, des_size, group):
        if self._input_size[group] == self._input_offset[group]:
            self._read_buffer(group)
        old_offset = self._input_offset[group]
        self._input_offset[group] += des_size
        return self._input[group][old_offset:self._input_offset[group]]

    def _read_buffer(self, group):
        if group:
            self._socket.send(SIGNAL_REQUEST_BUFFER_G1)
        else:
            self._socket.send(SIGNAL_REQUEST_BUFFER_G0)
        self._file_input_buffer.seek(0, 0)
        self._input_offset[group] = 0
        meta_size = recv_all(self._socket, 5)
        self._input_size[group] = unpack(">I", meta_size[:4])[0]
        self._was_last[group] = meta_size[4] == SIGNAL_WAS_LAST
        self._input[group] = self._file_input_buffer.read(self._input_size[group])

    def has_next(self, group):
        return not self._was_last[group] or not self._input_size[group] == self._input_offset[group]

    def reset(self):
        self._was_last = [False, False]
        self._input_size = [0, 0]
        self._input_offset = [0, 0]
        self._input = [b"", b""]


text:
![1.4 stars](../../images/ic_star_black_18dp_1x.png)![1.4 stars](../../images/ic_star_half_black_18dp_1x.png)![1.4 stars](../../images/ic_star_border_black_18dp_1x.png)![1.4 stars](../../images/ic_star_border_black_18dp_1x.png)![1.4 stars](../../images/ic_star_border_black_18dp_1x.png) 3

To use the WineAdvisor skill, try saying...

* *alexa ask the wine advisor what wine is good with fish*

* *ask the wine advisor which wine is good with steak*

* *ask the wine advisor which wines go with oysters*

The Treycent Wine Advisor answers your wine pairing questions like "ask the wine advisor what wine is good with fish".

***

### Skill Details

* **Invocation Name:** the wine advisor
* **Category:** null
* **ID:** amzn1.ask.skill.a853e193-b9ef-4734-ac52-371bdc9e0e81
* **ASIN:** B01M4O7VF3
* **Author:** Treycent
* **Release Date:** October 31, 2016 @ 12:43:41
* **Privacy Policy:** https://treycent.com/app/privacy.html
* **Terms of Use:** https://treycent.com/app/terms.html
* **In-App Purchasing:** No


text:
<?php

require_once dirname(__FILE__).'/../__init_script__.php';

$synopsis = <<<EOT
**save_lint.php**
    Discover lint problems and save them to database so that they can
    be displayed in Diffusion.

EOT;

$args = id(new PhutilArgumentParser($argv))
  ->setTagline(pht('save lint errors to database'))
  ->setSynopsis($synopsis)
  ->parseStandardArguments()
  ->parse(array(
    array(
      'name' => 'all',
      'help' => pht(
        'Discover problems in the whole repository instead of just changes '.
        'since the last run.'),
    ),
    array(
      'name' => 'arc',
      'param' => 'path',
      'default' => 'arc',
      'help' => pht('Path to Arcanist executable.'),
    ),
    array(
      'name' => 'severity',
      'param' => 'string',
      'default' => ArcanistLintSeverity::SEVERITY_ADVICE,
      'help' => pht(
        'Minimum severity, one of %s constants.',
        'ArcanistLintSeverity'),
    ),
    array(
      'name' => 'chunk-size',
      'param' => 'number',
      'default' => 256,
      'help' => pht('Number of paths passed to `%s` at once.', 'arc'),
    ),
    array(
      'name' => 'blame',
      'help' => pht(
        'Assign lint errors to authors who last modified the line.'),
    ),
  ));

echo pht('Saving lint errors to database...')."\n";

$count = id(new DiffusionLintSaveRunner())
  ->setAll($args->getArg('all', false))
  ->setArc($args->getArg('arc'))
  ->setSeverity($args->getArg('severity'))
  ->setChunkSize($args->getArg('chunk-size'))
  ->setNeedsBlame($args->getArg('blame'))
  ->run('.');

echo "\n".pht('Processed %d files.', $count)."\n";


text:
We have managed to send authentication details from the form on the frontend to our node-server. We tried using the request module to send the info from our backend to github but encountered problems,

```
error: ({"message":"Bad credentials","documentation_url":"https://developer.github.com/v3"})
```
this was not due to user input error
and are now about to switch methods to a standard https node request.
There is a good example here: https://nodejs.org/api/http.html


text:
import React from 'react';

import './InConstruction.scss';

const InConstruction = () => (

     In construction

);

export default InConstruction;


text:
typedef int64_t dv_size;

typedef struct DimDesc {
    dv_size        Extent;      // Number of elements in this dimension
    dv_size        Mult;        // Multiplier for this dimension.
                                // The number of bytes between successive
                                // elements in this dimension.
    dv_size        LowerBound;  // LowerBound of this dimension
} DimDesc ;

typedef struct ArrDesc {
    dv_size        Base;        // Base address
    dv_size        Len;         // Length of data type, used only for
                                // character strings.
    dv_size        Offset;
    dv_size        Flags;       // Flags
    dv_size        Rank;        // Rank of pointer
    dv_size        Reserved;    // reserved for openmp requests
    DimDesc Dim[ArrDescMaxArrayRank];
} ArrDesc ;

typedef ArrDesc* pArrDesc;

bool __dv_is_contiguous(const ArrDesc *dvp);

bool __dv_is_allocated(const ArrDesc *dvp);

uint64_t __dv_data_length(const ArrDesc *dvp);

uint64_t __dv_data_length(const ArrDesc *dvp, int64_t nelems);

CeanReadRanges * init_read_ranges_dv(const ArrDesc *dvp);

#if OFFLOAD_DEBUG > 0
void    __dv_desc_dump(const char *name, const ArrDesc *dvp);
#else // OFFLOAD_DEBUG
#define __dv_desc_dump(name, dvp)
#endif // OFFLOAD_DEBUG

#endif // DV_UTIL_H_INCLUDED


text:
import { sortboard } from '../src'

const sb = sortboard({
  container: '#sortlist',
  selector: 'li'
})

const anchors = children('#filters a')

anchors.forEach((el) => {
  el.addEventListener(
    'click',
    (event) => {
      const an = event.target

      if (!an.classList.contains('active')) {
        const data = an.getAttribute('data-filter')
        sb.filter(data)

        anchors.forEach((a) => {
          a.classList.remove('active')
        })
        an.classList.add('active')
      }
    },
    false
  )
})

function children (selector, parent = document) {
  return Array.prototype.slice
    .call(parent.querySelectorAll(selector))
}


text:
HashedAssetBundle
=================

The HashedAssetBundle provides an asset version strategy which uses a hash
of the file content as asset version. This allows bumping the asset version
separately for each asset (automatically).

[![CI](https://github.com/Incenteev/hashed-asset-bundle/actions/workflows/ci.yml/badge.svg)](https://github.com/Incenteev/hashed-asset-bundle/actions/workflows/ci.yml) [![Total Downloads](https://poser.pugx.org/incenteev/hashed-asset-bundle/downloads.svg)](https://packagist.org/packages/incenteev/hashed-asset-bundle) [![Latest Stable Version](https://poser.pugx.org/incenteev/hashed-asset-bundle/v/stable.svg)](https://packagist.org/packages/incenteev/hashed-asset-bundle)

## Installation

Use [Composer](https://getcomposer.org) to install the bundle:

```bash
$ composer require incenteev/hashed-asset-bundle
```

## Usage

Register the bundle in the kernel:

```php
// app/AppKernel.php

// ...

class AppKernel extends Kernel {
    public function registerBundles()
    {
        $bundles = array(
            // ...
            new Incenteev\HashedAssetBundle\IncenteevHashedAssetBundle(),
        );
    }
}
```

Then configure FrameworkBundle to use the new version strategy:

```yaml
framework:
    assets:
        version_strategy: incenteev_hashed_asset.strategy
```

## Advanced configuration

The default configuration should fit common needs, but the bundle exposes
a few configuration settings in case you need them:

```yaml
incenteev_hashed_asset:
    # Absolute path to the folder in which assets can be found
    # Note: in case you apply a base_path in your asset package, it is not
    # yet applied to the string received by the bundle
    web_root: '%kernel.project_dir%/web'
    # Format used to apply the version. This is equivalent to the
    # `framework > assets > version_format` of the static version strategy
    # of FrameworkBundle.
    version_format: '%%s?%%s'
```

## License

This bundle is under the [MIT license](LICENSE).

## Alternative projects

If you want to apply cache busting by renaming files in your asset pipeline
(for instance with the webpack-encore versioning feature), have a look at the
`json_manifest` strategy available in Symfony itself.

## Reporting an issue or a feature request

Issues and feature requests are tracked in the [Github issue tracker](https://github.com/Incenteev/hashed-asset-bundle/issues).


text:
package net.mastrgamr.mbmapboxutils.clustering.algo;

import net.mastrgamr.mbmapboxutils.clustering.Cluster;
import net.mastrgamr.mbmapboxutils.clustering.ClusterItem;

import java.util.Collection;
import java.util.Set;

/**
 * Logic for computing clusters
 */
public interface Algorithm<T extends ClusterItem> {
    void addItem(T item);

    void addItems(Collection<T> items);

    void clearItems();

    void removeItem(T item);

    Set<? extends Cluster<T>> getClusters(double zoom);

    Collection<T> getItems();
}


text:
<?php

/**
 * Register the classes
 */
ClassLoader::addClasses(array
(
    // Classes
    'Broadcast' => 'system/modules/be_broadcasts/classes/Broadcast.php'
));


text:
package com.helger.photon.bootstrap3.grid;

import java.io.Serializable;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;

import com.helger.commons.ValueEnforcer;
import com.helger.commons.string.ToStringGenerator;
import com.helger.html.hc.html.IHCElement;

@Immutable
public final class BootstrapGridSpec implements Serializable
{
  public static final BootstrapGridSpec NONE = new BootstrapGridSpec (null, null, null, null);

  private final EBootstrapGridXS m_eXS;
  private final EBootstrapGridSM m_eSM;
  private final EBootstrapGridMD m_eMD;
  private final EBootstrapGridLG m_eLG;

  public BootstrapGridSpec (@Nullable final EBootstrapGridXS eXS,
                            @Nullable final EBootstrapGridSM eSM,
                            @Nullable final EBootstrapGridMD eMD,
                            @Nullable final EBootstrapGridLG eLG)
  {
    m_eXS = eXS;
    m_eSM = eSM;
    m_eMD = eMD;
    m_eLG = eLG;
  }

  @Nullable
  public EBootstrapGridXS getXS ()
  {
    return m_eXS;
  }

  @Nullable
  public EBootstrapGridSM getSM ()
  {
    return m_eSM;
  }

  @Nullable
  public EBootstrapGridMD getMD ()
  {
    return m_eMD;
  }

  @Nullable
  public EBootstrapGridLG getLG ()
  {
    return m_eLG;
  }

  public void applyTo (@Nonnull final IHCElement <?> aElement)
  {
    ValueEnforcer.notNull (aElement, "Element");

    int nLastPartCount = -1;
    if (m_eXS != null)
    {
      aElement.addClass (m_eXS);
      nLastPartCount = m_eXS.getParts ();
    }
    // Apply only if different from the previous part count
    if (m_eSM != null && m_eSM.getParts () != nLastPartCount)
    {
      aElement.addClass (m_eSM);
      nLastPartCount = m_eSM.getParts ();
    }
    if (m_eMD != null && m_eMD.getParts () != nLastPartCount)
    {
      aElement.addClass (m_eMD);
      nLastPartCount = m_eMD.getParts ();
    }
    if (m_eLG != null && m_eLG.getParts () != nLastPartCount)
    {
      aElement.addClass (m_eLG);
      // nLastPartCount = m_eLG.getParts ();
    }
  }

  public void applyOffsetTo (@Nonnull final IHCElement <?> aElement)
  {
    ValueEnforcer.notNull (aElement, "Element");
    aElement.addClasses (m_eXS == null || m_eXS.isMax () ? null : m_eXS.getCSSClassOffset (),
                         m_eSM == null || m_eSM.isMax () ? null : m_eSM.getCSSClassOffset (),
                         m_eMD == null || m_eMD.isMax () ? null : m_eMD.getCSSClassOffset (),
                         m_eLG == null || m_eLG.isMax () ? null : m_eLG.getCSSClassOffset ());
  }

  public void applyPullTo (@Nonnull final IHCElement <?> aElement)
  {
    ValueEnforcer.notNull (aElement, "Element");
    aElement.addClasses (m_eXS == null ? null : m_eXS.getCSSClassPull (),
                         m_eSM == null ? null : m_eSM.getCSSClassPull (),
                         m_eMD == null ? null : m_eMD.getCSSClassPull (),
                         m_eLG == null ? null : m_eLG.getCSSClassPull ());
  }

  public void applyPushTo (@Nonnull final IHCElement <?> aElement)
  {
    ValueEnforcer.notNull (aElement, "Element");
    aElement.addClasses (m_eXS == null ? null : m_eXS.getCSSClassPush (),
                         m_eSM == null ? null : m_eSM.getCSSClassPush (),
                         m_eMD == null ? null : m_eMD.getCSSClassPush (),
                         m_eLG == null ? null : m_eLG.getCSSClassPush ());
  }

  @Override
  public String toString ()
  {
    return new ToStringGenerator (this).append ("xs", m_eXS).append ("sm", m_eSM).append ("md", m_eMD).append ("lg", m_eLG).getToString ();
  }

  @Nonnull
  public static BootstrapGridSpec create (final int nParts)
  {
    // The larger sizes inherit from the smaller sizes
    return create (nParts, -1, -1, -1);
  }

  @Nonnull
  public static BootstrapGridSpec create (final int nPartsXS, final int nPartsSM, final int nPartsMD, final int nPartsLG)
  {
    return new BootstrapGridSpec (nPartsXS <= 0 ? null : EBootstrapGridXS.getFromParts (nPartsXS),
                                  nPartsSM <= 0 ? null : EBootstrapGridSM.getFromParts (nPartsSM),
                                  nPartsMD <= 0 ? null : EBootstrapGridMD.getFromParts (nPartsMD),
                                  nPartsLG <= 0 ? null : EBootstrapGridLG.getFromParts (nPartsLG));
  }
}


text:
/* global angular */

// Allows for communication between controllers note set up for test data
angular.module('app').factory('metabolomicsDataFactory', function($rootScope, sharedFactory){
    var factory = {
        trace:  "259.022442",  // default is for alpha-D-Galactose 1-phosphate with [M-H]- adduct
        msmsIons: "215.03498 32.67\n259.02481 100.0\n259.02481 100.0\n261.03448 100.0",
        traceType: 'form',
        filterKovats: false,
        kovats: [0, 20000],
        filterLogP: false,
        logP: [-35, 35],
        params: {
            tolerance: 3,
            ppm: false,
            charge: false,
            halogens: false,
            adducts: [],
            models: [],
            energy_level: "10",
            scoring_function: 'dot product'
        },
        storeFormData: function($scope, $cookieStore) { // updates factory and cookies on search
            factory.trace =$scope.trace;
            factory.params.tolerance = $scope.tolerance + + 0.000000000000001;
            factory.params.halogens = $scope.halogens;
            factory.params.ppm = $scope.ppm;
            factory.params.adducts = $scope.adducts;
            factory.filterKovats = $scope.filterKovats;
            factory.kovats = $scope.kovats;
            factory.filterLogP = $scope.filterLogP;
            factory.logP = $scope.logP;
            $cookieStore.put("charge: "+ $scope.charge, $scope.adducts);
        },
        mzSearch: function(db){
            //clone the parameters before passing them so we don't end up change in the factory object
            var params = jQuery.extend({}, factory.params);
            if (factory.filterLogP) {params.logP = factory.logP;}
            if (factory.filterKovats) {params.kovats = factory.kovats;}
            console.log(params);
            var promise;
            factory.hits = null;
            if (factory.msmsIons.length){
                promise = sharedFactory.services.ms2_search(db, factory.trace+"\n"+factory.msmsIons, factory.traceType, params);
            }
            else {
                promise = sharedFactory.services.ms_adduct_search(db, factory.trace, factory.traceType, params);
            }
            promise.then(function(result){
                    factory.hits = result;
                    $rootScope.$broadcast("metabolitesLoaded");
                },
                function(err){alert("An Error occurred!\n\n" + err.error.error);}
            );
        },
        filterHits: function(list, mz, adduct, formula, compound, mine) {
            // filtering but we have to handle names carefully (sometimes not present) and use RegEx with formula
            var filteredList = [];
            var patt = new RegExp(formula);
            for (var i = 0; i < list.length  ; i++) {
                if((list[i].peak_name.toString().indexOf(mz) > -1) &&
                    (list[i].adduct.toString().indexOf(adduct) > -1) &&
                    (patt.test(list[i].Formula.toString())) &&
                    (list[i].MINE_id.toString().indexOf(mine) > -1) &&
                    (!compound || (typeof(list[i].Names) != 'undefined') && (list[i].Names[0].indexOf(compound) > -1)))
                {filteredList.push(list[i]);}
            }
            return filteredList
        },
        uploadFile: function(ele_id){
            var selectedFile = document.getElementById(ele_id).files[0];
            if (selectedFile.name.search('.mgf')>-1){factory.traceType = "mgf";}
            else if (selectedFile.name.search('.mzxml')>-1){factory.traceType = "mzxml";}
            else if (selectedFile.name.search('.msp')>-1){factory.traceType = "msp";}
            else {
                alert('Upload only supports .mgf, .msp, and .mzXML formats');
                return;
            }
            var reader = new FileReader();
            reader.readAsText(selectedFile);
            return reader;
        }
    };
    return factory
});

angular.module('app').controller('metabolomicsCtl', function($scope,$state,$cookieStore,sharedFactory,metabolomicsDataFactory){
    $scope.trace = metabolomicsDataFactory.trace;
    $scope.tolerance = parseInt(metabolomicsDataFactory.params.tolerance);
    $scope.halogens = metabolomicsDataFactory.params.halogens;
    $scope.ppm = metabolomicsDataFactory.params.ppm;
    $scope.filterLogP = metabolomicsDataFactory.filterLogP;
    $scope.logP = metabolomicsDataFactory.logP;
    $scope.filterKovats = metabolomicsDataFactory.filterKovats;
    $scope.kovats = metabolomicsDataFactory.kovats;
    $scope.adducts = [];
    var adductList;

    sharedFactory.services.get_adducts().then(
        function(result){
            adductList = result;
            $scope.charge = metabolomicsDataFactory.params.charge; // triggers following watch statement
            $scope.$apply();
        },
        function(err) {console.log(err)}
    );

    $scope.uploadFile = function(id) {
        var reader = metabolomicsDataFactory.uploadFile(id);
        reader.onload=function(){
            $scope.trace = reader.result;
            $scope.$apply();
        }
    };

    $scope.$watch('charge', function() { // if the charge changes, update the adduct list while checking the cookies
        if (adductList) {
            metabolomicsDataFactory.params.charge = $scope.charge;
            if ($scope.charge) {$scope.adduct_list = adductList[0];}
            else {$scope.adduct_list = adductList[1]}
            var adducts = $cookieStore.get("charge: "+ $scope.charge);
            if (typeof(adducts) == 'object') $scope.adducts = adducts;
            else $scope.adducts = [];
        }
    });

    $scope.metSearch = function() {
        metabolomicsDataFactory.storeFormData($scope, $cookieStore);
        metabolomicsDataFactory.msmsIons = "";
        $state.go("metabolomicsCompounds");
    };
});

angular.module('app').controller('ms2searchCtl', function($scope,$state,$cookieStore,sharedFactory,metabolomicsDataFactory){
    $scope.trace = metabolomicsDataFactory.trace;
    $scope.msmsIons = metabolomicsDataFactory.msmsIons;
    $scope.tolerance = parseInt(metabolomicsDataFactory.params.tolerance);
    $scope.halogens = metabolomicsDataFactory.params.halogens;
    $scope.ppm = metabolomicsDataFactory.params.ppm;
    $scope.filterLogP = metabolomicsDataFactory.filterLogP;
    $scope.logP = metabolomicsDataFactory.logP;
    $scope.filterKovats = metabolomicsDataFactory.filterKovats;
    $scope.kovats = metabolomicsDataFactory.kovats;
    $scope.energy = metabolomicsDataFactory.params.energy_level;
    $scope.metric = metabolomicsDataFactory.params.scoring_function;
    $scope.adducts = [];
    var adductList;

    sharedFactory.services.get_adducts().then(
        function(result){
            adductList = result;
            $scope.charge = metabolomicsDataFactory.params.charge; // triggers following watch statement
            $scope.$apply();
        },
        function(err) {console.log(err);}
    );

    $scope.uploadFile = function(id) {
        var reader = metabolomicsDataFactory.uploadFile(id);
        reader.onload=function(){
            $scope.trace = "";
            $scope.msmsIons = reader.result;
            $("#parent_ion").attr('disabled','disabled');
            $("#msmsIons").attr('disabled','disabled');
            $scope.$apply();
        }
    };

    $scope.$watch('charge', function() { // if the charge changes, update the adduct list while checking the cookies
        if (adductList) {
            metabolomicsDataFactory.params.charge = $scope.charge;
            if ($scope.charge) {$scope.adduct_list = adductList[0];}
            else {$scope.adduct_list = adductList[1];}
            var adducts = $cookieStore.get("charge: "+ $scope.charge);
            if (typeof(adducts) == 'object') $scope.adducts = adducts;
            else $scope.adducts = [];
        }
    });

    $scope.metSearch = function() {
        metabolomicsDataFactory.storeFormData($scope, $cookieStore);
        metabolomicsDataFactory.params.energy_level = $scope.energy;
        metabolomicsDataFactory.params.scoring_function = $scope.metric;
        metabolomicsDataFactory.msmsIons = $scope.msmsIons;
        $state.go("metabolomicsCompounds");
    };
});

angular.module('app').controller('metabolomicsCompoundsCtl', function($scope,$state,$stateParams,metabolomicsDataFactory,sharedFactory){
    $scope.currentPage = 1;
    $scope.numPerPage = sharedFactory.numPerPage;
    $scope.maxSize = 5;
    $scope.items = -1;
    $scope.totalItems = -1;
    $scope.searchMZ = "";
    $scope.searchAdduct = "";
    $scope.searchFormula = "";
    $scope.searchCompound = "";
    $scope.searchMINE = "";
    $scope.sortColumn = 'Generation';
    $scope.sortInvert = true;
    $scope.generateCompoundImages = sharedFactory.generateCompoundImages;
    $scope.selectedModels = metabolomicsDataFactory.metaModels;
    $scope.factory = metabolomicsDataFactory;
    $scope.db = $stateParams.db;
    var filteredData = [];

    // if we get here w/o parameters (ie direct link), return to the search screen
    if (!metabolomicsDataFactory.params.adducts.length) $state.go('msAdductSearch');
    else {
        if (sharedFactory.selected_model) metabolomicsDataFactory.params.models = [sharedFactory.selected_model.name];
        metabolomicsDataFactory.mzSearch(sharedFactory.dbId);
    }

    $scope.$on("metabolitesLoaded", function () {
        filteredData = metabolomicsDataFactory.filterHits(metabolomicsDataFactory.hits, $scope.searchMZ,
            $scope.searchAdduct, $scope.searchFormula, $scope.searchCompound, $scope.searchMINE);
        if (!metabolomicsDataFactory.msmsIons){
            filteredData = sharedFactory.sortList(filteredData,$scope.sortColumn,$scope.sortInvert);
        }
        $scope.displayData = sharedFactory.paginateList(filteredData, $scope.currentPage, $scope.numPerPage);
        $scope.roundLogP()
        $scope.items = filteredData.length;
        $scope.totalItems = metabolomicsDataFactory.hits.length;
        $scope.$apply();
        $scope.generateCompoundImages();
    });

    $scope.roundLogP = function() {
        for (var f of $scope.displayData) {
            f.logP = Math.round(f.logP * 100) / 100
        }
    }

    $scope.color = function(native,score){
        // If native_hit is true, make it green
        if(native === true){return "success";}
        if (score >= 0.75) {return "warning";}
        return "";
    };

    $scope.downloadResults = function(){
        var jsonObject = JSON.stringify(filteredData);
        //var exclude = {"$$hashKey":"", 'id':"", 'Likelihood_score':"",
        // 'Pos_CFM_spectra':"", 'Neg_CFM_spectra':""};
        var header = ["Spectral_score", "peak_name", "adduct", "MINE_id",
            "Inchikey", "SMILES", "Formula", "logP"];
        var csv = sharedFactory.convertToCSV(jsonObject, header);
        var d = new Date();
        sharedFactory.downloadFile(csv, d.toISOString()+'.csv');
    };

    $scope.$watch('searchMINE + searchMZ + searchAdduct + searchFormula + searchCompound', function() {
        if (metabolomicsDataFactory.hits) {
            filteredData = metabolomicsDataFactory.filterHits(metabolomicsDataFactory.hits, $scope.searchMZ,
                $scope.searchAdduct, $scope.searchFormula, $scope.searchCompound, $scope.searchMINE);
            filteredData = sharedFactory.sortList(filteredData, $scope.sortColumn, $scope.sortInvert);
            $scope.items = filteredData.length;
            $scope.roundLogP();
            $scope.displayData = sharedFactory.paginateList(filteredData, $scope.currentPage, $scope.numPerPage);
            setTimeout(() => $scope.generateCompoundImages(), 10);  // timeout so smilesdrawer can do its thing after page loads
        }
    });

    $scope.$watch('sortColumn + sortInvert', function(){
        filteredData = sharedFactory.sortList(filteredData,$scope.sortColumn,$scope.sortInvert);
        $scope.displayData = sharedFactory.paginateList(filteredData, $scope.currentPage, $scope.numPerPage);
        setTimeout(() => $scope.generateCompoundImages(), 10);  // timeout so smilesdrawer can do its thing after page loads
    });

    $scope.$watch('currentPage', function(){
        $scope.displayData = sharedFactory.paginateList(filteredData, $scope.currentPage, $scope.numPerPage);
        $scope.roundLogP();
        setTimeout(() => $scope.generateCompoundImages(), 10);  // timeout so smilesdrawer can do its thing after page loads
    });

});


text:
import cv2
print 'test'
print '123'


text:
${nls.queries}

					${nls.addNew}


text:
#ifndef H_NETWORKER_H_
#define H_NETWORKER_H_

#include "EventService.h"
#include "Parser.h"
#include "MsgTrigger.h"
#include "WorkerMgr.h"
#include "Session.h"

H_BNAMSP

//ÍøÂç¶Áд
class CNetWorker : public CEventService
{
public:
    CNetWorker(void);
    ~CNetWorker(void);

    void setMsgTrigger(CMsgTrigger *pMsgTrigger);
    CMsgTrigger *getMsgTrigger(void);
    void setWorkerMgr(CWorkerMgr *pWorkerMgr);
    CWorkerMgr *getWorkerMgr(void);
    void setNetMgr(class CNetMgr *pNetMgr);
    class CNetMgr *getNetMgr(void);

    //Ìí¼Ósocket½øÑ»·
    void addSock(class CLinkInfo *pLinkInfo, class CParser *pParser,
        const H_SOCK &sock, const unsigned short &usType);
    //°ó¶¨socketÏûÏ¢µ½ÈÎÎñ
    void bindWorker(const H_SOCK &uiSock, class CWorker *pWorker);
    void unBindWorker(const H_SOCK &uiSock);

    //Ö´ÐÐÇëÇó
    void onAdjure(CAdjure *pAdjure);
    void afterAdjure(CAdjure *pAdjure);

    void dispAdjure(CAdjure *pAdjure);
    class CWorker *getBindWorker(const H_SOCK &uiSock);
    void removeBind(const H_SOCK &uiSock);
    void setLinkStatus(class CLinkInfo *pLinkInfo, const LinkState emState);
    void handleAdjure(class CWorker *pBindWorker, CAdjure *pAdjure, const H_SOCK &uiSock);

private:
    void addSock(CAddSockInAdjure *pAdjure);
    void bindWorker(CBindToTaskAdjure *pAdjure);
    void unBindWorker(CToSockAdjure *pAdjure);
    void *handShakeMonitor(class CSession *pSession, const unsigned int &uiMs);
    CSession *newSession(class CParser *pParser, class CLinkInfo *pLinkInfo,
        H_SOCK &sock, const unsigned short &usType);
    void *newSockEvent(class CSession *pSession, H_SOCK &sock);

    static void onSocketClose(CSession *pSession, H_SOCK &sock);
    static void parseProtocol(CSession *pSession, H_SOCK &sock);
    static void socketEventCB(H_SOCK sock, short sEvent, void *pArg);
    static void handShakeTimeOut(H_SOCK, short, void *pArg);

private:
#ifdef H_OS_WIN
    typedef std::unordered_map<H_SOCK, class CWorker *>::iterator bindit;
    typedef std::unordered_map<H_SOCK, class CWorker *> bind_map;
#else
    typedef std::tr1::unordered_map<H_SOCK, class CWorker *>::iterator bindit;
    typedef std::tr1::unordered_map<H_SOCK, class CWorker *> bind_map;
#endif

    int m_iNoDelay;
    CMsgTrigger *m_pMsgTrigger;
    class CWorkerMgr *m_pWorkerMgr;
    class CNetMgr *m_pNetMgr;
    bind_map m_mapBind;
};

H_ENAMSP

#endif//H_NETWORKER_H_


text:
package org.sagebionetworks.web.client.widget.team;

import java.util.List;
import org.sagebionetworks.web.client.widget.LoadMoreWidgetContainer;
import org.sagebionetworks.web.shared.TeamMemberBundle;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.IsWidget;

public interface MemberListWidgetView extends IsWidget {

	/**
	 * Set this view's presenter
	 *
	 * @param presenter
	 */
	public void setPresenter(Presenter presenter);

	void setMembersContainer(LoadMoreWidgetContainer loadMoreWidget);

	void addMembers(List<TeamMemberBundle> members, boolean isAdmin);

	void clearMembers();

	void showInfo(String message);

	void showErrorMessage(String message);

	public interface Presenter {
		// used for the user profile links
		void goTo(Place place);

		void removeMember(String principalId);

		void setIsAdmin(String principalId, boolean isAdmin);
	}
}


text:
package com.thinkbiganalytics.metadata.api.category;

import com.thinkbiganalytics.metadata.api.BaseProvider;
import com.thinkbiganalytics.metadata.api.extension.UserFieldDescriptor;

import java.util.Optional;
import java.util.Set;

import javax.annotation.Nonnull;

/**
 * Manages the repository of category objects.
 *
 * @param <Category> the type of provided category
 */
public interface CategoryProvider extends BaseProvider<Category, Category.ID> {

    Category findBySystemName(String systemName);

    Category ensureCategory(String systemName);

    /**
     * Gets the user fields for all categories.
     *
     * @return user field descriptors
     * @since 0.4.0
     */
    @Nonnull
    Set<UserFieldDescriptor> getUserFields();

    /**
     * Sets the user fields for all categories.
     *
     * @param userFields user field descriptors
     * @since 0.4.0
     */
    void setUserFields(@Nonnull Set<UserFieldDescriptor> userFields);

    /**
     * Gets the user fields for all feeds within the specified category.
     *
     * @param categoryId the category id
     * @return user field descriptors, if the category exists
     * @since 0.4.0
     */
    @Nonnull
    Optional<Set<UserFieldDescriptor>> getFeedUserFields(@Nonnull Category.ID categoryId);

    /**
     * Sets the user fields for all feeds within the specified category.
     *
     * @param categoryId the category id
     * @param userFields user field descriptors
     * @since 0.4.0
     */
    void setFeedUserFields(@Nonnull Category.ID categoryId, @Nonnull Set<UserFieldDescriptor> userFields);

    /**
     * Renames system name for the specified category.
     *
     * @param categoryId the category id
     * @param newSystemName    the new system name
     */
    void renameSystemName(@Nonnull Category.ID categoryId, @Nonnull String newSystemName);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Novitates Mycologicae Novissimae (1947)

#### Original name
Ramaria tehovensis Velen.

### Remarks
null


text:
using System.Collections.Generic;

namespace Chooie.Logging
{
    public class CompositeLog : ILog
    {
        private readonly IEnumerable<ILog> _logs;

        public CompositeLog(IEnumerable<ILog> logs)
        {
            _logs = logs;
        }

        public void Log(LogMessage message)
        {
            foreach (ILog log in _logs)
            {
                log.Log(message);
            }
        }
    }
}