text:
package org.odk.collect.android.activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.spatial.MapHelper;
import org.odk.collect.android.utilities.InfoLogger;
import org.odk.collect.android.utilities.PlayServicesUtil;
import org.odk.collect.android.utilities.ToastUtils;
import org.odk.collect.android.widgets.GeoPointWidget;

import java.text.DecimalFormat;
import java.util.List;

/**
 * Version of the GeoPointMapActivity that uses the new Maps v2 API and Fragments to enable
 * specifying a location via placing a tracker on a map.
 *
 * @author guisalmon@gmail.com
 * @author jonnordling@gmail.com
 */
public class GeoPointMapActivity extends FragmentActivity implements LocationListener,
        OnMarkerDragListener, OnMapLongClickListener {

    private static final String LOCATION_COUNT = "locationCount";

    private GoogleMap mMap;
    private MarkerOptions mMarkerOption;
    private Marker mMarker;
    private LatLng mLatLng;

    private TextView mLocationStatus;
    private TextView mlocationInfo;

    private LocationManager mLocationManager;

    private Location mLocation;
    private Button mAcceptLocation;
    private Button mReloadLocation;

    private boolean mRefreshLocation = true;
    private boolean mIsDragged = false;
    private Button mShowLocation;
    private Button mLayers;
    private boolean mGPSOn = false;
    private boolean mNetworkOn = false;

    private double mLocationAccuracy;
    private int mLocationCount = 0;

    private boolean mZoomed = false;
    private MapHelper mHelper;
//	private KmlLayer kk;

    private AlertDialog zoomDialog;
    private View zoomDialogView;

    private Button zoomPointButton;
    private Button zoomLocationButton;

    private Button clearPointButton;

    private boolean setClear = false;
    private boolean mCaptureLocation = false;
    private Boolean foundFirstLocation = false;
    private int location_count_num = 0;
    private int location_count_found_limit = 1;
    private Boolean read_only = false;
    private Boolean draggable = false;
    private Boolean intent_draggable = false;
    private Boolean location_from_intent = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        if (savedInstanceState != null) {
            mLocationCount = savedInstanceState.getInt(LOCATION_COUNT);
        }

        try {
            setContentView(R.layout.geopoint_layout);
        } catch (NoClassDefFoundError e) {
            e.printStackTrace();
            ToastUtils.showShortToast(R.string.google_play_services_error_occured);
            finish();
            return;
        }

        if (PlayServicesUtil.checkPlayServices(GeoPointMapActivity.this)) {
            ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                    setupMap(googleMap);
                }
            });
        } else {
            PlayServicesUtil.requestPlayServicesErrorDialog(GeoPointMapActivity.this);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Collect.getInstance().getActivityLogger().logOnStart(this);
    }

    @Override
    protected void onStop() {
        Collect.getInstance().getActivityLogger().logOnStop(this);
        super.onStop();
    }

    private void returnLocation() {
        Intent i = new Intent();
        if (setClear || (read_only && mLatLng == null)) {
            i.putExtra(FormEntryActivity.LOCATION_RESULT, "");
            setResult(RESULT_OK, i);

        } else if (mIsDragged || read_only || location_from_intent) {
            Log.i(getClass().getName(), "IsDragged !!!");
            i.putExtra(
                    FormEntryActivity.LOCATION_RESULT,
                    mLatLng.latitude + " " + mLatLng.longitude + " "
                            + 0 + " " + 0);
            setResult(RESULT_OK, i);
        } else if (mLocation != null) {
            Log.i(getClass().getName(), "IsNotDragged !!!");

            i.putExtra(
                    FormEntryActivity.LOCATION_RESULT,
                    mLocation.getLatitude() + " " + mLocation.getLongitude() + " "
                            + mLocation.getAltitude() + " " + mLocation.getAccuracy());
            setResult(RESULT_OK, i);
        }
        finish();
    }

    private String truncateFloat(float f) {
        return new DecimalFormat("#.##").format(f);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mLocationManager != null) {
            mLocationManager.removeUpdates(this);
        }
    }

    private void setupMap(GoogleMap googleMap) {
        mMap = googleMap;
        if (mMap == null) {
            ToastUtils.showShortToast(R.string.google_play_services_error_occured);
            finish();
            return;
        }
        mHelper = new MapHelper(GeoPointMapActivity.this, mMap);
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setCompassEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
        mMap.getUiSettings().setZoomControlsEnabled(false);

        mMarkerOption = new MarkerOptions();
        mHelper = new MapHelper(this, mMap);

        mLocationAccuracy = GeoPointWidget.DEFAULT_LOCATION_ACCURACY;

        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocationStatus = (TextView) findViewById(R.id.location_status);
        mlocationInfo = (TextView) findViewById(R.id.location_info);

        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        mAcceptLocation = (Button) findViewById(R.id.accept_location);

        mAcceptLocation.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Collect.getInstance().getActivityLogger().logInstanceAction(this, "acceptLocation",
                        "OK");
                returnLocation();
            }
        });

        mReloadLocation = (Button) findViewById(R.id.reload_location);
        mReloadLocation.setEnabled(false);
        mReloadLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMarker != null) {
                    mMarker.remove();
                }
                mLatLng = null;
                mMarker = null;
                setClear = false;
                mLatLng = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
                mMarkerOption.position(mLatLng);
                if (mMarker == null) {
                    mMarker = mMap.addMarker(mMarkerOption);
                    if (draggable && !read_only) {
                        mMarker.setDraggable(true);
                    }
                }
                mCaptureLocation = true;
                mIsDragged = false;
                zoomToPoint();
            }
        });

        // Focuses on marked location
        mShowLocation = ((Button) findViewById(R.id.show_location));
        //mShowLocation.setClickable(false);
        mShowLocation.setEnabled(false);
        mShowLocation.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showZoomDialog();
            }
        });

        // Menu Layer Toggle
        mLayers = ((Button) findViewById(R.id.layer_menu));
        mLayers.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mHelper.showLayersDialog(GeoPointMapActivity.this);
            }
        });
        zoomDialogView = getLayoutInflater().inflate(R.layout.geopoint_zoom_dialog, null);
        zoomLocationButton = (Button) zoomDialogView.findViewById(R.id.zoom_location);
        zoomLocationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zoomToLocation();
                zoomDialog.dismiss();
            }
        });

        zoomPointButton = (Button) zoomDialogView.findViewById(R.id.zoom_point);
        zoomPointButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zoomToPoint();
                zoomDialog.dismiss();
            }
        });

        clearPointButton = (Button) findViewById(R.id.clear);
        clearPointButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMarker != null) {
                    mMarker.remove();
                }
                if (mLocation != null) {
                    mReloadLocation.setEnabled(true);
                    // mLocationStatus.setVisibility(View.VISIBLE);
                }
                // mReloadLocation.setEnabled(true);
                mlocationInfo.setVisibility(View.VISIBLE);
                mLocationStatus.setVisibility(View.VISIBLE);
                mLatLng = null;
                mMarker = null;
                setClear = true;
                mIsDragged = false;
                mCaptureLocation = false;
                draggable = intent_draggable;
                location_from_intent = false;
                overlayMyLocationLayers();
            }
        });

        Intent intent = getIntent();
        if (intent != null && intent.getExtras() != null) {
            if (intent.hasExtra(GeoPointWidget.DRAGGABLE_ONLY)) {
                draggable = intent.getBooleanExtra(GeoPointWidget.DRAGGABLE_ONLY, false);
                intent_draggable = draggable;
                if (!intent_draggable) {
                    // Not Draggable, set text for Map else leave as placement-map text
                    mlocationInfo.setText(getString(R.string.geopoint_no_draggable_instruction));
                }
            }

            if (intent.hasExtra(GeoPointWidget.READ_ONLY)) {
                read_only = intent.getBooleanExtra(GeoPointWidget.READ_ONLY, false);
                if (read_only) {
                    mCaptureLocation = true;
                    clearPointButton.setEnabled(false);
                }
            }

            if (intent.hasExtra(GeoPointWidget.LOCATION)) {
                double[] location = intent.getDoubleArrayExtra(GeoPointWidget.LOCATION);
                mLatLng = new LatLng(location[0], location[1]);
                mCaptureLocation = true;
                mReloadLocation.setEnabled(false);
                draggable = false; // If data loaded, must clear first
                location_from_intent = true;

            }

            if (intent.hasExtra(GeoPointWidget.ACCURACY_THRESHOLD)) {
                mLocationAccuracy = intent.getDoubleExtra(GeoPointWidget.ACCURACY_THRESHOLD,
                        GeoPointWidget.DEFAULT_LOCATION_ACCURACY);
            }
        }

		/*Zoom only if there's a previous location*/
        if (mLatLng != null) {
            mlocationInfo.setVisibility(View.GONE);
            mLocationStatus.setVisibility(View.GONE);
            mShowLocation.setEnabled(true);
            mMarkerOption.position(mLatLng);
            mMarker = mMap.addMarker(mMarkerOption);
            mCaptureLocation = true;
            foundFirstLocation = true;
            mZoomed = true;
            zoomToPoint();
        }

        mHelper.setBasemap();
        upMyLocationOverlayLayers();
    }

    private void upMyLocationOverlayLayers() {
        // make sure we have a good location provider before continuing
        location_count_num = 0;
        List<String> providers = mLocationManager.getProviders(true);
        for (String provider : providers) {
            if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
                mGPSOn = true;
                mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
                location_count_found_limit = 0;
            } else if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) {
                // Only if GPS Providor is not avaibe use network location. bug (well know
                // android bug) http://stackoverflow
                // .com/questions/6719207/locationmanager-returns-old-cached-wifi-location-with
                // -current-timestamp
                mNetworkOn = true;
                location_count_found_limit =
                        1; // increase count due to network location bug (well know android bug)
                mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                        this);
            }
        }
