text:
package org.apache.commons.compress.utils;

import static org.junit.Assert.assertThrows;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;

import org.junit.Assert;
import org.junit.jupiter.api.Test;

public class IOUtilsTest {

    private interface StreamWrapper {
        InputStream wrap(InputStream toWrap);
    }

    @Test
    public void skipUsingSkip() throws Exception {
        skip(toWrap -> toWrap);
    }

    @Test
    public void skipUsingRead() throws Exception {
        skip(toWrap -> new FilterInputStream(toWrap) {
            @Override
            public long skip(final long s) {
                return 0;
            }
        });
    }

    @Test
    public void skipUsingSkipAndRead() throws Exception {
        skip(toWrap -> new FilterInputStream(toWrap) {
            boolean skipped;
            @Override
            public long skip(final long s) throws IOException {
                if (!skipped) {
                    toWrap.skip(5);
                    skipped = true;
                    return 5;
                }
                return 0;
            }
        });
    }

    @Test
    public void readFullyOnChannelReadsFully() throws IOException {
        final ByteBuffer b = ByteBuffer.allocate(20);
        final byte[] source = new byte[20];
        for (byte i = 0; i < 20; i++) {
            source[i] = i;
        }
        readFully(source, b);
        Assert.assertArrayEquals(source, b.array());
    }

    @Test
    public void readFullyOnChannelThrowsEof() throws IOException {
        final ByteBuffer b = ByteBuffer.allocate(21);
        final byte[] source = new byte[20];
        for (byte i = 0; i < 20; i++) {
            source[i] = i;
        }
        assertThrows(EOFException.class, () -> readFully(source, b));
    }

    @Test
    public void copyThrowsOnZeroBufferSize() throws IOException {
        assertThrows(IllegalArgumentException.class, () -> IOUtils.copy(new ByteArrayInputStream(ByteUtils.EMPTY_BYTE_ARRAY), new ByteArrayOutputStream(), 0));
    }

    @Test
    public void copyRangeThrowsOnZeroBufferSize() throws IOException {
        assertThrows(IllegalArgumentException.class,
            () -> IOUtils.copyRange(new ByteArrayInputStream(ByteUtils.EMPTY_BYTE_ARRAY), 5, new ByteArrayOutputStream(), 0));
    }

    @Test
    public void copyRangeDoesntCopyMoreThanAskedFor() throws IOException {
        try (ByteArrayInputStream in = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5 });
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            Assert.assertEquals(3, IOUtils.copyRange(in, 3, out));
            out.close();
            Assert.assertArrayEquals(new byte[] { 1, 2, 3 }, out.toByteArray());
        }
    }

    @Test
    public void copyRangeStopsIfThereIsNothingToCopyAnymore() throws IOException {
        try (ByteArrayInputStream in = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5 });
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            Assert.assertEquals(5, IOUtils.copyRange(in, 10, out));
            out.close();
            Assert.assertArrayEquals(new byte[] { 1, 2, 3, 4, 5 }, out.toByteArray());
        }
    }

    @Test
    public void readRangeFromStreamDoesntReadMoreThanAskedFor() throws IOException {
        try (ByteArrayInputStream in = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5 })) {
            byte[] read = IOUtils.readRange(in, 3);
            Assert.assertArrayEquals(new byte[] { 1, 2, 3 }, read);
            Assert.assertEquals(4, in.read());
        }
    }

    @Test
    public void readRangeFromStreamStopsIfThereIsNothingToReadAnymore() throws IOException {
        try (ByteArrayInputStream in = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5 })) {
            byte[] read = IOUtils.readRange(in, 10);
            Assert.assertArrayEquals(new byte[] { 1, 2, 3, 4, 5 }, read);
            Assert.assertEquals(-1, in.read());
        }
    }

    @Test
    public void readRangeFromChannelDoesntReadMoreThanAskedFor() throws IOException {
        try (ReadableByteChannel in = new SeekableInMemoryByteChannel(new byte[] { 1, 2, 3, 4, 5 })) {
            byte[] read = IOUtils.readRange(in, 3);
            Assert.assertArrayEquals(new byte[] { 1, 2, 3 }, read);
            final ByteBuffer b = ByteBuffer.allocate(1);
            Assert.assertEquals(1, in.read(b));
            Assert.assertArrayEquals(new byte[] { 4 }, b.array());
        }
    }

    @Test
    public void readRangeFromChannelDoesntReadMoreThanAskedForWhenItGotLessInFirstReadCall() throws IOException {
        try (ReadableByteChannel in = new SeekableInMemoryByteChannel(new byte[] { 1, 2, 3, 4, 5, 6, 7 }) {
            @Override
            public int read(ByteBuffer buf) throws IOException {
                // Trickle max 2 bytes at a time to trigger COMPRESS-584
                final ByteBuffer temp = ByteBuffer.allocate(Math.min(2, buf.remaining()));
                final int read = super.read(temp);
                if (read > 0) {
                    buf.put(temp.array(), 0, read);
                }
                return read;
            }
        }) {
            final byte[] read = IOUtils.readRange(in, 5);
            Assert.assertArrayEquals(new byte[] { 1, 2, 3, 4, 5 }, read);
        }
    }

    @Test
    public void readRangeMoreThanCopyBufferSize() throws Exception {
        final Field COPY_BUF_SIZE = IOUtils.class.getDeclaredField("COPY_BUF_SIZE");
        COPY_BUF_SIZE.setAccessible(true);
        final int copyBufSize = (int)COPY_BUF_SIZE.get(null);

        // Make an input that requires two read loops to trigger COMPRESS-585
        final byte[] input = new byte[copyBufSize + 10];

        try (SeekableInMemoryByteChannel in = new SeekableInMemoryByteChannel(input)) {
            // Ask for less than the input length, but more than the buffer size
            final int toRead = copyBufSize + 1;
            final byte[] read = IOUtils.readRange(in, toRead);
            Assert.assertEquals(toRead, read.length);
            Assert.assertEquals(toRead, in.position());
        }
    }

    @Test
    public void readRangeFromChannelStopsIfThereIsNothingToReadAnymore() throws IOException {
        try (ReadableByteChannel in = new SeekableInMemoryByteChannel(new byte[] { 1, 2, 3, 4, 5 })) {
            byte[] read = IOUtils.readRange(in, 10);
            Assert.assertArrayEquals(new byte[] { 1, 2, 3, 4, 5 }, read);
            final ByteBuffer b = ByteBuffer.allocate(1);
            Assert.assertEquals(-1, in.read(b));
        }
    }

    private static void readFully(final byte[] source, final ByteBuffer b) throws IOException {
        IOUtils.readFully(new SeekableInMemoryByteChannel(source), b);
    }

    private void skip(final StreamWrapper wrapper) throws Exception {
        final ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
            });
        final InputStream sut = wrapper.wrap(in);
        Assert.assertEquals(10, IOUtils.skip(sut, 10));
        Assert.assertEquals(11, sut.read());
    }
}


text:
using System;

