text:
using System;
using System.Messaging;
using Castle.MicroKernel;
using Rhino.ServiceBus.Impl;
using Rhino.ServiceBus.Messages;
using Rhino.ServiceBus.Msmq;
using System.Linq;
using Rhino.ServiceBus.Serializers;
using Xunit;

namespace Rhino.ServiceBus.Tests
{
    public class MsmqSubscriptionTests : MsmqTestBase
    {
        [Fact]
        public void Can_read_subscription_from_queue()
        {
            var serializer = new XmlMessageSerializer(new DefaultReflection(), new DefaultKernel());

            var msg = new Message();
            serializer.Serialize(new object[]{new AddSubscription
            {
                Endpoint = TransactionalTestQueueUri,
                Type = typeof(TestMessage).FullName,
            }}, msg.BodyStream);

            msg.Extension = Guid.NewGuid().ToByteArray();
            queue.Send(msg, MessageQueueTransactionType.None);
            msg = queue.Peek(TimeSpan.FromSeconds(30));
            queue.MoveToSubQueue("subscriptions", msg);

            var subscriptionStorage = new MsmqSubscriptionStorage(new DefaultReflection(),
                serializer,
                TestQueueUri.Uri,
                new EndpointRouter(),
                new SubQueueStrategy());
            subscriptionStorage.Initialize();

            var uri = subscriptionStorage
                .GetSubscriptionsFor(typeof(TestMessage))
                .Single();

            Assert.Equal(TransactionalTestQueueUri.Uri, uri);
        }

        [Fact]
        public void Adding_then_removing_will_result_in_no_subscriptions()
        {
            var serializer = new XmlMessageSerializer(new DefaultReflection(), new DefaultKernel());
            var msg = new Message();
            serializer.Serialize(new object[]{new AddSubscription
            {
                Endpoint = TransactionalTestQueueUri,
                Type = typeof(TestMessage).FullName,
            }}, msg.BodyStream);
            msg.Extension = Guid.NewGuid().ToByteArray();

            queue.Send(msg, MessageQueueTransactionType.None);
            msg = queue.Peek(TimeSpan.FromSeconds(30));
            queue.MoveToSubQueue("subscriptions",msg);

            var subscriptionStorage = new MsmqSubscriptionStorage(new DefaultReflection(),
                serializer,
                TestQueueUri.Uri,
                new EndpointRouter(),
                new SubQueueStrategy());
            subscriptionStorage.Initialize();
            subscriptionStorage.RemoveSubscription(typeof(TestMessage).FullName, TransactionalTestQueueUri.Uri.ToString());

            var uris = subscriptionStorage
                .GetSubscriptionsFor(typeof (TestMessage));

            Assert.Equal(0, uris.Count());
        }

        public class TestMessage{}
    }
}


text:
package org.conqat.engine.core.bundle.library.license;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import org.conqat.lib.commons.filesystem.FileSystemUtils;
import org.conqat.lib.commons.string.StringUtils;

/**
 * Non-standard library license with custom information.
 *
 * @author $Author: poehlmann $
 * @version $Rev: 46536 $
 * @ConQAT.Rating YELLOW Hash: 59E2F9412943C5B62605E3334BD561BE
 */
public class CustomLicense implements ILicense {

	/** The name of the library. */
	private final String name;

	/** The website url with information about the library. */
	private final String website;

	/** Additional license notice. */
	private final String notice;

	/**
	 * Flag indicating whether the license is compatible with the Apache
	 * license.
	 */
	private final boolean isApacheCompatible;

	/**
	 * Flag indicating whether the license allows commercial use of the library.
	 */
	private final boolean isCommercialUseAllowed;

	/** Constructor. */
	private CustomLicense(String name, boolean isApacheCompatible,
			boolean isCommercialUseAllowed, String website, String notice) {
		this.name = name;
		this.isApacheCompatible = isApacheCompatible;
		this.isCommercialUseAllowed = isCommercialUseAllowed;
		this.website = website;
		this.notice = notice;
	}

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

	/** {@inheritDoc} */
	@Override
	public String getWebsite() {
		return website;
	}

	/** {@inheritDoc} */
	@Override
	public String getNotice() {
		return notice;
	}

	/** {@inheritDoc} */
	@Override
	public boolean isApacheCompatible() {
		return isApacheCompatible;
	}

	/** {@inheritDoc} */
	@Override
	public boolean isCommercialUseAllowed() {
		return isCommercialUseAllowed;
	}

	/**
	 * Creates a new license information by parsing a properties object and
	 * optionally reading a file containing notice information.
	 */
	public static CustomLicense fromProperties(Properties props, File noticeFile)
			throws IOException {
		String name = props.getProperty("license");
		String website = props.getProperty("license.website");
		String notice = props.getProperty("license.notice");

		// if the property is not set (i.e. null) parseBoolean returns false
		boolean apacheCompatible = Boolean.parseBoolean(props
				.getProperty("license.apacheCompatible"));
		boolean commercialUse = Boolean.parseBoolean(props
				.getProperty("license.commercialUse"));

		if (noticeFile != null && noticeFile.exists()) {
			notice = StringUtils.normalizeLineBreaks(FileSystemUtils
					.readFile(noticeFile));
		}

		return new CustomLicense(name, apacheCompatible, commercialUse,
				website, notice);
	}

}

redpajama_set_name: RedPajamaGithub


text:
require "pathname"

module Giblish
  # Provides relevant paths for layout resources based on the given options
  class ResourcePaths
    STYLE_EXTENSIONS = {
      "html5" => ".css",
      "html" => ".css",
      "pdf" => ".yml",
      "web-pdf" => ".css"
    }

    FONT_REGEX = /.*\.(ttf)|(TTF)$/
    RESOURCE_DST_TOP_BASENAME = Pathname.new("web_assets")

    # the relative path from the top of the resource area to the
    # style file
    attr_reader :src_style_path_rel

    # the absolute path from the top of the resource area to the
    # style file
    attr_reader :src_style_path_abs

    # a set with all dirs containing ttf files, paths are relative to resource area top
    attr_reader :font_dirs_abs

    # the relative path from the dst top dir to the copied style file (if it would be copied)
    attr_reader :dst_style_path_rel

    # the abs path to the top of the destination dir for resources
    attr_reader :dst_resource_dir_abs

    def initialize(cmd_opts)
      @style_ext = STYLE_EXTENSIONS.fetch(cmd_opts.format, nil)
      raise OptionParser::InvalidArgument, "Unsupported format: #{cmd_opts.format}" if @style_ext.nil?

      # Cache all file paths in the resource area
      r_top = cmd_opts.resource_dir
      file_tree = PathTree.build_from_fs(r_top)

      # find and validate paths
      @dst_resource_dir_abs = cmd_opts.dstdir / RESOURCE_DST_TOP_BASENAME
      @src_style_path_rel = find_style_file(file_tree, cmd_opts)
      @src_style_path_abs = r_top / @src_style_path_rel
      @dst_style_path_rel = RESOURCE_DST_TOP_BASENAME / @src_style_path_rel
      @font_dirs_abs = find_font_dirs(file_tree)
    end

    private

    # returns:: the relative path from the top of the file_tree to
    # the style file
    def find_style_file(file_tree, cmd_opts)
      # Get all files matching the style name
      style_basename = Pathname.new(cmd_opts.style_name).sub_ext(@style_ext)
      style_tree = file_tree.match(/.*#{style_basename}$/)

      # make sure we have exactly one css file with the given name
      raise OptionParser::InvalidArgument, "Did not find #{style_basename} under #{file_tree.pathname}" if style_tree.nil?

      l = style_tree.leave_pathnames(prune: true)
      if l.count > 1
        raise OptionParser::InvalidArgument, "Found #{l.count} instances of #{style_basename} under #{file_tree.pathname}. Requires exactly one."
      end

      # return the (pruned) path
      l[0]
    end

    def find_font_dirs(file_tree)
      tree = file_tree.match(FONT_REGEX)
      dirs = Set.new
      tree&.traverse_preorder do |level, node|
        next unless node.leaf?

        dirs << node.pathname.dirname
      end
      dirs
    end
  end

  # copy everything under cmd_opts.resource_dir to
  # dst_top/web_assets/.
  class CopyResourcesPreBuild
    # required opts:
    # resource_dir:: Pathname to the top of the resource area to be copied
    # style_name:: basename of the css to use for styling
    # dstdir:: Pathname to the destination dir where the copied resources will be
    # stored.
    def initialize(cmd_opts)
      @opts = cmd_opts.dup
      @paths = ResourcePaths.new(cmd_opts)
    end

    def on_prebuild(src_tree, dst_tree, converter)
      copy_resource_area(@opts)
    end

    private

    # copy everyting under cmd_opts.resource_dir to @web_asset_dir
    def copy_resource_area(cmd_opts)
      web_assets_dir = @paths.dst_resource_dir_abs
      web_assets_dir.mkpath unless web_assets_dir.exist?

      resource_dir = cmd_opts.resource_dir.cleanpath.to_s + "/."

      Giblog.logger&.info "Copy web assets (stylesheets et al) from #{resource_dir} to #{web_assets_dir}"
      FileUtils.cp_r(
        resource_dir,
        web_assets_dir.to_s
      )
    end
  end

  class CopyAssetDirsPostBuild
    def initialize(cmd_opts)
      @asset_regex = cmd_opts.copy_asset_folders
      @srcdir = cmd_opts.srcdir
      @dstdir = cmd_opts.dstdir
    end

    # Called from TreeConverter during post build phase
    #
    # copy all directories matching the regexp pattern from the
    # src tree to the dst tree
    def on_postbuild(src_tree, dst_tree, converter)
      return if @asset_regex.nil?

      # build a tree with all dirs matching the given regexp
      st = PathTree.build_from_fs(@srcdir, prune: true) do |p|
        p.directory? && @asset_regex =~ p.to_s
      end

      return if st.nil?

      Giblog.logger&.info "Copy asset directories from #{@srcdir} to #{@dstdir}"
      st.traverse_preorder do |level, node|
        next unless node.leaf?

        n = node.relative_path_from(st)
        src = @srcdir.join(n)
        dst = @dstdir.join(n).dirname
        dst.mkpath

        FileUtils.cp_r(src.to_s, dst.to_s)
      end
    end
  end
end


text:
Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

class Solution:
    # @param {integer} n
    # @return {integer}
    def totalNQueens(self, n):
        if n == 0: return 0
        self.result = 0   # Here we should use the global variable, otherwise the result will not change
        checklist = [-1 for i in xrange(n)]
        self.queen_helper(n, 0, checklist)
        return self.result

    def check_helper(self, depth, i, checklist):
            for k in xrange(depth):
                if checklist[k] == i or abs(checklist[k] - i) == abs(depth-k):
                    return False
            return True

    def queen_helper(self, n, depth, checklist):
        if depth == n:
            self.result += 1; return
        for i in xrange(n):
            if self.check_helper(depth, i, checklist):
                checklist[depth] = i
                self.queen_helper(n, depth+1, checklist)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using SpecialtySelector.Data;

namespace SpecialtySelector.Models.Subjects
{
    public class SubjectInfo
    {
        public ICollection<Teacher> Teachers { get; set; }
        public ICollection<Specialty> Specialties { get; set; }

        public int Id { get; set; }

        [Required]
        [MaxLength(1000)]
        [MinLength(1)]
        public string Name { get; set; }

        public bool IsMandatory { get; set; }

        public int Credits { get; set; }

        [Required]
        public int Course { get; set; }

        [StringLength(1600)]
        public string Description { get; set; }

        public DateTime? DeletedOn { get; set; }

        public string AdminId { get; set; }

        public virtual User Admin { get; set; }
    }
}


text:
import defaultParserInterface from '../utils/defaultParserInterface';
import pkg from 'regjsparser/package.json';

const ID = 'regjsparser';

export const defaultOptions = {
  unicodePropertyEscape: true,
  namedGroups: true,
  lookbehind: true,
};

export default {
  ...defaultParserInterface,

  id: ID,
  displayName: ID,
  version: pkg.version,
  homepage: pkg.homepage,
  locationProps: new Set(['range']),

  loadParser(callback) {
    require(['regjsparser'], callback);
  },

  parse(regjsparser, code, options) {
    if (Object.keys(options).length === 0) {
      options = this.getDefaultOptions();
    }
    var firstSlash = code.indexOf('/');
    var lastSlash = code.lastIndexOf('/');
    if (firstSlash !== 0 || lastSlash < 1) {
      throw new Error('Please wrap the regex pattern by slash `/`, i.e. /foo/');
    }
    var flags = code.slice(lastSlash + 1);
    var pattern = code.slice(firstSlash + 1, lastSlash);
    return regjsparser.parse(pattern, flags, options);
  },

  nodeToRange(node) {
    if (node.range != null) {
      return [node.range[0] + 1, node.range[1] + 1];
    }
  },

  opensByDefault(node, key) {
    return (
        key === 'body'
    );
  },

  getDefaultOptions() {
    return defaultOptions;
  },

};


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {

	public function index()
	{
		$this->load->model('coment');
		$titlecoment = $this->coment->gettitlecoment();
		$lang = $this->session->userdata('language');
		if($lang === FALSE)
			$lang = 'rus';
		if($lang == 'rus') $title = 'Главная страница'; else $title = 'Main page';
		$data = array(
			'titlecoment' => $titlecoment,
			'pageIndex' => 0,
			'lang' => $lang,
			'username' => $this->session->userdata('username'),
			'title' => $title
			);
		$this->load->view('menu',$data);
        $this->load->view('home');
        $this->load->view('footer');
	}
}


text:
package com.techshroom.emergencylanding.library.debug;

import java.io.IOException;
import java.io.InputStream;

import org.lwjgl.glfw.GLFW;

import com.google.common.io.Resources;
import com.techshroom.emergencylanding.library.lwjgl.DisplayLayer;
import com.techshroom.emergencylanding.library.main.KMain;
import com.techshroom.emergencylanding.library.sound.PlayingSound;
import com.techshroom.emergencylanding.library.sound.SoundPlayer;

public class TestSound extends KMain {

    private static DisplayLayer layer;

    public static void main(String[] args) throws Exception {
        try {
            layer = DisplayLayer.initDisplay(0, 800, 600, "Testing EL Sound", true, args);
            while (!layer.shouldClose()) {
                layer.loop(120);
            }
        } finally {
            if (layer != null) {
                layer.destroy();
            }
            DisplayLayer.finalExitCall();
        }
    }

    private PlayingSound a;
    private PlayingSound b;
    private PlayingSound c;
    private int elapsed = 0;
    private int state = 0;
    private SoundPlayer player;

    @Override
    public void onDisplayUpdate(int delta) {
        this.elapsed += delta;
        if (this.elapsed > 2000) {
            this.state++;
            this.elapsed = 0;
        }
        switch (this.state) {
            case 1:
                this.a.stop();
                break;
            case 2:
                this.b.stop();
                break;
            case 3:
                this.c.stop();
                break;
            case 4:
                this.player.close();
                GLFW.glfwSetWindowShouldClose(layer.getWindow(), true);
        }
    }

    @Override
    public void init(DisplayLayer layer, String[] args) {
        this.player = new SoundPlayer();
        InputStream stream;
        try {
            stream = Resources.asByteSource(Resources.getResource("ogg/test.ogg")).openBufferedStream();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        int buf = this.player.genBuffersFromVorbis(() -> stream);
        this.a = this.player.play(buf, 1.0f, .90f, true);
        this.b = this.player.play(buf, 1.0f, .60f, true);
        this.c = this.player.play(buf, 1.0f, 2.15f, true);
    }

}


text:
<?php

namespace Oro\Component\ChainProcessor;

abstract class AbstractParameterBag implements ParameterBagInterface
{
    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->toArray());
    }

    /**
     * {@inheritdoc}
     */
    public function count()
    {
        return count($this->toArray());
    }

    /**
     * {@inheritdoc}
     */
    public function offsetExists($offset)
    {
        return $this->has($offset);
    }

    /**
     * {@inheritdoc}
     */
    public function offsetGet($offset)
    {
        return $this->get($offset);
    }

    /**
     * {@inheritdoc}
     */
    public function offsetSet($offset, $value)
    {
        $this->set($offset, $value);
    }

    /**
     * {@inheritdoc}
     */
    public function offsetUnset($offset)
    {
        $this->remove($offset);
    }
}


