text:
/*
 * 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.
 */
package org.jctools.channels;

import org.jctools.util.JvmInfo;
import org.jctools.util.Pow2;
import org.jctools.util.UnsafeDirectByteBuffer;

import java.nio.ByteBuffer;

import static org.jctools.util.JvmInfo.CACHE_LINE_SIZE;
import static org.jctools.util.UnsafeAccess.UNSAFE;
import static org.jctools.util.UnsafeDirectByteBuffer.*;

/**
 * Channel protocol:
 * - Fixed message size
 * - 'null' indicator in message preceding byte (potentially use same for type mapping in future)
 * - Use FF algorithm relying on indicator to support in place detection of next element existence
 */
public abstract class OffHeapFixedMessageSizeRingBuffer {

    public static final int READY_MESSAGE_INDICATOR = 0;
    public static final int BUSY_MESSAGE_INDICATOR = 1;
    public static final byte MESSAGE_INDICATOR_SIZE = 4;
    public static final int HEADER_SIZE = 4 * JvmInfo.CACHE_LINE_SIZE;

    public static final long EOF = 0;

    private final ByteBuffer buffy;
    protected final long bufferAddress;
    protected final long consumerIndexAddress;
    protected final long producerIndexAddress;
    protected final long mask;
    protected final int messageSize;

    public static int getRequiredBufferSize(final int capacity, final int messageSize) {
        int alignedMessageSize = (int) Pow2.align(messageSize + MESSAGE_INDICATOR_SIZE, MESSAGE_INDICATOR_SIZE);
        return HEADER_SIZE + (Pow2.roundToPowerOfTwo(capacity) * alignedMessageSize);
    }

    public OffHeapFixedMessageSizeRingBuffer(final int capacity, final int messageSize) {
        this(allocateAlignedByteBuffer(getRequiredBufferSize(capacity, messageSize), CACHE_LINE_SIZE), Pow2
                .roundToPowerOfTwo(capacity), true, true, true, messageSize);
    }

    /**
     * This is to be used for an IPC queue with the direct buffer used being a memory mapped file.
     *
     * @param buff
     * @param capacity in messages, actual capacity will be
     * @param messageSize
     */
    protected OffHeapFixedMessageSizeRingBuffer(final ByteBuffer buff, final int capacity,
            final boolean isProducer, final boolean isConsumer, final boolean initialize,
            final int messageSize) {

        int actualCapacity = Pow2.roundToPowerOfTwo(capacity);
        // message size is aligned to indicator size, this ensure atomic writes of indicator
        this.messageSize = (int) Pow2.align(messageSize + MESSAGE_INDICATOR_SIZE, MESSAGE_INDICATOR_SIZE);
        this.buffy = alignedSlice(HEADER_SIZE + (actualCapacity * (this.messageSize)), CACHE_LINE_SIZE, buff);

        long alignedAddress = UnsafeDirectByteBuffer.getAddress(buffy);
        if (alignedAddress % JvmInfo.CACHE_LINE_SIZE != 0) {
            throw new IllegalStateException("buffer is expected to be cache line aligned by now");
        }
        // Layout of the RingBuffer (assuming 64b cache line):
        // consumerIndex(8b), pad(56b) |
        // pad(64b) |
        // producerIndex(8b), producerLookAheadCache(8b), pad(48b) |
        // pad(64b) |
        // buffer (capacity * messageSize)
        this.consumerIndexAddress = alignedAddress;
        this.producerIndexAddress = this.consumerIndexAddress + 2 * JvmInfo.CACHE_LINE_SIZE;
        this.bufferAddress = alignedAddress + HEADER_SIZE;
        this.mask = actualCapacity - 1;
        // producer owns tail and headCache
        if (isProducer && initialize) {
            soProducerIndex(0);
            // mark all messages as READY
            for (int i = 0; i < actualCapacity; i++) {
                final long offset = offsetForIndex(i);
                readyIndicator(offset);
            }
        }
        // consumer owns head
        if (isConsumer && initialize) {
            soConsumerIndex(0);
        }
    }

    public final int size() {
        return (int) (lvProducerIndex() - lvConsumerIndex());
    }

    public final boolean isEmpty() {
        return lvProducerIndex() == lvConsumerIndex();
    }

    protected final boolean isMessageReady(long offset) {
        return UNSAFE.getIntVolatile(null, offset) == READY_MESSAGE_INDICATOR;
    }

    protected final void busyIndicator(long offset) {
        UNSAFE.putOrderedInt(null, offset, BUSY_MESSAGE_INDICATOR);
    }

    protected final void readyIndicator(long offset) {
        UNSAFE.putOrderedInt(null, offset, READY_MESSAGE_INDICATOR);
    }

    protected final long offsetForIndex(long currentHead) {
        return bufferAddress + ((currentHead & mask) * messageSize);
    }

    protected final long lpConsumerIndex() {
        return UNSAFE.getLong(null, consumerIndexAddress);
    }

    protected final long lvConsumerIndex() {
        return UNSAFE.getLongVolatile(null, consumerIndexAddress);
    }

    protected final void soConsumerIndex(final long value) {
        UNSAFE.putOrderedLong(null, consumerIndexAddress, value);
    }

    protected final long lpProducerIndex() {
        return UNSAFE.getLong(null, producerIndexAddress);
    }

    protected final long lvProducerIndex() {
        return UNSAFE.getLongVolatile(null, producerIndexAddress);
    }

    protected final void soProducerIndex(final long value) {
        UNSAFE.putOrderedLong(null, producerIndexAddress, value);
    }

    /**
     * @return a base address for a message acquired to be read, or EOF if none is available
     */
    protected abstract long readAcquire();
    /**
     * @param offset the base address of a message that we are done reading and can be overwritten now
     */
    protected abstract void readRelease(long offset);
    /**
     * @return a base address for a message acquired to be written, or EOF if none is available
     */
    protected abstract long writeAcquire();

    /**
     * @param offset the base address of a message that we are done writing and can be read now
     */
    protected abstract void writeRelease(long offset);

}


text:
require 'spec_helper'

describe Client do
  it "should have some tests" do

  end
end

redpajama_set_name: RedPajamaGithub


text:
import os
import random

import flask
import grpc
import structlog

import shakesapp_pb2
import shakesapp_pb2_grpc

app = flask.Flask(__name__)

queries = {
    "hello": 349,
    "world": 728,
    "to be, or not to be": 1,
    "insolence": 14,
}

# Structured log configuration
def field_name_modifier(_, __, event_dict):
    """Replace log level field name 'level' with 'serverity' to meet
    Cloud Logging's data model.
    Make sure to call this processor after structlog.stdlib.add_log_level.
    https://cloud.google.com/logging/docs/reference/v2/rpc/google.logging.v2?hl=en#google.logging.v2.LogEntry
    """
    event_dict["severity"] = event_dict["level"]
    del event_dict["level"]
    return event_dict

def get_json_logger():
    structlog.configure(
        processors=[
            structlog.stdlib.add_log_level,
            field_name_modifier,
            structlog.processors.TimeStamper("iso"),
            structlog.processors.JSONRenderer(),
        ]
    )
    return structlog.get_logger()

logger = get_json_logger()

class ClientConfigError(Exception):
    pass

class UnexpectedResultError(Exception):
    pass

SERVER_ADDR = os.environ.get("SERVER_ADDR", "")
if SERVER_ADDR == "":
    raise ClientConfigError("environment variable SERVER_ADDR is not set")
logger.info(f"server address is {SERVER_ADDR}")

@app.route("/")
def main_handler():
    q, count = random.choice(list(queries.items()))

    channel = grpc.insecure_channel(SERVER_ADDR)
    stub = shakesapp_pb2_grpc.ShakespeareServiceStub(channel)
    logger.info(f"request to server with query: {q}")
    resp = stub.GetMatchCount(shakesapp_pb2.ShakespeareRequest(query=q))
    if count != resp.match_count:
        raise UnexpectedResultError(
            f"The expected count for '{q}' was {count}, but result was {resp.match_count } obtained"
        )
    result = str(resp.match_count)
    logger.info(f"matched count for '{q}' is {result}")
    return result

@app.route("/_healthz")
def healthz_handler():
    return "ok"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port="8080")


text:
package template

import (
	"fmt"
	"regexp"
	"strings"
)

var delimiter = "\\$"
var substitution = "[_a-z][_a-z0-9]*(?::?-[^}]+)?"

var patternString = fmt.Sprintf(
	"%s(?i:(?P<escaped>%s)|(?P<named>%s)|{(?P<braced>%s)}|(?P<invalid>))",
	delimiter, delimiter, substitution, substitution,
)

var pattern = regexp.MustCompile(patternString)

// InvalidTemplateError is returned when a variable template is not in a valid
// format
type InvalidTemplateError struct {
	Template string
}

func (e InvalidTemplateError) Error() string {
	return fmt.Sprintf("Invalid template: %#v", e.Template)
}

// Mapping is a user-supplied function which maps from variable names to values.
// Returns the value as a string and a bool indicating whether
// the value is present, to distinguish between an empty string
// and the absence of a value.
type Mapping func(string) (string, bool)

// Substitute variables in the string with their values
func Substitute(template string, mapping Mapping) (result string, err *InvalidTemplateError) {
	result = pattern.ReplaceAllStringFunc(template, func(substring string) string {
		matches := pattern.FindStringSubmatch(substring)
		groups := make(map[string]string)
		for i, name := range pattern.SubexpNames() {
			if i != 0 {
				groups[name] = matches[i]
			}
		}

		substitution := groups["named"]
		if substitution == "" {
			substitution = groups["braced"]
		}
		if substitution != "" {
			// Soft default (fall back if unset or empty)
			if strings.Contains(substitution, ":-") {
				name, defaultValue := partition(substitution, ":-")
				value, ok := mapping(name)
				if !ok || value == "" {
					return defaultValue
				}
				return value
			}

			// Hard default (fall back if-and-only-if empty)
			if strings.Contains(substitution, "-") {
				name, defaultValue := partition(substitution, "-")
				value, ok := mapping(name)
				if !ok {
					return defaultValue
				}
				return value
			}

			// No default (fall back to empty string)
			value, ok := mapping(substitution)
			if !ok {
				return ""
			}
			return value
		}

		if escaped := groups["escaped"]; escaped != "" {
			return escaped
		}

		err = &InvalidTemplateError{Template: template}
		return ""
	})

	return result, err
}

// Split the string at the first occurrence of sep, and return the part before the separator,
// and the part after the separator.
//
// If the separator is not found, return the string itself, followed by an empty string.
func partition(s, sep string) (string, string) {
	if strings.Contains(s, sep) {
		parts := strings.SplitN(s, sep, 2)
		return parts[0], parts[1]
	}
	return s, ""
}


text:
import os, time
from os.path import *
import mate_invest.defs

import gi
gi.require_version("Gtk", mate_invest.defs.GTK_API_VERSION)

from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from gi.repository import GObject
from gi.repository import MatePanelApplet

GObject.threads_init()
from gettext import gettext as _

import mate_invest, mate_invest.about, mate_invest.chart, mate_invest.preferences
from mate_invest.quotes import QuoteUpdater
from mate_invest.widgets import *

Gtk.Window.set_default_icon_from_file(join(mate_invest.ART_DATA_DIR, "invest_neutral.svg"))