//		mShowLocation.setClickable(mMarker != null);
        if (!mGPSOn && !mNetworkOn) {
            showGPSDisabledAlertToUser();
        } else {
            overlayMyLocationLayers();
        }
    }

    private void overlayMyLocationLayers() {
        if (draggable & !read_only) {
            mMap.setOnMarkerDragListener(this);
            mMap.setOnMapLongClickListener(this);
            if (mMarker != null) {
                mMarker.setDraggable(true);
            }
        }

    }

    @Override
    public void onLocationChanged(Location location) {
        mLocation = location;
        if (setClear) {
            mReloadLocation.setEnabled(true);
        }
        if (mLocation != null) {

            if (location_count_num >= location_count_found_limit) {
                mShowLocation.setEnabled(true);
                if (!mCaptureLocation & !setClear) {
                    mLatLng = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
                    mMarkerOption.position(mLatLng);
                    mMarker = mMap.addMarker(mMarkerOption);
                    mCaptureLocation = true;
                    mReloadLocation.setEnabled(true);
                }
                if (!foundFirstLocation) {
//					zoomToPoint();
                    showZoomDialog();
                    foundFirstLocation = true;
                }
                mLocationStatus.setText(
                        getString(R.string.location_provider_accuracy, mLocation.getProvider(),
                                truncateFloat(mLocation.getAccuracy())));
            } else {
                // Prevent from forever increasing
                if (location_count_num <= 100) {
                    location_count_num++;
                }
            }
        } else {
            InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
                    " onLocationChanged(" + mLocationCount + ") null location");
        }

    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onMarkerDrag(Marker arg0) {

    }

    @Override
    public void onMarkerDragEnd(Marker marker) {
        mLatLng = marker.getPosition();
        mIsDragged = true;
        mCaptureLocation = true;
        setClear = false;
        mMap.animateCamera(
                CameraUpdateFactory.newLatLngZoom(mLatLng, mMap.getCameraPosition().zoom));

    }

    @Override
    public void onMarkerDragStart(Marker arg0) {

    }

    @Override
    public void onMapLongClick(LatLng latLng) {
        mLatLng = latLng;
        if (mMarker == null) {
            mMarkerOption.position(latLng);
            mMarker = mMap.addMarker(mMarkerOption);
        } else {
            mMarker.setPosition(latLng);
        }
        mShowLocation.setEnabled(true);
        mMarker.setDraggable(true);
        mIsDragged = true;
        setClear = false;
        mCaptureLocation = true;
    }

    private void zoomToLocation() {
        LatLng here = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
        if (mLocation != null) {
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(here, 16));
        }
    }

    private void zoomToPoint() {
        if (mLatLng != null) {
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mMarker.getPosition(), 16));
        }

    }

    public void showZoomDialog() {

        if (zoomDialog == null) {
            AlertDialog.Builder p_builder = new AlertDialog.Builder(this);
            p_builder.setTitle(getString(R.string.zoom_to_where));
            p_builder.setView(zoomDialogView)
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    })
                    .setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            dialog.cancel();
                            zoomDialog.dismiss();
                        }
                    });
            zoomDialog = p_builder.create();
        }
        //If feature enable zoom to button else disable
        if (mLocation != null) {
            zoomLocationButton.setEnabled(true);
            zoomLocationButton.setBackgroundColor(Color.parseColor("#50cccccc"));
            zoomLocationButton.setTextColor(Color.parseColor("#ff333333"));
        } else {
            zoomLocationButton.setEnabled(false);
            zoomLocationButton.setBackgroundColor(Color.parseColor("#50e2e2e2"));
            zoomLocationButton.setTextColor(Color.parseColor("#FF979797"));
        }

        if (mLatLng != null & !setClear) {
            zoomPointButton.setEnabled(true);
            zoomPointButton.setBackgroundColor(Color.parseColor("#50cccccc"));
            zoomPointButton.setTextColor(Color.parseColor("#ff333333"));
        } else {
            zoomPointButton.setEnabled(false);
            zoomPointButton.setBackgroundColor(Color.parseColor("#50e2e2e2"));
            zoomPointButton.setTextColor(Color.parseColor("#FF979797"));
        }

        zoomDialog.show();

    }

    private void showGPSDisabledAlertToUser() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage(getString(R.string.gps_enable_message))
                .setCancelable(false)
                .setPositiveButton(getString(R.string.enable_gps),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                startActivityForResult(
                                        new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
                            }
                        });
        alertDialogBuilder.setNegativeButton(getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PlayServicesUtil.PLAY_SERVICE_ERROR_REQUEST_CODE) {
            finish();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}


text:
/* -*- c-file-style:"stroustrup"; indent-tabs-mode: nil -*- */

#if !defined INC_PUBNUB_FNTEST_MEDIUM
#define      INC_PUBNUB_FNTEST_MEDIUM

#include <string>

void complex_send_and_receive_over_several_channels_simultaneously(std::string const &pubkey, std::string const &keysub);

#endif // !defined INC_PUBNUB_FNTEST_MEDIUM

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
	exit;
}

global $table_prefix;
define('MODS_TABLE', $table_prefix . 'mods');

define('WRITE_DIRECT', 1);
define('WRITE_FTP', 2);
define('WRITE_MANUAL', 3);

function test_ftp_connection($method, &$test_ftp_connection, &$test_connection)
{
	global $phpbb_root_path, $phpEx;

	$transfer = new $method(request_var('host', ''), request_var('username', ''), request_var('password', ''), request_var('root_path', ''), request_var('port', ''), request_var('timeout', ''));

	$test_connection = $transfer->open_session();

	// Make sure that the directory is correct by checking for the existence of common.php
	if ($test_connection === true)
	{
		// Check for common.php file
		if (!$transfer->file_exists($phpbb_root_path, 'common.' . $phpEx))
		{
			$test_connection = 'ERR_WRONG_PATH_TO_PHPBB';
		}
	}

	$transfer->close_session();

	// Make sure the login details are correct before continuing
	if ($test_connection !== true)
	{
		$test_ftp_connection = true;
	}

	return;
}

/**
* Helper function
* Runs basename() on $path, then trims the extension from it
* @param string $path - path to be basenamed
*/
function core_basename($path)
{
	$path = basename($path);
	$path = substr($path, 0, strrpos($path, '.'));

	$parts = explode('-', $path);
	return end($parts);
}

/**
* Helper function for matching languages
* This is a fairly dumb function because it ignores dialects.  But I have
* not seen any MODs that specify more than one dialect of the same language
* @param string $user_language - ISO language code of the current user
* @param string $xml_language - ISO language code of the MODX tag
* @return bool Whether or not this is a match
*/
function match_language($user_language, $xml_language)
{
	return strtolower(substr($user_language, 0, 2)) == strtolower(substr($xml_language, 0, 2));
}

/**
* Grab MOD titles
*
* @param $header - variable holding all relevant tag information
* @return array(language iso => MOD name)
*/
function get_title($header)
{
	if (is_string($header['TITLE']))
	{
		return($header['TITLE']);
	}

	$return = array();
	foreach ($header['TITLE'] as $row)
	{
		if (!is_array($row))
		{
			continue;
		}

		$return[$row['attrs']['LANG']] = trim($row['data']);
	}

	return($return);
}

/**
 * Get localized MOD title or English title
 *
 * @param $titles, string or a serialized array containing the MOD name(s)
 * @param $lang, string language ISO.
 * @return string with MOD name in users selected language or English.
 */
function localize_title($title, $lang = 'en')
{
	$name_ary = array();

	if (!is_array($title))
	{
		if (($name_ary = @unserialize($title)) === false)
		{
			// Before AutoMOD 1.0.1 the title was a string with only the MOD name.
			return($title);
		}
	}
	else
	{
		$name_ary = $title;
	}

	// If we get here the MOD is installed with AutoMOD 1.0.1+
	// And the stored title is a serialized array.
	if (!empty($name_ary[$lang]))
	{
		return($name_ary[$lang]);
	}
	else if (!empty($name_ary['en']))
	{
		// Default to English if the selected language is not found.
		return($name_ary['en']);
	}

	// Something went wrong.
	// We have a array that neither contain the selected language nor English.
	// Return the first array element.
	return(array_shift($name_ary));
}

/**
* Easy method to grab localisable tags from the XML array
* @param $header - variable holding all relevant tag information
* @param $tagname - tag name to fetch
* @param $index - Index number to pull.  Not required.
* @return $output - Localised contents of the tag in question
*/
function localise_tags($header, $tagname, $index = false)
{
	global $user;

	$output = '';

	if (isset($header[$tagname]) && is_array($header[$tagname]))
	{
		foreach ($header[$tagname] as $i => $void)
		{
			// Ugly.
			if ($index !== false && $index != $i)
			{
				continue;
			}

			if (!isset($header[$tagname][$i]['attrs']['LANG']))
			{
				// avoid notice...although, if we get here, MODX is invalid.
				continue;
			}

			if (match_language($user->data['user_lang'], $header[$tagname][$i]['attrs']['LANG']))
			{
				$output = isset($header[$tagname][$i]['data']) ? htmlspecialchars(trim($header[$tagname][$i]['data'])) : '';
			}
			else if (match_language('en', $header[$tagname][$i]['attrs']['LANG']))
			{
				$output = isset($header[$tagname][$i]['data']) ? htmlspecialchars(trim($header[$tagname][$i]['data'])) : '';
			}
		}

		// If there was no language match, put something out there
		// This is probably fairly common for non-English users of the MODs Manager
		if (!$output)
		{
			$output = isset($header[$tagname][0]['data']) ? htmlspecialchars(trim($header[$tagname][0]['data'])) : '';
		}
	}

	if (!$output)
	{
		// Should never happen.  If it does, either the MOD is not valid MODX
		// or the tag being localised is optional
		$output = isset($user->lang['UNKNOWN_MOD_' . $tagname]) ? $user->lang['UNKNOWN_MOD_' . $tagname] : 'UNKNOWN_MOD_' .$tagname;
	}

	return $output;
}