namespace LeanTest.Attribute
{
    /// The test tag attribute.
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    public class TestTagAttribute : System.Attribute, IAttributeValue
    {
        /// A prefix put in a .trx-file before each tag value.
        public const string Prefix = @"TestTag = ###---";
        /// A postfix put in a .trx-file after each tag value.
        public const string Postfix = @"---###";
        /// Put in a .trx-file for each 'not implemented' tag value.
        public const string NotImplemented = @"LeanTest.NotImplemented";

        /// <inheritdoc />
        public TestTagAttribute(string value) => Value = value;
        /// The value.
        public string Value { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: "NeoPixel sur Raspberry Pi"
modified:
categories:
excerpt:
tags: []
image:
     feature:
date: 2018-04-22T12:33:00+02:00
published: true
author: Nico
---

Voici comment configurer un Raspberry Pi pour l'utiliser avec des LED NeoPixel WS281x. Je présente la version Python, mais d'autres langages sont supportés.

[![NeoPixel sur Raspberry Pi][image-1]][image-1]

> Les deux câbles brun et bleu à droite du *breadboard* sont connectés à une alimentation 5 V.

## Sources

Les informations de cet article proviennent des sources suivantes :

- [Adafruit NeoPixels On Raspberry Pi][Adafruit NeoPixels On Raspberry Pi]
- [rpi_ws281x from jgarff on GitHub][rpi_ws281x from jgarff on GitHub]

## Câblage

Le Rpi fonctionne en 3.3 V et les NeoPixels en 5 V. Il est donc nécessaire d'utiliser un *logic level converter*. Les données sont transmises aux LED depuis la broche 18 du Rpi.

L'anneau de LED a 4 connexions :

- DI (signal)
- 5 V
- GND
- DO (pas connecté)

## Matériel

- [Anneau de 24 LED WS2812 — NeoPixel][Anneau de 24 LED WS2812 — NeoPixel]
- [Logic Level Converter][Logic Level Converter]
- Raspberry Pi 2 Model B / Raspbian Stretch
- Raspberry Pi 3 Model B / Raspbian Jessie

## Compilation et installation de la librairie `rpi_ws281x`

    sudo apt-get update
    sudo apt-get install build-essential python-dev git scons swig
    git clone https://github.com/jgarff/rpi_ws281x.git
    cd rpi_ws281x
    scons
    cd python
    sudo python setup.py install

## Édition du fichier `strandtest.py`

    nano strandtest.py

Modifier la variable `LED_COUNT`

    LED_COUNT   = 24

## Utilisation du PWM

Comme la bibliothèque `rpi_ws281x` et l'audio du board du Raspberry utilisent tous les deux le PWM, elles ne peuvent pas être utilisées ensemble. Pour désactiver l'audio, il faut mettre le module du kernel audio de Broadcom dans une liste noire. Pour cela, il faut créer le fichier `snd-blacklist.conf` :

    sudo nano /etc/modprobe.d/snd-blacklist.conf

Et lui ajouter la commande suivante :

    blacklist snd_bcm2835

> Il faut se rappeler de commenter cette ligne si on veut utiliser l'audio dans d'autres projets !

Et finalement, il faut redémarrer le Rpi :

    sudo reboot

## Test

Maintenant que le Rpi est redémarré, on va dans le répertoire des exemples :

    cd ~/rpi_ws281x/python/examples

Et on exécute l'exemple `strandtest.py`. L'instruction `sudo` est requise car la bibliothèque `rpi_ws281x` utilise des fonctions de bas niveau et doit donc être exécutée avec les droits de `root` :

    sudo python strandtest.py

## Utilisation du CPU

Voici ce que me retourne la commande `top`. On voit que le processus `python` consomme 1.6% des ressources CPU sur un Raspberry Pi 3 modèle B. Pour pouvoir lancer cette commande, il faut faire tourner `strandtest.py` dans un autre shell avec la commande [`screen`][GNU Screen sur ouilogique.com].

    top - 13:30:48 up 14 min,  3 users,  load average: 0.19, 0.09, 0.02
    Tasks: 155 total,   1 running, 154 sleeping,   0 stopped,   0 zombie
    %Cpu(s):  0.7 us,  0.2 sy,  0.0 ni, 99.2 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
    KiB Mem:    945512 total,   327704 used,   617808 free,    25008 buffers
    KiB Swap:   102396 total,        0 used,   102396 free.   207116 cached Mem

      PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
     3438 root      20   0   14236  10712   5960 S   1.6  1.1   0:02.39 python
     3439 pi        20   0    5276   2520   2020 R   0.7  0.3   0:00.60 top
        1 root      20   0   22780   3952   2788 S   0.0  0.4   0:02.85 systemd
        2 root      20   0       0      0      0 S   0.0  0.0   0:00.00 kthreadd

[image-1]: ../../files/2018-04-22-neopixel-raspberry-pi/2018-04-22-neopixel-raspberry-pi-001_lowres.jpg

[Adafruit NeoPixels On Raspberry Pi]: https://learn.adafruit.com/neopixels-on-raspberry-pi/software

[rpi_ws281x from jgarff on GitHub]: https://github.com/jgarff/rpi_ws281x

[Anneau de 24 LED WS2812 — NeoPixel]: https://www.banggood.com/CJMCU-24-Bit-WS2812-5050-RGB-LED-Driver-Development-Board-p-974188.html?p=0431091025639201412F)

[Logic Level Converter]: https://www.banggood.com/Logic-Level-Converter-Bi-Directional-IIC-4-Way-Level-Conversion-Module-p-938774.html?p=0431091025639201412F)

[GNU Screen sur ouilogique.com]: https://ouilogique.com/installer-raspian-stretch/#gnu-screen


text:
/*

This example reads from the default PCM device
and writes to standard output for 5 seconds of data.

*/

/* Use the newer ALSA API */
#define ALSA_PCM_NEW_HW_PARAMS_API

#include <alsa/asoundlib.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char * argv[]) {
  long capture_loops;
  int capture_rc;
  int capture_size;
  snd_pcm_t *capture_handle;
  snd_pcm_hw_params_t *capture_params;
  unsigned int sample_rate;
  int capture_dir;
  snd_pcm_uframes_t capture_frames;
  char *capture_buffer;

  /* Open PCM device for recording (capture). */
  capture_rc = snd_pcm_open(&capture_handle, argv[1],
                    SND_PCM_STREAM_CAPTURE, 0);
  if (capture_rc < 0) {
    fprintf(stderr,
            "unable to open record pcm device: %s\n",
            snd_strerror(capture_rc));
    exit(1);
  }

  /* Allocate a hardware parameters object. */
  snd_pcm_hw_params_alloca(&capture_params);

  /* Fill it in with default values. */
  snd_pcm_hw_params_any(capture_handle, capture_params);

  /* Set the desired hardware parameters. */

  /* Interleaved mode */
  snd_pcm_hw_params_set_access(capture_handle, capture_params,
                      SND_PCM_ACCESS_RW_INTERLEAVED);

  /* Signed 16-bit little-endian format */
  snd_pcm_hw_params_set_format(capture_handle, capture_params,
                              SND_PCM_FORMAT_S16_LE);

  /* Two channels (stereo) */
  snd_pcm_hw_params_set_channels(capture_handle, capture_params, 2);

  /* 44100 bits/second sampling rate (CD quality) */
  sample_rate = 44100;
  snd_pcm_hw_params_set_rate_near(capture_handle, capture_params,
                                  &sample_rate, &capture_dir);

  /* Set period size to 32 frames. */
  capture_frames = 2;
  snd_pcm_hw_params_set_period_size_near(capture_handle,
                              capture_params, &capture_frames, &capture_dir);

  /* Write the parameters to the driver */
  capture_rc = snd_pcm_hw_params(capture_handle, capture_params);
  if (capture_rc < 0) {
    fprintf(stderr,
            "unable to set input hw parameters: %s\n",
            snd_strerror(capture_rc));
    exit(1);
  }

  /* Use a buffer large enough to hold one period */
  snd_pcm_hw_params_get_period_size(capture_params,
                                      &capture_frames, &capture_dir);
  capture_size = capture_frames * 4; /* 2 bytes/sample, 2 channels */
  capture_buffer = (char *) malloc(capture_size);

  /* We want to loop for 5 seconds */
  snd_pcm_hw_params_get_period_time(capture_params,
                                         &sample_rate, &capture_dir);
  capture_loops = 5000000 / sample_rate;

  //Output init

  int output_rc;
  int output_size;
  snd_pcm_t *output_handle;
  snd_pcm_hw_params_t *output_params;
  unsigned int output_val;
  int output_dir;
  snd_pcm_uframes_t output_frames;
  char *output_buffer;

  /* Open PCM device for playback. */
  output_rc = snd_pcm_open(&output_handle, argv[2],
                    SND_PCM_STREAM_PLAYBACK, 0);
  if (output_rc < 0) {
    fprintf(stderr,
            "unable to open output pcm device: %s\n",
            snd_strerror(output_rc));
    exit(1);
  }

  /* Allocate a hardware parameters object. */
  snd_pcm_hw_params_alloca(&output_params);

  /* Fill it in with default values. */
  snd_pcm_hw_params_any(output_handle, output_params);

  /* Set the desired hardware parameters. */

  /* Interleaved mode */
  snd_pcm_hw_params_set_access(output_handle, output_params,
                      SND_PCM_ACCESS_RW_INTERLEAVED);

  /* Signed 16-bit little-endian format */
  snd_pcm_hw_params_set_format(output_handle, output_params,
                              SND_PCM_FORMAT_S16_LE);

  /* Two channels (stereo) */
  snd_pcm_hw_params_set_channels(output_handle, output_params, 2);

  /* 44100 bits/second sampling rate (CD quality) */
  output_val = 44100;
  snd_pcm_hw_params_set_rate_near(output_handle, output_params,
                                  &output_val, &output_dir);

  /* Set period size to 32 frames. */
  output_frames = 32;
  snd_pcm_hw_params_set_period_size_near(output_handle,
                              output_params, &output_frames, &output_dir);

  /* Write the parameters to the driver */
  output_rc = snd_pcm_hw_params(output_handle, output_params);
  if (output_rc < 0) {
    fprintf(stderr,
            "unable to set output hw parameters: %s\n",
            snd_strerror(output_rc));
    exit(1);
  }

  //DIY DNC stuffs

  int look_back_length = 3;

  float prevRms = 0;
  float targetRms = 0.7;
  float currentRms = 0;

  //previous S_max
  float prev_gain;

  int firstRun = 1;

  //amount of gain to add
  float gain;
  float maxGain = 10;
  //max magnitude of frame
  float S_max = 0;
  //max magnitude of peak
  float Peak = 0.95f;
  //G[n]=Peak/abs(S_max[n])

  /*
  const uint32_t channels = 2;
  const uint32_t sampleRate = 44100;
  const uint32_t frameLenMsec = 100;
  const uint32_t filterSize = 15; //default 31
  const double peakValue = 0.95f; //0.95 default
  const double maxAmplification = 10f;
  //user input
  const double targetRms = 0.8f; // range from 0 to 1

  const bool channelsCoupled = true;
  const bool enableDCCorrection = false;
  const bool altBoundaryMode = false;
  FILE *const logFile = NULL;

  MDynamicAudioNormalizer_Handle* mdanHandle = createInstance(channels,sampleRate, frameLenMsec,filterSize,peakValue,maxAmplification, targetRms, compressFactor, channelsCoupled, enableDCCorrection, altBoundaryMode, logFile);

  */

  while (1) {
    capture_rc = snd_pcm_readi(capture_handle, capture_buffer, capture_frames);
    if (capture_rc == -EPIPE) {
      /* EPIPE means overrun */
      fprintf(stderr, "overrun occurred\n");
      snd_pcm_prepare(capture_handle);
    } else if (capture_rc < 0) {
      fprintf(stderr,
              "error from read: %s\n",
              snd_strerror(capture_rc));
    } else if (capture_rc != (int)capture_frames) {
      fprintf(stderr, "short read, read %d frames\n", capture_rc);
    }

    //output_rc = snd_pcm_writei(output_handle, capture_buffer, capture_frames);

    /*
    char leftChannel[(capture_size/2)];
    char rightChannel[(capture_size/2)];
    double leftBuffer[(capture_size/2)];
    double rightBuffer[(capture_size/2)];

    double inputSamples[2][capture_size/2];
    */
    short inputSamples[2][capture_size/2];

    //extract left and right channels into their buffers
    //temp buffer for conversion to float
    char temp[2];
    S_max = 0;
    for(int i = 0; i < capture_frames; i++){
      /*
        leftChannel[i] = capture_buffer[(i*4)];
        leftChannel[i] = capture_buffer[(i*4)+1];
        rightChannel[i] = capture_buffer[(i*4)+2];
        rightChannel[i] = capture_buffer[(i*4)+3];
      */
      temp[0] = capture_buffer[i*4];
      temp[1] = capture_buffer[i*4+1];
      inputSamples[0][i] = (short)(temp[0] + temp[1]*256 - 32767); // 32767;

      temp[0] = capture_buffer[i*4+2];
      temp[1] = capture_buffer[i*4+3];
      inputSamples[1][i] = (short)(temp[0] + temp[1]*256 - 32767); // 32767;

      //sanitization
      if(inputSamples[0][i] > 1){
        inputSamples[0][i] = 1;
      }
      else if(inputSamples[0][i] < -1){
        inputSamples[0][i] = -1;
      }

      //sanitization
      if(inputSamples[1][i] > 1){
        inputSamples[1][i] = 1;
      }
      else if(inputSamples[1][i] < -1){
        inputSamples[1][i] = -1;
      }

      if(inputSamples[0][i] > S_max){
          S_max = inputSamples[0][i];
      }
      if( abs(inputSamples[1][i]) > S_max){
          S_max = abs(inputSamples[1][i]);
      }

    }

    gain = Peak / S_max;

    if(gain > maxGain){
      gain = maxGain;
    }

    //printf("%f\n", gain);

    //smoothen the gain

    prev_gain = gain;

    //limit the rms of the entire buffer
    //currentRms = sqrt(    );

    //convert from 1.0 to -1 back to 2byte units
    //little endian
    signed short int tempSum = 0;

    char output[capture_size];

    for(int i = 0; i < capture_frames; i++){
      //left
      tempSum = (inputSamples[0][i]) + 32767;

      char small = tempSum%256;
      char big = tempSum/256;

      output[i*4] = small;
      output[i*4+1] = big;

      //right
      tempSum = (inputSamples[1][i]) + 32767;

      small = tempSum%256;
      big = tempSum/256;

      output[i*4+2] = small;
      output[i*4+3] = big;

    }

    output_rc = snd_pcm_writei(output_handle, output, capture_frames);

    if (output_rc == -EPIPE) {
      /* EPIPE means underrun */
      fprintf(stderr, "underrun occurred\n");
      snd_pcm_prepare(output_handle);
    } else if (output_rc < 0) {
      fprintf(stderr,
              "error from writei: %s\n",
              snd_strerror(output_rc));
    }  else if (output_rc != (int)capture_frames) {
      fprintf(stderr,
              "short write, write %d frames\n", output_rc);
    }

  }

  snd_pcm_drain(output_handle);
  snd_pcm_close(output_handle);
  free(output_buffer);

  // snd_pcm_drain(capture_handle);
  // snd_pcm_close(capture_handle);
  // free(capture_buffer);

  return 0;
}


text:
package com.thinkbiganalytics.feedmgr.nifi.controllerservice;

import org.apache.nifi.web.api.dto.ControllerServiceDTO;

import java.util.Objects;

import javax.annotation.Nonnull;

/**
 * Manages the properties for connecting to a data source managed by a controller service.
 */
public abstract class AbstractControllerServiceRequest {
    private String connectionStringPropertyKey;
    private String driverLocationsKey;
    private String userNamePropertyKey;
    private String passwordPropertyKey;
    private String driverClassNamePropertyKey;
    private String controllerServiceType;
    private String controllerServiceName;
    private String controllerServiceId;
    private ControllerServiceDTO controllerServiceDTO;
    private String password;
    private boolean useEnvironmentProperties;

    public String getConnectionStringPropertyKey() {
        return connectionStringPropertyKey;
    }

    public void setConnectionStringPropertyKey(String connectionStringPropertyKey) {
        this.connectionStringPropertyKey = connectionStringPropertyKey;
    }

    public String getUserNamePropertyKey() {
        return userNamePropertyKey;
    }

    public void setUserNamePropertyKey(String userNamePropertyKey) {
        this.userNamePropertyKey = userNamePropertyKey;
    }

    public String getPasswordPropertyKey() {
        return passwordPropertyKey;
    }

    public void setPasswordPropertyKey(String passwordPropertyKey) {
        this.passwordPropertyKey = passwordPropertyKey;
    }

    public String getDriverClassNamePropertyKey() {
        return driverClassNamePropertyKey;
    }

    public void setDriverClassNamePropertyKey(String driverClassNamePropertyKey) {
        this.driverClassNamePropertyKey = driverClassNamePropertyKey;
    }

    public String getControllerServiceType() {
        return controllerServiceType;
    }

    public void setControllerServiceType(String controllerServiceType) {
        this.controllerServiceType = controllerServiceType;
    }

    public String getControllerServiceName() {
        return controllerServiceName;
    }

    public void setControllerServiceName(String controllerServiceName) {
        this.controllerServiceName = controllerServiceName;
    }

    public String getControllerServiceId() {
        return controllerServiceId;
    }

    public void setControllerServiceId(String controllerServiceId) {
        this.controllerServiceId = controllerServiceId;
    }

    public ControllerServiceDTO getControllerServiceDTO() {
        return controllerServiceDTO;
    }

    public void setControllerServiceDTO(ControllerServiceDTO controllerServiceDTO) {
        this.controllerServiceDTO = controllerServiceDTO;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean useEnvironmentProperties() {
        return useEnvironmentProperties;
    }

    public void setUseEnvironmentProperties(boolean useEnvironmentProperties) {
        this.useEnvironmentProperties = useEnvironmentProperties;
    }

    public String getDriverLocationsKey() {
        return driverLocationsKey;
    }

    public void setDriverLocationsKey(String driverLocationsKey) {
        this.driverLocationsKey = driverLocationsKey;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        AbstractControllerServiceRequest that = (AbstractControllerServiceRequest) o;
        return Objects.equals(connectionStringPropertyKey, that.connectionStringPropertyKey) &&
               Objects.equals(controllerServiceName, that.controllerServiceName) &&
               Objects.equals(controllerServiceId, that.controllerServiceId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(connectionStringPropertyKey, controllerServiceName, controllerServiceId);
    }

    public abstract static class AbstractControllerServiceRequestBuilder<T extends AbstractControllerServiceRequestBuilder<T>> {

        private String connectionStringPropertyKey;
        private String driverLocationsKey;
        private String userNamePropertyKey;
        private String passwordPropertyKey;
        private String driverClassNamePropertyKey;
        private String controllerServiceType;
        private String controllerServiceName;
        private String controllerServiceId;
        private ControllerServiceDTO controllerServiceDTO;
        private String password;
        private boolean useEnvironmentProperties = true;

        protected AbstractControllerServiceRequestBuilder(@Nonnull final ControllerServiceDTO controllerServiceDTO) {
            this.controllerServiceDTO = controllerServiceDTO;
            this.controllerServiceType = controllerServiceDTO != null ? controllerServiceDTO.getType() : null;
            this.controllerServiceId = controllerServiceDTO != null ? controllerServiceDTO.getId() : null;
            this.controllerServiceName = controllerServiceDTO != null ? controllerServiceDTO.getName() : null;
            initializePropertiesFromControllerServiceType();
        }

        public T connectionStringPropertyKey(String connectionStringPropertyKey) {
            this.connectionStringPropertyKey = connectionStringPropertyKey;
            return (T) this;
        }

        public T userNamePropertyKey(String userNamePropertyKey) {
            this.userNamePropertyKey = userNamePropertyKey;
            return (T) this;
        }

        public T passwordPropertyKey(String passwordPropertyKey) {
            this.passwordPropertyKey = passwordPropertyKey;
            return (T) this;
        }

        public T driverClassNamePropertyKey(String driverClassNamePropertyKey) {
            this.driverClassNamePropertyKey = driverClassNamePropertyKey;
            return (T) this;
        }

        public T driverLocationsKey(String driverLocationsKey) {
            this.driverLocationsKey = driverLocationsKey;
            return (T) this;
        }

        public T controllerServiceType(String controllerServiceType) {
            this.controllerServiceType = controllerServiceType;
            return (T) this;
        }

        private void initializePropertiesFromControllerServiceType() {
            if ("org.apache.nifi.dbcp.DBCPConnectionPool".equalsIgnoreCase(controllerServiceType)) {
                this.connectionStringPropertyKey = "Database Connection URL";
                this.userNamePropertyKey = "Database User";
                this.passwordPropertyKey = "Password";
                this.driverClassNamePropertyKey = "Database Driver Class Name";
                this.driverLocationsKey = "database-driver-locations";
            } else if ("com.thinkbiganalytics.nifi.v2.sqoop.StandardSqoopConnectionService".equalsIgnoreCase(controllerServiceType)) {
                this.connectionStringPropertyKey = "Source Connection String";
                this.userNamePropertyKey = "Source User Name";
                this.passwordPropertyKey = "Password";  // users will need to add this as a different property to the application.properties file
            }
        }

        public T controllerService(ControllerServiceDTO controllerServiceDTO) {
            this.controllerServiceDTO = controllerServiceDTO;
            return (T) this;
        }

        public T controllerServiceName(String controllerServiceName) {
            this.controllerServiceName = controllerServiceName;
            return (T) this;
        }

        public T controllerServiceId(String controllerServiceId) {
            this.controllerServiceId = controllerServiceId;
            return (T) this;
        }

        public T password(String password) {
            this.password = password;
            return (T) this;
        }

        public T useEnvironmentProperties(boolean useEnvironmentProperties) {
            this.useEnvironmentProperties = useEnvironmentProperties;
            return (T) this;
        }

        @Nonnull
        protected <R extends AbstractControllerServiceRequest> T using(@Nonnull final R request) {
            this.connectionStringPropertyKey(request.getConnectionStringPropertyKey());
            this.connectionStringPropertyKey(request.getConnectionStringPropertyKey());
            this.controllerServiceName(request.getControllerServiceName());
            this.controllerServiceId(request.getControllerServiceId());
            this.controllerServiceType(request.getControllerServiceType());
            this.userNamePropertyKey(request.getUserNamePropertyKey());
            this.passwordPropertyKey(request.getPasswordPropertyKey());
            this.controllerService(request.getControllerServiceDTO());
            this.driverClassNamePropertyKey(request.getDriverClassNamePropertyKey());
            this.password(request.getPassword());
            this.useEnvironmentProperties(request.useEnvironmentProperties());
            this.driverLocationsKey(request.getDriverLocationsKey());
            return (T) this;
        }

        @Nonnull
        protected <R extends AbstractControllerServiceRequest> R build(@Nonnull final R request) {
            request.setConnectionStringPropertyKey(this.connectionStringPropertyKey);
            request.setControllerServiceName(this.controllerServiceName);
            request.setControllerServiceId(this.controllerServiceId);
            request.setControllerServiceType(this.controllerServiceType);
            request.setUserNamePropertyKey(userNamePropertyKey);
            request.setPasswordPropertyKey(passwordPropertyKey);
            request.setControllerServiceDTO(this.controllerServiceDTO);
            request.setDriverClassNamePropertyKey(this.driverClassNamePropertyKey);
            request.setPassword(password);
            request.setUseEnvironmentProperties(useEnvironmentProperties);
            request.setDriverLocationsKey(driverLocationsKey);
            return request;
        }
    }
}


text:
from fabric.api import cd, sudo
from fabric.contrib.files import exists

from shuttle.services.service import Service
from shuttle.hooks import hook
from shuttle.shared import apt_get_install, pip_install, SiteType

# http://dev.maxmind.com/geoip/legacy/geolite/
_CITY_PACKAGE_URL = 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz'
_COUNTRY_PACKAGE_URL = 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz'
_INSTALL_DIR = '/opt/geoip'

class GeoIP(Service):
    """Database to convert ip addresses into locations."""
    name = 'geoip'
    script = None

    def install(self):
        with hook('install %s' % self.name, self):
            if not exists(_INSTALL_DIR):
                apt_get_install('libgeoip1')
                sudo('mkdir %s' % _INSTALL_DIR)
                with cd(_INSTALL_DIR):
                    sudo('wget --no-clobber %s' % _CITY_PACKAGE_URL)
                    sudo('wget --no-clobber %s' % _COUNTRY_PACKAGE_URL)
                    sudo('gunzip %s' % _CITY_PACKAGE_URL.split('/')[-1])
                    sudo('gunzip %s' % _COUNTRY_PACKAGE_URL.split('/')[-1])

    def get_site_settings(self, site):
        if site['type'] == SiteType.DJANGO:
            return { 'GEOIP_PATH': _INSTALL_DIR }
        else:
            return super(GeoIP, self).get_site_settings(site)


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <View
        android:id="@+id/boundary"
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:layout_centerInParent="true" />

    <TextView
        android:id="@+id/hideText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/boundary"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="20dp"
        android:paddingTop="5dp"
        android:text="@string/hide" />

    <ImageButton
        android:id="@+id/encryptButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/hideText"
        android:layout_centerHorizontal="true"
        android:background="@drawable/lock"
        android:contentDescription="@string/encrypt_button_desc"
        android:src="@drawable/lock_selector" />

    <ImageButton
        android:id="@+id/decryptButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/boundary"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:background="@drawable/lock_open"
        android:contentDescription="@string/decrypt_button_desc"
        android:src="@drawable/lock_open_selector" />

    <TextView
        android:id="@+id/discoverText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/decryptButton"
        android:layout_centerHorizontal="true"
        android:paddingTop="5dp"
        android:text="@string/retrieve" />

</RelativeLayout>


text:
import { throwIfAborted } from '../aborterror';
import { wrapWithAbort } from './operators/withabort';

export async function extremaBy<TSource, TKey>(
  source: AsyncIterable<TSource>,
  selector: (item: TSource, signal?: AbortSignal) => TKey | Promise<TKey>,
  comparer: (left: TKey, right: TKey, signal?: AbortSignal) => number | Promise<number>,
  signal?: AbortSignal
): Promise<TSource[]> {
  throwIfAborted(signal);

  let result = [];
  const it = wrapWithAbort(source, signal)[Symbol.asyncIterator]();
  const { value, done } = await it.next();
  if (done) {
    throw new Error('Sequence contains no elements');
  }

  let resKey = await selector(value, signal);
  result.push(value);

  let next: IteratorResult<TSource>;
  while (!(next = await it.next()).done) {
    const current = next.value;
    const key = await selector(current, signal);
    const cmp = await comparer(key, resKey, signal);

    if (cmp === 0) {
      result.push(current);
    } else if (cmp > 0) {
      result = [current];
      resKey = key;
    }
  }

  return result;
}


text:
public @interface Spec {
    String pre();
    String post();
}


text:
module.exports = {
  detect: function() {
    return !!process.env.SEMAPHORE && !!process.env.SEMAPHORE_REPO_SLUG
  },

  configuration: function() {
    console.log('    Semaphore 1.x CI Detected')
    return {
      service: 'semaphore',
      build:
        process.env.SEMAPHORE_BUILD_NUMBER +
        '.' +
        process.env.SEMAPHORE_CURRENT_THREAD,
      commit: process.env.REVISION,
      branch: process.env.BRANCH_NAME,
      slug: process.env.SEMAPHORE_REPO_SLUG,
    }
  },
}


text:
package de.uniwuerzburg.info3.ofcprobe.vswitch.graphml;

import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author christian rachor
 */
public class Node {

    private static final Logger logger = LoggerFactory.getLogger(Node.class);

    private ArrayList<Integer> idlist;

    private int number;

    private String name;
    private String country;

    private double longitude;
    private double latitude;

    /**
     * Constructor
     *
     * @param number
     * @param name
     * @param id
     * @param country
     * @param longitude
     * @param latitude
     */
    public Node(int number, String name, int id, String country, double longitude, double latitude) {
        super();
        this.name = name;
        this.country = country;
        this.longitude = longitude;
        this.latitude = latitude;
        this.idlist = new ArrayList<>();
        this.idlist.add(id);
        this.setNumber(number);
    }

    /**
     * Get IDs
     *
     * @return the IDs
     */
    public ArrayList<Integer> getIds() {
        return this.idlist;
    }

    /**
     * Add ID
     *
     * @param id the id
     */
    public void addId(int id) {
        this.idlist.add(id);
    }

    /**
     * Prints ID
     */
    public void printIds() {
        System.out.print(name + ":");
        for (int i : idlist) {
            System.out.print(" " + i);
        }
        System.out.println();
    }

    /**
     * Gets the Node Name
     *
     * @return the Node Name
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the Node Name
     *
     * @param name the Node Name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Gets the Country the Node is in
     *
     * @return the Country
     */
    public String getCountry() {
        return country;
    }

    /**
     * Sets the Country the Node is in
     *
     * @param country the Country
     */
    public void setCountry(String country) {
        this.country = country;
    }

    /**
     * Get Longitude Location of Node
     *
     * @return the Longitude location
     */
    public double getLongitude() {
        return longitude;
    }

    /**
     * Set the Longitude Location of Node
     *
     * @param longitude the Longitude Location
     */
    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    /**
     * Get Latitude Location of the Node
     *
     * @return the Latitude Location
     */
    public double getLatitude() {
        return latitude;
    }

    /**
     * Set Latitude Location of the Node
     *
     * @param latitude
     */
    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    /**
     * Gets the Node Number
     *
     * @return the Number
     */
    public int getNumber() {
        return number;
    }

    /**
     * Sets the Node Number
     *
     * @param number
     */
    public void setNumber(int number) {
        this.number = number;
    }
}


text:
const crypto = require("crypto");
const ServiceBroker = require("../../../../src/service-broker");
const Middleware = require("../../../../src/middlewares").Transmit.Encryption;

describe("Test EncryptionMiddleware", () => {
	const broker = new ServiceBroker({ logger: false });
	const password = "mw-test";

	it("should register hooks", () => {
		const mw = Middleware(password);
		expect(mw.transporterSend).toBeInstanceOf(Function);
		expect(mw.transporterReceive).toBeInstanceOf(Function);
	});

	it("should encrypt the data", () => {
		const mw = Middleware(password);

		const meta = {};
		const next = jest.fn();
		const send = mw.transporterSend.call(broker, next);
		const encrypter = crypto.createCipher("aes-256-cbc", password);

		send("topic", Buffer.from("plaintext data"), meta);

		expect(next).toHaveBeenCalledTimes(1);
		expect(next).toHaveBeenCalledWith("topic", expect.any(Buffer), meta);
		expect(next.mock.calls[0][1]).toEqual(Buffer.concat([encrypter.update("plaintext data"), encrypter.final()]));
	});

	it("should encrypt the data with IV", () => {
		const pass = crypto.randomBytes(32);
		const iv = crypto.randomBytes(16);
		const mw = Middleware(pass, "aes-256-ctr", iv);

		const meta = {};
		const next = jest.fn();
		const send = mw.transporterSend.call(broker, next);
		const encrypter = crypto.createCipheriv("aes-256-ctr", pass, iv);

		send("topic", Buffer.from("plaintext data"), meta);

		expect(next).toHaveBeenCalledTimes(1);
		expect(next).toHaveBeenCalledWith("topic", expect.any(Buffer), meta);
		expect(next.mock.calls[0][1]).toEqual(Buffer.concat([encrypter.update("plaintext data"), encrypter.final()]));
	});

	it("should decrypt data with IV", () => {
		const mw = Middleware(password);

		const meta = {};
		const next = jest.fn();
		const receive = mw.transporterReceive.call(broker, next);
		const encrypter = crypto.createCipher("aes-256-cbc", password);
		const encryptedData = Buffer.concat([encrypter.update("plaintext data"), encrypter.final()]);

		receive("topic", encryptedData, meta);
		expect(next).toHaveBeenCalledTimes(1);
		expect(next).toHaveBeenCalledWith("topic", Buffer.from("plaintext data"), meta);
	});

	it("should decrypt data", () => {
		const pass = crypto.randomBytes(32);
		const iv = crypto.randomBytes(16);
		const mw = Middleware(pass, "aes-256-ctr", iv);

		const meta = {};
		const next = jest.fn();
		const receive = mw.transporterReceive.call(broker, next);
		const encrypter = crypto.createCipheriv("aes-256-ctr", pass, iv);
		const encryptedData = Buffer.concat([encrypter.update("plaintext data"), encrypter.final()]);

		receive("topic", encryptedData, meta);
		expect(next).toHaveBeenCalledTimes(1);
		expect(next).toHaveBeenCalledWith("topic", Buffer.from("plaintext data"), meta);
	});

});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Rabenhorst, Rabenh. Krypt. -Fl. (Leipzig) 6: 78 (1901)

#### Original name
Phyllosticta cinerea Pass.

### Remarks
null


text:
package cgeo.geocaching.utils;

import cgeo.geocaching.R;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.storage.ContentStorage;
import cgeo.geocaching.storage.PersistableFolder;
import cgeo.geocaching.ui.dialog.Dialogs;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.concurrent.atomic.AtomicReference;

import io.reactivex.rxjava3.schedulers.Schedulers;

public class DebugUtils {

    private DebugUtils() {
        // utility class
    }

    public static void createMemoryDump(@NonNull final Context context) {
        Toast.makeText(context, R.string.init_please_wait, Toast.LENGTH_LONG).show();
        final File file = ContentStorage.get().createTempFile();

        new Handler(Looper.getMainLooper()).postDelayed(() -> {
                try {
                    android.os.Debug.dumpHprofData(file.getPath());
                } catch (IOException e) {
                    Log.e("createMemoryDump", e);
                }
            final Uri dumpFileUri = ContentStorage.get().writeFileToFolder(PersistableFolder.LOGFILES, FileNameCreator.MEMORY_DUMP, file, true);

            ShareUtils.shareOrDismissDialog(context, dumpFileUri, "*/*", R.string.init_memory_dump, context.getString(R.string.init_memory_dumped, UriUtils.toUserDisplayableString(dumpFileUri)));
                }, 1000);
    }

    public static void askUserToReportProblem(@NonNull final Activity context, @Nullable final String errorMsg) {
        final StringBuilder message = new StringBuilder();
        if (errorMsg != null) {
            message.append(context.getString(R.string.debug_user_error_errortext)).append("\n[")
                .append(errorMsg).append("]\n\n");
            Log.w("User was asked to report problem: " + errorMsg);
        }
        message.append(context.getString(R.string.debug_user_error_explain_options));

        Dialogs.confirmPositiveNegativeNeutral(
            context,
            context.getString(R.string.debug_user_error_report_title),
            message.toString(),
            context.getString(R.string.about_system_info_send_button),
            null,
            context.getString(android.R.string.cancel),
            (dialog, which) -> createLogcatHelper(context, true, true,
                errorMsg == null ? null : context.getString(R.string.debug_user_error_report_title) + ": " + errorMsg),
            null,
            null);
    }

    public static void createLogcat(@NonNull final Activity activity) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            // no differentiation possible on older systems, so no need to ask
            createLogcatHelper(activity, true, false, null);
        } else {
            Dialogs.confirmPositiveNegativeNeutral(
                    activity,
                    activity.getString(R.string.about_system_write_logcat),
                    activity.getString(R.string.about_system_write_logcat_type),
                    activity.getString(R.string.about_system_write_logcat_type_standard),
                    null,
                    activity.getString(R.string.about_system_write_logcat_type_extended),
                    (dialog, which) -> createLogcatHelper(activity, false, false, null),
                    null,
                    (dialog, which) -> createLogcatHelper(activity, true, false, null));
        }
    }

    public static void dumpDownloadmanagerInfos(@NonNull final Activity activity) {
        final DownloadManager downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        final DownloadManager.Query query = new DownloadManager.Query();
        final StringBuilder sb = new StringBuilder();
        try (Cursor c = downloadManager.query(query)) {
            final int columnStatus = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
            final int columnReason = c.getColumnIndex(DownloadManager.COLUMN_REASON);
            final int[] columns = {
                c.getColumnIndex(DownloadManager.COLUMN_ID),
                c.getColumnIndex(DownloadManager.COLUMN_TITLE),
                columnStatus,
                columnReason,
                c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR),
                c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES),
                c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP),
                c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE),
                c.getColumnIndex(DownloadManager.COLUMN_URI),
                c.getColumnIndex(DownloadManager.COLUMN_MEDIAPROVIDER_URI),
                c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)
            };
            while (c.moveToNext()) {
                for (int column : columns) {
                    sb.append(c.getColumnName(column)).append(" = ");
                    if (column == columnStatus) {
                        sb.append(c.getString(column));
                        final int status = c.getInt(column);
                        if (status == DownloadManager.STATUS_FAILED) {
                            sb.append(" - download has failed (and will not be retried)");
                        } else if (status == DownloadManager.STATUS_PAUSED) {
                            sb.append(" - download is waiting to retry or resume");
                        } else if (status == DownloadManager.STATUS_PENDING) {
                            sb.append(" - download is waiting to start");
                        } else if (status == DownloadManager.STATUS_RUNNING) {
                            sb.append(" - download is currently running");
                        } else if (status == DownloadManager.STATUS_SUCCESSFUL) {
                            sb.append(" - download has successfully completed");
                        }
                    } else if (column == columnReason) {
                        final int reason = c.getInt(column);
                        sb.append(reason);
                        if (reason == DownloadManager.PAUSED_QUEUED_FOR_WIFI) {
                            sb.append(" - paused: download exceeds a size limit for downloads over mobile network / waiting for Wifi");
                        } else if (reason == DownloadManager.PAUSED_UNKNOWN) {
                            sb.append(" - paused: for some other reason");
                        } else if (reason == DownloadManager.PAUSED_WAITING_FOR_NETWORK) {
                            sb.append(" - paused: waiting for network connectivity to proceed");
                        } else if (reason == DownloadManager.PAUSED_WAITING_TO_RETRY) {
                            sb.append(" - paused: some network error occurred and the download manager is waiting before retrying the request");
                        } else if (reason == DownloadManager.ERROR_CANNOT_RESUME) {
                            sb.append(" - error: some possibly transient error occurred but we can't resume the download");
                        } else if (reason == DownloadManager.ERROR_DEVICE_NOT_FOUND) {
                            sb.append(" - error: no external storage device was found. SD card mounted?");
                        } else if (reason == DownloadManager.ERROR_FILE_ALREADY_EXISTS) {
                            sb.append(" - error: requested destination file already exists, will not be overwritten");
                        } else if (reason == DownloadManager.ERROR_FILE_ERROR) {
                            sb.append(" - error: unknown storage issue");
                        } else if (reason == DownloadManager.ERROR_HTTP_DATA_ERROR) {
                            sb.append(" - error: HTTP processing error at data level");
                        } else if (reason == DownloadManager.ERROR_INSUFFICIENT_SPACE) {
                            sb.append(" - error: insufficient storage space");
                        } else if (reason == DownloadManager.ERROR_TOO_MANY_REDIRECTS) {
                            sb.append(" - error: too many redirects");
                        } else if (reason == DownloadManager.ERROR_UNHANDLED_HTTP_CODE) {
                            sb.append(" - error: unhandled HTTP cod");
                        } else if (reason == DownloadManager.ERROR_UNKNOWN) {
                            sb.append(" - error: unknown error");
                        }

                    } else {
                        sb.append(c.getString(column));
                    }
                    sb.append("\n");
                }
                sb.append("\n------------------------\n\n");
            }
        }
        Dialogs.message(activity, "current downloads", sb.toString());
    }

    private static void createLogcatHelper(@NonNull final Activity activity, final boolean fullInfo, final boolean forceEmail, final String additionalMessage) {
        final AtomicReference<Uri> result = new AtomicReference(null);

        final File file = ContentStorage.get().createTempFile();

        AndroidRxUtils.andThenOnUi(Schedulers.io(), () -> {
            try {
                final ProcessBuilder builder = new ProcessBuilder();
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    builder.command("logcat", "-d", "-f", file.getAbsolutePath());
                } else {
                    if (fullInfo) {
                        builder.command("logcat", "-d", "*:V", "-f", file.getAbsolutePath());
                    } else {
                        builder.command("logcat", "-d", "AndroidRuntime:E", "cgeo:D", "cgeo.geocachin:I", "*:S", "-f", file.getAbsolutePath());
                    }
                }
                Log.iForce("[LogCat]Issuing command: " + builder.command());
                final int returnCode = builder.start().waitFor();
                if (returnCode == 0 && file.isFile()) {
                    final Uri logfileUri = ContentStorage.get().writeFileToFolder(PersistableFolder.LOGFILES, FileNameCreator.LOGFILE, file, true);
                    result.set(logfileUri);
                } else {
                    Log.w("Problem creating logfile " + file + " (returnCode=" + returnCode + ", isFile=" + file.isFile() + ")");
                }

            } catch (IOException | InterruptedException e) {
                Log.e("error calling logcat: " + e.getMessage());
            }
        }, () -> {
            if (result.get() != null) {
                if (forceEmail) {
                    shareLogfileAsEmail(activity, additionalMessage, result.get());
                } else {
                    Dialogs.confirmPositiveNegativeNeutral(activity, activity.getString(R.string.about_system_write_logcat),
                        String.format(activity.getString(R.string.about_system_write_logcat_success), UriUtils.getLastPathSegment(result.get()), PersistableFolder.LOGFILES.getFolder().toUserDisplayableString()),
                        activity.getString(android.R.string.ok), null, activity.getString(R.string.about_system_info_send_button),
                        null, null, (dialog, which) -> shareLogfileAsEmail(activity, additionalMessage, result.get()));
                }
            } else {
                ActivityMixin.showToast(activity, R.string.about_system_write_logcat_error);
            }
        });
    }

    private static void shareLogfileAsEmail(@NonNull final Activity activity, final String additionalMessage, final Uri logfileUri) {
        final String systemInfo = SystemInformation.getSystemInformation(activity);
        final String emailText = additionalMessage == null ? systemInfo : additionalMessage + "\n\n" + systemInfo;
        ShareUtils.shareAsEmail(activity, activity.getString(R.string.mailsubject_problem_report), emailText, logfileUri, R.string.about_system_info_send_chooser);
    }

    public static void logClassInformation(final String className) {
        if (Log.isEnabled(Log.LogLevel.VERBOSE)) {
            Log.v(String.format("Class info: %s", getClassInformation(className)));
        }
    }

    public static String getClassInformation(final String className) {
        final StringBuilder sb = new StringBuilder("Class[" + className + "]:");
        try {
            final Class<?> c = Class.forName(className);
            sb.append("Cons:[");
            for (Constructor<?> con : c.getDeclaredConstructors()) {
                sb.append(con.getName()).append("(").append(CollectionStream.of(con.getParameterTypes()).map(p -> p.getName()).toJoinedString(",")).append(");");
            }
            sb.append("]");

        } catch (ClassNotFoundException cnfe) {
            sb.append(" NOT EXISTING");
        } catch (Exception ex) {
            //something unexpected happened
            Log.w("Unexpected exception while trying to get class information for '" + className + "' (gathered so far: " + sb.toString() + ")", ex);
        }
        return sb.toString();

    }
}


