text:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE document SYSTEM "document.dtd">
<document>
  <documentinfo>
    <system>Erlang Systems</system>
    <type>Design and Configuration Process</type>
    <reference>CDOC XXXX</reference>
    <author>Sean Hinde</author>
    <version>0.1</version>
    <date>8th March 2004</date>
  </documentinfo>

<references>

</references>

<history>
  <version>
    <vsn>0.1</vsn>
    <status>Draft</status>
    <date>8th March 2004</date>
    <changes>Initial Version</changes>
    <author>Sean Hinde</author>
  </version>
</history>

<scope>
This document describes the design and configuration management
process used for Erlang based systems.
</scope>

<purpose>
The purpose of this document is to ensure that all systems meet a
basic set of maintainability targets
</purpose>

<sect1><title>Erlang Application Structure</title>

  <para>Erlang based applications have a structure defined by Ericsson as
    part of the OTP framework. A complete system is built from an
    Ericsson supplied runtime system and set of OTP
    Applications. These OTP Applications will include standard
    applications supplied by Ericsson (including as a minimum kernel
    and stdlib) and additional applications written by T-Mobile or 3rd
    parties. Regardless of the origin of the OTP Applications the same
    structure must be followed for all systems.
  </para>

  <para>
    All code for each individual OTP Application is structured in the
    filesystem and CVS repository following the standard OTP directory
    structure:
  </para>

app_name/src/
        /priv/
        /doc/
        /ebin/
        /vsn.mk

  <list>
    <item>
      src contains all Erlang source code files (also
      referred to as modules) plus the app_name.app.src
      and Emakefile.src files
    </item>
    <item>
      priv contains config files, port programs, esp
      dynamic web page templates etc
    </item>
    <item>doc contains the generated edoc source code documentation</item>
    <item>
      ebin is an empty directory which will contain the compiled
      Erlang .beam files after building.
    </item>
    <item>
      vsn.mk is a file containing a single line which contains the OTP
      application version number
    </item>
  </list>

  <sect2><title>The vsn.mk file</title>
    <para>
      The structure of the vsn.mk file is as below:
    </para>

	  APP_NAME_VSN = 1.0

    <para>
      This version string relates to the overall version of the OTP
      application. It is automatically included into the appropriate
      places by the release building routines.
    </para>
  </sect2>

  <sect2><title>The app_name.app.src file</title>
    <para>
      All applications must have an app_name.app.src
      file. This file should be stored in the src sub-directory of the
      app_name directory. This is the standard
      OTP app_name.app file which will ultimately be
      located in the ebin directory and used by the build system to
      create the overall boot script for the
      system. The .src version is parameterised by the
      application version number APP_NAME_VSN from
      the vsn.mk file. For example:
    </para>

{application, app_name,
        [{description, "Mission Critical Application"},
         {vsn, "%APP_NAME_VSN%"},
         {modules, [app_name,
                    app_name_app,
                    app_name_db,
                    app_name_lib,
                    app_name_server,
                    app_name_sms,
                    app_name_sup,
                    app_name_test,
                    app_name_web]},
         {registered, [	app_name_sup, app_name_server]},
         {applications, [kernel, stdlib]},
	 {mod, {app_name_app, []}}]}.

  </sect2>
  <sect2><title>Adding a new OTP Application</title>
    <para>
      Every OTP application must have an entry created in the Master
      CVS control file Modules. This entry ensures that
      the correct shell scripts are run after the export part of a
      system build.
    </para>
  </sect2>
</sect1>

<sect1><title>Version Management</title>
  <para>
    Version Management is carried out at a number of different levels
    following the standard Ericsson derived OTP scheme. Individual OTP
    applications have their own version number and independent upgrade
    paths. System level versioning is handled via the standard OTP
    release (.rel) file.
  </para>
  <para>
    The version control system used currently is CVS. CVS has a
    number of small limitations which drive some of the details of
    the versioning scheme (particularly tag naming).
  </para>

  <sect2><title>Code Module Level Versioning</title>
    <para>
      All source code files (Erlang modules) must have a vsn attribute
      included in the form:
    </para>

