text:
/*
  This wrapper is required to handle problems with the libpscslite
  library.  That library assumes that pthreads are used and fails
  badly if one tries to use it with a procerss using Pth.

  The operation model is pretty simple: It reads requests from stdin
  and returns the answer on stdout.  There is no direct mapping to the
  pcsc interface but to a higher level one which resembles the code
  used in scdaemon (apdu.c) when not using Pth or while running under
  Windows.

  The interface is binary consisting of a command tag and the length
  of the parameter list.  The calling process needs to pass the
  version number of the interface on the command line to make sure
  that both agree on the same interface.  For each port a separate
  instance of this process needs to be started.

*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>
#include <assert.h>
#include <dlfcn.h>

#define PGM "pcsc-wrapper"

/* Allow for a standalone build. */
#ifdef VERSION
#define MYVERSION_LINE PGM " (GnuPG) " VERSION
#define BUGREPORT_LINE "\nReport bugs to <bug-gnupg@gnu.org>.\n"
#else
#define MYVERSION_LINE PGM
#define BUGREPORT_LINE ""
#endif

#define DEFAULT_PCSC_DRIVER "libpcsclite.so"

static int verbose;

#if defined(__APPLE__) || defined(_WIN32) || defined(__CYGWIN__)
typedef unsigned int pcsc_dword_t;
#else
typedef unsigned long pcsc_dword_t;
#endif

/* PC/SC constants and function pointer. */
#define PCSC_SCOPE_USER      0
#define PCSC_SCOPE_TERMINAL  1
#define PCSC_SCOPE_SYSTEM    2
#define PCSC_SCOPE_GLOBAL    3

#define PCSC_PROTOCOL_T0     1
#define PCSC_PROTOCOL_T1     2
#define PCSC_PROTOCOL_RAW    4

#define PCSC_SHARE_EXCLUSIVE 1
#define PCSC_SHARE_SHARED    2
#define PCSC_SHARE_DIRECT    3

#define PCSC_LEAVE_CARD      0
#define PCSC_RESET_CARD      1
#define PCSC_UNPOWER_CARD    2
#define PCSC_EJECT_CARD      3

#define PCSC_UNKNOWN    0x0001
#define PCSC_ABSENT     0x0002  /* Card is absent.  */
#define PCSC_PRESENT    0x0004  /* Card is present.  */
#define PCSC_SWALLOWED  0x0008  /* Card is present and electrical connected. */
#define PCSC_POWERED    0x0010  /* Card is powered.  */
#define PCSC_NEGOTIABLE 0x0020  /* Card is awaiting PTS.  */
#define PCSC_SPECIFIC   0x0040  /* Card is ready for use.  */

#define PCSC_STATE_UNAWARE     0x0000  /* Want status.  */
#define PCSC_STATE_IGNORE      0x0001  /* Ignore this reader.  */
#define PCSC_STATE_CHANGED     0x0002  /* State has changed.  */
#define PCSC_STATE_UNKNOWN     0x0004  /* Reader unknown.  */
#define PCSC_STATE_UNAVAILABLE 0x0008  /* Status unavailable.  */
#define PCSC_STATE_EMPTY       0x0010  /* Card removed.  */
#define PCSC_STATE_PRESENT     0x0020  /* Card inserted.  */
#define PCSC_STATE_ATRMATCH    0x0040  /* ATR matches card. */
#define PCSC_STATE_EXCLUSIVE   0x0080  /* Exclusive Mode.  */
#define PCSC_STATE_INUSE       0x0100  /* Shared mode.  */
#define PCSC_STATE_MUTE	       0x0200  /* Unresponsive card.  */

struct pcsc_io_request_s {
  unsigned long protocol;
  unsigned long pci_len;
};

typedef struct pcsc_io_request_s *pcsc_io_request_t;

#ifdef __APPLE__
#pragma pack(1)
#endif

struct pcsc_readerstate_s
{
  const char *reader;
  void *user_data;
  pcsc_dword_t current_state;
  pcsc_dword_t event_state;
  pcsc_dword_t atrlen;
  unsigned char atr[33];
};

#ifdef __APPLE__
#pragma pack()
#endif

typedef struct pcsc_readerstate_s *pcsc_readerstate_t;

static int driver_is_open;     /* True if the PC/SC driver has been
                                  initialzied and is ready for
                                  operations.  The following variables
                                  are then valid. */
static long pcsc_context;  /* The current PC/CS context. */
static char *current_rdrname;
static long pcsc_card;
static pcsc_dword_t pcsc_protocol;
static unsigned char current_atr[33];
static size_t current_atrlen;

long (* pcsc_establish_context) (pcsc_dword_t scope,
                                 const void *reserved1,
                                 const void *reserved2,
                                 long *r_context);
long (* pcsc_release_context) (long context);
long (* pcsc_list_readers) (long context,
                            const char *groups,
                            char *readers, pcsc_dword_t *readerslen);
long (* pcsc_get_status_change) (long context,
                                 pcsc_dword_t timeout,
                                 pcsc_readerstate_t readerstates,
                                 pcsc_dword_t nreaderstates);
long (* pcsc_connect) (long context,
                       const char *reader,
                       pcsc_dword_t share_mode,
                       pcsc_dword_t preferred_protocols,
                       long *r_card,
                       pcsc_dword_t *r_active_protocol);
long (* pcsc_reconnect) (long card,
                         pcsc_dword_t share_mode,
                         pcsc_dword_t preferred_protocols,
                         pcsc_dword_t initialization,
                         pcsc_dword_t *r_active_protocol);
long (* pcsc_disconnect) (long card,
                          pcsc_dword_t disposition);
long (* pcsc_status) (long card,
                      char *reader, pcsc_dword_t *readerlen,
                      pcsc_dword_t *r_state,
                      pcsc_dword_t *r_protocol,
                      unsigned char *atr, pcsc_dword_t *atrlen);
long (* pcsc_begin_transaction) (long card);
long (* pcsc_end_transaction) (long card,
                               pcsc_dword_t disposition);
long (* pcsc_transmit) (long card,
                        const pcsc_io_request_t send_pci,
                        const unsigned char *send_buffer,
                        pcsc_dword_t send_len,
                        pcsc_io_request_t recv_pci,
                        unsigned char *recv_buffer,
                        pcsc_dword_t *recv_len);
long (* pcsc_set_timeout) (long context,
                           pcsc_dword_t timeout);
long (* pcsc_control) (long card,
                       pcsc_dword_t control_code,
                       const void *send_buffer,
                       pcsc_dword_t send_len,
                       void *recv_buffer,
                       pcsc_dword_t recv_len,
                       pcsc_dword_t *bytes_returned);

static void
bad_request (const char *type)
{
  fprintf (stderr, PGM ": bad `%s' request\n", type);
  exit (1);
}

static void
request_failed (int err)
{
  if (!err)
    err = -1;

  putchar (0x81); /* Simple error/success response. */

  putchar (0);
  putchar (0);
  putchar (0);
  putchar (4);

  putchar ((err >> 24) & 0xff);
  putchar ((err >> 16) & 0xff);
  putchar ((err >>  8) & 0xff);
  putchar ((err      ) & 0xff);

  fflush (stdout);
}

static void
request_succeeded (const void *buffer, size_t buflen)
{
  size_t len;

  putchar (0x81); /* Simple error/success response. */

  len = 4 + buflen;
  putchar ((len >> 24) & 0xff);
  putchar ((len >> 16) & 0xff);
  putchar ((len >>  8) & 0xff);
  putchar ((len      ) & 0xff);

  /* Error code. */
  putchar (0);
  putchar (0);
  putchar (0);
  putchar (0);

  /* Optional reponse string. */
  if (buffer)
    fwrite (buffer, buflen, 1, stdout);

  fflush (stdout);
}

static unsigned long
read_32 (FILE *fp)
{
  int c1, c2, c3, c4;

  c1 = getc (fp);
  c2 = getc (fp);
  c3 = getc (fp);
  c4 = getc (fp);
  if (c1 == EOF || c2 == EOF || c3 == EOF || c4 == EOF)
    {
      fprintf (stderr, PGM ": premature EOF while parsing request\n");
      exit (1);
    }
  return ((unsigned long)c1 << 24) | (c2 << 16) | (c3 << 8) | c4;
}

static const char *
pcsc_error_string (long err)
{
  const char *s;

  if (!err)
    return "okay";
  if ((err & 0x80100000) != 0x80100000)
    return "invalid PC/SC error code";
  err &= 0xffff;
  switch (err)
    {
    case 0x0002: s = "cancelled"; break;
    case 0x000e: s = "can't dispose"; break;
    case 0x0008: s = "insufficient buffer"; break;
    case 0x0015: s = "invalid ATR"; break;
    case 0x0003: s = "invalid handle"; break;
    case 0x0004: s = "invalid parameter"; break;
    case 0x0005: s = "invalid target"; break;
    case 0x0011: s = "invalid value"; break;
    case 0x0006: s = "no memory"; break;
    case 0x0013: s = "comm error"; break;
    case 0x0001: s = "internal error"; break;
    case 0x0014: s = "unknown error"; break;
    case 0x0007: s = "waited too long"; break;
    case 0x0009: s = "unknown reader"; break;
    case 0x000a: s = "timeout"; break;
    case 0x000b: s = "sharing violation"; break;
    case 0x000c: s = "no smartcard"; break;
    case 0x000d: s = "unknown card"; break;
    case 0x000f: s = "proto mismatch"; break;
    case 0x0010: s = "not ready"; break;
    case 0x0012: s = "system cancelled"; break;
    case 0x0016: s = "not transacted"; break;
    case 0x0017: s = "reader unavailable"; break;
    case 0x0065: s = "unsupported card"; break;
    case 0x0066: s = "unresponsive card"; break;
    case 0x0067: s = "unpowered card"; break;
    case 0x0068: s = "reset card"; break;
    case 0x0069: s = "removed card"; break;
    case 0x006a: s = "inserted card"; break;
    case 0x001f: s = "unsupported feature"; break;
    case 0x0019: s = "PCI too small"; break;
    case 0x001a: s = "reader unsupported"; break;
    case 0x001b: s = "duplicate reader"; break;
    case 0x001c: s = "card unsupported"; break;
    case 0x001d: s = "no service"; break;
    case 0x001e: s = "service stopped"; break;
    default:     s = "unknown PC/SC error code"; break;
    }
  return s;
}

static void
load_pcsc_driver (const char *libname)
{
  void *handle;

  handle = dlopen (libname, RTLD_LAZY);
  if (!handle)
    {
      fprintf (stderr, PGM ": failed to open driver `%s': %s",
               libname, dlerror ());
      exit (1);
    }

  pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
  pcsc_release_context   = dlsym (handle, "SCardReleaseContext");
  pcsc_list_readers      = dlsym (handle, "SCardListReaders");
  pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
  pcsc_connect           = dlsym (handle, "SCardConnect");
  pcsc_reconnect         = dlsym (handle, "SCardReconnect");
  pcsc_disconnect        = dlsym (handle, "SCardDisconnect");
  pcsc_status            = dlsym (handle, "SCardStatus");
  pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
  pcsc_end_transaction   = dlsym (handle, "SCardEndTransaction");
  pcsc_transmit          = dlsym (handle, "SCardTransmit");
  pcsc_set_timeout       = dlsym (handle, "SCardSetTimeout");
  pcsc_control           = dlsym (handle, "SCardControl");

  if (!pcsc_establish_context
      || !pcsc_release_context
      || !pcsc_list_readers
      || !pcsc_get_status_change
      || !pcsc_connect
      || !pcsc_reconnect
      || !pcsc_disconnect
      || !pcsc_status
      || !pcsc_begin_transaction
      || !pcsc_end_transaction
      || !pcsc_transmit
      || !pcsc_control
      /* || !pcsc_set_timeout */)
    {
      /* Note that set_timeout is currently not used and also not
         available under Windows. */
      fprintf (stderr,
               "apdu_open_reader: invalid PC/SC driver "
               "(%d%d%d%d%d%d%d%d%d%d%d%d%d)\n",
               !!pcsc_establish_context,
               !!pcsc_release_context,
               !!pcsc_list_readers,
               !!pcsc_get_status_change,
               !!pcsc_connect,
               !!pcsc_reconnect,
               !!pcsc_disconnect,
               !!pcsc_status,
               !!pcsc_begin_transaction,
               !!pcsc_end_transaction,
               !!pcsc_transmit,
               !!pcsc_set_timeout,
               !!pcsc_control );
      dlclose (handle);
      exit (1);
    }
}