/**
* List files matching specified PCRE pattern.
*
* @access public
* @param string Relative or absolute path to the directory to be scanned.
* @param string Search pattern (perl compatible regular expression).
* @param integer Number of subdirectory levels to scan (set to 1 to scan only current).
* @param boolean List sub-directories only instead of files
* @param integer This one is used internally to control recursion level.
* @return array List of all files found matching the specified pattern.
*/
function find_files($directory, $pattern, $max_levels = 20, $subdirs_only = false, $_current_level = 1)
{
	if ($_current_level <= 1)
	{
		if (strpos($directory, '\\') !== false)
		{
			$directory = str_replace('\\', '/', $directory);
		}
		if (empty($directory))
		{
			$directory = './';
		}
		else if (substr($directory, -1) != '/')
		{
			$directory .= '/';
		}
	}

	$files = array();
	$subdir = array();
	if (is_dir($directory))
	{
		$handle = @opendir($directory);
		while (($file = @readdir($handle)) !== false)
		{
			if ($file == '.' || $file == '..')
			{
				continue;
			}

			$fullname = $directory . $file;

			if (is_dir($fullname))
			{
				if ($_current_level < $max_levels)
				{
					if ($subdirs_only)
					{
						$subdir[] = $fullname . '/';
						$subdir = array_merge($subdir, find_files($fullname . '/', $pattern, $max_levels, true, $_current_level + 1));
					}
					else
					{
						$subdir = array_merge($subdir, find_files($fullname . '/', $pattern, $max_levels, false, $_current_level + 1));
					}
				}
			}
			else
			{
				if (!$subdirs_only && preg_match('/^' . $pattern . '$/i', $file))
				{
					$files[] = $fullname;
				}
			}
		}
		@closedir($handle);
		sort($files);
	}

	return array_merge($files, $subdir);
}

/**
* This function is common to all editor classes, so it is pulled out from them
* @param $filename - The filename to update
* @param $template_id - The template set to update
* @param $file_contents - The data to write
* @param $install_time - Essentially the current time
* @return bool true
*/
function update_database_template($filename, $template_id, $file_contents, $install_time)
{
	global $db;

	// grab filename
	preg_match('#styles/[a-z0-9_]+/template/([a-z0-9_]+.html)#i', $filename, $match);

	if (empty($match[1]))
	{
		return false;
	}

	$sql = 'UPDATE ' . STYLES_TEMPLATE_DATA_TABLE . "
		SET template_data = '" . $db->sql_escape($file_contents) . "', template_mtime = " . (int) $install_time . '
		WHERE template_id = ' . (int) $template_id . "
		AND template_filename = '" . $db->sql_escape($match[1]) . "'";
	$db->sql_query($sql);

	// if something failed, sql_query will error out
	return true;
}

function determine_write_method($preview = false)
{
	global $phpbb_root_path, $config;

	// to be truly correct, we should scan all files ...
	if (($config['write_method'] == WRITE_DIRECT && is_writable($phpbb_root_path)) || $preview)
	{
		$write_method = 'direct';
	}
	// FTP Method is now auto-detected
	else if ($config['write_method'] == WRITE_FTP)
	{
		$write_method = 'ftp';
	}
	// or zip or tarballs
	else if ($config['compress_method'])
	{
		$write_method = 'manual';
	}
	else
	{
		// We cannot go on without a write method set up.
		trigger_error('MODS_SETUP_INCOMPLETE', E_USER_ERROR);
	}

	return $write_method;
}

function handle_ftp_details($method, $test_ftp_connection, $test_connection)
{
	global $config, $template, $user;

	$s_hidden_fields = build_hidden_fields(array('method' => $method));

	if (!class_exists($method))
	{
		trigger_error('Method does not exist.', E_USER_ERROR);
	}

	$requested_data = call_user_func(array($method, 'data'));
	foreach ($requested_data as $data => $default)
	{
		$default = (!empty($config['ftp_' . $data])) ? $config['ftp_' . $data] : $default;

		$template->assign_block_vars('data', array(
			'DATA'		=> $data,
			'NAME'		=> $user->lang[strtoupper($method . '_' . $data)],
			'EXPLAIN'	=> $user->lang[strtoupper($method . '_' . $data) . '_EXPLAIN'],
			'DEFAULT'	=> (!empty($_REQUEST[$data])) ? request_var($data, '') : $default
		));
	}

	$template->assign_vars(array(
		'S_CONNECTION_SUCCESS'		=> ($test_ftp_connection && $test_connection === true) ? true : false,
		'S_CONNECTION_FAILED'		=> ($test_ftp_connection && $test_connection !== true) ? true : false,
		'ERROR_MSG'					=> ($test_ftp_connection && $test_connection !== true) ? $user->lang[$test_connection] : '',

		'S_FTP_UPLOAD'			=> true,
		'UPLOAD_METHOD'			=> $method,
		'S_HIDDEN_FIELDS_FTP'	=> $s_hidden_fields,
	));
}

/**
* Gets FTP information if we need it
*
* @param	$preview	bool	true if in pre_(install|uninstall), false otherwise
* @return				array	and array of connection info (currently only ftp)
*/
function get_connection_info($preview = false)
{
	global $config, $ftp_method, $test_ftp_connection, $test_connection;

	$conn_info_ary = array();

	// using $config instead of $editor because write_method is forced to direct
	// when in preview mode
	if ($config['write_method'] == WRITE_FTP)
	{
		if (!$preview && isset($_POST['password']))
		{
			$conn_info_ary['method'] = $config['ftp_method'];

			if (empty($config['ftp_method']))
			{
				trigger_error('FTP_METHOD_ERROR');
			}

			$requested_data = call_user_func(array($config['ftp_method'], 'data'));

			foreach ($requested_data as $data => $default)
			{
				if ($data == 'password')
				{
					$config['ftp_password'] = request_var('password', '');
				}
				$default = (!empty($config['ftp_' . $data])) ? $config['ftp_' . $data] : $default;

				$conn_info_ary[$data] = $default;
			}
		}

		handle_ftp_details($ftp_method, $test_ftp_connection, $test_connection);
	}

	return $conn_info_ary;
}

/**
 * Recursively delete a directory
 *
 * @param	string	$path (required)	Directory path to recursively delete
 * @author	jasmineaura
 */
function recursive_unlink($path)
{
	global $phpbb_root_path, $phpEx, $user;

	// Insurance - this should never really happen
	if ($path == $phpbb_root_path || is_file("$path/common.$phpEx"))
	{
		return false;
	}

	// Get all of the files in the source directory
	$files = find_files($path, '.*');
	// Get all of the sub-directories in the source directory
	$subdirs = find_files($path, '.*', 20, true);

	// Delete all the files
	foreach ($files as $file)
	{
		if (!unlink($file))
		{
			return sprintf($user->lang['MODS_RMFILE_FAILURE'], $file);
		}
	}

	// Delete all the sub-directories, in _reverse_ order (array_pop)
	for ($i=0, $cnt = count($subdirs); $i < $cnt; $i++)
	{
		$subdir = array_pop($subdirs);
		if (!rmdir($subdir))
		{
			return sprintf($user->lang['MODS_RMDIR_FAILURE'], $subdir);
		}
	}

	// Finally, delete the directory itself
	if (!rmdir($path))
	{
		return sprintf($user->lang['MODS_RMDIR_FAILURE'], $path);
	}

	return true;
}

/**
* PHP 5 Wrapper - simulate scandir, but only those features that we actually need
* NB: The third parameter of PHP5 native scandir is _not_ present in this wrapper
*/
if (!function_exists('scandir'))
{
	function scandir($directory, $sorting_order = false)
	{
		$files = array();

		$dp = opendir($directory);
		while (($filename = readdir($dp)) !== false)
		{
			$files[] = $filename;
		}

		if ($sorting_order)
		{
			rsort($files);
		}
		else
		{
			sort($files);
		}

		return $files;
	}
}

/**
* Return the number of files (optionally including sub-directories) in a directory, optionally recursively.
*
* @param	$dir		string (required)	- The directory you want to count files in
* @param	$subdirs	boolean (optional)	- Count subdirectories instead of files
* @param	$recurse	boolean (optional)	- Recursive count into sub-directories
* @param	$count		int (optional)		- Initial value of file (or subdirs) count
* @return				int					- Count of files (or count of subdirectories)
* @author	jasmineaura
*/
function directory_num_files($dir, $subdirs = false, $recurse = false, $count = 0)
{
	if (is_dir($dir))
	{
		if($handle = opendir($dir))
		{
			while (($file = readdir($handle)) !== false)
			{
				if ($file == '.' || $file == '..')
				{
					continue;
				}
				else if (is_dir($dir."/".$file))
				{
					if ($subdirs)
					{
						$count++;
					}
					else if ($recurse)
					{
						$count = directory_num_files($dir."/".$file, $subdirs, $recurse, $count);
					}
				}
				else if (!$subdirs)
				{
					$count++;
				}
			}

			closedir($handle);
		}
	}

	return $count;
}

/**
* Check if a directory is empty.
*
* @param $dir, string - directory to check
* @return bool, true if directory is empty.
*/
function check_empty_dir($dir)
{
	if (!is_dir($dir) || !is_readable($dir))
	{
		return(false);
	}

	if(!$handle = opendir($dir))
	{
		return(false);
	}

	while (($file = readdir($handle)) !== false)
	{
		if ($file == '.' || $file == '..')
		{
			continue;
		}

		// If we get here the directory is not empty
		closedir($handle);
		return(false);
	}

	// The directory is empty
	closedir($handle);
	return(true);
}

?>