text:
package carstore.servlets;

import carstore.controllers.CarStoreManager;
import carstore.models.Car;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Evgeny Khodzitskiy (evgeny.hodz@gmail.com)
 * @since 30.08.2017
 */
public class CarKeeper extends HttpServlet {
    /**
     * Keeps car saved in session. Also gets car's price and description
     * and sets it's values if they are = null, and keeps them in session too.
     *
     * @param req  .
     * @param resp .
     * @throws ServletException .
     * @throws IOException      .
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        CarStoreManager man = CarStoreManager.getCONTROLLER();

        String brand = req.getParameter("brand"),
                model = req.getParameter("model"),
                body = req.getParameter("body"),
                engine = req.getParameter("engine"),
                trans = req.getParameter("transmission"),
                drive = req.getParameter("wheeldrive"),
                hp = req.getParameter("horsepowers"),
                prod = req.getParameter("productionYear"),
                mileage = req.getParameter("mileage"),
                color = req.getParameter("color");

        if (brand == null || model == null || body == null || engine == null
                || trans == null || drive == null || hp == null
                || prod == null || mileage == null || color == null) {
            resp.getWriter().write("fail");

        } else {

            Car car = new Car();
            car.setBrand(man.findBrandByName(brand));
            car.setModel(man.findModelByName(model));
            car.setBodyStyle(man.findBodyByName(body));
            car.setEngine(man.findEngineByNameAndCapacity(engine));
            car.setTransmission(man.findTransmissionByName(trans));
            car.setWheelDrive(man.findWheelDriveByName(drive));
            car.setHorsePowers(Integer.valueOf(hp));
            car.setProductionYear(Integer.valueOf(prod));
            car.setMileage(Integer.valueOf(mileage));
            car.setColor(color);

            String desc = req.getParameter("description");
            String price = req.getParameter("price");

            if (desc == null) {
                desc = "The seller did not write a description for this car.";
            }

            if (price == null) {
                price = "0.0";
            }

            req.getSession().setAttribute("description", desc);
            req.getSession().setAttribute("price", price);
            req.getSession().setAttribute("car", car);

            resp.getWriter().write("success");
        }
    }
}


text:
package sarama

import (
	"errors"
	"log"
	"sync"
	"testing"
)

func TestSyncProducer(t *testing.T) {
	seedBroker := NewMockBroker(t, 1)
	leader := NewMockBroker(t, 2)

	metadataResponse := new(MetadataResponse)
	metadataResponse.AddBroker(leader.Addr(), leader.BrokerID())
	metadataResponse.AddTopicPartition("my_topic", 0, leader.BrokerID(), nil, nil, nil, ErrNoError)
	seedBroker.Returns(metadataResponse)

	prodSuccess := new(ProduceResponse)
	prodSuccess.AddTopicPartition("my_topic", 0, ErrNoError)
	for i := 0; i < 10; i++ {
		leader.Returns(prodSuccess)
	}

	config := NewTestConfig()
	config.Producer.Return.Successes = true
	producer, err := NewSyncProducer([]string{seedBroker.Addr()}, config)
	if err != nil {
		t.Fatal(err)
	}

	for i := 0; i < 10; i++ {
		msg := &ProducerMessage{
			Topic:    "my_topic",
			Value:    StringEncoder(TestMessage),
			Metadata: "test",
		}

		partition, offset, err := producer.SendMessage(msg)

		if partition != 0 || msg.Partition != partition {
			t.Error("Unexpected partition")
		}
		if offset != 0 || msg.Offset != offset {
			t.Error("Unexpected offset")
		}
		if str, ok := msg.Metadata.(string); !ok || str != "test" {
			t.Error("Unexpected metadata")
		}
		if err != nil {
			t.Error(err)
		}
	}

	safeClose(t, producer)
	leader.Close()
	seedBroker.Close()
}

func TestSyncProducerTransactional(t *testing.T) {
	seedBroker := NewMockBroker(t, 1)
	defer seedBroker.Close()
	leader := NewMockBroker(t, 2)
	defer leader.Close()

	config := NewTestConfig()
	config.Version = V0_11_0_0
	config.Producer.RequiredAcks = WaitForAll
	config.Producer.Return.Successes = true
	config.Producer.Transaction.ID = "test"
	config.Producer.Idempotent = true
	config.Producer.Retry.Max = 5
	config.Net.MaxOpenRequests = 1

	metadataResponse := new(MetadataResponse)
	metadataResponse.Version = 1
	metadataResponse.ControllerID = leader.BrokerID()
	metadataResponse.AddBroker(leader.Addr(), leader.BrokerID())
	metadataResponse.AddTopic("my_topic", ErrNoError)
	metadataResponse.AddTopicPartition("my_topic", 0, leader.BrokerID(), nil, nil, nil, ErrNoError)
	seedBroker.Returns(metadataResponse)

	client, err := NewClient([]string{seedBroker.Addr()}, config)
	if err != nil {
		t.Fatal(err)
	}

	findCoordinatorResponse := new(FindCoordinatorResponse)
	findCoordinatorResponse.Coordinator = client.Brokers()[0]
	findCoordinatorResponse.Version = 1
	seedBroker.Returns(findCoordinatorResponse)

	initProducerIdResponse := new(InitProducerIDResponse)
	leader.Returns(initProducerIdResponse)

	addPartitionToTxn := new(AddPartitionsToTxnResponse)
	addPartitionToTxn.Errors = map[string][]*PartitionError{
		"my_topic": {
			{
				Partition: 0,
			},
		},
	}
	leader.Returns(addPartitionToTxn)

	prodSuccess := new(ProduceResponse)
	prodSuccess.Version = 3
	prodSuccess.AddTopicPartition("my_topic", 0, ErrNoError)
	for i := 0; i < 10; i++ {
		leader.Returns(prodSuccess)
	}

	endTxnResponse := &EndTxnResponse{}
	leader.Returns(endTxnResponse)

	producer, err := NewSyncProducerFromClient(client)
	if err != nil {
		t.Fatal(err)
	}
	if !producer.IsTransactional() {
		t.Error("producer is not transactional")
	}

	err = producer.BeginTxn()
	if err != nil {
		t.Fatal(err)
	}
	if producer.TxnStatus()&ProducerTxnFlagInTransaction == 0 {
		t.Error("transaction must started")
	}

	for i := 0; i < 10; i++ {
		msg := &ProducerMessage{
			Topic:    "my_topic",
			Value:    StringEncoder(TestMessage),
			Metadata: "test",
		}

		partition, offset, err := producer.SendMessage(msg)

		if partition != 0 || msg.Partition != partition {
			t.Error("Unexpected partition")
		}
		if offset != 0 || msg.Offset != offset {
			t.Error("Unexpected offset")
		}
		if str, ok := msg.Metadata.(string); !ok || str != "test" {
			t.Error("Unexpected metadata")
		}
		if err != nil {
			t.Error(err)
		}
	}
	err = producer.CommitTxn()
	if err != nil {
		t.Fatal(err)
	}

	safeClose(t, producer)
}

func TestSyncProducerBatch(t *testing.T) {
	seedBroker := NewMockBroker(t, 1)
	leader := NewMockBroker(t, 2)

	metadataResponse := new(MetadataResponse)
	metadataResponse.AddBroker(leader.Addr(), leader.BrokerID())
	metadataResponse.AddTopicPartition("my_topic", 0, leader.BrokerID(), nil, nil, nil, ErrNoError)
	seedBroker.Returns(metadataResponse)

	prodSuccess := new(ProduceResponse)
	prodSuccess.AddTopicPartition("my_topic", 0, ErrNoError)
	leader.Returns(prodSuccess)

	config := NewTestConfig()
	config.Producer.Flush.Messages = 3
	config.Producer.Return.Successes = true
	producer, err := NewSyncProducer([]string{seedBroker.Addr()}, config)
	if err != nil {
		t.Fatal(err)
	}

	err = producer.SendMessages([]*ProducerMessage{
		{
			Topic:    "my_topic",
			Value:    StringEncoder(TestMessage),
			Metadata: "test",
		},
		{
			Topic:    "my_topic",
			Value:    StringEncoder(TestMessage),
			Metadata: "test",
		},
		{
			Topic:    "my_topic",
			Value:    StringEncoder(TestMessage),
			Metadata: "test",
		},
	})

	if err != nil {
		t.Error(err)
	}

	safeClose(t, producer)
	leader.Close()
	seedBroker.Close()
}

func TestConcurrentSyncProducer(t *testing.T) {
	seedBroker := NewMockBroker(t, 1)
	leader := NewMockBroker(t, 2)

	metadataResponse := new(MetadataResponse)
	metadataResponse.AddBroker(leader.Addr(), leader.BrokerID())
	metadataResponse.AddTopicPartition("my_topic", 0, leader.BrokerID(), nil, nil, nil, ErrNoError)
	seedBroker.Returns(metadataResponse)

	prodSuccess := new(ProduceResponse)
	prodSuccess.AddTopicPartition("my_topic", 0, ErrNoError)
	leader.Returns(prodSuccess)

	config := NewTestConfig()
	config.Producer.Flush.Messages = 100
	config.Producer.Return.Successes = true
	producer, err := NewSyncProducer([]string{seedBroker.Addr()}, config)
	if err != nil {
		t.Fatal(err)
	}

	wg := sync.WaitGroup{}

	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			msg := &ProducerMessage{Topic: "my_topic", Value: StringEncoder(TestMessage)}
			partition, _, err := producer.SendMessage(msg)
			if partition != 0 {
				t.Error("Unexpected partition")
			}
			if err != nil {
				t.Error(err)
			}
			wg.Done()
		}()
	}
	wg.Wait()

	safeClose(t, producer)
	leader.Close()
	seedBroker.Close()
}

func TestSyncProducerToNonExistingTopic(t *testing.T) {
	broker := NewMockBroker(t, 1)

	metadataResponse := new(MetadataResponse)
	metadataResponse.AddBroker(broker.Addr(), broker.BrokerID())
	metadataResponse.AddTopicPartition("my_topic", 0, broker.BrokerID(), nil, nil, nil, ErrNoError)
	broker.Returns(metadataResponse)

	config := NewTestConfig()
	config.Metadata.Retry.Max = 0
	config.Producer.Retry.Max = 0
	config.Producer.Return.Successes = true

	producer, err := NewSyncProducer([]string{broker.Addr()}, config)
	if err != nil {
		t.Fatal(err)
	}

	metadataResponse = new(MetadataResponse)
	metadataResponse.AddTopic("unknown", ErrUnknownTopicOrPartition)
	broker.Returns(metadataResponse)

	_, _, err = producer.SendMessage(&ProducerMessage{Topic: "unknown"})
	if !errors.Is(err, ErrUnknownTopicOrPartition) {
		t.Error("Uxpected ErrUnknownTopicOrPartition, found:", err)
	}

	safeClose(t, producer)
	broker.Close()
}

func TestSyncProducerRecoveryWithRetriesDisabled(t *testing.T) {
	seedBroker := NewMockBroker(t, 1)
	leader1 := NewMockBroker(t, 2)
	leader2 := NewMockBroker(t, 3)

	metadataLeader1 := new(MetadataResponse)
	metadataLeader1.AddBroker(leader1.Addr(), leader1.BrokerID())
	metadataLeader1.AddTopicPartition("my_topic", 0, leader1.BrokerID(), nil, nil, nil, ErrNoError)
	seedBroker.Returns(metadataLeader1)

	config := NewTestConfig()
	config.Producer.Retry.Max = 0 // disable!
	config.Producer.Retry.Backoff = 0
	config.Producer.Return.Successes = true
	producer, err := NewSyncProducer([]string{seedBroker.Addr()}, config)
	if err != nil {
		t.Fatal(err)
	}
	seedBroker.Close()

	prodNotLeader := new(ProduceResponse)
	prodNotLeader.AddTopicPartition("my_topic", 0, ErrNotLeaderForPartition)
	leader1.Returns(prodNotLeader)
	_, _, err = producer.SendMessage(&ProducerMessage{Topic: "my_topic", Value: StringEncoder(TestMessage)})
	if !errors.Is(err, ErrNotLeaderForPartition) {
		t.Fatal(err)
	}

	metadataLeader2 := new(MetadataResponse)
	metadataLeader2.AddBroker(leader2.Addr(), leader2.BrokerID())
	metadataLeader2.AddTopicPartition("my_topic", 0, leader2.BrokerID(), nil, nil, nil, ErrNoError)
	leader1.Returns(metadataLeader2)
	prodSuccess := new(ProduceResponse)
	prodSuccess.AddTopicPartition("my_topic", 0, ErrNoError)
	leader2.Returns(prodSuccess)
	_, _, err = producer.SendMessage(&ProducerMessage{Topic: "my_topic", Value: StringEncoder(TestMessage)})
	if err != nil {
		t.Fatal(err)
	}

	leader1.Close()
	leader2.Close()
	safeClose(t, producer)
}

// This example shows the basic usage pattern of the SyncProducer.
func ExampleSyncProducer() {
	producer, err := NewSyncProducer([]string{"localhost:9092"}, nil)
	if err != nil {
		log.Fatalln(err)
	}
	defer func() {
		if err := producer.Close(); err != nil {
			log.Fatalln(err)
		}
	}()

	msg := &ProducerMessage{Topic: "my_topic", Value: StringEncoder("testing 123")}
	partition, offset, err := producer.SendMessage(msg)
	if err != nil {
		log.Printf("FAILED to send message: %s\n", err)
	} else {
		log.Printf("> message sent to partition %d at offset %d\n", partition, offset)
	}
}


text:
//Problem 10.* Beer Time
//• A beer time is after  1:00 PM  and before  3:00 AM .
//• Write a program that enters a time in format "hh:mm tt"
//(an hour in range [01...12], a minute in range [00…59] and AM / PM
//designator) and prints  beer time  or  non-beer time  according to
//the definition above or  invalid time  if the time cannot be parsed.
//Note: You may need to learn how to parse dates and times.

//Examples:
//time        result
//1:00 PM     beer time
//4:30 PM     beer time
//10:57 PM    beer time
//8:30 AM     non-beer time
//02:59 AM    beer time
//03:00 AM    non-beer time
//03:26 AM    non-beer time

using System;
using System.Globalization;
using System.Threading;

class Beer_Time
{
    static void Main()
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
        Console.WriteLine("Enter the time in the format hh:mm tt (where tt is am/pm).");
        string input = Console.ReadLine();
        DateTime time;
        DateTime beerTimeStart = DateTime.Parse("1:00 PM");
        DateTime beerTimeEnd = DateTime.Parse("3:00 AM");
        if (DateTime.TryParse(input, out time))
        {
            if (time >= beerTimeStart || time < beerTimeEnd) //Note: && is not used because of the zeroing of time at midnight...
            {
                Console.WriteLine("Beer time hip hip hooray!");
            }
            else Console.WriteLine("Oh, dear, enjoy some tea for now...");
        }
        else Console.WriteLine("Invalid input.");

    }
}


text:
import React from "react";
import { mount, shallow } from "enzyme";
import { Alert } from "../index";
import renderer from "react-test-renderer";

describe("Test Alert component", () => {
  it("Test renders correctly", () => {
    const comp = (
      <Alert type="success">
        Success! This alert box indicates a successful or
        positive action.
      </Alert>
    );
    const tree = renderer.create(comp).toJSON();
    expect(tree).toMatchSnapshot();
  });
});

describe("Test Alert Component: Basic Tests", () => {
  const alrtBasic = shallow(
    <Alert>This alert box indicates a successful or positive action.</Alert>
  );

  it("Basic alert ", () => {
    expect(alrtBasic.exists(<Alert />)).toBe(true);
  });

  it("Test Alert has no children", () => {
    const alrt = mount(<Alert />);

    expect(alrt.props().children).toBeUndefined();
  });

  it("Test Alert contains a child", () => {
    expect(alrtBasic.props()).toHaveProperty("children");
  });

  it("Test Alert has success type", () => {
    const alrt = mount(<Alert type="success">This is success</Alert>);

    expect(alrt.props().type).toBe("success");
  });

  it("Test Alert has info type", () => {
    const alrt = mount(<Alert type="info">This is info</Alert>);

    expect(alrt.props().type).toBe("info");
  });

  it("Test Alert has warning type", () => {
    const alrt = mount(<Alert type="warning">This is warning</Alert>);

    expect(alrt.props().type).toBe("warning");
  });

  it("Test Alert has danger type", () => {
    const alrt = mount(<Alert type="danger">This is danger</Alert>);

    expect(alrt.props().type).toBe("danger");
  });

  it("Test Alert is dismissible", () => {
    const alrt = mount(
      <Alert type="danger" dismissible>
        This is danger
      </Alert>
    );

    expect(alrt.props().dismissible).toBe(true);
  });

  it("Test Alert is dismissible and has onDismiss prop", () => {
    const alrt = mount(
      <Alert
        type="danger"
        dismissible
        onDismiss={function() {
          console.log("closed");
        }}
      >
        This is danger
      </Alert>
    );

    global.console = {
      log: jest.fn()
    };

    expect(alrt.props().dismissible).toBe(true);
    expect(alrt.props().onDismiss).toBeDefined();

    alrt
      .find("div")
      .last()
      .simulate("click");
    expect(global.console.log).toBeCalled();
    expect(alrt.find("div").length).toBe(0);
  });

  it("Test Alert is dismissible when onDismiss prop is not defined", () => {
    const alrt = mount(
      <Alert type="danger" dismissible>
        This is danger
      </Alert>
    );

    expect(alrt.props().dismissible).toBe(true);

    alrt
      .find("div")
      .last()
      .simulate("click");
    expect(alrt.find("div").length).toBe(0);
  });
});


text:
<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\TblAssetTestSpeaker;

/**
 * SearchTblAssetTestSpeaker represents the model behind the search form about `common\models\TblAssetTestSpeaker`.
 */
class SearchTblAssetTestSpeaker extends TblAssetTestSpeaker
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'inventory_id', 'check_volume_control', 'check_audio_output', 'created_date', 'update_date', 'status'], 'integer'],
            [['service_period', 'comment'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = TblAssetTestSpeaker::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'inventory_id' => $this->inventory_id,
            'check_volume_control' => $this->check_volume_control,
            'check_audio_output' => $this->check_audio_output,
            'created_date' => $this->created_date,
            'update_date' => $this->update_date,
            'status' => $this->status,
        ]);

        $query->andFilterWhere(['like', 'service_period', $this->service_period])
            ->andFilterWhere(['like', 'comment', $this->comment]);

        return $dataProvider;
    }
}


