text:
/*
 * Argon2 source code package
 *
 * Written by Daniel Dinu and Dmitry Khovratovich, 2015
 *
 * This work is licensed under a Creative Commons CC0 1.0 License/Waiver.
 *
 * You should have received a copy of the CC0 Public Domain Dedication along
 * with
 * this software. If not, see
 * <http://creativecommons.org/publicdomain/zero/1.0/>.
 */

#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#ifdef HAVE_SYS_MMAN_H
# include <sys/mman.h>
#endif

#include "crypto_generichash_blake2b.h"
#include "private/common.h"
#include "private/implementations.h"
#include "runtime.h"
#include "utils.h"

#include "argon2-core.h"
#include "blake2b-long.h"

#if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
# define MAP_ANON MAP_ANONYMOUS
#endif
#ifndef MAP_NOCORE
# define MAP_NOCORE 0
#endif
#ifndef MAP_POPULATE
# define MAP_POPULATE 0
#endif

static fill_segment_fn fill_segment = fill_segment_ref;

static void
load_block(block *dst, const void *input)
{
    unsigned i;
    for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) {
        dst->v[i] = LOAD64_LE((const uint8_t *) input + i * sizeof(dst->v[i]));
    }
}

static void
store_block(void *output, const block *src)
{
    unsigned i;
    for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) {
        STORE64_LE((uint8_t *) output + i * sizeof(src->v[i]), src->v[i]);
    }
}

/***************Memory allocators*****************/
/* Allocates memory to the given pointer
 * @param memory pointer to the pointer to the memory
 * @param m_cost number of blocks to allocate in the memory
 * @return ARGON2_OK if @memory is a valid pointer and memory is allocated
 */
static int allocate_memory(block_region **memory, uint32_t m_cost);

static int
allocate_memory(block_region **region, uint32_t m_cost)
{
    void * base;
    block *memory;
    size_t memory_size;

    if (region == NULL) {
        return ARGON2_MEMORY_ALLOCATION_ERROR; /* LCOV_EXCL_LINE */
    }
    memory_size = sizeof(block) * m_cost;
    if (m_cost == 0 ||
        memory_size / m_cost !=
            sizeof(block)) { /*1. Check for multiplication overflow*/
        return ARGON2_MEMORY_ALLOCATION_ERROR; /* LCOV_EXCL_LINE */
    }
    *region = (block_region *) malloc(
        sizeof(block_region)); /*2. Try to allocate region*/
    if (!*region) {
        return ARGON2_MEMORY_ALLOCATION_ERROR; /* LCOV_EXCL_LINE */
    }
    (*region)->base = (*region)->memory = NULL;

#if defined(MAP_ANON) && defined(HAVE_MMAP)
    if ((base = mmap(NULL, memory_size, PROT_READ | PROT_WRITE,
                     MAP_ANON | MAP_PRIVATE | MAP_NOCORE | MAP_POPULATE,
                     -1, 0)) == MAP_FAILED) {
        base = NULL; /* LCOV_EXCL_LINE */
    }                /* LCOV_EXCL_LINE */
    memcpy(&memory, &base, sizeof memory);
#elif defined(HAVE_POSIX_MEMALIGN)
    if ((errno = posix_memalign((void **) &base, 64, memory_size)) != 0) {
        base = NULL;
    }
    memcpy(&memory, &base, sizeof memory);
#else
    memory = NULL;
    if (memory_size + 63 < memory_size) {
        base  = NULL;
        errno = ENOMEM;
    } else if ((base = malloc(memory_size + 63)) != NULL) {
        uint8_t *aligned = ((uint8_t *) base) + 63;
        aligned -= (uintptr_t) aligned & 63;
        memcpy(&memory, &aligned, sizeof memory);
    }
#endif
    if (base == NULL) {
        return ARGON2_MEMORY_ALLOCATION_ERROR; /* LCOV_EXCL_LINE */
    }
    (*region)->base   = base;
    (*region)->memory = memory;
    (*region)->size   = memory_size;

    return ARGON2_OK;
}

/*********Memory functions*/

/* Clears memory
 * @param instance pointer to the current instance
 * @param clear_memory indicates if we clear the memory with zeros.
 */
static void clear_memory(argon2_instance_t *instance, int clear);

static void
clear_memory(argon2_instance_t *instance, int clear)
{
    /* LCOV_EXCL_START */
    if (clear) {
        if (instance->region != NULL) {
            sodium_memzero(instance->region->memory,
                           sizeof(block) * instance->memory_blocks);
        }
        if (instance->pseudo_rands != NULL) {
            sodium_memzero(instance->pseudo_rands,
                           sizeof(uint64_t) * instance->segment_length);
        }
    }
    /* LCOV_EXCL_STOP */
}

/* Deallocates memory
 * @param memory pointer to the blocks
 */
static void free_memory(block_region *memory);

static void
free_memory(block_region *region)
{
    if (region && region->base) {
#if defined(MAP_ANON) && defined(HAVE_MMAP)
        if (munmap(region->base, region->size)) {
            return; /* LCOV_EXCL_LINE */
        }
#else
        free(region->base);
#endif
    }
    free(region);
}

void
free_instance(argon2_instance_t *instance, int flags)
{
    /* Clear memory */
    clear_memory(instance, flags & ARGON2_FLAG_CLEAR_MEMORY);

    /* Deallocate the memory */
    free(instance->pseudo_rands);
    instance->pseudo_rands = NULL;
    free_memory(instance->region);
    instance->region = NULL;
}

void
finalize(const argon2_context *context, argon2_instance_t *instance)
{
    if (context != NULL && instance != NULL) {
        block    blockhash;
        uint32_t l;

        copy_block(&blockhash,
                   instance->region->memory + instance->lane_length - 1);

        /* XOR the last blocks */
        for (l = 1; l < instance->lanes; ++l) {
            uint32_t last_block_in_lane =
                l * instance->lane_length + (instance->lane_length - 1);
            xor_block(&blockhash,
                      instance->region->memory + last_block_in_lane);
        }

        /* Hash the result */
        {
            uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE];
            store_block(blockhash_bytes, &blockhash);
            blake2b_long(context->out, context->outlen, blockhash_bytes,
                         ARGON2_BLOCK_SIZE);
            sodium_memzero(blockhash.v,
                           ARGON2_BLOCK_SIZE); /* clear blockhash */
            sodium_memzero(blockhash_bytes,
                           ARGON2_BLOCK_SIZE); /* clear blockhash_bytes */
        }

        free_instance(instance, context->flags);
    }
}

void
fill_memory_blocks(argon2_instance_t *instance, uint32_t pass)
{
    argon2_position_t position;
    uint32_t l;
    uint32_t s;

    if (instance == NULL || instance->lanes == 0) {
        return; /* LCOV_EXCL_LINE */
    }

    position.pass = pass;
    for (s = 0; s < ARGON2_SYNC_POINTS; ++s) {
        position.slice = (uint8_t) s;
        for (l = 0; l < instance->lanes; ++l) {
            position.lane  = l;
            position.index = 0;
            fill_segment(instance, position);
        }
    }
}

int
validate_inputs(const argon2_context *context)
{
    /* LCOV_EXCL_START */
    if (NULL == context) {
        return ARGON2_INCORRECT_PARAMETER;
    }

    if (NULL == context->out) {
        return ARGON2_OUTPUT_PTR_NULL;
    }

    /* Validate output length */
    if (ARGON2_MIN_OUTLEN > context->outlen) {
        return ARGON2_OUTPUT_TOO_SHORT;
    }

    if (ARGON2_MAX_OUTLEN < context->outlen) {
        return ARGON2_OUTPUT_TOO_LONG;
    }

    /* Validate password (required param) */
    if (NULL == context->pwd) {
        if (0 != context->pwdlen) {
            return ARGON2_PWD_PTR_MISMATCH;
        }
    }

    if (ARGON2_MIN_PWD_LENGTH > context->pwdlen) {
        return ARGON2_PWD_TOO_SHORT;
    }

    if (ARGON2_MAX_PWD_LENGTH < context->pwdlen) {
        return ARGON2_PWD_TOO_LONG;
    }

    /* Validate salt (required param) */
    if (NULL == context->salt) {
        if (0 != context->saltlen) {
            return ARGON2_SALT_PTR_MISMATCH;
        }
    }

    if (ARGON2_MIN_SALT_LENGTH > context->saltlen) {
        return ARGON2_SALT_TOO_SHORT;
    }

    if (ARGON2_MAX_SALT_LENGTH < context->saltlen) {
        return ARGON2_SALT_TOO_LONG;
    }

    /* Validate secret (optional param) */
    if (NULL == context->secret) {
        if (0 != context->secretlen) {
            return ARGON2_SECRET_PTR_MISMATCH;
        }
    } else {
        if (ARGON2_MIN_SECRET > context->secretlen) {
            return ARGON2_SECRET_TOO_SHORT;
        }

        if (ARGON2_MAX_SECRET < context->secretlen) {
            return ARGON2_SECRET_TOO_LONG;
        }
    }

    /* Validate associated data (optional param) */
    if (NULL == context->ad) {
        if (0 != context->adlen) {
            return ARGON2_AD_PTR_MISMATCH;
        }
    } else {
        if (ARGON2_MIN_AD_LENGTH > context->adlen) {
            return ARGON2_AD_TOO_SHORT;
        }

        if (ARGON2_MAX_AD_LENGTH < context->adlen) {
            return ARGON2_AD_TOO_LONG;
        }
    }

    /* Validate memory cost */
    if (ARGON2_MIN_MEMORY > context->m_cost) {
        return ARGON2_MEMORY_TOO_LITTLE;
    }

    if (ARGON2_MAX_MEMORY < context->m_cost) {
        return ARGON2_MEMORY_TOO_MUCH;
    }

    if (context->m_cost < 8 * context->lanes) {
        return ARGON2_MEMORY_TOO_LITTLE;
    }

    /* Validate time cost */
    if (ARGON2_MIN_TIME > context->t_cost) {
        return ARGON2_TIME_TOO_SMALL;
    }

    if (ARGON2_MAX_TIME < context->t_cost) {
        return ARGON2_TIME_TOO_LARGE;
    }

    /* Validate lanes */
    if (ARGON2_MIN_LANES > context->lanes) {
        return ARGON2_LANES_TOO_FEW;
    }

    if (ARGON2_MAX_LANES < context->lanes) {
        return ARGON2_LANES_TOO_MANY;
    }

    /* Validate threads */
    if (ARGON2_MIN_THREADS > context->threads) {
        return ARGON2_THREADS_TOO_FEW;
    }

    if (ARGON2_MAX_THREADS < context->threads) {
        return ARGON2_THREADS_TOO_MANY;
    }
    /* LCOV_EXCL_STOP */

    return ARGON2_OK;
}