class InvestApplet(MatePanelApplet.Applet):
	def __init__(self, applet):
		self.applet = applet

		# name, stock_id, label, accellerator, tooltip, callback
		menu_actions = [("About", Gtk.STOCK_ABOUT, _("About"), None, None, self.on_about),
				("Help", Gtk.STOCK_HELP, _("Help"), None, None, self.on_help),
				("Prefs", Gtk.STOCK_PREFERENCES, _("Preferences"), None, None, self.on_preferences),
				("Refresh", Gtk.STOCK_REFRESH, _("Refresh"), None, None, self.on_refresh)
				]
		actiongroup = Gtk.ActionGroup.new("InvestAppletActions")
		actiongroup.set_translation_domain(mate_invest.defs.GETTEXT_PACKAGE)
		actiongroup.add_actions(menu_actions, None)
		self.applet.setup_menu_from_file (join(mate_invest.defs.PKGDATADIR, "Invest_Applet.xml"), actiongroup)

		evbox = Gtk.HBox()
		self.applet_icon = Gtk.Image()
		self.set_applet_icon(0)
		self.applet_icon.show()
		evbox.add(self.applet_icon)
		self.applet.add(evbox)
		self.applet.connect("button-press-event", self.button_clicked)
		self.applet.show_all()
		self.new_ilw()

	def new_ilw(self):
		self.quotes_updater = QuoteUpdater(self.set_applet_icon,
						   self.set_applet_tooltip)
		self.investwidget = InvestWidget(self.quotes_updater)
		self.ilw = InvestmentsListWindow(self.applet, self.investwidget)

	def reload_ilw(self):
		self.ilw.destroy()
		self.new_ilw()

	def button_clicked(self, widget,event):
		if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 1:
			# Three cases...
			if len (mate_invest.STOCKS) == 0:
				# a) We aren't configured yet
				mate_invest.preferences.show_preferences(self, _("You have not entered any stock information yet"))
				self.reload_ilw()
			elif not self.quotes_updater.quotes_valid:
				# b) We can't get the data (e.g. offline)
				alert = Gtk.MessageDialog(buttons=Gtk.ButtonsType.CLOSE)
				alert.set_markup(_("No stock quotes are currently available"))
				alert.format_secondary_text(_("The server could not be contacted. The computer is either offline or the servers are down. Try again later."))
				alert.run()
				alert.destroy()
			else:
				# c) Everything is normal: pop-up the window
				self.ilw.toggle_show()

	def on_about(self, action):
		mate_invest.about.show_about()

	def on_help(self, action):
		mate_invest.help.show_help()

	def on_preferences(self, action):
		mate_invest.preferences.show_preferences(self)
		self.reload_ilw()

	def on_refresh(self, action):
		self.quotes_updater.refresh()

	def set_applet_icon(self, change):
		if change == 1:
			pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(join(mate_invest.ART_DATA_DIR, "invest-22_up.png"), -1,-1)
		elif change == 0:
			pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(join(mate_invest.ART_DATA_DIR, "invest-22_neutral.png"), -1,-1)
		else:
			pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(join(mate_invest.ART_DATA_DIR, "invest-22_down.png"), -1,-1)
		self.applet_icon.set_from_pixbuf(pixbuf)

	def set_applet_tooltip(self, text):
		self.applet_icon.set_tooltip_text(text)

class InvestmentsListWindow(Gtk.Window):
	def __init__(self, applet, list):
		Gtk.Window.__init__(self, type=Gtk.WindowType.TOPLEVEL)
		self.set_type_hint(Gdk.WindowTypeHint.DOCK)
		self.stick()
		self.set_resizable(False)
		self.set_border_width(6)

		self.applet = applet # this is the widget we want to align with
		self.alignment = self.applet.get_orient ()

		self.add(list)
		list.show()

		# boolean variable that identifies if the window is visible
		# show/hide is triggered by left-clicking on the applet
		self.hidden = True

	def toggle_show(self):
		if self.hidden == True:
			self.update_position()
			self.show_all()
			self.hidden = False
		elif self.hidden == False:
			self.hide()
			self.hidden = True

	def update_position (self):
		"""
		Calculates the position and moves the window to it.
		"""
		self.realize()

		# Get our own dimensions & position
		#(wx, wy) = self.get_origin()

		window = self.applet.get_window()
                if GTK_API_VERSION == '3.0':
		    screen = window.get_screen()
                    monitor = screen.get_monitor_geometry (screen.get_monitor_at_window (window))
                    (ret, ax, ay) = window.get_origin()
                    (ignored, ignored, aw, ah) = window.get_geometry()
                else:
                    screen = self.applet.get_screen()
                    monitor = Gdk.Rectangle(0, 0, 0, 0)
                    ax = ay = 0
                    self.applet.window.get_origin(ax, ay)
                    (aw, ah) = self.applet.window.get_size ()
                    screen.get_monitor_geometry (screen.get_monitor_at_window (self.applet.window), monitor)

		(ww, wh) = self.get_size()

		if self.alignment == MatePanelApplet.AppletOrient.LEFT:
			x = ax - ww
			y = ay

			if (y + wh > monitor.y + monitor.height):
				y = monitor.y + monitor.height - wh

			if (y < 0):
				y = 0

			if (y + wh > monitor.height / 2):
				gravity = Gdk.Gravity.SOUTH_WEST
			else:
				gravity = Gdk.Gravity.NORTH_WEST

		elif self.alignment == MatePanelApplet.AppletOrient.RIGHT:
			x = ax + aw
			y = ay

			if (y + wh > monitor.y + monitor.height):
				y = monitor.y + monitor.height - wh

			if (y < 0):
				y = 0

			if (y + wh > monitor.height / 2):
				gravity = Gdk.Gravity.SOUTH_EAST
			else:
				gravity = Gdk.Gravity.NORTH_EAST

		elif self.alignment == MatePanelApplet.AppletOrient.DOWN:
			x = ax
			y = ay + ah

			if (x + ww > monitor.x + monitor.width):
				x = monitor.x + monitor.width - ww

			if (x < 0):
				x = 0

			gravity = Gdk.Gravity.NORTH_WEST
		elif self.alignment == MatePanelApplet.AppletOrient.UP:
			x = ax
			y = ay - wh

			if (x + ww > monitor.x + monitor.width):
				x = monitor.x + monitor.width - ww

			if (x < 0):
				x = 0

			gravity = Gdk.Gravity.SOUTH_WEST

		self.move(x, y)
		self.set_gravity(gravity)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Magazin Ges. naturf. Freunde, Berlin 7: (1815)

#### Original name
Pittocarpium flavum Link

### Remarks
null


text:
require "spec_helper"

class SmallBatchJob
  extend Resque::Plugins::ScalingCanary
  @queue = 'small-batch-job'

  def self.perform; end
end

class LargeBatchJob
  extend Resque::Plugins::ScalingCanary
  @queue = 'large-batch-job'

  def self.minimum_workers_needed
    20
  end

  def self.perform; end
end

describe Resque::Plugins::ScalingCanary do
  before(:each) do
    @mock_heroku_client = Object.new
    Resque::Plugins::ScalingCanary.config do |config|
      config.heroku_user = "stub-user"
      config.heroku_password = "stub-password"
      config.heroku_app = "stub-app"
      config.polling_interval = 0
      config.stub(:heroku_client) { @mock_heroku_client }
    end
  end

  it "should pass Resque's plugin lint test" do
    lambda { Resque::Plugin.lint(Resque::Plugins::ScalingCanary) }.should_not raise_error
  end

  describe "after_enqueue_ensure_heroku_workers" do
    it "should scale workers up to 1 if no :minimum_workers_needed method is implemented" do
      @mock_heroku_client.should_receive(:ps_scale).with("stub-app", :type => "worker", :qty => 1).once
      @mock_heroku_client.should_receive(:ps_scale).with("stub-app", :type => "worker", :qty => 0).once
      @mock_heroku_client.stub(:info) { {:workers => 0} }
      Resque.enqueue SmallBatchJob
    end
    it "should scale workers up to the number specified by :minimum_workers_needed if an implementation is provided" do
      @mock_heroku_client.should_receive(:ps_scale).with("stub-app", :type => "worker", :qty => 20).once
      @mock_heroku_client.should_receive(:ps_scale).with("stub-app", :type => "worker", :qty => 0).once
      @mock_heroku_client.stub(:info) { {:workers => 0} }
      Resque.enqueue LargeBatchJob
    end
    it "should not scale workers at all if scaling is disabled" do
      Resque::Plugins::ScalingCanary::Config.disable_scaling_if{ true }
      @mock_heroku_client.stub(:ps_scale){ raise "Not expecting call to :ps_scale because scaling is disabled" }
      @mock_heroku_client.stub(:info) { {:workers => 0} }
      Resque.enqueue LargeBatchJob
    end
  end

end


text:
<?php

namespace CAIF\ManageBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

/**
 * @Route("/manage")
 */
class ManageController extends BaseController
{
    /**
     * @Route("/", name="caif_manage_index")
     */
    public function indexAction()
    {
        $em         = $this->getDoctrine()->getManager();
        $repository = $em->getRepository('CAIFSharedBundle:Student');
        $students   = $repository->findBy(['active' => true], ['lastName' => 'ASC']);

        $repository = $em->getRepository('CAIFSharedBundle:Host');
        $hosts      = $repository->findBy([
            'hosting' => true,
            'active'  => true,
        ], [
            'name' => 'ASC'
        ]);

        $members = $repository->findBy([
            'hosting' => false,
            'active'  => true,
        ], [
            'name' => 'ASC'
        ]);

        $repository = $em->getRepository('CAIFSharedBundle:Person');
        $archived   = $repository->findBy(['active' => false]);

        return $this->render('CAIFManageBundle:Manage:index.html.twig', [
            'students'    => $students,
            'hosts'       => $this->sortHostByLastName($hosts),
            'members'     => $this->sortHostByLastName($members),
            'archived'    => $archived,
        ]);
    }

    /**
     * @Route("/host-printable", name="caif_manage_host_printable")
     */
    public function hostPrintable()
    {
        $em         = $this->getDoctrine()->getManager();
        $repository = $em->getRepository('CAIFSharedBundle:Host');
        $hosts      = $repository->findBy([
            'hosting' => true,
            'active'  => true,
        ], [
            'name' => 'ASC'
        ]);

        return $this->render('CAIFManageBundle:Manage:hostPrintable.html.twig', [
            'hosts' => $this->sortHostByLastName($hosts),
        ]);
    }

    /**
     * @Route("/download/{type}", name="caif_manage_download")
     */
    public function downloadAction($type)
    {
        $em = $this->getDoctrine()->getManager();

        $filename = $type.'_'.date('m-d-Y');

        switch ($type) {
            case 'students':
                $repository = $em->getRepository('CAIFSharedBundle:Student');
                $people     = $repository->findBy([
                    'active' => true,
                ]);
                break;

            case 'hosts':
                $repository = $em->getRepository('CAIFSharedBundle:Host');
                $people     = $repository->findBy([
                    'active'  => true,
                    'hosting' => true,
                ]);

                $people = $this->sortHostByLastName($people);
                break;

            case 'community-members':
                $repository = $em->getRepository('CAIFSharedBundle:Host');
                $people     = $repository->findBy([
                    'active'  => true,
                    'hosting' => false,
                ]);

                $people = $this->sortHostByLastName($people);

                /* change type to host for twig template */
                $type = 'hosts';
                break;
        }

        $response = $this->render('CAIFManageBundle:Manage:'.$type.'Export.html.twig', [
            'people' => $people,
        ]);

        $response->headers->set('Content-Type', 'text/csv');
        $response->headers->set('Content-Disposition', 'attachment; filename="'.$filename.'.csv"');

        return $response;
    }