text:
namespace IntDoubleAndString
{
    using System;

    class IntDoubleAndString
    {
        static void Main()
        {
            string input = Console.ReadLine();

            switch (input)
            {
                case "text":
                {
                    Console.WriteLine(Console.ReadLine() + "*");
                    break;
                }

            case "integer":
                {
                    int newValue = int.Parse(Console.ReadLine());
                    Console.WriteLine(newValue + 1);
                    break;
                }

            case "real":
                {
                    double newValue = double.Parse(Console.ReadLine());
                    Console.WriteLine("{0:N2}", newValue + 1);
                    break;
                }
            }
        }
    }
}


text:
package com.deleidos.rtws.jms.router;

import javax.jms.ConnectionFactory;

/**
 * Information on connecting to a specific jms location (queue)
 *
 */
public class JMSConnectionDefinition {

	private ConnectionFactory connectionFactory;
	private String[] queues;
	private String jmxURL;

	public JMSConnectionDefinition() {
	}

	public ConnectionFactory getConnectionFactory() {
		return connectionFactory;
	}
	public void setConnectionFactory(ConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}
	public String[] getQueues() {
		return queues;
	}
	public void setQueues(String[] queues) {
		this.queues = queues;
	}
	public String getJmxURL() {
		return jmxURL;
	}
	public void setJmxURL(String jmxURL) {
		this.jmxURL = jmxURL;
	}

}


