text:
""" Tools to automate creation of workstation, master, and worker AMIs. """
from cirruscluster import core
import logging
import pkg_resources

class AmiSpecification(object):
  """ Parameters of the ami to be created. """
  def __init__(self, ami_release_name, region_name, instance_type,
               ubuntu_release_name, mapr_version, role, owner_id = 'self'):
    assert(region_name in ['us-west-1', 'us-east-1'])
    assert(instance_type in ['c1.xlarge', 'cc2.8xlarge'])
    assert(ubuntu_release_name in ['precise'])
    assert(mapr_version in ['v2.1.3'])
    assert(role in ['workstation', 'master', 'worker'])
    self.ami_release_name = ami_release_name
    self.owner_id = owner_id
    self.region_name = region_name
    self.instance_type = instance_type
    self.ubuntu_release_name = ubuntu_release_name
    self.mapr_version = mapr_version
    self.role = role
    self.root_store_type, self.virtualization_type = \
      core.GetRootStoreAndVirtualizationType(self.instance_type)
    # Currently only have tools to create ebs backed amis...
    self.root_store_type = 'ebs'
    self.ami_name = core.AmiName(ami_release_name, ubuntu_release_name,
                                    self.virtualization_type, self.mapr_version,
                                    self.role)
    return

def GetAmi(ec2, ami_spec):
    """ Get the boto ami object given a AmiSpecification object. """
    images = ec2.get_all_images(owners=[ami_spec.owner_id] )
    requested_image = None
    for image in images:
      if image.name == ami_spec.ami_name:
        requested_image = image
        break
    return requested_image

class AmiBuilder(object):
  """ Creates an ubuntu ami pre-configured for different cirrus roles. """
  def __init__(self, ec2, ami_spec, key_pair_name, ssh_key):
    self.ec2 = ec2
    self.ami_spec = ami_spec
    self.key_pair = ec2.get_key_pair(key_pair_name)
    self.ssh_key = ssh_key

    # Fail if an image matching this spec already exists
    if GetAmi(self.ec2, self.ami_spec):
      ami_webui_url = 'https://console.aws.amazon.com/ec2/home?' \
                      'region=%s#s=Images' % self.ami_spec.region_name
      raise RuntimeError('An AMI for this role already exists.  Please manually'
                         ' delete it here: %s' % ami_webui_url)
    return

  def Run(self):
    """ Build the Amazon Machine Image. """
    template_instance = None
    res = self.ec2.get_all_instances( \
            filters={'tag-key': 'spec',
                     'tag-value' : self.ami_spec.ami_name,
                     'instance-state-name' : 'running'})
    if res:
      running_template_instances = res[0].instances
      if running_template_instances:
        assert(len(running_template_instances) == 1)
        template_instance = running_template_instances[0]
    # if there is not a currently running template instance, start one
    if not template_instance:
      template_instance = self.__CreateTemplateInstance()
      template_instance.add_tag('spec', self.ami_spec.ami_name)
    assert(template_instance)
    if self.ami_spec.role == 'workstation':
      self.__ConfigureAsWorkstation(template_instance)
    elif self.ami_spec.role == 'master':
      self.__ConfigureAsClusterMaster(template_instance)
    elif self.ami_spec.role == 'worker':
      self.__ConfigureAsClusterWorker(template_instance)
    else:
      raise RuntimeError('unknown role: %s' % (self.ami_spec.role))

    print 'Please login and perform any custom manipulations before '\
          'snapshot is made!'

    raw_input('Press any key to shutdown and begin creating AMI. '\
              '(or ctrl-c to quit and re-run config process).')

    self.__SecurityScrub(template_instance)

    ami_id = None
    if self.ami_spec.root_store_type == 'ebs':
      ami_id = self.__CreateEbsAmi(template_instance)
    else:
      logging.info('Support for creating instance-store backed images has been'
                   ' disabled in this version because it required much greater'
                   ' complexity.')
      ami_id = self.__CreateEbsAmi(template_instance)

    logging.info('ami id: %s' % (ami_id))
    # TODO(heathkh): implement these features...

    #self.__SetImagePermissions(ami_id)
    #self.__DistributeImageToAllRegions(ami_id)

    print 'terminating template instance'
    self.ec2.terminate_instances(instance_ids=[template_instance.id])
    core.WaitForInstanceTerminated(template_instance)
    return

  def GetInstanceById(self, instance_id):
    reservations = self.ec2.get_all_instances([instance_id])
    instance = None
    for r in reservations:
       for i in r.instances:
         if i.id == instance_id:
           instance = i
           break
    return instance

  def __CreateTemplateInstance(self):
    template_image = self.__GetTemplateImage()
    self.__CreateSshSecurityGroup()
    reservation = template_image.run(key_name=self.key_pair.name,
                                     security_groups=['ssh'],
                                     instance_type=self.ami_spec.instance_type)
    instance = reservation.instances[0]
    core.WaitForInstanceRunning(instance)
    core.WaitForHostsReachable([instance.public_dns_name], self.ssh_key)
    return instance

  def __ConfigureAsWorkstation(self, instance):
    logging.info('Configuring a workstation...')
    playbook = pkg_resources.resource_filename(__name__,
      'playbooks/workstation/workstation.yml')
    extra_vars = {'mapr_version' : self.ami_spec.mapr_version,
                  'ubuntu_password': core.default_workstation_password}
    assert(core.RunPlaybookOnHost(playbook, instance.dns_name, self.ssh_key,
                                  extra_vars = extra_vars))

    dsa_key = '/usr/NX/share/keys/default.id_dsa.key'
    nx_client_ssh_key = core.ReadRemoteFile(dsa_key, instance.dns_name,
                                            self.ssh_key)
    print 'To connect with NX Client, you must paste this key into the gui '\
          'advanced settings config.'
    print nx_client_ssh_key
    return

  def __ConfigureAsClusterMaster(self, instance):
    logging.info('Configuring a cluster master...')
    #playbook = os.path.dirname(__file__) + '/templates/cluster/master.yml'
    playbook = pkg_resources.resource_filename(__name__,
                                               'playbooks/cluster/master.yml')
    extra_vars = {'mapr_version' : self.ami_spec.mapr_version,
                  'is_master' : True}
    assert(core.RunPlaybookOnHost(playbook, instance.dns_name, self.ssh_key,
                                  extra_vars = extra_vars))
    return

  def __ConfigureAsClusterWorker(self, instance):
    logging.info('Configuring a cluster worker...')
    #playbook = os.path.dirname(__file__) + '/templates/cluster/worker.yml'
    playbook = pkg_resources.resource_filename(__name__,
                                               'playbooks/cluster/worker.yml')
    extra_vars = {'mapr_version' : self.ami_spec.mapr_version}
    assert(core.RunPlaybookOnHost(playbook, instance.dns_name, self.ssh_key,
                                  extra_vars = extra_vars))
    return

  def __SecurityScrub(self, instance):

    # ensure no cirrus keys directory remains (workstation)
    cmd = 'sudo rm -rf /home/ubuntu/.ec2'
    assert(core.RunCommandOnHost(cmd, instance.dns_name, self.ssh_key))

    # delete the shell history
    cmd = 'sudo find /root/.*history /home/*/.*history -exec rm -f {} \\;'
    assert(core.RunCommandOnHost(cmd, instance.dns_name, self.ssh_key))
    # Clear cache of known hosts, otherwise first login fails
    cmd = 'sudo rm /usr/NX/home/nx/.ssh/known_hosts'
    core.RunCommandOnHost(cmd, instance.dns_name, self.ssh_key)
    # Only run this right before you create the ami
    # After you do this, you can't make a new connection via shared key auth
    cmd = 'sudo find / -name "authorized_keys" -exec rm -f {} \\;'
    assert(core.RunCommandOnHost(cmd, instance.dns_name, self.ssh_key))
    return

  def __CreateEbsAmi(self, instance):
    # details here:
    #http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-ebs.html
    # step 1: stop the instance so it is in a consistent state
    self.ec2.stop_instances(instance_ids=[instance.id])
    # wait till stopped
    core.WaitForInstanceStopped(instance)
    logging.info('instance stopped...'
                 ' ready to create image: %s' % (instance.id))
    ami_description = self.ami_spec.ami_name
    new_ami_id = self.ec2.create_image(instance.id, self.ami_spec.ami_name,
                                       ami_description)
    logging.info('new ami: %s' % (new_ami_id))
    return new_ami_id

  def __SetImagePermissions(self, ami_id):
    new_images = self.ec2.get_all_images(image_ids=[ami_id])
    assert(len(new_images) == 1)
    new_image = new_images[0]
    new_image.set_launch_permissions(group_names=['all'])
    return

  def __CreateSshSecurityGroup(self):
    ssh_group = None
    try:
      groups = self.ec2.get_all_security_groups(['ssh'])
      ssh_group = groups[0]
    except:
      pass

    if not ssh_group:
      ssh_group = self.ec2.create_security_group('ssh', 'Our ssh group')
      ssh_group.authorize('tcp', 22, 22, '0.0.0.0/0')
    return

  def __GetTemplateImage(self):
    template_ami_id = core.SearchUbuntuAmiDatabase(
      self.ami_spec.ubuntu_release_name, self.ami_spec.region_name,
      self.ami_spec.root_store_type, self.ami_spec.virtualization_type)
    template_images = self.ec2.get_all_images([template_ami_id])
    if (len(template_images) != 1):
      raise RuntimeError('Can\'t find image: %s' % (template_images))
    template_image = template_images[0]
    return template_image


text:
<Configuration xmlns="http://itude.com/schemas/MB/2.0">
	<Controller>
        <Actions>
        	<Action name="GetHomePageContent" className="GetHomePageContent"/>
        	<Action name="LoginAction" className="LoginAction"/>
        	<Action name="LogoutAction" className="LogoutAction"/>
		</Actions>
	</Controller>
</Configuration>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="digital_time_text_size">40dp</dimen>
    <dimen name="digital_time_text_size_round">45dp</dimen>
    <dimen name="digital_date_text_size">20dp</dimen>
    <dimen name="digital_date_text_size_round">25dp</dimen>
    <dimen name="digital_temperature_text_size">30dp</dimen>
    <dimen name="digital_temperature_text_size_round">35dp</dimen>
    <dimen name="digital_x_offset">15dp</dimen>
    <dimen name="digital_x_offset_round">25dp</dimen>
    <dimen name="digital_y_offset">90dp</dimen>
</resources>


text:
package gobblin.util.limiter;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.Semaphore;

import com.google.common.primitives.Ints;

/**
 * An implementation of {@link Limiter} that ony allows permits to be acquired from a pool.
 *
 * <p>
 *   This implementation uses a {@link Semaphore} as a permit pool. {@link #acquirePermits(long)}
 *   is blocking and will always return {@link true} after the permits are successfully acquired
 *   (probably after being blocked for some amount of time). Permit refills are supported by this
 *   implementation using {@link Semaphore#release(int)}. Also {@link #acquirePermits(long)} only
 *   accepts input arguments that can be safely casted to an integer bounded by
 *   {@link Integer#MAX_VALUE}.
 * </p>
 *
 * @author Yinan Li
 */
public class PoolBasedLimiter implements Limiter {

  private final Semaphore permitPool;

  public PoolBasedLimiter(int poolSize) {
    this.permitPool = new Semaphore(poolSize);
  }

  @Override
  public void start() {
    // Nothing to do
  }

  @Override
  public Closeable acquirePermits(long permits)
      throws InterruptedException {
    int permitsToAcquire = Ints.checkedCast(permits);
    this.permitPool.acquire(permitsToAcquire);
    return new PoolPermitCloseable(this.permitPool, permitsToAcquire);
  }