/* Handle a open request.  The argument is expected to be a string
   with the port identification.  ARGBUF is always guaranteed to be
   terminted by a 0 which is not counted in ARGLEN.  We may modifiy
   ARGBUF. */
static void
handle_open (unsigned char *argbuf, size_t arglen)
{
  long err;
  const char *portstr;
  char *list = NULL;
  char *rdrname = NULL;
  pcsc_dword_t nreader, atrlen;
  char *p;
  pcsc_dword_t card_state, card_protocol;
  unsigned char atr[33];

  /* Make sure there is only the port string */
  if (arglen != strlen ((char*)argbuf))
    bad_request ("OPEN");
  if (arglen == 0)
    portstr = NULL;
  else
    portstr = (char*)argbuf;

  if (driver_is_open)
    {
      fprintf (stderr, PGM ": PC/SC has already been opened\n");
      request_failed (-1);
      return;
    }

  err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL, &pcsc_context);
  if (err)
    {
      fprintf (stderr, PGM": pcsc_establish_context failed: %s (0x%lx)\n",
               pcsc_error_string (err), err);
      request_failed (err);
      return;
    }

  err = pcsc_list_readers (pcsc_context, NULL, NULL, &nreader);
  if (!err)
    {
      list = malloc (nreader+1); /* Better add 1 for safety reasons. */
      if (!list)
        {
          fprintf (stderr, PGM": error allocating memory for reader list\n");
          exit (1);
        }
      err = pcsc_list_readers (pcsc_context, NULL, list, &nreader);
    }
  if (err)
    {
      fprintf (stderr, PGM": pcsc_list_readers failed: %s (0x%lx)\n",
               pcsc_error_string (err), err);
      pcsc_release_context (pcsc_context);
      free (list);
      request_failed (err);
      return;
    }

  p = list;
  while (nreader)
    {
      if (!*p && !p[1])
        break;
      fprintf (stderr, PGM": detected reader `%s'\n", p);
      if (nreader < (strlen (p)+1))
        {
          fprintf (stderr, PGM": invalid response from pcsc_list_readers\n");
          break;
        }
      if (!rdrname && portstr && !strncmp (p, portstr, strlen (portstr)))
        rdrname = p;
      nreader -= strlen (p)+1;
      p += strlen (p) + 1;
    }

  if (!rdrname)
    rdrname = list;

  current_rdrname = strdup (rdrname);
  if (!current_rdrname)
    {
      fprintf (stderr, PGM": error allocating memory for reader name\n");
      exit (1);
    }
  free (list);

  err = pcsc_connect (pcsc_context,
                      current_rdrname,
                      PCSC_SHARE_EXCLUSIVE,
                      PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
                      &pcsc_card,
                      &pcsc_protocol);
  if (err == 0x8010000c) /* No smartcard.  */
    {
      pcsc_card = 0;
    }
  else if (err)
    {
      fprintf (stderr, PGM": pcsc_connect failed: %s (0x%lx)\n",
               pcsc_error_string (err), err);
      pcsc_release_context (pcsc_context);
      free (current_rdrname);
      current_rdrname = NULL;
      pcsc_card = 0;
      pcsc_protocol = 0;
      request_failed (err);
      return;
    }

  current_atrlen = 0;
  if (!err)
    {
      char reader[250];
      pcsc_dword_t readerlen;

      atrlen = 33;
      readerlen = sizeof reader -1;
      err = pcsc_status (pcsc_card,
                         reader, &readerlen,
                         &card_state, &card_protocol,
                         atr, &atrlen);
      if (err)
        fprintf (stderr, PGM": pcsc_status failed: %s (0x%lx)\n",
                 pcsc_error_string (err), err);
      else
        {
          if (atrlen >= sizeof atr || atrlen >= sizeof current_atr)
            {
              fprintf (stderr, PGM": ATR returned by pcsc_status"
                       " is too large\n");
              exit (4);
            }
          memcpy (current_atr, atr, atrlen);
          current_atrlen = atrlen;
        }
    }

  driver_is_open = 1;
  request_succeeded (current_atr, current_atrlen);
}

/* Handle a close request.  We expect no arguments.  We may modifiy
   ARGBUF. */
static void
handle_close (unsigned char *argbuf, size_t arglen)
{
  (void)argbuf;
  (void)arglen;

  if (!driver_is_open)
    {
      fprintf (stderr, PGM ": PC/SC has not yet been opened\n");
      request_failed (-1);
      return;
    }

  free (current_rdrname);
  current_rdrname = NULL;
  pcsc_release_context (pcsc_context);
  pcsc_card = 0;
  pcsc_protocol = 0;

  request_succeeded (NULL, 0);
}

/* Handle a status request.  We expect no arguments.  We may modifiy
   ARGBUF. */
static void
handle_status (unsigned char *argbuf, size_t arglen)
{
  long err;
  struct pcsc_readerstate_s rdrstates[1];
  int status;
  unsigned char buf[20];

  (void)argbuf;
  (void)arglen;

  if (!driver_is_open)
    {
      fprintf (stderr, PGM ": PC/SC has not yet been opened\n");
      request_failed (-1);
      return;
    }

  memset (rdrstates, 0, sizeof *rdrstates);
  rdrstates[0].reader = current_rdrname;
  rdrstates[0].current_state = PCSC_STATE_UNAWARE;
  err = pcsc_get_status_change (pcsc_context,
                                0,
                                rdrstates, 1);
  if (err == 0x8010000a) /* Timeout.  */
    err = 0;
  if (err)
    {
      fprintf (stderr, PGM": pcsc_get_status_change failed: %s (0x%lx)\n",
               pcsc_error_string (err), err);
      request_failed (err);
      return;
    }

  status = 0;
  if ( !(rdrstates[0].event_state & PCSC_STATE_UNKNOWN) )
    {
      if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
	{
	  status |= 2;
	  if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
	    status |= 4;
	}
      /* We indicate a useful card if it is not in use by another
         application.  This is because we only use exclusive access
         mode.  */
      if ( (status & 6) == 6
           && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
        status |= 1;
    }

  /* First word is identical to the one used by apdu.c. */
  buf[0] = 0;
  buf[1] = 0;
  buf[2] = 0;
  buf[3] = status;
  /* The second word is the native PCSC state.  */
  buf[4] = (rdrstates[0].event_state >> 24);
  buf[5] = (rdrstates[0].event_state >> 16);
  buf[6] = (rdrstates[0].event_state >>  8);
  buf[7] = (rdrstates[0].event_state >>  0);
  /* The third word is the protocol. */
  buf[8]  = (pcsc_protocol >> 24);
  buf[9]  = (pcsc_protocol >> 16);
  buf[10] = (pcsc_protocol >> 8);
  buf[11] = (pcsc_protocol);

  request_succeeded (buf, 8);
}

/* Handle a reset request.  We expect no arguments.  We may modifiy
   ARGBUF. */
static void
handle_reset (unsigned char *argbuf, size_t arglen)
{
  long err;
  char reader[250];
  pcsc_dword_t nreader, atrlen;
  pcsc_dword_t card_state, card_protocol;

  (void)argbuf;
  (void)arglen;

  if (!driver_is_open)
    {
      fprintf (stderr, PGM ": PC/SC has not yet been opened\n");
      request_failed (-1);
      return;
    }

  if (pcsc_card)
    {
      err = pcsc_disconnect (pcsc_card, PCSC_LEAVE_CARD);
      if (err == 0x80100003)  /* Invalid handle.  (already disconnected) */
        err = 0;
      if (err)
        {
          fprintf (stderr, PGM": pcsc_disconnect failed: %s (0x%lx)\n",
                     pcsc_error_string (err), err);
          request_failed (err);
          return;
        }
      pcsc_card = 0;
    }

  err = pcsc_connect (pcsc_context,
                      current_rdrname,
                      PCSC_SHARE_EXCLUSIVE,
                      PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
                      &pcsc_card,
                      &pcsc_protocol);
  if (err)
    {
      fprintf (stderr, PGM": pcsc_connect failed: %s (0x%lx)\n",
               pcsc_error_string (err), err);
      pcsc_card = 0;
      request_failed (err);
      return;
    }

  atrlen = 33;
  nreader = sizeof reader - 1;
  err = pcsc_status (pcsc_card,
                     reader, &nreader,
                     &card_state, &card_protocol,
                     current_atr, &atrlen);
  if (err)
    {
      fprintf (stderr, PGM": pcsc_status failed: %s (0x%lx)\n",
               pcsc_error_string (err), err);
      current_atrlen = 0;
      request_failed (err);
      return;
    }

  request_succeeded (current_atr, current_atrlen);
}

/* Handle a transmit request.  The argument is expected to be a buffer
   with the APDU.  We may modifiy ARGBUF. */
static void
handle_transmit (unsigned char *argbuf, size_t arglen)
{
  long err;
  struct pcsc_io_request_s send_pci;
  pcsc_dword_t recv_len;
  unsigned char buffer[4096];

  /* The apdu should at least be one byte. */
  if (!arglen)
    bad_request ("TRANSMIT");

  if (!driver_is_open)
    {
      fprintf (stderr, PGM ": PC/SC has not yet been opened\n");
      request_failed (-1);
      return;
    }
  if ((pcsc_protocol & PCSC_PROTOCOL_T1))
    send_pci.protocol = PCSC_PROTOCOL_T1;
  else
    send_pci.protocol = PCSC_PROTOCOL_T0;
  send_pci.pci_len = sizeof send_pci;
  recv_len = sizeof (buffer);
  err = pcsc_transmit (pcsc_card, &send_pci, argbuf, arglen,
                       NULL, buffer, &recv_len);
  if (err)
    {
      if (verbose)
        fprintf (stderr, PGM": pcsc_transmit failed: %s (0x%lx)\n",
                 pcsc_error_string (err), err);
      request_failed (err);
      return;
    }
  request_succeeded (buffer, recv_len);
}

/* Handle a control request.  The argument is expected to be a buffer
   which contains CONTROL_CODE (4-byte) and INPUT_BYTES.
 */
static void
handle_control (unsigned char *argbuf, size_t arglen)
{
  long err;
  pcsc_dword_t ioctl_code;
  pcsc_dword_t recv_len = 1024;
  unsigned char buffer[1024];

  if (arglen < 4)
    bad_request ("CONTROL");

  ioctl_code = (((pcsc_dword_t)argbuf[0] << 24)
                | (argbuf[1] << 16) | (argbuf[2] << 8) | argbuf[3]);
  argbuf += 4;
  arglen -= 4;

  recv_len = sizeof (buffer);
  err = pcsc_control (pcsc_card, ioctl_code, argbuf, arglen,
                      buffer, recv_len, &recv_len);
  if (err)
    {
      if (verbose)
        fprintf (stderr, PGM": pcsc_control failed: %s (0x%lx)\n",
                 pcsc_error_string (err), err);
      request_failed (err);
      return;
    }
  request_succeeded (buffer, recv_len);
}

static void
print_version (int with_help)
{
  fputs (MYVERSION_LINE "\n"
         "Copyright (C) 2004 Free Software Foundation, Inc.\n"
         "This program comes with ABSOLUTELY NO WARRANTY.\n"
         "This is free software, and you are welcome to redistribute it\n"
         "under certain conditions. See the file COPYING for details.\n",
         stdout);

  if (with_help)
    fputs ("\n"
          "Usage: " PGM " [OPTIONS] API-NUMBER [LIBNAME]\n"
          "Helper to connect scdaemon to the PC/SC library\n"
          "\n"
          "  --verbose   enable extra informational output\n"
          "  --version   print version of the program and exit\n"
          "  --help      display this help and exit\n"
          BUGREPORT_LINE, stdout );

  exit (0);
}

int
main (int argc, char **argv)
{
  int last_argc = -1;
  int api_number = 0;
  int c;

  if (argc)
    {
      argc--; argv++;
    }
  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--version"))
        print_version (0);
      else if (!strcmp (*argv, "--help"))
        print_version (1);
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose = 1;
          argc--; argv++;
        }
    }
  if (argc != 1 && argc != 2)
    {
      fprintf (stderr, "usage: " PGM " API-NUMBER [LIBNAME]\n");
      exit (1);
    }

  api_number = atoi (*argv);
  argv++; argc--;
  if (api_number != 1)
    {
      fprintf (stderr, PGM ": api-number %d is not valid\n", api_number);
      exit (1);
    }

  load_pcsc_driver (argc? *argv : DEFAULT_PCSC_DRIVER);

  while ((c = getc (stdin)) != EOF)
    {
      size_t arglen;
      unsigned char argbuffer[2048];

      arglen = read_32 (stdin);
      if (arglen >= sizeof argbuffer - 1)
        {
          fprintf (stderr, PGM ": request too long\n");
          exit (1);
        }
      if (arglen && fread (argbuffer, arglen, 1, stdin) != 1)
        {
          fprintf (stderr, PGM ": error reading request: %s\n",
                   strerror (errno));
          exit (1);
        }
      argbuffer[arglen] = 0;
      switch (c)
        {
        case 1:
          handle_open (argbuffer, arglen);
          break;

        case 2:
          handle_close (argbuffer, arglen);
          exit (0);
          break;

        case 3:
          handle_transmit (argbuffer, arglen);
          break;

        case 4:
          handle_status (argbuffer, arglen);
          break;

        case 5:
          handle_reset (argbuffer, arglen);
          break;

        case 6:
          handle_control (argbuffer, arglen);
          break;

        default:
          fprintf (stderr, PGM ": invalid request 0x%02X\n", c);
          exit (1);
        }
    }
  return 0;
}