text:
from __future__ import absolute_import, division, print_function

# Import the relevant PTS classes and modules
from ..core.component import ModelingComponent
from ...core.tools import filesystem as fs
from ...core.tools import tables
from ...core.launch.timing import TimingTable
from ...core.launch.memory import MemoryTable

# -----------------------------------------------------------------

contributions = ["old", "young", "ionizing"]

# -----------------------------------------------------------------

class FittingComponent(ModelingComponent):

    """
    This class...
    """

    def __init__(self, config=None):

        """
        The constructor ...
        :param config:
        :return:
        """

        # Call the constructor of the base class
        super(FittingComponent, self).__init__(config)

        # -- Attributes --

        # The path to the template ski file
        self.template_ski_path = None

        # The path to the fit/evolution directory
        self.fit_generations_path = None

        # The path to the fit/wavelength grids directory
        self.fit_wavelength_grids_path = None

        # The path to the fit/dust grids directory
        self.fit_dust_grids_path = None

        # The path to the fit/best directory
        self.fit_best_path = None

        # The path to the fit/prob directory
        self.fit_prob_path = None

        # The path to the fit/grid directory
        self.fit_grid_path = None

        # The path to the ski file
        self.fit_ski_path = None

        # The path to the generations table
        self.generations_table_path = None

        # The path to the parameter table
        self.parameter_table_path = None

        # The path to the chi squared table
        self.chi_squared_table_path = None

        # The path to the weights table
        self.weights_table_path = None

        # The path to the timing table
        self.timing_table_path = None

        # The path to the memory table
        self.memory_table_path = None

        # The path to the scripts directory
        self.fit_scripts_path = None

        # The path to the geometries directory
        self.fit_geometries_path = None

        # The paths of the directories of the simulations that calculate the contributions of the various stellar populations
        self.fit_best_contribution_paths = dict()

        # The path of the directory to generate simulated images for the best model
        self.fit_best_images_path = None

        # The paths to the probability distribution tables
        self.distribution_table_paths = dict()

        # The path to the reference image
        self.reference_path = None

    # -----------------------------------------------------------------

    def setup(self):

        """
        This function ...
        :return:
        """

        # Call the setup function of the base class
        super(FittingComponent, self).setup()

        # Set the path to the template ski file
        self.template_ski_path = fs.join(self.fit_path, "template.ski")

        # Set the path to the fit/generations directory
        self.fit_generations_path = fs.create_directory_in(self.fit_path, "generations")

        # Set the path to the fit/wavelength grids directory
        self.fit_wavelength_grids_path = fs.create_directory_in(self.fit_path, "wavelength grids")

        # Set the path to the fit/dust grids directory
        self.fit_dust_grids_path = fs.create_directory_in(self.fit_path, "dust grids")

        # Set the path to the fit/best directory
        self.fit_best_path = fs.create_directory_in(self.fit_path, "best")

        # Set the path to the fit/prob directory
        self.fit_prob_path = fs.create_directory_in(self.fit_path, "prob")

        # Set the path to the fit/grid directory
        self.fit_grid_path = fs.create_directory_in(self.fit_path, "grid")

        # Set the path to the fit/scripts directory
        self.fit_scripts_path = fs.create_directory_in(self.fit_path, "scripts")

        # Set the path to the fit/geometries directory
        self.fit_geometries_path = fs.create_directory_in(self.fit_path, "geometries")

        # Set and create the paths to the fit/best/ contribution directories
        for contribution in contributions:

            path = fs.join(self.fit_best_path, contribution)
            fs.create_directory(path)
            self.fit_best_contribution_paths[contribution] = path

        # Set the path to the fit/best/images directory
        self.fit_best_images_path = fs.create_directory_in(self.fit_best_path, "images")

        # Set the path to the generations table
        self.generations_table_path = fs.join(self.fit_path, "generations.dat")

        # -----------------------------------------------------------------

        # Set the path to the parameter file
        self.parameter_table_path = fs.join(self.fit_path, "parameters.dat")

        # Initialize the parameter file if that hasn't been done yet
        if not fs.is_file(self.parameter_table_path):

            # Create the table
            names = ["Simulation name", "FUV young", "FUV ionizing", "Dust mass"]
            data = [[], [], [], []]
            dtypes = ["S24", "float64", "float64", "float64"]
            table = tables.new(data, names, dtypes=dtypes)

            # Create the (empty) table
            tables.write(table, self.parameter_table_path, format="ascii.ecsv")

        # Determine the path to the ski file
        self.fit_ski_path = fs.join(self.fit_path, self.galaxy_name + ".ski")

        # Set the path to the chi squared table file
        self.chi_squared_table_path = fs.join(self.fit_path, "chi_squared.dat")

        # Initialize the chi squared file if that hasn't been done yet
        if not fs.is_file(self.chi_squared_table_path):

            # Create the table
            names = ["Simulation name", "Chi squared"]
            data = [[], []]
            dtypes = ["S24", "float64"]
            table = tables.new(data, names, dtypes=dtypes)

            # Write the (empty) table
            tables.write(table, self.chi_squared_table_path, format="ascii.ecsv")

        # Set the path to the weights table file
        self.weights_table_path = fs.join(self.fit_path, "weights.dat")

        # Set the path to the timing table file
        self.timing_table_path = fs.join(self.fit_path, "timing.dat")

        # Initialize the timing table
        timing_table = TimingTable(self.timing_table_path)

        # Set the path to the memory table file
        self.memory_table_path = fs.join(self.fit_path, "memory.dat")

        # Initialize the memory table
        memory_table = MemoryTable(self.memory_table_path)

        # Set the paths to the probability distribution tables
        if self.free_parameter_labels is not None:

            for label in self.free_parameter_labels:

                # Determine the path to the table
                path = fs.join(self.fit_prob_path, label + ".dat")

                # Set the path
                self.distribution_table_paths[label] = path

        # Set the path to the reference image
        self.reference_path = fs.join(self.truncation_path, self.reference_image + ".fits")

