text:
package database.serializer;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.Serializable;

import org.mapdb.Serializer;

import qora.assets.Order;

public class OrderSerializer implements Serializer<Order>, Serializable
{
	private static final long serialVersionUID = -6538913048331349777L;

	@Override
	public void serialize(DataOutput out, Order value) throws IOException
	{
		out.writeInt(value.getDataLength());
        out.write(value.toBytes());
    }

    @Override
    public Order deserialize(DataInput in, int available) throws IOException
    {
    	int length = in.readInt();
        byte[] bytes = new byte[length];
        in.readFully(bytes);
        try
        {
        	return Order.parse(bytes);
		}
        catch (Exception e)
        {
        	e.printStackTrace();
		}
		return null;
    }

    @Override
    public int fixedSize()
    {
    	return -1;
    }
}


text:
.. automodule:: pyaaf

AxFilmDescriptor
----------------

    .. autoclass:: AxFilmDescriptor
       :members:
       :undoc-members:
       :show-inheritance:

redpajama_set_name: RedPajamaGithub


text:
from robofab.world import CurrentFont,CurrentGlyph
from robofab.interface.all.dialogs import AskString

def setAnchor(g,distancia,sentido,anchorName):
    anchorName2="_"+anchorName
    for a in g.anchors:
        if a.name == anchorName or a.name == anchorName2:
            if sentido=='y':
                a.y=(a.y)+distancia
            elif sentido=='x':
                a.x=(a.x)+distancia

def moveAnchor(distancia,sentido,anchorName):
    f = CurrentFont()
    if anchorName!='':
        for g in f:
            if g.selected:
                if len(g.anchors)>0:
                    setAnchor(g,distancia,sentido,anchorName)
                else:
                    print 'No hay anchors'

        f.update()
    else:
        print "Debe declarar un nombre de anchor primero."

try: anchorName
except NameError:
    print "Debe declarar el anchor"
else:
    moveAnchor(5,'x',anchorName)


text:
package main

import (
	"bytes"
	_ "embed"
	"fmt"
	"io"

	"github.com/cilium/ebpf"
)

// loadBpf returns the embedded CollectionSpec for bpf.
func loadBpf() (*ebpf.CollectionSpec, error) {
	reader := bytes.NewReader(_BpfBytes)
	spec, err := ebpf.LoadCollectionSpecFromReader(reader)
	if err != nil {
		return nil, fmt.Errorf("can't load bpf: %w", err)
	}

	return spec, err
}

// loadBpfObjects loads bpf and converts it into a struct.
//
// The following types are suitable as obj argument:
//
//	*bpfObjects
//	*bpfPrograms
//	*bpfMaps
//
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
	spec, err := loadBpf()
	if err != nil {
		return err
	}

	return spec.LoadAndAssign(obj, opts)
}

// bpfSpecs contains maps and programs before they are loaded into the kernel.
//
// It can be passed ebpf.CollectionSpec.Assign.
type bpfSpecs struct {
	bpfProgramSpecs
	bpfMapSpecs
}

// bpfSpecs contains programs before they are loaded into the kernel.
//
// It can be passed ebpf.CollectionSpec.Assign.
type bpfProgramSpecs struct {
	MmPageAlloc *ebpf.ProgramSpec `ebpf:"mm_page_alloc"`
}

// bpfMapSpecs contains maps before they are loaded into the kernel.
//
// It can be passed ebpf.CollectionSpec.Assign.
type bpfMapSpecs struct {
	CountingMap *ebpf.MapSpec `ebpf:"counting_map"`
}

// bpfObjects contains all objects after they have been loaded into the kernel.
//
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
type bpfObjects struct {
	bpfPrograms
	bpfMaps
}

func (o *bpfObjects) Close() error {
	return _BpfClose(
		&o.bpfPrograms,
		&o.bpfMaps,
	)
}

// bpfMaps contains all maps after they have been loaded into the kernel.
//
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
type bpfMaps struct {
	CountingMap *ebpf.Map `ebpf:"counting_map"`
}

func (m *bpfMaps) Close() error {
	return _BpfClose(
		m.CountingMap,
	)
}

// bpfPrograms contains all programs after they have been loaded into the kernel.
//
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
type bpfPrograms struct {
	MmPageAlloc *ebpf.Program `ebpf:"mm_page_alloc"`
}

func (p *bpfPrograms) Close() error {
	return _BpfClose(
		p.MmPageAlloc,
	)
}

func _BpfClose(closers ...io.Closer) error {
	for _, closer := range closers {
		if err := closer.Close(); err != nil {
			return err
		}
	}
	return nil
}

// Do not access this directly.
//
//go:embed bpf_bpfel.o
var _BpfBytes []byte


text:
namespace VsChromium.Server.ProgressTracking {
  public class EnvironmentTickCountProvider : ITickCountProvider {
    public long TickCount {
      get {
        // TODO(rpaquay): Implement some logic to increment an internal counter
        // if the value rounds up.
        return System.Environment.TickCount;
      }
    }
  }
}


text:
package de.calette.mephisto3.ui;

import javafx.scene.Node;

/**
 * Common interface for panes that are used as controllable items.
 */
public interface ControllableItemPanel<T> {

  void deselect();

  void select();

  /**
   * Returns the factor used during selection scaling.
   */
  double getScaleFactor();

  /**
   * Returns the component to scale, which may differ from this component.
   */
  Node getScalingNode();

  /**
   * Delegation used for the node's user data.
   *
   * @return
   */
  T getUserData();

}


text:
#ifndef __BLACK_POINT_ESTIMATOR_TEST_H__
#define __BLACK_POINT_ESTIMATOR_TEST_H__

#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <zxing/common/GlobalHistogramBinarizer.h>

namespace zxing {
class BlackPointEstimatorTest : public CPPUNIT_NS::TestFixture {
  CPPUNIT_TEST_SUITE(BlackPointEstimatorTest);
  CPPUNIT_TEST(testBasic);
  CPPUNIT_TEST(testTooLittleRange);
  CPPUNIT_TEST_SUITE_END();

public:

protected:
  void testBasic();
  void testTooLittleRange();

private:
};
}

#endif // __BLACK_POINT_ESTIMATOR_TEST_H__


text:
package com.delix.delix;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

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

        String url = "file:///android_asset/index.html";
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        WebView view = new WebView(getApplicationContext());
        view.getSettings().setJavaScriptEnabled(true);
        // view.getSettings().setBuiltInZoomControls(true);
        view.loadUrl(url);
        setContentView(view);
        WebView.setWebContentsDebuggingEnabled(true);
        view.setWebViewClient(new WebViewClient(){

            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest url){
                return false;
            }
        });
    }
}


text:
#ifndef PVRTSTRINGHASH_H
#define PVRTSTRINGHASH_H

#include "PVRTString.h"
#include "PVRTHash.h"

/*!***********************************************************************
 @class        CPVRTStringHash
 @brief        Inherits from PVRTString to include PVRTHash functionality for
               quick string compares.
*************************************************************************/
class CPVRTStringHash
{
public:
	/*!***********************************************************************
	@brief      		Constructor
	@param[in]			_Ptr	A string
	@param[in]			_Count	Length of _Ptr
	************************************************************************/
	explicit CPVRTStringHash(const char* _Ptr, size_t _Count = CPVRTString::npos);

	/*!***********************************************************************
	@brief      		Constructor
	@param[in]			_Right	A string
	************************************************************************/
	explicit CPVRTStringHash(const CPVRTString& _Right);

	/*!***********************************************************************
	@brief      		Constructor
	************************************************************************/
	CPVRTStringHash();

	/*!***********************************************************************
	@brief      		Appends a string
	@param[in]			_Ptr	A string
	@return 			Updated string
	*************************************************************************/
	CPVRTStringHash& append(const char* _Ptr);

	/*!***********************************************************************
	@brief      		Appends a string
	@param[in]			_Str	A string
	@return 			Updated string
	*************************************************************************/
	CPVRTStringHash& append(const CPVRTString& _Str);

	/*!***********************************************************************
	@brief      		Assigns the string to the string _Ptr
	@param[in]			_Ptr A string
	@return 			Updated string
	*************************************************************************/
	CPVRTStringHash& assign(const char* _Ptr);

	/*!***********************************************************************
	@brief      		Assigns the string to the string _Str
	@param[in]			_Str A string
	@return 			Updated string
	*************************************************************************/
	CPVRTStringHash& assign(const CPVRTString& _Str);

	/*!***********************************************************************
	@brief      	== Operator. This function compares the hash values of
					the string.
	@param[in]		_Str 	A hashed string to compare with
	@return 		True if they match
	*************************************************************************/
	bool operator==(const CPVRTStringHash& _Str) const;

	/*!***********************************************************************
	@brief      	== Operator. This function performs a strcmp()
					as it's more efficient to strcmp than to hash the string
					for every comparison.
	@param[in]		_Str 	A string to compare with
	@return 		True if they match
	*************************************************************************/
	bool operator==(const char* _Str) const;

	/*!***********************************************************************
	@brief      	== Operator. This function performs a strcmp()
					as it's more efficient to strcmp than to hash the string
					for every comparison.
	@param[in]		_Str 	A string to compare with
	@return 		True if they match
	*************************************************************************/
	bool operator==(const CPVRTString& _Str) const;

	/*!***********************************************************************
	@brief      	== Operator. This function compares the hash values of
					the string.
	@param[in]		Hash 	A Hash to compare with
	@return 		True if they match
	*************************************************************************/
	bool operator==(const CPVRTHash& Hash) const;

	/*!***********************************************************************
	@brief      	!= Operator
	@param[in]		_Str 	A string to compare with
	@return 		True if they don't match
	*************************************************************************/
	bool operator!=(const CPVRTStringHash& _Str) const;

	/*!***********************************************************************
	@brief      	!= Operator. This function compares the hash values of
					the string.
	@param[in]		Hash 	A Hash to compare with
	@return 		True if they match
	*************************************************************************/
	bool operator!=(const CPVRTHash& Hash) const;

	/*!***********************************************************************
	@fn       		String
	@return 		The original string
	@brief      	Returns the original, base string.
	*************************************************************************/
	const CPVRTString& String() const;

	/*!***********************************************************************
	@brief      	Returns the hash of the base string
	@fn       		Hash
	@return 		The hash
	*************************************************************************/
	const CPVRTHash& Hash() const;

	/*!***************************************************************************
	@fn       		c_str
	@return			The original string.
	@brief      	Returns the base string as a const char*.
	*****************************************************************************/
	const char* c_str() const;

private:
	CPVRTString			m_String;
	CPVRTHash			m_Hash;
};

#endif


text:
package meter

import (
	"fmt"
	"strings"
)

type TranslationHandler struct {
	input  []Pattern
	output []string
}

func NewTranslationHandler(patterns map[string]string) *TranslationHandler {
	handler := &TranslationHandler{}

	for input, output := range patterns {
		handler.input = append(handler.input, NewPattern(input))
		handler.output = append(handler.output, output)
	}

	return handler
}

func (handler *TranslationHandler) HandleMeters(values map[string]float64) {
	for key, value := range values {
		if newKey, ok := handler.apply(key); ok {
			values[newKey] = value
		}
	}
}

func (handler *TranslationHandler) apply(key string) (string, bool) {
	for i, in := range handler.input {
		groups, ok := in.Match(key)
		if !ok {
			continue
		}

		newKey := handler.output[i]
		for i, group := range groups {
			newKey = strings.Replace(newKey, fmt.Sprintf("{%d}", i), group, -1)
		}

		return newKey, true
	}

	return key, false
}