void
fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance)
{
    uint32_t l;
    /* Make the first and second block in each lane as G(H0||i||0) or
       G(H0||i||1) */
    uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE];
    for (l = 0; l < instance->lanes; ++l) {
        STORE32_LE(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 0);
        STORE32_LE(blockhash + ARGON2_PREHASH_DIGEST_LENGTH + 4, l);
        blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash,
                     ARGON2_PREHASH_SEED_LENGTH);
        load_block(&instance->region->memory[l * instance->lane_length + 0],
                   blockhash_bytes);

        STORE32_LE(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 1);
        blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash,
                     ARGON2_PREHASH_SEED_LENGTH);
        load_block(&instance->region->memory[l * instance->lane_length + 1],
                   blockhash_bytes);
    }
    sodium_memzero(blockhash_bytes, ARGON2_BLOCK_SIZE);
}

void
initial_hash(uint8_t *blockhash, argon2_context *context, argon2_type type)
{
    crypto_generichash_blake2b_state BlakeHash;
    uint8_t                          value[4U /* sizeof(uint32_t) */];

    if (NULL == context || NULL == blockhash) {
        return; /* LCOV_EXCL_LINE */
    }

    crypto_generichash_blake2b_init(&BlakeHash, NULL, 0U,
                                    ARGON2_PREHASH_DIGEST_LENGTH);

    STORE32_LE(value, context->lanes);
    crypto_generichash_blake2b_update(&BlakeHash, value, sizeof(value));

    STORE32_LE(value, context->outlen);
    crypto_generichash_blake2b_update(&BlakeHash, value, sizeof(value));

    STORE32_LE(value, context->m_cost);
    crypto_generichash_blake2b_update(&BlakeHash, value, sizeof(value));

    STORE32_LE(value, context->t_cost);
    crypto_generichash_blake2b_update(&BlakeHash, value, sizeof(value));

    STORE32_LE(value, ARGON2_VERSION_NUMBER);
    crypto_generichash_blake2b_update(&BlakeHash, value, sizeof(value));

    STORE32_LE(value, (uint32_t) type);
    crypto_generichash_blake2b_update(&BlakeHash, value, sizeof(value));

    STORE32_LE(value, context->pwdlen);
    crypto_generichash_blake2b_update(&BlakeHash, value, sizeof(value));

    if (context->pwd != NULL) {
        crypto_generichash_blake2b_update(
            &BlakeHash, (const uint8_t *) context->pwd, context->pwdlen);

        /* LCOV_EXCL_START */
        if (context->flags & ARGON2_FLAG_CLEAR_PASSWORD) {
            sodium_memzero(context->pwd, context->pwdlen);
            context->pwdlen = 0;
        }
        /* LCOV_EXCL_STOP */
    }

    STORE32_LE(value, context->saltlen);
    crypto_generichash_blake2b_update(&BlakeHash, value, sizeof(value));

    if (context->salt != NULL) {
        crypto_generichash_blake2b_update(
            &BlakeHash, (const uint8_t *) context->salt, context->saltlen);
    }

    STORE32_LE(value, context->secretlen);
    crypto_generichash_blake2b_update(&BlakeHash, value, sizeof(value));

    /* LCOV_EXCL_START */
    if (context->secret != NULL) {
        crypto_generichash_blake2b_update(
            &BlakeHash, (const uint8_t *) context->secret, context->secretlen);

        if (context->flags & ARGON2_FLAG_CLEAR_SECRET) {
            sodium_memzero(context->secret, context->secretlen);
            context->secretlen = 0;
        }
    }
    /* LCOV_EXCL_STOP */

    STORE32_LE(value, context->adlen);
    crypto_generichash_blake2b_update(&BlakeHash, value, sizeof(value));

    /* LCOV_EXCL_START */
    if (context->ad != NULL) {
        crypto_generichash_blake2b_update(
            &BlakeHash, (const uint8_t *) context->ad, context->adlen);
    }
    /* LCOV_EXCL_STOP */

    crypto_generichash_blake2b_final(&BlakeHash, blockhash,
                                     ARGON2_PREHASH_DIGEST_LENGTH);
}

int
initialize(argon2_instance_t *instance, argon2_context *context)
{
    uint8_t blockhash[ARGON2_PREHASH_SEED_LENGTH];
    int     result = ARGON2_OK;

    if (instance == NULL || context == NULL) {
        return ARGON2_INCORRECT_PARAMETER;
    }

    /* 1. Memory allocation */

    if ((instance->pseudo_rands = (uint64_t *)
         malloc(sizeof(uint64_t) * instance->segment_length)) == NULL) {
        return ARGON2_MEMORY_ALLOCATION_ERROR;
    }

    result = allocate_memory(&(instance->region), instance->memory_blocks);
    if (ARGON2_OK != result) {
        free_instance(instance, context->flags);
        return result;
    }

    /* 2. Initial hashing */
    /* H_0 + 8 extra bytes to produce the first blocks */
    /* uint8_t blockhash[ARGON2_PREHASH_SEED_LENGTH]; */
    /* Hashing all inputs */
    initial_hash(blockhash, context, instance->type);
    /* Zeroing 8 extra bytes */
    sodium_memzero(blockhash + ARGON2_PREHASH_DIGEST_LENGTH,
                   ARGON2_PREHASH_SEED_LENGTH - ARGON2_PREHASH_DIGEST_LENGTH);

    /* 3. Creating first blocks, we always have at least two blocks in a slice
     */
    fill_first_blocks(blockhash, instance);
    /* Clearing the hash */
    sodium_memzero(blockhash, ARGON2_PREHASH_SEED_LENGTH);

    return ARGON2_OK;
}

int
argon2_pick_best_implementation(void)
{
/* LCOV_EXCL_START */
#if defined(HAVE_AVX512FINTRIN_H) && defined(HAVE_AVX2INTRIN_H) && \
    defined(HAVE_TMMINTRIN_H) && defined(HAVE_SMMINTRIN_H)
    if (sodium_runtime_has_avx512f()) {
        fill_segment = fill_segment_avx512f;
        return 0;
    }
#endif
#if defined(HAVE_AVX2INTRIN_H) && defined(HAVE_TMMINTRIN_H) && \
    defined(HAVE_SMMINTRIN_H)
    if (sodium_runtime_has_avx2()) {
        fill_segment = fill_segment_avx2;
        return 0;
    }
#endif
#if defined(HAVE_EMMINTRIN_H) && defined(HAVE_TMMINTRIN_H)
    if (sodium_runtime_has_ssse3()) {
        fill_segment = fill_segment_ssse3;
        return 0;
    }
#endif
    fill_segment = fill_segment_ref;

    return 0;
    /* LCOV_EXCL_STOP */
}

int
_crypto_pwhash_argon2_pick_best_implementation(void)
{
    return argon2_pick_best_implementation();
}


text:
package org.pentaho.di.core.plugins;

import java.net.URL;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.builder.CompareToBuilder;
import org.pentaho.di.core.Const;

/**
 * This describes the plugin itself, the IDs it listens too, what libraries (jar files) it uses, the names, the i18n
 * details, etc.
 *
 * @author matt
 *
 */
public class Plugin implements PluginInterface, Comparable<Plugin> {

  public static Comparator<PluginInterface> nullStringComparator =
    ( p1, p2 ) -> new CompareToBuilder()
      .append( p1.getName(), p2.getName(), Comparator.nullsLast( String::compareToIgnoreCase ) )
      .append( p1.getIds(), p2.getIds() )
      .toComparison();

  private String category;
  private String name;
  private String description;
  private String[] ids;
  private Class<? extends PluginTypeInterface> pluginType;
  private String imageFile;
  private boolean separateClassLoaderNeeded;
  private String classLoaderGroup;
  private boolean nativePlugin;
  private Map<Class<?>, String> classMap;
  private List<String> libraries;
  private String errorHelpFile;
  private Class<?> mainType;
  private URL pluginFolder;
  private String documentationUrl;
  private String casesUrl;
  private String forumUrl;
  private String suggestion;

  /**
   * @param ids
   * @param pluginType
   * @param category
   * @param name
   * @param description
   * @param imageFile
   * @param separateClassLoaderNeeded
   * @param nativePlugin
   * @param classMap
   * @param libraries
   */
  public Plugin( String[] ids, Class<? extends PluginTypeInterface> pluginType, Class<?> mainType,
                 String category, String name, String description, String imageFile, boolean separateClassLoaderNeeded,
                 boolean nativePlugin, Map<Class<?>, String> classMap, List<String> libraries, String errorHelpFile,
                 URL pluginFolder ) {
    this( ids, pluginType, mainType, category, name, description, imageFile, separateClassLoaderNeeded,
      nativePlugin, classMap, libraries, errorHelpFile, pluginFolder, null, null, null );
  }

  /**
   * @param ids
   * @param pluginType
   * @param category
   * @param name
   * @param description
   * @param imageFile
   * @param separateClassLoaderNeeded
   * @param nativePlugin
   * @param classMap
   * @param libraries
   */
  public Plugin( String[] ids, Class<? extends PluginTypeInterface> pluginType, Class<?> mainType,
                 String category, String name, String description, String imageFile, boolean separateClassLoaderNeeded,
                 boolean nativePlugin, Map<Class<?>, String> classMap, List<String> libraries, String errorHelpFile,
                 URL pluginFolder, String documentationUrl, String casesUrl, String forumUrl ) {
    this( ids, pluginType, mainType, category, name, description, imageFile, separateClassLoaderNeeded, null,
      nativePlugin, classMap, libraries, errorHelpFile, pluginFolder, documentationUrl, casesUrl, forumUrl );
  }

  /**
   * @param ids
   * @param pluginType
   * @param mainType
   * @param category
   * @param name
   * @param description
   * @param imageFile
   * @param separateClassLoaderNeeded
   * @param classLoaderGroup
   * @param nativePlugin
   * @param classMap
   * @param libraries
   * @param errorHelpFile
   * @param pluginFolder
   * @param documentationUrl
   * @param casesUrl
   * @param forumUrl
   */
  public Plugin( String[] ids, Class<? extends PluginTypeInterface> pluginType, Class<?> mainType,
                 String category, String name, String description, String imageFile, boolean separateClassLoaderNeeded,
                 String classLoaderGroup, boolean nativePlugin, Map<Class<?>, String> classMap, List<String> libraries,
                 String errorHelpFile, URL pluginFolder, String documentationUrl, String casesUrl, String forumUrl ) {
    this.ids = ids;
    this.pluginType = pluginType;
    this.mainType = mainType;
    this.category = category;
    this.name = name;
    this.description = description;
    this.imageFile = imageFile;
    this.separateClassLoaderNeeded = separateClassLoaderNeeded;
    this.classLoaderGroup = classLoaderGroup;
    this.nativePlugin = nativePlugin;
    this.classMap = classMap;
    this.libraries = libraries;
    this.errorHelpFile = errorHelpFile;
    this.pluginFolder = pluginFolder;
    this.documentationUrl = Const.getDocUrl( documentationUrl );
    this.casesUrl = casesUrl;
    this.forumUrl = forumUrl;
  }