    /**
     * @Route("/search-person/{query}")
     */
    public function searchPersonAction($query)
    {
        $em          = $this->getDoctrine()->getManager();
        $hostResults = $em->getRepository('CAIFSharedBundle:Host')->createQueryBuilder('h')
            ->where('h.name LIKE :query')
            ->setParameter('query', '%'.$query.'%')
            ->getQuery()
            ->getResult();

        $people = [];
        foreach ($hostResults as $result) {
            $people[] = [
                'name' => $result->getName().' - '.$result->getEntityType(),
                'id'   => $result->getId(),
                'type' => $result->getEntityType(),
            ];
        }

        $studentResults = $em->getRepository('CAIFSharedBundle:Student')->createQueryBuilder('s')
            ->where('s.firstName LIKE :query OR s.lastName LIKE :query')
            ->setParameter('query', '%'.$query.'%')
            ->getQuery()
            ->getResult();

        foreach ($studentResults as $result) {
            $people[] = [
                'name' => $result->getFirstName().' '.$result->getLastName().' - '.$result->getEntityType(),
                'id'   => $result->getId(),
                'type' => $result->getEntityType(),
            ];
        }

        return new JsonResponse($people);
    }
}


text:
import {
  instrument,
  subscribe,
  unsubscribe,
  reset
} from "ember-metal/instrumentation";

module("Ember Instrumentation", {
  setup: function() {

  },
  teardown: function() {
    reset();
  }
});

test("subscribing to a simple path receives the listener", function() {
  expect(12);

  var sentPayload = {}, count = 0;

  subscribe("render", {
    before: function(name, timestamp, payload) {
      if (count === 0) {
        strictEqual(name, "render");
      } else {
        strictEqual(name, "render.handlebars");
      }

      ok(typeof timestamp === 'number');
      strictEqual(payload, sentPayload);
    },

    after: function(name, timestamp, payload) {
      if (count === 0) {
        strictEqual(name, "render");
      } else {
        strictEqual(name, "render.handlebars");
      }

      ok(typeof timestamp === 'number');
      strictEqual(payload, sentPayload);

      count++;
    }
  });

  instrument("render", sentPayload, function() {

  });

  instrument("render.handlebars", sentPayload, function() {

  });
});

test("returning a value from the before callback passes it to the after callback", function() {
  expect(2);

  var passthru1 = {}, passthru2 = {};

  subscribe("render", {
    before: function(name, timestamp, payload) {
      return passthru1;
    },
    after: function(name, timestamp, payload, beforeValue) {
      strictEqual(beforeValue, passthru1);
    }
  });

  subscribe("render", {
    before: function(name, timestamp, payload) {
      return passthru2;
    },
    after: function(name, timestamp, payload, beforeValue) {
      strictEqual(beforeValue, passthru2);
    }
  });

  instrument("render", null, function() {});
});

test("raising an exception in the instrumentation attaches it to the payload", function() {
  expect(2);

  var error = new Error("Instrumentation");

  subscribe("render", {
    before: function() {},
    after: function(name, timestamp, payload) {
      strictEqual(payload.exception, error);
    }
  });

  subscribe("render", {
    before: function() {},
    after: function(name, timestamp, payload) {
      strictEqual(payload.exception, error);
    }
  });

  instrument("render.handlebars", null, function() {
    throw error;
  });
});

test("it is possible to add a new subscriber after the first instrument", function() {
  instrument("render.handlebars", null, function() {});

  subscribe("render", {
    before: function() {
      ok(true, "Before callback was called");
    },
    after: function() {
      ok(true, "After callback was called");
    }
  });

  instrument("render.handlebars", null, function() {});
});

test("it is possible to remove a subscriber", function() {
  expect(4);

  var count = 0;

  var subscriber = subscribe("render", {
    before: function() {
      equal(count, 0);
      ok(true, "Before callback was called");
    },
    after: function() {
      equal(count, 0);
      ok(true, "After callback was called");
      count++;
    }
  });

  instrument("render.handlebars", null, function() {});

  unsubscribe(subscriber);

  instrument("render.handlebars", null, function() {});
});


text: An attempt to wow the first years in the CompSoc orientation.


text:
#include "El.hpp"
using namespace El;

int
main( int argc, char* argv[] )
{
    Initialize( argc, argv );
    mpi::Comm comm = mpi::COMM_WORLD;
    const Int commSize = mpi::Size( comm );
    const Int commRank = mpi::Rank( comm );

    try
    {
        Int r = Input("--gridHeight","height of process grid",0);
        const bool colMajor = Input("--colMajor","column-major ordering?",true);
        const Int m = Input("--height","height of matrix",100);
        const Int n = Input("--width","width of matrix",100);
        const Int mb = Input("--blockHeight","height of dist block",32);
        const Int nb = Input("--blockWidth","width of dist block",32);
        const bool print = Input("--print","print wrong matrices?",false);
#ifdef EL_HAVE_SCALAPACK
        const bool fullTriangle = Input("--fullTriangle","full Schur?",true);
#endif
        ProcessInput();
        PrintInputReport();

        if( r == 0 )
            r = Grid::FindFactor( commSize );
        const GridOrder order = ( colMajor ? COLUMN_MAJOR : ROW_MAJOR );
        const Grid g( comm, r, order );

        BlockDistMatrix<Complex<double>> A(m,n,g,mb,nb);
        Fill( A, Complex<double>(1) );
        Scale( double(commRank), A.Matrix() );
        if( print )
            Print( A, "A" );
        DistMatrix<Complex<double>> AElem( A );
        Scale( 2., AElem );
        if( print )
            Print( AElem, "A := 2 A" );
        A = AElem;
        if( print )
            Print( A, "A" );
#ifdef EL_HAVE_SCALAPACK
        if( m == n )
        {
            // NOTE: There appears to be a bug in the parallel eigenvalue
            //       reordering in P{S,D}HSEQR (within P{S,D}TRORD).
            //       This driver was therefore switched to complex arithmetic.
            DistMatrix<Complex<double>,VR,STAR> w( m, 1, g );
            BlockDistMatrix<Complex<double>> Q(m,m,g,mb,nb);
            Schur( A, w, Q, fullTriangle );
            if( print )
            {
                Print( A, "Schur(A)" );
                Print( w, "w(A)" );
                Print( Q, "Q" );
            }
        }
#endif
    }
    catch( std::exception& e ) { ReportException(e); }

    Finalize();
    return 0;
}


text:
package com.lightbend.lagom.internal.javadsl.server

import java.io.File
import java.lang.reflect.Type
import java.util

import com.google.inject.Binding
import com.google.inject.Module
import com.google.inject.spi._
import com.lightbend.lagom.internal.javadsl.api._
import com.lightbend.lagom.internal.spi.ServiceAcl
import com.lightbend.lagom.internal.spi.ServiceDescription
import com.lightbend.lagom.internal.spi.ServiceDiscovery
import com.lightbend.lagom.javadsl.api.Descriptor
import com.lightbend.lagom.javadsl.api.Service
import com.lightbend.lagom.javadsl.api.deser._
import com.lightbend.lagom.javadsl.api.transport.MessageProtocol
import org.apache.commons.lang3.ClassUtils
import play.api.inject.guice.BinderOption
import play.api.inject.guice.GuiceableModule
import play.api.Configuration
import play.api.Environment
import play.api.Logger
import play.api.Mode

import scala.collection.mutable
import scala.collection.JavaConverters._
import scala.compat.java8.OptionConverters._

class JavadslServiceDiscovery extends ServiceDiscovery {
  private val log = Logger(this.getClass)

  /**
   * These stub factories are necessary in order to resolve a service descriptor.
   */
  private final val serializerFactories: Map[PlaceholderSerializerFactory, SerializerFactory] =
    Map(JacksonPlaceholderSerializerFactory -> new SerializerFactoryStub)
  private final val exceptionSerializers: Map[PlaceholderExceptionSerializer, ExceptionSerializer] =
    Map(JacksonPlaceholderExceptionSerializer -> new ExceptionSerializerStub)

  override def discoverServices(classLoader: ClassLoader): util.List[ServiceDescription] = {
    val descriptions = doDiscovery(classLoader)
    if (descriptions.size > 1) {
      log.warn(
        s"Found ServiceDescriptions: ${descriptions.map(_.name()).mkString("[", ",", "]")}. Support for multiple locatable services will be removed."
      )
    }
    descriptions.asJava
  }

  private def doDiscovery(classLoader: ClassLoader): scala.collection.Seq[ServiceDescription] = {
    val modules = loadModules(classLoader)
    resolveServiceInterfaces(modules).flatMap { serviceInterface =>
      val unresolvedDescriptor = ServiceReader.readServiceDescriptor(classLoader, serviceInterface)
      val resolvedDescriptor = ServiceReader.resolveServiceDescriptor(
        unresolvedDescriptor,
        classLoader,
        serializerFactories,
        exceptionSerializers
      )
      if (resolvedDescriptor.locatableService)
        Some(createServiceDescription(resolvedDescriptor))
      else
        None
    }
  }

  private def createServiceDescription(descriptor: Descriptor): ServiceDescription = {
    val convertedAcls = descriptor
      .acls()
      .asScala
      .map { acl =>
        new ServiceAcl {
          override def method()      = acl.method.asScala.map(_.name).asJava
          override def pathPattern() = acl.pathRegex()
        }.asInstanceOf[ServiceAcl]
      }
      .asJava

    new ServiceDescription {
      override def acls() = convertedAcls
      override def name() = descriptor.name
    }
  }

  /**
   * Load Guice modules for a given class loader
   */
  private def loadModules(classLoader: ClassLoader): Seq[Module] = {
    val env           = Environment(new File("."), classLoader, Mode.Test)
    val conf          = Configuration.load(env)
    val modules       = GuiceableModule.loadModules(env, conf)
    val binderOptions = BinderOption.defaults
    GuiceableModule.guiced(env, conf, binderOptions)(modules)
  }

  /**
   * Scans the given Guice modules to find and return the service interfaces.
   */
  private def resolveServiceInterfaces(modules: Seq[Module]): scala.collection.Seq[Class[_ <: Service]] = {
    val serviceInterfaces = mutable.ListBuffer.empty[Class[_ <: Service]]

    // Iterates through all bindings of a module to find and add the service interfaces to the `serviceInterfaces` buffer
    def addServiceInterfaces(element: Element): Unit =
      // Starting point is to create a `DefaultElementVisitor` to iterate through all the binding of a module
      element.acceptVisitor(new DefaultElementVisitor[Element] {
        override def visit[T](binding: Binding[T]): Element = {
          // Now we are only interested in the `UntargettedBinding`s to
          // filter out the binding of [[com.lightbend.lagom.javadsl.api.Service]] itself
          binding.acceptTargetVisitor(new DefaultBindingTargetVisitor[Any, Any] {
            override def visit(untargettedBinding: UntargettedBinding[_]): AnyRef = {
              // For each untargetted binding we check if the interface extends from [[com.lightbend.lagom.javadsl.api.Service]]
              // If so we add this interface to the `serviceInterfaces` buffer
              val serviceInterfaceOpt = serviceInterfaceResolver(untargettedBinding.getKey.getTypeLiteral.getRawType)
              serviceInterfaces ++= serviceInterfaceOpt
              untargettedBinding
            }
          })
          binding
        }
      })

    // Iterate through the Guice modules and find bindings which interface has `Service` as a superclass.
    // Add these service interfaces to the `serviceInterfaces` buffer and return the buffer
    Elements.getElements(modules.asJava).asScala.foreach(addServiceInterfaces)
    serviceInterfaces
  }

  private final val ExpectedDescriptorParamCount = 0
  private final val ExpectedDescriptorReturnType = classOf[Descriptor]

