text:
package org.kuali.kra.award.awardhierarchy.sync;

import org.kuali.rice.krad.bo.PersistableBusinessObject;

import java.io.Serializable;

/**
 * DTO bean for saving pending sync changes to build and persist after
 * a document save.
 */
public class AwardSyncPendingChangeBean implements Serializable {

    private static final long serialVersionUID = -7950844997053979351L;
    private AwardSyncType syncType;
    private PersistableBusinessObject object;
    private String attrName;
    private String awardAttr;

    public AwardSyncPendingChangeBean() {

    }

    public AwardSyncPendingChangeBean(AwardSyncType syncType, PersistableBusinessObject object, String awardAttr, String attrName) {
        this.syncType = syncType;
        this.object = object;
        this.attrName = attrName;
        this.awardAttr = awardAttr;
    }

    public AwardSyncPendingChangeBean(AwardSyncType syncType, PersistableBusinessObject object, String awardAttr) {
        this.syncType = syncType;
        this.object = object;
        this.attrName = null;
        this.awardAttr = awardAttr;
    }

    public AwardSyncType getSyncType() {
        return syncType;
    }
    public void setSyncType(AwardSyncType syncType) {
        this.syncType = syncType;
    }
    public PersistableBusinessObject getObject() {
        return object;
    }
    public void setObject(PersistableBusinessObject object) {
        this.object = object;
    }
    public String getAttrName() {
        return attrName;
    }
    public void setAttrName(String attrName) {
        this.attrName = attrName;
    }
    public String getAwardAttr() {
        return awardAttr;
    }
    public void setAwardAttr(String awardAttr) {
        this.awardAttr = awardAttr;
    }
}


text:
jQuery(function($){

  // Contextual buttons
  $('#toolbar ul.buttons li.contextual').css('display', 'inline');
  function editSelected() {
    document.location = $('#navigation').data('edit_url');
    return false;
  };
  function deleteSelected() {
    if (confirm(delete_message))
    {
      var id = $("#navigation").data('blog_id');
      $.post(delete_url, {'id' : id }, function() {
        $('#blog_' + id).slideUp();
      });
    }
  };

  // Filters
  $('#navigation .level1.blog a').live('click', function(e) {
    $('#preview').html('');
    $('#tree_filter .selected').removeClass('selected');
    $(this).addClass('selected');
    $("#navigation")
      .data('blog_id',  $.getQueryParameter(this.href, 'id'))
      .data('edit_url', this.href);
    $('#toolbar ul.buttons li.contextual').addClass('active');
    $('#toolbar ul.buttons li.blog_edit a').click(editSelected);
    $('#toolbar ul.buttons li.blog_delete a').click(deleteSelected);
    $('#preview').load(preview_url + '?id=' + $("#navigation").data('blog_id'));
    return false;
  });
  $('#navigation .level0 a').click(function() {
    $('#tree_filter .selected').removeClass('selected');
    $("#navigation")
      .data('blog_id',  null)
      .data('edit_url', null);
    $('#toolbar ul.buttons li.contextual').removeClass('active');
    $('#toolbar ul.buttons li.blog_edit a').unbind('click', editSelected);
    $('#toolbar ul.buttons li.blog_delete a').unbind('click', deleteSelected);
    return false;
  });
  $('#navigation .level1.blog a').live('dblclick', function(e) {
    document.location = this.href;
  });
});

redpajama_set_name: RedPajamaGithub


text:
package com.cqu.draggablelinearlistview.sample;

import java.lang.reflect.Field;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.ViewConfiguration;

public abstract class BaseActionBarActivity extends ActionBarActivity{

	protected ActionBar mActionBar = null;

	protected Cursor mCursor = null;

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

		/**
		 *	隐藏物理菜单键
		 *	以便多余的菜单项能全部显示在ActionBar上
		 */
		try {
			ViewConfiguration mconfig = ViewConfiguration.get(this);
			Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
			if(menuKeyField != null) {
				menuKeyField.setAccessible(true);
				menuKeyField.setBoolean(mconfig, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		mActionBar = getSupportActionBar();

	}

	/**
	 *	设置ActionBarHome键的可用性
	 * @param enable
	 */
	protected void setActionBarHomeEnable( boolean enable ){
		mActionBar.setDisplayHomeAsUpEnabled(enable);
	}

	/**
	 *	ActionBar上的Home键被按下的回调
	 * @return	true 表示事件被消费
	 */
	protected abstract boolean onHomeKeyDown();

	@Override
	public final boolean onOptionsItemSelected(MenuItem item) {
		switch( item.getItemId() ){
			case android.R.id.home:
				onHomeKeyDown();
				return true;
		}
		return onOptionsItemSelected(item, 0);
	}

	/**
	 *	覆盖并设置原方法为终态,可避免被子类重复处理相同的事件
	 *	子类若需监听别的菜单点击事件,覆写本方法即可
	 * @param item
	 * @param flag
	 * @return
	 */
	public boolean onOptionsItemSelected(MenuItem item, int flag){
		return super.onOptionsItemSelected(item);
	}

	/**
	 *	Back键按下回调事件
	 * @return	true 表示事件被消费
	 */
	protected abstract boolean onBackKeyDown();

	/**
	 *	Menu键按下的回调事件,各子类Activity可根据需要自行覆写该方法即可
	 * @return
	 */
	protected boolean onMenuKeyDown(){
		return false;
	}

	@Override
	public final boolean onKeyDown(int keyCode, KeyEvent event) {
		switch( keyCode ){
			case KeyEvent.KEYCODE_BACK:
				if( onBackKeyDown() ){
					return true;
				}
				break;
			case KeyEvent.KEYCODE_MENU:
				if( onMenuKeyDown() ){
					return true;
				}
				break;
			default:
				break;
		}
		return onKeyDown(keyCode, event, 0);
	}

	/**
	 *	类似于{@see #onOptionsItemSelected(MenuItem, int)}方法
	 * @param keyCode
	 * @param event
	 * @param flag
	 * @return
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event, int flag){
		return super.onKeyDown(keyCode, event);
	}

	/**
	 *	简单的打开一个新的Activity,并传入必要的参数
	 * @param target
	 * @param enterAnim
	 * @param exitAnim
	 * @param isFinish
	 * @param mBundle	可为空
	 */
	protected void startNewActivity( Class<? extends Activity> target, int enterAnim, int exitAnim, boolean isFinish, Bundle mBundle ){
		Intent mIntent = new Intent(this, target);
		if( mBundle != null ){
			mIntent.putExtras(mBundle);
		}
		startActivity(mIntent);
		overridePendingTransition(enterAnim, exitAnim);
		if( isFinish ){
			finish();
		}
	}

}


text:
// ☱☲☴ Images production

var gulp            = require('gulp');
var config          = require('../config.json');
var plumber         = require('gulp-plumber');

// Copy images into dist folder

gulp.task('images-production', function () {
    gulp.src([config.srcDir + 'images/**/*'])
        .pipe(plumber())
        .pipe(gulp.dest(config.distDir + 'images'));
});


text:
layout: post
title: 'Paper: Brain: Biomedical Knowledge Manipulation'
date: '2013-03-23T16:46:00.004Z'
author: John Overington
tags:
- Books and Papers
modified_time: '2013-03-23T17:55:59.231Z'
thumbnail: http://1.bp.blogspot.com/-fY95FLUlLMw/UU3clyr95DI/AAAAAAAAC6k/XgoeJfO07rc/s72-c/bioinf.png
blogger_id: tag:blogger.com,1999:blog-2546008714740235720.post-6521877784421126944
blogger_orig_url: http://chembl.blogspot.com/2013/03/paper-brain-biomedical-knowledge.html
---

There's a paper just out from Samuel, one of the PhD students in the group - the link to the Open Access paper is here. Brain is a Java software library facilitating the manipulation
and creation of ontologies and knowledge bases represented with the
Web Ontology Language (OWL).

%A S. Croset
%A J.P. Overington
%A D. Rebholz-Schuhman
%D 2013
%T Brain: Biomedical Knowledge Manipulation
%J Bioinformatics
%V 29
%O DOI:10.1093/bioinformatics/btt109
%O PMID:23505292


text:
class Upload < ApplicationRecord
  VALID_CONTENT_TYPES = [
    "application/pdf",
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/msword",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "image/jpeg",
    "image/gif",
    "image/png",
    "text/plain"
  ].freeze

  UPLOAD_CATEGORIES = {
    "W-9 from Landlord" => "W-9 from Landlord",
    "Lease Agreement" => "Relevant pages of lease (pages that show name of
        lessees, rental amount, security deposit amount, rental dates, and
        signatures of lessees and payee).  If a lease has not been signed,
        an Acknowledgement to Rent can be submitted in lieu of a lease.",
    "Verification of Owed Amounts" => "Verification of owed costs
        (3-Day Notice or other written verification of exactly what
        lessee owes)",
    "Verification of Income" => "Verification of income for every
        adult (pay stubs, letter verifying employment, benefits award
        letter, etc)",
    "Verification of Crisis" => "Verification of crisis (car repair
        bill, copy of no-fault notice to vacate, verification of illness)",
    "Grant Request Amount" => "Document supporting the remaining amount
        needs to be covered is less than the total amount."
  }.freeze

  belongs_to :user, polymorphic: true
  has_attached_file :file
  validates_attachment :file,
                       presence: true,
                       size: { in: 0..2.megabytes },
                       content_type: { content_type: VALID_CONTENT_TYPES }

  validates :user, presence: { if: :new_record? }
  validates :user, presence: { if: :user_id_changed? }
  validates :user, presence: { if: :user_type_changed? }
end


text:
<?xml version="1.0" encoding="UTF-8"?>
	<databaseChangeLog
		xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
		http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">

	<!-- US 127 -->

	    <changeSet author="mat_dev_user" id="1" context="prod">
	        <sql>
	        INSERT INTO `QDM_ATTRIBUTES` VALUES ('1001', 'Facility Location', 19, 'Data Type');

	    <!--    DATA_TYPE_ID, Description, CATAEBORY_ID -->
	    <!--    19, 'Diagnostic Study, Performed', 6 -->

	        </sql>
	    </changeSet>

	</databaseChangeLog>


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Foundatio.Caching;
using Foundatio.Extensions;
using Foundatio.Jobs;
using Foundatio.Lock;
using Foundatio.Logging;
using Foundatio.Messaging;
using Foundatio.Utility;
using Xunit;