  /**
   *
   * @param ids
   * @param pluginType
   * @param mainType
   * @param category
   * @param name
   * @param description
   * @param imageFile
   * @param separateClassLoaderNeeded
   * @param classLoaderGroup
   * @param nativePlugin
   * @param classMap
   * @param libraries
   * @param errorHelpFile
   * @param pluginFolder
   * @param documentationUrl
   * @param casesUrl
   * @param forumUrl
   * @param suggestion
   */
  public Plugin( String[] ids, Class<? extends PluginTypeInterface> pluginType, Class<?> mainType,
                 String category, String name, String description, String imageFile, boolean separateClassLoaderNeeded,
                 String classLoaderGroup, boolean nativePlugin, Map<Class<?>, String> classMap, List<String> libraries,
                 String errorHelpFile, URL pluginFolder, String documentationUrl, String casesUrl, String forumUrl,
                 String suggestion ) {
    this( ids, pluginType, mainType, category, name, description, imageFile, separateClassLoaderNeeded,
      classLoaderGroup, nativePlugin, classMap, libraries, errorHelpFile, pluginFolder, documentationUrl, casesUrl,
      forumUrl );
    this.suggestion = suggestion;
  }

  /**
   *
   * @param ids
   * @param pluginType
   * @param mainType
   * @param category
   * @param name
   * @param description
   * @param imageFile
   * @param separateClassLoaderNeeded
   * @param nativePlugin
   * @param classMap
   * @param libraries
   * @param errorHelpFile
   * @param pluginFolder
   * @param documentationUrl
   * @param casesUrl
   * @param forumUrl
   * @param suggestion
   */
  public Plugin( String[] ids, Class<? extends PluginTypeInterface> pluginType, Class<?> mainType,
                 String category, String name, String description, String imageFile, boolean separateClassLoaderNeeded,
                 boolean nativePlugin, Map<Class<?>, String> classMap, List<String> libraries, String errorHelpFile,
                 URL pluginFolder, String documentationUrl, String casesUrl, String forumUrl, String suggestion ) {
    this( ids, pluginType, mainType, category, name, description, imageFile, separateClassLoaderNeeded, null,
      nativePlugin, classMap, libraries, errorHelpFile, pluginFolder, documentationUrl, casesUrl, forumUrl );
    this.suggestion = suggestion;
  }

  @Override
  public String toString() {
    return ids[0] + "/" + name + "{" + pluginType + "}";
  }

  @Override
  public boolean equals( Object obj ) {
    return ( obj != null ) && ( obj instanceof Plugin ) && compareTo( (Plugin) obj ) == 0;
  }

  @Override
  public int hashCode() {
    return ids[0].hashCode();
  }

  @Override
  public int compareTo( Plugin o ) {
    // All the IDs have to be the same to match, otherwise it's a different plugin
    // This might be a bit over the top, usually we only have a single ID
    //

    return nullStringComparator.compare( this, o );
  }

  @Override
  public boolean matches( String id ) {
    return Const.indexOfString( id, ids ) >= 0;
  }

  /**
   * @return the category
   */
  @Override
  public String getCategory() {
    return category;
  }

  /**
   * @param category
   *          the category to set
   */
  public void setCategory( String category ) {
    this.category = category;
  }

  /**
   * @return the name
   */
  @Override
  public String getName() {
    return name;
  }

  /**
   * @param name
   *          the name to set
   */
  public void setName( String name ) {
    this.name = name;
  }

  /**
   * @return the description
   */
  @Override
  public String getDescription() {
    return description;
  }

  /**
   * @param description
   *          the description to set
   */
  public void setDescription( String description ) {
    this.description = description;
  }

  /**
   * @return the ids
   */
  @Override
  public String[] getIds() {
    return ids;
  }

  /**
   * @param ids
   *          the ids to set
   */
  public void setIds( String[] ids ) {
    this.ids = ids;
  }

  /**
   * @return the pluginType
   */
  @Override
  public Class<? extends PluginTypeInterface> getPluginType() {
    return pluginType;
  }

  /**
   * @param pluginType
   *          the pluginType to set
   */
  public void setPluginType( Class<? extends PluginTypeInterface> pluginType ) {
    this.pluginType = pluginType;
  }

  /**
   * @return the imageFile
   */
  @Override
  public String getImageFile() {
    return imageFile;
  }

  /**
   * @param imageFile
   *          the imageFile to set
   */
  @Override
  public void setImageFile( String imageFile ) {
    this.imageFile = imageFile;
  }

  /**
   * @return the separateClassLoaderNeeded
   */
  @Override
  public boolean isSeparateClassLoaderNeeded() {
    return separateClassLoaderNeeded;
  }

  /**
   * @param separateClassLoaderNeeded
   *          the separateClassLoaderNeeded to set
   */
  public void setSaperateClassLoaderNeeded( boolean separateClassLoaderNeeded ) {
    this.separateClassLoaderNeeded = separateClassLoaderNeeded;
  }

  /**
   * @return the nativePlugin
   */
  @Override
  public boolean isNativePlugin() {
    return nativePlugin;
  }

  /**
   * @param nativePlugin
   *          the nativePlugin to set
   */
  public void setNativePlugin( boolean nativePlugin ) {
    this.nativePlugin = nativePlugin;
  }

  /**
   * @return the classMap
   */
  @Override
  public Map<Class<?>, String> getClassMap() {
    return classMap;
  }

  /**
   * @param classMap
   *          the classMap to set
   */
  public void setClassMap( Map<Class<?>, String> classMap ) {
    this.classMap = classMap;
  }

  /**
   * @return the libraries
   */
  @Override
  public List<String> getLibraries() {
    return libraries;
  }

  /**
   * @param libraries
   *          the libraries to set
   */
  public void setLibraries( List<String> libraries ) {
    this.libraries = libraries;
  }

  /**
   * @return the errorHelpFile
   */
  @Override
  public String getErrorHelpFile() {
    return errorHelpFile;
  }

  /**
   * @param errorHelpFile
   *          the errorHelpFile to set
   */
  @Override
  public void setErrorHelpFile( String errorHelpFile ) {
    this.errorHelpFile = errorHelpFile;
  }

  @Override
  public Class<?> getMainType() {
    return mainType;
  }

  @Override
  public URL getPluginDirectory() {
    return this.pluginFolder;
  }

  /**
   * @return the documentationUrl
   */
  @Override
  public String getDocumentationUrl() {
    return documentationUrl;
  }

  /**
   * @param documentationUrl
   *          the documentationUrl to set
   */
  @Override
  public void setDocumentationUrl( String documentationUrl ) {
    this.documentationUrl = documentationUrl;
  }

  /**
   * @return the casesUrl
   */
  @Override
  public String getCasesUrl() {
    return casesUrl;
  }

  /**
   * @param casesUrl
   *          the casesUrl to set
   */
  @Override
  public void setCasesUrl( String casesUrl ) {
    this.casesUrl = casesUrl;
  }

  /**
   * @return the forum URL
   */
  @Override
  public String getForumUrl() {
    return forumUrl;
  }

  /**
   * @param forumUrl
   *          the forum URL to set
   */
  @Override
  public void setForumUrl( String forumUrl ) {
    this.forumUrl = forumUrl;
  }

  @Override
  public String getClassLoaderGroup() {
    return classLoaderGroup;
  }

  @Override
  public void setSuggestion( String suggestion ) {
    this.suggestion = suggestion;
  }

  @Override
  public String getSuggestion() {
    return suggestion;
  }