-vsn('$Id$').

    <para>
      This will be expanded by CVS to include all the required version
      info after ever check in. This vsn Id is used by the build
      system and also by tools built into the web gui of every
      application to query currently running code versions.
    </para>
  </sect2>

  <sect2><title>OTP Application Level Versioning</title>
    <para>
      The CVS tagging mechanism is used to track released files. Tags are
      applied at the OTP application level and below.
    </para>

    <sect3><title>Format of CVS version tags</title>
      <para>
        Tags are always created in a standard format. When a release
        of an OTP application level subsystem is made, all files in
        the
        app_name/* directory must be tagged with a tag
        of precisely the form rel-1-0. The hyphens are
        important, as is the quantity of numbering levels.
      </para>
      <para>
        Interim and bug fix releases of the OTP application or files
        within it must be tagged with a special tag format which hold
        the base release version and the patch level reached. Files
        released between up-issues of the overall application version
        number should therefore be tagged according to the following
        convention: rel-1-0-dcr175 where
        the -dcr175 part relates to the change request
        number this change was issued in. The build management tools
        understand this format and ensure that anyone asking
        for rel-1-0 automatically pick up the latest bug
        fix releases in version 1.0 while warning them that this is
        what it is doing.
      </para>
    </sect3>

    <sect3><title>When to increment the OTP Application version number</title>
      <para>
        An OTP Application level subsystem should have its main
        version number incremented in the following situations:
      </para>
      <list>
        <item>
          When a new system is being released which incorporates this
          OTP application and there have been any patches released on
          top of the current version of the application
          (i.e. any rel-x-y-dcr-xxx patches exist for the
          current rel-x-y version.
        </item>
        <item>
          When any non-backwards compatible change is made to any external API
          provided by the OTP application
        </item>
        <item>
          When any source code files are added or removed from the application
        </item>
      </list>
      <para>
        In other words the only time that the OTP Application version
        number should not be increased after a code change in one of
        its modules is when a change or fix is being released for an
        existing live system and none of the reasons given above
        apply.
      </para>
    </sect3>
  </sect2>

  <sect2><title>System Release Level Versioning</title>
    <para>
      The version of an overall system is controlled by a single
      file
      called system_name-1.0.rel. The -1.0
      part of this name is significant as it defines the overall
      version of the system. This file also controls the startup
      order of the OTP Applications within the system.
    </para>
    <sect3><title>Format of System Level Release File</title>
      <para>
        The system_name-1.0.rel file takes the form of this example:
      </para>

{release, {"SYSTEM_NAME Transaction Server","system_name-1.0"},
 {erts, "5.3"},
 [{kernel,"2.9"},
  {stdlib,"1.12"},
  {sasl, "1.10"},
  {runtime_tools, "1.4"},
  {os_mon, "1.6.1"},
  {snmp, "3.4"},
  {crypto, "1.2"},
  {ssl, "3.0.1"},
  {mnesia, "4.1.4"},
  {inets, "3.0.6"},
  {asn1, "1.4.2"},
  {shlib, "2.0"},
  {connector, "1.0"},
  {xmerl, "0.18"},
  {checksum, "1.0"},
  {audit_log, "1.0"},
  {cron, "1.0"},
  {stats, "1.1"},
  {alarms, "1.0"},
  {metrica, "1.0"},
  {bos, "1.0"},
  {http_mgr, "1.3"},
  {db_backup, "1.0"},
  {tcp_client, "1.1"},
  {xtc_client, "1.0"},
  {grouse, "2.4"},
  {events, "1.1"},
  {app_name, "1.0"}]}.

      <para>
        The first line has two parameters - the system name and
        version, and the Erlang runtime system version.
      </para>
      <para>
        Each line in the rest of the file lists an OTP application
        with its version number. Applications will be started in the
        order they appear in the list. The version number here must
        match the CVS Tag for the application or the build system will
        complain. So the tag rel-1-0 as applied to the
        CVS repository would match a version number "1.0"
        in this table.
      </para>
      <para>
        Note that a tag rel-1-0-dcr175 will also match
        the version numnber "1.0" in this list, and the
        build system will simply warn you that you are picking up some
        patches.
      </para>
    </sect3>
  </sect2>
</sect1>
<sect1><title>Documentation</title>
  <para>
    The following documents are required for every system delivered to the customer:
  </para>
  <list>
    <item>
      High Level Design
    </item>
    <item>
      Detailed Design
    </item>
    <item>
      User Guide
    </item>
    <item>
      Release Notes
    </item>
    <item>
      Code Documentation
    </item>
  </list>
  <para>
    Code documentation should be created in edoc format embedded
    within the code. Other documents may be created using either MS
    Word or created as XML files (preferred).
  </para>
  <sect2><title>Code Documentation</title>
    <para>
      Code documentation should be embedded in the source code files
      and processed with the edoc tool to extract the documentation
      into a set of web pages for the application.
    </para>
    <para>
      Each module should have a top level document describing its
      purpose and place in the OTP application. All exported functions
      should be documented including @spec type information.
    </para>
    <para>
      Created documents should be updated after every change. The
      contents of the doc directory should be tagged excatly the same
      as the rest of the files associated with the OTP Application
      (Check - this should not be strictly neccessary, but is useful
      for online browsing of docs).
    </para>
  </sect2>
  <sect2><title>System Documentation - XML based</title>
    <para>
      The objective of the XML based documentation ystem is to reduce
      the amount of duplication associated with producing the whole
      set of documentation. The documentation is created as a set of
      sections which are pulled together in different way to make
      e.g. a High Level design or Detailed design. The sections to be
      produced should include:
    </para>
    <list>
      <item>
        Master document including the system meta data
      </item>
      <item>
        Introduction to the system
      </item>
      <item>
        Database table desctiptions
      </item>
      <item>
        Stats Counter Descriptions
      </item>
      <item>
        Log File Descriptions
      </item>
      <item>
        User Manual for the web based pages associated solely with
        this application. Each of the other included OTP Applications
        will include their own contribution to the User Guide of a
        system.
      </item>
    </list>
    <para>
      System documents should be stored in the doc subdirectory of the
      system_name_rel CVS Module (Check).
    </para>
    <para>
      Each system shall have a set of XML Source documents
      produced. These documents will be processed into PDF files and
      web pages during the system build process (TODO).
    </para>
  </sect2>
</sect1>
<notes>
  Where to store release files, sys.config, and track real released versions
  Location of config files.
  Making the config location independent
  Installing on the tergat esystem
  Following the release build process
  Creating Certificates
  Cookies
  sys.config
  Top level directroies in a target system
  module naming convention
</notes>
</document>


text:
package org.sagebionetworks.web.client.widget.table.v2.results;

import org.gwtbootstrap3.client.ui.html.Strong;
import org.sagebionetworks.web.client.view.bootstrap.table.TableHeaderResizeGrip;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

public class StaticTableHeaderImpl implements StaticTableHeader {

	public interface Binder extends UiBinder<Widget, StaticTableHeaderImpl> {
	}

	@UiField
	Strong header;
	@UiField
	TableHeaderResizeGrip resizeGrip;
	Widget widget;

	@Inject
	public StaticTableHeaderImpl(Binder binder) {
		widget = binder.createAndBindUi(this);
	}

	@Override
	public void setHeader(String headerText) {
		header.setText(headerText);
	}

	@Override
	public Widget asWidget() {
		return widget;
	}

	@Override
	public void setIsResizable(boolean isResizable) {
		resizeGrip.setVisible(isResizable);
	}
}

redpajama_set_name: RedPajamaGithub


text:
layout: default
title: Airframe
---
## Diatone White Sheep
### Price
$50

### Links
[Purchase](http://www.banggood.com/Diatone-White-Sheep-PCB-Version-FPV-Quadcopter-Frame-Kit-p-970933.html?utm_source=google&utm_medium=cpc&utm_campaign=Crc-FrameK-rm-diatone500pcb&utm_content=nydia&utm_design=4&gclid=CKW6lNel2cUCFUgJvAodVXwA9w)


text:
Функциональные кусочки кода для рецептов и тасок конечных продуктов.
По сути здесь лежат те куски кода, которые захотелось выделить из плагинов для того чтобы их можно было легко
переиспользовать в тасках конечных продуктов, заодно смысловое разделение кода.

Вообще я не уверен насколько оно заживет, но пусть побудет, может данный уровень разделения окажется полезен.


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TextAnnotation.cs" company="OxyPlot">
//   The MIT License (MIT)
//
//   Copyright (c) 2012 Oystein Bjorke
//
//   Permission is hereby granted, free of charge, to any person obtaining a
//   copy of this software and associated documentation files (the
//   "Software"), to deal in the Software without restriction, including
//   without limitation the rights to use, copy, modify, merge, publish,
//   distribute, sublicense, and/or sell copies of the Software, and to
//   permit persons to whom the Software is furnished to do so, subject to
//   the following conditions:
//
//   The above copyright notice and this permission notice shall be included
//   in all copies or substantial portions of the Software.
//
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
//   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <summary>
//   This is a WPF wrapper of OxyPlot.TextAnnotation
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot.Wpf
{
    using System.Windows;
    using System.Windows.Media;

    /// <summary>
    /// This is a WPF wrapper of OxyPlot.TextAnnotation
    /// </summary>
    public class TextAnnotation : TextualAnnotation
    {
        /// <summary>
        /// The Background property.
        /// </summary>
        public static readonly DependencyProperty BackgroundProperty = DependencyProperty.Register(
            "Background", typeof(Color?), typeof(TextAnnotation), new PropertyMetadata(null, AppearanceChanged));

        /// <summary>
        /// The TextColor property.
        /// </summary>
        public static readonly DependencyProperty TextColorProperty = DependencyProperty.Register(
            "TextColor", typeof(Color), typeof(TextAnnotation), new PropertyMetadata(Colors.Blue, AppearanceChanged));

        /// <summary>
        /// The Offset property.
        /// </summary>
        public static readonly DependencyProperty OffsetProperty = DependencyProperty.Register(
            "Offset",
            typeof(Vector),
            typeof(TextAnnotation),
            new PropertyMetadata(default(Vector), AppearanceChanged));

        /// <summary>
        /// The Padding property.
        /// </summary>
        public static readonly DependencyProperty PaddingProperty = DependencyProperty.Register(
            "Padding",
            typeof(Thickness),
            typeof(TextAnnotation),
            new PropertyMetadata(new Thickness(4), AppearanceChanged));

        /// <summary>
        /// The Position property.
        /// </summary>
        public static readonly DependencyProperty PositionProperty = DependencyProperty.Register(
            "Position", typeof(DataPoint), typeof(TextAnnotation), new PropertyMetadata(AppearanceChanged));

        /// <summary>
        /// The Rotation property.
        /// </summary>
        public static readonly DependencyProperty RotationProperty = DependencyProperty.Register(
            "Rotation", typeof(double), typeof(TextAnnotation), new PropertyMetadata(0.0, AppearanceChanged));

        /// <summary>
        /// The Stroke property.
        /// </summary>
        public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(
            "Stroke", typeof(Color), typeof(TextAnnotation), new PropertyMetadata(Colors.Black, AppearanceChanged));

        /// <summary>
        /// The StrokeThickness property.
        /// </summary>
        public static readonly DependencyProperty StrokeThicknessProperty =
            DependencyProperty.Register(
                "StrokeThickness", typeof(double), typeof(TextAnnotation), new PropertyMetadata(1.0, AppearanceChanged));

        /// <summary>
        /// Initializes a new instance of the <see cref = "TextAnnotation" /> class.
        /// </summary>
        public TextAnnotation()
        {
            this.InternalAnnotation = new OxyPlot.Annotations.TextAnnotation();
        }

        /// <summary>
        /// Gets or sets the fill color of the background rectangle.
        /// </summary>
        public Color? Background
        {
            get
            {
                return (Color?)this.GetValue(BackgroundProperty);
            }

            set
            {
                this.SetValue(BackgroundProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the color of the text.
        /// </summary>
        public Color TextColor
        {
            get
            {
                return (Color)this.GetValue(TextColorProperty);
            }

            set
            {
                this.SetValue(TextColorProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the position offset (screen coordinates).
        /// </summary>
        public Vector Offset
        {
            get
            {
                return (Vector)this.GetValue(OffsetProperty);
            }

            set
            {
                this.SetValue(OffsetProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the padding of the background rectangle.
        /// </summary>
        public Thickness Padding
        {
            get
            {
                return (Thickness)this.GetValue(PaddingProperty);
            }

            set
            {
                this.SetValue(PaddingProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the position of the text.
        /// </summary>
        public DataPoint Position
        {
            get
            {
                return (DataPoint)this.GetValue(PositionProperty);
            }

            set
            {
                this.SetValue(PositionProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the rotation angle (degrees).
        /// </summary>
        public double Rotation
        {
            get
            {
                return (double)this.GetValue(RotationProperty);
            }

            set
            {
                this.SetValue(RotationProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the stroke color of the background rectangle.
        /// </summary>
        public Color Stroke
        {
            get
            {
                return (Color)this.GetValue(StrokeProperty);
            }

            set
            {
                this.SetValue(StrokeProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the stroke thickness of the background rectangle.
        /// </summary>
        public double StrokeThickness
        {
            get
            {
                return (double)this.GetValue(StrokeThicknessProperty);
            }

            set
            {
                this.SetValue(StrokeThicknessProperty, value);
            }
        }

        /// <summary>
        /// Creates the internal annotation object.
        /// </summary>
        /// <returns>
        /// The annotation.
        /// </returns>
        public override OxyPlot.Annotations.Annotation CreateModel()
        {
            this.SynchronizeProperties();
            return this.InternalAnnotation;
        }

        /// <summary>
        /// Synchronizes the properties.
        /// </summary>
        public override void SynchronizeProperties()
        {
            base.SynchronizeProperties();
            var a = (OxyPlot.Annotations.TextAnnotation)this.InternalAnnotation;
            a.HorizontalAlignment = this.HorizontalAlignment.ToHorizontalTextAlign();
            a.Background = this.Background.ToOxyColor();

            a.Position = this.Position;
            a.Offset = this.Offset.ToScreenVector();
            a.VerticalAlignment = this.VerticalAlignment.ToVerticalTextAlign();
            a.Padding = this.Padding.ToOxyThickness();

            a.TextColor = this.TextColor.ToOxyColor();
            a.Stroke = this.Stroke.ToOxyColor();
            a.StrokeThickness = this.StrokeThickness;

            a.Rotation = this.Rotation;
        }
    }
}


text:
package fr.paris.lutece.portal.business.resourceenhancer;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * Interface IResourceDisplayManager : enhance portlet XML or model with additionnel info
 *
 */
public interface IResourceDisplayManager
{
    /**
     * Add to the the XML String additional datas
     *
     * @param strXml
     *            The xml string use by stylesheet
     * @param strResourceType
     *            the resource type
     * @param nResourceId
     *            The resource Id
     */
    void getXmlAddOn( StringBuffer strXml, String strResourceType, int nResourceId );

    /**
     * Add datas to the model use by document template
     *
     * @param model
     *            The model use by document template
     * @param strResourceType
     *            the ressource Type
     * @param nIdResource
     *            The resource id
     * @param strPortletId
     *            The portlet ID
     * @param request
     *            The HTTP Request
     */
    void buildPageAddOn( Map<String, Object> model, String strResourceType, int nIdResource, String strPortletId, HttpServletRequest request );
}


text:
package org.hope6537.note.design.factory.mutli;

import org.hope6537.note.design.factory.human.Human;
import org.hope6537.note.design.factory.human.YellowHuman;

/**
 *
Describe: 人种的创建工厂实现

 *
Using:

 *
DevelopedTime: 2014年9月9日下午2:34:46

 *
Company: ChangChun Unviersity JiChuang Team

 *
 * @author Hope6537
 * @version 1.0
 * @see
 */
public class YellowHumanFactory extends AbstractHumanFactory {

    @Override
    public Human createHuman() {
        return new YellowHuman();
    }

}


text:
title: Java Swing
localeTitle: Java Swing
---
## Java Swing

