text:
<?php

class Matrixcode_Factory
{

    /**
     * Factory for Matrixcode_Abstract classes.
     *
     * First argument should be a string containing the base of the adapter class
     * name, e.g. 'qrcode' corresponds to class Matrixcode_Qrcode.  This
     * is case-insensitive.
     *
     * First argument may alternatively be an object of type Zend_Config.
     * The matrixcode class base name is read from the 'matrixcode' property.
     * The matrixcode config parameters are read from the 'params' property.
     *
     * Second argument is optional and may be an associative array of key-value
     * pairs.  This is used as the argument to the matrixcode constructor.
     *
     * If the first argument is of type Zend_Config and contains a 'params' key, it is assumed to contain
     * all parameters, and the second argument is ignored.
     *
     * The third parameter specifies the type of renderer, where the fourth parameter is an array or
     * Zend_Config object containing the renderer parameters
     *
     * @param string | array | Zend_Config $matrixcode
     * @param array | Zend_Config $matrixcodeConfig
     * @param string $renderer OPTIONAL
     * @param array | Zend_Config $rendererConfig OPTIONAL
     * @return Zend_Matrixcode_Abstract
     * @throws Zend_Matrixcode_Exception
     */
    public static function factory (
    	$matrixcode,
    	$matrixcodeConfig = array(),
    	$renderer = 'image',
    	$rendererConfig = array()
    ) {
        /*
         * Convert Zend_Config argument to plain string
         * matrixcode name and separate config object.
         */
        if ($matrixcode instanceof Zend_Config) {
            if (isset($matrixcode->rendererParams)) {
                $rendererConfig = $matrixcode->rendererParams->toArray();
            }
            if (isset($matrixcode->renderer)) {
                $renderer = (string) $matrixcode->renderer;
            }
            if (isset($matrixcode->matrixcodeParams)) {
                $matrixcodeConfig = $matrixcode->matrixcodeParams->toArray();
            }
            if (isset($matrixcode->matrixcode)) {
                $matrixcode = (string) $matrixcode->matrixcode;
            } else {
                $matrixcode = null;
            }
        }

        try {
            $matrixcode = self::getMatrixcode($matrixcode, $matrixcodeConfig);
            $renderer = self::getRenderer($renderer, $rendererConfig);
        } catch (Zend_Exception $e) {
            throw $e;
        }

        $renderer->setMatrixcode($matrixcode);
        return $renderer;
    }

	/**
     * Matrixcode Constructor
     *
     * @param mixed $matrixcode        String name of matrixcode class, or Zend_Config object.
     * @param mixed $matrixcodeConfig  OPTIONAL; an array or Zend_Config object with matrixcode parameters
     * @return Matrixcode_Abstract
     */
    public static function getMatrixcode($matrixcode, $matrixcodeConfig = array())
    {
        /*
         * Convert Zend_Config argument to plain string
         * matrixcode name and separate config object.
         */
        if ($matrixcode instanceof Zend_Config) {
            if (isset($matrixcode->matrixcodeParams) && $matrixcode->matrixcodeParams instanceof Zend_Config) {
                $matrixcodeConfig = $matrixcode->matrixcodeParams->toArray();
            }
            if (isset($matrixcode->matrixcode)) {
                $matrixcode = (string) $matrixcode->matrixcode;
            } else {
                $matrixcode = null;
            }
        }
        if ($matrixcodeConfig instanceof Zend_Config) {
            $matrixcodeConfig = $matrixcodeConfig->toArray();
        }

        /*
         * Verify that matrixcode parameters are in an array.
         */
        if (!is_array($matrixcodeConfig)) {
            throw new Matrixcode_Exception(
                'Matrixcode parameters must be in an array or a Zend_Config object'
            );
        }

        /*
         * Verify that a matrixcode name has been specified.
         */
        if (!is_string($matrixcode) || empty($matrixcode)) {
            throw new Matrixcode_Exception(
                'Matrixcode name must be specified in a string'
            );
        }

        /*
         * Form full matrixcode class name
         */
        $matrixcodeNamespace = 'Matrixcode';
        if (isset($matrixcodeConfig['matrixcodeNamespace'])) {
            $matrixcodeNamespace = $matrixcodeConfig['matrixcodeNamespace'];
        }
        $matrixcodeName = strtolower($matrixcodeNamespace . '_' . $matrixcode);
        $matrixcodeName = str_replace(' ', '_', ucwords(str_replace('_', ' ', $matrixcodeName)));

        /*
         * Create an instance of the matrixcode class.
         */
        $mcAdapter = new $matrixcodeName($matrixcodeConfig);

        /*
         * Verify that the object created is a descendent of the abstract matrixcode type.
         */
        if (!$mcAdapter instanceof Matrixcode_AbstractMatrixcode) {
            throw new Matrixcode_Exception(
                "Matrixcode class '$matrixcodeName' does not extend Matrixcode_AbstractMatrixcode"
            );
        }
        return $mcAdapter;
    }

	/**
     * Renderer Constructor
     *
     * @param mixed $renderer           String name of renderer class, or Zend_Config object.
     * @param mixed $rendererConfig     OPTIONAL; an array or Zend_Config object with renderer parameters.
     * @return Matrixcode_Renderer_Abstract
     */
    public static function getRenderer($renderer = 'image', $rendererConfig = array())
    {
        /*
         * Convert Zend_Config argument to plain string
         * renderer name and separate config object.
         */
        if ($renderer instanceof Zend_Config) {
            if (isset($renderer->rendererParams)) {
                $rendererConfig = $renderer->rendererParams->toArray();
            }
            if (isset($renderer->renderer)) {
                $renderer = (string) $renderer->renderer;
            }
        }
        if ($rendererConfig instanceof Zend_Config) {
            $rendererConfig = $rendererConfig->toArray();
        }

        /*
         * Verify that renderer parameters are in an array.
         */
        if (!is_array($rendererConfig)) {
            $e = new Matrixcode_Exception(
                'Renderer parameters must be in an array or a Zend_Config object'
            );
            throw $e;
        }

        /*
         * Verify that a renderer name has been specified.
         */
        if (!is_string($renderer) || empty($renderer)) {
            $e = new Matrixcode_Exception(
                'Renderer name must be specified in a string'
            );
            throw $e;
        }

        /*
         * Form full renderer class name
         */
        $rendererNamespace = 'Matrixcode_Renderer';
        if (isset($rendererConfig['rendererNamespace'])) {
            $rendererNamespace = $rendererConfig['rendererNamespace'];
        }
        $rendererName = strtolower($rendererNamespace . '_' . $renderer);
        $rendererName = str_replace(' ', '_', ucwords(str_replace( '_', ' ', $rendererName)));

        /*
         * Create an instance of the renderer class.
         */
        $rdrAdapter = new $rendererName($rendererConfig);

        /*
         * Verify that the object created is a descendent of the abstract renderer type.
         */
        if (!$rdrAdapter instanceof Matrixcode_Renderer_AbstractRenderer) {
            $e = new Matrixcode_Exception(
                "Renderer class '$rendererName' does not extend Matrixcode_Renderer_Abstract"
            );
            throw $e;
        }
        return $rdrAdapter;
    }

    /**
     * Proxy to renderer render() method
     *
     * @param string | array | Zend_Config $matrixcode
     * @param array | Zend_Config $matrixcodeConfig
     * @param string $renderer OPTIONAL
     * @param array | Zend_Config $rendererConfig OPTIONAL
     * @return mixed
     */
    public static function render (
    	$matrixcode,
    	$matrixcodeConfig = array(),
    	$renderer = 'image',
    	$rendererConfig = array()
    ) {
        return self::factory ($matrixcode, $matrixcodeConfig, $renderer, $rendererConfig)->render();
    }

}


text:
if Report.count == 0
  # if there is no current report
  Report.create(name: 'Kuh Bertha', start_date: Time.now)
end

# Create default topics:

Topic.find_or_create_by(name: "milk_quantity")
Topic.find_or_create_by(name: "milk_quality")
Topic.find_or_create_by(name: "movement")
Topic.find_or_create_by(name: "temperature")
Topic.find_or_create_by(name: "intake")
Topic.find_or_create_by(name: "birth")
Topic.find_or_create_by(name: "calf")
Topic.find_or_create_by(name: "noise")
Topic.find_or_create_by(name: "health")

Report.find_each do |report|
  default_channel = Channel.find_or_create_by(
    report: report,
    name: "sensorstory"
  ) do |c|
    c.description = "Default Channel"
  end

  Channel.find_or_create_by(
    report: report,
    name: "chatbot"
  ) do |c|
    c.description = "Chatbot Channel"
  end

  report.text_components.each do |text_component|
    text_component.channels << default_channel unless text_component.channels.include?(default_channel)
  end
end

attribute_hashes = [
  { property: 'Temperature',          unit: '°C'     },
  { property: 'Atmospheric Pressure', unit: 'Bar'    },
  { property: 'Motion',               unit: '0-10'   },
  { property: 'Brightness',           unit: '0-10'   },
  { property: 'Volume',               unit: '0-10'   },
  { property: 'Humidity',             unit: '%'      },
  { property: 'Button',               unit: 'On/Off' },
  { property: 'Geophone',             unit: '?...?'  },
  { property: 'Gas: Methan',          unit: '%'      },
  { property: 'Gas: Alcohol',         unit: '%'      },
  { property: 'Gas: Ozone',           unit: '%'      },
  { property: 'Air quality',          unit: '?...?'  },
  { property: 'Vibration',            unit: '0-10'   },
  { property: 'Relative Humidity',    unit: '%'      },

  { property: 'Pedometer'         , unit: 'km'                                           },
  { property: 'Qualität'          , unit: 'Note 1-6'                                     },
  { property: 'Gesundheitsstatus' , unit: '0 -1 gesund/krank'                            },
  { property: 'Preis'             , unit: '€'                                            },
  { property: 'Zeit'              , unit: 'hours'                                        },
  { property: 'Milchmenge'        , unit: 'kg'                                           },
  { property: 'Lautstärke'        , unit: '0-10 - still, leise, mittel, laut, sehr laut' },
  { property: 'Favs'              , unit: '0-unlimited'                                  },
  { property: 'pH Value'          , unit: 'pH'                                           },
  { property: 'Movement'          , unit: '1-100'                                        }
]

new_sensor_types = attribute_hashes.collect{ |attributes| SensorType.new attributes }
SensorType.find_each do |p|
  # avoid duplicates
  new_sensor_types.delete_if {|t| t.property == p.property && t.unit == p.unit }
end
new_sensor_types.each { |t| t.save! }

variable_hashes = [
  { report: Report.current , key: 'exemplar' , value: 'Bertha' }         ,
  { report: Report.current , key: 'bauer'    , value: 'Westrup' }        ,
  { report: Report.current , key: 'hof'      , value: 'Westrup - Koch' } ,
  { report: Report.current , key: 'kalb'     , value: 'Robert' }         ,
]

variable_hashes.each do |h|
  v = Variable.new(h)
  v.save
end

redpajama_set_name: RedPajamaGithub


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

namespace IheartBits
{
    class IHeartBits
    {
        static void Main()
        {
            //input -> amount of numbers to process
            int numInput = int.Parse(Console.ReadLine());

            // arrays to store numbers and rresults
            uint[] inputP = new uint[numInput];
            uint[] notP = new uint[numInput]; //P̃
            uint[] invertP = new uint[numInput]; //P̈
            uint[] result = new uint[numInput];

            // for every number
            for (int index = 0; index < numInput; index++)
            {
                // get a new number
                inputP[index] = uint.Parse(Console.ReadLine());

                // Step 1: reverse ONLY bits within the number
                //notP[index] = (~inputP[index]); inverts 32 bits
                uint tempMask = 1;
                uint tempNumb = inputP[index];

                // working
                while (tempNumb > 0)
                {
                    if ((tempNumb & tempMask) == 1) // if 1 add 0
                    {
                        notP[index] = notP[index] << 1;
                    }
                    else                                            // if 0 add 1
                    {
                        notP[index] = notP[index] << 1;
                        notP[index] = notP[index] | tempMask;
                    }
                    //1 bit right and go again
                    tempNumb = tempNumb >> 1;
                }

                // Step 2; get reveres bit sequence
                //read bits -> +1 to add 1, << to add 0
                tempMask = 1;
                tempNumb = inputP[index];

                while (tempNumb > 0)
                {
                    if ((tempNumb & tempMask) == 1) // if 1 add 1
                    {
                        invertP[index] = invertP[index] << 1;
                        invertP[index] = invertP[index] | tempMask;
                    }
                    else
                    {
                        invertP[index] = invertP[index] << 1; // if 0 add 0
                    }
                    //1 bit right and go again
                    tempNumb = tempNumb >> 1;
                }

                // get result - unnecessary
                result[index] = (inputP[index] ^ notP[index]);
                result[index] = result[index] & invertP[index];

                //print 100/ 100
                Console.WriteLine(invertP[index]);
            }
        }
    }
}


