text:
import {
  Directive,
  Component,
  AfterContentInit,
  ElementRef,
  OnChanges,
  ContentChild,
  Input,
  Output,
  Optional,
  HostBinding
} from "angular2/core";
import {NgModel, NgControl, FORM_PROVIDERS} from "angular2/common";
import {ObservableWrapper, EventEmitter, TimerWrapper} from "angular2/src/facade/async";
import {isBlank} from "angular2/src/facade/lang";
import {DOM} from "angular2/src/platform/dom/dom_adapter";

// TODO(jd): <select> hasFocus/hasValue classes
// TODO(jd): input container validation styles.
// TODO(jelbourn): textarea resizing
// TODO(jelbourn): max-length counter

@Directive({
  selector: 'input[md-input],input.md-input,textarea[md-input],textarea.md-input',
  host: {
    'class': 'md-input',
    '[value]': 'value',
    '(input)': 'value=$event.target.value',
    '(focus)': 'setHasFocus(true)',
    '(blur)': 'setHasFocus(false)'
  },
  providers: [FORM_PROVIDERS]
})
export class MdInput {
  _value: string;

  constructor(@Optional() private model: NgModel,
              @Optional() private control: NgControl) {
  }

  @Input('value')
  set value(value: string) {
    this._value = value;
    TimerWrapper.setTimeout(() => this.mdChange.emit(this.value), 1);
  }

  get value(): string {
    let val = this.model ? this.model.value : this.control ? this.control.value : this._value;
    return !isBlank(val) ? val : '';
  }

  @Input()
  placeholder: string;
  @Output('valueChange')
  mdChange: EventEmitter<any> = new EventEmitter();
  @Output()
  mdFocusChange: EventEmitter<any> = new EventEmitter(false);

  setHasFocus(hasFocus: boolean) {
    ObservableWrapper.callEmit(this.mdFocusChange, hasFocus);
  }
}

@Component({
  selector: 'md-input-container',
  template: `<ng-content></ng-content><div class="md-errors-spacer"></div>`
})
export class MdInputContainer implements AfterContentInit, OnChanges {

  // The MdInput or MdTextarea inside of this container.
  @ContentChild(MdInput)
  _input: MdInput = null;

  // Whether the input inside of this container has a non-empty value.
  @HostBinding('class.md-input-has-value')
  inputHasValue: boolean = false;

  // Whether the input inside of this container has focus.
  @HostBinding('class.md-input-focused')
  inputHasFocus: boolean = false;

  // Whether the input inside of this container has a placeholder
  @HostBinding('class.md-input-has-placeholder')
  inputHasPlaceholder: boolean = false;

  constructor(private _element: ElementRef) {
  }

  ngOnChanges(_) {
    this.inputHasValue = this._input.value !== '';

    // TODO(jd): Is there something like @ContentChild that accepts a selector? I would prefer not to
    // use a directive for label elements because I cannot use a parent->child selector to make them
    // specific to md-input
    this.inputHasPlaceholder = !!DOM.querySelector(this._element.nativeElement, 'label') && !!this._input.placeholder;
  }

  ngAfterContentInit() {
    // If there is no text input, just bail and do nothing.
    if (this._input === null) {
      return;
    }

    // TODO(jd): :sob: what is the correct way to update these variables after the component initializes?
    //  any time I do it directly here, debug mode complains about values changing after being checked. I
    //  need to wait until the content has been initialized so that `_input` is there
    // For now, just wrap it in a setTimeout to let the change detection finish up, and then set the values...
    TimerWrapper.setTimeout(() => this.ngOnChanges({}), 0);

    // Listen to input changes and focus events so that we can apply the appropriate CSS
    // classes based on the input state.
    this._input.mdChange.subscribe((value: string) => {
      this.inputHasValue = value !== '';
    });

    this._input.mdFocusChange.subscribe((hasFocus: boolean) => {
      this.inputHasFocus = hasFocus
    });

  }
}


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

<CodeXL>
    <Tests>
	        <TestResultsDirectory>GoldMasters_APPSDK_2_9</TestResultsDirectory>
        <LogFilesDirectory>C:\TEMP\testResults\</LogFilesDirectory>
		<Test>
            <ExecutablePath>samples\opencl\bin\x86_64\FluidSimulation2D.exe</ExecutablePath>
            <WorkingDirectory>samples\opencl\bin\x86_64\</WorkingDirectory>
            <TestName>FluidSimulation2D_LocalsTest</TestName>
            <TestType>LocalsTest</TestType>
            <Kernels>
                <Kernel>
                    <KernelName>lbm</KernelName>
					<WorkItemId>0,0,0</WorkItemId>
					<KernelLocals>
						<LocalsInLine lineNumber="56"></LocalsInLine>
						<LocalsInLine lineNumber="58"></LocalsInLine>
						<LocalsInLine lineNumber="59"></LocalsInLine>
						<LocalsInLine lineNumber="60"></LocalsInLine>
						<LocalsInLine lineNumber="62"></LocalsInLine>
                    </KernelLocals>
                </Kernel>
            </Kernels>
        </Test>
	</Tests>
</CodeXL>

redpajama_set_name: RedPajamaGithub


text:
namespace ash {

namespace {

// The name of the sticky settings pref.
constexpr char kScanningStickySettingsPref[] =
    "scanning.scanning_sticky_settings";

}  // namespace

ChromeScanningAppDelegate::ChromeScanningAppDelegate(content::WebUI* web_ui)
    : web_ui_(web_ui),
      task_runner_(base::ThreadPool::CreateSequencedTaskRunner(
          {base::MayBlock(), base::TaskPriority::USER_VISIBLE,
           base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) {
  const base::FilePath my_files_path =
      file_manager::util::GetMyFilesFolderForProfile(
          Profile::FromWebUI(web_ui));

  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::GetForProfile(
          Profile::FromWebUI(web_ui_));
  const bool drive_available = integration_service &&
                               integration_service->is_enabled() &&
                               integration_service->IsMounted();
  const base::FilePath google_drive_path =
      drive_available ? integration_service->GetMountPointPath()
                      : base::FilePath();
  SetValidPaths(google_drive_path, my_files_path);
}

ChromeScanningAppDelegate::~ChromeScanningAppDelegate() = default;

std::unique_ptr<ui::SelectFilePolicy>
ChromeScanningAppDelegate::CreateChromeSelectFilePolicy() {
  return std::make_unique<ChromeSelectFilePolicy>(web_ui_->GetWebContents());
}

std::string ChromeScanningAppDelegate::GetBaseNameFromPath(
    const base::FilePath& path) {
  return file_path_helper_.GetBaseNameFromPath(path);
}

base::FilePath ChromeScanningAppDelegate::GetMyFilesPath() {
  return file_path_helper_.GetMyFilesPath();
}

std::string ChromeScanningAppDelegate::GetScanSettingsFromPrefs() {
  return GetPrefs()->GetString(kScanningStickySettingsPref);
}

// Determines if |path_to_file| is a supported file path for the Files app. Only
// files under the |drive_path_| and |my_files_path_| paths are allowed to be
// opened to from the Scan app. Paths with references (i.e. "../path") are not
// supported.
bool ChromeScanningAppDelegate::IsFilePathSupported(
    const base::FilePath& path_to_file) {
  return file_path_helper_.IsFilePathSupported(path_to_file);
}

void ChromeScanningAppDelegate::OpenFilesInMediaApp(
    const std::vector<base::FilePath>& file_paths) {
  DCHECK(!file_paths.empty());

  web_app::SystemAppLaunchParams params;
  params.launch_paths = file_paths;
  params.launch_source = apps::mojom::LaunchSource::kFromOtherApp;
  web_app::LaunchSystemWebAppAsync(Profile::FromWebUI(web_ui_),
                                   web_app::SystemAppType::MEDIA, params);
}

void ChromeScanningAppDelegate::SaveScanSettingsToPrefs(
    const std::string& scan_settings) {
  GetPrefs()->SetString(kScanningStickySettingsPref, scan_settings);
}

void ChromeScanningAppDelegate::ShowFileInFilesApp(
    const base::FilePath& path_to_file,
    base::OnceCallback<void(bool)> callback) {
  if (!IsFilePathSupported(path_to_file)) {
    std::move(callback).Run(false);
    return;
  }

  task_runner_->PostTaskAndReplyWithResult(
      FROM_HERE, base::BindOnce(&base::PathExists, path_to_file),
      base::BindOnce(&ChromeScanningAppDelegate::OnPathExists,
                     base::Unretained(this), path_to_file,
                     std::move(callback)));
}

void ChromeScanningAppDelegate::OnPathExists(
    const base::FilePath& path_to_file,
    base::OnceCallback<void(bool)> callback,
    bool file_path_exists) {
  if (!file_path_exists) {
    std::move(callback).Run(false);
    return;
  }

  platform_util::ShowItemInFolder(Profile::FromWebUI(web_ui_), path_to_file);
  std::move(callback).Run(true);
}

// static
void ChromeScanningAppDelegate::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterStringPref(kScanningStickySettingsPref, std::string());
}

void ChromeScanningAppDelegate::SetValidPaths(
    const base::FilePath& google_drive_path,
    const base::FilePath& my_files_path) {
  file_path_helper_ = ScanningFilePathHelper(google_drive_path, my_files_path);
}

PrefService* ChromeScanningAppDelegate::GetPrefs() const {
  return Profile::FromWebUI(web_ui_)->GetPrefs();
}

void ChromeScanningAppDelegate::SetRemoveableMediaPathForTesting(
    const base::FilePath& path) {
  file_path_helper_.SetRemoveableMediaPathForTesting(path);
}

}  // namespace ash


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

class Users_m extends CI_Model {

    /*************  CHECK CONNECTION PATIENT************/
    public function check_connectionPatient($donnees)
    {
        $sql = "SELECT id_patient,patient_login,patient_password,patient_name,patient_surname FROM tbl_patient WHERE patient_login=\"".$donnees['username']."\"
        and patient_password=\"".$donnees['password']."\";";
        $query=$this->db->query($sql);
        if($query->num_rows()==1)
        {
            $row=$query->result_array();
            $donnees_resultat=$row[0];
            return $donnees_resultat;
        }
        else
            return false;
    }

    /*************  CHECK CONNECTION PATIENT************/
    public function check_connectionStaff($donnees)
    {
        $sql = "SELECT tbls.id_staff,tbls.staff_login,tbls.staff_password,tbls.staff_name,tbls.staff_surname,tblps.post_name,tblps.id_post,tblps.post_right from tbl_staff tbls,tbl_post_staff tblps WHERE tblps.id_post=tbls.id_post AND tbls.staff_login=\"".$donnees['username']."\"
        and tbls.staff_password=\"".$donnees['password']."\";";
        $query=$this->db->query($sql);
        if($query->num_rows()==1)
        {
            $row=$query->result_array();
            $donnees_resultat=$row[0];
            return $donnees_resultat;
        }
        else
            return false;
    }

    /*************  BE CONNECTED IN PATIENT ************/
    function beConnectedPatient()
    {
        return $this->session->userdata('patient_login') ;
    }

    /*************  BE CONNECTED IN STAFF ************/
    function beConnectedStaff()
    {
        return $this->session->userdata('staff_login') ;
    }
}


text:
interface MaskedInputOptions {
}

declare class MaskedInput {
	constructor(args: MaskedInputOptions);
}


text:
<?php

namespace Rhubarb\Leaf\SearchPanel\Leaves;

use Rhubarb\Crown\Events\Event;
use Rhubarb\Crown\Request\WebRequest;
use Rhubarb\Crown\String\StringTools;
use Rhubarb\Leaf\Leaves\Controls\Control;
use Rhubarb\Leaf\Leaves\Leaf;
use Rhubarb\Leaf\Leaves\LeafModel;
use Rhubarb\Leaf\Leaves\UrlStateLeaf;
use Rhubarb\Stem\Filters\Group;

/**
 * A search interface that raises search events on behalf of the contained search controls.
 */
class SearchPanel extends UrlStateLeaf
{
    /** @var SearchPanelView */
    protected $view;