  @Override
  public void setClassLoaderGroup( String classLoaderGroup ) {
    this.classLoaderGroup = classLoaderGroup;
  }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<config
    linePaint.strokeWidth="1dp"
    linePaint.color="#0000FF"
    fillPaint.color="#00000000" />


text:
"""\
QR Code and Micro QR Code implementation.

"QR Code" and "Micro QR Code" are registered trademarks of DENSO WAVE INCORPORATED.
"""
from __future__ import absolute_import, unicode_literals
import sys
import io
from . import encoder
from .encoder import DataOverflowError
from . import writers, utils
try:  # pragma: no cover
    str_type = basestring  # noqa: F821
except NameError:  # pragma: no cover
    str_type = str

__version__ = '1.5.3.dev'

__all__ = ('make', 'make_qr', 'make_micro', 'make_sequence', 'QRCode',
           'QRCodeSequence', 'DataOverflowError')

# <https://wiki.python.org/moin/PortingToPy3k/BilingualQuickRef#New_Style_Classes>
__metaclass__ = type

def make(content, error=None, version=None, mode=None, mask=None, encoding=None,
         eci=False, micro=None, boost_error=True):
    """\
    Creates a (Micro) QR Code.

    This is main entry point to create QR Codes and Micro QR Codes.

    Aside from `content`, all parameters are optional and an optimal (minimal)
    (Micro) QR code with a maximal error correction level is generated.

    :param content: The data to encode. Either a Unicode string, an integer or
            bytes. If bytes are provided, the `encoding` parameter should be
            used to specify the used encoding.
    :type content: str, int, bytes
    :param error: Error correction level. If ``None`` (default), error
            correction level ``L`` is used (note: Micro QR Code version M1 does
            not support any error correction. If an explicit error correction
            level is used, a M1 QR code won't be generated).
            Valid values: ``None`` (allowing generation of M1 codes or use error
            correction level "L" or better see :paramref:`boost_error <segno.make.boost_error>`),
            "L", "M", "Q", "H" (error correction level "H" isn't available for
            Micro QR Codes).

            =====================================   ===========================
            Error correction level                  Error correction capability
            =====================================   ===========================
            L (Segno's default unless version M1)   recovers  7% of data
            M                                       recovers 15% of data
            Q                                       recovers 25% of data
            H (not available for Micro QR Codes)    recovers 30% of data
            =====================================   ===========================

            Higher error levels may require larger QR codes (see also
            :paramref:`version <segno.make.version>` parameter).

            The `error` parameter is case insensitive.

            See also the :paramref:`boost_error <segno.make.boost_error>` parameter.
    :type error: str or None
    :param version: QR Code version. If the value is ``None`` (default), the
            minimal version which fits for the input data will be used.
            Valid values: "M1", "M2", "M3", "M4" (for Micro QR codes) or an
            integer between 1 and 40 (for QR codes).
            The `version` parameter is case insensitive.
    :type version: int, str or None
    :param mode: "numeric", "alphanumeric", "byte", "kanji" or "hanzi".
            If the value is ``None`` (default) the appropriate mode will
            automatically be determined.
            If `version` refers to a Micro QR code, this function may raise a
            :py:exc:`ValueError` if the provided `mode` is not supported.

            The `mode` parameter is case insensitive.

            ============    =======================
            Mode            (Micro) QR Code Version
            ============    =======================
            numeric         1 - 40, M1, M2, M3, M4
            alphanumeric    1 - 40,     M2, M3, M4
            byte            1 - 40,         M3, M4
            kanji           1 - 40,         M3, M4
            hanzi           1 - 40
            ============    =======================

            .. note::
                The Hanzi mode may not be supported by all QR code readers since
                it is not part of ISO/IEC 18004:2015(E).
                For this reason, this mode must be specified explicitly by the
                user::

                    import segno
                    qrcode = segno.make('书读百遍其义自现', mode='hanzi')

    :type mode: str or None
    :param mask: Data mask. If the value is ``None`` (default), the
            appropriate data mask is chosen automatically. If the `mask`
            parameter is provided, this function may raise a :py:exc:`ValueError`
            if the mask is invalid.
    :type mask: int or None
    :param encoding: Indicates the encoding in mode "byte". By default
            (`encoding` is ``None``) the implementation tries to use the
            standard conform ISO/IEC 8859-1 encoding and if it does not fit, it
            will use UTF-8. Note that no ECI mode indicator is inserted by
            default (see :paramref:`eci <segno.make.eci>`).
            The `encoding` parameter is case insensitive.
    :type encoding: str or None
    :param bool eci: Indicates if binary data which does not use the default
            encoding (ISO/IEC 8859-1) should enforce the ECI mode. Since a lot
            of QR code readers do not support the ECI mode, this feature is
            disabled by default and the data is encoded in the provided
            `encoding` using the usual "byte" mode. Set `eci` to ``True`` if
            an ECI header should be inserted into the QR Code. Note that
            the implementation may not know the ECI designator for the provided
            `encoding` and may raise an exception if the ECI designator cannot
            be found.
            The ECI mode is not supported by Micro QR Codes.
    :param micro: If :paramref:`version <segno.make.version>` is ``None`` (default)
            this parameter can be used to allow the creation of a Micro QR code.
            If set to ``False``, a QR code is generated. If set to
            ``None`` (default) a Micro QR code may be generated if applicable.
            If set to ``True`` the algorithm generates a Micro QR Code or
            raises an exception if the `mode` is not compatible or the `content`
            is too large for Micro QR codes.
    :type micro: bool or None
    :param bool boost_error: Indicates if the error correction level may be
            increased if it does not affect the version (default: ``True``).
            If set to ``True``, the :paramref:`error <segno.make.error>`
            parameter is interpreted as minimum error level. If set to ``False``,
            the resulting (Micro) QR code uses the provided `error` level
            (or the default error correction level, if error is ``None``)
    :raises: :py:exc:`ValueError` or :py:exc:`DataOverflowError`: In case the
             data does not fit into a (Micro) QR Code or it does not fit into
             the provided :paramref:`version`.
    :rtype: QRCode
    """
    return QRCode(encoder.encode(content, error, version, mode, mask, encoding,
                                 eci, micro, boost_error=boost_error))

def make_qr(content, error=None, version=None, mode=None, mask=None,
            encoding=None, eci=False, boost_error=True):
    """\
    Creates a QR code (never a Micro QR code).

    See :py:func:`make` for a description of the parameters.

    :rtype: QRCode
    """
    return make(content, error=error, version=version, mode=mode, mask=mask,
                encoding=encoding, eci=eci, micro=False, boost_error=boost_error)

def make_micro(content, error=None, version=None, mode=None, mask=None,
               encoding=None, boost_error=True):
    """\
    Creates a Micro QR code.

    See :py:func:`make` for a description of the parameters.

    Note: Error correction level "H" isn't available for Micro QR codes. If
    used, this function raises a :py:class:`segno.ErrorLevelError`.

    :rtype: QRCode
    """
    return make(content, error=error, version=version, mode=mode, mask=mask,
                encoding=encoding, micro=True, boost_error=boost_error)

def make_sequence(content, error=None, version=None, mode=None, mask=None,
                  encoding=None, boost_error=True, symbol_count=None):
    """\
    Creates a sequence of QR codes using the Structured Append mode.

    If the content fits into one QR code and neither ``version`` nor
    ``symbol_count`` is provided, this function may return a sequence with
    one QR Code which does not use the Structured Append mode. Otherwise a
    sequence of 2 .. n  (max. n = 16) QR codes is returned which use the
    Structured Append mode.

    The Structured Append mode allows to split the content over a number
    (max. 16) QR Codes.

    The Structured Append mode isn't available for Micro QR Codes, therefor
    the returned sequence contains QR codes, only.

    Since this function returns an iterable object, it may be used as follows:

    .. code-block:: python

        for i, qrcode in enumerate(segno.make_sequence(data, symbol_count=2)):
             qrcode.save('seq-%d.svg' % i, scale=10, color='darkblue')

    The number of QR codes is determined by the `version` or `symbol_count`
    parameter.

    See :py:func:`make` for a description of the other parameters.

    :param int symbol_count: Number of symbols.
    :rtype: QRCodeSequence
    """
    return QRCodeSequence(map(QRCode,
                              encoder.encode_sequence(content, error=error,
                                                      version=version,
                                                      mode=mode, mask=mask,
                                                      encoding=encoding,
                                                      boost_error=boost_error,
                                                      symbol_count=symbol_count)))

class QRCode:
    """\
    Represents a (Micro) QR Code.
    """
    __slots__ = ('matrix', 'mask', '_version', '_error', '_mode', '_matrix_size')

    def __init__(self, code):
        """\
        Initializes the QR Code object.

        :param code: An object with a ``matrix``, ``version``, ``error``,
            ``mask`` and ``segments`` attribute.
        """
        matrix = code.matrix
        self.matrix = matrix
        """Returns the matrix.

        :rtype: tuple of :py:class:`bytearray` instances.
        """
        self.mask = code.mask
        """Returns the data mask pattern reference

        :rtype: int
        """
        self._matrix_size = len(matrix[0]), len(matrix)
        self._version = code.version
        self._error = code.error
        self._mode = code.segments[0].mode if len(code.segments) == 1 else None

    @property
    def version(self):
        """\
        (Micro) QR Code version. Either a string ("M1", "M2", "M3", "M4") or
        an integer in the range of 1 .. 40.

        :rtype: str or int
        """
        return encoder.get_version_name(self._version)

    @property
    def error(self):
        """\
        Error correction level; either a string ("L", "M", "Q", "H") or ``None``
        if the QR code provides no error correction (Micro QR Code version M1)

        :rtype: str
        """
        if self._error is None:
            return None
        return encoder.get_error_name(self._error)

    @property
    def mode(self):
        """\
        String indicating the mode ("numeric", "alphanumeric", "byte", "kanji",
        or "hanzi").
        May be ``None`` if multiple modes are used.

        :rtype: str or None
        """
        if self._mode is not None:
            return encoder.get_mode_name(self._mode)
        return None

    @property
    def designator(self):
        """\
        Returns the version and error correction level as string `V-E` where
        `V` represents the version number and `E` the error level.

        :rtype: str
        """
        version = str(self.version)
        return '-'.join((version, self.error) if self.error else (version,))

    @property
    def default_border_size(self):
        """\
        Indicates the default border size aka quiet zone.

        QR Codes have a quiet zone of four light modules, while Micro QR Codes
        have a quiet zone of two light modules.

        :rtype: int
        """
        return utils.get_default_border_size(self._matrix_size)

    @property
    def is_micro(self):
        """\
        Indicates if this QR code is a Micro QR code

        :rtype: bool
        """
        return self._version < 1

    def __eq__(self, other):
        return self.__class__ == other.__class__ and self.matrix == other.matrix

    __hash__ = None

    def symbol_size(self, scale=1, border=None):
        """\
        Returns the symbol size (width x height) with the provided border and
        scaling factor.

        :param scale: Indicates the size of a single module (default: 1).
                The size of a module depends on the used output format; i.e.
                in a PNG context, a scaling factor of 2 indicates that a module
                has a size of 2 x 2 pixel. Some outputs (i.e. SVG) accept
                floating point values.
        :type scale: int or float
        :param int border: The border size or ``None`` to specify the
                default quiet zone (4 for QR Codes, 2 for Micro QR Codes).
        :rtype: tuple (width, height)
        """
        return utils.get_symbol_size(self._matrix_size, scale=scale, border=border)

    def matrix_iter(self, scale=1, border=None, verbose=False):
        """\
        Returns an iterator over the matrix which includes the border.

        The border is returned as sequence of light modules.
        Dark modules are reported as ``0x1``, light modules have the value
        ``0x0``.

        The following example converts the QR code matrix into a list of
        lists which use boolean values for the modules (True = dark module,
        False = light module)::

            >>> import segno
            >>> qrcode = segno.make('The Beatles')
            >>> width, height = qrcode.symbol_size(scale=2)
            >>> res = []
            >>> # Scaling factor 2, default border
            >>> for row in qrcode.matrix_iter(scale=2):
            >>>     res.append([col == 0x1 for col in row])
            >>> width == len(res[0])
            True
            >>> height == len(res)
            True

        If `verbose` is ``True``, the iterator returns integer constants which
        indicate the type of the module, i.e. ``segno.consts.TYPE_FINDER_PATTERN_DARK``,
        ``segno.consts.TYPE_FINDER_PATTERN_LIGHT``, ``segno.consts.TYPE_QUIET_ZONE`` etc.

        To check if the returned module type is dark or light, use::

            if mt >> 8:
                print('dark module')

            if not mt >> 8:
                print('light module')

        :param int scale: The scaling factor (default: ``1``).
        :param int border: The size of border / quiet zone or ``None`` to
                indicate the default border.
        :param bool verbose: Indicates if the type of the module should be returned
                instead of ``0x1`` and ``0x0`` values.
                See :py:mod:`segno.consts` for the return values.
                This feature is currently in EXPERIMENTAL state.
        :raises: :py:exc:`ValueError` if the scaling factor or the border is
                invalid (i.e. negative).
        """
        iterfn = utils.matrix_iter_verbose if verbose else utils.matrix_iter
        return iterfn(self.matrix, self._matrix_size, scale, border)

    def show(self, delete_after=20, scale=10, border=None, dark='#000',
             light='#fff'):  # pragma: no cover
        """\
        Displays this QR code.

        This method is mainly intended for debugging purposes.

        This method saves the QR code as an image (by default with a scaling
        factor of 10) to a temporary file and opens it with the standard PNG
        viewer application or within the standard webbrowser.
        The temporary file is deleted afterwards (unless
        :paramref:`delete_after <segno.QRCode.show.delete_after>` is set to ``None``).

        If this method does not show any result, try to increase the
        :paramref:`delete_after <segno.QRCode.show.delete_after>` value or set
        it to ``None``

        :param delete_after: Time in seconds to wait till the temporary file is
                deleted.
        :type delete_after: int or None
        :param int scale: Integer indicating the size of a single module.
        :param border: Integer indicating the size of the quiet zone.
                If set to ``None`` (default), the recommended border size
                will be used.
        :type border: int or None
        :param dark: The color of the dark modules (default: black).
        :param light: The color of the light modules (default: white).
        """
        import os
        import time
        import tempfile
        import webbrowser
        import threading
        try:  # Python 3
            from urllib.parse import urljoin
            from urllib.request import pathname2url
        except ImportError:  # Python 2
            from urlparse import urljoin  # noqa
            from urllib import pathname2url  # noqa

        def delete_file(name):
            time.sleep(delete_after)
            try:
                os.unlink(name)
            except OSError:
                pass

        f = tempfile.NamedTemporaryFile('wb', suffix='.png', delete=False)
        try:
            self.save(f, scale=scale, dark=dark, light=light, border=border)
        except:  # noqa: E722
            f.close()
            os.unlink(f.name)
            raise
        f.close()
        webbrowser.open_new_tab(urljoin('file:', pathname2url(f.name)))
        if delete_after is not None:
            t = threading.Thread(target=delete_file, args=(f.name,))
            t.start()