text:
package org.onosproject.net;

import org.onlab.packet.ChassisId;
import org.onosproject.net.driver.Behaviour;
import org.onosproject.net.driver.DefaultDriverHandler;
import org.onosproject.net.driver.Driver;
import org.onosproject.net.driver.DriverData;
import org.onosproject.net.driver.HandlerBehaviour;
import org.onosproject.net.provider.ProviderId;

import java.util.Objects;

import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;

/**
 * Default infrastructure device model implementation.
 */
public class DefaultDevice extends AbstractElement implements Device {

    private static final int MANUFACTURER_MAX_LENGTH = 256;
    private static final int HW_VERSION_MAX_LENGTH = 256;
    private static final int SW_VERSION_MAX_LENGTH = 256;
    private static final int SERIAL_NUMBER_MAX_LENGTH = 256;

    private final Type type;
    private final String manufacturer;
    private final String serialNumber;
    private final String hwVersion;
    private final String swVersion;
    private final ChassisId chassisId;

    // For serialization
    private DefaultDevice() {
        this.type = null;
        this.manufacturer = null;
        this.hwVersion = null;
        this.swVersion = null;
        this.serialNumber = null;
        this.chassisId = null;
    }

    /**
     * Creates a network element attributed to the specified provider.
     *
     * @param providerId   identity of the provider
     * @param id           device identifier
     * @param type         device type
     * @param manufacturer device manufacturer
     * @param hwVersion    device HW version
     * @param swVersion    device SW version
     * @param serialNumber device serial number
     * @param chassisId    chassis id
     * @param annotations  optional key/value annotations
     */
    public DefaultDevice(ProviderId providerId, DeviceId id, Type type,
                         String manufacturer, String hwVersion, String swVersion,
                         String serialNumber, ChassisId chassisId,
                         Annotations... annotations) {
        super(providerId, id, annotations);
        if (hwVersion != null) {
            checkArgument(hwVersion.length() <= HW_VERSION_MAX_LENGTH,
                    "hwVersion exceeds maximum length " + HW_VERSION_MAX_LENGTH);
        }
        if (swVersion != null) {
            checkArgument(swVersion.length() <= SW_VERSION_MAX_LENGTH,
                    "swVersion exceeds maximum length " + SW_VERSION_MAX_LENGTH);
        }
        if (manufacturer != null) {
            checkArgument(manufacturer.length() <= MANUFACTURER_MAX_LENGTH,
                    "manufacturer exceeds maximum length " + MANUFACTURER_MAX_LENGTH);
        }
        if (serialNumber != null) {
            checkArgument(serialNumber.length() <= SERIAL_NUMBER_MAX_LENGTH,
                    "serialNumber exceeds maximum length " + SERIAL_NUMBER_MAX_LENGTH);
        }
        this.type = type;
        this.manufacturer = manufacturer;
        this.hwVersion = hwVersion;
        this.swVersion = swVersion;
        this.serialNumber = serialNumber;
        this.chassisId = chassisId;
    }

