text:
/* This file is for implementing all "generic" SSL functions that all libcurl
   internals should use. It is then responsible for calling the proper
   "backend" function.

   SSL-functions in libcurl should call functions in this source file, and not
   to any specific SSL-layer.

   Curl_ssl_ - prefix for generic ones
   Curl_ossl_ - prefix for OpenSSL ones
   Curl_gtls_ - prefix for GnuTLS ones
   Curl_nss_ - prefix for NSS ones
   Curl_gskit_ - prefix for GSKit ones
   Curl_polarssl_ - prefix for PolarSSL ones
   Curl_cyassl_ - prefix for CyaSSL ones
   Curl_schannel_ - prefix for Schannel SSPI ones
   Curl_darwinssl_ - prefix for SecureTransport (Darwin) ones

   Note that this source code uses curlssl_* functions, and they are all
   defines/macros #defined by the lib-specific header files.

   "SSL/TLS Strong Encryption: An Introduction"
   https://httpd.apache.org/docs/2.0/ssl/ssl_intro.html
*/

#include "curl_setup.h"

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif

#include "urldata.h"

#include "vtls.h" /* generic SSL protos etc */
#include "slist.h"
#include "sendf.h"
#include "strcase.h"
#include "url.h"
#include "progress.h"
#include "share.h"
#include "multiif.h"
#include "timeval.h"
#include "curl_md5.h"
#include "warnless.h"
#include "curl_base64.h"
#include "curl_printf.h"

/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"

/* convenience macro to check if this handle is using a shared SSL session */
#define SSLSESSION_SHARED(data) (data->share &&                        \
                                 (data->share->specifier &             \
                                  (1<<CURL_LOCK_DATA_SSL_SESSION)))

#define CLONE_STRING(var)                    \
  if(source->var) {                          \
    dest->var = strdup(source->var);         \
    if(!dest->var)                           \
      return FALSE;                          \
  }                                          \
  else                                       \
    dest->var = NULL;

bool
Curl_ssl_config_matches(struct ssl_primary_config* data,
                        struct ssl_primary_config* needle)
{
  if((data->version == needle->version) &&
     (data->version_max == needle->version_max) &&
     (data->verifypeer == needle->verifypeer) &&
     (data->verifyhost == needle->verifyhost) &&
     Curl_safe_strcasecompare(data->CApath, needle->CApath) &&
     Curl_safe_strcasecompare(data->CAfile, needle->CAfile) &&
     Curl_safe_strcasecompare(data->clientcert, needle->clientcert) &&
     Curl_safe_strcasecompare(data->cipher_list, needle->cipher_list))
    return TRUE;

  return FALSE;
}

bool
Curl_clone_primary_ssl_config(struct ssl_primary_config *source,
                              struct ssl_primary_config *dest)
{
  dest->verifyhost = source->verifyhost;
  dest->verifypeer = source->verifypeer;
  dest->version = source->version;
  dest->version_max = source->version_max;

  CLONE_STRING(CAfile);
  CLONE_STRING(CApath);
  CLONE_STRING(cipher_list);
  CLONE_STRING(egdsocket);
  CLONE_STRING(random_file);
  CLONE_STRING(clientcert);

  /* Disable dest sessionid cache if a client cert is used, CVE-2016-5419. */
  dest->sessionid = (dest->clientcert ? false : source->sessionid);
  return TRUE;
}

void Curl_free_primary_ssl_config(struct ssl_primary_config* sslc)
{
  Curl_safefree(sslc->CAfile);
  Curl_safefree(sslc->CApath);
  Curl_safefree(sslc->cipher_list);
  Curl_safefree(sslc->egdsocket);
  Curl_safefree(sslc->random_file);
  Curl_safefree(sslc->clientcert);
}

int Curl_ssl_backend(void)
{
  return (int)CURL_SSL_BACKEND;
}

#ifdef USE_SSL

/* "global" init done? */
static bool init_ssl=FALSE;

/**
 * Global SSL init
 *
 * @retval 0 error initializing SSL
 * @retval 1 SSL initialized successfully
 */
int Curl_ssl_init(void)
{
  /* make sure this is only done once */
  if(init_ssl)
    return 1;
  init_ssl = TRUE; /* never again */

  return curlssl_init();
}

/* Global cleanup */
void Curl_ssl_cleanup(void)
{
  if(init_ssl) {
    /* only cleanup if we did a previous init */
    curlssl_cleanup();
    init_ssl = FALSE;
  }
}

static bool ssl_prefs_check(struct Curl_easy *data)
{
  /* check for CURLOPT_SSLVERSION invalid parameter value */
  const long sslver = data->set.ssl.primary.version;
  if((sslver < 0) || (sslver >= CURL_SSLVERSION_LAST)) {
    failf(data, "Unrecognized parameter value passed via CURLOPT_SSLVERSION");
    return FALSE;
  }

  switch(data->set.ssl.primary.version_max) {
  case CURL_SSLVERSION_MAX_NONE:
  case CURL_SSLVERSION_MAX_DEFAULT:
    break;

  default:
    if((data->set.ssl.primary.version_max >> 16) < sslver) {
      failf(data, "CURL_SSLVERSION_MAX incompatible with CURL_SSLVERSION");
      return FALSE;
    }
  }

  return TRUE;
}

static CURLcode
ssl_connect_init_proxy(struct connectdata *conn, int sockindex)
{
  DEBUGASSERT(conn->bits.proxy_ssl_connected[sockindex]);
  if(ssl_connection_complete == conn->ssl[sockindex].state &&
     !conn->proxy_ssl[sockindex].use) {
#if defined(HTTPS_PROXY_SUPPORT)
    conn->proxy_ssl[sockindex] = conn->ssl[sockindex];
    memset(&conn->ssl[sockindex], 0, sizeof(conn->ssl[sockindex]));
#else
    return CURLE_NOT_BUILT_IN;
#endif
  }
  return CURLE_OK;
}

CURLcode
Curl_ssl_connect(struct connectdata *conn, int sockindex)
{
  CURLcode result;

  if(conn->bits.proxy_ssl_connected[sockindex]) {
    result = ssl_connect_init_proxy(conn, sockindex);
    if(result)
      return result;
  }

  if(!ssl_prefs_check(conn->data))
    return CURLE_SSL_CONNECT_ERROR;

  /* mark this is being ssl-enabled from here on. */
  conn->ssl[sockindex].use = TRUE;
  conn->ssl[sockindex].state = ssl_connection_negotiating;

  result = curlssl_connect(conn, sockindex);

  if(!result)
    Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */

  return result;
}

CURLcode
Curl_ssl_connect_nonblocking(struct connectdata *conn, int sockindex,
                             bool *done)
{
  CURLcode result;
  if(conn->bits.proxy_ssl_connected[sockindex]) {
    result = ssl_connect_init_proxy(conn, sockindex);
    if(result)
      return result;
  }

  if(!ssl_prefs_check(conn->data))
    return CURLE_SSL_CONNECT_ERROR;

  /* mark this is being ssl requested from here on. */
  conn->ssl[sockindex].use = TRUE;
#ifdef curlssl_connect_nonblocking
  result = curlssl_connect_nonblocking(conn, sockindex, done);
#else
  *done = TRUE; /* fallback to BLOCKING */
  result = curlssl_connect(conn, sockindex);
#endif /* non-blocking connect support */
  if(!result && *done)
    Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */
  return result;
}

/*
 * Lock shared SSL session data
 */
void Curl_ssl_sessionid_lock(struct connectdata *conn)
{
  if(SSLSESSION_SHARED(conn->data))
    Curl_share_lock(conn->data,
                    CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE);
}

/*
 * Unlock shared SSL session data
 */
void Curl_ssl_sessionid_unlock(struct connectdata *conn)
{
  if(SSLSESSION_SHARED(conn->data))
    Curl_share_unlock(conn->data, CURL_LOCK_DATA_SSL_SESSION);
}

/*
 * Check if there's a session ID for the given connection in the cache, and if
 * there's one suitable, it is provided. Returns TRUE when no entry matched.
 */
bool Curl_ssl_getsessionid(struct connectdata *conn,
                           void **ssl_sessionid,
                           size_t *idsize, /* set 0 if unknown */
                           int sockindex)
{
  struct curl_ssl_session *check;
  struct Curl_easy *data = conn->data;
  size_t i;
  long *general_age;
  bool no_match = TRUE;

  const bool isProxy = CONNECT_PROXY_SSL();
  struct ssl_primary_config * const ssl_config = isProxy ?
    &conn->proxy_ssl_config :
    &conn->ssl_config;
  const char * const name = isProxy ? conn->http_proxy.host.name :
    conn->host.name;
  int port = isProxy ? (int)conn->port : conn->remote_port;
  *ssl_sessionid = NULL;

  DEBUGASSERT(SSL_SET_OPTION(primary.sessionid));

  if(!SSL_SET_OPTION(primary.sessionid))
    /* session ID re-use is disabled */
    return TRUE;

  /* Lock if shared */
  if(SSLSESSION_SHARED(data))
    general_age = &data->share->sessionage;
  else
    general_age = &data->state.sessionage;

  for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) {
    check = &data->state.session[i];
    if(!check->sessionid)
      /* not session ID means blank entry */
      continue;
    if(strcasecompare(name, check->name) &&
       ((!conn->bits.conn_to_host && !check->conn_to_host) ||
        (conn->bits.conn_to_host && check->conn_to_host &&
         strcasecompare(conn->conn_to_host.name, check->conn_to_host))) &&
       ((!conn->bits.conn_to_port && check->conn_to_port == -1) ||
        (conn->bits.conn_to_port && check->conn_to_port != -1 &&
         conn->conn_to_port == check->conn_to_port)) &&
       (port == check->remote_port) &&
       strcasecompare(conn->handler->scheme, check->scheme) &&
       Curl_ssl_config_matches(ssl_config, &check->ssl_config)) {
      /* yes, we have a session ID! */
      (*general_age)++;          /* increase general age */
      check->age = *general_age; /* set this as used in this age */
      *ssl_sessionid = check->sessionid;
      if(idsize)
        *idsize = check->idsize;
      no_match = FALSE;
      break;
    }
  }

  return no_match;
}

/*
 * Kill a single session ID entry in the cache.
 */
void Curl_ssl_kill_session(struct curl_ssl_session *session)
{
  if(session->sessionid) {
    /* defensive check */

    /* free the ID the SSL-layer specific way */
    curlssl_session_free(session->sessionid);

    session->sessionid = NULL;
    session->age = 0; /* fresh */

    Curl_free_primary_ssl_config(&session->ssl_config);

    Curl_safefree(session->name);
    Curl_safefree(session->conn_to_host);
  }
}

/*
 * Delete the given session ID from the cache.
 */
void Curl_ssl_delsessionid(struct connectdata *conn, void *ssl_sessionid)
{
  size_t i;
  struct Curl_easy *data=conn->data;

  for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) {
    struct curl_ssl_session *check = &data->state.session[i];

    if(check->sessionid == ssl_sessionid) {
      Curl_ssl_kill_session(check);
      break;
    }
  }
}

/*
 * Store session id in the session cache. The ID passed on to this function
 * must already have been extracted and allocated the proper way for the SSL
 * layer. Curl_XXXX_session_free() will be called to free/kill the session ID
 * later on.
 */