text:
namespace jai { namespace drawable {

    ShaderCoordColor::ShaderCoordColor(const char * vShader, const char *fShader,
                                         bool effect)
    {
		mHasEffect = effect;
        mProgram.makeAttachAndLink(vShader, fShader);
        mACoord = mProgram.getAttributeLocation("aCoord");
        mAColor = mProgram.getAttributeLocation("aColor");
        if(effect) mUEffect = mProgram.getUniformLocation("uEffect");
        mUTransform = mProgram.getUniformLocation("uTransform");
        mUPointSize = mProgram.getUniformLocation("uPointSize");
        mUColor = mProgram.getUniformLocation("uColor");
    }

    void ShaderCoordColor::use()
    {
        mProgram.active();
    }

    static const char * vShader =
    SHA_PRECISION
    "attribute vec4 aCoord;"
    "attribute vec4 aColor;"
    "uniform mat4 uTransform;"
	"uniform float uPointSize;"
    "varying vec4 vColor;"
    "void main()"
    "{"
    "   vColor = aColor;"
	"	gl_PointSize = uPointSize;"
    "	gl_Position = uTransform * aCoord;"
    "}";

    ShaderCoordColor * ShaderCoordColor::GetNoraml()
    {
        static const char * fShader =
        SHA_PRECISION
        "varying vec4 vColor;"
        "uniform vec4 uColor;"
        "void main()"
        "{"
        "	gl_FragColor = vColor * uColor;"
        "}";

        static ShaderCoordColor * me = new ShaderCoordColor(vShader, fShader, false);
        return me;
    }

    ShaderCoordColor * ShaderCoordColor::GetWithEffect()
    {
        static const char * fShader =
        SHA_PRECISION
        "uniform mat4 uEffect;"
        "varying vec4 vColor;"
        "uniform float uOpacity;"
        "void main()"
        "{"
        "	gl_FragColor = uEffect * vColor * uOpacity;"
        "}";
        static ShaderCoordColor * me = new ShaderCoordColor(vShader, fShader, true);
        return me;
    }

    ShaderCoordColor * ShaderCoordColor::GetGrey()
    {
        static const char * fShader =
        SHA_PRECISION
        "varying vec4 vColor;"
        "uniform float uOpacity;"
        "const mat4 grey = mat4("
        "   vec4(0.3,0.6,0.1,0.0),"
        "   vec4(0.3,0.6,0.1,0.0),"
        "   vec4(0.3,0.6,0.1,0.0),"
        "   vec4(0.0,0.0,0.0,1.0)"
        ");"
        "void main()"
        "{"
        "	gl_FragColor = grey * vColor * uOpacity;"
        "}";

        static ShaderCoordColor * me = new ShaderCoordColor(vShader, fShader, false);
        return me;
    }
}}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Jb. nassau. Ver. Naturk. 23-24: 393 (1870)

#### Original name
Diplodia pseudodiplodia Fuckel

### Remarks
null


text:
require 'spec_helper'

describe ResponseMate::CLI do
  describe '.package_name' do
    it 'names the tool response_mate' do
      content = capture(:stdout) { ResponseMate::CLI.start %w[help] }
      expect(content).to match(/response_mate commands:/m)
    end
  end

  let(:command) { double(run: 'yay') }

  describe '#record' do
    before do
      allow(ResponseMate::Commands::Record).to receive(:new).and_return(command)
    end

    it 'initializes ResponseMate::Commands::Record' do
      expect(ResponseMate::Commands::Record).to receive(:new)
      capture(:stdout) { ResponseMate::CLI.start %w[record] }
    end

    it 'runs the command passing any given options, arguments' do
      expect(command).to receive(:run)
      capture(:stdout) { ResponseMate::CLI.start %w[record] }
    end
  end

  describe '#inspect' do
    before do
      allow(ResponseMate::Commands::Inspect).to receive(:new).and_return(command)
    end

    it 'initializes ResponseMate::Commands::Inspect' do
      expect(ResponseMate::Commands::Inspect).to receive(:new)
      capture(:stdout) { ResponseMate::CLI.start %w[inspect] }
    end

    it 'runs the command passing any given options, arguments' do
      expect(command).to receive(:run)
      capture(:stdout) { ResponseMate::CLI.start %w[inspect] }
    end
  end

  describe '#list' do
    before do
      allow(ResponseMate::Commands::List).to receive(:new).and_return(command)
    end

    it 'initializes ResponseMate::Commands::List' do
      expect(ResponseMate::Commands::List).to receive(:new)
      capture(:stdout) { ResponseMate::CLI.start %w[list] }
    end

    it 'runs the command passing any given options, arguments' do
      expect(command).to receive(:run)
      capture(:stdout) { ResponseMate::CLI.start %w[list] }
    end
  end

  describe '#export' do
    before do
      allow(ResponseMate::Commands::Export).to receive(:new).and_return(command)
    end

    it 'initializes ResponseMate::Commands::Export' do
      expect(ResponseMate::Commands::Export).to receive(:new)
      capture(:stdout) { ResponseMate::CLI.start %w[export] }
    end

    it 'runs the command passing any given options, arguments' do
      expect(command).to receive(:run)
      capture(:stdout) { ResponseMate::CLI.start %w[export] }
    end
  end
end


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context=".AdvancedSearchActivity">

</menu>


text:
extern "Java"
{
  namespace gnu
  {
    namespace javax
    {
      namespace sound
      {
        namespace midi
        {
          namespace dssi
          {
              class DSSISynthesizer;
              class DSSISynthesizer$DSSIInstrument;
          }
        }
      }
    }
  }
  namespace javax
  {
    namespace sound
    {
      namespace midi
      {
          class Patch;
          class Soundbank;
      }
    }
  }
}

class gnu::javax::sound::midi::dssi::DSSISynthesizer$DSSIInstrument : public ::javax::sound::midi::Instrument
{

public: // actually package-private
  DSSISynthesizer$DSSIInstrument(::gnu::javax::sound::midi::dssi::DSSISynthesizer *, ::javax::sound::midi::Soundbank *, ::javax::sound::midi::Patch *, ::java::lang::String *);
public:
  virtual ::java::lang::Object * getData();
public: // actually package-private
  ::gnu::javax::sound::midi::dssi::DSSISynthesizer * __attribute__((aligned(__alignof__( ::javax::sound::midi::Instrument)))) this$0;
public:
  static ::java::lang::Class class$;
};

#endif // __gnu_javax_sound_midi_dssi_DSSISynthesizer$DSSIInstrument__


text:
package org.elasticsearch.test.rest.spec;

import org.elasticsearch.common.xcontent.XContentParser;

import java.io.IOException;

/**
 * Parser for a REST api spec (single json file)
 */
public class RestApiParser {

    public RestApi parse(XContentParser parser) throws IOException {

        try {
            while ( parser.nextToken() != XContentParser.Token.FIELD_NAME ) {
                //move to first field name
            }

            RestApi restApi = new RestApi(parser.currentName());

            int level = -1;
            while (parser.nextToken() != XContentParser.Token.END_OBJECT || level >= 0) {

                if (parser.currentToken() == XContentParser.Token.FIELD_NAME) {
                    if ("methods".equals(parser.currentName())) {
                        parser.nextToken();
                        while (parser.nextToken() == XContentParser.Token.VALUE_STRING) {
                            restApi.addMethod(parser.text());
                        }
                    }

                    if ("url".equals(parser.currentName())) {
                        String currentFieldName = "url";
                        int innerLevel = -1;
                        while(parser.nextToken() != XContentParser.Token.END_OBJECT || innerLevel >= 0) {
                            if (parser.currentToken() == XContentParser.Token.FIELD_NAME) {
                                currentFieldName = parser.currentName();
                            }

                            if (parser.currentToken() == XContentParser.Token.START_ARRAY && "paths".equals(currentFieldName)) {
                                while (parser.nextToken() == XContentParser.Token.VALUE_STRING) {
                                    restApi.addPath(parser.text());
                                }
                            }

                            if (parser.currentToken() == XContentParser.Token.START_OBJECT && "parts".equals(currentFieldName)) {
                                while (parser.nextToken() == XContentParser.Token.FIELD_NAME) {
                                    restApi.addPathPart(parser.currentName());
                                    parser.nextToken();
                                    if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
                                        throw new IOException("Expected parts field in rest api definition to contain an object");
                                    }
                                    parser.skipChildren();
                                }
                            }

                            if (parser.currentToken() == XContentParser.Token.START_OBJECT && "params".equals(currentFieldName)) {
                                while (parser.nextToken() == XContentParser.Token.FIELD_NAME) {
                                    restApi.addParam(parser.currentName());
                                    parser.nextToken();
                                    if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
                                        throw new IOException("Expected params field in rest api definition to contain an object");
                                    }
                                    parser.skipChildren();
                                }
                            }

                            if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
                                innerLevel++;
                            }
                            if (parser.currentToken() == XContentParser.Token.END_OBJECT) {
                                innerLevel--;
                            }
                        }
                    }

                    if ("body".equals(parser.currentName())) {
                        parser.nextToken();
                        if (parser.currentToken() != XContentParser.Token.VALUE_NULL) {
                            boolean requiredFound = false;
                            while(parser.nextToken() != XContentParser.Token.END_OBJECT) {
                                if (parser.currentToken() == XContentParser.Token.FIELD_NAME) {
                                    if ("required".equals(parser.currentName())) {
                                        requiredFound = true;
                                        parser.nextToken();
                                        if (parser.booleanValue()) {
                                            restApi.setBodyRequired();
                                        } else {
                                            restApi.setBodyOptional();
                                        }
                                    }
                                }
                            }
                            if (!requiredFound) {
                                restApi.setBodyOptional();
                            }
                        }
                    }
                }

                if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
                    level++;
                }
                if (parser.currentToken() == XContentParser.Token.END_OBJECT) {
                    level--;
                }

            }

            parser.nextToken();
            assert parser.currentToken() == XContentParser.Token.END_OBJECT;
            parser.nextToken();

            return restApi;

        } finally {
            parser.close();
        }
    }

}


text:
#include "PeriodicTaskScheduler.h"

#include "folly/Memory.h"
#include "folly/ThreadName.h"
#include "mcrouter/lib/fbi/debug.h"

namespace facebook { namespace memcache { namespace mcrouter {

PeriodicTaskScheduler::TaskThread::TaskThread(
    PeriodicTaskScheduler& scheduler,
    int32_t timeoutMs,
    std::function<void(PeriodicTaskScheduler&)> fn)
  :  tmoMs(timeoutMs),
     func(std::move(fn)),
     t{[this, &scheduler] () {
       folly::setThreadName("mcrtr-periodic");
       scheduler.schedulerThreadRun(*this);
      }} {}

void PeriodicTaskScheduler::scheduleTask(
    int32_t tmoMs,
    std::function<void(PeriodicTaskScheduler&)> func) {
  tasks_.push_back(
      folly::make_unique<TaskThread>(*this, tmoMs, std::move(func)));
}

PeriodicTaskScheduler::PeriodicTaskScheduler()
  : shutdown_(false) {}

void PeriodicTaskScheduler::shutdownAllTasks() {
  if (shutdown_.exchange(true)) {
    throw std::runtime_error("Received a second call on shutdownAllTasks.");
  }
  cv_.notify_all();
  for (auto& task: tasks_) {
    task->t.join();
  }
}

void PeriodicTaskScheduler::forkWorkAround() {
  for (auto& task: tasks_) {
    task->t.detach();
  }
}

void PeriodicTaskScheduler::schedulerThreadRun(TaskThread& task) {
  while (sleepThread(task.tmoMs)) {
    try {
      task.func(*this);
    } catch (const std::exception& ex) {
      LOG(ERROR) << "Error while executing periodic function: " << ex.what();
      break;
    } catch (...) {
      LOG(ERROR) << "Unknown error occured while executing periodic function";
      break;
    }
  }
}

bool PeriodicTaskScheduler::sleepThread(int32_t tmoMs) {
  std::unique_lock<std::mutex> lock(cvMutex_);
  return !cv_.wait_for(
      lock,
      std::chrono::milliseconds(tmoMs),
      [this]() { return this->shutdown_.load(); });
}

}}} // namespace


text:
package org.spongepowered.api.entity;