/*
Local Variables:
compile-command: "gcc -Wall -g -o pcsc-wrapper pcsc-wrapper.c -ldl"
End:
*/


text:
{% extends "layout.html" %}

{% block title %}Golem : {{project|capitalize}} : Tests{% endblock %}

{% block head %}
	<link rel="stylesheet" href="{{ url_for('static', filename='css/list_common.css') }}">
{% endblock %}

{% block content %}

{{project|capitalize|replace("_", " ")}} - Tests

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
<?php

// OroInstallerBundle:Process/Step:schema.html.twig
return array (
);


text:
@interface MOBProjectionEPSG5560 : MOBProjection

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kiss.Data.Schema;

namespace Kiss.Data
{
    /// <summary>
    /// IDbSchemaProvider
    /// </summary>
    public interface IDbSchemaProvider
    {
        /// <summary>
        /// get procedure schema
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        SqlProcedure GetProcedure(string name);

        /// <summary>
        /// get table/view schema
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        SqlTable GetTable(string name);
    }
}


text:
/* eslint-disable */
import * as Long from 'long';
import { util, configure, Writer, Reader } from 'protobufjs/minimal';
export const protobufPackage = 'zigbeealliance.distributedcomplianceledger.pki';
const baseGrant = { address: '', time: 0, info: '' };
export const Grant = {
    encode(message, writer = Writer.create()) {
        if (message.address !== '') {
            writer.uint32(10).string(message.address);
        }
        if (message.time !== 0) {
            writer.uint32(16).int64(message.time);
        }
        if (message.info !== '') {
            writer.uint32(26).string(message.info);
        }
        return writer;
    },
    decode(input, length) {
        const reader = input instanceof Uint8Array ? new Reader(input) : input;
        let end = length === undefined ? reader.len : reader.pos + length;
        const message = { ...baseGrant };
        while (reader.pos < end) {
            const tag = reader.uint32();
            switch (tag >>> 3) {
                case 1:
                    message.address = reader.string();
                    break;
                case 2:
                    message.time = longToNumber(reader.int64());
                    break;
                case 3:
                    message.info = reader.string();
                    break;
                default:
                    reader.skipType(tag & 7);
                    break;
            }
        }
        return message;
    },
    fromJSON(object) {
        const message = { ...baseGrant };
        if (object.address !== undefined && object.address !== null) {
            message.address = String(object.address);
        }
        else {
            message.address = '';
        }
        if (object.time !== undefined && object.time !== null) {
            message.time = Number(object.time);
        }
        else {
            message.time = 0;
        }
        if (object.info !== undefined && object.info !== null) {
            message.info = String(object.info);
        }
        else {
            message.info = '';
        }
        return message;
    },
    toJSON(message) {
        const obj = {};
        message.address !== undefined && (obj.address = message.address);
        message.time !== undefined && (obj.time = message.time);
        message.info !== undefined && (obj.info = message.info);
        return obj;
    },
    fromPartial(object) {
        const message = { ...baseGrant };
        if (object.address !== undefined && object.address !== null) {
            message.address = object.address;
        }
        else {
            message.address = '';
        }
        if (object.time !== undefined && object.time !== null) {
            message.time = object.time;
        }
        else {
            message.time = 0;
        }
        if (object.info !== undefined && object.info !== null) {
            message.info = object.info;
        }
        else {
            message.info = '';
        }
        return message;
    }
};
var globalThis = (() => {
    if (typeof globalThis !== 'undefined')
        return globalThis;
    if (typeof self !== 'undefined')
        return self;
    if (typeof window !== 'undefined')
        return window;
    if (typeof global !== 'undefined')
        return global;
    throw 'Unable to locate global object';
})();
function longToNumber(long) {
    if (long.gt(Number.MAX_SAFE_INTEGER)) {
        throw new globalThis.Error('Value is larger than Number.MAX_SAFE_INTEGER');
    }
    return long.toNumber();
}
if (util.Long !== Long) {
    util.Long = Long;
    configure();
}


text:
package org.jbpm.casemgmt.impl.command;

import java.util.Map;

import org.drools.core.command.impl.KnowledgeCommandContext;
import org.jbpm.casemgmt.api.StageNotFoundException;
import org.jbpm.casemgmt.impl.event.CaseEventSupport;
import org.jbpm.services.api.ProcessInstanceNotFoundException;
import org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl;
import org.jbpm.workflow.instance.node.DynamicNodeInstance;
import org.jbpm.workflow.instance.node.DynamicUtils;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.internal.command.Context;

/**
 * Adds subprocess (identified by processId) to selected ad hoc process instance with given parameters
 */
public class AddDynamicProcessToStageCommand extends CaseCommand<Void> {

    private static final long serialVersionUID = 6345222909719335953L;

    private String caseId;
    private String processId;
    private String stageId;
    private long processInstanceId;
    private Map<String, Object> parameters;

    public AddDynamicProcessToStageCommand(String caseId, Long processInstanceId, String stageId, String processId, Map<String, Object> parameters) {
        this.caseId = caseId;
        this.processInstanceId = processInstanceId;
        this.stageId = stageId;
        this.processId = processId;
        this.parameters = parameters;

        if (processInstanceId == null || processId == null || stageId == null) {
            throw new IllegalArgumentException("Mandatory parameters are missing - process instance id / process id / stage id");
        }
    }

    @Override
    public Void execute(Context context) {
        KieSession ksession = ((KnowledgeCommandContext) context).getKieSession();

        ProcessInstance processInstance = ksession.getProcessInstance(processInstanceId);
        if (processInstance == null) {
            throw new ProcessInstanceNotFoundException("No process instance found with id " + processInstanceId);
        }

        DynamicNodeInstance dynamicContext = (DynamicNodeInstance) ((WorkflowProcessInstanceImpl) processInstance).getNodeInstances(true).stream()
                .filter(ni -> (ni instanceof DynamicNodeInstance) && stageId.equals(ni.getNode().getMetaData().get("UniqueId")))
                .findFirst()
                .orElse(null);

        if (dynamicContext == null) {
            throw new StageNotFoundException("No stage found with id " + stageId);
        }
        CaseEventSupport caseEventSupport = getCaseEventSupport(context);
        caseEventSupport.fireBeforeDynamicProcessAdded(caseId, processInstanceId, processId, parameters);

        long subProcessInstanceId = DynamicUtils.addDynamicSubProcess(dynamicContext, ksession, processId, parameters);

        caseEventSupport.fireAfterDynamicProcessAdded(caseId, processInstanceId, processId, parameters, subProcessInstanceId);
        return null;
    }

}


text:
import { DeviceType } from './device-type';

let instance;

const type = 'action.devices.types.LIGHT'
const iconFunction = (attributes) => {
  if (attributes.colorTemperatureRange) {
    return 'image:wb-iridescent'
  }
  return 'image:wb-incandescent'
}

class Light extends DeviceType {
  constructor() {
    super()
    this.monochromeValuesArray = [{
      nicknames: ['ceiling lights'],
      roomHint: 'Family Room',
    }, {
      nicknames: ['garden lights'],
      roomHint: 'Front Yard',
    }, {
      nicknames: ['workshop light'],
      roomHint: 'Shed',
    }, {
      nicknames: ['porch light'],
      roomHint: 'Front Yard',
    }];

    this.rgbValuesArray = [{
      nicknames: ['table lamp'],
      roomHint: 'Living Room',
    }, {
      nicknames: ['reading lamp'],
      roomHint: 'Bedroom',
    }, {
      nicknames: ['doorway'],
      roomHint: 'Hallway',
    }, {
      nicknames: ['stairway'],
      roomHint: 'Hallway',
    }];
  }

  static createMonochromeLight() {
    if (!instance) {
      instance = new Light()
    }
    const element = instance.monochromeValuesArray.shift();

    return {
      id: instance.genUuid(),
      type,
      traits: [
        'action.devices.traits.Brightness',
        'action.devices.traits.OnOff',
        'action.devices.traits.ColorSetting',
      ],
      defaultNames: [`Smart Lamp`],
      name: `Smart Lamp`,
      nicknames: instance.getNicknames(element),
      roomHint: instance.getRoomHint(element),
      attributes: {
        colorModel: 'rgb',
        colorTemperatureRange: {
          temperatureMinK: 2000,
          temperatureMaxK: 9000,
        },
      },
      willReportState: true,
      states: {
        on: false,
        online: true,
        brightness: 90,
        color: {
          temperatureK: 2000,
        },
      },
      hwVersion: '1.0.0',
      swVersion: '2.0.0',
      model: 'L',
      manufacturer: 'L',
    };
  }

  static createRgbLight() {
    if (!instance) {
      instance = new Light()
    }
    const element = instance.rgbValuesArray.shift();

    return {
      id: instance.genUuid(),
      type,
      traits: [
        'action.devices.traits.Brightness',
        'action.devices.traits.OnOff',
        'action.devices.traits.ColorSetting',
      ],
      defaultNames: [`Smart RGB Light`],
      name: `Smart RGB Light`,
      nicknames: instance.getNicknames(element),
      roomHint: instance.getRoomHint(element),
      attributes: {
        colorModel: 'rgb',
      },
      willReportState: true,
      states: {
        on: false,
        online: true,
        brightness: 90,
        color: {
          spectrumRgb: 0xFF0000 /* Red */,
        },
      },
      hwVersion: '1.0.0',
      swVersion: '2.0.0',
      model: 'L',
      manufacturer: 'L',
    };
  }
}