namespace Foundatio.Tests.Jobs {
    public class WithLockingJob : JobWithLockBase {
        private readonly ILockProvider _locker;

        public WithLockingJob(ILoggerFactory loggerFactory) : base(loggerFactory) {
            _locker = new CacheLockProvider(new InMemoryCacheClient(loggerFactory), new InMemoryMessageBus(loggerFactory), loggerFactory);
        }

        public int RunCount { get; set; }

        protected override Task<ILock> GetLockAsync(CancellationToken cancellationToken = default(CancellationToken)){
            return _locker.AcquireAsync(nameof(WithLockingJob), TimeSpan.FromSeconds(1), TimeSpan.Zero);
        }

        protected override async Task<JobResult> RunInternalAsync(JobContext context) {
            RunCount++;

            await SystemClock.SleepAsync(150, context.CancellationToken).AnyContext();
            Assert.True(await _locker.IsLockedAsync("WithLockingJob").AnyContext());

            return JobResult.Success;
        }
    }
}


text:
#region Copyright & License

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

#endregion

using System;
using System.Diagnostics.CodeAnalysis;
using System.Xml;
using Be.Stateless.Extensions;
using Microsoft.XLANGs.BaseTypes;

namespace Be.Stateless.BizTalk.Tracking.Processing
{
	[SuppressMessage("ReSharper", "LocalizableElement")]
	public partial class ProcessingStep
	{
		/// <summary>
		/// Method intended to be called when starting a processing step in the middle of an orchestration. It is expected
		/// that a tracking context has been created previously, at the start of the orchestration by a call to <see
		/// cref="Process.Initiate(XLANGMessage)"/> or by a call to this method. A new processing step tracking activity
		/// is always started, and it is always linked to the process tracking activity identified in <paramref
		/// name="trackingContext"/>.
		/// </summary>
		/// <param name="trackingContext">
		///   The tracking context that is applicable just before entering the new processing step.
		/// </param>
		/// <param name="processingStepName">
		///   The name of the processing step entered.
		/// </param>
		/// <returns>
		/// The new <see cref="TrackingContext"/> for the processing step scope.
		/// </returns>
		public static TrackingContext Initiate(TrackingContext trackingContext, string processingStepName)
		{
			if (string.IsNullOrEmpty(processingStepName)) throw new ArgumentException("Processing step name is null or empty.", "processingStepName");
			if (trackingContext.ProcessActivityId.IsNullOrEmpty()) throw new ArgumentException("trackingContext.ProcessActivityId is null or empty: process tracking has not been initiated.", "trackingContext");

			var processingStep = new ProcessingStep();
			processingStep.BeginProcessingStepActivity();
			processingStep.BeginTime = DateTime.UtcNow;
			processingStep.MachineName = Environment.MachineName;
			processingStep.ProcessActivityID = trackingContext.ProcessActivityId;
			processingStep.Status = TrackingStatus.Pending;
			processingStep.StepName = processingStepName;
			// set up continuation for later processing step completion or failure
			processingStep.EnableContinuation();
			processingStep.CommitProcessingStepActivity();
			processingStep.EndProcessingStepActivity();

			// propagate the tracking context with this processing step's activity id
			var newTrackingContext = trackingContext;
			newTrackingContext.ProcessingStepActivityId = processingStep.ActivityId;
			return newTrackingContext;
		}

		/// <summary>
		/// Method to be called at the end of a successful orchestration processing step.
		/// </summary>
		/// <param name="trackingContext"><see cref="TrackingContext"/>
		/// Structure containing the appropriate activity identifiers.
		/// </param>
		/// <remarks>
		/// It will end the processing step activity, setting its <see cref="Status"/> to <see
		/// cref="TrackingStatus.Completed"/>, but will not end the process activity.
		/// </remarks>
		public static void Complete(TrackingContext trackingContext)
		{
			Terminate(trackingContext, TrackingStatus.Completed, null);
		}

		/// <summary>
		/// Method to be called at the end of a failed orchestration processing step.
		/// </summary>
		/// <param name="trackingContext"><see cref="TrackingContext"/>
		/// Structure containing the appropriate activity identifiers.
		/// </param>
		/// <param name="exception">
		/// The exception that causes the processing step to fail.
		/// </param>
		/// <remarks>
		/// It will end the processing step activity, setting its <see cref="Status"/> to <see
		/// cref="TrackingStatus.Failed"/>.
		/// </remarks>
		public static void Fail(TrackingContext trackingContext, Exception exception)
		{
			Terminate(trackingContext, TrackingStatus.Failed, exception.IfNotNull(e => e.ToString()));
		}

		/// <summary>
		/// Method to be called at the end of a failed orchestration processing step.
		/// </summary>
		/// <param name="trackingContext"><see cref="TrackingContext"/>
		/// Structure containing the appropriate activity identifiers.
		/// </param>
		/// <param name="faultMessage">
		/// The fault message that causes the processing step to fail.
		/// </param>
		/// <remarks>
		/// It will end the processing step activity, setting its <see cref="Status"/> to <see
		/// cref="TrackingStatus.Failed"/>.
		/// </remarks>
		public static void Fail(TrackingContext trackingContext, XLANGMessage faultMessage)
		{
			string errorDescription = null;
			if (faultMessage != null)
			{
				var faultDocument = (XmlDocument) faultMessage[0].RetrieveAs(typeof(XmlDocument));
				// TODO: extract error info from fault message
				errorDescription = faultDocument.OuterXml;
			}

			Terminate(trackingContext, TrackingStatus.Failed, errorDescription);
		}

		private static void Terminate(TrackingContext trackingContext, string status, string errorDescription)
		{
			if (trackingContext.ProcessingStepActivityId.IsNullOrEmpty()) throw new ArgumentException("trackingContext.ProcessingStepActivityId is null or empty: processing step tracking has not been initiated.", "trackingContext");

			var processingStep = new ProcessingStep(ContinuationPrefix + trackingContext.ProcessingStepActivityId) {
				EndTime = DateTime.UtcNow,
				ErrorDescription = errorDescription,
				MachineName = Environment.MachineName,
				Status = status
			};
			processingStep.CommitProcessingStepActivity();
			processingStep.EndProcessingStepActivity();
		}

		internal ProcessingStep() : this(Tracking.ActivityId.NewActivityId()) { }
	}
}


text:
layout: demo
title: pageui Demo
---

      Back

Preloader

Indicator

Preloader with Title

Loading-a(default)

Loading-b

hideLoading


text:
If you didn't go through Chapters 2-8, the simplest way to catch up is to copy data from my bucket:
* Go to the 02_ingest folder of the repo, run the program ./ingest_from_crsbucket.sh and specify your bucket name.
* Go to the 04_streaming folder of the repo, run the program ./ingest_from_crsbucket.sh and specify your bucket name.
* Create a dataset named "flights" in BigQuery by typing:
	```
	bq mk flights
	```
* Go to the 05_bqnotebook folder of the repo, run the script to load data into BigQuery:
	```
	bash load_into_bq.sh <BUCKET-NAME>
	```
* In BigQuery, run this query and save the results as a table named trainday
	```
	  #standardsql
	SELECT
	  FL_DATE,
	  IF(MOD(ABS(FARM_FINGERPRINT(CAST(FL_DATE AS STRING))), 100) < 70, 'True', 'False') AS is_train_day
	FROM (
	  SELECT
	    DISTINCT(FL_DATE) AS FL_DATE
	  FROM
	    `flights.tzcorr`)
	ORDER BY
	  FL_DATE
	```
* Go to the 08_dataflow folder of the repo, run the program ./ingest_from_crsbucket.sh and specify your bucket name.

### This Chapter
You can do it two ways: from a notebook or from CloudShell.

#### 1. From AI Platform Notebooks
* Start Cloud AI Platform Notebook instance with TensorFlow 2.1 or greater
* Open a Terminal and type:
  ``` git clone https://github.com/GoogleCloudPlatform/data-science-on-gcp```
* Browse to, and open flights_model_tf2.ipynb
* Run the code to train and deploy the model
* The above code was on a small subset of the model. To run on the full dataset, run the cells in flights_caip.ipynb

#### (Optional) From CloudShell
* Get the model to predict:
    ```
    ./call_predict.py --project=$(gcloud config get-value core/project)
    ```
* Get the model to predict, but also provide a reason:
    ```
    ./call_predict_reason.py --project=$(gcloud config get-value core/project)
    ```


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Darwiniana 16(3-4): 419 (1971)

#### Original name
Morchella herediana Gomez {?}

### Remarks
null


text:
package com.lucidchart.open.cashylive.util

import scala.concurrent.ExecutionContext
import java.util.concurrent.{Executors => JavaExecutors}

object Executors {
	/**
	 * Creates an Executor that uses a single worker thread operating off an
	 * unbounded queue.
	 */
	def singleThreadExecutor(threadNamePrefix: String) = {
		ExecutionContext.fromExecutor(
			JavaExecutors.newSingleThreadExecutor(
				new NamedThreadFactory(threadNamePrefix)
			)
		)
	}

	/**
	 * Creates a thread pool that reuses a fixed number of threads operating
	 * off a shared unbounded queue.
	 */
	def fixedThreadPool(threadPoolSize: Int, threadNamePrefix: String) = {
		ExecutionContext.fromExecutor(
			JavaExecutors.newFixedThreadPool(
				threadPoolSize,
				new NamedThreadFactory(threadNamePrefix)
			)
		)
	}

	/**
	 * Creates a thread pool that creates new threads as needed,
	 * but will reuse previously constructed threads when they are available.
	 */
	def cachedThreadPool(threadNamePrefix: String) = {
		ExecutionContext.fromExecutor(
			JavaExecutors.newCachedThreadPool(
				new NamedThreadFactory(threadNamePrefix)
			)
		)
	}

	/**
	 * Creates a single-threaded executor that can schedule commands to run
	 * after a given delay, or to execute periodically.
	 */
	def singleThreadScheduledExecutor(threadNamePrefix: String) = {
		ExecutionContext.fromExecutor(
			JavaExecutors.newSingleThreadScheduledExecutor(
				new NamedThreadFactory(threadNamePrefix)
			)
		)
	}