    /**
     * @var Event
     */
    public $searchedEvent;

    private $defaultControlValues = [];

    /**
     * @var SearchPanelModel
     */
    protected $model;

    public function __construct($name = "")
    {
        parent::__construct($name);

        $this->snapshotDefaultControlValues();
    }

    protected final function snapshotDefaultControlValues()
    {
        $controls = $this->model->searchControls;
        $defaultValues = $this->getDefaultControlValues();

        foreach ($controls as $control) {
            if (!isset($defaultValues[$control->getName()])) {
                $defaultValues[$control->getName()] = "";
            }
        }

        $this->model->searchValues = $defaultValues;
        $this->defaultControlValues = $this->getSearchControlValues();
    }

    /**
     * Override to set default control values on the model.
     */
    protected function getDefaultControlValues()
    {
        return [];
    }

    /**
     * You should implement this to return an ordered collection of control presenters to use in the search.
     *
     * @return array
     */
    protected function createSearchControls()
    {
        return [];
    }

    protected function setSearchControlsColumnCount($columns = 6)
    {
        $this->model->searchControlsColumnCount = $columns;
    }

    /**
     * Returns a key value pair array of each control name and it's value
     *
     * @return string[]
     */
    public function getSearchControlValues()
    {
        $data = $this->model->searchValues;
        $controlData = [];

        foreach ($this->model->searchControls as $control) {
            $controlName = $control->getName();

            if (isset($data[$controlName])) {
                $controlData[$controlName] = $data[$controlName];
            }
        }

        return $controlData;
    }

    private $previousSearchValues;

    /**
     * Sets the values of the search controls.
     *
     * @param array $controlValues A key value pair array.
     */
    public function setSearchControlValues($controlValues = [], $rememberPrevious = false)
    {
        if ($rememberPrevious){
            $this->previousSearchValues = $this->model->searchValues;
        } else {
            if ($this->previousSearchValues)   {
                $this->model->searchValues = $this->previousSearchValues;
                $this->previousSearchValues = null;
                return;
            }
        }

        $controlValues = array_merge($this->defaultControlValues, $controlValues);

        foreach ($this->model->searchControls as $control) {
            $controlName = $control->getName();

            if (isset($controlValues[$controlName])) {
                $this->model->searchValues[$controlName] = $controlValues[$controlName];
            }
        }

        $this->reRender();

        $this->searchedEvent->raise();
    }

    protected function bindEvents(Leaf $leaf)
    {
        if (property_exists($leaf, "getFilterEvent")) {
            $leaf->getFilterEvent->attachHandler(function () {
                return $this->onGetFilter();
            });
        }

        if (property_exists($leaf, "getSearchControlValuesEvent")) {
            $leaf->getSearchControlValuesEvent->attachHandler(function () {
                return $this->getSearchControlValues();
            });
        }
    }

    /**
     * Override this method to create any filters that are required.
     *
     * @param \Rhubarb\Stem\Filters\Group $filterGroup
     */
    public function populateFilterGroup(Group $filterGroup)
    {
    }

    protected function onGetFilter()
    {
        $group = new Group("AND");

        $this->populateFilterGroup($group);

        $filters = $group->getFilters();

        if (sizeof($filters) == 0) {
            // The search doesn't want to filter anything.
            return null;
        }

        return $group;
    }

    /**
     * Returns the name of the standard view used for this leaf.
     *
     * @return string
     */
    protected function getViewClass()
    {
        return SearchPanelView::class;
    }

    /**
     * Should return a class that derives from LeafModel
     *
     * @return LeafModel
     */
    protected function createModel()
    {
        $model = new SearchPanelModel();

        $model->searchControls = $this->createSearchControls();

        $model->urlStateNames = $this->getUrlStateNames($model->searchControls);

        // Pass through of searchedEvent
        $this->searchedEvent = $model->searchedEvent;

        return $model;
    }

    /**
     * Return URL GET param names for the controls in this panel
     *
     * @param Control[] $searchControls
     * @return \string[] An array with keys matching the control names and values defining the GET param names
     */
    protected function getUrlStateNames(array $searchControls)
    {
        $names = [];
        foreach ($searchControls as $control) {
            $name = $control->getName();
            $names[$name] = StringTools::camelCaseToSeparated($name);
        }

        return $names;
    }
}


text:
package com.tyrlib2.bitmap;

import com.tyrlib2.files.IBitmap;

public interface IDrawableBitmap {
	public int getWidth();
	public int getHeight();
	public void recycle();

	public void eraseColor(int color);
	public int toTexture();
	public IBitmap toBitmap();
}


text:
/*
 * This is a "plugin assembly", consumed in our "p5.active-event-sample" console program. Neither contains
 * any references to the other in any ways, still our console program is able to invoke Active Events in this assembly,
 * as if they were methods in a library.
 */

using p5.core;

namespace p5_active_event_sample_plugins
{
    public class SomeActiveEventHandler
    {
        // Here we register a *STATIC* Active Event handler, which will be invoked every time
        // the "foo" Active Event is raised
        [ActiveEvent (Name = "foo")]
        public static void foo (ApplicationContext context, ActiveEventArgs e)
        {
            // Simply outputting some text to the console, proving we were here
            System.Console.WriteLine ("Hello from plugin!");

            // Before showing how we can return values from our Active Event handlers.
            e.Args.Value = "Phosphorus Five";
        }

        // This Active Event will create an instance handler, showing this feature of P5
        // Notice, after this Active Event has been invoked, we will have *TWO* methods handling our
        // "foo" Active Event.
        [ActiveEvent (Name = "create-instance-handler")]
        public static void create_instance_handler (ApplicationContext context, ActiveEventArgs e)
        {
            var fooInstance = new SomeActiveEventHandler ();
            context.RegisterListeningInstance (fooInstance);
        }

        // Notice how this event handler, handles the same ("foo") Active Event, but is *NOT*a static method
        // Hence it is an "instance handler", which will only kick in, for each registered instance of this class
        [ActiveEvent (Name = "foo")]
        public void foo_instance (ApplicationContext context, ActiveEventArgs e)
        {
            // Simply outputting some text to the console, proving we were here
            System.Console.WriteLine ("ANOTHER Hello from plugin!");
        }

        // This Active Event will create an instance handler, showing this feature of P5
        [ActiveEvent (Name = "unregister-instance-handler")]
        public void unregister_instance_handler (ApplicationContext context, ActiveEventArgs e)
        {
            context.UnregisterListeningInstance (this);
        }
    }
}


text:
var CleanUp = require('./clean-up');
var Splitter = require('../../utils/splitter');

var RGB = require('../../colors/rgb');
var HSL = require('../../colors/hsl');
var HexNameShortener = require('../../colors/hex-name-shortener');

var processable = require('../../properties/processable');

var DEFAULT_ROUNDING_PRECISION = 2;
var CHARSET_TOKEN = '@charset';
var CHARSET_REGEXP = new RegExp('^' + CHARSET_TOKEN, 'i');

function SimpleOptimizer(options) {
  this.options = options;

  var units = ['px', 'em', 'ex', 'cm', 'mm', 'in', 'pt', 'pc', '%'];
  if (options.compatibility.units.rem)
    units.push('rem');
  options.unitsRegexp = new RegExp('(^|\\s|\\(|,)0(?:' + units.join('|') + ')', 'g');

  options.precision = {};
  options.precision.value = options.roundingPrecision === undefined ?
    DEFAULT_ROUNDING_PRECISION :
    options.roundingPrecision;
  options.precision.multiplier = Math.pow(10, options.precision.value);
  options.precision.regexp = new RegExp('(\\d*\\.\\d{' + (options.precision.value + 1) + ',})px', 'g');

  options.updateMetadata = this.options.advanced;
}

var valueMinifiers = {
  'background': function (value) {
    return value == 'none' || value == 'transparent' ? '0 0' : value;
  },
  'border-*-radius': function (value) {
    if (value.indexOf('/') == -1)
      return value;

    var parts = value.split(/\s*\/\s*/);
    if (parts[0] == parts[1])
      return parts[0];
    else
      return parts[0] + '/' + parts[1];
  },
  'filter': function (value) {
    if (value.indexOf('DXImageTransform') === value.lastIndexOf('DXImageTransform')) {
      value = value.replace(/progid:DXImageTransform\.Microsoft\.(Alpha|Chroma)/, function (match, filter) {
        return filter.toLowerCase();
      });
    }

    return value
      .replace(/,(\S)/g, ', $1')
      .replace(/ ?= ?/g, '=');
  },
  'font': function (value) {
    var parts = value.split(' ');

    if (parts[1] != 'normal' && parts[1] != 'bold' && !/^[1-9]00/.test(parts[1]))
      parts[0] = this['font-weight'](parts[0]);

    return parts.join(' ');
  },
  'font-weight': function (value) {
    if (value == 'normal')
      return '400';
    else if (value == 'bold')
      return '700';
    else
      return value;
  },
  'outline': function (value) {
    return value == 'none' ? '0' : value;
  }
};

function isNegative(value) {
  var parts = new Splitter(',').split(value);
  for (var i = 0, l = parts.length; i < l; i++) {
    if (parts[i][0] == '-' && parseFloat(parts[i]) < 0)
      return true;
  }

  return false;
}

function zeroMinifier(_, value) {
  if (value.indexOf('0') == -1)
    return value;

  return value
    .replace(/\-0$/g, '0')
    .replace(/\-0([^\.])/g, '0$1')
    .replace(/(^|\s)0+([1-9])/g, '$1$2')
    .replace(/(^|\D)\.0+(\D|$)/g, '$10$2')
    .replace(/(^|\D)\.0+(\D|$)/g, '$10$2')
    .replace(/\.([1-9]*)0+(\D|$)/g, function(match, nonZeroPart, suffix) {
      return (nonZeroPart.length > 0 ? '.' : '') + nonZeroPart + suffix;
    })
    .replace(/(^|\D)0\.(\d)/g, '$1.$2');
}

function zeroDegMinifier(_, value) {
  if (value.indexOf('0deg') == -1)
    return value;

  return value.replace(/\(0deg\)/g, '(0)');
}

function precisionMinifier(_, value, precisionOptions) {
  if (precisionOptions.value === -1 || value.indexOf('.') === -1)
    return value;

  return value
    .replace(precisionOptions.regexp, function(match, number) {
      return Math.round(parseFloat(number) * precisionOptions.multiplier) / precisionOptions.multiplier + 'px';
    })
    .replace(/(\d)\.($|\D)/g, '$1$2');
}

function unitMinifier(_, value, unitsRegexp) {
  return value.replace(unitsRegexp, '$1' + '0');
}

function multipleZerosMinifier(property, value) {
  if (value.indexOf('0 0 0 0') == -1)
    return value;

  if (property.indexOf('box-shadow') > -1)
    return value == '0 0 0 0' ? '0 0' : value;

  return value.replace(/^0 0 0 0$/, '0');
}

function colorMininifier(property, value, compatibility) {
  if (value.indexOf('#') === -1 && value.indexOf('rgb') == -1 && value.indexOf('hsl') == -1)
    return HexNameShortener.shorten(value);

  value = value
    .replace(/rgb\((\-?\d+),(\-?\d+),(\-?\d+)\)/g, function (match, red, green, blue) {
      return new RGB(red, green, blue).toHex();
    })
    .replace(/hsl\((-?\d+),(-?\d+)%?,(-?\d+)%?\)/g, function (match, hue, saturation, lightness) {
      return new HSL(hue, saturation, lightness).toHex();
    })
    .replace(/(^|[^='"])#([0-9a-f]{6})/gi, function (match, prefix, color) {
      if (color[0] == color[1] && color[2] == color[3] && color[4] == color[5])
        return prefix + '#' + color[0] + color[2] + color[4];
      else
        return prefix + '#' + color;
    })
    .replace(/(rgb|rgba|hsl|hsla)\(([^\)]+)\)/g, function(match, colorFunction, colorDef) {
      var tokens = colorDef.split(',');
      var applies = colorFunction == 'hsl' || colorFunction == 'hsla' || tokens[0].indexOf('%') > -1;
      if (!applies)
        return match;

      if (tokens[1].indexOf('%') == -1)
        tokens[1] += '%';
      if (tokens[2].indexOf('%') == -1)
        tokens[2] += '%';
      return colorFunction + '(' + tokens.join(',') + ')';
    });

  if (compatibility.colors.opacity) {
    value = value.replace(/(?:rgba|hsla)\(0,0%?,0%?,0\)/g, function (match) {
      if (new Splitter(',').split(value).pop().indexOf('gradient(') > -1)
        return match;

      return 'transparent';
    });
  }

  return HexNameShortener.shorten(value);
}

function spaceMinifier(property, value) {
  if (property == 'filter' || processable.implementedFor.test(property))
    return value;

  return value.replace(/\) /g, ')');
}