CURLcode Curl_ssl_addsessionid(struct connectdata *conn,
                               void *ssl_sessionid,
                               size_t idsize,
                               int sockindex)
{
  size_t i;
  struct Curl_easy *data=conn->data; /* the mother of all structs */
  struct curl_ssl_session *store = &data->state.session[0];
  long oldest_age=data->state.session[0].age; /* zero if unused */
  char *clone_host;
  char *clone_conn_to_host;
  int conn_to_port;
  long *general_age;
  const bool isProxy = CONNECT_PROXY_SSL();
  struct ssl_primary_config * const ssl_config = isProxy ?
    &conn->proxy_ssl_config :
    &conn->ssl_config;

  DEBUGASSERT(SSL_SET_OPTION(primary.sessionid));

  clone_host = strdup(isProxy ? conn->http_proxy.host.name : conn->host.name);
  if(!clone_host)
    return CURLE_OUT_OF_MEMORY; /* bail out */

  if(conn->bits.conn_to_host) {
    clone_conn_to_host = strdup(conn->conn_to_host.name);
    if(!clone_conn_to_host) {
      free(clone_host);
      return CURLE_OUT_OF_MEMORY; /* bail out */
    }
  }
  else
    clone_conn_to_host = NULL;

  if(conn->bits.conn_to_port)
    conn_to_port = conn->conn_to_port;
  else
    conn_to_port = -1;

  /* Now we should add the session ID and the host name to the cache, (remove
     the oldest if necessary) */

  /* If using shared SSL session, lock! */
  if(SSLSESSION_SHARED(data)) {
    general_age = &data->share->sessionage;
  }
  else {
    general_age = &data->state.sessionage;
  }

  /* find an empty slot for us, or find the oldest */
  for(i = 1; (i < data->set.general_ssl.max_ssl_sessions) &&
        data->state.session[i].sessionid; i++) {
    if(data->state.session[i].age < oldest_age) {
      oldest_age = data->state.session[i].age;
      store = &data->state.session[i];
    }
  }
  if(i == data->set.general_ssl.max_ssl_sessions)
    /* cache is full, we must "kill" the oldest entry! */
    Curl_ssl_kill_session(store);
  else
    store = &data->state.session[i]; /* use this slot */

  /* now init the session struct wisely */
  store->sessionid = ssl_sessionid;
  store->idsize = idsize;
  store->age = *general_age;    /* set current age */
  /* free it if there's one already present */
  free(store->name);
  free(store->conn_to_host);
  store->name = clone_host;               /* clone host name */
  store->conn_to_host = clone_conn_to_host; /* clone connect to host name */
  store->conn_to_port = conn_to_port; /* connect to port number */
  /* port number */
  store->remote_port = isProxy ? (int)conn->port : conn->remote_port;
  store->scheme = conn->handler->scheme;

  if(!Curl_clone_primary_ssl_config(ssl_config, &store->ssl_config)) {
    store->sessionid = NULL; /* let caller free sessionid */
    free(clone_host);
    free(clone_conn_to_host);
    return CURLE_OUT_OF_MEMORY;
  }

  return CURLE_OK;
}

void Curl_ssl_close_all(struct Curl_easy *data)
{
  size_t i;
  /* kill the session ID cache if not shared */
  if(data->state.session && !SSLSESSION_SHARED(data)) {
    for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++)
      /* the single-killer function handles empty table slots */
      Curl_ssl_kill_session(&data->state.session[i]);

    /* free the cache data */
    Curl_safefree(data->state.session);
  }

  curlssl_close_all(data);
}

#if defined(USE_OPENSSL) || defined(USE_GNUTLS) || defined(USE_SCHANNEL) || \
  defined(USE_DARWINSSL) || defined(USE_POLARSSL) || defined(USE_NSS) || \
  defined(USE_MBEDTLS)
int Curl_ssl_getsock(struct connectdata *conn, curl_socket_t *socks,
                     int numsocks)
{
  struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET];

  if(!numsocks)
    return GETSOCK_BLANK;

  if(connssl->connecting_state == ssl_connect_2_writing) {
    /* write mode */
    socks[0] = conn->sock[FIRSTSOCKET];
    return GETSOCK_WRITESOCK(0);
  }
  if(connssl->connecting_state == ssl_connect_2_reading) {
    /* read mode */
    socks[0] = conn->sock[FIRSTSOCKET];
    return GETSOCK_READSOCK(0);
  }

  return GETSOCK_BLANK;
}
#else
int Curl_ssl_getsock(struct connectdata *conn,
                     curl_socket_t *socks,
                     int numsocks)
{
  (void)conn;
  (void)socks;
  (void)numsocks;
  return GETSOCK_BLANK;
}
/* USE_OPENSSL || USE_GNUTLS || USE_SCHANNEL || USE_DARWINSSL || USE_NSS */
#endif

void Curl_ssl_close(struct connectdata *conn, int sockindex)
{
  DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
  curlssl_close(conn, sockindex);
}

CURLcode Curl_ssl_shutdown(struct connectdata *conn, int sockindex)
{
  if(curlssl_shutdown(conn, sockindex))
    return CURLE_SSL_SHUTDOWN_FAILED;

  conn->ssl[sockindex].use = FALSE; /* get back to ordinary socket usage */
  conn->ssl[sockindex].state = ssl_connection_none;

  conn->recv[sockindex] = Curl_recv_plain;
  conn->send[sockindex] = Curl_send_plain;

  return CURLE_OK;
}

/* Selects an SSL crypto engine
 */
CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine)
{
  return curlssl_set_engine(data, engine);
}

/* Selects the default SSL crypto engine
 */
CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data)
{
  return curlssl_set_engine_default(data);
}

/* Return list of OpenSSL crypto engine names. */
struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data)
{
  return curlssl_engines_list(data);
}

/*
 * This sets up a session ID cache to the specified size. Make sure this code
 * is agnostic to what underlying SSL technology we use.
 */
CURLcode Curl_ssl_initsessions(struct Curl_easy *data, size_t amount)
{
  struct curl_ssl_session *session;

  if(data->state.session)
    /* this is just a precaution to prevent multiple inits */
    return CURLE_OK;

  session = calloc(amount, sizeof(struct curl_ssl_session));
  if(!session)
    return CURLE_OUT_OF_MEMORY;

  /* store the info in the SSL section */
  data->set.general_ssl.max_ssl_sessions = amount;
  data->state.session = session;
  data->state.sessionage = 1; /* this is brand new */
  return CURLE_OK;
}

size_t Curl_ssl_version(char *buffer, size_t size)
{
  return curlssl_version(buffer, size);
}

/*
 * This function tries to determine connection status.
 *
 * Return codes:
 *     1 means the connection is still in place
 *     0 means the connection has been closed
 *    -1 means the connection status is unknown
 */
int Curl_ssl_check_cxn(struct connectdata *conn)
{
  return curlssl_check_cxn(conn);
}

bool Curl_ssl_data_pending(const struct connectdata *conn,
                           int connindex)
{
  return curlssl_data_pending(conn, connindex);
}

void Curl_ssl_free_certinfo(struct Curl_easy *data)
{
  int i;
  struct curl_certinfo *ci = &data->info.certs;

  if(ci->num_of_certs) {
    /* free all individual lists used */
    for(i=0; i<ci->num_of_certs; i++) {
      curl_slist_free_all(ci->certinfo[i]);
      ci->certinfo[i] = NULL;
    }

    free(ci->certinfo); /* free the actual array too */
    ci->certinfo = NULL;
    ci->num_of_certs = 0;
  }
}

CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num)
{
  struct curl_certinfo *ci = &data->info.certs;
  struct curl_slist **table;

  /* Free any previous certificate information structures */
  Curl_ssl_free_certinfo(data);

  /* Allocate the required certificate information structures */
  table = calloc((size_t) num, sizeof(struct curl_slist *));
  if(!table)
    return CURLE_OUT_OF_MEMORY;

  ci->num_of_certs = num;
  ci->certinfo = table;

  return CURLE_OK;
}

/*
 * 'value' is NOT a zero terminated string
 */
CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data,
                                    int certnum,
                                    const char *label,
                                    const char *value,
                                    size_t valuelen)
{
  struct curl_certinfo *ci = &data->info.certs;
  char *output;
  struct curl_slist *nl;
  CURLcode result = CURLE_OK;
  size_t labellen = strlen(label);
  size_t outlen = labellen + 1 + valuelen + 1; /* label:value\0 */

  output = malloc(outlen);
  if(!output)
    return CURLE_OUT_OF_MEMORY;

  /* sprintf the label and colon */
  snprintf(output, outlen, "%s:", label);

  /* memcpy the value (it might not be zero terminated) */
  memcpy(&output[labellen+1], value, valuelen);

  /* zero terminate the output */
  output[labellen + 1 + valuelen] = 0;

  nl = Curl_slist_append_nodup(ci->certinfo[certnum], output);
  if(!nl) {
    free(output);
    curl_slist_free_all(ci->certinfo[certnum]);
    result = CURLE_OUT_OF_MEMORY;
  }

  ci->certinfo[certnum] = nl;
  return result;
}

/*
 * This is a convenience function for push_certinfo_len that takes a zero
 * terminated value.
 */
CURLcode Curl_ssl_push_certinfo(struct Curl_easy *data,
                                int certnum,
                                const char *label,
                                const char *value)
{
  size_t valuelen = strlen(value);

  return Curl_ssl_push_certinfo_len(data, certnum, label, value, valuelen);
}

CURLcode Curl_ssl_random(struct Curl_easy *data,
                         unsigned char *entropy,
                         size_t length)
{
  return curlssl_random(data, entropy, length);
}

/*
 * Public key pem to der conversion
 */

static CURLcode pubkey_pem_to_der(const char *pem,
                                  unsigned char **der, size_t *der_len)
{
  char *stripped_pem, *begin_pos, *end_pos;
  size_t pem_count, stripped_pem_count = 0, pem_len;
  CURLcode result;

  /* if no pem, exit. */
  if(!pem)
    return CURLE_BAD_CONTENT_ENCODING;

  begin_pos = strstr(pem, "-----BEGIN PUBLIC KEY-----");
  if(!begin_pos)
    return CURLE_BAD_CONTENT_ENCODING;

  pem_count = begin_pos - pem;
  /* Invalid if not at beginning AND not directly following \n */
  if(0 != pem_count && '\n' != pem[pem_count - 1])
    return CURLE_BAD_CONTENT_ENCODING;

  /* 26 is length of "-----BEGIN PUBLIC KEY-----" */
  pem_count += 26;

  /* Invalid if not directly following \n */
  end_pos = strstr(pem + pem_count, "\n-----END PUBLIC KEY-----");
  if(!end_pos)
    return CURLE_BAD_CONTENT_ENCODING;

  pem_len = end_pos - pem;

  stripped_pem = malloc(pem_len - pem_count + 1);
  if(!stripped_pem)
    return CURLE_OUT_OF_MEMORY;

  /*
   * Here we loop through the pem array one character at a time between the
   * correct indices, and place each character that is not '\n' or '\r'
   * into the stripped_pem array, which should represent the raw base64 string
   */
  while(pem_count < pem_len) {
    if('\n' != pem[pem_count] && '\r' != pem[pem_count])
      stripped_pem[stripped_pem_count++] = pem[pem_count];
    ++pem_count;
  }
  /* Place the null terminator in the correct place */
  stripped_pem[stripped_pem_count] = '\0';

  result = Curl_base64_decode(stripped_pem, der, der_len);

  Curl_safefree(stripped_pem);

  return result;
}

/*
 * Generic pinned public key check.
 */

CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data,
                              const char *pinnedpubkey,
                              const unsigned char *pubkey, size_t pubkeylen)
{
  FILE *fp;
  unsigned char *buf = NULL, *pem_ptr = NULL;
  long filesize;
  size_t size, pem_len;
  CURLcode pem_read;
  CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
#ifdef curlssl_sha256sum
  CURLcode encode;
  size_t encodedlen, pinkeylen;
  char *encoded, *pinkeycopy, *begin_pos, *end_pos;
  unsigned char *sha256sumdigest = NULL;
#endif

  /* if a path wasn't specified, don't pin */
  if(!pinnedpubkey)
    return CURLE_OK;
  if(!pubkey || !pubkeylen)
    return result;

  /* only do this if pinnedpubkey starts with "sha256//", length 8 */
  if(strncmp(pinnedpubkey, "sha256//", 8) == 0) {
#ifdef curlssl_sha256sum
    /* compute sha256sum of public key */
    sha256sumdigest = malloc(SHA256_DIGEST_LENGTH);
    if(!sha256sumdigest)
      return CURLE_OUT_OF_MEMORY;
    curlssl_sha256sum(pubkey, pubkeylen,
                      sha256sumdigest, SHA256_DIGEST_LENGTH);
    encode = Curl_base64_encode(data, (char *)sha256sumdigest,
                                SHA256_DIGEST_LENGTH, &encoded, &encodedlen);
    Curl_safefree(sha256sumdigest);

    if(encode)
      return encode;

    infof(data, "\t public key hash: sha256//%s\n", encoded);

    /* it starts with sha256//, copy so we can modify it */
    pinkeylen = strlen(pinnedpubkey) + 1;
    pinkeycopy = malloc(pinkeylen);
    if(!pinkeycopy) {
      Curl_safefree(encoded);
      return CURLE_OUT_OF_MEMORY;
    }
    memcpy(pinkeycopy, pinnedpubkey, pinkeylen);
    /* point begin_pos to the copy, and start extracting keys */
    begin_pos = pinkeycopy;
    do {
      end_pos = strstr(begin_pos, ";sha256//");
      /*
       * if there is an end_pos, null terminate,
       * otherwise it'll go to the end of the original string
       */
      if(end_pos)
        end_pos[0] = '\0';

      /* compare base64 sha256 digests, 8 is the length of "sha256//" */
      if(encodedlen == strlen(begin_pos + 8) &&
         !memcmp(encoded, begin_pos + 8, encodedlen)) {
        result = CURLE_OK;
        break;
      }

      /*
       * change back the null-terminator we changed earlier,
       * and look for next begin
       */
      if(end_pos) {
        end_pos[0] = ';';
        begin_pos = strstr(end_pos, "sha256//");
      }
    } while(end_pos && begin_pos);
    Curl_safefree(encoded);
    Curl_safefree(pinkeycopy);
#else
    /* without sha256 support, this cannot match */
    (void)data;
#endif
    return result;
  }

  fp = fopen(pinnedpubkey, "rb");
  if(!fp)
    return result;

  do {
    /* Determine the file's size */
    if(fseek(fp, 0, SEEK_END))
      break;
    filesize = ftell(fp);
    if(fseek(fp, 0, SEEK_SET))
      break;
    if(filesize < 0 || filesize > MAX_PINNED_PUBKEY_SIZE)
      break;

    /*
     * if the size of our certificate is bigger than the file
     * size then it can't match
     */
    size = curlx_sotouz((curl_off_t) filesize);
    if(pubkeylen > size)
      break;

    /*
     * Allocate buffer for the pinned key
     * With 1 additional byte for null terminator in case of PEM key
     */
    buf = malloc(size + 1);
    if(!buf)
      break;

    /* Returns number of elements read, which should be 1 */
    if((int) fread(buf, size, 1, fp) != 1)
      break;

    /* If the sizes are the same, it can't be base64 encoded, must be der */
    if(pubkeylen == size) {
      if(!memcmp(pubkey, buf, pubkeylen))
        result = CURLE_OK;
      break;
    }

    /*
     * Otherwise we will assume it's PEM and try to decode it
     * after placing null terminator
     */
    buf[size] = '\0';
    pem_read = pubkey_pem_to_der((const char *)buf, &pem_ptr, &pem_len);
    /* if it wasn't read successfully, exit */
    if(pem_read)
      break;

    /*
     * if the size of our certificate doesn't match the size of
     * the decoded file, they can't be the same, otherwise compare
     */
    if(pubkeylen == pem_len && !memcmp(pubkey, pem_ptr, pubkeylen))
      result = CURLE_OK;
  } while(0);

  Curl_safefree(buf);
  Curl_safefree(pem_ptr);
  fclose(fp);

  return result;
}

#ifndef CURL_DISABLE_CRYPTO_AUTH
CURLcode Curl_ssl_md5sum(unsigned char *tmp, /* input */
                         size_t tmplen,
                         unsigned char *md5sum, /* output */
                         size_t md5len)
{
#ifdef curlssl_md5sum
  curlssl_md5sum(tmp, tmplen, md5sum, md5len);
#else
  MD5_context *MD5pw;

  (void) md5len;

  MD5pw = Curl_MD5_init(Curl_DIGEST_MD5);
  if(!MD5pw)
    return CURLE_OUT_OF_MEMORY;
  Curl_MD5_update(MD5pw, tmp, curlx_uztoui(tmplen));
  Curl_MD5_final(MD5pw, md5sum);
#endif
  return CURLE_OK;
}
#endif

/*
 * Check whether the SSL backend supports the status_request extension.
 */
bool Curl_ssl_cert_status_request(void)
{
#ifdef curlssl_cert_status_request
  return curlssl_cert_status_request();
#else
  return FALSE;
#endif
}

/*
 * Check whether the SSL backend supports false start.
 */
bool Curl_ssl_false_start(void)
{
#ifdef curlssl_false_start
  return curlssl_false_start();
#else
  return FALSE;
#endif
}

#endif /* USE_SSL */


text:
<?php

namespace Teknei\CtrlBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class SecurityController extends Controller
{
	/**
	 * @Route("/login")
	 */
	 public function loginAction()

    {
        return $this->render('TekneiCtrlBundle:Security:login.html.twig');
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "config.h"
#include "JSWebAssemblyCompileError.h"

#if ENABLE(WEBASSEMBLY)

#include "JSCInlines.h"

namespace JSC {

JSWebAssemblyCompileError* JSWebAssemblyCompileError::create(ExecState* exec, VM& vm, Structure* structure, const String& message)
{
    auto* instance = new (NotNull, allocateCell<JSWebAssemblyCompileError>(vm.heap)) JSWebAssemblyCompileError(vm, structure);
    instance->m_sourceAppender = defaultSourceAppender;
    bool useCurrentFrame = true;
    instance->finishCreation(exec, vm, message, useCurrentFrame);
    return instance;
}

JSWebAssemblyCompileError::JSWebAssemblyCompileError(VM& vm, Structure* structure)
    : Base(vm, structure)
{
}

const ClassInfo JSWebAssemblyCompileError::s_info = { "WebAssembly.CompileError", &Base::s_info, 0, CREATE_METHOD_TABLE(JSWebAssemblyCompileError) };

JSObject* createJSWebAssemblyCompileError(ExecState* exec, VM& vm, const String& message)
{
    ASSERT(!message.isEmpty());
    JSGlobalObject* globalObject = exec->lexicalGlobalObject();
    return JSWebAssemblyCompileError::create(exec, vm, globalObject->WebAssemblyCompileErrorStructure(), message);
}

} // namespace JSC

#endif // ENABLE(WEBASSEMBLY)


text:
/**
 * Board-offline.js
 *
 * @description :: TODO: You might write a short summary of how this model works and what it represents here.
 * @docs        :: http://sailsjs.org/documentation/concepts/models-and-orm/models
 */

var Q = require('q');
var json2csv = require('json2csv');

var util = require( 'util' ),
  actionUtil = require( '../blueprints/_util/actionUtil' );

module.exports = {

  attributes: {
  	number: 'string',
  	totalVotes: 'string',
  	blankVotes: 'string',
  	recurredVotes: 'string',
  	inpugnedVotes: 'string',
    nullVotes: 'string',
  	columnVotes: 'string',
    remitedVotes: 'string',
    electorVotes: 'string',
    packetUsed: 'string',

    isCertificate: 'boolean',
    isProvisorio: 'boolean',

  	town: {
  		model: 'town'
  	},

    instance: {
      model: 'instance'
    },

  	config: {
  		model: 'config'
  	},

  	votes: 'json'
  },

  afterCreate: function (args, next) {
    var self = this;
    Board.findOne({name: args.number, town: args.town}).populate('school').exec(function (err, board) {
        if (board === undefined) next();

        if (board) {
          var votes = JSON.parse(args.votes);

          if (!votes[0].candidateId) {
            votes = JSON.parse(votes);
          }

          var candivotes = [];

          _.each(votes, function (candidate) {
            var p = {
              school: board.school.id,
              borough: board.school.borough,
              candidate: candidate.candidateId,
              instance: args.instance,
              board: board.id,
              config: args.config
            };
            candivotes.push(p);
          });

          Candivote.findOrCreate(candivotes).exec(function (err, records) {

            _.each(records, function (candivote) {
              var index = _.findIndex(votes, { 'candidateId': candivote.candidate});
              //console.log(candivote, index);
              if (index >= 0) {
                candivote.votes = votes[index].votes;
                candivote.boardOffline = args.id,
                candivote.save();
              }
            });

            board.totalVotes = args.totalVotes;
            board.blankVotes = args.blankVotes;
            board.recurredVotes = args.recurredVotes;
            board.inpugnedVotes = args.inpugnedVotes;
            board.nullVotes = args.nullVotes;
            board.isCertificate = args.isCertificate;
            board.isProvisorio = args.isProvisorio;

            board.save();

            Config.publishUpdate(args.config, {id: args.config}, null, { previous: { } });

            next();
          });
        }
    });
  },
};


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.appnexus.opensdk.mediatedviews.SmartAdServer">

    <application>
        <uses-library android:name="org.apache.http.legacy" android:required="false"/>
    </application>
</manifest>


text:
convert player.xcf player.png
convert player.png -colorspace Gray enemy.png
convert enemy.png -fill "#920000" -opaque "#787878" enemy.png

# create intro png's

cp player.png ../game/scenes/intro/player.png
cp enemy.png ../game/scenes/intro/enemy.png
convert intro.xcf ../game/scenes/intro/intro.png

# create battleground
convert -layers flatten battleground.xcf ../game/scenes/battleground/battleground.png

# create hero and enemy animations for animationsprite
for f in animation/*
do
	convert $f ../game/scenes/hero/$(basename ${f%.xcf}).png
	convert $f -colorspace Gray ../game/scenes/enemy/$(basename ${f%.xcf}).png
	convert ../game/scenes/enemy/$(basename ${f%.xcf}).png -fill "#920000" -opaque "#787878" ../game/scenes/enemy/$(basename ${f%.xcf}).png
done

# create keyframes
for f in frames/*
do
	convert $f ../game/scenes/hero/$(basename ${f%.xcf}).png
	convert $f -colorspace Gray ../game/scenes/enemy/$(basename ${f%.xcf}).png
	convert ../game/scenes/enemy/$(basename ${f%.xcf}).png -fill "#920000" -opaque "#787878" ../game/scenes/enemy/$(basename ${f%.xcf}).png
done


text:
package com.sysdeo.eclipse.tomcat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import com.sysdeo.eclipse.tomcat.editors.ProjectListElement;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathAttribute;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.JavaRuntime;

/**
 * Start and stop Tomcat
 * Subclasses contains all information specific to a Tomcat Version
 */

public abstract class TomcatBootstrap {

	private static final String WEBAPP_CLASSPATH_FILENAME = ".#webclasspath";
	private static final int RUN = 1;
	private static final int LOG = 2;
	private static final int ADD_LAUNCH = 3;

	public abstract String[] getClasspath();
	public abstract String[] getVmArgs();
	public abstract String[] getPrgArgs(String command);
	public abstract String getStartCommand();
	public abstract String getStopCommand();
	public abstract String getMainClass();

	abstract public String getLabel();

	abstract public String getContextWorkDir(String workFolder);

	abstract public IPath getServletJarPath();
	abstract public IPath getJasperJarPath();
	abstract public IPath getJSPJarPath();

	public Collection getTomcatJars() {
		IPath tomcatHomePath = TomcatLauncherPlugin.getDefault().getTomcatIPath();
		ArrayList jars = new ArrayList();

		if(this.getServletJarPath() != null) {
			jars.add(JavaCore.newVariableEntry(tomcatHomePath.append(this.getServletJarPath()), null, null));
		}

		if(this.getJasperJarPath() != null)	{
			jars.add(JavaCore.newVariableEntry(tomcatHomePath.append(this.getJasperJarPath()), null, null));
		}

		if(this.getJSPJarPath() != null)	{
			jars.add(JavaCore.newVariableEntry(tomcatHomePath.append(this.getJSPJarPath()), null, null));
		}

		return jars;
	}

	/**
	 * Return the tag that will be used to find where context definition should be added in server.xml
	 */
	public abstract String getXMLTagAfterContextDefinition();

	/**
	 * See %TOMCAT_HOME%/bin/startup.bat
	 */
	public void start() throws CoreException {
		this.runTomcatBootsrap(getStartCommand(), true, RUN, false);
	}
	/**
	 * See %TOMCAT_HOME%/bin/shutdown.bat
	 */
	public void stop() throws CoreException {
		this.runTomcatBootsrap(getStopCommand(), false, RUN, false);
	}

	/**
	 * Simply stop and start
	 */
	public void restart() throws CoreException {
		this.stop();

		// Hack, need more testings
		try {
			Thread.sleep(5000);
		} catch (InterruptedException ex) {
		}

		this.start();
	}

	/**
	 * Write tomcat launch configuration to .metadata/.log
	 */
	public void logConfig() throws CoreException {
		this.runTomcatBootsrap(getStartCommand(), true, LOG, false);
	}

	/**
	 * Create an Eclipse launch configuration
	 */
	public void addLaunch() throws CoreException {
		this.runTomcatBootsrap(getStartCommand(), true, ADD_LAUNCH, true);
	}

	/**
	 * Launch a new JVM running Tomcat Main class
	 * Set classpath, bootclasspath and environment variable
	 */
	private void runTomcatBootsrap(String tomcatBootOption, boolean showInDebugger, int action, boolean saveConfig) throws CoreException {
		String[] prgArgs = this.getPrgArgs(tomcatBootOption);

		IProject[] projects = TomcatLauncherPlugin.getWorkspace().getRoot().getProjects();

		for (int i = 0; i < projects.length; i++) {
			if (!projects[i].isOpen())
				continue;
			TomcatProject tomcatProject = (TomcatProject) projects[i].getNature(TomcatLauncherPlugin.NATURE_ID);
			if (tomcatProject != null) {
				ArrayList al = new ArrayList();
				ArrayList visitedProjects = new ArrayList(); /*IMC*/
				IJavaProject javaProject = (IJavaProject) projects[i].getNature(JavaCore.NATURE_ID);
				WebClassPathEntries entries = tomcatProject.getWebClassPathEntries();
				if (entries != null) {
					getClassPathEntries(javaProject, al, false, entries.getList(), visitedProjects);

					IFile file = null;
				 	if(tomcatProject.getRootDirFolder() == null) {
				 		file = projects[i].getFile(new Path(WEBAPP_CLASSPATH_FILENAME));
				 	} else {
				 		file = tomcatProject.getRootDirFolder().getFile(new Path(WEBAPP_CLASSPATH_FILENAME));
				 	}

					File cpFile = file.getLocation().makeAbsolute().toFile();
					if (cpFile.exists()) {
						cpFile.delete();
					}
					try {
						if (cpFile.createNewFile()) {
							PrintWriter pw = new PrintWriter(new FileOutputStream(cpFile));

							for (int j = 0; j < al.size(); j++) {
								pw.println(al.get(j));
							}
							pw.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}

		String[] classpath = new String[0];
		classpath = addPreferenceJvmToClasspath(classpath);
		classpath = addPreferenceProjectListToClasspath(classpath);
		classpath = StringUtil.concatUniq(classpath, this.getClasspath());

		String[] vmArgs = this.getVmArgs();
		vmArgs = addPreferenceParameters(vmArgs);

		String[] bootClasspath = addPreferenceJvmToBootClasspath(new String[0]);

		StringBuffer programArguments = new StringBuffer();
		for (int i = 0; i < prgArgs.length; i++) {
			programArguments.append(" " + prgArgs[i]);
		}

		StringBuffer jvmArguments = new StringBuffer();
		for (int i = 0; i < vmArgs.length; i++) {
			jvmArguments.append(" " + vmArgs[i]);
		}

		if(action == RUN) {
			VMLauncherUtility.runVM(getLabel(), getMainClass(), classpath, bootClasspath, jvmArguments.toString(), programArguments.toString(), isDebugMode(), showInDebugger, saveConfig);
		}
		if(action == LOG) {
			VMLauncherUtility.log(getLabel(), getMainClass(), classpath, bootClasspath, jvmArguments.toString(), programArguments.toString(), isDebugMode(), showInDebugger);
		}
		if(action == ADD_LAUNCH) {
			VMLauncherUtility.createConfig(getLabel(), getMainClass(), classpath, bootClasspath, jvmArguments.toString(), programArguments.toString(), isDebugMode(), showInDebugger, true);
		}

	}

	private void add(ArrayList data, IPath entry) {
		if (entry.isAbsolute() == false)
			entry = entry.makeAbsolute();
		String tmp = entry.toFile().toString();
		if (!data.contains(tmp)) {
			data.add(tmp);
		}
	}

	private void add(ArrayList data, IResource con) {
		if (con == null)
			return;
		add(data, con.getLocation());
	}

	private void getClassPathEntries(IJavaProject prj, ArrayList data, boolean fromSelectedContainer, List selectedPaths, ArrayList visitedProjects) {
		IClasspathEntry[] entries = null;

		IPath outputPath = null;
		try {
			outputPath = prj.getOutputLocation();
			if (fromSelectedContainer || selectedPaths.contains(outputPath.toFile().toString().replace('\\', '/'))) {
				add(data, prj.getProject().getWorkspace().getRoot().findMember(outputPath));
			}
			entries = prj.getRawClasspath();
		} catch (JavaModelException e) {
			TomcatLauncherPlugin.log(e);
		}

		if (entries != null) {
			getClassPathEntries(entries, prj, data, selectedPaths, visitedProjects, outputPath);
		}
	}

	private void getClassPathEntries(IClasspathEntry[] entries, IJavaProject prj, ArrayList data, List selectedPaths, ArrayList visitedProjects, IPath outputPath) {
		for (int i = 0; i < entries.length; i++) {
			IClasspathEntry entry = entries[i];
			IPath path = entry.getPath();
			if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
				path = entry.getOutputLocation();
				if(path == null) continue;
			}
			if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
				String prjName = entry.getPath().lastSegment();
				if(!visitedProjects.contains(prjName)) {
					visitedProjects.add(prjName);
					getClassPathEntries(prj.getJavaModel().getJavaProject(prjName), data, false, selectedPaths, visitedProjects);
				}
				continue;
			} else if (!selectedPaths.contains(path.toFile().toString().replace('\\', '/'))) {
				if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER &&
					!entry.getPath().toString().contains("org.eclipse.jdt.launching.JRE_CONTAINER")) {

					// entires in container are only processed individually
					// if container itself is not selected

					IClasspathContainer container;
					try {
						container = JavaCore.getClasspathContainer(path, prj);
					} catch (JavaModelException e1) {
						TomcatLauncherPlugin.log(e1);
						container = null;
					}

					if (container != null) {
						getClassPathEntries(
							container.getClasspathEntries(),
							prj, data,
							selectedPaths, visitedProjects,
							outputPath);
					}
				}
				continue;
			}

			IClasspathEntry[] tmpEntry = null;
			if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
				try {
					tmpEntry = JavaCore.getClasspathContainer(path, prj).getClasspathEntries();
				} catch (JavaModelException e1) {
					TomcatLauncherPlugin.log(e1);
					continue;
				}
			} else {
				tmpEntry = new IClasspathEntry[1];
				tmpEntry[0] = JavaCore.getResolvedClasspathEntry(entry);
			}

			for (int j = 0; j < tmpEntry.length; j++) {
                // Check maven scope if defined
                boolean isRuntime = true;
                boolean isSnapshot = false;
                boolean isTestJar = false;
                for (IClasspathAttribute att : tmpEntry[j].getExtraAttributes()) {
                    if ("maven.scope".equals(att.getName())) {
                        isRuntime = "compile".equals(att.getValue()) || "runtime".equals(att.getValue());
                    }
                    else if ("maven.version".equals(att.getName())) {
                    	isSnapshot = att.getValue() != null && att.getValue().contains("SNAPSHOT");
                    }
                    else if ("maven.classifier".equals(att.getName())) {
                    	isTestJar = "tests".equals(att.getValue());
                    }
                }

                // If a project depends on both the jar/compile and test-jar/test dependency of the same eclipse project,
                // the maven container only contains the definition for the latter (ie: test dependency)
                // So we need to force the include of the project
                if( !isRuntime && isSnapshot && isTestJar && tmpEntry[j].getEntryKind() == IClasspathEntry.CPE_PROJECT ) {
                	isRuntime = true;;
                }

				if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
					IResource res = prj.getProject().getWorkspace().getRoot().findMember(tmpEntry[j].getPath());
					if (res != null)
						add(data, res);
					else
						add(data, tmpEntry[j].getPath());
				} else if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
					IPath srcPath = entry.getOutputLocation();
					if(srcPath != null && !srcPath.equals(outputPath))
					{
						add(data, prj.getProject().getWorkspace().getRoot().findMember(srcPath));
					}
				// Trying to fix code for m2eclipse container
                }
                else if (isRuntime && entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER
                        && tmpEntry[j].getEntryKind() == IClasspathEntry.CPE_PROJECT) {
					String prjName = tmpEntry[j].getPath().lastSegment();
                    visitedProjects.add(prjName);
                    getClassPathEntries(prj.getJavaModel().getJavaProject(prjName), data, true, selectedPaths, visitedProjects);
                }
                else if (isRuntime) {
					TomcatLauncherPlugin.log(">>> " + tmpEntry[j]);
					if(tmpEntry[j].getPath() != null)
						add(data, tmpEntry[j].getPath());
				}
			}
		}
	}
	private boolean isDebugMode() {
		return TomcatLauncherPlugin.getDefault().isDebugMode();
	}