  // Checks if the given class has an interface that extends from [[com.lightbend.lagom.javadsl.api.Service]]
  private[lagom] def serviceInterfaceResolver(clazz: Class[_]): Option[Class[_ <: Service]] = {
    // Checks if a the given service interface has implemented the method `descriptor()`
    def verify(serviceInterface: Class[_]): Either[String, Class[_ <: Service]] =
      try {
        val method = serviceInterface.getDeclaredMethod(ServiceReader.DescriptorMethodName)
        if (method.getParameterCount == ExpectedDescriptorParamCount && method.getReturnType == ExpectedDescriptorReturnType)
          Right(serviceInterface.asSubclass(classOf[Service]))
        else
          Left(
            s"Service interface $serviceInterface does contain expected method ${ServiceReader.DescriptorMethodName} with an invalid return type or parameter count. " +
              s"Expected return type: $ExpectedDescriptorReturnType, actual: ${method.getReturnType}, Expected parameter count: $ExpectedDescriptorParamCount, actual: ${method.getParameterCount}"
          )
      } catch {
        case _: NoSuchMethodException =>
          Left(
            s"Service interface $serviceInterface does not contain expected method ${ServiceReader.DescriptorMethodName}()."
          )
      }

    // Get interfaces of service implementation, e.g. HelloServiceImpl > HelloService
    val interfaces = ClassUtils.getAllInterfaces(clazz)

    // Collect the first interface, starting from the lowest interface in the inheritance hierarchy, that
    // is assignable from [[com.lightbend.lagom.javadsl.api.Service]] and that overrides the `descriptor` method.
    val errorsOrServiceInterfaces = interfaces.asScala.collect {
      case serviceInterface if classOf[Service].isAssignableFrom(serviceInterface) => verify(serviceInterface)
    }

    val serviceInterfaceOpt = errorsOrServiceInterfaces.find(_.isRight).map(_.right.get)

    // Log errors if no service interface has implemented the `descriptor()` method
    // This can happen if the method name or signature has been changed.
    if (serviceInterfaceOpt.isEmpty)
      errorsOrServiceInterfaces.filter(_.isLeft).foreach(error => log.error(error.left.get))

    serviceInterfaceOpt
  }

  /**
   * This serializer factory stub is necessary in order to resolve a service descriptor.
   * The implementation of this stub is not relevant here because the api tools library is not interested
   * in the request or response body.
   */
  private class SerializerFactoryStub extends SerializerFactory {
    private def stub = throw new NotImplementedError("SerializerFactory is not provided in the api tools library.")
    override def messageSerializerFor[MessageEntity](`type`: Type): MessageSerializer[MessageEntity, _] =
      new StrictMessageSerializer[MessageEntity] {
        override def deserializer(messageHeader: MessageProtocol)                              = stub
        override def serializerForResponse(acceptedMessageHeaders: util.List[MessageProtocol]) = stub
        override def serializerForRequest()                                                    = stub
      }
  }

  /**
   * This exception serializer factory stub is necessary in order to resolve a service descriptor.
   * The implementation of this stub is not relevant here because the api tools library is not interested
   * in the request or response body.
   */
  private class ExceptionSerializerStub extends ExceptionSerializer {
    private def stub                                                                                = throw new NotImplementedError("ExceptionSerializer is not provided in the api tools library.")
    override def serialize(exception: Throwable, accept: util.Collection[MessageProtocol]): RawExceptionMessage = stub
    override def deserialize(message: RawExceptionMessage): Throwable                                           = stub
  }
}


text:
#ifdef HAVE_XLOCALE_H
#include <xlocale.h>
#endif
#include <locale.h>

#ifdef __APPLE__
# include <string.h>
# include <xlocale.h>
#endif

#if defined(_WIN32) || defined(WIN32) || defined(_WIN64) || defined(WIN64) || defined(WINDOWS)
typedef _locale_t xls_locale_t;
#else
typedef locale_t xls_locale_t;
#endif

xls_locale_t xls_createlocale(void);
void xls_freelocale(xls_locale_t locale);
size_t xls_wcstombs_l(char *s, const wchar_t *pwcs, size_t n, xls_locale_t loc);


text:
<?php

namespace SilexCMS\Tests\Response;

use Symfony\Component\HttpFoundation\Request;

use SilexCMS\Application;
use SilexCMS\Response\TransientResponse;

use SilexCMS\Tests\Base;

class TemplateLoaderTest extends Base
{
    public function testLoad()
    {
        $app = $this->createApplication();

        $this->assertEquals('foo.html.twig', $app['silexcms.template.loader']->load('foo.html.twig'));
        $this->assertTrue(false !== strpos($app['silexcms.template.loader']->load('hello'), 'SilexCMS/Response/../Resources/views/hello'));
    }
}


text:
require 'rails_helper'

describe Api::V1::ParticipantsController do
  login_admin

  let(:participant) { FactoryGirl.create(:participant) }

  describe '#show' do
    it 'returns a successful 200 response' do
      get :show, id: participant
      expect(response.status).to eq(200)
    end

    it 'returns data of a single participant' do
      get :show, id: participant
      expect(response.body).to be_jsonapi_response_for('participants')
      parsed_response = JSON.parse(response.body)
      expect(parsed_response['data']['id'].to_i).to eq(participant.id)
    end

    it 'returns an error if the participant does not exist' do
      get :show, id: 0
      parsed_response = JSON.parse(response.body)
      expect(parsed_response['errors']).to include(/not found/)
      expect(response.status).to eq(404)
    end
  end

  describe '#create' do
    it 'returns a successful json response' do
      post :create, data: {type: 'participants', attributes: {first_name: 'Johnny', last_name: 'Appleseed', gender: 'male'}}
      expect(response.body).to be_jsonapi_response_for('participants')
      parsed_response = JSON.parse(response.body)
      expect(parsed_response['data']['id']).not_to be_nil
      expect(response.status).to eq(201)
    end

    it 'creates a participant record' do
      expect(Participant.all.count).to eq(0)
      post :create, data: {type: 'participants', attributes: {first_name: 'Johnny', last_name: 'Appleseed', gender: 'male'}}
      expect(Participant.all.count).to eq(1)
    end
  end

  describe '#update' do
    let(:attributes) { {last_name: 'Updated Last Name'} }

    it 'returns a successful json response' do
      put :update, id: participant, data: {type: 'participants', attributes: attributes}
      expect(response.body).to be_jsonapi_response_for('participants')
      expect(response.status).to eq(200)
    end

    it 'updates the specified fields' do
      put :update, id: participant, data: {type: 'participants', attributes: attributes}
      participant.reload
      expect(participant.last_name).to eq(attributes[:last_name])
    end

    it 'returns an error if the participant does not exist' do
      put :update, id: 0, data: {type: 'participants', attributes: attributes}
      parsed_response = JSON.parse(response.body)
      expect(parsed_response['errors']).to include(/not found/)
      expect(response.status).to eq(404)
    end
  end

  describe '#destroy' do
    it 'returns a successful json response' do
      delete :destroy, id: participant
      expect(response).to be_success
    end

    it 'destroys the participant record' do
      test_participant = participant
      expect(Participant.all.count).to eq(1)
      delete :destroy, id: test_participant
      expect(Participant.all.count).to eq(0)
    end

    it 'returns an error if the participant does not exist' do
      delete :destroy, id: 0
      parsed_response = JSON.parse(response.body)
      expect(parsed_response['errors']).to include(/not found/)
      expect(response.status).to eq(404)
    end
  end
end


text:
import { by, ElementFinder } from 'protractor';
import { LogItemGroup } from '../page-objects/log-item-group.pageobject';

export class SignalObstructionGroup extends LogItemGroup {

    readonly possibleProblemSourceInput: ElementFinder = this.currentItemContainer
                    .element(by.css('text-input[controlName="possibleProblemSource"] input'));
    readonly notesInput: ElementFinder = this.currentItemContainer
                    .element(by.css('textarea-input[controlName="notes"] textarea'));

    public constructor() {
        super('Signal Obstruction');
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.FileProviders;

namespace RazorLight.Templating.FileSystem
{
	public class FilesystemTemplateManager : ITemplateManager, IDisposable
	{
		private readonly PhysicalFileProvider fileProvider;

		public FilesystemTemplateManager(string root)
		{
			if (string.IsNullOrEmpty(root))
			{
				throw new ArgumentNullException(nameof(root));
			}

			this.Root = root;
			this.fileProvider = new PhysicalFileProvider(root);
		}

		public string Root { get; }

		public ITemplateSource Resolve(string key)
		{
			IFileInfo fileInfo = GetFileInfo(key);

			FileTemplateSource source = new FileTemplateSource(fileInfo, key);

			return source;
		}

		private IFileInfo GetFileInfo(string key)
		{
			if (string.IsNullOrEmpty(key))
			{
				throw new ArgumentNullException(nameof(key));
			}

			List<string> patterns = new List<string> {
				key,
				$"Shared/{key}"
			};
			if (key.StartsWith("/Views/")) patterns.Add(key.Substring("/Views/".Length));
			var fileInfos = patterns.Select(p => fileProvider.GetFileInfo(p));
			IFileInfo fileInfo = (from p in fileInfos
								  where p.Exists
								  select p).FirstOrDefault() ?? fileInfos.FirstOrDefault();
			if (!fileInfo.Exists || fileInfo.IsDirectory)
			{
				throw new FileNotFoundException("Can't find a file with a specified key", key);
			}

			return fileInfo;
		}

		public void Dispose()
		{
			if (fileProvider != null)
			{
				fileProvider.Dispose();
			}
		}
	}
}


text:
package com.amazonaws.services.cloudfront.model.transform;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.cloudfront.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * PublicKey StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PublicKeyStaxUnmarshaller implements Unmarshaller<PublicKey, StaxUnmarshallerContext> {

    public PublicKey unmarshall(StaxUnmarshallerContext context) throws Exception {
        PublicKey publicKey = new PublicKey();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return publicKey;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("Id", targetDepth)) {
                    publicKey.setId(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("CreatedTime", targetDepth)) {
                    publicKey.setCreatedTime(DateStaxUnmarshallerFactory.getInstance("iso8601").unmarshall(context));
                    continue;
                }

                if (context.testExpression("PublicKeyConfig", targetDepth)) {
                    publicKey.setPublicKeyConfig(PublicKeyConfigStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return publicKey;
                }
            }
        }
    }

    private static PublicKeyStaxUnmarshaller instance;

    public static PublicKeyStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new PublicKeyStaxUnmarshaller();
        return instance;
    }
}


text:
/*globals CONFIG */

(function() {
	'use strict';

	/************************************************************************************************
	 * BULLET CLASS
	 *
	 * Just one single enemy bullet
	 *
	 *
	 ************************************************************************************************/

	function Bullet(state, type) {

		this.state = state;
		this.game = state.game;

		// Call parent constructor
		window['firsttry'].Spriter.call(this, state, 'mob_bullet_' + (type + 1));

		this.type = 0;

		this.energy = 30;
		this.speed = 120;
		this.shooter = undefined;

		// this.checkWorldBounds = true;
		// this.outOfBoundsKill = true;
	}

	Bullet.prototype = Object.create(window['firsttry'].Spriter.prototype);
	Bullet.prototype.constructor = Bullet;

	Bullet.prototype.revive = function (shooter, angle) {

		this.shooter = shooter;

		this.reset(shooter.x, shooter.y);
		this.body.velocity.x = (this.speed * Math.sin(angle)) * CONFIG.PIXEL_RATIO;
		this.body.velocity.y = (this.speed * Math.cos(angle)) * CONFIG.PIXEL_RATIO;
	};

	Bullet.prototype.update = function () {

		if (this.alive) {

			// Call parent update function
			window['firsttry'].Spriter.prototype.update.call(this);

			// Kill bullet if out of the screen
			var safeRange = 20;

			if (this.x < - safeRange * CONFIG.PIXEL_RATIO ||
				this.x > (CONFIG.WORLD_WIDTH * 24 + safeRange) * CONFIG.PIXEL_RATIO ||
				this.y < - safeRange * CONFIG.PIXEL_RATIO ||
				this.y > (CONFIG.GAME_HEIGHT + safeRange) * CONFIG.PIXEL_RATIO) {
				this.kill();
			}
		}
	};

	// Export the object
	window['firsttry'] = window['firsttry'] || {};
	window['firsttry'].Bullet = Bullet;
}());