function reduce(body, options) {
  var reduced = [];
  var properties = [];
  var newProperty;

  for (var i = 0, l = body.length; i < l; i++) {
    var token = body[i];

    // FIXME: the check should be gone with #396
    if (token.value.indexOf('__ESCAPED_') === 0) {
      reduced.push(token);
      properties.push(token.value);
      continue;
    }

    var firstColon = token.value.indexOf(':');
    var property = token.value.substring(0, firstColon);
    var value = token.value.substring(firstColon + 1);
    var important = false;

    if (!options.compatibility.properties.iePrefixHack && (property[0] == '_' || property[0] == '*'))
      continue;

    if (value.indexOf('!important') > 0 || value.indexOf('! important') > 0) {
      value = value.substring(0, value.indexOf('!')).trim();
      important = true;
    }

    if (property.indexOf('padding') === 0 && isNegative(value))
      continue;

    if (property.indexOf('border') === 0 && property.indexOf('radius') > 0)
      value = valueMinifiers['border-*-radius'](value);

    if (valueMinifiers[property])
      value = valueMinifiers[property](value);

    value = precisionMinifier(property, value, options.precision);
    value = zeroMinifier(property, value);
    value = zeroDegMinifier(property, value);
    value = unitMinifier(property, value, options.unitsRegexp);
    value = multipleZerosMinifier(property, value);
    value = colorMininifier(property, value, options.compatibility);

    if (!options.compatibility.properties.spaceAfterClosingBrace)
      value = spaceMinifier(property, value);

    newProperty = property + ':' + value + (important ? '!important' : '');
    reduced.push({ value: newProperty, metadata: token.metadata });
    properties.push(newProperty);
  }

  return {
    tokenized: reduced,
    list: properties
  };
}

SimpleOptimizer.prototype.optimize = function(tokens) {
  var self = this;
  var hasCharset = false;
  var options = this.options;

  function _optimize(tokens) {
    for (var i = 0, l = tokens.length; i < l; i++) {
      var token = tokens[i];
      // FIXME: why it's so?
      if (!token)
        break;

      if (token.kind == 'selector') {
        var newSelectors = CleanUp.selectors(token.value, !options.compatibility.selectors.ie7Hack, options.compatibility.selectors.adjacentSpace);
        token.value = newSelectors.tokenized;

        if (token.value.length === 0) {
          tokens.splice(i, 1);
          i--;
          continue;
        }
        var newBody = reduce(token.body, self.options);
        token.body = newBody.tokenized;

        if (options.updateMetadata) {
          token.metadata.body = newBody.list.join(';');
          token.metadata.bodiesList = newBody.list;
          token.metadata.selector = newSelectors.list.join(',');
          token.metadata.selectorsList = newSelectors.list;
        }
      } else if (token.kind == 'block') {
        token.value = CleanUp.block(token.value);
        if (token.isFlatBlock)
          token.body = reduce(token.body, self.options).tokenized;
        else
          _optimize(token.body);
      } else if (token.kind == 'at-rule') {
        token.value = CleanUp.atRule(token.value);

        if (CHARSET_REGEXP.test(token.value)) {
          if (hasCharset || token.value.indexOf(CHARSET_TOKEN) == -1) {
            tokens.splice(i, 1);
            i--;
          } else {
            hasCharset = true;
            tokens.splice(i, 1);
            tokens.unshift({ kind: 'at-rule', value: token.value.replace(CHARSET_REGEXP, CHARSET_TOKEN) });
          }
        }
      }
    }
  }

  _optimize(tokens);
};

module.exports = SimpleOptimizer;


text:
<?php
$loader = __DIR__ . '/core/wp-blog-header.php';

if ( ! file_exists( $loader ) ) {
    die( 'WordPress is not installed. Use <i>wp core download</i> command' );
}

ini_set( 'error_log', dirname( __DIR__ ) . '/logs/php.log' );
define( 'WP_USE_THEMES', true );
require( $loader );


text:
require_relative('../../puppet/property/netscaler_truthy')

Puppet::Type.newtype(:netscaler_csvserver_responderpolicy_binding) do
  @doc = 'Manage a binding between a content switching vserver and a responder policy.'

  apply_to_device
  ensurable

  newparam(:name, :namevar => true) do
    desc "csvserver_name/policy_name"
  end

  newproperty(:priority) do
    desc "The priority of the policy binding.

Min = 1
Max = 2147483647"
    newvalues(/^\d+$/)
    munge do |value|
      Integer(value)
    end
  end

  newproperty(:goto_expression) do
    desc "Expression specifying the priority of the next policy which will get evaluated if the current policy rule evaluates to TRUE"
  end

  newproperty(:invoke_policy_label) do
    desc "Label of policy to invoke if the bound policy evaluates to true."
  end

  newproperty(:invoke_vserver_label) do
    desc "Label of vserver to invoke if the bound policy evaluates to true."
  end

  autorequire(:netscaler_csvserver) do
    [self[:name].split('/')[0], self[:invoke_vserver_label]]
  end

  autorequire(:netscaler_responderpolicy) do
    self[:name].split('/')[1]
  end

  autorequire(:netscaler_lbvserver) do
    self[:invoke_vserver_label]
  end

  autorequire(:netscaler_responderpolicylabel) do
    self[:invoke_policy_label]
  end

  validate do
    if [
      self[:invoke_policy_label],
      self[:invoke_vserver_label],
    ].compact.length > 1
      fail "Only one of invoke_policy_label or invoke_vserver_label may be specified per binding."
    end
  end
end


text:
const getManyComplete = require('../../../posts/dal/getManyComplete');

module.exports = (req, res, next) => {
  // Get location posts with their attachments and urls completed.
  //

  getManyComplete({
    locationId: req.location._id,
    deleted: false,
  }, {
    // NOTE skip and limit already validated by middleware
    skip: req.query.skip,
    limit: req.query.limit + 1, // +1 to detect if there is more
  }, (err, posts) => {
    if (err) {
      return next(err);
    }

    // Hint if the client should show Load More button
    let moreAvailable = false;
    if (posts.length > req.query.limit) {
      moreAvailable = true;
    }

    // Remove the Load More detector
    const limitedPosts = posts.slice(0, req.query.limit);

    return res.json({
      entries: limitedPosts,
      more: moreAvailable,
    });
  });

};


text:
package org.apache.nifi.provenance.store;