text:
using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using Hl7.Fhir.Support;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Hl7.Fhir.Introspection
{
    public class PropertyMapping
    {
        public string Name { get; private set; }

        public bool IsCollection { get; private set; }

        public bool IsPrimitive { get; private set; }
        public bool RepresentsValueElement { get; private set; }
        public bool InSummary { get; private set; }

        public Type ReturnType { get; private set; }
        public Type ElementType { get; private set; }

        public int Order { get; private set; }

        public XmlSerializationHint SerializationHint { get; set; }

        public ChoiceType Choice { get; set; }

        public static PropertyMapping Create(PropertyInfo prop)
        {
            IEnumerable<Type> dummy;

            return Create(prop, out dummy);
        }

        internal static PropertyMapping Create(PropertyInfo prop, out IEnumerable<Type> referredTypes)
        {
            if (prop == null) throw Error.ArgumentNull("prop");

            var foundTypes = new List<Type>();

            PropertyMapping result = new PropertyMapping();

#if PORTABLE45
			var elementAttr = prop.GetCustomAttribute<FhirElementAttribute>();
#else
			var elementAttr = (FhirElementAttribute)Attribute.GetCustomAttribute(prop, typeof(FhirElementAttribute));
#endif

            result.Name = determinePropertyName(prop);
            result.ReturnType = prop.PropertyType;
            result.ElementType = result.ReturnType;

            result.InSummary = elementAttr != null ? elementAttr.InSummary : false;
            result.Choice = elementAttr != null ? elementAttr.Choice : ChoiceType.None;

            if (elementAttr != null)
            {
                result.SerializationHint = elementAttr.XmlSerialization;
                result.Order = elementAttr.Order;
            }

            foundTypes.Add(result.ElementType);

            result.IsCollection = ReflectionHelper.IsTypedCollection(prop.PropertyType) && !prop.PropertyType.IsArray;

            // Get to the actual (native) type representing this element
            if (result.IsCollection) result.ElementType = ReflectionHelper.GetCollectionItemType(prop.PropertyType);
            if (ReflectionHelper.IsNullableType(result.ElementType)) result.ElementType = ReflectionHelper.GetNullableArgument(result.ElementType);
            result.IsPrimitive = isAllowedNativeTypeForDataTypeValue(result.ElementType);

            // Check wether this property represents a native .NET type
            // marked to receive the class' primitive value in the fhir serialization
            // (e.g. the value from the Xml 'value' attribute or the Json primitive member value)
            if(result.IsPrimitive) result.RepresentsValueElement = isPrimitiveValueElement(prop);

            referredTypes = foundTypes;

            // May need to generate getters/setters using pre-compiled expression trees for performance.
            // See http://weblogs.asp.net/marianor/archive/2009/04/10/using-expression-trees-to-get-property-getter-and-setters.aspx
            result._getter = instance => prop.GetValue(instance, null);
            result._setter = (instance,value) => prop.SetValue(instance, value, null);

            return result;
        }

        private static string determinePropertyName(PropertyInfo prop)
        {
#if PORTABLE45
			var elementAttr = prop.GetCustomAttribute<FhirElementAttribute>();
#else
			var elementAttr = (FhirElementAttribute)Attribute.GetCustomAttribute(prop, typeof(FhirElementAttribute));
#endif

            if(elementAttr != null && elementAttr.Name != null)
                return elementAttr.Name;
            else
                return lowerCamel(prop.Name);
        }

        private static string lowerCamel(string p)
        {
            if (p == null) return p;

            var c = p[0];

            return Char.ToLowerInvariant(c) + p.Remove(0, 1);
        }

        private static string buildQualifiedPropName(PropertyInfo prop)
        {
            return prop.DeclaringType.Name + "." + prop.Name;
        }

        private static bool isPrimitiveValueElement(PropertyInfo prop)
        {
#if PORTABLE45
			var valueElementAttr = prop.GetCustomAttribute<FhirElementAttribute>();
#else
			var valueElementAttr = (FhirElementAttribute)Attribute.GetCustomAttribute(prop, typeof(FhirElementAttribute));
#endif
            var isValueElement = valueElementAttr != null && valueElementAttr.IsPrimitiveValue;

            if(isValueElement && !isAllowedNativeTypeForDataTypeValue(prop.PropertyType))
                throw Error.Argument("prop", "Property {0} is marked for use as a primitive element value, but its .NET type ({1}) is not supported by the serializer.", buildQualifiedPropName(prop), prop.PropertyType.Name);

            return isValueElement;
        }

         //// Special case: this is a member that uses the closed generic Code<T> type -
         //       // do mapping for its open, defining type instead
         //       if (elementType.IsGenericType)
         //       {
         //           if (ReflectionHelper.IsClosedGenericType(elementType) &&
         //               ReflectionHelper.IsConstructedFromGenericTypeDefinition(elementType, typeof(Code<>)) )
         //           {
         //               result.CodeOfTEnumType = elementType.GetGenericArguments()[0];
         //               elementType = elementType.GetGenericTypeDefinition();
         //           }
         //           else
         //               throw Error.NotSupported("Property {0} on type {1} uses an open generic type, which is not yet supported", prop.Name, prop.DeclaringType.Name);
         //       }

        public bool MatchesSuffixedName(string suffixedName)
        {
            if (suffixedName == null) throw Error.ArgumentNull("suffixedName");

            return Choice == ChoiceType.DatatypeChoice && suffixedName.ToUpperInvariant().StartsWith(Name.ToUpperInvariant());
        }

        public string GetChoiceSuffixFromName(string suffixedName)
        {
            if (suffixedName == null) throw Error.ArgumentNull("suffixedName");

            if (MatchesSuffixedName(suffixedName))
                return suffixedName.Remove(0, Name.Length);
            else
                throw Error.Argument("suffixedName", "The given suffixed name {0} does not match this property's name {1}",
                                            suffixedName, Name);
        }

        //public Type GetChoiceType(string choiceSuffix)
        //{
        //    string suffix = choiceSuffix.ToUpperInvariant();

        //    if(!HasChoices) return null;

        //    return _choices
        //                .Where(cattr => cattr.TypeName.ToUpperInvariant() == suffix)
        //                .Select(cattr => cattr.Type)
        //                .FirstOrDefault();
        //}

        private static bool isAllowedNativeTypeForDataTypeValue(Type type)
        {
            // Special case, allow Nullable<enum>
            if (ReflectionHelper.IsNullableType(type))
                type = ReflectionHelper.GetNullableArgument(type);

            return type.IsEnum() ||
                    PrimitiveTypeConverter.CanConvert(type);
        }

        private Func<object, object> _getter;
        private Action<object, object> _setter;

        public object GetValue(object instance)
        {
            return _getter(instance);
        }

        public void SetValue(object instance, object value)
        {
            _setter(instance, value);
        }
    }
}


text:
CatfishWindow .sidebar .button.flat {
    padding: 4px 6px;
    transition: none;
}

CatfishWindow .sidebar .button.flat:active,
CatfishWindow .sidebar .button.flat:checked {
    border-color: shade(@theme_bg_color, 0.8);
    background-color: shade(@theme_bg_color, 0.95);
    background-image: none;
}

XfceHeading {
    margin: 0;
    padding: 0;
    border-width: 0;
    background-color: @theme_base_color;
    background-image: none;
    color: @theme_text_color;
}

.xfce4-panel {
    background-color: @panel_bg_color;
    color: @panel_fg_color;
    font: normal;
}

.xfce4-panel .button {
    padding: 0 2px;
    border-radius: 0;
    border-style: none;
    color: @panel_fg_color;
}

.xfce4-panel .button:active {
    background-color: shade(@panel_bg_color, 0.8);
    background-image: none;
    color: @panel_fg_color;
}

.xfce4-panel .button:hover,
.xfce4-panel .button:active:hover {
    background-color: mix(@panel_bg_color, @panel_fg_color, 0.21);
    background-image: none;
    color: shade(@panel_fg_color, 1.08);
}