    @Override
    public DeviceId id() {
        return (DeviceId) id;
    }

    @Override
    public Type type() {
        return type;
    }

    @Override
    public String manufacturer() {
        return manufacturer;
    }

    @Override
    public String hwVersion() {
        return hwVersion;
    }

    @Override
    public String swVersion() {
        return swVersion;
    }

    @Override
    public String serialNumber() {
        return serialNumber;
    }

    @Override
    public ChassisId chassisId() {
        return chassisId;
    }

    @Override
    public <B extends Behaviour> B as(Class<B> projectionClass) {
        if (HandlerBehaviour.class.isAssignableFrom(projectionClass)) {
            bindAndCheckDriver();
            return driver().createBehaviour(new DefaultDriverHandler(asData()), projectionClass);
        }
        return super.as(projectionClass);
    }

    /**
     * Returns self as an immutable driver data instance.
     *
     * @return self as driver data
     */
    protected DriverData asData() {
        return new DeviceDriverData();
    }

    @Override
    protected Driver locateDriver() {
        Driver driver = super.locateDriver();
        return driver != null ? driver :
                driverService().getDriver(manufacturer, hwVersion, swVersion);
    }

    /**
     * Projection of the parent entity as a driver data entity.
     */
    protected class DeviceDriverData extends AnnotationDriverData {
        @Override
        public DeviceId deviceId() {
            return id();
        }
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, type, manufacturer, hwVersion, swVersion, serialNumber);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof DefaultDevice) {
            final DefaultDevice other = (DefaultDevice) obj;
            return Objects.equals(this.id, other.id) &&
                    Objects.equals(this.type, other.type) &&
                    Objects.equals(this.manufacturer, other.manufacturer) &&
                    Objects.equals(this.hwVersion, other.hwVersion) &&
                    Objects.equals(this.swVersion, other.swVersion) &&
                    Objects.equals(this.serialNumber, other.serialNumber);
        }
        return false;
    }

    @Override
    public String toString() {
        return toStringHelper(this)
                .add("id", id)
                .add("type", type)
                .add("manufacturer", manufacturer)
                .add("hwVersion", hwVersion)
                .add("swVersion", swVersion)
                .add("serialNumber", serialNumber)
                .add("driver", driver() != null ? driver().name() : "")
                .toString();
    }

}


text:
package idv.chatea.gldemo.postprocess;

import android.opengl.GLES20;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLContext;

/**
 * FrameBuffer provide a FBO with 1 ColorTexture and 1 DepthTexture.
 * This is useful to store as result of pre-processing, then used for post processing.
 *
 * The color is argb per 8 bit and the depth is 8 bit.
 */
public class FrameBuffer {
    private float mWidth;
    private float mHeight;

    private int[] mFBOIds;
    private int[] mColorTextureIds;
    private int[] mDepthTextureIds;
    // TODO stencil texture.

    /**
     * Must run in GLThread
     */
    public FrameBuffer(int width, int height) {
        if (((EGL10) EGLContext.getEGL()).eglGetCurrentContext().equals(EGL10.EGL_NO_CONTEXT)) {
            // no current context.
            throw new IllegalStateException("There is no EGLContext");
        }

        mWidth = width;
        mHeight = height;

        mFBOIds = new int[1];
        mColorTextureIds = new int[1];
        mDepthTextureIds = new int[1];

        // bind depth texture to FBO
        GLES20.glGenFramebuffers(1, mFBOIds, 0);
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFBOIds[0]);

        GLES20.glGenTextures(1, mColorTextureIds, 0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mColorTextureIds[0]);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
        GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);

        GLES20.glGenTextures(1, mDepthTextureIds, 0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mDepthTextureIds[0]);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
        GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_DEPTH_COMPONENT, width, height, 0, GLES20.GL_DEPTH_COMPONENT, GLES20.GL_UNSIGNED_SHORT, null);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);

        GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, mColorTextureIds[0], 0);
        GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_DEPTH_ATTACHMENT, GLES20.GL_TEXTURE_2D, mDepthTextureIds[0], 0);

        if (GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER) != GLES20.GL_FRAMEBUFFER_COMPLETE) {
            throw new RuntimeException("Create GL Framebuffer of shadow failed.");
        }

        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
    }

    public float getWidth() {
        return mWidth;
    }

    public float getHeight() {
        return mHeight;
    }

    public int getColorTexture() {
        return mColorTextureIds[0];
    }

    public int getDepthTexture() {
        return mDepthTextureIds[0];
    }

    /**
     * Must be call before using shadow
     */
    public void bind() {
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFBOIds[0]);
    }

    /**
     * Must be call after using shadow complete
     */
    public void unbind() {
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
    }

    @Override
    protected void finalize() throws Throwable {
        // TODO clear GL resource.
        super.finalize();
    }
}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
	value: true
});

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

var Property = (function () {
	function Property(name, value) {
		_classCallCheck(this, Property);

		this.name = name;
		this.value = value;
	}

	_createClass(Property, [{
		key: 'isActive',
		value: function isActive(activation, target) {
			var result = false;

			switch (activation) {
				case 'ACTIVE_IF_GREATER_THAN':
					if (this.value > target) result = true;
					break;
				case 'ACTIVE_IF_EQUALS_OR_GREATER_THAN':
					if (this.value >= target) result = true;
					break;
				case 'ACTIVE_IF_LESS_THAN':
					if (this.value < target) result = true;
					break;
				case 'ACTIVE_IF_EQUALS_OR_LESS_THAN':
					if (this.value <= target) result = true;
					break;
				case 'ACTIVE_IF_EQUALS':
					if (this.value == target) result = true;
					break;
				case 'ACTIVE_IF_DIVISABLE_OF':
					if (this.value % target == 0) result = true;
					break;
				case 'ACTIVE_IF_ODD':
					if (this.value % 2 != 0) result = true;
					break;
				case 'ACTIVE_IF_EVEN':
					if (this.value % 2 == 0) result = true;
					break;
				default:
					result = false;
			}
			return result;
		}
	}]);

	return Property;
})();