	protected String getTomcatDir() {
		return TomcatLauncherPlugin.getDefault().getTomcatDir();
	}

	protected String getTomcatBase() {
		return TomcatLauncherPlugin.getDefault().getTomcatBase();
	}

	private String[] addPreferenceProjectListToClasspath(String[] previouscp) {
		List projectsList = TomcatLauncherPlugin.getDefault().getProjectsInCP();
		String[] result = previouscp;
		Iterator it = projectsList.iterator();
		while (it.hasNext()) {
			try {
				ProjectListElement ple = (ProjectListElement) it.next();
				IJavaProject jproject = JavaCore.create(ple.getProject());
				result = this.addProjectToClasspath(result, jproject);
			} catch (Exception e) {
				// nothing will be added to classpath
			}
		}

		return result;

	}

	private String[] addProjectToClasspath(String[] previouscp, IJavaProject project) throws CoreException {
		//		IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
		//		IJavaProject project = JavaCore.getJavaCore().create(root.getProject(projectName));
		if ((project != null) && (project.exists() && project.isOpen())) {
			String[] projectcp = JavaRuntime.computeDefaultRuntimeClassPath(project);
			return StringUtil.concatUniq(projectcp, previouscp);
		} else {
			return previouscp;
		}
	}

	private String[] addPreferenceParameters(String[] previous) {
		String[] prefParams = StringUtil.cutString(TomcatLauncherPlugin.getDefault().getJvmParamaters(), TomcatPluginResources.PREF_PAGE_LIST_SEPARATOR);
		return StringUtil.concat(previous, prefParams);
	}

	private String[] addPreferenceJvmToClasspath(String[] previous) {
		String[] prefClasspath = StringUtil.cutString(TomcatLauncherPlugin.getDefault().getJvmClasspath(), TomcatPluginResources.PREF_PAGE_LIST_SEPARATOR);
		return StringUtil.concatUniq(previous, prefClasspath);
	}

	private String[] addPreferenceJvmToBootClasspath(String[] previous) {
		String[] prefBootClasspath = StringUtil.cutString(TomcatLauncherPlugin.getDefault().getJvmBootClasspath(), TomcatPluginResources.PREF_PAGE_LIST_SEPARATOR);
		return StringUtil.concatUniq(previous, prefBootClasspath);
	}

}


text:
package net.sf.jabb.util.db.impl;

import java.io.IOException;
import java.sql.SQLException;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mchange.v2.c3p0.DataSources;
import com.mchange.v2.c3p0.PooledDataSource;

import net.sf.jabb.util.db.DataSourceProvider;
import net.sf.jabb.util.prop.PropertiesLoader;

/**
 *
 * @author Zhengmao HU (James)
 */
public class C3p0DataSourceProvider implements DataSourceProvider {
	private static final Log log = LogFactory.getLog(C3p0DataSourceProvider.class);
	protected static PropertiesLoader propLoader = new PropertiesLoader();

	@Override
	public DataSource createDataSource(String source, Properties configurationProperties, String config) {
		Properties props1 = configurationProperties;

		DataSource ds = null;
		try {
			DirectDataSourceConfiguration lowerConfig = new DirectDataSourceConfiguration(props1);
			Class.forName(lowerConfig.getDriverClassName());
			DataSource unpooled = DataSources.unpooledDataSource(lowerConfig.getUrl(),lowerConfig.getConnectionProperties());
			if (StringUtils.isNotBlank(config)){
				Properties props2 = propLoader.load(config);
				if (props2 == null){
					log.error("Cannot find configuration resource for '" + source + "' at location: " + config);
				}else{
					ds = DataSources.pooledDataSource(unpooled, props2);
				}
			}else{
				ds = unpooled;
			}
		} catch (ClassNotFoundException e) {
			log.error("Driver class not found for '" + source + "' with configuration: " + configurationProperties + ", " + config, e);
		} catch (SQLException e) {
			log.error("Error getting c3p0 data source for '" + source + "' with configuration: " + configurationProperties + ", " + config, e);
		} catch (Exception e) {
			log.error("Error creating data source for '" + source + "' with configuration: " + configurationProperties + ", " + config, e);
		}
		return ds;
	}