text: I am a partial in this {{ world }} and my backend is "{{ @backend }}"


text:
module Softlayer
  module Billing
    class Item
      module User
        module Customer
          module External
            autoload :Binding, 'softlayer/billing/item/user/customer/external/binding'
          end
        end
      end
    end
  end
end


text:
from datetime import datetime, timedelta
from glob import glob
from multiprocessing import Pool as mp_Pool
import os

from RAPIDpy.inflow import run_lsm_rapid_process
from RAPIDpy.inflow.lsm_rapid_process import determine_start_end_timestep

from .imports.generate_warning_points import generate_lsm_warning_points
from .imports.helper_functions import (CaptureStdOutToLog,
                                       clean_main_logs,
                                       get_valid_watershed_list,
                                       get_watershed_subbasin_from_folder, )

from .imports.streamflow_assimilation import (compute_initial_flows_lsm,
                                              compute_seasonal_average_initial_flows_multiprocess_worker)

# ----------------------------------------------------------------------------------------
# MAIN PROCESS
# ----------------------------------------------------------------------------------------
def run_lsm_forecast_process(rapid_executable_location,
                             rapid_io_files_location,
                             lsm_forecast_location,
                             main_log_directory,
                             timedelta_between_forecasts=timedelta(seconds=12 * 3600),
                             historical_data_location="",
                             warning_flow_threshold=None):
    """
    Parameters
    ----------
    rapid_executable_location: str
        Path to RAPID executable.
    rapid_io_files_location: str
        Path ro RAPID input/output directory.
    lsm_forecast_location: str
        Path to WRF forecast directory.
    main_log_directory: str
        Path to directory to store main logs.
    timedelta_between_forecasts: :obj:`datetime.timedelta`
        Time difference between forecasts.
    historical_data_location: str, optional
        Path to return period and seasonal data.
    warning_flow_threshold: float, optional
        Minimum value for return period in m3/s to generate warning.
        Default is None.
    """
    time_begin_all = datetime.utcnow()

    log_file_path = os.path.join(
        main_log_directory,
        "spt_compute_lsm_{0}.log".format(time_begin_all.strftime("%y%m%d%H%M%S"))
    )

    with CaptureStdOutToLog(log_file_path):
        clean_main_logs(main_log_directory, prepend="spt_compute_lsm_")
        # get list of correclty formatted rapid input directories in rapid directory
        rapid_input_directories = get_valid_watershed_list(os.path.join(rapid_io_files_location, "input"))

        current_forecast_start_datetime = \
            determine_start_end_timestep(sorted(glob(os.path.join(lsm_forecast_location, "*.nc"))))[0]

        forecast_date_string = current_forecast_start_datetime.strftime("%Y%m%dt%H")
        # look for past forecast qinit
        past_forecast_date_string = (current_forecast_start_datetime - timedelta_between_forecasts).strftime("%Y%m%dt%H")
        init_file_name = 'Qinit_{0}.csv'.format(past_forecast_date_string)

        # PHASE 1: SEASONAL INITIALIZATION ON FIRST RUN
        if historical_data_location and os.path.exists(historical_data_location):
            seasonal_init_job_list = []
            # iterate over models
            for rapid_input_directory in rapid_input_directories:
                seasonal_master_watershed_input_directory = os.path.join(rapid_io_files_location, "input",
                                                                         rapid_input_directory)
                init_file_path = os.path.join(seasonal_master_watershed_input_directory, init_file_name)
                historical_watershed_directory = os.path.join(historical_data_location, rapid_input_directory)
                if os.path.exists(historical_watershed_directory):
                    seasonal_streamflow_file = glob(
                        os.path.join(historical_watershed_directory, "seasonal_average*.nc"))
                    if seasonal_streamflow_file and not os.path.exists(init_file_path):
                        seasonal_init_job_list.append((
                            seasonal_streamflow_file[0],
                            seasonal_master_watershed_input_directory,
                            init_file_path,
                        ))

            if seasonal_init_job_list:
                if len(seasonal_init_job_list) > 1:
                    seasonal_pool = mp_Pool()
                    seasonal_pool.imap(compute_seasonal_average_initial_flows_multiprocess_worker,
                                       seasonal_init_job_list,
                                       chunksize=1)
                    seasonal_pool.close()
                    seasonal_pool.join()
                else:
                    compute_seasonal_average_initial_flows_multiprocess_worker(seasonal_init_job_list[0])

        # PHASE 2: MAIN RUN
        for rapid_input_directory in rapid_input_directories:
            master_watershed_input_directory = os.path.join(rapid_io_files_location, "input",
                                                            rapid_input_directory)
            master_watershed_output_directory = os.path.join(rapid_io_files_location, 'output',
                                                             rapid_input_directory, forecast_date_string)
            watershed, subbasin = get_watershed_subbasin_from_folder(rapid_input_directory)

            # PHASE 2.1 RUN RAPID
            output_file_information = run_lsm_rapid_process(
                rapid_executable_location=rapid_executable_location,
                lsm_data_location=lsm_forecast_location,
                rapid_input_location=master_watershed_input_directory,
                rapid_output_location=master_watershed_output_directory,
                initial_flows_file=os.path.join(master_watershed_input_directory, init_file_name),
            )

            forecast_file = output_file_information[0][rapid_input_directory]['qout']
            m3_riv_file = output_file_information[0][rapid_input_directory]['m3_riv']

            try:
                os.remove(m3_riv_file)
            except OSError:
                pass

            # PHASE 2.2: GENERATE WARNINGS
            forecast_directory = os.path.join(rapid_io_files_location,
                                              'output',
                                              rapid_input_directory,
                                              forecast_date_string)

            historical_watershed_directory = os.path.join(historical_data_location, rapid_input_directory)
            if os.path.exists(historical_watershed_directory):
                return_period_files = glob(os.path.join(historical_watershed_directory, "return_period*.nc"))
                if return_period_files:
                    print("Generating warning points for {0}-{1} from {2}"
                          .format(watershed, subbasin, forecast_date_string))
                    try:
                        generate_lsm_warning_points(forecast_file,
                                                    return_period_files[0],
                                                    forecast_directory,
                                                    warning_flow_threshold)
                    except Exception as ex:
                        print(ex)
                        pass

            # PHASE 2.3: GENERATE INITIALIZATION FOR NEXT RUN
            print("Initializing flows for {0}-{1} from {2}"
                  .format(watershed, subbasin, forecast_date_string))
            try:
                compute_initial_flows_lsm(forecast_file,
                                          master_watershed_input_directory,
                                          current_forecast_start_datetime +
                                          timedelta_between_forecasts)
            except Exception as ex:
                print(ex)
                pass

        # print info to user
        time_end = datetime.utcnow()
        print("Time Begin: {0}".format(time_begin_all))
        print("Time Finish: {0}".format(time_end))
        print("TOTAL TIME: {0}".format(time_end - time_begin_all))


text:
> Get the extensions of executable file names as glob pattern or regular expression

