text:
<title>Addressing Modes - GNU Compiler Collection (GCC) Internals</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="GNU Compiler Collection (GCC) Internals">
<meta name="generator" content="makeinfo 4.7">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Target-Macros.html#Target-Macros" title="Target Macros">
<link rel="prev" href="Library-Calls.html#Library-Calls" title="Library Calls">
<link rel="next" href="Anchored-Addresses.html#Anchored-Addresses" title="Anchored Addresses">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Anchored Addresses,
Previous: Library Calls,
Up: Target Macros

15.14 Addressing Modes

This is about addressing modes.

— Macro: HAVE_PRE_INCREMENT<var></var>

— Macro: HAVE_PRE_DECREMENT<var></var>

— Macro: HAVE_POST_INCREMENT<var></var>

— Macro: HAVE_POST_DECREMENT<var></var>

A C expression that is nonzero if the machine supports pre-increment,
pre-decrement, post-increment, or post-decrement addressing respectively.

— Macro: HAVE_PRE_MODIFY_DISP<var></var>

— Macro: HAVE_POST_MODIFY_DISP<var></var>

A C expression that is nonzero if the machine supports pre- or
post-address side-effect generation involving constants other than
the size of the memory operand.

— Macro: HAVE_PRE_MODIFY_REG<var></var>

— Macro: HAVE_POST_MODIFY_REG<var></var>

A C expression that is nonzero if the machine supports pre- or
post-address side-effect generation involving a register displacement.

— Macro: CONSTANT_ADDRESS_P (<var>x</var>)<var></var>

A C expression that is 1 if the RTX <var>x</var> is a constant which
is a valid address.  On most machines, this can be defined as
CONSTANT_P (<var>x</var>), but a few machines are more restrictive
in which constant addresses are supported.

— Macro: CONSTANT_P (<var>x</var>)<var></var>

CONSTANT_P, which is defined by target-independent code,
accepts integer-values expressions whose values are not explicitly
known, such as symbol_ref, label_ref, and high
expressions and const arithmetic expressions, in addition to
const_int and const_double expressions.

— Macro: MAX_REGS_PER_ADDRESS<var></var>

A number, the maximum number of registers that can appear in a valid
memory address.  Note that it is up to you to specify a value equal to
the maximum number that GO_IF_LEGITIMATE_ADDRESS would ever
accept.

— Macro: GO_IF_LEGITIMATE_ADDRESS (<var>mode, x, label</var>)<var></var>

A C compound statement with a conditional goto <var>label</var>;
executed if <var>x</var> (an RTX) is a legitimate memory address on the
target machine for a memory operand of mode <var>mode</var>.

It usually pays to define several simpler macros to serve as
subroutines for this one.  Otherwise it may be too complicated to
understand.

This macro must exist in two variants: a strict variant and a
non-strict one.  The strict variant is used in the reload pass.  It
must be defined so that any pseudo-register that has not been
allocated a hard register is considered a memory reference.  In
contexts where some kind of register is required, a pseudo-register
with no hard register must be rejected.

The non-strict variant is used in other passes.  It must be defined to
accept all pseudo-registers in every context where some kind of
register is required.

Compiler source files that want to use the strict variant of this
macro define the macro REG_OK_STRICT.  You should use an
#ifdef REG_OK_STRICT conditional to define the strict variant
in that case and the non-strict variant otherwise.

Subroutines to check for acceptable registers for various purposes (one
for base registers, one for index registers, and so on) are typically
among the subroutines used to define GO_IF_LEGITIMATE_ADDRESS.
Then only these subroutine macros need have two variants; the higher
levels of macros may be the same whether strict or not.

Normally, constant addresses which are the sum of a symbol_ref
and an integer are stored inside a const RTX to mark them as
constant.  Therefore, there is no need to recognize such sums
specifically as legitimate addresses.  Normally you would simply
recognize any const as legitimate.

Usually PRINT_OPERAND_ADDRESS is not prepared to handle constant
sums that are not marked with  const.  It assumes that a naked
plus indicates indexing.  If so, then you must reject such
naked constant sums as illegitimate addresses, so that none of them will
be given to PRINT_OPERAND_ADDRESS.

On some machines, whether a symbolic address is legitimate depends on
the section that the address refers to.  On these machines, define the
target hook TARGET_ENCODE_SECTION_INFO to store the information
into the symbol_ref, and then check for it here.  When you see a
const, you will have to look inside it to find the
symbol_ref in order to determine the section.  See Assembler Format.

— Macro: FIND_BASE_TERM (<var>x</var>)<var></var>