text:
#ifdef PERF_ANALYSIS_INFRASTRUCTURE

#ifndef ART_OPT_INFRASTRUCTURE_INSTRUMENTATION_H_
#define ART_OPT_INFRASTRUCTURE_INSTRUMENTATION_H_

#include "nodes.h"
#include "optimization.h"
#include "perf_analysis_metrics.h"

namespace art {

/**
 * @brief Structure holding the instrumentation of the Perf. Analysis Infrastructure.
 * It holds the metrics to be used, and provides methods to start and stop analyses and collections,
 * as well as dumping the results of the metrics once the instrumentation is done.
 */
class PerfAnalysisInfrastructure : public ArenaObject<kArenaAllocMisc> {
  public:
    PerfAnalysisInfrastructure(ArenaAllocator* arena = nullptr,
                               const PassManagerOptions* pass_options = nullptr) :
    arena_(arena),
    timing_(),
    tsclock_(),
    malloc_stats_(),
    arena_bytes_allocated_(),
    arena_num_allocations_(),
    pass_stats_() {
      if (pass_options != nullptr) {
        SetOptions(pass_options);
      }
    }

    ~PerfAnalysisInfrastructure() {
      if (arena_ != nullptr) {
        arena_->SetInstrumentOff();
      }
    }

    /**
     * @brief Sets the list of metrics according to the options provided by the command line.
     * @details Calling this method on an instance is required before starting an Analysis or
     * a Collection, otherwise no metric will be set.
     * @param options The options data structure holding the list of user requested metrics.
     */
    void SetOptions(const PassManagerOptions* options);

    /**
     * @brief Some metrics require an arena allocator pointer in order to work.
     * This method should be called before SetOptions in case we want to enable
     * arena related metrics (memory-consumption).
     * @param arena The arena that will be analyzed by the Perf. Analysis Infrastructure.
     */
    void SetArena(ArenaAllocator* arena) {
      arena_ = arena;
      arena_->SetInstrumentOn();
      arena_bytes_allocated_.SetArena(arena);
      arena_num_allocations_.SetArena(arena);
    }

    bool ShouldInstrument() const {
      return metrics_.size() > 0u;
    }

    /**
     * @brief Starts an analysis. An analysis will be represented as an output file, holding
     * one or several metric collections. It should be stopped with StopAnalysis.
     * @param analysis_name The name of the analysis. This name will be used to identify
     * the analysis for later use.
     * @sa StopAnalysis.
     */
    void StartAnalysis(const std::string& analysis_name);

    /**
     * @brief Starts a metric collection. A collection represents an instrumentation of one or
     * several metrics. It should be stopped with StopCollection.
     * @details A collection must be part of an analysis, therefore at least one call to
     * StartAnalysis should be done before calling this method.
     * @param analysis_name The identifier of the analysis corresponding to this collection.
     * @param collection_name The name of this metric collection. It must be unique throughout
     * the analysis.
     * @param data The optional data we want to pass to the collection. By default, it is nullptr.
     */
    void StartCollection(const std::string& analysis_name,
                         const std::string& collection_name,
                         void* data = nullptr);

    /**
     * @brief Stops a metric collection. It must be preceded by a StartAnalysis and a
     * StartCollection calls.
     * @param analysis_name The identifier of the analysis corresponding to this collection.
     * @param collection_name The name of the metric collection that was started. It must be
     * unique throughout the analysis.
     * @param data The optional data we want to pass to the collection. By default, it is nullptr.
     */
    void StopCollection(const std::string& analysis_name,
                         const std::string& collection_name,
                         void* data = nullptr);

    /**
     * @brief Stops an analysis. This call must be preceded by a StartAnalysis with the
     * corresponding @p analysis_name. This call will dump a file with the collected data.
     * @details The file will not be dumped if there has been no collections, or no metrics
     * selected.
     * @param analysis_name The name of the analysis that needs to be stopped.
     * @param hash_name Whether the output file name needs to be hashed. This is handy when the
     * analysis name does not respect standards file-system restrictions, such as special
     * characters, or filename length.
     */
    void StopAnalysis(const std::string& analysis_name, bool hash_name);

    /**
     * @brief Facility to perform an Analysis. It is scope-based, which means that the analysis
     * starts when the instance is created, and it is stopped (and possibly dumped, see
     * StopAnalysis) as soon as the scope of the instance ends.
     */
    class ScopedAnalysis {
      public:
        /**
         * @brief Initiates an analysis.
         * @param name The name of the analysis.
         * @param hash_name Whether we want to hash the output file name (see StopAnalysis)
         * @param perf_analysis An instance to the parent PerfAnalysisInfrastructure class
         * needs to be attached to the instance. If it is nullptr, the ScopedAnalysis won't
         * perform an analysis.
         */
        ScopedAnalysis(const char* name, bool hash_name, PerfAnalysisInfrastructure* perf_analysis)
        : name_(name), hash_name_(hash_name), perf_analysis_(perf_analysis) {
          if (perf_analysis_ != nullptr) {
            perf_analysis_->StartAnalysis(name_);
          }
        }

        /**
         * @brief Ends the analysis. If the PerfAnalysisInfrastructure instance provided during the
         * construction of the instance is nullptr, it won't do anything.
         */
        ~ScopedAnalysis() {
          if (perf_analysis_ != nullptr) {
            perf_analysis_->StopAnalysis(name_, hash_name_);
          }
        }

      private:
        const char* name_;
        bool hash_name_;
        PerfAnalysisInfrastructure* perf_analysis_;
    };

    /**
     * @brief Facility to perform a metric collection. It is scope-based, which means the
     * collection starts when the instance is created, and it is stopped as soon as the scope
     * of the instance ends.
     */
    class ScopedCollection {
      public:
        /**
         * @brief Initiates a metric collection.
         * @param analysis_name This instance requires an already-started analysis name. This
         * represents the analysis identifier of the corresponding analysis.
         * @param collection_name This is the name of the collection performed by this instance.
         * @param perf_analysis An instance to the parent PerfAnalysisInfrastructure class
         * needs to be attached to the instance. If it is nullptr, the ScopedCollection won't
         * perform a metric collection.
         * @param data The optional data we can pass to the metrics. By default, it is nullptr.
         */
        ScopedCollection(const char* analysis_name, const char* collection_name,
               PerfAnalysisInfrastructure* perf_analysis, void* data = nullptr) :
        analysis_name_(analysis_name),
        collection_name_(collection_name),
        optional_data_(data),
        perf_analysis_(perf_analysis) {
          if (perf_analysis_ != nullptr) {
            perf_analysis_->StartCollection(analysis_name_,
                                            collection_name_,
                                            optional_data_);
          }
        }

        /**
         * @brief Ends the metric collection. If the PerfAnalysisInfrastructure
         * instance provided during the construction of the instance is
         * nullptr, it won't do anything.
         */
        ~ScopedCollection() {
          if (perf_analysis_ != nullptr) {
            perf_analysis_->StopCollection(analysis_name_, collection_name_, optional_data_);
          }
        }

      private:
        const char* analysis_name_;
        const char* collection_name_;
        void* optional_data_;
        PerfAnalysisInfrastructure* perf_analysis_;
    };

  private:
    /**
     * @brief This data structure holds the metrics data of an analysis, as well
     * as the order of the performed collections.
     */
    struct AnalysisData {
      std::unordered_map<std::string, std::vector<PassData<uint64_t>>> collections_;
      std::vector<std::string> collection_order_;
    };

    /**
     * @brief Allocate space in the AnalysisData structure to hold metrics collection data.
     * @param data The data structure which corresponds to the new allocated space.
     * @param collection_name The name of the collection we want to prepare.
     * @return Returns the allocated vector.
     */
    std::vector<PassData<uint64_t>>&
    PrepareCollection(AnalysisData& data, const std::string& collection_name);

    /**
     * @brief Stores the results of the metrics in a file in a csv format.
     * @details This method should be called only after EndPassInstrumentation is called.
     * @param analysis_name The name of the analysis to dump.
     * @param hash_name Whether we want to hash the name. See StopAnalysis for more information.
     * @sa StopAnalysis.
     */
    void Dump(const std::string& analysis_name, bool hash_name);

    ArenaAllocator* arena_;

    // Compile-time related metrics.
    Timing timing_;
    TSClock tsclock_;

    // Memory-consumption related metrics.
    MallocStats malloc_stats_;
    ArenaBytesAllocated arena_bytes_allocated_;
    ArenaNumAllocations arena_num_allocations_;
    const PassManagerOptions* pass_options_;

    // Pass-usage related metric.
    PassStats pass_stats_;

    std::vector<Metric<uint64_t>*> metrics_;  // Holds the activated metrics.

    // The pool of currently started analyses. There can be one or more analyses started at once.
    std::unordered_map<std::string, AnalysisData> analyses_pool_;
};
}  // namespace art.

#endif  // ART_OPT_INFRASTRUCTURE_INSTRUMENTATION_H_

#endif  // PERF_ANALYSIS_INFRASTRUCTURE


text:
<?php

namespace CmsCommon\Mvc\Service;

use Zend\ServiceManager\ServiceLocatorInterface,
    CmsCommon\Mvc\Controller\RestfulController,
    CmsCommon\Mvc\Controller\Options\RestfulControllerOptionsInterface,
    CmsCommon\Mvc\Controller\Options\RestfulControllerOptions;

class RestfulControllerAbstractServiceFactory extends AbstractControllerAbstractServiceFactory
{
    /**
     * @var string
     */
    protected $configKey = 'rest_controllers';

    /**
     * {@inheritDoc}
     */
    public function canCreateServiceWithName(ServiceLocatorInterface $controllers, $name, $requestedName)
    {
        $services =  $controllers->getServiceLocator();

        return $this->getRequest($services)->isXmlHttpRequest()
            && parent::canCreateServiceWithName($controllers, $name, $requestedName);
    }

    /**
     * {@inheritDoc}
     *
     * @return RestfulController
     */
    protected function createControllerWithName(ServiceLocatorInterface $services, $requestedName)
    {
        $options = $this->getOptions($requestedName, $services);

        $controllerType = $options->getControllerType() ?: RestfulController::class;

        return new $controllerType(
            $services->get('DomainServiceManager')->get($requestedName),
            $options
        );
    }

    /**
     * {@inheritDoc}
     *
     * @return RestfulControllerOptionsInterface
     */
    protected function getDefaultOptions(ServiceLocatorInterface $services)
    {
        $options = parent::getDefaultOptions($services);

        if (!$options instanceof RestfulControllerOptionsInterface) {
            $optionsType = RestfulControllerOptions::class;
            $options = new $optionsType($options ?: []);
        }

        return $options;
    }
}


text:
using Lucene.Net.Support;
using NUnit.Framework;
using RandomizedTesting.Generators;
using System;
using System.Reflection;
using Assert = Lucene.Net.TestFramework.Assert;

namespace Lucene.Net.Index
{

    using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;

    [TestFixture]
    public class TestNoMergeScheduler : LuceneTestCase
    {
        [Test]
        public virtual void TestNoMergeScheduler_Mem()
        {
            MergeScheduler ms = NoMergeScheduler.INSTANCE;
            ms.Dispose();
            ms.Merge(null, RandomPicks.RandomFrom(Random, (MergeTrigger[])Enum.GetValues(typeof(MergeTrigger))), Random.NextBoolean());
        }