    def svg_data_uri(self, xmldecl=False, encode_minimal=False,
                     omit_charset=False, nl=False, **kw):
        """\
        Converts the QR code into an SVG data URI.

        The XML declaration is omitted by default (set
        :paramref:`xmldecl <segno.QRCode.svg_data_uri.xmldecl>` to ``True``
        to enable it), further the newline is omitted by default (set ``nl`` to
        ``True`` to enable it).

        Aside from the missing `out` parameter, the different `xmldecl` and
        `nl` default values, and the additional parameters
        :paramref:`encode_minimal <segno.QRCode.svg_data_uri.encode_minimal>`
        and :paramref:`omit_charset <segno.QRCode.svg_data_uri.omit_charset>`,
        this method uses the same parameters as the usual SVG serializer, see
        :py:func:`save` and the available `SVG parameters <#svg>`_

        .. note::
            In order to embed a SVG image in HTML without generating a file, the
            :py:func:`svg_inline` method could serve better results, as it
            usually produces a smaller output.

        :param bool xmldecl: Indicates if the XML declaration should be
                        serialized (default: ``False``)
        :param bool encode_minimal: Indicates if the resulting data URI should
                        use minimal percent encoding (disabled by default).
        :param bool omit_charset: Indicates if the ``;charset=...`` should be omitted
                        (disabled by default)
        :param bool nl: Indicates if the document should have a trailing newline
                        (default: ``False``)
        :rtype: str
        """
        return writers.as_svg_data_uri(self.matrix, self._matrix_size,
                                       xmldecl=xmldecl, nl=nl,
                                       encode_minimal=encode_minimal,
                                       omit_charset=omit_charset, **kw)

    def svg_inline(self, **kw):
        """\
        Returns an SVG representation which is embeddable into HTML5 contexts.

        Due to the fact that HTML5 directly supports SVG, various elements of
        an SVG document can or should be suppressed (i.e. the XML declaration and
        the SVG namespace).

        This method returns a string that can be used in an HTML context.

        This method uses the same parameters as the usual SVG serializer, see
        :py:func:`save` and the available `SVG parameters <#svg>`_ (the ``out``
        and ``kind`` parameters are not supported).

        The returned string can be used directly in
        `Jinja <https://jinja.palletsprojects.com/>`_ and
        `Django <https://www.djangoproject.com/>`_ templates, provided the
        ``safe`` filter is used which marks a string as not requiring further
        HTML escaping prior to output.
        ::

            <div>{{ qr.svg_inline(dark='#228b22', scale=3) | safe }}</div>

        :rtype: str
        """
        buff = io.BytesIO()
        self.save(buff, kind='svg', xmldecl=False, svgns=False, nl=False, **kw)
        return buff.getvalue().decode(kw.get('encoding', 'utf-8'))

    def png_data_uri(self, **kw):
        """\
        Converts the QR code into a PNG data URI.

        Uses the same keyword parameters as the usual PNG serializer,
        see :py:func:`save` and the available `PNG parameters <#png>`_

        :rtype: str
        """
        return writers.as_png_data_uri(self.matrix, self._matrix_size, **kw)

    def terminal(self, out=None, border=None, compact=False):
        """\
        Serializes the matrix as ANSI escape code or Unicode Block Elements
        (if ``compact`` is ``True``).

        Under Windows, no ANSI escape sequence is generated but the Windows
        API is used *unless* :paramref:`out <segno.QRCode.terminal.out>`
        is a writable object or using WinAPI fails or if ``compact`` is ``True``.

        :param out: Filename or a file-like object supporting to write text.
                If ``None`` (default), the matrix is written to :py:class:`sys.stdout`.
        :param int border: Integer indicating the size of the quiet zone.
                If set to ``None`` (default), the recommended border size
                will be used (``4`` for QR Codes, ``2`` for Micro QR Codes).
        :param bool compact: Indicates if a more compact QR code should be shown
                (default: ``False``).
        """
        if compact:
            writers.write_terminal_compact(self.matrix, self._matrix_size, out or sys.stdout, border)
        elif out is None and sys.platform == 'win32':  # pragma: no cover
            # Windows < 10 does not support ANSI escape sequences, try to
            # call the a Windows specific terminal output which uses the
            # Windows API.
            try:
                writers.write_terminal_win(self.matrix, self._matrix_size, border)
            except OSError:
                # Use the standard output even if it may print garbage
                writers.write_terminal(self.matrix, self._matrix_size, sys.stdout, border)
        else:
            writers.write_terminal(self.matrix, self._matrix_size, out or sys.stdout, border)