import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.entity.player.gamemode.GameModes;

/**
 * An list {@link EntityInteractionType}s available in Vanilla.
 */
public final class EntityInteractionTypes {

    /**
     * Represents an interaction by "attacking", bound to left
     * click in the client by default.
     */
    public static final EntityInteractionType ATTACK = null;

    /**
     * Represents an interaction by middle clicking, bound to the
     * scroll wheel in the client by default.
     *
     *
This is only valid for {@link BlockType}s, and has the effect
     * of giving a player the picked block if in {@link GameModes#CREATIVE}.

     */
    public static final EntityInteractionType PICK_BLOCK = null;

    /**
     * Represents an interaction by right clicking, bound to right
     * click in the client by default.
     */
    public static final EntityInteractionType USE = null;

    /**
     * Represents an interaction that occurs indirectly by an {@link Entity}.
     *
     *
A good example is an entity walking over a pressure plate and invoking
     * an event. The interaction type in the event would be considered "indirect" as
     * the entity wasn't directly interacting with the pressure plate.

     */
    public static final EntityInteractionType INDIRECT = null;

    private EntityInteractionTypes() {

    }
}


text:
#include "lib.h"

#include "overlay_blacklist.h"
#include "overlay_exe/overlay_exe.h"

#undef max // for std::numeric_limits<T>::max()

static HANDLE hMapObject = NULL;
static HANDLE hHookMutex = NULL;
static HHOOK hhookWnd = 0;

BOOL bIsWin8 = FALSE;

static BOOL bMumble = FALSE;
static BOOL bDebug = FALSE;
static BOOL bBlackListed = FALSE;

static HardHook hhLoad;
static HardHook hhLoadW;

static SharedData *sd = NULL;

CRITICAL_SECTION Mutex::cs;

void Mutex::init() {
	InitializeCriticalSection(&cs);
}

Mutex::Mutex() {
	if (! TryEnterCriticalSection(&cs)) {
		ods("Lib: Mutex: CritFail - blocking until able to enter critical section");
		EnterCriticalSection(&cs);
	}
}

Mutex::~Mutex() {
	LeaveCriticalSection(&cs);
}

void __cdecl ods(const char *format, ...) {
#ifndef DEBUG
	if (!bDebug)
		return;
#endif
	va_list args;

	va_start(args, format);
	_ods_out(format, &args);
	va_end(args);
}

void __cdecl checkForWPF() {
	if (!bBlackListed && (GetModuleHandleW(L"wpfgfx_v0300.dll") || GetModuleHandleW(L"wpfgfx_v0400.dll"))) {
		ods("Lib: Blacklisted for loading WPF library");
		bBlackListed = TRUE;
	}
}

Pipe::Pipe() {
	hSocket = INVALID_HANDLE_VALUE;
	hMemory = NULL;
	a_ucTexture = NULL;

	omMsg.omh.iLength = -1;

	dwAlreadyRead = 0;

	uiWidth = uiHeight = 0;
	uiLeft = uiRight = uiTop = uiBottom = 0;
}

Pipe::~Pipe() {
	disconnect();
}

void Pipe::release() {
	if (hMemory) {
		CloseHandle(hMemory);
		hMemory = NULL;
		if (a_ucTexture) {
			UnmapViewOfFile(a_ucTexture);
			a_ucTexture = NULL;
		}

		uiLeft = uiRight = uiTop = uiBottom = 0;
	}
}

void Pipe::disconnect() {
	release();
	if (hSocket != INVALID_HANDLE_VALUE) {
		ods("Pipe: Disconnect");
		CloseHandle(hSocket);
		hSocket = INVALID_HANDLE_VALUE;
	}
	uiWidth = 0;
	uiHeight = 0;
	omMsg.omh.iLength = -1;
}

bool Pipe::sendMessage(const OverlayMsg &om) {
	DWORD dwBytesToWrite = sizeof(OverlayMsgHeader) + om.omh.iLength;
	DWORD dwBytesWritten = dwBytesToWrite;

	if (WriteFile(hSocket, om.headerbuffer, sizeof(OverlayMsgHeader) + om.omh.iLength, &dwBytesWritten, NULL))
		if (dwBytesToWrite == dwBytesWritten)
			return true;

	ods("Pipe: Short write");
	disconnect();
	return false;
}

void Pipe::checkMessage(unsigned int width, unsigned int height) {
	if (!width || ! height)
		return;

	if (hSocket == INVALID_HANDLE_VALUE) {
		hSocket = CreateFileW(L"\\\\.\\pipe\\MumbleOverlayPipe", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
		if (hSocket == INVALID_HANDLE_VALUE) {
			ods("Pipe: Connection failed");
			return;
		}
		ods("Pipe: Connected");

		uiWidth = 0;
		uiHeight = 0;

		// initially, instantiate and send an OverlayMessage with the current process id
		OverlayMsg om;
		om.omh.uiMagic = OVERLAY_MAGIC_NUMBER;
		om.omh.uiType = OVERLAY_MSGTYPE_PID;
		om.omh.iLength = sizeof(OverlayMsgPid);
		om.omp.pid = GetCurrentProcessId();

		if (!sendMessage(om))
			return;

		ods("Pipe: Process ID sent");
	}

	// if the passed width and height do not match the current overlays uiWidth and uiHeight, re-initialize
	if ((uiWidth != width) || (uiHeight != height)) {
		release();

		uiWidth = width;
		uiHeight = height;

		// instantiate and send an initialization-OverlayMessage
		OverlayMsg om;
		om.omh.uiMagic = OVERLAY_MAGIC_NUMBER;
		om.omh.uiType = OVERLAY_MSGTYPE_INIT;
		om.omh.iLength = sizeof(OverlayMsgInit);
		om.omi.uiWidth = uiWidth;
		om.omi.uiHeight = uiHeight;

		if (!sendMessage(om))
			return;

		ods("Pipe: SentInitMsg with w h %d %d", uiWidth, uiHeight);
	}

	std::vector<RECT> blits;

	while (1) {
		DWORD dwBytesLeft;
		DWORD dwBytesRead;

		if (! PeekNamedPipe(hSocket, NULL, 0, NULL, &dwBytesLeft, NULL)) {
			ods("Pipe: Could not peek");
			disconnect();
			return;
		}

		if (! dwBytesLeft)
			break;

		if (omMsg.omh.iLength == -1) {
			if (! ReadFile(hSocket, reinterpret_cast<unsigned char *>(omMsg.headerbuffer) + dwAlreadyRead, sizeof(OverlayMsgHeader) - dwAlreadyRead, &dwBytesRead, NULL)) {
				ods("Pipe: Read header fail");
				disconnect();
				return;
			}

			dwBytesLeft -= dwBytesRead;
			dwAlreadyRead += dwBytesRead;

			if (dwAlreadyRead != sizeof(OverlayMsgHeader)) {
				break;
			}

			dwAlreadyRead = 0;

			if (omMsg.omh.uiMagic != OVERLAY_MAGIC_NUMBER) {
				ods("Pipe: Invalid magic number %x", omMsg.omh.uiMagic);
				disconnect();
				return;
			}

			if (static_cast<int>(dwBytesLeft) < omMsg.omh.iLength)
				continue;
		}

		if (! ReadFile(hSocket, reinterpret_cast<unsigned char *>(omMsg.msgbuffer) + dwAlreadyRead, omMsg.omh.iLength - dwAlreadyRead, &dwBytesRead, NULL)) {
			ods("Pipe: Read data fail");
			disconnect();
			return;
		}

		dwAlreadyRead += dwBytesRead;

		if (static_cast<int>(dwBytesLeft) < omMsg.omh.iLength)
			continue;

		dwAlreadyRead = 0;

		switch (omMsg.omh.uiType) {
			case OVERLAY_MSGTYPE_SHMEM: {
					wchar_t memname[2048];
					memname[0] = 0;

					MultiByteToWideChar(CP_UTF8, 0, omMsg.oms.a_cName, omMsg.omh.iLength, memname, 2048);

					release();

					hMemory = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, uiWidth * uiHeight * 4, memname);

					if (GetLastError() != ERROR_ALREADY_EXISTS) {
						ods("Pipe: Memory %s(%d) => %ls doesn't exist", omMsg.oms.a_cName, omMsg.omh.iLength, memname);
						if (hMemory) {
							CloseHandle(hMemory);
							hMemory = NULL;
							break;
						}
					}

					if (! hMemory) {
						ods("Pipe: CreateFileMapping failed");
						break;
					}

					a_ucTexture = reinterpret_cast<unsigned char *>(MapViewOfFile(hMemory, FILE_MAP_ALL_ACCESS, 0, 0, 0));

					if (a_ucTexture == NULL) {
						ods("Pipe: Failed to map memory");
						CloseHandle(hMemory);
						hMemory = NULL;
						break;
					}

					MEMORY_BASIC_INFORMATION mbi;
					memset(&mbi, 0, sizeof(mbi));
					if ((VirtualQuery(a_ucTexture, &mbi, sizeof(mbi)) == 0) || (mbi.RegionSize < (uiHeight * uiWidth * 4))) {
						ods("Pipe: Memory too small");
						UnmapViewOfFile(a_ucTexture);
						CloseHandle(hMemory);
						a_ucTexture = NULL;
						hMemory = NULL;
						break;
					}

					OverlayMsg om;
					om.omh.uiMagic = OVERLAY_MAGIC_NUMBER;
					om.omh.uiType = OVERLAY_MSGTYPE_SHMEM;
					om.omh.iLength = 0;

					if (!sendMessage(om))
						return;

					newTexture(uiWidth, uiHeight);
				}
				break;
			case OVERLAY_MSGTYPE_BLIT: {
					RECT r = {omMsg.omb.x, omMsg.omb.y, omMsg.omb.x + omMsg.omb.w, omMsg.omb.y + omMsg.omb.h};

					std::vector<RECT>::iterator i = blits.begin();
					while (i != blits.end()) {
						RECT is;
						if (::IntersectRect(&is, &r, & *i)) {
							::UnionRect(&is, &r, & *i);
							r = is;
							blits.erase(i);
							i = blits.begin();
						} else {
							++i;
						}
					}
					blits.push_back(r);
				}
				break;
			case OVERLAY_MSGTYPE_ACTIVE: {
					uiLeft = omMsg.oma.x;
					uiTop = omMsg.oma.y;
					uiRight = omMsg.oma.x + omMsg.oma.w;
					uiBottom = omMsg.oma.y + omMsg.oma.h;
					if (a_ucTexture)
						setRect();
				}
				break;
			default:
				break;
		}
		omMsg.omh.iLength = -1;
	}

	if (!a_ucTexture)
		return;

	for (std::vector<RECT>::iterator i = blits.begin(); i != blits.end(); ++i)
		blit((*i).left, (*i).top, (*i).right - (*i).left, (*i).bottom - (*i).top);
}

static void checkHooks(bool preonly) {
	checkD3D9Hook(preonly);
	checkDXGIHook(preonly);
	checkDXGI10Hook(preonly);
	checkDXGI11Hook(preonly);
	checkOpenGLHook();
}

typedef HMODULE(__stdcall *LoadLibraryAType)(const char *);
static HMODULE WINAPI MyLoadLibrary(const char *lpFileName) {
	//TODO: Move logic to HardHook.
	// Call base without active hook in case of no trampoline.
	LoadLibraryAType oLoadLibrary = (LoadLibraryAType) hhLoad.call;
	hhLoad.restore();
	HMODULE h = oLoadLibrary(lpFileName);
	hhLoad.inject();

	ods("Lib: Library %s loaded to %p", lpFileName, h);

	if (! bBlackListed) {
		checkHooks();
	}

	return h;
}

typedef HMODULE(__stdcall *LoadLibraryWType)(const wchar_t *);
static HMODULE WINAPI MyLoadLibraryW(const wchar_t *lpFileName) {
	//TODO: Move logic to HardHook.
	// Call base without active hook in case of no trampoline.
	LoadLibraryWType oLoadLibrary = (LoadLibraryWType) hhLoadW.call;
	hhLoadW.restore();
	HMODULE h = oLoadLibrary(lpFileName);
	hhLoadW.inject();

	ods("Lib: Library %ls wloaded to %p", lpFileName, h);

	checkForWPF();

	if (! bBlackListed) {
		checkHooks();
	}

	return h;
}

static LRESULT CALLBACK CallWndProc(int nCode, WPARAM wParam, LPARAM lParam) {
	return CallNextHookEx(hhookWnd, nCode, wParam, lParam);
}