.xfce4-panel .menu {
    -gtk-image-effect: none;
}


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Time {

	public static $offset = 0;
	public static $display = 'Y-m-d  H:i';

	/**
	 * Return the timestamp with the user's timezone and his display options.
	 * @param integer $timestamp time in seconds
	 * @param integer $ago_days  number of days to display x day(s) ago formating
	 */
	public static function date($timestamp, $ago_days = 2)
	{

		// Check if $ago_days is null, or if timestamp is more then time - $ago_days.
		if ( ! $ago_days OR $timestamp > time() - (Date::DAY * $ago_days))
		{
			return Time::ago($timestamp);
		}

		$timestamp += Time::$offset * 3600;

		return date(Time::$display, $timestamp);

	}

	/**
	 * Return the time since the timestamp was created nicely formatted.
	 * @param integer $timestamp  time in seconds
	 */
	static public function ago($timestamp){

		$difference = time() - $timestamp;
		$periods = array( 'second', 'minute', 'hour', 'day', 'week', 'month', 'year' );
		$lengths = array( '60', '60', '24', '7', '4.35', '12', '100' );

		for( $j = 0; $difference >= $lengths[$j]; $j++ )
			$difference /= $lengths[$j];

		$difference = round($difference);
		if($difference != 1) $periods[$j].= "s";
			$text = $difference.' '.__($periods[$j]).' '.__('ago');

		return $text;

	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<d:fileset xmlns:d="http://www.daisy.org/ns/pipeline/data" xml:base="file:/tmp/">
    <d:file media-type="application/xhtml+xml" href="application/xhtml+xml"/>
    <d:file media-type="application/smil+xml" href="application/smil+xml"/>
    <d:file media-type="audio/mpeg" href="audio/mpeg"/>
    <d:file media-type="application/epub+zip" href="application/epub+zip"/>
    <d:file media-type="application/xproc+xml" href="application/xproc+xml"/>
    <d:file media-type="application/xslt+xml" href="application/xslt+xml"/>
    <d:file media-type="application/xquery+xml" href="application/xquery+xml"/>
    <d:file media-type="application/x-font-opentype" href="application/x-font-opentype"/>
    <d:file media-type="audio/x-wav" href="audio/x-wav"/>
    <d:file media-type="application/oebps-package+xml" href="application/oebps-package+xml"/>
    <d:file media-type="application/x-dtbncx+xml" href="application/x-dtbncx+xml"/>
    <d:file media-type="audio/mpeg4-generic" href="audio/mpeg4-generic"/>
    <d:file media-type="image/jpeg" href="image/jpeg"/>
    <d:file media-type="image/png" href="image/png"/>
    <d:file media-type="image/svg+xml" href="image/svg+xml"/>
    <d:file media-type="text/css" href="text/css"/>
    <d:file media-type="application/xml-dtd" href="application/xml-dtd"/>
    <d:file media-type="application/x-dtbresource+xml" href="application/x-dtbresource+xml"/>
    <d:file media-type="audio/ogg" href="audio/ogg"/>
    <d:file media-type="audio/basic" href="audio/basic"/>
    <d:file media-type="audio/mid" href="audio/mid"/>
    <d:file media-type="audio/x-aiff" href="audio/x-aiff"/>
    <d:file media-type="audio/x-mpegurl" href="audio/x-mpegurl"/>
    <d:file media-type="audio/x-pn-realaudio" href="audio/x-pn-realaudio"/>
    <d:file media-type="image/bmp" href="image/bmp"/>
    <d:file media-type="image/cis-cod" href="image/cis-cod"/>
    <d:file media-type="image/gif" href="image/gif"/>
    <d:file media-type="image/ief" href="image/ief"/>
    <d:file media-type="image/pipeg" href="image/pipeg"/>
    <d:file media-type="image/tiff" href="image/tiff"/>
    <d:file media-type="image/x-cmu-raster" href="image/x-cmu-raster"/>
    <d:file media-type="image/x-cmx" href="image/x-cmx"/>
    <d:file media-type="image/x-icon" href="image/x-icon"/>
    <d:file media-type="image/x-portable-anymap" href="image/x-portable-anymap"/>
    <d:file media-type="image/x-portable-bitmap" href="image/x-portable-bitmap"/>
    <d:file media-type="image/x-portable-graymap" href="image/x-portable-graymap"/>
    <d:file media-type="image/x-portable-pixmap" href="image/x-portable-pixmap"/>
    <d:file media-type="image/x-rgb" href="image/x-rgb"/>
    <d:file media-type="image/x-xbitmap" href="image/x-xbitmap"/>
    <d:file media-type="image/x-xpixmap" href="image/x-xpixmap"/>
    <d:file media-type="image/x-xwindowdump" href="image/x-xwindowdump"/>
    <d:file media-type="video/mpeg" href="video/mpeg"/>
    <d:file media-type="video/quicktime" href="video/quicktime"/>
    <d:file media-type="video/x-la-asf" href="video/x-la-asf"/>
    <d:file media-type="video/x-ms-asf" href="video/x-ms-asf"/>
    <d:file media-type="video/x-msvideo" href="video/x-msvideo"/>
    <d:file media-type="video/x-sgi-movie" href="video/x-sgi-movie"/>
    <d:file media-type="text/h323" href="text/h323"/>
    <d:file media-type="text/html" href="text/html"/>
    <d:file media-type="text/iuls" href="text/iuls"/>
    <d:file media-type="text/plain" href="text/plain"/>
    <d:file media-type="text/richtext" href="text/richtext"/>
    <d:file media-type="text/scriptlet" href="text/scriptlet"/>
    <d:file media-type="text/tab-separated-values" href="text/tab-separated-values"/>
    <d:file media-type="text/webviewhtml" href="text/webviewhtml"/>
    <d:file media-type="text/x-component" href="text/x-component"/>
    <d:file media-type="text/x-setext" href="text/x-setext"/>
    <d:file media-type="text/x-vcard" href="text/x-vcard"/>
    <d:file media-type="message/rfc822" href="message/rfc822"/>
    <d:file media-type="application/envoy" href="application/envoy"/>
    <d:file media-type="application/fractals" href="application/fractals"/>
    <d:file media-type="application/futuresplash" href="application/futuresplash"/>
    <d:file media-type="application/hta" href="application/hta"/>
    <d:file media-type="application/internet-property-stream" href="application/internet-property-stream"/>
    <d:file media-type="application/mac-binhex40" href="application/mac-binhex40"/>
    <d:file media-type="application/msword" href="application/msword"/>
    <d:file media-type="application/octet-stream" href="application/octet-stream"/>
    <d:file media-type="application/oda" href="application/oda"/>
    <d:file media-type="application/olescript" href="application/olescript"/>
    <d:file media-type="application/pdf" href="application/pdf"/>
    <d:file media-type="application/pics-rules" href="application/pics-rules"/>
    <d:file media-type="application/pkcs10" href="application/pkcs10"/>
    <d:file media-type="application/pkix-crl" href="application/pkix-crl"/>
    <d:file media-type="application/postscript" href="application/postscript"/>
    <d:file media-type="application/rtf" href="application/rtf"/>
    <d:file media-type="application/set-payment-initiation" href="application/set-payment-initiation"/>
    <d:file media-type="application/set-registration-initiation" href="application/set-registration-initiation"/>
    <d:file media-type="application/vnd.ms-excel" href="application/vnd.ms-excel"/>
    <d:file media-type="application/vnd.ms-outlook" href="application/vnd.ms-outlook"/>
    <d:file media-type="application/vnd.ms-pkicertstore" href="application/vnd.ms-pkicertstore"/>
    <d:file media-type="application/vnd.ms-pkiseccat" href="application/vnd.ms-pkiseccat"/>
    <d:file media-type="application/vnd.ms-pkistl" href="application/vnd.ms-pkistl"/>
    <d:file media-type="application/vnd.ms-powerpoint" href="application/vnd.ms-powerpoint"/>
    <d:file media-type="application/vnd.ms-project" href="application/vnd.ms-project"/>
    <d:file media-type="application/vnd.ms-works" href="application/vnd.ms-works"/>
    <d:file media-type="application/winhlp" href="application/winhlp"/>
    <d:file media-type="application/x-bcpio" href="application/x-bcpio"/>
    <d:file media-type="application/x-cdf" href="application/x-cdf"/>
    <d:file media-type="application/x-compress" href="application/x-compress"/>
    <d:file media-type="application/x-compressed" href="application/x-compressed"/>
    <d:file media-type="application/x-cpio" href="application/x-cpio"/>
    <d:file media-type="application/x-csh" href="application/x-csh"/>
    <d:file media-type="application/x-director" href="application/x-director"/>
    <d:file media-type="application/x-dvi" href="application/x-dvi"/>
    <d:file media-type="application/x-gtar" href="application/x-gtar"/>
    <d:file media-type="application/x-gzip" href="application/x-gzip"/>
    <d:file media-type="application/x-hdf" href="application/x-hdf"/>
    <d:file media-type="application/x-internet-signup" href="application/x-internet-signup"/>
    <d:file media-type="application/x-iphone" href="application/x-iphone"/>
    <d:file media-type="application/x-javascript" href="application/x-javascript"/>
    <d:file media-type="application/x-latex" href="application/x-latex"/>
    <d:file media-type="application/x-msaccess" href="application/x-msaccess"/>
    <d:file media-type="application/x-mscardfile" href="application/x-mscardfile"/>
    <d:file media-type="application/x-msclip" href="application/x-msclip"/>
    <d:file media-type="application/x-msdownload" href="application/x-msdownload"/>
    <d:file media-type="application/x-msmediaview" href="application/x-msmediaview"/>
    <d:file media-type="application/x-msmetafile" href="application/x-msmetafile"/>
    <d:file media-type="application/x-msmoney" href="application/x-msmoney"/>
    <d:file media-type="application/x-mspublisher" href="application/x-mspublisher"/>
    <d:file media-type="application/x-msschedule" href="application/x-msschedule"/>
    <d:file media-type="application/x-msterminal" href="application/x-msterminal"/>
    <d:file media-type="application/x-mswrite" href="application/x-mswrite"/>
    <d:file media-type="application/x-netcdf" href="application/x-netcdf"/>
    <d:file media-type="application/x-perfmon" href="application/x-perfmon"/>
    <d:file media-type="application/x-pkcs12" href="application/x-pkcs12"/>
    <d:file media-type="application/x-pkcs7-certificates" href="application/x-pkcs7-certificates"/>
    <d:file media-type="application/x-pkcs7-certreqresp" href="application/x-pkcs7-certreqresp"/>
    <d:file media-type="application/x-pkcs7-mime" href="application/x-pkcs7-mime"/>
    <d:file media-type="application/x-pkcs7-signature" href="application/x-pkcs7-signature"/>
    <d:file media-type="application/x-sh" href="application/x-sh"/>
    <d:file media-type="application/x-shar" href="application/x-shar"/>
    <d:file media-type="application/x-shockwave-flash" href="application/x-shockwave-flash"/>
    <d:file media-type="application/x-stuffit" href="application/x-stuffit"/>
    <d:file media-type="application/x-sv4cpio" href="application/x-sv4cpio"/>
    <d:file media-type="application/x-sv4crc" href="application/x-sv4crc"/>
    <d:file media-type="application/x-tar" href="application/x-tar"/>
    <d:file media-type="application/x-tcl" href="application/x-tcl"/>
    <d:file media-type="application/x-tex" href="application/x-tex"/>
    <d:file media-type="application/x-texinfo" href="application/x-texinfo"/>
    <d:file media-type="application/x-troff" href="application/x-troff"/>
    <d:file media-type="application/x-troff-man" href="application/x-troff-man"/>
    <d:file media-type="application/x-troff-me" href="application/x-troff-me"/>
    <d:file media-type="application/x-troff-ms" href="application/x-troff-ms"/>
    <d:file media-type="application/x-ustar" href="application/x-ustar"/>
    <d:file media-type="application/x-wais-source" href="application/x-wais-source"/>
    <d:file media-type="application/x-x509-ca-cert" href="application/x-x509-ca-cert"/>
    <d:file media-type="application/ynd.ms-pkipko" href="application/ynd.ms-pkipko"/>
    <d:file media-type="application/zip" href="application/zip"/>
    <d:file media-type="x-world/x-vrml" href="x-world/x-vrml"/>
    <d:file media-type="application/xml" href="application/xml"/>
    <d:file media-type="application/x-dtbook+xml" href="application/x-dtbook+xml"/>
    <d:file media-type="application/z3998-auth+xml" href="application/z3998-auth+xml"/>
</d:fileset>


text:
module P

  class ListExpr < Atom

    def initialize( value=[] )
      @value = value
    end

    def evaluate( environment )
      P.list( *value.map { |expr| expr.evaluate( environment ) } )
    end

    def to_s
      value.to_s
    end

    def inspect
      to_s
    end

  end

end


text:
namespace BeriChitai
{
    partial class BeriPanel
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BeriPanel));
            this.splitContainer1 = new System.Windows.Forms.SplitContainer();
            this.splitContainer2 = new System.Windows.Forms.SplitContainer();
            this._readerList = new System.Windows.Forms.ListBox();
            this.label1 = new System.Windows.Forms.Label();
            this._readerBrowser = new System.Windows.Forms.WebBrowser();
            this.toolStrip2 = new System.Windows.Forms.ToolStrip();
            this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel();
            this._phoneBox = new System.Windows.Forms.ToolStripTextBox();
            this._copyPhoneButton = new System.Windows.Forms.ToolStripButton();
            this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
            this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel();
            this._mailBox = new System.Windows.Forms.ToolStripTextBox();
            this._copyMailButton = new System.Windows.Forms.ToolStripButton();
            this.label2 = new System.Windows.Forms.Label();
            this.splitContainer3 = new System.Windows.Forms.SplitContainer();
            this._bookList = new System.Windows.Forms.ListBox();
            this.label3 = new System.Windows.Forms.Label();
            this._bookBrowser = new System.Windows.Forms.WebBrowser();
            this.toolStrip1 = new System.Windows.Forms.ToolStrip();
            this._giveButton = new System.Windows.Forms.ToolStripButton();
            this._rejectButton = new System.Windows.Forms.ToolStripButton();
            this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this._refreshButton = new System.Windows.Forms.ToolStripButton();
            this._readerSource = new System.Windows.Forms.BindingSource(this.components);
            this._timer1 = new System.Windows.Forms.Timer(this.components);
            this._bookSource = new System.Windows.Forms.BindingSource(this.components);
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
            this.splitContainer1.Panel1.SuspendLayout();
            this.splitContainer1.Panel2.SuspendLayout();
            this.splitContainer1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();
            this.splitContainer2.Panel1.SuspendLayout();
            this.splitContainer2.Panel2.SuspendLayout();
            this.splitContainer2.SuspendLayout();
            this.toolStrip2.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer3)).BeginInit();
            this.splitContainer3.Panel1.SuspendLayout();
            this.splitContainer3.Panel2.SuspendLayout();
            this.splitContainer3.SuspendLayout();
            this.toolStrip1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this._readerSource)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this._bookSource)).BeginInit();
            this.SuspendLayout();
            //
            // splitContainer1
            //
            this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;
            this.splitContainer1.Location = new System.Drawing.Point(0, 0);
            this.splitContainer1.Name = "splitContainer1";
            this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
            //
            // splitContainer1.Panel1
            //
            this.splitContainer1.Panel1.Controls.Add(this.splitContainer2);
            //
            // splitContainer1.Panel2
            //
            this.splitContainer1.Panel2.Controls.Add(this.splitContainer3);
            this.splitContainer1.Size = new System.Drawing.Size(884, 547);
            this.splitContainer1.SplitterDistance = 366;
            this.splitContainer1.TabIndex = 0;
            //
            // splitContainer2
            //
            this.splitContainer2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.splitContainer2.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
            this.splitContainer2.Location = new System.Drawing.Point(0, 0);
            this.splitContainer2.Name = "splitContainer2";
            //
            // splitContainer2.Panel1
            //
            this.splitContainer2.Panel1.Controls.Add(this._readerList);
            this.splitContainer2.Panel1.Controls.Add(this.label1);
            //
            // splitContainer2.Panel2
            //
            this.splitContainer2.Panel2.Controls.Add(this._readerBrowser);
            this.splitContainer2.Panel2.Controls.Add(this.label2);
            this.splitContainer2.Size = new System.Drawing.Size(884, 366);
            this.splitContainer2.SplitterDistance = 468;
            this.splitContainer2.TabIndex = 0;
            //
            // _readerList
            //
            this._readerList.Dock = System.Windows.Forms.DockStyle.Fill;
            this._readerList.FormattingEnabled = true;
            this._readerList.Location = new System.Drawing.Point(0, 16);
            this._readerList.Name = "_readerList";
            this._readerList.ScrollAlwaysVisible = true;
            this._readerList.Size = new System.Drawing.Size(466, 348);
            this._readerList.TabIndex = 0;
            this._readerList.SelectedIndexChanged += new System.EventHandler(this._readerList_SelectedIndexChanged);
            //
            // label1
            //
            this.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label1.Dock = System.Windows.Forms.DockStyle.Top;
            this.label1.Location = new System.Drawing.Point(0, 0);
            this.label1.Margin = new System.Windows.Forms.Padding(3);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(466, 16);
            this.label1.TabIndex = 1;
            this.label1.Text = "Читатели, оставившие заказы";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // _readerBrowser
            //
            this._readerBrowser.Dock = System.Windows.Forms.DockStyle.Fill;
            this._readerBrowser.Location = new System.Drawing.Point(0, 16);
            this._readerBrowser.MinimumSize = new System.Drawing.Size(20, 20);
            this._readerBrowser.Name = "_readerBrowser";
            this._readerBrowser.Size = new System.Drawing.Size(410, 348);
            this._readerBrowser.TabIndex = 1;
            //
            // toolStrip2
            //
            this.toolStrip2.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.toolStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripLabel1,
            this._phoneBox,
            this._copyPhoneButton,
            this.toolStripSeparator2,
            this.toolStripLabel2,
            this._mailBox,
            this._copyMailButton});
            this.toolStrip2.Location = new System.Drawing.Point(0, 150);
            this.toolStrip2.Name = "toolStrip2";
            this.toolStrip2.Size = new System.Drawing.Size(466, 25);
            this.toolStrip2.TabIndex = 2;
            this.toolStrip2.Text = "toolStrip2";
            //
            // toolStripLabel1
            //
            this.toolStripLabel1.Name = "toolStripLabel1";
            this.toolStripLabel1.Size = new System.Drawing.Size(30, 22);
            this.toolStripLabel1.Text = "Тел.";
            //
            // _phoneBox
            //
            this._phoneBox.Name = "_phoneBox";
            this._phoneBox.ReadOnly = true;
            this._phoneBox.Size = new System.Drawing.Size(80, 25);
            //
            // _copyPhoneButton
            //
            this._copyPhoneButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this._copyPhoneButton.Image = ((System.Drawing.Image)(resources.GetObject("_copyPhoneButton.Image")));
            this._copyPhoneButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this._copyPhoneButton.Name = "_copyPhoneButton";
            this._copyPhoneButton.Size = new System.Drawing.Size(23, 22);
            this._copyPhoneButton.Text = "Копировать";
            this._copyPhoneButton.Click += new System.EventHandler(this._copyPhoneButton_Click);
            //
            // toolStripSeparator2
            //
            this.toolStripSeparator2.Name = "toolStripSeparator2";
            this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
            //
            // toolStripLabel2
            //
            this.toolStripLabel2.Name = "toolStripLabel2";
            this.toolStripLabel2.Size = new System.Drawing.Size(30, 22);
            this.toolStripLabel2.Text = "Mail";
            //
            // _mailBox
            //
            this._mailBox.Name = "_mailBox";
            this._mailBox.ReadOnly = true;
            this._mailBox.Size = new System.Drawing.Size(200, 25);
            //
            // _copyMailButton
            //
            this._copyMailButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this._copyMailButton.Image = ((System.Drawing.Image)(resources.GetObject("_copyMailButton.Image")));
            this._copyMailButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this._copyMailButton.Name = "_copyMailButton";
            this._copyMailButton.Size = new System.Drawing.Size(23, 22);
            this._copyMailButton.Text = "Копировать";
            this._copyMailButton.Click += new System.EventHandler(this._copyMailButton_Click);
            //
            // label2
            //
            this.label2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label2.Dock = System.Windows.Forms.DockStyle.Top;
            this.label2.Location = new System.Drawing.Point(0, 0);
            this.label2.Margin = new System.Windows.Forms.Padding(3);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(410, 16);
            this.label2.TabIndex = 0;
            this.label2.Text = "Сведения о читателе";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // splitContainer3
            //
            this.splitContainer3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.splitContainer3.Dock = System.Windows.Forms.DockStyle.Fill;
            this.splitContainer3.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
            this.splitContainer3.Location = new System.Drawing.Point(0, 0);
            this.splitContainer3.Name = "splitContainer3";
            //
            // splitContainer3.Panel1
            //
            this.splitContainer3.Panel1.Controls.Add(this._bookList);
            this.splitContainer3.Panel1.Controls.Add(this.label3);
            this.splitContainer3.Panel1.Controls.Add(this.toolStrip2);
            //
            // splitContainer3.Panel2
            //
            this.splitContainer3.Panel2.Controls.Add(this._bookBrowser);
            this.splitContainer3.Panel2.Controls.Add(this.toolStrip1);
            this.splitContainer3.Size = new System.Drawing.Size(884, 177);
            this.splitContainer3.SplitterDistance = 468;
            this.splitContainer3.TabIndex = 0;
            //
            // _bookList
            //
            this._bookList.Dock = System.Windows.Forms.DockStyle.Fill;
            this._bookList.FormattingEnabled = true;
            this._bookList.Location = new System.Drawing.Point(0, 16);
            this._bookList.Name = "_bookList";
            this._bookList.ScrollAlwaysVisible = true;
            this._bookList.Size = new System.Drawing.Size(466, 134);
            this._bookList.TabIndex = 1;
            this._bookList.SelectedIndexChanged += new System.EventHandler(this._bookList_SelectedIndexChanged);
            //
            // label3
            //
            this.label3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label3.Dock = System.Windows.Forms.DockStyle.Top;
            this.label3.Location = new System.Drawing.Point(0, 0);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(466, 16);
            this.label3.TabIndex = 0;
            this.label3.Text = "Книги, заказанные читателем";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // _bookBrowser
            //
            this._bookBrowser.Dock = System.Windows.Forms.DockStyle.Fill;
            this._bookBrowser.Location = new System.Drawing.Point(0, 25);
            this._bookBrowser.MinimumSize = new System.Drawing.Size(20, 20);
            this._bookBrowser.Name = "_bookBrowser";
            this._bookBrowser.Size = new System.Drawing.Size(410, 150);
            this._bookBrowser.TabIndex = 1;
            //
            // toolStrip1
            //
            this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this._giveButton,
            this._rejectButton,
            this.toolStripSeparator1,
            this._refreshButton});
            this.toolStrip1.Location = new System.Drawing.Point(0, 0);
            this.toolStrip1.Name = "toolStrip1";
            this.toolStrip1.Size = new System.Drawing.Size(410, 25);
            this.toolStrip1.TabIndex = 0;
            this.toolStrip1.Text = "toolStrip1";
            //
            // _giveButton
            //
            this._giveButton.Image = ((System.Drawing.Image)(resources.GetObject("_giveButton.Image")));
            this._giveButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this._giveButton.Name = "_giveButton";
            this._giveButton.Size = new System.Drawing.Size(66, 22);
            this._giveButton.Text = "Выдать";
            this._giveButton.Click += new System.EventHandler(this._giveButton_Click);
            //
            // _rejectButton
            //
            this._rejectButton.Image = ((System.Drawing.Image)(resources.GetObject("_rejectButton.Image")));
            this._rejectButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this._rejectButton.Name = "_rejectButton";
            this._rejectButton.Size = new System.Drawing.Size(112, 22);
            this._rejectButton.Text = "Отменить заказ";
            this._rejectButton.Click += new System.EventHandler(this._rejectButton_Click);
            //
            // toolStripSeparator1
            //
            this.toolStripSeparator1.Name = "toolStripSeparator1";
            this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
            //
            // _refreshButton
            //
            this._refreshButton.Image = ((System.Drawing.Image)(resources.GetObject("_refreshButton.Image")));
            this._refreshButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this._refreshButton.Name = "_refreshButton";
            this._refreshButton.Size = new System.Drawing.Size(125, 22);
            this._refreshButton.Text = "Обновить данные";
            this._refreshButton.Click += new System.EventHandler(this._refreshButton_Click);
            //
            // _readerSource
            //
            this._readerSource.AllowNew = false;
            this._readerSource.CurrentChanged += new System.EventHandler(this._readerSource_CurrentChanged);
            //
            // _timer1
            //
            this._timer1.Tick += new System.EventHandler(this._timer1_Tick);
            //
            // _bookSource
            //
            this._bookSource.AllowNew = false;
            //
            // BeriPanel
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.splitContainer1);
            this.Name = "BeriPanel";
            this.Size = new System.Drawing.Size(884, 547);
            this.splitContainer1.Panel1.ResumeLayout(false);
            this.splitContainer1.Panel2.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
            this.splitContainer1.ResumeLayout(false);
            this.splitContainer2.Panel1.ResumeLayout(false);
            this.splitContainer2.Panel2.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();
            this.splitContainer2.ResumeLayout(false);
            this.toolStrip2.ResumeLayout(false);
            this.toolStrip2.PerformLayout();
            this.splitContainer3.Panel1.ResumeLayout(false);
            this.splitContainer3.Panel1.PerformLayout();
            this.splitContainer3.Panel2.ResumeLayout(false);
            this.splitContainer3.Panel2.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer3)).EndInit();
            this.splitContainer3.ResumeLayout(false);
            this.toolStrip1.ResumeLayout(false);
            this.toolStrip1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this._readerSource)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this._bookSource)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.SplitContainer splitContainer1;
        private System.Windows.Forms.SplitContainer splitContainer2;
        private System.Windows.Forms.SplitContainer splitContainer3;
        private System.Windows.Forms.BindingSource _readerSource;
        private System.Windows.Forms.ListBox _readerList;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.WebBrowser _readerBrowser;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.ListBox _bookList;
        private System.Windows.Forms.WebBrowser _bookBrowser;
        private System.Windows.Forms.ToolStrip toolStrip1;
        private System.Windows.Forms.Timer _timer1;
        private System.Windows.Forms.BindingSource _bookSource;
        private System.Windows.Forms.ToolStripButton _giveButton;
        private System.Windows.Forms.ToolStripButton _rejectButton;
        private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
        private System.Windows.Forms.ToolStripButton _refreshButton;
        private System.Windows.Forms.ToolStrip toolStrip2;
        private System.Windows.Forms.ToolStripLabel toolStripLabel1;
        private System.Windows.Forms.ToolStripTextBox _phoneBox;
        private System.Windows.Forms.ToolStripButton _copyPhoneButton;
        private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
        private System.Windows.Forms.ToolStripLabel toolStripLabel2;
        private System.Windows.Forms.ToolStripTextBox _mailBox;
        private System.Windows.Forms.ToolStripButton _copyMailButton;
    }
}