	/**
	 * Creates a thread pool that can schedule commands to run after a given
	 * delay, or to execute periodically.
	 */
	def scheduledThreadPool(threadPoolSize: Int, threadNamePrefix: String) = {
		ExecutionContext.fromExecutor(
			JavaExecutors.newScheduledThreadPool(
				threadPoolSize,
				new NamedThreadFactory(threadNamePrefix)
			)
		)
	}
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Diagnostics;
using JsonApiDotNetCore.Queries.Expressions;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Resources.Annotations;

namespace JsonApiDotNetCore.Queries.Internal
{
    /// <inheritdoc />
    [PublicAPI]
    public class QueryLayerComposer : IQueryLayerComposer
    {
        private readonly CollectionConverter _collectionConverter = new();
        private readonly IEnumerable<IQueryConstraintProvider> _constraintProviders;
        private readonly IResourceGraph _resourceGraph;
        private readonly IResourceDefinitionAccessor _resourceDefinitionAccessor;
        private readonly IJsonApiOptions _options;
        private readonly IPaginationContext _paginationContext;
        private readonly ITargetedFields _targetedFields;
        private readonly IEvaluatedIncludeCache _evaluatedIncludeCache;
        private readonly SparseFieldSetCache _sparseFieldSetCache;

        public QueryLayerComposer(IEnumerable<IQueryConstraintProvider> constraintProviders, IResourceGraph resourceGraph,
            IResourceDefinitionAccessor resourceDefinitionAccessor, IJsonApiOptions options, IPaginationContext paginationContext,
            ITargetedFields targetedFields, IEvaluatedIncludeCache evaluatedIncludeCache)
        {
            ArgumentGuard.NotNull(constraintProviders, nameof(constraintProviders));
            ArgumentGuard.NotNull(resourceGraph, nameof(resourceGraph));
            ArgumentGuard.NotNull(resourceDefinitionAccessor, nameof(resourceDefinitionAccessor));
            ArgumentGuard.NotNull(options, nameof(options));
            ArgumentGuard.NotNull(paginationContext, nameof(paginationContext));
            ArgumentGuard.NotNull(targetedFields, nameof(targetedFields));
            ArgumentGuard.NotNull(evaluatedIncludeCache, nameof(evaluatedIncludeCache));

            _constraintProviders = constraintProviders;
            _resourceGraph = resourceGraph;
            _resourceDefinitionAccessor = resourceDefinitionAccessor;
            _options = options;
            _paginationContext = paginationContext;
            _targetedFields = targetedFields;
            _evaluatedIncludeCache = evaluatedIncludeCache;
            _sparseFieldSetCache = new SparseFieldSetCache(_constraintProviders, resourceDefinitionAccessor);
        }

        /// <inheritdoc />
        public FilterExpression GetTopFilterFromConstraints(ResourceContext resourceContext)
        {
            ExpressionInScope[] constraints = _constraintProviders.SelectMany(provider => provider.GetConstraints()).ToArray();

            // @formatter:wrap_chained_method_calls chop_always
            // @formatter:keep_existing_linebreaks true

            FilterExpression[] filtersInTopScope = constraints
                .Where(constraint => constraint.Scope == null)
                .Select(constraint => constraint.Expression)
                .OfType<FilterExpression>()
                .ToArray();

            // @formatter:keep_existing_linebreaks restore
            // @formatter:wrap_chained_method_calls restore

            return GetFilter(filtersInTopScope, resourceContext);
        }

        /// <inheritdoc />
        public QueryLayer ComposeFromConstraints(ResourceContext requestResource)
        {
            ArgumentGuard.NotNull(requestResource, nameof(requestResource));

            ExpressionInScope[] constraints = _constraintProviders.SelectMany(provider => provider.GetConstraints()).ToArray();

            QueryLayer topLayer = ComposeTopLayer(constraints, requestResource);
            topLayer.Include = ComposeChildren(topLayer, constraints);

            _evaluatedIncludeCache.Set(topLayer.Include);

            return topLayer;
        }

        private QueryLayer ComposeTopLayer(IEnumerable<ExpressionInScope> constraints, ResourceContext resourceContext)
        {
            using IDisposable _ = CodeTimingSessionManager.Current.Measure("Top-level query composition");

            // @formatter:wrap_chained_method_calls chop_always
            // @formatter:keep_existing_linebreaks true

            QueryExpression[] expressionsInTopScope = constraints
                .Where(constraint => constraint.Scope == null)
                .Select(constraint => constraint.Expression)
                .ToArray();

            // @formatter:keep_existing_linebreaks restore
            // @formatter:wrap_chained_method_calls restore

            PaginationExpression topPagination = GetPagination(expressionsInTopScope, resourceContext);

            if (topPagination != null)
            {
                _paginationContext.PageSize = topPagination.PageSize;
                _paginationContext.PageNumber = topPagination.PageNumber;
            }

            return new QueryLayer(resourceContext)
            {
                Filter = GetFilter(expressionsInTopScope, resourceContext),
                Sort = GetSort(expressionsInTopScope, resourceContext),
                Pagination = ((JsonApiOptions)_options).DisableTopPagination ? null : topPagination,
                Projection = GetProjectionForSparseAttributeSet(resourceContext)
            };
        }

        private IncludeExpression ComposeChildren(QueryLayer topLayer, ICollection<ExpressionInScope> constraints)
        {
            using IDisposable _ = CodeTimingSessionManager.Current.Measure("Nested query composition");

            // @formatter:wrap_chained_method_calls chop_always
            // @formatter:keep_existing_linebreaks true

            IncludeExpression include = constraints
                .Where(constraint => constraint.Scope == null)
                .Select(constraint => constraint.Expression)
                .OfType<IncludeExpression>()
                .FirstOrDefault() ?? IncludeExpression.Empty;

            // @formatter:keep_existing_linebreaks restore
            // @formatter:wrap_chained_method_calls restore

            IImmutableList<IncludeElementExpression> includeElements =
                ProcessIncludeSet(include.Elements, topLayer, new List<RelationshipAttribute>(), constraints);

            return !ReferenceEquals(includeElements, include.Elements)
                ? includeElements.Any() ? new IncludeExpression(includeElements) : IncludeExpression.Empty
                : include;
        }

        private IImmutableList<IncludeElementExpression> ProcessIncludeSet(IImmutableList<IncludeElementExpression> includeElements, QueryLayer parentLayer,
            ICollection<RelationshipAttribute> parentRelationshipChain, ICollection<ExpressionInScope> constraints)
        {
            IImmutableList<IncludeElementExpression> includeElementsEvaluated =
                GetIncludeElements(includeElements, parentLayer.ResourceContext) ?? ImmutableArray<IncludeElementExpression>.Empty;

            var updatesInChildren = new Dictionary<IncludeElementExpression, IImmutableList<IncludeElementExpression>>();

            foreach (IncludeElementExpression includeElement in includeElementsEvaluated)
            {
                parentLayer.Projection ??= new Dictionary<ResourceFieldAttribute, QueryLayer>();

                if (!parentLayer.Projection.ContainsKey(includeElement.Relationship))
                {
                    var relationshipChain = new List<RelationshipAttribute>(parentRelationshipChain)
                    {
                        includeElement.Relationship
                    };

                    // @formatter:wrap_chained_method_calls chop_always
                    // @formatter:keep_existing_linebreaks true

                    QueryExpression[] expressionsInCurrentScope = constraints
                        .Where(constraint =>
                            constraint.Scope != null && constraint.Scope.Fields.SequenceEqual(relationshipChain))
                        .Select(constraint => constraint.Expression)
                        .ToArray();

                    // @formatter:keep_existing_linebreaks restore
                    // @formatter:wrap_chained_method_calls restore

                    ResourceContext resourceContext = _resourceGraph.GetResourceContext(includeElement.Relationship.RightType);
                    bool isToManyRelationship = includeElement.Relationship is HasManyAttribute;

                    var child = new QueryLayer(resourceContext)
                    {
                        Filter = isToManyRelationship ? GetFilter(expressionsInCurrentScope, resourceContext) : null,
                        Sort = isToManyRelationship ? GetSort(expressionsInCurrentScope, resourceContext) : null,
                        Pagination = isToManyRelationship
                            ? ((JsonApiOptions)_options).DisableChildrenPagination ? null : GetPagination(expressionsInCurrentScope, resourceContext)
                            : null,
                        Projection = GetProjectionForSparseAttributeSet(resourceContext)
                    };

                    parentLayer.Projection.Add(includeElement.Relationship, child);

                    if (includeElement.Children.Any())
                    {
                        IImmutableList<IncludeElementExpression> updatedChildren =
                            ProcessIncludeSet(includeElement.Children, child, relationshipChain, constraints);

                        if (!ReferenceEquals(includeElement.Children, updatedChildren))
                        {
                            updatesInChildren.Add(includeElement, updatedChildren);
                        }
                    }
                }
            }

            return !updatesInChildren.Any() ? includeElementsEvaluated : ApplyIncludeElementUpdates(includeElementsEvaluated, updatesInChildren);
        }

        private static IImmutableList<IncludeElementExpression> ApplyIncludeElementUpdates(IImmutableList<IncludeElementExpression> includeElements,
            IDictionary<IncludeElementExpression, IImmutableList<IncludeElementExpression>> updatesInChildren)
        {
            ImmutableArray<IncludeElementExpression>.Builder newElementsBuilder = ImmutableArray.CreateBuilder<IncludeElementExpression>(includeElements.Count);
            newElementsBuilder.AddRange(includeElements);

            foreach ((IncludeElementExpression existingElement, IImmutableList<IncludeElementExpression> updatedChildren) in updatesInChildren)
            {
                int existingIndex = newElementsBuilder.IndexOf(existingElement);
                newElementsBuilder[existingIndex] = new IncludeElementExpression(existingElement.Relationship, updatedChildren);
            }

            return newElementsBuilder.ToImmutable();
        }