extern "C" __declspec(dllexport) void __cdecl RemoveHooks() {
	DWORD dwWaitResult = WaitForSingleObject(hHookMutex, 1000L);
	if (dwWaitResult == WAIT_OBJECT_0) {
		if (sd != NULL && sd->bHooked) {
			if (hhookWnd) {
				UnhookWindowsHookEx(hhookWnd);
				hhookWnd = NULL;
			}
			sd->bHooked = false;
		}
		ReleaseMutex(hHookMutex);
	}
}

extern "C" __declspec(dllexport) void __cdecl InstallHooks() {
	DWORD dwWaitResult = WaitForSingleObject(hHookMutex, 1000L);
	if (dwWaitResult == WAIT_OBJECT_0) {
		if (sd != NULL && ! sd->bHooked) {
			HMODULE hSelf = NULL;
			GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (char *) &InstallHooks, &hSelf);
			if (hSelf == NULL) {
				ods("Lib: Failed to find myself");
			} else {
				hhookWnd = SetWindowsHookEx(WH_CBT, CallWndProc, hSelf, 0);
				if (hhookWnd == NULL)
					ods("Lib: Failed to insert WNDProc hook");
			}

			sd->bHooked = true;
		}
		ReleaseMutex(hHookMutex);
	}
}

extern "C" __declspec(dllexport) unsigned int __cdecl GetOverlayMagicVersion() {
	return OVERLAY_MAGIC_NUMBER;
}

// Via d3d9.cpp
extern "C" __declspec(dllexport) void __cdecl PrepareD3D9();
// Via dxgi.cpp
extern "C" __declspec(dllexport) void __cdecl PrepareDXGI();

void __stdcall OverlayHelperProcessParentDeathThread(void *udata) {
	HANDLE parent = reinterpret_cast<HANDLE>(udata);
	DWORD status = WaitForSingleObject(parent, INFINITE);
	if (status != WAIT_OBJECT_0) {
		ExitProcess(OVERLAY_HELPER_ERROR_DLL_PDEATH_WAIT_FAIL);
	}

	ExitProcess(0);
}

extern "C" __declspec(dllexport) int __cdecl OverlayHelperProcessMain(unsigned int magic, HANDLE parent) {
	int retval = 0;

	if (GetOverlayMagicVersion() != magic) {
		return OVERLAY_HELPER_ERROR_DLL_MAGIC_MISMATCH;
	}

	HANDLE pcheckHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) OverlayHelperProcessParentDeathThread,
	                                   reinterpret_cast<void *>(parent), 0, NULL);
	if (pcheckHandle == 0) {
		return OVERLAY_HELPER_ERROR_DLL_PDEATH_THREAD_ERROR;
	}

	PrepareD3D9();
	PrepareDXGI();

	InstallHooks();

	while (1) {
		MSG msg;
		BOOL ret;

		ret = GetMessage(&msg, NULL, 0, 0);

		// The ret variable is set to 0 on WM_QUIT,
		// and -1 on error.
		if (ret == 0) {
			retval = 0;
			break;
		} else if (ret == -1) {
			retval = -1001;
			break;
		}

		if (msg.message == WM_CLOSE) {
			retval = 0;
			break;
		}

		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	RemoveHooks();

	return retval;
}

static bool dllmainProcAttachCheckProcessIsBlacklisted(char procname[], char *p);
static bool createSharedDataMap();

static void dllmainProcAttach(char *procname) {
	Mutex::init();

	char *p = strrchr(procname, '\\');
	if (!p) {
		// No blacklisting if the file has no path
	} else if (GetProcAddress(NULL, "mumbleSelfDetection") != NULL) {
		ods("Lib: Attached to overlay helper or Mumble process. Blacklisted - no overlay injection.");
		bBlackListed = TRUE;
		bMumble = TRUE;
	} else {
		if (dllmainProcAttachCheckProcessIsBlacklisted(procname, p)) {
			ods("Lib: Process %s is blacklisted - no overlay injection.", procname);
			return;
		}
	}

	OSVERSIONINFOEX ovi;
	memset(&ovi, 0, sizeof(ovi));
	ovi.dwOSVersionInfoSize = sizeof(ovi);
	GetVersionEx(reinterpret_cast<OSVERSIONINFO *>(&ovi));
	bIsWin8 = (ovi.dwMajorVersion >= 7) || ((ovi.dwMajorVersion == 6) && (ovi.dwBuildNumber >= 9200));

	ods("Lib: bIsWin8: %i", bIsWin8);

	hHookMutex = CreateMutex(NULL, false, "MumbleHookMutex");
	if (hHookMutex == NULL) {
		ods("Lib: CreateMutex failed");
		return;
	}

	if(!createSharedDataMap())
		return;

	if (! bMumble) {
		// Hook our own LoadLibrary functions so we notice when a new library (like the d3d ones) is loaded.
		hhLoad.setup(reinterpret_cast<voidFunc>(LoadLibraryA), reinterpret_cast<voidFunc>(MyLoadLibrary));
		hhLoadW.setup(reinterpret_cast<voidFunc>(LoadLibraryW), reinterpret_cast<voidFunc>(MyLoadLibraryW));

		checkHooks(true);
		ods("Lib: Injected into %s", procname);
	}
}

// Is the process black(listed)?
static bool dllmainProcAttachCheckProcessIsBlacklisted(char procname[], char *p) {
	DWORD buffsize = MAX_PATH * 20; // Initial buffer size for registry operation

	bool usewhitelist = false;
	HKEY key = NULL;

	char *buffer = new char[buffsize];

	// check if we're using a whitelist or a blacklist
	DWORD tmpsize = buffsize - 1;
	bool success = (RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\Mumble\\Mumble\\overlay", NULL, KEY_READ, &key) == ERROR_SUCCESS) &&
	          (RegQueryValueExA(key, "usewhitelist", NULL, NULL, (LPBYTE)buffer, &tmpsize) == ERROR_SUCCESS);

	if (success) {
		buffer[tmpsize] = '\0';
		usewhitelist = (_stricmp(buffer, "true") == 0);
		// reset tmpsize to the buffers size (minus 1 char for str-termination), as it was changed by RegQuery
		tmpsize = buffsize - 1;

		// read the whitelist or blacklist (depending on which one we use)
		DWORD ret;
		while ((ret = RegQueryValueExA(key, usewhitelist ? "whitelist" : "blacklist", NULL, NULL, (LPBYTE)buffer, &tmpsize)) == ERROR_MORE_DATA) {
			// Increase the buffsize according to the required size RegQuery wrote into tmpsize, so we can read the whole value
			delete []buffer;
			buffsize = tmpsize + 1;
			buffer = new char[buffsize];
		}

		success = (ret == ERROR_SUCCESS);
	}

	if (key)
		RegCloseKey(key);

	if (success) {
		buffer[tmpsize] = '\0';
		unsigned int pos = 0;

		if (usewhitelist) {
			// check if process is whitelisted
			bool onwhitelist = false;
			while (pos < buffsize && buffer[pos] != 0) {
				if (_stricmp(procname, buffer + pos) == 0 || _stricmp(p+1, buffer + pos) == 0) {
					ods("Lib: Overlay enabled for whitelisted '%s'", buffer + pos);
					onwhitelist = true;
					break;
				}
				pos += static_cast<unsigned int>(strlen(buffer + pos)) + 1;
			}

			if (!onwhitelist) {
				ods("Lib: No whitelist entry found for '%s', auto-blacklisted", procname);
				bBlackListed = TRUE;
				return true;
			}
		} else {
			// check if process is blacklisted
			while (pos < buffsize && buffer[pos] != 0) {
				if (_stricmp(procname, buffer + pos) == 0 || _stricmp(p+1, buffer + pos) == 0) {
					ods("Lib: Overlay blacklist entry found for '%s'", buffer + pos);
					bBlackListed = TRUE;
					return true;
				}
				pos += static_cast<unsigned int>(strlen(buffer + pos)) + 1;
			}
		}
	} else {
		ods("Lib: no blacklist/whitelist found in the registry");
	}

	// As a last resort, if we're using blacklisting, check the built-in blacklist.
	//
	// If the registry query failed this means we're guaranteed to check the
	// built-in list.
	//
	// If the list in the registry is out of sync, for example because the built-
	// in list in overlay_blacklist.h was updated got updated, we're also
	// guaranteed that we include all built-in blacklisted items in our check.
	if (!usewhitelist) {
		ods("Lib: Overlay fallback to default blacklist");
		int i = 0;
		while (overlayBlacklist[i]) {
			if (_stricmp(procname, overlayBlacklist[i]) == 0 || _stricmp(p+1, overlayBlacklist[i])==0) {
				ods("Lib: Overlay default blacklist entry found for '%s'", overlayBlacklist[i]);
				bBlackListed = TRUE;
				return true;
			}
			i++;
		}
	}

	// Make sure to always free/destroy buffer & heap
	delete []buffer;

	// if the processname is already found to be blacklisted, we can stop here
	if (bBlackListed)
		return true;

	// check if there is a "nooverlay" file in the executables folder, which would disable/blacklist the overlay
	// Same buffersize as procname; which we copy from.
	char fname[PROCNAMEFILEPATH_EXTENDED_BUFFER_BUFLEN];

	size_t pathlength = static_cast<size_t>(p - procname);
	p = fname + pathlength;
	strncpy_s(fname, sizeof(fname), procname, pathlength + 1);

	strcpy_s(p+1, PROCNAMEFILEPATH_EXTENDED_EXTLEN, "nooverlay");
	HANDLE h = CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (h != INVALID_HANDLE_VALUE) {
		CloseHandle(h);
		ods("Lib: Overlay disable %s found", fname);
		bBlackListed = TRUE;
		return true;
	}

	// check for "debugoverlay" file, which would enable overlay debugging
	strcpy_s(p+1, PROCNAMEFILEPATH_EXTENDED_EXTLEN, "debugoverlay");
	h = CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (h != INVALID_HANDLE_VALUE) {
		CloseHandle(h);
		ods("Lib: Overlay debug %s found", fname);
		bDebug = TRUE;
	}

	// check for blacklisting for loading WPF library
	checkForWPF();

	if (bBlackListed)
		return true;

	return false;
}

static bool createSharedDataMap() {
	DWORD dwSharedSize = sizeof(SharedData) + sizeof(Direct3D9Data) + sizeof(DXGIData) + sizeof(D3D10Data) + sizeof(D3D11Data);

#if defined(_M_IX86)
	const char *name = "MumbleOverlayPrivate-x86";
#elif defined(_M_X64)
	const char *name = "MumbleOverlayPrivate-x64";
#else
# error Unsupported architecture
#endif

	hMapObject = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, dwSharedSize, name);
	if (hMapObject == NULL) {
		ods("Lib: CreateFileMapping failed");
		return false;
	}

	//Note: If the mapping exists dwSharedSize value will be ignored and existing handle returned
	bool bInit = (GetLastError() != ERROR_ALREADY_EXISTS);

	unsigned char *rawSharedPointer = static_cast<unsigned char *>(
			MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, dwSharedSize));

	if (rawSharedPointer == NULL) {
		ods("Lib: MapViewOfFile failed");
		return false;
	}

	if (bInit)
		memset(rawSharedPointer, 0, dwSharedSize);

	sd = reinterpret_cast<SharedData *>(rawSharedPointer);
	rawSharedPointer += sizeof(SharedData);

	d3dd = reinterpret_cast<Direct3D9Data *>(rawSharedPointer);
	rawSharedPointer += sizeof(Direct3D9Data);

	dxgi = reinterpret_cast<DXGIData *>(rawSharedPointer);
	rawSharedPointer += sizeof(DXGIData);

	d3d10 = reinterpret_cast<D3D10Data *>(rawSharedPointer);
	rawSharedPointer += sizeof(D3D10Data);

	d3d11 = reinterpret_cast<D3D11Data *>(rawSharedPointer);
	rawSharedPointer += sizeof(D3D11Data);

	return true;
}

static void dllmainProcDetach() {

	hhLoad.restore(true);
	hhLoad.reset();
	hhLoadW.restore(true);
	hhLoadW.reset();

	if (sd)
		UnmapViewOfFile(sd);
	if (hMapObject)
		CloseHandle(hMapObject);
	if (hHookMutex)
		CloseHandle(hHookMutex);
}

static void dllmainThreadAttach() {
	static bool bTriedHook = false;
	if (!bBlackListed && sd && ! bTriedHook) {
		bTriedHook = true;
		checkForWPF();

		if (!bBlackListed) {
			ods("Lib: Checking for hooks, potentially injecting");
			checkHooks();
		}
	}
}