import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.nifi.events.EventReporter;
import org.apache.nifi.provenance.ProvenanceEventRecord;
import org.apache.nifi.provenance.RepositoryConfiguration;
import org.apache.nifi.provenance.StandardProvenanceEventRecord;
import org.apache.nifi.provenance.authorization.EventAuthorizer;
import org.apache.nifi.provenance.index.EventIndex;
import org.apache.nifi.provenance.serialization.RecordReader;
import org.apache.nifi.provenance.serialization.RecordWriter;
import org.apache.nifi.provenance.serialization.StorageSummary;
import org.apache.nifi.provenance.store.iterator.EventIterator;
import org.apache.nifi.provenance.store.iterator.SelectiveRecordReaderEventIterator;
import org.apache.nifi.provenance.store.iterator.SequentialRecordReaderEventIterator;
import org.apache.nifi.provenance.toc.TocUtil;
import org.apache.nifi.provenance.util.DirectoryUtils;
import org.apache.nifi.provenance.util.NamedThreadFactory;
import org.apache.nifi.util.FormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WriteAheadStorePartition implements EventStorePartition {
    private static final Logger logger = LoggerFactory.getLogger(WriteAheadStorePartition.class);

    private final RepositoryConfiguration config;
    private final File partitionDirectory;
    private final String partitionName;
    private final RecordWriterFactory recordWriterFactory;
    private final RecordReaderFactory recordReaderFactory;
    private final BlockingQueue<File> filesToCompress;
    private final AtomicLong idGenerator;
    private final AtomicLong maxEventId = new AtomicLong(-1L);
    private volatile boolean closed = false;

    private AtomicReference<RecordWriterLease> eventWriterLeaseRef = new AtomicReference<>();

    private final SortedMap<Long, File> minEventIdToPathMap = new TreeMap<>();  // guarded by synchronizing on object

    public WriteAheadStorePartition(final File storageDirectory, final String partitionName, final RepositoryConfiguration repoConfig, final RecordWriterFactory recordWriterFactory,
        final RecordReaderFactory recordReaderFactory, final BlockingQueue<File> filesToCompress, final AtomicLong idGenerator, final EventReporter eventReporter) {

        this.partitionName = partitionName;
        this.config = repoConfig;
        this.idGenerator = idGenerator;
        this.partitionDirectory = storageDirectory;
        this.recordWriterFactory = recordWriterFactory;
        this.recordReaderFactory = recordReaderFactory;
        this.filesToCompress = filesToCompress;
    }

    @Override
    public void close() throws IOException {
        closed = true;

        final RecordWriterLease lease = eventWriterLeaseRef.get();
        if (lease != null) {
            lease.close();
        }
    }

    @Override
    public synchronized void initialize() throws IOException {
        if (!partitionDirectory.exists()) {
            Files.createDirectories(partitionDirectory.toPath());
        }

        final File[] files = partitionDirectory.listFiles(DirectoryUtils.EVENT_FILE_FILTER);
        if (files == null) {
            throw new IOException("Could not access files in the " + partitionDirectory + " directory");
        }

        // We need to determine what the largest Event ID is in this partition. To do this, we
        // iterate over all files starting with the file that has the greatest ID, and try to find
        // the largest Event ID in that file. Once we successfully determine the greatest Event ID
        // in any one of the files, we are done, since we are iterating over the files in order of
        // the Largest Event ID to the smallest.
        long maxEventId = -1L;
        final List<File> fileList = Arrays.asList(files);
        Collections.sort(fileList, DirectoryUtils.LARGEST_ID_FIRST);
        for (final File file : fileList) {
            try {
                final RecordReader reader = recordReaderFactory.newRecordReader(file, Collections.emptyList(), Integer.MAX_VALUE);
                final long eventId = reader.getMaxEventId();
                if (eventId > maxEventId) {
                    maxEventId = eventId;
                    break;
                }
            } catch (final Exception e) {
                logger.warn("Could not read file {}; if this file contains Provenance Events, new events may be created with the same event identifiers", file, e);
            }
        }

        synchronized (minEventIdToPathMap) {
            for (final File file : fileList) {
                final long minEventId = DirectoryUtils.getMinId(file);
                minEventIdToPathMap.put(minEventId, file);
            }
        }

        this.maxEventId.set(maxEventId);

        // If configured to compress, compress any files that are not yet compressed.
        if (config.isCompressOnRollover()) {
            final File[] uncompressedFiles = partitionDirectory.listFiles(f -> f.getName().endsWith(".prov"));
            if (uncompressedFiles != null) {
                for (final File file : uncompressedFiles) {
                    // If we have both a compressed file and an uncompressed file for the same .prov file, then
                    // we must have been in the process of compressing it when NiFi was restarted. Delete the partial
                    // .gz file and we will start compressing it again.
                    final File compressed = new File(file.getParentFile(), file.getName() + ".gz");
                    if (compressed.exists()) {
                        compressed.delete();
                    }
                }
            }
        }

        // Update the ID Generator to the max of the ID Generator or maxEventId
        final long nextPartitionId = maxEventId + 1;
        final long updatedId = idGenerator.updateAndGet(curVal -> Math.max(curVal, nextPartitionId));
        logger.info("After recovering {}, next Event ID to be generated will be {}", partitionDirectory, updatedId);
    }

    @Override
    public StorageResult addEvents(final Iterable<ProvenanceEventRecord> events) throws IOException {
        if (closed) {
            throw new IOException(this + " is closed");
        }

        // Claim a Record Writer Lease so that we have a writer to persist the events to
        boolean claimed = false;
        RecordWriterLease lease = null;
        while (!claimed) {
            lease = getLease();
            claimed = lease.tryClaim();

            if (claimed) {
                break;
            }

            if (lease.shouldRoll()) {
                tryRollover(lease);
            }
        }

        // Add the events to the writer and ensure that we always
        // relinquish the claim that we've obtained on the writer
        Map<ProvenanceEventRecord, StorageSummary> storageMap;
        final RecordWriter writer = lease.getWriter();
        try {
            storageMap = addEvents(events, writer);
        } finally {
            lease.relinquishClaim();
        }

        // Roll over the writer if necessary
        Integer eventsRolledOver = null;
        final boolean shouldRoll = lease.shouldRoll();
        try {
            if (shouldRoll && tryRollover(lease)) {
                eventsRolledOver = writer.getRecordsWritten();
            }
        } catch (final IOException ioe) {
            logger.error("Updated {} but failed to rollover to a new Event File", this, ioe);
        }

        final Integer rolloverCount = eventsRolledOver;
        return new StorageResult() {
            @Override
            public Map<ProvenanceEventRecord, StorageSummary> getStorageLocations() {
                return storageMap;
            }

            @Override
            public boolean triggeredRollover() {
                return rolloverCount != null;
            }

            @Override
            public Integer getEventsRolledOver() {
                return rolloverCount;
            }

            @Override
            public String toString() {
                return getStorageLocations().toString();
            }
        };
    }

    private RecordWriterLease getLease() throws IOException {
        while (true) {
            final RecordWriterLease lease = eventWriterLeaseRef.get();
            if (lease != null) {
                return lease;
            }

            if (tryRollover(null)) {
                return eventWriterLeaseRef.get();
            }
        }
    }

    private synchronized boolean tryRollover(final RecordWriterLease lease) throws IOException {
        if (!Objects.equals(lease, eventWriterLeaseRef.get())) {
            return false;
        }

        final long nextEventId = idGenerator.get();
        final File updatedEventFile = new File(partitionDirectory, nextEventId + ".prov");
        final RecordWriter updatedWriter = recordWriterFactory.createWriter(updatedEventFile, idGenerator, false, true);

        // Synchronize on the writer to ensure that no other thread is able to obtain the writer and start writing events to it until after it has
        // been fully initialized (i.e., the header has been written, etc.)
        synchronized (updatedWriter) {
            final RecordWriterLease updatedLease = new RecordWriterLease(updatedWriter, config.getMaxEventFileCapacity(), config.getMaxEventFileCount());
            final boolean updated = eventWriterLeaseRef.compareAndSet(lease, updatedLease);

            if (updated) {
                if (lease != null) {
                    lease.close();
                }

                updatedWriter.writeHeader(nextEventId);

                synchronized (minEventIdToPathMap) {
                    minEventIdToPathMap.put(nextEventId, updatedEventFile);
                }

                if (config.isCompressOnRollover() && lease != null && lease.getWriter() != null) {
                    boolean offered = false;
                    while (!offered && !closed) {
                        try {
                            offered = filesToCompress.offer(lease.getWriter().getFile(), 1, TimeUnit.SECONDS);
                        } catch (final InterruptedException ie) {
                            Thread.currentThread().interrupt();
                            throw new IOException("Interrupted while waiting to enqueue " + lease.getWriter().getFile() + " for compression");
                        }
                    }
                }

                return true;
            } else {
                try {
                    updatedWriter.close();
                } catch (final Exception e) {
                    logger.warn("Failed to close Record Writer {}; some resources may not be cleaned up properly.", updatedWriter, e);
                }

                updatedEventFile.delete();
                return false;
            }
        }
    }

    private Map<ProvenanceEventRecord, StorageSummary> addEvents(final Iterable<ProvenanceEventRecord> events, final RecordWriter writer) throws IOException {
        final Map<ProvenanceEventRecord, StorageSummary> locationMap = new HashMap<>();

        try {
            long maxId = -1L;
            int numEvents = 0;
            for (final ProvenanceEventRecord nextEvent : events) {
                final StorageSummary writerSummary = writer.writeRecord(nextEvent);
                final StorageSummary summaryWithIndex = new StorageSummary(writerSummary.getEventId(), writerSummary.getStorageLocation(), this.partitionName,
                    writerSummary.getBlockIndex(), writerSummary.getSerializedLength(), writerSummary.getBytesWritten());
                locationMap.put(nextEvent, summaryWithIndex);
                maxId = summaryWithIndex.getEventId();
                numEvents++;
            }

            if (numEvents == 0) {
                return locationMap;
            }

            writer.flush();

            // Update max event id to be equal to be the greater of the current value or the
            // max value just written.
            final long maxIdWritten = maxId;
            this.maxEventId.getAndUpdate(cur -> maxIdWritten > cur ? maxIdWritten : cur);

            if (config.isAlwaysSync()) {
                writer.sync();
            }
        } catch (final Exception e) {
            // We need to set the repoDirty flag before we release the lock for this journal.
            // Otherwise, another thread may write to this journal -- this is a problem because
            // the journal contains part of our record but not all of it. Writing to the end of this
            // journal will result in corruption!
            writer.markDirty();
            throw e;
        }

        return locationMap;
    }

    @Override
    public long getSize() {
        return getEventFilesFromDisk()
            .collect(Collectors.summarizingLong(file -> file.length()))
            .getSum();
    }

    private Stream<File> getEventFilesFromDisk() {
        final File[] files = partitionDirectory.listFiles(DirectoryUtils.EVENT_FILE_FILTER);
        return files == null ? Stream.empty() : Arrays.stream(files);
    }

    @Override
    public long getMaxEventId() {
        return maxEventId.get();
    }

    @Override
    public Optional<ProvenanceEventRecord> getEvent(final long id) throws IOException {
        final Optional<File> option = getPathForEventId(id);
        if (!option.isPresent()) {
            return Optional.empty();
        }

        try (final RecordReader reader = recordReaderFactory.newRecordReader(option.get(), Collections.emptyList(), config.getMaxAttributeChars())) {
            final Optional<ProvenanceEventRecord> eventOption = reader.skipToEvent(id);
            if (!eventOption.isPresent()) {
                return eventOption;
            }

            // If an event is returned, the event may be the one we want, or it may be an event with a
            // higher event ID, if the desired event is not in the record reader. So we need to get the
            // event and check the Event ID to know whether to return the empty optional or the Optional
            // that was returned.
            final ProvenanceEventRecord event = eventOption.get();
            if (event.getEventId() == id) {
                return eventOption;
            } else {
                return Optional.empty();
            }
        }
    }

    @Override
    public List<ProvenanceEventRecord> getEvents(final long firstRecordId, final int maxEvents, final EventAuthorizer authorizer) throws IOException {
        final List<ProvenanceEventRecord> events = new ArrayList<>(Math.min(maxEvents, 1000));
        try (final EventIterator iterator = createEventIterator(firstRecordId)) {
            Optional<ProvenanceEventRecord> eventOption;
            while ((eventOption = iterator.nextEvent()).isPresent() && events.size() < maxEvents) {
                final ProvenanceEventRecord event = eventOption.get();
                if (authorizer.isAuthorized(event)) {
                    events.add(event);
                }
            }
        }

        return events;
    }

    @Override
    public EventIterator createEventIterator(final long minDesiredId) {
        final List<File> filesOfInterest = new ArrayList<>();
        synchronized (minEventIdToPathMap) {
            File lastFile = null;

            for (final Map.Entry<Long, File> entry : minEventIdToPathMap.entrySet()) {
                final long minFileId = entry.getKey();

                // If the minimum ID for the file is greater than the minDesiredId, then
                // that means that we will want to iterate over this file.
                if (minFileId > minDesiredId) {
                    // The minimum ID for this file is greater than the desired ID, so
                    // that means that the last file we saw may have the minimum desired
                    // ID and any number of more events before we get to this file. So
                    // if we've not already added the lastFile, add it now.
                    if (filesOfInterest.isEmpty() && lastFile != null) {
                        filesOfInterest.add(lastFile);
                    }

                    filesOfInterest.add(entry.getValue());
                }

                lastFile = entry.getValue();
            }

            // We don't know the max ID of the last file, so we always want to include it, since it may contain
            // an event with an ID greater than minDesiredId.
            if (lastFile != null && !filesOfInterest.contains(lastFile)) {
                filesOfInterest.add(lastFile);
            }
        }

        if (filesOfInterest.isEmpty()) {
            return EventIterator.EMPTY;
        }

        return new SequentialRecordReaderEventIterator(filesOfInterest, recordReaderFactory, minDesiredId, config.getMaxAttributeChars());
    }

    @Override
    public EventIterator createEventIterator(final List<Long> eventIds) {
        final List<File> allFiles;
        synchronized (minEventIdToPathMap) {
            allFiles = new ArrayList<>(minEventIdToPathMap.values());
        }

        if (allFiles.isEmpty()) {
            return EventIterator.EMPTY;
        }

        return new SelectiveRecordReaderEventIterator(allFiles, recordReaderFactory, eventIds, config.getMaxAttributeChars());
    }

    private Optional<File> getPathForEventId(final long id) {
        File lastFile = null;

        synchronized (minEventIdToPathMap) {
            for (final Map.Entry<Long, File> entry : minEventIdToPathMap.entrySet()) {
                final long minId = entry.getKey();
                if (minId > id) {
                    break;
                }

                lastFile = entry.getValue();
            }
        }

        return Optional.ofNullable(lastFile);
    }

    @Override
    public void purgeOldEvents(final long olderThan, final TimeUnit unit) {
        final long timeCutoff = System.currentTimeMillis() - unit.toMillis(olderThan);

        getEventFilesFromDisk().filter(file -> file.lastModified() < timeCutoff)
            .sorted(DirectoryUtils.SMALLEST_ID_FIRST)
            .forEach(file -> delete(file));
    }

    @Override
    public long purgeOldestEvents() {
        final List<File> eventFiles = getEventFilesFromDisk().sorted(DirectoryUtils.SMALLEST_ID_FIRST).collect(Collectors.toList());
        if (eventFiles.isEmpty()) {
            return 0L;
        }

        for (final File eventFile : eventFiles) {
            final long fileSize = eventFile.length();

            if (delete(eventFile)) {
                logger.debug("{} Deleted {} event file ({}) due to storage limits", this, eventFile, FormatUtils.formatDataSize(fileSize));
                return fileSize;
            } else {
                logger.warn("{} Failed to delete oldest event file {}. This file should be cleaned up manually.", this, eventFile);
                continue;
            }
        }

        return 0L;
    }

    private boolean delete(final File file) {
        final long firstEventId = DirectoryUtils.getMinId(file);
        synchronized (minEventIdToPathMap) {
            minEventIdToPathMap.remove(firstEventId);
        }

        if (!file.delete()) {
            logger.warn("Failed to remove Provenance Event file {}; this file should be cleaned up manually", file);
            return false;
        }

        final File tocFile = TocUtil.getTocFile(file);
        if (tocFile.exists() && !tocFile.delete()) {
            logger.warn("Failed to remove Provenance Table-of-Contents file {}; this file should be cleaned up manually", tocFile);
        }

        return true;
    }

    void reindexLatestEvents(final EventIndex eventIndex) {
        final List<File> eventFiles = getEventFilesFromDisk().sorted(DirectoryUtils.SMALLEST_ID_FIRST).collect(Collectors.toList());
        if (eventFiles.isEmpty()) {
            return;
        }

        final long minEventIdToReindex = eventIndex.getMinimumEventIdToReindex(partitionName);
        final long maxEventId = getMaxEventId();
        final long eventsToReindex = maxEventId - minEventIdToReindex;

        logger.info("The last Provenance Event indexed for partition {} is {}, but the last event written to partition has ID {}. "
            + "Re-indexing up to the last {} events to ensure that the Event Index is accurate and up-to-date",
            partitionName, minEventIdToReindex, maxEventId, eventsToReindex, partitionDirectory);

        // Find the first event file that we care about.
        int firstEventFileIndex = 0;
        for (int i = eventFiles.size() - 1; i >= 0; i--) {
            final File eventFile = eventFiles.get(i);
            final long minIdInFile = DirectoryUtils.getMinId(eventFile);
            if (minIdInFile <= minEventIdToReindex) {
                firstEventFileIndex = i;
                break;
            }
        }

        // Create a subList that contains the files of interest
        final List<File> eventFilesToReindex = eventFiles.subList(firstEventFileIndex, eventFiles.size());

        final ExecutorService executor = Executors.newFixedThreadPool(Math.min(4, eventFilesToReindex.size()), new NamedThreadFactory("Re-Index Provenance Events", true));
        final List<Future<?>> futures = new ArrayList<>(eventFilesToReindex.size());
        final AtomicLong reindexedCount = new AtomicLong(0L);

        // Re-Index the last bunch of events.
        // We don't use an Event Iterator here because it's possible that one of the event files could be corrupt (for example, if NiFi does while
        // writing to the file, a record may be incomplete). We don't want to prevent us from moving on and continuing to index the rest of the
        // un-indexed events. So we just use a List of files and create a reader for each one.
        final long start = System.nanoTime();
        int fileCount = 0;
        for (final File eventFile : eventFilesToReindex) {
            final boolean skipToEvent;
            if (fileCount++ == 0) {
                skipToEvent = true;
            } else {
                skipToEvent = false;
            }

            final Runnable reindexTask = new Runnable() {
                @Override
                public void run() {
                    final Map<ProvenanceEventRecord, StorageSummary> storageMap = new HashMap<>(1000);

                    try (final RecordReader recordReader = recordReaderFactory.newRecordReader(eventFile, Collections.emptyList(), Integer.MAX_VALUE)) {
                        if (skipToEvent) {
                            final Optional<ProvenanceEventRecord> eventOption = recordReader.skipToEvent(minEventIdToReindex);
                            if (!eventOption.isPresent()) {
                                return;
                            }
                        }

                        StandardProvenanceEventRecord event = null;
                        while (true) {
                            final long startBytesConsumed = recordReader.getBytesConsumed();

                            event = recordReader.nextRecord();
                            if (event == null) {
                                eventIndex.reindexEvents(storageMap);
                                reindexedCount.addAndGet(storageMap.size());
                                storageMap.clear();
                                break; // stop reading from this file
                            } else {
                                final long eventSize = recordReader.getBytesConsumed() - startBytesConsumed;
                                storageMap.put(event, new StorageSummary(event.getEventId(), eventFile.getName(), partitionName, recordReader.getBlockIndex(), eventSize, 0L));

                                if (storageMap.size() == 1000) {
                                    eventIndex.reindexEvents(storageMap);
                                    reindexedCount.addAndGet(storageMap.size());
                                    storageMap.clear();
                                }
                            }
                        }
                    } catch (final EOFException eof) {
                        // Ran out of data. Continue on.
                        logger.warn("Failed to find event with ID {} in Event File {} due to {}", minEventIdToReindex, eventFile, eof.toString());
                    } catch (final Exception e) {
                        logger.error("Failed to index Provenance Events found in {}", eventFile, e);
                    }
                }
            };

            futures.add(executor.submit(reindexTask));
        }

        for (final Future<?> future : futures) {
            try {
                future.get();
            } catch (final ExecutionException ee) {
                logger.error("Failed to re-index some Provenance events. These events may not be query-able via the Provenance interface", ee.getCause());
            } catch (final InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.error("Interrupted while waiting for Provenance events to be re-indexed", e);
                break;
            }
        }

        try {
            eventIndex.commitChanges(partitionName);
        } catch (final IOException e) {
            logger.error("Failed to re-index Provenance Events for partition " + partitionName, e);
        }

        executor.shutdown();

        final long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
        final long seconds = millis / 1000L;
        final long millisRemainder = millis % 1000L;
        logger.info("Finished re-indexing {} events across {} files for {} in {}.{} seconds",
            reindexedCount.get(), eventFilesToReindex.size(), partitionDirectory, seconds, millisRemainder);
    }

    @Override
    public String toString() {
        return "Provenance Event Store Partition[directory=" + partitionDirectory + "]";
    }
}