# -----------------------------------------------------------------


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/pbusLinkSvc.H $                                */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2020                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file pbusLinkSvc.H
 *
 *  Singleton service to provide validation of pbus connections and
 *  return validated valid connections
 *
 */

#ifndef __PBUSLINKSVC_H
#define __PBUSLINKSVC_H

#include    <stdint.h>
#include    <util/singleton.H>
#include    <map>

#include    <errl/errlentry.H>

//  targeting support
#include    <targeting/common/commontargeting.H>
#include    <targeting/common/utilFilter.H>
#include    <targeting/common/trace.H>

namespace   EDI_EI_INITIALIZATION
{

using   namespace   TARGETING;

typedef std::map<const TARGETING::Target*,
                 const TARGETING::Target*> TargetPairs_t;

class PbusLinkSvc
{

public:

    /**
     * @brief Get singleton instance of this class.
     *
     *  @return the (one and only) instance of PbusLinkSvc
     */
    static PbusLinkSvc& getTheInstance();

    /**
     * @brief getPbusConnections() will collect all pbus connections of
     *        the specified bus type. If this is the first time collection,
     *        it will perform the collection and save them into the vectors
     *        within the singleton. Then, it will make a copy into the
     *        caller's map whose reference is passed to this function.
     *
     * @parm[out] o_PbusConnections, reference of a map for getting a copy
     *            of the map of specified bus connections
     * @parm[in]  i_busType, type of bus connection, e.g. IOHS_CONFIG_MODE_SMPX
     * @parm[in]  i_noDuplicate, set to true to eliminate duplicates, i.e.
     *            only (endpoint1,endpoint2) or (endpoint2,endpoint1) will
     *            be in the present in the map
     * @return    errlHndl_t if encountering an error, or NULL (no error)
     *
     */