    def save(self, out, kind=None, **kw):
        """\
        Serializes the QR code in one of the supported formats.
        The serialization format depends on the filename extension.

        .. _common_keywords:

        **Common keywords**

        ==========    ==============================================================
        Name          Description
        ==========    ==============================================================
        scale         Integer or float indicating the size of a single module.
                      Default: 1. The interpretation of the scaling factor depends
                      on the serializer. For pixel-based output (like :ref:`PNG <png>`)
                      the scaling factor is interpreted as pixel-size (1 = 1 pixel).
                      :ref:`EPS <eps>` interprets ``1`` as 1 point (1/72 inch) per
                      module.
                      Some serializers (like :ref:`SVG <svg>`) accept float values.
                      If the serializer does not accept float values, the value will be
                      converted to an integer value (note: int(1.6) == 1).
        border        Integer indicating the size of the quiet zone.
                      If set to ``None`` (default), the recommended border size
                      will be used (``4`` for QR codes, ``2`` for a Micro QR codes).
                      A value of ``0`` indicates that border should be omitted.
        dark          A string or tuple representing a color value for the dark
                      modules. The default value is "black".  The color can be
                      provided as ``(R, G, B)`` tuple, as web color name
                      (like "red") or in hexadecimal format (``#RGB`` or
                      ``#RRGGBB``). Some serializers (i.e. :ref:`SVG <svg>` and
                      :ref:`PNG <png>`) accept an alpha transparency value like
                      ``#RRGGBBAA``.
        light         A string or tuple representing a color for the light modules.
                      See `dark` for valid values.
                      The default value depends on the serializer. :ref:`SVG <svg>`
                      uses no color (``None``) for light modules by default, other
                      serializers, like :ref:`PNG <png>`, use "white" as default
                      light color.
        ==========    ==============================================================

        .. _module_colors:

        **Module Colors**

        ===============    =======================================================
        Name               Description
        ===============    =======================================================
        finder_dark        Color of the dark modules of the finder patterns
                           Default: undefined, use value of "dark"
        finder_light       Color of the light modules of the finder patterns
                           Default: undefined, use value of "light"
        data_dark          Color of the dark data modules
                           Default: undefined, use value of "dark"
        data_light         Color of the light data modules.
                           Default: undefined, use value of "light".
        version_dark       Color of the dark modules of the version information.
                           Default: undefined, use value of "dark".
        version_light      Color of the light modules of the version information,
                           Default: undefined, use value of "light".
        format_dark        Color of the dark modules of the format information.
                           Default: undefined, use value of "dark".
        format_light       Color of the light modules of the format information.
                           Default: undefined, use value of "light".
        alignment_dark     Color of the dark modules of the alignment patterns.
                           Default: undefined, use value of "dark".
        alignment_light    Color of the light modules of the alignment patterns.
                           Default: undefined, use value of "light".
        timing_dark        Color of the dark modules of the timing patterns.
                           Default: undefined, use value of "dark".
        timing_light       Color of the light modules of the timing patterns.
                           Default: undefined, use value of "light".
        separator          Color of the separator.
                           Default: undefined, use value of "light".
        dark_module        Color of the dark module (a single dark module which
                           occurs in all QR Codes but not in Micro QR Codes.
                           Default: undefined, use value of "dark".
        quiet_zone         Color of the quiet zone / border.
                           Default: undefined, use value of "light".
        ===============    =======================================================

        .. _svg:

        **Scalable Vector Graphics (SVG)**

        All :ref:`common keywords <common_keywords>` and :ref:`module colors <module_colors>`
        are supported.

        ================ ==============================================================
        Name             Description
        ================ ==============================================================
        out              Filename or :py:class:`io.BytesIO`
        kind             "svg" or "svgz" (to create a gzip compressed SVG)
        scale            integer or float
        dark             Default: "#000" (black)
                         ``None`` is a valid value. If set to ``None``, the resulting
                         path won't have a "stroke" attribute. The "stroke" attribute
                         may be defined via CSS (external).
                         If an alpha channel is defined, the output depends of the
                         used SVG version. For SVG versions >= 2.0, the "stroke"
                         attribute will have a value like "rgba(R, G, B, A)", otherwise
                         the path gets another attribute "stroke-opacity" to emulate
                         the alpha channel.
                         To minimize the document size, the SVG serializer uses
                         automatically the shortest color representation: If
                         a value like "#000000" is provided, the resulting
                         document will have a color value of "#000". If the color
                         is "#FF0000", the resulting color is not "#F00", but
                         the web color name "red".
        light            Default value ``None``. If this parameter is set to another
                         value, the resulting image will have another path which
                         is used to define the color of the light modules.
                         If an alpha channel is used, the resulting path may
                         have a "fill-opacity" attribute (for SVG version < 2.0)
                         or the "fill" attribute has a "rgba(R, G, B, A)" value.
        xmldecl          Boolean value (default: ``True``) indicating whether the
                         document should have an XML declaration header.
                         Set to ``False`` to omit the header.
        svgns            Boolean value (default: ``True``) indicating whether the
                         document should have an explicit SVG namespace declaration.
                         Set to ``False`` to omit the namespace declaration.
                         The latter might be useful if the document should be
                         embedded into a HTML 5 document where the SVG namespace
                         is implicitly defined.
        title            String (default: ``None``) Optional title of the generated
                         SVG document.
        desc             String (default: ``None``) Optional description of the
                         generated SVG document.
        svgid            A string indicating the ID of the SVG document
                         (if set to ``None`` (default), the SVG element won't have
                         an ID).
        svgclass         Default: "segno". The CSS class of the SVG document
                         (if set to ``None``, the SVG element won't have a class).
        lineclass        Default: "qrline". The CSS class of the path element
                         (which draws the dark modules (if set to ``None``, the path
                         won't have a class).
        omitsize         Indicates if width and height attributes should be
                         omitted (default: ``False``). If these attributes are
                         omitted, a ``viewBox`` attribute will be added to the
                         document.
        unit             Default: ``None``
                         Indicates the unit for width / height and other coordinates.
                         By default, the unit is unspecified and all values are
                         in the user space.
                         Valid values: em, ex, px, pt, pc, cm, mm, in, and percentages
                         (any string is accepted, this parameter is not validated
                         by the serializer)
        encoding         Encoding of the XML document. "utf-8" by default.
        svgversion       SVG version (default: ``None``). If specified (a float),
                         the resulting document has an explicit "version" attribute.
                         If set to ``None``, the document won't have a "version"
                         attribute. This parameter is not validated.
        compresslevel    Default: 9. This parameter is only valid, if a compressed
                         SVG document should be created (file extension "svgz").
                         1 is fastest and produces the least compression, 9 is slowest
                         and produces the most. 0 is no compression.
        draw_transparent Indicates if transparent SVG paths should be
                         added to the graphic (default: ``False``)
        nl               Indicates if the document should have a trailing newline
                         (default: ``True``)
        ================ ==============================================================

        .. _png:

        **Portable Network Graphics (PNG)**

        This writes either a grayscale (maybe with transparency) PNG (color type 0)
        or a palette-based (maybe with transparency) image (color type 3).
        If the dark / light values are ``None``, white or black, the serializer
        chooses the more compact grayscale mode, in all other cases a palette-based
        image is written.

        All :ref:`common keywords <common_keywords>` and :ref:`module colors <module_colors>`
        are supported.

        ===============    ==============================================================
        Name               Description
        ===============    ==============================================================
        out                Filename or :py:class:`io.BytesIO`
        kind               "png"
        scale              integer
        dark               Default: "#000" (black)
                           ``None`` is a valid value iff light is not ``None``.
                           If set to ``None``, the dark modules become transparent.
        light              Default value "#fff" (white)
                           See keyword "dark" for further details.
        compresslevel      Default: 9. Integer indicating the compression level
                           for the ``IDAT`` (data) chunk.
                           1 is fastest and produces the least compression, 9 is slowest
                           and produces the most. 0 is no compression.
        dpi                Default: ``None``. Specifies the DPI value for the image.
                           By default, the DPI value is unspecified. Please note
                           that the DPI value is converted into meters (maybe with
                           rounding errors) since PNG does not support the unit
                           "dots per inch".
        ===============    ==============================================================

        .. _eps:

        **Encapsulated PostScript (EPS)**

        All :ref:`common keywords <common_keywords>` are supported.

        =============    ==============================================================
        Name             Description
        =============    ==============================================================
        out              Filename or :py:class:`io.StringIO`
        kind             "eps"
        scale            integer or float
        dark             Default: "#000" (black)
        light            Default value: ``None`` (transparent light modules)
        =============    ==============================================================

        .. _pdf:

        **Portable Document Format (PDF)**

        All :ref:`common keywords <common_keywords>` are supported.

        =============    ==============================================================
        Name             Description
        =============    ==============================================================
        out              Filename or :py:class:`io.BytesIO`
        kind             "pdf"
        scale            integer or float
        dark             Default: "#000" (black)
        light            Default value: ``None`` (transparent light modules)
        compresslevel    Default: 9. Integer indicating the compression level.
                         1 is fastest and produces the least compression, 9 is slowest
                         and produces the most. 0 is no compression.
        =============    ==============================================================

        .. _txt:

        **Text (TXT)**

        Aside of "scale", all :ref:`common keywords <common_keywords>` are supported.

        =============    ==============================================================
        Name             Description
        =============    ==============================================================
        out              Filename or :py:class:`io.StringIO`
        kind             "txt"
        dark             Default: "1"
        light            Default: "0"
        =============    ==============================================================

        .. _ansi:

        **ANSI escape code**

        Supports the "border" keyword, only!

        =============    ==============================================================
        Name             Description
        =============    ==============================================================
        out              Filename or :py:class:`io.StringIO`
        kind             "ans"
        =============    ==============================================================

        .. _pbm:

        **Portable Bitmap (PBM)**

        All :ref:`common keywords <common_keywords>` are supported.

        =============    ==============================================================
        Name             Description
        =============    ==============================================================
        out              Filename or :py:class:`io.BytesIO`
        kind             "pbm"
        scale            integer
        plain            Default: False. Boolean to switch between the P4 and P1 format.
                         If set to ``True``, the (outdated) P1 serialization format is
                         used.
        =============    ==============================================================

        .. _pam:

        **Portable Arbitrary Map (PAM)**

        All :ref:`common keywords <common_keywords>` are supported.

        =============    ==============================================================
        Name             Description
        =============    ==============================================================
        out              Filename or :py:class:`io.BytesIO`
        kind             "pam"
        scale            integer
        dark             Default: "#000" (black).
        light            Default value "#fff" (white). Use ``None`` for transparent
                         light modules.
        =============    ==============================================================

        .. _ppm:

        **Portable Pixmap (PPM)**

        All :ref:`common keywords <common_keywords>` and :ref:`module colors <module_colors>`
        are supported.

        =============    ==============================================================
        Name             Description
        =============    ==============================================================
        out              Filename or :py:class:`io.BytesIO`
        kind             "ppm"
        scale            integer
        dark             Default: "#000" (black).
        light            Default value "#fff" (white).
        =============    ==============================================================

        .. _latex:

        **LaTeX / PGF/TikZ**

        To use the output of this serializer, the ``PGF/TikZ`` (and optionally
        ``hyperref``) package is required in the LaTeX environment. The
        serializer itself does not depend on any external packages.

        All :ref:`common keywords <common_keywords>` are supported.

        =============    ==============================================================
        Name             Description
        =============    ==============================================================
        out              Filename or :py:class:`io.StringIO`
        kind             "tex"
        scale            integer or float
        dark             LaTeX color name (default: "black"). The color is written
                         "at it is", please ensure that the color is a standard color
                         or it has been defined in the enclosing LaTeX document.
        url              Default: ``None``. Optional URL where the QR code should
                         point to. Requires the ``hyperref`` package in the LaTeX
                         environment.
        =============    ==============================================================

        .. _xbm:

        **X BitMap (XBM)**

        All :ref:`common keywords <common_keywords>` are supported.

        =============    ==============================================================
        Name             Description
        =============    ==============================================================
        out              Filename or :py:class:`io.StringIO`
        kind             "xbm"
        scale            integer
        name             Name of the variable (default: "img")
        =============    ==============================================================

        .. _xpm:

        **X PixMap (XPM)**

        All :ref:`common keywords <common_keywords>` are supported.

        =============    ==============================================================
        Name             Description
        =============    ==============================================================
        out              Filename or :py:class:`io.StringIO`
        kind             "xpm"
        scale            integer
        dark             Default: "#000" (black).
                         ``None`` indicates transparent dark modules.
        light            Default value "#fff" (white)
                         ``None`` indicates transparent light modules.
        name             Name of the variable (default: "img")
        =============    ==============================================================

        :param out: A filename or a writable file-like object with a
                ``name`` attribute. Use the :paramref:`kind <segno.QRCode.save.kind>`
                parameter if `out` is a :py:class:`io.BytesIO` or
                :py:class:`io.StringIO` stream which don't have a ``name``
                attribute.
        :param str kind: Default ``None``.
                If the desired output format cannot be determined from
                the :paramref:`out <segno.QRCode.save.out>` parameter, this
                parameter can be used to indicate the serialization format
                (i.e. "svg" to enforce SVG output). The value is case
                insensitive.
        :param kw: Any of the supported keywords by the specific serializer.
        """
        writers.save(self.matrix, self._matrix_size, out, kind, **kw)

    def __getattr__(self, name):
        """\
        This is used to plug-in external serializers.

        When a "to_<name>" method is invoked, this method tries to find
        a ``segno.plugin.converter`` plugin with the provided ``<name>``.
        If such a plugin exists, a callable function is returned. The result
        of invoking the function depends on the plugin.
        """
        if name.startswith('to_'):
            from pkg_resources import iter_entry_points
            from functools import partial
            for ep in iter_entry_points(group='segno.plugin.converter',
                                        name=name[3:]):
                plugin = ep.load()
                return partial(plugin, self)
        raise AttributeError('{0} object has no attribute {1}'
                             .format(self.__class__, name))

class QRCodeSequence(tuple):
    """\
    Represents a sequence of  1 .. n (max. n = 16) :py:class:`QRCode` instances.

    Iff this sequence contains only one item, it behaves like :py:class:`QRCode`.
    """
    __slots__ = ()

    def __new__(cls, qrcodes):
        return super(QRCodeSequence, cls).__new__(cls, qrcodes)

    def terminal(self, out=None, border=None, compact=False):
        """\
        Serializes the sequence of QR codes as ANSI escape code.

        See :py:meth:`QRCode.terminal()` for details.
        """
        for qrcode in self:
            qrcode.terminal(out=out, border=border, compact=compact)

    def save(self, out, kind=None, **kw):
        """\
        Saves the sequence of QR codes to `out`.

        If `out` is a filename, this method modifies the filename and adds
        ``<Number of QR codes>-<Current QR code>`` to it.
        ``structured-append.svg`` becomes (if the sequence contains two QR codes):
        ``structured-append-02-01.svg`` and ``structured-append-02-02.svg``

        Please note that using a file or file-like object may result into an
        invalid serialization format since all QR codes are written to the same
        output.

        See :py:meth:`QRCode.save()` for a detailed enumeration of options.
        """
        filename = lambda o, n: o  # noqa: E731
        m = len(self)
        if m > 1 and isinstance(out, str_type):
            dot_idx = out.rfind('.')
            if dot_idx > -1:
                out = out[:dot_idx] + '-{0:02d}-{1:02d}' + out[dot_idx:]
                filename = lambda o, n: o.format(m, n)  # noqa: E731
        for n, qrcode in enumerate(self, start=1):
            qrcode.save(filename(out, n), kind=kind, **kw)