window.deviceTypes.push({
  type,
  identifier: '_addMonochromeLight',
  icon: 'image:wb-iridescent',
  label: 'Monochrome Light',
  iconFunction,
  function: (app) => {
    app._createDevice(Light.createMonochromeLight());
  },
})

window.deviceTypes.push({
  type,
  identifier: '_addLight',
  icon: 'image:wb-incandescent',
  label: 'RGB Light',
  iconFunction,
  function: (app) => {
    app._createDevice(Light.createRgbLight());
  },
})


text:
<!DOCTYPE html>

        <title>My blog - test/thing2.html</title>

Custom paths with leading slash

This asserts that you can specify custom file paths with a leading slash and it doesn't make a difference.


text:
      <form class="login-form" ng-submit="ac.login()">
        <input type="text" placeholder="username" ng-model="ac.username" />
        <input type="password" placeholder="password" ng-model="ac.password" />
        <button>login</button>

Not registered? Create Account

      </form>


text:
using Marten.Internal;
using Marten.Storage;
using Marten.Testing.Documents;
using NSubstitute;
using Shouldly;
using Xunit;

namespace Marten.Testing.Internals
{
    public class StorageCheckingPersistenceGraphTests
    {
        [Fact]
        public void only_calls_ensure_storage_exists_on_first_call()
        {
            var options = new StoreOptions();
            var inner = new ProviderGraph(options);
            var storage = Substitute.For<ITenantStorage>();

            var graph = new StorageCheckingProviderGraph(storage, inner);

            var userPersistence = graph.StorageFor<User>();
            var userPersistence2 = graph.StorageFor<User>();
            var userPersistence3 = graph.StorageFor<User>();

            storage.Received(1).EnsureStorageExists(typeof(User));

            userPersistence.ShouldBeSameAs(userPersistence2);
            userPersistence.ShouldBeSameAs(userPersistence3);
        }
    }
}


text:
jQuery(document).ready(function() {
    jQuery('.toggle-nav').click(function(e) {
        jQuery(this).toggleClass('active');
        jQuery('.menu ul').toggleClass('active');

        e.preventDefault();
    });
});


text:
    Bridge.define("System.Collections.Generic.SortedSet$1.TreeSubSet", function (T) { return {
        inherits: [System.Collections.Generic.SortedSet$1(T)],
        $kind: "nested class",
        fields: {
            underlying: null,
            min: Bridge.getDefaultValue(T),
            max: Bridge.getDefaultValue(T),
            lBoundActive: false,
            uBoundActive: false
        },
        alias: [
            "contains", "System$Collections$Generic$ICollection$1$" + Bridge.getTypeAlias(T) + "$contains",
            "clear", "System$Collections$Generic$ICollection$1$" + Bridge.getTypeAlias(T) + "$clear"
        ],
        ctors: {
            $ctor1: function (Underlying, Min, Max, lowerBoundActive, upperBoundActive) {
                this.$initialize();
                System.Collections.Generic.SortedSet$1(T).$ctor1.call(this, Underlying.Comparer);
                this.underlying = Underlying;
                this.min = Min;
                this.max = Max;
                this.lBoundActive = lowerBoundActive;
                this.uBoundActive = upperBoundActive;
                this.root = this.underlying.FindRange$1(this.min, this.max, this.lBoundActive, this.uBoundActive);
                this.count = 0;
                this.version = -1;
                this.VersionCheckImpl();
            },
            ctor: function () {
                this.$initialize();
                System.Collections.Generic.SortedSet$1(T).ctor.call(this);
                this.comparer = null;
            }
        },
        methods: {
            AddIfNotPresent: function (item) {

                if (!this.IsWithinRange(item)) {
                    System.ThrowHelper.ThrowArgumentOutOfRangeException$1(System.ExceptionArgument.collection);
                }

                var ret = this.underlying.AddIfNotPresent(item);
                this.VersionCheck();

                return ret;
            },
            contains: function (item) {
                this.VersionCheck();
                return System.Collections.Generic.SortedSet$1(T).prototype.contains.call(this, item);
            },
            DoRemove: function (item) {

                if (!this.IsWithinRange(item)) {
                    return false;
                }

                var ret = this.underlying.remove(item);
                this.VersionCheck();
                return ret;
            },
            clear: function () {

                if (this.count === 0) {
                    return;
                }

                var toRemove = new (System.Collections.Generic.List$1(T)).ctor();
                this.BreadthFirstTreeWalk(function (n) {
                    toRemove.add(n.Item);
                    return true;
                });
                while (toRemove.Count !== 0) {
                    this.underlying.remove(toRemove.getItem(((toRemove.Count - 1) | 0)));
                    toRemove.removeAt(((toRemove.Count - 1) | 0));
                }
                this.root = null;
                this.count = 0;
                this.version = this.underlying.version;
            },
            IsWithinRange: function (item) {
                var $t, $t1;

                var comp = (this.lBoundActive ? ($t = this.Comparer)[Bridge.geti($t, "System$Collections$Generic$IComparer$1$" + Bridge.getTypeAlias(T) + "$compare", "System$Collections$Generic$IComparer$1$compare")](this.min, item) : -1);
                if (comp > 0) {
                    return false;
                }
                comp = (this.uBoundActive ? ($t1 = this.Comparer)[Bridge.geti($t1, "System$Collections$Generic$IComparer$1$" + Bridge.getTypeAlias(T) + "$compare", "System$Collections$Generic$IComparer$1$compare")](this.max, item) : 1);
                if (comp < 0) {
                    return false;
                }
                return true;
            },
            InOrderTreeWalk$1: function (action, reverse) {
                var $t, $t1;
                this.VersionCheck();

                if (this.root == null) {
                    return true;
                }

                var stack = new (System.Collections.Generic.Stack$1(System.Collections.Generic.SortedSet$1.Node(T))).$ctor2(Bridge.Int.mul(2, System.Collections.Generic.SortedSet$1(T).log2(((this.count + 1) | 0))));
                var current = this.root;
                while (current != null) {
                    if (this.IsWithinRange(current.Item)) {
                        stack.Push(current);
                        current = (reverse ? current.Right : current.Left);
                    } else if (this.lBoundActive && ($t = this.Comparer)[Bridge.geti($t, "System$Collections$Generic$IComparer$1$" + Bridge.getTypeAlias(T) + "$compare", "System$Collections$Generic$IComparer$1$compare")](this.min, current.Item) > 0) {
                        current = current.Right;
                    } else {
                        current = current.Left;
                    }
                }

                while (stack.Count !== 0) {
                    current = stack.Pop();
                    if (!action(current)) {
                        return false;
                    }

                    var node = (reverse ? current.Left : current.Right);
                    while (node != null) {
                        if (this.IsWithinRange(node.Item)) {
                            stack.Push(node);
                            node = (reverse ? node.Right : node.Left);
                        } else if (this.lBoundActive && ($t1 = this.Comparer)[Bridge.geti($t1, "System$Collections$Generic$IComparer$1$" + Bridge.getTypeAlias(T) + "$compare", "System$Collections$Generic$IComparer$1$compare")](this.min, node.Item) > 0) {
                            node = node.Right;
                        } else {
                            node = node.Left;
                        }
                    }
                }
                return true;
            },
            BreadthFirstTreeWalk: function (action) {
                var $t, $t1;
                this.VersionCheck();

                if (this.root == null) {
                    return true;
                }

                var processQueue = new (System.Collections.Generic.List$1(System.Collections.Generic.SortedSet$1.Node(T))).ctor();
                processQueue.add(this.root);
                var current;

                while (processQueue.Count !== 0) {
                    current = processQueue.getItem(0);
                    processQueue.removeAt(0);
                    if (this.IsWithinRange(current.Item) && !action(current)) {
                        return false;
                    }
                    if (current.Left != null && (!this.lBoundActive || ($t = this.Comparer)[Bridge.geti($t, "System$Collections$Generic$IComparer$1$" + Bridge.getTypeAlias(T) + "$compare", "System$Collections$Generic$IComparer$1$compare")](this.min, current.Item) < 0)) {
                        processQueue.add(current.Left);
                    }
                    if (current.Right != null && (!this.uBoundActive || ($t1 = this.Comparer)[Bridge.geti($t1, "System$Collections$Generic$IComparer$1$" + Bridge.getTypeAlias(T) + "$compare", "System$Collections$Generic$IComparer$1$compare")](this.max, current.Item) > 0)) {
                        processQueue.add(current.Right);
                    }

                }
                return true;
            },
            FindNode: function (item) {

                if (!this.IsWithinRange(item)) {
                    return null;
                }
                this.VersionCheck();
                return System.Collections.Generic.SortedSet$1(T).prototype.FindNode.call(this, item);
            },
            InternalIndexOf: function (item) {
                var $t, $t1;
                var count = -1;
                $t = Bridge.getEnumerator(this);
                try {
                    while ($t.moveNext()) {
                        var i = $t.Current;
                        count = (count + 1) | 0;
                        if (($t1 = this.Comparer)[Bridge.geti($t1, "System$Collections$Generic$IComparer$1$" + Bridge.getTypeAlias(T) + "$compare", "System$Collections$Generic$IComparer$1$compare")](item, i) === 0) {
                            return count;
                        }
                    }
                } finally {
                    if (Bridge.is($t, System.IDisposable)) {
                        $t.System$IDisposable$Dispose();
                    }
                }
                return -1;
            },
            VersionCheck: function () {
                this.VersionCheckImpl();
            },
            VersionCheckImpl: function () {
                if (this.version !== this.underlying.version) {
                    this.root = this.underlying.FindRange$1(this.min, this.max, this.lBoundActive, this.uBoundActive);
                    this.version = this.underlying.version;
                    this.count = 0;
                    this.InOrderTreeWalk(Bridge.fn.bind(this, $asm.$.System.Collections.Generic.SortedSet$1.TreeSubSet.f1));
                }
            },
            GetViewBetween: function (lowerValue, upperValue) {
                var $t, $t1;

                if (this.lBoundActive && ($t = this.Comparer)[Bridge.geti($t, "System$Collections$Generic$IComparer$1$" + Bridge.getTypeAlias(T) + "$compare", "System$Collections$Generic$IComparer$1$compare")](this.min, lowerValue) > 0) {
                    throw new System.ArgumentOutOfRangeException.$ctor1("lowerValue");
                }
                if (this.uBoundActive && ($t1 = this.Comparer)[Bridge.geti($t1, "System$Collections$Generic$IComparer$1$" + Bridge.getTypeAlias(T) + "$compare", "System$Collections$Generic$IComparer$1$compare")](this.max, upperValue) < 0) {
                    throw new System.ArgumentOutOfRangeException.$ctor1("upperValue");
                }
                var ret = Bridge.cast(this.underlying.GetViewBetween(lowerValue, upperValue), System.Collections.Generic.SortedSet$1.TreeSubSet(T));
                return ret;
            },
            IntersectWithEnumerable: function (other) {
                var $t;

                var toSave = new (System.Collections.Generic.List$1(T)).$ctor2(this.Count);
                $t = Bridge.getEnumerator(other, T);
                try {
                    while ($t.moveNext()) {
                        var item = $t.Current;
                        if (this.contains(item)) {
                            toSave.add(item);
                            this.remove(item);
                        }
                    }
                } finally {
                    if (Bridge.is($t, System.IDisposable)) {
                        $t.System$IDisposable$Dispose();
                    }
                }
                this.clear();
                this.AddAllElements(toSave);
            }
        }
    }; });

    Bridge.ns("System.Collections.Generic.SortedSet$1.TreeSubSet", $asm.$);

    Bridge.apply($asm.$.System.Collections.Generic.SortedSet$1.TreeSubSet, {
        f1: function (n) {
            this.count = (this.count + 1) | 0;
            return true;
        }
    });


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('quiz', '0003_question_points'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Quizzer',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=200)),
                ('points', models.IntegerField(default=0)),
                ('answered', models.ManyToManyField(to='quiz.Question')),
                ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]