exports.Property = Property;

var Achievement = function Achievement(name, props) {
	_classCallCheck(this, Achievement);

	this.name = name;
	this.props = props;
	this.unlocked = false;
};

exports.Achievement = Achievement;

var Achieve = (function () {
	function Achieve() {
		_classCallCheck(this, Achieve);

		this.ACTIVE_IF_GREATER_THAN = '';
		this.ACTIVE_IF_LESS_THAN = '';
		this.ACTIVE_IF_EQUALS = '';
		this.props = {};
		this.achievements = [];
	}

	_createClass(Achieve, [{
		key: 'defineProperty',
		value: function defineProperty(name, value) {
			this.props[name] = new Property(name, value);
		}

		// props is an object
	}, {
		key: 'defineAchievement',
		value: function defineAchievement(name, props) {
			// props contains: name, activation, activationValue
			this.achievements[name] = new Achievement(name, props);
		}
	}, {
		key: 'getValue',
		value: function getValue(propName) {
			return this.props[propName].value;
		}
	}, {
		key: 'setValue',
		value: function setValue(propName, value) {
			this.props[propName].value = value;
		}
	}, {
		key: 'addValue',
		value: function addValue(propName, value) {
			this.setValue(propName, this.props[propName].value + value);
		}
	}, {
		key: 'subtractValue',
		value: function subtractValue(propName, value) {
			this.setValue(propName, this.props[propName].value - value);
		}

		/**
  * @param {String} filter locked or unlocked or empty for all
  */
	}, {
		key: 'getAchievements',
		value: function getAchievements(filter) {
			var results = [];
			var self = this;

			for (var a in self.achievements) {
				if (self.achievements.hasOwnProperty(a)) {
					var achievement = self.achievements[a];

					if (filter == 'unlocked') {
						if (achievement.unlocked) results.push(achievement);
					} else if (filter == 'locked') {
						if (!achievement.unlocked) results.push(achievement);
					} else results.push(achievement);
				}
			}
			return results;
		}
	}, {
		key: 'checkAchievements',
		value: function checkAchievements() {
			var results = Array();
			var self = this;

			for (var a in self.achievements) {
				if (self.achievements.hasOwnProperty(a)) {
					var achievement = self.achievements[a];
					achievement.progress = 0;
					if (achievement.props.length > 0) {
						var activeProps = 0;
						for (var i = 0; i < achievement.props.length; i++) {
							var p = achievement.props[i];
							achievement.props[i].isActive = self.props[achievement.props[i].propName].isActive(p.activation, p.activationValue);
							if (achievement.props[i].isActive) activeProps++;
						};

						if (activeProps == achievement.props.length) self.achievements[a].unlocked = true;else self.achievements[a].unlocked = false;
					}
					achievement.progress = activeProps / achievement.props.length * 100;
				}
			}
			return self.getAchievements('unlocked');
		}
	}]);

	return Achieve;
})();

exports.Achieve = Achieve;


text:
<!--
    @license
    Copyright 2014 Google Inc

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<link rel="import" href="../polymer/polymer.html">

<!--
A Polymer element to observe changes to the properties of items in an array.

##### Example

    <observe-array-items array="{{contacts}}"
                         path="home.phone"
                         on-array-item-changed="{{handleArrayItemChanged}}">
    </observe-array-items>

@element observe-array-items
@blurb A Polymer element to observe changes to the properties of items in an array.
@status alpha
@homepage https://jeffposnick.github.io/observe-array-items
-->
<polymer-element name="observe-array-items" attributes="array path">
  <script>
    Polymer({
      /**
       * The `array` attribute sets the `Array` containing the `Object`s whose
       * properties we're watching.
       *
       * This is required.
       *
       * @attribute array
       * @type Array
       */
      array: null,

      /**
       * The `path` attribute determines which properties we're observing.
       *
       * This value will be passed in to the [`PathObserver`](https://github.com/polymer/observe-js#pathobserver)
       * constructor, so this supports [`Path`](https://github.com/polymer/observe-js#path-objects)
       * objects as well as strings, though strings are the most common use case.
       *
       * The default value of `''` signifies that the root object is being observed.
       *
       * @property path
       * @type string
       * @default ''
       */
      path: '',

      /**
       * The `array-item-changed` event is fired whenever there is a change to the property
       * matching path `this.path` of an `Object` in `this.array`.
       *
       * @event array-item-changed
       * @param {Object} detail
       *   @param {Object} detail.oldValue The previous value for the property at `this.path`.
       *   @param {Object} detail.newValue The current value for the property at `this.path`.
       *   @param {Number} detail.index The index of the item in `this.array` whose property changed.
       */

      _observers: null,

      arrayChanged: function() {
        this._observers.forEach(function(observer) {
          observer.close();
        });
        this._observers = [];

        this.array.forEach(function(item, i) {
          var observer = new PathObserver(item, this.path);

          observer.open(function(newValue, oldValue) {
            this.asyncFire('array-item-changed', {
              oldValue: oldValue,
              newValue: newValue,
              index: i
            });
          }.bind(this));

          this._observers.push(observer);
        }.bind(this));
      },

      ready: function() {
        this._observers = [];
      }
    });
  </script>
</polymer-element>


text:
set -ex

# Keep track of the DevStack directory
TOP_DIR=$(cd $(dirname "$0")/.. && pwd)

NAME=$1
CPU=$2
MEM=$(( 1024 * $3 ))
# Extra G to allow fuzz for partition table : flavor size and registered size
# need to be different to actual size.
DISK=$(( $4 + 1))

case $5 in
    i386) ARCH='i686' ;;
    amd64) ARCH='x86_64' ;;
    *) echo "Unsupported arch $4!" ; exit 1 ;;
esac

BRIDGE=$6
EMULATOR=$7
LOGDIR=$8

LIBVIRT_NIC_DRIVER=${LIBVIRT_NIC_DRIVER:-"e1000"}
LIBVIRT_STORAGE_POOL=${LIBVIRT_STORAGE_POOL:-"default"}
LIBVIRT_CONNECT_URI=${LIBVIRT_CONNECT_URI:-"qemu:///system"}

export VIRSH_DEFAULT_CONNECT_URI=$LIBVIRT_CONNECT_URI

if ! virsh pool-list --all | grep -q $LIBVIRT_STORAGE_POOL; then
    virsh pool-define-as --name $LIBVIRT_STORAGE_POOL dir --target /var/lib/libvirt/images >&2
    virsh pool-autostart $LIBVIRT_STORAGE_POOL >&2
    virsh pool-start $LIBVIRT_STORAGE_POOL >&2
fi

pool_state=$(virsh pool-info $LIBVIRT_STORAGE_POOL | grep State | awk '{ print $2 }')
if [ "$pool_state" != "running" ] ; then
    [ ! -d /var/lib/libvirt/images ] && sudo mkdir /var/lib/libvirt/images
    virsh pool-start $LIBVIRT_STORAGE_POOL >&2
fi

if [ -n "$LOGDIR" ] ; then
    mkdir -p "$LOGDIR"
fi

PREALLOC=
if [ -f /etc/debian_version ]; then
    PREALLOC="--prealloc-metadata"
fi

if [ -n "$LOGDIR" ] ; then
    VM_LOGGING="--console-log $LOGDIR/${NAME}_console.log"
else
    VM_LOGGING=""
fi
VOL_NAME="${NAME}.qcow2"

if ! virsh list --all | grep -q $NAME; then
    virsh vol-list --pool $LIBVIRT_STORAGE_POOL | grep -q $VOL_NAME &&
        virsh vol-delete $VOL_NAME --pool $LIBVIRT_STORAGE_POOL >&2
    virsh vol-create-as $LIBVIRT_STORAGE_POOL ${VOL_NAME} ${DISK}G --format qcow2 $PREALLOC >&2
    volume_path=$(virsh vol-path --pool $LIBVIRT_STORAGE_POOL $VOL_NAME)
    # Pre-touch the VM to set +C, as it can only be set on empty files.
    sudo touch "$volume_path"
    sudo chattr +C "$volume_path" || true
    $TOP_DIR/scripts/configure-vm.py \
        --bootdev network --name $NAME --image "$volume_path" \
        --arch $ARCH --cpus $CPU --memory $MEM --libvirt-nic-driver $LIBVIRT_NIC_DRIVER \
        --emulator $EMULATOR --network $BRIDGE $VM_LOGGING >&2
fi

# echo mac
virsh dumpxml $NAME | grep "mac address" | head -1 | cut -d\' -f2


text:
namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkViewModule::WatermarkViewModule(
                WindowsNativeState& nativeState,
                IWatermarkViewModel& viewModel,
				IWatermarkDataRepository& watermarkDataRepository,
                ExampleAppMessaging::TMessageBus& messageBus,
                Metrics::IMetricsService& metricsService
            )
            {
				ASSERT_UI_THREAD

				const WatermarkData& defaultWatermarkData = watermarkDataRepository.GetWatermarkDataWithKey("eegeo");

                m_pView = Eegeo_NEW(WatermarkView)(nativeState, defaultWatermarkData);

                m_pController = Eegeo_NEW(WatermarkController)(
                                    viewModel,
                                    *m_pView,
									watermarkDataRepository,
                                    messageBus,
                                    metricsService);

            }

            WatermarkViewModule::~WatermarkViewModule()
            {
                ASSERT_UI_THREAD
                Eegeo_DELETE m_pController;
                Eegeo_DELETE m_pView;
            }
        }
    }
}


text:
package main

import (
	"github.com/lextoumbourou/idle"
	"log"
	"time"
)

func main() {
	var err error
	var idleTime time.Duration

	oneSecond, _ := time.ParseDuration("1s")

	for err == nil {
		idleTime, err = idle.Get()

		if idleTime.Seconds() > 1.0 {
			log.Printf("Idle for %d seconds.", int(idleTime.Seconds()))
		}

		time.Sleep(oneSecond)
	}

	if err != nil {
		log.Fatal(err)
	}
}


text:
package gnu.java.rmi.activation;

import gnu.java.rmi.server.ActivatableServerRef;
import gnu.java.rmi.server.UnicastServer;

import java.lang.reflect.Constructor;
import java.rmi.MarshalledObject;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.activation.ActivationDesc;
import java.rmi.activation.ActivationException;
import java.rmi.activation.ActivationGroup;
import java.rmi.activation.ActivationGroupID;
import java.rmi.activation.ActivationID;
import java.rmi.activation.UnknownObjectException;

/**
 * The default activation group class. This activation group assumes that
 * all classes are accessible via current thread context class loader.
 * The remote class loading is not supported for security reasons. The
 * activation always occurs in the current jre.
 *
 * @author Audrius Meskauskas (audriusa@Bioinformatics.org)
 */