    def __getattr__(self, item):
        """\
        Behaves like :py:class:`QRCode` iff this sequence contains a single item.
        """
        if len(self) == 1:
            return getattr(self[0], item)
        raise AttributeError("{0} object has no attribute '{1}'"
                             .format(self.__class__, item))


text:
Free JavaScripts provided

by The JavaScript Source


text:
#ifndef __log_h__
#define __log_h__ 1

#include <mqx_cnfg.h>

#if (!MQX_USE_LOGS) && (!defined __lwlog_h__) && (! defined (MQX_DISABLE_CONFIG_CHECK))
#error LOG component is currently disabled in MQX kernel. Please set MQX_USE_LOGS to 1 in user_config.h and recompile kernel.
#endif

/*--------------------------------------------------------------------------*/
/*                        CONSTANT DEFINITIONS                              */

/* Maximum number of logs allowed */
#define LOG_MAXIMUM_NUMBER (16)

/*
 * The kernel system logging uses log number 0
 */
#define LOG_KERNEL_LOG_NUMBER      (0)

/* Configuration flags */
#define LOG_OVERWRITE              (1)

/* Types of log reads */
#define LOG_READ_NEWEST            (1)
#define LOG_READ_OLDEST            (2)
#define LOG_READ_NEXT              (3)
#define LOG_READ_OLDEST_AND_DELETE (4)

/* Error codes */
#define LOG_INVALID                (LOG_ERROR_BASE|0x00)
#define LOG_EXISTS                 (LOG_ERROR_BASE|0x01)
#define LOG_DOES_NOT_EXIST         (LOG_ERROR_BASE|0x02)
#define LOG_FULL                   (LOG_ERROR_BASE|0x03)
#define LOG_ENTRY_NOT_AVAILABLE    (LOG_ERROR_BASE|0x04)
#define LOG_DISABLED               (LOG_ERROR_BASE|0x05)
#define LOG_INVALID_READ_TYPE      (LOG_ERROR_BASE|0x06)
#define LOG_INVALID_SIZE           (LOG_ERROR_BASE|0x07)

/*--------------------------------------------------------------------------*/
/*                        DATATYPE DECLARATIONS                             */

/*                        LOG_ENTRY_STRUCT                                  */
/*!
 * \brief Header of an entry in a user log.
 *
 * The length of the entry depends on the SIZE field.
 *
 * \see _log_read
 * \see _log_write
 */

typedef struct log_entry_struct
{

   /*! \brief The size of this entry in _mqx_uints. */
   _mqx_uint    SIZE;

   /*! \brief The sequence number for the entry. */
   _mqx_uint    SEQUENCE_NUMBER;

   /*! \brief The time (in seconds) at which MQX wrote the entry. */
   uint_32      SECONDS;

   /*! \brief The time (in milliseconds) at which MQX wrote the entry. */
   uint_16      MILLISECONDS;

   /*! \brief The time (in microseconds) at which MQX wrote the entry. */
   uint_16      MICROSECONDS;

} LOG_ENTRY_STRUCT, _PTR_ LOG_ENTRY_STRUCT_PTR;

/*--------------------------------------------------------------------------*/
/*                           EXTERNAL DECLARATIONS                          */

#ifdef __cplusplus
extern "C" {
#endif

extern _mqx_uint _log_create(_mqx_uint, _mqx_uint, uint_32);
extern _mqx_uint _log_create_component(void);
extern _mqx_uint _log_destroy(_mqx_uint);
extern _mqx_uint _log_disable(_mqx_uint);
extern _mqx_uint _log_enable(_mqx_uint);
extern _mqx_uint _log_read(_mqx_uint, _mqx_uint, _mqx_uint,
   LOG_ENTRY_STRUCT_PTR);
extern _mqx_uint _log_reset(_mqx_uint);
extern _mqx_uint _log_test(_mqx_uint _PTR_);
extern _mqx_uint _log_write(_mqx_uint, _mqx_uint, ... );

#ifdef __cplusplus
}
#endif

#endif
/* EOF */


text:
import {Directive} from '@slicky/core';

@Directive({
	selector: 'test-directive',
})
class TestDirective {}


text:
using Famoser.SyncApi.Models.Interfaces.Base;

namespace Famoser.SyncApi.Models.Interfaces
{
    public interface ICollectionModel : IUniqueSyncModel
    {
    }
}


text:
export type QuoteStats = {
  consumed: number;
  whole: number;
};


text:
NSString * const kPBAppDelegateDefaultPayload = @"{\n\t\"aps\":{\n\t\t\"alert\":\"Test\",\n\t\t\"sound\":\"default\",\n\t\t\"badge\":0\n\t}\n}";

@interface SBAppDelegate ()
- (NSArray *)identities;
@property (nonatomic, strong) MGSFragaria *fragaria;
@property (nonatomic, strong, readonly) NSDictionary *payload;
@property (nonatomic, strong) SBAPNS *APNS;
@property (nonatomic, strong) SBNetServiceSearcher *searcher;
@end

@implementation SBAppDelegate

@synthesize window = _window;
@dynamic identityName;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
  [self APNS];
  [self searcher];
}

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender {
  [self.window makeKeyAndOrderFront:self];
  return NO;
}

- (void)awakeFromNib {
  [super awakeFromNib];
  [self.fragaria embedInView:self.containerView];
}

#pragma mark Actions

- (IBAction)chooseIdentity:(id)sender {
	SFChooseIdentityPanel *panel = [SFChooseIdentityPanel sharedChooseIdentityPanel];
	[panel setAlternateButtonTitle:@"Cancel"];

	[panel beginSheetForWindow:self.window
							 modalDelegate:self
							didEndSelector:@selector(chooseIdentityPanelDidEnd:returnCode:contextInfo:)
								 contextInfo:nil
									identities:[self identities]
										 message:@"Choose the identity to use for delivering notifications: \n(Issued by Apple in the Provisioning Portal)"];
}

- (IBAction)chooseNetServiceDevice:(id)sender {
  NSPopUpButton *button = sender;

  NSInteger index = [button indexOfSelectedItem];
  NSNetService *netService = [self.searcher.availableNetServices objectAtIndex:index];
  NSData *data = [[NSNetService dictionaryFromTXTRecordData:netService.TXTRecordData] objectForKey:@"token"];
  NSString *token = [data.description stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];

  [self.tokenTextField setStringValue:token];
}

-(void)chooseIdentityPanelDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
	if (returnCode == NSFileHandlingPanelOKButton) {
		SecIdentityRef identity = [SFChooseIdentityPanel sharedChooseIdentityPanel].identity;
		SBIdentityType type = SBSecIdentityGetType(identity);
		BOOL isSandbox = (type == SBIdentityTypeDevelopment);
		[self.APNS setIdentity:identity];
		[self.APNS setSandbox:isSandbox];

		// KVO trigger
		[self willChangeValueForKey:@"identityName"];
		[self didChangeValueForKey:@"identityName"];
	}
}

- (IBAction)push:(id)sender {
	if (self.APNS.identity != NULL) {
    NSString *token = [self preparedToken];
    [self.APNS pushPayload:self.payload withToken:token];
  } else {
		NSAlert *alert = [NSAlert alertWithMessageText:@"Missing identity"
                                     defaultButton:@"OK"
                                   alternateButton:nil
                                       otherButton:nil
                         informativeTextWithFormat:@"You have not choosen an identity for signing the notification."];

		[alert beginSheetModalForWindow:self.window
											modalDelegate:self
										 didEndSelector:nil
												contextInfo:nil];
	}
}

- (IBAction)exportIdentity:(id)sender {
  if (self.APNS.identity != NULL) {
    CFDataRef data = NULL;

    // Generate a random passphrase and filename
    NSString *passphrase = [[NSUUID UUID] UUIDString];
    NSString *PKCS12FileName = [[NSUUID UUID] UUIDString];

    // Export to PKCS12
    SecItemImportExportKeyParameters keyParams = {
      SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION,
      0,
      (__bridge CFStringRef)passphrase,
      NULL,
      NULL,
      NULL,
      NULL,
      (__bridge CFArrayRef)@[@(CSSM_KEYATTR_PERMANENT)]
    };

    if (noErr == SecItemExport(self.APNS.identity,
                               kSecFormatPKCS12,
                               0,
                               &keyParams,
                               &data)) {

      NSSavePanel *panel = [NSSavePanel savePanel];
      [panel setPrompt:@"Export"];
      [panel setNameFieldLabel:@"Export As:"];
      [panel setNameFieldStringValue:@"cert.pem"];

      [panel beginSheetModalForWindow:self.window
                    completionHandler:^(NSInteger result) {
                      if (result == NSFileHandlingPanelCancelButton)
                        return;

                      // Write to temp file
                      NSURL *tempURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
                      tempURL = [tempURL URLByAppendingPathComponent:PKCS12FileName];

                      [(__bridge NSData *)data writeToURL:tempURL atomically:YES];

                      // convert with openssl to pem
                      NSTask *task = [NSTask new];
                      [task setLaunchPath:@"/bin/sh"];
                      [task setArguments:@[
                       @"-c",
                       [NSString stringWithFormat:@"/usr/bin/openssl pkcs12 -in %@ -out %@ -nodes", tempURL.path, panel.URL.path]
                       ]];

                      // Remove temp file on completion
                      [task setTerminationHandler:^(NSTask *task) {
                        [[NSFileManager defaultManager] removeItemAtURL:tempURL error:NULL];
                      }];

                      NSPipe *pipe = [NSPipe pipe];
                      [pipe.fileHandleForWriting writeData:[[NSString stringWithFormat:@"%@\n", passphrase] dataUsingEncoding:NSUTF8StringEncoding]];
                      [task setStandardInput:pipe];

                      [task launch];
                    }];
    }
  }
}

#pragma mark -

- (NSArray *)identities {
  NSMutableArray *result;

  NSDictionary *query = @{
    (id)kSecClass:(id)kSecClassIdentity,
    (id)kSecMatchLimit:(id)kSecMatchLimitAll,
    (id)kSecReturnRef:(id)kCFBooleanTrue
  };

  CFArrayRef identities;
  OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef *)&identities);
  if (status != noErr) return nil;
  result = [(__bridge NSArray *) identities mutableCopy];
  CFRelease(identities);

  // Allow only identities with APNS certificate
  NSPredicate *predicate = [NSPredicate predicateWithBlock:^(id object, NSDictionary *bindings) {
    SecIdentityRef identity = (__bridge SecIdentityRef) object;
	SBIdentityType type = SBSecIdentityGetType(identity);
	BOOL isValid = (type != SBIdentityTypeInvalid);
    return isValid;
  }];
  [result filterUsingPredicate:predicate];

  // Sort identities by name
  NSComparator comparator = (NSComparator) ^(SecIdentityRef id1, SecIdentityRef id2) {
    SecCertificateRef cert1;
    SecIdentityCopyCertificate(id1, &cert1);
    NSString *name1 = (__bridge_transfer NSString*)SecCertificateCopyShortDescription(NULL, cert1, NULL);
    CFRelease(cert1);

    SecCertificateRef cert2;
    SecIdentityCopyCertificate(id2, &cert2);
    NSString *name2 = (__bridge_transfer NSString*)SecCertificateCopyShortDescription(NULL, cert2, NULL);
    CFRelease(cert2);

    return [name1 compare:name2];
  };
  [result sortUsingComparator:comparator];

  return result;
}

- (NSString *)preparedToken {
  NSString *token = self.tokenTextField.stringValue;

  // Clean token
  NSCharacterSet *removeCharacterSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
  token = [[token componentsSeparatedByCharactersInSet:removeCharacterSet] componentsJoinedByString:@""];
  token = [token lowercaseString];

  // Split into chunks
  static NSUInteger const tokenChunkCount = 8;
  static NSUInteger const tokenChunkSize = 8;

  NSUInteger characterCount = tokenChunkCount * tokenChunkSize;
  NSUInteger spacesCount = tokenChunkCount - 1;

  // If shorter than the expected size, split and pad with spaces
  if ([token length] < characterCount + spacesCount) {
    NSMutableArray *chunks = [[NSMutableArray alloc] initWithCapacity:tokenChunkCount];

    for (NSUInteger i = 0; i < tokenChunkCount; ++i) {
      NSRange range = NSMakeRange(i * tokenChunkSize, tokenChunkSize);
      if (range.location + range.length <= [token length]) {
        [chunks addObject:[token substringWithRange:range]];
      }
    }

    token = [chunks componentsJoinedByString:@" "];
  }

  return token;
}

#pragma mark - Properties

- (NSString *)alertString {
  return [self.payload valueForKeyPath:@"aps.alert"];
}

- (NSString *)soundString {
  return [self.payload valueForKeyPath:@"aps.sound"];
}

- (NSString *)badgeString {
  return [NSString stringWithFormat:@"%@", [self.payload valueForKeyPath:@"aps.badge"]];
}

