text:
for iOS and Android, by [Eddy Verbruggen](http://www.x-services.nl)

1. [Description](https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin#1-description)
2. [Installation](https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin#2-installation)
	2. [Automatically (CLI / Plugman)](https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin#automatically-cli--plugman)
	2. [Manually](https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin#manually)
	2. [PhoneGap Build](https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin#phonegap-build)
3. [Usage](https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin#3-usage)
4. [Credits](https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin#4-credits)
5. [License](https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin#5-license)

## 1. Description

This plugin allows you to add events to the Calendar of the mobile device.

* Works with PhoneGap >= 3.0.
* For PhoneGap 2.x, see [the pre-3.0 branch](https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin/tree/pre-3.0).
* Compatible with [Cordova Plugman](https://github.com/apache/cordova-plugman).
* [Officially supported by PhoneGap Build](https://build.phonegap.com/plugins).

### iOS specifics
* Supported methods: `find`, `create`, `modify`, `delete`, ..
* All methods work without showing the native calendar. Your app never looses control.
* Tested on iOS 6 and 7.

### Android specifics
* Supported methods on Android 4: `find`, `create` (silent and interactive), `delete`, ..
* Supported methods on Android 2 and 3: `create` interactive only: the user is presented a prefilled Calendar event. Pressing the hardware back button will give control back to your app.

## 2. Installation

### Automatically (CLI / Plugman)
Calendar is compatible with [Cordova Plugman](https://github.com/apache/cordova-plugman) and ready for the [PhoneGap 3.0 CLI](http://docs.phonegap.com/en/3.0.0/guide_cli_index.md.html#The%20Command-line%20Interface_add_features), here's how it works with the CLI:

```
$ phonegap local plugin add https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin.git
```
or
```
$ cordova plugin add https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin.git
```
and run this command afterwards:
```
$ cordova build
```

### Manually

#### iOS

1\. Add the following xml to your `config.xml`:
```xml
<!-- for iOS -->
<feature name="Calendar">
	<param name="ios-package" value="Calendar" />
</feature>
```

2\. Grab a copy of Calendar.js, add it to your project and reference it in `index.html`:
```html
<script type="text/javascript" src="js/Calendar.js"></script>
```

3\. Download the source files for iOS and copy them to your project.

Copy `Calendar.h` and `Calendar.m` to `platforms/ios/<ProjectName>/Plugins`

4\. Click your project in XCode, Build Phases, Link Binary With Libraries, search for and add `EventKit.framework` and `EventKitUI.framework`.

#### Android

1\. Add the following xml to your `config.xml`:
```xml
<!-- for Android -->
<feature name="Calendar">
  <param name="android-package" value="nl.xservices.plugins.Calendar" />
</feature>
```

2\. Grab a copy of Calendar.js, add it to your project and reference it in `index.html`:
```html
<script type="text/javascript" src="js/Calendar.js"></script>
```

3\. Download the source files for Android and copy them to your project.

Android: Copy `Calendar.java` to `platforms/android/src/nl/xservices/plugins` (create the folders/packages).
Then create a package called `accessor` and copy other 3 java Classes into it.

4\. Add these permissions to your AndroidManifest.xml:
```xml
<uses-permission android:name="android.permission.READ_CALENDAR"/>
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
```

Note that if you don't want your app to ask for these permissions, you can leave them out, but you'll only be able to
use one function of this plugin: `createEventInteractively`.

### PhoneGap Build

Add the following xml to your `config.xml` to always use the latest version of this plugin:
```xml
<gap:plugin name="nl.x-services.plugins.calendar" />
```
or to use this exact version:
```xml
<gap:plugin name="nl.x-services.plugins.calendar" version="4.2" />
```

## 3. Usage

Basic operations, you'll want to copy-paste this for testing purposes:

```javascript
  // prep some variables
  var startDate = new Date(2014,2,15,18,30,0,0,0); // beware: month 0 = january, 11 = december
  var endDate = new Date(2014,2,15,19,30,0,0,0);
  var title = "My nice event";
  var location = "Home";
  var notes = "Some notes about this event.";
  var success = function(message) { alert("Success: " + JSON.stringify(message)); };
  var error = function(message) { alert("Error: " + message); };

  // create a calendar (iOS only for now)
  window.plugins.calendar.createCalendar(calendarName,success,error);
  // if you want to create a calendar with a specific color, pass in a JS object like this:
  var createCalOptions = window.plugins.calendar.getCreateCalendarOptions();
  createCalOptions.calendarName = "My Cal Name";
  createCalOptions.calendarColor = "#FF0000"; // an optional hex color (with the # char), default is null, so the OS picks a color
  window.plugins.calendar.createCalendar(createCalOptions,success,error);

  // delete a calendar (iOS only for now)
  window.plugins.calendar.deleteCalendar(calendarName,success,error);

  // create an event silently (on Android < 4 an interactive dialog is shown)
  window.plugins.calendar.createEvent(title,location,notes,startDate,endDate,success,error);

  // create an event silently (on Android < 4 an interactive dialog is shown which doesn't use this options) with options:
  var calOptions = window.plugins.calendar.getCalendarOptions(); // grab the defaults
  calOptions.firstReminderMinutes = 120; // default is 60, pass in null for no reminder (alarm)
  calOptions.secondReminderMinutes = 5;

  // Added these options in version 4.2.4:
  calOptions.recurrence = "monthly"; // supported are: daily, weekly, monthly, yearly
  calOptions.recurrenceEndDate = new Date(2015,6,1,0,0,0,0,0); // leave null to add events into infinity and beyond
  calOptions.calendarName = "MyCreatedCalendar"; // iOS only
  window.plugins.calendar.createEventWithOptions(title,location,notes,startDate,endDate,calOptions,success,error);

  // create an event interactively (only supported on Android)
  window.plugins.calendar.createEventInteractively(title,location,notes,startDate,endDate,success,error);

  // create an event in a named calendar (iOS only for now)
  window.plugins.calendar.createEventInNamedCalendar(title,location,notes,startDate,endDate,calendarName,success,error);

  // find events
  window.plugins.calendar.findEvent(title,location,notes,startDate,endDate,success,error);

  // list all events in a date range (only supported on Android for now)
  window.plugins.calendar.listEventsInRange(startDate,endDate,success,error);

  // list all calendar names - returns this JS Object to the success callback: [{"id":"1", "name":"first"}, ..]
  window.plugins.calendar.listCalendars(success,error);

  // find all events in a named calendar (iOS only for now)
  window.plugins.calendar.findAllEventsInNamedCalendar(calendarName,success,error);

  // change an event (iOS only for now)
  var newTitle = "New title!";
  window.plugins.calendar.modifyEvent(title,location,notes,startDate,endDate,newTitle,location,notes,startDate,endDate,success,error);

  // delete an event (you can pass nulls for irrelevant parameters, note that on Android `notes` is ignored)
  window.plugins.calendar.deleteEvent(newTitle,location,notes,startDate,endDate,success,error);
```

Creating an all day event:

```javascript
  // set the startdate to midnight and set the enddate to midnight the next day
  var startDate = new Date(2014,2,15,0,0,0,0,0);
  var endDate = new Date(2014,2,16,0,0,0,0,0);
```

Creating an event for 3 full days

```javascript
  // set the startdate to midnight and set the enddate to midnight 3 days later
  var startDate = new Date(2014,2,24,0,0,0,0,0);
  var endDate = new Date(2014,2,27,0,0,0,0,0);
```

## 4. CREDITS ##

This plugin was enhanced for Plugman / PhoneGap Build by [Eddy Verbruggen](http://www.x-services.nl). I fixed some issues in the native code (mainly for iOS) and changed the JS-Native functions a little in order to make a universal JS API for both platforms.
* Inspired by [this nice blog of Devgirl](http://devgirl.org/2013/07/17/tutorial-how-to-write-a-phonegap-plugin-for-android/).
* Credits for the original iOS code go to [Felix Montanez](https://github.com/felixactv8/Phonegap-Calendar-Plugin-ios).
* Credits for the original Android code go to [Ten Forward Consulting](https://github.com/tenforwardconsulting/Phonegap-Calendar-Plugin-android) and [twistandshout](https://github.com/twistandshout/phonegap-calendar-plugin).
* Special thanks to [four32c.com](http://four32c.com) for sponsoring part of the implementation, while keeping the plugin opensource.

## 5. License

[The MIT License (MIT)](http://www.opensource.org/licenses/mit-license.html)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
package org.apache.drill.exec.ops;

import java.util.List;

import org.apache.drill.exec.memory.BufferAllocator;
import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import org.apache.drill.exec.proto.UserBitShared.MinorFragmentProfile;

import com.codahale.metrics.MetricRegistry;
import com.google.common.collect.Lists;

public class FragmentStats {
  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FragmentStats.class);

  private List<OperatorStats> operators = Lists.newArrayList();
  private final long startTime;
  private final DrillbitEndpoint endpoint;

  public FragmentStats(MetricRegistry metrics, DrillbitEndpoint endpoint) {
    this.startTime = System.currentTimeMillis();
    this.endpoint = endpoint;
  }

  public void addMetricsToStatus(MinorFragmentProfile.Builder prfB) {
    prfB.setStartTime(startTime);
    prfB.setEndTime(System.currentTimeMillis());
    prfB.setEndpoint(endpoint);
    for(OperatorStats o : operators){
      prfB.addOperatorProfile(o.getProfile());
    }
  }

  public OperatorStats getOperatorStats(OpProfileDef profileDef, BufferAllocator allocator){
    OperatorStats stats = new OperatorStats(profileDef, allocator);
    if(profileDef.operatorType != -1){
      operators.add(stats);
    }
    return stats;
  }

  public void addOperatorStats(OperatorStats stats) {
    operators.add(stats);
  }

}

redpajama_set_name: RedPajamaGithub


text:
[![browser support](https://ci.testling.com/jsantell/mongoose-schema-model.png)](https://ci.testling.com/jsantell/mongoose-schema-model)

[![Build Status](https://travis-ci.org/jsantell/mongoose-schema-model.png)](https://travis-ci.org/jsantell/mongoose-schema-model)

Small model definitions (MongooseDB style) for composable use in other environments.

* Share the same model definitions from MongooseDB on the server with your client
* Use to apply transformations getters/setters between client and REST API (casting form strings as numbers, etc.)
* Shared validations in server/client

## Install

Currently only in npm as commonjs.

`npm install mongoose-schema-model`

## Usage

Using a [Mongoose Schema](http://mongoosejs.com/docs/guide.html) definition, apply getter and setter transformations and validation.

```javascript

// Declare a schema definition

var Model = require("mongoose-schema-model");

function numberCast (x) { return ~~x; }
function split (x) { return x.split(', '); }

var definitions = {
  year: { type: Number, min: 1900, max: 2014, set: numberCast },
  items: { type: [String], lowercase: true, get: split },

};

var model = Model(definitions);

// `get` applies the `get` transformation
model.get("items", ["hello", "world"]); // "hello, world"

// `set` applies all implicit and `set` transformations, as well as subsequently validating
// the model, post-transform.
var response = model.set("items", ["HELLO", "WORLD"]);
response.value; // `["hello", "world"]`, the implicit `lowercase` transform was applied to each element
response.error; // null

response = model.set("year", "2000");
response.value; // `2000`, transforms applied via `set`
response.error ; // null

response = model.set("year", "1550");
response.value; // `2000`, transforms applied, via `set`
response.error; // "Path `year` (1550) is less than the minimum allowed value (1900)."
```

## Supported Types

* `Number`
* `String`
* `[Number]`
* `[String]`

## Supported Properties

### Transforms

* [set](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set)
* [get](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get)
* [uppercase](http://mongoosejs.com/docs/api.html#schema_string_SchemaString-uppercase) (String-types)
* [lowercase](http://mongoosejs.com/docs/api.html#schema_string_SchemaString-lowercase) (String-types)
* [trim](http://mongoosejs.com/docs/api.html#schema_string_SchemaString-trim)

### Validations

* [required](http://mongoosejs.com/docs/api.html#schematype_SchemaType-required)
* [validate](http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate)
* [enum](http://mongoosejs.com/docs/api.html#schema_string_SchemaString-enum) (String-types)
* [match](http://mongoosejs.com/docs/api.html#schema_string_SchemaString-match) (String-types)
* [max](http://mongoosejs.com/docs/api.html#schema_number_SchemaNumber-max) (Number-types)
* [min](http://mongoosejs.com/docs/api.html#schema_number_SchemaNumber-min) (Number-types)

## License

MIT License


text:
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace IO.Swagger.Model
{
    /// <summary>
    ///
    /// </summary>
    [DataContract]
    public partial class ChargeClause :  IEquatable<ChargeClause>
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="ChargeClause" /> class.
        /// Initializes a new instance of the <see cref="ChargeClause" />class.
        /// </summary>
        /// <param name="CreCode">CreCode.</param>
        /// <param name="Description">Description.</param>

        public ChargeClause(string CreCode = null, string Description = null)
        {
            this.CreCode = CreCode;
            this.Description = Description;

        }

        /// <summary>
        /// Gets or Sets CreCode
        /// </summary>
        [DataMember(Name="cre_code", EmitDefaultValue=false)]
        public string CreCode { get; set; }

        /// <summary>
        /// Gets or Sets Description
        /// </summary>
        [DataMember(Name="description", EmitDefaultValue=false)]
        public string Description { get; set; }

        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("class ChargeClause {\n");
            sb.Append("  CreCode: ").Append(CreCode).Append("\n");
            sb.Append("  Description: ").Append(Description).Append("\n");

            sb.Append("}\n");
            return sb.ToString();
        }

        /// <summary>
        /// Returns the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }

        /// <summary>
        /// Returns true if objects are equal
        /// </summary>
        /// <param name="obj">Object to be compared</param>
        /// <returns>Boolean</returns>
        public override bool Equals(object obj)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            return this.Equals(obj as ChargeClause);
        }

        /// <summary>
        /// Returns true if ChargeClause instances are equal
        /// </summary>
        /// <param name="other">Instance of ChargeClause to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(ChargeClause other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return
                (
                    this.CreCode == other.CreCode ||
                    this.CreCode != null &&
                    this.CreCode.Equals(other.CreCode)
                ) &&
                (
                    this.Description == other.Description ||
                    this.Description != null &&
                    this.Description.Equals(other.Description)
                );
        }

        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            // credit: http://stackoverflow.com/a/263416/677735
            unchecked // Overflow is fine, just wrap
            {
                int hash = 41;
                // Suitable nullity checks etc, of course :)

                if (this.CreCode != null)
                    hash = hash * 59 + this.CreCode.GetHashCode();

                if (this.Description != null)
                    hash = hash * 59 + this.Description.GetHashCode();

                return hash;
            }
        }

    }
}


text:
#ifndef GrMtlCommandBuffer_DEFINED
#  define GrMtlCommandBuffer_DEFINED
#  include "include/core/SkRefCnt.h"
#  include "src/gpu/mtl/GrMtlUtil.h"
class GrMtlGpu;
class GrMtlPipelineState;
class GrMtlOpsRenderPass;
class GrMtlCommandBuffer
{
public:
  static GrMtlCommandBuffer* Create(id < MTLCommandQueue > queue);
  ~GrMtlCommandBuffer();
  void commit(bool waitUntilCompleted);
  id<MTLBlitCommandEncoder> getBlitCommandEncoder();
  id<MTLRenderCommandEncoder> getRenderCommandEncoder(MTLRenderPassDescriptor*, const GrMtlPipelineState*, GrMtlOpsRenderPass* opsRenderPass);
  void addCompletedHandler(MTLCommandBufferHandler block)
  {
//        [fCmdBuffer addCompletedHandler:block];
  }
#  ifdef GR_METAL_SDK_SUPPORTS_EVENTS
  void encodeSignalEvent(id<MTLEvent>, uint64_t value);
  void encodeWaitForEvent(id<MTLEvent>, uint64_t value);
#  endif
private:
  GrMtlCommandBuffer(id<MTLCommandBuffer> cmdBuffer)
    : fCmdBuffer(cmdBuffer)
    , fPreviousRenderPassDescriptor(nil)
  {
  }
  void endAllEncoding();
  id<MTLCommandBuffer> fCmdBuffer;
  id<MTLBlitCommandEncoder> fActiveBlitCommandEncoder;
  id<MTLRenderCommandEncoder> fActiveRenderCommandEncoder;
  MTLRenderPassDescriptor* fPreviousRenderPassDescriptor;
};
#endif


text:
// Copyright 2017 The Kubernetes Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import componentsModule from 'common/components/module';

describe('Middle ellipsis controller', () => {
  /** @type {!MiddleEllipsisController} */
  let ctrl;
  let element;
  /** @type {!angular.JQLite} */
  beforeEach(() => {
    angular.mock.module(componentsModule.name);

    angular.mock.inject(($componentController) => {
      element = angular.element(
          '
Hello World!
');
      document.body.appendChild(element[0]);
      ctrl = $componentController('kdMiddleEllipsis', {$element: element});
    });
  });

  it('should initialize controller', () => {
    expect(ctrl).not.toBeNull();
  });

  it('checks if isTruncated logic works', () => {
    expect(ctrl.isTruncated()).toBeTruthy();
  });

  afterEach(() => {
    document.body.removeChild(element[0]);
  });
});


text:
export const environment = {
  production: false,
  hmr: true,
  restEndpointConfig: '/api/config',
  restEndpointMail: '/api/mails',
  restEndpointDomains: '/api/domains'
};


text:
package org.springframework.beans.factory.support;

/**
 * Created by IntelliJ IDEA.
 * User: stevend
 * Date: 23-feb-2006
 * Time: 18:24:26
 * To change this template use File | Settings | File Templates.
 */
public class MatchManager {
    public Match createMatch(Player player1, Player player2, long id) {
        throw new UnsupportedOperationException();
    }
}


text:
package org.cleartk.clearnlp;

import java.util.List;

import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.cas.FSArray;
import org.apache.uima.jcas.tcas.Annotation;
import org.cleartk.syntax.dependency.type.DependencyNode;
import org.cleartk.syntax.dependency.type.DependencyRelation;
import org.cleartk.syntax.dependency.type.TopDependencyNode;
import org.cleartk.token.type.Sentence;
import org.cleartk.token.type.Token;
import org.apache.uima.fit.util.FSCollectionFactory;
import org.apache.uima.fit.util.JCasUtil;

import com.google.common.annotations.Beta;
import com.google.common.collect.Lists;

/**
 * Defines common set of dependency graph data type operations used to convert and query ClearTK dependency types
 * such as {@link TopDependencyNode}, {@link DependencyNode} and {@link DependencyRelation}
 *
 *
 * @author Lee Becker
 *
 */
@Beta
public class CleartkDependencyOps implements DependencyOps<DependencyNode, Token, TopDependencyNode, Sentence, DependencyRelation> {

  @Override
  public TopDependencyNode selectRootNode(JCas jCas, Annotation coveringAnnotation) {
    List<TopDependencyNode> nodes = JCasUtil.selectCovered(jCas, TopDependencyNode.class, coveringAnnotation);
    if (nodes.size() != 1) {
      throw new IllegalArgumentException("Expected 1 root node, found " + nodes.size());
    }
    return nodes.get(0);
  }

  @Override
  public List<DependencyNode> selectNodes(JCas jCas, Annotation coveringAnnotation) {
    List<DependencyNode> result = Lists.newArrayList();
    for (DependencyNode node : JCasUtil.selectCovered(jCas, DependencyNode.class, coveringAnnotation)) {
      if (!(node instanceof TopDependencyNode)) {
        result.add(node);
      }
    }
    return result;
  }

  @Override
  public List<DependencyRelation> getHeadRelations(JCas jCas, DependencyNode node) {
    return Lists.newArrayList(JCasUtil.select(node.getHeadRelations(), DependencyRelation.class));
  }

  @Override
  public DependencyNode getHead(JCas jCas, DependencyRelation relation) {
    return relation.getHead();
  }

  @Override
  public String getLabel(JCas jCas, DependencyRelation relation) {
    return relation.getRelation();
  }

  @Override
  public TopDependencyNode createRootNode(JCas jCas, Sentence sentence) {
    return new TopDependencyNode(jCas, sentence.getBegin(), sentence.getEnd());
  }

  @Override
  public DependencyNode createNode(JCas jCas, Token token) {
    return new DependencyNode(jCas, token.getBegin(), token.getEnd());
  }

  @Override
  public DependencyRelation createRelation(JCas jCas, DependencyNode head, DependencyNode child, String relation) {
    DependencyRelation rel = new DependencyRelation(jCas);
    rel.setChild(child);
    rel.setHead(head);
    rel.setRelation(relation);
    return rel;
  }

  @Override
  public void setHeadRelations(
      JCas jCas,
      DependencyNode node,
      List<DependencyRelation> headRelations) {
    node.setHeadRelations(new FSArray(jCas, headRelations.size()));
    FSCollectionFactory.fillArrayFS(node.getHeadRelations(), headRelations);
  }

  @Override
  public void setChildRelations(
      JCas jCas,
      DependencyNode node,
      List<DependencyRelation> childRelations) {
    node.setChildRelations(new FSArray(jCas, childRelations.size()));
    FSCollectionFactory.fillArrayFS(node.getChildRelations(), childRelations);
  }

}


text:
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import { html, body } from '../CssBaseline/CssBaseline';
export const styles = theme => ({
  /* Styles applied to the root element. */
  root: _extends({}, html, body(theme), {
    '& *, & *::before, & *::after': {
      boxSizing: 'inherit'
    },
    '& strong, & b': {
      fontWeight: theme.typography.fontWeightBold
    }
  })
});
const ScopedCssBaseline = /*#__PURE__*/React.forwardRef(function ScopedCssBaseline(props, ref) {
  const {
    classes,
    className
  } = props,
        other = _objectWithoutPropertiesLoose(props, ["classes", "className"]);

  return /*#__PURE__*/React.createElement("div", _extends({
    className: clsx(classes.root, className),
    ref: ref
  }, other));
});
process.env.NODE_ENV !== "production" ? ScopedCssBaseline.propTypes = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------

  /**
   * The content of the component.
   */
  children: PropTypes.node,

  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,

  /**
   * @ignore
   */
  className: PropTypes.string
} : void 0;
export default withStyles(styles, {
  name: 'MuiScopedCssBaseline'
})(ScopedCssBaseline);


text:
class Postmen
  module Types
    # Address object
    #
    # @see https://docs.postmen.com/api.html#address API Documentation
    class Address < Dry::Struct
      constructor_type :strict_with_defaults

      attribute :country, Types::Country
      attribute :contact_name, Types::String.optional.default(nil)
      attribute :phone, Types::String.optional.default(nil)
      attribute :fax, Types::String.optional.default(nil)
      attribute :email, Types::String.optional.default(nil)
      attribute :company_name, Types::String.optional.default(nil)
      attribute :street1, Types::String.optional.default(nil)
      attribute :street2, Types::String.optional.default(nil)
      attribute :street3, Types::String.optional.default(nil)
      attribute :city, Types::String.optional.default(nil)
      attribute :state, Types::String.optional.default(nil)
      attribute :postal_code, Types::String.optional.default(nil)
      attribute :type, Types::AddressType.optional.default(nil)
      attribute :tax_id, Types::String.optional.default(nil)

      # Converts object to hash
      # @return [Hash]
      def to_hash
        super.reject { |_k, v| v.nil? }
      end
    end
  end
end


text:
package com.cra.figaro.algorithm

/**
 * A lazy algorithm is an algorithm that can be run to increasing depths.
 */
trait LazyAlgorithm extends Algorithm {
  /**
   * The current depth to which the algorithm should be run.
   */
  var depth = 0

  /**
   * Run the algorithm to the given depth.
   */
  def run(depth: Int): Unit

  /**
   * Start the algorithm. This will run the algorithm to one depth.
   */
  def doStart() { pump() }

  /**
   * Increase the depth and run the algorithm again.
   */
  def pump() { depth += 1; run(depth) }

  /**
   * Stop the algorithm.
   */
  def doStop() { }

  /**
   * Resume the algorithm by increasing the depth and running again.
   */
  def doResume() { pump() }

  /**
   * Kill the algorithm.
   */
  def doKill() { depth = -1 }
}


text:
using arrow::Buffer;
using arrow::Status;

namespace plasma {

/// Object buffer data structure.
struct ObjectBuffer {
  /// The data buffer.
  std::shared_ptr<Buffer> data;
  /// The metadata buffer.
  std::shared_ptr<Buffer> metadata;
  /// The device number.
  int device_num;
};

class ARROW_EXPORT PlasmaClient {
 public:
  PlasmaClient();
  ~PlasmaClient();

  /// Connect to the local plasma store. Return the resulting connection.
  ///
  /// \param store_socket_name The name of the UNIX domain socket to use to
  ///        connect to the Plasma store.
  /// \param manager_socket_name The name of the UNIX domain socket to use to
  ///        connect to the local Plasma manager. If this is "", then this
  ///        function will not connect to a manager.
  ///        Note that plasma manager is no longer supported, this function
  ///        will return failure if this is not "".
  /// \param release_delay Deprecated (not used).
  /// \param num_retries number of attempts to connect to IPC socket, default 50
  /// \return The return status.
  Status Connect(const std::string& store_socket_name,
                 const std::string& manager_socket_name = "", int release_delay = 0,
                 int num_retries = -1);

  /// Create an object in the Plasma Store. Any metadata for this object must be
  /// be passed in when the object is created.
  ///
  /// \param object_id The ID to use for the newly created object.
  /// \param data_size The size in bytes of the space to be allocated for this
  /// object's
  ///        data (this does not include space used for metadata).
  /// \param metadata The object's metadata. If there is no metadata, this
  /// pointer
  ///        should be NULL.
  /// \param metadata_size The size in bytes of the metadata. If there is no
  ///        metadata, this should be 0.
  /// \param data The address of the newly created object will be written here.
  /// \param device_num The number of the device where the object is being
  ///        created.
  ///        device_num = 0 corresponds to the host,
  ///        device_num = 1 corresponds to GPU0,
  ///        device_num = 2 corresponds to GPU1, etc.
  /// \return The return status.
  ///
  /// The returned object must be released once it is done with.  It must also
  /// be either sealed or aborted.
  Status Create(const ObjectID& object_id, int64_t data_size, const uint8_t* metadata,
                int64_t metadata_size, std::shared_ptr<Buffer>* data, int device_num = 0);

  /// Create and seal an object in the object store. This is an optimization
  /// which allows small objects to be created quickly with fewer messages to
  /// the store.
  ///
  /// \param object_id The ID of the object to create.
  /// \param data The data for the object to create.
  /// \param metadata The metadata for the object to create.
  /// \return The return status.
  Status CreateAndSeal(const ObjectID& object_id, const std::string& data,
                       const std::string& metadata);

  /// Get some objects from the Plasma Store. This function will block until the
  /// objects have all been created and sealed in the Plasma Store or the
  /// timeout expires.
  ///
  /// If an object was not retrieved, the corresponding metadata and data
  /// fields in the ObjectBuffer structure will evaluate to false.
  /// Objects are automatically released by the client when their buffers
  /// get out of scope.
  ///
  /// \param object_ids The IDs of the objects to get.
  /// \param timeout_ms The amount of time in milliseconds to wait before this
  ///        request times out. If this value is -1, then no timeout is set.
  /// \param[out] object_buffers The object results.
  /// \return The return status.
  Status Get(const std::vector<ObjectID>& object_ids, int64_t timeout_ms,
             std::vector<ObjectBuffer>* object_buffers);

  /// Deprecated variant of Get() that doesn't automatically release buffers
  /// when they get out of scope.
  ///
  /// \param object_ids The IDs of the objects to get.
  /// \param num_objects The number of object IDs to get.
  /// \param timeout_ms The amount of time in milliseconds to wait before this
  ///        request times out. If this value is -1, then no timeout is set.
  /// \param object_buffers An array where the results will be stored.
  /// \return The return status.
  ///
  /// The caller is responsible for releasing any retrieved objects, but it
  /// should not release objects that were not retrieved.
  Status Get(const ObjectID* object_ids, int64_t num_objects, int64_t timeout_ms,
             ObjectBuffer* object_buffers);

  /// Tell Plasma that the client no longer needs the object. This should be
  /// called after Get() or Create() when the client is done with the object.
  /// After this call, the buffer returned by Get() is no longer valid.
  ///
  /// \param object_id The ID of the object that is no longer needed.
  /// \return The return status.
  Status Release(const ObjectID& object_id);

  /// Check if the object store contains a particular object and the object has
  /// been sealed. The result will be stored in has_object.
  ///
  /// @todo: We may want to indicate if the object has been created but not
  /// sealed.
  ///
  /// \param object_id The ID of the object whose presence we are checking.
  /// \param has_object The function will write true at this address if
  ///        the object is present and false if it is not present.
  /// \return The return status.
  Status Contains(const ObjectID& object_id, bool* has_object);

  /// List all the objects in the object store.
  ///
  /// This API is experimental and might change in the future.
  ///
  /// \param[out] objects ObjectTable of objects in the store. For each entry
  ///             in the map, the following fields are available:
  ///             - metadata_size: Size of the object metadata in bytes
  ///             - data_size: Size of the object data in bytes
  ///             - ref_count: Number of clients referencing the object buffer
  ///             - create_time: Unix timestamp of the object creation
  ///             - construct_duration: Object creation time in seconds
  ///             - state: Is the object still being created or already sealed?
  /// \return The return status.
  Status List(ObjectTable* objects);

  /// Abort an unsealed object in the object store. If the abort succeeds, then
  /// it will be as if the object was never created at all. The unsealed object
  /// must have only a single reference (the one that would have been removed by
  /// calling Seal).
  ///
  /// \param object_id The ID of the object to abort.
  /// \return The return status.
  Status Abort(const ObjectID& object_id);

  /// Seal an object in the object store. The object will be immutable after
  /// this
  /// call.
  ///
  /// \param object_id The ID of the object to seal.
  /// \return The return status.
  Status Seal(const ObjectID& object_id);

  /// Delete an object from the object store. This currently assumes that the
  /// object is present, has been sealed and not used by another client. Otherwise,
  /// it is a no operation.
  ///
  /// @todo We may want to allow the deletion of objects that are not present or
  ///       haven't been sealed.
  ///
  /// \param object_id The ID of the object to delete.
  /// \return The return status.
  Status Delete(const ObjectID& object_id);

  /// Delete a list of objects from the object store. This currently assumes that the
  /// object is present, has been sealed and not used by another client. Otherwise,
  /// it is a no operation.
  ///
  /// \param object_ids The list of IDs of the objects to delete.
  /// \return The return status. If all the objects are non-existent, return OK.
  Status Delete(const std::vector<ObjectID>& object_ids);

  /// Delete objects until we have freed up num_bytes bytes or there are no more
  /// released objects that can be deleted.
  ///
  /// \param num_bytes The number of bytes to try to free up.
  /// \param num_bytes_evicted Out parameter for total number of bytes of space
  /// retrieved.
  /// \return The return status.
  Status Evict(int64_t num_bytes, int64_t& num_bytes_evicted);

  /// Compute the hash of an object in the object store.
  ///
  /// \param object_id The ID of the object we want to hash.
  /// \param digest A pointer at which to return the hash digest of the object.
  ///        The pointer must have at least kDigestSize bytes allocated.
  /// \return The return status.
  Status Hash(const ObjectID& object_id, uint8_t* digest);

  /// Subscribe to notifications when objects are sealed in the object store.
  /// Whenever an object is sealed, a message will be written to the client
  /// socket that is returned by this method.
  ///
  /// \param fd Out parameter for the file descriptor the client should use to
  /// read notifications
  ///         from the object store about sealed objects.
  /// \return The return status.
  Status Subscribe(int* fd);

  /// Receive next object notification for this client if Subscribe has been called.
  ///
  /// \param fd The file descriptor we are reading the notification from.
  /// \param object_id Out parameter, the object_id of the object that was sealed.
  /// \param data_size Out parameter, the data size of the object that was sealed.
  /// \param metadata_size Out parameter, the metadata size of the object that was sealed.
  /// \return The return status.
  Status GetNotification(int fd, ObjectID* object_id, int64_t* data_size,
                         int64_t* metadata_size);

  Status DecodeNotification(const uint8_t* buffer, ObjectID* object_id,
                            int64_t* data_size, int64_t* metadata_size);

  /// Disconnect from the local plasma instance, including the local store and
  /// manager.
  ///
  /// \return The return status.
  Status Disconnect();

  /// Get the memory capacity of the store.
  ///
  /// \return Memory capacity of the store in bytes.
  int64_t store_capacity();

 private:
  friend class PlasmaBuffer;
  FRIEND_TEST(TestPlasmaStore, GetTest);
  FRIEND_TEST(TestPlasmaStore, LegacyGetTest);
  FRIEND_TEST(TestPlasmaStore, AbortTest);

  bool IsInUse(const ObjectID& object_id);

  class ARROW_NO_EXPORT Impl;
  std::shared_ptr<Impl> impl_;
};

}  // namespace plasma

#endif  // PLASMA_CLIENT_H


text:
"""
Imports blog posts from a BlogMl file.

Dependends on python-dateutil being installed.
"""
import xml.etree.ElementTree

from django.core.management.base import CommandError
from django.utils import timezone

from mezzanine.blog.management.base import BaseImporterCommand

class Command(BaseImporterCommand):
    """
    Imports blog posts from a BlogMl file.
    See http://www.blogml.com/2006/09/BlogML for more info.
    """

    def add_arguments(self, parser):
        super().add_arguments(parser)
        parser.add_argument(
            "-x",
            "--xmldumpfname",
            dest="xmlfilename",
            help="xml file to import blog from",
        )

    def handle_import(self, options):
        """
        Gets posts from provided xml dump.
        """

        try:
            from dateutil.parser import parse
        except ImportError:
            raise CommandError("dateutil package is required")

        xmlfname = options.get("xmlfilename")
        set_tz = timezone.get_current_timezone()
        # parsing xml tree and populating variables for post addition
        tree = xml.etree.ElementTree.parse(xmlfname)
        # namespace for easier searching
        ns = {"blogml": "http://www.blogml.com/2006/09/BlogML"}
        search_paths = {
            "find_posts": ".blogml:posts/blogml:post",
            "find_comments": ".blogml:comments/blogml:comment",
            "find_categories": "blogml:categories/blogml:category",
            "find_tags": "blogml:tags/blogml:tag",
        }

        def _process_post_element(post_element, blog_categories):
            """
            Converts post BlogML element into post data.
            """
            post_dict = dict()
            post_dict["title"] = post_element.find("blogml:title", namespaces=ns).text
            post_dict["content"] = post_element.find(
                "blogml:content", namespaces=ns
            ).text
            post_dict["post-url"] = post_element.attrib["post-url"]
            post_dict["date-created"] = parse(
                post_element.attrib["date-created"]
            ).replace(tzinfo=set_tz)
            post_category_refs = [
                cat_element.attrib["ref"]
                for cat_element in post_element.findall(
                    search_paths["find_categories"], namespaces=ns
                )
            ]
            post_dict["categories"] = list(
                blog_categories[category_id] for category_id in post_category_refs
            )
            post_dict["tags"] = [
                x.attrib["ref"]
                for x in post_element.findall("blogml:tags/blogml:tag", namespaces=ns)
            ]
            return post_dict

        def _process_comment_element(comment_element):
            """
            Converts comment BlogML element into comment data.
            """
            comment_dict = dict()
            comment_dict["name"] = comment_element.attrib["user-name"]
            comment_dict["email"] = comment_element.attrib["user-email"]
            comment_dict["pub_date"] = parse(
                comment_element.attrib["date-created"]
            ).replace(tzinfo=set_tz)
            comment_dict["website"] = comment_element.attrib["user-url"]
            comment_dict["body"] = comment_element.find(
                "blogml:content", namespaces=ns
            ).text
            return comment_dict

        def _process_categories(root_tree):
            """
            Finds all categories within BlogMl root tree
            """
            cat_elements = root_tree.findall(
                search_paths["find_categories"], namespaces=ns
            )
            cat_ids = tuple(x.attrib["id"] for x in cat_elements)
            cat_title_txt = tuple(
                x.find("blogml:title", namespaces=ns).text for x in cat_elements
            )
            categories_dict = dict(zip(cat_ids, cat_title_txt))
            return categories_dict

        categories_found = _process_categories(tree)
        posts_found = tree.findall(search_paths["find_posts"], namespaces=ns)

        for post in posts_found:
            post_info = _process_post_element(post, categories_found)
            post_entered = self.add_post(
                title=post_info["title"],
                content=post_info["content"],
                old_url=post_info["post-url"],
                pub_date=post_info["date-created"],
                categories=post_info["categories"],
            )
            comments_found = post.findall(search_paths["find_comments"], namespaces=ns)
            for comment in comments_found:
                comment_info = _process_comment_element(comment)
                self.add_comment(
                    post=post_entered,
                    name=comment_info["name"],
                    email=comment_info["email"],
                    pub_date=comment_info["pub_date"],
                    website=comment_info["website"],
                    body=comment_info["body"],
                )


text:
package es.gob.jmulticard;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.Key;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;

/** Funcionalidades criptográficas de utilidad que pueden variar entre
 * JSE/JME/Dalvik.
 * @author Tomás García-Merás */
public abstract class CryptoHelper {

	/** Nombre de curva ekíptica. */
	public enum EcCurve {

		/** BrainpoolP256r1. */
		BRAINPOOL_P256_R1("brainpoolP256R1"); //$NON-NLS-1$

		private final String name;
		private EcCurve(final String n) {
			this.name = n;
		}

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

	/** Algoritmo de huella digital. */
	public enum DigestAlgorithm {

		/** SHA-1. */
		SHA1("SHA1"), //$NON-NLS-1$

		/** SHA-256. */
		SHA256("SHA-256"), //$NON-NLS-1$

		/** SHA-384. */
		SHA384("SHA-384"), //$NON-NLS-1$

		/** SHA-512. */
		SHA512("SHA-512"); //$NON-NLS-1$

		private final String name;
		private DigestAlgorithm(final String n) {
			this.name = n;
		}

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

	private static final int PKCS1_LEN_1024 = 128;
	private static final int PKCS1_LEN_2048 = 256;
	private static final byte PKCS1_BLOCK_TYPE = (byte) 0x01;
	private static final byte PKCS1_FILL = (byte) 0xff;
	private static final byte PKCS1_DELIMIT = (byte) 0x00;

	/** Añade relleno PKCS#1 para operaciones con clave privada.
	 * @param in Datos a los que se quiere añadir relleno PKCS#1.
	 * @param keySize Tamaño de la clave privada que operará posteriormente con estos datos con relleno.
	 * @return Datos con el relleno PKCS#1 añadido.
	 * @throws IOException En caso de error el el tratamiento de datos. */
	public final static byte[] addPkcs1PaddingForPrivateKeyOperation(final byte[] in, final int keySize) throws IOException {
		if (in == null) {
			throw new IllegalArgumentException("Los datos de entrada no pueden ser nulos"); //$NON-NLS-1$
		}
		if (keySize != 1024 && keySize != 2048) {
			throw new IllegalArgumentException("Solo se soportan claves de 1024 o 2048 bits, y se ha indicado " + keySize); //$NON-NLS-1$
		}
		final int len = keySize == 1024 ? PKCS1_LEN_1024 : PKCS1_LEN_2048;
		if (in.length > len - 3) {
			throw new IllegalArgumentException(
				"Los datos son demasiado grandes para el valor de clave indicado: " + in.length + " > " + len + "-3" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
			);
		}
		final ByteArrayOutputStream baos = new ByteArrayOutputStream(len);
		baos.write(PKCS1_DELIMIT);    // Delimitador :   00
		baos.write(PKCS1_BLOCK_TYPE); // Tipo de bloque: 01
		while (baos.size() < len - (1 + in.length)) { // Se rellena hasta dejar sitio justo para un delimitador y los datos
			baos.write(PKCS1_FILL);
		}
		baos.write(PKCS1_DELIMIT);    // Delimitador :   00
		baos.write(in);               // Datos

		return baos.toByteArray();
	}

    /** Realiza una huella digital de los datos proporcionados.
     * @param algorithm Algoritmo de huella digital que debe utilizarse.
     * @param data Datos de entrada.
     * @return Huella digital de los datos.
     * @throws IOException Si ocurre algún problema generando la huella
     *         digital. */
    public abstract byte[] digest(final DigestAlgorithm algorithm, final byte[] data) throws IOException;

    /** Encripta datos mediante Triple DES (modo CBC sin relleno) y con un
     * salto de (IV) de 8 bytes a cero. Si se le indica una clave de 24 bytes,
     * la utilizaráa tal cual. Si se le indica una clave de 16 bytes,
     * duplicará los 8 primeros y los agregará al final para
     * obtener una de 24.
     * @param data Datos a encriptar.
     * @param key Clave 3DES de cifrado.
     * @return Datos cifrados.
     * @throws IOException Si ocurre algún problema durante el
     *         encriptado. */
    public abstract byte[] desedeEncrypt(final byte[] data, final byte[] key) throws IOException;

    /** Desencripta datos mediante Triple DES (modo CBC sin relleno) y con un
     * salto de (IV) de 8 bytes a cero. Si se le indica una clave de 24 bytes,
     * la utilizaráa tal cual. Si se le indica una clave de 16 bytes,
     * duplicará los 8 primeros y los agregará al final para obtener una de 24.
     * @param data Datos a desencriptar.
     * @param key Clave 3DES de descifrado.
     * @return Datos descifrados.
     * @throws IOException Si ocurre algún problema durante el
     *         desencriptado. */
    public abstract byte[] desedeDecrypt(final byte[] data, final byte[] key) throws IOException;

    /** Encripta datos mediante DES (modo ECB sin relleno).
     * @param data Datos a encriptar.
     * @param key Clave DES de cifrado.
     * @return Datos cifrados.
     * @throws IOException Si ocurre algún problema durante el
     *         encriptado. */
    public abstract byte[] desEncrypt(final byte[] data, final byte[] key) throws IOException;

    /** Desencripta datos mediante DES (modo ECB sin relleno).
     * @param data Datos a desencriptar.
     * @param key Clave DES de descifrado.
     * @return Datos descifrados.
     * @throws IOException Si ocurre algún problema durante el
     *         desencriptado. */
    public abstract byte[] desDecrypt(final byte[] data, final byte[] key) throws IOException;

    /** Desencripta datos mediante AES (modo CBC sin relleno).
     * @param data Datos a encriptar.
     * @param key Clave AES de cifrado.
     * @return Datos cifrados.
     * @throws IOException Si ocurre algún problema durante el
     *         encriptado. */
    public abstract byte[] aesDecrypt(final byte[] data, final byte[] key) throws IOException;

    /** Desencripta datos mediante RSA.
     * @param cipheredData Datos a desencriptar.
     * @param key Clava RSA de descifrado.
     * @return Datos descifrados.
     * @throws IOException Si ocurre algún problema durante el
     *         desencriptado. */
    public abstract byte[] rsaDecrypt(final byte[] cipheredData, final Key key) throws IOException;

    /** Encripta datos mediante RSA.
     * @param data Datos a encriptar.
     * @param key Clava RSA de cifrado.
     * @return Datos encriptados.
     * @throws IOException Si ocurre algún problema durante el
     *         encriptado. */
    public abstract byte[] rsaEncrypt(final byte[] data, final Key key) throws IOException;

    /** Genera un certificado del tipo indicado a partir de su codificación.
     * @param encode Codificación del certificado.
     * @return Certificado generado.
     * @throws CertificateException Si ocurre algún problema durante la
     *         generación. */
    public abstract Certificate generateCertificate(byte[] encode) throws CertificateException;

    /** Genera un aleatorio contenido en un array de bytes.
     * @param numBytes Número de bytes aleatorios que generar.
     * @return Array de bytes aleatorios.
     * @throws IOException Si ocurre algún problema durante la
     *         generación del aleatorio. */
    public abstract byte[] generateRandomBytes(int numBytes) throws IOException;

	/** Genera un par de claves de tipo curva elíptica.
	 * @param curveName Tipo de curva elíptica a utilizar.
	 * @return Par de claves generadas.
	 * @throws NoSuchAlgorithmException Si el sistema no soporta la generación de curvas elípticas.
	 * @throws InvalidAlgorithmParameterException Si el sistema no soporta el tipo de curva elíptica indicada. */
	public abstract KeyPair generateEcKeyPair(final EcCurve curveName) throws NoSuchAlgorithmException,
	                                                                          InvalidAlgorithmParameterException;
}


text:
#ifndef itkMultiStartOptimizerv4_h
#define itkMultiStartOptimizerv4_h

#include "itkObjectToObjectOptimizerBase.h"
#include "itkGradientDescentOptimizerv4.h"

namespace itk
{
  /** \class MultiStartOptimizerv4Template
   *  \brief Multi-start searches over input parameters and returns the best metric value
   *
   *   The multi-start algorithm performs gradient descent from N (large) number of starting points and
   *   returns the best solution. Ideal start points would sample the solution space almost uniformly, thus,
   *   in theory, this is a global optimizer.  In this implementation, the quality of the optimization
   *   depends on the parameter space samples that the user inputs to the optimizer.  Multi-start can be
   *   modified in numerous ways to improve robustness of standard approaches.  These improvements usually
   *   focus modifying the parameter sample space.  This is why we place the burden on the user to provide
   *   the parameter samples over which to optimize.
   *
   * \ingroup ITKOptimizersv4
   */
template<typename TInternalComputationValueType>
class MultiStartOptimizerv4Template
: public ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType>
{
public:
  /** Standard class typedefs. */
  typedef MultiStartOptimizerv4Template                                Self;
  typedef ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> Superclass;
  typedef SmartPointer< Self >                                         Pointer;
  typedef SmartPointer< const Self >                                   ConstPointer;

  /** Run-time type information (and related methods). */
  itkTypeMacro(MultiStartOptimizerv4Template, Superclass);

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  typedef typename Superclass::ParametersType                                 ParametersType;
  typedef std::vector< ParametersType >                                       ParametersListType;
  typedef typename ParametersListType::size_type                              ParameterListSizeType;

  typedef ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType>              OptimizerType;
  typedef typename OptimizerType::Pointer                                           OptimizerPointer;
  typedef typename itk::GradientDescentOptimizerv4Template<TInternalComputationValueType> LocalOptimizerType;
  typedef typename LocalOptimizerType::Pointer                                      LocalOptimizerPointer;

  /** Codes of stopping conditions. */
  typedef enum {
    MAXIMUM_NUMBER_OF_ITERATIONS,
    COSTFUNCTION_ERROR,
    UPDATE_PARAMETERS_ERROR,
    STEP_TOO_SMALL,
    CONVERGENCE_CHECKER_PASSED,
    OTHER_ERROR
  } StopConditionType;

  /** Stop condition return string type */
  typedef typename Superclass::StopConditionReturnStringType StopConditionReturnStringType;

  /** Stop condition internal string type */
  typedef typename Superclass::StopConditionDescriptionType  StopConditionDescriptionType;
  /** Stop condition return string type */

  /** It should be possible to derive the internal computation type from the class object. */
  typedef TInternalComputationValueType             InternalComputationValueType;

  /** Metric type over which this class is templated */
  typedef typename Superclass::MetricType           MetricType;
  typedef typename MetricType::Pointer              MetricTypePointer;

  /** Derivative type */
  typedef typename MetricType::DerivativeType       DerivativeType;

  /** Measure type */
  typedef typename Superclass::MeasureType          MeasureType;
  typedef std::vector< MeasureType >                MetricValuesListType;

  /** Get stop condition enum */
  itkGetConstReferenceMacro(StopCondition, StopConditionType);

  /** Create an instance of the local optimizer */
  void InstantiateLocalOptimizer();

  /** Begin the optimization */
  virtual void StartOptimization( bool doOnlyInitialization = false ) ITK_OVERRIDE;

  /** Stop optimization. The object is left in a state so the
   * optimization can be resumed by calling ResumeOptimization. */
  virtual void StopOptimization();

  /** Resume the optimization. Can be called after StopOptimization to
   * resume. The bulk of the optimization work loop is here. */
  virtual void ResumeOptimization();

  /** Get the reason for termination */
  virtual const StopConditionReturnStringType GetStopConditionDescription() const ITK_OVERRIDE;

  /** Get the list of parameters over which to search.  */
  ParametersListType & GetParametersList();

  /** Set the list of parameters over which to search */
  void SetParametersList(ParametersListType & p);

  /** Get the list of metric values that we produced after the multi-start search.  */
  const MetricValuesListType & GetMetricValuesList() const;

  /** Return the parameters from the best visited position */
  ParametersType GetBestParameters( );

  /** Set/Get the optimizer. */
  itkSetObjectMacro( LocalOptimizer, OptimizerType );
  itkGetModifiableObjectMacro(LocalOptimizer, OptimizerType );

  inline ParameterListSizeType GetBestParametersIndex( ) { return this->m_BestParametersIndex; }

protected:
  /** Default constructor */
  MultiStartOptimizerv4Template();
  virtual ~MultiStartOptimizerv4Template();

  virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE;

  /* Common variables for optimization control and reporting */
  bool                          m_Stop;
  StopConditionType             m_StopCondition;
  StopConditionDescriptionType  m_StopConditionDescription;
  ParametersListType            m_ParametersList;
  MetricValuesListType          m_MetricValuesList;
  MeasureType                   m_MinimumMetricValue;
  MeasureType                   m_MaximumMetricValue;
  ParameterListSizeType         m_BestParametersIndex;
  OptimizerPointer              m_LocalOptimizer;

private:
  ITK_DISALLOW_COPY_AND_ASSIGN(MultiStartOptimizerv4Template);

};

/** This helps to meet backward compatibility */
typedef MultiStartOptimizerv4Template<double> MultiStartOptimizerv4;

} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkMultiStartOptimizerv4.hxx"
#endif

#endif