text:
define([
    'bluebird',
    'kb_lib/jsonRpc/genericClient',
    'kb_common_ts/HttpClient',
    'kb_lib/props',
    'semver'
], function (
    Promise,
    GenericClient,
    httpClient,
    props,
    semver
) {
    'use strict';

    class KBaseServiceManager {
        constructor({ runtime, throwErrors }) {
            this.runtime = runtime;
            this.coreServices = this.runtime.config('coreServices');
            this.timeout = runtime.config('ui.constants.service_check_timeouts.hard');
            this.throwErrors = throwErrors || false;
        }

        checkREST(serviceConfig) {
            const http = new httpClient.HttpClient();
            const header = new httpClient.HttpHeader();
            header.setHeader('accept', 'application/json');
            return http
                .request({
                    method: 'GET',
                    url: serviceConfig.url + serviceConfig.version.path,
                    header: header,
                    timeout: this.timeout
                })
                .then((result) => {
                    const contentType = result.header.getHeader('content-type');
                    if (contentType !== 'application/json') {
                        const errorMessage = 'Unexpected content type; expected "application/json", received "' + contentType + '"';
                        if (this.throwErrors) {
                            throw new Error(errorMessage);
                        } else {
                            console.error(errorMessage);
                        }
                    }
                    return JSON.parse(result.response);
                })
                .catch((err) => {
                    const errorMessage =
            'An error was encountered checking the service "' + serviceConfig.module + '": ' + err.message;
                    if (this.throwErrors) {
                        throw new Error(errorMessage);
                    } else {
                        console.error(errorMessage);
                        return null;
                    }
                });
        }

        checkJSONRPC(serviceConfig) {
            const client = new GenericClient({
                module: serviceConfig.module,
                url: serviceConfig.url,
                timeout: this.timeout
            });
            return client
                .callFunc(serviceConfig.version.method, [])
                .spread((result) => {
                    return result;
                })
                .catch((err) => {
                    const errorMessage =
            'An error was encountered checking the service "' + serviceConfig.module + '": ' + err.message;
                    if (this.throwErrors) {
                        throw new Error(errorMessage);
                    } else {
                        console.error(errorMessage);
                        return null;
                    }
                });
        }

        check() {
            const disabledServices = this.runtime.config('ui.coreServices.disabled', []);
            return Promise.all(
                this.coreServices
                    .filter((serviceConfig) => {
                        const disabled = disabledServices.includes(serviceConfig.module);
                        if (disabled) {
                            console.warn('Check disabled for core service: ' + serviceConfig.module);
                        }
                        return !disabled;
                    })
                    .map((serviceConfig) => {
                        return Promise.try(() => {
                            switch (serviceConfig.type) {
                            case 'jsonrpc':
                                return this.checkJSONRPC(serviceConfig);
                            case 'rest':
                                return this.checkREST(serviceConfig);
                            case 'jsonrpc2':
                                console.warn('Ignoring jsonrpc core service for now', serviceConfig);
                                return null;
                            default:
                                var errorMessage = 'Unsupported core service type: ' + serviceConfig.type;
                                if (this.throwErrors) {
                                    throw new Error(errorMessage);
                                } else {
                                    console.error(errorMessage);
                                    return null;
                                }
                            }
                        }).then((result) => {
                            let version;
                            if (result === null) {
                                if (!this.throwErrors) {
                                    return null;
                                } else {
                                    throw new Error('Invalid semver check result: ' + result);
                                }
                            }
                            if (serviceConfig.version.semverNotImplemented) {
                                return null;
                            } else if (serviceConfig.version.propertyPath) {
                                version = props.getProp(result, serviceConfig.version.propertyPath);
                            } else {
                                version = result;
                            }

                            if (serviceConfig.version.required) {
                                if (semver.intersects(version, serviceConfig.version.required)) {
                                    return null;
                                }
                                return {
                                    module: serviceConfig.module,
                                    requiredVersion: serviceConfig.version.required,
                                    serviceVersion: version
                                };
                            } else {
                                console.warn(`for service "${serviceConfig.module}", semver check not disabled, but no required version provided`);
                            }
                        });
                    })
            ).then((result) => {
                const mismatches = result.filter((result) => {
                    return result === null ? false : true;
                });
                if (mismatches.length > 0) {
                    const message = mismatches
                        .map((mismatch) => {
                            return `service "${mismatch.module}" version ${mismatch.serviceVersion} incompatible with the required ${mismatch.requiredVersion}`;
                        })
                        .join('; ');
                    let prefix;
                    if (mismatches.length === 1) {
                        prefix = 'Incompatible service';
                    } else {
                        prefix = 'Incompatible services';
                    }
                    const errorMessage = `${prefix}: ${message}`;
                    if (this.throwErrors) {
                        throw new Error(errorMessage);
                    } else {
                        console.error(errorMessage);
                    }
                }
            });
        }
    }

    return { KBaseServiceManager };
});


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/autofill/core/browser/address_normalizer_impl.h"