text:
package org.railsschool.tiramisu.views.patterns;

import android.content.Context;
import android.view.View;
import android.widget.TextView;

import org.railsschool.tiramisu.R;
import org.railsschool.tiramisu.models.dao.DayNotificationPreference;
import org.railsschool.tiramisu.models.dao.TwoHourNotificationPreference;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * @class ReminderSeekbarLabelPattern
 * @brief
 */
public class ReminderSeekbarLabelPattern {
    private Context _context;

    @InjectView(R.id.pattern_reminder_seekbar_always)
    TextView _always;

    @InjectView(R.id.pattern_reminder_seekbar_attending)
    TextView _onlyIfAttending;

    @InjectView(R.id.pattern_reminder_seekbar_never)
    TextView _never;

    public ReminderSeekbarLabelPattern(Context context, View pattern) {
        this._context = context;
        ButterKnife.inject(this, pattern);
    }

    private void _setCurrent(int value) {
        int softGray = _context.getResources().getColor(R.color.soft_gray),
            blue = _context.getResources().getColor(R.color.blue);

        _always.setTextColor(softGray);
        _onlyIfAttending.setTextColor(softGray);
        _never.setTextColor(softGray);

        if (value == 0) {
            _always.setTextColor(blue);
        } else if (value == 2) {
            _never.setTextColor(blue);
        } else {
            _onlyIfAttending.setTextColor(blue);
        }
    }

    public void update(TwoHourNotificationPreference preference) {
        _setCurrent(preference.toInt());
    }

    public void update(DayNotificationPreference preference) {
        _setCurrent(preference.toInt());
    }
}


text:
using namespace std;

int display_image(char** argv, string file_name, string title);

#endif


text:
/*!
 @header KOStoryMyStoryInfo.h
 카카오스토리의 내스토리 정보를 담고 있는 구조체.
 */

#import <Foundation/Foundation.h>

/*!
 @abstract KOStoryMediaType 스토리의 미디어 형식
 @constant KOStoryMediaTypeUnknown 알수 없는 미디어 형식
 @constant KOStoryMediaTypeNotSupported 지원되지 않는 미디어 형식
 @constant KOStoryMediaTypeNote 텍스트 같은 노트 형식
 @constant KOStoryMediaTypePhoto 사진 이미지 같은 포토 형식
 */
typedef NS_ENUM(NSInteger, KOStoryMediaType) {
    KOStoryMediaTypeUnknown = 0,
    KOStoryMediaTypeNotSupported,
    KOStoryMediaTypeNote,
    KOStoryMediaTypePhoto
};

/*!
 @abstract KOStoryPermission 스토리의 공개 범위
 @constant KOStoryPermissionUnknown 알수 없는 공개 범위
 @constant KOStoryPermissionPublic 전체공개
 @constant KOStoryPermissionFriend 친구공개
 @constant KOStoryPermissionOnlyMe 나만보기
 */
typedef NS_ENUM(NSInteger, KOStoryPermission) {
    KOStoryPermissionUnknown = 0,
    KOStoryPermissionPublic,
    KOStoryPermissionFriend,
    KOStoryPermissionOnlyMe
};

@class KOStoryMyStoryImageInfo;
@class KOStoryCommentInfo;
@class KOStoryLikeInfo;

/*!
 @class KOStoryMyStoryInfo
 @discussion 카카오스토리의 내스토리 정보를 담고 있는 구조체.
 */

@interface KOStoryMyStoryInfo : NSObject

/*!
 @property ID
 @abstract 내스토리 정보의 id(포스트 id)
 */
@property(nonatomic, readonly) NSString *ID;

/*!
 @property content
 @abstract 내스토리 정보의 내용
 */
@property(nonatomic, readonly) NSString *content;

/*!
 @property mediaType
 @abstract 내스토리 정보의 미디어타입. 예) NOTE, PHOTO, LINK, UNKNOWN
 */
@property(nonatomic, readonly) KOStoryMediaType mediaType;

/*!
 @property createdAt
 @abstract 내스토리 정보의 생성시간. RFC3339를 따름.
 */
@property(nonatomic, readonly) NSString *createdAt;

/*!
 @property media
 @abstract 내스토리 정보의 미디어타입이 PHOTO일 경우 이미지 내용의 array. KOStoryMyStoryImageInfo 객체의 array.
 */
@property(nonatomic, readonly) NSArray<KOStoryMyStoryImageInfo *> *media;

/*!
 @property url
 @abstract 내스토리 정보의 url
 */
@property(nonatomic, readonly) NSString *url;

/*!
 @property commentCount
 @abstract 내스토리 정보의 comment 숫자
 */
@property(nonatomic, readonly) NSNumber *commentCount;

/*!
 @property likeCount
 @abstract 내스토리 정보의 like 숫자
 */
@property(nonatomic, readonly) NSNumber *likeCount;

/*!
 @property comments
 @abstract 댓글 정보들을 담고 있는 array. KOStoryCommentInfo 객체의 array. 내스토리 정보 요청을 통해 값이 채워짐.
 */
@property(nonatomic, readonly) NSArray<KOStoryCommentInfo *> *comments;

/*!
 @property likes
 @abstract 좋아요 등 느낌(감성표현)에 대한 정보들을 담고 있는 array. KOStoryLikeInfo 객체의 array. 내스토리 정보 요청을 통해 값이 채워짐.
 */
@property(nonatomic, readonly) NSArray<KOStoryLikeInfo *> *likes;

/*!
 @property permission
 @abstract 내스토리 정보의 공개 범위. 예) PUBLIC, FRIEND, ONLY_ME, UNKNOWN
 */
@property(nonatomic, readonly) KOStoryPermission permission;

- (id)initWithID:(NSString *)myStoryID
         content:(NSString *)content
       mediaType:(KOStoryMediaType)mediaType
       createdAt:(NSString *)createdAt
           media:(NSArray<KOStoryMyStoryImageInfo *> *)media
             url:(NSString *)url
    commentCount:(NSNumber *)commentCount
       likeCount:(NSNumber *)likeCount
        comments:(NSArray<KOStoryCommentInfo *> *)comments
           likes:(NSArray<KOStoryLikeInfo *> *)likes
      permission:(KOStoryPermission)permission;

- (NSString *)convertMediaTypeToString:(KOStoryMediaType)mediaType;

- (NSString *)convertPermissionToString:(KOStoryPermission)permission;

@end


text:
A generic ND array with compile time dimensions
This requires C++14

## Features:

* Type safety and sanity unlike C arrays - preserve array dimensions across function calls
* Fast accessing and slicing - as performant as C arrays + type safety
* Stack allocatable - no new or malloc calls, and also doesn't introduce an extra layer of dereferencing in an array of structures of arrays
* Safe reshaping - ensures shapes are compatible at compile time
* Assert based runtime checks - safe to use on GPUs, and doesn't violate the "only pay for what you use" concept (though maybe exceptions will be fine with C++29+ with respect to this... Until then)
* Header only - not certain this is a feature (ie, compile times); but at least it's easy to snapshot in :)

## Usage:

```c++
#include "nd_array/nd_array.hpp"

ND_Array<Object_type, dim_0, dim_1, ..., dim_k> a;
ND_Array<Object_type, dim_2, dim_3, ..., dim_k> & b = a.outer_slice(idx_dim0, idx_dim1);
ND_Array<Object_type, newdim_1, newdim_2, ..., newdim_m> & c = b.template reshape<ND_Array<Object_type, newdim1, ..., newdim_m> >();

a(idx_1, idx_2, ..., idx_k) = Object_type();

auto itr = a.begin();

// Returns the iterator offset by the specified amounts in each dimension
// This may result in an invalid iterator, comparisons with begin() and end() should be made after
auto itr_offset = a.offset(itr, 5, -2, 4, 6, 7);
```

# Zip Iterator
Also included: a Zip iterator which enables iterating over multiple iterable containers of the same size.
Performance of the iterator was a major concern; tests indicate it's as good as manually iterating over all of the containers simultaneously.
Note that the zip iterator defaults to assuming all of the iterable containers are of the Random Access type, this can be changed by specifying the type as the first template parameter.
This requires C++17

Basic usage:

```c++
#include "nd_array/zip.hpp"

ND_Array<double, 2, 10, 10> vel;
for(auto [vel_x, vel_y] : zip::make_zip(vel.outer_slice(0), vel.outer_slice(1))) {
  // ...
}
// With the iterator tag specified
for(auto [vel_x, vel_y] : zip::make_zip<std::random_access_iterator_tag>(vel.outer_slice(0), vel.outer_slice(1))) {
  // ...
}
```

# Performance results

The performance comparison executable is built by default; it assumes google benchmark is installed in `/usr/local`.
To change this, specify `google_benchmark_path` when configuring with CMake.

The following results are the averrage and standard deviation (in that order) of the CPU time collected by running the performance tests 5 times:

## Gcc 9, `-O3 -fmarch=native -fstrict-aliasing`, `Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz`
```
BM_Null                                  1       0.08
BM_ND_Array_Create                   69758    4400

BM_C_Array_Iterate                   45240     380
BM_ND_Array_Iterate_Index            47020     450
BM_ND_Array_Iterate_Pointer          41116     700
BM_ND_Array_Iterate_Iterator         40658     130

BM_C_Array_Initialize               129758     690
BM_ND_Array_Initialize_Index        130136     710
BM_ND_Array_Initialize_Pointer      129483    1400
BM_ND_Array_Initialize_Iterator     129983    1300

BM_ND_Array_Iterate_2_Index         115402     810
BM_ND_Array_Iterate_2_Pointer       115964    2300
BM_ND_Array_Iterate_2_Iterator      115351    1000
BM_ND_Array_Iterate_2_Zip           116129     290

BM_ND_Array_Initialize_2_Index      259394     920
BM_ND_Array_Initialize_2_Pointer    259251     720
BM_ND_Array_Initialize_2_Iterator   260720    3400
BM_ND_Array_Initialize_2_Zip        259068    1300

BM_ND_Array_Deref_MMul             1206767   98000
BM_ND_Array_MMul                   1259991    3100
BM_C_Array_MMul                     200179   16000
BM_C_Ptr_MMul                       277302    3000
```

The GCC results indicate that performance is mostly as expected; ie equivalent to using a C array.
The major outlier to this is the performance of the matrix multiplication, GCC is able to optimize the C array but not the ND Array; some study is needed to understand why.
Future tests should be done with a less naive implementation of the matrix multiply algorithm to make certain these results hold.

## Clang 8, `-O3 -fmarch=native -fstrict-aliasing`, `Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz`
```
BM_Null                                  0      0.040
BM_ND_Array_Create                   23935   2400

BM_C_Array_Iterate                   41199    530
BM_ND_Array_Iterate_Index            41333    150
BM_ND_Array_Iterate_Pointer          32654    100
BM_ND_Array_Iterate_Iterator         32784    150

BM_C_Array_Initialize               118901  11000
BM_ND_Array_Initialize_Index        115346  16000
BM_ND_Array_Initialize_Pointer      115272  16000
BM_ND_Array_Initialize_Iterator     115270  16000

BM_ND_Array_Iterate_2_Index          23247    610
BM_ND_Array_Iterate_2_Pointer         2808     14
BM_ND_Array_Iterate_2_Iterator       32683    430
BM_ND_Array_Iterate_2_Zip            32751    450

BM_ND_Array_Initialize_2_Index      254585    530
BM_ND_Array_Initialize_2_Pointer    254403    290
BM_ND_Array_Initialize_2_Iterator   234290  27000
BM_ND_Array_Initialize_2_Zip        231021  32000

BM_ND_Array_Deref_MMul              421887  44000
BM_ND_Array_MMul                    439503   2700
BM_C_Array_MMul                     447811   6700
BM_C_Ptr_MMul                       440590   1567
```