text:
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using MvcBasic.Models;

namespace MvcBasic
{
    // このアプリケーションで使用されるアプリケーション ユーザー マネージャーを設定します。UserManager は ASP.NET Identity の中で定義されており、このアプリケーションで使用されます。

    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
            // ユーザー名の検証ロジックを設定します
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };
            // パスワードの検証ロジックを設定します
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };
            // 2 要素認証プロバイダーを登録します。このアプリケーションでは、Phone and Emails をユーザー検証用コード受け取りのステップとして使用します。
            // 独自のプロバイダーを作成して、ここにプラグインすることができます。
            manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser>
            {
                MessageFormat = "Your security code is: {0}"
            });
            manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<ApplicationUser>
            {
                Subject = "セキュリティ コード",
                BodyFormat = "Your security code is: {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
    }

    public class EmailService : IIdentityMessageService
    {
        public Task SendAsync(IdentityMessage message)
        {
            // 電子メールを送信するには、電子メール サービスをここにプラグインします。
            return Task.FromResult(0);
        }
    }

    public class SmsService : IIdentityMessageService
    {
        public Task SendAsync(IdentityMessage message)
        {
            // テキスト メッセージを送信するには、SMS サービスをここにプラグインします。
            return Task.FromResult(0);
        }
    }
}


text:
If Lambdas aren't for you, and your system desires to have the heartbeat monitor to
check for partial failures, then you need a service running at an interval,
which checks the health of the running activities.


text:
package cd4017be.automation.pipes;

import cd4017be.automation.Objects;
import cd4017be.automation.Block.BlockLiquidPipe;
import cd4017be.automation.Item.PipeUpgradeFluid;
import cd4017be.lib.ModTileEntity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ITickable;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;

public class FluidExtractor extends FluidComp implements ITickable {

	public FluidExtractor(BasicWarpPipe pipe, byte side) {
		super(pipe, side);
	}

	@Override
	public void update() {
		if (!this.isValid()) return;
		IFluidHandler acc = link.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, EnumFacing.VALUES[side^1]);
		if (acc == null || (filter != null && !filter.active(pipe.redstone))) return;
		FluidStack stack = PipeUpgradeFluid.isNullEq(filter) ? acc.drain(Integer.MAX_VALUE, false) : filter.getExtract(null, acc);
		if (stack == null) return;
		int n = stack.amount;
		FluidStack result = pipe.network.insertFluid(stack.copy(), filter == null || (filter.mode & 2) == 0 ? Byte.MAX_VALUE : filter.priority);
		if (result != null) stack.amount -= result.amount;
		if (n > 0) acc.drain(stack, true);
	}

	@Override
	public boolean onClicked(EntityPlayer player, EnumHand hand, ItemStack item, long uid) {
		if (player == null) ((ModTileEntity)pipe.tile).dropStack(new ItemStack(Objects.liquidPipe, 1, BlockLiquidPipe.ID_Extraction));
		if (super.onClicked(player, hand, item, uid) || player == null) return true;
		if (player.isSneaking() && player.getHeldItemMainhand() == null) {
			((ModTileEntity)pipe.tile).dropStack(new ItemStack(Objects.liquidPipe, 1, BlockLiquidPipe.ID_Extraction));
			pipe.con[side] = 0;
			pipe.network.remConnector(pipe, side);
			pipe.updateCon = true;
			pipe.hasFilters &= ~(1 << side);
			((ModTileEntity)pipe.tile).markUpdate();
			return true;
		}
		return false;
	}

}


text:
describe('BC services', function() {
	describe('Service: bcrypt', function(){

		var bcrypt;

		beforeEach(module('bc'));

		beforeEach(inject(function (_bcrypt_) {
			bcrypt = _bcrypt_;
		}));

		it('should encrypt and decrypt string', function() {
			var encrypted = bcrypt.encrypt('hello world!', 'mypassword');
			expect(encrypted).not.toEqual("");

			var decrypted = bcrypt.decrypt(encrypted, 'mypassword');
			expect(decrypted).toEqual("hello world!");

		});
	});
});


text:
var _ = require('underscore');
var models = require('../models');

var Scrape = models.Scrape;

var makerPage = function(req, res) {

    Scrape.ScrapeModel.findByOwner(req.session.account._id, function(err, docs) {

        if(err) {
            console.log(err);
            return res.status(400).json({error:'An error occurred'});
        }

        res.render('thumb', {scrapes: docs});
    });
};

var makeScrape = function(req, res) {
    if(!req.body.url || !req.body.query) {
        return res.status(400).json({error: "Both URL and Query are required"});
    }

    var scrapeData = {
        url: req.body.url,
        query: req.body.query,
        results: [{url: 'http://supermotojunkie.com/forumdisplay.php?72-Bikes'},{url: 'http://forum.miata.net/vb/forumdisplay.php?f=99'}],
        owner: req.session.account._id
    };

    var newScrape = new Scrape.ScrapeModel(scrapeData);

    newScrape.save(function(err) {
        if(err) {
            console.log(err);
            return res.status(400).json({error:'An error occurred'});
        }

        res.json({redirect: '/thumb'});
    });

};

module.exports.makerPage = makerPage;
module.exports.make = makeScrape;


text:
====================
Install with Docker
====================

.. _install-with-docker:

Want the easiest way to start contributing to AMO? Try our Docker-based
development environment.

First you'll need to install Docker_. Please read their docs for
the installation steps specific to your operating system.

There are two options for running docker depending on the platform
you are running.

 * Run docker on the host machine directly (recommended)
 * Run docker-machine which will run docker inside a virtual-machine