  @Override
  public void stop() {
    // Nothing to do
  }

  private static class PoolPermitCloseable implements Closeable {

    private final Semaphore permitPool;
    private final int permits;

    public PoolPermitCloseable(Semaphore permitPool, int permits) {
      this.permitPool = permitPool;
      this.permits = permits;
    }

    @Override
    public void close()
        throws IOException {
      this.permitPool.release(this.permits);
    }
  }
}


text:
QiFi
========

License
-------
Expat/MIT License. See the `LICENSE` file for details.

Installation
------------
1. `git clone https://github.com/evgeni/qifi.git`
1. `git submodules init`
1. `git submodules update`

Configuration
-------------
Really? Configuration? There is none.

Usage
-----
Open `index.html` in a browser.


text:
package Muscle::MuscleImpl;
use strict;
use Bio::KBase::Exceptions;
# Use Semantic Versioning (2.0.0-rc.1)
# http://semver.org
our $VERSION = "0.1.0";

=head1 NAME

Muscle

=head1 DESCRIPTION

A KBase module: Muscle
This sample module contains one small method - filter_contigs.

=cut

#BEGIN_HEADER
use Bio::KBase::AuthToken;
use Bio::KBase::workspace::Client;
use Config::IniFiles;
use Data::Dumper;
#END_HEADER

sub new
{
    my($class, @args) = @_;
    my $self = {
    };
    bless $self, $class;
    #BEGIN_CONSTRUCTOR

    my $config_file = $ENV{ KB_DEPLOYMENT_CONFIG };
    my $cfg = Config::IniFiles->new(-file=>$config_file);
    my $wsInstance = $cfg->val('Muscle','workspace-url');
    die "no workspace-url defined" unless $wsInstance;

    $self->{'workspace-url'} = $wsInstance;

    #END_CONSTRUCTOR

    if ($self->can('_init_instance'))
    {
	$self->_init_instance();
    }
    return $self;
}

=head1 METHODS

=head2 filter_contigs

  $return = $obj->filter_contigs($params)

=over 4

=item Parameter and return types

=begin html

$params is a Muscle.FilterContigsParams
$return is a Muscle.FilterContigsResults
FilterContigsParams is a reference to a hash where the following keys are defined:
	workspace has a value which is a Muscle.workspace_name
	contigset_id has a value which is a Muscle.contigset_id
	min_length has a value which is an int
workspace_name is a string
contigset_id is a string
FilterContigsResults is a reference to a hash where the following keys are defined:
	new_contigset_ref has a value which is a Muscle.ws_contigset_id
	n_initial_contigs has a value which is an int
	n_contigs_removed has a value which is an int
	n_contigs_remaining has a value which is an int
ws_contigset_id is a string

=end html

=begin text

$params is a Muscle.FilterContigsParams
$return is a Muscle.FilterContigsResults
FilterContigsParams is a reference to a hash where the following keys are defined:
	workspace has a value which is a Muscle.workspace_name
	contigset_id has a value which is a Muscle.contigset_id
	min_length has a value which is an int
workspace_name is a string
contigset_id is a string
FilterContigsResults is a reference to a hash where the following keys are defined:
	new_contigset_ref has a value which is a Muscle.ws_contigset_id
	n_initial_contigs has a value which is an int
	n_contigs_removed has a value which is an int
	n_contigs_remaining has a value which is an int
ws_contigset_id is a string

=end text

=item Description

Filter contigs in a ContigSet by DNA length

=back

=cut

sub run_muscle
{
    my $self = shift;
    my($params) = @_;

    my @_bad_arguments;
    (ref($params) eq 'HASH') or push(@_bad_arguments, "Invalid type for argument \"params\" (value was \"$params\")");
    if (@_bad_arguments) {
	my $msg = "Invalid arguments passed to run_muscle:\n" . join("", map { "\t$_\n" } @_bad_arguments);
	Bio::KBase::Exceptions::ArgumentValidationError->throw(error => $msg,
							       method_name => 'run_muscle');
    }

    my $ctx = $Muscle::MuscleServer::CallContext;
    my($return);
    #BEGIN run_muscle

    print("Starting run muscle method.\n");

    if (!exists $params->{'workspace'}) {
        die "Parameter workspace is not set in input arguments";
    }
    my $workspace_name=$params->{'workspace'};

		if (!exists $params->{'feature_ids'}) {
        print  "Parameter feature_ids is not set in input arguments";
    }
    my $feature_ids=$params->{'feature_ids'};

    if (!exists $params->{'featureset_id'}) {
        print  "Parameter featureset_id is not set in input arguments";
    }
    my $featureset_id=$params->{'featureset_id'};

		if (!exists $params->{'feature_ids'} && !exists $params->{'featureset_id'}){
			die "Parameter feature_ids or featureset_id is required!!";
		}

    if (!exists $params->{'seq_type'}) {
        die "Parameter seq_type is not set in input arguments";
    }
    my $seq_type = $params->{'seq_type'};

    my $token=$ctx->token;
    my $provenance=$ctx->provenance;
    my $wsClient=Bio::KBase::workspace::Client->new($self->{'workspace-url'},token=>$token);
    my $featureSet=undef;

		my @fasta = ();

		foreach my $feature_id (@{$params->{'feature_ids'}}){

			my $feature=$wsClient->get_objects([{workspace=>$workspace_name,name=>$feature_id}])->[0]{data};

			#print "Feature_id: $feature_id\n";
			#print "Feature data:\n". Dumper($feature). "\n\n";

			push @fasta, ">$feature->{id}   $feature->{function}\n$feature->{dna_sequence}\n" if $params->{seq_type} eq 'NA';
			push @fasta, ">$feature->{id}   $feature->{function}\n$feature->{protein_translation}\n" if $params->{seq_type} eq 'AA';

		}

		my $fasta = join "", @fasta;

		#print "$fasta\n";

		my $muscle_out = "";

		$muscle_out = `echo "$fasta" \| muscle -clw`;

		print "\n\n$muscle_out\n\n";

=pod

		eval {
        $featureSet=$wsClient->get_objects([{workspace=>$workspace_name,name=>$featureset_id}])->[0]{data};
    };
    if ($@) {
        die "Error loading original FeatureSet object from workspace:\n".$@;
    }
    my $features=$featureSet->{features};

    print("Got FeatureSet data.\n");

		foreach my $feature_id (@{$params->{'featureset_ids'}}){
			print "$feature_id\n";
			my $feature=$wsClient->get_objects([{workspace=>$workspace_name,name=>$feature_id}])->[0]{data};

			print Dumper $feature."\n\n";

		}

=pod
    my $good_contigs=[];
    my $n_total = 0;
    my $n_remaining = 0;
    for my $contig (@$contigs) {
        $n_total++;
        if (length($contig->{'sequence'}) >= $min_length) {
            push(@$good_contigs, $contig);
            $n_remaining++;
        }
    }

    # replace the contigs in the contigSet object in local memory
    $contigSet->{'contigs'} = $good_contigs;

    print("Filtered ContigSet to ".$n_remaining." contigs out of ".$n_total."\n");

################## stopped here

    # save the new object to the workspace
    my $obj_info_list = undef;
    eval {
        $obj_info_list = $wsClient->save_objects({
            'workspace'=>$workspace_name,
            'objects'=>[{
                'type'=>'KBaseGenomes.ContigSet',
                'data'=>$contigSet,
                'name'=>$contigset_id,
                'provenance'=>$provenance
            }]
        });
    };
    if ($@) {
        die "Error saving filtered ContigSet object to workspace:\n".$@;
    }
    my $info = $obj_info_list->[0];

    print("saved:".Dumper($info)."\n");

    $return = {
        'new_contigset_ref'=>$info->[6].'/'.$info->[0].'/'.$info->[4],
        'n_initial_contigs'=>$n_total,
        'n_contigs_removed'=>$n_total-$n_remaining,
        'n_contigs_remaining'=>$n_remaining
    };

    print("returning: ".Dumper($return)."\n");
=cut

    #END run_muscle
    my @_bad_returns;
    (ref($return) eq 'HASH') or push(@_bad_returns, "Invalid type for return variable \"return\" (value was \"$return\")");
    if (@_bad_returns) {
	my $msg = "Invalid returns passed to run_muscle:\n" . join("", map { "\t$_\n" } @_bad_returns);
	Bio::KBase::Exceptions::ArgumentValidationError->throw(error => $msg,
							       method_name => 'run_muscle');
    }
    return($return);
}

=head2 version

  $return = $obj->version()

=over 4

=item Parameter and return types

=begin html

$return is a string

=end html

=begin text

$return is a string

=end text

=item Description

Return the module version. This is a Semantic Versioning number.

=back

=cut

sub version {
    return $VERSION;
}

=head1 TYPES

=head2 contigset_id

=over 4

=item Description

A string representing a ContigSet id.

=item Definition

=begin html

a string

=end html

=begin text

a string

=end text

=back

=head2 workspace_name

=over 4

=item Description

A string representing a workspace name.

=item Definition

=begin html

a string

=end html

=begin text

a string

=end text

=back

=head2 FilterContigsParams

=over 4

=item Definition

=begin html

a reference to a hash where the following keys are defined:
workspace has a value which is a Muscle.workspace_name
contigset_id has a value which is a Muscle.contigset_id
min_length has a value which is an int

=end html

=begin text

a reference to a hash where the following keys are defined:
workspace has a value which is a Muscle.workspace_name
contigset_id has a value which is a Muscle.contigset_id
min_length has a value which is an int

=end text

=back

=head2 ws_contigset_id

=over 4

=item Description

The workspace ID for a ContigSet data object.
@id ws KBaseGenomes.ContigSet

=item Definition

=begin html

a string

=end html

=begin text

a string

=end text

=back

=head2 FilterContigsResults

=over 4

=item Definition

=begin html

a reference to a hash where the following keys are defined:
new_contigset_ref has a value which is a Muscle.ws_contigset_id
n_initial_contigs has a value which is an int
n_contigs_removed has a value which is an int
n_contigs_remaining has a value which is an int

=end html

=begin text

a reference to a hash where the following keys are defined:
new_contigset_ref has a value which is a Muscle.ws_contigset_id
n_initial_contigs has a value which is an int
n_contigs_removed has a value which is an int
n_contigs_remaining has a value which is an int

=end text

=back

=cut

1;


text:
title: "Simple slow-rotation neutron star structure solver"
modified:
categories: code
excerpt:
link: https://github.com/duetosymmetry/simple-slow-rot-NS-solver
tags: [code, compact objects, scientific computing]
date: 2017-09-08T14:24:09-07:00
---