extern "C" BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID) {

	char procname[PROCNAMEFILEPATH_EXTENDED_BUFFER_BUFLEN];
	GetModuleFileNameA(NULL, procname, ARRAY_NUM_ELEMENTS(procname));
	// Fix for windows XP; on length nSize does not include null-termination
	// @see http://msdn.microsoft.com/en-us/library/windows/desktop/ms683197%28v=vs.85%29.aspx
	procname[ARRAY_NUM_ELEMENTS(procname) - 1] = '\0';

	switch (fdwReason) {
		case DLL_PROCESS_ATTACH:
			ods("Lib: ProcAttach: %s", procname);
			dllmainProcAttach(procname);
			break;
		case DLL_PROCESS_DETACH:
			ods("Lib: ProcDetach: %s", procname);
			dllmainProcDetach();
			break;
		case DLL_THREAD_ATTACH:
			ods("Lib: ThreadAttach: %s", procname);
			dllmainThreadAttach();
			break;
		default:
			break;
	}
	return TRUE;
}

bool IsFnInModule(voidFunc fnptr, wchar_t *refmodulepath, const std::string &logPrefix, const std::string &fnName) {

	HMODULE hModule = NULL;

	BOOL success = GetModuleHandleEx(
			GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
			reinterpret_cast<LPCSTR>(fnptr), &hModule);
	if (!success) {
		ods((logPrefix + ": Failed to get module for " + fnName).c_str());
	} else {
		wchar_t modulename[MODULEFILEPATH_BUFLEN];
		GetModuleFileNameW(hModule, modulename, ARRAY_NUM_ELEMENTS(modulename));
		return _wcsicmp(modulename, refmodulepath) == 0;
	}
	return false;
}

int GetFnOffsetInModule(voidFunc fnptr, wchar_t *refmodulepath, unsigned int refmodulepathLen, const std::string &logPrefix, const std::string &fnName) {

	HMODULE hModule = NULL;

	if (! GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (char *) fnptr, &hModule)) {
		ods((logPrefix + ": Failed to get module for " + fnName).c_str());
		return -1;
	}

	const bool bInit = refmodulepath[0] == '\0';
	if (bInit) {
		GetModuleFileNameW(hModule, refmodulepath, refmodulepathLen);
	} else {
		wchar_t modulename[MODULEFILEPATH_BUFLEN];
		GetModuleFileNameW(hModule, modulename, ARRAY_NUM_ELEMENTS(modulename));
		if (_wcsicmp(modulename, refmodulepath) != 0) {
			ods((logPrefix + ": " + fnName + " functions module path does not match previously found. Now: '%ls', Previously: '%ls'").c_str(), modulename, refmodulepath);
			return -2;
		}
	}

	unsigned char *fn = reinterpret_cast<unsigned char *>(fnptr);
	unsigned char *base = reinterpret_cast<unsigned char *>(hModule);
	unsigned long off = static_cast<unsigned long>(fn - base);

	// XXX: convert this function to use something other than int.
	// Issue mumble-voip/mumble#1924.
	if (off > static_cast<unsigned long>(std::numeric_limits<int>::max())) {
		ods("Internal overlay error: GetFnOffsetInModule() offset greater than return type can hold.");
		return -1;
	}

	return static_cast<int>(off);
}


text:
layout: page
title: Quality Lotus Solutions Seminar
date: 2016-05-24
author: Jacqueline Valentine
tags: weekly links, java
status: published
summary: Morbi eget elit nec nisl sodales rutrum. In.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 09/27/2019
  endDate: 10/01/2019
  ctyhocn: SHVBSHX
  groupCode: QLSS
published: true
---
Sed quis feugiat ex, condimentum rhoncus ex. Aliquam nulla metus, pretium eget tempus ac, ultricies eget erat. Vivamus sed fringilla urna, in convallis justo. Etiam eget sapien fermentum, suscipit massa sed, aliquam diam. Praesent fermentum placerat leo at rhoncus. Ut porttitor, quam vel fringilla ullamcorper, ante mi suscipit metus, hendrerit condimentum dolor massa eu odio. Suspendisse faucibus enim id arcu pulvinar, ut tempor felis fringilla. Phasellus ac eleifend lacus. Morbi lobortis ante consectetur dolor elementum luctus. Suspendisse vel rutrum metus, ut scelerisque sem. Duis elementum finibus massa, at pretium lectus pharetra et. Phasellus condimentum finibus quam sit amet accumsan.

* Ut gravida lacus ac ex suscipit venenatis
* Duis scelerisque eros sed arcu pellentesque mattis
* Etiam iaculis turpis vel consequat vulputate
* Vestibulum sit amet nisi a sapien commodo scelerisque
* Nunc a est nec velit fringilla rutrum eget eleifend orci.

Ut mattis ultricies eros eu malesuada. Cras pharetra ligula vitae efficitur accumsan. Curabitur eget fringilla enim. In dapibus, erat in varius pellentesque, purus nisl interdum mauris, eu gravida nisi lorem in felis. Praesent gravida imperdiet vehicula. Cras rutrum urna eget tempus euismod. Nam molestie mollis bibendum. Ut lectus mauris, malesuada vel maximus id, feugiat sit amet urna.


text:
<?php

namespace Eva\Form;

use Eva\Html\Input as HtmlInput;

class Input extends HtmlInput implements ElementInterface
{
    use ElementTrait;

    public function setValue($value)
    {
        if ($this->getAttribute('type') == 'checkbox') {
            if ($value) {
                $this->setAttribute('checked', 'checked');
            }
        }

        $this->value = $value;

        return $this;
    }
}


text:
<?php

namespace App\Http\Controllers\plt\prod;

use App\Http\Controllers\Controller;

class PltRcpController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        return view('plt.prod.rcp');
    }
}


text:
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

Mueve los marcadores.


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <rotate
        android:fromDegrees="0"
        android:toDegrees="15"
        android:pivotX="50%"
        android:pivotY="50%"
        />

</set>


text:
package com.google.android.gms.internal;

import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.google.android.gms.common.internal.safeparcel.a;
import com.google.android.gms.common.internal.safeparcel.a.a;
import com.google.android.gms.common.internal.safeparcel.b;
import java.util.HashSet;
import java.util.Set;