Historically Mac and Windows could only run Docker via a vm. That has
recently changed with the arrival of docker-for-mac_ and docker-for-windows_.

If your platform can run Docker directly either on Linux, with docker-for-mac_
or docker-for-windows_ then this is the easiest way to run ``addons-server``.

If you have problems, due to not meeting the minimum specifications for
docker-for-windows_ or you'd prefer to keep running docker-machine vms then
docker-machine will still work just fine. See the docs for creating the
vm here :ref:`creating-the-docker-vm`

.. note::
    If you're on a Mac and already have a working docker-machine setup you
    can run that and docker-for-mac (*but not docker-for-windows*) side by side.
    The only caveat is it's recommended that you keep the versions of Docker on
    the vm and the host in-sync to ensure compatibility when you switch between
    them.

Setting up the containers
~~~~~~~~~~~~~~~~~~~~~~~~~

.. note::
    docker-toolbox, docker-for-mac and docker-for-windows will install ``docker-compose``
    for you. If you're on Linux and you need it, you can install it manually with::

        pip install docker-compose

Next once you have Docker up and running follow these steps
on your host machine::

    # Checkout the addons-server sourcecode.
    git clone git://github.com/mozilla/addons-server.git
    cd addons-server
    # Download the containers
    docker-compose pull  # Can take a while depending on your internet bandwidth.
    # Start up the containers
    docker-compose up -d
    make initialize_docker  # Answer yes, and create your superuser when asked.
    # On Windows you can substitute `make initialize_docker` for the command:
    docker-compose exec web make initialize

.. note::

   Docker requires the code checkout to exist within your home directory so
   that Docker can mount the source-code into the container.

Accessing the web server
~~~~~~~~~~~~~~~~~~~~~~~~

By default our docker-compose config exposes the web-server on port 80 of localhost.

We use ``olympia.dev`` as the default hostname to access your container server (e.g. for
Firefox Accounts). To be able access the development environment using ``http://olympia.dev``
you'll need to  edit your ``/etc/hosts`` file on your native operating system.
For example::

    [ip-address]  olympia.dev

Typically the IP address is localhost (127.0.0.1) but if you're using docker-machine
see :ref:`accessing-the-web-server-docker-machine` for details of how to get the ip of
the Docker vm.

By default we configure `OLYMPIA_SITE_URL` to point to `http://olympia.dev`.

If you choose a different hostname you'll need to set that environment variable
and restart the Docker containers::

    docker-compose stop # only needed if running
    export OLYMPIA_SITE_URL=http://[YOUR_HOSTNAME}
    docker-compose up -d

Running common commands
~~~~~~~~~~~~~~~~~~~~~~~

Run the tests using ``make``, *outside* of the Docker container::

    make test
    # or
    docker-compose exec web py.test src/olympia/

You can run commands inside the Docker container by ``ssh``\ing into it using::

    make shell
    # or
    docker-compose exec web bash

Then to run the tests inside the Docker container you can run::

    py.test

You can also run single commands from your host machine without opening a shell
on each container. Here is an example of running the ``py.test`` command on the
``web`` container::

    docker-compose run web py.test

If you'd like to use a python debugger to interactively
debug Django view code, check out the :ref:`debugging` section.

.. note::
    If you see an error like ``No such container: addonsserver_web_1`` and
    your containers are running you can overwrite the base name for docker
    containers with the ``COMPOSE_PROJECT_NAME`` environment variable. If your
    container is named ``localaddons_web_1`` you would set
    ``COMPOSE_PROJECT_NAME=localaddons``.

Updating your containers
~~~~~~~~~~~~~~~~~~~~~~~~

Any time you update Olympia (e.g., by running ``git pull``), you should make
sure to update your Docker image and database with any new requirements or
migrations::

    docker-compose stop
    docker-compose pull
    docker-compose up -d
    make update_docker  # Runs database migrations and rebuilds assets.
    # On Windows you can substitute `make update_docker` for the following two commands:
    docker-compose exec worker make update_deps
    docker-compose exec web make update

Gotchas!
~~~~~~~~

Here's a list of a few of the issues you might face when using Docker.

Can't access the web server?
----------------------------

Check you've created a hosts file entry pointing ``olympia.dev`` to the
relevant IP address.

If containers are failing to start use ``docker-compose ps`` to check their
running status.

Another way to find out what's wrong is to run ``docker-compose logs``.

Getting "Programming error [table] doesn't exist"?
--------------------------------------------------

Make sure you've run the ``make initialize_docker`` step as detailed in
the initial setup instructions.

Port collisions (nginx container fails to start)
------------------------------------------------

If you're already running a service on port 80 or 8000 on your host machine,
the ``nginx`` container will fail to start. This is because the
``docker-compose.override.yml`` file tells ``nginx`` to listen on port 80
and the web service to listen on port 8000 by default.

This problem will manifest itself by the services failing to start. Here's an
example for the most common case of ``nginx`` not starting due to a collision on
port 80::

    ERROR: for nginx  Cannot start service nginx:.....
    ...Error starting userland proxy: Bind for 0.0.0.0:80: unexpected error (Failure EADDRINUSE)
    ERROR: Encountered errors while bringing up the project.

You can check what's running on that port by using (sudo is required if
you're looking at port < 1024)::

    sudo lsof -i :80

We specify the ports ``nginx`` listens on in the ``docker-compose.override.yml``
file. If you wish to override the ports you can do so by creating a new ``docker-compose``
config and starting the containers using that config alongside the default config.

For example if you create a file called ``docker-compose-ports.yml``::

    nginx:
      ports:
        - 8880:80

Next you would stop and start the containers with the following::

    docker-compose stop # only needed if running
    docker-compose -f docker-compose.yml -f docker-compose-ports.yml up -d

Now the container ``nginx`` is listening on 8880 on the host. You can now proxy
to the container ``nginx`` from the host ``nginx`` with the following ``nginx`` config::

    server {
        listen       80;
        server_name  olympia.dev;
        location / {
            proxy_pass   http://olympia.dev:8880;
        }
    }

Persisting changes
------------------

Please note: any command that would result in files added or modified
outside of the ``addons-server`` folder (e.g. modifying pip or npm
dependencies) won't persist, and thus won't survive after the
running container exits.

.. note::
    If you need to persist any changes to the image, they should be carried out
    via the ``Dockerfile``. Commits to master will result in the Dockerfile
    being rebuilt on the Docker hub.

Restarting docker-machine vms following a reboot
------------------------------------------------

If you quit docker-machine, or restart your computer, docker-machine will need
to start again using::

    docker-machine start addons-dev

You'll then need to :ref:`export the variables <creating-the-docker-vm>` again,
and start the services::

    docker-compose up -d

Hacking on the Docker image
~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you want to test out changes to the Olympia Docker image locally, use the
normal `Docker commands <https://docs.docker.com/reference/commandline/cli/>`_
such as this to build a new image::

    cd addons-server
    docker build -t addons/addons-server .
    docker-compose up -d

After you test your new image, commit to master and the image will be published
to Docker Hub for other developers to use after they pull image changes.

.. _Docker: https://docs.docker.com/installation/#installation
.. _docker-toolbox: https://www.docker.com/toolbox
.. _docker-for-windows: https://docs.docker.com/engine/installation/windows/#/docker-for-windows
.. _docker-for-mac: https://docs.docker.com/engine/installation/mac/#/docker-for-mac


text:
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex;
using MathNet.Numerics.LinearAlgebra.Complex.Solvers;
using MathNet.Numerics.LinearAlgebra.Solvers;
using NUnit.Framework;

namespace MathNet.Numerics.Tests.LinearAlgebraTests.Complex.Solvers.Preconditioners
{
    using Complex = System.Numerics.Complex;

    /// <summary>
    /// Diagonal preconditioner test.
    /// </summary>
    [TestFixture, Category("LASolver")]
    public sealed class DiagonalTest : PreconditionerTest
    {
        /// <summary>
        /// Create preconditioner.
        /// </summary>
        /// <returns>New preconditioner instance.</returns>
        internal override IPreconditioner<Complex> CreatePreconditioner()
        {
            return new DiagonalPreconditioner();
        }

        /// <summary>
        /// Check the result.
        /// </summary>
        /// <param name="preconditioner">Specific preconditioner.</param>
        /// <param name="matrix">Source matrix.</param>
        /// <param name="vector">Initial vector.</param>
        /// <param name="result">Result vector.</param>
        protected override void CheckResult(IPreconditioner<Complex> preconditioner, SparseMatrix matrix, Vector<Complex> vector, Vector<Complex> result)
        {
            Assert.AreEqual(typeof (DiagonalPreconditioner), preconditioner.GetType(), "#01");

            // Compute M * result = product
            // compare vector and product. Should be equal
            var product = new DenseVector(result.Count);
            matrix.Multiply(result, product);

            for (var i = 0; i < product.Count; i++)
            {
                Assert.IsTrue(vector[i].Real.AlmostEqualNumbersBetween(product[i].Real, -Epsilon.Magnitude()), "#02-" + i);
                Assert.IsTrue(vector[i].Imaginary.AlmostEqualNumbersBetween(product[i].Imaginary, -Epsilon.Magnitude()), "#03-" + i);
            }
        }
    }
}


text:
node_count=4
start_peer_port=6331
start_public_port=8000
path_to_app=/root/.cargo/bin/exonum-timestamping

cd backend && mkdir example && cd example
${path_to_app} generate-template common.toml --validators-count ${node_count}

for i in $(seq 0 $((node_count - 1)))
do
  peer_port=$((start_peer_port + i))
  ${path_to_app} generate-config common.toml $((i + 1)) --peer-address 127.0.0.1:${peer_port} -n
done

for i in $(seq 0 $((node_count - 1)))
do
  public_port=$((start_public_port + i))
  private_port=$((public_port + node_count))
  ${path_to_app} finalize --public-api-address 0.0.0.0:${public_port} --private-api-address 0.0.0.0:${private_port} $((i + 1))/sec.toml $((i + 1))/node.toml --public-configs {1,2,3,4}/pub.toml
done

for i in $(seq 0 $((node_count - 1)))
do
  public_port=$((start_public_port + i))
  private_port=$((public_port + node_count))
  ${path_to_app} run --node-config $((i + 1))/node.toml --db-path $((i + 1))/db --public-api-address 0.0.0.0:${public_port} --master-key-pass pass  &
  echo "new node with ports: $public_port (public) and $private_port (private)"
  sleep 1
done

echo "Deployment of the timestamping service is in progress..."
sleep 10
python3 -m exonum_launcher -i ../../timestamping.yaml

cd ../../frontend
npm start -- --port=$((start_public_port + 2 * node_count)) --api-root=http://127.0.0.1:${start_public_port}


text:
<?php

/*
Register the custom post type
=============================
E.g. here I have called them 'Resources'.

To change this, do a search-and-replace for:
	"Resource" (singular)
	"Resources" (plural)
	"resource" (singular)
And replace with "your-type" -- as above: uppercase singular, uppercase plural, lowercase singular.

Be sure to rename the TEMPLATE too -- single-resource.php => single-your-type.php
*/