public class DefaultActivationGroup
    extends ActivationGroup
{
  /**
   * Use the serialVersionUID for interoperability.
   */
  private static final long serialVersionUID = 1;

  /**
   * Used during the group creation (required constructor).
   */
  static final Class[] cConstructorTypes = new Class[]
                                                   {
                                                    ActivationID.class,
                                                    MarshalledObject.class
                                                   };

  /**
   * Create the new default activation group.
   *
   * @param id the group activation id.
   * @param data may contain the group initialization data (unused and can be
   *          null)
   * @throws RemoteException if the super constructor does
   */
  public DefaultActivationGroup(ActivationGroupID id, MarshalledObject data)
  throws RemoteException
  {
    super(id);
  }

  /**
   * May be overridden and used as a hook. This method is called each time
   * the new object is instantiated.
   */
  public void activeObject(ActivationID id, Remote obj)
      throws ActivationException, UnknownObjectException, RemoteException
  {
    // Nothing to do (the monitor is already notified in newInstance)
  }

  /**
   * Create the new instance of the object, using the class name and location
   * information, stored in the passed descriptor. The method expects the object
   * class to have the two parameter constructor, the first parameter being the
   * {@link ActivationID} and the second the {@link MarshalledObject}.
   *
   * @param id the object activation id
   * @param desc the activation descriptor, providing the information, necessary
   *          to create and activate the object
   * @return the marshalled object, containing the exported stub of the created
   *         object
   * @throws ActivationException if the activation fails due any reason
   */
  public MarshalledObject newInstance(ActivationID id, ActivationDesc desc)
      throws ActivationException, RemoteException
  {
    try
      {
        if (ActivationSystemTransient.debug)
          System.out.println("Instantiating "+desc.getClassName());

        Remote object;
        Class objectClass;

        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        objectClass = loader.loadClass(desc.getClassName());
        Constructor constructor = objectClass.getConstructor(cConstructorTypes);
        object = (Remote) constructor.newInstance(
          new Object[] { id, desc.getData() });

        // Make the object accessible and create the stub.
        ActivatableServerRef ref = UnicastServer.getActivatableRef(id);
        Remote stub = ref.exportObject(object);

        MarshalledObject marsh = new MarshalledObject(stub);

        // Notify the activation monitor.
        activeObject(id, marsh);

        // Make call to the hook that may be overridden.
        activeObject(id, stub);

        return marsh;
      }
    catch (Exception e)
      {
        ActivationException acex = new ActivationException(
          "Unable to activate "+ desc.getClassName()
            + " from "+ desc.getLocation(), e);
        throw acex;
      }
  }

}


text:
<?php

declare(strict_types=1);

namespace Phoenix\Tests\Command\CleanupCommand;

use Phoenix\Command\CleanupCommand;
use Phoenix\Command\InitCommand;
use Phoenix\Exception\ConfigException;
use Phoenix\Tests\Command\BaseCommandTest;
use Phoenix\Tests\Mock\Command\Output;
use Symfony\Component\Console\Output\OutputInterface;

abstract class CleanupCommandTest extends BaseCommandTest
{
    public function testDefaultName(): void
    {
        $command = new CleanupCommand();
        $this->assertEquals('cleanup', $command->getName());
    }

    public function testCustomName(): void
    {
        $command = new CleanupCommand('my_cleanup');
        $this->assertEquals('my_cleanup', $command->getName());
    }

    public function testMissingDefaultConfig(): void
    {
        $command = new CleanupCommand();
        $this->expectException(ConfigException::class);
        $this->expectExceptionMessage('No configuration file exists. Create phoenix.php or phoenix.yml or phoenix.neon or phoenix.json in your project root or specify path to your existing config file with --config option');
        $command->run($this->input, $this->output);
    }

    public function testUserConfigFileNotFound(): void
    {
        $command = new CleanupCommand();
        $this->input->setOption('config', 'xyz.neon');
        $this->expectException(ConfigException::class);
        $this->expectExceptionMessage('Configuration file "xyz.neon" doesn\'t exist.');
        $command->run($this->input, $this->output);
    }

    public function testUserConfigFile(): void
    {
        $initCommand = new InitCommand();
        $input = $this->createInput();
        $input->setOption('config', __DIR__ . '/../../../testing_migrations/config/phoenix.php');
        $initCommand->run($input, new Output());

        $command = new CleanupCommand();
        $this->input->setOption('config', __DIR__ . '/../../../testing_migrations/config/phoenix.php');
        $command->run($this->input, $this->output);

        $messages = $this->output->getMessages();

        $this->assertTrue(is_array($messages));
        $this->assertArrayHasKey(0, $messages);
        $this->assertCount(6, $messages[0]);
        $this->assertEquals('<info>Phoenix cleaned</info>' . "\n", $messages[0][1]);
        $this->assertArrayHasKey(OutputInterface::VERBOSITY_DEBUG, $messages);
        $this->assertTrue(count($messages[OutputInterface::VERBOSITY_DEBUG]) > 0);
    }

    public function testUserConfigFileAndJsonOutput(): void
    {
        $initCommand = new InitCommand();
        $input = $this->createInput();
        $input->setOption('config', __DIR__ . '/../../../testing_migrations/config/phoenix.php');
        $initCommand->run($input, new Output());

        $command = new CleanupCommand();
        $this->input->setOption('config', __DIR__ . '/../../../testing_migrations/config/phoenix.php');
        $this->input->setOption('output-format', 'json');
        $command->run($this->input, $this->output);

        $messages = $this->output->getMessages(0);

        $this->assertTrue(is_array($messages));
        $this->assertCount(1, $messages);
        $this->assertArrayHasKey(0, $messages);
        $this->assertJson($messages[0]);

        $message = json_decode($messages[0], true);

        $this->assertArrayHasKey('message', $message);
        $this->assertEquals('Phoenix cleaned', $message['message']);
        $this->assertArrayNotHasKey('executed_migrations', $message);
        $this->assertArrayHasKey('execution_time', $message);
    }

    public function testUserConfigFileAndJsonOutputAndDebugVerbosity(): void
    {
        $initCommand = new InitCommand();
        $input = $this->createInput();
        $input->setOption('config', __DIR__ . '/../../../testing_migrations/config/phoenix.php');
        $initCommand->run($input, new Output());

        $command = new CleanupCommand();
        $this->input->setOption('config', __DIR__ . '/../../../testing_migrations/config/phoenix.php');
        $this->input->setOption('output-format', 'json');
        $this->output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
        $command->run($this->input, $this->output);

        $messages = $this->output->getMessages(0);

        $this->assertTrue(is_array($messages));
        $this->assertCount(1, $messages);
        $this->assertArrayHasKey(0, $messages);
        $this->assertJson($messages[0]);

        $message = json_decode($messages[0], true);

        $this->assertArrayHasKey('message', $message);
        $this->assertEquals('Phoenix cleaned', $message['message']);
        $this->assertArrayHasKey('executed_migrations', $message);
        $this->assertArrayHasKey('execution_time', $message);
    }
}


text:
const int32 LIFE = 42;

struct Foo {
  int32 hello[42]; // arrays are always of constant size
  int32 hello2[LIFE]; // constants can also be used

  float world[int32]; // if a type is specified, another variable is created that specifies the size

  float world2[int32, int32]; // if a second type is specified, the first is the number of items and second value is actual size of the array

  float world3[int32, 42]; // the second type can also be a constant
  float world4[int32, LIFE];
}


text:
package org.nekperu15739.microservices.springcloudconfig;

import static org.hamcrest.CoreMatchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.apache.commons.lang3.StringUtils;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

/**
 *
 * @author nekperu15739
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class SpringCloudConfigApplicationTest {

    @Autowired
    private MockMvc mvc;

    @Value("${spring.application.name:licensingservice}")
    private String application;

    private static final String SEPARATOR = "/";
    private static final String LABEL = "/label";
    private static final String PROFILES_DEV = "dev";

    private static final String ROUTE_ONE = "/%s/%s%s";
    private static final String ROUTE_TWO = "/%s-%s.yml";
    private static final String ROUTE_THREE = "%s/%s-%s.yml";
    private static final String ROUTE_FOUR = "/%s-%s.properties";
    private static final String ROUTE_FIVE = "%s/%s-%s.properties";

    /**
     * /{application}/{profile}[/{label}]
     *
     * @throws Exception
     */
    @Test
    public void routeOneTest() throws Exception {
        this.mvc.perform(get(String.format(ROUTE_ONE, application, PROFILES_DEV, StringUtils.EMPTY)).accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk()).andExpect(content().string(containsString("10")));

        this.mvc.perform(get(String.format(ROUTE_ONE, application, PROFILES_DEV, LABEL)).accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk()).andExpect(content().string(containsString("20")));
    }

    /**
     * /{application}-{profile}.yml
     *
     * @throws Exception
     */
    @Test
    public void routeTwoTest() throws Exception {
        this.mvc.perform(get(String.format(ROUTE_TWO, application, PROFILES_DEV)).accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk()).andExpect(content().string(containsString("10")));
    }

    /**
     * /{label}/{application}-{profile}.yml
     *
     * @throws Exception
     */
    @Test
    public void routeThreeTest() throws Exception {
        this.mvc.perform(get(String.format(ROUTE_THREE, LABEL ,application, PROFILES_DEV)).accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk()).andExpect(content().string(containsString("20")));
    }

    /**
     * /{application}-{profile}.properties
     * @throws Exception
     */
    @Test
    public void routeFourTest() throws Exception {
        this.mvc.perform(get(String.format(ROUTE_FOUR, application, PROFILES_DEV)).accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk()).andExpect(content().string(containsString("10")));
    }

    /**
     *  /{label}/{application}-{profile}.properties
     */
    @Test
    public void routeFiveTest() throws Exception {
        this.mvc.perform(get(String.format(ROUTE_FIVE, LABEL, application, PROFILES_DEV)).accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk()).andExpect(content().string(containsString("20")));
    }
}


text:
import EmberObject from '@ember/object';
import { module, test } from 'qunit';
import { setupIntegrationTest } from 'open-event-frontend/tests/helpers/setup-integration-test';
import hbs from 'htmlbars-inline-precompile';
import { render } from '@ember/test-helpers';

module('Integration | Component | session card', function(hooks) {
  setupIntegrationTest(hooks);

  const session = EmberObject.create({ id: 123, title: 'Super cool JS', state: 'rejected', event: 'OS Tech', startsAt: new Date(), endsAt: new Date() });

  test('it renders', async function(assert) {
    this.set('session', session);
    await render(hbs`{{session-card session=session}}`);
    assert.ok(this.element.innerHTML.trim().includes('rejected'));
  });
});


text:
export default function SpecialArray () {
    // 创建数组
    let values = new Array()
    // 添加值
    values.push.apply(values, arguments)
    // 添加方法
    values.toPipedString = function () {
        return this.join('|')
    }
    // 返回数组
    return values
}


text:
require 'test_helper'

class DeviceMailerTest < ActionMailer::TestCase
  test "new_device" do
    mail = DeviceMailer.new_device
    assert_equal "New device", mail.subject
    assert_equal ["to@example.org"], mail.to
    assert_equal ["from@example.com"], mail.from
    assert_match "Hi", mail.body.encoded
  end

end


text:
package com.jobxhub.common.util;