Vamos explorar o tutorial de swing do Java. Antes de sujarmos as mãos com o Swing, é recomendável que você passe pelo [AWT (Abstract Window Toolkit). Mais](https://www.studytonight.com/java/java-awt.php) cedo, Swing foi adicionado como parte do [JFC (Java Foundation Classes)](https://en.wikipedia.org/wiki/Java_Foundation_Classes) . No entanto, ele foi totalmente mesclado no Java de Java. 1.2 em diante.

### Recursos impressionáveis

1.  Componentes leves - Como os componentes do Swing são escritos completamente em JAVA, eles não usam recursos específicos da plataforma como os componentes AWT.

2.  Olhar e sentir plugável (PLAF) - O aspecto visual e visual é inteiramente determinado pelo próprio Swing. Isso facilita a distinção entre aparência e lógica do componente.

Swing GUI consiste em dois pilares principais: -componentes e contêineres.A parte seguinte discute sobre os dois completamente.

### Componentes

Um Componente é simplesmente um controle visual independente. Os componentes de observação são derivados da classe JComponent. Além disso, o JComponent herda todas as suas características de Contêineres e Componentes do AWT. Para obter mais informações, consulte a hierarquia da classe [JComponent](https://docs.oracle.com/javase/tutorial/uiswing/components/jcomponent.html) .

### Recipientes

Todos os contêineres também são componentes. Recipientes podem incluir um ou mais componentes. Swing define dois tipos de contêineres

*   herda de JComponent - por exemplo, JFrame, JWindow, JApplet, JDialog
*   não herda de JComponent - por exemplo, JPanel

### Pacotes

O Swing é composto por um grande número de pacotes. Por favor, [leia a documentação oficial](https://docs.oracle.com/javase/7/docs/api/javax/swing/package-use.html) para mais informações.

#### Mais Informações:

*   [Docs do Oracle](https://docs.oracle.com/javase/7/docs/api/javax/swing/package-use.html)
*   [Wikipedia](https://en.wikipedia.org/wiki/Swing_(Java)


text:
export default function clearListingOnChange() {
    const context = this;

    this.controls.wrap
        .selectAll('.control-group')
        .filter(control => ['dropdown', 'subsetter'].indexOf(control.type) > -1)
        .on('change', function(d) {
            //Clear bar highlighting.
            context.svg
                .selectAll('.bar')
                .classed('selected', false)
                .style({
                    'stroke-width': '1px',
                    fill: d => context.colorScale(d.key)
                });

            //Reset listing.
            context.listing.wrap.selectAll('*').remove();
            context.listing.init(context.filtered_data);
        });
}


text:
#ifndef __included_resource_h
#define __included_resource_h

#include "unrar.h"

#include "App/binary_stream_readers.h"
#include "App/text_stream_readers.h"

class Resource
{
private:
    Data::RedBlackTree<const char *, MemMappedFile *>    m_resourceFiles;

public:
    Resource();
    ~Resource();

    void             ParseArchive             ( char const *_dataFile, char const *_password);
    BinaryReader    *GetBinaryReader          ( char const *_filename );
    SDL_Surface     *GetImage                 ( char const *_filename );
#ifdef USE_SDLMIXER
    Mix_Chunk       *GetSound                 ( char const *_filename );
#endif
    TextReader      *GetTextReader            ( char const *_filename );
    MemMappedFile   *GetUncompressedFile      ( char const *_filename );
};

#endif


text:
class SMessage;
class CGUIRender;
class String;

class CButtonUI: public CControlUI {
public:
	CButtonUI() {}
	virtual ~CButtonUI();

	virtual uint8 Init();
	uint8 Init(const int32 x, const int32 y);
	uint8 Init(const int32 x, const int32 y, Image * const defaultImg,
		Image * const onClickImg, Image * const inactiveImg = nullptr);

	void SetPosition(const int32 x, const int32 y);
	void SetText(String &newText);

	virtual bool ManageEvent(const CEvent * const ev);

	virtual void Update();
	virtual void Render();
private:
	bool MouseIsOver(const CEvent * const ev);

	int32 m_x, m_y;
	bool m_pressed;
};

#endif //!_C_BUTTON_UI_H


text:
package org.pitest.mutationtest.incremental;

import java.math.BigInteger;

import org.pitest.classinfo.ClassName;
import org.pitest.functional.Option;
import org.pitest.mutationtest.MutationStatusTestPair;
import org.pitest.mutationtest.engine.MutationIdentifier;

public interface CodeHistory {

  Option<MutationStatusTestPair> getPreviousResult(final MutationIdentifier id);

  boolean hasClassChanged(ClassName className);

  boolean hasCoverageChanged(ClassName className, BigInteger currentCoverage);

}


text:
package com.training.notessample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class DatabaseHandler extends SQLiteOpenHelper {

	private static final int DATABASE_VERSION = 1;
	private static final String DATABASE_NAME = "notes_db";
	private static final String TABLE_NOTES = "notes";
	private static final String KEY_ID = "_id";
	private static final String KEY_BODY = "body";

	private static DatabaseHandler instance;

	public synchronized static DatabaseHandler getInstance(Context context) {
		if (instance == null) {
			instance = new DatabaseHandler(context.getApplicationContext());
		}
		return instance;
	}

	private DatabaseHandler(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	// Creating Tables
	@Override
	public void onCreate(SQLiteDatabase db) {
		String CREATE_NOTES_TABLE = "CREATE TABLE " + TABLE_NOTES + "("
				+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_BODY + " TEXT" + ")";
		db.execSQL(CREATE_NOTES_TABLE);
	}

	// Upgrading database
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// Drop older table if existed
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);

		// Create tables again
		onCreate(db);
	}

	void addNote(Note note) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(KEY_BODY, note.getBody()); // note body

		// Inserting Row
		db.insert(TABLE_NOTES, null, values);
		db.close(); // Closing database connection
	}

	Note getNote(int id) {
		SQLiteDatabase db = this.getReadableDatabase();

		Cursor cursor = db.query(TABLE_NOTES,
				new String[] { KEY_ID, KEY_BODY }, KEY_ID + "=?",
				new String[] { String.valueOf(id) }, null, null, null, null);
		if (cursor != null)
			cursor.moveToFirst();

		int idColumnIndex = cursor.getColumnIndex(KEY_ID);
		int bodyColumndIndex = cursor.getColumnIndex(KEY_BODY);

		Note note = new Note(cursor.getInt(idColumnIndex),
				cursor.getString(bodyColumndIndex));

		return note;
	}

	public List<Note> getAllNotes() {
		List<Note> notesList = new ArrayList<Note>();
		String selectQuery = "SELECT  * FROM " + TABLE_NOTES;

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		int idColumnIndex = cursor.getColumnIndex(KEY_ID);
		int bodyColumnIndex = cursor.getColumnIndex(KEY_BODY);

		if (cursor.moveToFirst()) {
			do {
				int id = cursor.getInt(idColumnIndex);
				String body = cursor.getString(bodyColumnIndex);
				Note note = new Note(id, body);

				notesList.add(note);
			} while (cursor.moveToNext());
		}

		return notesList;
	}

	public int updateNote(Note note) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(KEY_BODY, note.getBody());

		return db.update(TABLE_NOTES, values, KEY_ID + " = ?",
				new String[] { String.valueOf(note.getId()) });
	}

	public void deleteNote(Note note) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.delete(TABLE_NOTES, KEY_ID + " = ?",
				new String[] { String.valueOf(note.getId()) });
		db.close();
	}

	public int getNotesCount() {
		String countQuery = "SELECT  * FROM " + TABLE_NOTES;
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.rawQuery(countQuery, null);
		cursor.close();

		return cursor.getCount();
	}

}


text:
require 'ruboty/itamae_search/actions/itamae-sonar_helper'

module Ruboty
  module ItamaeSearch
    module Actions
      class Random < Ruboty::Actions::Base
        include ItamaeSonarHelper

        def call
          message.reply(random)
        end

        private

        def random
          gem_info = call_method(:random)
          <<-EOS
name:#{gem_info[:name]}
desc:#{gem_info[:desc]}
downloads:#{gem_info[:downloads]}
rubygems_uri:#{gem_info[:rubygems_uri]}
homepage_uri:#{gem_info[:homepage_uri]}
          EOS
        end
      end
    end
  end
end


text:
from six import with_metaclass
import abc

class AbstractFailedResponse(with_metaclass(abc.ABCMeta, object)):
    @abc.abstractmethod
    def __init__(self):
        self.request = None

    def getRequest(self):
        return self.request

    def setRequest(self, request):
        self.request = request


text:
<!--
  ~ Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved.
  ~
  ~ 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.
  -->

<assembly>
    <includeBaseDirectory>true</includeBaseDirectory>
    <baseDirectory>wso2uuf-${project.version}</baseDirectory>
    <id>msf4j</id>
    <formats>
        <format>zip</format>
    </formats>

    <fileSets>
        <fileSet>
            <directory>target/wso2carbon-kernel-${carbon.kernel.version}</directory>
            <outputDirectory>.</outputDirectory>
            <excludes>
                <exclude>README.txt</exclude>
                <exclude>LICENSE.txt</exclude>
                <exclude>INSTALL.txt</exclude>
                <exclude>release-notes.html</exclude>
                <exclude>**/*.ipr</exclude>
                <exclude>**/*.iwr</exclude>
                <exclude>**/*.eclipse</exclude>
                <exclude>**/carbon.sh</exclude>
                <exclude>**/carbon.bat</exclude>
                <exclude>**/netty-transports.yml</exclude>
            </excludes>
        </fileSet>

        <fileSet>
            <directory>carbon-home/conf/transports</directory>
            <outputDirectory>conf/transports</outputDirectory>
            <fileMode>644</fileMode>
        </fileSet>

        <fileSet>
            <directory>carbon-home/bin</directory>
            <outputDirectory>bin</outputDirectory>
            <fileMode>755</fileMode>
        </fileSet>

        <fileSet>
            <directory>carbon-home/conf/osgi</directory>
            <outputDirectory>conf/wso2</outputDirectory>
            <fileMode>644</fileMode>
        </fileSet>

        <fileSet>
            <directory>carbon-home/conf/data-bridge</directory>
            <outputDirectory>conf/data-bridge</outputDirectory>
            <fileMode>644</fileMode>
        </fileSet>

        <fileSet>
            <directory>carbon-home/deployment/</directory>
            <outputDirectory>deployment/</outputDirectory>
            <fileMode>644</fileMode>
        </fileSet>

        <fileSet>
            <directory>carbon-home/resources/</directory>
            <outputDirectory>resources/</outputDirectory>
            <fileMode>644</fileMode>
        </fileSet>

        <fileSet>
            <directory>carbon-home/datasources/</directory>
            <outputDirectory>conf/datasources/</outputDirectory>
            <fileMode>644</fileMode>
        </fileSet>

        <!-- Copy the analytics setup -->
        <fileSet>
            <directory>../analytics/das-setup</directory>
            <outputDirectory>analytics/das-setup</outputDirectory>
            <excludes>
                <exclude>**/target/**</exclude>
                <exclude>**/*.iml</exclude>
                <exclude>**/*.ipr</exclude>
                <exclude>**/*.iwr</exclude>
                <exclude>**/*.eclipse</exclude>
            </excludes>
        </fileSet>
    </fileSets>

    <files>
        <file>
            <source>carbon-home/LICENSE.txt</source>
            <outputDirectory></outputDirectory>
            <fileMode>644</fileMode>
            <filtered>false</filtered>
        </file>

        <file>
            <source>carbon-home/README.txt</source>
            <outputDirectory></outputDirectory>
            <fileMode>644</fileMode>
            <filtered>false</filtered>
        </file>
    </files>
</assembly>


text:
#pragma once

#include "JavascriptEditorStyle.generated.h"

/**
 *
 */
UCLASS()
class JAVASCRIPTEDITOR_API UJavascriptEditorStyle : public UObject
{
	GENERATED_UCLASS_BODY()

public:

#if WITH_EDITOR
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FButtonStyle GetButtonStyle(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FTextBlockStyle GetTextBlockStyle(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FEditableTextStyle GetEditableTextStyle(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FEditableTextBoxStyle GetEditableTextBoxStyle(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FCheckBoxStyle GetCheckBoxStyle(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FComboBoxStyle GetComboBoxStyle(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FComboButtonStyle GetComboButtonStyle(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FMargin GetMargin(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FSlateColor GetSlateColor(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FSlateBrush GetBrush(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FLinearColor GetColor(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FVector2D GetVector(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static float GetFloat(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FSlateFontInfo GetFontStyle(const FName& StyleName);
	UFUNCTION(BlueprintCallable, Category = "Javascript")
	static FSlateSound GetSound(const FName& StyleName);
#endif

	UPROPERTY()
	FSlateColor SlateColor;

	UPROPERTY()
	FSlateBrush SlateBrush;

	UPROPERTY()
	FButtonStyle ButtonStyle;

	UPROPERTY()
	FTextBlockStyle TextBlockStyle;

	UPROPERTY()
	FEditableTextStyle EditableTextStyle;

	UPROPERTY()
	FEditableTextBoxStyle EditableTextBoxStyle;

	UPROPERTY()
	FCheckBoxStyle CheckBoxStyle;

	UPROPERTY()
	FComboBoxStyle ComboBoxStyle;

	UPROPERTY()
	FComboButtonStyle ComboButtonStyle;
};


text:
const arithmeticSearch = require('../arithmeticSearch');
const checks = require('../../checks');
const ConstantOrConstantPower = require('./ConstantOrConstantPower');
const multiplyFractionsSearch = require('../multiplyFractionsSearch');

const ChangeTypes = require('../../ChangeTypes');
const Node = require('../../node');
const NthRoot = require('../functionsSearch/nthRoot');

// Multiplies a list of nodes that are polynomial or constant power like terms.
// Returns a node.
// The polynomial nodes should *not* have coefficients. (multiplying
// coefficients is handled in collecting like terms for multiplication)
function multiplyLikeTerms(node, polynomialOnly=false) {
  if (!Node.Type.isOperator(node)) {
    return Node.Status.noChange(node);
  }
  let status;

  if (!polynomialOnly && !checks.canMultiplyLikeTermConstantNodes(node)) {
    status = arithmeticSearch(node);
    if (status.hasChanged()) {
      status.changeType = ChangeTypes.MULTIPLY_COEFFICIENTS;
      return status;
    }

    status = multiplyFractionsSearch(node);
    if (status.hasChanged()) {
      status.changeType = ChangeTypes.MULTIPLY_COEFFICIENTS;
      return status;
    }
  }

  status = multiplyPolynomialTerms(node);
  if (status.hasChanged()) {
    status.changeType = ChangeTypes.MULTIPLY_COEFFICIENTS;
    return status;
  }

  status = multiplyNthRoots(node);
  if (status.hasChanged()) {
    return status;
  }

  return Node.Status.noChange(node);
}

function multiplyNthRoots(node) {
  if (!checks.canMultiplyLikeTermsNthRoots(node)){
    return Node.Status.noChange(node);
  }

  let newNode = node.cloneDeep();

  // Array of radicands of all the nthRoot terms being multiplied
  const radicands = node.args.map(term => NthRoot.getRadicandNode(term));

  // Multiply them
  const newRadicandNode = Node.Creator.operator('*', radicands);

  // All the args at this point have the same root,
  // so we arbitrarily take the first one
  const firstArg = node.args[0];
  const rootNode = NthRoot.getRootNode(firstArg);

  newNode = Node.Creator.nthRoot(newRadicandNode, rootNode);

  return Node.Status.nodeChanged(ChangeTypes.MULTIPLY_NTH_ROOTS, node, newNode, false);
}

function multiplyPolynomialTerms(node) {
  if (!checks.canMultiplyLikeTermPolynomialNodes(node) &&
      !checks.canMultiplyLikeTermConstantNodes(node)) {
    return Node.Status.noChange(node);
  }

  const substeps = [];
  let newNode = node.cloneDeep();

  // STEP 1: If any term has no exponent, make it have exponent 1
  // e.g. x -> x^1 (this is for pedagogy reasons)
  // (this step only happens under certain conditions and later steps might
  // happen even if step 1 does not)
  let status = addOneExponent(newNode);
  if (status.hasChanged()) {
    substeps.push(status);
    newNode = Node.Status.resetChangeGroups(status.newNode);
  }

  // STEP 2: collect exponents to a single exponent sum
  // e.g. x^1 * x^3 -> x^(1+3)
  // e.g. 10^2 * 10^3 -> 10^(2+3)
  if (checks.canMultiplyLikeTermConstantNodes(node)) {
    status = collectConstantExponents(newNode);
  }
  else {
    status = collectPolynomialExponents(newNode);
  }
  substeps.push(status);
  newNode = Node.Status.resetChangeGroups(status.newNode);

  // STEP 3: add exponents together.
  // NOTE: This might not be a step if the exponents aren't all constants,
  // but this case isn't that common and can be caught in other steps.
  // e.g. x^(2+4+z)
  // TODO: handle fractions, combining and collecting like terms, etc, here
  const exponentSum = newNode.args[1].content;
  const sumStatus = arithmeticSearch(exponentSum);
  if (sumStatus.hasChanged()) {
    status = Node.Status.childChanged(newNode, sumStatus, 1);
    substeps.push(status);
    newNode = Node.Status.resetChangeGroups(status.newNode);
  }

  if (substeps.length === 1) { // possible if only step 2 happens
    return substeps[0];
  }
  else {
    return Node.Status.nodeChanged(
      ChangeTypes.MULTIPLY_POLYNOMIAL_TERMS,
      node, newNode, true, substeps);
  }
}

// Given a product of polynomial or constant terms, changes any
// term with no exponent
// into a term with an explicit exponent of 1. This is for pedagogy, and
// makes the adding exponents step clearer.
// e.g. x^2 * x -> x^2 * x^1
// e.g. 10^2 * 10 -> 10^2 * 10^1
// Returns a Node.Status object.
function addOneExponent(node) {
  const newNode = node.cloneDeep();
  let change = false;

  let changeGroup = 1;
  if (checks.canMultiplyLikeTermConstantNodes(node)) {
    newNode.args.forEach((child, i) => {
      if (Node.Type.isConstant(child)) { // true if child is a constant node, e.g 3
        const base = ConstantOrConstantPower.getBaseNode(child);
        const exponent = Node.Creator.constant(1);
        newNode.args[i] = Node.Creator.operator('^', [base, exponent]);

        newNode.args[i].changeGroup = changeGroup;
        node.args[i].changeGroup = changeGroup; // note that this is the "oldNode"

        change = true;
        changeGroup++;
      }
    });
  }
  else {
    newNode.args.forEach((child, i) => {
      const polyTerm = new Node.PolynomialTerm(child);
      if (!polyTerm.getExponentNode()) {
        newNode.args[i] = Node.Creator.polynomialTerm(
          polyTerm.getSymbolNode(),
          Node.Creator.constant(1),
          polyTerm.getCoeffNode());

        newNode.args[i].changeGroup = changeGroup;
        node.args[i].changeGroup = changeGroup; // note that this is the "oldNode"

        change = true;
        changeGroup++;
      }
    });
  }

  if (change) {
    return Node.Status.nodeChanged(
      ChangeTypes.ADD_EXPONENT_OF_ONE, node, newNode, false);
  }
  else {
    return Node.Status.noChange(node);
  }
}

// Given a product of constant terms, groups the exponents into a sum
// e.g. 10^2 * 10^3 -> 10^(2+3)
// Returns a Node.Status object.
function collectConstantExponents(node) {
  // If we're multiplying constant nodes together, they all share the same
  // base. Get that from the first node.
  const baseNode = ConstantOrConstantPower.getBaseNode(node.args[0]);
  // The new exponent will be a sum of exponents (an operation, wrapped in
  // parens) e.g. 10^(3+4+5)
  const exponentNodeList = node.args.map(
    ConstantOrConstantPower.getExponentNode);
  const newExponent = Node.Creator.parenthesis(
    Node.Creator.operator('+', exponentNodeList));
  const newNode = Node.Creator.operator('^', [baseNode, newExponent]);
  return Node.Status.nodeChanged(
    ChangeTypes.COLLECT_CONSTANT_EXPONENTS, node, newNode);
}

// Given a product of polynomial terms, groups the exponents into a sum
// e.g. x^2 * x^3 * x^1 -> x^(2 + 3 + 1)
// Returns a Node.Status object.
function collectPolynomialExponents(node) {
  const polynomialTermList = node.args.map(n => new Node.PolynomialTerm(n));

  // If we're multiplying polynomial nodes together, they all share the same
  // symbol. Get that from the first node.
  const symbolNode = polynomialTermList[0].getSymbolNode();

  // The new exponent will be a sum of exponents (an operation, wrapped in
  // parens) e.g. x^(3+4+5)
  const exponentNodeList = polynomialTermList.map(p => p.getExponentNode(true));
  const newExponent = Node.Creator.parenthesis(
    Node.Creator.operator('+', exponentNodeList));
  const newNode = Node.Creator.polynomialTerm(symbolNode, newExponent, null);
  return Node.Status.nodeChanged(
    ChangeTypes.COLLECT_POLYNOMIAL_EXPONENTS, node, newNode);
}

module.exports = multiplyLikeTerms;


text:
package benchmarks;

public class StaticDispatch {

    public static int inc(int i) {
        return i + 1;
    }
}


text:
package com.twitter.finagle.liveness

import com.twitter.conversions.DurationOps._
import com.twitter.finagle.stats.{InMemoryStatsReceiver, NullStatsReceiver}
import com.twitter.finagle.service._
import com.twitter.finagle._
import com.twitter.util._
import java.util.concurrent.TimeUnit
import org.mockito.Mockito.{times, verify, when}
import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.Answer
import org.mockito.Matchers
import org.mockito.Matchers._
import org.scalatest.FunSuite
import org.scalatestplus.mockito.MockitoSugar
import scala.util.Random

class FailureAccrualFactoryTest extends FunSuite with MockitoSugar {

  val markDeadFor = Backoff.equalJittered(5.seconds, 60.seconds)
  val markDeadForList = markDeadFor.take(6)

  def consecutiveFailures = FailureAccrualPolicy.consecutiveFailures(3, markDeadFor)

  class ExceptionWithFailureFlags(val flags: Long = FailureFlags.Empty)
      extends FailureFlags[ExceptionWithFailureFlags] {

    def copyWithFlags(newFlags: Long): ExceptionWithFailureFlags =
      new ExceptionWithFailureFlags(newFlags)
  }

  val ignorableFailures = Seq(
    Failure.ignorable("ignore me!"),
    new ExceptionWithFailureFlags(FailureFlags.Ignorable)
  )

  class Helper(failureAccrualPolicy: FailureAccrualPolicy) {
    val statsReceiver = new InMemoryStatsReceiver
    val underlyingService = mock[Service[Int, Int]]
    when(underlyingService.close(any[Time])) thenReturn Future.Done
    when(underlyingService.status) thenReturn Status.Open
    when(underlyingService(Matchers.anyInt)) thenReturn Future.exception(new Exception)

    val underlying = mock[ServiceFactory[Int, Int]]
    when(underlying.close(any[Time])) thenReturn Future.Done
    when(underlying.status) thenReturn Status.Open
    when(underlying()) thenReturn Future.value(underlyingService)

    val timer = new MockTimer

    val factory = new FailureAccrualFactory[Int, Int](
      underlying,
      failureAccrualPolicy,
      ResponseClassifier.Default,
      timer,
      statsReceiver
    )
    val service = Await.result(factory(), 5.seconds)
    verify(underlying)()
  }

  test("default policy is hybrid") {
    val faf = FailureAccrualFactory.defaultPolicy.toString
    assert(
      faf.contains("FailureAccrualPolicy.successRateWithinDuration") &&
        faf.contains("FailureAccrualPolicy.consecutiveFailures")
    )
  }

  test("a failing service should become unavailable") {
    val h = new Helper(consecutiveFailures)
    import h._

    Time.withCurrentTimeFrozen { timeControl =>
      for (i <- 0 until 3) {
        assert(factory.isAvailable)
        assert(service.isAvailable)
        intercept[Exception] {
          Await.result(service(123), 5.seconds)
        }
      }
      // Now failed

      assert(statsReceiver.counters(List("removals")) == 1)
      assert(!factory.isAvailable)
      assert(!service.isAvailable)

      verify(underlyingService, times(3))(123)
    }
  }

  test("uses ResponseClassifier for determining success") {
    val svcFactory = ServiceFactory.const {
      Service.mk { i: Int =>
        Future.exception[Int](new IllegalArgumentException(i.toString))
      }
    }
    val classifier: ResponseClassifier = {
      case ReqRep(in: Int, Throw(_)) if in < 0 => ResponseClass.Success
      case ReqRep(_, Throw(ex)) if ex.getMessage.toInt == 10 => ResponseClass.Success
    }
    val stats = new InMemoryStatsReceiver()
    val faf = new FailureAccrualFactory[Int, Int](
      underlying = svcFactory,
      policy = FailureAccrualPolicy.consecutiveFailures(1, Backoff.const(2.seconds)),
      timer = Timer.Nil,
      statsReceiver = stats,
      responseClassifier = classifier
    )
    val svc = Await.result(faf(), 5.seconds)

    // normally these are failures, but these will not trip it...
    svc(-1)
    svc(10)
    assert(stats.counter("removals")() == 0)

    // trip it.
    svc(5)
    assert(stats.counter("removals")() == 1)
  }

  ignorableFailures.foreach { ignorableFailure =>
    test(s"does not count ignorable failure ($ignorableFailure) as failure") {
      val svcFactory = ServiceFactory.const {
        Service.mk { i: Int =>
          Future.exception[Int](ignorableFailure)
        }
      }
      val stats = new InMemoryStatsReceiver()
      val faf = new FailureAccrualFactory[Int, Int](
        underlying = svcFactory,
        policy = FailureAccrualPolicy.consecutiveFailures(1, Backoff.const(2.seconds)),
        timer = Timer.Nil,
        statsReceiver = stats,
        responseClassifier = ResponseClassifier.Default
      )

      val svc = Await.result(faf(), 5.seconds)
      svc(-1)
      assert(stats.counter("removals")() == 0)
      assert(faf.isAvailable)
    }

    test(s"does not count ignorable failure ($ignorableFailure) as success") {
      var ret = Future.exception[Int](new Exception("boom!"))
      val svcFactory = ServiceFactory.const {
        Service.mk { i: Int =>
          ret
        }
      }
      val stats = new InMemoryStatsReceiver()
      val faf = new FailureAccrualFactory[Int, Int](
        underlying = svcFactory,
        policy = FailureAccrualPolicy.consecutiveFailures(3, Backoff.const(2.seconds)),
        timer = new MockTimer,
        statsReceiver = stats,
        responseClassifier = ResponseClassifier.Default
      )

      val svc = Await.result(faf(), 5.seconds)
      svc(-1)
      svc(-1)

      assert(stats.counter("removals")() == 0)
      assert(faf.isAvailable)

      ret = Future.exception[Int](ignorableFailure)

      svc(-1) // this should not be counted as a success
      assert(stats.counter("removals")() == 0)
      assert(faf.isAvailable)

      ret = Future.exception[Int](new Exception("boom!"))

      svc(-1) // Third "real" exception in a row; should trip FA

      assert(stats.counter("removals")() == 1)
      assert(!faf.isAvailable)
    }

    test(s"keeps probe open on ignorable failure ($ignorableFailure)") {
      var ret = Future.exception[Int](new Exception("boom!"))
      Time.withCurrentTimeFrozen { timeControl =>
        val svcFactory = ServiceFactory.const {
          Service.mk { i: Int =>
            ret
          }
        }
        val stats = new InMemoryStatsReceiver()
        val timer = new MockTimer
        val faf = new FailureAccrualFactory[Int, Int](
          underlying = svcFactory,
          policy = FailureAccrualPolicy.consecutiveFailures(1, Backoff.const(2.seconds)),
          timer = timer,
          statsReceiver = stats,
          responseClassifier = ResponseClassifier.Default
        )

        val svc = Await.result(faf(), 5.seconds)
        svc(-1)

        // Trip FA
        assert(stats.counter("removals")() == 1)
        assert(!faf.isAvailable)

        timeControl.advance(10.seconds)
        timer.tick()

        assert(faf.isAvailable)

        ret = Future.exception[Int](ignorableFailure)

        svc(-1)

        // ensure that the ignorable not counted as a success, but that we can still send requests
        // (ProbeOpen state)
        assert(stats.counters(List("revivals")) == 0)
        assert(stats.counter("probes")() == 1)
        assert(stats.counter("removals")() == 1)
        assert(faf.isAvailable)
      }
    }
  }

  test("a failing service should enter the probing state after the markDeadFor duration") {
    val h = new Helper(consecutiveFailures)
    import h._

    Time.withCurrentTimeFrozen { timeControl =>
      for (i <- 0 until 3) {
        intercept[Exception] {
          Await.result(service(123), 5.seconds)
        }
      }
      assert(statsReceiver.counters(List("removals")) == 1)
      assert(!factory.isAvailable)
      assert(!service.isAvailable)

      timeControl.advance(10.seconds)
      timer.tick()

      // Probing, not revived yet.
      assert(statsReceiver.counters(List("removals")) == 1)
      assert(statsReceiver.counters(List("revivals")) == 0)

      assert(factory.isAvailable)
      assert(service.isAvailable)

      // But after one bad dispatch, mark it again unhealthy.
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }
      assert(statsReceiver.counters.get(List("probes")) == Some(1))
      assert(statsReceiver.counters.get(List("removals")) == Some(1))
      assert(!factory.isAvailable)
      assert(!service.isAvailable)
    }
  }

  test("a failing service should be revived on a backoff mechanism by default") {
    val h = new Helper(consecutiveFailures)
    import h._

    Time.withCurrentTimeFrozen { timeControl =>
      when(underlyingService(456)) thenReturn Future.value(654)

      // 3 failures must occur before the service is initially removed,
      // then one failure after each re-instating
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }
      // After another failure, the service should be unavailable
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }

      for (i <- 0 until markDeadForList.length) {
        assert(statsReceiver.counters.get(List("removals")) == Some(1))
        assert(!factory.isAvailable)
        assert(!service.isAvailable)

        // Make sure the backoff follows the pattern above; after another
        // markDeadForList(i) - 1 seconds it should still be unavailable
        timeControl.advance(markDeadForList(i) - 1.second)
        timer.tick()

        assert(statsReceiver.counters.get(List("removals")) == Some(1))
        assert(!factory.isAvailable)
        assert(!service.isAvailable)

        // Now advance to + markDeadForList(i) seconds past marking dead, to equal the
        // backoff time
        timeControl.advance(1.second)
        timer.tick()

        // The service should be available for a probe
        assert(statsReceiver.counters.get(List("removals")) == Some(1))
        assert(statsReceiver.counters(List("revivals")) == 0)
        assert(factory.isAvailable)
        assert(service.isAvailable)

        // After another failure, the service should be unavailable
        intercept[Exception] {
          Await.result(service(123), 5.seconds)
        }
        val probeStat = statsReceiver.counters.get(List("probes"))
        assert(probeStat.isDefined && probeStat.get >= 1)
      }
    }
  }

  test("backoff should be 5 minutes when stream runs out") {
    val markDeadFor = Backoff.equalJittered(5.seconds, 60.seconds) take 3

    val statsReceiver = new InMemoryStatsReceiver()
    val underlyingService = mock[Service[Int, Int]]
    when(underlyingService.close(any[Time])) thenReturn Future.Done
    when(underlyingService.status) thenReturn Status.Open
    when(underlyingService(Matchers.anyInt)) thenReturn Future.exception(new Exception)

    val underlying = mock[ServiceFactory[Int, Int]]
    when(underlying.close(any[Time])) thenReturn Future.Done
    when(underlying.status) thenReturn Status.Open
    when(underlying()) thenReturn Future.value(underlyingService)

    val timer = new MockTimer

    val factory = new FailureAccrualFactory[Int, Int](
      underlying = underlying,
      policy = FailureAccrualPolicy.consecutiveFailures(3, markDeadFor),
      responseClassifier = ResponseClassifier.Default,
      timer = timer,
      statsReceiver = statsReceiver
    )
    val service = Await.result(factory())
    verify(underlying)()

    Time.withCurrentTimeFrozen { timeControl =>
      // 3 failures must occur before the service is initially removed,
      // then one failure after each re-instating
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }

      for (i <- 0 until markDeadFor.length) {
        // After another failure, the service should be unavailable
        intercept[Exception] {
          Await.result(service(123), 5.seconds)
        }

        assert(statsReceiver.counters.get(List("removals")) == Some(1))
        assert(!factory.isAvailable)
        assert(!service.isAvailable)

        // Make sure the backoff follows the pattern above; after another
        // markDeadForList(i) - 1 seconds it should still be unavailable
        timeControl.advance(markDeadFor(i) - 1.second)
        timer.tick()

        assert(statsReceiver.counters.get(List("removals")) == Some(1))
        assert(!factory.isAvailable)
        assert(!service.isAvailable)

        // Now advance to + markDeadForList(i) seconds past marking dead, to equal the
        // backoff time
        timeControl.advance(1.second)
        timer.tick()

        // The service should be available for a probe
        assert(statsReceiver.counters.get(List("removals")) == Some(1))
        assert(statsReceiver.counters(List("revivals")) == 0)
        assert(factory.isAvailable)
        assert(service.isAvailable)
      }

      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }

      // The stream of backoffs has run out, so we should be using 300 seconds
      // as the default.
      assert(!factory.isAvailable)
      assert(!service.isAvailable)

      timeControl.advance(300.seconds - 1.second)
      timer.tick()

      assert(!factory.isAvailable)
      assert(!service.isAvailable)

      timeControl.advance(1.second)
      timer.tick()

      assert(factory.isAvailable)
      assert(service.isAvailable)
    }
  }

  test("backoff time should be reset after a success") {
    val h = new Helper(consecutiveFailures)
    import h._

    Time.withCurrentTimeFrozen { timeControl =>
      when(underlyingService(456)) thenReturn Future.value(654)

      // 3 failures must occur before the service is initially removed,
      // then one failure after each probing
      for (i <- 0 until 2) {
        intercept[Exception] {
          Await.result(service(123), 5.seconds)
        }
      }

      for (i <- 0 until markDeadForList.length) {
        // After another failure, the service should be unavailable
        intercept[Exception] {
          Await.result(service(123), 5.seconds)
        }

        // Make sure the backoff follows the pattern above; after another
        // markDeadForList(i) - 1 seconds it should still be unavailable
        timeControl.advance(markDeadForList(i) - 1.second)
        timer.tick()

        // Now advance to + markDeadForList(i) seconds past marking dead, to equal the
        // backoff time
        timeControl.advance(1.second)
        timer.tick()
      }

      // Now succeed; markdead should be reset
      Await.result(service(456), 5.seconds)

      // Fail again
      for (i <- 0 until 3) {
        when(underlyingService(123)) thenReturn Future.exception(new Exception)
        intercept[Exception] {
          Await.result(service(123), 5.seconds)
        }
      }

      assert(!factory.isAvailable)
      assert(!service.isAvailable)

      timeControl.advance(markDeadForList(0))
      timer.tick()

      assert(factory.isAvailable)
      assert(service.isAvailable)
    }
  }

  test("a failing factory should be busy; done when revived") {
    Time.withCurrentTimeFrozen { tc =>
      val h = new Helper(consecutiveFailures)
      import h._

      assert(factory.status == Status.Open)
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }
      intercept[Exception] {
        Await.result(service(123))
      }
      assert(factory.status == Status.Open)
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }

      assert(factory.status == Status.Busy)

      tc.advance(10.seconds)
      timer.tick()

      assert(factory.status == Status.Open)
    }
  }

  test(
    "a failing service should only be able to accept one request after " +
      "being revived, then multiple requests after it successfully completes"
  ) {
    val h = new Helper(consecutiveFailures)
    import h._

    Time.withCurrentTimeFrozen { tc =>
      for (i <- 1 to 3) {
        intercept[Exception] {
          Await.result(service(123), 5.seconds)
        }
      }

      assert(factory.status == Status.Busy)

      tc.advance(10.seconds)
      timer.tick()

      assert(factory.status == Status.Open)

      when(underlyingService(456)).thenAnswer {
        new Answer[Future[Int]] {
          override def answer(invocation: InvocationOnMock) = {
            // The service should be busy after one request while probing
            assert(factory.status == Status.Busy)
            Future(456)
          }
        }
      }

      Await.result(service(456), 5.seconds)
      assert(factory.status == Status.Open)
    }
  }

  test("a failing service should go back to the Busy state after probing fails") {
    val h = new Helper(consecutiveFailures)
    import h._

    Time.withCurrentTimeFrozen { tc =>
      for (i <- 1 to 3) {
        intercept[Exception] {
          Await.result(service(123), 5.seconds)
        }
      }

      assert(factory.status == Status.Busy)

      tc.advance(10.seconds)
      timer.tick()

      assert(factory.status == Status.Open)

      when(underlyingService(456)).thenAnswer {
        new Answer[Future[Int]] {
          override def answer(invocation: InvocationOnMock) = {
            // The service should be busy after one request while probing
            assert(factory.status == Status.Busy)
            // Fail the probing request
            Future.exception(new Exception)
          }
        }
      }

      intercept[Exception] {
        Await.result(service(456), 5.seconds)
      }

      // Should be busy after probe fails
      assert(factory.status == Status.Busy)
    }
  }

  test("a failing service should reset failure counters after an individual success") {
    val h = new Helper(consecutiveFailures)
    import h._

    Time.withCurrentTimeFrozen { timeControl =>
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }
      assert(statsReceiver.counters.get(List("removals")) == Some(1))
      assert(!factory.isAvailable)
      assert(!service.isAvailable)

      timeControl.advance(10.seconds)
      timer.tick()

      // Probing, not revived yet.
      assert(statsReceiver.counters(List("revivals")) == 0)
      assert(statsReceiver.counters.get(List("removals")) == Some(1))
      assert(factory.isAvailable)
      assert(service.isAvailable)

      when(underlyingService(123)) thenReturn Future.value(321)
      Await.result(service(123), 5.seconds)

      // A good dispatch; revived
      assert(statsReceiver.counters.get(List("revivals")) == Some(1))
      assert(statsReceiver.counters.get(List("removals")) == Some(1))
      assert(Await.result(service(123), 5.seconds) == 321)

      assert(factory.isAvailable)
      assert(service.isAvailable)

      // Counts are now reset.
      when(underlyingService(123)) thenReturn Future.exception(new Exception)
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }
      assert(statsReceiver.counters.get(List("revivals")) == Some(1))
      assert(statsReceiver.counters.get(List("removals")) == Some(1))
      assert(factory.isAvailable)
      assert(service.isAvailable)
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }
      assert(factory.isAvailable)
      assert(service.isAvailable)
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }
      assert(statsReceiver.counters.get(List("revivals")) == Some(1))
      assert(statsReceiver.counters.get(List("removals")) == Some(2))
      assert(!factory.isAvailable)
      assert(!service.isAvailable)
    }
  }

  test("A failure during probing that does not mark dead moves back to probing") {
    val policy = new FailureAccrualPolicy {
      var markDead = true

      def recordSuccess() = ()
      def revived() = ()
      def markDeadOnFailure(): Option[Duration] = {
        if (markDead) {
          markDead = false
          Some(1.second)
        } else None
      }
    }

    val h = new Helper(policy)
    import h._

    Time.withCurrentTimeFrozen { tc =>
      // Fail a request to mark dead
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }
      assert(!factory.isAvailable)
      assert(!service.isAvailable)

      // Advance past period
      tc.advance(2.seconds)
      timer.tick()

      // Although the underlying service is failing, the policy tells us
      // we are healthy. Make sure we accept more requests to reconcile
      // with the policy.
      intercept[Exception] {
        Await.result(service(123), 5.seconds)
      }
      assert(factory.isAvailable)
      assert(service.isAvailable)
    }
  }

  class HealthyServiceHelper {
    val statsReceiver = new InMemoryStatsReceiver()
    val underlyingService = mock[Service[Int, Int]]
    when(underlyingService.close(any[Time])) thenReturn Future.Done
    when(underlyingService.status) thenReturn Status.Open
    when(underlyingService(Matchers.anyInt)) thenReturn Future.value(321)

    val underlying = mock[ServiceFactory[Int, Int]]
    when(underlying.close(any[Time])) thenReturn Future.Done
    when(underlying.status) thenReturn Status.Open
    when(underlying()) thenReturn Future.value(underlyingService)

    val factory = new FailureAccrualFactory[Int, Int](
      underlying = underlying,
      policy = FailureAccrualPolicy.consecutiveFailures(3, FailureAccrualFactory.jitteredBackoff),
      responseClassifier = ResponseClassifier.Default,
      timer = new MockTimer,
      statsReceiver = statsReceiver
    )
    val service = Await.result(factory(), 5.seconds)
    verify(underlying)()
  }

  test("a healthy service should [service] pass through underlying availability") {
    val h = new HealthyServiceHelper
    import h._

    assert(service.isAvailable)
    when(underlyingService.status) thenReturn Status.Closed
    assert(!service.isAvailable)
  }

  test("a healthy service should [factory] pass through underlying availability") {
    val h = new HealthyServiceHelper
    import h._

    assert(factory.isAvailable)
    assert(service.isAvailable)
    when(underlying.status) thenReturn Status.Closed
    assert(!factory.isAvailable)

    // This propagates to the service as well.
    assert(!service.isAvailable)

    when(underlying.status) thenReturn Status.Busy

    assert(service.status == Status.Busy)
  }

  class BrokenFactoryHelper {
    val statsReceiver = new InMemoryStatsReceiver()
    val underlying = mock[ServiceFactory[Int, Int]]
    when(underlying.close(any[Time])) thenReturn Future.Done
    when(underlying.status) thenReturn Status.Open
    val exc = new Exception("i broked :-(")
    when(underlying()) thenReturn Future.exception(exc)
    val timer = new MockTimer
    val factory = new FailureAccrualFactory[Int, Int](
      underlying,
      FailureAccrualPolicy.consecutiveFailures(3, FailureAccrualFactory.jitteredBackoff),
      ResponseClassifier.Default,
      timer,
      statsReceiver
    )
  }

  test("a broken factory should fail after the given number of tries") {
    val h = new BrokenFactoryHelper
    import h._

    Time.withCurrentTimeFrozen { timeControl =>
      for (i <- 1 to 3) {
        assert(factory.isAvailable)
        intercept[Exception] {
          Await.result(factory(), 5.seconds)
        }
      }
      assert(!factory.isAvailable)

      // Advance past period
      timeControl.advance(10.seconds)
      timer.tick()

      // Probing should fail due to factory exception. It should stop the probing and mark it dead again
      intercept[Exception] {
        Await.result(factory(), 5.seconds)
      }
      assert(statsReceiver.counters.get(List("probes")) == Some(1))
      assert(statsReceiver.counters.get(List("removals")) == Some(1))
      assert(!factory.isAvailable)
      assert(factory.status == Status.Busy)
    }
  }

  class CustomizedFactory {
    class CustomizedFailureAccrualFactory(
      underlying: ServiceFactory[Int, Int],
      failureAccrualPolicy: FailureAccrualPolicy,
      responseClassifier: ResponseClassifier,
      timer: Timer)
        extends FailureAccrualFactory[Int, Int](
          underlying,
          failureAccrualPolicy,
          responseClassifier,
          timer,
          NullStatsReceiver
        ) {
      override def isSuccess(reqRep: ReqRep): Boolean = {
        reqRep.response match {
          case Throw(_) => false
          case Return(x) => x != 321
        }
      }
    }

    val underlyingService = mock[Service[Int, Int]]
    when(underlyingService.close(any[Time])) thenReturn Future.Done
    when(underlyingService.status) thenReturn Status.Open
    when(underlyingService(Matchers.anyInt)) thenReturn Future.value(321)

    val underlying = mock[ServiceFactory[Int, Int]]
    when(underlying.close(any[Time])) thenReturn Future.Done
    when(underlying.status) thenReturn Status.Open
    when(underlying()) thenReturn Future.value(underlyingService)

    val timer = new MockTimer
    val factory = new CustomizedFailureAccrualFactory(
      underlying,
      FailureAccrualPolicy.consecutiveFailures(3, Backoff.const(5.seconds)),
      ResponseClassifier.Default,
      timer
    )
    val service = Await.result(factory(), 5.seconds)
    verify(underlying)()
  }

  test("a customized factory should become unavailable") {
    val h = new CustomizedFactory
    import h._

    Time.withCurrentTimeFrozen { timeControl =>
      assert(Await.result(service(123), 5.seconds) == 321)
      assert(Await.result(service(123), 5.seconds) == 321)
      assert(factory.isAvailable)
      assert(service.isAvailable)

      // Now fail:
      assert(Await.result(service(123), 5.seconds) == 321)
      assert(!service.isAvailable)

      verify(underlyingService, times(3))(123)
    }
  }

  test("perturbs") {
    val perturbation = 0.2f
    val duration = 1.seconds
    val rand = new Random(1)
    for (_ <- 1 to 50) {
      val d = FailureAccrualFactory.perturb(duration, perturbation, rand)()
      val diff = d.diff(duration).inUnit(TimeUnit.MILLISECONDS)
      assert(diff >= 0)
      assert(diff < 200)
    }
  }

  test("param") {
    import FailureAccrualFactory._

    val failureAccrualPolicy =
      FailureAccrualPolicy.consecutiveFailures(42, Backoff.const(10.seconds))

    val p1: Param = Param.Configured(() => failureAccrualPolicy)
    val p2: Param = Replaced(_ => ServiceFactoryWrapper.identity)
    val p3: Param = Disabled

    assert((p1 match {
      case Param.Configured(x) => x()
      case x => throw new MatchError(x)
    }) == failureAccrualPolicy)

    assert((p2 match {
      case Param.Replaced(f) => f(null)
      case x => throw new MatchError(x)
    }) == ServiceFactoryWrapper.identity)

    assert(p3 match {
      case Disabled => true
      case x => throw new MatchError(x)
    })

    val ps1: Stack.Params = Stack.Params.empty + p1
    assert(ps1.contains[Param])
    assert((ps1[Param] match {
      case Param.Configured(x) => x()
      case x => throw new MatchError(x)
    }) == failureAccrualPolicy)

    val ps2: Stack.Params = Stack.Params.empty + p2 + p1
    assert(ps2.contains[Param])
    assert((ps2[Param] match {
      case Param.Configured(x) => x()
      case x => throw new MatchError(x)
    }) == failureAccrualPolicy)

    val ps3: Stack.Params = Stack.Params.empty + p1 + p2 + p3
    assert(ps3.contains[Param])
    assert(ps3[Param] match {
      case Disabled => true
      case x => throw new MatchError(x)
    })
  }

  test("module") {
    val h = new Helper(consecutiveFailures)
    val s: Stack[ServiceFactory[Int, Int]] =
      FailureAccrualFactory
        .module[Int, Int]
        .toStack(Stack.leaf(Stack.Role("Service"), h.underlying))

    val ps: Stack.Params = Stack.Params.empty + param.Stats(h.statsReceiver)

    // disabled
    Await.ready(s.make(ps + FailureAccrualFactory.Disabled).toService(10))
    assert(!h.statsReceiver.counters.contains(Seq("failure_accrual", "removals")))

    // replaced
    Await.ready(
      s.make(ps + FailureAccrualFactory.Replaced(ServiceFactoryWrapper.identity)).toService(10)
    )
    assert(!h.statsReceiver.counters.contains(Seq("failure_accrual", "removals")))

    // configured
    Await.ready(s.make(ps + FailureAccrualFactory.Param(1, Duration.Top)).toService(10))
    assert(h.statsReceiver.counters.contains(Seq("failure_accrual", "removals")))
  }
}


text:
require 'stockboy/exceptions'
require 'stockboy/registry'
require 'stockboy/translator'

module Stockboy

  # Registry of available {Translator} classes for lookup by symbolic name in the
  # job template DSL.
  #
  module Translations
    extend Stockboy::Registry

    # Register a translator under a convenient symbolic name
    #
    # @param [Symbol] name
    #   Symbolic name of the class
    # @param [Translator, #call] callable
    #   Translator class or any callable object
    #
    def self.register(name, callable)
      if callable.respond_to?(:call) or callable < Stockboy::Translator
        @registry[name.to_sym] = callable
      else
        raise ArgumentError, "Registered translators must be callable"
      end
    end

    # Calls a named translator for the raw value
    #
    # @param [Symbol, Translator, #call] func_name
    #   Symbol representing a registered translator, or an actual translator
    # @param [SourceRecord, MappedRecord, Hash, String] context
    #   Collection of fields or the raw value to which the translation is applied
    #
    def self.translate(func_name, context)
      translator_for(:value, func_name).call(context)
    end

    # Prepare a translator for a given attribute
    #
    # @param [Symbol] attr
    #   Name of the mapped record attribute to address for translation
    # @param [Symbol, #call] lookup
    #   Symbolic translator name or callable object
    # @return [Translator] instance
    #
    def self.translator_for(attr, lookup)
      if lookup.respond_to?(:call)
        lookup
      elsif tr = self[lookup]
        tr.is_a?(Class) && tr < Stockboy::Translator ? tr.new(attr) : tr
      else
        ->(context) { context.public_send attr } # no-op
      end
    end

  end
end


text:
package com.lucidastar.hodgepodge.ui.activity.otherfeature;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.lucidastar.hodgepodge.R;
import com.mine.lucidastarutils.log.KLog;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TestBitmapActivity extends AppCompatActivity {

    @BindView(R.id.btn_getBitmapSize)
    Button mBtnGetBitmapSize;
    @BindView(R.id.tv_size)
    TextView mTvSize;
    @BindView(R.id.iv_test)
    ImageView mIvTest;
    @BindView(R.id.imageWidth)
    EditText mImageWidth;
    @BindView(R.id.imageHeight)
    EditText mImageHeight;
    @BindView((R.id.tv_phone_info))
    TextView mTvPhoneInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_bitmap);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        mTvPhoneInfo.setText("像素密度:"+getDensityDpi());
    }

    //获取占用内存大小
    public final int getByteCount(Bitmap bitmap) {
        // int result permits bitmaps up to 46,340 x 46,340
        KLog.d("getByteCount:"+bitmap.getByteCount());
        return bitmap.getRowBytes() * bitmap.getHeight();
    }

    private final float getDensityDpi(){
        return getResources().getDisplayMetrics().densityDpi;
    }

    @OnClick({R.id.btn_getBitmapSize, R.id.btn_imageSize, R.id.btn_getScreenInfo, R.id.btn_getCustomImage})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_getBitmapSize:
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.forself);
                int byteCount = getByteCount(bitmap);