The Clang results are somewhat odd, particularly the pointer iteration over 2 ND arrays is clearly wrong, suggesting some issue with Clang optimizing things it shouldn't.
The matrix multiplication performance is essentially identical regardless of the datastructure used. Thus, with Clang, the performance difference between a C array and an ND Array is likely negligible; though perhaps slower than a C array with GCC when performing mathematical operations.


text:
import React from 'react';
import { createFixtureTree } from 'react-cosmos-shared2/fixtureTree';
import { FixtureId, FixtureList } from 'react-cosmos-shared2/renderer';
import { useValue } from 'react-cosmos/fixture';
import { TreeExpansion } from '../../../shared/treeExpansion';
import { FixtureTree } from './FixtureTree';

const fixtures: FixtureList = {
  'src/Dashboard.ts': { type: 'single' },
  'src/Settings.ts': { type: 'single' },
  'src/shared/Dropdown.ts': { type: 'single' },
  'src/shared/Button.ts': {
    type: 'multi',
    fixtureNames: ['normal', 'disabled'],
  },
};
const rootNode = createFixtureTree({
  fixtures,
  fixturesDir: '__fixtures__',
  fixtureFileSuffix: 'fixture',
});

const disabledFixtureId = { path: 'src/shared/Button.ts', name: 'disabled' };

export default {
  collapsed: createTreeFixture(),
  expanded: createTreeFixture({ shared: true }),
  'selected collapsed': createTreeFixture({}, disabledFixtureId),
  'selected expanded': createTreeFixture({ shared: true }, disabledFixtureId),
};

function createTreeFixture(
  initialTreeExpansion: TreeExpansion = {},
  fixtureId: null | FixtureId = null
) {
  return () => {
    const [selectedFixtureId, setSelectedFixtureId] = useValue(
      'selectedFixtureId',
      { defaultValue: fixtureId }
    );
    const [expansion, setExpansion] = useValue('treeExpansion', {
      defaultValue: initialTreeExpansion,
    });
    return (
      <FixtureTree
        rootNode={rootNode}
        selectedFixtureId={selectedFixtureId}
        selectedRef={{ current: null }}
        expansion={expansion}
        onSelect={setSelectedFixtureId}
        setExpansion={setExpansion}
      />
    );
  };
}


text:
using System;
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Commenter.IntegrationTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Tunnel Vision Laboratories, LLC")]
[assembly: AssemblyProduct("Commenter.IntegrationTests")]
[assembly: AssemblyCopyright("Copyright © Sam Harwell 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("308c510f-5639-4021-8797-27ab1d8c31c5")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
<?php
/**
 * Text block implementation, it extends DDElementTemplate like all other elements
 */
	class TF_FusionSlider extends DDElementTemplate {
		public function __construct() {

			parent::__construct();
		}

		// Implementation for the element structure.
		public function create_element_structure() {

			// Add name of the class to deserialize it again when the element is sent back to the server from the web page
			$this->config['php_class'] 		= get_class($this);
			// element id
			$this->config['id']	   		= 'fusionslider';
			// element shortcode base
			$this->config['base']	   		= 'fusionslider';
			// element name
			$this->config['name']	 		= __('Fusion Slider', 'fusion-core');
			// element icon
			$this->config['icon_url']  		= "";
			// css class related to this element
			$this->config['css_class'] 		= "fusion_element_box";
			// element icon class
			$this->config['icon_class']		= 'fusion-icon builder-options-icon fusiona-TFicon';
			// tooltip that will be displyed upon mouse over the element
			//$this->config['tool_tip']  		= 'Creates a simple text block';
			// any special html data attribute (i.e. data-width) needs to be passed
			// drop_level: elements with higher drop level can be dropped in elements with lower drop_level,
			// i.e. element with drop_level = 2 can be dropped in element with drop_level = 0 or 1 only.
			$this->config['data'] 			= array("drop_level"   => "4");
		}

		// override default implemenation for this function as this element have special view
		public function create_visual_editor( $params ) {

			$innerHtml  = '
';
			$innerHtml .= '
'.__('Fusion Slider', 'fusion-core').'
[fusionslider name="106"]

';
			$innerHtml .= '
';
			$this->config['innerHtml'] = $innerHtml;
		}

		//this function defines TextBlock sub elements or structure
		function popup_elements() {

			$this->config['subElements'] = array(

				array("name"	  => __('Slider Name', 'fusion-core'),
					  "desc"	  => __('This is the shortcode name that can be used in the post content area. It is usually all lowercase and contains only letters, numbers, and hyphens. ex: "fusionslider_slidernamehere"', 'fusion-core'),
					  "id"		=> "name",
					  "type"	  => ElementTypeEnum::SELECT,
					  "value"	   => "",
					  "allowedValues"   => FusionHelper::fusion_shortcodes_categories( 'slide-page' )
			),

				array("name" 			=> __('CSS Class', 'fusion-core'),
					  "desc"			=> __('Add a class to the wrapping HTML element.', 'fusion-core'),
					  "id" 				=> "class",
					  "type" 			=> ElementTypeEnum::INPUT,
					  "value" 			=> ""
					  ),

				array("name" 			=> __('CSS ID', 'fusion-core'),
					  "desc"			=> __('Add an ID to the wrapping HTML element.', 'fusion-core'),
					  "id" 				=> "id",
					  "type" 			=> ElementTypeEnum::INPUT,
					  "value" 			=> ""
					  ),
				);
		}
	}


text:
package org.apache.falcon.regression;

import org.apache.falcon.entity.v0.EntityType;
import org.apache.falcon.regression.core.bundle.Bundle;
import org.apache.falcon.entity.v0.Frequency.TimeUnit;
import org.apache.falcon.regression.core.enumsAndConstants.MerlinConstants;
import org.apache.falcon.regression.core.helpers.ColoHelper;
import org.apache.falcon.regression.core.util.*;
import org.apache.falcon.regression.testHelper.BaseTestClass;
import org.apache.hadoop.fs.FileSystem;
import org.apache.log4j.Logger;
import org.apache.oozie.client.Job.Status;
import org.apache.oozie.client.OozieClient;
import org.testng.Assert;
import org.testng.annotations.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * Tests with process lib folder with workflow.xml.
 */
@Test(groups = "embedded")
public class ProcessLibPathLoadTest extends BaseTestClass {

    private ColoHelper cluster = servers.get(0);
    private OozieClient clusterOC = serverOC.get(0);
    private FileSystem clusterFS = serverFS.get(0);
    private String testDir = cleanAndGetTestDir();
    private String aggregateWorkflowDir = testDir + "/aggregator";
    private static final Logger LOGGER = Logger.getLogger(ProcessLibPathLoadTest.class);

    private String oozieLib = MerlinConstants.OOZIE_EXAMPLE_LIB;
    private String oozieLibName = oozieLib.substring(oozieLib.lastIndexOf('/') + 1);
    private String filename = OSUtil.OOZIE_LIB_FOLDER + "lib/" + oozieLibName;
    private String processName;
    private String process;

    @BeforeClass(alwaysRun = true)
    public void createTestData() throws Exception {
        LOGGER.info("in @BeforeClass");
        saveUrlToFile(oozieLib);
    }

    @BeforeMethod(alwaysRun = true)
    public void setup() throws Exception {
        uploadDirToClusters(aggregateWorkflowDir, OSUtil.OOZIE_LIB_FOLDER);
        bundles[0] = BundleUtil.readELBundle();
        bundles[0] = new Bundle(bundles[0], cluster);
        bundles[0].generateUniqueBundle(this);
        bundles[0].setInputFeedDataPath(testDir + MINUTE_DATE_PATTERN);
        bundles[0].setProcessValidity("2015-01-02T01:00Z", "2015-01-02T01:04Z");
        bundles[0].setProcessPeriodicity(5, TimeUnit.minutes);
        bundles[0].setOutputFeedPeriodicity(5, TimeUnit.minutes);
        bundles[0].setOutputFeedLocationData(testDir + "/output-data" + MINUTE_DATE_PATTERN);
        bundles[0].setProcessConcurrency(1);
        bundles[0].setProcessLibPath(aggregateWorkflowDir + "/lib");
        process = bundles[0].getProcessData();
        processName = Util.readEntityName(process);
    }

    @AfterMethod(alwaysRun = true)
    public void tearDown() {
        removeTestClassEntities();
    }

    @AfterClass(alwaysRun = true)
    public void deleteJar() {
        File file = new File(filename);
        Assert.assertEquals(file.delete(), true, filename + " is not present.");
    }

    /**
     * Test which test a process with jar in lib location.
     * Schedule a process, it should succeed.
     *
     * @throws Exception
     */
    @Test
    public void setRightJarInWorkflowLib() throws Exception {
        bundles[0].setProcessWorkflow(aggregateWorkflowDir);
        bundles[0].submitFeedsScheduleProcess(prism);
        InstanceUtil.waitTillInstancesAreCreated(clusterOC, process, 0);
        OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0);
        OozieUtil.waitForBundleToReachState(clusterOC, processName, Status.SUCCEEDED);
    }

    /**
     * Test which test a process with no jar in lib location.
     * Schedule a process, it should get killed.
     *
     * @throws Exception
     */
    @Test
    public void setNoJarInWorkflowLibLocation() throws Exception {
        HadoopUtil.deleteDirIfExists(aggregateWorkflowDir + "/lib/" + oozieLibName, clusterFS);
        bundles[0].setProcessWorkflow(aggregateWorkflowDir);
        bundles[0].submitFeedsScheduleProcess(prism);
        InstanceUtil.waitTillInstancesAreCreated(clusterOC, process, 0);
        OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0);
        OozieUtil.waitForBundleToReachState(clusterOC, processName, Status.KILLED);
    }

    /**
     * Function to download jar at remote public location.
     * @param urlString public location from where jar is to be downloaded
     * filename is the location where the jar is to be saved
     * @throws Exception
     */
    private void saveUrlToFile(String urlString)
        throws IOException {

        URL url = new URL(urlString);
        String link;
        HttpURLConnection http = (HttpURLConnection) url.openConnection();
        Map<String, List<String>> header = http.getHeaderFields();
        while (isRedirected(header)) {
            link = header.get("Location").get(0);
            url = new URL(link);
            http = (HttpURLConnection) url.openConnection();
            header = http.getHeaderFields();
        }

        InputStream input = http.getInputStream();
        byte[] buffer = new byte[4096];
        int n = -1;
        OutputStream output = new FileOutputStream(new File(filename));
        while ((n = input.read(buffer)) != -1) {
            output.write(buffer, 0, n);
        }
        output.close();
    }

    private static boolean isRedirected(Map<String, List<String>> header) {
        for (String hv : header.get(null)) {
            if (hv.contains(" 301 ") || hv.contains(" 302 ")) {
                return true;
            }
        }
        return false;
    }

}


text:
package tracing

import (
	"context"
	"fmt"
	"reflect"
	"time"

	"github.com/go-kit/log"
	"github.com/go-kit/log/level"
	config_util "github.com/prometheus/common/config"
	"github.com/prometheus/common/version"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	tracesdk "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.12.0"
	"go.opentelemetry.io/otel/trace"
	"google.golang.org/grpc/credentials"

	"github.com/prometheus/prometheus/config"
)

const serviceName = "prometheus"

// Manager is capable of building, (re)installing and shutting down
// the tracer provider.
type Manager struct {
	logger       log.Logger
	done         chan struct{}
	config       config.TracingConfig
	shutdownFunc func() error
}

// NewManager creates a new tracing manager.
func NewManager(logger log.Logger) *Manager {
	return &Manager{
		logger: logger,
		done:   make(chan struct{}),
	}
}

// Run starts the tracing manager. It registers the global text map propagator and error handler.
// It is blocking.
func (m *Manager) Run() {
	otel.SetTextMapPropagator(propagation.TraceContext{})
	otel.SetErrorHandler(otelErrHandler(func(err error) {
		level.Error(m.logger).Log("msg", "OpenTelemetry handler returned an error", "err", err)
	}))
	<-m.done
}