Install with [npm](https://www.npmjs.com/)

```sh
$ npm i require-extensions --save
```

## Usage

```javascript
require.extensions.glob             // -> '.{js,coffee}'      (String)
require.extensions.regexp           // -> /(?:\.js|\.coffee)/ (RegExp)
require.extensions.regexp_string    // -> '(?:\.js|\.coffee)' (String)
```

```javascript
require('require-extensions');

var glob = require('glob');
var files = glob.sync("plugins/*" + require.extensions.glob);
// -> ['plugins/thisfile.js', 'plugins/thatfile.coffee', 'plugins/thisfile.litcoffee']

files[0].match(require.extensions.regexp);
// -> != null
```

### Functions

### [glob](index.js#L19)

return a glob pattern for `require.extensions`

### [regexp](index.js#L30)

return a new `RegExp` object that matches `require.extensions`

### [regexp_string](index.js#L43)

return a new `String` regular expression that matches `require.extensions`

## Motivation

Many libraries use a hardcoded `.js` string to discover executable file names, unfortunately leaving out other extensions that contain executable code such as `.coffee`, `.litcoffee`, and potentially others that are accessible through Node's `require.extensions` property. By making this property accessible as a glob pattern and regular expression, it will become easier to use it as a search pattern and load code that was written in other languages or dialects.

## Author

**Andreas Pizsa**

+ [github/AndreasPizsa](https://github.com/AndreasPizsa)
+ [twitter/AndreasPizsa](http://twitter.com/AndreasPizsa)

## License

Copyright © 2016 Andreas Pizsa
Released under the MIT license.

***

_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on January 21, 2016._


text:
vent.menus package
==================

Submodules
----------

vent.menus.add module
---------------------

.. automodule:: vent.menus.add
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.add\_options module
------------------------------

.. automodule:: vent.menus.add_options
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.backup module
------------------------

.. automodule:: vent.menus.backup
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.choose\_tools module
-------------------------------

.. automodule:: vent.menus.choose_tools
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.del\_instances module
--------------------------------

.. automodule:: vent.menus.del_instances
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.editor module
------------------------

.. automodule:: vent.menus.editor
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.help module
----------------------

.. automodule:: vent.menus.help
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.inventory module
---------------------------

.. automodule:: vent.menus.inventory
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.inventory\_forms module
----------------------------------

.. automodule:: vent.menus.inventory_forms
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.logs module
----------------------

.. automodule:: vent.menus.logs
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.main module
----------------------

.. automodule:: vent.menus.main
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.ntap module
----------------------

.. automodule:: vent.menus.ntap
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.services module
--------------------------

.. automodule:: vent.menus.services
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.tools module
-----------------------

.. automodule:: vent.menus.tools
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.tutorial\_forms module
---------------------------------

.. automodule:: vent.menus.tutorial_forms
    :members:
    :undoc-members:
    :show-inheritance:

vent.menus.tutorials module
---------------------------

.. automodule:: vent.menus.tutorials
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: vent.menus
    :members:
    :undoc-members:
    :show-inheritance:


text:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by CSGenerator.
// </auto-generated>
//------------------------------------------------------------------------------
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

using jsval = JSApi.jsval;

public class JSB_UnityEngine_Color
{

////////////////////// Color ///////////////////////////////////////
// constructors
public static ConstructorID constructorID0 = new ConstructorID(null, null);

static bool Color_Color1(JSVCall vc, int argc)
{
    int _this = JSApi.getObject((int)JSApi.GetType.Arg);
    JSApi.attachFinalizerObject(_this);
    --argc;

    int len = argc;
    if (len == 0)
    {
        JSMgr.addJSCSRel(_this, new UnityEngine.Color());
    }

    return true;
}

static bool Color_Color2(JSVCall vc, int argc)
{
    int _this = JSApi.getObject((int)JSApi.GetType.Arg);
    JSApi.attachFinalizerObject(_this);
    --argc;

    int len = argc;
    if (len == 4)
    {
        System.Single arg0 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        System.Single arg1 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        System.Single arg2 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        System.Single arg3 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        JSMgr.addJSCSRel(_this, new UnityEngine.Color(arg0, arg1, arg2, arg3));
    }

    return true;
}

static bool Color_Color3(JSVCall vc, int argc)
{
    int _this = JSApi.getObject((int)JSApi.GetType.Arg);
    JSApi.attachFinalizerObject(_this);
    --argc;

    int len = argc;
    if (len == 3)
    {
        System.Single arg0 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        System.Single arg1 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        System.Single arg2 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        JSMgr.addJSCSRel(_this, new UnityEngine.Color(arg0, arg1, arg2));
    }

    return true;
}

// fields
static void Color_r(JSVCall vc)
{
    if (vc.bGet) {
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        var result = _this.r;
                JSApi.setSingle((int)JSApi.SetType.Rval, (System.Single)(result));
    }
    else {
        System.Single arg0 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        _this.r = arg0;
        JSMgr.changeJSObj(vc.jsObjID, _this);
    }
}
static void Color_g(JSVCall vc)
{
    if (vc.bGet) {
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        var result = _this.g;
                JSApi.setSingle((int)JSApi.SetType.Rval, (System.Single)(result));
    }
    else {
        System.Single arg0 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        _this.g = arg0;
        JSMgr.changeJSObj(vc.jsObjID, _this);
    }
}
static void Color_b(JSVCall vc)
{
    if (vc.bGet) {
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        var result = _this.b;
                JSApi.setSingle((int)JSApi.SetType.Rval, (System.Single)(result));
    }
    else {
        System.Single arg0 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        _this.b = arg0;
        JSMgr.changeJSObj(vc.jsObjID, _this);
    }
}
static void Color_a(JSVCall vc)
{
    if (vc.bGet) {
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        var result = _this.a;
                JSApi.setSingle((int)JSApi.SetType.Rval, (System.Single)(result));
    }
    else {
        System.Single arg0 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        _this.a = arg0;
        JSMgr.changeJSObj(vc.jsObjID, _this);
    }
}

// properties
static void Color_red(JSVCall vc)
{
        var result = UnityEngine.Color.red;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void Color_green(JSVCall vc)
{
        var result = UnityEngine.Color.green;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void Color_blue(JSVCall vc)
{
        var result = UnityEngine.Color.blue;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void Color_white(JSVCall vc)
{
        var result = UnityEngine.Color.white;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void Color_black(JSVCall vc)
{
        var result = UnityEngine.Color.black;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void Color_yellow(JSVCall vc)
{
        var result = UnityEngine.Color.yellow;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void Color_cyan(JSVCall vc)
{
        var result = UnityEngine.Color.cyan;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void Color_magenta(JSVCall vc)
{
        var result = UnityEngine.Color.magenta;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void Color_gray(JSVCall vc)
{
        var result = UnityEngine.Color.gray;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void Color_grey(JSVCall vc)
{
        var result = UnityEngine.Color.grey;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void Color_clear(JSVCall vc)
{
        var result = UnityEngine.Color.clear;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void Color_grayscale(JSVCall vc)
{
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        var result = _this.grayscale;
                JSApi.setSingle((int)JSApi.SetType.Rval, (System.Single)(result));
}
static void Color_linear(JSVCall vc)
{
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        var result = _this.linear;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void Color_gamma(JSVCall vc)
{
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        var result = _this.gamma;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void Color_maxColorComponent(JSVCall vc)
{
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        var result = _this.maxColorComponent;
                JSApi.setSingle((int)JSApi.SetType.Rval, (System.Single)(result));
}
static void Color_Item_Int32(JSVCall vc)
{
        System.Int32 arg0 = (System.Int32)JSApi.getInt32((int)JSApi.GetType.Arg);
    if (vc.bGet)
    {
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        var result = _this[arg0];
                JSApi.setSingle((int)JSApi.SetType.Rval, (System.Single)(result));
    }
    else
    {
        System.Single arg1 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        UnityEngine.Color _this = (UnityEngine.Color)vc.csObj;
        _this[arg0] = arg1;
        JSMgr.changeJSObj(vc.jsObjID, _this);
    }
}

// methods

static bool Color_Equals__Object(JSVCall vc, int argc)
{
    int len = argc;
    if (len == 1)
    {
        System.Object arg0 = (System.Object)JSMgr.datax.getWhatever((int)JSApi.GetType.Arg);
UnityEngine.Color argThis = (UnityEngine.Color)vc.csObj;                JSApi.setBooleanS((int)JSApi.SetType.Rval, (System.Boolean)(argThis.Equals(arg0)));
        JSMgr.changeJSObj(vc.jsObjID, argThis);
    }

    return true;
}

static bool Color_GetHashCode(JSVCall vc, int argc)
{
    int len = argc;
    if (len == 0)
    {
UnityEngine.Color argThis = (UnityEngine.Color)vc.csObj;                JSApi.setInt32((int)JSApi.SetType.Rval, (System.Int32)(argThis.GetHashCode()));
        JSMgr.changeJSObj(vc.jsObjID, argThis);
    }

    return true;
}

static bool Color_ToString__String(JSVCall vc, int argc)
{
    int len = argc;
    if (len == 1)
    {
        System.String arg0 = (System.String)JSApi.getStringS((int)JSApi.GetType.Arg);
UnityEngine.Color argThis = (UnityEngine.Color)vc.csObj;                JSApi.setStringS((int)JSApi.SetType.Rval, argThis.ToString(arg0));
        JSMgr.changeJSObj(vc.jsObjID, argThis);
    }

    return true;
}

static bool Color_ToString(JSVCall vc, int argc)
{
    int len = argc;
    if (len == 0)
    {
UnityEngine.Color argThis = (UnityEngine.Color)vc.csObj;                JSApi.setStringS((int)JSApi.SetType.Rval, argThis.ToString());
        JSMgr.changeJSObj(vc.jsObjID, argThis);
    }

    return true;
}

static bool Color_HSVToRGB__Single__Single__Single__Boolean(JSVCall vc, int argc)
{
    int len = argc;
    if (len == 4)
    {
        System.Single arg0 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        System.Single arg1 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        System.Single arg2 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        System.Boolean arg3 = (System.Boolean)JSApi.getBooleanS((int)JSApi.GetType.Arg);
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, UnityEngine.Color.HSVToRGB(arg0, arg1, arg2, arg3));
    }

    return true;
}

static bool Color_HSVToRGB__Single__Single__Single(JSVCall vc, int argc)
{
    int len = argc;
    if (len == 3)
    {
        System.Single arg0 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        System.Single arg1 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
        System.Single arg2 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, UnityEngine.Color.HSVToRGB(arg0, arg1, arg2));
    }

    return true;
}

static bool Color_Lerp__Color__Color__Single(JSVCall vc, int argc)
{
    int len = argc;
    if (len == 3)
    {
        UnityEngine.Color arg0 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
        UnityEngine.Color arg1 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
        System.Single arg2 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, UnityEngine.Color.Lerp(arg0, arg1, arg2));
    }

    return true;
}

static bool Color_LerpUnclamped__Color__Color__Single(JSVCall vc, int argc)
{
    int len = argc;
    if (len == 3)
    {
        UnityEngine.Color arg0 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
        UnityEngine.Color arg1 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
        System.Single arg2 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, UnityEngine.Color.LerpUnclamped(arg0, arg1, arg2));
    }

    return true;
}

static bool Color_op_Addition__Color__Color(JSVCall vc, int argc)
{
    UnityEngine.Color arg0 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
    UnityEngine.Color arg1 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            JSMgr.datax.setObject((int)JSApi.SetType.Rval, arg0 + arg1);
    return true;
}

static bool Color_op_Division__Color__Single(JSVCall vc, int argc)
{
    UnityEngine.Color arg0 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
    System.Single arg1 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
            JSMgr.datax.setObject((int)JSApi.SetType.Rval, arg0 / arg1);
    return true;
}

static bool Color_op_Equality__Color__Color(JSVCall vc, int argc)
{
    UnityEngine.Color arg0 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
    UnityEngine.Color arg1 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            JSApi.setBooleanS((int)JSApi.SetType.Rval, (System.Boolean)(arg0 == arg1));
    return true;
}

static bool Color_op_Implicit__Vector4_to_Color(JSVCall vc, int argc)
{
    UnityEngine.Vector4 arg0 = (UnityEngine.Vector4)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            JSMgr.datax.setObject((int)JSApi.SetType.Rval, (UnityEngine.Color)arg0);
    return true;
}

static bool Color_op_Implicit__Color_to_Vector4(JSVCall vc, int argc)
{
    UnityEngine.Color arg0 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            JSMgr.datax.setObject((int)JSApi.SetType.Rval, (UnityEngine.Vector4)arg0);
    return true;
}

static bool Color_op_Inequality__Color__Color(JSVCall vc, int argc)
{
    UnityEngine.Color arg0 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
    UnityEngine.Color arg1 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            JSApi.setBooleanS((int)JSApi.SetType.Rval, (System.Boolean)(arg0 != arg1));
    return true;
}

static bool Color_op_Multiply__Color__Color(JSVCall vc, int argc)
{
    UnityEngine.Color arg0 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
    UnityEngine.Color arg1 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            JSMgr.datax.setObject((int)JSApi.SetType.Rval, arg0 * arg1);
    return true;
}

static bool Color_op_Multiply__Color__Single(JSVCall vc, int argc)
{
    UnityEngine.Color arg0 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
    System.Single arg1 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
            JSMgr.datax.setObject((int)JSApi.SetType.Rval, arg0 * arg1);
    return true;
}

static bool Color_op_Multiply__Single__Color(JSVCall vc, int argc)
{
    System.Single arg0 = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
    UnityEngine.Color arg1 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            JSMgr.datax.setObject((int)JSApi.SetType.Rval, arg0 * arg1);
    return true;
}

static bool Color_op_Subtraction__Color__Color(JSVCall vc, int argc)
{
    UnityEngine.Color arg0 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
    UnityEngine.Color arg1 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            JSMgr.datax.setObject((int)JSApi.SetType.Rval, arg0 - arg1);
    return true;
}

static bool Color_RGBToHSV__Color__Single__Single__Single(JSVCall vc, int argc)
{
    int len = argc;
    if (len == 4)
    {
        UnityEngine.Color arg0 = (UnityEngine.Color)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
        int r_arg1 = JSApi.incArgIndex();
        System.Single arg1;
        int r_arg2 = JSApi.incArgIndex();
        System.Single arg2;
        int r_arg3 = JSApi.incArgIndex();
        System.Single arg3;
        UnityEngine.Color.RGBToHSV(arg0, out arg1, out arg2, out arg3);
        JSApi.setArgIndex(r_arg1);
        JSApi.setSingle((int)JSApi.SetType.ArgRef, arg1);
        JSApi.setArgIndex(r_arg2);
        JSApi.setSingle((int)JSApi.SetType.ArgRef, arg2);
        JSApi.setArgIndex(r_arg3);
        JSApi.setSingle((int)JSApi.SetType.ArgRef, arg3);
    }

    return true;
}

//register

public static void __Register()
{
    JSMgr.CallbackInfo ci = new JSMgr.CallbackInfo();
    ci.type = typeof(UnityEngine.Color);
    ci.fields = new JSMgr.CSCallbackField[]
    {
        Color_r,
        Color_g,
        Color_b,
        Color_a,

    };
    ci.properties = new JSMgr.CSCallbackProperty[]
    {
        Color_red,
        Color_green,
        Color_blue,
        Color_white,
        Color_black,
        Color_yellow,
        Color_cyan,
        Color_magenta,
        Color_gray,
        Color_grey,
        Color_clear,
        Color_grayscale,
        Color_linear,
        Color_gamma,
        Color_maxColorComponent,
        Color_Item_Int32,

    };
    ci.constructors = new JSMgr.MethodCallBackInfo[]
    {
        new JSMgr.MethodCallBackInfo(Color_Color1, ".ctor"),
        new JSMgr.MethodCallBackInfo(Color_Color2, ".ctor"),
        new JSMgr.MethodCallBackInfo(Color_Color3, ".ctor"),

    };
    ci.methods = new JSMgr.MethodCallBackInfo[]
    {
        new JSMgr.MethodCallBackInfo(Color_Equals__Object, "Equals"),
        new JSMgr.MethodCallBackInfo(Color_GetHashCode, "GetHashCode"),
        new JSMgr.MethodCallBackInfo(Color_ToString__String, "ToString"),
        new JSMgr.MethodCallBackInfo(Color_ToString, "ToString"),
        new JSMgr.MethodCallBackInfo(Color_HSVToRGB__Single__Single__Single__Boolean, "HSVToRGB"),
        new JSMgr.MethodCallBackInfo(Color_HSVToRGB__Single__Single__Single, "HSVToRGB"),
        new JSMgr.MethodCallBackInfo(Color_Lerp__Color__Color__Single, "Lerp"),
        new JSMgr.MethodCallBackInfo(Color_LerpUnclamped__Color__Color__Single, "LerpUnclamped"),
        new JSMgr.MethodCallBackInfo(Color_op_Addition__Color__Color, "op_Addition"),
        new JSMgr.MethodCallBackInfo(Color_op_Division__Color__Single, "op_Division"),
        new JSMgr.MethodCallBackInfo(Color_op_Equality__Color__Color, "op_Equality"),
        new JSMgr.MethodCallBackInfo(Color_op_Implicit__Vector4_to_Color, "op_Implicit"),
        new JSMgr.MethodCallBackInfo(Color_op_Implicit__Color_to_Vector4, "op_Implicit"),
        new JSMgr.MethodCallBackInfo(Color_op_Inequality__Color__Color, "op_Inequality"),
        new JSMgr.MethodCallBackInfo(Color_op_Multiply__Color__Color, "op_Multiply"),
        new JSMgr.MethodCallBackInfo(Color_op_Multiply__Color__Single, "op_Multiply"),
        new JSMgr.MethodCallBackInfo(Color_op_Multiply__Single__Color, "op_Multiply"),
        new JSMgr.MethodCallBackInfo(Color_op_Subtraction__Color__Color, "op_Subtraction"),
        new JSMgr.MethodCallBackInfo(Color_RGBToHSV__Color__Single__Single__Single, "RGBToHSV"),

    };
    JSMgr.allCallbackInfo.Add(ci);
}

}


text:
class RemovePlatform < ActiveRecord::Migration
  def change
    remove_column :tests, :platform, :string
    remove_column :baselines, :platform, :string
  end
end


text:
<oimplugins xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <plugins pluginpoint="oracle.iam.platform.kernel.spi.EventHandler">
      <plugin pluginclass="com.blogspot.oraclestack.eventhandlers.UserCreatePreprocessEH" version="1.0" name="UserCreatePreprocessEH"/>
   </plugins>
</oimplugins>


text:
package system;

/**
 * The Magazine class.
 * @author Joris Schelfaut
 */
public class Magazine extends Periodical {

    private String topic;

    public Magazine(String title, String author, int year, Rating rating,
            String issn, int number, String series, String topic)
            throws IllegalArgumentException {
        super(title, author, year, rating, issn, number, series);
        this.setTopic(topic);
    }

    /**
     * @param topic the general topic of the magazine.
     */
    private void setTopic(String topic) {
        this.topic = topic;
    }

    /**
     * @return the general topic of the magazine.
     */
    public String getTopic() {
        return topic;
    }
}


text:
Service Container
=================

[![Build Status](https://travis-ci.org/herrera-io/php-service-container.png)](http://travis-ci.org/herrera-io/php-service-container)

A simple service container.

Summary
-------

This library provides a simple service container. It is heavily influenced by Fabien Potencier's [Pimple](https://github.com/fabpot/Pimple) project (in particular, Igor Wielder's modifications). The differences from Pimple are

- naming convention
- handling of service provider registration
- library specific exceptions
- different implementations of `shared()` and `protect()`

Installation
------------

Add it to your list of Composer dependencies:

```sh
$ composer require herrera-io/service-container=1.*
```

Usage
-----

### Simple usage

```php
<?php

use Herrera\Service\Container;

$container = new Container(array('var' => 123));

$container['factory'] = $container->many(function () {
    return new ArrayObject(array('rand' => rand()));
});

$container['shared'] = $container->once(function() {
    return new ArrayObject(array('rand' => rand()));
});

echo $container['factory']['rand']; // echo "1197692050"
echo $container['factory']['rand']; // echo "995449132"
echo $container['shared']['rand']; // echo "89432412"
echo $container['shared']['rand']; // echo "89432412"
```

### Service provider usage

```php
<?php

use Herrera\Service\Container;
use Herrera\Service\ProviderInterface;

class MyProvider implements ProviderInterface
{
    public function register(Container $container)
    {
        $container['hello'] = $container->once(function (Container $container) {
            echo 'Hello, ', $container['name'], "!\n";
        });
    }
}

$container =  new Container();
$container->register(new MyProvider(), array(
    'name' => 'Guest'
));

```


text:
/*
 * @test
 * @bug 4095319 4286358
 * @summary Test cases for the containsKey, keySet, and handleKeySet
 * methods that are new in Mustang.
 * @build KeySetMessages KeySetMessages_zh_CN
 * @run main KeySetTest
 */

import java.lang.reflect.*;
import java.util.*;

public class KeySetTest {
    static final List<String> fullKeys = Arrays.asList("food", "drink", "tea");
    static final List<String> localKeys = Arrays.asList("food", "tea");

    public static void main(String[] args) {
        // Test PropertyResourceBundle
        testKeys("KeySetResources", Locale.JAPAN);

        // Test ListResourceBundle
        testKeys("KeySetMessages", Locale.CHINA);
    }

    static void testKeys(String bundleName, Locale locale) {
        ResourceBundle rb = ResourceBundle.getBundle(bundleName, locale);
        System.out.println("food = " + rb.getString("food"));

        // Test keySet()
        Set<String> allKeys = rb.keySet();
        if (!(allKeys.containsAll(fullKeys) && fullKeys.containsAll(allKeys))) {
            throw new RuntimeException("got "+allKeys + ", expected " + fullKeys);
        }

        // Test containsKey()
        for (String key : fullKeys) {
            if (!rb.containsKey(key)) {
                throw new RuntimeException("rb doesn't contain: " + key);
            }
        }
        for (String key : new String[] { "snack", "beer" }) {
            if (rb.containsKey(key)) {
                throw new RuntimeException("rb contains: " + key);
            }
        }

        // Make sure that the default handleKeySet implementation
        // returns the subset keys of the given locale.
        TestBundle tb = new TestBundle(bundleName, locale);
        Set<String> childKeys = tb.handleKeySet();
        if (!(childKeys.containsAll(localKeys) || localKeys.containsAll(childKeys))) {
            throw new RuntimeException("get " + childKeys + ", expected " + localKeys);
        }
    }

    static class TestBundle extends ResourceBundle {
        ResourceBundle bundle;
        Method m;

        public TestBundle() {}

        public TestBundle(String name, Locale locale) {
            bundle = ResourceBundle.getBundle(name, locale);

            // Prepare for the handleGetObject call
            try {
                Class clazz = bundle.getClass();
                m = clazz.getMethod("handleGetObject", String.class);
                m.setAccessible(true);
            } catch (Exception e) {
                throw new RuntimeException("method preparation error", e);
            }
        }

        public Enumeration<String> getKeys() {
            return bundle.getKeys();
        }

        // handleGetObject() doesn't look up its parent bundles.
        protected Object handleGetObject(String key) {
            try {
                return m.invoke(bundle, key);
            } catch (Exception e) {
                throw new RuntimeException("handleGetObject error", e);
            }
        }

        public Set<String> handleKeySet() {
            return super.handleKeySet();
        }
    }
}


text:
package ladok.lpw.service.register.facadeclient;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for grpTillhorVO complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="grpTillhorVO">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="grpkod" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="kod" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "grpTillhorVO", propOrder = {
    "grpkod",
    "kod"
})
public class GrpTillhorVO {

    protected String grpkod;
    protected String kod;

    /**
     * Gets the value of the grpkod property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getGrpkod() {
        return grpkod;
    }

    /**
     * Sets the value of the grpkod property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setGrpkod(String value) {
        this.grpkod = value;
    }

    /**
     * Gets the value of the kod property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getKod() {
        return kod;
    }

    /**
     * Sets the value of the kod property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setKod(String value) {
        this.kod = value;
    }

}


text:
module Language.LoopGotoWhile.While.Transform
    ( toExtended
    , toStrict
    , toGoto
    ) where

import Control.Monad
import Control.Monad.State
import Data.List (nub)

import qualified Language.LoopGotoWhile.Goto.ExtendedAS as GotoAS
import qualified Language.LoopGotoWhile.While.StrictAS as Strict
import Language.LoopGotoWhile.While.ExtendedAS
import Language.LoopGotoWhile.Shared.Transform
import Language.LoopGotoWhile.Goto.Transform
    ( TransformState
    , getUnusedLabel
    , getStrictUnusedLabels
    )

-- * Transformation from strict While to extended While
--   ==================================================

-- | Transform a strict syntax tree into an extended one without changing the
-- semantics of the program.
--
-- Since the strict syntax is a subset of the extended syntax this functions
-- merely translates the strict data constructors to the extended ones in
-- a very direct manner. This function is only needed to make some
-- transformations / function compositions easier.
toExtended :: Strict.Program -> Program
toExtended (Strict.Assign i j Strict.Plus c) =
    Assign ('x' : show i) (AOp "+" (Var ('x' : show j)) (Const c))
toExtended (Strict.Assign i j Strict.Minus c) =
    Assign ('x' : show i) (AOp "-" (Var ('x' : show j)) (Const c))
toExtended (Strict.While i stat) =
    While (RelOp "!=" (Var ('x' : show i)) (Const 0)) (toExtended stat)
toExtended (Strict.Seq stats) = Seq $ map toExtended stats

-- * Transformation from extended While to strict While
--   ==================================================

-- | Transform an extended syntax tree into a strict one without changing the
-- semantics of the program.
toStrict :: Program -> Strict.Program
toStrict = toStrict' . toStrictStat . toStrictVars

-- | Transform an extended syntax tree into a strict one. Assume that the AST
-- is given in a directly translatable form.
toStrict' :: Program -> Strict.Program
toStrict' (Assign (_:i) (AOp "+" (Var (_:j)) (Const c))) =
    Strict.Assign (read i) (read j) Strict.Plus c
toStrict' (Assign (_:i) (AOp "-" (Var (_:j)) (Const c))) =
    Strict.Assign (read i) (read j) Strict.Minus c
toStrict' (While (RelOp "!=" (Var (_:i)) (Const 0)) stat) =
    Strict.While (read i) (toStrict' stat)
toStrict' (Seq stats) = Strict.Seq (map toStrict' stats)
toStrict' ast = error $ "Extended AST is not in strict form: " ++ show ast

-- ** Renaming of Variables
--    ---------------------

-- | Change all occurences of unstrict variable names into strict variable
-- names without altering the semantics of the AST.
toStrictVars :: Stat -> Stat
toStrictVars ast = foldr (uncurry renameVar) ast renameMappings
  where renameMappings     = zip unstrict unused
        unused             = getStrictUnusedVars strict
        (strict, unstrict) = partitionVars $ getVarNames ast

-- | Rename all occurences of 'from' as a variable identifier to 'to' in the
-- given AST.
renameVar :: VarIdent -> VarIdent -> Stat -> Stat
renameVar from to ast = case ast of
    Assign var aexp      -> Assign (r var) (rAExp aexp)
    While bexp stat      -> While (rBExp bexp) (rVar stat)
    If bexp s1 Nothing   -> If (rBExp bexp) (rVar s1) Nothing
    If bexp s1 (Just s2) -> If (rBExp bexp) (rVar s1) (Just (rVar s2))
    Seq stats            -> Seq (map rVar stats)
  where rVar  = renameVar from to
        rAExp = renameVarInAExp from to
        rBExp = renameVarInBExp from to
        r var | var == from = to | otherwise = var

-- | Analyze the AST and return a list without duplicates of all used variable
-- names.
getVarNames :: Stat -> [VarIdent]
getVarNames = nub . f
  where f (Assign var aexp)      = var : getVarNamesInAExp aexp
        f (While bexp stat)      = getVarNamesInBExp bexp ++ f stat
        f (If bexp s1 Nothing)   = getVarNamesInBExp bexp ++ f s1
        f (If bexp s1 (Just s2)) = getVarNamesInBExp bexp ++ f s1 ++ f s2
        f (Seq stats)            = concatMap f stats

-- ** Statements
--    ----------

-- | Transform an extended While AST into a strict While AST. Assume that all
-- variables are already strict.
toStrictStat :: Stat -> Stat
toStrictStat ast =
    evalState (toStrictStat' ast) (getStrictUnusedVars (getVarNames ast))

-- Since sometimes an unused variable is needed in order to correctly transform
-- a statement an infinite list of unused variable names is carried along as
-- state that gets updated whenever an unused variable name is requested.
toStrictStat' :: Stat -> State [VarIdent] Stat
-- v0 := v1 +- c. Keep unchanged!
toStrictStat' stat@(Assign _ (AOp op (Var _) (Const _)))
    | op `elem` ["+","-"] = return stat
-- v0 := v1
toStrictStat' (Assign v0 (Var v1)) = return $
    Assign v0 (AOp "+" (Var v1) (Const 0))
-- v0 := c
toStrictStat' (Assign v0 (Const c)) = do
    unused <- getUnusedVar
    return $ Assign v0 (AOp "+" (Var unused) (Const c))
-- v0 := v1 o v2
toStrictStat' (Assign v0 (AOp op (Var v1) (Var v2))) = case op of
    "+" -> do ltw <- loopToWhile $ Loop (Var v2) (Assign v0 (AOp "+" (Var v0) (Const 1)))
              toStrictStat' $ Seq
                  [ Assign v0 (Var v1)
                  , ltw
                  ]
    "-" -> do ltw <- loopToWhile $ Loop (Var v2) (Assign v0 (AOp "-" (Var v0) (Const 1)))
              toStrictStat' $ Seq
                  [ Assign v0 (Var v1)
                  , ltw
                  ]
    "*" -> do u <- getUnusedVar
              ltw <- loopToWhile $ Loop (Var v2) (Assign u (AOp "+" (Var u) (Var v1)))
              toStrictStat' $ Seq
                  [ Assign u (Const 0)
                  , ltw
                  , Assign v0 (Var u)
                  ]
    "^" -> do u <- getUnusedVar
              ltw <- loopToWhile $ Loop (Var v2) (Assign u (AOp "*" (Var u) (Var v1)))
              toStrictStat' $ Seq
                  [ Assign u (Const 1)
                  , ltw
                  , Assign v0 (Var u)
                  ]
    "/" -> do c <- getUnusedVar
              ltw <- loopToWhile $ Loop (Var v0) (If (RelOp ">=" (Var v0) (Var v2)) (Seq
                         [ Assign c  (AOp "+" (Var c) (Const 1))
                         , Assign v0 (AOp "-" (Var v0) (Var v2))
                         ]) Nothing)
              toStrictStat' $ Seq
                  [ Assign c (Const 0)
                  , Assign v0 (Var v1)
                  , ltw
                  , Assign v0 (Var c)
                  ]
    "%" -> do ltw <- loopToWhile $ Loop (Var v0) (If (RelOp ">=" (Var v0) (Var v2))
                         (Assign v0 (AOp "-" (Var v0) (Var v2))) Nothing)
              toStrictStat' $ Seq
                  [ Assign v0 (Var v1)
                  , ltw
                  ]
    _   -> error "Impossible! Wrong operator!"
-- v0 := a o b
toStrictStat' (Assign v0 (AOp op a b)) = do    -- v0 := a o b =>
    ua <- getUnusedVar
    ub <- getUnusedVar
    toStrictStat' $ Seq
        [ Assign ua a                          -- ua := a
        , Assign ub b                          -- ub := b
        , Assign v0 (AOp op (Var ua) (Var ub)) -- v0 := ua o ub
        ]
-- IF b THEN P {ELSE P2} END
toStrictStat' (If (RelOp op a b) stat1 stat2) = case op of
    -- TODO: This is ugly because I want to handle both the if and ifelse case
    -- in one do expression. Maybe add code duplication for the sake of
    -- readability?
    "="  -> do u1 <- getUnusedVar
               u2 <- getUnusedVar
               let t = Assign u2 (Const 0)
               (body, u3) <- case stat2 of
                               Nothing -> return (t, Nothing)
                               Just _  -> do u3 <- getUnusedVar
                                             return (Seq [t, Assign u3 (Const 1)], Just u3)
               ltw1 <- loopToWhile $ Loop (Var u1) body
               ltw2 <- loopToWhile $ Loop (Var u2) stat1
               t' <- case (stat2, u3) of
                          (Just s, Just u) -> do ltw3 <- loopToWhile $ Loop (Var u) s
                                                 return [ltw3]
                          _                -> return []
               toStrictStat' $ Seq $
                   [ Assign u1 (AOp "+" (AOp "-" a b) (AOp "-" b a))
                   , Assign u2 (Const 1)
                   ] ++ case u3 of
                          Just u -> [Assign u (Const 0)]
                          _      -> []
                     ++
                   [ ltw1
                   , ltw2
                   ] ++ t'
    "!=" -> f (AOp "+" (AOp "-" a b) (AOp "-" b a))
    "<"  -> f (AOp "-" b a)
    ">"  -> toStrictStat' $ If (RelOp "<" b a) stat1 stat2
    "<=" -> toStrictStat' $ If (BOp "||" (RelOp "<" a b) (RelOp "=" a b)) stat1 stat2
    ">=" -> toStrictStat' $ If (BOp "||" (RelOp ">" a b) (RelOp "=" a b)) stat1 stat2
    _    -> error "Impossible! Wrong operator!"
  where f aexp = do
            u1 <- getUnusedVar
            u2 <- getUnusedVar
            let t = Assign u2 (Const 1)
            (body, u3) <- case stat2 of
                            Nothing -> return (t, Nothing)
                            Just _  -> do u3 <- getUnusedVar
                                          return (Seq [t, Assign u3 (Const 0)], Just u3)
            ltw1 <- loopToWhile $ Loop (Var u1) body
            ltw2 <- loopToWhile $ Loop (Var u2) stat1
            t' <- case (stat2, u3) of
                       (Just s, Just u) -> do ltw3 <- loopToWhile $ Loop (Var u) s
                                              return [ltw3]
                       _                -> return []
            toStrictStat' $ Seq $
                [ Assign u1 aexp
                , Assign u2 (Const 0)
                ] ++ case u3 of
                       Just u -> [Assign u (Const 1)]
                       _      -> []
                  ++
                [ ltw1
                , ltw2
                ] ++ t'
toStrictStat' (If (BOp "&&" a b) stat1 Nothing) = toStrictStat' $
    If a (If b stat1 Nothing) Nothing
toStrictStat' (If (BOp "&&" a b) stat1 (Just stat2)) = do
    u <- getUnusedVar
    ltw <- loopToWhile $ Loop (Var u) stat2
    toStrictStat' $ Seq
        [ Assign u (Const 1)
        , If a (If b (Seq [Assign u (Const 0), stat1]) Nothing) Nothing
        , ltw
        ]
toStrictStat' (If (BOp "||" a b) stat1 Nothing) = do
    u <- getUnusedVar
    ltw <- loopToWhile $ Loop (Var u) stat1
    toStrictStat' $ Seq
        [ Assign u (Const 0)
        , If a (Assign u (Const 1)) Nothing
        , If b (Assign u (Const 1)) Nothing
        , ltw
        ]
toStrictStat' (If (BOp "||" a b) stat1 (Just stat2)) = do
    u1 <- getUnusedVar
    u2 <- getUnusedVar
    ltw1 <- loopToWhile $ Loop (Var u1) stat1
    ltw2 <- loopToWhile $ Loop (Var u2) stat2
    toStrictStat' $ Seq
        [ Assign u1 (Const 0)
        , Assign u2 (Const 1)
        , If a (Seq [Assign u1 (Const 1), Assign u2 (Const 0)]) Nothing
        , If b (Seq [Assign u1 (Const 1), Assign u2 (Const 0)]) Nothing
        , ltw1
        , ltw2
        ]
toStrictStat' (If (BNegOp bexp) stat1 stat2) = toStrictStat' $ case bexp of
    RelOp "="  a b -> If (RelOp "!=" a b) stat1 stat2
    RelOp "!=" a b -> If (RelOp "="  a b) stat1 stat2
    RelOp "<"  a b -> If (RelOp ">=" a b) stat1 stat2
    RelOp ">"  a b -> If (RelOp "<=" a b) stat1 stat2
    RelOp "<=" a b -> If (RelOp ">"  a b) stat1 stat2
    RelOp ">=" a b -> If (RelOp "<"  a b) stat1 stat2
    BOp "&&" a b -> If (BOp "||" (BNegOp a) (BNegOp b)) stat1 stat2
    BOp "||" a b -> If (BOp "&&" (BNegOp a) (BNegOp b)) stat1 stat2
    BNegOp bexp' -> If bexp' stat1 stat2
    _ -> error "Impossible! Wrong operator!"
-- WHILE a DO P END
toStrictStat' (While rel@(RelOp "!=" (Var _) (Const 0)) stat) =
    liftM (While rel) $ toStrictStat' stat
toStrictStat' (While bexp stat) = do
    c <- getUnusedVar
    let if' = If bexp (Assign c (Const 1)) (Just (Assign c (Const 0)))
    toStrictStat' $ Seq
        [ if'
        , While (RelOp "!=" (Var c) (Const 0)) $ Seq
              [ stat
              , if'
              ]
        ]
-- P1; P2;...
toStrictStat' (Seq stats) = liftM (Seq . flatten) $ mapM toStrictStat' stats
    where flatten = foldr f []
          f (Seq stmnts) acc = stmnts ++ acc
          f x            acc = x : acc
-- All cases must have been checked by now.
toStrictStat' _ = error $ "Not all cases were considered when transforming " ++
                          "extended Goto to strict Goto!"

-- Helper to make the toStrictStat' as close as possible to the Loop version
data Loop = Loop AExp Stat

loopToWhile :: Loop -> State [VarIdent] Stat
loopToWhile (Loop aexp stat) = do
    c <- getUnusedVar
    toStrictStat' $ Seq
        [ Assign c aexp
        , While (RelOp "!=" (Var c) (Const 0)) $ Seq
              [ Assign c (AOp "-" (Var c) (Const 1))
              , stat
              ]
        ]

-- * Transformation to Goto
--   ======================

-- | Transform a While AST to a Goto AST.
toGoto :: Stat -> GotoAS.Stat
toGoto ast = evalState (
                 evalStateT (toGoto' ast) (getStrictUnusedLabels [])
             ) []

-- The reason for the use of the state monad is that the transformation of
-- a While loop to a "Goto loop" needs unused labels and the list of unusued
-- labels is carried along in the state.
toGoto' :: Stat -> TransformState GotoAS.Stat
toGoto' (Assign v aexp) = return $ GotoAS.Assign v aexp
toGoto' (If bexp statThen statElse) = do
    gStatThen <- toGoto' statThen
    gStatElse <- case statElse of
                   Just s  -> do s' <- toGoto' s
                                 return $ Just s'
                   Nothing -> return Nothing
    return $ GotoAS.If bexp gStatThen gStatElse
toGoto' (While bexp stat) = do
    m0 <- getUnusedLabel
    m1 <- getUnusedLabel
    s <- toGoto' stat
    return $ GotoAS.Seq $
        [ GotoAS.Label m0 $ GotoAS.If (BNegOp bexp) (GotoAS.Goto m1) Nothing
        ] ++ flatten s ++
        [ GotoAS.Goto m0
        , GotoAS.Label m1 $ GotoAS.Assign "x0" (GotoAS.Var "x0")
        ]
  where flatten (GotoAS.Seq xs)              = xs
        flatten x                            = [x]
toGoto' (Seq stats) = liftM GotoAS.Seq $ mapM toGoto' stats


text:
package org.intellij.lang.xpath.xslt.run;

import com.intellij.execution.filters.Filter;
import com.intellij.execution.filters.HyperlinkInfo;
import com.intellij.execution.filters.InvalidExpressionException;
import com.intellij.execution.filters.OpenFileHyperlinkInfo;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.util.io.URLUtil;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Copy of com.intellij.execution.filters.RegexpFilter
 *
 * Sascha Weinreuter - 2005-11-07 - Modfied to be able to use a customized filename/url pattern
 *
 * @author Yura Cangea
 * @version 1.0
 */
@SuppressWarnings({"ALL"})
public class CustomRegexpFilter implements Filter {
  @SuppressWarnings({"HardCodedStringLiteral"})
  public static final String FILE_PATH_MACROS = "$FILE_PATH$";
  @SuppressWarnings({"HardCodedStringLiteral"})
  public static final String LINE_MACROS = "$LINE$";
  @SuppressWarnings({"HardCodedStringLiteral"})
  public static final String COLUMN_MACROS = "$COLUMN$";

  @SuppressWarnings({"HardCodedStringLiteral"})
  private static final String DEFAULT_REGEXP = "((?:\\p{Alpha}\\:)?[0-9 a-z_A-Z\\-\\\\./]+)";
  private static final String NUMBER_REGEXP = "([0-9]+)";

  private int myFileRegister;
  private int myLineRegister;
  private int myColumnRegister;

  private Pattern myPattern;
  private Project myProject;
  private final VirtualFile myBase;
  private final String myFilePathRegexp;

  public CustomRegexpFilter(Project project, String expression, VirtualFile base) {
    this(project, expression, base, DEFAULT_REGEXP);
  }

  public CustomRegexpFilter(Project project, String expression, VirtualFile base, String filePathExpr) {
    myFilePathRegexp = filePathExpr;

    myProject = project;
    myBase = base;
    validate(expression);

    if (expression == null || "".equals(expression.trim())) {
        throw new InvalidExpressionException("expression == null or empty");
    }

    int filePathIndex = expression.indexOf(FILE_PATH_MACROS);
    int lineIndex = expression.indexOf(LINE_MACROS);
    int columnIndex = expression.indexOf(COLUMN_MACROS);

    if (filePathIndex == -1) {
        throw new InvalidExpressionException("Expression must contain " + FILE_PATH_MACROS + " macros.");
    }

    final TreeMap<Integer, String> map = new TreeMap<Integer, String>();

    map.put(new Integer(filePathIndex), "file");

    expression = StringUtil.replace(expression, FILE_PATH_MACROS, myFilePathRegexp);

    if (lineIndex != -1) {
        expression = StringUtil.replace(expression, LINE_MACROS, NUMBER_REGEXP);
        map.put(new Integer(lineIndex), "line");
    }

    if (columnIndex != -1) {
        expression = StringUtil.replace(expression, COLUMN_MACROS, NUMBER_REGEXP);
        map.put(new Integer(columnIndex), "column");
    }

    // The block below determines the registers based on the sorted map.
    int count = 0;
    final Iterator<Integer> itr = map.keySet().iterator();
    while (itr.hasNext()) {
        count++;
        final String s = map.get(itr.next());

        if ("file".equals(s)) {
            filePathIndex = count;
        } else if ("line".equals(s)) {
            lineIndex = count;
        } else if ("column".equals(s)) {
            columnIndex = count;
        }
    }

    myFileRegister = filePathIndex;
    myLineRegister = lineIndex;
    myColumnRegister = columnIndex;
    myPattern = Pattern.compile(expression, Pattern.MULTILINE);
  }

  public void validate(String expression) {
    if (expression == null || "".equals(expression.trim())) {
      throw new InvalidExpressionException("expression == null or empty");
    }

    expression = substituteMacrosesWithRegexps(expression);

    Pattern.compile(expression, Pattern.MULTILINE);
  }

  private String substituteMacrosesWithRegexps(String expression) {
    int filePathIndex = expression.indexOf(FILE_PATH_MACROS);
    int lineIndex = expression.indexOf(LINE_MACROS);
    int columnIndex = expression.indexOf(COLUMN_MACROS);

    if (filePathIndex == -1) {
      throw new InvalidExpressionException("Expression must contain " + FILE_PATH_MACROS + " macros.");
    }

    expression = StringUtil.replace(expression, FILE_PATH_MACROS, myFilePathRegexp);

    if (lineIndex != -1) {
      expression = StringUtil.replace(expression, LINE_MACROS, NUMBER_REGEXP);
    }

    if (columnIndex != -1) {
      expression = StringUtil.replace(expression, COLUMN_MACROS, NUMBER_REGEXP);
    }
    return expression;
  }

  public Result applyFilter(final String line, final int entireLength) {

    final Matcher matcher = myPattern.matcher(line);
    if (matcher.find()) {
      return createResult(matcher, entireLength - line.length());
    }

    return null;
  }

  private Result createResult(final Matcher matcher, final int entireLen) {
    final String filePath = matcher.group(myFileRegister);

    String lineNumber = "0";
    String columnNumber = "0";

    if (myLineRegister != -1) {
      lineNumber = matcher.group(myLineRegister);
    }

    if (myColumnRegister != -1) {
      columnNumber = matcher.group(myColumnRegister);
    }

    int line = 0;
    int column = 0;
    try {
      line = Integer.parseInt(lineNumber);
      column = Integer.parseInt(columnNumber);
    } catch (NumberFormatException e) {
      // Do nothing, so that line and column will remain at their initial
      // zero values.
    }

    if (line > 0) line -= 1;
    if (column > 0) column -= 1;
    // Calculate the offsets relative to the entire text.
    final int highlightStartOffset;
    final int highlightEndOffset;
    if ((filePath == null || filePath.length() == 0) && myLineRegister != -1) {
      highlightStartOffset = entireLen + matcher.start(myLineRegister);
      highlightEndOffset = highlightStartOffset + lineNumber.length();
    } else {
      highlightStartOffset = entireLen + matcher.start(myFileRegister);
      highlightEndOffset = highlightStartOffset + filePath.length();
    }
    final HyperlinkInfo info = createOpenFileHyperlink(filePath, line, column);
    // don't return a result if the filename cannot be resolved to a file
    return info != null ? new Result(highlightStartOffset, highlightEndOffset, info) : null;
  }

  protected HyperlinkInfo createOpenFileHyperlink(String fileName, final int line, int column) {
    if ((fileName == null || fileName.length() == 0)) {
        if (myBase != null) {
            fileName = myBase.getPresentableUrl();
        } else {
            return null;
        }
    }
    fileName = fileName.replace(File.separatorChar, '/');

    VirtualFile file;
    // try to interpret the filename as URL
    if (URLUtil.containsScheme(fileName)) {
      try {
        file = VfsUtil.findFileByURL(new URL(fileName));
      } catch (MalformedURLException e) {
        file = VirtualFileManager.getInstance().findFileByUrl(VfsUtil.pathToUrl(fileName));
      }
    } else {
      file = VfsUtil.findRelativeFile(fileName, myBase);
    }
    if (file == null) {
      //noinspection ConstantConditions
      return null;
    }

    final FileType fileType = file.getFileType();
    if (fileType != null && column > 0) {
      final Document document = FileDocumentManager.getInstance().getDocument(file);

      final int start = document.getLineStartOffset(line);
      final int max = document.getLineEndOffset(line);
      final int tabSize = CodeStyleSettingsManager.getInstance(myProject).getCurrentSettings().getTabSize(fileType);
      column = EditorUtil.calcColumnNumber(null, document.getCharsSequence(), start, Math.min(start + column, max), tabSize);
    }
    return new OpenFileHyperlinkInfo(myProject, file, line, column);
  }

  public static String[] getMacrosName() {
    return new String[] {FILE_PATH_MACROS, LINE_MACROS, COLUMN_MACROS};
  }
}


text:
package eventdb

import (
	"errors"
	"github.com/garyburd/redigo/redis"
	"io/ioutil"
	"log"
	"time"
)

var ErrCouldNotSelectDb = errors.New("could not select db")

const (
	GOOSE_REDIS_UFO_LIST   = "goose:unexpected"
	GOOSE_REDIS_REQ_PREFIX = "goose:requests:"
)

type redisdb struct {
	net     string
	addr    string
	db      int
	pool    *redis.Pool
	verbose int
}

func (db *redisdb) Dial() (err error) {
	db.pool = makePool(db.net, db.addr, db.db)

	err = db.ping()
	if err != nil {
		return
	}

	if db.verbose > 0 {
		log.Printf("goose/eventdb: connected to redis on %s:%s\n", db.net, db.addr)
	}
	return
}

func (db *redisdb) ping() error {
	c := db.pool.Get()
	defer c.Close()
	_, err := c.Do("PING")
	return err
}

func (db *redisdb) Close() {
	db.pool.Close()

	if db.verbose > 0 {
		log.Println("goose/eventdb: redis connection pool released")
	}
}

func (db *redisdb) Trace(m *Message) (err error) {
	log.Print(m.String())

	// Ensure that we've got a tag.
	tag := m.Tag
	if !m.Tagged() {
		tag = GOOSE_REDIS_UFO_LIST
	}

	// Convert the request body to a base64-encoded string.
	input, err := ioutil.ReadAll(m.Request.Body)
	if err != nil {
		return
	}

	body, err := EncodeBuffer(input)
	if err != nil {
		return
	}

	// Merge message key/value pairs.
	args := make(map[string]string)
	copymap(args, m.MoreInfo)
	copymap(args, map[string]string{
		"tag":        tag,
		"timestamp":  string(m.Timestamp),
		"remoteAddr": m.Request.RemoteAddr,
		"method":     m.Request.Method,
		"url":        m.Request.URL.String(),
		"body":       body,
	})

	// Deliver the message to Redis.
	err = deliver(db.pool, tag, args)
	return
}

func deliver(pool *redis.Pool, key string, data map[string]string) (err error) {
	hkey, err := RandomKey(GOOSE_REDIS_REQ_PREFIX, 16)
	if err != nil {
		return
	}

	conn := pool.Get()
	defer conn.Close()

	// Record the request/match.
	for field, val := range data {
		if err = conn.Send("HSET", hkey, field, val); err != nil {
			return
		}
	}

	// Notify any processes blocking on the associated list.
	if err = conn.Send("LPUSH", key, hkey); err != nil {
		return
	}

	// Flush the pipeline.
	if err = conn.Flush(); err != nil {
		return
	}

	// Read all of the replies, but just drop them on the ground.
	for i := 0; i < len(data)+1; i += 1 {
		if _, err = conn.Receive(); err != nil {
			return
		}
	}

	return
}

func makePool(net, addr string, db int) *redis.Pool {
	return &redis.Pool{
		MaxIdle:     3,
		IdleTimeout: 240 * time.Second,
		Dial: func() (c redis.Conn, err error) {
			c, err = redis.Dial(net, addr)
			if err != nil {
				return
			}

			_, err = c.Do("SELECT", db)
			if err != nil {
				c.Close()
				return
			}

			return
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
}

func copymap(dst, src map[string]string) {
	for k, v := range src {
		dst[k] = v
	}
}


text:
Tällä kerralla käydään läpi joitain rakenteita, jotka ovat idiomaattisia
Pythonissa, mutta eivät tyypillisiä (ainakaan kaikissa) muissa kielissä.

Yleensä Python ei ole ollut pioneeri missään, vaan on lainannut muista
kielistä näitä ideoita.  Lähinnä on nähty paljon vaivaa siihen, että
ominaisuudet olisivat "nättejä" ja sopisivat Pythonin muihin
ominaisuuksiin.

## Generaattorit ja perustietorakenteiden algebra

Tätä on käsitelty jo, mutta muutamia linkkejä:

 * Listakeräelmät: https://www.python.org/dev/peps/pep-0202/
 * Generaattorilauseet: https://www.python.org/dev/peps/pep-0289/
 * Iteraattorialgebra:
   https://docs.python.org/3/library/itertools.html#itertools-recipes
 * Funktionaalisia apuja:
   https://docs.python.org/3/library/functools.html ja erityisesti
   lisäkirjasto https://github.com/Suor/funcy

Iteraattoreita voi luoda kolmella tavalla:

 * Oliona:
   https://docs.python.org/3/library/stdtypes.html#iterator-types
 * Generaattorifunktiona: https://www.python.org/dev/peps/pep-0255/
   (tähän palataan myöhemmin)
 * Generaattorilauseena.

Iteraattoreilla voi tehdä potentiaalisesti äärettömiä kokoelmia:

```python
from itertools import *
list(islice(cycle([1,2,3]), 10))
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1]
```

Äärettömästä kokoelmasta voi tuottaa toisen äärettömän kokoelman:

```python
list(islice((el+7 for el in cycle([1,2,3]) if el%2), 10))
[8, 10, 8, 10, 8, 10, 8, 10, 8, 10]
```

## `with` ja kontekstinkäsittelijät

Tämä tuli jo vastaan testifixtureissa.  Kontekstinkäsittelijät on
tarkoitettu asioihin, joissa on tärkeää tietää, milloin tiettyä oliota
(resurssia, tms) lakataan käyttämästä.

 * alkuperäinen määrittely: https://www.python.org/dev/peps/pep-0343/
 * erilaisia avuliaiksi tarkoitettuja kontekstinkäsittelijöitä:
   https://docs.python.org/3/library/contextlib.html

Tietokannat, niiden transaktiot ja kursorit ovat yleensä
kontekstinkäsittelijöitä (toteuttavat kontekstiprotokollan).

 * Postgresille: http://initd.org/psycopg/docs/usage.html#with-statement
 * MySQL:lle:
   https://pythonhosted.org/oursql/api.html#cursor-context-manager
 * SQLitelle:
   https://docs.python.org/3/library/sqlite3.html#using-the-connection-as-a-context-manager

Usein, jos kokonainen funktio on wrapattu `with`-blokkiin, kannattaa
wrappausta varten tehdä koristerija.  Eli aasinsillan kautta:

## Koristelijat (dekoraattorit)

Koristelijat "muuntavat" määriteltävää funktiota haluamallaan tavalla.
Nämä kaksi tarkoittavat suunnilleen samaa:

```python
@koristele(argumentti)
def mun_funktio(x): return jotain(x)
```

ja

```python
def mun_funktio(x): return jotain(x)
mun_funktio = koristele(argumentti)(mun_funktio)
```

Mitä koristelija voi tehdä?  Ainakin:

 * Estää `mun_funktio`:n kutsumisen jossain tilanteessa
 * Kutsua `mun_funktio`:ta monta kertaa
 * Muutella `mun_funktio`:n argumentteja
 * Tehdä jotain (esim. lokitusta, resurssinvarauksia, ...) ennen ja
   jälkeen `mun_funktio`:n kutsujen
 * Merkitä jotain muistiin heti määrittelyvaiheessa

Lisää tietoa:

 * määrittely: https://www.python.org/dev/peps/pep-0318/
 * http://python-3-patterns-idioms-test.readthedocs.io/en/latest/PythonDecorators.html
 * Aivan sikana esimerkkikäyttötapauksia:
   https://stackoverflow.com/questions/489720/what-are-some-common-uses-for-python-decorators
 * Flask-kirjasto käyttää runsaasti dekoraattoreita antamaan
   lisämäärityksiä (ja osoitteita) erilaisten HTTP-kutsujen
   käsittelijöille:
   http://flask.pocoo.org/docs/0.12/patterns/viewdecorators/

## `yield` ja generaattorifunktiot

Generaattorifunktiot ovat keskeytettäviä suorituskonteksteja.  Tämä on
tosi monipuolinen ohjelmointitekniikka, jolla voi toteuttaa korutiineja,
asynkronisia ohjelmia ja vaikkapa kontekstinkäsittelijöitä.  Jos
"korutiini" ei ole tuttu sana, niin se on ... yleistys siitä mitä
vaikkapa Clojuren transduktorit tai Unixin putket pyrkivät tekemään :)

Generaattorifunktioilla voi tehdä asioita, jotka ovat epäluontevia
generaattorilauseilla:

```python
def fibonacci_seq():
    x, y = 1, 1
    while True:
        yield x
        x, y = y, x+y

list(islice(fibonacci_seq(), 10))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

```

Joskus saman saa tosin aikaan pahalla kikkailulla:

```python
list(islice((a for a, b in
  accumulate(cycle([(1,1)]), lambda x, _: (x[1], x[0]+x[1]))),
  10))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
```

Generaattorifunktiot voivat olla rekursiivisia:

```python
def numbers_from(x):
    yield x
    yield from numbers_from(x+1)

list(islice(numbers_from(1), 5))
[1, 2, 3, 4, 5]
```

Sillä voi tehdä asioita, jotka ovat vaan tosi vaikeita
generaattorilauseilla:

```python
def bifurcate(num):
    if num < 0: return
    yield from bifurcate(num-1)
    yield num
    yield from bifurcate(num-1)

list(bifurcate(3))
[0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0]
```

Taikka vaikka rekursiivisen Erastotheneen seulan:

```python
def sieve(nums):
    p = next(nums)
    yield p
    yield from sieve(n for n in nums if n%p)

list(islice(sieve(count(2)), 10))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
```

Olennaista on, että generaattoreiden on helppoa kutsua toisiaan.

```python
def insane_processing_step(coll):
    acc = 15
    for num in coll:
        acc = int((num - acc) * .75)
        yield acc

list(islice(insane_processing_step(count(0)), 15))
[-11, 9, -5, 6, -1, 4, 1, 4, 3, 4, 4, 5, 5, 6, 6]
```

## Asynkroninen ohjelmointi

Koska generaattorit pystyvät keskeyttämään koodin suorituksen tiettyyn
pisteeseen (`yield`) ja jatkamaan siitä pyydettäessä, niitä käytetään
myös asynkronisessa ohjelmoinnissa kertomaan, että ohjelma haluaa
odotella jotain ja on aika tehdä välillä jotain muuta.  Mutta viime
aikoina Pythonissa on asteittain rakennettu erillinen tuki
asynkroniselle ohjelmoinnille ja generaattoreita yritetään kovasti
eriyttää asynkronisista korutiineista.

Esimerkkejä nykyaikaisesta asynkronisesta Python-ohjelmoinnista löytyy
vaikkapa täältä: https://aiohttp.readthedocs.io/en/stable/


text:
package org.conqat.engine.text.comments.utils;

/**
 * Tags used in the training data set
 *
 * @author $Author: steidl $
 * @version $Rev: 46589 $
 * @ConQAT.Rating YELLOW Hash: EF0D472E2BC367A339936CEF26747091
 */
public class CommentTags {

	/**
	 * separator tag, comments are tagged like /** &copyright&
	 */
	public static final String separator = "§";

	/** copyright tag */
	public static final String tagCopyright = "copyright";
	/** interface tag */
	public static final String tagInterface = "interface";
	/** header */
	public static final String tagHeader = "header";
	/** inline tag */
	public static final String tagInline = "inline";
	/** code tag */
	public static final String tagCode = "code";
	/** task tag */
	public static final String tagTask = "task";
	/** section tag */
	public static final String tagSection = "section";

	/** Returns true if the given string if a comment tag. */
	public static boolean isTag(String tag) {
		return ((tagCopyright.equals(tag)) || (tagInterface.equals(tag))
				|| (tagHeader.equals(tag)) || (tagInline.equals(tag))
				|| (tagCode.equals(tag)) || (tagTask.equals(tag)) || (tagSection
					.equals(tag)));
	}
}


text:
use std::fmt;

use super::Field;
use byteorder::{BigEndian, ByteOrder};
use common;
use schema::Facet;
use std::str;
use DateTime;

/// Size (in bytes) of the buffer of a int field.
const INT_TERM_LEN: usize = 4 + 8;

/// Term represents the value that the token can take.
///
/// It actually wraps a `Vec<u8>`.
#[derive(Clone, PartialEq, PartialOrd, Ord, Eq, Hash)]
pub struct Term<B = Vec<u8>>(B)
where
    B: AsRef<[u8]>;

impl Term {
    /// Builds a term given a field, and a u64-value
    ///
    /// Assuming the term has a field id of 1, and a u64 value of 3234,
    /// the Term will have 8 bytes.
    ///
    /// The first four byte are dedicated to storing the field id as a u64.
    /// The 4 following bytes are encoding the u64 value.
    pub fn from_field_i64(field: Field, val: i64) -> Term {
        let val_u64: u64 = common::i64_to_u64(val);
        Term::from_field_u64(field, val_u64)
    }

    /// Builds a term given a field, and a DateTime value
    ///
    /// Assuming the term has a field id of 1, and a timestamp i64 value of 3234,
    /// the Term will have 8 bytes.
    ///
    /// The first four byte are dedicated to storing the field id as a u64.
    /// The 4 following bytes are encoding the DateTime as i64 timestamp value.
    pub fn from_field_date(field: Field, val: &DateTime) -> Term {
        let val_timestamp = val.timestamp();
        Term::from_field_i64(field, val_timestamp)
    }

    /// Creates a `Term` given a facet.
    pub fn from_facet(field: Field, facet: &Facet) -> Term {
        let bytes = facet.encoded_str().as_bytes();
        let buffer = Vec::with_capacity(4 + bytes.len());
        let mut term = Term(buffer);
        term.set_field(field);
        term.set_bytes(bytes);
        term
    }

    /// Builds a term given a field, and a string value
    ///
    /// Assuming the term has a field id of 2, and a text value of "abc",
    /// the Term will have 4 bytes.
    /// The first byte is 2, and the three following bytes are the utf-8
    /// representation of "abc".
    pub fn from_field_text(field: Field, text: &str) -> Term {
        let buffer = Vec::with_capacity(4 + text.len());
        let mut term = Term(buffer);
        term.set_field(field);
        term.set_text(text);
        term
    }

    /// Builds a term given a field, and a u64-value
    ///
    /// Assuming the term has a field id of 1, and a u64 value of 3234,
    /// the Term will have 8 bytes.
    ///
    /// The first four byte are dedicated to storing the field id as a u64.
    /// The 4 following bytes are encoding the u64 value.
    pub fn from_field_u64(field: Field, val: u64) -> Term {
        let mut term = Term(vec![0u8; INT_TERM_LEN]);
        term.set_field(field);
        term.set_u64(val);
        term
    }

    /// Creates a new Term for a given field.
    pub(crate) fn for_field(field: Field) -> Term {
        let mut term = Term(Vec::with_capacity(100));
        term.set_field(field);
        term
    }

    /// Returns the field.
    pub fn set_field(&mut self, field: Field) {
        if self.0.len() < 4 {
            self.0.resize(4, 0u8);
        }
        BigEndian::write_u32(&mut self.0[0..4], field.0);
    }

    /// Sets a u64 value in the term.
    ///
    /// U64 are serialized using (8-byte) BigEndian
    /// representation.
    /// The use of BigEndian has the benefit of preserving
    /// the natural order of the values.
    pub fn set_u64(&mut self, val: u64) {
        self.0.resize(INT_TERM_LEN, 0u8);
        BigEndian::write_u64(&mut self.0[4..], val);
    }

    /// Sets a `i64` value in the term.
    pub fn set_i64(&mut self, val: i64) {
        self.set_u64(common::i64_to_u64(val));
    }

    fn set_bytes(&mut self, bytes: &[u8]) {
        self.0.resize(4, 0u8);
        self.0.extend(bytes);
    }

    pub(crate) fn from_field_bytes(field: Field, bytes: &[u8]) -> Term {
        let mut term = Term::for_field(field);
        term.set_bytes(bytes);
        term
    }

    /// Set the texts only, keeping the field untouched.
    pub fn set_text(&mut self, text: &str) {
        self.set_bytes(text.as_bytes());
    }
}

impl<B> Term<B>
where
    B: AsRef<[u8]>,
{
    /// Wraps a source of data
    pub fn wrap(data: B) -> Term<B> {
        Term(data)
    }

    /// Returns the field.
    pub fn field(&self) -> Field {
        Field(BigEndian::read_u32(&self.0.as_ref()[..4]))
    }

    /// Returns the `u64` value stored in a term.
    ///
    /// # Panics
    /// ... or returns an invalid value
    /// if the term is not a `u64` field.
    pub fn get_u64(&self) -> u64 {
        BigEndian::read_u64(&self.0.as_ref()[4..])
    }

    /// Returns the `i64` value stored in a term.
    ///
    /// # Panics
    /// ... or returns an invalid value
    /// if the term is not a `i64` field.
    pub fn get_i64(&self) -> i64 {
        common::u64_to_i64(BigEndian::read_u64(&self.0.as_ref()[4..]))
    }

    /// Returns the text associated with the term.
    ///
    /// # Panics
    /// If the value is not valid utf-8. This may happen
    /// if the index is corrupted or if you try to
    /// call this method on a non-string type.
    pub fn text(&self) -> &str {
        str::from_utf8(self.value_bytes()).expect("Term does not contain valid utf-8.")
    }

    /// Returns the serialized value of the term.
    /// (this does not include the field.)
    ///
    /// If the term is a string, its value is utf-8 encoded.
    /// If the term is a u64, its value is encoded according
    /// to `byteorder::LittleEndian`.
    pub fn value_bytes(&self) -> &[u8] {
        &self.0.as_ref()[4..]
    }

    /// Returns the underlying `&[u8]`
    pub fn as_slice(&self) -> &[u8] {
        self.0.as_ref()
    }
}

impl<B> AsRef<[u8]> for Term<B>
where
    B: AsRef<[u8]>,
{
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

impl fmt::Debug for Term {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Term({:?})", &self.0[..])
    }
}

#[cfg(test)]
mod tests {

    use schema::*;

    #[test]
    pub fn test_term() {
        let mut schema_builder = Schema::builder();
        schema_builder.add_text_field("text", STRING);
        let title_field = schema_builder.add_text_field("title", STRING);
        let count_field = schema_builder.add_text_field("count", STRING);
        {
            let term = Term::from_field_text(title_field, "test");
            assert_eq!(term.field(), title_field);
            assert_eq!(&term.as_slice()[0..4], &[0u8, 0u8, 0u8, 1u8]);
            assert_eq!(&term.as_slice()[4..], "test".as_bytes());
        }
        {
            let term = Term::from_field_u64(count_field, 983u64);
            assert_eq!(term.field(), count_field);
            assert_eq!(&term.as_slice()[0..4], &[0u8, 0u8, 0u8, 2u8]);
            assert_eq!(term.as_slice().len(), 4 + 8);
            assert_eq!(term.as_slice()[4], 0u8);
            assert_eq!(term.as_slice()[5], 0u8);
            assert_eq!(term.as_slice()[6], 0u8);
            assert_eq!(term.as_slice()[7], 0u8);
            assert_eq!(term.as_slice()[8], 0u8);
            assert_eq!(term.as_slice()[9], 0u8);
            assert_eq!(term.as_slice()[10], (933u64 / 256u64) as u8);
            assert_eq!(term.as_slice()[11], (983u64 % 256u64) as u8);
        }
    }
}


text:
"""
Tests for L{twisted.python.monkey}.
"""

from twisted.trial import unittest
from twisted.python.monkey import MonkeyPatcher

class TestObj:
    def __init__(self):
        self.foo = 'foo value'
        self.bar = 'bar value'
        self.baz = 'baz value'

class MonkeyPatcherTest(unittest.TestCase):
    """
    Tests for L{MonkeyPatcher} monkey-patching class.
    """

    def setUp(self):
        self.testObject = TestObj()
        self.originalObject = TestObj()
        self.monkeyPatcher = MonkeyPatcher()

    def test_empty(self):
        """
        A monkey patcher without patches shouldn't change a thing.
        """
        self.monkeyPatcher.patch()

        # We can't assert that all state is unchanged, but at least we can
        # check our test object.
        self.assertEqual(self.originalObject.foo, self.testObject.foo)
        self.assertEqual(self.originalObject.bar, self.testObject.bar)
        self.assertEqual(self.originalObject.baz, self.testObject.baz)

    def test_constructWithPatches(self):
        """
        Constructing a L{MonkeyPatcher} with patches should add all of the
        given patches to the patch list.
        """
        patcher = MonkeyPatcher((self.testObject, 'foo', 'haha'),
                                (self.testObject, 'bar', 'hehe'))
        patcher.patch()
        self.assertEqual('haha', self.testObject.foo)
        self.assertEqual('hehe', self.testObject.bar)
        self.assertEqual(self.originalObject.baz, self.testObject.baz)

    def test_patchExisting(self):
        """
        Patching an attribute that exists sets it to the value defined in the
        patch.
        """
        self.monkeyPatcher.addPatch(self.testObject, 'foo', 'haha')
        self.monkeyPatcher.patch()
        self.assertEqual(self.testObject.foo, 'haha')

    def test_patchNonExisting(self):
        """
        Patching a non-existing attribute fails with an C{AttributeError}.
        """
        self.monkeyPatcher.addPatch(self.testObject, 'nowhere',
                                    'blow up please')
        self.assertRaises(AttributeError, self.monkeyPatcher.patch)

    def test_patchAlreadyPatched(self):
        """
        Adding a patch for an object and attribute that already have a patch
        overrides the existing patch.
        """
        self.monkeyPatcher.addPatch(self.testObject, 'foo', 'blah')
        self.monkeyPatcher.addPatch(self.testObject, 'foo', 'BLAH')
        self.monkeyPatcher.patch()
        self.assertEqual(self.testObject.foo, 'BLAH')
        self.monkeyPatcher.restore()
        self.assertEqual(self.testObject.foo, self.originalObject.foo)

    def test_restoreTwiceIsANoOp(self):
        """
        Restoring an already-restored monkey patch is a no-op.
        """
        self.monkeyPatcher.addPatch(self.testObject, 'foo', 'blah')
        self.monkeyPatcher.patch()
        self.monkeyPatcher.restore()
        self.assertEqual(self.testObject.foo, self.originalObject.foo)
        self.monkeyPatcher.restore()
        self.assertEqual(self.testObject.foo, self.originalObject.foo)

    def test_runWithPatchesDecoration(self):
        """
        runWithPatches should run the given callable, passing in all arguments
        and keyword arguments, and return the return value of the callable.
        """
        log = []

        def f(a, b, c=None):
            log.append((a, b, c))
            return 'foo'

        result = self.monkeyPatcher.runWithPatches(f, 1, 2, c=10)
        self.assertEqual('foo', result)
        self.assertEqual([(1, 2, 10)], log)

    def test_repeatedRunWithPatches(self):
        """
        We should be able to call the same function with runWithPatches more
        than once. All patches should apply for each call.
        """
        def f():
            return (self.testObject.foo, self.testObject.bar,
                    self.testObject.baz)

        self.monkeyPatcher.addPatch(self.testObject, 'foo', 'haha')
        result = self.monkeyPatcher.runWithPatches(f)
        self.assertEqual(
            ('haha', self.originalObject.bar, self.originalObject.baz), result)
        result = self.monkeyPatcher.runWithPatches(f)
        self.assertEqual(
            ('haha', self.originalObject.bar, self.originalObject.baz),
            result)

    def test_runWithPatchesRestores(self):
        """
        C{runWithPatches} should restore the original values after the function
        has executed.
        """
        self.monkeyPatcher.addPatch(self.testObject, 'foo', 'haha')
        self.assertEqual(self.originalObject.foo, self.testObject.foo)
        self.monkeyPatcher.runWithPatches(lambda: None)
        self.assertEqual(self.originalObject.foo, self.testObject.foo)

    def test_runWithPatchesRestoresOnException(self):
        """
        Test runWithPatches restores the original values even when the function
        raises an exception.
        """
        def _():
            self.assertEqual(self.testObject.foo, 'haha')
            self.assertEqual(self.testObject.bar, 'blahblah')
            raise RuntimeError, "Something went wrong!"

        self.monkeyPatcher.addPatch(self.testObject, 'foo', 'haha')
        self.monkeyPatcher.addPatch(self.testObject, 'bar', 'blahblah')

        self.assertRaises(RuntimeError, self.monkeyPatcher.runWithPatches, _)
        self.assertEqual(self.testObject.foo, self.originalObject.foo)
        self.assertEqual(self.testObject.bar, self.originalObject.bar)