        /// <inheritdoc />
        public QueryLayer ComposeForGetById<TId>(TId id, ResourceContext resourceContext, TopFieldSelection fieldSelection)
        {
            ArgumentGuard.NotNull(resourceContext, nameof(resourceContext));

            AttrAttribute idAttribute = GetIdAttribute(resourceContext);

            QueryLayer queryLayer = ComposeFromConstraints(resourceContext);
            queryLayer.Sort = null;
            queryLayer.Pagination = null;
            queryLayer.Filter = CreateFilterByIds(id.AsArray(), idAttribute, queryLayer.Filter);

            if (fieldSelection == TopFieldSelection.OnlyIdAttribute)
            {
                queryLayer.Projection = new Dictionary<ResourceFieldAttribute, QueryLayer>
                {
                    [idAttribute] = null
                };
            }
            else if (fieldSelection == TopFieldSelection.WithAllAttributes && queryLayer.Projection != null)
            {
                // Discard any top-level ?fields[]= or attribute exclusions from resource definition, because we need the full database row.
                while (queryLayer.Projection.Any(pair => pair.Key is AttrAttribute))
                {
                    queryLayer.Projection.Remove(queryLayer.Projection.First(pair => pair.Key is AttrAttribute));
                }
            }

            return queryLayer;
        }

        /// <inheritdoc />
        public QueryLayer ComposeSecondaryLayerForRelationship(ResourceContext secondaryResourceContext)
        {
            ArgumentGuard.NotNull(secondaryResourceContext, nameof(secondaryResourceContext));

            QueryLayer secondaryLayer = ComposeFromConstraints(secondaryResourceContext);
            secondaryLayer.Projection = GetProjectionForRelationship(secondaryResourceContext);
            secondaryLayer.Include = null;

            return secondaryLayer;
        }

        private IDictionary<ResourceFieldAttribute, QueryLayer> GetProjectionForRelationship(ResourceContext secondaryResourceContext)
        {
            IImmutableSet<AttrAttribute> secondaryAttributeSet = _sparseFieldSetCache.GetIdAttributeSetForRelationshipQuery(secondaryResourceContext);

            return secondaryAttributeSet.ToDictionary(key => (ResourceFieldAttribute)key, _ => (QueryLayer)null);
        }

        /// <inheritdoc />
        public QueryLayer WrapLayerForSecondaryEndpoint<TId>(QueryLayer secondaryLayer, ResourceContext primaryResourceContext, TId primaryId,
            RelationshipAttribute secondaryRelationship)
        {
            ArgumentGuard.NotNull(secondaryLayer, nameof(secondaryLayer));
            ArgumentGuard.NotNull(primaryResourceContext, nameof(primaryResourceContext));
            ArgumentGuard.NotNull(secondaryRelationship, nameof(secondaryRelationship));

            IncludeExpression innerInclude = secondaryLayer.Include;
            secondaryLayer.Include = null;

            IImmutableSet<AttrAttribute> primaryAttributeSet = _sparseFieldSetCache.GetIdAttributeSetForRelationshipQuery(primaryResourceContext);

            Dictionary<ResourceFieldAttribute, QueryLayer> primaryProjection =
                primaryAttributeSet.ToDictionary(key => (ResourceFieldAttribute)key, _ => (QueryLayer)null);

            primaryProjection[secondaryRelationship] = secondaryLayer;

            FilterExpression primaryFilter = GetFilter(Array.Empty<QueryExpression>(), primaryResourceContext);
            AttrAttribute primaryIdAttribute = GetIdAttribute(primaryResourceContext);

            return new QueryLayer(primaryResourceContext)
            {
                Include = RewriteIncludeForSecondaryEndpoint(innerInclude, secondaryRelationship),
                Filter = CreateFilterByIds(primaryId.AsArray(), primaryIdAttribute, primaryFilter),
                Projection = primaryProjection
            };
        }

        private IncludeExpression RewriteIncludeForSecondaryEndpoint(IncludeExpression relativeInclude, RelationshipAttribute secondaryRelationship)
        {
            IncludeElementExpression parentElement = relativeInclude != null
                ? new IncludeElementExpression(secondaryRelationship, relativeInclude.Elements)
                : new IncludeElementExpression(secondaryRelationship);

            return new IncludeExpression(ImmutableArray.Create(parentElement));
        }

        private FilterExpression CreateFilterByIds<TId>(IReadOnlyCollection<TId> ids, AttrAttribute idAttribute, FilterExpression existingFilter)
        {
            var idChain = new ResourceFieldChainExpression(idAttribute);

            FilterExpression filter = null;

            if (ids.Count == 1)
            {
                var constant = new LiteralConstantExpression(ids.Single().ToString());
                filter = new ComparisonExpression(ComparisonOperator.Equals, idChain, constant);
            }
            else if (ids.Count > 1)
            {
                ImmutableHashSet<LiteralConstantExpression> constants = ids.Select(id => new LiteralConstantExpression(id.ToString())).ToImmutableHashSet();
                filter = new AnyExpression(idChain, constants);
            }

            return filter == null ? existingFilter : existingFilter == null ? filter : new LogicalExpression(LogicalOperator.And, filter, existingFilter);
        }

        /// <inheritdoc />
        public QueryLayer ComposeForUpdate<TId>(TId id, ResourceContext primaryResource)
        {
            ArgumentGuard.NotNull(primaryResource, nameof(primaryResource));

            ImmutableArray<IncludeElementExpression> includeElements = _targetedFields.Relationships
                .Select(relationship => new IncludeElementExpression(relationship)).ToImmutableArray();

            AttrAttribute primaryIdAttribute = GetIdAttribute(primaryResource);

            QueryLayer primaryLayer = ComposeTopLayer(Array.Empty<ExpressionInScope>(), primaryResource);
            primaryLayer.Include = includeElements.Any() ? new IncludeExpression(includeElements) : IncludeExpression.Empty;
            primaryLayer.Sort = null;
            primaryLayer.Pagination = null;
            primaryLayer.Filter = CreateFilterByIds(id.AsArray(), primaryIdAttribute, primaryLayer.Filter);
            primaryLayer.Projection = null;

            return primaryLayer;
        }

        /// <inheritdoc />
        public IEnumerable<(QueryLayer, RelationshipAttribute)> ComposeForGetTargetedSecondaryResourceIds(IIdentifiable primaryResource)
        {
            ArgumentGuard.NotNull(primaryResource, nameof(primaryResource));

            foreach (RelationshipAttribute relationship in _targetedFields.Relationships)
            {
                object rightValue = relationship.GetValue(primaryResource);
                ICollection<IIdentifiable> rightResourceIds = _collectionConverter.ExtractResources(rightValue);

                if (rightResourceIds.Any())
                {
                    QueryLayer queryLayer = ComposeForGetRelationshipRightIds(relationship, rightResourceIds);
                    yield return (queryLayer, relationship);
                }
            }
        }

        /// <inheritdoc />
        public QueryLayer ComposeForGetRelationshipRightIds(RelationshipAttribute relationship, ICollection<IIdentifiable> rightResourceIds)
        {
            ArgumentGuard.NotNull(relationship, nameof(relationship));
            ArgumentGuard.NotNull(rightResourceIds, nameof(rightResourceIds));

            ResourceContext rightResourceContext = _resourceGraph.GetResourceContext(relationship.RightType);
            AttrAttribute rightIdAttribute = GetIdAttribute(rightResourceContext);

            object[] typedIds = rightResourceIds.Select(resource => resource.GetTypedId()).ToArray();

            FilterExpression baseFilter = GetFilter(Array.Empty<QueryExpression>(), rightResourceContext);
            FilterExpression filter = CreateFilterByIds(typedIds, rightIdAttribute, baseFilter);

            return new QueryLayer(rightResourceContext)
            {
                Include = IncludeExpression.Empty,
                Filter = filter,
                Projection = new Dictionary<ResourceFieldAttribute, QueryLayer>
                {
                    [rightIdAttribute] = null
                }
            };
        }

        /// <inheritdoc />
        public QueryLayer ComposeForHasMany<TId>(HasManyAttribute hasManyRelationship, TId leftId, ICollection<IIdentifiable> rightResourceIds)
        {
            ArgumentGuard.NotNull(hasManyRelationship, nameof(hasManyRelationship));
            ArgumentGuard.NotNull(rightResourceIds, nameof(rightResourceIds));

            ResourceContext leftResourceContext = _resourceGraph.GetResourceContext(hasManyRelationship.LeftType);
            AttrAttribute leftIdAttribute = GetIdAttribute(leftResourceContext);

            ResourceContext rightResourceContext = _resourceGraph.GetResourceContext(hasManyRelationship.RightType);
            AttrAttribute rightIdAttribute = GetIdAttribute(rightResourceContext);
            object[] rightTypedIds = rightResourceIds.Select(resource => resource.GetTypedId()).ToArray();

            FilterExpression leftFilter = CreateFilterByIds(leftId.AsArray(), leftIdAttribute, null);
            FilterExpression rightFilter = CreateFilterByIds(rightTypedIds, rightIdAttribute, null);

            return new QueryLayer(leftResourceContext)
            {
                Include = new IncludeExpression(ImmutableArray.Create(new IncludeElementExpression(hasManyRelationship))),
                Filter = leftFilter,
                Projection = new Dictionary<ResourceFieldAttribute, QueryLayer>
                {
                    [hasManyRelationship] = new(rightResourceContext)
                    {
                        Filter = rightFilter,
                        Projection = new Dictionary<ResourceFieldAttribute, QueryLayer>
                        {
                            [rightIdAttribute] = null
                        }
                    },
                    [leftIdAttribute] = null
                }
            };
        }

        protected virtual IImmutableList<IncludeElementExpression> GetIncludeElements(IImmutableList<IncludeElementExpression> includeElements,
            ResourceContext resourceContext)
        {
            ArgumentGuard.NotNull(resourceContext, nameof(resourceContext));

            return _resourceDefinitionAccessor.OnApplyIncludes(resourceContext.ResourceType, includeElements);
        }

        protected virtual FilterExpression GetFilter(IReadOnlyCollection<QueryExpression> expressionsInScope, ResourceContext resourceContext)
        {
            ArgumentGuard.NotNull(expressionsInScope, nameof(expressionsInScope));
            ArgumentGuard.NotNull(resourceContext, nameof(resourceContext));

            ImmutableArray<FilterExpression> filters = expressionsInScope.OfType<FilterExpression>().ToImmutableArray();
            FilterExpression filter = filters.Length > 1 ? new LogicalExpression(LogicalOperator.And, filters) : filters.FirstOrDefault();

            return _resourceDefinitionAccessor.OnApplyFilter(resourceContext.ResourceType, filter);
        }