    errlHndl_t getPbusConnections( TargetPairs_t & o_PbusConnections,
                                   IOHS_CONFIG_MODE i_busType,  bool i_noDuplicate = true );

protected:
    /**
     * @brief Constructor for the PbusLinkSvc object.
     */
    PbusLinkSvc();

    /**
     * @brief Destructor for the PbusLinkSvc object.
     */
    ~PbusLinkSvc();

private:
    /**
     * @note   Disable copy constructor and assignment operator
     */
    PbusLinkSvc(const PbusLinkSvc& i_right);
    PbusLinkSvc& operator=(const PbusLinkSvc& i_right);

    std::map<IOHS_CONFIG_MODE, TargetPairs_t> iv_busConnections;
    std::map<IOHS_CONFIG_MODE, TargetPairs_t> iv_uniqueBusConnections;

    // Mutex serializing changes to the above maps
    mutex_t iv_mutex;

    /**
     * @brief collectPbusConnections() will collect all pbus connections of
     *        the specified bus type. It checks for mixed-type connection,
     *        conflicting connection, and invalid-same-chip connection.
     *        The connections are saved within the singleton.
     *
     * @parm[in]  i_busType, type of bus connection, e.g. IOHS_CONFIG_MODE_SMPX
     * @return    errlHndl_t if encountering an error, or NULL (no error)
     *
     */
    errlHndl_t collectPbusConnections( IOHS_CONFIG_MODE i_busType );

};

}

#endif


text:
using namespace std;

namespace IGCS::Utils
{
	BOOL isMainWindow(HWND handle)
	{
		BOOL toReturn = GetWindow(handle, GW_OWNER) == (HWND)0 && IsWindowVisible(handle);
		if (toReturn)
		{
			// check window title as there can be more top windows.
			int bufsize = GetWindowTextLength(handle) + 1;
			LPWSTR title = new WCHAR[bufsize];
			GetWindowText(handle, title, bufsize);
			toReturn &= (_wcsicmp(title, TEXT(GAME_WINDOW_TITLE)) == 0);
#ifdef _DEBUG
			wcout << "Window found with title: '" << title << "'" << endl;
#endif
		}
		return toReturn;
	}

	BOOL CALLBACK enumWindowsCallback(HWND handle, LPARAM lParam)
	{
		handle_data& data = *(handle_data*)lParam;
		unsigned long process_id = 0;
		GetWindowThreadProcessId(handle, &process_id);
		if (data.process_id != process_id || !isMainWindow(handle))
		{
			return TRUE;
		}
		data.best_handle = handle;
		return FALSE;
	}