public class Holder<T> {

    private volatile T value;

    public void set(T value) {
        this.value = value;
    }

    public T get() {
        return value;
    }

}


text:
.employee-list {
  height: 600px;
  overflow-y: scroll;
}


text:
/**
 * Module dependencies.
 */
var
    fs = require('fs'),
    path = require('path'),
    os = require('os'),
    exists = fs.exists || path.exists,
    tmpDir = os.tmpDir || _getTMPDir,
    _c = require('constants');

/**
 * The working inner variables.
 */
var
    // store the actual TMP directory
    _TMP = tmpDir(),

    // the random characters to choose from
    randomChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",
    randomCharsLength = randomChars.length,

    // this will hold the objects need to be removed on exit
    _removeObjects = [],

    _gracefulCleanup = false,
    _uncaughtException = false;

/**
 * Gets the temp directory.
 *
 * @return {String}
 * @api private
 */
function _getTMPDir() {
    var tmpNames = ['TMPDIR', 'TMP', 'TEMP'];

    for (var i = 0, length = tmpNames.length; i < length; i++) {
        if (_isUndefined(process.env[tmpNames[i]])) {
            continue;
        }

        return process.env[tmpNames[i]];
    }

    // fallback to the default
    return '/tmp';
}

/**
 * Checks whether the `obj` parameter is defined or not.
 *
 * @param {Object} obj
 * @return {Boolean}
 * @api private
 */
function _isUndefined(obj) {
    return typeof obj === 'undefined';
}

/**
 * Parses the function arguments.
 *
 * This function helps to have optional arguments.
 *
 * @param {Object} options
 * @param {Function} callback
 * @api private
 */
function _parseArguments(options, callback) {
    if (!callback || typeof callback != "function") {
        callback = options;
        options = {};
    }

    return [options, callback];
}

/**
 * Gets a temporary file name.
 *
 * @param {Object} opts
 * @param {Function} cb
 * @api private
 */
function _getTmpName(options, callback) {
    var
        args = _parseArguments(options, callback),
        opts = args[0],
        cb = args[1],
        template = opts.template,
        templateDefined = !_isUndefined(template),
        tries = opts.tries || 3;

    if (isNaN(tries) || tries < 0) {
        return cb(new Error('Invalid tries'));
    }

    if (templateDefined && !template.match(/XXXXXX/)) {
        return cb(new Error('Invalid template provided'));
    }

    function _getName() {

        // prefix and postfix
        if (!templateDefined) {
            var name = [
                (_isUndefined(opts.prefix)) ? 'tmp-' : opts.prefix,
                process.pid,
                (Math.random() * 0x1000000000).toString(36),
                opts.postfix
            ].join('');

            return path.join(opts.dir || _TMP, name);
        }

        // mkstemps like template
        var chars = [];

        for (var i = 0; i < 6; i++) {
            chars.push(randomChars.substr(Math.floor(Math.random() * randomCharsLength), 1));
        }

        return template.replace(/XXXXXX/, chars.join(''));
    }

    (function _getUniqueName() {
        var name = _getName();

        // check whether the path exists then retry if needed
        exists(name, function _pathExists(pathExists) {
            if (pathExists) {
                if (tries-- > 0) {
                    return _getUniqueName();
                }

                return cb(new Error('Could not get a unique tmp filename, max tries reached'));
            }

            cb(null, name);
        });
    }());
}

/**
 * Creates and opens a temporary file.
 *
 * @param {Object} options
 * @param {Function} callback
 * @api public
 */
function _createTmpFile(options, callback) {
    var
        args = _parseArguments(options, callback),
        opts = args[0],
        cb = args[1];

    opts.postfix = (_isUndefined(opts.postfix)) ? '.tmp' : opts.postfix;

    // gets a temporary filename
    _getTmpName(opts, function _tmpNameCreated(err, name) {
        if (err) {
            return cb(err);
        }

        // create and open the file
        fs.open(name, _c.O_CREAT | _c.O_EXCL | _c.O_RDWR, opts.mode || 0600, function _fileCreated(err, fd) {
            if (err) {
                return cb(err);
            }

            if (!opts.keep) {
                _removeObjects.unshift([fs.unlinkSync, name]);
            }

            cb(null, name, fd);
        });
    });
}

/**
 * Removes files and folders in a directory recursively.
 *
 * @param {String} path
 */
function _rmdirRecursiveSync(dir) {
    var files = fs.readdirSync(dir);

    for (var i = 0, length = files.length; i < length; i++) {
        var file = path.join(dir, files[i]);
        // lstat so we don't recurse into symlinked directories.
        var stat = fs.lstatSync(file);

        if (stat.isDirectory()) {
            _rmdirRecursiveSync(file);
        } else {
            fs.unlinkSync(file);
        }
    }

    fs.rmdirSync(dir);
}

/**
 * Creates a temporary directory.
 *
 * @param {Object} options
 * @param {Function} callback
 * @api public
 */
function _createTmpDir(options, callback) {
    var
        args = _parseArguments(options, callback),
        opts = args[0],
        cb = args[1];

    // gets a temporary filename
    _getTmpName(opts, function _tmpNameCreated(err, name) {
        if (err) {
            return cb(err);
        }

        // create the directory
        fs.mkdir(name, opts.mode || 0700, function _dirCreated(err) {
            if (err) {
                return cb(err);
            }

            if (!opts.keep) {
                if (opts.unsafeCleanup) {
                    _removeObjects.unshift([_rmdirRecursiveSync, name]);
                } else {
                    _removeObjects.unshift([fs.rmdirSync, name]);
                }
            }

            cb(null, name);
        });
    });
}

/**
 * The garbage collector.
 *
 * @api private
 */
function _garbageCollector() {
    if (_uncaughtException && !_gracefulCleanup) {
        return;
    }

    for (var i = 0, length = _removeObjects.length; i < length; i++) {
        try {
            _removeObjects[i][0].call(null, _removeObjects[i][1]);
        } catch (e) {
            // already removed?
        }
    }
}

function _setGracefulCleanup() {
    _gracefulCleanup = true;
}

var version = process.versions.node.split('.').map(function (value) {
    return parseInt(value, 10);
});

if (version[0] === 0 && (version[1] < 9 || version[1] === 9 && version[2] < 5)) {
    process.addListener('uncaughtException', function _uncaughtExceptionThrown(err) {
        _uncaughtException = true;
        _garbageCollector();

        throw err;
    });
}

process.addListener('exit', function _exit(code) {
    if (code) {
        _uncaughtException = true;
    }
    _garbageCollector();
});

// exporting all the needed methods
module.exports.tmpdir = _TMP;
module.exports.dir = _createTmpDir;
module.exports.file = _createTmpFile;
module.exports.tmpName = _getTmpName;
module.exports.setGracefulCleanup = _setGracefulCleanup;


text:
var moment = require('moment');
var uuid = require('uuid');

function Pamadara() {
  this.timers = [];

  this.timerRes = 1000;
}

/*
  Start a timer with an optional cb to be run after the timer is complete
*/
Pamadara.prototype.startTimer = function(cb) {
  // Generate a unique ID
  var id = uuid.v4();

  var startTime = moment();
  var endTime = startTime.add(25, 'minutes');

  var timer = {
    _id: id,
    startTime: startTime,
    endTime: endTime,
    onEnd: cb
  }

  this.timers.push(timer);

  return timer._id;
};

/*
  Handle the ending of a timer
*/
Pamadara.prototype.handleTimerEnd = function(timer) {
  // Emit an event saying the timer has been finished
  var evt = {
    timerId: timer._id
  }

  // Run the timer callback
  timer.onEnd && timer.onEnd();
};

/*
  Look for timers about to run out
*/
Pamadara.prototype.startWatch = function() {
  var self = this;

  (function checkForEndedTimers() {
    setTimeout(checkForEndedTimers, self.timerRes);

    // Abort if no timers exist
    if (self.timers.length === 0) return;

    // check the timers
    var now = moment();

    // Timers should be sorted by start/end time
    while (now.isAfter(self.timers[0].endTime)) {
      // Handle the finished timer
      self.handleTimerEnd(self.timers[0]);

      // Remove the finished timer
      self.timers.shift();

      // If no more timers exit
      if (self.timers.length === 0) {
        break;
      }
    }
  })();
};

module.exports = Pamadara;


text:
#ifndef MAP_H_
#define MAP_H_

#include <opencv2/core.hpp> // Basic OpenCV structures (cv::Mat, Scalar)

/** @defgroup reg Image Registration

The Registration module implements parametric image registration. The implemented method is direct
alignment, that is, it uses directly the pixel values for calculating the registration between a
pair of images, as opposed to feature-based registration. The implementation follows essentially the
corresponding part of @cite Szeliski06 .

Feature based methods have some advantages over pixel based methods when we are trying to register
pictures that have been shoot under different lighting conditions or exposition times, or when the
images overlap only partially. On the other hand, the main advantage of pixel-based methods when
compared to feature based methods is their better precision for some pictures (those shoot under
similar lighting conditions and that have a significative overlap), due to the fact that we are
using all the information available in the image, which allows us to achieve subpixel accuracy. This
is particularly important for certain applications like multi-frame denoising or super-resolution.

In fact, pixel and feature registration methods can complement each other: an application could
first obtain a coarse registration using features and then refine the registration using a pixel
based method on the overlapping area of the images. The code developed allows this use case.

The module implements classes derived from the abstract classes cv::reg::Map or cv::reg::Mapper. The
former models a coordinate transformation between two reference frames, while the later encapsulates
a way of invoking a method that calculates a Map between two images. Although the objective has been
to implement pixel based methods, the module can be extended to support other methods that can
calculate transformations between images (feature methods, optical flow, etc.).

Each class derived from Map implements a motion model, as follows:

-   MapShift: Models a simple translation
-   MapAffine: Models an affine transformation
-   MapProjec: Models a projective transformation

MapProject can also be used to model affine motion or translations, but some operations on it are
more costly, and that is the reason for defining the other two classes.

The classes derived from Mapper are

-   MapperGradShift: Gradient based alignment for calculating translations. It produces a MapShift
    (two parameters that correspond to the shift vector).
-   MapperGradEuclid: Gradient based alignment for euclidean motions, that is, rotations and
    translations. It calculates three parameters (angle and shift vector), although the result is
    stored in a MapAffine object for convenience.
-   MapperGradSimilar: Gradient based alignment for calculating similarities, which adds scaling to
    the euclidean motion. It calculates four parameters (two for the anti-symmetric matrix and two
    for the shift vector), although the result is stored in a MapAffine object for better
    convenience.
-   MapperGradAffine: Gradient based alignment for an affine motion model. The number of parameters
    is six and the result is stored in a MapAffine object.
-   MapperGradProj: Gradient based alignment for calculating projective transformations. The number
    of parameters is eight and the result is stored in a MapProject object.
-   MapperPyramid: It implements hyerarchical motion estimation using a Gaussian pyramid. Its
    constructor accepts as argument any other object that implements the Mapper interface, and it is
    that mapper the one called by MapperPyramid for each scale of the pyramid.

If the motion between the images is not very small, the normal way of using these classes is to
create a MapperGrad\* object and use it as input to create a MapperPyramid, which in turn is called
to perform the calculation. However, if the motion between the images is small enough, we can use
directly the MapperGrad\* classes. Another possibility is to use first a feature based method to
perform a coarse registration and then do a refinement through MapperPyramid or directly a
MapperGrad\* object. The "calculate" method of the mappers accepts an initial estimation of the
motion as input.

When deciding which MapperGrad to use we must take into account that mappers with more parameters
can handle more complex motions, but involve more calculations and are therefore slower. Also, if we
are confident on the motion model that is followed by the sequence, increasing the number of
parameters beyond what we need will decrease the accuracy: it is better to use the least number of
degrees of freedom that we can.

In the module tests there are examples that show how to register a pair of images using any of the
implemented mappers.
*/