function create_resource_post_type() {
    $args = array(
        'description' => 'Resources Post Type',
        'show_ui' => true, // So it appears in the WordPress admin sidebar.
        'menu_position' => 20,
        // This menu_position is just below 'Pages' in the WordPress Admin sidebar.
        // If you have multiple Custom Post Types, then position them how you like.
        'exclude_from_search' => true,
        'menu_icon' => 'dashicons-book-alt',
        // Or choose another dashicon, http://www.kevinleary.net/wordpress-dashicons-list-custom-post-type-icons/
        'labels' => array(
            'name'=> 'Resources',
            'singular_name' => 'Resource',
            'add_new' => 'Add New Resource',
            'add_new_item' => 'Add New Resource',
            'edit' => 'Edit Resources',
            'edit_item' => 'Edit Resource',
            'new-item' => 'New Resource',
            'view' => 'View Resources',
            'view_item' => 'View Resource',
            'search_items' => 'Search Resources',
            'not_found' => 'No Resources Found',
            'not_found_in_trash' => 'No Resources Found in Trash',
            'parent' => 'Parent Resource'
        ),
        'public' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'rewrite' => true,
        'supports' => array(
            'title',
            'editor',
            'excerpt',
            'trackbacks',
            'custom-fields',
            'comments',
            'revisions',
            'thumbnail',
            'author',
            'page-attributes',)
        // Delete [, comments] above if not appropriate.
    );
    register_post_type( 'resource' , $args );
}

add_action( 'init', 'create_resource_post_type' );

/*
NOTES on registering a custom post type
=======================================
You can now create these 'posts' in the normal way: Start a New Resource, e.g. compose a Resources 'post' and hit PUBLISH. Job done.

NOTE: WordPress throws a 404 error on NEW custom post types, because the CMS can't discover them for some reason. So you will need to go into PERMALINKS and change the settings to "Post name" /%postname%/ and hit SAVE. (Even if you have this setting already, please hit SAVE again.) This will flush the rewrite rules so WordPress rebuilds its permalinks (Just remember to do this every time you write code like this to register *another* Custom Post Type.)
*/

/*
Register the custom post taxonomy
=================================
E.g. Building upon the same example ('Resources') as above.
You need STEP TWO (the code below) so that you can have a hierarchy of sub-pages, e.g.
    • Resources
        - Free Resources
        - Cheap Resources
        – Expensive Resources
*/

function register_resource_taxonomy() {
    register_taxonomy('resource_category', 'resource', array (
        'labels' => array (
            'name' => 'Resource Categories',
            'singular_name' => 'Resource Category',
            'search_items' => 'Search Resource Categories',
            'popular_items' => 'Popular Resource Categories',
            'all_items' => 'All Resource Categories',
            'parent_item' => 'Parent Resource Category',
            'parent_item_colon' => 'Parent Resource Category:',
            'edit_item' => 'Edit Resource Category',
            'update_item' => 'Update Resource Category',
            'add_new_item' => 'Add New Resource Category',
            'new_item_name' => 'New Resource Category',
            ),
            'hierarchical' =>true,
            'show_ui' => true,
            'show_tagcloud' => true,
            'rewrite' => false,
            'public'=>true
        )
    );
}

add_action('init', 'register_resource_taxonomy');

/*
NOTES on registering the custom post taxonomy
=============================================
So, now you will see a form in the Resource Editor's Right Column, containing an option to "+ Add New Resource Category". You can do this, calling it (e.g.) Health Resources. Next, create some more Resource 'posts' and you can use that same form to [] check them into your Resource Categories.

And you will notice that you can ORGANIZE (and reorganise) your Resource categories into a hierarchical tree, easily.
*/

/*
Displaying, managing, editing and filtering your custom post types
==================================================================
*/

function resource_edit_columns($columns){
    $columns = array(
        "cb" => "<input type='checkbox' />",
        "photo" => __("Image"),
        "title" => __("Resource"),
        "resource_category" => __("Resource Category"),
        "date" => __("Date")
    );
    return $columns;
}
add_filter("manage_edit-resource_columns", "resource_edit_columns");

function resource_custom_columns($column){
    global $post;
    switch ($column){
        case "photo": if(has_post_thumbnail()) the_post_thumbnail(array(50,50));
        break;
        case "resource_category": echo get_the_term_list($post->ID, 'resource_category', '', ', ','');
        break;
    }
}
add_action("manage_resource_posts_custom_column",  "resource_custom_columns");

if ( isset($_GET['post_type']) ) {
    $post_type = $_GET['post_type'];
} else {
    $post_type = '';
}

if ( $post_type == 'resource' ) {
    add_action( 'restrict_manage_posts','resource_filter_list' );
    add_filter( 'parse_query','perform_filtering' );
}

function resource_filter_list() {
    global $typenow, $wp_query;
    if ($typenow == 'resource') {
        wp_dropdown_categories(array(
            'show_option_all' => 'Show All Resource Categories',
            'taxonomy' => 'resource_category',
            'name' => 'resource_category',
            'orderby' => 'name',
            'selected' =>( isset( $wp_query->query['resource_category'] ) ? $wp_query->query['resource_category'] : '' ),
            'hierarchical' => false,
            'depth' => 3,
            'show_count' => false,
            'hide_empty' => true,
        ));
    }
}

function perform_filtering( $query ){
    $qv = &$query->query_vars;
    if (( $qv['resource_category'] ) && is_numeric( $qv['resource_category'] ) ) {
        $term = get_term_by( 'id', $qv['resource_category'], 'resource_category' );
        $qv['resource_category'] = $term->slug;
    }
}

/*
NOTES on displaying, managing, editing and filtering your custom post types
===========================================================================
All of the above is required to properly 'wire in' your custom post type, so that when you have lots of these 'pages' and categories, you can go to their Listing and do 'quick edits' on them there, renaming, reorganizing, renaming slugs, changing their publication date, changing their status [Published, Pending Review, Draft], etc.
*/


text:
namespace Telefonbuch.Areas.HelpPage.ModelDescriptions
{
    public class DictionaryModelDescription : KeyValuePairModelDescription
    {
    }
}


text:
import { Dispatch } from 'redux';
import {
    Action,
    ActionMeta,
    ActionFunction0,
    ActionFunction1,
    ActionFunction2,
    ActionFunction3,
    ActionFunction4,
    ActionFunctionAny,
} from 'redux-actions';
import { FormSubmitHandler } from 'redux-form';

export function routinePromiseWatcherSaga(): IterableIterator<any>;

export type RoutineStages = 'TRIGGER' | 'REQUEST' | 'SUCCESS' | 'FAILURE' | 'FULFILL';

export type ActionCreatorFunction<Payload = any, Meta = any> = ActionFunctionAny<
    Action<Payload> | ActionMeta<Payload, Meta>
>;

export type Routine<
    TTriggerActionCreator = ActionCreatorFunction,
    TRequestActionCreator = ActionCreatorFunction,
    TSuccessActionCreator = ActionCreatorFunction,
    TFailureActionCreator = ActionCreatorFunction,
    TFulfillActionCreator = ActionCreatorFunction
> = TTriggerActionCreator &
    {
        [key in RoutineStages]: string;
    } & {
        trigger: TTriggerActionCreator;
        request: TRequestActionCreator;
        success: TSuccessActionCreator;
        failure: TFailureActionCreator;
        fulfill: TFulfillActionCreator;
    };

export type UnifiedRoutine<TActionCreator = ActionCreatorFunction> = Routine<
    TActionCreator,
    TActionCreator,
    TActionCreator,
    TActionCreator,
    TActionCreator
>;

export type ResolveFunctionReturnType<TFunction> = TFunction extends (...args: any[]) => infer TReturn
    ? TReturn
    : undefined;

export type ResolveFunctionArg1Type<TFunction> = TFunction extends (arg1: infer TArg1, ...args: any[]) => any
    ? TArg1
    : undefined;

export type ResolveFunctionArg2Type<TFunction> = TFunction extends (arg1: any, arg2: infer TArg1, ...args: any[]) => any
    ? TArg1
    : undefined;

export type ResolveFunctionArg3Type<TFunction> = TFunction extends (
    arg1: any,
    arg2: any,
    arg3: infer TArg1,
    ...args: any[]
) => any
    ? TArg1
    : undefined;

export type ResolveFunctionArg4Type<TFunction> = TFunction extends (
    arg1: any,
    arg2: any,
    arg3: any,
    arg4: infer TArg1,
    ...args: any[]
) => any
    ? TArg1
    : undefined;

export type ResolveActionCreatorByPayload<
    TPayloadCreator,
    TPayload = ResolveFunctionReturnType<TPayloadCreator>,
    TArg1 = ResolveFunctionArg1Type<TPayloadCreator>,
    TArg2 = ResolveFunctionArg2Type<TPayloadCreator>,
    TArg3 = ResolveFunctionArg3Type<TPayloadCreator>,
    TArg4 = ResolveFunctionArg4Type<TPayloadCreator>
> = TPayloadCreator extends ActionFunction0<TPayload>
    ? ActionFunction0<Action<TPayload>>
    : TPayloadCreator extends ActionFunction1<TArg1, TPayload>
    ? ActionFunction1<TArg1, Action<TPayload>>
    : TPayloadCreator extends ActionFunction2<TArg1, TArg2, TPayload>
    ? ActionFunction2<TArg1, TArg2, Action<TPayload>>
    : TPayloadCreator extends ActionFunction3<TArg1, TArg2, TArg3, TPayload>
    ? ActionFunction3<TArg1, TArg2, TArg3, Action<TPayload>>
    : TPayloadCreator extends ActionFunction4<TArg1, TArg2, TArg3, TArg4, TPayload>
    ? ActionFunction4<TArg1, TArg2, TArg3, TArg4, Action<TPayload>>
    : ActionFunctionAny<Action<TPayload>>;

export type ResolveActionCreatorByMeta<
    TMetaCreator,
    TMeta = ResolveFunctionReturnType<TMetaCreator>,
    TArg1 = ResolveFunctionArg1Type<TMetaCreator>,
    TArg2 = ResolveFunctionArg2Type<TMetaCreator>,
    TArg3 = ResolveFunctionArg3Type<TMetaCreator>,
    TArg4 = ResolveFunctionArg4Type<TMetaCreator>
> = TMetaCreator extends ActionFunction0<TMeta>
    ? ActionFunction0<ActionMeta<any, TMeta>>
    : TMetaCreator extends ActionFunction1<TArg1, TMeta>
    ? ActionFunction1<TArg1, ActionMeta<any, TMeta>>
    : TMetaCreator extends ActionFunction2<TArg1, TArg2, TMeta>
    ? ActionFunction2<TArg1, TArg2, ActionMeta<any, TMeta>>
    : TMetaCreator extends ActionFunction3<TArg1, TArg2, TArg3, TMeta>
    ? ActionFunction3<TArg1, TArg2, TArg3, ActionMeta<any, TMeta>>
    : TMetaCreator extends ActionFunction4<TArg1, TArg2, TArg3, TArg4, TMeta>
    ? ActionFunction4<TArg1, TArg2, TArg3, TArg4, ActionMeta<any, TMeta>>
    : ActionFunctionAny<ActionMeta<any, TMeta>>;

export type ResolveActionCreatorByPayloadMeta<
    TPayloadCreator,
    TMetaCreator,
    TPayload = ResolveFunctionReturnType<TPayloadCreator>,
    TMeta = ResolveFunctionReturnType<TMetaCreator>,
    TArg1 = ResolveFunctionArg1Type<TPayloadCreator>,
    TArg2 = ResolveFunctionArg2Type<TPayloadCreator>,
    TArg3 = ResolveFunctionArg3Type<TPayloadCreator>,
    TArg4 = ResolveFunctionArg4Type<TPayloadCreator>