//                byte[] bytes = ImageUtils.bitmap2Bytes(bitmap, Bitmap.CompressFormat.PNG);
                KLog.i("图片占用内存的大小:" + byteCount);

                mTvSize.setText("图片占用内存的大小:" + getDataSize(byteCount) + "," + imageWidthAndHeight(R.drawable.forself));
                break;

            case R.id.btn_imageSize:
                BitmapDrawable bitmapDrawable = (BitmapDrawable) mIvTest.getDrawable();
                Bitmap bitmap1 = bitmapDrawable.getBitmap();
                int byteCount1 = getByteCount(bitmap1);
                mTvSize.setText("image的图片:" + getDataSize(byteCount1));
                break;
            case R.id.btn_getScreenInfo:
                DisplayMetrics dm = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(dm);
                float width = dm.widthPixels * dm.density;
                float height = dm.heightPixels * dm.density;
                mTvSize.setText("屏幕的宽:" + dm.widthPixels + "\n屏幕的高:" + dm.heightPixels + "\n" + "密度(每平方英寸中的像素数):" + dm.density + "\n" + "密度dpi(代表每寸多少个像素点):" + dm.densityDpi + "\n" + "xdpi:" + dm.xdpi + ",ydpi:" + dm.ydpi + "\n分辨率:" + width + "*" + height);

                break;

            case R.id.btn_getCustomImage:
                int h = Integer.valueOf(mImageHeight.getText().toString());
                int w = Integer.valueOf(mImageWidth.getText().toString());
                Bitmap bitmap2 = decodeSampledBitmapFromResource(getResources(), R.drawable.forself, w, h);
                mIvTest.setImageBitmap(bitmap2);
                break;
        }
    }

    public static String getDataSize(long size) {
        if (size < 0) {
            size = 0;
        }
        DecimalFormat format = new DecimalFormat("####.00");
        if (size < 1024) {
            return size + "bytes";
        } else if (size < 1024 * 1024) {
            float kbSize = size / 1024f;
            return format.format(kbSize) + "KB";
        } else if (size < 1024 * 1024 * 1024) {
            float mbSize = size / 1024f / 1024f;
            return format.format(mbSize) + "MB";
        } else if (size < 1024 * 1024 * 1024 * 1024) {
            float gbSize = size / 1024f / 1024f / 1024f;
            return format.format(gbSize) + "GB";
        } else {
            return "size: error";
        }

    }

    public String imageWidthAndHeight(int drawId) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(getResources(), drawId, opts);
        opts.inSampleSize = 1;
        opts.inJustDecodeBounds = false;