        protected virtual SortExpression GetSort(IReadOnlyCollection<QueryExpression> expressionsInScope, ResourceContext resourceContext)
        {
            ArgumentGuard.NotNull(expressionsInScope, nameof(expressionsInScope));
            ArgumentGuard.NotNull(resourceContext, nameof(resourceContext));

            SortExpression sort = expressionsInScope.OfType<SortExpression>().FirstOrDefault();

            sort = _resourceDefinitionAccessor.OnApplySort(resourceContext.ResourceType, sort);

            if (sort == null)
            {
                AttrAttribute idAttribute = GetIdAttribute(resourceContext);
                var idAscendingSort = new SortElementExpression(new ResourceFieldChainExpression(idAttribute), true);
                sort = new SortExpression(ImmutableArray.Create(idAscendingSort));
            }

            return sort;
        }

        protected virtual PaginationExpression GetPagination(IReadOnlyCollection<QueryExpression> expressionsInScope, ResourceContext resourceContext)
        {
            ArgumentGuard.NotNull(expressionsInScope, nameof(expressionsInScope));
            ArgumentGuard.NotNull(resourceContext, nameof(resourceContext));

            PaginationExpression pagination = expressionsInScope.OfType<PaginationExpression>().FirstOrDefault();

            pagination = _resourceDefinitionAccessor.OnApplyPagination(resourceContext.ResourceType, pagination);

            pagination ??= new PaginationExpression(PageNumber.ValueOne, _options.DefaultPageSize);

            return pagination;
        }

        protected virtual IDictionary<ResourceFieldAttribute, QueryLayer> GetProjectionForSparseAttributeSet(ResourceContext resourceContext)
        {
            ArgumentGuard.NotNull(resourceContext, nameof(resourceContext));

            IImmutableSet<ResourceFieldAttribute> fieldSet = _sparseFieldSetCache.GetSparseFieldSetForQuery(resourceContext);

            if (!fieldSet.Any())
            {
                return null;
            }

            HashSet<AttrAttribute> attributeSet = fieldSet.OfType<AttrAttribute>().ToHashSet();
            AttrAttribute idAttribute = GetIdAttribute(resourceContext);
            attributeSet.Add(idAttribute);

            return attributeSet.ToDictionary(key => (ResourceFieldAttribute)key, _ => (QueryLayer)null);
        }

        private static AttrAttribute GetIdAttribute(ResourceContext resourceContext)
        {
            return resourceContext.GetAttributeByPropertyName(nameof(Identifiable.Id));
        }
    }
}


text:
package generic;

import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNull;

/**
 * Class for testing the "Store" interface and the "AbstractStore" class.
 *
 * @author Dmitrii Eskov (eskovdmi@gmail.com)
 * @version 1.0
 * @since 22.02.2019
 */
public class StoreTest {

    /**
     * Storage of users.
     */
    private UserStore users;

    /**
     * Storage of roles.
     */
    private RoleStore roles;

    /**
     * Setting up the storage of users.
     */
    @Before
    public void setUpUserStore() {
        this.users = new UserStore(6);
        users.add(new User("1"));
        users.add(new User("2"));
        users.add(new User("3"));
        users.add(new User("4"));
        users.add(new User("5"));
    }

    /**
     * Setting up the storage of roles.
     */
    @Before
    public void setUpRoleStore() {
        this.roles = new RoleStore(6);
        roles.add(new Role("11"));
        roles.add(new Role("22"));
        roles.add(new Role("33"));
        roles.add(new Role("44"));
        roles.add(new Role("55"));
    }

    /**
     * When adding a new user.
     */
    @Test
    public void whenAddElementsToUserStoreThenSuccess() {
        this.users.add(new User("7"));
    }

    /**
     * When adding a new role.
     */
    @Test
    public void whenAddElementsToRoleStoreThenSuccess() {
        this.roles.add(new Role("17"));
    }

    /**
     * When replacing a user.
     */
    @Test
    public void whenReplaceUserThenTrueOrFalse() {
        assertThat(this.users.replace("1", new User("66")), is(true));
        assertThat(this.users.replace("3", new User("55")), is(true));
        assertThat(this.users.replace("5", new User("77")), is(true));
        assertThat(this.users.replace("6", new User("34")), is(false));
        assertThat(this.users.replace("7", new User("36")), is(false));
    }

    /**
     * When replacing a role.
     */
    @Test
    public void whenReplaceRoleThenTrueOrFalse() {
        assertThat(this.roles.replace("11", new Role("66")), is(true));
        assertThat(this.roles.replace("22", new Role("71")), is(true));
        assertThat(this.roles.replace("33", new Role("77")), is(true));
        assertThat(this.roles.replace("45", new Role("34")), is(false));
        assertThat(this.roles.replace("58", new Role("36")), is(false));
    }

    /**
     * When deleting users.
     */
    @Test
    public void whenDeleteUsersThenTrueOrFalse() {
        assertThat(this.users.delete("1"), is(true));
        assertThat(this.users.delete("6"), is(false));
    }

    /**
     * When deleting roles.
     */
    @Test
    public void whenDeleteRolesThenTrueOrFalse() {
        assertThat(this.roles.delete("11"), is(true));
        assertThat(this.roles.delete("56"), is(false));
    }

    /**
     * When searching for a user by their id.
     */
    @Test
    public void whenFindUserByIDThenSuccessOrNull() {
        User user = new User("12");
        this.users.add(user);
        assertThat(this.users.findById("12"), is(user));
        assertNull(this.users.findById("13"));
    }

    /**
     * When searching for a role by their id.
     */
    @Test
    public void whenFindRoleByIDThenSuccessOrNull() {
        Role role = new Role("12");
        this.roles.add(role);
        assertThat(this.roles.findById("12"), is(role));
        assertNull(this.roles.findById("13"));
    }
}


text:
"""
Light-weight remote execution library and utilities.

There are some examples in the unittest but I added another that is more
luigi-specific in the examples directory (examples/ssh_remote_execution.py)

:class:`RemoteContext` is meant to provide functionality similar to that of the
standard library subprocess module, but where the commands executed are run on
a remote machine instead, without the user having to think about prefixing
everything with "ssh" and credentials etc.

Using this mini library (which is just a convenience wrapper for subprocess),
:class:`RemoteTarget` is created to let you stream data from a remotely stored file using
the luigi :class:`~luigi.target.FileSystemTarget` semantics.

As a bonus, :class:`RemoteContext` also provides a really cool feature that let's you
set up ssh tunnels super easily using a python context manager (there is an example
in the integration part of unittests).

This can be super convenient when you want secure communication using a non-secure
protocol or circumvent firewalls (as long as they are open for ssh traffic).
"""

import contextlib
import logging
import os
import random
import subprocess
import posixpath

import luigi
import luigi.format
import luigi.target

logger = logging.getLogger('luigi-interface')

class RemoteCalledProcessError(subprocess.CalledProcessError):
    def __init__(self, returncode, command, host, output=None):
        super(RemoteCalledProcessError, self).__init__(returncode, command, output)
        self.host = host

    def __str__(self):
        return "Command '%s' on host %s returned non-zero exit status %d" % (
            self.cmd, self.host, self.returncode)

class RemoteContext:

    def __init__(self, host, **kwargs):
        self.host = host
        self.username = kwargs.get('username', None)
        self.key_file = kwargs.get('key_file', None)
        self.connect_timeout = kwargs.get('connect_timeout', None)
        self.port = kwargs.get('port', None)
        self.no_host_key_check = kwargs.get('no_host_key_check', False)
        self.sshpass = kwargs.get('sshpass', False)
        self.tty = kwargs.get('tty', False)

    def __repr__(self):
        return '%s(%r, %r, %r, %r, %r)' % (
            type(self).__name__, self.host, self.username, self.key_file, self.connect_timeout, self.port)

    def __eq__(self, other):
        return repr(self) == repr(other)

    def __hash__(self):
        return hash(repr(self))

    def _host_ref(self):
        if self.username:
            return "{0}@{1}".format(self.username, self.host)
        else:
            return self.host

    def _prepare_cmd(self, cmd):
        connection_cmd = ["ssh", self._host_ref(), "-o", "ControlMaster=no"]
        if self.sshpass:
            connection_cmd = ["sshpass", "-e"] + connection_cmd
        else:
            connection_cmd += ["-o", "BatchMode=yes"]  # no password prompts etc
        if self.port:
            connection_cmd.extend(["-p", self.port])

        if self.connect_timeout is not None:
            connection_cmd += ['-o', 'ConnectTimeout=%d' % self.connect_timeout]

        if self.no_host_key_check:
            connection_cmd += ['-o', 'UserKnownHostsFile=/dev/null',
                               '-o', 'StrictHostKeyChecking=no']

        if self.key_file:
            connection_cmd.extend(["-i", self.key_file])

        if self.tty:
            connection_cmd.append('-t')
        return connection_cmd + cmd

    def Popen(self, cmd, **kwargs):
        """
        Remote Popen.
        """
        prefixed_cmd = self._prepare_cmd(cmd)
        return subprocess.Popen(prefixed_cmd, **kwargs)

    def check_output(self, cmd):
        """
        Execute a shell command remotely and return the output.

        Simplified version of Popen when you only want the output as a string and detect any errors.
        """
        p = self.Popen(cmd, stdout=subprocess.PIPE)
        output, _ = p.communicate()
        if p.returncode != 0:
            raise RemoteCalledProcessError(p.returncode, cmd, self.host, output=output)
        return output