> = TMetaCreator extends ActionFunction0<TMeta>
    ? ActionFunction0<ActionMeta<TPayload, TMeta>>
    : TMetaCreator extends ActionFunction1<TArg1, TMeta>
    ? ActionFunction1<TArg1, ActionMeta<TPayload, TMeta>>
    : TMetaCreator extends ActionFunction2<TArg1, TArg2, TMeta>
    ? ActionFunction2<TArg1, TArg2, ActionMeta<TPayload, TMeta>>
    : TMetaCreator extends ActionFunction3<TArg1, TArg2, TArg3, TMeta>
    ? ActionFunction3<TArg1, TArg2, TArg3, ActionMeta<TPayload, TMeta>>
    : TMetaCreator extends ActionFunction4<TArg1, TArg2, TArg3, TArg4, TMeta>
    ? ActionFunction4<TArg1, TArg2, TArg3, TArg4, ActionMeta<TPayload, TMeta>>
    : ActionFunctionAny<ActionMeta<TPayload, TMeta>>;

export type ResolvePayloadByActionCreator<TActionCreator> = TActionCreator extends (
    ...args: any[]
) => Action<infer TPayload>
    ? TPayload
    : undefined;

export interface ReduxFormPayload<TFormData = {}, TProps = {}> {
    values: TFormData;
    props: TProps;
}

export function bindRoutineToReduxForm<TFormData = {}, TProps = {}>(
    routine:
        | Routine<ActionFunction1<ReduxFormPayload<TFormData, TProps>, Action<ReduxFormPayload<TFormData, TProps>>>>
        | Routine<
              ActionFunction1<ReduxFormPayload<TFormData, TProps>, ActionMeta<ReduxFormPayload<TFormData, TProps>, any>>
          >,
    noSuccessPayload?: boolean,
): FormSubmitHandler<TFormData, TProps>;

export type PayloadTypeOrUndefinable<TPayload> = { _: {} } extends { _: TPayload } ? {} | undefined : TPayload;

export type PromiseCreator<TPayload = {}> = (
    payload: PayloadTypeOrUndefinable<TPayload>,
    dispatch: Dispatch,
) => PromiseLike<any>;

export function promisifyRoutine<
    TTriggerActionCreator = ActionCreatorFunction,
    TRequestActionCreator = ActionCreatorFunction,
    TSuccessActionCreator = ActionCreatorFunction,
    TFailureActionCreator = ActionCreatorFunction,
    TFulfillActionCreator = ActionCreatorFunction
>(
    routine: Routine<
        TTriggerActionCreator,
        TRequestActionCreator, // tslint:disable-line: no-unnecessary-generics
        TSuccessActionCreator, // tslint:disable-line: no-unnecessary-generics
        TFailureActionCreator, // tslint:disable-line: no-unnecessary-generics
        TFulfillActionCreator // tslint:disable-line: no-unnecessary-generics
    >,
): PromiseCreator<ResolvePayloadByActionCreator<TTriggerActionCreator>>;

export type BoundPromiseCreator<TPayload = {}> = { _: {} } extends { _: TPayload }
    ? (payload?: TPayload) => PromiseLike<any>
    : (payload: TPayload) => PromiseLike<any>;

export function bindPromiseCreators<TPayload>(
    promiseCreator: PromiseCreator<TPayload>,
    dispatch: Dispatch,
): BoundPromiseCreator<TPayload>;

export function bindPromiseCreators(
    promiseCreators: { [key: string]: PromiseCreator },
    dispatch: Dispatch,
): { [key: string]: BoundPromiseCreator };

export function bindPromiseCreators(
    promiseCreators: { [key: number]: PromiseCreator },
    dispatch: Dispatch,
): { [key: number]: BoundPromiseCreator };

export const ROUTINE_PROMISE_ACTION: string;

// NOTE: Default payloadCreator is identity (x => x)
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<Payload = any>(
    typePrefix: string,
): UnifiedRoutine<(payload?: Payload) => Action<Payload | undefined>>;

// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<Payload>(
    typePrefix: string,
    payloadCreator: ActionFunction0<Payload>,
): UnifiedRoutine<ActionFunction0<Action<Payload>>>;

// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<Payload, Arg1>(
    typePrefix: string,
    payloadCreator: ActionFunction1<Arg1, Payload>,
): UnifiedRoutine<ActionFunction1<Arg1, Action<Payload>>>;

// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<Payload, Arg1, Arg2>(
    typePrefix: string,
    payloadCreator: ActionFunction2<Arg1, Arg2, Payload>,
): UnifiedRoutine<ActionFunction2<Arg1, Arg2, Action<Payload>>>;

// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<Payload, Arg1, Arg2, Arg3>(
    typePrefix: string,
    payloadCreator: ActionFunction3<Arg1, Arg2, Arg3, Payload>,
): UnifiedRoutine<ActionFunction3<Arg1, Arg2, Arg3, Action<Payload>>>;

// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<Payload, Arg1, Arg2, Arg3, Arg4>(
    typePrefix: string,
    payloadCreator: ActionFunction4<Arg1, Arg2, Arg3, Arg4, Payload>,
): UnifiedRoutine<ActionFunction4<Arg1, Arg2, Arg3, Arg4, Action<Payload>>>;

// NOTE: Default payloadCreator is identity (x => x)
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<Meta>(
    typePrefix: string,
    payloadCreator: null | undefined,
    metaCreator: ActionFunctionAny<Meta>,
): UnifiedRoutine<(payload?: any) => ActionMeta<any, Meta>>;

// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<Payload, Meta>(
    typePrefix: string,
    payloadCreator: ActionFunctionAny<Payload>,
    metaCreator: ActionFunctionAny<Meta>,
): UnifiedRoutine<ActionFunctionAny<ActionMeta<Payload, Meta>>>;

// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<Payload, Meta, Arg1>(
    typePrefix: string,
    payloadCreator: ActionFunction1<Arg1, Payload>,
    metaCreator: ActionFunction1<Arg1, Meta>,
): UnifiedRoutine<ActionFunction1<Arg1, ActionMeta<Payload, Meta>>>;

// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<Payload, Meta, Arg1, Arg2>(
    typePrefix: string,
    payloadCreator: ActionFunction2<Arg1, Arg2, Payload>,
    metaCreator: ActionFunction2<Arg1, Arg2, Meta>,
): UnifiedRoutine<ActionFunction2<Arg1, Arg2, ActionMeta<Payload, Meta>>>;

// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<Payload, Meta, Arg1, Arg2, Arg3>(
    typePrefix: string,
    payloadCreator: ActionFunction3<Arg1, Arg2, Arg3, Payload>,
    metaCreator: ActionFunction3<Arg1, Arg2, Arg3, Meta>,
): UnifiedRoutine<ActionFunction3<Arg1, Arg2, Arg3, ActionMeta<Payload, Meta>>>;

// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<Payload, Meta, Arg1, Arg2, Arg3, Arg4>(
    typePrefix: string,
    payloadCreator: ActionFunction4<Arg1, Arg2, Arg3, Arg4, Payload>,
    metaCreator: ActionFunction4<Arg1, Arg2, Arg3, Arg4, Meta>,
): UnifiedRoutine<ActionFunction4<Arg1, Arg2, Arg3, Arg4, ActionMeta<Payload, Meta>>>;

export function createRoutine<
    TTriggerPayloadCreator,
    TRequestPayloadCreator,
    TSuccessPayloadCreator,
    TFailurePayloadCreator,
    TFulfillPayloadCreator
>(
    typePrefix: string,
    payloadCreator: {
        TRIGGER?: TTriggerPayloadCreator;
        trigger?: TTriggerPayloadCreator;
        REQUEST?: TRequestPayloadCreator;
        request?: TRequestPayloadCreator;
        SUCCESS?: TSuccessPayloadCreator;
        success?: TSuccessPayloadCreator;
        FAILURE?: TFailurePayloadCreator;
        failure?: TFailurePayloadCreator;
        FULFILL?: TFulfillPayloadCreator;
        fulfill?: TFulfillPayloadCreator;
    },
): Routine<
    ResolveActionCreatorByPayload<TTriggerPayloadCreator>,
    ResolveActionCreatorByPayload<TRequestPayloadCreator>,
    ResolveActionCreatorByPayload<TSuccessPayloadCreator>,
    ResolveActionCreatorByPayload<TFailurePayloadCreator>,
    ResolveActionCreatorByPayload<TFulfillPayloadCreator>
>;

export function createRoutine<
    TTriggerMetaCreator,
    TRequestMetaCreator,
    TSuccessMetaCreator,
    TFailureMetaCreator,
    TFulfillMetaCreator
>(
    typePrefix: string,
    payloadCreator: null | undefined,
    metaCreator: {
        TRIGGER?: TTriggerMetaCreator;
        trigger?: TTriggerMetaCreator;
        REQUEST?: TRequestMetaCreator;
        request?: TRequestMetaCreator;
        SUCCESS?: TSuccessMetaCreator;
        success?: TSuccessMetaCreator;
        FAILURE?: TFailureMetaCreator;
        failure?: TFailureMetaCreator;
        FULFILL?: TFulfillMetaCreator;
        fulfill?: TFulfillMetaCreator;
    },
): Routine<
    ResolveActionCreatorByMeta<TTriggerMetaCreator>,
    ResolveActionCreatorByMeta<TRequestMetaCreator>,
    ResolveActionCreatorByMeta<TSuccessMetaCreator>,
    ResolveActionCreatorByMeta<TFailureMetaCreator>,
    ResolveActionCreatorByMeta<TFulfillMetaCreator>
>;

export function createRoutine<
    TTriggerPayloadCreator,
    TRequestPayloadCreator,
    TSuccessPayloadCreator,
    TFailurePayloadCreator,
    TFulfillPayloadCreator,
    TTriggerMetaCreator,
    TRequestMetaCreator,
    TSuccessMetaCreator,
    TFailureMetaCreator,
    TFulfillMetaCreator
>(
    typePrefix: string,
    payloadCreator: {
        TRIGGER?: TTriggerPayloadCreator;
        trigger?: TTriggerPayloadCreator;
        REQUEST?: TRequestPayloadCreator;
        request?: TRequestPayloadCreator;
        SUCCESS?: TSuccessPayloadCreator;
        success?: TSuccessPayloadCreator;
        FAILURE?: TFailurePayloadCreator;
        failure?: TFailurePayloadCreator;
        FULFILL?: TFulfillPayloadCreator;
        fulfill?: TFulfillPayloadCreator;
    },
    metaCreator: {
        TRIGGER?: TTriggerMetaCreator;
        trigger?: TTriggerMetaCreator;
        REQUEST?: TRequestMetaCreator;
        request?: TRequestMetaCreator;
        SUCCESS?: TSuccessMetaCreator;
        success?: TSuccessMetaCreator;
        FAILURE?: TFailureMetaCreator;
        failure?: TFailureMetaCreator;
        FULFILL?: TFulfillMetaCreator;
        fulfill?: TFulfillMetaCreator;
    },
): Routine<
    ResolveActionCreatorByPayloadMeta<TTriggerPayloadCreator, TTriggerMetaCreator>,
    ResolveActionCreatorByPayloadMeta<TRequestPayloadCreator, TRequestMetaCreator>,
    ResolveActionCreatorByPayloadMeta<TSuccessPayloadCreator, TSuccessMetaCreator>,
    ResolveActionCreatorByPayloadMeta<TFailurePayloadCreator, TFailureMetaCreator>,
    ResolveActionCreatorByPayloadMeta<TFulfillPayloadCreator, TFulfillMetaCreator>
>;


text:
package org.cadixdev.lorenz.util;

/**
 * Interface for describing an object that can be reversed.
 *
 * @param <T> The type of the reversible object
 * @param <P> The type of the parent object
 *
 * @author Jamie Mansfield
 * @since 0.5.0
 */
public interface Reversible<T, P> {

    /**
     * Produces a new object that is a reverse copy of the original.
     *
     * @param parent The parent object
     * @return The reversed object
     */
    T reverse(final P parent);

}