//        Bitmap mBitmap =BitmapFactory.decodeResource(getResources(), drawId, opts);
        int width = opts.outWidth;
        int height = opts.outHeight;
        return "图片的信息:高-->" + height + ",宽-->" + width;
    }

    //先进行测量合适的宽高
    public int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    //生成想要的尺寸的图片
    public Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                         int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

}


text:
/// <reference types="react" />
import * as React from "react";
import { DiagramEngine } from "../DiagramEngine";
export interface NodeLayerProps {
    diagramEngine: DiagramEngine;
}
export interface NodeLayerState {
}
/**
 * @author Dylan Vorster
 */
export declare class NodeLayerWidget extends React.Component<NodeLayerProps, NodeLayerState> {
    constructor(props: NodeLayerProps);
    render(): React.DOMElement<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
}


text:
<!DOCTYPE html      PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:rsf="http://ponder.org.uk/rsf">
<head>
<title>Sakai RSF Portal Material Contributor</title>
<script type="text/javascript" language="JavaScript" src="../js/rsf.js"
	rsf:id="scr=contribute-script"></script>
<script type="text/javascript" language="JavaScript"
	src="../js/rsfsakaiportal.js" rsf:id="scr=contribute-script"></script>
</head>
<body>
</body>
</html>


text:
function nolazyloadingTest(test,wd,hg,imageType,articleImageType){
    //change viewport size
    this.then(function() {
        casper.viewport(wd, hg,function(){
            test.comment('Window resolution is ' + this.evaluate(function() {
                return window.innerWidth+'x'+window.innerHeight;
            }), 'DEBUG');
        });
    });
    this.then(function reload(){
        casper.addConsoleListener();

        casper.reload();
    });

    //check image properties
    this.then(function testProperties() {
        //check images & article images
        var property = 'src';
        var value;
        var element = 'section > img';
        value = [
            'images/image-'+imageType+'.jpg',
            'images/image-'+imageType+'.jpg',
            'images/image-'+imageType+'.jpg',
            'images/image-'+imageType+'.jpg',
            'images/image-'+imageType+'.jpg'
        ];
        test.assertElementCount(element,5);
        test.assertExists(element,'images are found');
        test.assertEquals(this.getElementsAttribute(element,property),value,'section images okay');

        //check for console issues
        casper.checkConsoleErrors();
        test.assertEquals(casper.issues.length,0,'Amount of client console errors is not more than 0.');

        element = 'article > img';
        value = [
            'images/image-'+articleImageType+'.jpg',
            'images/image-'+articleImageType+'.jpg',
            'images/image-'+articleImageType+'.jpg',
            'images/image-'+articleImageType+'.jpg'
        ];
        test.assertElementCount(element,4);
        test.assertExists(element,'article images are found');
        test.assertEquals(this.getElementsAttribute(element,property),value,'article images okay');

        //check for console issues
        casper.checkConsoleErrors();
        test.assertEquals(casper.issues.length,0,'Amount of client console errors is not more than 0.');

        //remove listeners
        casper.removeListener('page.error', failed);
        casper.removeListener('remote.message', failed);
    });
};