#include <stddef.h>
#include <utility>

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/cancelable_callback.h"
#include "base/check_op.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/time/time.h"
#include "components/autofill/core/browser/autofill_data_util.h"
#include "components/autofill/core/browser/data_model/autofill_profile.h"
#include "components/autofill/core/browser/geo/address_i18n.h"
#include "components/autofill/core/browser/geo/phone_number_i18n.h"
#include "third_party/libaddressinput/chromium/chrome_address_validator.h"
#include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h"
#include "third_party/libaddressinput/src/cpp/include/libaddressinput/source.h"
#include "third_party/libaddressinput/src/cpp/include/libaddressinput/storage.h"

namespace autofill {

namespace {

using ::i18n::addressinput::Source;
using ::i18n::addressinput::Storage;

using DeleteOnTaskRunnerStorageUniquePtr =
    std::unique_ptr<Storage, base::OnTaskRunnerDeleter>;

bool NormalizeProfileWithValidator(AutofillProfile* profile,
                                   const std::string& app_locale,
                                   AddressValidator* address_validator) {
  DCHECK(address_validator);

  // Create the AddressData from the profile.
  ::i18n::addressinput::AddressData address_data =
      *autofill::i18n::CreateAddressDataFromAutofillProfile(*profile,
                                                            app_locale);

  // Normalize the address.
  if (!address_validator->NormalizeAddress(&address_data))
    return false;

  profile->SetRawInfo(ADDRESS_HOME_STATE,
                      base::UTF8ToUTF16(address_data.administrative_area));
  profile->SetRawInfo(ADDRESS_HOME_CITY,
                      base::UTF8ToUTF16(address_data.locality));
  profile->SetRawInfo(ADDRESS_HOME_DEPENDENT_LOCALITY,
                      base::UTF8ToUTF16(address_data.dependent_locality));
  return true;
}

// Formats the phone number in |profile| to E.164 format. Leaves the original
// phone number if formatting was not possible (or already optimal).
void FormatPhoneNumberToE164(AutofillProfile* profile,
                             const std::string& region_code,
                             const std::string& app_locale) {
  const std::string formatted_number = autofill::i18n::FormatPhoneForResponse(
      base::UTF16ToUTF8(
          profile->GetInfo(AutofillType(PHONE_HOME_WHOLE_NUMBER), app_locale)),
      region_code);

  profile->SetRawInfo(PHONE_HOME_WHOLE_NUMBER,
                      base::UTF8ToUTF16(formatted_number));
}

std::unique_ptr<AddressValidator> CreateAddressValidator(
    std::unique_ptr<Source> source,
    DeleteOnTaskRunnerStorageUniquePtr storage,
    LoadRulesListener* load_rules_listener) {
  return std::make_unique<AddressValidator>(
      std::move(source), std::unique_ptr<Storage>(storage.release()),
      load_rules_listener);
}

}  // namespace

class AddressNormalizerImpl::NormalizationRequest {
 public:
  NormalizationRequest(const AutofillProfile& profile,
                       const std::string& app_locale,
                       int timeout_seconds,
                       AddressNormalizer::NormalizationCallback callback)
      : profile_(profile),
        app_locale_(app_locale),
        callback_(std::move(callback)) {
    // OnRulesLoaded will be called in |timeout_seconds| if the rules are not
    // loaded in time.
    base::SequencedTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&NormalizationRequest::OnRulesLoaded,
                       weak_ptr_factory_.GetWeakPtr(),
                       /*success=*/false,
                       /*address_validator=*/nullptr),
        base::TimeDelta::FromSeconds(timeout_seconds));
  }

  ~NormalizationRequest() {}

  void OnRulesLoaded(bool success, AddressValidator* address_validator) {
    // Check if the timeout happened before the rules were loaded.
    if (has_responded_)
      return;
    has_responded_ = true;

    // The phone number formatting doesn't require the rules to have been
    // successfully loaded. Therefore it is done for every request regardless of
    // |success|.
    const std::string region_code =
        data_util::GetCountryCodeWithFallback(profile_, app_locale_);
    FormatPhoneNumberToE164(&profile_, region_code, app_locale_);

    if (!success) {
      std::move(callback_).Run(/*success=*/false, profile_);
      return;
    }

    // The rules should be loaded.
    DCHECK(address_validator->AreRulesLoadedForRegion(region_code));

    bool normalization_success = NormalizeProfileWithValidator(
        &profile_, app_locale_, address_validator);

    std::move(callback_).Run(/*success=*/normalization_success, profile_);
  }

 private:
  AutofillProfile profile_;
  const std::string app_locale_;
  AddressNormalizer::NormalizationCallback callback_;

  bool has_responded_ = false;
  base::WeakPtrFactory<NormalizationRequest> weak_ptr_factory_{this};

  DISALLOW_COPY_AND_ASSIGN(NormalizationRequest);
};