// ApplyConfig takes care of refreshing the tracing configuration by shutting down
// the current tracer provider (if any is registered) and installing a new one.
func (m *Manager) ApplyConfig(cfg *config.Config) error {
	// Update only if a config change is detected. If TLS configuration is
	// set, we have to restart the manager to make sure that new TLS
	// certificates are picked up.
	var blankTLSConfig config_util.TLSConfig
	if reflect.DeepEqual(m.config, cfg.TracingConfig) && m.config.TLSConfig == blankTLSConfig {
		return nil
	}

	if m.shutdownFunc != nil {
		if err := m.shutdownFunc(); err != nil {
			return fmt.Errorf("failed to shut down the tracer provider: %w", err)
		}
	}

	// If no endpoint is set, assume tracing should be disabled.
	if cfg.TracingConfig.Endpoint == "" {
		m.config = cfg.TracingConfig
		m.shutdownFunc = nil
		otel.SetTracerProvider(trace.NewNoopTracerProvider())
		level.Info(m.logger).Log("msg", "Tracing provider uninstalled.")
		return nil
	}

	tp, shutdownFunc, err := buildTracerProvider(context.Background(), cfg.TracingConfig)
	if err != nil {
		return fmt.Errorf("failed to install a new tracer provider: %w", err)
	}

	m.shutdownFunc = shutdownFunc
	m.config = cfg.TracingConfig
	otel.SetTracerProvider(tp)

	level.Info(m.logger).Log("msg", "Successfully installed a new tracer provider.")
	return nil
}

// Stop gracefully shuts down the tracer provider and stops the tracing manager.
func (m *Manager) Stop() {
	defer close(m.done)

	if m.shutdownFunc == nil {
		return
	}

	if err := m.shutdownFunc(); err != nil {
		level.Error(m.logger).Log("msg", "failed to shut down the tracer provider", "err", err)
	}

	level.Info(m.logger).Log("msg", "Tracing manager stopped")
}

type otelErrHandler func(err error)

func (o otelErrHandler) Handle(err error) {
	o(err)
}

// buildTracerProvider return a new tracer provider ready for installation, together
// with a shutdown function.
func buildTracerProvider(ctx context.Context, tracingCfg config.TracingConfig) (trace.TracerProvider, func() error, error) {
	client, err := getClient(tracingCfg)
	if err != nil {
		return nil, nil, err
	}

	exp, err := otlptrace.New(ctx, client)
	if err != nil {
		return nil, nil, err
	}

	// Create a resource describing the service and the runtime.
	res, err := resource.New(
		ctx,
		resource.WithSchemaURL(semconv.SchemaURL),
		resource.WithAttributes(
			semconv.ServiceNameKey.String(serviceName),
			semconv.ServiceVersionKey.String(version.Version),
		),
		resource.WithProcessRuntimeDescription(),
		resource.WithTelemetrySDK(),
	)
	if err != nil {
		return nil, nil, err
	}

	tp := tracesdk.NewTracerProvider(
		tracesdk.WithBatcher(exp),
		tracesdk.WithSampler(tracesdk.ParentBased(
			tracesdk.TraceIDRatioBased(tracingCfg.SamplingFraction),
		)),
		tracesdk.WithResource(res),
	)

	return tp, func() error {
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		err := tp.Shutdown(ctx)
		if err != nil {
			return err
		}

		return nil
	}, nil
}

// getClient returns an appropriate OTLP client (either gRPC or HTTP), based
// on the provided tracing configuration.
func getClient(tracingCfg config.TracingConfig) (otlptrace.Client, error) {
	var client otlptrace.Client
	switch tracingCfg.ClientType {
	case config.TracingClientGRPC:
		opts := []otlptracegrpc.Option{otlptracegrpc.WithEndpoint(tracingCfg.Endpoint)}
		if tracingCfg.Insecure {
			opts = append(opts, otlptracegrpc.WithInsecure())
		} else {
			// Use of TLS Credentials forces the use of TLS. Therefore it can
			// only be set when `insecure` is set to false.
			tlsConf, err := config_util.NewTLSConfig(&tracingCfg.TLSConfig)
			if err != nil {
				return nil, err
			}
			opts = append(opts, otlptracegrpc.WithTLSCredentials(credentials.NewTLS(tlsConf)))
		}
		if tracingCfg.Compression != "" {
			opts = append(opts, otlptracegrpc.WithCompressor(tracingCfg.Compression))
		}
		if len(tracingCfg.Headers) != 0 {
			opts = append(opts, otlptracegrpc.WithHeaders(tracingCfg.Headers))
		}
		if tracingCfg.Timeout != 0 {
			opts = append(opts, otlptracegrpc.WithTimeout(time.Duration(tracingCfg.Timeout)))
		}

		client = otlptracegrpc.NewClient(opts...)
	case config.TracingClientHTTP:
		opts := []otlptracehttp.Option{otlptracehttp.WithEndpoint(tracingCfg.Endpoint)}
		if tracingCfg.Insecure {
			opts = append(opts, otlptracehttp.WithInsecure())
		}
		// Currently, OTEL supports only gzip compression.
		if tracingCfg.Compression == config.GzipCompression {
			opts = append(opts, otlptracehttp.WithCompression(otlptracehttp.GzipCompression))
		}
		if len(tracingCfg.Headers) != 0 {
			opts = append(opts, otlptracehttp.WithHeaders(tracingCfg.Headers))
		}
		if tracingCfg.Timeout != 0 {
			opts = append(opts, otlptracehttp.WithTimeout(time.Duration(tracingCfg.Timeout)))
		}

		tlsConf, err := config_util.NewTLSConfig(&tracingCfg.TLSConfig)
		if err != nil {
			return nil, err
		}
		opts = append(opts, otlptracehttp.WithTLSClientConfig(tlsConf))

		client = otlptracehttp.NewClient(opts...)
	}

	return client, nil
}


text:
import {Injectable}    from '@angular/core';
import {Http, URLSearchParams, Response} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from "rxjs";
import "rxjs";
import "rxjs/Rx";
import {Config} from "../config/config";
import {SearchService} from "./search.service";
import {LoginService} from "./login.service";

@Injectable()
export class BookingService {
    constructor(private http: Http, private searchService: SearchService, private loginService: LoginService) {
    }

    getBookings(): Observable<any[]> {
        let params = new URLSearchParams();
        params.set('token', this.loginService.logedUser.token.toString());
        return this.http.get(Config.API_ROUTES.ostravel + "api/reservations", {search: params})
            .map((res: Response) => res.json())
            .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
    }

    getBooking(id): Observable<any> {
        let params = new URLSearchParams();
        params.set('token', this.loginService.logedUser.token.toString());
        return this.http.get(Config.API_ROUTES.ostravel + "api/reservations/"+id, {search: params})
            .map((res: Response) => res.json())
            .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
    }

    cancel(id): Observable<any> {
        let params = new URLSearchParams();
        params.set('token', this.loginService.logedUser.token.toString());
        return this.http.get(Config.API_ROUTES.ostravel + "api/reservations/"+id+"/cancel", {search: params})
            .map((res: Response) => res.json())
            .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
    }

    validate(id): Observable<any> {
        let params = new URLSearchParams();
        params.set('token', this.loginService.logedUser.token.toString());
        return this.http.get(Config.API_ROUTES.ostravel + "api/amicales/"+id+"/validation", {search: params})
            .map((res: Response) => res.json())
            .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
    }

}