	MODULEINFO getModuleInfoOfContainingProcess()
	{
		HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId());
		HMODULE processModule = nullptr;
		if (nullptr != processHandle)
		{
			DWORD cbNeeded;
			if(!EnumProcessModulesEx(processHandle, &processModule, sizeof(processModule), &cbNeeded, LIST_MODULES_32BIT | LIST_MODULES_64BIT))
			{
				processModule = nullptr;
			}
		}
		MODULEINFO toReturn;
		if (nullptr != processModule)
		{
			if (!GetModuleInformation(processHandle, processModule, &toReturn, sizeof(MODULEINFO)))
			{
				toReturn.lpBaseOfDll = nullptr;
			}
		}
		CloseHandle(processHandle);
		return toReturn;
	}

	MODULEINFO getModuleInfoOfDll(LPCWSTR libraryName)
	{
		HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId());
		HMODULE dllModule = GetModuleHandle(libraryName);
		MODULEINFO toReturn;
		if (nullptr != dllModule)
		{
			if (!GetModuleInformation(processHandle, dllModule, &toReturn, sizeof(MODULEINFO)))
			{
				toReturn.lpBaseOfDll = nullptr;
			}
		}
		CloseHandle(processHandle);
		return toReturn;
	}

	HWND findMainWindow(unsigned long process_id)
	{
		handle_data data;
		data.process_id = process_id;
		data.best_handle = 0;
		EnumWindows(enumWindowsCallback, (LPARAM)&data);
		return data.best_handle;
	}

	uint8_t CharTouint8_t(char c)
	{
		uint8_t b;
		sscanf_s(&c, "%hhx", &b);
		return b;
	}

	bool DataCompare(LPBYTE image, LPBYTE uint8_tPattern, char* patternMask)
	{
		for (; *patternMask; ++patternMask, ++image, ++uint8_tPattern)
		{
			if (*patternMask == 'x' && *image != *uint8_tPattern)
			{
				return false;
			}
		}
		return (*patternMask) == 0;
	}

	LPBYTE findAOBPattern(LPBYTE imageAddress, DWORD imageSize, AOBBlock* const toScanFor)
	{
		register uint8_t firstuint8_t = *(toScanFor->uint8_tPattern());
		__int64 length = (__int64)imageAddress + imageSize - toScanFor->patternSize();

		LPBYTE toReturn = nullptr;
		LPBYTE startOfScan = imageAddress;
		for (int occurrence = 0; occurrence < toScanFor->occurrence(); occurrence++)
		{
			// reset the pointer found, as we're not interested in this occurrence, we need a following occurrence.
			toReturn = nullptr;
			for (register __int64 i = (__int64)startOfScan; i < length; i += 4)
			{
				unsigned x = *(unsigned*)(i);

				if ((x & 0xFF) == firstuint8_t)
				{
					if (DataCompare(reinterpret_cast<uint8_t*>(i), toScanFor->uint8_tPattern(), toScanFor->patternMask()))
					{
						toReturn = reinterpret_cast<uint8_t*>(i);
						break;
					}
				}
				if ((x & 0xFF00) >> 8 == firstuint8_t)
				{
					if (DataCompare(reinterpret_cast<uint8_t*>(i + 1), toScanFor->uint8_tPattern(), toScanFor->patternMask()))
					{
						toReturn = reinterpret_cast<uint8_t*>(i + 1);
						break;
					}
				}
				if ((x & 0xFF0000) >> 16 == firstuint8_t)
				{
					if (DataCompare(reinterpret_cast<uint8_t*>(i + 2), toScanFor->uint8_tPattern(), toScanFor->patternMask()))
					{
						toReturn = reinterpret_cast<uint8_t*>(i + 2);
						break;
					}
				}
				if ((x & 0xFF000000) >> 24 == firstuint8_t)
				{
					if (DataCompare(reinterpret_cast<uint8_t*>(i + 3), toScanFor->uint8_tPattern(), toScanFor->patternMask()))
					{
						toReturn = reinterpret_cast<uint8_t*>(i + 3);
						break;
					}
				}
			}
			if (nullptr == toReturn)
			{
				// not found, give up
				return toReturn;
			}
			startOfScan = toReturn + 1;	// otherwise we'll match ourselves.
		}
		return toReturn;
	}

	// locationData is the AOB block with the address of the rip relative value to read for the calculation.
	// nextOpCodeOffset is used to calculate the address of the next instruction as that's the address the rip relative value is relative off. In general
	// this is 4 (the size of the int32 for the rip relative value), but sometimes the rip relative value is inside an instruction following one or more uint8_ts before the
	// next instruction starts.
	LPBYTE calculateAbsoluteAddress(AOBBlock* locationData, int nextOpCodeOffset)
	{
		// ripRelativeValueAddress is the absolute address of a DWORD value which is a RIP relative offset. A calculation has to be performed on x64 to
		// calculate from that rip relative value and its location the real absolute address it refers to. That address is returned.
		LPBYTE ripRelativeValueAddress = locationData->locationInImage() + locationData->customOffset();
		return  ripRelativeValueAddress + nextOpCodeOffset + *((__int32*)ripRelativeValueAddress);
	}
}


text:
package com.navercorp.pinpoint.profiler.instrument.classreading;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.navercorp.pinpoint.common.util.ClassLoaderUtils;
import com.navercorp.pinpoint.profiler.util.BytecodeUtils;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

import static org.hamcrest.Matchers.containsInAnyOrder;

/**
 * @author Woonduk Kang(emeroad)
 */
public class SimpleClassMetadataReaderTest {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Test
    public void testSimpleClassMetadata() {
        Class<?> clazz = String.class;
        byte[] classFile = BytecodeUtils.getClassFile(ClassLoaderUtils.getDefaultClassLoader(), clazz.getName());

        SimpleClassMetadata simpleClassMetadata = SimpleClassMetadataReader.readSimpleClassMetadata(classFile);
        // name.
        Assert.assertEquals(simpleClassMetadata.getClassName(), clazz.getName());

        // interfaces
        List<String> interfaceList = getInterfaceList(clazz.getInterfaces());
        List<String> interfaceNames = simpleClassMetadata.getInterfaceNames();
        Assert.assertThat(interfaceNames, containsInAnyOrder(interfaceList.toArray()));

        // super
        Assert.assertEquals(simpleClassMetadata.getSuperClassName(), "java.lang.Object");

        // access
        simpleClassMetadata.getAccessFlag();
        // version
        simpleClassMetadata.getVersion();
    }

    private List<String> getInterfaceList(Class<?>[] interfaces) {
        List<Class<?>> collection = Lists.newArrayList(interfaces);
        return Lists.transform(collection, new Function<Class<?>, String>() {
            @Override
            public String apply(Class<?> input) {
                return input.getName();
            }
        });
    }
}


text:
package org.zalando.nakadi.util;

import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import org.springframework.stereotype.Component;
import org.zalando.nakadi.domain.SubscriptionBase;

import static com.google.common.base.Charsets.UTF_8;

@Component
public class HashGenerator {

    public String generateSubscriptionKeyFieldsHash(final SubscriptionBase subscription) {
        final Hasher hasher = Hashing.md5()
                .newHasher()
                .putString(subscription.getOwningApplication(), UTF_8)
                .putString(subscription.getConsumerGroup(), UTF_8);
        subscription.getEventTypes()
                .stream()
                .sorted()
                .forEach(et -> hasher.putString(et, UTF_8));
        return hasher.hash().toString();
    }

}


text:
sudo dfu-programmer atmega16u2 erase
sudo dfu-programmer atmega16u2 flash --debug 1 firmwares/usbserial-uno-R3.hex
sudo dfu-programmer atmega16u2 reset


text:
'use strict'

var resumable = require('./index.js')
  , session = eval(resumable)

  exports['should eval code'] = function (test) {
  var session = eval(resumable)
  test.equal(session.eval('2 + 3').result, 5)
  test.done()
}

exports['should eval code in scope'] = function (test) {
  var session = eval(resumable)
    , x = 10
  test.equal(session.eval('x + 1').result, 11)
  test.done()
}

exports['should add variables to scope'] = function (test) {
  var session = eval(resumable)
  test.equal(session
    .eval('var x = 3')
    .eval('x')
    .result, 3)
  test.done()
}

exports['should add variables to scope in a chain'] = function (test) {
  var session = eval(resumable)
  test.equal(session
    .eval('var x = 3')
    .eval('var y = 4')
    .eval('x + y')
    .result, 7)
  test.done()
}

exports['should return undefined for variable declaration'] = function (test) {
  var session = eval(resumable)
  test.equal(session.eval('var x = 3').result, undefined)
  test.done()
}

// These tests are less important,
// but they are a side-effect of the implementation
// so I'll include them here:
exports['should split sessions'] = function (test) {
  var session = eval(resumable)
    , varSession = session.eval('var x = 3')
  varSession.eval('var y = 4')
  test.equal(varSession.eval('typeof y').result, 'undefined')
  test.done()
}

exports['should share variables in a parent session'] = function (test) {
  var session = eval(resumable).eval('var x = 3')
  session.eval('x = 4')
  session.eval('x = 5')
  test.equal(session.eval('x').result, 5)
  test.done()
}


text:
namespace ColorManager
{
    /// <summary>
    /// Stores information and values of the LCHuv color model
    /// </summary>
    public unsafe sealed class ColorLCHuv : ColorLCHBase
    {
        #region Variables

        /// <summary>
        /// The name of this model
        /// </summary>
        public override string Name
        {
            get { return ModelName; }
        }
        /// <summary>
        /// The name of this model
        /// </summary>
        public static string ModelName
        {
            get { return "LCHuv"; }
        }
        /// <summary>
        /// Minimum value for each channel
        /// </summary>
        public override double[] MinValues
        {
            get { return new double[] { Min_L, Min_C, Min_H }; }
        }
        /// <summary>
        /// Maximum value for each channel
        /// </summary>
        public override double[] MaxValues
        {
            get { return new double[] { Max_L, Max_C, Max_H }; }
        }

        /// <summary>
        /// Minimum value for each channel
        /// </summary>
        public static double[] Min
        {
            get { return new double[] { Min_L, Min_C, Min_H }; }
        }
        /// <summary>
        /// Maximum value for each channel
        /// </summary>
        public static double[] Max
        {
            get { return new double[] { Max_L, Max_C, Max_H }; }
        }

        /// <summary>
        /// Minimum value for the <see cref="ColorLCHBase.L"/> channel
        /// </summary>
        public static readonly double Min_L = 0.0;
        /// <summary>
        /// Minimum value for the <see cref="ColorLCHBase.C"/> channel
        /// </summary>
        public static readonly double Min_C = 0.0;
        /// <summary>
        /// Minimum value for the <see cref="ColorLCHBase.H"/> channel
        /// </summary>
        public static readonly double Min_H = 0.0;

        /// <summary>
        /// Maximum value for the <see cref="ColorLCHBase.L"/> channel
        /// </summary>
        public static readonly double Max_L = 100.0;
        /// <summary>
        /// Maximum value for the <see cref="ColorLCHBase.C"/> channel
        /// </summary>
        public static readonly double Max_C = 255.0;
        /// <summary>
        /// Maximum value for the <see cref="ColorLCHBase.H"/> channel
        /// </summary>
        public static readonly double Max_H = 360.0;

        #endregion

        /// <summary>
        /// Creates a new instance of the <see cref="ColorLCHuv"/> class
        /// </summary>
        public ColorLCHuv()
            : base()
        { }

        /// <summary>
        /// Creates a new instance of the <see cref="ColorLCHuv"/> class
        /// </summary>
        /// <param name="L">Value for the Lightness channel</param>
        /// <param name="C">Value for the Chroma channel</param>
        /// <param name="H">Value for the Hue channel</param>
        public ColorLCHuv(double L, double C, double H)
            : base(L, C, H)
        { }

        /// <summary>
        /// Creates a new instance of the <see cref="ColorLCHuv"/> class
        /// </summary>
        /// <param name="wp">The reference white for this color</param>
        public ColorLCHuv(Whitepoint wp)
            : base(wp)
        { }

        /// <summary>
        /// Creates a new instance of the <see cref="ColorLCHuv"/> class
        /// </summary>
        /// <param name="L">Value for the Lightness channel</param>
        /// <param name="C">Value for the Chroma channel</param>
        /// <param name="H">Value for the Hue channel</param>
        /// <param name="wp">The reference white for this color</param>
        public ColorLCHuv(double L, double C, double H, Whitepoint wp)
            : base(L, C, H, wp)
        { }
    }
}