public class ij
  implements Parcelable.Creator<ig.b>
{
  static void a(ig.b paramb, Parcel paramParcel, int paramInt)
  {
    int i = b.o(paramParcel);
    Set localSet = paramb.fa();
    if (localSet.contains(Integer.valueOf(1)))
      b.c(paramParcel, 1, paramb.getVersionCode());
    if (localSet.contains(Integer.valueOf(2)))
      b.a(paramParcel, 2, paramb.fE(), paramInt, true);
    if (localSet.contains(Integer.valueOf(3)))
      b.a(paramParcel, 3, paramb.fF(), paramInt, true);
    if (localSet.contains(Integer.valueOf(4)))
      b.c(paramParcel, 4, paramb.getLayout());
    b.D(paramParcel, i);
  }

  public ig.b aw(Parcel paramParcel)
  {
    int i = a.n(paramParcel);
    HashSet localHashSet = new HashSet();
    int j = 0;
    ig.b.a locala = null;
    ig.b.b localb = null;
    int k = 0;
    while (paramParcel.dataPosition() < i)
    {
      int m = a.m(paramParcel);
      switch (a.M(m))
      {
      default:
        break;
      case 1:
        j = a.g(paramParcel, m);
        localHashSet.add(Integer.valueOf(1));
        break;
      case 2:
        locala = (ig.b.a)a.a(paramParcel, m, ig.b.a.CREATOR);
        localHashSet.add(Integer.valueOf(2));
        break;
      case 3:
        localb = (ig.b.b)a.a(paramParcel, m, ig.b.b.CREATOR);
        localHashSet.add(Integer.valueOf(3));
        break;
      case 4:
        k = a.g(paramParcel, m);
        localHashSet.add(Integer.valueOf(4));
        continue;
        a.b(paramParcel, m);
      }
    }
    if (paramParcel.dataPosition() != i)
      throw new a.a("Overread allowed size end=" + i, paramParcel);
    return new ig.b(localHashSet, j, locala, localb, k);
  }

  public ig.b[] bo(int paramInt)
  {
    return new ig.b[paramInt];
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.google.android.gms.internal.ij
 * JD-Core Version:    0.6.2
 */


text:
package io.reactivesocket.integration;

import io.reactivesocket.AbstractReactiveSocket;
import io.reactivesocket.Payload;
import io.reactivesocket.ReactiveSocket;
import io.reactivesocket.client.KeepAliveProvider;
import io.reactivesocket.client.ReactiveSocketClient;
import io.reactivesocket.client.SetupProvider;
import io.reactivesocket.lease.DisabledLeaseAcceptingSocket;
import io.reactivesocket.server.ReactiveSocketServer;
import io.reactivesocket.transport.TransportServer.StartedServer;
import io.reactivesocket.transport.tcp.client.TcpTransportClient;
import io.reactivesocket.transport.tcp.server.TcpTransportServer;
import io.reactivesocket.util.PayloadImpl;
import io.reactivex.Flowable;
import io.reactivex.Single;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.reactivestreams.Publisher;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

public class IntegrationTest {

    @Rule
    public final ClientServerRule rule = new ClientServerRule();

    @Test(timeout = 2_000L)
    public void testRequest() {
        Flowable.fromPublisher(rule.client.requestResponse(new PayloadImpl("REQUEST", "META")))
                .blockingFirst();
        assertThat("Server did not see the request.", rule.requestCount.get(), is(1));
    }

    @Test(timeout = 2_000L)
    public void testClose() throws ExecutionException, InterruptedException, TimeoutException {
        Flowable.fromPublisher(rule.client.close()).ignoreElements().blockingGet();
        Thread.sleep(100);
        assertThat("Server did not disconnect.", rule.disconnectionCounter.get(), is(1));
    }

    public static class ClientServerRule extends ExternalResource {

        private StartedServer server;
        private ReactiveSocket client;
        private AtomicInteger requestCount;
        private AtomicInteger disconnectionCounter;

        @Override
        public Statement apply(final Statement base, Description description) {
            return new Statement() {
                @Override
                public void evaluate() throws Throwable {
                    requestCount = new AtomicInteger();
                    disconnectionCounter = new AtomicInteger();
                    server = ReactiveSocketServer.create(TcpTransportServer.create())
                                        .start((setup, sendingSocket) -> {
                                            Flowable.fromPublisher(sendingSocket.onClose())
                                                .doOnTerminate(() -> disconnectionCounter.incrementAndGet())
                                                .subscribe();

                                            return new DisabledLeaseAcceptingSocket(new AbstractReactiveSocket() {
                                                @Override
                                                public Publisher<Payload> requestResponse(Payload payload) {
                                                    return Flowable.<Payload>just(new PayloadImpl("RESPONSE", "METADATA"))
                                                            .doOnSubscribe(s -> requestCount.incrementAndGet());
                                                }
                                            });
                                        });
                    client = Single.fromPublisher(ReactiveSocketClient.create(TcpTransportClient.create(server.getServerAddress()),
                                                                     SetupProvider.keepAlive(KeepAliveProvider.never())
                                                                                .disableLease())
                                                             .connect())
                                   .blockingGet();
                    base.evaluate();
                }
            };
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants"
    android:orientation="horizontal">

    <RatingBar
        android:id="@+id/rate_img"
        style="@style/ratingBarStyle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:maxWidth="20dp"
        android:minWidth="20dp"
        android:numStars="5"
        android:stepSize="1" />

    <TextView
        android:id="@+id/text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="0.5"
        android:gravity="center"
        android:textStyle="bold" />

</LinearLayout>


text:
#ifndef slideshow_h_
#define slideshow_h_

#include "screen.h"

//////////////////////////////////////////////////////////////////////////////
//
// Slideshow Screen
//
//////////////////////////////////////////////////////////////////////////////

class Slideshow :
    public Screen,
    public IEventSink,
    public IKeyboardInput
{
    private:
        TRef<IObjectList>       m_pSlideList;
        TRef<Image>             m_pImage;
        TRef<WrapImage>         m_pWrapImage;
        bool                    m_bNextSlide;
        TRef<ISoundInstance>    m_pSoundInstance;
        TRef<IKeyboardInput>    m_pkeyboardInputOldFocus;
        TRef<IEventSink>        m_pEventSink;
        bool                    m_bInTimer;

        class PickImage : public Image
        {
            private:
                Slideshow*  m_pSlideshow;

            public:
                PickImage (Slideshow* pSlideshow) :
                    m_pSlideshow(pSlideshow)
                {
                }

                MouseResult HitTest (IInputProvider* pProvider, const Point& point)
                {
                    return MouseResultHit();
                }

                MouseResult Button (IInputProvider* pProvider, const Point& point, int button, bool bCaptured, bool bInside, bool bDown)
                {
                    if (bDown)
                        m_pSlideshow->Picked();
                    return MouseResult();
                }
        };

                void        CleanUpTimers (void);
                void        StopSound (void);

        static  bool        m_bIsInSlideShow;

    public:
                /* void */  Slideshow (Modeler* pmodeler, const ZString& strNamespace);
                /* void */  ~Slideshow (void);
                void        NextSlide (void);
        virtual Image*      GetImage (void);
        virtual void        OnFrame (void);
        virtual void        Dismiss (void);
        virtual bool        OnEvent (IEventSource* pevent);
        virtual void        Picked (void);
        virtual bool        OnKey (IInputProvider* pprovider, const KeyState& ks, bool& fForceTranslate);
        static  bool        IsInSlideShow (void);
};

#endif


text:
import pytest
from pexpect import TIMEOUT
from tests.functional.utils import spawn, functional, bare

envs = ((u'bash', 'ubuntu-bash', u'''
FROM ubuntu:latest
RUN apt-get update
RUN apt-get install -yy bash
'''), (u'bash', 'generic-bash', u'''
FROM fedora:latest
RUN dnf install -yy python-devel sudo which gcc
'''))

@functional
@pytest.mark.skipif(
    bool(bare), reason="Can't be tested in bare run")
@pytest.mark.parametrize('shell, tag, dockerfile', envs)
def test_installation(request, shell, tag, dockerfile):
    proc = spawn(request, tag, dockerfile, shell, install=False)
    proc.sendline(u'cat /src/install.sh | sh - && $0')
    proc.sendline(u'thefuck --version')
    assert proc.expect([TIMEOUT, u'The Fuck'], timeout=600)
    proc.sendline(u'fuck')
    assert proc.expect([TIMEOUT, u'No fucks given'])


text:
<?xml version="1.0" encoding="UTF-8"?><!--
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
-->
<assembly>
  <id>php</id>
  <formats>
    <format>zip</format>
    <format>tar.gz</format>
    <format>tar.bz2</format>
  </formats>
  <includeBaseDirectory>false</includeBaseDirectory>
  <fileSets>
    <fileSet>
      <outputDirectory>shindig-${pom.version}-php</outputDirectory>
      <directory>../</directory>
      <includes>
        <include>features/**</include>
        <include>javascript/**</include>
        <include>config/**</include>
        <include>DISCLAIMER</include>
      </includes>
      <excludes>
        <exclude>site/**</exclude>
        <exclude>resources/**</exclude>
        <exclude>etc/**</exclude>
        <exclude>assembly/**</exclude>
        <exclude>java/**</exclude>
        <!-- scm -->
        <exclude>**/.git/**</exclude>
        <exclude>**/.svn/**</exclude>
        <!-- IDE -->
        <exclude>**/*.iws</exclude>
        <exclude>**/*.ipr</exclude>
        <exclude>**/*.iml</exclude>
        <exclude>**/.project/**</exclude>
        <exclude>**/.classpath/**</exclude>
        <exclude>**/.settings/**</exclude>
        <exclude>**/.externalToolBuilders/**</exclude>
        <exclude>**/maven-eclipse.xml</exclude>
        <exclude>**/.deployables/**</exclude>
        <exclude>**/.wtpmodules/**</exclude>
        <!-- maven -->
        <exclude>**/pom.xml</exclude>
        <exclude>**/target/**</exclude>
        <!-- misc -->
        <exclude>*.patch</exclude>
        <exclude>*.diff</exclude>
        <exclude>LICENSE</exclude>
        <exclude>NOTICE</exclude>
        <exclude>README</exclude>
      </excludes>
    </fileSet>
    <fileSet>
      <outputDirectory>shindig-${pom.version}-php</outputDirectory>
      <directory>../php</directory>
      <excludes>
        <exclude>config/**</exclude>
        <!-- scm -->
        <exclude>**/.git/**</exclude>
        <exclude>**/.svn/**</exclude>
        <!-- IDE -->
        <exclude>**/*.iws</exclude>
        <exclude>**/*.ipr</exclude>
        <exclude>**/*.iml</exclude>
        <exclude>**/.project/**</exclude>
        <exclude>**/.classpath/**</exclude>
        <exclude>**/.settings/**</exclude>
        <exclude>**/.externalToolBuilders/**</exclude>
        <exclude>**/maven-eclipse.xml</exclude>
        <exclude>**/.deployables/**</exclude>
        <exclude>**/.wtpmodules/**</exclude>
        <!-- maven -->
        <exclude>**/pom.xml</exclude>
        <exclude>**/target/**</exclude>
        <!-- misc -->
        <exclude>*.patch</exclude>
        <exclude>*.diff</exclude>
        <exclude>*.zip</exclude>
        <exclude>*.tar.gz</exclude>
        <exclude>*.tar.bz2</exclude>
        <exclude>*.sh</exclude>
        <exclude>*.bat</exclude>
        <exclude>**/*.log</exclude>
        <exclude>**/*.bak</exclude>

        <exclude>NOTICE</exclude>
        <exclude>README</exclude>
      </excludes>
    </fileSet>
    <!-- Using the temp container.php created by Maven using Antrun plugin to rewrite
      default configuration to release structure -->
    <fileSet>
      <outputDirectory>shindig-${pom.version}-php/config</outputDirectory>
      <directory>target/php/config</directory>
      <excludes>
        <!-- scm -->
        <exclude>**/.git/**</exclude>
        <exclude>**/.svn/**</exclude>
      </excludes>
    </fileSet>
  </fileSets>
  <files>
    <file>
      <source>../php/README</source>
      <outputDirectory>shindig-${pom.version}-php</outputDirectory>
      <filtered>true</filtered>
    </file>
    <file>
      <source>../php/NOTICE</source>
      <outputDirectory>shindig-${pom.version}-php</outputDirectory>
      <filtered>true</filtered>
    </file>
  </files>
</assembly>


text:
Storm is a distributed realtime computation system. Similar to how Hadoop provides a set of general primitives for doing batch processing, Storm provides a set of general primitives for doing realtime computation. Storm is simple, can be used with any programming language, [is used by many companies](https://github.com/nathanmarz/storm/wiki/Powered-By), and is a lot of fun to use!

The [Rationale page](https://github.com/nathanmarz/storm/wiki/Rationale) on the wiki explains what Storm is and why it was built. [This presentation](http://vimeo.com/40972420) is also a good introduction to the project.

Storm has a website at [storm-project.net](http://storm-project.net). Follow [@stormprocessor](https://twitter.com/stormprocessor) on Twitter for updates on the project.

## Documentation

Documentation and tutorials can be found on the [Storm wiki](http://github.com/nathanmarz/storm/wiki).

Developers and contributors should also take a look at our [Developer documentation](DEVELOPER.md).

## Getting help

__NOTE:__ The google groups account storm-user@googlegroups.com is now officially deprecated in favor of the Apache-hosted user/dev mailing lists.

### Storm Users
Storm users should send messages and subscribe to [user@storm.incubator.apache.org](mailto:user@storm.incubator.apache.org).

You can subscribe to this list by sending an email to [user-subscribe@storm.incubator.apache.org](mailto:user-subscribe@storm.incubator.apache.org). Likewise, you can cancel a subscription by sending an email to [user-unsubscribe@storm.incubator.apache.org](mailto:user-unsubscribe@storm.incubator.apache.org).

You can also [browse the archives of the storm-user mailing list](http://mail-archives.apache.org/mod_mbox/incubator-storm-user/).

### Storm Developers
Storm developers should send messages and subscribe to [dev@storm.incubator.apache.org](mailto:dev@storm.incubator.apache.org).

You can subscribe to this list by sending an email to [dev-subscribe@storm.incubator.apache.org](mailto:dev-subscribe@storm.incubator.apache.org). Likewise, you can cancel a subscription by sending an email to [dev-unsubscribe@storm.incubator.apache.org](mailto:dev-unsubscribe@storm.incubator.apache.org).

You can also [browse the archives of the storm-dev mailing list](http://mail-archives.apache.org/mod_mbox/incubator-storm-dev/).

### Which list should I send/subscribe to?
If you are using a pre-built binary distribution of Storm, then chances are you should send questions, comments, storm-related announcements, etc. to [user@storm.apache.incubator.org](user@storm.apache.incubator.org).

If you are building storm from source, developing new features, or otherwise hacking storm source code, then [dev@storm.incubator.apache.org](dev@storm.incubator.apache.org) is more appropriate.

### What will happen with storm-user@googlegroups.com?
All existing messages will remain archived there, and can be accessed/searched [here](https://groups.google.com/forum/#!forum/storm-user).

New messages sent to storm-user@googlegroups.com will either be rejected/bounced or replied to with a message to direct the email to the appropriate Apache-hosted group.

### IRC
You can also come to the #storm-user room on [freenode](http://freenode.net/). You can usually find a Storm developer there to help you out.

## License

Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.

## Project lead

* Nathan Marz ([@nathanmarz](http://twitter.com/nathanmarz))

## Committers

* James Xu ([@xumingming](https://github.com/xumingming))
* Jason Jackson ([@jason_j](http://twitter.com/jason_j))
* Andy Feng ([@anfeng](https://github.com/anfeng))
* Flip Kromer ([@mrflip](https://github.com/mrflip))
* David Lao ([@davidlao2k](https://github.com/davidlao2k))
* P. Taylor Goetz ([@ptgoetz](https://github.com/ptgoetz))
* Derek Dagit ([@d2r](https://github.com/d2r))
* Robert Evans ([@revans2](https://github.com/revans2))
* Michael G. Noll ([@miguno](https://github.com/miguno))

## Contributors

* Christopher Bertels ([@bakkdoor](http://twitter.com/bakkdoor))
* Michael Montano ([@michaelmontano](http://twitter.com/michaelmontano))
* Dennis Zhuang ([@killme2008](https://github.com/killme2008))
* Trevor Smith ([@trevorsummerssmith](https://github.com/trevorsummerssmith))
* Ben Hughes ([@schleyfox](https://github.com/schleyfox))
* Alexey Kachayev ([@kachayev](https://github.com/kachayev))
* Haitao Yao ([@haitaoyao](https://github.com/haitaoyao))
* Dan Dillinger ([@ddillinger](https://github.com/ddillinger))
* Kang Xiao ([@xiaokang](https://github.com/xiaokang))
* Gabriel Grant ([@gabrielgrant](https://github.com/gabrielgrant))
* Travis Wellman ([@travisfw](https://github.com/travisfw))
* Kasper Madsen ([@KasperMadsen](https://github.com/KasperMadsen))
* Michael Cetrulo ([@git2samus](https://github.com/git2samus))
* Thomas Jack ([@tomo](https://github.com/tomo))
* Nicolas Yzet ([@nicoo](https://github.com/nicoo))
* Fabian Neumann ([@hellp](https://github.com/hellp))
* Soren Macbeth ([@sorenmacbeth](https://github.com/sorenmacbeth))
* Ashley Brown ([@ashleywbrown](https://github.com/ashleywbrown))
* Guanpeng Xu ([@herberteuler](https://github.com/herberteuler))
* Vinod Chandru ([@vinodc](https://github.com/vinodc))
* Martin Kleppmann ([@ept](https://github.com/ept))
* Evan Chan ([@velvia](https://github.com/velvia))
* Sjoerd Mulder ([@sjoerdmulder](https://github.com/sjoerdmulder))
* Yuta Okamoto ([@okapies](https://github.com/okapies))
* Barry Hart ([@barrywhart](https://github.com/barrywhart))
* Sergey Lukjanov ([@Frostman](https://github.com/Frostman))
* Ross Feinstein ([@rnfein](https://github.com/rnfein))
* Junichiro Takagi ([@tjun](https://github.com/tjun))
* Bryan Peterson ([@Lazyshot](https://github.com/Lazyshot))
* Sam Ritchie ([@sritchie](https://github.com/sritchie))
* Stuart Anderson ([@emblem](https://github.com/emblem))
* Lorcan Coyle ([@lorcan](https://github.com/lorcan))
* Andrew Olson ([@noslowerdna](https://github.com/noslowerdna))
* Gavin Li ([@lyogavin](https://github.com/lyogavin))
* Tudor Scurtu ([@tscurtu](https://github.com/tscurtu))
* Homer Strong ([@strongh](https://github.com/strongh))
* Sean Melody ([@srmelody](https://github.com/srmelody))
* Jake Donham ([@jaked](https://github.com/jaked))
* Ankit Toshniwal ([@ankitoshniwal](https://github.com/ankitoshniwal))

## Acknowledgements

YourKit is kindly supporting open source projects with its full-featured Java Profiler. YourKit, LLC is the creator of innovative and intelligent tools for profiling Java and .NET applications. Take a look at YourKit's leading software products: [YourKit Java Profiler](http://www.yourkit.com/java/profiler/index.jsp) and [YourKit .NET Profiler](http://www.yourkit.com/.net/profiler/index.jsp).


text:
package cmd

import (
	"fmt"

	"github.com/cilium/cilium/pkg/bpf"
	"github.com/cilium/cilium/pkg/command"
	"github.com/cilium/cilium/pkg/common"
	"github.com/cilium/cilium/pkg/loadbalancer"
	"github.com/cilium/cilium/pkg/maps/lbmap"

	"github.com/spf13/cobra"
)

const (
	idTitle             = "ID"
	serviceAddressTitle = "SERVICE ADDRESS"
	backendAddressTitle = "BACKEND ADDRESS"
)

var (
	listRevNAT bool
)

func dumpRevNat(serviceList map[string][]string) {
	if err := lbmap.RevNat4Map.DumpIfExists(serviceList); err != nil {
		Fatalf("Unable to dump IPv4 reverse NAT table: %s", err)
	}
	if err := lbmap.RevNat6Map.DumpIfExists(serviceList); err != nil {
		Fatalf("Unable to dump IPv6 reverse NAT table: %s", err)
	}
}

func dumpSVC(serviceList map[string][]string) {
	// It's safe to use the same map for both IPv4 and IPv6, as backend
	// IDs are allocated from the same pool regardless the protocol
	backendMap := make(map[loadbalancer.BackendID]lbmap.BackendValue)

	parseBackendEntry := func(key bpf.MapKey, value bpf.MapValue) {
		id := key.(lbmap.BackendKey).GetID()
		backendMap[id] = value.DeepCopyMapValue().(lbmap.BackendValue).ToHost()
	}
	if err := lbmap.Backend4Map.DumpWithCallbackIfExists(parseBackendEntry); err != nil {
		Fatalf("Unable to dump IPv4 backends table: %s", err)
	}
	if err := lbmap.Backend6Map.DumpWithCallbackIfExists(parseBackendEntry); err != nil {
		Fatalf("Unable to dump IPv6 backends table: %s", err)
	}

	parseSVCEntry := func(key bpf.MapKey, value bpf.MapValue) {
		var entry string

		svcKey := key.(lbmap.ServiceKey)
		svcVal := value.(lbmap.ServiceValue).ToHost()
		svc := svcKey.String()
		svcKey = svcKey.ToHost()
		revNATID := svcVal.GetRevNat()
		backendID := svcVal.GetBackendID()
		flags := loadbalancer.ServiceFlags(svcVal.GetFlags())

		if svcKey.GetBackendSlot() == 0 {
			ip := "0.0.0.0"
			if svcKey.IsIPv6() {
				ip = "[::]"
			}
			entry = fmt.Sprintf("%s:%d (%d) [%s]", ip, 0, revNATID, flags)
		} else if backend, found := backendMap[backendID]; !found {
			entry = fmt.Sprintf("backend %d not found", backendID)
		} else {
			fmtStr := "%s:%d (%d)"
			if svcKey.IsIPv6() {
				fmtStr = "[%s]:%d (%d)"
			}
			entry = fmt.Sprintf(fmtStr, backend.GetAddress(),
				backend.GetPort(), revNATID)
		}

		serviceList[svc] = append(serviceList[svc], entry)
	}

	if err := lbmap.Service4MapV2.DumpWithCallbackIfExists(parseSVCEntry); err != nil {
		Fatalf("Unable to dump IPv4 services table: %s", err)
	}
	if err := lbmap.Service6MapV2.DumpWithCallbackIfExists(parseSVCEntry); err != nil {
		Fatalf("Unable to dump IPv6 services table: %s", err)
	}
}

// bpfLBListCmd represents the bpf_lb_list command
var bpfLBListCmd = &cobra.Command{
	Use:     "list",
	Aliases: []string{"ls"},
	Short:   "List load-balancing configuration",
	Run: func(cmd *cobra.Command, args []string) {
		common.RequireRootPrivilege("cilium bpf lb list")

		// Ensure that the BPF map objects have been initialized before trying
		// to list them. Note, this is _not_ creating a new map, but rather
		// initializing the Go object representing the map. We don't need to
		// pass the correct sizes here because once the maps are opened, their
		// size will be read.
		lbmap.Init(lbmap.InitParams{IPv4: true, IPv6: true})

		var firstTitle string
		serviceList := make(map[string][]string)
		switch {
		case listRevNAT:
			firstTitle = idTitle
			dumpRevNat(serviceList)
		default:
			firstTitle = serviceAddressTitle
			dumpSVC(serviceList)
		}

		if command.OutputJSON() {
			if err := command.PrintOutput(serviceList); err != nil {
				Fatalf("Unable to generate JSON output: %s", err)
			}
			return
		}

		TablePrinter(firstTitle, backendAddressTitle, serviceList)
	},
}

func init() {
	bpfLBCmd.AddCommand(bpfLBListCmd)
	bpfLBListCmd.Flags().BoolVarP(&listRevNAT, "revnat", "", false, "List reverse NAT entries")
	command.AddJSONOutput(bpfLBListCmd)
}


text:
PACKAGENAME=cv4tw

package:
	ctanify --pkgname $(PACKAGENAME) examples/*.pdf examples/*.tex *.cls *.sty README.md LICENSE


text:
/*global obelisk:true*/

/*
 * Slope East
 */

(function (obelisk) {
    "use strict";

    var SlopeEast, p;
    SlopeEast = function (dimension, color, border, useDefaultCanvas) {
        this.initialize(dimension, color, border, useDefaultCanvas);
    };
    p = SlopeEast.prototype = new obelisk.AbstractPrimitive();

    // constructor
    p.initialize = function (dimension, color, border, useDefaultCanvas) {
        this.initRender(dimension, color, border, useDefaultCanvas);
        this.initRectangle();
        this.initBitmapData();
        this.build();
        this.renderBitmapDataForCanvas();
        return this;
    };

    // private method
    p.initRender = function (dimension, color, border, useDefaultCanvas) {
        this.useDefaultCanvas = useDefaultCanvas || false;
        this.border = border || border === undefined;
        this.dimension = dimension === undefined ? new obelisk.SlopeDimension() : dimension;
        this.color = color === undefined ? new obelisk.SlopeColor() : color;
    };

    p.initRectangle = function () {

        this.w = this.dimension.xAxis + this.dimension.yAxis;
        this.h = this.dimension.xAxis * 2 + this.dimension.yAxis / 2;

        // 22.6 degrees implementation
        this.w -= 2;
        this.h -= 3;

        // the matrix offset between the bitmap and the 3d pixel coordinate ZERO point
        this.matrix = new obelisk.Matrix();
        this.matrix.tx = -(this.dimension.yAxis - 2);
        this.matrix.ty = -(this.dimension.xAxis * 3 / 2 - 2);
    };

    p.initBitmapData = function () {
        this.bitmapData = new obelisk.BitmapData(this.w, this.h, this.useDefaultCanvas);
    };
    p.renderBitmapDataForCanvas = function () {
        this.bitmapData.context.putImageData(this.bitmapData.imageData, 0, 0);
        this.canvas = this.bitmapData.canvas;
    };

    p.build = function () {
        var colorBorderLeft, colorBorderRight,
            i, j, k, m, n;

        colorBorderLeft = this.border ? this.color.border : this.color.left;
        colorBorderRight = this.border ? this.color.border : this.color.rightSlope;

        // y axis
        for (j = 0; j < this.dimension.yAxis; j += 1) {
            this.bitmapData.setPixel(j, this.dimension.yAxis / 2 - Math.floor(j / 2) - 1, colorBorderRight);
            this.bitmapData.setPixel(j + this.dimension.xAxis - 2, this.h - Math.floor(j / 2) - 1, colorBorderRight);
        }

        // x axis
        for (i = 0; i < this.dimension.xAxis; i += 1) {
            this.bitmapData.setPixel(i, this.h - this.dimension.xAxis / 2 + Math.floor(i / 2), colorBorderLeft);
        }

        // z axis
        for (k = this.dimension.yAxis / 2 - 1; k < this.h - this.dimension.xAxis / 2; k += 1) {
            this.bitmapData.setPixel(0, k, colorBorderLeft);
        }

        // slot
        for (m = 0; m < this.dimension.xAxis * 2 - 2; m += 1) {
            this.bitmapData.setPixel(this.dimension.yAxis - 1 + Math.floor(m / 2), m, colorBorderRight);
            this.bitmapData.setPixel(1 + Math.floor(m / 2), this.dimension.yAxis / 2 + m - 1, colorBorderRight);
        }

        // flood fill
        this.bitmapData.floodFill(this.dimension.yAxis - 2, 1, this.color.rightSlope);
        this.bitmapData.floodFill(this.dimension.xAxis - 3, this.h - 3, this.color.left);
        // hack single pixel
        this.bitmapData.setPixel(this.dimension.xAxis - 2, this.h - 2, this.color.left);

        // highlight
        if (this.border) {
            for (n = 1; n < this.dimension.xAxis * 2 - 3; n += 1) {
                this.bitmapData.setPixel(1 + Math.floor(n / 2), this.dimension.yAxis / 2 + n - 1, this.color.borderHighlight);
            }
        }
    };

    // public methods
    p.toString = function () {
        return "[SlopeEast]";
    };

    obelisk.SlopeEast = SlopeEast;
}(obelisk));


text:
@class NSString, TNDRMomentsCameraToEditAnimationController;

@interface TNDRMomentsCameraToEditTransitioningDelegate : NSObject <UIViewControllerTransitioningDelegate>
{
    TNDRMomentsCameraToEditAnimationController *_transitioning;
}

- (void).cxx_destruct;
- (id)animationControllerForDismissedController:(id)arg1;
- (id)animationControllerForPresentedController:(id)arg1 presentingController:(id)arg2 sourceController:(id)arg3;
@property(retain, nonatomic) TNDRMomentsCameraToEditAnimationController *transitioning; // @synthesize transitioning=_transitioning;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned int hash;
@property(readonly) Class superclass;

@end


text:
BookmarkBarInstructionsGtk::BookmarkBarInstructionsGtk(Delegate* delegate,
                                                       Profile* profile)
    : delegate_(delegate),
      profile_(profile),
      theme_service_(GtkThemeService::GetFrom(profile_)) {
  instructions_hbox_ = gtk_chrome_shrinkable_hbox_new(FALSE, FALSE, 0);
  gtk_widget_set_size_request(instructions_hbox_, 0, -1);

  instructions_label_ = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_BOOKMARKS_NO_ITEMS).c_str());
  gtk_misc_set_alignment(GTK_MISC(instructions_label_), 0, 0.5);
  gtk_util::CenterWidgetInHBox(instructions_hbox_, instructions_label_,
                               false, 1);
  g_signal_connect(instructions_label_, "map",
                   G_CALLBACK(gtk_util::InitLabelSizeRequestAndEllipsizeMode),
                   NULL);

  instructions_link_ = theme_service_->BuildChromeLinkButton(
      l10n_util::GetStringUTF8(IDS_BOOKMARK_BAR_IMPORT_LINK));
  gtk_misc_set_alignment(
      GTK_MISC(GTK_CHROME_LINK_BUTTON(instructions_link_)->label), 0, 0.5);
  g_signal_connect(instructions_link_, "clicked",
                   G_CALLBACK(OnButtonClickThunk), this);
  gtk_util::SetButtonTriggersNavigation(instructions_link_);
  // Until we switch to vector graphics, force the font size.
  // 13.4px == 10pt @ 96dpi
  gtk_util::ForceFontSizePixels(
      GTK_CHROME_LINK_BUTTON(instructions_link_)->label, 13.4);
  gtk_util::CenterWidgetInHBox(instructions_hbox_, instructions_link_,
                               false, 6);
  g_signal_connect(GTK_CHROME_LINK_BUTTON(instructions_link_)->label, "map",
                   G_CALLBACK(gtk_util::InitLabelSizeRequestAndEllipsizeMode),
                   NULL);

  registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
                 content::Source<ThemeService>(theme_service_));
  theme_service_->InitThemesFor(this);
}

void BookmarkBarInstructionsGtk::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  if (type == chrome::NOTIFICATION_BROWSER_THEME_CHANGED)
    UpdateColors();
}

void BookmarkBarInstructionsGtk::OnButtonClick(GtkWidget* button) {
  delegate_->ShowImportDialog();
}

void BookmarkBarInstructionsGtk::UpdateColors() {
  GdkColor bookmark_color = theme_service_->GetGdkColor(
      ThemeService::COLOR_BOOKMARK_TEXT);
  if (theme_service_->UsingNativeTheme()) {
    gtk_util::SetLabelColor(instructions_label_, NULL);
    gtk_chrome_link_button_set_normal_color(
        GTK_CHROME_LINK_BUTTON(instructions_link_), NULL);
  } else {
    gtk_util::SetLabelColor(instructions_label_, &bookmark_color);

    // When using a non-standard, non-gtk theme, we make the link color match
    // the bookmark text color. Otherwise, standard link blue can look very
    // bad for some dark themes.
    if (theme_service_->GetColor(ThemeService::COLOR_BOOKMARK_TEXT) ==
        ThemeService::GetDefaultColor(
            ThemeService::COLOR_BOOKMARK_TEXT)) {
      gtk_chrome_link_button_set_normal_color(
          GTK_CHROME_LINK_BUTTON(instructions_link_), NULL);
    } else {
      gtk_chrome_link_button_set_normal_color(
          GTK_CHROME_LINK_BUTTON(instructions_link_), &bookmark_color);
    }
  }
}


text:
import pyproctor
from shelf.endpoint_decorators import decorators
from mock import Mock, call

class EndpointDecoratorsTest(pyproctor.TestBase):
    def setUp(self):
        self.response_mock = type("FakeResponse", (), {
            "data": {},
            "headers": {
                "content-type": "application/json"
            },
            "status_code": 200
        })

    def test_authorization_header_is_not_logged(self):
        """
            Very simple test. We found out the Authorization header was being
            logged by endpoint decorators. The only function that logs headers
            is decorators.logheaders, so this is testing that function. It
            must redact any headers added to the REDACTED_HEADERS list.
        """
        logger_mock = Mock()
        logger_mock.info = Mock()
        request_mock = type("FakeRequest", (), {
            "headers": {
                "Authorization": "no",
                "SafeStuff": "This better be logged this way",
                "authorization": "no",
                "auThOrIzAtion": "no",
                "authentication": "no",
                "host": "yes",
                "accept": "yes"
            },
            "method": "POST"
        })
        mock_container = type("FakeContainer", (), {
            "logger": logger_mock,
            "request": request_mock
        })

        @decorators.logheaders
        def test_log_headers(*args, **kwargs):
            return self.response_mock

        test_log_headers(mock_container)
        logger_mock.info.assert_has_calls(
            [
                call(
                    "REQUEST HEADERS : \n"
                    "authentication: REDACTED\n"
                    "accept: yes\n"
                    "host: yes\n"
                    "auThOrIzAtion: REDACTED\n"
                    "Authorization: REDACTED\n"
                    "authorization: REDACTED\n"
                    "SafeStuff: This better be logged this way"
                ),
                call("RESPONSE HEADERS : \nSTATUS CODE: 200\ncontent-type: application/json")
            ]
        )

    def test_logbodies_errors_on_invalid_json(self):
        """
            Tests the logbodies function to make sure it correctly
            catches invalid JSON requests.
        """
        data = "{\"invalid\": ...}"
        valueErrorStr = "No JSON object could be decoded"
        logger_mock = Mock()
        request_mock = type("FakeRequest", (), {
            "headers": {
                "content-type": "application/json"
            },
            "data": data
        })
        request_mock.get_data = Mock(return_value=data)
        mock_container = type("FakeContainer", (), {
            "logger": logger_mock,
            "request": request_mock
        })

        @decorators.logbodies
        def test_log_bodies(container):
            return self.response_mock

        test_log_bodies(mock_container)
        logger_mock.info.assert_any_call("Invalid JSON from request.")

        # Get the call arguments from logger_mock.exception,
        # and assert if the first argument is a ValueError with
        # the correct error message.
        callArg = logger_mock.exception.call_args[0][0]
        self.assertEqual(ValueError, type(callArg))
        self.assertEqual(valueErrorStr, callArg.message)


text:
namespace PlanetWars.Shared
{
    public enum MapGenerationOption
    {
        None = -1,
        Basic = 0,
        Random = 1
    }
}


text:
<?php

namespace blizzard\api\wow;

use \blizzard\api\wow\WowApiAbstract;
use \blizzard\api\wow\WowApiException;

include_once 'WowApiAbstract.php';
include_once 'WowApiException.php';

class AuctionApi extends WowApiAbstract {

	/**
	 * Constants for factions.
	 */
	const FAC_HORDE		= 'horde';
	const FAC_ALLIANCE	= 'alliance';
	const FAC_NEUTRAL	= 'neutral';

	/**
	 * Constants for auction time left.
	 */
	const TIME_VERY_LONG	= 'VERY_LONG';
	const TIME_LONG			= 'LONG';
	const TIME_MEDIUM		= 'MEDIUM';
	const TIME_SHORT		= 'SHORT';

	/**
	 * Auction data structure.
	 *
	 *		timeleft <string> - Remaining time for the auction.
	 *		faction <string> - Horde, Alliance, or Neutral.
	 *
	 * @access protected
	 * @var array
	 */
	protected $_schema = array(
		'timeleft' => array(
			self::TIME_VERY_LONG,
			self::TIME_LONG,
			self::TIME_MEDIUM,
			self::TIME_SHORT
		),
		'faction' => array(
			self::FAC_HORDE,
			self::FAC_ALLIANCE,
			self::FAC_NEUTRAL,
		),
	);

	/**
	 * Last modified time for auctions.
	 *
	 * @access protected
	 * @var protected
	 */
	protected $_lastModified;

	/**
	 * Append guild and realm to API URL.
	 *
	 * @access public
	 * @param array $config
	 * @return void
	 * @constructor
	 * @throws WoWApiException
	 */
	public function __construct(array $config = array()) {
		if (empty($config['realm'])) {
			throw new WowApiException('Please provide a realm name.');
		}

		parent::__construct($config);

		$this->setApiUrl($this->getApiUrl() . sprintf('auction/data/%s/', $this->_config['realm']));
	}

	/**
	 * Return the auction data, and set the lastModified property.
	 *
	 * @access protected
	 * @return void
	 * @throws WoWApiException
	 */
	public function getAuctions(){
		$results = $this->results();
		if(!isset($results['files'])){
			throw new WowApiException('No results were returned. Check for usage of If-Modified-Since.');
		}
		$this->setApiUrl($results['files'][0]['url']);

		$engine = $this->getCacheEngine();
		$key = $engine->key($this->_cacheKey . 'auctions');

		if ($engine->has($key)) {
			return $engine->get($key);
		}

		$request = $this->request();
		$results = $request->response();

		if (!empty($results)) {
			$engine->set($key, $results);
		}

		return $results;
	}

	/**
	 * Get auction(s) by faction
	 *
	 * @access public
	 * @param string|array $faction
	 * @return array
	 */
	public function filterByFaction($faction) {
		if (!in_array($faction, $this->schema('faction'))) {
			throw new WowApiException(sprintf('Invalid faction for %s.', __METHOD__));
		}

		$this->cache();
		$engine = $this->getCacheEngine();
		$results = $engine->get($this->_cacheKey);

		if(is_array($faction)){
			$resultArray = array();
			foreach($faction as $single){
				$resultArray[] = $results[$single];
			}
			return $resultsArray;
		}else{
			return $results[$faction]['auctions'];
		}
	}

	/**
	 * Get auction(s) based on owner name.
	 *
	 * @access public
	 * @param string|array $name
	 * @return array
	 */
	public function filterByName($name) {
		if (empty($name)) {
			throw new WowApiException(sprintf('Name required for %s.', __METHOD__));
		}

		return $this->filterAuctionsBy(__METHOD__, 'owner', $name);
	}

	/**
	 * Get auction(s) based on item id.
	 *
	 * @access public
	 * @param string|array $item
	 * @return array
	 */
	public function filterByItem($item) {
		if (empty($item)) {
			throw new WowApiException(sprintf('ItemId required for %s.', __METHOD__));
		}

		return $this->filterAuctionsBy(__METHOD__, 'item', $item);
	}

	/**
	 * Get auction(s) based on time left.
	 *
	 * @access public
	 * @param string|array $timeleft
	 * @return array
	 */
	public function filterByTimeLeft($timeleft) {
		if (!in_array($timeleft, $this->schema('timeleft'))) {
			throw new WowApiException(sprintf('Invalid time left type for %s.', __METHOD__));
		}

		return $this->filterAuctionsBy(__METHOD__, 'timeLeft', $timeleft);
	}

	/**
	 * Used internally to filter auctions from the cache.
	 * Used because the structure of auction data is not able to be
	 * passed into the main filterBy() method. The alliance, horde, and
	 * neutral auction data needs to be merged, then filtered on.
	 *
	 * @access protected
	 * @param string $method The method called from, used as the cache key
	 * @param string $field The field upon which to search for $filter
	 * @param string|array $filter The data to be searched for
	 * @return array
	 */
	protected function filterAuctionsBy($method, $field, $filter){
		$this->getAuctions();
		$engine = $this->getCacheEngine();

		$key = $engine->key($method, $filter);

		if ($engine->has($key)) {
			return $engine->get($key);
		}

		$fullResults = $engine->get($this->_cacheKey . 'auctions');

		$filterOn = array_merge($fullResults['alliance']['auctions'], $fullResults['horde']['auctions'], $fullResults['neutral']['auctions']);

		$filteredResults = $this->filter($filterOn, $field, $filter);
		$engine->set($key, $filteredResults);
		return $filteredResults;
	}

	/**
	 * Store a cache of the base results. We will use this cache to filter upon
	 * instead of doing subsequent HTTP requests.
	 *
	 * @access public
	 * @return boolean
	 * @final
	 */
	final public function cache() {
		if ($this->getCacheEngine()->has($this->_cacheKey)) {
			return true;
		}

		$request = $this->request();
		$results = $request->response();

		if (!empty($results)) {
			$this->getCacheEngine()->set($this->_cacheKey, $results);
			return true;
		}

		return false;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_checked="true"
        android:drawable="@drawable/navbar_allselected"
    />
    <item android:drawable="@drawable/navbar_allnormal"  />
</selector>


text:
namespace storage
{
TestMapFilesDownloader::TestMapFilesDownloader() : HttpMapFilesDownloader()
{
  SetServersList({"http://localhost:34568/unit_tests/"});
}
}  // namespace storage


text:
'use strict';

var path = require('path');
var fs = require('fs');

function get_paths(env) {
    var opts = env || process.env;
    var cert_dir = opts.CERT_DIR || '/etc/enmasse-certs';
    var paths = {};
    paths.ca = opts.CA_PATH || path.resolve(cert_dir, 'ca.crt');
    paths.cert = opts.CERT_PATH || path.resolve(cert_dir, 'tls.crt');
    paths.key = opts.KEY_PATH || path.resolve(cert_dir, 'tls.key');
    return paths;
}

function get_client_options(config, env) {
    var options = config || {};
    var paths = get_paths(env);
    options.ca = [fs.readFileSync(paths.ca)];
    options.key = fs.readFileSync(paths.key);
    options.cert = fs.readFileSync(paths.cert);
    options.enable_sasl_external = true;
    options.transport = 'tls';
    options.rejectUnauthorized = false;
    return options;
}

function get_server_options(config, env) {
    var options = config || {};
    get_client_options(options, env);
    options.requestCert = true;
    options.rejectUnauthorized = true;
    return options;
}

function get_console_server_options(config, env) {
    var options = config || {};
    var paths = get_paths(env);
    options.key = fs.readFileSync(paths.key);
    options.cert = fs.readFileSync(paths.cert);
    options.transport = 'tls';
    return options;
}

module.exports.get_client_options = get_client_options;
module.exports.get_server_options = get_server_options;
module.exports.get_console_server_options = get_console_server_options;
module.exports.get_paths = get_paths;


text:
(function() {
  'use strict';

  angular.module('staurtherApp')
    .factory('ErrorService', function() {
      var formErrors = {};

      return {
        getFormErrors: function() {
          return formErrors;
        },
        setFormErrors: function(response, formCtrl) {
          angular.forEach(response, function(obj, key) {
            formCtrl[key].$setValidity('server-error', false);
            formErrors[key] = obj.msg;
          });
        },
        clearForm: function(formCtrl) {
          // clear the form's state
          formCtrl.$setPristine();
          formCtrl.$setUntouched();
          return formCtrl;
        }
      };
    });

})();