text:
using MediaBrowser.Model.Sync;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace Emby.ApiClient.Data
{
    public interface IFileRepository
    {
        /// <summary>
        /// Gets the file system entries.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>Task<List<DeviceFileInfo>>.</returns>
        Task<List<DeviceFileInfo>> GetFileSystemEntries(string path);

        /// <summary>
        /// Saves the file.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="path">The path.</param>
        /// <returns>Task.</returns>
        Task SaveFile(Stream stream, string path);

#if WINDOWS_UWP
        /// <summary>
        /// Saves the file.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="path">The path.</param>
        /// <returns>Task.</returns>
        Task SaveFile(Windows.Storage.IStorageFile file, string path);
#endif

        /// <summary>
        /// Deletes the file.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>Task.</returns>
        Task DeleteFile(string path);

        /// <summary>
        /// Deletes the directory.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>Task.</returns>
        Task DeleteFolder(string path);

        /// <summary>
        /// Strips invalid characters from a given name
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns>System.String.</returns>
        string GetValidFileName(string name);

        /// <summary>
        /// Files the exists.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>Task<System.Boolean>.</returns>
        Task<bool> FileExists(string path);

        /// <summary>
        /// Gets the full local path.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>System.String.</returns>
        string GetFullLocalPath(IEnumerable<string> path);

        /// <summary>
        /// Gets the parent directory path.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>System.String.</returns>
        string GetParentDirectoryPath(string path);

        /// <summary>
        /// Gets the file stream.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>Task<Stream>.</returns>
        Task<Stream> GetFileStream(string path);
#if WINDOWS_UWP
        /// <summary>
        /// Gets the file.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>Task<File>.</returns>
        Task<Windows.Storage.IStorageFile> GetFile(string path);
#endif
    }
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Assert = NUnit.Framework.Assert;

namespace Mkko.AnyLogAnalyzerTests.CliApp
{
    [TestClass]
    public class CommandLineInterfaceTests
    {
        [TestMethod]
        public void AppReturnsFileNotFoundReturnCodeIfFileIsMissing()
        {
            string[] args = {"-l", "not/existing/log.file", "-d", "not/existing/definitions.file"};
            var returncode = CommandLineInterface.Main(args);

            Assert.AreEqual((int)CliReturnCodes.FileNotFound, returncode);
        }

        [TestMethod]
        public void AppReturnsMissingParametersReturnCodeIfMandatoryParametersAreMissing()
        {
            string[] args = { "-l", TestConstants.EmbeddedJbossLogfile };
            var returncode = CommandLineInterface.Main(args);

            Assert.AreEqual((int)CliReturnCodes.MissingParameters, returncode);
        }
    }
}


text:
var connect = require('connect')
  , __pause = connect.utils.pause
  , everyauth = module.exports = {};

everyauth.helpExpress = require('./lib/expressHelper');

everyauth.debug = false;

// The connect middleware. e.g.,
//     connect(
//         ...
//       , everyauth.middleware()
//       , ...
//     )
everyauth.middleware = function () {
  var app = connect(
      function registerReqGettersAndMethods (req, res, next) {
        var methods = everyauth._req._methods
          , getters = everyauth._req._getters;
        for (var name in methods) {
          req[name] = methods[name];
        }
        for (name in getters) {
          Object.defineProperty(req, name, {
            get: getters[name]
          });
        }
        next();
      }
    , function fetchUserFromSession (req, res, next) {
        var sess = req.session
          , auth = sess && sess.auth
          , everymodule, findUser;
        if (!auth) return next();
        if (!auth.userId) return next();
        everymodule = everyauth.everymodule;
        if (!everymodule._findUserById) return next();
        var pause = __pause(req);
        everymodule._findUserById(auth.userId, function (err, user) {
          if (err) throw err; // TODO Leverage everyauth's error handling
          if (user) req.user = user;
          else delete sess.auth;
          next();
          pause.resume();
        });
      }
    , connect.router(function (app) {
        var modules = everyauth.enabled
          , _module;
        for (var _name in modules) {
          _module = modules[_name];
          _module.validateSteps();
          _module.routeApp(app);
        }
      })
  );
  return app;
};

everyauth._req = {
    _methods: {}
  , _getters: {}
};

everyauth.addRequestMethod = function (name, fn) {
  this._req._methods[name] = fn;
  return this;
};

everyauth.addRequestGetter = function (name, fn, isAsync) {
  this._req._getters[name] = fn;
  return this;
};

everyauth
  .addRequestMethod('logout', function () {
    var req = this;
    delete req.session.auth;

  }).addRequestGetter('loggedIn', function () {
    var req = this;
    if (req.session && req.session.auth && req.session.auth.loggedIn) {
      return true;
    } else {
      return false;
    }
  });

everyauth.modules = {};
everyauth.enabled = {};

// Grab all filenames in ./modules -- They correspond to the modules of the same name
// as the filename (minus '.js')
var fs = require('fs');
var files = fs.readdirSync(__dirname + '/lib/modules');
var includeModules = files.map( function (fname) {
  return fname.substring(0, fname.length - 3);
});
for (var i = 0, l = includeModules.length; i < l; i++) {
  var name = includeModules[i];

  // Lazy enabling of a module via `everyauth` getters
  // i.e., the `facebook` module is not loaded into memory
  // until `everyauth.facebook` is evaluated
  Object.defineProperty(everyauth, name, {
    get: (function (name) {
      return function () {
        var mod = this.modules[name] || (this.modules[name] = require('./lib/modules/' + name));
        // Make `everyauth` accessible from each auth strategy module
        if (!mod.everyauth) mod.everyauth = this;
        if (mod.shouldSetup)
          this.enabled[name] = mod;
        return mod;
      }
    })(name)
  });
};


text:
<!DOCTYPE html>

  <meta charset="<?php bloginfo('charset'); ?>">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title><?php wp_title('|',true,'right'); bloginfo('name'); ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <?php get_template_part('partials/seo'); ?>

  <link rel="alternate" type="application/rss+xml" title="<?php bloginfo('name'); ?> RSS Feed" href="<?php bloginfo('rss2_url'); ?>" />
  <link rel="icon" href="<?php bloginfo('stylesheet_directory'); ?>/img/dist/favicon.png">
  <link rel="shortcut" href="<?php bloginfo('stylesheet_directory'); ?>/img/dist/favicon.ico">
  <link rel="apple-touch-icon" href="<?php bloginfo('stylesheet_directory'); ?>/img/dist/favicon-touch.png">
  <link rel="apple-touch-icon" sizes="114x114" href="<?php bloginfo('stylesheet_directory'); ?>/img/dist/favicon.png">

  <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
  <?php wp_head(); ?>

<body <?php body_class(); ?>>

          <a href="<?php echo home_url(); ?>">
<?php bloginfo('name'); ?>

            <?php
              $active_slug = get_active_slug();
              $show_journal = IGV_get_option('_igv_show_journal');
            ?>
            <li <?php menu_active('about-me', $active_slug, 'menu-item'); ?>><a href="<?php echo home_url('about-me/'); ?>"><?php echo __('[:es]Acerca de[:en]About me'); ?>

            <li <?php menu_active('pichon', $active_slug, 'menu-item'); ?>><a href="<?php echo home_url('pichon/'); ?>"><?php echo __('[:es]Pichón[:en]Pichón'); ?>

            <?php
              if ($show_journal) {
            ?>
            <li <?php menu_active(array('journal', 'post'), $active_slug, 'menu-item'); ?>><a href="<?php echo home_url('journal/'); ?>"><?php echo __('[:es]Journal[:en]Journal'); ?>

            <?php
              }
            ?>
            <li <?php menu_active(array('recipe', 'ingredient', 'recipe_category'), $active_slug, 'menu-item'); ?>><a href="<?php echo home_url('recipes/'); ?>"><?php echo __('[:es]Recetas[:en]Recipes'); ?>

            <li <?php menu_active('client', $active_slug, 'menu-item'); ?>><a href="<?php echo home_url('clients/'); ?>"><?php echo __('[:es]Clientes[:en]Clients'); ?>

            <li <?php menu_active('press', $active_slug, 'menu-item'); ?>><a href="<?php echo home_url('press/'); ?>"><?php echo __('[:es]Prensa[:en]Press'); ?>

          <?php echo qtranxf_generateLanguageSelectCode('both'); ?>


text:
[Slides](VS2017_Saturday.pdf) and Demo of MY Session: **COME ESSERE PRODUTTIVI CON VSCODE** - VSSaturday 21 Oct 2017

## VIDEO LIVE SESSION (Ita) [https://youtu.be/OyoJcj2pNYo](https://youtu.be/OyoJcj2pNYo)
[![VIDEO LIVE SESSION](https://img.youtube.com/vi/OyoJcj2pNYo/0.jpg)](https://www.youtube.com/watch?v=OyoJcj2pNYo)

### Kudos to [Marco](https://twitter.com/marcobortolin) for great photos!

ME start presenting VSCODE on my Mac, and ... | [Davide](https://twitter.com/davidecontin) helping w/[Cubetto](https://www.primotoys.com) -Q: VSCODE Editor or IDE?
:---: | :---:
![ME Presenting](photo/me_presenting.jpeg) | ![Davide with Cubetto - VSCODE Editor or IDE](photo/davide_with_cubetto.jpeg)

 Thanks | to **EVERYONE** | who partecipated | to my session.
:---: | :---: | :---: | :---:
![live2](photo/live2.JPG) | ![live1](photo/live1.jpg) | ![live3](photo/live3.JPG) | ![live4](photo/live4.JPG)


text:
(async function() {
  TestRunner.addResult(
      `Test that debugger will pause in all event listeners when corresponding breakpoint is set. Bug 77331.\n`);
  await TestRunner.loadLegacyModule('sources'); await TestRunner.loadLegacyModule('panels/browser_debugger'); await TestRunner.loadTestModule('sources_test_runner');
  await TestRunner.showPanel('sources');
  await TestRunner.loadHTML(`
      <input type="button" id="test">
    `);
  await TestRunner.evaluateInPagePromise(`
      function listener1()
      {
      }

      function listener2()
      {
      }

      function listener3()
      {
      }

      function addListenerAndClick()
      {
          var element = document.getElementById("test");
          element.addEventListener("click", listener1, true);
          element.addEventListener("click", listener2, true);
          document.body.addEventListener("click", listener3, true);
          document.body.addEventListener("click", listener3, false);
          element.click();
      }
  `);

  SourcesTestRunner.runDebuggerTestSuite([function testClickBreakpoint(next) {
    SourcesTestRunner.setEventListenerBreakpoint('listener:click', true);
    SourcesTestRunner.waitUntilPaused(paused1);
    TestRunner.evaluateInPageWithTimeout('addListenerAndClick()');

    async function paused1(callFrames) {
      await SourcesTestRunner.captureStackTrace(callFrames);
      SourcesTestRunner.resumeExecution(resumed1);
    }

    function resumed1() {
      SourcesTestRunner.waitUntilPaused(paused2);
    }

    async function paused2(callFrames) {
      await SourcesTestRunner.captureStackTrace(callFrames);
      SourcesTestRunner.resumeExecution(resumed2);
    }

    function resumed2() {
      SourcesTestRunner.waitUntilPaused(paused3);
    }

    async function paused3(callFrames) {
      await SourcesTestRunner.captureStackTrace(callFrames);
      SourcesTestRunner.resumeExecution(resumed3);
    }

    function resumed3() {
      SourcesTestRunner.waitUntilPaused(paused4);
    }

    async function paused4(callFrames) {
      await SourcesTestRunner.captureStackTrace(callFrames);
      SourcesTestRunner.setEventListenerBreakpoint('listener:click', false);
      SourcesTestRunner.resumeExecution(next);
    }
  }]);
})();


text:
package com.vladkel.eFindMe.IHM.View;

import com.vladkel.eFindMe.IHM.MainWindow;
import com.vladkel.eFindMe.search.engine.SearchEngine;
import com.vladkel.eFindMe.search.engine.model.Url;

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;

/**
 * Created by eliott on 06/02/15.
 */
public class AddUrlView extends JFrame {

	private static final long serialVersionUID = 2371035244213180842L;

	private MainWindow mainWindow;

    private JLabel addurlsToLookForLabel = new JLabel("Ajouter une url :");

    private JLabel nameUrlLabel = new JLabel("Nom :");
    private JTextField nameUrlTextField = new JTextField();

    private JLabel descriptionUrlLabel = new JLabel("Description :");
    private JTextField descriptionUrlTextArea = new JTextField();

    private JLabel urlLabel = new JLabel("Url :");
    private JTextField urlTextField = new JTextField();

    private JButton addUrl = new JButton("Ajouter");

    public AddUrlView(MainWindow mainWindow){
        setLayout();
        events();

        this.mainWindow = mainWindow;

        this.setBackground(Color.WHITE);
        this.setTitle("Ajouter un utilisateur");
        this.setSize(new Dimension(300,250));
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    private void setLayout(){

        this.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        addurlsToLookForLabel.setFont(new Font("Arial", Font.BOLD, 16));

        urlTextField.setPreferredSize(new Dimension(150,20));
        nameUrlTextField.setPreferredSize(new Dimension(150,20));
        descriptionUrlTextArea.setPreferredSize(new Dimension(150,20));

        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridheight = 2;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(15,5,0,0);
        gbc.anchor = GridBagConstraints.CENTER;
        this.add(addurlsToLookForLabel, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridheight = 1;
        gbc.gridwidth = 1;
        gbc.insets = new Insets(15,5,0,0);
        gbc.anchor = GridBagConstraints.CENTER;
        this.add(nameUrlLabel, gbc);

        gbc.gridx = 1;
        gbc.gridy = 2;
        gbc.gridheight = 1;
        gbc.gridwidth = 1;
        gbc.insets = new Insets(5,5,0,0);
        gbc.anchor = GridBagConstraints.CENTER;
        this.add(nameUrlTextField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridheight = 1;
        gbc.gridwidth = 1;
        gbc.insets = new Insets(5,0,0,0);
        gbc.anchor = GridBagConstraints.CENTER;
        this.add(descriptionUrlLabel, gbc);

        gbc.gridx = 1;
        gbc.gridy = 3;
        gbc.gridheight = 1;
        gbc.gridwidth = 1;
        gbc.insets = new Insets(5,5,0,0);
        gbc.anchor = GridBagConstraints.CENTER;
        this.add(descriptionUrlTextArea, gbc);

        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridheight = 1;
        gbc.gridwidth = 1;
        gbc.insets = new Insets(5,0,0,0);
        gbc.anchor = GridBagConstraints.CENTER;
        this.add(urlLabel, gbc);

        gbc.gridx = 1;
        gbc.gridy = 4;
        gbc.gridheight = 1;
        gbc.gridwidth = 1;
        gbc.insets = new Insets(5,5,0,0);
        gbc.anchor = GridBagConstraints.CENTER;
        this.add(urlTextField, gbc);

        gbc.gridx = 1;
        gbc.gridy = 5;
        gbc.gridheight = 1;
        gbc.gridwidth = 1;
        gbc.insets = new Insets(5,5,0,0);
        gbc.anchor = GridBagConstraints.EAST;
        this.add(addUrl, gbc);

    }

    private void events(){
        addUrl.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event){

                if(isReadyToAddUrl()){
                    Url url = new Url();

                    Integer indice = SearchEngine.getInstance().currentUser.getUrlsToLookFor().size();

                    System.out.println("Indice url : " + indice.toString());

                    url.setId(indice.toString());
                    url.setDescription(descriptionUrlTextArea.getText());
                    url.setName(nameUrlTextField.getText());
                    url.setUrl(urlTextField.getText());

                    mainWindow.getModelUrlsToLookFor().addElement(url);
                    close();
                }
                else {
                    JOptionPane.showMessageDialog(null,
                            "Veuillez remplir les champs Nom, Description et Url pour enregistrer une url."
                    );
                }

            }
        });
    }

    private boolean isReadyToAddUrl(){
        return nameUrlTextField.getText().length() > 0 &&
                descriptionUrlLabel.getText().length() > 0 &&
                urlTextField.getText().length() > 0
                ;
    }

    private void close(){
        this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    }

}