AddressNormalizerImpl::AddressNormalizerImpl(std::unique_ptr<Source> source,
                                             std::unique_ptr<Storage> storage,
                                             const std::string& app_locale)
    : app_locale_(app_locale) {
  // |address_validator_| is created in the background. Once initialized, it
  // will run any pending normalization.
  //
  // |storage| is wrapped in a DeleteOnTaskRunnerStorageUniquePtr to ensure that
  // it is deleted on the current sequence even if the task is skipped on
  // shutdown. This is important to prevent an access race when the destructor
  // of |storage| accesses an ObserverList that lives on the current sequence.
  // https://crbug.com/829122
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
      base::BindOnce(
          &CreateAddressValidator, std::move(source),
          DeleteOnTaskRunnerStorageUniquePtr(
              storage.release(), base::OnTaskRunnerDeleter(
                                     base::SequencedTaskRunnerHandle::Get())),
          this),
      base::BindOnce(&AddressNormalizerImpl::OnAddressValidatorCreated,
                     weak_ptr_factory_.GetWeakPtr()));
}

AddressNormalizerImpl::~AddressNormalizerImpl() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}

void AddressNormalizerImpl::LoadRulesForRegion(const std::string& region_code) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // The |address_validator_| is initialized in a background task. It may not
  // be available yet.
  if (!address_validator_)
    return;

  address_validator_->LoadRules(region_code);
}

void AddressNormalizerImpl::NormalizeAddressAsync(
    const AutofillProfile& profile,
    int timeout_seconds,
    AddressNormalizer::NormalizationCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_GE(timeout_seconds, 0);

  std::unique_ptr<NormalizationRequest> request =
      std::make_unique<NormalizationRequest>(
          profile, app_locale_, timeout_seconds, std::move(callback));

  // If the rules are already loaded for |region_code| and the validator is
  // initialized, the |request| will callback synchronously.
  const std::string region_code =
      data_util::GetCountryCodeWithFallback(profile, app_locale_);
  if (address_validator_ && AreRulesLoadedForRegion(region_code)) {
    request->OnRulesLoaded(/*success=*/true, address_validator_.get());
    return;
  }

  // Otherwise, the request is added to the queue for |region_code|.
  AddNormalizationRequestForRegion(std::move(request), region_code);

  // Start loading the rules for that region. If the rules were already in the
  // process of being loaded or |address_validator_| is not yet initialized,
  // this call will do nothing.
  LoadRulesForRegion(region_code);
}

bool AddressNormalizerImpl::NormalizeAddressSync(AutofillProfile* profile) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Phone number is always formatted, regardless of whether the address rules
  // are loaded for |region_code|.
  const std::string region_code =
      data_util::GetCountryCodeWithFallback(*profile, app_locale_);
  FormatPhoneNumberToE164(profile, region_code, app_locale_);
  if (!address_validator_) {
    // Can't normalize the address synchronously. Add an empty
    // NormalizationRequest so that the rules are loaded when the validator is
    // initialized (See OnAddressValidatorCreated).
    AddNormalizationRequestForRegion(nullptr, region_code);
    return false;
  }

  if (!AreRulesLoadedForRegion(region_code)) {
    // Ensure that the rules are being loaded for that region.
    LoadRulesForRegion(region_code);
    return false;
  }

  return NormalizeProfileWithValidator(profile, app_locale_,
                                       address_validator_.get());
}

bool AddressNormalizerImpl::AreRulesLoadedForRegion(
    const std::string& region_code) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  return address_validator_->AreRulesLoadedForRegion(region_code);
}

void AddressNormalizerImpl::OnAddressValidationRulesLoaded(
    const std::string& region_code,
    bool success) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // |address_validator_| is logically loaded at this point, but DCHECK anyway.
  DCHECK(address_validator_);

  // Check if an address normalization is pending for |region_code|.
  auto it = pending_normalization_.find(region_code);
  if (it != pending_normalization_.end()) {
    for (size_t i = 0; i < it->second.size(); ++i) {
      // Some NormalizationRequest are null, and served only to load the rules.
      if (it->second[i]) {
        // TODO(crbug.com/777417): |success| appears to be true even when the
        // key was not actually found.
        it->second[i]->OnRulesLoaded(AreRulesLoadedForRegion(region_code),
                                     address_validator_.get());
      }
    }
    pending_normalization_.erase(it);
  }
}

void AddressNormalizerImpl::OnAddressValidatorCreated(
    std::unique_ptr<AddressValidator> validator) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!address_validator_);

  address_validator_ = std::move(validator);

  // Make a copy of region keys before calling LoadRulesForRegion on them,
  // because LoadRulesForRegion may synchronously modify
  // |pending_normalization_|.
  std::vector<std::string> region_keys;
  region_keys.reserve(pending_normalization_.size());
  for (const auto& entry : pending_normalization_)
    region_keys.push_back(entry.first);

  // Load rules for regions with pending normalization requests.
  for (const std::string& region : region_keys)
    LoadRulesForRegion(region);
}

void AddressNormalizerImpl::AddNormalizationRequestForRegion(
    std::unique_ptr<NormalizationRequest> request,
    const std::string& region_code) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Setup the variables so the profile gets normalized when the rules have
  // finished loading.
  pending_normalization_[region_code].push_back(std::move(request));
}

}  // namespace autofill


text:
<?php

namespace Fxp\Component\FormExtensions\Form\Util;

use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\ResolvedFormTypeInterface;
use Symfony\Component\Form\Util\FormUtil as BaseFormUtil;

/**
 * @author François Pluchino <francois.pluchino@gmail.com>
 */
class FormUtil extends BaseFormUtil
{
    /**
     * Check if form is a specific type.
     *
     * @param FormInterface   $form  The form
     * @param string|string[] $types The class name of types
     *
     * @return bool
     */
    public static function isFormType(FormInterface $form, $types)
    {
        return static::isType((array) $types, $form->getConfig()->getType());
    }

    /**
     * Check if the parent type of the current type is allowed.
     *
     * @param string[]                  $types The class name of types
     * @param ResolvedFormTypeInterface $rType The resolved form type
     *
     * @return bool
     */
    protected static function isType(array $types, ResolvedFormTypeInterface $rType = null)
    {
        if (null === $rType) {
            return false;
        } elseif (!\in_array(\get_class($rType->getInnerType()), $types)) {
            return static::isType($types, $rType->getParent());
        }

        return true;
    }
}


text:
package com.jtdowney.chloride;

public class ChlorideException extends Exception {
    public ChlorideException(Exception e) {
        this.initCause(e);
    }

    @Override
    public String getMessage() {
        return this.getCause().getMessage();
    }
}