        [Test]
        public virtual void TestFinalSingleton()
        {
            assertTrue(typeof(NoMergeScheduler).IsSealed);
            ConstructorInfo[] ctors = typeof(NoMergeScheduler).GetConstructors(BindingFlags.Instance |
                    BindingFlags.NonPublic |
                    BindingFlags.Public |
                    BindingFlags.DeclaredOnly); // LUCENENET NOTE: It seems .NET automatically adds a private static constructor, so leaving off the static BindingFlag
            assertEquals("expected 1 private ctor only: " + Arrays.ToString(ctors), 1, ctors.Length);
            assertTrue("that 1 should be private: " + ctors[0], ctors[0].IsPrivate);
        }

        [Test]
        public virtual void TestMethodsOverridden()
        {
            // Ensures that all methods of MergeScheduler are overridden. That's
            // important to ensure that NoMergeScheduler overrides everything, so that
            // no unexpected behavior/error occurs
            foreach (MethodInfo m in typeof(NoMergeScheduler).GetMethods())
            {
                // getDeclaredMethods() returns just those methods that are declared on
                // NoMergeScheduler. getMethods() returns those that are visible in that
                // context, including ones from Object. So just filter out Object. If in
                // the future MergeScheduler will extend a different class than Object,
                // this will need to change.
                if (m.DeclaringType != typeof(object) && !m.IsFinal && m.IsVirtual)
                {
                    Assert.IsTrue(m.DeclaringType == typeof(NoMergeScheduler), m + " is not overridden !");
                }
            }
        }
    }
}


text:
module Fog
  module AWS
    class CloudFormation
      class Real

        require 'fog/aws/parsers/cloud_formation/describe_stack_resources'

        # Describe stack resources
        #
        # ==== Parameters
        # * options<~Hash>:
        #   * 'PhysicalResourceId'<~String>: name or unique identifier that corresponds to a physical instance ID
        #   or (one of PhysicalResourceId and StackName is required)
        #   * 'StackName'<~String>: only return events related to this stack name
        #   * 'LogicalResourceId'<~String>: logical name of the resource as specified in the template
        #
        # ==== Returns
        # * response<~Excon::Response>:
        #   * body<~Hash>:
        #     * 'StackResources'<~Array> - Matching resources
        #       * resource<~Hash>:
        #         * 'StackId'<~String> -
        #         * 'StackName'<~String> -
        #         * 'LogicalResourceId'<~String> -
        #         * 'PhysicalResourceId'<~String> -
        #         * 'ResourceType'<~String> -
        #         * 'Timestamp'<~Time> -
        #         * 'ResourceStatus'<~String> -
        #
        # ==== See Also
        # http://docs.amazonwebservices.com/AWSCloudFormation/latest/APIReference/API_DescribeStackResources.html
        #
        def describe_stack_resources(options = {})
          request({
            'Action'    => 'DescribeStackResources',
            :parser     => Fog::Parsers::AWS::CloudFormation::DescribeStackResources.new
          }.merge!(options))
        end

      end
    end
  end
end


text:
package fr.univnantes.lina.mlnlp.connectors.tagset;

import java.util.Map;

/**
 * Interface describing the method signatures to analyse a tagset
 * (e.g. a POS tagset)
 *
 * @author hernandez
 *
 */
public interface TagsetAnalyser {

	/**
	 * Take in parameters String variables which corresponds to the description
	 * tags of a textual unit
	 * (e.g. a morpho-syntax description of a tagset for a word)
	 * Return a map of detailed morpho-syntax features
	*/
	public Map<String, Object> analyseTag (Map<String, Object> tagFeaturesMap);

}


text:
package ai.world;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ai.pathfinding.AStar;
import ai.pathfinding.commons.Connection;
import ai.pathfinding.commons.Connection2D;
import ai.pathfinding.commons.PathfindingGraph;
import ai.pathfinding.commons.PredictedPath;
import ai.pathfinding.heu.EstimatedCostHeuristic;
import ai.pathfinding.heu.EuclideanDistanceHeuristic;
import ai.tiled.TiledMapProcessor;
import ludum.mighty.square.world.pathnodes.PathNode;

import com.badlogic.gdx.math.Vector2;

public class AIWorld
{

	//Node representations record (for A-star)
	Map< Integer, NodeRepresentations> nodeList;

	//Graph map with the connections among nodes for A-star
	HashMap<Integer, List<Connection>> graphMap;

	TiledMapProcessor tiledProcessor;

	List<PathNode> zoneList;

	List<PathNode> pathList;

	HashMap<Integer, List<PathNode>> zonePathMap;

	public AIWorld(TiledMapProcessor tiledProcessor,
			String zoneLayer,
			String pathLayer)
	{
		this.tiledProcessor = tiledProcessor;

		//Obtain zones
		this.zoneList = tiledProcessor.obtainZoning(zoneLayer);

		//Obtain paths
		this.pathList = tiledProcessor.obtainPathFinding(pathLayer);

		//Obtain the path nodes in each zone
		this.obtainPathsInZone();

		//Build the pathfinding graph
		this.obtainPathfindingGraph();

	}

	public void aStarFullTest()
	{

		System.out.println("\n\nFull Test A star ");
		AStar aStar = new AStar();

		EstimatedCostHeuristic heuristic =
				new EuclideanDistanceHeuristic( this.nodeList);

		for (NodeRepresentations nodeSource : this.nodeList.values())
		{
			for (NodeRepresentations nodeSink : this.nodeList.values())
			{
				PredictedPath predPath = aStar.pathfindAStar( new PathfindingGraph( this.graphMap),
						nodeSource.getIdNode(),
						nodeSink.getIdNode(),
						heuristic);

				if (nodeSource.getIdNode() == nodeSink.getIdNode())
				{
					//They should be null
					if (predPath.getPredConn().size() > 0)
					{
						System.out.println("Own Path "+ nodeSource.getIdNode());

					}
				}
				else
				{
					if (predPath.getPredConn().size() == 0)
					{
						System.out.println("No Route "+ nodeSource.getIdNode()+
								" "+ nodeSink.getIdNode());
					}
				}

			}

		}

	}

	private void obtainPathsInZone()
	{
		this.zonePathMap = new HashMap<Integer, List<PathNode>>();

		for (PathNode pathNode : this.pathList)
		{
			for (PathNode zoneNode : this.zoneList)
			{

				if (zoneNode.getNodeShape().overlaps(pathNode.getNodeShape()))
				{
					if (!this.zonePathMap.containsKey(zoneNode.getIdNode()))
					{
						this.zonePathMap.put(zoneNode.getIdNode(),
								new ArrayList<PathNode>());
					}

					//Add the new sample to the list
					this.zonePathMap.get(zoneNode.getIdNode())
						.add( pathNode );
				}
			}
		}

	}

	public int obtainCurrentZone(Vector2 currentPos)
	{
		int currentZone = -1;

		for (PathNode zoneNode : this.zoneList)
		{
			if ( zoneNode.getNodeShape().contains(currentPos) )
			{
				currentZone = zoneNode.getIdNode();
				break;
			}
		}

		return currentZone;

	}

	public PathNode obtainCurrentNode(Vector2 currentPos)
	{

		//Initially search in the zone

		int currentZone = -1;

		for (PathNode zoneNode : this.zoneList)
		{
			if ( zoneNode.getNodeShape().contains(currentPos) )
			{
				currentZone = zoneNode.getIdNode();
				break;
			}
		}

		if (currentZone < 0) return null;

		for (PathNode pathNode : this.zonePathMap.get(currentZone))
		{
			if (pathNode.getNodeShape().contains(currentPos))
			{
				//Square found, return pathNode
				return pathNode;

			}
		}

		//No path node found
		return null;
	}

	private void obtainPathfindingGraph()
	{

		//Init variables
		int connCounter = 0;

		this.nodeList =
				new HashMap< Integer, NodeRepresentations>();

		this.graphMap = new HashMap<Integer, List<Connection>>();

		for ( PathNode pathNode : pathList )
		{
			NodeRepresentations nodeRecord =
					new NodeRepresentations(pathNode.getIdNode(),
							pathNode.getReferencePoint().x,
							pathNode.getReferencePoint().y);

			this.nodeList.put(nodeRecord.getIdNode(), nodeRecord);

			List<Connection> connList = new ArrayList<Connection>();

			for (Integer jumpNode : pathNode.getConnectionJumpList())
			{

				Connection newConn = new Connection2D(
						connCounter,
						pathNode.getIdNode(),
						jumpNode,
						0.0, //Initially put the cost to 0
						true,
						false,
						false);

				//Increment the counter of connections
				connCounter++;

				connList.add(newConn);
			}

			for (Integer landNode : pathNode.getConnectionLandingList())
			{

				Connection newConn = new Connection2D(
						connCounter,
						pathNode.getIdNode(),
						landNode,
						0.0, //Initially put the cost to 0
						false,
						true,
						false);

				//Increment the counter of connections
				connCounter++;

				connList.add(newConn);
			}

			for (Integer normalNode : pathNode.getConnectionList())
			{

				Connection newConn = new Connection2D(
						connCounter,
						pathNode.getIdNode(),
						normalNode,
						Double.MAX_VALUE, //Initially put the cost to maximum
						false,
						false,
						true);

				//Increment the counter of connections
				connCounter++;

				connList.add(newConn);
			}

			this.graphMap.put( pathNode.getIdNode(), connList);
		}

		//Finally update the cost to the right value
		for (Integer key : this.graphMap.keySet())
		{
			//System.out.println("Updating connections for "+ key);

			//Loop over all the connections
			for (int i = 0; i < this.graphMap.get(key).size(); i++)
			{

				Connection conn = this.graphMap.get(key).get(i);
				conn.setCost(this.getCost( this.nodeList.get(conn.getSourceNodeId()),
						this.nodeList.get(conn.getSinkNodeId())));
			}
		}

	}

	private double getCost(NodeRepresentations sourceNode, NodeRepresentations sinkNode)
	{
		return Math.abs(sourceNode.getX() - sinkNode.getX()) + Math.abs(sourceNode.getY()- sinkNode.getY());
	}

	//Getters and setters
	public Map<Integer, NodeRepresentations> getNodeList() {
		return nodeList;
	}

	public void setNodeList(Map<Integer, NodeRepresentations> nodeList) {
		this.nodeList = nodeList;
	}

	public HashMap<Integer, List<Connection>> getGraphMap() {
		return graphMap;
	}

	public void setGraphMap(HashMap<Integer, List<Connection>> graphMap) {
		this.graphMap = graphMap;
	}

	public HashMap<Integer, List<PathNode>> getZonePathMap() {
		return zonePathMap;
	}

	public void setZonePathMap(HashMap<Integer, List<PathNode>> zonePathMap) {
		this.zonePathMap = zonePathMap;
	}

	public List<PathNode> getPathList() {
		return pathList;
	}

	public void setPathList(List<PathNode> pathList) {
		this.pathList = pathList;
	}

}


text:
<?php

namespace Denner\Client\Response;

use ArrayIterator;

use GuzzleHttp\Command\Event\ProcessEvent;
use GuzzleHttp\Command\Guzzle\Operation;
use GuzzleHttp\Message\ResponseInterface as HttpResponseInterface;

interface ResponseInterface
{
    /**
     * @param Operation $operation
     * @param ProcessEvent $event
     * @return ResponseInterface
     */
    public static function fromOperation(Operation $operation, ProcessEvent $event);

    /**
     * @return HttpResponseInterface
     */
    public function getHttpResponse();

    /**
     * @return ArrayIterator
     */
    public function getIterator();

    /**
     * @return integer
     */
    public function count();

    /**
     * @return array
     */
    public function toArray();
}


text:
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_H_
#include "gtest/gtest.h"
#include "gmock/gmock.h"