	@Override
	public DataSource createDataSource(String source, String config) {
		String[] cfgs = config.split(PropertiesLoader.DELIMITERS, 2);
		if (cfgs.length < 1 || cfgs.length > 2){
			log.error("Wrong configuration format for '" + source + "' : " + config);
			return null;
		}
		DataSource ds = null;
		try {
			Properties props1 = propLoader.load(cfgs[0]);
			if (props1 == null){
				log.error("Cannot find configuration resource for '" + source + "' at location: " + cfgs[0]);
			}else{
				ds = createDataSource(source, props1, cfgs.length == 2 ? cfgs[1] : null);
			}
		} catch (InvalidPropertiesFormatException e) {
			log.error("Wrong configuration properties file format for '" + source + "' with configuration: " + config, e);
		} catch (IOException e) {
			log.error("Error loading configuration file for '" + source + "' with configuration: " + config, e);
		} catch (Exception e) {
			log.error("Error creating data source for '" + source + "' with configuration: " + config, e);
		}
		return ds;
	}

	@Override
	public boolean destroyDataSource(DataSource dataSource) {
		if (dataSource instanceof PooledDataSource){
			try {
				DataSources.destroy(dataSource);
				return true;
			} catch (Exception e) {
				log.warn("Error destroying c3p0 data source: " + dataSource, e);
			}
		}
		return false;
	}

}


text:
extern struct process *g_switchingProcess;
extern struct thread  *g_switchingThread;

int init_switching();
int start_switching();

int switch_thread( struct thread * );

/// \todo these macros should be CAPITILIZED ...

#define current_process()	 g_switchingProcess
#define current_thread()	 g_switchingThread

#define current_pid()	(( g_switchingProcess == NULL ) ? -1 : g_switchingProcess->pid)
#define current_tid()	(( g_switchingThread == NULL ) ? -1 : g_switchingThread->tid)

int inside_scheduler();

#endif


text:
题目描述

Write a function to find the longest common prefix string amongst an array of strings.

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        if(strs.empty()) return "";

        for(int idx = 0; idx < strs[0].size(); idx++){
            for(int i = 1; i < strs.size(); i++){
                if(strs[i][idx] != strs[0][idx])
                    return strs[0].substr(0, idx);
            }
        }
        return strs[0];
    }
};


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

namespace LifxNet
{
	internal enum MessageType : ushort
	{
		//Device Messages
		DeviceGetService = 0x02,
		DeviceStateService = 0x03,
		DeviceGetTime = 0x04,
		DeviceSetTime = 0x05,
		DeviceStateTime = 0x06,
		DeviceGetHostInfo = 12,
		DeviceStateHostInfo = 13,
		DeviceGetHostFirmware = 14,
		DeviceStateHostFirmware = 15,
		DeviceGetWifiInfo = 16,
		DeviceStateWifiInfo = 17,
		DeviceGetWifiFirmware = 18,
		DeviceStateWifiFirmware = 19,
		DeviceGetPower = 20,
		DeviceSetPower = 21,
		DeviceStatePower = 22,
		DeviceGetLabel = 23,
		DeviceSetLabel = 24,
		DeviceStateLabel = 25,
		DeviceGetVersion = 32,
		DeviceStateVersion = 33,
		DeviceGetInfo = 34,
		DeviceStateInfo = 35,
		DeviceAcknowledgement = 45,
		DeviceGetLocation = 48,
		DeviceSetLocation = 49,
		DeviceStateLocation = 50,
		DeviceGetGroup = 51,
		DeviceSetGroup = 52,
		DeviceStateGroup = 53,
		DeviceEchoRequest = 58,
		DeviceEchoResponse = 59,
		//Light messages
		LightGet = 101,
		LightSetColor = 102,
		LightSetWaveform = 103,
		LightState = 107,
		LightGetPower = 116,
		LightSetPower = 117,
		LightStatePower = 118,
		LightSetWaveformOptional = 119,
		//Infrared
		InfraredGet = 120,
		InfraredState = 121,
		InfraredSet = 122,

		//Unofficial
		LightGetTemperature = 0x6E,
        //LightStateTemperature = 0x6f,
		SetLightBrightness = 0x68
	}
}


text:
fetch release history

### Synopsis

History prints historical revisions for a given release.

A default maximum of 256 revisions will be returned. Setting '--max'
configures the maximum length of the revision list returned.

The historical release set is printed as a formatted table, e.g:

    $ helm history angry-bird --max=4
    REVISION   UPDATED                      STATUS           CHART        DESCRIPTION
    1           Mon Oct 3 10:15:13 2016     SUPERSEDED      alpine-0.1.0  Initial install
    2           Mon Oct 3 10:15:13 2016     SUPERSEDED      alpine-0.1.0  Upgraded successfully
    3           Mon Oct 3 10:15:13 2016     SUPERSEDED      alpine-0.1.0  Rolled back to 2
    4           Mon Oct 3 10:15:13 2016     DEPLOYED        alpine-0.1.0  Upgraded successfully

```
helm history [flags] RELEASE_NAME
```

### Options

```
      --max int32   maximum number of revision to include in history (default 256)
```

### Options inherited from parent commands

```
      --debug                     enable verbose output
      --home string               location of your Helm config. Overrides $HELM_HOME (default "~/.helm")
      --host string               address of tiller. Overrides $HELM_HOST
      --kube-context string       name of the kubeconfig context to use
      --tiller-namespace string   namespace of tiller (default "kube-system")
```

### SEE ALSO
* [helm](helm.md)	 - The Helm package manager for Kubernetes.

###### Auto generated by spf13/cobra on 11-Mar-2017


text:
BIN=bin

all: smlnj

smlnj:
	mkdir -p bin
	sml build/go-nj.sml
	build/mkexec.sh `which sml` `pwd` jonprl

test:
	bin/jonprl example/choice.jonprl example/monoid.jonprl example/squash.jonprl example/unique.jonprl
	bin/jonprl example/image.jonprl
	bin/jonprl stdlib/*.jonprl
	bin/jonprl example/tautology.jonprl

clean:
	rm -f bin/.heapimg.*
	rm -f bin/jonprl
	rm -rf .cm

install:
	rm -f $(DESTDIR)/bin/jonprl.new
	cp bin/jonprl $(DESTDIR)/bin/jonprl.new
	mv $(DESTDIR)/bin/jonprl.new $(DESTDIR)/bin/jonprl


text:
using ClipboardExtensionApiTest = extensions::ExtensionApiTest;

#if BUILDFLAG(IS_CHROMEOS)
// Disable due to flaky, https://crbug.com/1206809
IN_PROC_BROWSER_TEST_F(ClipboardExtensionApiTest,
                       DISABLED_ClipboardDataChanged) {
  ExtensionTestMessageListener result_listener("success 2");
  ASSERT_TRUE(RunExtensionTest("clipboard/clipboard_data_changed",
                               {.launch_as_platform_app = true}))
      << message_;
  ASSERT_TRUE(result_listener.WaitUntilSatisfied());
}

IN_PROC_BROWSER_TEST_F(ClipboardExtensionApiTest, SetImageData) {
  ASSERT_TRUE(StartEmbeddedTestServer());
  ExtensionTestMessageListener clipboard_change_listener(
      "clipboard data changed 2");
  ASSERT_TRUE(RunExtensionTest("clipboard/set_image_data",
                               {.launch_as_platform_app = true}))
      << message_;
  ASSERT_TRUE(clipboard_change_listener.WaitUntilSatisfied());
}

#endif  // BUILDFLAG(IS_CHROMEOS)


text:
namespace Levolution.Reversi.Records
{
    /// <summary>
    /// Player disc color.
    /// </summary>
    public enum Player
    {
        /// <summary>
        /// Dark side player.
        /// </summary>
        Dark = CellState.Dark,

        /// <summary>
        /// Light side player.
        /// </summary>
        Light = CellState.Light
    }
}


text:
<?php

namespace Phlite\Logging\Handler;

use Phlite\Logging;

/**
 * A handler class which writes logging records, appropriately formatted,
 * to a stream. Note that this class does not close the stream, as
 * php://stdout or php://stderr may be used.
 */
class StreamHandler extends Logging\Handler {

    function __construct($stream=null) {
        parent::__construct();
        $this->stream = fopen($stream ?: 'php://stderr', 'w');
    }

    function flush() {
        fflush($this->stream);
    }

    /**
     * Emit a record.
     *
     * If a formatter is specified, it is used to format the record.
     * The record is then written to the stream with a trailing newline.  If
     * exception information is present, it is formatted using
     * traceback.print_exception and appended to the stream.  If the stream
     * has an 'encoding' attribute, it is used to determine how to do the
     * output to the stream.
     */
    function emit($record) {
        try {
            $msg = $this->format($record);
            $stream = $this->stream;
            $fs = "%s\n";
            fwrite($this->stream, sprintf($fs, $msg));
            $this->flush();
        }
        catch (Exception $ex) {
            $this->handleError($record, $ex);
        }
    }
}


text:
@interface ComicZineDoubleLabel ()
@property (strong, nonatomic) UILabel * foregroundLabel;
@property (strong, nonatomic) UILabel * backgroundLabel;
@end

@implementation ComicZineDoubleLabel

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}

- (id)init {
    self = [super init];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)initialize {
    self.backgroundLabel = [[UILabel alloc] initWithFrame:CGRectMake(-5.0, -2.35, self.frame.size.width, self.self.frame.size.height)];
    self.backgroundLabel.textAlignment = NSTextAlignmentCenter;
    self.backgroundLabel.textColor = [UIColor colorWithRed:0.9490 green:0.8353 blue:0.3098 alpha:1.0000];
    self.backgroundLabel.backgroundColor = [UIColor clearColor];
    self.backgroundLabel.font = [UIFont fontWithName:@"ComicZineSolid-Regular" size:(29.0)];
    self.backgroundLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self addSubview:self.backgroundLabel];

    self.foregroundLabel = [[UILabel alloc] initWithFrame:CGRectMake(-5.0, 1, self.frame.size.width, self.self.frame.size.height)];
    self.foregroundLabel.textAlignment = NSTextAlignmentCenter;
    self.foregroundLabel.textColor = [UIColor blackColor];
    self.foregroundLabel.backgroundColor = [UIColor clearColor];
    self.foregroundLabel.font = [UIFont fontWithName:@"ComicZineOT" size:(29.0)];
    self.foregroundLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
   [self addSubview:self.foregroundLabel];
}

- (void)setText:(NSString *)text {
    _text = text;
    self.backgroundLabel.text = text;
    self.foregroundLabel.text = text;
}