I'm releasing into the wild [a simple code for computing neutron star
structure in the slow-rotation
expansion](https://github.com/duetosymmetry/simple-slow-rot-NS-solver)
to first and second order.  This code was originally from Nico Yunes,
with a bunch of development by Kent Yagi.  I rewrote huge chunks of it
to give it a command line/config file interface, turned some magic
numbers into configurable parameters, C++ified some important bits,
etc.  Kent gave me his blessing to release it into the wild.  For IP
reasons, I first had to remove the dependence on code from Numerical
Recipes, which is why it looks like the commit history starts in
Sept. 2017.

Of course there are already codes like
[RNS](http://www.gravity.phys.uwm.edu/rns/) and
[LORENE](http://www.lorene.obspm.fr/), so who needs another NS code?
This code is useful for two reasons:

1. There is a modular implementation of the piecewise-polytropic model
from Read, Lackey, Owen, and Friedman (2009)
[[arXiv:0812.2163](https://arxiv.org/abs/0812.2163)] along with their
fits for named EOSs; and
2. The slow-rotation expansion allows to
accurately extract the moment of inertia and quadrupole moment.

Feel free to improve the code in any way you see fit and send me a
pull request, or open a new issue, anything you want under the MIT
license.


text:
package com.cola.lib.jpa.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * cola
 * Created by jiachen.shi on 7/20/2016.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Inherited
@Documented
public @interface RetryOnOptimisticLockingFailure {
    /**
     * Max retries int.
     * @return the int
     */
    int maxRetries() default 3;
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Rawr.DPSDK
{
    public enum RunesUsed
    {
        Blood,
        Frost,
        Unholy,
        UnholyFrost,
        RunicPower,
        BloodUnholyFrost,
        None
    }
    public enum GCDType
    {
        Spell,
        Melee,
        None
    }

    public abstract class RuneAbility
    {
        private Character _character;

        public Character character
        {
            get { return _character; }
            set { _character = value; }
        }

        private String _name;
        public String Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private double _damageMod;
        public double DamageMod
        {
            get { return _damageMod; }
            set { _damageMod = value; }
        }

        private double _secondaryDamageMod;
        public double SecondaryDamageMod
        {
            get { return _secondaryDamageMod; }
            set { _secondaryDamageMod = value; }
        }

        public abstract double Damage { get; }

        public abstract double SecondaryDamage{get;}

        private double _staticThreat;
        public double StaticThreat
        {
            get { return _staticThreat; }
            set { _staticThreat = value; }
        }

        private double _threatMod;
        public double ThreatMod
        {
            get { return _threatMod; }
            set { _threatMod = value; }
        }
        private Stats _stats;
        public Stats stats
        {
            get { return _stats; }
            set { _stats = value; }
        }

        private CombatTable _combatTable;

        public CombatTable combatTable
        {
            get { return _combatTable; }
            set { _combatTable = value; }
        }

        private RunesUsed _runes;

        public RunesUsed Runes
        {
            get { return _runes; }
            set { _runes = value; }
        }
        private GCDType gcdType;

        public GCDType GcdType
        {
            get { return gcdType; }
            set { gcdType = value; }
        }
        private CalculationOptionsDPSDK _calcOpts;

        public CalculationOptionsDPSDK calcOpts
        {
            get { return _calcOpts; }
            set { _calcOpts = value; }
        }
        private DeathKnightTalents _talents;
        public DeathKnightTalents talents
        {
            get { return _talents; }
            set { _talents = value; }
        }
        private double _threat;
        public double Threat
        {
            get
            {
                _threat = Damage + SecondaryDamage;
                _threat += StaticThreat;
                _threat *= ThreatMod;
                if (calcOpts.rotation.presence != CalculationOptionsDPSDK.Presence.Frost)
                {
                    _threat *= 0.8f;
                    _threat *= 1f - (talents.Subversion * 25d / 3d);
                }
                else
                {
                    _threat *= 1.45f;
                }
                return _threat;
            }
        }
        public RuneAbility()
        {
            character = null;
            stats = null;
            combatTable = null;
            Runes = RunesUsed.Blood;
            gcdType = GCDType.Melee;
            calcOpts = null;
        }
        public override String ToString()
        {
            return Name;
        }
    }

    public class BloodStrike : RuneAbility
    {
        public BloodStrike(Character c, Stats s, CalculationOptionsDPSDK CalcOpts, CombatTable table, DeathKnightTalents Talents)
        {
            character = c; stats = s; calcOpts = CalcOpts; combatTable = table; GcdType = GCDType.Melee; Runes = RunesUsed.Blood; talents = Talents; Name = "Blood Strike";
        }
        private double _damage;
        public override double Damage
        {
            get
            {
                double BSDmg = ((combatTable.MH.baseDamage + ((stats.AttackPower / 14d) * combatTable.normalizationFactor) + 764d) *
                            0.4d) + stats.BonusBloodStrikeDamage;
                if (combatTable.DW)
                {
                    double BSDmgOH = ((combatTable.OH.baseDamage + ((stats.AttackPower / 14d) *
                            combatTable.normalizationFactor) + 764d) * 0.4d);
                    BSDmgOH *= 0.5d;
                    BSDmgOH += stats.BonusBloodStrikeDamage;
                    BSDmgOH *= 1d + 0.08333333333d * (double)talents.NervesOfColdSteel;
                    BSDmgOH *= (talents.ThreatOfThassarian * (1d / 3d));
                    BSDmg += BSDmgOH;
                }
                BSDmg *= 1d + 0.125d * (double)calcOpts.rotation.AvgDiseaseMult * (1d + stats.BonusPerDiseaseBloodStrikeDamage);
                _damage = BSDmg;
                double BSCritDmgMult = 1d + (.15d * (double)talents.MightOfMograine);
                BSCritDmgMult += (.15d * (double)talents.GuileOfGorefiend) + stats.BonusCritMultiplier;
                double BSCrit = 1d + ((combatTable.physCrits + (.03f * (double)talents.Subversion)) * BSCritDmgMult);
                _damage = (_damage) * BSCrit;
                return _damage * DamageMod;
            }
        }
        public override double SecondaryDamage
        {
            get { return 0; }
        }
    }

    public class  DeathCoil : RuneAbility
    {
        public DeathCoil(Character c, Stats s, CalculationOptionsDPSDK CalcOpts, CombatTable table, DeathKnightTalents Talents)
        {
            character = c; stats = s; calcOpts = CalcOpts; combatTable = table; GcdType = GCDType.Spell; Runes = RunesUsed.RunicPower; talents = Talents; Name = "Death Coil";
        }
        private double _damage;
        public override double Damage
        {
            get
            {
                _damage = 443f + ((0.15d * (1d + (talents.Impurity * .04d))) * stats.AttackPower) + stats.BonusDeathCoilDamage;
                double DCCritDmgMult = 0.5f * (2f + stats.BonusCritMultiplier);
                double DCCrit = 1d + ((combatTable.spellCrits + stats.BonusDeathCoilCrit) * DCCritDmgMult);
                _damage *= DCCrit;
                return _damage * DamageMod;
            }
        }
        public override double SecondaryDamage
        {
            get { return 0; }
        }
    }

    public class IcyTouch : RuneAbility
    {
        public IcyTouch(Character c, Stats s, CalculationOptionsDPSDK CalcOpts, CombatTable table, DeathKnightTalents Talents)
        {
            character = c; stats = s; calcOpts = CalcOpts; combatTable = table; GcdType = GCDType.Spell; Runes = RunesUsed.Frost; talents = Talents; Name = "Icy Touch";
        }
        private double _damage;
        public override double Damage
        {
            get
            {
                _damage = 236f + ((0.1d * (1d + talents.Impurity * .04d)) * stats.AttackPower) + stats.BonusIcyTouchDamage;
                double ITCritDmgMult = .5f * (2f + stats.CritBonusDamage + stats.BonusCritMultiplier);
                double ITCrit = 1f + (Math.Min((combatTable.spellCrits + (.05f * (float)talents.Rime)), 1f) * ITCritDmgMult);
                _damage *= ITCrit;
                return _damage * DamageMod;
            }
        }
        public override double SecondaryDamage
        {
            get { return 0; }
        }
    }

    public class PlagueStrike : RuneAbility
    {
        public PlagueStrike(Character c, Stats s, CalculationOptionsDPSDK CalcOpts, CombatTable table, DeathKnightTalents Talents)
        {
            character = c; stats = s; calcOpts = CalcOpts; combatTable = table; talents = Talents; GcdType = GCDType.Melee; Runes = RunesUsed.Unholy; Name = "Plague Strike";
        }
        private double _damage;
        public override double Damage
        {
            get
            {
                _damage = (combatTable.MH.baseDamage + ((stats.AttackPower / 14f) *
                                        combatTable.normalizationFactor) + 378f) * 0.5f;
                _damage += ((combatTable.DW ? ((combatTable.OH.baseDamage + ((stats.AttackPower / 14f) *
                                        combatTable.normalizationFactor) + 378f) * 0.5f) : 0d) * talents.ThreatOfThassarian / 3d) *
                    (0.5d * 1d + talents.NervesOfColdSteel * .0833333333d);
                double PSCritDmgMult = 1d + (.15d * talents.ViciousStrikes) + stats.BonusCritMultiplier;
                PSCritDmgMult = 1d + ((combatTable.physCrits + (.03d * talents.ViciousStrikes) + stats.BonusPlagueStrikeCrit) * PSCritDmgMult);
                _damage *= PSCritDmgMult;
                return _damage * DamageMod;
            }
        }
        public override double SecondaryDamage
        {
            get { return 0; }
        }
    }

    public class ScourgeStrike : RuneAbility
    {
        public ScourgeStrike(Character c, Stats s, CalculationOptionsDPSDK CalcOpts, CombatTable table, DeathKnightTalents Talents)
        {
            character = c; stats = s; calcOpts = CalcOpts; combatTable = table; talents = Talents; GcdType = GCDType.Melee; Runes = RunesUsed.UnholyFrost; Name = "Scourge Strike";
        }

        private double _damage;
        public override double Damage
        {
            get
            {
                _damage = (combatTable.MH.baseDamage + ((stats.AttackPower / 14d) *
                                combatTable.normalizationFactor)) * 0.7d + 560d + stats.BonusScourgeStrikeDamage;
                double SSCritDmgMult = 1d + .15d * talents.ViciousStrikes + stats.BonusCritMultiplier;
                SSCritDmgMult = 1d + ((combatTable.physCrits + .03d * (talents.ViciousStrikes + talents.Subversion) + stats.BonusScourgeStrikeCrit) * SSCritDmgMult);
                _damage *= SSCritDmgMult;
                _damage *= DamageMod;
                return _damage;
            }
        }
        private double _secondaryDamage;
        public override double SecondaryDamage
        {
            get
            {
                _secondaryDamage = Damage * calcOpts.rotation.AvgDiseaseMult * .12d;
                double SSCritDmgMult = 1d + .15d * talents.ViciousStrikes + stats.BonusCritMultiplier;
                SSCritDmgMult = 1d + ((combatTable.physCrits + .03d * (talents.ViciousStrikes + talents.Subversion) + stats.BonusScourgeStrikeCrit) * SSCritDmgMult);
                SSCritDmgMult = 1d;
                _secondaryDamage *= SSCritDmgMult;
                _secondaryDamage *= SecondaryDamageMod;
                return _secondaryDamage;
            }
        }
    }

    public class HowlingBlast : RuneAbility
    {
        public HowlingBlast(Character c, Stats s, CalculationOptionsDPSDK CalcOpts, CombatTable table, DeathKnightTalents Talents)
        {
            character = c; stats = s; calcOpts = CalcOpts; combatTable = table; talents = Talents; GcdType = GCDType.Spell; Runes = RunesUsed.UnholyFrost; Name = "Howling Blast";
        }
        private double _damage;
        public override double Damage
        {
            get
            {
                _damage = 540 + 0.2d * (1d + talents.Impurity * .04d) * stats.AttackPower;
                double HBCritDmgMult = (0.5d * (2d + (.15d * talents.GuileOfGorefiend) + stats.BonusCritMultiplier));
                HBCritDmgMult = 1d + (Math.Min((combatTable.spellCrits), 1d) * HBCritDmgMult);
                _damage *= HBCritDmgMult;
                _damage *= DamageMod;
                return _damage;
            }
        }
        private double _secondaryDamage;
        public override double SecondaryDamage
        {
            get
            {
                _secondaryDamage = 540 + 0.2d * (1d + talents.Impurity * .04d) * stats.AttackPower;
                double HBCritDmgMult = (0.5d * (2d + (.15d * talents.GuileOfGorefiend) + stats.BonusCritMultiplier));
                HBCritDmgMult = 1d + HBCritDmgMult;
                _secondaryDamage *= HBCritDmgMult;
                _secondaryDamage *= DamageMod;
                return _secondaryDamage;
            }
        }
    }

    public class FrostStrike : RuneAbility
    {
        public FrostStrike(Character c, Stats s, CalculationOptionsDPSDK CalcOpts, CombatTable table, DeathKnightTalents Talents)
        {
            character = c; stats = s; calcOpts = CalcOpts; combatTable = table; talents = Talents; GcdType = GCDType.Melee; Runes = RunesUsed.RunicPower; Name = "Frost Strike";
        }
        private double _damage;
        public override double Damage
        {
            get
            {
                _damage = ((combatTable.MH.baseDamage + ((stats.AttackPower / 14d) *
                                combatTable.normalizationFactor)) +
                                250d) * 0.55d + stats.BonusFrostStrikeDamage;
                _damage += ((!combatTable.DW ? 0 : (((combatTable.OH.baseDamage + ((stats.AttackPower / 14d) *
                                combatTable.normalizationFactor)) +
                                250d) * 0.55d * 0.5d) + stats.BonusFrostStrikeDamage)
                                        * (1d + (talents.NervesOfColdSteel * .083333333333d))) * talents.ThreatOfThassarian / 3d;
                double FSCritDmgMult = 1d + .15d * talents.GuileOfGorefiend + stats.BonusCritMultiplier;
                FSCritDmgMult = 1d + (Math.Min((combatTable.physCrits + stats.BonusFrostStrikeCrit), 1d) * FSCritDmgMult);
                _damage *= FSCritDmgMult;
                _damage *= DamageMod;
                return _damage;
            }
        }

        private double _secondaryDamage;
        public override double SecondaryDamage
        {
            get
            {
                _secondaryDamage = ((combatTable.MH.baseDamage + ((stats.AttackPower / 14d) *
                                combatTable.normalizationFactor)) +
                                250d) * 0.55f + stats.BonusFrostStrikeDamage;
                _secondaryDamage += ((!combatTable.DW ? 0 : (((combatTable.OH.baseDamage + ((stats.AttackPower / 14d) *
                                combatTable.normalizationFactor)) +
                                250d) * 0.55d * 0.5d) + stats.BonusFrostStrikeDamage)
                                        * (1d + (talents.NervesOfColdSteel * .08333333333333d))) * talents.ThreatOfThassarian / 3d;
                double FSCritDmgMult = 1d + .15d * talents.GuileOfGorefiend + stats.BonusCritMultiplier;
                FSCritDmgMult = 1d + FSCritDmgMult;
                _secondaryDamage *= FSCritDmgMult;
                _secondaryDamage *= DamageMod;
                return _secondaryDamage;
            }
        }
    }

    public class Obliterate : RuneAbility
    {
        public Obliterate(Character c, Stats s, CalculationOptionsDPSDK CalcOpts, CombatTable table, DeathKnightTalents Talents)
        {
            character = c; stats = s; calcOpts = CalcOpts; combatTable = table; talents = Talents; GcdType = GCDType.Melee; Runes = RunesUsed.UnholyFrost; Name = "Obliterate";
        }

        private double _damage;
        public override double Damage
        {
            get
            {
                _damage = ((combatTable.MH.baseDamage + ((stats.AttackPower / 14d) * combatTable.normalizationFactor) + 584d) *
                    (talents.GlyphofObliterate ? 1 : 0.8d)) + stats.BonusObliterateDamage;
                _damage += ((!combatTable.DW ? 0 : (((combatTable.OH.baseDamage + ((stats.AttackPower / 14d) * combatTable.normalizationFactor) + 584f) *
                    (talents.GlyphofObliterate ? 1 : 0.8d)) * 0.5d) + stats.BonusObliterateDamage)
                                        * (1d + (talents.NervesOfColdSteel * .08333333333d))) * talents.ThreatOfThassarian / 3d;
                _damage *= 1f + (talents.GlyphofObliterate ? 0.1d : 0.125d) * calcOpts.rotation.AvgDiseaseMult * (1f + stats.BonusPerDiseaseObliterateDamage);
                double OblitCritDmgMult = 1d + (.15d * talents.GuileOfGorefiend) + stats.BonusCritMultiplier;
                OblitCritDmgMult = 1d + (combatTable.physCrits +
                        .03d * talents.Subversion +
                        .05d * talents.Rime +
                        stats.BonusObliterateCrit) * OblitCritDmgMult;
                _damage *= OblitCritDmgMult;
                _damage *= DamageMod;
                return _damage;
            }
        }
        public override double SecondaryDamage
        {
            get { return 0; }
        }
    }

    public class DeathStrike : RuneAbility
    {
        public DeathStrike(Character c, Stats s, CalculationOptionsDPSDK CalcOpts, CombatTable table, DeathKnightTalents Talents)
        {
            character = c; stats = s; calcOpts = CalcOpts; combatTable = table; talents = Talents; GcdType = GCDType.Melee; Runes = RunesUsed.UnholyFrost; Name = "Death Strike";
        }
        private double _damage;
        public override double Damage
        {
            get
            {
                _damage = ((combatTable.MH.baseDamage + ((stats.AttackPower / 14d) * combatTable.normalizationFactor) + 297) * 0.75d) + stats.BonusDeathStrikeDamage;
                _damage += ((!combatTable.DW ? 0 : (((combatTable.OH.baseDamage + ((stats.AttackPower / 14d) * combatTable.normalizationFactor) + 297) * 0.75d) * 0.5d) + stats.BonusDeathStrikeDamage)
                                        * (1d + (talents.NervesOfColdSteel * .0833333333333d))) * talents.ThreatOfThassarian / 3d;
                double DSCritDmgMult = 1d + (.15d * talents.MightOfMograine) + stats.BonusCritMultiplier;
                DSCritDmgMult = 1d + (combatTable.physCrits +
                     .03d * talents.ImprovedDeathStrike +
                     stats.BonusDeathStrikeCrit) * DSCritDmgMult;
                _damage *= DSCritDmgMult;
                _damage *= DamageMod;
                return _damage;
            }
        }
        public override double SecondaryDamage
        {
            get { return 0; }
        }
    }

    public class HeartStrike : RuneAbility
    {
        public HeartStrike(Character c, Stats s, CalculationOptionsDPSDK CalcOpts, CombatTable table, DeathKnightTalents Talents)
        {
            character = c; stats = s; calcOpts = CalcOpts; combatTable = table; talents = Talents; GcdType = GCDType.Melee; Runes = RunesUsed.Blood; Name = "Heart Strike";
        }

        private double _damage;
        public override double Damage
        {
            get
            {
                _damage = ((combatTable.MH.baseDamage + ((stats.AttackPower / 14f) * combatTable.normalizationFactor) + 736f) *
                            0.5f) + stats.BonusHeartStrikeDamage;
                _damage *= 1d + 0.1d * calcOpts.rotation.AvgDiseaseMult * (1d + stats.BonusPerDiseaseHeartStrikeDamage);
                double HSCritDmgMult = 1d + (.15d * talents.MightOfMograine) + stats.BonusCritMultiplier;
                HSCritDmgMult = 1d + ((combatTable.physCrits + (.03d * talents.Subversion)) * HSCritDmgMult);
                _damage *= HSCritDmgMult;
                _damage *= DamageMod;
                return _damage;
            }
        }
        public override double SecondaryDamage
        {
            get { return 0; }
        }
    }

    public class BloodBoil : RuneAbility
    {
        public BloodBoil(Character c, Stats s, CalculationOptionsDPSDK CalcOpts, CombatTable table, DeathKnightTalents Talents)
        {
            character = c; stats = s; calcOpts = CalcOpts; combatTable = table; talents = Talents; GcdType = GCDType.Spell; Runes = RunesUsed.Blood; Name = "Blood Boil";
        }

        private double _damage;
        public override double Damage
        {
            get
            {
                if (calcOpts.rotation.AvgDiseaseMult > 0)
                {
                    _damage = 295d + 0.095d * (1d + talents.Impurity * .04d) * stats.AttackPower;
                }
                else
                {
                    _damage = 200d + 0.06d * (1d + talents.Impurity * .04d) * stats.AttackPower;
                }
                double BloodBoilCritMult = .5d * (2d + stats.BonusCritMultiplier);
                BloodBoilCritMult = 1d + combatTable.spellCrits * BloodBoilCritMult;
                _damage *= BloodBoilCritMult;
                _damage *= DamageMod;
                return _damage;
            }
        }
        public override double SecondaryDamage
        {
            get { return 0; }
        }
    }

    public class Disease : RuneAbility
    {
        public Disease(Character c, Stats s, CalculationOptionsDPSDK Calcopts, CombatTable table, DeathKnightTalents Talents)
        {
            character = c; stats = s; calcOpts = Calcopts; combatTable = table; talents = Talents; GcdType = GCDType.None; Runes = RunesUsed.None; Name = "A Disease";
        }

        private int _duration = 0;
        public int Duration
        {
            get { return (_duration == 0 ? talents.Epidemic * 3 + 15 : _duration); }
            set { _duration = value; }
        }

        private double _damage;
        public override double Damage
        {
            get
            {
                _damage = stats.AttackPower * .055 * 1.15 * (1d + talents.Impurity * .04d);
                _damage *= DamageMod;
                return _damage;
            }
        }
        public override double SecondaryDamage
        {
            get { return 0; }
        }
    }
}


text:
using System;
using Core.Common;
using TheChan.Common.Core;

namespace TheChan.ViewModels {
    public class CloudflareViewModel : Tab {
        public CloudflareViewModel(IBoard board) {
            Board = board;
            DisplayName = Translate("Name");
            PageUri = Board.UrlService.GetFullUrl("/");
        }

        private IBoard Board { get; }
        public Uri PageUri { get; }
    }
}


text:
package org.jclouds.rackspace.cloudfiles.v1.blobstore.integration;

import static org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes.API_KEY_CREDENTIALS;

import java.util.Properties;

import org.jclouds.openstack.swift.v1.blobstore.integration.SwiftBlobLiveTest;
import org.testng.annotations.Test;

@Test(groups = "live", testName = "CloudFilesBlobLiveTest")
public class CloudFilesBlobLiveTest extends SwiftBlobLiveTest {

   public CloudFilesBlobLiveTest() {
      provider = "rackspace-cloudfiles";
   }

   @Override
   protected Properties setupProperties() {
      Properties props = super.setupProperties();
      setIfTestSystemPropertyPresent(props, API_KEY_CREDENTIALS);
      return props;
   }
}


text:
Graph::Graph(MainWindow* p_main)
{
    main = p_main;
}

Graph::Graph(const Graph& rvalue): chicken(rvalue.chicken), vertices(rvalue.vertices), cameFrom(rvalue.cameFrom)
{

}

std::shared_ptr<Vertex> Graph::addVertex(int xpos, int ypos, bool isWall, bool hasPill, bool hasWeapon)
{
    std::shared_ptr<Vertex> vertex = std::make_shared<Vertex>(xpos, ypos, isWall, hasPill, hasWeapon);
    return vertex;
}

std::shared_ptr<Vertex> Graph::addVertex(int xpos, int ypos, bool isWall)
{
    std::shared_ptr<Vertex> vertex = std::make_shared<Vertex>(xpos, ypos, isWall);
    return vertex;
}

void Graph::addEdge(std::shared_ptr<Vertex> from, std::shared_ptr<Vertex> to)
{
    int weight = 5;
    from->addEdge(to, weight);
}

void Graph::addEdges(std::shared_ptr<Vertex> from, std::shared_ptr<Vertex> to)
{
    int weight = 5;
    from->addEdges(to, weight);
}

void Graph::addEdges(std::shared_ptr<Vertex> from, std::shared_ptr<Vertex> to, int weight)
{
    from->addEdges(to, weight);
}

void Graph::setVertices(std::shared_ptr<std::vector<std::vector<std::shared_ptr<Vertex>>>> p_vertices)
{
    vertices = p_vertices;
}

std::vector<std::vector<std::shared_ptr<Vertex>>> Graph::getVertices()
{
    return *vertices;
}

int Graph::getWidth()
{
    return vertices->at(0).size();
}

int Graph::getHeight()
{
    return vertices->size();
}

void Graph::setUnits(std::shared_ptr<Chicken> p_chicken)
{
    chicken = p_chicken;
}

std::vector<std::shared_ptr<Vertex>> Graph::getRouteChicken(std::shared_ptr<Vertex> start)
{
    return getRoute(start, chicken->getPosition());
}

std::shared_ptr<Vertex> Graph::getRandomVertex()
{
    std::shared_ptr<Vertex> end;
    do{
        int x = Utils::randomNumber(getWidth() - 1);
        int y = Utils::randomNumber(getHeight() - 1);

        end = std::shared_ptr<Vertex>(vertices->at(y).at(x));
    }
    while (end->isWall());
    return end;
}

std::vector<std::shared_ptr<Vertex>> Graph::getRouteRandom(std::shared_ptr<Vertex> start)
{
    std::shared_ptr<Vertex> end = getRandomVertex();
    return getRoute(start, end);
}

std::vector<std::shared_ptr<Vertex>> Graph::getRoute(std::shared_ptr<Vertex> start, std::shared_ptr<Vertex> end)
{
    cameFrom = new std::map<std::shared_ptr<Vertex>, std::shared_ptr<Vertex>>();
    std::map<std::shared_ptr<Vertex>, int> costSoFar;

    PriorityQueue queue;
    queue.put(start, 0);

    cameFrom->insert(std::pair<std::shared_ptr<Vertex>, std::shared_ptr<Vertex>>(start, start));
    costSoFar[start] = 0;

    while (!queue.empty())
    {
        std::shared_ptr<Vertex> currentNode = queue.get();

        if (currentNode == end)
        {
            break;
        }

        for (std::shared_ptr<Edge> edge : currentNode->getEdges())
        {
            int cost = costSoFar[currentNode] + edge->getWeight();
            // If it doesn't contain this neighbour or the cost for this step is less than the existing step
            if (!costSoFar.count(edge->getDestination()) || cost < costSoFar[edge->getDestination()])
            {
                costSoFar[edge->getDestination()] = cost;

                // calculate priority for in the queue
                // add the total cost till this step with the heuristic
                int priority = cost + calculateHeuristic(edge->getDestination(), end);
                queue.put(edge->getDestination(), priority);
                // Add to the path map
                cameFrom->insert(std::pair<std::shared_ptr<Vertex>, std::shared_ptr<Vertex>>(edge->getDestination(), currentNode));
            }
        }

        if (DEBUG_PATH)
        {
            main->setPaths(*cameFrom);
            main->repaint();
            qApp->processEvents();
        }
    }
    return createPath(start, end);
}

int Graph::calculateHeuristic(std::shared_ptr<Vertex> start, std::shared_ptr<Vertex> end)
{
    // euclidean heuristic
    int dx = start->getXpos() - end->getXpos();
    int dy = start->getYpos() - end->getYpos();
    //return static_cast<int>(sqrt(dx*dx+dy*dy));

    // Manhattan
    return abs(dx) + abs(dy);

    // Chebyshev
    //return Utils::max(abs(dx), abs(dy));
}

std::vector<std::shared_ptr<Vertex>> Graph::createPath(std::shared_ptr<Vertex> start, std::shared_ptr<Vertex> end)
{
    std::vector<std::shared_ptr<Vertex>> reconstruction;

    std::shared_ptr<Vertex> current = end;
    reconstruction.push_back(end);
    while (current != start)
    {
        current = (*cameFrom)[current];

        // don't push the start, not needed
        if (current != start)
            reconstruction.push_back(current);
    }
    delete cameFrom;

    // reverse vector because we pushed from end to start
    std::reverse(reconstruction.begin(),reconstruction.end());

    return reconstruction;
}


text:
package org.apache.camel.component.flatpack;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import net.sf.flatpack.DataSet;
import net.sf.flatpack.DefaultParserFactory;
import net.sf.flatpack.Parser;
import net.sf.flatpack.ParserFactory;
import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.Exchange;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.processor.loadbalancer.LoadBalancer;
import org.apache.camel.processor.loadbalancer.RoundRobinLoadBalancer;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.support.DefaultPollingEndpoint;
import org.apache.camel.support.ExchangeHelper;
import org.apache.camel.support.ResourceHelper;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;

/**
 * The flatpack component supports fixed width and delimited file parsing via the FlatPack library.
 */
@UriEndpoint(firstVersion = "1.4.0", scheme = "flatpack", title = "Flatpack", syntax = "flatpack:type:resourceUri", label = "transformation")
public class FlatpackEndpoint extends DefaultPollingEndpoint {

    private LoadBalancer loadBalancer = new RoundRobinLoadBalancer();
    private ParserFactory parserFactory = DefaultParserFactory.getInstance();

    @UriPath @Metadata(required = false, defaultValue = "delim")
    private FlatpackType type;
    @UriPath @Metadata(required = true)
    private String resourceUri;

    @UriParam(defaultValue = "true")
    private boolean splitRows = true;
    @UriParam
    private boolean allowShortLines;
    @UriParam
    private boolean ignoreExtraColumns;

    // delimited
    @UriParam(defaultValue = ",")
    private char delimiter = ',';
    @UriParam
    private char textQualifier = '"';
    @UriParam(defaultValue = "true")
    private boolean ignoreFirstRecord = true;

    public FlatpackEndpoint() {
    }

    public FlatpackEndpoint(String endpointUri, Component component, String resourceUri) {
        super(endpointUri, component);
        this.resourceUri = resourceUri;
    }

    public boolean isSingleton() {
        return true;
    }

    public Producer createProducer() throws Exception {
        return new FlatpackProducer(this);
    }

    public Consumer createConsumer(Processor processor) throws Exception {
        return new FlatpackConsumer(this, processor, loadBalancer);
    }

    public void processDataSet(Exchange originalExchange, DataSet dataSet, int counter) throws Exception {
        Exchange exchange = ExchangeHelper.createCorrelatedCopy(originalExchange, false);
        Message in = exchange.getIn();
        in.setBody(dataSet);
        in.setHeader("CamelFlatpackCounter", counter);
        loadBalancer.process(exchange);
    }

    public Parser createParser(Exchange exchange) throws Exception {
        Reader bodyReader = exchange.getIn().getMandatoryBody(Reader.class);
        try {
            if (FlatpackType.fixed == type) {
                return createFixedParser(resourceUri, bodyReader);
            } else {
                return createDelimitedParser(exchange);
            }
        } catch (Exception e) {
            // must close reader in case of some exception
            IOHelper.close(bodyReader);
            throw e;
        }
    }

    protected Parser createFixedParser(String resourceUri, Reader bodyReader) throws IOException {
        InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), resourceUri);
        InputStreamReader reader = new InputStreamReader(is);
        Parser parser = getParserFactory().newFixedLengthParser(reader, bodyReader);
        if (isAllowShortLines()) {
            parser.setHandlingShortLines(true);
            parser.setIgnoreParseWarnings(true);
        }
        if (isIgnoreExtraColumns()) {
            parser.setIgnoreExtraColumns(true);
            parser.setIgnoreParseWarnings(true);
        }
        return parser;
    }

    public Parser createDelimitedParser(Exchange exchange) throws InvalidPayloadException, IOException {
        Reader bodyReader = exchange.getIn().getMandatoryBody(Reader.class);

        Parser parser;
        if (ObjectHelper.isEmpty(getResourceUri())) {
            parser = getParserFactory().newDelimitedParser(bodyReader, delimiter, textQualifier);
        } else {
            InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), resourceUri);
            InputStreamReader reader = new InputStreamReader(is, ExchangeHelper.getCharsetName(exchange));
            parser = getParserFactory().newDelimitedParser(reader, bodyReader, delimiter, textQualifier, ignoreFirstRecord);
        }

        if (isAllowShortLines()) {
            parser.setHandlingShortLines(true);
            parser.setIgnoreParseWarnings(true);
        }
        if (isIgnoreExtraColumns()) {
            parser.setIgnoreExtraColumns(true);
            parser.setIgnoreParseWarnings(true);
        }

        return parser;
    }

    // Properties
    //-------------------------------------------------------------------------

    public String getResourceUri() {
        return resourceUri;
    }

    public ParserFactory getParserFactory() {
        return parserFactory;
    }

    public void setParserFactory(ParserFactory parserFactory) {
        this.parserFactory = parserFactory;
    }

    public LoadBalancer getLoadBalancer() {
        return loadBalancer;
    }

    public void setLoadBalancer(LoadBalancer loadBalancer) {
        this.loadBalancer = loadBalancer;
    }

    public boolean isSplitRows() {
        return splitRows;
    }

    /**
     * Sets the Component to send each row as a separate exchange once parsed
     */
    public void setSplitRows(boolean splitRows) {
        this.splitRows = splitRows;
    }

    public boolean isAllowShortLines() {
        return this.allowShortLines;
    }

    /**
     * Allows for lines to be shorter than expected and ignores the extra characters
     */
    public void setAllowShortLines(boolean allowShortLines) {
        this.allowShortLines = allowShortLines;
    }

    /**
     * Allows for lines to be longer than expected and ignores the extra characters
     */
    public void setIgnoreExtraColumns(boolean ignoreExtraColumns) {
        this.ignoreExtraColumns = ignoreExtraColumns;
    }

    public boolean isIgnoreExtraColumns() {
        return ignoreExtraColumns;
    }

    public FlatpackType getType() {
        return type;
    }

    /**
     * Whether to use fixed or delimiter
     */
    public void setType(FlatpackType type) {
        this.type = type;
    }

    /**
     * URL for loading the flatpack mapping file from classpath or file system
     */
    public void setResourceUri(String resourceUri) {
        this.resourceUri = resourceUri;
    }

    public char getDelimiter() {
        return delimiter;
    }

    /**
     * The default character delimiter for delimited files.
     */
    public void setDelimiter(char delimiter) {
        this.delimiter = delimiter;
    }

    public char getTextQualifier() {
        return textQualifier;
    }

    /**
     * The text qualifier for delimited files.
     */
    public void setTextQualifier(char textQualifier) {
        this.textQualifier = textQualifier;
    }

    public boolean isIgnoreFirstRecord() {
        return ignoreFirstRecord;
    }

    /**
     * Whether the first line is ignored for delimited files (for the column headers).
     */
    public void setIgnoreFirstRecord(boolean ignoreFirstRecord) {
        this.ignoreFirstRecord = ignoreFirstRecord;
    }
}


text:
package org.apache.kafka.clients.consumer;

import org.apache.kafka.clients.consumer.internals.AbstractPartitionAssignor;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.utils.CircularIterator;
import org.apache.kafka.common.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 *
The round robin assignor lays out all the available partitions and all the available consumers. It
 * then proceeds to do a round robin assignment from partition to consumer. If the subscriptions of all consumer
 * instances are identical, then the partitions will be uniformly distributed. (i.e., the partition ownership counts
 * will be within a delta of exactly one across all consumers.)
 *
 *
For example, suppose there are two consumers C0 and C1, two topics t0 and t1,
 * and each topic has 3 partitions, resulting in partitions t0p0, t0p1, t0p2,
 * t1p0, t1p1, and t1p2.
 *
 *
The assignment will be:
 *

 *
C0: [t0p0, t0p2, t1p1]
 *
C1: [t0p1, t1p0, t1p2]
 *

 *
 *
When subscriptions differ across consumer instances, the assignment process still considers each
 * consumer instance in round robin fashion but skips over an instance if it is not subscribed to
 * the topic. Unlike the case when subscriptions are identical, this can result in imbalanced
 * assignments. For example, we have three consumers C0, C1, C2,
 * and three topics t0, t1, t2, with 1, 2, and 3 partitions, respectively.
 * Therefore, the partitions are t0p0, t1p0, t1p1, t2p0, t2p1, t2p2.
 * C0 is subscribed to t0;
 * C1 is subscribed to t0, t1;
 * and C2 is subscribed to t0, t1, t2.
 *
 *
That assignment will be:
 *

 *
C0: [t0p0]
 *
C1: [t1p0]
 *
C2: [t1p1, t2p0, t2p1, t2p2]
 *

 *
 * Since the introduction of static membership, we could leverage group.instance.id to make the assignment behavior more sticky.
 * For example, we have three consumers with assigned member.id C0, C1, C2,
 * two topics t0 and t1, and each topic has 3 partitions, resulting in partitions t0p0,
 * t0p1, t0p2, t1p0, t1p1, and t1p2. We choose to honor
 * the sorted order based on ephemeral member.id.
 *
 *
The assignment will be:
 *

 *
C0: [t0p0, t1p0]
 *
C1: [t0p1, t1p1]
 *
C2: [t0p2, t1p2]
 *

 *
 * After one rolling bounce, group coordinator will attempt to assign new member.id towards consumers,
 * for example C0 -> C5 C1 -> C3, C2 -> C4.
 *
 *
The assignment could be completely shuffled to:
 *

 *
C3 (was C1): [t0p0, t1p0] (before was [t0p1, t1p1])
 *
C4 (was C2): [t0p1, t1p1] (before was [t0p2, t1p2])
 *
C5 (was C0): [t0p2, t1p2] (before was [t0p0, t1p0])
 *

 *
 * This issue could be mitigated by the introduction of static membership. Consumers will have individual instance ids
 * I1, I2, I3. As long as
 * 1. Number of members remain the same across generation
 * 2. Static members' identities persist across generation
 * 3. Subscription pattern doesn't change for any member
 *
 *
The assignment will always be:
 *

 *
I0: [t0p0, t1p0]
 *
I1: [t0p1, t1p1]
 *
I2: [t0p2, t1p2]
 *

 */
public class RoundRobinAssignor extends AbstractPartitionAssignor {
    public static final String ROUNDROBIN_ASSIGNOR_NAME = "roundrobin";

    @Override
    public Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic,
                                                    Map<String, Subscription> subscriptions) {
        Map<String, List<TopicPartition>> assignment = new HashMap<>();
        List<MemberInfo> memberInfoList = new ArrayList<>();
        for (Map.Entry<String, Subscription> memberSubscription : subscriptions.entrySet()) {
            assignment.put(memberSubscription.getKey(), new ArrayList<>());
            memberInfoList.add(new MemberInfo(memberSubscription.getKey(),
                                              memberSubscription.getValue().groupInstanceId()));
        }

        CircularIterator<MemberInfo> assigner = new CircularIterator<>(Utils.sorted(memberInfoList));

        for (TopicPartition partition : allPartitionsSorted(partitionsPerTopic, subscriptions)) {
            final String topic = partition.topic();
            while (!subscriptions.get(assigner.peek().memberId).topics().contains(topic))
                assigner.next();
            assignment.get(assigner.next().memberId).add(partition);
        }
        return assignment;
    }

    private List<TopicPartition> allPartitionsSorted(Map<String, Integer> partitionsPerTopic,
                                                     Map<String, Subscription> subscriptions) {
        SortedSet<String> topics = new TreeSet<>();
        for (Subscription subscription : subscriptions.values())
            topics.addAll(subscription.topics());

        List<TopicPartition> allPartitions = new ArrayList<>();
        for (String topic : topics) {
            Integer numPartitionsForTopic = partitionsPerTopic.get(topic);
            if (numPartitionsForTopic != null)
                allPartitions.addAll(AbstractPartitionAssignor.partitions(topic, numPartitionsForTopic));
        }
        return allPartitions;
    }

    @Override
    public String name() {
        return ROUNDROBIN_ASSIGNOR_NAME;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2010 Research Studios Austria Forschungsgesellschaft mBH
  ~
  ~ This file is part of easyrec.
  ~
  ~ easyrec is free software: you can redistribute it and/or modify
  ~ it under the terms of the GNU General Public License as published by
  ~ the Free Software Foundation, either version 3 of the License, or
  ~ (at your option) any later version.
  ~
  ~ easyrec is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
  ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  ~ GNU General Public License for more details.
  ~
  ~ You should have received a copy of the GNU General Public License
  ~ along with easyrec.  If not, see <http://www.gnu.org/licenses/>.
  -->

<!-- $Author$ -->
<!-- $Revision$ -->
<!-- $Date$ -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-2.5.6.xsd">

    <!-- The spring config named "easyrec-plugin.xml" placed in the root package will be automatically loaded when
         the plugin is installed in easyrec. -->
    <!-- You can include all spring dependencies you have at this place -->

    <!-- create our generator bean so it can be detected by easyrec's plugin loader
         (only loaded spring beans extending the class GeneratorPluginSupport) -->
    <bean id="randomGenerator" class="org.easyrec.plugin.sample.SampleGenerator"/>

</beans>


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=struct.S3ClientError.html">

Redirecting to struct.S3ClientError.html...


text:
var request = require('request');

module.exports = function (RED) {
    var cfenv = require('cfenv');

    var services = cfenv.getAppEnv().services,
        service = null;

    if (services['user-provided']) { service = services['user-provided'][0]; }

    RED.httpAdmin.get('/watson-alchemy-face-detection/vcap', function (req, res) {
        res.json(service);
    });

    function FaceDetectNode (config) {
        RED.nodes.createNode(this, config);
        var node = this;

        if (!service) {
            node.error('No question and answer service bound');
        } else {

            this.on('input', function (msg) {
                if (!msg.payload) {
                    node.error('Missing property: msg.payload');
                    return;
                }

                var image = msg.payload.image || undefined,
                    params = {},
                    urlKVPairs = [];

                if (!image) {
                    node.error('Invalid request format! No property "image" found.');
                    return;
                }

                params['apikey'] = service.credentials.apikey;
                params['outputMode'] = 'json';
                params['imagePostMode'] = 'raw';
                Object.keys(params).forEach(function(key) {
                    urlKVPairs.push(key+'='+encodeURIComponent(params[key]));
                });

                image = new Buffer(image, 'base64');
                var options = {
                    uri: service.credentials.url+'/calls/image/ImageGetRankedImageFaceTags?'+urlKVPairs.join('&'),
                    headers: { 'Content-Length': image.length },
                    body: image
                };

                request.post(options, function (err, res, body) {
                    if (err) { node.error('API responses with error: ' + err.msg); }
                    else {
                        try {
                            msg.payload = JSON.parse(body);
                            node.send(msg);
                        } catch (e) {
                            node.error('API responses with error: ' + e);
                        }
                    }
                });
            });
        }
    }
    RED.nodes.registerType('watson-alchemy-face-detection', FaceDetectNode);
};


text:
package com.intellij.openapi.vcs.ex;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.impl.Interval;
import com.intellij.openapi.util.Pair;
import com.intellij.util.containers.ContainerUtil;
import kotlin.Unit;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class VisibleRangeMerger<T> {
  @NotNull private final Editor myEditor;
  @NotNull private final FlagsProvider<T> myFlagsProvider;

  @NotNull private ChangesBlock<T> myBlock = new ChangesBlock<>();

  @NotNull private final List<ChangesBlock<T>> myResult = new ArrayList<>();

  private VisibleRangeMerger(@NotNull Editor editor, @NotNull FlagsProvider<T> flagsProvider) {
    myEditor = editor;
    myFlagsProvider = flagsProvider;
  }

  public static List<ChangesBlock<Unit>> merge(@NotNull Editor editor,
                                               @NotNull List<? extends Range> ranges,
                                               @NotNull Rectangle clip) {
    return new VisibleRangeMerger<>(editor, FlagsProvider.EMPTY).run(ranges, clip);
  }

  public static <T> List<ChangesBlock<T>> merge(@NotNull Editor editor,
                                                @NotNull List<? extends Range> ranges,
                                                @NotNull FlagsProvider<T> flagsProvider,
                                                @NotNull Rectangle clip) {
    return new VisibleRangeMerger<>(editor, flagsProvider).run(ranges, clip);
  }

  @NotNull
  private List<ChangesBlock<T>> run(@NotNull List<? extends Range> ranges, @NotNull Rectangle clip) {
    int visibleLinesStart = EditorUtil.yToLogicalLineRange(myEditor, clip.y).intervalStart();
    int visibleLinesEnd = EditorUtil.yToLogicalLineRange(myEditor, clip.y + Math.max(clip.height - 1, 0)).intervalEnd() + 1;

    for (Range range : ranges) {
      int line1 = range.getLine1();
      int line2 = range.getLine2();

      if (line2 < visibleLinesStart) continue;
      if (line1 > visibleLinesEnd) break;

      T flags = myFlagsProvider.getFlags(range);
      List<Range.InnerRange> innerRanges = range.getInnerRanges();

      if (innerRanges == null || myFlagsProvider.shouldIgnoreInnerRanges(flags)) {
        processLine(range, line1, line2, range.getType(), flags);
      }
      else {
        for (Range.InnerRange innerRange : innerRanges) {
          int innerLine1 = line1 + innerRange.getLine1();
          int innerLine2 = line1 + innerRange.getLine2();
          byte innerType = innerRange.getType();

          processLine(range, innerLine1, innerLine2, innerType, flags);
        }
      }
    }

    finishBlock();
    return myResult;
  }

  private void processLine(@NotNull Range range, int start, int end, byte type, @NotNull T flags) {
    Pair<@NotNull Interval, @Nullable Interval> pair1 = EditorUtil.logicalLineToYRange(myEditor, start);
    int visualStart = pair1.first.intervalStart();

    int sharedPrefixHeight;
    if (pair1.second == null) {
      sharedPrefixHeight = pair1.first.intervalEnd() - pair1.first.intervalStart();
    }
    else {
      sharedPrefixHeight = pair1.second.intervalStart() - pair1.first.intervalStart();
    }

    if (start == end) {
      if (sharedPrefixHeight != 0) {
        appendChange(range, new ChangedLines<>(visualStart, visualStart + sharedPrefixHeight, Range.MODIFIED, flags));
      }
      else {
        appendChange(range, new ChangedLines<>(visualStart, visualStart, type, flags));
      }
    }
    else {
      Pair<@NotNull Interval, @Nullable Interval> pair2 = EditorUtil.logicalLineToYRange(myEditor, end - 1);
      int visualEnd = pair2.first.intervalEnd();

      int sharedSuffixHeight;
      if (pair2.second == null) {
        sharedSuffixHeight = pair2.first.intervalEnd() - pair2.first.intervalStart();
      }
      else {
        sharedSuffixHeight = pair2.first.intervalEnd() - pair2.second.intervalEnd();
      }

      if (type == Range.EQUAL || type == Range.MODIFIED) {
        appendChange(range, new ChangedLines<>(visualStart, visualEnd, type, flags));
      }
      else {
        if (sharedPrefixHeight != 0 && visualEnd - visualStart > sharedPrefixHeight) {
          appendChange(range, new ChangedLines<>(visualStart, visualStart + sharedPrefixHeight, Range.MODIFIED, flags));
          visualStart += sharedPrefixHeight;
          sharedPrefixHeight = 0;
        }
        if (sharedSuffixHeight != 0 && visualEnd - visualStart > sharedSuffixHeight) {
          appendChange(range, new ChangedLines<>(visualStart, visualEnd - sharedSuffixHeight, type, flags));
          appendChange(range, new ChangedLines<>(visualEnd - sharedSuffixHeight, visualEnd, Range.MODIFIED, flags));
        }
        else {
          byte bodyType = sharedPrefixHeight != 0 || sharedSuffixHeight != 0 ? Range.MODIFIED : type;
          appendChange(range, new ChangedLines<>(visualStart, visualEnd, bodyType, flags));
        }
      }
    }
  }

  private void appendChange(@NotNull Range range, @NotNull ChangedLines<T> newChange) {
    ChangedLines<T> lastItem = ContainerUtil.getLastItem(myBlock.changes);
    if (lastItem != null && lastItem.y2 < newChange.y1) {
      finishBlock();
    }

    List<ChangedLines<T>> changes = myBlock.changes;
    List<Range> ranges = myBlock.ranges;

    if (ContainerUtil.getLastItem(ranges) != range) {
      ranges.add(range);
    }

    if (changes.isEmpty()) {
      changes.add(newChange);
      return;
    }

    ChangedLines<T> lastChange = changes.remove(changes.size() - 1);

    if (lastChange.y1 == lastChange.y2 &&
        newChange.y1 == newChange.y2) {
      assert lastChange.y1 == newChange.y1;
      byte type = mergeTypes(lastChange, newChange);
      T flags = myFlagsProvider.mergeFlags(lastChange.flags, newChange.flags);
      changes.add(new ChangedLines<>(lastChange.y1, lastChange.y2, type, flags));
    }
    else if (lastChange.y1 == lastChange.y2 && newChange.type == Range.EQUAL ||
             newChange.y1 == newChange.y2 && lastChange.type == Range.EQUAL) {
      changes.add(lastChange);
      changes.add(newChange);
    }
    else if (lastChange.type == newChange.type &&
             Objects.equals(lastChange.flags, newChange.flags)) {
      int union1 = Math.min(lastChange.y1, newChange.y1);
      int union2 = Math.max(lastChange.y2, newChange.y2);
      changes.add(new ChangedLines<>(union1, union2, lastChange.type, lastChange.flags));
    }
    else {
      int intersection1 = Math.max(lastChange.y1, newChange.y1);
      int intersection2 = Math.min(lastChange.y2, newChange.y2);

      if (lastChange.y1 != intersection1) {
        changes.add(new ChangedLines<>(lastChange.y1, intersection1, lastChange.type, lastChange.flags));
      }

      if (intersection1 != intersection2) {
        byte type = mergeTypes(lastChange, newChange);
        T flags = myFlagsProvider.mergeFlags(lastChange.flags, newChange.flags);
        changes.add(new ChangedLines<>(intersection1, intersection2, type, flags));
      }

      if (newChange.y2 != intersection2) {
        changes.add(new ChangedLines<>(intersection2, newChange.y2, newChange.type, newChange.flags));
      }
    }
  }

  private void finishBlock() {
    if (myBlock.changes.isEmpty()) return;
    myResult.add(myBlock);
    myBlock = new ChangesBlock<>();
  }

  private byte mergeTypes(@NotNull ChangedLines<T> change1, @NotNull ChangedLines<T> change2) {
    return change1.type == change2.type ? change1.type : Range.MODIFIED;
  }

  public interface FlagsProvider<T> {
    @NotNull
    T getFlags(@NotNull Range range);

    @NotNull
    T mergeFlags(@NotNull T flags1, @NotNull T flags2);

    default boolean shouldIgnoreInnerRanges(@NotNull T flag) {
      return false;
    }

    FlagsProvider<Unit> EMPTY = new FlagsProvider<>() {
      @Override
      public @NotNull Unit getFlags(@NotNull Range range) {
        return Unit.INSTANCE;
      }

      @Override
      public @NotNull Unit mergeFlags(@NotNull Unit flags1, @NotNull Unit flags2) {
        return Unit.INSTANCE;
      }

      @Override
      public boolean shouldIgnoreInnerRanges(@NotNull Unit flag) {
        return true;
      }
    };
  }
}


text:
use crate::{
    models::{Layout, Project},
    ProjectBundle, Targets,
};
use language_tags::LanguageTag;
use log::trace;
use serde::de::DeserializeOwned;
use std::{
    collections::HashMap,
    default::Default,
    ffi::OsStr,
    fs::{canonicalize, read_dir},
    hash::BuildHasher,
    path::{Path, PathBuf},
};
use thiserror::Error;

pub trait Load: Sized {
    /// Read data from given path into a structure of this type
    fn load(path: impl AsRef<Path>) -> Result<Self, Error>;
}

impl Load for ProjectBundle {
    fn load(bundle_path: impl AsRef<Path>) -> Result<Self, Error> {
        let bundle_path: &Path = bundle_path.as_ref();
        trace!("Loading {:?}", bundle_path);

        Ok(ProjectBundle {
            path: Some(
                canonicalize(&bundle_path).map_err(|source| Error::ReadFile {
                    path: bundle_path.into(),
                    source,
                })?,
            ),
            project: Load::load(&bundle_path.join("project.yaml"))?,
            layouts: Load::load(&bundle_path.join("layouts"))?,
            targets: Load::load(&bundle_path.join("targets"))?,
        })
    }
}

impl Load for Project {
    fn load(path: impl AsRef<Path>) -> Result<Self, Error> {
        let path: &Path = path.as_ref();
        Ok(read_yml(path)?)
    }
}

impl<S: BuildHasher + Default> Load for HashMap<LanguageTag, Layout, S> {
    fn load(path: impl AsRef<Path>) -> Result<Self, Error> {
        let path: &Path = path.as_ref();
        let yml_files = read_dir(path)
            .map_err(|source| Error::ReadFile {
                path: path.into(),
                source,
            })?
            .filter_map(Result::ok)
            .map(|f| f.path())
            .filter(|p| p.is_file())
            .filter(|p| p.extension() == Some(OsStr::new("yaml")));

        yml_files
            .map(|path| {
                let tag = path
                    .file_stem()
                    .ok_or_else(|| Error::MalformedFilename { path: path.clone() })?
                    .to_string_lossy();

                let tag: LanguageTag = tag.parse().map_err(|_| Error::InvalidLanguageTag {
                    tag: tag.to_string(),
                })?;
                let data = read_yml(&path)?;
                Ok((tag, data))
            })
            .collect()
    }
}

impl Load for Targets {
    fn load(path: impl AsRef<Path>) -> Result<Self, Error> {
        let path: &Path = path.as_ref();
        Ok(Targets {
            android: read_yml_if_exists(&path.join("android.yaml"))?,
            ios: read_yml_if_exists(&path.join("ios.yaml"))?,
            macos: read_yml_if_exists(&path.join("mac.yaml"))?,
            windows: read_yml_if_exists(&path.join("win.yaml"))?,
            chrome: read_yml_if_exists(&path.join("chrome.yaml"))?,
            x11: read_yml_if_exists(&path.join("x11.yaml"))?,
            mim: read_yml_if_exists(&path.join("mim.yaml"))?,
        })
    }
}

fn read_yml<T: DeserializeOwned>(path: &Path) -> Result<T, Error> {
    use std::{fs::File, io::BufReader};

    let file = File::open(path).map_err(|source| Error::ReadFile {
        path: path.into(),
        source,
    })?;
    let reader = BufReader::new(file);
    let parsed = serde_yaml::from_reader(reader).map_err(|source| Error::ParseFile {
        path: path.into(),
        source,
    })?;
    Ok(parsed)
}

fn read_yml_if_exists<T: DeserializeOwned>(path: impl AsRef<Path>) -> Result<Option<T>, Error> {
    let path: &Path = path.as_ref();
    if !path.is_file() {
        return Ok(None);
    }
    read_yml(path)
}

#[derive(Debug, Error)]
pub enum Error {
    #[error("Could not read `{}`: {}", path.display(), source)]
    ReadFile {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("Could not parse file with malfolmed name:: `{}`", path.display())]
    MalformedFilename { path: PathBuf },
    #[error("Could not parse language tag: `{}`", tag)]
    InvalidLanguageTag { tag: String },
    #[error("Could not parse `{}`: {}", path.display(), source)]
    ParseFile {
        path: PathBuf,
        source: serde_yaml::Error,
    },
}


text:
package com.amazonaws.services.lambda.runtime.events.transformers.v2;

import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.dynamodb.model.Record;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static com.amazonaws.services.lambda.runtime.events.transformers.v2.dynamodb.DynamodbRecordTransformerTest.record_event;
import static com.amazonaws.services.lambda.runtime.events.transformers.v2.dynamodb.DynamodbRecordTransformerTest.record_v2;

public class DynamodbEventTransformerTest {

    private final DynamodbEvent dynamodbEvent;

    {
        record_event.setEventSourceARN("arn:aws:dynamodb:us-west-2:account-id:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899");
        dynamodbEvent = new DynamodbEvent();
        dynamodbEvent.setRecords(Collections.singletonList(record_event));
    }

    private final List<Record> expectedRecordsV2 = Collections.singletonList(record_v2);

    @Test
    public void testDynamodbEventToRecordsV2() {
        List<Record> convertedRecords = DynamodbEventTransformer.toRecordsV2(dynamodbEvent);
        Assertions.assertEquals(expectedRecordsV2, convertedRecords);
    }

    @Test
    public void testDynamodbEventToRecordsV2_FiltersNullRecords() {
        DynamodbEvent event = dynamodbEvent.clone();
        event.setRecords(Arrays.asList(record_event, null));
        Assertions.assertEquals(2, event.getRecords().size());

        List<Record> convertedRecords = DynamodbEventTransformer.toRecordsV2(event);
        Assertions.assertEquals(expectedRecordsV2, convertedRecords);
        Assertions.assertEquals(1, convertedRecords.size());
    }
}


text:
import sys
import paramiko
import time
import socket
from getpass import getpass

__author__ = 'aismagilov'
__docformat__ = 'reStructuredText'
__license__ = "MIT"

if __name__ == '__main__':
    pass
else:
    sys.exit("It cannot be imported...yet.")

IP_ADDR = '50.76.53.27'
SSH_PORT = 22
MAX_BUFFER = 65535

# username = raw_input('Username: ')
# password = getpass()

# here I'll hardcode the credentials for testing purposes:
username = 'pyclass'
password = '88newclass'

def disable_terminal_paging(command='terminal length 0\n', delay=1):
    """This function disables paging for the SSHClient VTY session
    :param command: command to send
    :type command: str
    :param delay: how long to wait for command to complete
    :type delay: int
    :returns: doesn't returns anything
    :rtype: NoneType
    """

    remote_connect.send('\n')
    remote_connect.send(command)
    time.sleep(delay)

# instantiate a paramiko SSHClient object
ssh_client = paramiko.SSHClient()

# load the ~/.ssh/known_hosts
ssh_client.load_system_host_keys()

# alternatively (or in addition to the system's ones), we can load the known_hosts from the specific file
ssh_client.load_host_keys(r'~/.ssh/known_hosts')

# set paramiko to automatically accept missing public keys (i.e. not in the known_hosts) of a remote host we connect to
# otherwise if the host is unknown, it will throw an exception
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:
    # Create a paramiko SSH-channel
    ssh_client.connect(IP_ADDR, username=username, password=password, timeout=10)
except paramiko.SSHException as e:
    ssh_client.close()
    sys.exit("Something is wrong with paramiko SSH-channel creation: " + str(e))
except socket.error as e:
    ssh_client.close()
    sys.exit("Something is wrong with paramiko SSH-channel creation. Socket error: " + str(e))
except Exception as e:
    ssh_client.close()
    sys.exit("Something is completely wrong with paramiko: " + str(e))

# Configure the channel to run interactive mode
remote_connect = ssh_client.invoke_shell()

# instead of the invoke_shell() method we might use the exec_command('sh ip int br'), but since the Cisco devices
# implement SSH only partially (unlike Linux boxed, for example), the close the TCP-session as soon as the channel
# is closed. And the exec_command() method works in a way that it closes the channel after its job is completed.
# All this means that when we're talking to the Cisco devices, we only able to execute one command at a time.
# To execute multiple commands on Cisco using exec_command() method, we would need to re-create the SSH-session every
# time.
# ssh_client.exec_command('sh ip int br')

# set timeout in seconds for SSH-session to wait for requested data (i.e. through the recv() method).
# Otherwise it may wait for it almost indefinitely
remote_connect.settimeout(6.0)

# send something into a channel. This method returns the amount of bytes we've sent
remote_connect.send('\n')

time.sleep(1)

disable_terminal_paging()

remote_connect.send('show version\n')

# wait for the command to complete (in seconds)
# For 'big' commands like 'show running-config' it might take the long time
time.sleep(2)

device_output = ""
while remote_connect.recv_ready():
    # The recv_ready() method returns True if the channel buffer has something for us to read.
    # Otherwise it returns False.

    # read up to this amount of bytes from the SSH-channel buffer (max size is 65535 bytes, i.e. 64KB)
    # If we have more than 64KB, we need to iterate over it
    device_output += remote_connect.recv(MAX_BUFFER)

print device_output

ssh_client.close()


text:
// =====================================================================
//
//  This file is part of the Microsoft Dynamics CRM SDK Code Samples.
//
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or online documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
//
//  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//
// =====================================================================
//<snippetCodeCustomizationService>

// Define REMOVE_PROXY_TYPE_ASSEMBLY_ATTRIBUTE if you plan on compiling the output from
// this CrmSvcUtil extension with the output from the unextended CrmSvcUtil in the same
// assembly (this assembly attribute can only be defined once in the assembly).
#define REMOVE_PROXY_TYPE_ASSEMBLY_ATTRIBUTE

using System;
using System.CodeDom;
using System.Diagnostics;
using Microsoft.Crm.Services.Utility;

namespace CrmSvcUtilExtensions
{
    /// <summary>
    /// Create an implementation of ICustomizeCodeDomService if you want to manipulate the
    /// code dom after ICodeGenerationService has run.
    /// </summary>
    public sealed class OptionSetsCodeCustomizationService : ICustomizeCodeDomService
    {
        /// <summary>
        /// Remove the unnecessary classes that we generated for entities.
        /// </summary>
        public void CustomizeCodeDom(CodeCompileUnit codeUnit, IServiceProvider services)
        {
            Trace.TraceInformation("Entering ICustomizeCodeDomService.CustomizeCodeDom");
            Trace.TraceInformation(
                "Number of Namespaces generated: {0}", codeUnit.Namespaces.Count);

#if REMOVE_PROXY_TYPE_ASSEMBLY_ATTRIBUTE

            foreach (CodeAttributeDeclaration attribute in codeUnit.AssemblyCustomAttributes)
            {
                Trace.TraceInformation("Attribute BaseType is {0}",
                    attribute.AttributeType.BaseType);
                if (attribute.AttributeType.BaseType ==
                    "Microsoft.Xrm.Sdk.Client.ProxyTypesAssemblyAttribute")
                {
                    codeUnit.AssemblyCustomAttributes.Remove(attribute);
                    break;
                }
            }

#endif

            // Iterate over all of the namespaces that were generated.
            for (var i = 0; i < codeUnit.Namespaces.Count; ++i)
            {
                var types = codeUnit.Namespaces[i].Types;
                Trace.TraceInformation("Number of types in Namespace {0}: {1}",
                    codeUnit.Namespaces[i].Name, types.Count);
                // Iterate over all of the types that were created in the namespace.
                for (var j = 0; j < types.Count; )
                {
                    // Remove the type if it is not an enum (all OptionSets are enums) or has no members.
                    if (!types[j].IsEnum || types[j].Members.Count == 0)
                    {
                        types.RemoveAt(j);
                    }
                    else
                    {
                        j += 1;
                    }
                }
            }
            Trace.TraceInformation("Exiting ICustomizeCodeDomService.CustomizeCodeDom");
        }
    }
}
//</snippetCodeCustomizationService>


text:
namespace EffekseerMaterial
{

Library::Library()
{

	Contents.push_back(std::make_shared<LibraryContent<NodeOutput>>());

	// Math
	Contents.push_back(std::make_shared<LibraryContent<NodeAdd>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeSubtract>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeMultiply>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeDivide>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeFmod>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeCeil>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeFloor>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeFrac>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeStep>>());

	Contents.push_back(std::make_shared<LibraryContent<NodeMin>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeMax>>());
	Contents.push_back(std::make_shared<LibraryContent<NodePower>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeSquareRoot>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeClamp>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeDotProduct>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeCrossProduct>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeNormalize>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeLinearInterpolate>>());

	Contents.push_back(std::make_shared<LibraryContent<NodeAbs>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeComponentMask>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeAppendVector>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeOneMinus>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeSine>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeArctangent2>>());

	Contents.push_back(std::make_shared<LibraryContent<NodeTextureCoordinate>>());
	Contents.push_back(std::make_shared<LibraryContent<NodePanner>>());

	Contents.push_back(std::make_shared<LibraryContent<NodeSampleTexture>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeTextureObjectParameter>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeTextureObject>>());

	Contents.push_back(std::make_shared<LibraryContent<NodeWorldPosition>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeVertexNormalWS>>());
	Contents.push_back(std::make_shared<LibraryContent<NodePixelNormalWS>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeVertexColor>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeObjectScale>>());

#ifdef _DEBUG
	Contents.push_back(std::make_shared<LibraryContent<NodeVertexTangentWS>>());
#endif
	Contents.push_back(std::make_shared<LibraryContent<NodeCustomData1>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeCustomData2>>());

	// Constant
	Contents.push_back(std::make_shared<LibraryContent<NodeTime>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeLocalTime>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeEffectScale>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeCameraPositionWS>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeConstant1>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeConstant2>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeConstant3>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeConstant4>>());

	// Parameter
	Contents.push_back(std::make_shared<LibraryContent<NodeParameter1>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeParameter2>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeParameter3>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeParameter4>>());

	// Gradient
	Contents.push_back(std::make_shared<LibraryContent<NodeSampleGradient>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeGradientParameter>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeGradient>>());

	Contents.push_back(std::make_shared<LibraryContent<NodeSimpleNoise>>());

	Contents.push_back(std::make_shared<LibraryContent<NodeLight>>());

	// Comment
	Contents.push_back(std::make_shared<LibraryContent<NodeComment>>());

	Contents.push_back(std::make_shared<LibraryContent<NodeFresnel>>());
	Contents.push_back(std::make_shared<LibraryContent<NodeRotator>>());
	Contents.push_back(std::make_shared<LibraryContent<NodePolarCoords>>());

	Contents.push_back(std::make_shared<LibraryContent<NodeDepthFade>>());

	MakeGroups();
}

Library::~Library()
{
}

void Library::MakeGroups()
{
	// TODO recurcive
	Root = std::make_shared<LibraryContentGroup>();

	for (auto content : Contents)
	{
		if (content->Group.size() == 0)
		{
			Root->Contents.push_back(content);
			continue;
		}

		bool found = false;

		for (auto& group : Root->Groups)
		{
			if (group->Name == content->Group[0])
			{
				group->Contents.push_back(content);
				found = true;
				break;
			}
		}

		if (!found)
		{
			auto group = std::make_shared<LibraryContentGroup>();
			group->Name = content->Group[0];
			group->Contents.push_back(content);
			Root->Groups.push_back(group);
		}
	}
}

} // namespace EffekseerMaterial


text:
package br.com.wicketlocadora.web.pages.cliente;

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

import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Predicate;

import br.com.wicketlocadora.persistence.domain.Cliente;
import br.com.wicketlocadora.persistence.domain.QCliente;
import br.com.wicketlocadora.service.cliente.ClienteService;
import br.com.wicketlocadora.web.util.LinkPanel;
import br.com.wicketlocadora.web.util.ProviderGenerico;
import br.com.wicketlocadora.web.util.tabela.Coluna;
import br.com.wicketlocadora.web.util.tabela.Tabela;

public class ListaClientesPanel extends Panel {

    private static final long serialVersionUID = -1197209504623272195L;

    private String nomeContem;
    private String email;
    private Tabela<Cliente> tabela;

    @SpringBean
    private ClienteService service;

    public ListaClientesPanel(String id) {
	super(id);
    }

    @Override
    protected void onInitialize() {
	super.onInitialize();
	addFiltros();
	List<Coluna<Cliente>> colunas = new ArrayList<Coluna<Cliente>>();

	colunas.add(new Coluna<Cliente>("Nome", "nome"));
	colunas.add(new Coluna<Cliente>("E-mail", "email"));
	colunas.add(new Coluna<Cliente>("Endereço", "endereco.enderecoFormatado"));

	colunas.add(new Coluna<Cliente>("Ações", "") {

	    @Override
	    public void populateItem(Item<ICellPopulator<Cliente>> cellItem, String componentId,
		    IModel<Cliente> rowModel) {
		PageParameters parameters = new PageParameters();
		parameters.add("id", rowModel.getObject().getId());
		cellItem.add(new LinkPanel<Cliente>(componentId, "Alterar", ManterClientePage.class, parameters));
	    }
	});

	tabela = new Tabela<Cliente>("dtClientes", colunas, new ClientesProvider(), 20);
	tabela.setOutputMarkupId(true);

	add(tabela);
    }

    private void addFiltros() {
	Form formulario = new Form("formularioFiltro");
	add(formulario);
	formulario.add(new TextField<String>("nomeContem", new PropertyModel<String>(this, "nomeContem")));
	formulario.add(new TextField<String>("email", new PropertyModel<String>(this, "email")));
	formulario.add(new AjaxButton("btnFiltrar") {
	    @Override
	    protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
		target.add(tabela);
	    }
	});
    }

    private class ClientesProvider extends ProviderGenerico<Cliente> {

	private static final long serialVersionUID = -7569110715710900773L;

	@Override
	public Iterator<? extends Cliente> iterator(long first, long count) {
	    return service.getRepository().findAll(getFiltros()).iterator();
	}

	@Override
	public long size() {
	    return service.getRepository().count(getFiltros());
	}
    }

    private Predicate getFiltros() {
	QCliente cliente = QCliente.cliente;
	BooleanBuilder builder = new BooleanBuilder();
	if (StringUtils.isNotBlank(nomeContem)) {
	    builder.and(cliente.nome.containsIgnoreCase(nomeContem));
	}
	if (StringUtils.isNotBlank(email)) {
	    builder.and(cliente.email.equalsIgnoreCase(email));
	}

	return builder;
    }
}


text:
REM Build binaries

pushd .\crio\java\nav6
call ant clean jar
popd

pushd .\roborio\java\navx-mxp
call ant clean jar
popd