text:
#include "cinder/msw/CinderMswGdiPlus.h"
#include <windows.h>

namespace cinder { namespace msw {

Surface8u convertGdiplusBitmap( Gdiplus::Bitmap &bitmap )
{
	Gdiplus::BitmapData bitmapData;
	Gdiplus::Rect rect( 0, 0, bitmap.GetWidth(), bitmap.GetHeight() );

	Gdiplus::PixelFormat requestedFormat = bitmap.GetPixelFormat();
	SurfaceChannelOrder sco;
	bool premult;
	gdiplusPixelFormatToSurfaceChannelOrder( requestedFormat, &sco, &premult );
	if( sco == SurfaceChannelOrder::UNSPECIFIED ) {
		UINT flags = bitmap.GetFlags();
		sco = ( flags & Gdiplus::ImageFlagsHasAlpha ) ? SurfaceChannelOrder::BGRA : SurfaceChannelOrder::BGR;
		requestedFormat = ( flags & Gdiplus::ImageFlagsHasAlpha ) ? PixelFormat32bppARGB : PixelFormat24bppRGB;
	}

	bitmap.LockBits( &rect, Gdiplus::ImageLockModeRead, requestedFormat, &bitmapData );
	Surface8u result( bitmap.GetWidth(), bitmap.GetHeight(), sco.hasAlpha(), sco );

	const uint8_t *srcDataBase = (uint8_t*)bitmapData.Scan0;
	int32_t width = bitmap.GetWidth();
	for( uint32_t y = 0; y < bitmap.GetHeight(); ++y ) {
		memcpy( result.getData( ivec2( 0, y ) ), srcDataBase + y * bitmapData.Stride, width * result.getPixelInc() );
	}

	bitmap.UnlockBits( &bitmapData );
	return result;
}

void gdiplusPixelFormatToSurfaceChannelOrder( Gdiplus::PixelFormat format, SurfaceChannelOrder *resultChannelOrder, bool *resultPremultiplied )
{
	*resultPremultiplied = false;
	if( format == PixelFormat32bppPARGB ) {
		*resultPremultiplied = true;
		*resultChannelOrder = SurfaceChannelOrder::BGRA;
	}
	else if( format == PixelFormat32bppARGB ) *resultChannelOrder = SurfaceChannelOrder::BGRA;
	else if( format == PixelFormat24bppRGB ) *resultChannelOrder = SurfaceChannelOrder::BGR;
	else if( format == PixelFormat32bppRGB ) *resultChannelOrder = SurfaceChannelOrder::BGRX;
	else
		*resultChannelOrder = SurfaceChannelOrder::UNSPECIFIED;
}

Gdiplus::PixelFormat surfaceChannelOrderToGdiplusPixelFormat( const SurfaceChannelOrder &sco, bool premultiplied )
{
	switch( sco.getCode() ) {
		case SurfaceChannelOrder::BGR:
			return PixelFormat24bppRGB;
		break;
		case SurfaceChannelOrder::BGRX: // untested code path
			return PixelFormat32bppRGB;
		break;
		case SurfaceChannelOrder::BGRA:
			return ( premultiplied ) ? PixelFormat32bppPARGB : PixelFormat32bppARGB;
		break;
		default:
			return PixelFormatUndefined;
	}
}

Gdiplus::Bitmap* createGdiplusBitmap( const Surface8u &surface )
{
	if( ( surface.getRowBytes() % 4 ) != 0 )
		throw SurfaceConstraintsExc();

	Gdiplus::PixelFormat pf = surfaceChannelOrderToGdiplusPixelFormat( surface.getChannelOrder(), surface.isPremultiplied() );
	if( pf == PixelFormatUndefined )
		throw SurfaceConstraintsExc();

	return new Gdiplus::Bitmap( surface.getWidth(), surface.getHeight(), surface.getRowBytes(), pf, (BYTE*)surface.getData() );
}

} } // namespace cinder::msw


text:
"""
To run this script, ensure that you have set your PYTHONPATH:

export PYTHONPATH=$PYTHONPATH:/home/{user}/Coding/Projects/nlp:/home/{user}/Coding/Projects/nlp/tokenizer:/home/{user}/Coding/Projects/nlp/naive:/home/{user}/Coding/Projects/nlp/fileparser

export PYTHONPATH=$PYTHONPATH:/Users/dionysiakiaraxifara/Documents/NLP/nlp:/Users/dionysiakiaraxifara/Documents/NLP/nlp/tokenizer:/Users/dionysiakiaraxifara/Documents/NLP/nlp/naive:/Users/dionysiakiaraxifara/Documents/NLP/nlp/fileparser

where {user} is your username. Note that the above paths are for a linux system and according to my sub-directory convention. Yours will inevitably be different.

Once the paths are set, navigate to the 'nlp' directory in the Terminal and then

$python nlp.py

where the $ indicates the command prompt.

Currently, the output is simply printed to the terminal.

-I needed to install:
sudo easy_install pip
sudo easy_install beautifulsoup4
intalled Xcode from the Apple Store
Xcode - preferences - download - install command line tools
sudo easy_install pandas
sudo pip install lxml
sudo pip install html5lib
sudo pip install nose
sudo pip install coverage

"""

# Package version number:
__version__ = '0.1.0'

# Required modules:
import fileparser as fp
import tokenizer as tk
import naive as nsa
import pickle

# The url to parse:
url = 'http://www.bbc.co.uk/news/world-europe-23283684'

# Instantiate a new parser:
parser = fp.FileParser()

# Parse the url:
doc = parser.parse(url)

# Run the document through the tokenizer:
tokenizer = tk.Tokenizer() #initialize object
tokenizer.filename = 'test.txt' #cannot do tok.filename('test.txt') because here we're redefining an attribute (assigning a value)
tokenizer.tokenize(doc) #here we're calling a method which needs a parameter

#print tokens

with open('test.txt', 'rb') as f:
	thedata = pickle.load(f)

print(thedata)

#len(thedata)
#thedata[4][1:20]

#write out to file: use python's way to save unicode to string
#then read in file (which is an array of arrays) to do the SA


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.jenkins-ci.plugins</groupId>
    <artifactId>plugin</artifactId>
    <version>1.509.3</version><!-- which version of Jenkins is this plugin built against? -->
  </parent>

  <groupId>com.sulake.jenkins.plugins</groupId>
  <artifactId>jeff-plugin</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>hpi</packaging>

  <name>Jeff Plugin</name>

  <!-- get every artifact through repo.jenkins-ci.org, which proxies all the artifacts that we need -->
  <repositories>
    <repository>
      <id>repo.jenkins-ci.org</id>
      <url>http://repo.jenkins-ci.org/public/</url>
    </repository>
  </repositories>

  <pluginRepositories>
    <pluginRepository>
      <id>repo.jenkins-ci.org</id>
      <url>http://repo.jenkins-ci.org/public/</url>
    </pluginRepository>
  </pluginRepositories>

</project>


text:
#ifndef _STACK_H_
#define _STACK_H_

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

/* Uncomment the below lines to use MemPool instead of system's default functions malloc and free */

//#include "../../MemPool/src/mempool.h"
//#define MEMPOOL

#ifdef MEMPOOL
	#define malloc(size) getMemNode()
	#define free(ptr) releaseMemNode(ptr)
#endif

typedef unsigned int UINT;

 /* Stack Element */
typedef struct StackElement_t {
	void *data;
	struct StackElement_t *next;
}StackElement;

/* Stack
 *	destroy -> Appropriate function in order to free an element's data
 */
typedef struct Stack_t {
	StackElement *head;
	UINT size;
	void (*destroy) (void *data);
}Stack;

/* Initializes a stack */
int initStack(Stack *stack, void (*destroy) (void *data));

/* Adds a StackElement to the top of the stack */
int push(Stack *stack, void *data);

/* Removes a StackElement from the top of the stack */
int pop(Stack *stack, void **data);

/* Destroys the stack
 *	Attention: If you use MemPool then after destroyStack you must call freeMemory()
 */
void destroyStack(Stack *stack);

/* Returns the size of the stack */
#define Stack_size(stack) ((stack)->size)
/* Returns the top element of the stack */
#define Stack_peek(stack) ((stack)->head == NULL ? NULL : (stack)->head->data)

#endif


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p27;

public class Production549 {

    private Production546 property0;

    public Production546 getProperty0() {
        return property0;
    }

    public void setProperty0(Production546 value) {
        property0 = value;
    }

    private Production547 property1;

    public Production547 getProperty1() {
        return property1;
    }

    public void setProperty1(Production547 value) {
        property1 = value;
    }

    private Production548 property2;

    public Production548 getProperty2() {
        return property2;
    }

    public void setProperty2(Production548 value) {
        property2 = value;
    }

    private String property3;

    public String getProperty3() {
        return property3;
    }

    public void setProperty3(String value) {
        property3 = value;
    }

    private String property4;

    public String getProperty4() {
        return property4;
    }

    public void setProperty4(String value) {
        property4 = value;
    }

    private String property5;

    public String getProperty5() {
        return property5;
    }

    public void setProperty5(String value) {
        property5 = value;
    }

    private String property6;

    public String getProperty6() {
        return property6;
    }

    public void setProperty6(String value) {
        property6 = value;
    }

    private String property7;

    public String getProperty7() {
        return property7;
    }

    public void setProperty7(String value) {
        property7 = value;
    }

    private String property8;

    public String getProperty8() {
        return property8;
    }

    public void setProperty8(String value) {
        property8 = value;
    }

    private String property9;

    public String getProperty9() {
        return property9;
    }

    public void setProperty9(String value) {
        property9 = value;
    }

}


text:
{% block propuestas_base %}
	{% if user %}

			SUBIR UNA NUEVA PROPUESTA

	{% else %}

			Tienes que identificarte para hacer una propuesta, votarla o comentarla.

	{% endif %}

Más valoradas

Más consenso

Más debatidas

Más recientes

Propuestas ordenadas por mayor número de votos (positivos o negativos)

            {% set list = valoradas %}
            {% include 'propuestas_list.html' with list %}

Propuestas ordenadas por mayor porcentaje de votos positivos

            {% set list = consensuadas %}
            {% include 'propuestas_list.html' with list %}

Propuestas ordenadas por mayor número de comentarios

            {% set list = debatidas %}
            {% include 'propuestas_list.html' with list %}

Propuestas ordenadas por creadación más recientemente

            {% set list = recientes %}
            {% include 'propuestas_list.html' with list %}

        {% if mostrar_todas %}
        Ver todas
        {% endif %}

{% endblock %}