text:
<?php
namespace Elementor;

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class Control_Switcher extends Control_Base {

	public function get_type() {
		return 'switcher';
	}

	public function content_template() {
		?>

			{{{ data.label }}}

					<input type="checkbox" data-setting="{{ data.name }}" class="elementor-switch-input" value="{{ data.return_value }}">

		<# if ( data.description ) { #>

{{{ data.description }}}

		<# } #>
		<?php
	}

	protected function get_default_settings() {
		return [
			'label_off' => '',
			'label_on' => '',
			'return_value' => 'yes',
		];
	}
}


text:
<?php

namespace Behat\WiremockExtension\Collection;

use Behat\WiremockExtension\Service\ServiceInterface;

/**
 * Class Collection
 *
 * @package Behat\WiremockExtension\Collection
 */
class Collection extends \ArrayObject
{
    /**
     * @param ServiceInterface $service
     */
    public function add(ServiceInterface $service)
    {
        $this->offsetSet($service->getName(), $service);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { ColorPickerComponent } from './color-picker.component';
import { MatDialogModule } from '@angular/material/dialog';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { NO_ERRORS_SCHEMA } from '@angular/core';

describe('ColorPickerComponent', () => {
  let component: ColorPickerComponent;
  let fixture: ComponentFixture<ColorPickerComponent>;
  const dialogRef: Partial<MatDialogRef<ColorPickerComponent>> = {};

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [ColorPickerComponent],
        imports: [MatDialogModule],
        providers: [
          { provide: MAT_DIALOG_DATA, useValue: {} },
          { provide: MatDialogRef, useValue: dialogRef },
        ],
        schemas: [NO_ERRORS_SCHEMA],
      }).compileComponents();
    })
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(ColorPickerComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
package me.mattem.formation.calibration;

import java.util.List;
import java.util.Map;

import me.mattem.formation.annotations.FormationExclude;
import me.mattem.formation.annotations.FormationInclude;

@FormationInclude
public class FormationListCalibration {
	//public List<?> genericList;
	private List<String> stringList;
	private List<Map<String, String>> mapList;
	private List<List<String>> listStringList;
	private List<FormationListCalibration> recursiveList;
	private List<FormationInterfaceCalibrationClass> interfaceList;

	private String debugString;

	public List<String> getStringList() {
		return stringList;
	}

	public void setStringList(List<String> stringList) {
		this.stringList = stringList;
	}

	public List<Map<String, String>> getMapList() {
		return mapList;
	}

	public void setMapList(List<Map<String, String>> mapList) {
		this.mapList = mapList;
	}

	public List<List<String>> getListStringList() {
		return listStringList;
	}

	public void setListStringList(List<List<String>> listStringList) {
		this.listStringList = listStringList;
	}

	public List<FormationListCalibration> getRecursiveList() {
		return recursiveList;
	}

	public void setRecursiveList(List<FormationListCalibration> recursiveList) {
		this.recursiveList = recursiveList;
	}

	public String getDebugString() {
		return debugString;
	}

	public void setDebugString(String debugString) {
		this.debugString = debugString;
	}

	@FormationExclude // This currently wont work
	public List<FormationInterfaceCalibrationClass> getInterfaceList() {
		return interfaceList;
	}

	public void setInterfaceList(List<FormationInterfaceCalibrationClass> interfaceList) {
		this.interfaceList = interfaceList;
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>me.machadolucas.dataconverter.template</title>
<meta name="date" content="2014-04-05">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package me.machadolucas.dataconverter.template

Class Summary

Class
Description

ArrayOfJSON

JSONObject

JSONPair

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
<?php
namespace App\Workflow;

use App\Workflow\Eloquent\Definition;
use App\Workflow\Eloquent\Entry;
use App\Workflow\Eloquent\CurrentStep;
use App\Workflow\Eloquent\HistoryStep;

use App\Workflow\Exceptions\StateNotActivatedException;
use App\Workflow\Exceptions\StepNotFoundException;
use App\Workflow\Exceptions\CurrentStepNotFoundException;
use App\Workflow\Exceptions\ActionNotFoundException;
use App\Workflow\Exceptions\ActionNotAvailableException;
use App\Workflow\Exceptions\ResultNotFoundException;
use App\Workflow\Exceptions\ResultNotAvailableException;
use App\Workflow\Exceptions\FunctionNotFoundException;
use App\Workflow\Exceptions\EntryNotFoundException;
use App\Workflow\Exceptions\ConfigNotFoundException;
use App\Workflow\Exceptions\SplitNotFoundException;
use App\Workflow\Exceptions\JoinNotFoundException;

class Workflow {

    /**
     * The workflow five states.
     *
     * @var int
     */
    const OSWF_CREATED    = 1;
    const OSWF_ACTIVATED  = 2;
    const OSWF_SUSPENDED  = 3;
    const OSWF_COMPLETED  = 4;
    const OSWF_KILLED     = 5;

    /**
     * The workflow instance object.
     *
     * @var App\Workflow\Eloquent\Entry
     */
    protected $entry;

    /**
     * The workflow config description.
     *
     * @var array
     */
    protected $wf_config;

    /**
     * workflow options
     *
     * @var array
     */
    protected $options = [];

    /**
     * workflow constructor
     *
     * @param  string $entry_id
     * @return void
    */
    public function __construct($entry_id)
    {
        $entry = Entry::find($entry_id);
        if ($entry)
        {
            $this->entry = $entry;
            $definition = Definition::find($entry->definition_id);
            if (!$definition)
            {
                throw new ConfigNotFoundException();
            }

            if (isset($definition->contents) && $definition->contents)
            {
                $this->wf_config = $definition->contents;
            }
            else
            {
                throw new ConfigNotFoundException();
            }
        }
        else
        {
            throw new EntryNotFoundException();
        }
    }

    /**
     * create workflow.
     *
     * @param string $definition_id
     * @param string $caller
     * @return string
     */
    public static function createInstance($definition_id, $caller)
    {
        $entry = new Entry;
        $entry->definition_id = $definition_id;
        $entry->creator = $caller;
        $entry->state = self::OSWF_CREATED;
        $entry->save();
        return new Workflow($entry->id);
    }

    /**
     * get entry id.
     *
     * @return string
     */
    public function getEntryId()
    {
       return $this->entry->id;
    }

    /**
     * check action is available
     *
     * @param array $action_descriptor
     * @return boolean
     */
    private function isActionAvailable($action_descriptor)
    {
        if (isset($action_descriptor['restrict_to']) && isset($action_descriptor['restrict_to']['conditions']) && $action_descriptor['restrict_to']['conditions'])
        {
            if (!$this->passesConditions($action_descriptor['restrict_to']['conditions']))
            {
                return false;
            }
        }
        return true;
    }

    /**
     * initialize workflow.
     *
     * @param array options
     * @return void
     */
    public function start($options=[])
    {
        $this->options = array_merge($this->options, $options);

        if (!isset($this->wf_config['initial_action']) || !$this->wf_config['initial_action'])
        {
            throw new ActionNotFoundException();
        }

        //$available_action_flg = false;
        //foreach ($this->wf_config['initial_actions'] as $action_descriptor)
        //{
        //    if ($this->isActionAvailable($action_descriptor))
        //    {
        //        $available_action_flg = true;
        //        break;
        //    }
        //}
        //if (!$available_action_flg)
        //{
        //    throw new ActionNotAvailableException();
        //}

        $action_descriptor = $this->wf_config['initial_action'];
        if (!$this->isActionAvailable($action_descriptor))
        {
            throw new ActionNotAvailableException();
        }

        // confirm result whose condition is satified.
        if (!isset($action_descriptor['results']) || !$action_descriptor['results'])
        {
            throw new ResultNotFoundException();
        }

        $available_result_descriptor = $this->getAvailableResult($action_descriptor['results']);
        if (!$available_result_descriptor)
        {
            throw new ResultNotAvailableException();
        }
        // create new current step
        $this->createNewCurrentStep($available_result_descriptor, $action_descriptor['id'], '');
        // change workflow state to activited
        $this->changeEntryState(self::OSWF_ACTIVATED);

        return $this;
    }

    /**
     * get workflow state.
     *
     * @return string
     */
    public function getEntryState()
    {
        return $this->entry->state;
    }

    /**
     * change workflow state.
     *
     * @param string $new_state
     * @return void
     */
    public function changeEntryState($new_state)
    {
        $entry = Entry::find($this->entry->id);
        $entry->state = $new_state;
        $entry->save();
    }

    /**
     * complete workflow.
     *
     * @param string $entry_id
     * @return void
     */
    protected function completeEntry($entry_id)
    {
        return $this->changeEntryState($entry_id, self::OSWF_COMPLETED);
    }

    /**
     * get current steps for workflow.
     *
     * @return array
     */
    public function getCurrentSteps()
    {
        return Entry::find($this->entry->id)->currentSteps;
    }

    /**
     *  get step meta.
     *
     * @param string $step_id
     * @return array
     */
    public function getStepMeta($step_id, $name='')
    {
        $step_description = $this->getStepDescriptor($step_id);
        if ($name)
        {
            return isset($step_description[$name]) ? $step_description[$name] : '';
        }
        return $step_description;
    }

    /**
     *  move workflow step to history
     *
     * @param App\Workflow\Eloquent\CurrentStep $current_step
     * @param int $action_id
     * @return string previous_id
     */
    private function moveToHistory($current_step, $action_id)
    {
        // add to history records
        $history_step = new HistoryStep;
        $history_step->fill($current_step->toArray());
        $history_step->action_id = $action_id;
        $history_step->caller = isset($this->options['caller']) ? $this->options['caller'] : '';
        $history_step->finish_time = time();
        $history_step->save();

        // delete from current step
        $current_step->delete();

        return $history_step->id;
    }

    /**
     *  create new workflow step.
     *
     * @param array $result_descriptor
     * @param int $action_id
     * @param string $previous_id
     * @return void
     */
    private function createNewCurrentStep($result_descriptor, $action_id, $previous_id='')
    {
        $step_descriptor = [];
        if (isset($result_descriptor['step']) && $result_descriptor['step'])
        {
            $step_descriptor = $this->getStepDescriptor($result_descriptor['step']);
            if (!$step_descriptor)
            {
                throw new StepNotFoundException();
            }
        }
        if (!$step_descriptor)
        {
            return;
        }
        // order to use for workflow post-function
        if (isset($step_descriptor['state']) && $step_descriptor['state'])
        {
            $this->options['state'] = $step_descriptor['state'];
        }

        $new_current_step = new CurrentStep;
        $new_current_step->entry_id = $this->entry->id;
        $new_current_step->action_id = $action_id;
        $new_current_step->step_id = isset($result_descriptor['step']) ? intval($result_descriptor['step']) : 0;
        $new_current_step->previous_id = $previous_id;
        $new_current_step->status = isset($result_descriptor['status']) ? $result_descriptor['status'] : 'Finished';
        $new_current_step->start_time = time();
        $new_current_step->owners =  isset($this->options['owners']) ? $this->options['owners'] : '';
        $new_current_step->comments = isset($this->options['comments']) ? $this->options['comments'] : '';
        $new_current_step->caller = isset($this->options['caller']) ? $this->options['caller'] : '';
        $new_current_step->save();

        // trigger before step
        if (isset($step_descriptor['pre_functions']) && $step_descriptor['pre_functions'])
        {
            $this->executeFunctions($step_descriptor['pre_functions']);
        }
    }

    /**
     * transfer workflow step.
     *
     * @param array $current_steps
     * @param int $action;
     * @return void
     */
    private function transitionWorkflow($current_steps, $action_id)
    {
        foreach ($current_steps as $current_step)
        {
            $step_descriptor = $this->getStepDescriptor($current_step->step_id);
            if (!$step_descriptor)
            {
                throw new StepNotFoundException();
            }

            $action_descriptor = $this->getActionDescriptor(isset($step_descriptor['actions']) ? $step_descriptor['actions'] : [], $action_id);
            if ($action_descriptor)
            {
                break;
            }
        }
        if (!$action_descriptor)
        {
            throw new ActionNotFoundException();
        }
        if (!$this->isActionAvailable($action_descriptor))
        {
            throw new ActionNotAvailableException();
        }

        if (!isset($action_descriptor['results']) || !$action_descriptor['results'])
        {
            throw new ResultNotFoundException();
        }
        // confirm result whose condition is satified.
        $available_result_descriptor = $this->getAvailableResult($action_descriptor['results']);
        if (!$available_result_descriptor)
        {
            throw new ResultNotAvailableException();
        }

        // triggers after step
        if (isset($step_descriptor['post_functions']) && $step_descriptor['post_functions'])
        {
            $this->executeFunctions($step_descriptor['post_functions']);
        }
        // triggers before action
        if (isset($action_descriptor['pre_functions']) && $action_descriptor['pre_functions'])
        {
            $this->executeFunctions($action_descriptor['pre_functions']);
        }
        // triggers before result
        if (isset($available_result_descriptor['pre_functions']) && $available_result_descriptor['pre_functions'])
        {
            $this->executeFunctions($available_result_descriptor['pre_functions']);
        }
        // split workflow
        if (isset($available_result_descriptor['split']) && $available_result_descriptor['split'])
        {
            // get split result
            $split_descriptor = $this->getSplitDescriptor($available_result_descriptor['split']);
            if (!$split_descriptor)
            {
                throw new SplitNotFoundException();
            }

            // move current to history step
            $prevoius_id = $this->moveToHistory($current_step, $action_id);
            foreach ($split_descriptor['list'] as $result_descriptor)
            {
                $this->createNewCurrentStep($result_descriptor, $action_id, $prevoius_id);
            }
        }
        else if (isset($available_result_descriptor['join']) && $available_result_descriptor['join'])
        {
            // fix me. join logic will be realized, suggest using the propertyset
            // get join result
            $join_descriptor = $this->getJoinDescriptor($available_result_descriptor['join']);
            if (!$join_descriptor)
            {
                throw new JoinNotFoundException();
            }

            // move current to history step
            $prevoius_id = $this->moveToHistory($current_step, $action_id);
            if ($this->isJoinCompleted())
            {
                // record other previous_ids by propertyset
                $this->createNewCurrentStep($join_descriptor, $action_id, $prevoius_id);
            }
        }
        else
        {
            // move current to history step
            $prevoius_id = $this->moveToHistory($current_step, $action_id);
            // create current step
            $this->createNewCurrentStep($available_result_descriptor, $action_id, $prevoius_id);
        }
        // triggers after result
        if (isset($available_result_descriptor['post_functions']) && $available_result_descriptor['post_functions'])
        {
            $this->executeFunctions($available_result_descriptor['post_functions']);
        }
        // triggers after action
        if (isset($action_descriptor['post_functions']) && $action_descriptor['post_functions'])
        {
            $this->executeFunctions($action_descriptor['post_functions']);
        }
    }

    /**
     * check if the join is completed
     */
    private function isJoinCompleted()
    {
        return !CurrentStep::where('entry_id', $this->entry->id)->exists();
    }

    /**
     * execute action
     *
     * @param string $action_id
     * @param array $options;
     * @return string
     */
    public function doAction($action_id, $options=[])
    {
        $state = $this->getEntryState($this->entry->id);
        if ($state != self::OSWF_CREATED && $state != self::OSWF_ACTIVATED)
        {
            throw new StateNotActivatedException();
        }

        $current_steps = $this->getCurrentSteps();
        if (!$current_steps)
        {
            throw new CurrentStepNotFoundException();
        }

        // set options
        $this->options = array_merge($this->options, $options);
        // complete workflow step transition
        $this->transitionWorkflow($current_steps, intval($action_id));
    }

    /**
     * get join descriptor from list.
     *
     * @param string $join_id
     * @return array
     */
    private function getJoinDescriptor($join_id)
    {
        foreach ($this->wf_config['joins'] as $join)
        {
            if ($join['id'] == $join_id)
            {
                return $join;
            }
        }
        return [];
    }

    /**
     * get split descriptor from list.
     *
     * @param string $split_id
     * @return array
     */
    private function getSplitDescriptor($split_id)
    {
        foreach ($this->wf_config['splits'] as $split)
        {
            if ($split['id'] == $split_id)
            {
                return $split;
            }
        }
        return [];
    }

    /**
     * get action descriptor from list.
     *
     * @param array $actions
     * @param string $action_id
     * @return array
     */
    private function getActionDescriptor($actions, $action_id)
    {
        // get global config
        $actions = $actions ?: [];
        foreach ($actions as $action)
        {
            if ($action['id'] == $action_id)
            {
                return $action;
            }
        }
        return [];
    }

    /**
     *  get step configuration.
     *
     * @param array $steps
     * @param string $step_id
     * @return array
     */
    private function getStepDescriptor($step_id)
    {
        foreach ($this->wf_config['steps'] as $step)
        {
            if ($step['id'] == $step_id)
            {
                return $step;
            }
        }
        return [];
    }

    /**
     * save workflow configuration info.
     *
     * @param array $info
     * @return void
     */
    public static function saveWorkflowDefinition($info)
    {
        $definition = $info['_id'] ? Definition::find($info['_id']) : new Definition;
        $definition->fill($info);
        $definition->save();
    }

    /**
     * remove configuration info.
     *
     * @param string $definition_id
     * @return void
     */
    public static function removeWorkflowDefinition($definition_id)
    {
        Definition::find($definition_id)->delete();
    }

    /**
     * get all available actions
     *
     * @param array $info
     * @param bool $dest_state added for kanban dnd, is not common param.
     * @return array
     */
    public function getAvailableActions($options=[], $dest_state = false)
    {
        // set options
        $this->options = array_merge($this->options, $options);

        $available_actions = [];
        // get current steps
        $current_steps = $this->getCurrentSteps();
        foreach ($current_steps as $current_step)
        {
            $actions = $this->getAvailableActionsFromStep($current_step->step_id, $dest_state);
            $actions && $available_actions += $actions;
        }
        return $available_actions;
    }

    /**
     * get available actions for step
     *
     * @param string $step_id
     * @param bool $dest_state added for kanban dnd, is not common param.
     * @return array
     */
    private function getAvailableActionsFromStep($step_id, $dest_state = false)
    {
        $step_descriptor = $this->getStepDescriptor($step_id);
        if (!$step_descriptor)
        {
            throw new StepNotFoundException();
        }
        if (!isset($step_descriptor['actions']) || !$step_descriptor['actions'])
        {
            return [];
        }
        // global conditions for step
        if (!$this->isActionAvailable($step_descriptor))
        {
            return [];
        }

        $available_actions = [];
        foreach ($step_descriptor['actions'] as $action)
        {
            if ($this->isActionAvailable($action))
            {
                if ($dest_state)
                {
                    $state = '';
                    if (isset($action['results']) && is_array($action['results']) && count($action['results']) > 0 && isset($action['results'][0]['step']))
                    {
                        $dest_step_descriptor = $this->getStepDescriptor($action['results'][0]['step']);
                        $state = $dest_step_descriptor['state'];
                    }

                    $available_actions[] = [ 'id' => $action['id'], 'name' => $action['name'], 'screen' => $action['screen'] ?: '', 'state' => $state ];
                }
                else
                {
                    $available_actions[] = [ 'id' => $action['id'], 'name' => $action['name'], 'screen' => $action['screen'] ?: '' ];
                }
            }
        }

        return $available_actions;
    }

    /**
     * get available result from result-list
     *
     * @param array $results_descriptor
     * @return array
     */
    public function getAvailableResult($results_descriptor)
    {
        $available_result_descriptor = [];

        // confirm result whose condition is satified.
        foreach ($results_descriptor as $result_descriptor)
        {
            if (isset($result_descriptor['conditions']) && $result_descriptor['conditions'])
            {
                if ($this->passesConditions($result_descriptor['conditions']))
                {
                    $available_result_descriptor = $result_descriptor;
                    break;
                }
            }
            else
            {
                $available_result_descriptor = $result_descriptor;
            }
        }
        return $available_result_descriptor;
    }

    /**
     * check conditions is passed
     *
     * @param array $conditions
     * @return boolean
     */
    private function passesConditions($conditions)
    {
        if (!isset($conditions['list']) || !$conditions['list'])
        {
            return true;
        }

        $type = isset($conditions['type']) && isset($conditions['type']) ? $conditions['type'] : 'and';
        $result = $type == 'and' ? true : false;

        foreach ($conditions['list'] as $condition)
        {
            $tmp = $this->passesCondition($condition);
            if ($type == 'and' && !$tmp)
            {
                return false;
            }
            if ($type == 'or' && $tmp)
            {
                return true;
            }
        }
        return $result;
    }

    /**
     * check condition is passed
     *
     * @param array $condition
     * @return boolean
     */
    private function passesCondition($condition)
    {
        return $this->executeFunction($condition);
    }

    /**
     * execute functions
     *
     * @param array function
     * @return void
     */
    private function executeFunctions($functions)
    {
        if (!$functions || !is_array($functions))
        {
            return;
        }

        foreach ($functions as $function)
        {
            if (is_array($function) && $function)
            {
                $this->executeFunction($function);
            }
        }
    }

    /**
     * execute function
     *
     * @param array $function
     * @return mixed
     */
    private function executeFunction($function)
    {
        $method = explode('@', $function['name']);
        $class = $method[0];
        $action = isset($method[1]) && $method[1] ? $method[1] : 'handle';

        // check handle function exists
        if (!method_exists($class, $action))
        {
            throw new FunctionNotFoundException();
        }
        $args = isset($function['args']) ? $function['args'] : [];
        // generate temporary vars
        $tmp_vars = $this->genTmpVars($args);
        // call handle function
        return $class::$action($tmp_vars);
    }

    /**
     * get all workflows' name.
     *
     * @return array
     */
    public static function getWorkflowNames()
    {
        return Definition::all(['name']);
    }

    /**
     * generate temporary variable.
     *
     * @return array
     */
    private function genTmpVars($args=[])
    {
        $tmp_vars = [];
        foreach ($this->entry as $key => $val)
        {
            $tmp_vars[$key] = $val;
        }
        $tmp_vars = array_merge($tmp_vars, $this->options);

        return array_merge($tmp_vars, $args);
    }

    /**
     * get property set
     *
     * @return mixed
     */
    public function getPropertySet($key)
    {
        return $key ? $this->entry->propertysets[$key] : $this->entry->propertysets;
    }

    /**
     * add property set
     *
     * @return void
     */
    public function setPropertySet($key, $val)
    {
        $this->entry->propertysets = array_merge($this->entry->propertysets ?: [], [ $key => $val ]);
        $this->entry->save();
    }

    /**
     * remove property set
     *
     * @return void
     */
    public function removePropertySet($key)
    {
        $this->entry->unset($key ? ('propertysets.' . $key) : 'propertysets');
    }

    /**
     * get used states in the workflow
     *
     * @return array
     */
    public static function getStates($contents)
    {
        $state_ids = [];
        $steps = isset($contents['steps']) && $contents['steps'] ? $contents['steps'] : [];
        foreach ($steps as $step)
        {
            $state_ids[] = isset($step['state']) ? $step['state'] : '';
        }
        return $state_ids;
    }

    /**
     * get used screens in the workflow
     *
     * @return array
     */
    public static function getScreens($contents)
    {
        $screen_ids = [];
        $steps = isset($contents['steps']) && $contents['steps'] ? $contents['steps'] : [];
        foreach ($steps as $step)
        {
            if (!isset($step['actions']) || !$step['actions'])
            {
                continue;
            }
            foreach ($step['actions'] as $action)
            {
                if (!isset($action['screen']) || !$action['screen'])
                {
                    continue;
                }
                $action['screen'] !=  '-1' && !in_array($action['screen'], $screen_ids) && $screen_ids[] = $action['screen'];
            }
        }
        return $screen_ids;
    }

    /**
     * get step num
     *
     * @return int
     */
    public static function getStepNum($contents)
    {
        $steps = isset($contents['steps']) && $contents['steps'] ? $contents['steps'] : [];
        return count($steps);
    }

    /**
     * fake new workflow step.
     *
     * @param array $result_descriptor
     * @param array $caller
     * @return void
     */
    public function fakeNewCurrentStep($result_descriptor, $caller)
    {
        $new_current_step = new CurrentStep;
        $new_current_step->entry_id = $this->entry->id;
        $new_current_step->step_id = intval($result_descriptor['id']);
        $new_current_step->status = isset($result_descriptor['status']) ? $result_descriptor['status'] : '';
        $new_current_step->start_time = time();
        $new_current_step->caller = $caller ?: '';
        $new_current_step->save();
    }
}


text:
package com.twitter.summingbird.javaapi;

import scala.Option;
import scala.Tuple2;

import com.twitter.summingbird.Platform;
import com.twitter.summingbird.Summer;

/**
 * Wraps a Summer (a KeyedProducer that is also a TailProducer)
 *
 * @author Julien Le Dem
 *
 * @param <P> underlying Platform
 * @param <K> key type
 * @param <V> value type
 */
public interface JSummer<P extends Platform<P>, K, V>
  extends
    JKeyedProducer<P, K, Tuple2<Option<V>, V>>,
    JTailProducer<P, Tuple2<K, Tuple2<Option<V>, V>>> {

  /**
   * @return the wrapped Summer
   */
  Summer<P, K, V> unwrap();

}


text: <ng-content></ng-content>


text:
module Merb
  module Static

    ##
    # TODO Refactor
    # * Try with fresh destination. Are the directories created as needed?
    # * It may be better to sync a separate directory, then symlink it to the live directory.

    module SimpleRsync

      def self.sync(options={})
        require 'net/ssh'
        require 'net/sftp'

        file_perm = 0644

        local_path  = Merb.root / "output"
        remote_path = options[:path]

        extra_net_ssh_options              = {}
        extra_net_ssh_options[:password]   = options[:password]   if options[:password]
        extra_net_ssh_options[:passphrase] = options[:passphrase] if options[:passphrase]

        puts "Connecting to #{options[:domain]}"
        Net::SSH.start(options[:domain], options[:username], extra_net_ssh_options) do |ssh|
          ssh.sftp.connect do |sftp|
            puts 'Checking for files which need updating'

            puts "Making initial remote directory: #{remote_path}"
            puts ssh.exec!("mkdir -p #{remote_path}")

            filenames_with_assets_first = Dir[local_path + '/**/*'].sort { |a,b|
              a_is_asset = (a =~ /\.(jpg|png|css|js|gif)$/)
              b_is_asset = (b =~ /\.(jpg|png|css|js|gif)$/)
              if (a_is_asset && b_is_asset)
                0
              elsif (a_is_asset)
                -1
              else
                1
              end
            }

            filenames_with_assets_first.each do |file|
              remote_file = remote_path + file.sub(/^#{local_path}/, '')

              if File.stat(file).directory?
                begin
                  sftp.stat!(remote_file)
                rescue Net::SFTP::StatusException => e
                  raise unless e.code == 2
                  puts "Making remote directory: #{remote_file}"
                  puts ssh.exec!("mkdir -p #{remote_file}")
                end
                next
              end

              begin
                rstat = sftp.stat!(remote_file)
              rescue Net::SFTP::StatusException => e
                raise unless e.code == 2
                puts "Uploading: #{file}"
                sftp.upload!(file, remote_file)
                sftp.setstat(remote_file, :permissions => file_perm)
                next
              end

              if File.stat(file).mtime > Time.at(rstat.mtime)
                puts "Copying #{file} to #{remote_file}"
                sftp.upload!(file, remote_file)
              end
            end
          end

          puts 'Disconnecting from remote server'
        end

        puts 'File transfer complete'
      end

    end
  end
end


text:
layout: data_model
title: PDFTrailerType
this_version: 1.1.1
---

  Heads up! These docs are for STIX 1.1.1, which is not the latest version (1.2). View the latest!

PDFTrailerTypePDF File Object Schema

The PDFTrailerType captures the details of a PDF trailer.

      <form id="nav-version">
        <select>

            <option value="1.2" >STIX 1.2</option>

            <option value="1.1.1" selected="selected">STIX 1.1.1</option>

            <option value="1.1" >STIX 1.1</option>

            <option value="1.0.1" >STIX 1.0.1</option>

            <option value="1.0" >STIX 1.0</option>

        </select>
      </form>

Fields

      Field Name
      Type
      Description

      Size0..1

          PositiveIntegerObjectPropertyType

The Size field captures the total number of entries in the file's cross-reference table.

      Prev0..1

          PositiveIntegerObjectPropertyType

The Prev field the byte offset from the beginning of the file to the beginning of the previous cross-reference table. This is only applicable for files that have more than one cross-reference table.

      Root0..1

          PDFIndirectObjectIDType

The Root field captures an indirect object reference that points to the catalog dictionary for the PDF document contained in the file.

      Encrypt0..1

          PDFDictionaryType

The Encrypt field captures the PDF document's encryption dictionary, either through an indirect reference or embedded set of key/value pairs.

      Info0..1

          PDFIndirectObjectIDType

The Info field captures an indirect object reference that points to the document information dictionary.

      ID0..1

          PDFFileIDType

The ID field captures an array of two strings that constitutes a file identifier.

      Last_Cross_Reference_Offset0..1

          PositiveIntegerObjectPropertyType

The Last_Cross_Reference_Offset field captures the byte offset, relative to the beginning of the file, of the last cross-reference table contained in the file.

      Offset0..1

          PositiveIntegerObjectPropertyType

The Offset field specifies the offset of the trailer from the beginning of the file, in bytes.

      Hashes0..1

          HashListType

The Hashes field captures any hashes that were computed for the trailer.


text:
__author__ = 'geoffc'
import cherrypy
from BaseResource import BaseResource
from bson.objectid import ObjectId
from ..services.user_service import UserService

@cherrypy.popargs('id')
class User(BaseResource):
    exposed = True

    def __init__(self):
        super(User, self).__init__()
        self.service = UserService()

    def GET(self, id=None):
        if id:
            item = self.service.get_user_by_id(id)
            cookie = cherrypy.request.cookie
            if 'user' in cookie:
                cookie_id = cookie['user'].value
                if cookie_id == id:
                    item['isLoggedIn'] = True

            return item
        else:
            items = self.service.get_users()
            return [i for i in items]

    @cherrypy.tools.json_in()
    def POST(self, id):
        item = cherrypy.request.json
        self.service.update_user(id, item)

    @cherrypy.tools.json_in()
    def DELETE(self, id):
        pass


text:
module awk.grid {

    var utils = Utils;

    var template =
            '
'+
                '
'+
                    '<select class="ag-filter-select" id="filterType">'+
                        '<option value="1">[EQUALS]</option>'+
                        '<option value="2">[LESS THAN]</option>'+
                        '<option value="3">[GREATER THAN]</option>'+
                    '</select>'+
                '
'+
                '
'+
                    '<input class="ag-filter-filter" id="filterText" type="text" placeholder="[FILTER...]"/>'+
                '
'+
                '
'+
                    '<button type="button" id="applyButton">Apply Filter</button>' +
                '
'+
            '
';

    var EQUALS = 1;
    var LESS_THAN = 2;
    var GREATER_THAN = 3;

    export class NumberFilter implements Filter {

        private filterParams: any;
        private filterChangedCallback: any;
        private filterModifiedCallback: any;
        private localeTextFunc: any;
        private valueGetter: any;
        private filterNumber: any;
        private filterType: any;
        private api: any;

        private eGui: any;
        private eFilterTextField: any;
        private eTypeSelect: any;
        private applyActive: any;
        private eApplyButton: any;

        constructor(params: any) {
            this.filterParams = params.filterParams;
            this.applyActive = this.filterParams && this.filterParams.apply == true;
            this.filterChangedCallback = params.filterChangedCallback;
            this.filterModifiedCallback = params.filterModifiedCallback;
            this.localeTextFunc = params.localeTextFunc;
            this.valueGetter = params.valueGetter;
            this.createGui();
            this.filterNumber = null;
            this.filterType = EQUALS;
            this.createApi();
        }

        public onNewRowsLoaded() {
            var keepSelection = this.filterParams && this.filterParams.newRowsAction === 'keep';
            if (!keepSelection) {
                this.api.setType(EQUALS);
                this.api.setFilter(null);
            }
        }

        public afterGuiAttached() {
            this.eFilterTextField.focus();
        }

        public doesFilterPass(node: any) {
            if (this.filterNumber === null) {
                return true;
            }
            var value = this.valueGetter(node);

            if (!value && value !== 0) {
                return false;
            }

            var valueAsNumber: any;
            if (typeof value === 'number') {
                valueAsNumber = value;
            } else {
                valueAsNumber = parseFloat(value);
            }

            switch (this.filterType) {
                case EQUALS:
                    return valueAsNumber === this.filterNumber;
                case LESS_THAN:
                    return valueAsNumber < this.filterNumber;
                case GREATER_THAN:
                    return valueAsNumber > this.filterNumber;
                default:
                    // should never happen
                    console.warn('invalid filter type ' + this.filterType);
                    return false;
            }
        }

        public getGui() {
            return this.eGui;
        }

        public isFilterActive() {
            return this.filterNumber !== null;
        }

        private createTemplate() {
            return template
                .replace('[FILTER...]', this.localeTextFunc('filterOoo', 'Filter...'))
                .replace('[EQUALS]', this.localeTextFunc('equals', 'Equals'))
                .replace('[LESS THAN]', this.localeTextFunc('lessThan', 'Less than'))
                .replace('[GREATER THAN]', this.localeTextFunc('greaterThan', 'Greater than'));
        }

        private createGui() {
            this.eGui = utils.loadTemplate(this.createTemplate());
            this.eFilterTextField = this.eGui.querySelector("#filterText");
            this.eTypeSelect = this.eGui.querySelector("#filterType");

            utils.addChangeListener(this.eFilterTextField, this.onFilterChanged.bind(this));
            this.eTypeSelect.addEventListener("change", this.onTypeChanged.bind(this));

            this.setupApply();
        }

        private setupApply() {
            if (this.applyActive) {
                this.eApplyButton = this.eGui.querySelector('#applyButton');
                this.eApplyButton.addEventListener('click', () => {
                    this.filterChangedCallback();
                });
            } else {
                utils.removeElement(this.eGui, '#applyPanel');
            }
        }

        private onTypeChanged() {
            this.filterType = parseInt(this.eTypeSelect.value);
            this.filterChanged();
        }

        private filterChanged() {
            this.filterModifiedCallback();
            if (!this.applyActive) {
                this.filterChangedCallback();
            }
        }

        private onFilterChanged() {
            var filterText = utils.makeNull(this.eFilterTextField.value);
            if (filterText && filterText.trim() === '') {
                filterText = null;
            }
            var newFilter: number;
            if (filterText !== null && filterText !== undefined) {
                newFilter = parseFloat(filterText);
            } else {
                newFilter = null;
            }
            if (this.filterNumber !== newFilter) {
                this.filterNumber = newFilter;
                this.filterChanged();
            }
        }

        private createApi() {
            var that = this;
            this.api = {
                EQUALS: EQUALS,
                LESS_THAN: LESS_THAN,
                GREATER_THAN: GREATER_THAN,
                setType: function (type: any) {
                    that.filterType = type;
                    that.eTypeSelect.value = type;
                },
                setFilter: function (filter: any) {
                    filter = utils.makeNull(filter);

                    if (filter !== null && !(typeof filter === 'number')) {
                        filter = parseFloat(filter);
                    }
                    that.filterNumber = filter;
                    that.eFilterTextField.value = filter;
                },
                getType: function () {
                    return that.filterType;
                },
                getFilter: function () {
                    return that.filterNumber;
                },
                getModel: function () {
                    if (that.isFilterActive()) {
                        return {
                            type: that.filterType,
                            filter: that.filterNumber
                        };
                    } else {
                        return null;
                    }
                },
                setModel: function (dataModel: any) {
                    if (dataModel) {
                        this.setType(dataModel.type);
                        this.setFilter(dataModel.filter);
                    } else {
                        this.setFilter(null);
                    }
                }
            };
        }

        private getApi() {
            return this.api;
        }
    }
}


text:
package com.google.security.zynamics.binnavi.API.reil;

import com.google.security.zynamics.binnavi.REIL.ReilGraphConverter;

// / Function of REIL code
/**
 * Represents a single REIL function.
 */
public final class ReilFunction {
  /**
   * REIL graph of the function.
   */
  private final ReilGraph m_graph;

  /**
   * The wrapped internal REIL function object.
   */
  private final com.google.security.zynamics.reil.ReilFunction m_function;

  // / @cond INTERNAL
  /**
   * Creates a new API REIL function object.
   *
   * @param function The wrapped internal REIL function object.
   */
  // / @endcond
  public ReilFunction(final com.google.security.zynamics.reil.ReilFunction function) {
    m_function = function;

    m_graph = ReilGraphConverter.createReilGraph(function.getGraph());
  }

  // ! The graph of the function.
  /**
   * Returns the graph of the REIL function.
   *
   * @return The graph of the REIL function.
   */
  public ReilGraph getGraph() {
    return m_graph;
  }

  // ! The name of the function.
  /**
   * Returns the name of the REIL function.
   *
   * @return The name of the REIL function.
   */
  public String getName() {
    return m_function.getName();
  }

  // ! Printable representation of the REIL function.
  /**
   * Returns the string representation of the REIL function.
   *
   * @return The string representation of the REIL function.
   */
  @Override
  public String toString() {
    return String.format("REIL function %s", getName());
  }
}


text:
layout: post
title: IRis at the Research and Scholarship Expo
categories:
- Information and Society
- Library News and Events
- Research Online
- Scholarly Communications
tags:
- Digital Commons
- hillary corbett
- IRis
- Research and Scholarship Expo
status: publish
type: post
published: true
meta:
  _edit_last: '14'
---
Tomorrow, March 24, Northeastern is hosting the Research and Scholarship Expo in the Cabot Cage. It takes place from 11 am- 2:30 pm and is an exhibition and poster session for student and faculty research.

Hillary Corbett, Scholarly Communications Librarian, will be representing the Library and sharing information about IRis, a digital archive that collects, manages, preserves, and shares the intellectual output and historical record of Northeastern University, in booth 142.

The Library has recently implemented a new platform for IRis, Digital Commons, which offers enhanced options for publishing journals and other materials.  Hillary says, "Universities produce plenty of material that may not get published through traditional means. With the Digital Commons software, faculty can produce online journals, conference proceedings, e-books, and more. Northeastern University celebrates its global experience and outreach, and faculty and researchers will be able to leverage the openness of IRis to increase the global impact of their work."

Download a brochure about IRis here.

Be sure and stop by Cabot on Wednesday, to see the Expo and visit Hillary!


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PPM.Common.DtoModels
{
    public class BudgetDto
    {
        public Guid Id { get; set; }
        public string Name { get; set; }

        public double AmountOfCosts { get; set; }
    }
}


text:
#pragma once
#include <aws/macie2/Macie2_EXPORTS.h>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Macie2
{
namespace Model
{

  /**
   *
Provides information about the block public access settings for an S3 bucket.
   * These settings can apply to a bucket at the account level or bucket level. For
   * detailed information about each setting, see Blocking
   * public access to your Amazon S3 storage in the Amazon Simple Storage
   * Service User Guide.

See Also:
   AWS
   * API Reference

   */
  class AWS_MACIE2_API BlockPublicAccess
  {
  public:
    BlockPublicAccess();
    BlockPublicAccess(Aws::Utils::Json::JsonView jsonValue);
    BlockPublicAccess& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
Specifies whether Amazon S3 blocks public access control lists (ACLs) for the
     * bucket and objects in the bucket.

     */
    inline bool GetBlockPublicAcls() const{ return m_blockPublicAcls; }

    /**
     *
Specifies whether Amazon S3 blocks public access control lists (ACLs) for the
     * bucket and objects in the bucket.

     */
    inline bool BlockPublicAclsHasBeenSet() const { return m_blockPublicAclsHasBeenSet; }

    /**
     *
Specifies whether Amazon S3 blocks public access control lists (ACLs) for the
     * bucket and objects in the bucket.

     */
    inline void SetBlockPublicAcls(bool value) { m_blockPublicAclsHasBeenSet = true; m_blockPublicAcls = value; }

    /**
     *
Specifies whether Amazon S3 blocks public access control lists (ACLs) for the
     * bucket and objects in the bucket.

     */
    inline BlockPublicAccess& WithBlockPublicAcls(bool value) { SetBlockPublicAcls(value); return *this;}

    /**
     *
Specifies whether Amazon S3 blocks public bucket policies for the bucket.

     */
    inline bool GetBlockPublicPolicy() const{ return m_blockPublicPolicy; }

    /**
     *
Specifies whether Amazon S3 blocks public bucket policies for the bucket.

     */
    inline bool BlockPublicPolicyHasBeenSet() const { return m_blockPublicPolicyHasBeenSet; }

    /**
     *
Specifies whether Amazon S3 blocks public bucket policies for the bucket.

     */
    inline void SetBlockPublicPolicy(bool value) { m_blockPublicPolicyHasBeenSet = true; m_blockPublicPolicy = value; }

    /**
     *
Specifies whether Amazon S3 blocks public bucket policies for the bucket.

     */
    inline BlockPublicAccess& WithBlockPublicPolicy(bool value) { SetBlockPublicPolicy(value); return *this;}

    /**
     *
Specifies whether Amazon S3 ignores public ACLs for the bucket and objects in
     * the bucket.

     */
    inline bool GetIgnorePublicAcls() const{ return m_ignorePublicAcls; }

    /**
     *
Specifies whether Amazon S3 ignores public ACLs for the bucket and objects in
     * the bucket.

     */
    inline bool IgnorePublicAclsHasBeenSet() const { return m_ignorePublicAclsHasBeenSet; }

    /**
     *
Specifies whether Amazon S3 ignores public ACLs for the bucket and objects in
     * the bucket.

     */
    inline void SetIgnorePublicAcls(bool value) { m_ignorePublicAclsHasBeenSet = true; m_ignorePublicAcls = value; }

    /**
     *
Specifies whether Amazon S3 ignores public ACLs for the bucket and objects in
     * the bucket.

     */
    inline BlockPublicAccess& WithIgnorePublicAcls(bool value) { SetIgnorePublicAcls(value); return *this;}

    /**
     *
Specifies whether Amazon S3 restricts public bucket policies for the
     * bucket.

     */
    inline bool GetRestrictPublicBuckets() const{ return m_restrictPublicBuckets; }

    /**
     *
Specifies whether Amazon S3 restricts public bucket policies for the
     * bucket.

     */
    inline bool RestrictPublicBucketsHasBeenSet() const { return m_restrictPublicBucketsHasBeenSet; }

    /**
     *
Specifies whether Amazon S3 restricts public bucket policies for the
     * bucket.

     */
    inline void SetRestrictPublicBuckets(bool value) { m_restrictPublicBucketsHasBeenSet = true; m_restrictPublicBuckets = value; }

    /**
     *
Specifies whether Amazon S3 restricts public bucket policies for the
     * bucket.

     */
    inline BlockPublicAccess& WithRestrictPublicBuckets(bool value) { SetRestrictPublicBuckets(value); return *this;}

  private:

    bool m_blockPublicAcls;
    bool m_blockPublicAclsHasBeenSet;

    bool m_blockPublicPolicy;
    bool m_blockPublicPolicyHasBeenSet;

    bool m_ignorePublicAcls;
    bool m_ignorePublicAclsHasBeenSet;

    bool m_restrictPublicBuckets;
    bool m_restrictPublicBucketsHasBeenSet;
  };

} // namespace Model
} // namespace Macie2
} // namespace Aws


text:
package controllers;

import models.Location;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpPost;
import play.data.Form;
import play.libs.Json;
import play.mvc.*;

import views.html.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class GeoUtil extends Controller {

    List<List<String>> locationMatrix = new ArrayList<>();

    public Result index() {
        return ok(map.render("Hii"));
    }

    public Result getData() {
        return ok(Json.toJson(locationMatrix));
    }

    public Result populate() {
        String subject = Form.form().bindFromRequest().get("lang");
        locationMatrix.clear();
        populateMatrix(subject);
        return redirect(routes.GeoUtil.index());
    }

    private void populateMatrix(String lang) {
        List<Location> locationPagedList = Location.find.where().ieq("repository_language", lang).findList();
        HashMap<String, Integer> frequency = new HashMap<>();
        int count;
        for (Location location : locationPagedList) {
            String[] loc = location.repository_owner_location.split(",");
            int len = loc.length;
            if (frequency.get(loc[len - 1]) == null) {
                frequency.put(loc[len - 1], 1);
            } else {
                count = frequency.get(loc[len - 1]);
                frequency.replace(loc[len - 1], ++count);
            }
        }

        Iterator<String> set = frequency.keySet().iterator();
        String place;
        while (set.hasNext()) {
            place = set.next();
            count = frequency.get(place);
            if (StringUtils.isAlphanumeric(place)) {
                List<String> res = new ArrayList<>();
                res.add(place);
                res.add(lang);
                res.add(count + "");
                locationMatrix.add(res);
            }
        }
    }

}


text:
package org.kaazing.netx.http.internal;

import static java.util.Arrays.asList;

import java.io.IOException;
import java.net.URI;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.Collection;
import java.util.List;

import org.kaazing.netx.URLConnectionHelperSpi;

public final class HttpsURLConnectionHelper extends URLConnectionHelperSpi {

    private static final List<String> SUPPORTED_PROTOCOLS = asList("https");

    @Override
    public URLStreamHandler newStreamHandler() throws IOException {
        return new HttpsURLStreamHandler();
    }

    @Override
    public URLConnection openConnection(URI location) throws IOException {
        assert SUPPORTED_PROTOCOLS.contains(location.getScheme());
        return new HttpURLConnectionImpl(location.toURL());
    }

    @Override
    public Collection<String> getSupportedProtocols() {
        return SUPPORTED_PROTOCOLS;
    }

}


text:
import unittest
import numpy as np
from scipy.linalg import norm

from .channel_state import (
    amplitude_damping_channel,
    dephasing_channel,
    depolarizing_channel,
)

class ChannelTest(unittest.TestCase):

    def setUp(self):
        """Initialize a few density matrices"""
        zero_state = np.array([[1], [0]], dtype=complex)
        one_state = np.array([[0], [1]], dtype=complex)
        one_one_state = np.kron(one_state, one_state)
        zero_zero_state = np.kron(zero_state, zero_state)
        cat_state = 1. / np.sqrt(2) * (zero_zero_state + one_one_state)

        self.density_matrix = np.dot(one_one_state, one_one_state.T)
        self.cat_matrix = np.dot(cat_state, cat_state.T)

    def test_amplitude_damping(self):
        """Test amplitude damping on a simple qubit state"""

        # With probability 0
        test_density_matrix = (amplitude_damping_channel(
            self.density_matrix, 0, 1))
        self.assertAlmostEqual(norm(self.density_matrix - test_density_matrix),
                               0.0)

        test_density_matrix = (amplitude_damping_channel(self.density_matrix,
                                                         0,
                                                         1,
                                                         transpose=True))
        self.assertAlmostEqual(norm(self.density_matrix - test_density_matrix),
                               0.0)

        # With probability 1
        correct_density_matrix = np.zeros((4, 4), dtype=complex)
        correct_density_matrix[2, 2] = 1

        test_density_matrix = (amplitude_damping_channel(
            self.density_matrix, 1, 1))

        self.assertAlmostEqual(
            norm(correct_density_matrix - test_density_matrix), 0.0)

    def test_dephasing(self):
        """Test dephasing on a simple qubit state"""

        # Check for identity on |11> state
        test_density_matrix = (dephasing_channel(self.density_matrix, 1, 1))
        self.assertAlmostEqual(norm(self.density_matrix - test_density_matrix),
                               0.0)

        test_density_matrix = (dephasing_channel(self.density_matrix,
                                                 1,
                                                 1,
                                                 transpose=True))

        correct_matrix = np.array([[0., 0., 0., 0.], [0., 0., 0., 0.],
                                   [0., 0., 0.5, -0.5], [0., 0., -0.5, 1.]])
        self.assertAlmostEqual(norm(correct_matrix - test_density_matrix), 0.0)

        # Check for correct action on cat state
        # With probability = 0
        test_density_matrix = (dephasing_channel(self.cat_matrix, 0, 1))
        self.assertAlmostEqual(norm(self.cat_matrix - test_density_matrix), 0.0)
        # With probability = 1

        correct_matrix = np.array([[0.50, 0.25, 0.00, 0.00],
                                   [0.25, 0.25, 0.00, -0.25],
                                   [0.00, 0.00, 0.00, 0.00],
                                   [0.00, -0.25, 0.00, 0.50]])
        test_density_matrix = (dephasing_channel(self.cat_matrix, 1, 1))
        self.assertAlmostEqual(norm(correct_matrix - test_density_matrix), 0.0)

    def test_depolarizing(self):
        """Test depolarizing on a simple qubit state"""

        # With probability = 0
        test_density_matrix = (depolarizing_channel(self.cat_matrix, 0, 1))
        self.assertAlmostEqual(norm(self.cat_matrix - test_density_matrix), 0.0)

        test_density_matrix = (depolarizing_channel(self.cat_matrix,
                                                    0,
                                                    1,
                                                    transpose=True))
        self.assertAlmostEqual(norm(self.cat_matrix - test_density_matrix), 0.0)

        # With probability 1 on both qubits
        correct_density_matrix = (np.array(
            [[0.27777778, 0.00000000, 0.00000000, 0.05555556],
             [0.00000000, 0.22222222, 0.00000000, 0.00000000],
             [0.00000000, 0.00000000, 0.22222222, 0.00000000],
             [0.05555556, 0.00000000, 0.00000000, 0.27777778]]))

        test_density_matrix = (depolarizing_channel(self.cat_matrix, 1, 0))
        test_density_matrix = (depolarizing_channel(test_density_matrix, 1, 1))

        self.assertAlmostEqual(norm(correct_density_matrix -
                                    test_density_matrix),
                               0.0,
                               places=6)

        # Depolarizing channel should be self-adjoint
        test_density_matrix = (depolarizing_channel(self.cat_matrix,
                                                    1,
                                                    0,
                                                    transpose=True))
        test_density_matrix = (depolarizing_channel(test_density_matrix,
                                                    1,
                                                    1,
                                                    transpose=True))

        self.assertAlmostEqual(norm(correct_density_matrix -
                                    test_density_matrix),
                               0.0,
                               places=6)

        # With probability 1 for total depolarization
        correct_density_matrix = np.eye(4) / 4.0
        test_density_matrix = (depolarizing_channel(self.cat_matrix, 1, 'All'))
        self.assertAlmostEqual(norm(correct_density_matrix -
                                    test_density_matrix),
                               0.0,
                               places=6)

    def test_verification(self):
        """Verify basic sanity checking on inputs"""
        with self.assertRaises(ValueError):
            _ = amplitude_damping_channel(self.density_matrix, 2, 1)

        with self.assertRaises(ValueError):
            _ = amplitude_damping_channel(self.density_matrix, 0.5, 3)

        with self.assertRaises(ValueError):
            bad_density = np.zeros((3, 4))
            _ = amplitude_damping_channel(bad_density, 0.5, 3)


text:
import { plainToClass } from 'class-transformer';

import { Injectable, OnDestroy } from '@angular/core';
import { JwtHelper } from 'angular2-jwt';
import { MadameService } from '@strictd/madame/dist/madame-service';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';

import { Subscription } from 'rxjs/Subscription';
import { ILogin, ILoginResponse, ILoginToken } from '../models/i-login';

import { ConfigApp } from '../../config/config.app';
import { ProfileApp } from '../../config/profile.app';

import 'rxjs/add/operator/share';
import 'rxjs/add/operator/map';

@Injectable()
export class LoginService {
  madame: MadameService;
  runningLogin = false;

  constructor(
    _config: ConfigApp,
    _madame: MadameService,
  ) {
    this.madame = _madame;
    _madame.setServer('main', _config.madameService());
  }

  doLogin(login_info: ILogin): Promise<string> {
    return new Promise((resolve, reject) => {
      this.madame.
          post('sessions/create', login_info).
          map(res => plainToClass(ILoginResponse, res as Object)).
          subscribe(
      (resp: ILoginResponse) => {
        const dataSet = plainToClass(ILoginToken, JSON.parse(resp._body) as Object);

        if (typeof dataSet.id_token !== 'undefined') {
          LoginCmd._loggedInObserver.next(dataSet.id_token);
          resolve(dataSet.id_token);
        } else {
          reject('');
        }
      });
    });
  }

  doLogoff() {
    localStorage.removeItem('jwt');
  }

}

@Injectable()
export class LoginCmd implements OnDestroy {
  static _loggedInObserver: Observer<any>;
  static _loggedInObservable = new Observable((observer: Observer<any>) => {
   LoginCmd._loggedInObserver = observer; // Assign to static App._loggedInObserver
  }).share();

  static _loggedOutObserver: Observer<any>;
  static _loggedOutObservable = new Observable((observer: Observer<any>) => {
   LoginCmd._loggedOutObserver = observer; // Assign to static App._loggedOutObserver
  }).share();

  static _forceLoginObserver: Observer<any>;
  static _forceLoginObservable = new Observable((observer: Observer<any>) => {
   LoginCmd._forceLoginObserver = observer; // Assign to static
                                       // App._loggedOutObserver
  }).share();

  tokenLogin: Subscription;
  localAppLogout: Subscription;
  localForceLogin: Subscription;

  constructor(_profile: ProfileApp, _jwt: JwtHelper) {
    // Set Token on login
    this.tokenLogin = LoginCmd._loggedInObservable.subscribe(
      (_token: string) => {}
    );
    // this.socket.openSocket('main', decoded);

    this.localAppLogout = LoginCmd._loggedOutObservable.subscribe(
      () => _profile.token = ''
    );

    this.localForceLogin = LoginCmd._forceLoginObservable.subscribe(
      (_token: string) => {}
    );
  }

  ngOnDestroy() {
    this.tokenLogin.unsubscribe();
    this.localAppLogout.unsubscribe();
    this.localForceLogin.unsubscribe();

    LoginCmd._loggedInObserver.complete();
    LoginCmd._loggedOutObserver.complete();
    LoginCmd._forceLoginObserver.complete();
  }
}


text:
using System.Collections.Generic;
using System.Windows.Forms;
using Greet.DataStructureV4.Interfaces;
using System;

namespace Example1.UI
{
    internal partial class ResultsControl : UserControl
    {
        /// <summary>
        /// Hard-coded "Greenhouse Gases" group ID
        /// </summary>
        const int ghgGroupID = 1;

        public ResultsControl()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Invoked when a pathway is selected in order to represent the life cycle results
        /// for the product produced by this pathway and defined as it's main output (which is
        /// equivalent to the main output of the last process in the pathway)
        /// </summary>
        /// <param name="name">Name of the pathway, will simply be displayed as is</param>
        /// <param name="results">Result object from the pathway for the desired productID</param>
        /// <param name="productID">ProductID represents the ID of a resource in the IData.Resources</param>
        /// <returns>Returns 0 if succeed</returns>
        public int SetResults(string name, IResults results, int productID)
        {
            //Check that the resuls object is non null
            if (results == null)
                return -1;

            //Set the label text as the name of the pathway
            this.labelName.Text = name;

            //Get an instance of the data object that we are going to use to look for a Resource
            IData data = ResultsAccess.controler.CurrentProject.Data;

            //Set the label text as the Resource.Name for the produced product of the pathway
            //i.e. If the pathway is producing Gasoline, we're going to get the Resource object using the value productID
            //which should correspond to the Gasoline resource object in the database
            if (data.Resources.KeyExists(productID))
                this.labelProduct.Text = data.Resources.ValueForKey(productID).Name;
            else
                this.labelProduct.Text = "Product ID not found: " + productID;

            //Dictionary of emission group, indexed by IEmissionGroup.Id
            //Emission groups may be created by the user and contains a couple of default group such as "Greenhouse Gases", "Criteria Pollutants"
            //In this case we are going to use the GHGs group and display the life cycle results for this pathway
            Dictionary<int, IValue> emissionGroups = results.WellToProductEmissionsGroups(ResultsAccess.controler.CurrentProject.Data);
            if (emissionGroups != null && emissionGroups.ContainsKey(ghgGroupID))
            {
                IValue quantity = emissionGroups[ghgGroupID];
                //Format the value nicely using the quantity and the unit as well as the preferences defined by the user in the main UI GREET preferences
                string GHGVal = "";
                try
                {
                    GHGVal =  ResultsAccess.controler.FormatValue(quantity.Value, quantity.UnitExpression, 0)
                    + " or " + ResultsAccess.controler.FormatValue(quantity.Value, quantity.UnitExpression, 1, false);
                }
                catch (Exception e)
                {
                    GHGVal = e.Message;
                };

                this.labelGHGs.Text = GHGVal;
            }

            //Displays the functional unit for this results, very important in order to know if we are looking at results
            //per joule of product, or per cubic meters of product, or per kilograms of prododuct
            this.labelFunctionalUnit.Text = "Per " + results.FunctionalUnit;
            //If the user wants to see results in a different functional unit, the IValue quantity must be converted to the desired functional unit

            return 0;
        }
    }
}


text:
package local.org.apache.http.impl.auth;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.ContextAwareAuthScheme;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.InvalidCredentialsException;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.CharArrayBuffer;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.Oid;

/**
 * @since 4.2
 */
public abstract class GGSSchemeBase extends AuthSchemeBase {

    enum State {
        UNINITIATED,
        CHALLENGE_RECEIVED,
        TOKEN_GENERATED,
        FAILED,
    }

    private final Log log = LogFactory.getLog(getClass());

    private final boolean stripPort;
    private final Base64 base64codec;

    /** Authentication process state */
    private State state;

    /** base64 decoded challenge **/
    private byte[] token;

    GGSSchemeBase(boolean stripPort) {
        super();
        this.base64codec = new Base64();
        this.state = State.UNINITIATED;
        this.stripPort = stripPort;
    }

    GGSSchemeBase() {
        this(false);
    }

    protected GSSManager getManager() {
        return GSSManager.getInstance();
    }

    protected byte[] generateGSSToken(
            final byte[] input, final Oid oid, final String authServer) throws GSSException {
        byte[] token = input;
        if (token == null) {
            token = new byte[0];
        }
        GSSManager manager = getManager();
        GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
        GSSContext gssContext = manager.createContext(
                serverName.canonicalize(oid), oid, null, GSSContext.DEFAULT_LIFETIME);
        gssContext.requestMutualAuth(true);
        gssContext.requestCredDeleg(true);
        return gssContext.initSecContext(token, 0, token.length);
    }

    protected abstract byte[] generateToken(
            byte[] input, final String authServer) throws GSSException;

    public boolean isComplete() {
        return this.state == State.TOKEN_GENERATED || this.state == State.FAILED;
    }

    /**
     * @deprecated (4.2) Use {@link ContextAwareAuthScheme#authenticate(Credentials, HttpRequest, org.apache.http.protocol.HttpContext)}
     */
    @Deprecated
    public Header authenticate(
            final Credentials credentials,
            final HttpRequest request) throws AuthenticationException {
        return authenticate(credentials, request, null);
    }

    @Override
    public Header authenticate(
            final Credentials credentials,
            final HttpRequest request,
            final HttpContext context) throws AuthenticationException {
        if (request == null) {
            throw new IllegalArgumentException("HTTP request may not be null");
        }
        switch (state) {
        case UNINITIATED:
            throw new AuthenticationException(getSchemeName() + " authentication has not been initiated");
        case FAILED:
            throw new AuthenticationException(getSchemeName() + " authentication has failed");
        case CHALLENGE_RECEIVED:
            try {
                String key = null;
                if (isProxy()) {
                    key = ExecutionContext.HTTP_PROXY_HOST;
                } else {
                    key = ExecutionContext.HTTP_TARGET_HOST;
                }
                HttpHost host = (HttpHost) context.getAttribute(key);
                if (host == null) {
                    throw new AuthenticationException("Authentication host is not set " +
                            "in the execution context");
                }
                String authServer;
                if (!this.stripPort && host.getPort() > 0) {
                    authServer = host.toHostString();
                } else {
                    authServer = host.getHostName();
                }

                if (log.isDebugEnabled()) {
                    log.debug("init " + authServer);
                }
                token = generateToken(token, authServer);
                state = State.TOKEN_GENERATED;
            } catch (GSSException gsse) {
                state = State.FAILED;
                if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
                        || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
                    throw new InvalidCredentialsException(gsse.getMessage(), gsse);
                if (gsse.getMajor() == GSSException.NO_CRED )
                    throw new InvalidCredentialsException(gsse.getMessage(), gsse);
                if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN
                        || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
                        || gsse.getMajor() == GSSException.OLD_TOKEN)
                    throw new AuthenticationException(gsse.getMessage(), gsse);
                // other error
                throw new AuthenticationException(gsse.getMessage());
            }
        case TOKEN_GENERATED:
            String tokenstr = new String(base64codec.encode(token));
            if (log.isDebugEnabled()) {
                log.debug("Sending response '" + tokenstr + "' back to the auth server");
            }
            return new BasicHeader("Authorization", "Negotiate " + tokenstr);
        default:
            throw new IllegalStateException("Illegal state: " + state);
        }
    }

    @Override
    protected void parseChallenge(
            final CharArrayBuffer buffer,
            int beginIndex, int endIndex) throws MalformedChallengeException {
        String challenge = buffer.substringTrimmed(beginIndex, endIndex);
        if (log.isDebugEnabled()) {
            log.debug("Received challenge '" + challenge + "' from the auth server");
        }
        if (state == State.UNINITIATED) {
            token = base64codec.decode(challenge.getBytes());
            state = State.CHALLENGE_RECEIVED;
        } else {
            log.debug("Authentication already attempted");
            state = State.FAILED;
        }
    }

}


text:
using SocialLogin.UWP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SocialLogin;
using Microsoft.WindowsAzure.MobileServices;
using SocialLogin.Helpers;
using Xamarin.Forms;

[assembly: Xamarin.Forms.Dependency(typeof(AuthenticationImpl))]
namespace SocialLogin.UWP
{
    public class AuthenticationImpl : IAuthentication
    {
        public async Task<MobileServiceUser> LoginAsync(MobileServiceClient client, MobileServiceAuthenticationProvider provider, IDictionary<string, string> parameters = null)
        {
            try
            {
                var user = await client.LoginAsync(provider);

                Settings.AuthToken = user?.MobileServiceAuthenticationToken ?? string.Empty;
                Settings.UserId = user?.UserId;

                return user;
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using XmlDoc2CmdletDoc.Core.Comments;
using XmlDoc2CmdletDoc.Core.Domain;

namespace XmlDoc2CmdletDoc.Core.Extensions
{
    ///
    /// Extension methods for <see cref="ICommentReader"/>.
    ///
    public static class CommentReaderExtensions
    {
        private static readonly XNamespace mshNs = XNamespace.Get("http://msh");
        private static readonly XNamespace mamlNs = XNamespace.Get("http://schemas.microsoft.com/maml/2004/10");
        private static readonly XNamespace commandNs = XNamespace.Get("http://schemas.microsoft.com/maml/dev/command/2004/10");
        private static readonly XNamespace devNs = XNamespace.Get("http://schemas.microsoft.com/maml/dev/2004/10");

        private static readonly IXmlNamespaceResolver resolver;

        static CommentReaderExtensions()
        {
            var manager = new XmlNamespaceManager(new NameTable());
            manager.AddNamespace("", mshNs.NamespaceName);
            manager.AddNamespace("maml", mamlNs.NamespaceName);
            manager.AddNamespace("command", commandNs.NamespaceName);
            manager.AddNamespace("dev", devNs.NamespaceName);
            resolver = manager;
        }

        ///
        /// Obtains a <maml:description> element for a cmdlet's synopsis.
        ///
        /// <param name="commentReader">The comment reader.</param>
        /// <param name="command">The command.</param>
        /// <param name="reportWarning">Used to record warnings.</param>
        /// <returns>A description element for the cmdlet's synopsis.</returns>
        public static XElement GetCommandSynopsisElement(this ICommentReader commentReader, Command command, ReportWarning reportWarning)
        {
            var cmdletType = command.CmdletType;
            var commentsElement = commentReader.GetComments(cmdletType);
            return GetMamlDescriptionElementFromXmlDocComment(commentsElement, "synopsis", warningText => reportWarning(cmdletType, warningText));
        }

        ///
        /// Obtains a <maml:description> element for a cmdlet's full description.
        ///
        /// <param name="commentReader">The comment reader.</param>
        /// <param name="command">The command.</param>
        /// <param name="reportWarning">Used to record warnings.</param>
        /// <returns>A description element for the cmdlet's full description.</returns>
        public static XElement GetCommandDescriptionElement(this ICommentReader commentReader, Command command, ReportWarning reportWarning)
        {
            var cmdletType = command.CmdletType;
            var commentsElement = commentReader.GetComments(cmdletType);
            return GetMamlDescriptionElementFromXmlDocComment(commentsElement, "description", warningText => reportWarning(cmdletType, warningText));
        }

        ///
        /// Obtains a <command:examples> element for a cmdlet's examples.
        ///
        /// <param name="commentReader">The comment reader.</param>
        /// <param name="command">The command.</param>
        /// <param name="reportWarning">Used to log any warnings.</param>
        /// <returns>An examples element for the cmdlet.</returns>
        public static XElement GetCommandExamplesElement(this ICommentReader commentReader, Command command, ReportWarning reportWarning)
        {
            var cmdletType = command.CmdletType;
            var comments = commentReader.GetComments(cmdletType);
            if (comments == null)
            {
                reportWarning(cmdletType, "No XML doc comment found.");
                return null;
            }

            var xmlDocExamples = comments.XPathSelectElements("//example").ToList();
            if (!xmlDocExamples.Any())
            {
                reportWarning(cmdletType, "No examples found.");
                return null;
            }

            var examples = new XElement(commandNs + "examples");
            int exampleNumber = 1;
            foreach (var xmlDocExample in xmlDocExamples)
            {
                var example = GetCommandExampleElement(xmlDocExample, exampleNumber, warningText => reportWarning(cmdletType, warningText));
                if (example != null)
                {
                    examples.Add(example);
                    exampleNumber++;
                }
            }
            return exampleNumber == 1 ? null : examples;
        }

        ///
        /// Obtains a <command:example> element based on an <example> XML doc comment element.
        ///
        /// <param name="exampleElement">The XML doc comment example element.</param>
        /// <param name="exampleNumber">The number of the example.</param>
        /// <param name="reportWarning">Used to log any warnings.</param>
        /// <returns>An example element.</returns>
        private static XElement GetCommandExampleElement(XElement exampleElement, int exampleNumber, Action<string> reportWarning)
        {
            var items = exampleElement.XPathSelectElements("para | code").ToList();
            var intros = items.TakeWhile(x => x.Name == "para").ToList();
            var code = items.SkipWhile(x => x.Name == "para").TakeWhile(x => x.Name == "code").FirstOrDefault();
            var paras = items.SkipWhile(x => x.Name == "para").SkipWhile(x => x.Name == "code").ToList();

            var example = new XElement(commandNs + "example",
                           new XElement(mamlNs + "title", string.Format("----------  EXAMPLE {0}  ----------", exampleNumber)));

            bool isEmpty = true;
            if (intros.Any())
            {
                var introduction = new XElement(mamlNs + "introduction");
                intros.ForEach(intro => introduction.Add(new XElement(mamlNs + "para", Tidy(intro.Value))));
                example.Add(introduction);
                isEmpty = false;
            }
            if (code != null)
            {
                example.Add(new XElement(devNs + "code", TidyCode(code.Value)));
                isEmpty = false;
            }
            if (paras.Any())
            {
                var remarks = new XElement(devNs + "remarks");
                paras.ForEach(para => remarks.Add(new XElement(mamlNs + "para", Tidy(para.Value))));
                example.Add(remarks);
                isEmpty = false;
            }

            if (isEmpty)
            {
                reportWarning(string.Format("No para or code elements found for example {0}.", exampleNumber));
            }

            return example;
        }

        ///
        /// Obtains a <command:relatedLinks> element for a cmdlet's related links.
        ///
        /// <param name="commentReader">The comment reader.</param>
        /// <param name="command">The command.</param>
        /// <param name="reportWarning">Used to log any warnings.</param>
        /// <returns>An relatedLinks element for the cmdlet.</returns>
        public static XElement GetCommandRelatedLinksElement(this ICommentReader commentReader, Command command, ReportWarning reportWarning)
        {
            var cmdletType = command.CmdletType;
            var comments = commentReader.GetComments(cmdletType);
            if (comments == null)
            {
                return null;
            }

            var paras = comments.XPathSelectElements("//para[@type='link']").ToList();
            if (!paras.Any()) return null;

            var relatedLinks = new XElement(mamlNs + "relatedLinks");
            foreach (var para in paras)
            {
                var navigationLink = new XElement(mamlNs + "navigationLink",
                                                  new XElement(mamlNs + "linkText", para.Value));
                var uri = para.Attribute("uri");
                if (uri != null)
                {
                    navigationLink.Add(new XElement(mamlNs + "uri", uri.Value));
                }
                relatedLinks.Add(navigationLink);
            }
            return relatedLinks;
        }

        ///
        /// Obtains a <maml:alertSet> element for a cmdlet's notes.
        ///
        /// <param name="commentReader">The comment reader.</param>
        /// <param name="command">The command.</param>
        /// <param name="reportWarning">Used to log any warnings.</param>
        /// <returns>A <maml:alertSet> element for the cmdlet's notes.</returns>
        public static XElement GetCommandAlertSetElement(this ICommentReader commentReader, Command command, ReportWarning reportWarning)
        {
            var cmdletType = command.CmdletType;
            var comments = commentReader.GetComments(cmdletType);
            if (comments == null)
            {
                return null;
            }

            // First see if there's an alertSet element in the comments
            var alertSet = comments.XPathSelectElement("//maml:alertSet", resolver);
            if (alertSet != null)
            {
                return alertSet;
            }

            // Next, search for a list element of type alertSet.
            var list = comments.XPathSelectElement("//list[@type='alertSet']");
            if (list == null)
            {
                return null;
            }
            alertSet = new XElement(mamlNs + "alertSet");
            foreach (var item in list.XPathSelectElements("item"))
            {
                var term = item.XPathSelectElement("term");
                var description = item.XPathSelectElement("description");
                if (term != null && description != null)
                {
                    var alertTitle = new XElement(mamlNs + "title", Tidy(term.Value));

                    var alert = new XElement(mamlNs + "alert");
                    var paras = description.XPathSelectElements("para").ToList();
                    if (paras.Any())
                    {
                        paras.ForEach(para => alert.Add(new XElement(mamlNs + "para", Tidy(para.Value))));
                    }
                    else
                    {
                        alert.Add(new XElement(mamlNs + "para", Tidy(description.Value)));
                    }

                    alertSet.Add(alertTitle, alert);
                }
            }
            return alertSet;
        }

        ///
        /// Obtains a <maml:description> element for a parameter.
        ///
        /// <param name="commentReader">The comment reader.</param>
        /// <param name="parameter">The parameter.</param>
        /// <param name="reportWarning">Used to record warnings.</param>
        /// <returns>A description element for the parameter.</returns>
        public static XElement GetParameterDescriptionElement(this ICommentReader commentReader, Parameter parameter, ReportWarning reportWarning)
        {
            var memberInfo = parameter.MemberInfo;
            var commentsElement = commentReader.GetComments(memberInfo);
            return GetMamlDescriptionElementFromXmlDocComment(commentsElement, "description", warningText => reportWarning(memberInfo, warningText));
        }

        ///
        ///
        ///
        /// <param name="commentReader">The comment reader.</param>
        /// <param name="parameter">The parameter.</param>
        /// <param name="reportWarning">Used to record warnings.</param>
        /// <returns>A description element for the parameter.</returns>
        public static XElement GetParameterValueElement(this ICommentReader commentReader, Parameter parameter, ReportWarning reportWarning)
        {
            return new XElement(commandNs + "parameterValue",
                                new XAttribute("required", true),
                                GetSimpleTypeName(parameter.ParameterType));
        }

        ///
        /// Obtains a <dev:defaultValue> element for a parameter.
        ///
        /// <param name="commentReader">The comment reader.</param>
        /// <param name="parameter">The parameter.</param>
        /// <returns>A default value element for the parameter's default value, or null if a default value could not be obtained.</returns>
        public static XElement GetParameterDefaultValueElement(this ICommentReader commentReader, Parameter parameter)
        {
            var defaultValue = parameter.DefaultValue; // TODO: Get the default value from the doc comments?
            if (defaultValue != null)
            {
                return new XElement(devNs + "defaultValue", defaultValue.ToString());
            }
            return null;
        }

        ///
        /// Obtains a <maml:description> for an <command:inputType> coresponding to a specified parameter that accepts pipeline input.
        ///
        /// <param name="commentReader">The comment reader.</param>
        /// <param name="parameter">The parameter.</param>
        /// <param name="reportWarning">Used to log any warnings.</param>
        /// <returns>A <maml:description> for an <command:inputType> for the parameter, or null if no explicit description is available
        /// for the input type.</returns>
        public static XElement GetInputTypeDescriptionElement(this ICommentReader commentReader, Parameter parameter, ReportWarning reportWarning)
        {
            var parameterMemberInfo = parameter.MemberInfo;
            var commentsElement = commentReader.GetComments(parameterMemberInfo);

            // First try to read the explicit inputType description.
            var inputTypeDescription = GetMamlDescriptionElementFromXmlDocComment(commentsElement, "inputType", _ => { });
            if (inputTypeDescription != null)
            {
                return inputTypeDescription;
            }

            // Then fall back to using the parameter description.
            var parameterDescription = commentReader.GetParameterDescriptionElement(parameter, reportWarning);
            if (parameterDescription == null)
            {
                reportWarning(parameterMemberInfo, "No inputType comment found and no fallback description comment found.");
            }
            return parameterDescription;
        }

        public static XElement GetOutputTypeDescriptionElement(this ICommentReader commentReader,
                                                               Command command,
                                                               Type outputType,
                                                               ReportWarning reportWarning)
        {
            // TODO: Get the description from the <remarks type="outputType" cref="<type>"> element
            return commentReader.GetTypeDescriptionElement(outputType, reportWarning);
        }

        ///
        /// Obtains a <maml:description> element for a type.
        ///
        /// <param name="commentReader">The comment reader.</param>
        /// <param name="type">The type for which a description is required.</param>
        /// <param name="reportWarning">Used to log any warnings.</param>
        /// <returns>A description for the type, or null if no description is available.</returns>
        public static XElement GetTypeDescriptionElement(this ICommentReader commentReader, Type type, ReportWarning reportWarning)
        {
            var commentsElement = commentReader.GetComments(type);
            return GetMamlDescriptionElementFromXmlDocComment(commentsElement, "description", warningText => reportWarning(type, warningText));
        }

        ///
        /// Helper method to retrieve the XML doc commments from a <see cref="MemberInfo"/> that represents either a property or a field.
        ///
        /// <param name="commentReader">The comment reader.</param>
        /// <param name="memberInfo">The member whose comments are to be retrieved.</param>
        /// <param name="reportWarning">Used to log any warnings.</param>
        /// <returns>The XML doc commments for the <paramref name="memberInfo"/>, ornull if they are not available.</returns>
        private static XElement GetComments(this ICommentReader commentReader, MemberInfo memberInfo)
        {
            switch (memberInfo.MemberType)
            {
                case MemberTypes.Field:
                    return commentReader.GetComments((FieldInfo) memberInfo);

                case MemberTypes.Property:
                    return commentReader.GetComments((PropertyInfo) memberInfo);

                default:
                    throw new NotSupportedException("Member type not supported: " + memberInfo.MemberType);
            }
        }

        ///
        /// Obtains a <maml:description> from an XML doc comment.
        ///
        /// <param name="commentsElement">The XML doc comments element as retrieved from an <see cref="ICommentReader"/>. May be <c>null</c>.</param>
        /// <param name="typeAttribute">
        /// <para>An identifier used to select specific content from the XML doc comment.</para>
        /// <para>The first <maml:description> element with a type="<<paramref name="typeAttribute"/>>"
        /// attribute will be used to provide the description (where <<paramref name="typeAttribute"/>> is the value of the
        /// <paramref name="typeAttribute"/> parameter).</para>
        /// <para>Alternatively, the XML Doc comments may contain multiple <para> elements. Those
        /// with the type="<<paramref name="typeAttribute"/>>" attribute will be used to provide content for the description.</para>
        /// </param>
        /// <param name="reportWarning">Used to log any warnings.</param>
        /// <returns>A description element derived from the XML doc comment, or null if a description could not be obtained.</returns>
        private static XElement GetMamlDescriptionElementFromXmlDocComment(XElement commentsElement, string typeAttribute, Action<string> reportWarning)
        {
            if (commentsElement != null)
            {
                // Examine the XML doc comment first for an embedded <maml:description> element.
                var mamlDescriptionElement = commentsElement.XPathSelectElement(string.Format(".//maml:description[@type='{0}']", typeAttribute), resolver);
                if (mamlDescriptionElement != null)
                {
                    mamlDescriptionElement = new XElement(mamlDescriptionElement); // Deep clone the element, as we're about to modify it.
                    mamlDescriptionElement.RemoveAttributes(); // Intended to remove the xmlns:maml namespace declaration and id attribute. Assumes there aren't any further attributes.
                    return mamlDescriptionElement;
                }

                // Next try <para type="typeAttribute"> elements.
                var paraElements = commentsElement.XPathSelectElements(string.Format(".//para[@type='{0}']", typeAttribute)).ToList();
                if (paraElements.Any())
                {
                    var descriptionElement = new XElement(mamlNs + "description");
                    paraElements.ForEach(para => descriptionElement.Add(new XElement(mamlNs + "para", Tidy(para.Value))));
                    return descriptionElement;
                }
            }

            // We've failed to provide a description from the XML doc commment.
            reportWarning(string.Format("No {0} comment found.", typeAttribute));
            return null;
        }

        ///
        /// Tidies up the text retrieved from an XML doc comment. Multiple whitespace characters, including CR/LF,
        /// are replaced with a single space, and leading and trailing whitespace is removed.
        ///
        /// <param name="value">The string to tidy.</param>
        /// <returns>The tidied string.</returns>
        private static string Tidy(string value)
        {
            return new Regex(@"\s{2,}").Replace(value, " ").Trim();
        }

        private static string TidyCode(string value)
        {
            // Split the value into separate lines, and eliminate leading and trailing empty lines.
            IEnumerable<string> lines = value.Split(new[] {"\r\n", "\n"}, StringSplitOptions.None)
                             .SkipWhile(string.IsNullOrWhiteSpace)
                             .Reverse()
                             .SkipWhile(string.IsNullOrWhiteSpace)
                             .Reverse()
                             .ToList();

            // If all of the non-empty lines start with leading whitespace, remove it. (i.e. dedent the code).
            var pattern = new Regex(@"^\s*");
            var nonEmptyLines = lines.Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
            if (nonEmptyLines.Any())
            {
                var shortestPrefixLength = nonEmptyLines.Min(s => pattern.Match(s).Value.Length);
                if (shortestPrefixLength > 0)
                {
                    lines = lines.Select(s => s.Length <= shortestPrefixLength ? "" : s.Substring(shortestPrefixLength));
                }
            }

            return string.Join(Environment.NewLine, lines);
        }

        private static string GetSimpleTypeName(Type type)
        {
            if (type.IsArray)
            {
                return GetSimpleTypeName(type.GetElementType()) + "[]";
            }

            string result;
            if (PredefinedSimpleTypeNames.TryGetValue(type, out result))
            {
                return result;
            }
            return type.Name;
        }

        private static readonly IDictionary<Type, string> PredefinedSimpleTypeNames =
            new Dictionary<Type, string>
            {
                {typeof(object), "object"},
                {typeof(string), "string"},
                {typeof(bool), "bool"},
                {typeof(byte), "byte"},
                {typeof(char), "char"},
                {typeof(short), "short"},
                {typeof(ushort), "ushort"},
                {typeof(int), "int"},
                {typeof(uint), "uint"},
                {typeof(long), "long"},
                {typeof(ulong), "ulong"},
                {typeof(float), "float"},
                {typeof(double), "double"},
            };
    }
}