casper.test.begin('No lazy loading test', 145, function suite(test) {
    var currentURL = params.url + '/nolazyloading.html';
    casper.start(currentURL, function() {
        test.assertTitle('no lazy loading (scroll) test', "page title is okay");
    });

    casper.nolazyloadingTest = nolazyloadingTest;

    casper.then(function() {
        casper.nolazyloadingTest(test, 319, 480, 'tiny', 'tiny');
        casper.nolazyloadingTest(test, 320, 480, 'tiny', 'tiny');
        casper.nolazyloadingTest(test, 321, 480, 'tiny', 'tiny');
        casper.nolazyloadingTest(test, 479, 480, 'tiny', 'tiny');
        casper.nolazyloadingTest(test, 480, 480, 'small', 'tiny');
        casper.nolazyloadingTest(test, 481, 480, 'small', 'tiny');
        casper.nolazyloadingTest(test, 599, 480, 'small', 'tiny');
        casper.nolazyloadingTest(test, 600, 480, 'medium', 'tiny');
        casper.nolazyloadingTest(test, 601, 480, 'medium', 'tiny');
        casper.nolazyloadingTest(test, 767, 600, 'medium', 'tiny');
        casper.nolazyloadingTest(test, 768, 600, 'regular', 'tiny');
        casper.nolazyloadingTest(test, 769, 600, 'regular', 'tiny');
        casper.nolazyloadingTest(test, 1023, 768, 'regular', 'small');
        casper.nolazyloadingTest(test, 1024, 768, 'large', 'small');
        casper.nolazyloadingTest(test, 1025, 768, 'large', 'small');
        casper.nolazyloadingTest(test, 1199, 768, 'large', 'small');
        casper.nolazyloadingTest(test, 1200, 1024, 'huge', 'small');
        casper.nolazyloadingTest(test, 1201, 1024, 'huge', 'small');
    });

    //start
    casper.run(function(){
        test.done();
    });
});