- (NSString *)identityName {
	if (self.APNS.identity == NULL)
		return @"Choose an identity";
	else {
    SecCertificateRef cert = NULL;
    if (noErr == SecIdentityCopyCertificate(self.APNS.identity, &cert)) {
      CFStringRef commonName = NULL;
      SecCertificateCopyCommonName(cert, &commonName);
      CFRelease(cert);

      return (__bridge_transfer NSString *)commonName;
    }
  }
  return @"";
}

- (MGSFragaria *)fragaria {
  if (!_fragaria) {
    _fragaria = [[MGSFragaria alloc] init];
    [[MGSFragariaPreferences sharedInstance] revertToStandardSettings:nil];

    [_fragaria setObject:self forKey:MGSFODelegate];
    [_fragaria setObject:@"JavaScript" forKey:MGSFOSyntaxDefinitionName];

    dispatch_async(dispatch_get_main_queue(), ^{
      [self willChangeValueForKey:@"payload"];
      [_fragaria setString:kPBAppDelegateDefaultPayload];
      [self didChangeValueForKey:@"payload"];
    });
  }
  return _fragaria;
}

- (NSDictionary *)payload {
  NSData *data = [self.fragaria.string dataUsingEncoding:NSUTF8StringEncoding];

  if (data) {
    NSDictionary *payload = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
    if (payload && [payload isKindOfClass:[NSDictionary class]])
      return payload;
  }

  return nil;
}

- (SBAPNS *)APNS {
  if (!_APNS) {
    _APNS = [SBAPNS new];
    __weak SBAppDelegate *weakSelf = self;
    [_APNS setErrorBlock:^(uint8_t status, NSString *description, uint32_t identifier) {
      NSAlert *alert = [NSAlert alertWithMessageText:@"Error delivering notification"
                                       defaultButton:@"OK"
                                     alternateButton:nil
                                         otherButton:nil
                           informativeTextWithFormat:@"There was an error delivering the notificaton %d: %@", identifier, description];

      [alert beginSheetModalForWindow:weakSelf.window
                        modalDelegate:nil
                       didEndSelector:nil
                          contextInfo:nil];
    }];
  }
  return _APNS;
}

- (SBNetServiceSearcher *)searcher {
  if (!_searcher) {
    _searcher = [SBNetServiceSearcher new];
    [_searcher setSearching:YES];
  }
  return _searcher;
}

#pragma mark - KVO Keys

+ (BOOL)automaticallyNotifiesObserversOfPayload {
  return NO;
}

+ (NSSet *)keyPathsForValuesAffectingAlertString {
  return [NSSet setWithObject:@"payload"];
}

+ (NSSet *)keyPathsForValuesAffectingSoundString {
  return [NSSet setWithObject:@"payload"];
}

+ (NSSet *)keyPathsForValuesAffectingBadgeString {
  return [NSSet setWithObject:@"payload"];
}

#pragma mark - NSTextDelegate

- (void)textDidChange:(NSNotification *)notification {
  [self willChangeValueForKey:@"payload"];
  [self didChangeValueForKey:@"payload"];
}

@end


text:
<?php

namespace Grpc;

/**
 * Represents an active call that allows for sending and recieving messages in
 * streams in any order.
 */
class BidiStreamingCall extends AbstractCall
{
    /**
     * Start the call.
     *
     * @param array $metadata Metadata to send with the call, if applicable
     */
    public function start(array $metadata = [])
    {
        $this->call->startBatch([
            OP_SEND_INITIAL_METADATA => $metadata,
        ]);
    }

    /**
     * Reads the next value from the server.
     *
     * @return mixed The next value from the server, or null if there is none
     */
    public function read()
    {
        $batch = [OP_RECV_MESSAGE => true];
        if ($this->metadata === null) {
            $batch[OP_RECV_INITIAL_METADATA] = true;
        }
        $read_event = $this->call->startBatch($batch);
        if ($this->metadata === null) {
            $this->metadata = $read_event->metadata;
        }

        return $this->deserializeResponse($read_event->message);
    }

    /**
     * Write a single message to the server. This cannot be called after
     * writesDone is called.
     *
     * @param ByteBuffer $data    The data to write
     * @param array      $options an array of options, possible keys:
     *                            'flags' => a number
     */
    public function write($data, $options = [])
    {
        $message_array = ['message' => $data->serialize()];
        if (array_key_exists('flags', $options)) {
            $message_array['flags'] = $options['flags'];
        }
        $this->call->startBatch([
            OP_SEND_MESSAGE => $message_array,
        ]);
    }

    /**
     * Indicate that no more writes will be sent.
     */
    public function writesDone()
    {
        $this->call->startBatch([
            OP_SEND_CLOSE_FROM_CLIENT => true,
        ]);
    }

    /**
     * Wait for the server to send the status, and return it.
     *
     * @return \stdClass The status object, with integer $code, string $details,
     *                   and array $metadata members
     */
    public function getStatus()
    {
        $status_event = $this->call->startBatch([
            OP_RECV_STATUS_ON_CLIENT => true,
        ]);

        $this->trailing_metadata = $status_event->status->metadata;

        return $status_event->status;
    }
}


text:
<?php
namespace Model;

class User
{
	/**
	 * Vrátí uživatele podle jména a hesla
	 * @param String[$username] Uživatelské jméno
	 * @param String[$password] Heslo
	 * @access public
	 * @return PDOStatement Výsledek dotazu
	 */
	public function getByUsernameAndPassword( $username, $password )
	{
		return Database::parameters("
			SELECT * FROM `user`
			WHERE
			`name` = ?
			AND
			`password` = ?
		", array($username, $password));
	}

	/**
	 * Vrátí uživatele podle ID
	 * @param Integer[$id] Identifikační číslo
	 * @access public
	 * @return PDOStatement Výsledek dotazu
	 */
	public function getById( $id )
	{
		return Database::parameters("
			SELECT * FROM `user`
			WHERE
			`id` = ?
		", array($id));
	}

	/**
	 * Změní uživatelské údaje
	 * @param Array()[$values] Nové uživatelské údaje
	 * @access public
	 * @return PDOStatement Výsledek dotazu
	 */
	public function update( $values )
	{
		$values["id"] = $_SESSION["data"]["id"];

		return Database::parameters("
			UPDATE `user`
			SET
			`name` = :name,
			`description` = :description,
			`cv` = :cv
			WHERE
			`id` = :id
		", $values);
	}
}


text:
package io.fabric8.gateway.handlers.detecting.protocol.openwire.support;

import java.util.Date;
import java.util.HashMap;

import io.fabric8.gateway.handlers.detecting.protocol.openwire.command.ActiveMQDestination;

public final class TypeConversionSupport {

    static class ConversionKey {
        final Class from;
        final Class to;
        final int hashCode;

        public ConversionKey(Class from, Class to) {
            this.from = from;
            this.to = to;
            this.hashCode = from.hashCode() ^ (to.hashCode() << 1);
        }

        public boolean equals(Object o) {
            ConversionKey x = (ConversionKey)o;
            return x.from == from && x.to == to;
        }

        public int hashCode() {
            return hashCode;
        }
    }

    interface Converter {
        Object convert(Object value);
    }

    private static final HashMap<ConversionKey, Converter> CONVERSION_MAP = new HashMap<ConversionKey, Converter>();
    static {
        Converter toStringConverter = new Converter() {
            public Object convert(Object value) {
                return value.toString();
            }
        };
        CONVERSION_MAP.put(new ConversionKey(Boolean.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(Byte.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(Short.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(Integer.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(Long.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(Float.class, String.class), toStringConverter);
        CONVERSION_MAP.put(new ConversionKey(Double.class, String.class), toStringConverter);

        CONVERSION_MAP.put(new ConversionKey(String.class, Boolean.class), new Converter() {
            public Object convert(Object value) {
                return Boolean.valueOf((String)value);
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, Byte.class), new Converter() {
            public Object convert(Object value) {
                return Byte.valueOf((String)value);
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, Short.class), new Converter() {
            public Object convert(Object value) {
                return Short.valueOf((String)value);
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, Integer.class), new Converter() {
            public Object convert(Object value) {
                return Integer.valueOf((String)value);
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, Long.class), new Converter() {
            public Object convert(Object value) {
                return Long.valueOf((String)value);
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, Float.class), new Converter() {
            public Object convert(Object value) {
                return Float.valueOf((String)value);
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, Double.class), new Converter() {
            public Object convert(Object value) {
                return Double.valueOf((String)value);
            }
        });

        Converter longConverter = new Converter() {
            public Object convert(Object value) {
                return Long.valueOf(((Number)value).longValue());
            }
        };
        CONVERSION_MAP.put(new ConversionKey(Byte.class, Long.class), longConverter);
        CONVERSION_MAP.put(new ConversionKey(Short.class, Long.class), longConverter);
        CONVERSION_MAP.put(new ConversionKey(Integer.class, Long.class), longConverter);
        CONVERSION_MAP.put(new ConversionKey(Date.class, Long.class), new Converter() {
            public Object convert(Object value) {
                return Long.valueOf(((Date)value).getTime());
            }
        });

        Converter intConverter = new Converter() {
            public Object convert(Object value) {
                return Integer.valueOf(((Number)value).intValue());
            }
        };
        CONVERSION_MAP.put(new ConversionKey(Byte.class, Integer.class), intConverter);
        CONVERSION_MAP.put(new ConversionKey(Short.class, Integer.class), intConverter);

        CONVERSION_MAP.put(new ConversionKey(Byte.class, Short.class), new Converter() {
            public Object convert(Object value) {
                return Short.valueOf(((Number)value).shortValue());
            }
        });

        CONVERSION_MAP.put(new ConversionKey(Float.class, Double.class), new Converter() {
            public Object convert(Object value) {
                return new Double(((Number)value).doubleValue());
            }
        });
        CONVERSION_MAP.put(new ConversionKey(String.class, ActiveMQDestination.class), new Converter() {
            public Object convert(Object value) {
                return ActiveMQDestination.createDestination((String)value);
            }
        });
    }

    private TypeConversionSupport() {
    }

    public static Object convert(Object value, Class clazz) {

        assert value != null && clazz != null;

        if (value.getClass() == clazz) {
            return value;
        }

        Converter c = CONVERSION_MAP.get(new ConversionKey(value.getClass(), clazz));
        if (c == null) {
            return null;
        }
        return c.convert(value);

    }

}


text:
package org.wildfly.extras.creaper.commands.elytron.realm;

import org.wildfly.extras.creaper.commands.elytron.AbstractAddCustom;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.GroovyXmlTransform;

public final class AddCustomModifiableRealm extends AbstractAddCustom {

    protected AddCustomModifiableRealm(Builder builder) {
        super(builder);
    }

    @Override
    protected String getCustomTypeName() {
        return "custom-modifiable-realm";
    }

    @Override
    protected GroovyXmlTransform.Builder getGroovyBuilder() {
        return GroovyXmlTransform.of(AddCustomModifiableRealm.class);
    }

    public static final class Builder extends AbstractAddCustom.Builder<Builder> {
        public Builder(String name) {
            super(name);
        }

        public AddCustomModifiableRealm build() {
            if (className == null || className.isEmpty()) {
                throw new IllegalArgumentException("className must not be null or empty string");
            }
            return new AddCustomModifiableRealm(this);
        }
    }
}