A C expression to determine the base term of address <var>x</var>.
This macro is used in only one place: `find_base_term' in alias.c.

It is always safe for this macro to not be defined.  It exists so
that alias analysis can understand machine-dependent addresses.

The typical use of this macro is to handle addresses containing
a label_ref or symbol_ref within an UNSPEC.

— Macro: LEGITIMIZE_ADDRESS (<var>x, oldx, mode, win</var>)<var></var>

A C compound statement that attempts to replace <var>x</var> with a valid
memory address for an operand of mode <var>mode</var>.  <var>win</var> will be a
C statement label elsewhere in the code; the macro definition may use

          GO_IF_LEGITIMATE_ADDRESS (<var>mode</var>, <var>x</var>, <var>win</var>);

to avoid further processing if the address has become legitimate.

<var>x</var> will always be the result of a call to break_out_memory_refs,
and <var>oldx</var> will be the operand that was given to that function to produce
<var>x</var>.

The code generated by this macro should not alter the substructure of
<var>x</var>.  If it transforms <var>x</var> into a more legitimate form, it
should assign <var>x</var> (which will always be a C variable) a new value.

It is not necessary for this macro to come up with a legitimate
address.  The compiler has standard ways of doing so in all cases.  In
fact, it is safe to omit this macro.  But often a
machine-dependent strategy can generate better code.

— Macro: LEGITIMIZE_RELOAD_ADDRESS (<var>x, mode, opnum, type, ind_levels, win</var>)<var></var>

A C compound statement that attempts to replace <var>x</var>, which is an address
that needs reloading, with a valid memory address for an operand of mode
<var>mode</var>.  <var>win</var> will be a C statement label elsewhere in the code.
It is not necessary to define this macro, but it might be useful for
performance reasons.

For example, on the i386, it is sometimes possible to use a single
reload register instead of two by reloading a sum of two pseudo
registers into a register.  On the other hand, for number of RISC
processors offsets are limited so that often an intermediate address
needs to be generated in order to address a stack slot.  By defining
LEGITIMIZE_RELOAD_ADDRESS appropriately, the intermediate addresses
generated for adjacent some stack slots can be made identical, and thus
be shared.

Note: This macro should be used with caution.  It is necessary
to know something of how reload works in order to effectively use this,
and it is quite easy to produce macros that build in too much knowledge
of reload internals.

Note: This macro must be able to reload an address created by a
previous invocation of this macro.  If it fails to handle such addresses
then the compiler may generate incorrect code or abort.

The macro definition should use push_reload to indicate parts that
need reloading; <var>opnum</var>, <var>type</var> and <var>ind_levels</var> are usually
suitable to be passed unaltered to push_reload.

The code generated by this macro must not alter the substructure of
<var>x</var>.  If it transforms <var>x</var> into a more legitimate form, it
should assign <var>x</var> (which will always be a C variable) a new value.
This also applies to parts that you change indirectly by calling
push_reload.

The macro definition may use strict_memory_address_p to test if
the address has become legitimate.

If you want to change only a part of <var>x</var>, one standard way of doing
this is to use copy_rtx.  Note, however, that it unshares only a
single level of rtl.  Thus, if the part to be changed is not at the
top level, you'll need to replace first the top level.
It is not necessary for this macro to come up with a legitimate
address;  but often a machine-dependent strategy can generate better code.

— Macro: GO_IF_MODE_DEPENDENT_ADDRESS (<var>addr, label</var>)<var></var>

A C statement or compound statement with a conditional goto
<var>label</var>; executed if memory address <var>x</var> (an RTX) can have
different meanings depending on the machine mode of the memory
reference it is used for or if the address is valid for some modes
but not others.

Autoincrement and autodecrement addresses typically have mode-dependent
effects because the amount of the increment or decrement is the size
of the operand being addressed.  Some machines have other mode-dependent
addresses.  Many RISC machines have no mode-dependent addresses.

You may assume that <var>addr</var> is a valid address for the machine.

— Macro: LEGITIMATE_CONSTANT_P (<var>x</var>)<var></var>

A C expression that is nonzero if <var>x</var> is a legitimate constant for
an immediate operand on the target machine.  You can assume that
<var>x</var> satisfies CONSTANT_P, so you need not check this.  In fact,
1 is a suitable definition for this macro on machines where
anything CONSTANT_P is valid.

— Target Hook: rtx TARGET_DELEGITIMIZE_ADDRESS (<var>rtx x</var>)<var></var>

This hook is used to undo the possibly obfuscating effects of the
LEGITIMIZE_ADDRESS and LEGITIMIZE_RELOAD_ADDRESS target
macros.  Some backend implementations of these macros wrap symbol
references inside an UNSPEC rtx to represent PIC or similar
addressing modes.  This target hook allows GCC's optimizers to understand
the semantics of these opaque UNSPECs by converting them back
into their original form.

— Target Hook: bool TARGET_CANNOT_FORCE_CONST_MEM (<var>rtx x</var>)<var></var>

This hook should return true if <var>x</var> is of a form that cannot (or
should not) be spilled to the constant pool.  The default version of
this hook returns false.

The primary reason to define this hook is to prevent reload from
deciding that a non-legitimate constant would be better reloaded
from the constant pool instead of spilling and reloading a register
holding the constant.  This restriction is often true of addresses
of TLS symbols for various targets.

— Target Hook: bool TARGET_USE_BLOCKS_FOR_CONSTANT_P (<var>enum machine_mode mode, rtx x</var>)<var></var>

This hook should return true if pool entries for constant <var>x</var> can
be placed in an object_block structure.  <var>mode</var> is the mode
of <var>x</var>.

The default version returns false for all constants.

— Target Hook: tree TARGET_BUILTIN_RECIPROCAL (<var>enum tree_code fn, bool tm_fn, bool sqrt</var>)<var></var>

This hook should return the DECL of a function that implements reciprocal of
the builtin function with builtin function code <var>fn</var>, or
NULL_TREE if such a function is not available.  <var>tm_fn</var> is true
when <var>fn</var> is a code of a machine-dependent builtin function.  When
<var>sqrt</var> is true, additional optimizations that apply only to the reciprocal
of a square root function are performed, and only reciprocals of sqrt
function are valid.

— Target Hook: tree TARGET_VECTORIZE_BUILTIN_MASK_FOR_LOAD (<var>void</var>)<var></var>

This hook should return the DECL of a function <var>f</var> that given an
address <var>addr</var> as an argument returns a mask <var>m</var> that can be
used to extract from two vectors the relevant data that resides in
<var>addr</var> in case <var>addr</var> is not properly aligned.

The autovectorizer, when vectorizing a load operation from an address
<var>addr</var> that may be unaligned, will generate two vector loads from
the two aligned addresses around <var>addr</var>. It then generates a
REALIGN_LOAD operation to extract the relevant data from the
two loaded vectors. The first two arguments to REALIGN_LOAD,
<var>v1</var> and <var>v2</var>, are the two vectors, each of size <var>VS</var>, and
the third argument, <var>OFF</var>, defines how the data will be extracted
from these two vectors: if <var>OFF</var> is 0, then the returned vector is
<var>v2</var>; otherwise, the returned vector is composed from the last
<var>VS</var>-<var>OFF</var> elements of <var>v1</var> concatenated to the first
<var>OFF</var> elements of <var>v2</var>.

If this hook is defined, the autovectorizer will generate a call
to <var>f</var> (using the DECL tree that this hook returns) and will
use the return value of <var>f</var> as the argument <var>OFF</var> to
REALIGN_LOAD. Therefore, the mask <var>m</var> returned by <var>f</var>
should comply with the semantics expected by REALIGN_LOAD
described above.
If this hook is not defined, then <var>addr</var> will be used as
the argument <var>OFF</var> to REALIGN_LOAD, in which case the low
log2(<var>VS</var>)-1 bits of <var>addr</var> will be considered.

— Target Hook: tree TARGET_VECTORIZE_BUILTIN_MUL_WIDEN_EVEN (<var>tree x</var>)<var></var>

This hook should return the DECL of a function <var>f</var> that implements
widening multiplication of the even elements of two input vectors of type <var>x</var>.

If this hook is defined, the autovectorizer will use it along with the
TARGET_VECTORIZE_BUILTIN_MUL_WIDEN_ODD target hook when vectorizing
widening multiplication in cases that the order of the results does not have to be
preserved (e.g. used only by a reduction computation). Otherwise, the
widen_mult_hi/lo idioms will be used.

— Target Hook: tree TARGET_VECTORIZE_BUILTIN_MUL_WIDEN_ODD (<var>tree x</var>)<var></var>

This hook should return the DECL of a function <var>f</var> that implements
widening multiplication of the odd elements of two input vectors of type <var>x</var>.

If this hook is defined, the autovectorizer will use it along with the
TARGET_VECTORIZE_BUILTIN_MUL_WIDEN_EVEN target hook when vectorizing
widening multiplication in cases that the order of the results does not have to be
preserved (e.g. used only by a reduction computation). Otherwise, the
widen_mult_hi/lo idioms will be used.

— Target Hook: tree TARGET_VECTORIZE_BUILTIN_CONVERSION (<var>enum tree_code code, tree type</var>)<var></var>

This hook should return the DECL of a function that implements conversion of the
input vector of type <var>type</var>.
If <var>type</var> is an integral type, the result of the conversion is a vector of
floating-point type of the same size.
If <var>type</var> is a floating-point type, the result of the conversion is a vector
of integral type of the same size.
<var>code</var> specifies how the conversion is to be applied
(truncation, rounding, etc.).

If this hook is defined, the autovectorizer will use the
TARGET_VECTORIZE_BUILTIN_CONVERSION target hook when vectorizing
conversion. Otherwise, it will return NULL_TREE.

— Target Hook: tree TARGET_VECTORIZE_BUILTIN_VECTORIZED_FUNCTION (<var>enum built_in_function code, tree vec_type_out, tree vec_type_in</var>)<var></var>

This hook should return the decl of a function that implements the vectorized
variant of the builtin function with builtin function code <var>code</var> or
NULL_TREE if such a function is not available.  The return type of
the vectorized function shall be of vector type <var>vec_type_out</var> and the
argument types should be <var>vec_type_in</var>.


text:
//
// Sloth: An Energy-Efficient Activity Recognition System
// Copyright 2016 Pejman Ghorbanzade <pejman@ghorbanzade.com>
// Released under the terms of MIT License
// https://github.com/ghorbanzade/sloth/blob/master/LICENSE
//

package com.ghorbanzade.sloth.cli;

import com.ghorbanzade.sloth.Config;
import com.ghorbanzade.sloth.ConfigManager;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

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

/**
 * Defines a command line interface for the Sloth program.
 *
 * @author Pejman Ghorbanzade
 * @see Instruction
 */
public final class Cli {

  private final Config cfg;
  private final History history;
  private final Scanner scanner = new Scanner(System.in, "UTF-8");
  private final Map<String, Command> commands = new HashMap<String, Command>();
  private static final Logger log = Logger.getLogger(Cli.class);

  /**
   * constructs the CLI with a set of recognizable commands.
   *
   * @param config main configuration parameters of the program
   */
  public Cli(Config config) {
    this.cfg = config;
    this.history = new History();
    this.initCommands();
  }

  /**
   * Initializes a list of commands recognized by the CLI.
   */
  private void initCommands() {
    this.commands.put("classify", new ClassifyCommand());
    this.commands.put("history", new HistoryCommand());
    this.commands.put("learn", new LearnCommand());
    this.commands.put("exit", new ExitCommand());
  }

  /**
   * Takes an instruction, converts it to a command and executes it.
   *
   * @param instruction the instruction as given by the user
   * @throws Cli.Exception if the command fails to execute user request or
   *         the user explicitly asks for termination of the program.
   */
  public void execute(Instruction instruction) throws Cli.Exception {
    try {
      Command command = this.parse(instruction);
      this.history.add(instruction);
      command.check(instruction);
      command.execute(this, instruction);
    } catch (InvalidCommandException ex) {
      // intentionally left blank
    }
  }

  /**
   * Converts user instruction to a given executable command
   *
   * @return an executable command corresponding to the given instruction
   * @throws Cli.InvalidCommandException if given command is not recognized
   */
  private Command parse(Instruction instruction)
      throws Cli.InvalidCommandException {
    String name = instruction.getName();
    if (!this.commands.containsKey(name)) {
      throw new InvalidCommandException(instruction, "command not found");
    }
    return this.commands.get(name);
  }

  /**
   * Returns an organized structure for a given user input to the CLI.
   *
   * @return an organized structure for a given user input to the CLI.
   */
  public Instruction getInstruction() {
    while (true) {
      System.out.printf(this.getPrompt());
      String str = scanner.nextLine();
      if (!str.isEmpty()) {
        Instruction instruction = new Instruction(str);
        return instruction;
      }
    }
  }

  /**
   * Returns the command line prompt.
   *
   * @return the command line prompt
   */
  public String getPrompt() {
    return "$ ";
  }

  /**
   * Returns a list of recent instructions passed to the CLI.
   *
   * @return a list of recent isntructions passed to the CLI.
   */
  public List<Map.Entry<Integer, Instruction>> getInstructions() {
    return this.history.getInstructions();
  }

  /**
   * History of a CLI is simply a list of most recent instructions given
   * by the user. The size of the list can be configured by client using
   * the
set cli.history.size
 command.
   *
   * @author Pejman Ghorbanzade
   * @see Cli
   */
  private final class History {

    private int limit;
    private int itemCounter = 1000;
    private final List<Map.Entry<Integer, Instruction>> list;

    /**
     * A history is simply a list of most recent instructions given by the user
     * to the Cli object. The list has a limited size which is determined based
     * on
cli.history.size
 paramter in the configuration file.
     */
    public History() {
      this.limit = cfg.getAsInt("cli.history.size");
      this.list = new ArrayList<Map.Entry<Integer, Instruction>>(
          this.limit
      );
    }

    /**
     * Adds a new instruciton to the list of instructions recorded in history.
     *
     * @param instruction the instruction recently executed by cli
     */
    public void add(Instruction instruction) {
      if (this.list.size() == this.limit) {
        this.list.remove(0);
      }
      this.list.add(
          new AbstractMap.SimpleImmutableEntry<Integer, Instruction>(
              this.itemCounter++, instruction
          )
      );
    }

    /**
     * Updates the number of instructions that can be saved in the history.
     *
     * @param limit the number of instructions recorded in history
     */
    public void setSize(int limit) {
      this.limit = limit;
    }

    /**
     * Returns a list of instructions stored in the history.
     *
     * @return list of instructions recorded in history
     */
    public List<Map.Entry<Integer, Instruction>> getInstructions() {
      return this.list;
    }

  }

  /**
   * The superclass of all exceptions that can occur when using the CLI.
   *
   * @author Pejman Ghorbanzade
   * @see FailedCommandException
   * @see GracefulExitException
   * @see InvalidCommandException
   */
  @SuppressWarnings("serial")
  public abstract static class Exception extends RuntimeException {

    /**
     * Logs a debug message for every exception that is thrown.
     *
     * @param level the level with which the given message should be logged
     * @param message the message to be logged for a thrown exception.
     */
    public Exception(Level level, String message) {
      log.log(level, message);
    }

  }

  /**
   * Thrown when user enters an instruction which does not correspond to
   * any command recognized by the CLI.
   *
   * @author Pejman Ghorbanzade
   */
  @SuppressWarnings("serial")
  public static final class InvalidCommandException
      extends com.ghorbanzade.sloth.cli.Cli.Exception {

    /**
     * Prepares a debug message to be logged when this exception is thrown.
     *
     * @param instruction the instruction as given by the user
     * @param message the message to be printed alongside with the instruction
     *        name.
     */
    public InvalidCommandException(Instruction instruction, String message) {
      super(Level.INFO, String.format("%s: %s", instruction, message));
    }

  }

  /**
   * Thrown when user calls the exit command from the CLI.
   *
   * @author Pejman Ghorbanzade
   */
  @SuppressWarnings("serial")
  public static final class GracefulExitException
      extends com.ghorbanzade.sloth.cli.Cli.Exception {

    /**
     * Prepares a debug message to be logged when this exception is thrown.
     */
    public GracefulExitException() {
      super(Level.DEBUG, "terminating program per user request");
    }

  }

  /**
   * Thrown when a command encounters irrecoverable error during execution.
   *
   * @author Pejman Ghorbanzade
   * @see Cli.Exception
   */
  @SuppressWarnings("serial")
  public static final class FailedCommandException
      extends com.ghorbanzade.sloth.cli.Cli.Exception {

    /**
     * Prepares a debug message to be logged when this exception is thrown.
     *
     * @param instruction the instruction that failed to successfully execute
     * @param message the message to be logged when exception is thrown
     */
    public FailedCommandException(Instruction instruction, String message) {
      super(
          Level.INFO, String.format("%s: %s", instruction.getName(), message)
      );
    }

  }

}

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.SqlServer.Server;
using System;

namespace Sql.Net.Mathematic
{
	public static class Constants
	{
		[SqlFunction()]
		public static Double Pi()
		{
			return Math.PI;
		}

		[SqlFunction()]
		public static Double E()
		{
			return Math.E;
		}
	}
}


text:
package org.apache.geronimo.interceptor;

/**
 *
 *
 *
 * @version $Rev$ $Date$
 */
public interface Interceptor {

    /**
     * Interceptor does a little work for the invocation and then invokes the next interceptor
     * in the chain.
     *
     * @param invocation the invocation for which work will be done
     * @return the result of the invocation (includes return or application Exception)
     * @throws java.lang.Throwable if a system exception occures while doing the work
     */
    InvocationResult invoke(Invocation invocation) throws Throwable;
}


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

class user extends CI_Controller {

	function __construct()
        {
		parent::__construct();
		$this->load->model('Users');
	}

	public function index($permission)
	{
		$data['list'] = $this->Users->User_List();
		$data['permission'] = $permission;
		echo json_encode($this->load->view('users/list', $data, true));
	}

	public function getUser(){
		$data['data'] = $this->Users->getUser($this->input->post());
		$response['html'] = $this->load->view('users/view_', $data, true);

		echo json_encode($response);
	}

	public function setUser(){
		$data = $this->Users->setUser($this->input->post());
		if($data  == false)
		{
			echo json_encode(false);
		}
		else
		{
			echo json_encode(true);
		}
	}

	public function lost(){
		$data = array();
		echo json_encode($this->load->view('users/lost', null, true));
	}

	public function cerrarSession(){
		$this->Users->cerrarSession();
	}

	public function editProfile(){
		$data['data'] = $this->Users->editProfile();
		$response['html'] = $this->load->view('users/profile_', $data, true);

		echo json_encode($response);
	}

	public function updateUserProfile(){
		$data = $this->Users->updateUserProfile($this->input->post());
		if($data  == false)
		{
			echo json_encode(false);
		}
		else
		{
			echo json_encode(true);
		}
	}

}


text:
package io.joern.scanners.ghidra

import io.joern.suites.GhidraQueryTestSuite

class UserInputIntoDangerousFunctionsTests extends GhidraQueryTestSuite(UserInputIntoDangerousFunctions) {

  "getenvToStrcpy query" when {
    def query = queryBundle.getenvToStrcpy()

    "executed on CPG for binary call to `strcpy`, but no call to `getenv`" should {
      "return an empty set of matched method names" in {
        buildCpgForBin("buf1.exe")
        val results = methodNamesForMatchedPoints(query)
        results shouldBe Set()
      }
    }

    "executed on CPG for binary call to `strcpy`, and call to `getenv`, but no dataflow between them" should {
      "return an empty set of matched method names" in {
        buildCpgForBin("buf2_neg.exe")
        val results = methodNamesForMatchedPoints(query)
        results shouldBe Set()
      }
    }

    "executed on CPG for binary with dataflow between `getenv` return value and `strcpy` source argument" should {
      "find main function with data flow between getenv and strcpy" in {
        buildCpgForBin("buf2.exe")
        val results = methodNamesForMatchedPoints(query)
        results shouldBe Set("main")
      }
    }
  }
}


text:
import { DEBUG } from '@glimmer/env';

let debugToString: undefined | ((value: unknown) => string);

if (DEBUG) {
  let getFunctionName = (fn: Function) => {
    let functionName = fn.name;

    if (functionName === undefined) {
      let match = Function.prototype.toString.call(fn).match(/function (\w+)\s*\(/);

      functionName = (match && match[1]) || '';
    }

    return functionName.replace(/^bound /, '');
  };

  let getObjectName = (obj: object) => {
    let name;
    let className;

    if (obj.constructor && typeof obj.constructor === 'function') {
      className = getFunctionName(obj.constructor);
    }

    if (
      'toString' in obj &&
      obj.toString !== Object.prototype.toString &&
      obj.toString !== Function.prototype.toString
    ) {
      name = obj.toString();
    }

    // If the class has a decent looking name, and the `toString` is one of the
    // default Ember toStrings, replace the constructor portion of the toString
    // with the class name. We check the length of the class name to prevent doing
    // this when the value is minified.
    if (
      name &&
      name.match(/<.*:ember\d+>/) &&
      className &&
      className[0] !== '_' &&
      className.length > 2 &&
      className !== 'Class'
    ) {
      return name.replace(/<.*:/, `<${className}:`);
    }

    return name || className;
  };

  let getPrimitiveName = (value: any) => {
    return String(value);
  };

  debugToString = (value: unknown) => {
    if (typeof value === 'function') {
      return getFunctionName(value) || `(unknown function)`;
    } else if (typeof value === 'object' && value !== null) {
      return getObjectName(value) || `(unknown object)`;
    } else {
      return getPrimitiveName(value);
    }
  };
}

export default debugToString;


text:
package hook

import (
	"context"
	"fmt"
	gotime "time"

	"github.com/sirupsen/logrus"

	"github.com/skygeario/skygear-server/pkg/auth/dependency/auth"
	"github.com/skygeario/skygear-server/pkg/auth/event"
	"github.com/skygeario/skygear-server/pkg/auth/model"
	"github.com/skygeario/skygear-server/pkg/core/authn"
	"github.com/skygeario/skygear-server/pkg/core/db"
	"github.com/skygeario/skygear-server/pkg/core/errors"
	"github.com/skygeario/skygear-server/pkg/core/logging"
	"github.com/skygeario/skygear-server/pkg/core/skyerr"
	"github.com/skygeario/skygear-server/pkg/core/time"
)

//go:generate mockgen -source=provider_impl.go -destination=provider_impl_mock_test.go -package hook

type UserProvider interface {
	Get(id string) (*model.User, error)
}

type providerImpl struct {
	Store                   Store
	Context                 context.Context
	TxContext               db.TxContext
	TimeProvider            time.Provider
	Users                   UserProvider
	Deliverer               Deliverer
	PersistentEventPayloads []event.Payload
	Logger                  *logrus.Entry

	txHooked bool
}

func NewProvider(
	ctx context.Context,
	store Store,
	txContext db.TxContext,
	timeProvider time.Provider,
	users UserProvider,
	deliverer Deliverer,
	loggerFactory logging.Factory,
) Provider {
	return &providerImpl{
		Context:      ctx,
		Store:        store,
		TxContext:    txContext,
		TimeProvider: timeProvider,
		Users:        users,
		Deliverer:    deliverer,
		Logger:       loggerFactory.NewLogger("hook"),
	}
}

func (provider *providerImpl) DispatchEvent(payload event.Payload, user *model.User) (err error) {
	var seq int64
	switch typedPayload := payload.(type) {
	case event.OperationPayload:
		if provider.Deliverer.WillDeliver(typedPayload.BeforeEventType()) {
			seq, err = provider.Store.NextSequenceNumber()
			if err != nil {
				err = errors.HandledWithMessage(err, "failed to dispatch event")
				return
			}
			event := event.NewBeforeEvent(seq, typedPayload, provider.makeContext())
			err = provider.Deliverer.DeliverBeforeEvent(event, user)
			if err != nil {
				if !skyerr.IsKind(err, WebHookDisallowed) {
					err = errors.HandledWithMessage(err, "failed to dispatch event")
				}
				return
			}

			// update payload since it may have been updated by mutations
			payload = event.Payload
		}

		provider.PersistentEventPayloads = append(provider.PersistentEventPayloads, payload)

	case event.NotificationPayload:
		provider.PersistentEventPayloads = append(provider.PersistentEventPayloads, payload)
		err = nil

	default:
		panic(fmt.Sprintf("hook: invalid event payload: %T", payload))
	}

	if !provider.txHooked {
		provider.TxContext.UseHook(provider)
		provider.txHooked = true
	}
	return
}

func (provider *providerImpl) WillCommitTx() error {
	err := provider.dispatchSyncUserEventIfNeeded()
	if err != nil {
		return err
	}

	events := []*event.Event{}
	for _, payload := range provider.PersistentEventPayloads {
		var ev *event.Event

		switch typedPayload := payload.(type) {
		case event.OperationPayload:
			if provider.Deliverer.WillDeliver(typedPayload.AfterEventType()) {
				seq, err := provider.Store.NextSequenceNumber()
				if err != nil {
					err = errors.HandledWithMessage(err, "failed to persist event")
					return err
				}
				ev = event.NewAfterEvent(seq, typedPayload, provider.makeContext())
			}

		case event.NotificationPayload:
			if provider.Deliverer.WillDeliver(typedPayload.EventType()) {
				seq, err := provider.Store.NextSequenceNumber()
				if err != nil {
					err = errors.HandledWithMessage(err, "failed to persist event")
					return err
				}
				ev = event.NewEvent(seq, typedPayload, provider.makeContext())
			}

		default:
			panic(fmt.Sprintf("hook: invalid event payload: %T", payload))
		}

		if ev == nil {
			continue
		}
		events = append(events, ev)
	}

	err = provider.Store.AddEvents(events)
	if err != nil {
		err = errors.HandledWithMessage(err, "failed to persist event")
		return err
	}
	provider.PersistentEventPayloads = nil

	return nil
}

func (provider *providerImpl) DidCommitTx() {
	// TODO(webhook): deliver persisted events
	events, _ := provider.Store.GetEventsForDelivery()
	for _, event := range events {
		err := provider.Deliverer.DeliverNonBeforeEvent(event, 60*gotime.Second)
		if err != nil {
			provider.Logger.WithError(err).Debug("Failed to dispatch event")
		}
	}
}

func (provider *providerImpl) dispatchSyncUserEventIfNeeded() error {
	userIDToSync := []string{}

	for _, payload := range provider.PersistentEventPayloads {
		if _, isOperation := payload.(event.OperationPayload); !isOperation {
			continue
		}
		if userAwarePayload, ok := payload.(event.UserAwarePayload); ok {
			userIDToSync = append(userIDToSync, userAwarePayload.UserID())
		}
	}

	for _, userID := range userIDToSync {
		user, err := provider.Users.Get(userID)
		if err != nil {
			return err
		}

		payload := event.UserSyncEvent{User: *user}
		err = provider.DispatchEvent(payload, user)
		if err != nil {
			return err
		}
	}

	return nil
}

func (provider *providerImpl) makeContext() event.Context {
	var userID *string
	var session *model.Session

	user := authn.GetUser(provider.Context)
	sess := authn.GetSession(provider.Context)
	if user == nil {
		userID = nil
		session = nil
	} else {
		userID = &user.ID
		session = sess.(auth.AuthSession).ToAPIModel()
	}

	return event.Context{
		Timestamp: provider.TimeProvider.NowUTC().Unix(),
		UserID:    userID,
		Session:   session,
	}
}


text:
//
//
// MIT License
//
// Copyright (c) 2017 Stellacore Corporation.
//
// 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.
//
//

#ifndef ro_QuadForm_INCL_
#define ro_QuadForm_INCL_

/*! \file
\brief Declarations for ro::QuadForm
*/

#include "libdat/validity.h"
#include "libro/ro.h"

#include <array>
#include <string>

namespace ro
{

/*! \brief Quadratic form representation of RO (e.g. Fundamental Matrix)

\par Example
\dontinclude testro/uQuadForm.cpp
\skip ExampleStart
\until ExampleEnd
*/

class QuadForm
{
	using Row = std::array<double, 3u>;
	using Matrix = std::array<Row, 3u>;

	Matrix theMatF;

public: // methods

	//! default null constructor
	QuadForm
		();

	//! Construct from generic RO (using tripleProductGap() operations)
	explicit
	QuadForm
		( OriPair const & roPair
		);

	//! True if instance is valid
	bool
	isValid
		() const;

	//! Matrix implementation (faster if cached) for tripleProductGap()
	double
	tripleProductGap
		( ro::PairUV const & uvPair
		) const;

	//! Descriptive information about this instance.
	std::string
	infoString
		( std::string const & title = std::string()
		) const;

}; // QuadForm

} // ro

// Inline definitions
// #include "libro/QuadForm.inl"

#endif // ro_QuadForm_INCL_


text:
<?php

namespace Skaphandrus\AppBundle\Controller;

use Skaphandrus\AppBundle\Entity\FosUser;
use Skaphandrus\AppBundle\Entity\SkPersonal;
use Skaphandrus\AppBundle\Entity\SkPhotoContest;
use Skaphandrus\AppBundle\Entity\SkPhotoContestAward;
use Skaphandrus\AppBundle\Entity\SkPhotoContestCategory;
use Skaphandrus\AppBundle\Entity\SkPhotoContestJudge;
use Skaphandrus\AppBundle\Entity\SkPhotoContestSponsor;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

/**
 * Testes controller.
 *
 */
class TestesController extends Controller {

    public function testeEmailAction() {

        $user = $this->getDoctrine()->getRepository('SkaphandrusAppBundle:FosUser')->findOneBy(array('id' => 5));

        return $this->render('SkaphandrusAppBundle:Email:content_email.html.twig', array(
                    'user' => $user,
        ));
    }

}


text:
<?php

namespace G4\CleanCore\Validator\Param;

use G4\CleanCore\Validator\Param\ParamAbstract;

class Param extends ParamAbstract
{
    public function getValue()
    {
        return $this->factory()->getValue();
    }

    private function factory(): object
    {
        $className = class_exists($this->meta['type'])
            ? $this->meta['type']
            : 'G4\CleanCore\Validator\Param\Type\\' . $this->meta['type'];
        return new $className($this->name, $this->getRequest(), $this->meta);
    }
}


text:
@class JavaUtilEventObject;
@class RAREStackPaneViewer;
@class RARETabPaneViewer;
@protocol RAREiPlatformIcon;
@protocol RAREiViewer;
@protocol RAREiWidget;

#import "JreEmulation.h"
#include "com/appnativa/rare/iFunctionCallback.h"
#include "com/appnativa/rare/ui/iEventHandler.h"
#include "java/lang/Runnable.h"

#define CCPBVCardStack_GO_DOWN 1
#define CCPBVCardStack_GO_LEFT 2
#define CCPBVCardStack_GO_RIGHT 3
#define CCPBVCardStack_GO_UP 0

@interface CCPBVCardStack : NSObject < RAREiEventHandler, RAREiFunctionCallback > {
 @public
  id<RAREiPlatformIcon> bundleIcon_;
  long long int lastKeyTime_;
  BOOL switching_;
  int flingVelocityThreshold_;
  int keyTimeThreshold_;
}

+ (int)GO_DOWN;
+ (int)GO_LEFT;
+ (int)GO_RIGHT;
+ (int)GO_UP;
+ (int)pinDigitCount;
+ (int *)pinDigitCountRef;
- (id)init;
+ (int)getPinDigitCount;
- (void)drillDownWithRAREiViewer:(id<RAREiViewer>)v;
- (void)finishedWithBoolean:(BOOL)canceled
                     withId:(id)returnValue;
- (void)goUpWithRAREiWidget:(id<RAREiWidget>)widget;
- (void)onChangeEventWithNSString:(NSString *)eventName
                  withRAREiWidget:(id<RAREiWidget>)widget
          withJavaUtilEventObject:(JavaUtilEventObject *)event;
- (void)onConfigurePinValueWithNSString:(NSString *)eventName
                        withRAREiWidget:(id<RAREiWidget>)widget
                withJavaUtilEventObject:(JavaUtilEventObject *)event;
- (void)onEventWithNSString:(NSString *)eventName
            withRAREiWidget:(id<RAREiWidget>)widget
    withJavaUtilEventObject:(JavaUtilEventObject *)event;
- (void)onFlingEventWithNSString:(NSString *)eventName
                 withRAREiWidget:(id<RAREiWidget>)widget
         withJavaUtilEventObject:(JavaUtilEventObject *)event;
- (void)onKeyUpEventWithNSString:(NSString *)eventName
                 withRAREiWidget:(id<RAREiWidget>)widget
         withJavaUtilEventObject:(JavaUtilEventObject *)event;
- (void)onTabPaneConfiguredWithNSString:(NSString *)eventName
                        withRAREiWidget:(id<RAREiWidget>)widget
                withJavaUtilEventObject:(JavaUtilEventObject *)event;
- (void)onTapEventWithNSString:(NSString *)eventName
               withRAREiWidget:(id<RAREiWidget>)widget
       withJavaUtilEventObject:(JavaUtilEventObject *)event;
- (void)goWithRAREiWidget:(id<RAREiWidget>)widget
                  withInt:(int)direction;
- (void)switchToWithRAREStackPaneViewer:(RAREStackPaneViewer *)sp
                                withInt:(int)index;
- (void)switchToWithRARETabPaneViewer:(RARETabPaneViewer *)tp
                              withInt:(int)index;
- (void)copyAllFieldsTo:(CCPBVCardStack *)other;
@end

J2OBJC_FIELD_SETTER(CCPBVCardStack, bundleIcon_, id<RAREiPlatformIcon>)

typedef CCPBVCardStack ComSparsewareBellavistaCardStack;

@interface CCPBVCardStack_$1 : NSObject < JavaLangRunnable > {
 @public
  CCPBVCardStack *this$0_;
  int val$direction_;
  RARETabPaneViewer *val$tp_;
  id<RAREiWidget> val$widget_;
  RAREStackPaneViewer *val$sp_;
}

- (void)run;
- (id)initWithCCPBVCardStack:(CCPBVCardStack *)outer$
                     withInt:(int)capture$0
       withRARETabPaneViewer:(RARETabPaneViewer *)capture$1
             withRAREiWidget:(id<RAREiWidget>)capture$2
     withRAREStackPaneViewer:(RAREStackPaneViewer *)capture$3;
@end

J2OBJC_FIELD_SETTER(CCPBVCardStack_$1, this$0_, CCPBVCardStack *)
J2OBJC_FIELD_SETTER(CCPBVCardStack_$1, val$tp_, RARETabPaneViewer *)
J2OBJC_FIELD_SETTER(CCPBVCardStack_$1, val$widget_, id<RAREiWidget>)
J2OBJC_FIELD_SETTER(CCPBVCardStack_$1, val$sp_, RAREStackPaneViewer *)

@interface CCPBVCardStack_$2 : NSObject < RAREiFunctionCallback > {
 @public
  RAREStackPaneViewer *val$sp_;
  int val$index_;
}

- (void)finishedWithBoolean:(BOOL)canceled
                     withId:(id)returnValue;
- (id)initWithRAREStackPaneViewer:(RAREStackPaneViewer *)capture$0
                          withInt:(int)capture$1;
@end

J2OBJC_FIELD_SETTER(CCPBVCardStack_$2, val$sp_, RAREStackPaneViewer *)

@interface CCPBVCardStack_$3 : NSObject < RAREiFunctionCallback > {
 @public
  RARETabPaneViewer *val$tp_;
  int val$index_;
}

- (void)finishedWithBoolean:(BOOL)canceled
                     withId:(id)returnValue;
- (id)initWithRARETabPaneViewer:(RARETabPaneViewer *)capture$0
                        withInt:(int)capture$1;
@end

J2OBJC_FIELD_SETTER(CCPBVCardStack_$3, val$tp_, RARETabPaneViewer *)

#endif // _CCPBVCardStack_H_


text:
import { Component } from '@angular/core';
@Component({
    selector: 'app-tree-antd',
    templateUrl: './tree-antd.component.html',
    styleUrls: [ './tree-antd.component.scss' ]
})
export class TreeAntdComponent {

}


text:
package org.apache.geode.tools.pulse.tests;

public class Member extends JMXBaseBean implements MemberMBean {
  private String name = null;

  public Member(String name) {
    this.name = name;
  }

  protected String getKey(String propName) {
    return "member." + name + "." + propName;
  }

  @Override
  public boolean getManager() {
    return getBoolean("manager");
  }

  @Override
  public int getTotalRegionCount() {
    // This count is built dynamically in Pulse backend and region count is maintained in
    // Cluster.Member data structure
    // return getInt("totalRegionCount");
    return 0;
  }

  @Override
  public boolean getLocator() {
    return getBoolean("locator");
  }

  @Override
  public long getTotalDiskUsage() {
    return getLong("totalDiskUsage");
  }

  @Override
  public boolean getServer() {
    return getBoolean("sever");
  }

  @Override
  public String[] getGroups() {
    return getStringArray("Groups");
  }

  @Override
  /*
   * public String[] getRedundancyZone() { return getStringArray("RedundancyZone"); }
   */
  public String getRedundancyZone() {
    return getString("RedundancyZone");
  }

  @Override
  public long getTotalFileDescriptorOpen() {
    return getLong("totalFileDescriptorOpen");
  }

  @Override
  public double getLoadAverage() {
    return getDouble("loadAverage");
  }

  @Override
  public double getDiskWritesRate() {
    return getDouble("diskWritesRate");
  }

  @Override
  public long getJVMPauses() {
    return getLong("JVMPauses");
  }

  @Override
  public long getCurrentHeapSize() {
    // return getLong("currentHeapSize");
    return getLong("UsedMemory");
  }

  @Override
  public long getMaximumHeapSize() {
    // return getLong("maximumHeapSize");
    return getLong("MaxMemory");
  }

  @Override
  public long getUsedMemory() {
    return getLong("UsedMemory");
  }

  @Override
  public long getMaxMemory() {
    return getLong("MaxMemory");
  }

  @Override
  public int getNumThreads() {
    return getInt("numThreads");
  }

  @Override
  public long getMemberUpTime() {
    return getLong("memberUpTime");
  }

  @Override
  public String getHost() {
    return getString("host");
  }

  @Override
  public long getTotalBytesOnDisk() {
    return getLong("totalBytesOnDisk");
  }

  @Override
  public double getCpuUsage() {
    return getDouble("cpuUsage");
  }

  @Override
  public String getMember() {
    return getString("member");
  }

  @Override
  public String getId() {
    return getString("id");
  }

  @Override
  public double getAverageReads() {
    return getDouble("averageReads");
  }

  @Override
  public double getAverageWrites() {
    return getDouble("averageWrites");
  }

  @Override
  public int getPort() {
    return getInt("port");
  }

  @Override
  public long getFoo() {
    return getLong("foo");
  }

  @Override
  public long getOffHeapFreeSize() {
    return getLong("OffHeapFreeSize");
  }

  @Override
  public long getOffHeapUsedSize() {
    return getLong("OffHeapUsedSize");
  }

  @Override
  public long getOffHeapFreeMemory() {
    return getLong("OffHeapFreeMemory");
  }

  @Override
  public long getOffHeapUsedMemory() {
    return getLong("OffHeapUsedMemory");
  }

  @Override
  public String getVersion() {
    return getString("Version");
  }
}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S15.9.5_A03_T1;
 * @section: 15.9.5;
 * @assertion: The Date.prototype has the property "toDateString";
 * @description: The Date.prototype has the property "toDateString";
 */

if(Date.prototype.hasOwnProperty("toDateString") !== true){
  $ERROR('#1: The Date.prototype has the property "toDateString"');
}


text:
@interface WBWebViewController ()

@property (nonatomic, strong) WBWKWebView * webView;

@end

@implementation WBWebViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"Browser";

    self.webView = [[WBWKWebView alloc] initWithFrame:self.view.bounds];
    self.webView.JSBridge.interfaceName = @"WKWebViewBridge";
    self.webView.JSBridge.readyEventName = @"WKWebViewBridgeReady";
    self.webView.JSBridge.invokeScheme = @"wkwebview-bridge://invoke";

    [self.view addSubview:self.webView];

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://apple.com"]]];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Console" style:UIBarButtonItemStylePlain target:self action:@selector(showConsole:)];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self webDebugAddContextMenuItems];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

    [self webDebugRemoveContextMenuItems];
}

- (void)showConsole:(id)sender
{
    WBWebDebugConsoleViewController * controller = [[WBWebDebugConsoleViewController alloc] initWithConsole:_webView.console];

    [self.navigationController pushViewController:controller animated:YES];
}

- (void)webDebugAddContextMenuItems
{
    UIMenuItem * item = [[UIMenuItem alloc] initWithTitle:@"Inspect Element" action:@selector(webDebugInspectCurrentSelectedElement:)];
    [[UIMenuController sharedMenuController] setMenuItems:@[item]];
}

- (void)webDebugRemoveContextMenuItems
{
    [[UIMenuController sharedMenuController] setMenuItems:nil];
}

- (void)webDebugInspectCurrentSelectedElement:(id)sender
{
    NSString * variable = @"WeiboConsoleLastSelection";

    [self.webView.console storeCurrentSelectedElementToJavaScriptVariable:variable completion:^(BOOL success) {
        if (success)
        {
            WBWebDebugConsoleViewController * consoleViewController = [[WBWebDebugConsoleViewController alloc] initWithConsole:self.webView.console];
            consoleViewController.initialCommand = variable;

            [self.navigationController pushViewController:consoleViewController animated:YES];
        }
        else
        {
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"Can not get current selected element" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alertView show];
        }
    }];
}

@end


text:
package com.example.root.monerotest.InitActivity.RestoreWallet;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.example.root.monerotest.R;

public class RestoreWalletActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.restore_wallet_activity);
    }
}


text:
package po

import (
	"bytes"
	"fmt"
	"io"
	"strconv"
	"strings"
)

// A Message is a PO file entry.
// A PO file is made up of many entries,
// each entry holding the relation between an original untranslated string
// and its corresponding translation.
//
// See http://www.gnu.org/software/gettext/manual/html_node/PO-Files.html
type Message struct {
	Comment               // Coments
	MsgContext   string   // msgctxt context
	MsgId        string   // msgid untranslated-string
	MsgIdPlural  string   // msgid_plural untranslated-string-plural
	MsgStr       string   // msgstr translated-string
	MsgStrPlural []string // msgstr[0] translated-string-case-0
}

type byMessages []Message

func (d byMessages) Len() int {
	return len(d)
}
func (d byMessages) Less(i, j int) bool {
	if d[i].Comment.less(&d[j].Comment) {
		return true
	}
	if a, b := d[i].MsgContext, d[j].MsgContext; a != b {
		return a < b
	}
	if a, b := d[i].MsgId, d[j].MsgId; a != b {
		return a < b
	}
	if a, b := d[i].MsgIdPlural, d[j].MsgIdPlural; a != b {
		return a < b
	}
	return false
}
func (d byMessages) Swap(i, j int) {
	d[i], d[j] = d[j], d[i]
}

func (p *Message) readPoEntry(r *lineReader) (err error) {
	*p = Message{}
	if err = r.skipBlankLine(); err != nil {
		return
	}
	defer func(oldPos int) {
		newPos := r.currentPos()
		if newPos != oldPos && err == io.EOF {
			err = nil
		}
	}(r.currentPos())

	if err = p.Comment.readPoComment(r); err != nil {
		return
	}
	for {
		var s string
		if s, _, err = r.currentLine(); err != nil {
			return
		}

		if p.isInvalidLine(s) {
			err = fmt.Errorf("gettext: line %d, %v", r.currentPos(), "invalid line")
			return
		}
		if reComment.MatchString(s) || reBlankLine.MatchString(s) {
			return
		}

		if err = p.readMsgContext(r); err != nil {
			return
		}
		if err = p.readMsgId(r); err != nil {
			return
		}
		if err = p.readMsgIdPlural(r); err != nil {
			return
		}
		if err = p.readMsgStrOrPlural(r); err != nil {
			return
		}
	}
}

func (p *Message) readMsgContext(r *lineReader) (err error) {
	var s string
	if s, _, err = r.currentLine(); err != nil {
		return
	}
	if !reMsgContext.MatchString(s) {
		return
	}
	p.MsgContext, err = p.readString(r)
	return
}

func (p *Message) readMsgId(r *lineReader) (err error) {
	var s string
	if s, _, err = r.currentLine(); err != nil {
		return
	}
	if !reMsgId.MatchString(s) {
		return
	}
	p.MsgId, err = p.readString(r)
	return
}

func (p *Message) readMsgIdPlural(r *lineReader) (err error) {
	var s string
	if s, _, err = r.currentLine(); err != nil {
		return
	}
	if !reMsgIdPlural.MatchString(s) {
		return
	}
	p.MsgIdPlural, err = p.readString(r)
	return
}

func (p *Message) readMsgStrOrPlural(r *lineReader) (err error) {
	var s string
	if s, _, err = r.currentLine(); err != nil {
		return
	}
	if !reMsgStr.MatchString(s) && !reMsgStrPlural.MatchString(s) {
		return
	}
	if reMsgStrPlural.MatchString(s) {
		left, right := strings.Index(s, `[`), strings.LastIndex(s, `]`)
		idx, _ := strconv.Atoi(s[left+1 : right])
		s, err = p.readString(r)
		if n := len(p.MsgStrPlural); (idx + 1) > n {
			p.MsgStrPlural = append(p.MsgStrPlural, make([]string, (idx+1)-n)...)
		}
		p.MsgStrPlural[idx] = s
	} else {
		p.MsgStr, err = p.readString(r)
	}
	return
}

func (p *Message) readString(r *lineReader) (msg string, err error) {
	var s string
	if s, _, err = r.readLine(); err != nil {
		return
	}
	msg += decodePoString(s)
	for {
		if s, _, err = r.readLine(); err != nil {
			return
		}
		if !reStringLine.MatchString(s) {
			r.unreadLine()
			break
		}
		msg += decodePoString(s)
	}
	return
}

// String returns the po format entry string.
func (p Message) String() string {
	var buf bytes.Buffer
	fmt.Fprintf(&buf, "%s", p.Comment.String())
	if p.MsgContext != "" {
		fmt.Fprintf(&buf, "msgctxt %s", encodePoString(p.MsgContext))
	}
	fmt.Fprintf(&buf, "msgid %s", encodePoString(p.MsgId))
	if p.MsgIdPlural != "" {
		fmt.Fprintf(&buf, "msgid_plural %s", encodePoString(p.MsgIdPlural))
	}
	if p.MsgStr != "" || len(p.MsgStrPlural) == 0 {
		fmt.Fprintf(&buf, "msgstr %s", encodePoString(p.MsgStr))
	}
	for i := 0; i < len(p.MsgStrPlural); i++ {
		fmt.Fprintf(&buf, "msgstr[%d] %s", i, encodePoString(p.MsgStrPlural[i]))
	}
	return buf.String()
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
	<!--
		* Licensed to the Sakai Foundation (SF) under one * or more
		contributor license agreements. See the NOTICE file * distributed with
		this work for additional information * regarding copyright ownership.
		The SF licenses this file * to you under the Apache License, Version
		2.0 (the * "License"); you may not use this file except in compliance
		* with the License. You may obtain a copy of the License at * *
		http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by
		applicable law or agreed to in writing, * software distributed under
		the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES
		OR CONDITIONS OF ANY * KIND, either express or implied. See the
		License for the * specific language governing permissions and
		limitations under the License.
	-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.sakaiproject.nakamura</groupId>
		<artifactId>base</artifactId>
		<version>1.4.0-SNAPSHOT</version>
	</parent>
	<artifactId>org.sakaiproject.nakamura.import</artifactId>
	<packaging>bundle</packaging>
	<name>Sakai Nakamura :: Sakai Import Bundle</name>
	<description>Sakai import bundle</description>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-scr-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
				<extensions>true</extensions>
				<configuration>
					<instructions>
						<Bundle-Category> sakai-nakamura </Bundle-Category>
						<Export-Package> org.sakaiproject.nakamura.api.importer </Export-Package>
						<Private-Package> org.sakaiproject.nakamura.importer.* </Private-Package>
            <Sling-Nodetypes>SLING-INF/nodetypes/types.cnd</Sling-Nodetypes>
						<Sling-Initial-Content>SLING-INF/content;overwriteProperties:=true;uninstall:=false</Sling-Initial-Content>
						<Import-Package>
							javax.xml.stream.*,
							org.codehaus.stax2.*,
							com.ctc.wstx.*,
							org.relaxng.datatype.*,
							*
						</Import-Package>
					</instructions>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<!--  sling and JCR -->
		<dependency>
			<groupId>org.apache.felix</groupId>
			<artifactId>org.apache.felix.scr.annotations</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.jackrabbit</groupId>
			<artifactId>jackrabbit-jcr-commons</artifactId>
		</dependency>
		<dependency>
		  <groupId>javax.jcr</groupId>
		  <artifactId>jcr</artifactId>
		</dependency>
		<dependency>
		  <groupId>org.apache.sling</groupId>
		  <artifactId>org.apache.sling.jcr.api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.sakaiproject.nakamura</groupId>
			<artifactId>org.sakaiproject.nakamura.files</artifactId>
			<version>1.4.0-SNAPSHOT</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.sakaiproject.nakamura</groupId>
			<artifactId>org.sakaiproject.nakamura.cluster</artifactId>
			<version>1.4.0-SNAPSHOT</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.api</artifactId>
		</dependency>
		<!-- servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
		</dependency>
		<!-- logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</dependency>
		<!--  -->
		<dependency>
			<groupId>org.sakaiproject.nakamura</groupId>
			<artifactId>org.sakaiproject.nakamura.core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.sakaiproject.nakamura</groupId>
			<artifactId>org.sakaiproject.nakamura.doc</artifactId>
			<version>1.4.0-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
		</dependency>
		<dependency>
			<groupId>org.codehaus.woodstox</groupId>
			<artifactId>stax2-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.codehaus.woodstox</groupId>
			<artifactId>woodstox-core-asl</artifactId>
			<version>4.0.7</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>relaxngDatatype</groupId>
			<artifactId>relaxngDatatype</artifactId>
			<version>20020414</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.sakaiproject.nakamura</groupId>
			<artifactId>org.sakaiproject.nakamura.testutils</artifactId>
			<version>1.4.0-SNAPSHOT</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.commons.testing</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
		</dependency>
	</dependencies>
</project>