text:
package com.temperance2015.onesecond;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity{

    private long firstExitTime = 0L;
    private static final int EXIT_TIME = 2000;
    private double second;
    private Button mainButton;
    private TextView secondText;
    private TextView complimentText;
    private long downTime;
    private long upTime;
    private ShareActionProvider shareActionProvider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        secondText = (TextView)findViewById(R.id.second_text);
        complimentText = (TextView)findViewById(R.id.compliment_text);
        mainButton = (Button)findViewById(R.id.main_button);
        mainButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN){
                    downTime = System.currentTimeMillis();
                    complimentText.setText("………………");
                }
                else if (event.getAction() == MotionEvent.ACTION_UP){
                    upTime = System.currentTimeMillis();
                    second = (double)(upTime-downTime)/1000;
                    secondText.setText(second+" Second");
                }
                if (second > 0.95 && second < 1.05){
                    complimentText.setText("Absolutely Fantastic!");
                }else if(second > 0.9 && second < 1.1){
                    complimentText.setText("Perfect!");
                }else if (second > 0.8 && second < 1.2){
                    complimentText.setText("Just so so");
                }else {
                    complimentText.setText("interesting");
                }
                return false;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem item = menu.findItem(R.id.action_share);
        shareActionProvider = (ShareActionProvider) item.getActionProvider();
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_share) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            share(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setShareIntent(Intent shareIntent){
        if (shareActionProvider != null){
            shareActionProvider.setShareIntent(shareIntent);
        }
    }

    private void share(Intent intent){
        intent.setType("image/");
        intent.putExtra(Intent.EXTRA_SUBJECT,"Share");
        intent.putExtra(Intent.EXTRA_TEXT, secondText.getText());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        setShareIntent(intent);
    }

    @Override
    public void onBackPressed(){
        long curTime = System.currentTimeMillis();
        if (curTime - firstExitTime < EXIT_TIME){
            finish();
        }
        else {
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            firstExitTime = curTime;
        }
    }

}