    @contextlib.contextmanager
    def tunnel(self, local_port, remote_port=None, remote_host="localhost"):
        """
        Open a tunnel between localhost:local_port and remote_host:remote_port via the host specified by this context.

        Remember to close() the returned "tunnel" object in order to clean up
        after yourself when you are done with the tunnel.
        """
        tunnel_host = "{0}:{1}:{2}".format(local_port, remote_host, remote_port)
        proc = self.Popen(
            # cat so we can shut down gracefully by closing stdin
            ["-L", tunnel_host, "echo -n ready && cat"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
        )
        # make sure to get the data so we know the connection is established
        ready = proc.stdout.read(5)
        assert ready == b"ready", "Didn't get ready from remote echo"
        yield  # user code executed here
        proc.communicate()
        assert proc.returncode == 0, "Tunnel process did an unclean exit (returncode %s)" % (proc.returncode,)

class RemoteFileSystem(luigi.target.FileSystem):

    def __init__(self, host, **kwargs):
        self.remote_context = RemoteContext(host, **kwargs)

    def exists(self, path):
        """
        Return `True` if file or directory at `path` exist, False otherwise.
        """
        try:
            self.remote_context.check_output(["test", "-e", path])
        except subprocess.CalledProcessError as e:
            if e.returncode == 1:
                return False
            else:
                raise
        return True

    def listdir(self, path):
        while path.endswith('/'):
            path = path[:-1]

        path = path or '.'
        listing = self.remote_context.check_output(["find", "-L", path, "-type", "f"]).splitlines()
        return [v.decode('utf-8') for v in listing]

    def isdir(self, path):
        """
        Return `True` if directory at `path` exist, False otherwise.
        """
        try:
            self.remote_context.check_output(["test", "-d", path])
        except subprocess.CalledProcessError as e:
            if e.returncode == 1:
                return False
            else:
                raise
        return True

    def remove(self, path, recursive=True):
        """
        Remove file or directory at location `path`.
        """
        if recursive:
            cmd = ["rm", "-r", path]
        else:
            cmd = ["rm", path]

        self.remote_context.check_output(cmd)

    def mkdir(self, path, parents=True, raise_if_exists=False):
        if self.exists(path):
            if raise_if_exists:
                raise luigi.target.FileAlreadyExists()
            elif not self.isdir(path):
                raise luigi.target.NotADirectory()
            else:
                return

        if parents:
            cmd = ['mkdir', '-p', path]
        else:
            cmd = ['mkdir', path, '2>&1']

        try:
            self.remote_context.check_output(cmd)
        except subprocess.CalledProcessError as e:
            if b'no such file' in e.output.lower():
                raise luigi.target.MissingParentDirectory()
            raise

    def _scp(self, src, dest):
        cmd = ["scp", "-q", "-C", "-o", "ControlMaster=no"]
        if self.remote_context.sshpass:
            cmd = ["sshpass", "-e"] + cmd
        else:
            cmd.append("-B")
        if self.remote_context.no_host_key_check:
            cmd.extend(['-o', 'UserKnownHostsFile=/dev/null',
                        '-o', 'StrictHostKeyChecking=no'])
        if self.remote_context.key_file:
            cmd.extend(["-i", self.remote_context.key_file])
        if self.remote_context.port:
            cmd.extend(["-P", self.remote_context.port])
        if os.path.isdir(src):
            cmd.extend(["-r"])
        cmd.extend([src, dest])
        p = subprocess.Popen(cmd)
        output, _ = p.communicate()
        if p.returncode != 0:
            raise subprocess.CalledProcessError(p.returncode, cmd, output=output)

    def put(self, local_path, path):
        # create parent folder if not exists
        normpath = posixpath.normpath(path)
        folder = os.path.dirname(normpath)
        if folder and not self.exists(folder):
            self.remote_context.check_output(['mkdir', '-p', folder])

        tmp_path = path + '-luigi-tmp-%09d' % random.randrange(0, 1e10)
        self._scp(local_path, "%s:%s" % (self.remote_context._host_ref(), tmp_path))
        self.remote_context.check_output(['mv', tmp_path, path])

    def get(self, path, local_path):
        # Create folder if it does not exist
        normpath = os.path.normpath(local_path)
        folder = os.path.dirname(normpath)
        if folder:
            try:
                os.makedirs(folder)
            except OSError:
                pass

        tmp_local_path = local_path + '-luigi-tmp-%09d' % random.randrange(0, 1e10)
        self._scp("%s:%s" % (self.remote_context._host_ref(), path), tmp_local_path)
        os.rename(tmp_local_path, local_path)

class AtomicRemoteFileWriter(luigi.format.OutputPipeProcessWrapper):

    def __init__(self, fs, path):
        self._fs = fs
        self.path = path

        # create parent folder if not exists
        normpath = os.path.normpath(self.path)
        folder = os.path.dirname(normpath)
        if folder:
            self.fs.mkdir(folder)

        self.__tmp_path = self.path + '-luigi-tmp-%09d' % random.randrange(0, 1e10)
        super(AtomicRemoteFileWriter, self).__init__(
            self.fs.remote_context._prepare_cmd(['cat', '>', self.__tmp_path]))

    def __del__(self):
        super(AtomicRemoteFileWriter, self).__del__()

        try:
            if self.fs.exists(self.__tmp_path):
                self.fs.remote_context.check_output(['rm', self.__tmp_path])
        except Exception:
            # Don't propagate the exception; bad things can happen.
            logger.exception('Failed to delete in-flight file')

    def close(self):
        super(AtomicRemoteFileWriter, self).close()
        self.fs.remote_context.check_output(['mv', self.__tmp_path, self.path])

    @property
    def tmp_path(self):
        return self.__tmp_path

    @property
    def fs(self):
        return self._fs

class RemoteTarget(luigi.target.FileSystemTarget):
    """
    Target used for reading from remote files.

    The target is implemented using ssh commands streaming data over the network.
    """

    def __init__(self, path, host, format=None, **kwargs):
        super(RemoteTarget, self).__init__(path)
        if format is None:
            format = luigi.format.get_default_format()
        self.format = format
        self._fs = RemoteFileSystem(host, **kwargs)

    @property
    def fs(self):
        return self._fs

    def open(self, mode='r'):
        if mode == 'w':
            file_writer = AtomicRemoteFileWriter(self.fs, self.path)
            if self.format:
                return self.format.pipe_writer(file_writer)
            else:
                return file_writer
        elif mode == 'r':
            file_reader = luigi.format.InputPipeProcessWrapper(
                self.fs.remote_context._prepare_cmd(["cat", self.path]))
            if self.format:
                return self.format.pipe_reader(file_reader)
            else:
                return file_reader
        else:
            raise Exception("mode must be 'r' or 'w' (got: %s)" % mode)

    def put(self, local_path):
        self.fs.put(local_path, self.path)

    def get(self, local_path):
        self.fs.get(self.path, local_path)


text:
class UpdateRssFeeds < ActiveRecord::Migration

  def self.up
    add_column :rss_feeds, :feed, :text
    add_column :rss_feeds, :updated_at, :datetime
    add_column :rss_feeds, :created_at, :datetime
    add_column :rss_feeds, :last_feed_date, :datetime
    add_column :rss_feeds, :sanitise, :boolean, {:default => false}
    add_column :rss_feeds, :update_frequency, :string
    add_column :rss_feeds, :next_update, :datetime
  end

  def self.down
    remove_column :rss_feeds, :feed
    remove_column :rss_feeds, :updated_at
    remove_column :rss_feeds, :created_at
    remove_column :rss_feeds, :last_feed_date
    remove_column :rss_feeds, :sanitise
    remove_column :rss_feeds, :update_frequency
    remove_column :rss_feeds, :next_update
  end

end


text:
@interface RPINMSSHErrorHandler : NSObject

+(instancetype)sharedInstance;
-(NSError*)lastError;

@end


text:
/*! \file abstractcontext.h

    Defines an abstract context, which could be used for evaluation
 */
#pragma once
#include "errorcodes.h"
#include <string>

namespace dukpp03
{

class AbstractCallable;

/*! A wapper for basic context for data
 */
class AbstractContext
{
public:
    /*! Constructs new basic context
     */
    AbstractContext();
    /*! Can be inherited
     */
    virtual ~AbstractContext();
    /*! Tries to get current context from raw context
        \param[in] ctx context
        \return context
     */
    static dukpp03::AbstractContext* getContext(duk_context* ctx);
    /*! Evals string, with code in it. If no error occured, result is not popped
        out from stack, since we still may need it
        \param[in] string a string
        \param[in] clean_heap whether heap should be cleaned after execution. If provided, result is popped from stack
        \param[out] error a string, where error should be written
        \return true if no error
     */
    bool eval(const std::string& string, bool clean_heap = true,std::string* error = nullptr);
    /*! Throws error from a context
        \param[in] error_string string data for error
        \param[in] code error codes
     */
    void throwError(const std::string& error_string, dukpp03::ErrorCodes code = dukpp03::ErrorCodes::D03_DUK_ERROR);
    /*! Resets context fully, erasing all data
     */
    virtual void reset() = 0;
    /*! Tries to perform call on specified value, passed by Duktape
        \param[in] value a value
        \return result of call
     */
    virtual int call(void* value) = 0;
    /*! Returns new context
        \return context data
     */
    virtual duk_context* context();
    /*! Checks, whether timeout is reached for context. Called, while
        evaluating value
     */
    bool timeoutReached() const;
    /*! Sets maximal execution time for a script
        \param[in] time maximal execution time
     */
    void setMaximumExecutionTime(double time);
    /*! Return maximal execution time for a script
        \return maximal execution time
     */
    double maximumExecutionTime() const;
    /*! A simple wrapper aroun duk_get_top for getting count of values on stack
        \return count of values on stack
     */
    int getTop() const;
    /*! Throws error, that function has invalid amount of arguments
        \param[in] expected how many arguments did function expect
        \param[in] got how many arguments it got
     */
    virtual void throwInvalidArgumentCountError(int expected, int got);
    /*! Throws error, that invalid type has passed into function
        \param[in] argnumber argument number
        \param[in] type expected type
     */
    virtual void throwInvalidTypeError(int argnumber, const std::string& type);
    /*! Throws error, that invalid type has passed into function as this
        \param[in] type expected type
     */
    virtual void throwInvalidTypeForThisError(const std::string& type);
    /*! Throws error, that caught exception, when calling function
     */
    virtual void throwCaughtException();
    /*! Throws, error, that function should be called only as constructor
     */
    virtual void throwFunctionCallShouldBeACalledOnlyAsConstructor();
    /*! Throws, error, that function should not be called as constructor
     */
    virtual void throwFunctionCallShouldNotBeCalledAsConstructor();
    /*! Registers native function
        \param[in] callable_name a name for function
        \param[in] f function
        \param[in] args an argument list
     */
    void registerNativeFunction(const std::string& callable_name, duk_c_function f, duk_idx_t args);
	/*! Pushes callable to stack
        \param[in] callable a callable object
        \param[in] own whether context will own callable
        \param[in] as_attribute push as attribute getter (adds additional pop in wrapper)
     */
    void pushCallable(dukpp03::AbstractCallable* callable, bool own = true, bool as_attribute = false);
protected:
    /*! Registers callable as property of global object
        \param[in] callable_name name of property of global object
        \param[in] callable a callable object
        \param[in] own whether context will own callable
     */
    void registerCallable(const std::string& callable_name, dukpp03::AbstractCallable* callable, bool own = true);
    /*! Inits context for evaluating
     */
    virtual void initContextBeforeAccessing();
    /*! Starts evaluating object, needed for data
     */
    virtual void startEvaluating() = 0;
    /*! Returns time, elapsed from evaluation
     */
    virtual double elapsedFromEvaluation() = 0;
    /*! Adds callable to needed set
        \param[in] c callable
     */
    virtual void addCallableToSet(dukpp03::AbstractCallable* c) = 0;
    /*! Inner context
     */
    duk_context* m_context;
    /*! A maximal execution time
     */
    double m_maximal_execution_time;
    /*! Whether execution is running
     */
    bool m_running;
private:
    /*! This object is non-copyable
        \param[in] p context
     */
    AbstractContext(const dukpp03::AbstractContext& p);
    /*! This object is non-copyable
        \param[in] p context
        \return self-reference
     */
    dukpp03::AbstractContext& operator=(const dukpp03::AbstractContext& p);
};

}


text:
layout: home
title:  "Home"
section: "home"
---

[![Join the chat at https://gitter.im/julien-truffaut/Monocle](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/julien-truffaut/Monocle?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Maven Central](https://img.shields.io/maven-central/v/com.github.julien-truffaut/monocle_2.11.svg)](http://search.maven.org/#search|ga|1|com.github.julien-truffaut.monocle)
[![Build Status](https://api.travis-ci.org/julien-truffaut/Monocle.svg?branch=master)](https://travis-ci.org/julien-truffaut/Monocle)

## Table of contents
- [Motivation](#motivation)
- [Lens creation](#lens-creation)
- [Typeclass and instance location](#typeclass-and-instance-location)
- [Optics hierarchy](#optics-hierarchy)
- [Maintainers and contributors](#maintainers-and-contributors)
- [Copyright and licence](#copyright-and-license)

### Motivation

Monocle is a `Lens` library, or more generally an Optics library where Optics gather the concepts
of `Lens`, `Traversal`, `Optional`, `Prism` and `Iso`. Monocle is strongly inspired by Haskell [Lens](https://github.com/ekmett/lens).

#### What does it mean?

Optics are a set of purely functional abstractions to manipulate (get, set, modify) immutable objects.
Optics compose between each other and particularly shine with nested objects.

#### Why do I need this?

Scala already provides getters and setters for case classes but modifying nested object is verbose which makes code
difficult to understand and reason about. Let's have a look at some examples:

```tut:silent
case class Street(number: Int, name: String)
case class Address(city: String, street: Street)
case class Company(name: String, address: Address)
case class Employee(name: String, company: Company)
```

Let's say we have an employee and we need to set the first character of his company street name address in upper case.
Here is how we could write it in vanilla Scala:

```tut:silent
val employee = Employee("john", Company("awesome inc", Address("london", Street(23, "high street"))))
```

```tut:book
employee.copy(
  company = employee.company.copy(
    address = employee.company.address.copy(
      street = employee.company.address.street.copy(
        name = employee.company.address.street.name.capitalize // luckily capitalize exists
      )
    )
  )
)
```

As you can see copy is not convenient to update nested objects as we need to repeat at each level the full path
to reach it. Let's see what could we do with Monocle (type annotations are only for clarity):

```tut:silent
import monocle.Lens
import monocle.macros.GenLens

val company   : Lens[Employee, Company] = GenLens[Employee](_.company)
val address   : Lens[Company , Address] = GenLens[Company](_.address)
val street    : Lens[Address , Street]  = GenLens[Address](_.street)
val streetName: Lens[Street  , String]  = GenLens[Street](_.name)
```

```tut:book
(company composeLens address composeLens street composeLens streetName).modify(_.capitalize)(employee)
```

ComposeLens takes two `Lens`, one from A to B and another from B to C and creates a third `Lens` from A to C.
Therefore, after composing `company`, `address`, `street` and `name`, we obtain a `Lens` from `Employee` to `String` (the street name).

#### More abstractions

In the above example, we used capitalize to upper case the first letter of a `String`.
It works but it would be clearer if we could use `Lens` to zoom into the first character of a `String`.
However, we cannot write such a `Lens` because a `Lens` defines how to focus from an object `S` into a *mandatory*
object `A` and in our case, the first character of a `String` is optional as a `String` might be empty. For this
we need a sort of partial `Lens`, in Monocle it is called `Optional`.

```tut:silent
import monocle.function.Cons.headOption // to use headOption (an optic from Cons typeclass)
```

```tut:book
(company composeLens address
         composeLens street
         composeLens streetName
         composeOptional headOption).modify(_.toUpper)(employee)
```

Similarly to composeLens, composeOptional takes two `Optional`, one from A to B and another from B to C and
creates a third `Optional` from A to C. All `Lens` can be seen as `Optional` where the optional element to zoom to is always
present, hence composing an `Optional` and a `Lens` always produces an `Optional` (see class diagram for full inheritance
relation between Optics).

### Lens creation

There are 3 ways to create `Lens`, each with their pro and cons:

1.   The manual method where we construct a `Lens` by passing `get` and `set` functions:

     ```scala
     import monocle.Lens
     val company = Lens[Employee, Company](_.company)(c => e => e.copy(company = c))
     // or with some type inference
     val company = Lens((_: Employee).company)(c => e => e.copy(company = c))
     ```

2.   The semi-automatic method using the `GenLens` blackbox macro:

     ```scala
     import monocle.macros.GenLens
     val company = GenLens[Employee](_.company)
     ```

3.   Finally, the fully automatic method using the `@Lenses` macro annotation.
     `@Lenses` generates `Lens` for every accessor of a case class in its companion object (even if there is no companion object defined).
     This solution is the most boiler plate free but it has several disadvantages:
     1.   users need to add the macro paradise plugin to their project.
     2.   requires access to the case classes since you need to annotate them.

     ```scala
     import monocle.macros.Lenses
     @Lenses case class Employee(name: String, company: Company)
     // generates Employee.company: Lens[Employee, Company]
     // and       Employee.name   : Lens[Employee, String]

     // you can add a prefix to Lenses constructor

     @Lenses("_")
     case class Employee(company: Company, name: String)

     // generates Employee._company: Lens[Employee, Company]
     ```

Note: `GenLens` and `@Lenses` are both limited to case classes

### Optics in the REPL and tut

`Iso`, `Prism`, `Lens`, `Optional`, `Traversal` and `Setter` are all type aliases for more general polymorphic optics,
for example here is the definition of `Lens`:

```scala
type Lens[S, A] = PLens[S, S, A, A]

object Lens {
  def apply[S, A](get: S => A)(set: A => S => S): Lens[S, A] =
    PLens(get)(set)
}
```

This is a completely fine Scala definition and it will work perfectly in your code. However, if you try to create optics
in the REPL you will probably encounter a similar error:

```
scala> import monocle.Lens
import monocle.Lens

scala> case class Example(s: String, i: Int)
defined class Example

scala> val s = Lens[Example, String](_.s)(s => _.copy(s = s))
s: monocle.Lens[Example,String] = monocle.PLens$$anon$7@46aa4219

scala> val i = Lens[Example, Int](_.i)(i => _.copy(i = i))
<console>:13: error: object Lens does not take type parameters.
       val i = Lens[Example, Int](_.i)(i => _.copy(i = i))
```

We managed to create the first `Lens` but the second call to `apply` failed. This is a known bug in the REPL which is
tracked by [SI-7139](https://issues.scala-lang.org/browse/SI-7139). You will also face this error if you use [tut](https://github.com/tpolecat/tut)
to create documentation. This issue should be fixed in scala 2.12.1

### Typeclass and instance location

All typeclasses are defined in `monocle.function` package, you can import optic individually with

```scala
import monocle.function.$TYPE_CLASS.$OPTIC
```

For example

```tut:silent
import monocle.function.At.at
import monocle.function.Cons.{headOption, tailOption}
```

or you can import all typeclass based optics with

```tut:silent
import monocle.function.all._
```

Here is a complete example

```tut:reset:silent
import monocle.function.all._
import monocle.macros.GenLens

case class Foo(s: String, is: List[Int])
val foo = Foo("Hello", List(1,2,3))

val is = GenLens[Foo](_.is)
```

```tut:book
(is composeOptional headOption).getOption(foo)
```

Note: if you use a version of monocle before 1.4.x, you need another import to get the typeclass instance

```tut:silent
import monocle.std.list._
```

### Optics hierarchy
![Class Diagram](https://raw.github.com/julien-truffaut/Monocle/master/image/class-diagram.png)<br>

### Maintainers and contributors
The current maintainers (people who can merge pull requests) are:

* Julien Truffaut - [@julien-truffaut](https://github.com/julien-truffaut)
* Ilan Godik - [@NightRa](https://github.com/NightRa)
* Naoki Aoyama - [@aoiroaoino](https://github.com/aoiroaoino)
* Kenji Yoshida - [@xuwei-k](https://github.com/xuwei-k)

and the [contributors](https://github.com/julien-truffaut/Monocle/graphs/contributors) (people who committed to Monocle).

### Copyright and license

All code is available to you under the MIT license, available [here](http://opensource.org/licenses/mit-license.php).
The design is informed by many other projects, in particular Haskell [Lens](https://github.com/ekmett/lens).

Copyright the maintainers, 2016.


text:
using Swagger.ObjectModel;

namespace Nancy.Swagger.Services
{
    public interface ISwaggerTagProvider
    {
        Tag GetTag();
    }
}


text:
#include "pioneerLuaGeneratorFactory.h"

#include <generatorBase/simpleGenerators/waitForButtonGenerator.h>

#include "parts/ledPart.h"
#include "parts/magnetPart.h"
#include "parts/randomGeneratorPart.h"
#include "simpleGenerators/endOfHandlerGenerator.h"
#include "simpleGenerators/geoLandingGenerator.h"
#include "simpleGenerators/geoTakeoffGenerator.h"
#include "simpleGenerators/gotoGenerator.h"
#include "simpleGenerators/goToPointGenerator.h"
#include "simpleGenerators/initialNodeGenerator.h"
#include "simpleGenerators/labelGenerator.h"
#include "simpleGenerators/pioneerMagnetGenerator.h"
#include "simpleGenerators/pioneerPrintGenerator.h"
#include "simpleGenerators/pioneerSystemGenerator.h"
#include "simpleGenerators/pioneerLedGenerator.h"
#include "simpleGenerators/pioneerYawGenerator.h"
#include "simpleGenerators/randomInitGenerator.h"

using namespace pioneer::lua;
using namespace generatorBase::simple;

PioneerLuaGeneratorFactory::PioneerLuaGeneratorFactory(const qrRepo::RepoApi &repo
		, qReal::ErrorReporterInterface &errorReporter
		, const kitBase::robotModel::RobotModelManagerInterface &robotModelManager
		, generatorBase::lua::LuaProcessor &luaProcessor
		, const QString &generatorName
		, GotoLabelManager &gotoLabelManager)
	: GeneratorFactoryBase(repo, errorReporter, robotModelManager, luaProcessor)
	, mGeneratorName(generatorName)
	, mGotoLabelManager(gotoLabelManager)
{
}

PioneerLuaGeneratorFactory::~PioneerLuaGeneratorFactory()
{
}

generatorBase::simple::AbstractSimpleGenerator *PioneerLuaGeneratorFactory::simpleGenerator(const qReal::Id &id
		, generatorBase::GeneratorCustomizer &customizer)
{
	const QString elementType = id.element();
	if (elementType == "EndOfHandler") {
		return new EndOfHandlerGenerator(mRepo, customizer, id, this);
	} else if (elementType == "InitialNode") {
		return new InitialNodeGenerator(mRepo, customizer, id, this);
	} else if (elementType == "GeoTakeoff") {
		return new GeoTakeoffGenerator(mRepo, customizer, id, this);
	} else if (elementType == "GeoLanding") {
		return new GeoLandingGenerator(mRepo, customizer, id, this);
	} else if (elementType == "GoToPoint") {
		return new GoToPointGenerator(mRepo, customizer, id, this);
	} else if (elementType == "PioneerMagnet") {
		return new PioneerMagnetGenerator(mRepo, customizer, id, this);
	} else if (elementType == "PioneerPrint") {
		return new PioneerPrintGenerator(mRepo, customizer, id, this);
	} else if (elementType == "PioneerSystem") {
		return new PioneerSystemGenerator(mRepo, customizer, id, this);
	} else if (elementType == "PioneerLed") {
		return new PioneerLedGenerator(mRepo, customizer, id, this);
	} else if (elementType == "PioneerYaw") {
		return new PioneerYawGenerator(mRepo, customizer, id, this);
	} else if (elementType == "Randomizer") {
		return new RandomInitGenerator(mRepo, customizer, id, this);
	}

	return GeneratorFactoryBase::simpleGenerator(id, customizer);
}

QStringList PioneerLuaGeneratorFactory::pathsToTemplates() const
{
	return {":/" + mGeneratorName + "/templates"};
}

void PioneerLuaGeneratorFactory::initialize()
{
	generatorBase::GeneratorFactoryBase::initialize();
	mLedPart.reset(new LedPart(pathsToTemplates()));
	mMagnetPart.reset(new MagnetPart(pathsToTemplates()));
	mRandomGeneratorPart.reset(new RandomGeneratorPart(pathsToTemplates()));
}

LedPart& PioneerLuaGeneratorFactory::ledPart()
{
	return *mLedPart;
}

MagnetPart& PioneerLuaGeneratorFactory::magnetPart()
{
	return *mMagnetPart;
}

RandomGeneratorPart& PioneerLuaGeneratorFactory::randomGeneratorPart()
{
	return *mRandomGeneratorPart;
}

generatorBase::simple::AbstractSimpleGenerator *PioneerLuaGeneratorFactory::labelGenerator(const qReal::Id &id
		, generatorBase::GeneratorCustomizer &customizer)
{
	return new LabelGenerator(mRepo, customizer, id, this, mGotoLabelManager);
}

generatorBase::simple::AbstractSimpleGenerator *PioneerLuaGeneratorFactory::gotoSimpleGenerator(const qReal::Id &id
		, generatorBase::GeneratorCustomizer &customizer)
{
	return new GotoGenerator(mRepo, customizer, id, this, mGotoLabelManager);
}

QList<generatorBase::parts::InitTerminateCodeGenerator *> PioneerLuaGeneratorFactory::initTerminateGenerators()
{
	auto result = generatorBase::GeneratorFactoryBase::initTerminateGenerators();
	result << mRandomGeneratorPart.data() << mMagnetPart.data() << mLedPart.data();
	return result;
}


text:
var searchData=
[
  ['initialization_2c_20version_20and_20error_20reference_764',['Initialization, version and error reference',['../group__init.html',1,'']]],
  ['input_20reference_765',['Input reference',['../group__input.html',1,'']]]
];


text:
import { Component, OnInit, ViewChild } from '@angular/core';
import { NavbarComponent } from '../shared/navbar/navbar.component';

@Component({
    moduleId: module.id,
    selector: 'mm-payment-cancel',
    templateUrl: 'payment-cancel.component.html',
    styleUrls: ['payment.component.css']
})

export class PaymentCancelComponent implements OnInit {

    @ViewChild(NavbarComponent) navbarComponent: NavbarComponent;

    ngOnInit() {
        this.navbarComponent.navbarColor(0, '#6960FF');
    }
}


text:
package com.freetymekiyan.algorithms.level.medium;

import java.util.PriorityQueue;

/**
 * 215. Kth Largest Element in an Array
 *

 * Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not
 * the kth distinct element.
 *

 * For example,
 * Given [3,2,1,5,6,4] and k = 2, return 5.
 *

 * Note:
 * You may assume k is always valid, 1 ≤ k ≤ array's length.
 *

 * Company Tags: Facebook, Amazon, Microsoft, Apple, Bloomberg, Pocket Gems
 * Tags: Heap, Divide and Conquer
 * Similar Problems: (M) Wiggle Sort II, (M) Top K Frequent Elements, (E) Third Maximum Number
 */
public class KthLargestElementInAnArray {

  /**
   * Heap. Priority queue. O(nlogk) Time, O(k) Space.
   * Create a min heap as a window.
   * For each number in the array, add it to the heap.
   * If heap size > k, poll from the heap.
   * Return the top of the heap at the end.
   */
  public int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> pq = new PriorityQueue<>();
    for (int n : nums) {
      pq.offer(n);
      if (pq.size() > k) {
        pq.poll();
      }
    }
    return pq.peek();
  }

  /**
   * QuickSelect. Binary Search. Partition. O(nlogn) Time.
   * Use partition algorithm in Quick Sort, which gives us the pivot's index.
   * With that, we can then know which part of the array the kth largest element is in.
   * Each round get the rth largest ranking returned by the partition algorithm.
   * If r > k - 1, ranking is too large, the pivot is too small, should search in [lo, r-1].
   * If r < k - 1, ranking is too large, the pivot is too large, should search in [r+1, high].
   * If r = k - 1, the kth largest number is found.
   */
  public int findKthLargest2(int[] nums, int k) {
    int lo = 0;
    int hi = nums.length - 1;
    while (lo < hi) { // Here, lo must be smaller than hi as partition's input.
      int r = partition(nums, lo, hi);
      if (r < k - 1) { // k - 1, not k, because the ranking is 0-based.
        lo = r + 1;
      } else if (r > k - 1) {
        hi = r - 1;
      } else {
        break;
      }
    }
    return nums[k - 1];
  }

  /**
   * Partition algorithm in quick sort. O(n) Time.
   * Find ranking: how large is a[hi] in the array.
   * Given an array and the range to be partitioned.
   * Initialize the last element as the pivot.
   * Initialize two pointers, i from lower bound, j from higher bound - 1.
   * Move i to the next number <= a[hi], which will be thrown to the end of the array.
   * Move j to the next number > a[hi], which should be in the front of the array.
   * Check whether i and j overlap.
   * If doesn't, swap a[i] and a[j].
   * If overlap, break, and swap a[i] and a[hi] to move pivot to the position it belongs.
   * i is the final position since all elements before i are > a[hi].
   */
  private int partition(int[] a, int lo, int hi) {
    /*
     * Last element as pivot makes sure that when we swap with i, i is either:
     * 1. the pivot
     * 2. the element that's <= pivot, which guarantees all elements before i are > pivot.
     * The last swap will always be correct.
     */
    int pivot = a[hi];
    int i = lo;
    int j = hi - 1;
    while (true) {
      while (i < hi && a[i] > pivot) {
        i++;
      }
      while (j >= lo && a[j] <= pivot) {
        j--;
      }
      if (i >= j) {
        break;
      }
      swap(a, i, j);
    }
    swap(a, hi, i);
    return i;
  }

  private void swap(int[] a, int i, int j) {
    int tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
  }

  /**
   * Try using start as pivot. What changes need to be done?
   * mid now returns the ranking, not the index.
   * So it can directly compare with k instead of k-1.
   * But when we return we must convert mid to the correct index.
   * Since mid also means how many numbers are from pivot to the end, index = nums.length - mid.
   */
  public int findKthLargest3(int[] nums, int k) {
    int lo = 0;
    int hi = nums.length - 1;
    while (lo < hi) {
      int mid = partition2(nums, lo, hi);
      if (mid == k) {
        break;
      } else if (mid > k) {
        lo = nums.length - mid + 1;
      } else {
        hi = nums.length - mid - 1;
      }
    }
    return nums[nums.length - k];
  }

  /**
   * Using start as pivot, not end.
   * Swap with the pointer moving backward, j.
   * So j's right should only have numbers > pivot.
   */
  private int partition2(int[] nums, int s, int e) {
    int p = nums[s];
    int i = s + 1;
    int j = e;
    while (true) {
      while (i < e && nums[i] <= p) i++;
      while (j > s && nums[j] > p) j--;
      if (i >= j) break;
      swap(nums, i, j);
    }
    swap(nums, s, j);
    return nums.length - j;
  }
}