+(UIView*)titleView:(NSString*)title navigationBar:(UINavigationBar*)navigationBar {
    CGFloat height = navigationBar.frame.size.height;
    CGFloat width = navigationBar.frame.size.width;

    ComicZineDoubleLabel * label = [[ComicZineDoubleLabel alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    label.text = title;
    return label;
}

@end


text:
class BackupsController < ApplicationController
  def create
    service = Service.find(params[:service_id])
    service.backup
    redirect_back fallback_location: service
  end
end


text:
package shijimi.type;

import java.io.Serializable;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;

public class TypeAssignment {
    protected static TypeAssignment instance = new TypeAssignment();
    protected TypeParameterizedCast pCast = TypeParameterizedCast.v();

    public static TypeAssignment v() {
        return instance;
    }

    public boolean isAssignable(Type from, Type to) {
        if (to instanceof TypeVariable<?>) {
            return isAssignableToVar(from, (TypeVariable<?>) to);
        } else if (to instanceof WildcardType) {
            return isAssignableToWildcard(from, (WildcardType) to);
        } else {
            if (from instanceof Class<?>) {
                return isAssignableClass((Class<?>) from, to);
            } else if (from instanceof GenericArrayType) {
                return isAssignableGenericArrayType((GenericArrayType) from, to);
            } else if (from instanceof ParameterizedType) {
                return isAssignableParameterizedType((ParameterizedType) from, to);
            } else if (from instanceof TypeVariable<?>) {
                return isAssignableTypeVariable((TypeVariable<?>) from, to);
            } else if (from instanceof WildcardType) {
                return isAssignableWildcardType((WildcardType) from, to);
            } else {

            }
        }
        return false;
    }

    /**
     *

     * isAssignable(X extends U, X extends U)
     *  => true
     *
     * isAssignable(X extends U, Y extends V)
     *  => false
     *
     * isAssignable(? super L extends U, X extends V)
     *  => false
     *
     * isAssignable(T, X extends U)
     *  => isAssignable(T,U)
     *

     */
    public boolean isAssignableToVar(Type from, TypeVariable<?> to) {
        if (from.equals(to)) {
            return true;
        } else if (from instanceof TypeVariable<?>) {
            return false;
        } else if (from instanceof WildcardType) {
            return false;
        } else {
            for (Type upperBound : to.getBounds()) {
                if (!isAssignable(from, upperBound)) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     *

     * isAssignable(? super S extends E, ? super L extends U)
     *  if equals(? super S extends E, ? super L extends U)
     *  => true
     *
     * isAssignable(C, ? super L)
     *  => isAssignable(C, L)
     * isAssignable(T[P], ? super L)
     *  => isAssignable(T[P], L)
     * isAssignable(T[], ? super L)
     *  => isAssignable(T[], L)
     * isAssignable(? super S extends E, ? super L)
     *  => isAssignable(? super S extends E, L)
     * isAssignable(X extends V, ? super L)
     *  => isAssignable(X extends V, L)
     *
     * e.g.
     *  List[String] l1 = ...
     *  List[? super CharSequence] l2 = ...
     *  l2 = l1; //Error
     *  l2.add(l1.get(0)); //OK
     *
     *  List[CharSequence] l1 = ...
     *  List[? super String] l2 = ...
     *  l2 = l1; //OK
     *  l2.add(l1.get(0)); //Error
     *

     */
    public boolean isAssignableToWildcard(Type from, WildcardType to) {
        if (TypeEquals.v().equals(from, to)) {
            return true;
        }
        boolean result = false;
        for (Type lowerBound : to.getLowerBounds()) {
            if (!isAssignable(from, lowerBound)) {
                return false;
            } else {
                result = true;
            }
        }
        if (result) {
            for (Type upperBound : to.getUpperBounds()) {
                if (!isAssignable(from, upperBound)) {
                    return false;
                }
            }
        }
        return result;
    }

    /**
     *

     *  isAssignable(C,D)
     *   => D.isAssignableFrom(C)
     *
     *  isAssignable(C[],T[])
     *   => isAssignable(C, T)
     *
     *  isAssignable(C, T[P])
     *   => isAssignableClass(C,T) //raw type conversion
     *
     *  isAssignable(C, X extends U) //isAssignableToVar(C,X)
     *  isAssignable(C, ?) //isAssignableToWildcard(C,?)
     *
     *  e.g.
     *    isAssginable(String,Object) => true
     *    isAssignable(String[],Object[]) => true
     *    isAssignable(ArrayList,List<String>)
     *         => isAssignableClass(ArrayList,List) => true
     *
     *

     */
    public boolean isAssignableClass(Class<?> from, Type to) {
        if (to instanceof Class<?>) {
            return ((Class<?>) to).isAssignableFrom(from);
        } else if (to instanceof GenericArrayType) {
            return from.isArray() &&
            isAssignableClass(
                    from.getComponentType(),
                    ((GenericArrayType) to).getGenericComponentType());
        } else if (to instanceof ParameterizedType) {
            return isAssignableClass(from, ((ParameterizedType) to).getRawType());
        } else if (to instanceof TypeVariable<?>) {
            return isAssignableToVar(from, (TypeVariable<?>) to);
        } else if (to instanceof WildcardType) {
            return isAssignableToWildcard(from, (WildcardType) to);
        }
        return false;
    }

    /**
     *

     *  isAssignable(T[],Object)
     *  isAssignable(T[],Cloneable)
     *  isAssignable(T[],Serializable)
     *   => true
     *
     *  isAssignable(T[],C[])
     *   => isAssignable(T,C)
     *
     *  isAssignable(F[],T[])
     *   => isAssignable(F,T)
     *
     *  isAssignable(T[], C[][P])
     *   => isAssignable(T,C[P])
     *
     *  isAssignable(T[], C[P])
     *   => false
     *
     *  isAssignable(T[], X extends U) //isAssignableToVar(T[],X)
     *  isAssignable(T[], ?) //isAssignableToWildcard(T[],?)
     *

     */
    public boolean isAssignableGenericArrayType(GenericArrayType from, Type to) {
        if (to instanceof Class<?>) {
            Class<?> cls = (Class<?>) to;
            return cls.equals(Object.class) || cls.equals(Cloneable.class) || cls.equals(Serializable.class) ||
            (cls.isArray() &&
                    isAssignable(from.getGenericComponentType(), cls.getComponentType()));
        } else if (to instanceof GenericArrayType) {
            return isAssignable(from.getGenericComponentType(),
                    ((GenericArrayType) to).getGenericComponentType());
        } else if (to instanceof ParameterizedType) {
            ParameterizedType ptype = (ParameterizedType) to;
            Class<?> rawType = (Class<?>) ptype.getRawType();
            if (rawType.isArray()) {
                TypeFactory f = TypeFactory.v();
                return isAssignable(from.getGenericComponentType(),
                        f.make(rawType.getComponentType(), ptype.getActualTypeArguments()));
            } else {
                return false;
            }
        } else if (to instanceof TypeVariable<?>) {
            return isAssignableToVar(from, (TypeVariable<?>) to);
        } else if (to instanceof WildcardType) {
            return isAssignableToWildcard(from, (WildcardType) to);
        }
        return false;
    }

    /**
     *

     *  isAssignable(T[P],C)
     *   => isAssignable(T,C)
     *
     *  isAssignable(C[][P],T[])
     *   => isAssignable(C[P], T)
     *  isAssignable(C[P],T[])
     *   => false
     *
     *  isAssignable(F[P],T[V])
     *   => isAssignable(F,T) && isAssignableParameter(P,V)
     *
     *  e.g.
     *       isAssignable(ArrayList<String>, List)
     *       => isAssignable(ArrayList,List) => true
     *       isAssignable(ArrayList<String>, List[])
     *       => isAssignable(ArrayList,List[]) => false
     *       isAssignable(ArrayList[]<String>, List[])
     *       => isAssignable(ArrayList<String>, List) => true
     *
     *       isAssginable(ArrayList<String>,List<Object>)
     *       => isAssignable(ArrayList,List)
     *        && isAssignableParameter(String,Object) => true
     *
     *

     */
    public boolean isAssignableParameterizedType(ParameterizedType from, Type to) {
        if (to instanceof Class<?>) {
            return isAssignable(from.getRawType(), to);
        } else if (to instanceof GenericArrayType) {
            Class<?> rawType = (Class<?>) from.getRawType();
            if (rawType.isArray()) {
                return isAssignable(rawType.getComponentType(),
                        ((GenericArrayType) to).getGenericComponentType());
            } else {
                return false;
            }
        } else if (to instanceof ParameterizedType) {
            ParameterizedType pTo = (ParameterizedType) to;
            if (!isAssignable(from.getRawType(), pTo.getRawType())) {
                return false;
            }
            from = pCast.asParameterizedType(from, (Class<?>) pTo.getRawType());

            Type[] fs = from.getActualTypeArguments();
            Type[] ts = pTo.getActualTypeArguments();
            int flen = fs.length;
            int tlen = ts.length;
            if (flen != tlen) {
                return false;
            }
            for (int i = 0; i < flen; ++i) {
                if (!isAssignableParameter(fs[i], ts[i])) {
                    return false;
                }
            }
            return true;
        } else if (to instanceof TypeVariable<?>) {
            return isAssignableToVar(from, (TypeVariable<?>) to);
        } else if (to instanceof WildcardType) {
            return isAssignableToWildcard(from, (WildcardType) to);
        }
        return false;
    }

    /**
     *

     *  isAssignable(X extends U,C)
     *   => isAssignable(U,C)
     *  isAssignable(X extends U,T[])
     *   => isAssignable(U,T[])
     *  isAssignable(X extends U,T[P])
     *   => isAssignable(U,T[P])
     *
     *  e.g.
     *   class S {}
     *   class A extends S {}
     *   class X[T extends A] {
     *     T t = ...
     *     S s = t; //OK
     *
     *     T[] ts = ...
     *     S[] ss = ts; //OK
     *
     *     List[T] ts = ...
     *     List[S] ss = ts; //Error
     *
     *     List[?] ws = ts; //OK
     *   }
     *
     *   isAssignable(<V extends ArrayList>,List)
     *    => isAssigneble(ArrayList,List)
     *

     */
    public boolean isAssignableTypeVariable(TypeVariable<?> from, Type to) {
        if (to instanceof Class<?> ||
                to instanceof GenericArrayType ||
                to instanceof ParameterizedType) {
            boolean result = false;
            for (Type upperBound : from.getBounds()) {
                if (!isAssignable(upperBound, to)) {
                    return false;
                } else {
                    result = true;
                }
            }
            return result;
        } else if (to instanceof TypeVariable<?>) {
            return isAssignableToVar(from, (TypeVariable<?>) to);
        } else if (to instanceof WildcardType) {
            return isAssignableToWildcard(from, (WildcardType) to);
        }
        return false;
    }

    /**
     *

     *  isAssignable(? extends U,C)
     *   => isAssignable(U,C)
     *  isAssignable(? extends U,T[])
     *   => isAssignable(U,T[])
     *  isAssignable(? extends U,T[P])
     *   => isAssignable(U,T[P])
     *

     */
    public boolean isAssignableWildcardType(WildcardType from, Type to) {
        if (to instanceof Class<?> ||
                to instanceof GenericArrayType ||
                to instanceof ParameterizedType) {
            boolean result = false;
            for (Type upperBound : from.getUpperBounds()) {
                if (!isAssignable(upperBound, to)) {
                    return false;
                } else {
                    result = true;
                }
            }
            return result;
        } else if (to instanceof TypeVariable<?>) {
            return isAssignableToVar(from, (TypeVariable<?>) to);
        } else if (to instanceof WildcardType) {
            return isAssignableToWildcard(from, (WildcardType) to);
        }
        return false;
    }

    public boolean isAssignableParameter(Type from, Type to) {
        return TypeAssignmentParameter.v().isAssignable(from, to);
    }

}


text:
layout: post
title:  "Domorodá vesnice Nabusimake"
date:   2013-02-05 00:00:00
categories: cestování
---

{% include googlePhotosFotogallery.html galleryId='YZ1ZUfZR5QZ5dNJy6' %}


text:
"""
WTForms validator
-----------------

:copyright: 2017-02-16 by hbldh <henrik.blidh@swedwise.com>

"""

from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

import bankkonto

try:
    from wtforms.validators import ValidationError
except:  # noqa
    # Flask-WTF is not installed. To be able to use this properly
    # it needs to be, so we can safely use ValueError instead.
    ValidationError = ValueError

class BankkontoValidator(object):
    """
    Validates that input in this field is a valid Swedish bank account number.
    """
    field_flags = ('', )

    def __init__(self, *args, **kwargs):
        pass

    def __call__(self, form, field):
        cn, bn = bankkonto.clean_and_split(field.data)
        try:
            bankkonto.validate(cn, bn)
        except bankkonto.BankkontoValidationError as e:
            raise ValidationError(str(e))


text:
package org.springframework.cloud.netflix.hystrix;

import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.test.ClassPathExclusions;
import org.springframework.cloud.test.ModifiedClassPathRunner;
import org.springframework.context.ConfigurableApplicationContext;

import static org.assertj.core.api.Assertions.fail;

@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions({ "micrometer-core-*" })
public class HystrixAutoConfigurationTests {

	@Test
	@Ignore // TODO: why does this test fail in maven, but not in IDE?
	public void contextStarts() {
		try (ConfigurableApplicationContext context = new SpringApplicationBuilder()
				.web(WebApplicationType.NONE).sources(TestApp.class).run()) {
			try {
				context.getBean("hystrixMetricsBinder");
				fail("HystrixMetricsBinder class should not be found");
			}
			catch (NoSuchBeanDefinitionException e) {
				// this is the correct case
			}
		}
	}

	@EnableCircuitBreaker
	@SpringBootConfiguration
	@EnableAutoConfiguration
	protected static class TestApp {

	}

}


text:
package com.javarush.task.task17.task1706;

/*
Синхронизированный президент

И снова Singleton паттерн — синхронизация в статическом блоке
Внутри класса OurPresident в статическом блоке создайте синхронизированный блок.
Внутри синхронизированного блока инициализируйте president.
*/

public class Solution {
    public static void main(String[] args) {
        OurPresident expectedPresident = OurPresident.getOurPresident();
        OurPresident ourPresident = OurPresident.getOurPresident();
        System.out.println(expectedPresident == ourPresident );
    }
}


text:
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------

<#
.SYNOPSIS
Tests creating new resource group and a simple resource.
#>
function Test-CreatesNewSimpleResource
{
	# Setup
	$rgname = Get-ResourceGroupName
	$rname = Get-ResourceName
	$rglocation = Get-ProviderLocation ResourceManagement
	$location = Get-ProviderLocation "Microsoft.Sql/servers"
	$apiversion = "2014-04-01"
	$resourceType = "Microsoft.Sql/servers"

	# Test
	New-AzureRmResourceGroup -Name $rgname -Location $rglocation
    $actual = New-AzureRmResource -Name $rname -Location $location -Tags @{Name = "testtag"; Value = "testval"} -ResourceGroupName $rgname -ResourceType $resourceType -PropertyObject @{"administratorLogin" = "adminuser"; "administratorLoginPassword" = "P@ssword1"} -SkuObject @{ Name = "A0" } -ApiVersion $apiversion
	$expected = Get-AzureRmResource -Name $rname -ResourceGroupName $rgname -ResourceType $resourceType -ApiVersion $apiversion

	$list = Get-AzureRmResource -ResourceGroupName $rgname

	# Assert
	Assert-AreEqual $expected.Name $actual.Name
	Assert-AreEqual $expected.ResourceGroupName $actual.ResourceGroupName
	Assert-AreEqual $expected.ResourceType $actual.ResourceType
	Assert-AreEqual 1 @($list).Count
	Assert-AreEqual $expected.Name $list[0].Name
	Assert-AreEqual $expected.Sku $actual.Sku
}

<#
.SYNOPSIS
Tests creating new resource group and parent and child resources.
#>
function Test-CreatesNewComplexResource
{
	# Setup
	$rgname = Get-ResourceGroupName
	$rnameParent = Get-ResourceName
	$rnameChild = Get-ResourceName
	$resourceTypeParent = "Microsoft.Sql/servers"
	$resourceTypeChild = "Microsoft.Sql/servers/databases"
	$rglocation = Get-ProviderLocation ResourceManagement
	$location = Get-ProviderLocation $resourceTypeParent
	$apiversion = "2014-04-01"

	# Test
	New-AzureRmResourceGroup -Name $rgname -Location $rglocation
	$actualParent = New-AzureRmResource -Name $rnameParent -Location $location -ResourceGroupName $rgname -ResourceType $resourceTypeParent -PropertyObject @{"administratorLogin" = "adminuser"; "administratorLoginPassword" = "P@ssword1"} -ApiVersion $apiversion
	$expectedParent = Get-AzureRmResource -Name $rnameParent -ResourceGroupName $rgname -ResourceType $resourceTypeParent -ApiVersion $apiversion

	$actualChild = New-AzureRmResource -Name $rnameChild -Location $location -ResourceGroupName $rgname -ResourceType $resourceTypeChild -ParentResource servers/$rnameParent -PropertyObject @{"edition" = "Web"; "collation" = "SQL_Latin1_General_CP1_CI_AS"; "maxSizeBytes" = "1073741824"} -ApiVersion $apiversion
	$expectedChild = Get-AzureRmResource -Name $rnameChild -ResourceGroupName $rgname -ResourceType $resourceTypeChild -ParentResource servers/$rnameParent -ApiVersion $apiversion

	$list = Get-AzureRmResource -ResourceGroupName $rgname

	$parentFromList = $list | where {$_.ResourceType -eq $resourceTypeParent} | Select-Object -First 1
	$childFromList = $list | where {$_.ResourceType -eq $resourceTypeChild} | Select-Object -First 1

	$listOfServers = Get-AzureRmResource -ResourceType $resourceTypeParent -ResourceGroupName $rgname
	$listOfDatabases = Get-AzureRmResource -ResourceType $resourceTypeChild -ResourceGroupName $rgname

	# Assert
	Assert-AreEqual $expectedParent.Name $actualParent.Name
	Assert-AreEqual $expectedChild.Name $actualChild.Name
	Assert-AreEqual $expectedParent.ResourceType $actualParent.ResourceType
	Assert-AreEqual $expectedChild.ResourceType $actualChild.ResourceType

	Assert-AreEqual 2 @($list).Count
	Assert-AreEqual $expectedParent.Name $parentFromList.Name
	Assert-AreEqual $expectedChild.Name $childFromList.Name
	Assert-AreEqual $expectedParent.ResourceType $parentFromList.ResourceType
	Assert-AreEqual $expectedChild.ResourceType $childFromList.ResourceType

	Assert-AreEqual 1 @($listOfServers).Count
	Assert-AreEqual 1 @($listOfDatabases).Count
}

<#
.SYNOPSIS
Tests get resources via piping from resource group
#>
function Test-GetResourcesViaPiping
{
	# Setup
	$rgname = Get-ResourceGroupName
	$rnameParent = Get-ResourceName
	$rnameChild = Get-ResourceName
	$resourceTypeParent = "Microsoft.Sql/servers"
	$resourceTypeChild = "Microsoft.Sql/servers/databases"
	$rglocation = Get-ProviderLocation ResourceManagement
	$location = Get-ProviderLocation $resourceTypeParent
	$apiversion = "2014-04-01"

	# Test
	New-AzureRmResourceGroup -Name $rgname -Location $rglocation
	New-AzureRmResource -Name $rnameParent -Location $location -ResourceGroupName $rgname -ResourceType $resourceTypeParent -PropertyObject @{"administratorLogin" = "adminuser"; "administratorLoginPassword" = "P@ssword1"} -ApiVersion $apiversion
	New-AzureRmResource -Name $rnameChild -Location $location -ResourceGroupName $rgname -ResourceType $resourceTypeChild -ParentResource servers/$rnameParent -PropertyObject @{"edition" = "Web"; "collation" = "SQL_Latin1_General_CP1_CI_AS"; "maxSizeBytes" = "1073741824"} -ApiVersion $apiversion

	$list = Get-AzureRmResourceGroup -Name $rgname | Get-AzureRmResource
	$serverFromList = $list | where {$_.ResourceType -eq $resourceTypeParent} | Select-Object -First 1
	$databaseFromList = $list | where {$_.ResourceType -eq $resourceTypeChild} | Select-Object -First 1

	# Assert
	Assert-AreEqual 2 @($list).Count
	Assert-AreEqual $rnameParent $serverFromList.Name
	Assert-AreEqual $rnameChild $databaseFromList.Name
	Assert-AreEqual $resourceTypeParent $serverFromList.ResourceType
	Assert-AreEqual $resourceTypeChild $databaseFromList.ResourceType
}

<#
.SYNOPSIS
Nagative test. Get resources from an empty group.
#>
function Test-GetResourcesFromEmptyGroup
{
	# Setup
	$rgname = Get-ResourceGroupName
	$location = Get-ProviderLocation ResourceManagement

	# Test
	New-AzureRmResourceGroup -Name $rgname -Location $location
	$listViaPiping = Get-AzureRmResourceGroup -Name $rgname | Get-AzureRmResource
	$listViaDirect = Get-AzureRmResource -ResourceGroupName $rgname

	# Assert
	Assert-AreEqual 0 @($listViaPiping).Count
	Assert-AreEqual 0 @($listViaDirect).Count
}

<#
.SYNOPSIS
Nagative test. Get resources from an non-existing empty group.
#>
function Test-GetResourcesFromNonExisingGroup
{
	# Setup
	$rgname = Get-ResourceGroupName

	# Test
	Assert-Throws { Get-AzureRmResource -ResourceGroupName $rgname } "Provided resource group does not exist."
}

<#
.SYNOPSIS
Nagative test. Get resources from non-existing type.
#>
function Test-GetResourcesForNonExisingType
{
	# Test
	$list = Get-AzureRmResource -ResourceType 'Non-Existing'

	# Assert
	Assert-AreEqual 0 @($list).Count
}

<#
.SYNOPSIS
Nagative test. Get non-existing resource.
#>
function Test-GetResourceForNonExisingResource
{
	# Setup
	$rgname = Get-ResourceGroupName
	$rname = Get-ResourceGroupName
	$location = Get-ProviderLocation ResourceManagement
	$resourceTypeWeb = "Microsoft.Web/sites"
	$resourceTypeSql = "Microsoft.Sql/servers"
	$apiversion = "2014-04-01"

	# Test
	New-AzureRmResourceGroup -Name $rgname -Location $location
	Assert-Throws { Get-AzureRmResource -Name $rname -ResourceGroupName $rgname -ResourceType $resourceTypeWeb -ApiVersion $apiversion } "Provided resource does not exist."
	Assert-Throws { Get-AzureRmResource -Name $rname -ResourceGroupName $rgname -ResourceType $resourceTypeSql -ApiVersion $apiversion } "Provided resource does not exist."
	Assert-Throws { Get-AzureRmResource -Name $rname -ResourceGroupName $rgname -ResourceType 'Microsoft.Fake/nonexisting' -ApiVersion $apiversion } "Provided resource does not exist."
}

<#
.SYNOPSIS
Tests get resources via piping from resource group
#>
function Test-GetResourcesViaPipingFromAnotherResource
{
	# Setup
	$rgname = Get-ResourceGroupName
	$rnameParent = Get-ResourceName
	$rnameChild = Get-ResourceName
	$resourceTypeParent = "Microsoft.Sql/servers"
	$resourceTypeChild = "Microsoft.Sql/servers/databases"
	$rglocation = Get-ProviderLocation ResourceManagement
	$location = Get-ProviderLocation $resourceTypeParent
	$apiversion = "2014-04-01"

	# Test
	New-AzureRmResourceGroup -Name $rgname -Location $rglocation
	New-AzureRmResource -Name $rnameParent -Location $location -ResourceGroupName $rgname -ResourceType $resourceTypeParent -PropertyObject @{"administratorLogin" = "adminuser"; "administratorLoginPassword" = "P@ssword1"} -ApiVersion $apiversion
	New-AzureRmResource -Name $rnameChild -Location $location -ResourceGroupName $rgname -ResourceType $resourceTypeChild -ParentResource servers/$rnameParent -PropertyObject @{"edition" = "Web"; "collation" = "SQL_Latin1_General_CP1_CI_AS"; "maxSizeBytes" = "1073741824"} -ApiVersion $apiversion

	$list = Get-AzureRmResource -ResourceGroupName $rgname | Get-AzureRmResource -ApiVersion $apiversion

	# Assert
	Assert-AreEqual 2 @($list).Count
}

<#
.SYNOPSIS
Tests moving a resource.
#>
function Test-MoveAResource
{
	# Setup
	$rgname = Get-ResourceGroupName
	$rgname2 = Get-ResourceGroupName + "test3"
	$rname = Get-ResourceName
	$rglocation = Get-ProviderLocation ResourceManagement
	$apiversion = "2014-04-01"
	$resourceType = "Providers.Test/statefulResources"

	# Test
	New-AzureRmResourceGroup -Name $rgname -Location $rglocation
	New-AzureRmResourceGroup -Name $rgname2 -Location $rglocation
	$resource = New-AzureRmResource -Name $rname -Location $rglocation -Tags @{Name = "testtag"; Value = "testval"} -ResourceGroupName $rgname -ResourceType $resourceType -PropertyObject @{"key" = "value"} -ApiVersion $apiversion -Force
	Move-AzureRmResource -ResourceId $resource.ResourceId -DestinationResourceGroupName $rgname2 -Force

	$movedResource = Get-AzureRmResource -ResourceGroupName $rgname2 -ResourceName $rname -ResourceType $resourceType

	# Assert
	Assert-AreEqual $movedResource.Name $resource.Name
	Assert-AreEqual $movedResource.ResourceGroupName $rgname2
	Assert-AreEqual $movedResource.ResourceType $resource.ResourceType
}

<#
.SYNOPSIS
Tests setting a resource.
#>
function Test-SetAResource
{
	# Setup
	$rgname = Get-ResourceGroupName
	$rname = Get-ResourceName
	$rglocation = Get-ProviderLocation ResourceManagement
	$apiversion = "2014-04-01"
	$resourceType = "Providers.Test/statefulResources"

	# Test
	New-AzureRmResourceGroup -Name $rgname -Location $rglocation
	$resource = New-AzureRmResource -Name $rname -Location $rglocation -Tags @{Name = "testtag"; Value = "testval"} -ResourceGroupName $rgname -ResourceType $resourceType -PropertyObject @{"key" = "value"} -SkuObject @{ Name = "A0" } -ApiVersion $apiversion -Force
	Set-AzureRmResource -ResourceGroupName $rgname -ResourceName $rname -ResourceType $resourceType -Properties @{"key2" = "value2"} -Force
	Set-AzureRmResource -ResourceGroupName $rgname -ResourceName $rname -ResourceType $resourceType -SkuObject @{ Name = "A1" }  -Force

	$modifiedResource = Get-AzureRmResource -ResourceGroupName $rgname -ResourceName $rname -ResourceType $resourceType

	# Assert
	Assert-AreEqual $modifiedResource.Properties.key2 "value2"
	Assert-AreEqual $modifiedResource.Sku.Name "A1"
}

<#
.SYNOPSIS
Tests finding a resource.
#>
function Test-FindAResource
{
	# Setup
	$rgname = Get-ResourceGroupName
	$rname = "testname"
	$rname2 = "test2name"
	$rglocation = Get-ProviderLocation ResourceManagement
	$apiversion = "2014-04-01"
	$resourceType = "Providers.Test/statefulResources"

	# Test
	New-AzureRmResourceGroup -Name $rgname -Location $rglocation
	$actual = New-AzureRmResource -Name $rname -Location $rglocation -Tags @{Name = "testtag"; Value = "testval"} -ResourceGroupName $rgname -ResourceType $resourceType -PropertyObject @{"key" = "value"} -SkuObject @{ Name = "A0" } -ApiVersion $apiversion -Force
	$expected = Find-AzureRmResource -ResourceNameContains test -ResourceGroupNameContains $rgname
	Assert-NotNull $expected
	Assert-AreEqual $actual.ResourceId $expected[0].ResourceId

	$expected = Find-AzureRmResource -ResourceType $resourceType -ResourceGroupNameContains $rgName
	Assert-NotNull $expected
	Assert-AreEqual $actual.ResourceId $expected[0].ResourceId

	New-AzureRmResource -Name $rname2 -Location $rglocation -Tags @{Name = "testtag"; Value = "testval"} -ResourceGroupName $rgname -ResourceType $resourceType -PropertyObject @{"key" = "value"} -SkuObject @{ Name = "A0" } -ApiVersion $apiversion -Force
	$expected = Find-AzureRmResource -ResourceNameContains test -ResourceGroupNameContains $rgname
	Assert-AreEqual 2 @($expected).Count
}

<#
.SYNOPSIS
Tests getting a resource with properties expanded
#>
function Test-GetResourceExpandProperties
{
	# Setup
	$rgname = Get-ResourceGroupName
	$rname = Get-ResourceName
	$rglocation = Get-ProviderLocation ResourceManagement
	$apiversion = "2014-04-01"
	$resourceType = "Providers.Test/statefulResources"

	# Test
	New-AzureRmResourceGroup -Name $rgname -Location $rglocation
	$resource = New-AzureRmResource -Name $rname -Location $rglocation -Tags @{Name = "testtag"; Value = "testval"} -ResourceGroupName $rgname -ResourceType $resourceType -PropertyObject @{"key" = "value"} -SkuObject @{ Name = "A0" } -ApiVersion $apiversion -Force
	$resourceGet = Get-AzureRmResource -ResourceName $rname -ResourceGroupName $rgname -ExpandProperties

	# Assert
	Assert-AreEqual $resourceGet.Properties.key "value"
}


text:
package com.citrix.netscaler.nitro.resource.config.ssl;

import com.citrix.netscaler.nitro.resource.base.*;
import com.citrix.netscaler.nitro.service.nitro_service;
import com.citrix.netscaler.nitro.service.options;
import com.citrix.netscaler.nitro.util.*;
import com.citrix.netscaler.nitro.exception.nitro_exception;

class sslwrapkey_response extends base_response
{
	public sslwrapkey[] sslwrapkey;
}
/**
* Configuration for WRAP key resource.
*/

public class sslwrapkey extends base_resource
{
	private String wrapkeyname;
	private String password;
	private String salt;
	private Long __count;

	/**
	*

	* Name for the wrap key. Must begin with an ASCII alphanumeric or underscore (_) character, and must contain only ASCII alphanumeric, underscore, hash (#), period (.), space, colon (:), at (@), equals (=), and hyphen (-) characters. Cannot be changed after the wrap key is created.
The following requirement applies only to the NetScaler CLI:
If the name includes one or more spaces, enclose the name in double or single quotation marks (for example, "my key" or 'my key').
 Minimum length =  1
	*

	*/
	public void set_wrapkeyname(String wrapkeyname) throws Exception{
		this.wrapkeyname = wrapkeyname;
	}

	/**
	*

	* Name for the wrap key. Must begin with an ASCII alphanumeric or underscore (_) character, and must contain only ASCII alphanumeric, underscore, hash (#), period (.), space, colon (:), at (@), equals (=), and hyphen (-) characters. Cannot be changed after the wrap key is created.
The following requirement applies only to the NetScaler CLI:
If the name includes one or more spaces, enclose the name in double or single quotation marks (for example, "my key" or 'my key').
 Minimum length =  1
	*

	*/
	public String get_wrapkeyname() throws Exception {
		return this.wrapkeyname;
	}

	/**
	*

	* Password string for the wrap key.
 Minimum length =  1
	*

	*/
	public void set_password(String password) throws Exception{
		this.password = password;
	}

	/**
	*

	* Password string for the wrap key.
 Minimum length =  1
	*

	*/
	public String get_password() throws Exception {
		return this.password;
	}

	/**
	*

	* Salt string for the wrap key.
 Minimum length =  1
	*

	*/
	public void set_salt(String salt) throws Exception{
		this.salt = salt;
	}

	/**
	*

	* Salt string for the wrap key.
 Minimum length =  1
	*

	*/
	public String get_salt() throws Exception {
		return this.salt;
	}

	/**
	*

	* converts nitro response into object and returns the object array in case of get request.
	*

	*/
	protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception{
		sslwrapkey_response result = (sslwrapkey_response) service.get_payload_formatter().string_to_resource(sslwrapkey_response.class, response);
		if(result.errorcode != 0) {
			if (result.errorcode == 444) {
				service.clear_session();
			}
			if(result.severity != null)
			{
				if (result.severity.equals("ERROR"))
					throw new nitro_exception(result.message,result.errorcode);
			}
			else
			{
				throw new nitro_exception(result.message,result.errorcode);
			}
		}
		return result.sslwrapkey;
	}

	/**
	*

	* Returns the value of object identifier argument
	*

	*/

	protected String get_object_name() {
		return this.wrapkeyname;
	}

	/**
	* Use this API to create sslwrapkey.
	*/
	public static base_response create(nitro_service client, sslwrapkey resource) throws Exception {
		sslwrapkey createresource = new sslwrapkey();
		createresource.wrapkeyname = resource.wrapkeyname;
		createresource.password = resource.password;
		createresource.salt = resource.salt;
		return createresource.perform_operation(client,"create");
	}

	/**
	* Use this API to create sslwrapkey resources.
	*/
	public static base_responses create(nitro_service client, sslwrapkey resources[]) throws Exception {
		base_responses result = null;
		if (resources != null && resources.length > 0) {
			sslwrapkey createresources[] = new sslwrapkey[resources.length];
			for (int i=0;i<resources.length;i++){
				createresources[i] = new sslwrapkey();
				createresources[i].wrapkeyname = resources[i].wrapkeyname;
				createresources[i].password = resources[i].password;
				createresources[i].salt = resources[i].salt;
			}
			result = perform_operation_bulk_request(client, createresources,"create");
		}
		return result;
	}

	/**
	* Use this API to delete sslwrapkey of given name.
	*/
	public static base_response delete(nitro_service client, String wrapkeyname) throws Exception {
		sslwrapkey deleteresource = new sslwrapkey();
		deleteresource.wrapkeyname = wrapkeyname;
		return deleteresource.delete_resource(client);
	}

	/**
	* Use this API to delete sslwrapkey.
	*/
	public static base_response delete(nitro_service client, sslwrapkey resource) throws Exception {
		sslwrapkey deleteresource = new sslwrapkey();
		deleteresource.wrapkeyname = resource.wrapkeyname;
		return deleteresource.delete_resource(client);
	}

	/**
	* Use this API to delete sslwrapkey resources of given names.
	*/
	public static base_responses delete(nitro_service client, String wrapkeyname[]) throws Exception {
		base_responses result = null;
		if (wrapkeyname != null && wrapkeyname.length > 0) {
			sslwrapkey deleteresources[] = new sslwrapkey[wrapkeyname.length];
			for (int i=0;i<wrapkeyname.length;i++){
				deleteresources[i] = new sslwrapkey();
				deleteresources[i].wrapkeyname = wrapkeyname[i];
			}
			result = delete_bulk_request(client, deleteresources);
		}
		return result;
	}

	/**
	* Use this API to delete sslwrapkey resources.
	*/
	public static base_responses delete(nitro_service client, sslwrapkey resources[]) throws Exception {
		base_responses result = null;
		if (resources != null && resources.length > 0) {
			sslwrapkey deleteresources[] = new sslwrapkey[resources.length];
			for (int i=0;i<resources.length;i++){
				deleteresources[i] = new sslwrapkey();
				deleteresources[i].wrapkeyname = resources[i].wrapkeyname;
			}
			result = delete_bulk_request(client, deleteresources);
		}
		return result;
	}

	/**
	* Use this API to fetch all the sslwrapkey resources that are configured on netscaler.
	*/
	public static sslwrapkey[] get(nitro_service service) throws Exception{
		sslwrapkey obj = new sslwrapkey();
		sslwrapkey[] response = (sslwrapkey[])obj.get_resources(service);
		return response;
	}
	/**
	* Use this API to fetch all the sslwrapkey resources that are configured on netscaler.
	*/
	public static sslwrapkey[] get(nitro_service service, options option) throws Exception{
		sslwrapkey obj = new sslwrapkey();
		sslwrapkey[] response = (sslwrapkey[])obj.get_resources(service,option);
		return response;
	}
	/**
	* Use this API to fetch filtered set of sslwrapkey resources.
	* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
	*/
	public static sslwrapkey[] get_filtered(nitro_service service, String filter) throws Exception{
		sslwrapkey obj = new sslwrapkey();
		options option = new options();
		option.set_filter(filter);
		sslwrapkey[] response = (sslwrapkey[]) obj.getfiltered(service, option);
		return response;
	}

	/**
	* Use this API to fetch filtered set of sslwrapkey resources.
	* set the filter parameter values in filtervalue object.
	*/
	public static sslwrapkey[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{
		sslwrapkey obj = new sslwrapkey();
		options option = new options();
		option.set_filter(filter);
		sslwrapkey[] response = (sslwrapkey[]) obj.getfiltered(service, option);
		return response;
	}

	/**
	* Use this API to count the sslwrapkey resources configured on NetScaler.
	*/
	public static long count(nitro_service service) throws Exception{
		sslwrapkey obj = new sslwrapkey();
		options option = new options();
		option.set_count(true);
		sslwrapkey[] response = (sslwrapkey[])obj.get_resources(service, option);
		if (response != null) {
			return response[0].__count;
		}
		return 0;
	}

	/**
	* Use this API to count filtered the set of sslwrapkey resources.
	* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
	*/
	public static long count_filtered(nitro_service service, String filter) throws Exception{
		sslwrapkey obj = new sslwrapkey();
		options option = new options();
		option.set_count(true);
		option.set_filter(filter);
		sslwrapkey[] response = (sslwrapkey[]) obj.getfiltered(service, option);
		if (response != null) {
			return response[0].__count;
		}
		return 0;
	}

	/**
	* Use this API to count the filtered set of sslwrapkey resources.
	* set the filter parameter values in filtervalue object.
	*/
	public static long count_filtered(nitro_service service, filtervalue[] filter) throws Exception{
		sslwrapkey obj = new sslwrapkey();
		options option = new options();
		option.set_count(true);
		option.set_filter(filter);
		sslwrapkey[] response = (sslwrapkey[]) obj.getfiltered(service, option);
		if (response != null) {
			return response[0].__count;
		}
		return 0;
	}

}


text:
<?php

namespace Groups\CoreBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/groups');

       // $this->assertTrue($crawler->filter('html:contains("lk")')->count() > 0);

        $this->assertTrue($client->getResponse()->isSuccessful(), 'Nije uspesan url zahtev');

        $this->assertCount(2,$crawler->filter('h2'), 'Mora biti 3 naslova');
    }
}