#include <stdint.h>
#include <vector>
#include <map>
#include <set>
#include "application_manager/hmi_command_factory.h"
#include "application_manager/application_manager.h"
#include "application_manager/hmi_capabilities.h"
#include "application_manager/message.h"
#include "application_manager/request_controller.h"
#include "application_manager/resume_ctrl.h"
#include "application_manager/vehicle_info_data.h"
#include "application_manager/state_controller.h"
#include "protocol_handler/protocol_observer.h"
#include "protocol_handler/protocol_handler.h"
#include "hmi_message_handler/hmi_message_observer.h"
#include "hmi_message_handler/hmi_message_sender.h"

#include "media_manager/media_manager_impl.h"

#include "connection_handler/connection_handler_observer.h"
#include "connection_handler/device.h"

#include "formatters/CSmartFactory.hpp"

#include "interfaces/HMI_API.h"
#include "interfaces/HMI_API_schema.h"
#include "interfaces/MOBILE_API_schema.h"

#include "interfaces/v4_protocol_v1_2_no_extra.h"
#include "interfaces/v4_protocol_v1_2_no_extra_schema.h"
#ifdef TIME_TESTER
#include "time_metric_observer.h"
#endif  // TIME_TESTER

#include "utils/macro.h"
#include "utils/shared_ptr.h"
#include "utils/message_queue.h"
#include "utils/prioritized_queue.h"
#include "utils/threads/thread.h"
#include "utils/threads/message_loop_thread.h"
#include "utils/lock.h"
#include "utils/singleton.h"

namespace application_manager {
  enum VRTTSSessionChanging {
    kVRSessionChanging = 0,
    kTTSSessionChanging
  };

namespace impl {

struct MessageFromMobile: public utils::SharedPtr<Message> {
  explicit MessageFromMobile(const utils::SharedPtr<Message>& message)
      : utils::SharedPtr<Message>(message) {
  }
  // PrioritizedQueue requres this method to decide which priority to assign
  size_t PriorityOrder() const {
    return (*this)->Priority().OrderingValue();
  }
};

struct MessageToMobile: public utils::SharedPtr<Message> {
  explicit MessageToMobile(const utils::SharedPtr<Message>& message,
                           bool final_message)
      : utils::SharedPtr<Message>(message),
        is_final(final_message) {
  }
  // PrioritizedQueue requres this method to decide which priority to assign
  size_t PriorityOrder() const {
    return (*this)->Priority().OrderingValue();
  }
  // Signals if connection to mobile must be closed after sending this message
  bool is_final;
};

struct MessageFromHmi: public utils::SharedPtr<Message> {
  explicit MessageFromHmi(const utils::SharedPtr<Message>& message)
      : utils::SharedPtr<Message>(message) {
  }
  // PrioritizedQueue requres this method to decide which priority to assign
  size_t PriorityOrder() const {
    return (*this)->Priority().OrderingValue();
  }
};

struct MessageToHmi: public utils::SharedPtr<Message> {
  explicit MessageToHmi(const utils::SharedPtr<Message>& message)
      : utils::SharedPtr<Message>(message) {
  }
  // PrioritizedQueue requres this method to decide which priority to assign
  size_t PriorityOrder() const {
    return (*this)->Priority().OrderingValue();
  }
};

typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageFromMobile> > FromMobileQueue;
typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageToMobile> > ToMobileQueue;
typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageFromHmi> > FromHmiQueue;
typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageToHmi> > ToHmiQueue;

// AudioPassThru
typedef struct  {
std::vector<uint8_t> binary_data;
int32_t              session_key;
} AudioData;
typedef std::queue<AudioData>                          RawAudioDataQueue;
typedef threads::MessageLoopThread<RawAudioDataQueue>  AudioPassThruQueue;
}
typedef std::vector<std::string> RPCParams;

class ApplicationManagerImpl : public ApplicationManager,
  public hmi_message_handler::HMIMessageObserver,
  public protocol_handler::ProtocolObserver,
  public connection_handler::ConnectionHandlerObserver,
  public impl::FromMobileQueue::Handler, public impl::ToMobileQueue::Handler,
  public impl::FromHmiQueue::Handler, public impl::ToHmiQueue::Handler,
  public impl::AudioPassThruQueue::Handler,
  public utils::Singleton<ApplicationManagerImpl> {

    friend class ResumeCtrl;
    friend class CommandImpl;

 public:
    ApplicationManagerImpl() {
        std::cout << "ApplicationManagerImpl Mock created " << std::endl;
    }

  MOCK_METHOD0(Init, bool());
  MOCK_METHOD0(Stop, bool());
  MOCK_METHOD1(OnMessageReceived, void (utils::SharedPtr<application_manager::Message>));
  MOCK_METHOD1(OnErrorSending, void (utils::SharedPtr<application_manager::Message>));
  MOCK_METHOD1(OnMessageReceived, void (const ::protocol_handler::RawMessagePtr));
  MOCK_METHOD1(OnMobileMessageSent, void (const ::protocol_handler::RawMessagePtr));
  MOCK_METHOD1(OnDeviceListUpdated, void (const connection_handler::DeviceMap&));
  MOCK_METHOD0(OnFindNewApplicationsRequest, void ());
  MOCK_METHOD1(RemoveDevice, void (const connection_handler::DeviceHandle&));
  MOCK_METHOD3(OnServiceStartedCallback, bool (const connection_handler::DeviceHandle&,
                                            const int32_t&,
                                            const protocol_handler::ServiceType&));
  MOCK_METHOD3(OnServiceEndedCallback, void (const int32_t&,
                                             const protocol_handler::ServiceType&,
                                             const connection_handler::CloseSessionReason&));
  MOCK_METHOD1(Handle, void (const impl::MessageFromMobile));
  MOCK_METHOD1(Handle, void (const impl::MessageToMobile));
  MOCK_METHOD1(Handle, void (const impl::MessageFromHmi));
  MOCK_METHOD1(Handle, void (const impl::MessageToHmi));
  MOCK_METHOD1(Handle, void (const impl::AudioData));

  //ApplicationManager methods
  MOCK_METHOD1(set_hmi_message_handler, void (hmi_message_handler::HMIMessageHandler*));
  MOCK_METHOD1(set_protocol_handler, void (protocol_handler::ProtocolHandler*));
  MOCK_METHOD1(set_connection_handler, void (connection_handler::ConnectionHandler*));

  //ApplicationManagerImpl methods:
#ifdef TIME_TESTER
  MOCK_METHOD1(SetTimeMetricObserver, void(AMMetricObserver*));
#endif
  MOCK_METHOD1(RegisterApplication,
                ApplicationSharedPtr(const utils::SharedPtr<smart_objects::SmartObject>&));
  MOCK_METHOD0(hmi_capabilities, HMICapabilities& ());
  MOCK_METHOD1(ProcessQueryApp, void (const smart_objects::SmartObject& sm_object));
  MOCK_METHOD1(ManageHMICommand, bool (const utils::SharedPtr<smart_objects::SmartObject>&));
  MOCK_METHOD1(ManageMobileCommand, bool (const utils::SharedPtr<smart_objects::SmartObject>& message));
  MOCK_METHOD1(SendMessageToHMI, bool (const utils::SharedPtr<smart_objects::SmartObject>&));
  MOCK_METHOD2(SendMessageToMobile, bool (const utils::SharedPtr<smart_objects::SmartObject>&,
                                          bool));
  MOCK_METHOD1(SendMessageToMobile, bool (const utils::SharedPtr<smart_objects::SmartObject>&));
  MOCK_METHOD1(GetDeviceName, std::string (connection_handler::DeviceHandle));
  MOCK_METHOD1(GetDeviceTransportType, hmi_apis::Common_TransportType::eType (const std::string&));
  MOCK_METHOD1(application, ApplicationSharedPtr (uint32_t));
  MOCK_METHOD1(application_by_policy_id, ApplicationSharedPtr (const std::string&));
  MOCK_METHOD1(RemoveAppDataFromHMI, bool(ApplicationSharedPtr));
  MOCK_METHOD1(HeadUnitReset, void(mobile_api::AppInterfaceUnregisteredReason::eType));
  MOCK_METHOD1(LoadAppDataToHMI, bool(ApplicationSharedPtr));
  MOCK_METHOD1(ActivateApplication, bool (ApplicationSharedPtr));
  MOCK_METHOD1(IsHmiLevelFullAllowed, mobile_api::HMILevel::eType (ApplicationSharedPtr));
  MOCK_METHOD3(OnHMILevelChanged, void  (uint32_t, mobile_apis::HMILevel::eType, mobile_apis::HMILevel::eType));
  MOCK_METHOD2(UnregisterRevokedApplication, void(uint32_t, mobile_apis::Result::eType));
  MOCK_METHOD1(SetUnregisterAllApplicationsReason, void(mobile_api::AppInterfaceUnregisteredReason::eType));
  MOCK_METHOD0(UnregisterAllApplications, void());
  MOCK_METHOD0(connection_handler, connection_handler::ConnectionHandler*());
  MOCK_METHOD0(protocol_handler, protocol_handler::ProtocolHandler*());
  MOCK_METHOD0(hmi_message_handler, hmi_message_handler::HMIMessageHandler*());
  MOCK_METHOD5(CheckPolicyPermissions, mobile_apis::Result::eType(const std::string&,
                                                           mobile_apis::HMILevel::eType,
                                                           mobile_apis::FunctionID::eType,
                                                           const RPCParams&,
                                                           CommandParametersPermissions*));
  MOCK_METHOD3(updateRequestTimeout, void(uint32_t, uint32_t, uint32_t));
  MOCK_METHOD0(GenerateGrammarID, uint32_t());
  MOCK_METHOD0(GenerateNewHMIAppID, uint32_t());
  MOCK_METHOD1(GetAvailableSpaceForApp, uint32_t(const std::string&));
  MOCK_METHOD0(begin_audio_pass_thru, bool ());
  MOCK_METHOD0(end_audio_pass_thru, uint32_t());
  MOCK_METHOD1(StopAudioPassThru, void(uint32_t));
  MOCK_METHOD1(applications_by_button, std::vector<ApplicationSharedPtr>(uint32_t));
  MOCK_METHOD0(applications_with_navi, std::vector<ApplicationSharedPtr>());
  MOCK_METHOD1(applications_by_ivi, std::vector<ApplicationSharedPtr>(uint32_t));
  MOCK_METHOD2(IviInfoUpdated, std::vector<utils::SharedPtr<Application>> (VehicleDataType,
                                                                   int));
  MOCK_METHOD6(StartAudioPassThruThread, void(uint32_t, uint32_t, uint32_t,
                                            uint32_t, uint32_t, uint32_t));
  MOCK_METHOD4(SaveBinary, mobile_apis::Result::eType(const std::vector<uint8_t>&,
                                const std::string&,
                                const std::string&,
                                const int64_t));
  MOCK_METHOD1(ReplaceHMIByMobileAppId, void(smart_objects::SmartObject&));
  MOCK_METHOD1(ReplaceMobileByHMIAppId, void(smart_objects::SmartObject&));
  MOCK_METHOD0(resume_controller, ResumeCtrl&());
  MOCK_METHOD1(GetDefaultHmiLevel, mobile_api::HMILevel::eType (ApplicationSharedPtr));

  MOCK_METHOD2(HMILevelAllowsStreaming, bool(uint32_t, protocol_handler::ServiceType));
  MOCK_METHOD2(CanAppStream, bool(uint32_t, protocol_handler::ServiceType));
  MOCK_METHOD1(EndNaviServices, void(int32_t));
  MOCK_METHOD1(ForbidStreaming, void(int32_t));
  MOCK_METHOD3(OnAppStreaming, void(int32_t, protocol_handler::ServiceType, bool));

  MOCK_METHOD1(Unmute, void(VRTTSSessionChanging));
  MOCK_METHOD1(Mute, void(VRTTSSessionChanging));
  MOCK_METHOD2(set_application_id, void(const int32_t, const uint32_t));
  MOCK_METHOD1(application_id, uint32_t(const int32_t));
  MOCK_METHOD1(removeNotification, void(const commands::Command*));
  MOCK_METHOD1(addNotification, void(const CommandSharedPtr ));
  MOCK_METHOD0(StartDevicesDiscovery, void());
  MOCK_METHOD2(SendAudioPassThroughNotification, void(uint32_t, std::vector<uint8_t>&));
  MOCK_METHOD1(set_all_apps_allowed, void(const bool));
  MOCK_METHOD4(CreateRegularState, HmiStatePtr (uint32_t, mobile_api::HMILevel::eType,
                                                     mobile_apis::AudioStreamingState::eType,
                                                     mobile_apis::SystemContext::eType));

  template<bool SendActivateApp>
  MOCK_METHOD2(SetState, void(uint32_t, HmiState));
  template<bool SendActivateApp>
  MOCK_METHOD2(SetState, void(uint32_t, mobile_api::HMILevel::eType));
  template<bool SendActivateApp>
  MOCK_METHOD3(SetState, void(uint32_t, mobile_api::HMILevel::eType,
                              mobile_apis::AudioStreamingState::eType));
  template<bool SendActivateApp>
  MOCK_METHOD4(SetState, void(uint32_t, mobile_api::HMILevel::eType,
                              mobile_apis::AudioStreamingState::eType,
                              mobile_apis::SystemContext::eType));
  MOCK_METHOD2(SetState, void(uint32_t,
                              mobile_apis::AudioStreamingState::eType));

  MOCK_CONST_METHOD0(all_apps_allowed, bool());
  MOCK_METHOD1(set_vr_session_started, void(const bool));
  MOCK_CONST_METHOD0(vr_session_started, bool());
  MOCK_METHOD1(set_driver_distraction, void(const bool));
  MOCK_CONST_METHOD0(driver_distraction, bool());
  MOCK_METHOD1(ConnectToDevice, void(uint32_t));
  MOCK_METHOD0(OnHMIStartedCooperation, void());
  MOCK_METHOD0(GetNextHMICorrelationID, uint32_t ());
  MOCK_CONST_METHOD0(IsHMICooperating, bool());
  MOCK_METHOD0(OnTimerSendTTSGlobalProperties, void());
  MOCK_METHOD0(CreatePhoneCallAppList, void());
  MOCK_METHOD0(ResetPhoneCallAppList, void());
  MOCK_METHOD2(ChangeAppsHMILevel, void(uint32_t, mobile_apis::HMILevel::eType));
  MOCK_METHOD1(AddAppToTTSGlobalPropertiesList, void(const uint32_t));
  MOCK_METHOD1(RemoveAppFromTTSGlobalPropertiesList, void(const uint32_t));
  MOCK_METHOD1(application_by_hmi_app, ApplicationSharedPtr(uint32_t));
  MOCK_METHOD2(UnregisterApplication, void(const uint32_t,mobile_apis::Result::eType));
  MOCK_METHOD3(UnregisterApplication, void(const uint32_t,mobile_apis::Result::eType,
                                        bool));
  MOCK_METHOD4(UnregisterApplication, void(const uint32_t,mobile_apis::Result::eType,
                                        bool, bool));
  MOCK_METHOD1(OnAppUnauthorized, void(const uint32_t&));
  MOCK_CONST_METHOD0(get_limited_media_application, ApplicationSharedPtr());
  MOCK_CONST_METHOD0(get_limited_navi_application, ApplicationSharedPtr());
  MOCK_CONST_METHOD0(get_limited_voice_application, ApplicationSharedPtr());
  MOCK_CONST_METHOD1(IsAppTypeExistsInFullOrLimited, bool(ApplicationSharedPtr));
  MOCK_CONST_METHOD0(active_application, ApplicationSharedPtr ());
  MOCK_METHOD0(OnApplicationListUpdateTimer, void());
  MOCK_METHOD0(OnLowVoltage, void());
  MOCK_METHOD0(OnWakeUp, void());
  MOCK_METHOD1(OnUpdateHMIAppType, void(std::map<std::string, std::vector<std::string> >));
  MOCK_METHOD3(set_state, void(ApplicationSharedPtr app,
                               mobile_apis::HMILevel::eType,
                               mobile_apis::AudioStreamingState::eType));
MOCK_CONST_METHOD0(IsStopping, bool());

  struct ApplicationsAppIdSorter {
    bool operator() (const ApplicationSharedPtr lhs,
                     const ApplicationSharedPtr rhs) {
      return lhs->app_id() < rhs->app_id();
    }
  };

  // typedef for Applications list
  typedef std::set<ApplicationSharedPtr,
                   ApplicationsAppIdSorter> ApplictionSet;

  // typedef for Applications list iterator
  typedef ApplictionSet::iterator ApplictionSetIt;

  // typedef for Applications list const iterator
  typedef ApplictionSet::const_iterator ApplictionSetConstIt;

  /**
   * Class for thread-safe access to applications list
   */
  class ApplicationListAccessor: public DataAccessor<ApplictionSet> {
    public:
      ApplicationListAccessor() :
        DataAccessor<ApplictionSet>(ApplictionSet(),sync_primitives::Lock()) {
      }
      MOCK_CONST_METHOD0(applications, const ApplictionSet());
      MOCK_METHOD0(begin, ApplictionSetConstIt());
      MOCK_METHOD0(end, ApplictionSetConstIt());
      MOCK_METHOD1(Erase, void(ApplicationSharedPtr));
      MOCK_METHOD1(Insert, void(ApplicationSharedPtr));
      MOCK_METHOD0(Empty, bool());
  };

  friend class ApplicationListAccessor;

  class ApplicationListUpdateTimer : public timer::TimerThread<ApplicationManagerImpl> {
   public:
    ApplicationListUpdateTimer(ApplicationManagerImpl* callee) :
        timer::TimerThread<ApplicationManagerImpl>("AM ListUpdater",
            callee, &ApplicationManagerImpl::OnApplicationListUpdateTimer
        ) {
    }
  };
  typedef utils::SharedPtr<ApplicationListUpdateTimer> ApplicationListUpdateTimerSptr;

  private:
    //FIXME(AKutsan) In resume_controller is is nessesery to change realisation for remove using application_list_
    ApplictionSet application_list_;
  FRIEND_BASE_SINGLETON_CLASS(ApplicationManagerImpl);
};

} //application_manager
#endif  // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_H_


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