namespace cv {
namespace reg {

//! @addtogroup reg
//! @{

/** @brief Base class for modelling a Map between two images.

The class is only used to define the common interface for any possible map.
 */
class CV_EXPORTS Map
{
public:
    /*!
     * Virtual destructor
     */
    virtual ~Map(void);

    /*!
     * Warps image to a new coordinate frame. The calculation is img2(x)=img1(T^{-1}(x)), as we
     * have to apply the inverse transformation to the points to move them to were the values
     * of img2 are.
     * \param[in] img1 Original image
     * \param[out] img2 Warped image
     */
    virtual void warp(const cv::Mat& img1, cv::Mat& img2) const;

    /*!
     * Warps image to a new coordinate frame. The calculation is img2(x)=img1(T(x)), so in fact
     * this is the inverse warping as we are taking the value of img1 with the forward
     * transformation of the points.
     * \param[in] img1 Original image
     * \param[out] img2 Warped image
     */
    virtual void inverseWarp(const cv::Mat& img1, cv::Mat& img2) const = 0;

    /*!
     * Calculates the inverse map
     * \return Inverse map
     */
    virtual cv::Ptr<Map> inverseMap(void) const = 0;

    /*!
     * Changes the map composing the current transformation with the one provided in the call.
     * The order is first the current transformation, then the input argument.
     * \param[in] map Transformation to compose with.
     */
    virtual void compose(const Map& map) = 0;

    /*!
     * Scales the map by a given factor as if the coordinates system is expanded/compressed
     * by that factor.
     * \param[in] factor Expansion if bigger than one, compression if smaller than one
     */
    virtual void scale(double factor) = 0;
};

//! @}

}}  // namespace cv::reg

#endif  // MAP_H_


text:
/*
    Utility functions
*/
"use strict";

var protectedProperties = ['scope',  'dom'],

    isProtected = function (key) {
        return (protectedProperties.indexOf(key) !== -1);
    },

    /*
        Get var type as string

        @param: Variable to test
        @return [string]: Returns, for instance 'Object' if [object Object]
    */
    varType = function (variable) {
        return Object.prototype.toString.call(variable).slice(8, -1);
    };

module.exports = {

    /*
        Iterate over an object and fire a callback for every item in it

        @param [object]: Properties
        @param [function]: Callback to fire
    */
    each: function (props, callback) {
        var keys = Object.keys(props),
            numKeys = keys.length;

        for (let i = 0; i < numKeys; i++) {
            let key = keys[i],
                prop = props[key];

            if (callback(key, prop) === false) {
                break;
            }
        }
    },

    /*
        Has one object changed from the other

        Compares the two provided inputs and returns true if they are different

        @param [object]: Input A
        @param [object]: Input B
        @return [boolean]: True if different
    */
    hasChanged: function (a, b) {
        var hasChanged = false,
            key = '';

        for (key in b) {
            if (a.hasOwnProperty(key) && b.hasOwnProperty(key)) {
                if (a[key] !== b[key]) {
                    hasChanged = true;
                }
            } else {
                hasChanged = true;
            }
        }

        return hasChanged;
    },

    /*
        Is this var a number?

        @param: Variable to test
        @return [boolean]: Returns true if typeof === 'number'
    */
    isNum: function (num) {
        return (typeof num === 'number');
    },

    /*
        Is this var an object?

        @param: Variable to test
        @return [boolean]: Returns true if typeof === 'object'
    */
    isObj: function (obj) {
        return (typeof obj === 'object');
    },

    /*
        Is this var a function ?

        @param: Variable to test
        @return [boolean]: Returns true if this.varType === 'Function'
    */
    isFunc: function (obj) {
        return (varType(obj) === 'Function');
    },

    /*
        Is this var a string ?

        @param: Variable to test
        @return [boolean]: Returns true if typeof str === 'string'
    */
    isString: function (str) {
        return (typeof str === 'string');
    },

    /*
        Is this a relative value assignment?

        @param [string]: Variable to test
        @return [boolean]: If this looks like a relative value assignment
    */
    isRelativeValue: function (value) {
        return (value && value.indexOf && value.indexOf('=') > 0);
    },

    /*
        Is this var an array ?

        @param: Variable to test
        @return [boolean]: Returns true if this.varType === 'Array'
    */
    isArray: function (arr) {
        return (varType(arr) === 'Array');
    },

    /*
        Copy object or array

        Checks whether base is an array or object and makes
        appropriate copy

        @param [array || object]: Array or object to copy
        @param [array || object]: New copy of array or object
    */
    copy: function (base) {
        return (this.isArray(base)) ? this.copyArray(base) : this.copyObject(base);
    },

    /*
        Deep copy an object

        Iterates over an object and creates a new copy of every item,
        deep copying if it finds any objects/arrays

        @param [object]: Object to copy
        @param [object]: New copy of object
    */
    copyObject: function (base) {
        var newObject = {};

        for (var key in base) {
            if (base.hasOwnProperty(key)) {
                newObject[key] = (this.isObj(base[key]) && !isProtected(key)) ? this.copy(base[key]) : base[key];
            }
        }

        return newObject;
    },

    /*
        Deep copy an array

        Loops through an array and creates a new copy of every item,
        deep copying if it finds any objects/arrays

        @param [array]: Array to copy
        @return [array]: New copy of array
    */
    copyArray: function (base) {
        var newArray = [],
            length = base.length,
            i = 0;

        for (; i < length; i++) {
            newArray[i] = (this.isObj(base[i])) ? this.copy(base[i]) : base[i];
        }

        return newArray;
    },

    /*
        Non-destructive merge of object or array

        @param [array || object]: Array or object to use as base
        @param [array || object]: Array or object to overwrite base with
        @return [array || object]: New array or object
    */
    merge: function (base, overwrite) {
        return (this.isArray(base)) ? this.copyArray(overwrite) : this.mergeObject(base, overwrite);
    },

    /*
        Non-destructive merge of object

        @param [object]: Object to use as base
        @param [object]: Object to overwrite base with
        @return [object]: New object
    */
    mergeObject: function (base, overwrite) {
        var hasBase = this.isObj(base),
            newObject = hasBase ? this.copy(base) : this.copy(overwrite),
            key = '';

        if (hasBase) {
            for (key in overwrite) {
                if (overwrite.hasOwnProperty(key)) {
                    newObject[key] = (this.isObj(overwrite[key]) && !isProtected(key)) ? this.merge(base[key], overwrite[key]) : overwrite[key];
                }
            }
        }
        return newObject;
    },

    /*
        Split a value into a value/unit object

            "200px" -> { value: 200, unit: "px" }

        @param [string]: Value to split
        @return [object]: Object with value and unit props
    */
    splitValUnit: function (value) {
        let splitVal = value.match(/(-?\d*\.?\d*)(.*)/);

        return {
            value: splitVal[1],
            unit:  splitVal[2]
        };
    },

    /*
        Create stepped version of 0-1 progress

        @param [number]: Current value
        @param [int]: Number of steps
        @return [number]: Stepped value
    */
    stepProgress: function (progress, steps) {
        var segment = 1 / (steps - 1),
            target = 1 - (1 / steps),
            progressOfTarget = Math.min(progress / target, 1);

        return Math.floor(progressOfTarget / segment) * segment;
    },

    /*
        Generate current timestamp

        @return [timestamp]: Current UNIX timestamp
    */
    currentTime: function () {
	    return (typeof performance !== "undefined") ? performance.now() : new Date().getTime();
    }

};


text:
title: Parsing WarcraftLogs for fun and profit. Well, not profit.
layout: default
---

## How does my spec scale?

I initially started this project by wondering how well Outlaw rogues scaled relative to Assassination and Subtlety rogues. Community wisdom holds that Outlaw doesn't scale well, but why rely on that when we can go straight to the data? [WarcraftLogs](https://warcraftlogs.com) provides scads of data on the performance of various specs in prolonged raid encounters, long the "gold standard" of performance benchmarking.

The procedure is basically to pull the top 1,000 parses for each spec for each "bucket" of item levels from 840 to 880. Then, for an encounter, for each spec/ilvl bucket combo, we reject the top and bottom 5% of parses, and chart the data with a box plot, then fit it with both a local polynomial regression fitter and a linear regression fitter. This lets us eyeball how well a spec performs as gear levels increase.

We also plot the number of parses per ilvl per spec for the encounter, and provide plots of how well a spec scales over time (effectively, an approximation of the first derivative of the polynomial fit, taken by regressing against the deltas in the dataset), and finally, provide a very blunt linear regression per spec per encounter that attempts to compare how well spec X scales compared to spec Y for that encounter.

You'll find the code to grab and distill the data, as well as the RStudio notebooks used to generate this output at [https://github.com/cheald/warcraftlogs-parses](https://github.com/cheald/warcraftlogs-parses).

## tl;dr

* [Overall scaling, and per encounter](overall.html)

![Overall Scaling](download.png)

This shows the rate of change in DPS per ilvl gained, across the entire data set. This is *not* damage potential, but rather the rate of change of damage improvement as your gear improves.

While I initially started this project to find out if Outlaw scaled significantly worse than the other rogue specs, I found that not only is Outlaw the worst-scaling rogue spec, it's the worst-scaling raid spec overall, and by quite a large amount! Beast Mastery Hunters, Survival Hunters, and Unholy Death Knights suffer lower-than-average scaling, as well. On the other end of the scale, Shadow Priests, Assassination Rogues, and Retribution Paladins appear to have the strongest scaling, which aligns with common beliefs, as well.

## The parses

Below you'll find the parses for individual classes. While some classes (such as paladins and priests) don't have more than one damage spec, they are included for completeness.

* [Death Knight](death_knight.html)
* [Demon Hunter](demon_hunter.html)
* [Druid](druid.html)
* [Hunter](hunter.html)
* [Mage](mage.html)
* [Monk](monk.html)
* [Paladin](paladin.html)
* [Priest](priest.html)
* [Rogue](rogue.html)
* [Shaman](shaman.html)
* [Warlock](warlock.html)
* [Warrior](warrior.html)

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-16557101-2', 'auto');
  ga('send', 'pageview');
</script>