text:
#include <sys/time.h>
#include <sched.h>
#include <sys/mman.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include "bench.h"
#include "cpupol.h"
#include "rdtsc.h"

static struct bench *running_bench;

static uint64_t usec(void)
{
        struct timeval tv;
        gettimeofday(&tv, 0);
        return (uint64_t)tv.tv_sec * 1000000 + tv.tv_usec;
}

static inline void nop_pause(void)
{
        __asm __volatile("pause");
}

static inline void wmb(void)
{
        __asm__ __volatile__("sfence":::"memory");
}

static int setaffinity(int c)
{
        cpu_set_t cpuset;
        CPU_ZERO(&cpuset);
        CPU_SET(c, &cpuset);
        return sched_setaffinity(0, sizeof(cpuset), &cpuset);
}

struct bench *alloc_bench(int ncpu, int nbg)
{
        struct bench *bench;
        struct worker *worker;
        void *shmem;
        int shmem_size = sizeof(*bench) + sizeof(*worker) * ncpu;
        int i;

        /* alloc shared memory using mmap */
        shmem = mmap(0, shmem_size, PROT_READ | PROT_WRITE,
                     MAP_SHARED | MAP_ANONYMOUS, -1, 0);
        if (shmem == MAP_FAILED)
                return NULL;
        memset(shmem, 0, shmem_size);

        /* init. */
        bench = (struct bench *)shmem;
        bench->ncpu = ncpu;
        bench->nbg  = nbg;
        bench->workers = (struct worker*)(shmem + sizeof(*bench));
        for (i = 0; i < ncpu; ++i) {
                worker = &bench->workers[i];
                worker->bench = bench;
                worker->id = seq_cores[i];
		worker->is_bg = i >= (ncpu - nbg);
        }

        return bench;
}

static void sighandler(int x)
{
        running_bench->stop = 1;
}

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-result"

static void worker_main(void *arg)
{
        struct worker *worker = (struct worker*)arg;
        struct bench *bench = worker->bench;
        uint64_t s_clk = 1, s_us = 1;
        uint64_t e_clk = 0, e_us = 0;
        int err = 0;

        /* set affinity */
        setaffinity(worker->id);

        /* pre-work */
        if (bench->ops.pre_work) {
                err = bench->ops.pre_work(worker);
                if (err) goto err_out;
        }

        /* wait for start signal */
        worker->ready = 1;
        if (worker->id) {
                while (!bench->start)
                        nop_pause();
        }
	else {
		/* are all workers ready? */
		int i;
		for (i = 1; i < bench->ncpu; i++) {
			struct worker *w = &bench->workers[i];
			while (!w->ready)
				nop_pause();
		}
		/* make things more deterministic */
		sync();

		/* start performance profiling */
		if (bench->profile_start_cmd[0])
			system(bench->profile_start_cmd);

                /* ok, before running, set timer */
                if (signal(SIGALRM, sighandler) == SIG_ERR) {
                        err = errno;
                        goto err_out;
                }
                running_bench = bench;
                alarm(bench->duration);
                bench->start = 1;
                wmb();
        }

        /* start time */
        s_clk = rdtsc_beg();
        s_us = usec();

        /* main work */
        if (bench->ops.main_work) {
                err = bench->ops.main_work(worker);
                if (err && err != ENOSPC)
                        goto err_out;
        }

        /* end time */
        e_clk = rdtsc_end();
        e_us = usec();

	/* stop performance profiling */
        if (!worker->id && bench->profile_stop_cmd[0])
		system(bench->profile_stop_cmd);

        /* post-work */
        if (bench->ops.post_work)
                err = bench->ops.post_work(worker);
err_out:
        worker->ret = err;
        worker->usecs = e_us - s_us;
        wmb();
        worker->clocks = e_clk - s_clk;
}

static void wait(struct bench *bench)
{
        int i;
        for (i = 0; i < bench->ncpu; i++) {
                struct worker *w = &bench->workers[i];
                while (!w->clocks)
                        nop_pause();
        }
}

void run_bench(struct bench *bench)
{
        int i;
	for (i = 1; i < bench->ncpu; ++i) {
		/**
		 * fork() is intentionally used instead of pthread
		 * to avoid known scalability bottlenecks
		 * of linux virtual memory subsystem.
		 */
		pid_t p = fork();
		if (p < 0)
			bench->workers[i].ret = errno;
		else if (!p) {
			worker_main(&bench->workers[i]);
			exit(0);
		}
	}
	worker_main(&bench->workers[0]);
	wait(bench);
}

void report_bench(struct bench *bench, FILE *out)
{
	static char *empty_str = "";
        uint64_t total_usecs = 0;
        double   total_works = 0.0;
        double   avg_secs;
	char *profile_name, *profile_data;
        int i, n_fg_cpu;

        /* if report_bench is overloaded */
        if (bench->ops.report_bench) {
                bench->ops.report_bench(bench, out);
                return;
        }

        /* default report_bench impl. */
        for (i = 0; i < bench->ncpu; ++i) {
                struct worker *w = &bench->workers[i];
		if (w->is_bg) continue;
                total_usecs += w->usecs;
                total_works += w->works;
        }
	n_fg_cpu = bench->ncpu - bench->nbg;
        avg_secs = (double)total_usecs/(double)n_fg_cpu/1000000.0;

	/* get profiling result */
	profile_name = profile_data = empty_str;
	if (bench->profile_stat_file[0]) {
		FILE *fp = fopen(bench->profile_stat_file, "r");
		size_t len;

		if (fp) {
			profile_name = profile_data = NULL;
			getline(&profile_name, &len, fp);
			getline(&profile_data, &len, fp);
			fclose(fp);
		}
	}

        fprintf(out, "# ncpu secs works works/sec %s\n", profile_name);
        fprintf(out, "%d %f %f %f %s\n",
                n_fg_cpu, avg_secs, total_works, total_works/avg_secs, profile_data);

	if (profile_name != empty_str)
		free(profile_name);
	if (profile_data != empty_str)
		free(profile_data);
}

#pragma GCC diagnostic pop