-->
<animation-list
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:oneshot="false">
    <item android:drawable="@drawable/progressbar_indeterminate_1" android:duration="50" />
    <item android:drawable="@drawable/progressbar_indeterminate_2" android:duration="50" />
    <item android:drawable="@drawable/progressbar_indeterminate_3" android:duration="50" />
    <item android:drawable="@drawable/progressbar_indeterminate_4" android:duration="50" />
    <item android:drawable="@drawable/progressbar_indeterminate_5" android:duration="50" />
    <item android:drawable="@drawable/progressbar_indeterminate_6" android:duration="50" />
    <item android:drawable="@drawable/progressbar_indeterminate_7" android:duration="50" />
    <item android:drawable="@drawable/progressbar_indeterminate_8" android:duration="50" />
</animation-list>


text:
package com.alibaba.nacos.client.config.impl;

import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.common.http.AbstractHttpClientFactory;
import com.alibaba.nacos.common.http.HttpClientBeanHolder;
import com.alibaba.nacos.common.http.HttpClientConfig;
import com.alibaba.nacos.common.http.HttpClientFactory;
import com.alibaba.nacos.common.http.client.HttpClientRequestInterceptor;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.common.lifecycle.Closeable;
import com.alibaba.nacos.common.model.RequestHttpEntity;
import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.MD5Utils;
import org.slf4j.Logger;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;

/**
 * config http Manager.
 *
 * @author mai.jh
 */
public class ConfigHttpClientManager implements Closeable {

    private static final Logger LOGGER = LogUtils.logger(ConfigHttpClientManager.class);

    private static final HttpClientFactory HTTP_CLIENT_FACTORY = new ConfigHttpClientFactory();

    private static final int CON_TIME_OUT_MILLIS = ParamUtil.getConnectTimeout();

    private static final int READ_TIME_OUT_MILLIS = 3000;

    private static final NacosRestTemplate NACOS_REST_TEMPLATE;

    static {
        NACOS_REST_TEMPLATE = HttpClientBeanHolder.getNacosRestTemplate(HTTP_CLIENT_FACTORY);
        NACOS_REST_TEMPLATE.getInterceptors().add(new LimiterHttpClientRequestInterceptor());
    }

    private static class ConfigHttpClientManagerInstance {

        private static final ConfigHttpClientManager INSTANCE = new ConfigHttpClientManager();
    }

    public static ConfigHttpClientManager getInstance() {
        return ConfigHttpClientManagerInstance.INSTANCE;
    }

    @Override
    public void shutdown() throws NacosException {
        NAMING_LOGGER.warn("[ConfigHttpClientManager] Start destroying NacosRestTemplate");
        try {
            HttpClientBeanHolder.shutdownNacostSyncRest(HTTP_CLIENT_FACTORY.getClass().getName());
        } catch (Exception ex) {
            NAMING_LOGGER.error("[ConfigHttpClientManager] An exception occurred when the HTTP client was closed : {}",
                    ExceptionUtil.getStackTrace(ex));
        }
        NAMING_LOGGER.warn("[ConfigHttpClientManager] Destruction of the end");
    }

    /**
     * get connectTimeout.
     *
     * @param connectTimeout connectTimeout
     * @return int return max timeout
     */
    public int getConnectTimeoutOrDefault(int connectTimeout) {
        return Math.max(CON_TIME_OUT_MILLIS, connectTimeout);
    }

    /**
     * get NacosRestTemplate Instance.
     *
     * @return NacosRestTemplate
     */
    public NacosRestTemplate getNacosRestTemplate() {
        return NACOS_REST_TEMPLATE;
    }

    /**
     * ConfigHttpClientFactory.
     */
    private static class ConfigHttpClientFactory extends AbstractHttpClientFactory {

        @Override
        protected HttpClientConfig buildHttpClientConfig() {
            return HttpClientConfig.builder().setConTimeOutMillis(CON_TIME_OUT_MILLIS)
                    .setReadTimeOutMillis(READ_TIME_OUT_MILLIS).build();
        }

        @Override
        protected Logger assignLogger() {
            return LOGGER;
        }
    }

    /**
     * config Limiter implement.
     */
    private static class LimiterHttpClientRequestInterceptor implements HttpClientRequestInterceptor {

        @Override
        public boolean isIntercept(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity) {
            final String body = requestHttpEntity.getBody() == null ? "" : JacksonUtils.toJson(requestHttpEntity.getBody());
            return Limiter.isLimit(MD5Utils.md5Hex(uri + body, Constants.ENCODE));
        }

        @Override
        public HttpClientResponse intercept() {
            return new LimitResponse();
        }
    }

    /**
     * Limit Interrupt response.
     */
    private static class LimitResponse implements HttpClientResponse {

        @Override
        public Header getHeaders() {
            return Header.EMPTY;
        }

        @Override
        public InputStream getBody() throws IOException {
            return new ByteArrayInputStream("More than client-side current limit threshold".getBytes());
        }

        @Override
        public int getStatusCode() {
            return NacosException.CLIENT_OVER_THRESHOLD;
        }

        @Override
        public String getStatusText() {
            return null;
        }

        @Override
        public void close() {

        }
    }
}


text:
function insert(item, user, request) {

    request.execute();

}