text:
package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation;

import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItem;
import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl;
import rx.Observable;
import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateReplicationProtectedItemInputProperties;
import java.util.List;
import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.EnableProtectionInputProperties;
import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItemProperties;
import rx.functions.Func1;

class ReplicationProtectedItemImpl extends CreatableUpdatableImpl<ReplicationProtectedItem, ReplicationProtectedItemInner, ReplicationProtectedItemImpl> implements ReplicationProtectedItem, ReplicationProtectedItem.Definition, ReplicationProtectedItem.Update {
    private final RecoveryServicesManager manager;
    private String fabricName;
    private String protectionContainerName;
    private String replicatedProtectedItemName;
    private EnableProtectionInputProperties cproperties;
    private UpdateReplicationProtectedItemInputProperties uproperties;

    ReplicationProtectedItemImpl(String name, RecoveryServicesManager manager) {
        super(name, new ReplicationProtectedItemInner());
        this.manager = manager;
        // Set resource name
        this.replicatedProtectedItemName = name;
        //
        this.cproperties = new EnableProtectionInputProperties();
        this.uproperties = new UpdateReplicationProtectedItemInputProperties();
    }

    ReplicationProtectedItemImpl(ReplicationProtectedItemInner inner, RecoveryServicesManager manager) {
        super(inner.name(), inner);
        this.manager = manager;
        // Set resource name
        this.replicatedProtectedItemName = inner.name();
        // set resource ancestor and positional variables
        this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics");
        this.protectionContainerName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationProtectionContainers");
        this.replicatedProtectedItemName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationProtectedItems");
        //
        this.cproperties = new EnableProtectionInputProperties();
        this.uproperties = new UpdateReplicationProtectedItemInputProperties();
    }

    @Override
    public RecoveryServicesManager manager() {
        return this.manager;
    }

    @Override
    public Observable<ReplicationProtectedItem> createResourceAsync() {
        ReplicationProtectedItemsInner client = this.manager().inner().replicationProtectedItems();
        return client.createAsync(this.fabricName, this.protectionContainerName, this.replicatedProtectedItemName, this.cproperties)
            .map(new Func1<ReplicationProtectedItemInner, ReplicationProtectedItemInner>() {
               @Override
               public ReplicationProtectedItemInner call(ReplicationProtectedItemInner resource) {
                   resetCreateUpdateParameters();
                   return resource;
               }
            })
            .map(innerToFluentMap(this));
    }

    @Override
    public Observable<ReplicationProtectedItem> updateResourceAsync() {
        ReplicationProtectedItemsInner client = this.manager().inner().replicationProtectedItems();
        return client.updateAsync(this.fabricName, this.protectionContainerName, this.replicatedProtectedItemName, this.uproperties)
            .map(new Func1<ReplicationProtectedItemInner, ReplicationProtectedItemInner>() {
               @Override
               public ReplicationProtectedItemInner call(ReplicationProtectedItemInner resource) {
                   resetCreateUpdateParameters();
                   return resource;
               }
            })
            .map(innerToFluentMap(this));
    }

    @Override
    protected Observable<ReplicationProtectedItemInner> getInnerAsync() {
        ReplicationProtectedItemsInner client = this.manager().inner().replicationProtectedItems();
        return client.getAsync(this.fabricName, this.protectionContainerName, this.replicatedProtectedItemName);
    }

    @Override
    public boolean isInCreateMode() {
        return this.inner().id() == null;
    }

    private void resetCreateUpdateParameters() {
        this.cproperties = new EnableProtectionInputProperties();
        this.uproperties = new UpdateReplicationProtectedItemInputProperties();
    }

    @Override
    public String id() {
        return this.inner().id();
    }

    @Override
    public String location() {
        return this.inner().location();
    }

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

    @Override
    public ReplicationProtectedItemProperties properties() {
        return this.inner().properties();
    }

    @Override
    public String type() {
        return this.inner().type();
    }

    @Override
    public ReplicationProtectedItemImpl withExistingReplicationProtectionContainer(String fabricName, String protectionContainerName) {
        this.fabricName = fabricName;
        this.protectionContainerName = protectionContainerName;
        return this;
    }

    @Override
    public ReplicationProtectedItemImpl withProperties(EnableProtectionInputProperties properties) {
        this.cproperties = properties;
        return this;
    }

    @Override
    public ReplicationProtectedItemImpl withProperties(UpdateReplicationProtectedItemInputProperties properties) {
        this.uproperties = properties;
        return this;
    }

}


text:
<?php

namespace FTR\WebBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * Nearly2siteRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class Nearly2siteRepository extends EntityRepository
{
}

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.buck.core.module.impl.deps.test_module;

import com.facebook.buck.core.module.impl.TestExtension;
import java.io.Serializable;
import org.pf4j.Extension;

@Extension
public class TestModuleExtension implements TestExtension, Serializable {}


text:
<?php
namespace Elements\Tags;

use Elements\Abstracts\Tag;

class HTML extends Tag{

}


text:
/* config.h.in.  Generated from configure.ac by autoheader.  */

/* use 8 or 12 */
#define BITS_IN_JSAMPLE 1

/* libjpeg-turbo build number */
/* #undef BUILD */

/* Support arithmetic encoding */
#define C_ARITH_CODING_SUPPORTED 1

/* Support arithmetic decoding */
#define D_ARITH_CODING_SUPPORTED 1

/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1

/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1

/* Define to 1 if you have the <jni.h> header file. */
/* #undef HAVE_JNI_H */

/* Define to 1 if you have the <locale.h> header file. */
#define HAVE_LOCALE_H 1

/* Define to 1 if you have the `memcpy' function. */
#define HAVE_MEMCPY 1

/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1

/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1

/* Define to 1 if you have the <stddef.h> header file. */
#define HAVE_STDDEF_H 1

/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1

/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1

/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1

/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1

/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1

/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1

/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1

/* Define to 1 if the system has the type `unsigned char'. */
#define HAVE_UNSIGNED_CHAR 1

/* Define to 1 if the system has the type `unsigned short'. */
#define HAVE_UNSIGNED_SHORT 1

/* Compiler does not support pointers to undefined structures. */
/* #undef INCOMPLETE_TYPES_BROKEN */

/* How to obtain function inlining. */
#define INLINE __attribute__((always_inline))

/* libjpeg API version */
#define JPEG_LIB_VERSION 80

/* libjpeg-turbo version */
#define LIBJPEG_TURBO_VERSION 1.5.0

/* libjpeg-turbo version in integer form */
#define LIBJPEG_TURBO_VERSION_NUMBER 1

/* Define to the sub-directory where libtool stores uninstalled libraries. */
#define LT_OBJDIR ".libs/"

/* Support in-memory source/destination managers */
/* #undef MEM_SRCDST_SUPPORTED */

/* Define if you have BSD-like bzero and bcopy in <strings.h> rather than
   memset/memcpy in <string.h>. */
/* #undef NEED_BSD_STRINGS */

/* Define if you need to include <sys/types.h> to get size_t. */
#define NEED_SYS_TYPES_H 1

/* Name of package */
#define PACKAGE "libjpeg-turbo"

/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT 1

/* Define to the full name of this package. */
#define PACKAGE_NAME "libjpeg-turbo"

/* Define to the full name and version of this package. */
#define PACKAGE_STRING "libjpeg-turbo 1.5.0"

/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "libjpeg-turbo"

/* Define to the home page for this package. */
#define PACKAGE_URL ""

/* Define to the version of this package. */
#define PACKAGE_VERSION "1.5.0"

/* Define if your (broken) compiler shifts signed values as if they were
   unsigned. */
/* #undef RIGHT_SHIFT_IS_UNSIGNED */

#define SIZEOF_SIZE_T 1

/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1

#define VERSION "1.5.0"

/* Use accelerated SIMD routines. */
#define WITH_SIMD 1

/* Define to 1 if type `char' is unsigned and you are not using gcc.  */
#ifndef __CHAR_UNSIGNED__
/* # undef __CHAR_UNSIGNED__ */
#endif

/* Define to `__inline__' or `__inline' if that's what the C compiler
   calls it, or to nothing if 'inline' is not supported under any name.  */
#ifndef __cplusplus
/* #undef inline */
#endif

/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */


text:
module TeamSnap
  module Item

    class << self
      def load_items(client, collection)
        collection
          .fetch(:items) { [] }
          .map { |item|
            data = parse_data(item)
              .merge(:href => item[:href])
              .merge(url_attributes(item))
            type = type_of(item)
            cls = load_class(type, data)

            cls.new(data).tap { |obj|
              obj.send(:load_links, client, item.fetch(:links) { [] })
            }
          }
      end

      def parse_data(item)
        data = item
          .fetch(:data)
          .map { |datum|
            name = datum.fetch(:name)
            value = datum.fetch(:value)
            type = datum.fetch(:type) { :default }

            value = DateTime.parse(value) if value && type == "DateTime"

            [name, value]
          }
        hashify(data)
      end

      def type_of(item)
        item
          .fetch(:data)
          .find { |datum| datum.fetch(:name) == "type" }
          .fetch(:value)
      end

      def load_class(type, data)
        TeamSnap.const_get(Inflecto.camelize(type), false).tap { |cls|
          if cls.include?(Virtus::Model::Core)
            cls.class_eval do
              attributes = cls.attribute_set.map(&:name)
              data
                .select { |name, _| !attributes.include?(name.to_sym) }
                .each { |name, value| attribute name, value.class }
            end
          else
            cls.class_eval do
              include Virtus.value_object

              attribute :href, String
              values do
                data.each { |name, value| attribute name, value.class }
              end
            end
          end
        }
      end

      def url_attributes(item)
        links = item
          .fetch(:links) { [] }
          .map { |link| ["#{link.fetch(:rel)}_url", link.fetch(:href)] }
        hashify(links)
      end

      def hashify(arr)
        arr.inject({}) { |hash, (key, value)| hash[key] = value; hash }
      end
    end

    private

    def load_links(client, links)
      links.each do |link|
        next if EXCLUDED_RELS.include?(link.fetch(:rel))

        rel = link.fetch(:rel)
        href = link.fetch(:href)
        is_singular = rel == Inflecto.singularize(rel)

        define_singleton_method(rel) {
          instance_variable_get("@#{rel}") || instance_variable_set(
            "@#{rel}", -> {
              coll = TeamSnap::Item.load_items(
                client,
                TeamSnap.run(client, :get, href)
              )
              is_singular ? coll.first : coll
            }.call
          )
        }
      end

      define_singleton_method(:update) { |attributes|
        patch_attributes = TeamSnap::Api.template_attributes(attributes)

        response = TeamSnap.run(client, :patch, instance_variable_get("@href"), patch_attributes)
        TeamSnap::Item.load_items(client, response).first
      }

      define_singleton_method(:delete) {
        response = TeamSnap.run(client, :delete, instance_variable_get("@href"), {})
        TeamSnap::Item.load_items(client, response).first
      }
    end
  end
end


text:
package talecraft.items;

import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import talecraft.TaleCraft;
import talecraft.clipboard.ClipboardItem;
import talecraft.server.ServerClipboard;
import talecraft.server.ServerHandler;
import talecraft.server.ServerMirror;
import talecraft.util.WorldHelper;

public class CutItem extends TCItem {

	@Override
	public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) {
		if(world.isRemote) {
			rightClickClient(world, player);
		} else {
			rightClickServer(world, player);
			world.notifyBlockUpdate(pos, world.getBlockState(pos), world.getBlockState(pos), 0);
		}

		return EnumActionResult.SUCCESS;
	}

	@Override
	public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) {
		ItemStack stack = player.getHeldItem(hand);
		if(world.isRemote)
			rightClickClient(world, player);
		else
			rightClickServer(world, player);

		return ActionResult.newResult(EnumActionResult.SUCCESS, stack);
	}

	public static void rightClickServer(World world, EntityPlayer player) {
		ServerMirror mirror = ServerHandler.getServerMirror(null);
		ServerClipboard clipboard = mirror.getClipboard();

		int[] bounds = WandItem.getBoundsFromPlayerOrNull(player);
		String keyString = "player."+player.getGameProfile().getId().toString();

		if(bounds == null)
			return;

		ClipboardItem item = ClipboardItem.copyRegion(bounds, world, keyString, player);

		if(item != null) {
			clipboard.put(keyString, item);
			WorldHelper.fill(world, bounds, Blocks.AIR.getDefaultState());
		}
	}

	public static void rightClickClient(World world, EntityPlayer player) {
		int[] bounds = WandItem.getBoundsFromPlayerOrNull(player);

		if(bounds == null)
			return;

		ClipboardItem item = ClipboardItem.copyRegion(bounds, world, "player.self", player);

		if(item != null) {
			TaleCraft.asClient().setClipboard(item);
		}
	}

	@Override
	public boolean onLeftClickEntity(ItemStack stack, EntityPlayer player, Entity entity) {
		// cut entity to clipboard!

		// ClipboardItem.copyEntity();

		// by returning TRUE, we prevent damaging the entity being hit.
		return true;
	}

}


text:
module Main (main) where

import System.IO (hSetEncoding, utf8)

import Summoner (summonCli)

main :: IO ()
main = hSetEncoding stdout utf8 >> summonCli


text:
`roslaunch manipulator_interface nanopi.launch`

## Dependencies

RPi.GPIO GPIO library for NanoPi. The library is integrated in the UbuntuCore
images for the NanoPi NEO/NEO2+.


text:
({
    EMPTY_STRING : '',
    /**
     * Test when value is not assigned.
     */
    testUnassigned: {
        test : function(component) {
            var attr = component.get("v.value");
            $A.test.assertEquals(undefined, attr);
        }
    },

	/**
	 * Test max value.
	 */
    testMax: {
        attributes : {max : 9876.54321},
        test : function(component){
            $A.test.assertEquals(9876.54321, component.get("v.max"), "max does not equal expected");
        }
    },

    /**
     * Test min value.
     */
    testMin: {
        attributes : {min : 0.0003},
        test : function(component){
            $A.test.assertEquals(0.0003, component.get("v.min"), "min does not equal expected");
        }
    },

    /**
     * Test step.
     */
    testStep: {
        attributes : {step : 1.23},
        test : function(component){
            $A.test.assertEquals(1.23, component.get("v.step"), "step does not equal expected");
        }
    },

    /**
     * Test disabled.
     */
    testDisabled: {
        attributes : {disabled : true},
        test : function(component){
            var inputElm = component.getElement();
            $A.test.assertTrue(component.get("v.disabled"), "disable should be true");
            $A.test.assertDefined(inputElm.getAttribute("disabled"), "<input> should have 'disabled' attribute");
        }
    },

    /**
     * Test decimal value.
     */
    testDecimalValue: {
        attributes : {value : 10.3249},
        test : function(component){
            $A.test.assertEquals(10.3249, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test integer value
     */
    testIntValue: {
        attributes : {value : 100},
        test : function(component){
            $A.test.assertEquals(100, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test negative value.
     */
    testNegativeValue: {
        attributes : {value : -5},
        test : function(component){
            $A.test.assertEquals(-5, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Assign Negative value for attribute 'value' and special negative format
     */
    testNegativeValueWithNegativeFormat:{
        attributes: {value : -123.936, format:"#.0#;(#.0#)"},
        test: function(component){
        	var value = component.getElement().value;
            $A.test.assertEquals(-123.936, component.get("v.value"), "Cmp value: Negative values not displayed correctly.");
            $A.test.assertEquals('(123.94)', value, "Element value: Negative values not displayed correctly.");
        }
    },

    /**
     * Test small decimal value.
     */
    testSmallValue: {
        attributes : {value : 0.000005},
        test : function(component){
            $A.test.assertEquals(0.000005, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test large number
     */
    testLargeValue: {
        attributes : {value : 99999999999999},
        test : function(component){
            $A.test.assertEquals(99999999999999, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test zero value.
     */
    testZeroValue: {
        attributes : {value : 0},
        test : function(component){
            $A.test.assertEquals(0, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test when value is empty string
     */
    testEmptyValue: {
        attributes : {value : ""},
        test : function(component){
            $A.test.assertEquals(undefined, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test number formated correctly.
     */
    testNumberFormat: {
    	attributes : {value : 123, format : "#,#"},
    	test : function(component){
    		var value = component.getElement().value;
    		$A.test.assertEquals(123, component.get("v.value"), "Cmp value does not equal expected");
    		$A.test.assertEquals("1,2,3", value, "Element value does not equal expected");
    	}
    },

    /**
     * Test number formated correctly when format is empty.
     */
    testNumberFormatEmptyString: {
    	attributes : {value : 123, format : ""},
    	test : function(component){
    		var value = component.getElement().value;
    		$A.test.assertEquals(123, component.get("v.value"), "Cmp value does not equal expected");
    		$A.test.assertEquals("123", value, "Element value does not equal expected");
    	}
    },

    /**
     * Test number formated correctly when format is invalid.
     */
    testNumberFormatInvalidFormat: {
    	attributes : {value : 123, format : "#.#,0"},
    	test : function(component){
    		var value = component.getElement().value;
    		$A.test.assertEquals(123, component.get("v.value"), "Cmp value does not equal expected");
    		$A.test.assertEquals("123", value, "Element value does not equal expected");
    	}
    },

    /**
     * Test number formated correctly when format is not of a recognizable type.
     */
    testNumberFormatUnrecognizedFormat: {
    	attributes : {value : 123, format : "xyz"},
    	test : function(component){
    		var value = component.getElement().value;
    		$A.test.assertEquals(123, component.get("v.value"), "Cmp value does not equal expected");
    		$A.test.assertEquals("123", value, "Element value does not equal expected");
    	}
    },

    /**
    * Positive test case: Assign nothing to format value and verify default precision used to display decimal.
    */
   testDefaultDecimalPrecision: {
       attributes : {value : 123.450},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(123.45, component.get("v.value"), "Cmp value not displayed as expected when format is not specified.");
           $A.test.assertEquals("123.45", value, " Element value not displayed as expected when format is not specified.");
       }
   },

   /**
    * Verify Rounding up of lots of 9s
    */
   testRoundingLotsOfNines: {
       attributes : {value : 999999.9, format : '#,##0'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(999999.9, component.get("v.value"), "Cmp value: Nines were not rounded up correctly");
           $A.test.assertEquals('1,000,000', value, "Element value: Nines were not rounded up correctly");
       }
   },
   /**
    * Verify Rounding up of lots of 9s with extra zero padding
    */
   testRoundingLotsOfNinesAndZeroPadding: {
       attributes : {value : 999999.9, format : '00000000'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(999999.9, component.get("v.value"), "Cmp value: Nines were not round up correctly");
           $A.test.assertEquals('01000000', value, "Element value: Nines were not round up correctly");
       }
   },
   /**
    * Verify Rounding up of decimal part of value.
    */
   testFormat2DecimalPlaces_RoundUp: {
       attributes : {value : 3.1459, format : '.00'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(3.1459, component.get("v.value"), "Cmp value: Decimal part of value was not rounded up based on format.");
           $A.test.assertEquals('3.15', value, "Element value: Decimal part of value was not rounded up based on format.");
       }
   },
   /**
    * Verify Rounding down of decimal part of value.
    */
   testFormat2DecimalPlaces_RoundDown: {
       attributes : {value : 3.14159, format : '.00'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(3.14159, component.get("v.value"), "Cmp value: Decimal part of value was not rounded down based on format.");
           $A.test.assertEquals('3.14', value, "Element value: Decimal part of value was not rounded down based on format.");
       }
   },
   /**
    * Verify Rounding functionality when length of integer part is restricted by format.
    */
   testFormatDoesNotRestrictIntegerValue: {
       attributes : {value : 22.7, format : '0.0'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(22.7, component.get("v.value"), "Cmp value: Should have displayed full value but was probably truncated.");
           $A.test.assertEquals('22.7', value, "Element value: Should have displayed full value but was probably truncated.");
       }
   },
   /**
    * Verify that zeros are appended to decimal value to match format.
    */
   testAppendingZeroToMatchFormat: {
       attributes : {value : 22.7, format : '.000'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(22.7, component.get("v.value"), "Cmp value: Should have appended two zeros to match format.");
           $A.test.assertEquals('22.700', value, "Element value: Should have appended two zeros to match format.");
       }
   },

    /**
     * Test big value that is too large for a js number and is represented instead by a string
     *
     * Disabled for now due to new changes to inputNumber
     * TODO: wait for this W-2947804 and re-enable the test
     */
    _testBigDecimal: {
        attributes: {value: '1234567890123456789012345678901234567890.12', format: '.00'},
        test: function(component){
            var value = component.getElement().value;
            $A.test.assertEquals('1234567890123456789012345678901234567890.12', component.get("v.value"), "Cmp value: Unexpected value.");
            $A.test.assertEquals('1234567890123456789012345678901234567890.12', value, "Element value: Unexpected value.");
        }
    },

    /**
     * Test well-formatted value
     */
    testSetValueWithWellFormattedValue: {
        test: [function(component) {
            component.set('v.value', '56,789');
        }, function(component) {
            this.assertCmpElemValues(component, 56789, '56,789');
        }]
    },

    /**
     * Test set value using number string
     */
    testSetValueWithString: {
        test: [function(component) {
            component.set('v.value', '56789');
        }, function(component) {
            this.assertCmpElemValues(component, '56789', '56,789');
        }]
    },

   /**
    * Verify that when the value changes it is rerendered with the unformated new value
    */
   testUpdateValue: {
       attributes : {value : 22.7, format : '##,#0,00.00#####'},
       test: [function(component){
    	   var value = component.getElement().value;
    	   $A.test.assertEquals(22.7, component.get("v.value"), "Cmp: Value not formatted correctly.");
           $A.test.assertEquals('0,22.70', value, "Element: Value not formatted correctly.");
           component.set("v.value", 49322);
       }, function(component){
           // after dirty component is re-rendered, now input element
           // should be displaying the new value
    	   var value = component.getElement().value;
    	   $A.test.assertEquals(49322, component.get("v.value"), "Cmp: Value not formatted correctly.");
           $A.test.assertEquals('4,93,22.00', value, "Element: Value not formatted correctly.");
       }]
   },

   /**
    * Verify that when the format changes it is not rerendered with the new format
    */
   testUpdateFormat: {
       attributes : {value : 22.7, format : '##,#0,00.00#####'},
       test: [function(component){
    	   var value = component.getElement().value;
    	   $A.test.assertEquals(22.7, component.get("v.value"), "Cmp: Value not formatted correctly.");
           $A.test.assertEquals('0,22.70', value, "Element: Value not formatted correctly.");
           component.set("v.format", '.000');
       }, function(component){
           // updating format dynamically is not supported
           // value stays the same
           var value = component.getElement().value;
    	   $A.test.assertEquals(22.7, component.get("v.value"), "Cmp: Value not formatted correctly.");
           $A.test.assertEquals('0,22.70', value, "Element: Value not formatted correctly.");
       }]
   },

    /*
     * Verify that when value is set to an invalid value,
     * internal v.value should be undefined
     * displayed value should be empty
     */
    testSetInvalidValue: {
        attributes: {value: 12},
        test: [function (component) {
            component.set('v.value', 'abc');
        }, function(component){
            var inputValue = component.getElement().value;
            $A.test.assertEquals(this.EMPTY_STRING, inputValue, "Cmp: input value should be empty string");
            $A.test.assertEquals(null, component.get("v.value"), "Cmp: value should be undefined.");
        }]
    },

    /**
     * Test shortcut K/k as in thousand
     */
    testShortcutK: {
        test: [function(component) {
            this.inputValue(component, "1k");
        }, function(component) {
            this.triggerUpdateCmpElmValues(component);
        }, function(component) {
            this.assertCmpElemValues(component, 1000, "1,000");
        }, function(component) {
            this.inputValue(component, "1K");
        }, function(component) {
            this.triggerUpdateCmpElmValues(component);
        }, function(component) {
            this.assertCmpElemValues(component, 1000, "1,000");
        }]
    },

    /**
     * Test shortcut M/m as in million
     */
    testShortcutM: {
        test: [function(component) {
            this.inputValue(component, "1m");
        }, function(component) {
            this.triggerUpdateCmpElmValues(component);
        }, function(component) {
            this.assertCmpElemValues(component, 1000000, "1,000,000");
        }, function(component) {
            this.inputValue(component, "1M");
        }, function(component) {
            this.triggerUpdateCmpElmValues(component);
        }, function(component) {
            this.assertCmpElemValues(component, 1000000, "1,000,000");
        }]
    },

    /**
     * Test shortcut B/b as in billion
     */
    testShortcutB: {
        test: [function(component) {
            this.inputValue(component, "1b");
        }, function(component) {
            this.triggerUpdateCmpElmValues(component);
        }, function(component) {
            this.assertCmpElemValues(component, 1000000000, "1,000,000,000");
        }, function(component) {
            this.inputValue(component, "1B");
        }, function(component) {
            this.triggerUpdateCmpElmValues(component);
        }, function(component) {
            this.assertCmpElemValues(component, 1000000000, "1,000,000,000");
        }]
    },

    /**
     * Test shortcut T/t as in trillion
     */
    testShortcutT: {
        test: [function(component) {
            this.inputValue(component, "1t");
        }, function(component) {
            this.triggerUpdateCmpElmValues(component);
        }, function(component) {
            this.assertCmpElemValues(component, 1000000000000, "1,000,000,000,000");
        }, function(component) {
            this.inputValue(component, "1T");
        }, function(component) {
            this.triggerUpdateCmpElmValues(component);
        }, function(component) {
            this.assertCmpElemValues(component, 1000000000000, "1,000,000,000,000");
        }]
    },

    /**
     * Test shortcut should still work after decimal marker
     */
    testShortcutAfterDecimalMark: {
        test: [function(component) {
            this.inputValue(component, "0.1m");
        }, function(component) {
            this.triggerUpdateCmpElmValues(component);
        }, function(component) {
            this.assertCmpElemValues(component, 100000, "100,000");
        }]
    },

    /**
     * Test input with a positive sign
     */
    testPositiveSign: {
        test: [function(component) {
            this.inputValue(component, "+123");
        }, function(component) {
            this.triggerUpdateCmpElmValues(component);
        }, function(component) {
            this.assertCmpElemValues(component, 123, "123");
        }]
    },

    /**
     * Test input with a negative sign
     */
    testNegativeSign: {
        test: [function(component) {
            this.inputValue(component, "-123");
        }, function(component) {
            this.triggerUpdateCmpElmValues(component);
        }, function(component) {
            this.assertCmpElemValues(component, -123, "-123");
        }]
    },

    /**
     * Any number of thousand marker should be allowed in integer part
     */
    testThousandMarkerInIntegerPart: {
        test: [function(component) {
            this.inputValue(component, "1,2,3,4,5");
        }, function(component) {
            this.triggerUpdateCmpElmValues(component);
        }, function(component) {
            this.assertCmpElemValues(component, 12345, "12,345");
        }]
    },

    /*****************
     * Helpers
     *****************/

    // set element value and fire appropriate events to simulate what happens
    // when user types in input box
    inputValue: function(component, value) {
        var inputElm = component.getElement();
        inputElm.value = value;
        // typing triggers input event
        // it tells the component to cache the elem value for when a change/blur event happens
        $A.test.fireDomEvent(inputElm, "input");
    },

    // fire blur event to update v.value and format elem value
    triggerUpdateCmpElmValues: function(component) {
        var inputElm = component.getElement();
        $A.test.fireDomEvent(inputElm, "blur");
    },

    // check component's internval v.value and displayed value on the input box
    assertCmpElemValues: function (component, expectedCmpVal, expectedElemVal) {
        $A.test.assertEquals(expectedCmpVal, component.get("v.value"),
                "Cmp value doesn't equal to expected");
        $A.test.assertEquals(expectedElemVal, component.getElement().value,
                "Element value is not displayed/formatted correctly.");
    }
})// eslint-disable-line semi


text:
set -ex

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt-get update
apt-cache policy docker-ce
sudo apt-get install -y docker-ce
sudo usermod -aG docker ${USER}


text:
package org.dynmap.modsupport.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import org.dynmap.modsupport.BlockSide;
import org.dynmap.modsupport.ModelBlockModel;

public class ModelBlockModelImpl extends BlockModelImpl implements ModelBlockModel {

	private static class ModelSide {
		private double[] uv;
		private SideRotation rot;
		int textureid;
	};
	private static class ModelBlockImpl implements ModelBlock {
		private HashMap<BlockSide, ModelSide> sides = new HashMap<BlockSide, ModelSide>();
		private double[] from = { 0, 0, 0 };
		private double[] to = { 16, 16, 16 };
		private double xrot = 0, yrot = 0, zrot = 0;
		private boolean shade;
		private double[] rotorigin;
		private int modrotx = 0, modroty = 0, modrotz = 0;
		@Override
		public void addBlockSide(BlockSide side, double[] uv, SideRotation rot, int textureid, int tintidx) {
			ModelSide ms = new ModelSide();
			ms.textureid = textureid;
			if (uv != null) {
				ms.uv = Arrays.copyOf(uv, uv.length);
			}
			if (rot != null) {
				ms.rot = rot;
			}
			if (side == BlockSide.FACE_0 || side == BlockSide.Y_MINUS) side = BlockSide.BOTTOM;
			if (side == BlockSide.FACE_1 || side == BlockSide.Y_PLUS) side = BlockSide.TOP;
			if (side == BlockSide.FACE_2 || side == BlockSide.Z_MINUS) side = BlockSide.NORTH;
			if (side == BlockSide.FACE_3 || side == BlockSide.Z_PLUS) side = BlockSide.SOUTH;
			if (side == BlockSide.FACE_4 || side == BlockSide.X_MINUS) side = BlockSide.WEST;
			if (side == BlockSide.FACE_5 || side == BlockSide.X_PLUS) side = BlockSide.EAST;

			sides.put(side,  ms);
		}
		@Override
		public void addBlockSide(BlockSide side, double[] uv, SideRotation rot, int textureid) {
			addBlockSide(side, uv, rot, textureid, -1);
		}
	}
	private ArrayList<ModelBlockImpl> boxes = new ArrayList<ModelBlockImpl>();

    public ModelBlockModelImpl(String blkname, ModModelDefinitionImpl mdf) {
        super(blkname, mdf);
    }

    private static HashMap<BlockSide, String> fromBlockSide = new HashMap<BlockSide, String>();
    static {
    	fromBlockSide.put(BlockSide.TOP, "u");
    	fromBlockSide.put(BlockSide.BOTTOM, "d");
    	fromBlockSide.put(BlockSide.NORTH, "n");
    	fromBlockSide.put(BlockSide.SOUTH, "s");
    	fromBlockSide.put(BlockSide.WEST, "w");
    	fromBlockSide.put(BlockSide.EAST, "e");
    };

    @Override
    public String getLine() {
        String ids = this.getIDsAndMeta();
        if (ids == null) return null;
        String line;
    	line = String.format("modellist:%s", ids);
    	for (ModelBlockImpl mb: boxes) {
    		line += String.format(",box=%f/%f/%f", mb.from[0], mb.from[1], mb.from[2]);
    		if (!mb.shade) {	// if shade=false
        		line += "/false";
    		}
    		line += String.format(":%f/%f/%f", mb.to[0], mb.to[1], mb.to[2]);
    		if ((mb.xrot != 0) || (mb.yrot != 0) || (mb.zrot != 0)) {	// If needed, add rotation
    			line += String.format("/%f/%f/%f", mb.xrot, mb.yrot, mb.zrot);
    			// If origin also defined, add it
    			if (mb.rotorigin != null) {
        			line += String.format("/%f/%f/%f", mb.rotorigin[0], mb.rotorigin[1], mb.rotorigin[2]);
    			}
    		}
    		for (BlockSide bs : fromBlockSide.keySet()) {
    			String side = fromBlockSide.get(bs);
    			ModelSide mside = mb.sides.get(bs);
    			if (mside != null) {
    				String rval = side;
    				switch (mside.rot) {
        				case DEG0:
        				default:
        					break;
        				case DEG90:
        					rval += "90";
        					break;
        				case DEG180:
        					rval += "180";
        					break;
        				case DEG270:
        					rval += "270";
        					break;
    				}
    				if (mside.uv != null) {
    					line += String.format(":%s/%d/%f/%f/%f/%f", rval, mside.textureid, mside.uv[0], mside.uv[1], mside.uv[2], mside.uv[3]);
    				}
    				else {
    					line += String.format(":%s/%d", rval, mside.textureid);
    				}
    			}
    		}
    		if ((mb.modrotx != 0) || (mb.modroty != 0) || (mb.modrotz != 0)) {
    			line += String.format(":R/%d/%d/%d", mb.modrotx, mb.modroty, mb.modrotz);
    		}
        }
        return line;
    }
    /**
     * Factory method to build a block of patches relative to a typical element in a MC model file.
     * Specifically, all coordinates are relative to 0-16 range for
     * side of a cube, and relative to 0-16 range for U,V within a texture:
     *
     *    from, to in model drive 'from', 'to' inputs
     *
     *    face, uv of face, and texture in model drives face, uv, textureid (added using addBlockSide)
     *
     * @param from - vector of lower left corner of box (0-16 range for coordinates - min x, y, z)
     * @param to - vector of upper right corner of box (0-16 range for coordinates max x, y, z)
     * @param xrot - degrees of rotation of block around X
     * @param yrot - degrees of rotation of block around Y
     * @param zrot - degrees of rotation of block around Z
     * @param shade - shade setting for model
     * @param rotorigin - rotation origin, if any (default [ 8, 8, 8 ](
     * @param modrotx - model level rotation in degrees (0, 90, 180, 270)
     * @param modroty - model level rotation in degrees (0, 90, 180, 270)
     * @param modrotz - model level rotation in degrees (0, 90, 180, 270)
	 * @return model block to add faces to
     */
    @Override
    public ModelBlock addModelBlock(double[] from, double[] to, double xrot, double yrot, double zrot,
    	boolean shade, double[] rotorigin, int modrotx, int modroty, int modrotz) {
    	ModelBlockImpl mbi = new ModelBlockImpl();
    	if (from != null) { mbi.from[0] = from[0]; mbi.from[1] = from[1]; mbi.from[2] = from[2]; }
    	if (to != null) { mbi.to[0] = to[0]; mbi.to[1] = to[1]; mbi.to[2] = to[2]; }
    	mbi.xrot = xrot; mbi.yrot = yrot; mbi.zrot = zrot;
    	mbi.shade = shade;
    	if (rotorigin != null) {
    		mbi.rotorigin = Arrays.copyOf(rotorigin, 3);
    	}
    	mbi.modrotx = modrotx;
    	mbi.modroty = modroty;
    	mbi.modrotz = modrotz;
    	boxes.add(mbi);
    	return mbi;
    }
}


text:
use crate::errors::invalid_data_error;
use iso7816::aid::Aid;
use iso7816::command::instruction::Instruction;
use iso7816::command::Command;
use iso7816::response::Status;
use iso7816_tlv::ber::{Tag, Tlv, Value};
use rdp::model::error::*;
use rsa::pkcs1::DecodeRsaPrivateKey;
use rsa::{BigUint, PublicKeyParts, RsaPrivateKey};
use std::convert::TryFrom;
use std::fmt::Write as _;
use std::io::{Cursor, Read};
use uuid::Uuid;

// AID (Application ID) of PIV application, per
// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf
const PIV_AID: Aid = Aid::new_truncatable(
    &[
        0xA0, 0x00, 0x00, 0x03, 0x08, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00,
    ],
    5, // usually truncates to first 5 bytes
);

// Card implements a PIV-compatible smartcard, per:
// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf
#[derive(Debug, PartialEq, Eq)]
pub struct Card<const S: usize> {
    // Card-holder user ID (CHUID). In federal agencies, this value would be unique per employee
    // and encodes some agency information. In our case it's static.
    chuid: Vec<u8>,
    piv_auth_cert: Vec<u8>,
    piv_auth_key: RsaPrivateKey,
    pin: String,
    // Pending command and response to receive/send over multiple messages when they don't fit into
    // one.
    pending_command: Option<Command<S>>,
    pending_response: Option<Cursor<Vec<u8>>>,
}

impl<const S: usize> Card<S> {
    pub fn new(uuid: Uuid, cert_der: &[u8], key_der: &[u8], pin: String) -> RdpResult<Self> {
        let piv_auth_key = RsaPrivateKey::from_pkcs1_der(key_der).map_err(|e| {
            invalid_data_error(&format!("failed to parse private key from DER: {:?}", e))
        })?;

        Ok(Self {
            chuid: Self::build_chuid(uuid),
            piv_auth_cert: Self::build_piv_auth_cert(cert_der),
            piv_auth_key,
            pin,
            pending_command: None,
            pending_response: None,
        })
    }

    pub fn handle(&mut self, cmd: Command<S>) -> RdpResult<Response> {
        debug!("got command: {:?}", cmd);
        debug!("command data: {}", hex_data(&cmd));

        // Handle chained commands.
        let cmd = match self.pending_command.as_mut() {
            None => cmd,
            Some(pending) => {
                pending
                    .extend_from_command(&cmd)
                    .map_err(|_| invalid_data_error("could not build chained command"))?;

                pending.clone()
            }
        };
        if cmd.class().chain().not_the_last() {
            self.pending_command = Some(cmd);
            return Ok(Response::new(Status::Success));
        } else {
            self.pending_command = None;
        }

        let resp = match cmd.instruction() {
            Instruction::Select => self.handle_select(cmd),
            Instruction::Verify => self.handle_verify(cmd),
            Instruction::GetData => self.handle_get_data(cmd),
            Instruction::GetResponse => self.handle_get_response(cmd),
            Instruction::GeneralAuthenticate => self.handle_general_authenticate(cmd),
            _ => {
                warn!("unimplemented instruction {:?}", cmd.instruction());
                Ok(Response::new(Status::InstructionNotSupportedOrInvalid))
            }
        }?;
        debug!("send response: {:?}", resp);
        debug!("response data: {}", to_hex(&resp.encode()));
        Ok(resp)
    }

    fn handle_select(&mut self, cmd: Command<S>) -> RdpResult<Response> {
        // For our use case, we only allow selecting the PIV application on the smartcard.
        //
        // P1=04 and P2=00 means selection of DF (usually) application by name. Everything else not
        // supported.
        if cmd.p1 != 0x04 && cmd.p2 != 0x00 {
            return Ok(Response::new(Status::NotFound));
        }
        if !PIV_AID.matches(cmd.data()) {
            return Ok(Response::new(Status::NotFound));
        }

        // See https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf section
        // 3.1.1
        let resp = tlv(
            TLV_TAG_PIV_APPLICATION_PROPERTY_TEMPLATE,
            Value::Constructed(vec![
                tlv(
                    TLV_TAG_AID,
                    Value::Primitive(vec![0x00, 0x00, 0x10, 0x00, 0x01, 0x00]),
                )?,
                tlv(
                    TLV_TAG_COEXISTENT_TAG_ALLOCATION_AUTHORITY,
                    Value::Constructed(vec![tlv(
                        TLV_TAG_AID,
                        Value::Primitive(PIV_AID.truncated().to_vec()),
                    )?]),
                )?,
            ]),
        )?;
        Ok(Response::with_data(Status::Success, resp.to_vec()))
    }

    fn handle_verify(&mut self, cmd: Command<S>) -> RdpResult<Response> {
        if cmd.data() == self.pin.as_bytes() {
            Ok(Response::new(Status::Success))
        } else {
            warn!("PIN mismatch, want {}, got {:?}", self.pin, cmd.data());
            Ok(Response::new(Status::VerificationFailed))
        }
    }

    fn handle_get_data(&mut self, cmd: Command<S>) -> RdpResult<Response> {
        // See https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf section
        // 3.1.2.
        if cmd.p1 != 0x3F && cmd.p2 != 0xFF {
            return Ok(Response::new(Status::NotFound));
        }
        let request_tlv = Tlv::from_bytes(cmd.data())
            .map_err(|e| invalid_data_error(&format!("TLV invalid: {:?}", e)))?;
        if *request_tlv.tag() != tlv_tag(0x5C)? {
            return Ok(Response::new(Status::NotFound));
        }
        match request_tlv.value() {
            Value::Primitive(tag) => match to_hex(tag).as_str() {
                // Card Holder Unique Identifier.
                "5FC102" => Ok(Response::with_data(Status::Success, self.chuid.clone())),
                // X.509 Certificate for PIV Authentication
                "5FC105" => {
                    self.pending_response = Some(Cursor::new(self.piv_auth_cert.clone()));
                    self.handle_get_response(cmd)
                }
                _ => {
                    // Some other unimplemented data object.
                    Ok(Response::new(Status::NotFound))
                }
            },
            Value::Constructed(_) => Ok(Response::new(Status::NotFound)),
        }
    }

    fn handle_get_response(&mut self, _cmd: Command<S>) -> RdpResult<Response> {
        // CHINK_SIZE is the max response data size in bytes, without resorting to "extended"
        // messages.
        const CHUNK_SIZE: usize = 256;
        match &mut self.pending_response {
            None => Ok(Response::new(Status::NotFound)),
            Some(cursor) => {
                let mut chunk = [0; CHUNK_SIZE];
                let n = cursor.read(&mut chunk)?;
                let mut chunk = chunk.to_vec();
                chunk.truncate(n);
                let remaining = cursor.get_ref().len() as u64 - cursor.position();
                let status = if remaining == 0 {
                    Status::Success
                } else if remaining < CHUNK_SIZE as u64 {
                    Status::MoreAvailable(remaining as u8)
                } else {
                    Status::MoreAvailable(0)
                };
                Ok(Response::with_data(status, chunk))
            }
        }
    }

    /// Sign the challenge.
    ///
    /// Note: for signatures, typically you'd use a signer that hashes the input data, adds padding
    /// according to some scheme (like PKCS1v15 or PSS) and then "decrypts" this data with the key.
    /// The decrypted blob is the signature.
    ///
    /// In our case, the RDP server does the hashing and padding, and only gives us a finished blob
    /// to decrypt. Most crypto libraries don't directly expose RSA decryption without padding, as
    /// it's easy to build insecure crypto systems. Thankfully for us, this decryption is just a single
    /// modpow operation which is suppored by RustCrypto.
    fn sign_auth_challenge(&self, challenge: &[u8]) -> Vec<u8> {
        let c = BigUint::from_bytes_be(challenge);
        let plain_text = c
            .modpow(self.piv_auth_key.d(), self.piv_auth_key.n())
            .to_bytes_be();

        let mut result = vec![0u8; self.piv_auth_key.size()];
        let start = result.len() - plain_text.len();
        result[start..].copy_from_slice(&plain_text);
        result
    }

    fn handle_general_authenticate(&mut self, cmd: Command<S>) -> RdpResult<Response> {
        // See section 3.2.4 and example in Appending A.3 from
        // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf

        // P1='07' means 2048-bit RSA.
        //
        // TODO(zmb3): compare algorithm against the private key using consts from
        // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-78-4.pdf
        // TODO(zmb3): support non-RSA keys, if needed.
        if cmd.p1 != 0x07 {
            return Err(invalid_data_error(&format!(
                "unsupported algorithm identifier P1:{:#X} in general authenticate command",
                cmd.p1
            )));
        }
        // P2='9A' means PIV Authentication Key (matches our cert '5FC105' in handle_get_data).
        if cmd.p2 != 0x9A {
            return Err(invalid_data_error(&format!(
                "unsupported key reference P2:{:#X} in general authenticate command",
                cmd.p2
            )));
        }

        let request_tlv = Tlv::from_bytes(cmd.data())
            .map_err(|e| invalid_data_error(&format!("TLV invalid: {:?}", e)))?;
        if *request_tlv.tag() != tlv_tag(TLV_TAG_DYNAMIC_AUTHENTICATION_TEMPLATE)? {
            return Err(invalid_data_error(&format!(
                "general authenticate command TLV invalid: {:?}",
                request_tlv
            )));
        }

        // Extract the challenge field.
        let request_tlvs = match request_tlv.value() {
            Value::Primitive(_) => {
                return Err(invalid_data_error(&format!(
                    "general authenticate command TLV invalid: {:?}",
                    request_tlv
                )));
            }
            Value::Constructed(tlvs) => tlvs,
        };
        let mut challenge = None;
        for data in request_tlvs {
            if *data.tag() != tlv_tag(TLV_TAG_CHALLENGE)? {
                continue;
            }
            challenge = match data.value() {
                Value::Primitive(chal) => Some(chal),
                Value::Constructed(_) => {
                    return Err(invalid_data_error(&format!(
                        "general authenticate command TLV invalid: {:?}",
                        request_tlv
                    )));
                }
            };
        }
        let challenge = challenge.ok_or_else(|| {
            invalid_data_error(&format!(
                "general authenticate command TLV invalid: {:?}, missing challenge data",
                request_tlv
            ))
        })?;

        // TODO(zmb3): support non-RSA keys, if needed.
        let signed_challenge = self.sign_auth_challenge(challenge);

        // Return signed challenge.
        let resp = tlv(
            TLV_TAG_DYNAMIC_AUTHENTICATION_TEMPLATE,
            Value::Constructed(vec![tlv(
                TLV_TAG_RESPONSE,
                Value::Primitive(signed_challenge),
            )?]),
        )?
        .to_vec();
        self.pending_response = Some(Cursor::new(resp));
        self.handle_get_response(cmd)
    }

    fn build_chuid(uuid: Uuid) -> Vec<u8> {
        // This is gross: the response is a BER-TLV value, but it has nested SIMPLE-TLV
        // values. None of the TLV encoding libraries out there support this, they fail
        // when checking the tag of nested TLVs.
        //
        // So, construct the TLV by hand from raw bytes. Hopefully the comments will be
        // enough to explain the structure.
        //
        // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf
        // table 9 has the explanation of fields.
        //
        // Start with a top-level BER-TLV tag and length:
        let mut resp = vec![TLV_TAG_DATA_FIELD, 0x3B];
        // TLV tag and length for FASC-N.
        resp.extend_from_slice(&[TLV_TAG_FASC_N, 0x19]);
        // FASC-N value containing S9999F9999F999999F0F1F0000000000300001E, with a
        // weird encoding from section 6 of:
        // https://www.idmanagement.gov/docs/pacs-tig-scepacs.pdf
        resp.extend_from_slice(&[
            0xd4, 0xe7, 0x39, 0xda, 0x73, 0x9c, 0xed, 0x39, 0xce, 0x73, 0x9d, 0x83, 0x68, 0x58,
            0x21, 0x08, 0x42, 0x10, 0x84, 0x21, 0xc8, 0x42, 0x10, 0xc3, 0xeb,
        ]);
        // TLV for user UUID.
        resp.extend_from_slice(&[TLV_TAG_GUID, 0x10]);
        resp.extend_from_slice(uuid.as_bytes());
        // TLV for expiration date (YYYYMMDD).
        resp.extend_from_slice(&[TLV_TAG_EXPIRATION_DATE, 0x08]);
        // TODO(awly): generate this from current time.
        resp.extend_from_slice("20300101".as_bytes());
        // TLV for signature (empty).
        resp.extend_from_slice(&[TLV_TAG_ISSUER_ASYMMETRIC_SIGNATURE, 0x00]);
        // TLV for error detection code.
        resp.extend_from_slice(&[TLV_TAG_ERROR_DETECTION_CODE, 0x00]);
        resp
    }

    fn build_piv_auth_cert(cert_der: &[u8]) -> Vec<u8> {
        // Same as above, tags in this BER-TLV value are not compatible with the spec
        // and existing libraries. Marshal by hand.
        //
        // Certificate TLV tag and length.
        let mut resp = vec![TLV_TAG_CERTIFICATE];
        resp.extend_from_slice(&len_to_vec(cert_der.len()));
        resp.extend_from_slice(cert_der);
        // CertInfo TLV (0x00 indicates uncompressed cert).
        resp.extend_from_slice(&[TLV_TAG_CERTINFO, 0x01, 0x00]);
        // TLV for error detection code.
        resp.extend_from_slice(&[TLV_TAG_ERROR_DETECTION_CODE, 0x00]);

        // Wrap with top-level TLV tag and length.
        let mut resp_outer = vec![TLV_TAG_DATA_FIELD];
        resp_outer.extend_from_slice(&len_to_vec(resp.len()));
        resp_outer.extend_from_slice(&resp);
        resp_outer
    }
}

#[derive(Debug)]
pub struct Response {
    data: Option<Vec<u8>>,
    status: Status,
}

impl Response {
    fn new(status: Status) -> Self {
        Self { data: None, status }
    }
    fn with_data(status: Status, data: Vec<u8>) -> Self {
        Self {
            data: Some(data),
            status,
        }
    }

    pub fn encode(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        if let Some(data) = &self.data {
            buf.extend_from_slice(data);
        }
        let status: [u8; 2] = self.status.into();
        buf.extend_from_slice(&status);
        buf
    }
}

// SELECT command tags.
const TLV_TAG_PIV_APPLICATION_PROPERTY_TEMPLATE: u8 = 0x61;
const TLV_TAG_AID: u8 = 0x4F;
const TLV_TAG_COEXISTENT_TAG_ALLOCATION_AUTHORITY: u8 = 0x79;
const TLV_TAG_DATA_FIELD: u8 = 0x53;
const TLV_TAG_FASC_N: u8 = 0x30;
const TLV_TAG_GUID: u8 = 0x34;
const TLV_TAG_EXPIRATION_DATE: u8 = 0x35;
const TLV_TAG_ISSUER_ASYMMETRIC_SIGNATURE: u8 = 0x3E;
const TLV_TAG_ERROR_DETECTION_CODE: u8 = 0xFE;
const TLV_TAG_CERTIFICATE: u8 = 0x70;
const TLV_TAG_CERTINFO: u8 = 0x71;
// GENERAL AUTHENTICATE command tags.
const TLV_TAG_DYNAMIC_AUTHENTICATION_TEMPLATE: u8 = 0x7C;
const TLV_TAG_CHALLENGE: u8 = 0x81;
const TLV_TAG_RESPONSE: u8 = 0x82;

fn tlv(tag: u8, value: Value) -> RdpResult<Tlv> {
    Tlv::new(tlv_tag(tag)?, value)
        .map_err(|e| invalid_data_error(&format!("TLV with tag {:#X} invalid: {:?}", tag, e)))
}

fn tlv_tag(val: u8) -> RdpResult<Tag> {
    Tag::try_from(val)
        .map_err(|e| invalid_data_error(&format!("TLV tag {:#X} invalid: {:?}", val, e)))
}

fn hex_data<const S: usize>(cmd: &Command<S>) -> String {
    to_hex(cmd.data())
}

fn to_hex(bytes: &[u8]) -> String {
    let mut s = String::new();
    for b in bytes {
        // https://rust-lang.github.io/rust-clippy/master/index.html#format_push_string
        let _ = write!(s, "{:02X}", b);
    }
    s
}

#[allow(clippy::cast_possible_truncation)]
fn len_to_vec(len: usize) -> Vec<u8> {
    if len < 0x7f {
        vec![len as u8]
    } else {
        let mut ret: Vec<u8> = len
            .to_be_bytes()
            .iter()
            .skip_while(|&x| *x == 0)
            .cloned()
            .collect();
        ret.insert(0, 0x80 | ret.len() as u8);
        ret
    }
}


text:
<sr-navbar></sr-navbar>
<router-outlet></router-outlet>
<toaster-container [toasterconfig]="toasterConfig"></toaster-container>


text:
package com.google.android.apps.dashclock.api;

import com.google.android.apps.dashclock.api.internal.IExtension;
import com.google.android.apps.dashclock.api.internal.IExtensionHost;

import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.util.Log;

/**
 * Base class for a DashClock extension. Extensions are a way for other apps to show additional
 * status information within DashClock widgets that the user may add to the lockscreen or home
 * screen. A limited amount of status information is supported. See the {@link ExtensionData} class
 * for the types of information that can be displayed.
 *
 *
Subclassing {@link DashClockExtension}

 *
 * Subclasses must implement at least the {@link #onUpdateData(int)} method, which will be called
 * when DashClock requests updated data to show for this extension. Once the extension has new
 * data to show, call {@link #publishUpdate(ExtensionData)} to pass the data to the main DashClock
 * process. {@link #onUpdateData(int)} will by default be called roughly once per hour, but
 * extensions can use methods such as {@link #setUpdateWhenScreenOn(boolean)} and
 * {@link #addWatchContentUris(String[])} to request more frequent updates.
 *
 *

 * Subclasses can also override the {@link #onInitialize(boolean)} method to perform basic
 * initialization each time a connection to DashClock is established or re-established.
 *
 *
Registering extensions

 * An extension is simply a service that the DashClock process binds to. Subclasses of this
 * base {@link DashClockExtension} class should thus be declared as <service>
 * components in the application's AndroidManifest.xml file.
 *
 *

 * The main DashClock app discovers available extensions using Android's {@link Intent} mechanism.
 * Ensure that your service definition includes an <intent-filter>
 * with an action of {@link #ACTION_EXTENSION}. Also make sure to require the
 * {@link #PERMISSION_READ_EXTENSION_DATA} permission so that only DashClock can bind to your
 * service and request updates. Lastly, there are a few <meta-data> elements that
 * you should add to your service definition:
 *
 *

 *
protocolVersion (required): should be 1.

 *
description (required): should be a one- or two-sentence description
 * of the extension, as a string.

 *
settingsActivity (optional): if present, should be the qualified
 * component name for a configuration activity in the extension's package that DashClock can offer
 * to the user for customizing the extension.

 *

 *
 *
Example

 *
 * Below is an example extension declaration in the manifest:
 *
 *

 * <service android:name=".ExampleExtension"
 *     android:icon="@drawable/ic_extension_example"
 *     android:label="@string/extension_title"
 *     android:permission="com.google.android.apps.dashclock.permission.READ_EXTENSION_DATA">
 *     <intent-filter>
 *         <action android:name="com.google.android.apps.dashclock.Extension" />
 *     </intent-filter>
 *     <meta-data android:name="protocolVersion" android:value="1" />
 *     <meta-data android:name="description"
 *         android:value="@string/extension_description" />
 *     <!-- A settings activity is optional -->
 *     <meta-data android:name="settingsActivity"
 *         android:value=".ExampleSettingsActivity" />
 * </service>
 *

 *
 * If a settingsActivity meta-data element is present, an activity with the given
 * component name should be defined and exported in the application's manifest as well. An example
 * is shown below:
 *
 *

 * <activity android:name=".ExampleSettingsActivity"
 *     android:label="@string/title_settings"
 *     android:exported="true" />
 *

 *
 * Finally, below is a simple example {@link DashClockExtension} subclass that shows static data in
 * DashClock:
 *
 *

 * public class ExampleExtension extends DashClockExtension {
 *     protected void onUpdateData() {
 *         publishUpdate(new ExtensionData()
 *                 .visible(true)
 *                 .icon(R.drawable.ic_extension_example)
 *                 .status("Hello")
 *                 .expandedTitle("Hello, world!")
 *                 .expandedBody("This is an example.")
 *                 .clickIntent(new Intent(Intent.ACTION_VIEW,
 *                         Uri.parse("http://www.google.com"))));
 *     }
 * }
 *

 */
public abstract class DashClockExtension extends Service {
    private static final String TAG = "DashClockExtension";

    /**
     * Indicates that {@link #onUpdateData(int)} was triggered for an unknown reason. This should
     * be treated as a generic update (similar to {@link #UPDATE_REASON_PERIODIC}.
     */
    public static final int UPDATE_REASON_UNKNOWN = 0;

    /**
     * Indicates that this is the first call to {@link #onUpdateData(int)} since the connection to
     * the main DashClock app was established. Note that updates aren't requested in response to
     * reconnections after a connection is lost.
     */
    public static final int UPDATE_REASON_INITIAL = 1;

    /**
     * Indicates that {@link #onUpdateData(int)} was triggered due to a normal perioidic refresh
     * of extension data.
     */
    public static final int UPDATE_REASON_PERIODIC = 2;

    /**
     * Indicates that {@link #onUpdateData(int)} was triggered because settings for this extension
     * may have changed.
     */
    public static final int UPDATE_REASON_SETTINGS_CHANGED = 3;

    /**
     * Indicates that {@link #onUpdateData(int)} was triggered because content changed on a content
     * URI previously registered with {@link #addWatchContentUris(String[])}.
     */
    public static final int UPDATE_REASON_CONTENT_CHANGED = 4;

    /**
     * Indicates that {@link #onUpdateData(int)} was triggered because the device screen turned on
     * and the extension has called
     * {@link #setUpdateWhenScreenOn(boolean) setUpdateWhenScreenOn(true)}.
     */
    public static final int UPDATE_REASON_SCREEN_ON = 5;

    /**
     * The {@link Intent} action representing a DashClock extension. This service should
     * declare an <intent-filter> for this action in order to register with
     * DashClock.
     */
    public static final String ACTION_EXTENSION = "com.google.android.apps.dashclock.Extension";

    /**
     * The permission that DashClock extensions should require callers to have before providing
     * any status updates. Permission checks are implemented automatically by the base class.
     */
    public static final String PERMISSION_READ_EXTENSION_DATA
            = "com.google.android.apps.dashclock.permission.READ_EXTENSION_DATA";

    private boolean mInitialized = false;
    private IExtensionHost mHost;

    private volatile Looper mServiceLooper;
    private volatile Handler mServiceHandler;

    protected DashClockExtension() {
        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        HandlerThread thread = new HandlerThread(
                "DashClockExtension:" + getClass().getSimpleName());
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new Handler(mServiceLooper);
    }

    @Override
    public void onDestroy() {
        mServiceHandler.removeCallbacksAndMessages(null); // remove all callbacks
        mServiceLooper.quit();
    }

    @Override
    public final IBinder onBind(Intent intent) {
        return mBinder;
    }

    private IExtension.Stub mBinder = new IExtension.Stub() {
        @Override
        public void onInitialize(IExtensionHost host, boolean isReconnect)
                throws RemoteException {
            if (checkCallingOrSelfPermission(PERMISSION_READ_EXTENSION_DATA)
                    != PackageManager.PERMISSION_GRANTED) {
                throw new SecurityException("Caller does not have the READ_EXTENSION_DATA "
                        + "permission.");
            }

            mHost = host;

            if (!mInitialized) {
                DashClockExtension.this.onInitialize(isReconnect);
                mInitialized = true;
            }
        }

        @Override
        public void onUpdate(final int reason) throws RemoteException {
            if (checkCallingOrSelfPermission(PERMISSION_READ_EXTENSION_DATA)
                    != PackageManager.PERMISSION_GRANTED) {
                throw new SecurityException("Caller does not have the READ_EXTENSION_DATA "
                        + "permission.");
            }

            if (!mInitialized) {
                return;
            }

            // Do this in a separate thread
            mServiceHandler.post(new Runnable() {
                @Override
                public void run() {
                    DashClockExtension.this.onUpdateData(reason);
                }
            });
        }
    };

    /**
     * Called when a connection with the main DashClock app has been established or re-established
     * after a previous one was lost. In this latter case, the parameter isReconnect
     * will be true. Override this method to perform basic extension initialization before calls
     * to {@link #onUpdateData(int)} are made.
     *
     * @param isReconnect Whether or not this call is being made after a connection was dropped and
     *                    a new connection has been established.
     */
    protected void onInitialize(boolean isReconnect) {
    }

    /**
     * Called when the DashClock app process is requesting that the extension provide updated
     * information to show to the user. Implementations can choose to do nothing, or more commonly,
     * provide an update using the {@link #publishUpdate(ExtensionData)} method. Note that doing
     * nothing doesn't clear existing data. To clear any existing data, call
     * {@link #publishUpdate(ExtensionData)} with null data.
     *
     * @param reason The reason for the update. See {@link #UPDATE_REASON_PERIODIC} and related
     *               constants for more details.
     */
    protected abstract void onUpdateData(int reason);

    /**
     * Notifies the main DashClock app that new data is available for the extension and should
     * potentially be shown to the user. Note that this call does not necessarily need to be made
     * from inside the {@link #onUpdateData(int)} method, but can be made only after
     * {@link #onInitialize(boolean)} has been called. If you only call this from within
     * {@link #onUpdateData(int)} this is already ensured.
     *
     * @param data The data to show, or null if existing data should be cleared (hiding
     *             the extension from view).
     */
    protected final void publishUpdate(ExtensionData data) {
        try {
            mHost.publishUpdate(data);
        } catch (RemoteException e) {
            Log.e(TAG, "Couldn't publish updated extension data.", e);
        }
    }

    /**
     * Requests that the main DashClock app watch the given content URIs (using
     * {@link android.content.ContentResolver#registerContentObserver(android.net.Uri, boolean,
     * android.database.ContentObserver) ContentResolver.registerContentObserver})
     * and call this extension's {@link #onUpdateData(int)} method when changes are observed.
     * This should generally be called in the {@link #onInitialize(boolean)} method.
     *
     * @param uris The URIs to watch.
     */
    protected final void addWatchContentUris(String[] uris) {
        try {
            mHost.addWatchContentUris(uris);
        } catch (RemoteException e) {
            Log.e(TAG, "Couldn't watch content URIs.", e);
        }
    }

    /**
     * Requests that the main DashClock app call (or not call) this extension's
     * {@link #onUpdateData(int)} method when the screen turns on (the phone resumes from idle).
     * This should generally be called in the {@link #onInitialize(boolean)} method.
     *
     * @see Intent#ACTION_SCREEN_ON
     * @param updateWhenScreenOn Whether or not a call to {@link #onUpdateData(int)} method when
     *                           the screen turns on.
     */
    protected final void setUpdateWhenScreenOn(boolean updateWhenScreenOn) {
        try {
            mHost.setUpdateWhenScreenOn(updateWhenScreenOn);
        } catch (RemoteException e) {
            Log.e(TAG, "Couldn't set the extension to update upon ACTION_SCREEN_ON.", e);
        }
    }
}


text:
{# ------------------------------------------------------- #}
{# INDIVIDUAL VIEW FOR EACH membership #}
{# This page can use any data from http:localhost:2000/cms/#/form/membership/ #}
{# Webhook uses the SWIG.js (like Djagno/Twig) templating system. Their documentation is here: #}
{# http://paularmstrong.github.io/swig/docs/tags/ #}
{# Learn about calling data into Webhook pages here: #}
{# http://www.webhook.com/docs/template-rules-and-filters/ #}
{# ------------------------------------------------------- #}
{# Confused what extends and blocks do? Watch a primer: #}
{# http://www.webhook.com/docs/template-inheritance-blocks/ #}
{% extends "templates/partials/base.html" %}
{# This sets our page <title>. It will append this membership's name to the site title defined in base.html #}
{% block title %}{% parent %} - {{ item.name }}{% endblock %}
{% block content %}

View a list of all membership

{{ item.name }}

        Name:
        {{ item.name }}

        Create Date:
        {# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #}
        {{ item.create_date|date('F d Y') }}

        Last Updated:
        {# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #}
        {{ item.last_updated|date('F d Y') }}

        Publish Date:
        {# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #}
        {{ item.publish_date|date('F d Y') }}

        CMS Description:
        {{ item.cms_description }}

        Preview URL:
        {{ item.preview_url }}

        Slug:
        {{ item.slug }}

{% endblock %}


text:
/**
 * Get info text associated with a field
 * @param showErrors Flag to show errors or not
 * @param errors Object with error properties
 * @param error Error index
 * @param showInfo Flag to show info or not
 * @param info Field info
 * @returns Info text
 */
export function getInfo (
  showErrors: boolean,
  errors: Record<string, string>,
  error: string,
  showInfo: boolean,
  info?: string
): string | undefined {
  if (showErrors && error) {
    if (error === 'required') {
      return 'Required';
    } else {
      return (errors && errors[error]) ? errors[error] : 'Invalid content';
    }
  }
  return showInfo ? info : undefined;
}


text:
<?php
namespace Acf\DataBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Acf\DataBundle\Entity\User;
use Acf\DataBundle\Entity\Company;
use Acf\DataBundle\Entity\Trace;
use Acf\DataBundle\Entity\Job;
use Acf\DataBundle\Entity\CompanyType;
use Acf\DataBundle\Entity\Sector;

/**
 * TraceRepository
 * This class was generated by the Doctrine ORM.
 * Add your own custom
 * repository methods below.
 */
class TraceRepository extends EntityRepository
{

    /**
     * Get Query for All Entities
     *
     * @param \DateTime $minDtCrea
     *
     * @return \Doctrine\ORM\Query
     */
    public function getAllQuery(\DateTime $minDtCrea = null)
    {
        if (null == $minDtCrea) {
            return $this->createQueryBuilder('t')->orderBy('t.dtCrea', 'ASC')->addOrderBy('t.actionType', 'ASC')->addOrderBy('t.actionEntity', 'ASC')->getQuery();
        } else {
            return $this->createQueryBuilder('t')->where('t.dtCrea >= :minDate')->orderBy('t.dtCrea', 'ASC')->addOrderBy('t.actionType', 'ASC')->addOrderBy('t.actionEntity', 'ASC')->setParameter('minDate', $minDtCrea)->getQuery();
        }
    }

    /**
     * Get All Entities
     *
     * @param \DateTime $minDtCrea
     *
     * @return mixed|\Doctrine\DBAL\Driver\Statement|array|NULL
     */
    public function getAll(\DateTime $minDtCrea = null)
    {
        return $this->getAllQuery($minDtCrea)->execute();
    }

    /**
     * Get Query for All Entities
     *
     * @param User $user
     *
     * @param \DateTime $minDtCrea
     *
     * @return \Doctrine\ORM\Query
     */
    public function getAllByAdminQuery(User $user, \DateTime $minDtCrea = null)
    {
        $companies = $user->getAdmCompanies();
        if (null == $companies || \count($companies) == 0) {
            if (null == $minDtCrea) {
                return $this->createQueryBuilder('t')->where('t.companyId IN (:companyIds)')->andWhere('t.actionEntity NOT IN (:entities)')->orderBy('t.dtCrea', 'ASC')->addOrderBy('t.actionType', 'ASC')->addOrderBy('t.actionEntity', 'ASC')->setParameter('companyIds', null)->setParameter('entities', array(
                    Trace::AE_DOCGROUPSYST,
                    Trace::AE_DOCGROUPAUDIT,
                    Trace::AE_SHAREHOLDER,
                    Trace::AE_PILOT,
                    Trace::AE_CUSER,
                    Trace::AE_CADMIN
                ))->getQuery();
            } else {
                return $this->createQueryBuilder('t')->where('t.companyId IN (:companyIds)')->andWhere('t.actionEntity NOT IN (:entities)')->andWhere('t.dtCrea >= :minDate')->orderBy('t.dtCrea', 'ASC')->addOrderBy('t.actionType', 'ASC')->addOrderBy('t.actionEntity', 'ASC')->setParameter('companyIds', null)->setParameter('entities', array(
                    Trace::AE_DOCGROUPSYST,
                    Trace::AE_DOCGROUPAUDIT,
                    Trace::AE_SHAREHOLDER,
                    Trace::AE_PILOT,
                    Trace::AE_CUSER,
                    Trace::AE_CADMIN
                ))->setParameter('minDate', $minDtCrea)->getQuery();
            }
        } else {
            $cIds = array();
            foreach ($companies as $company) {
                $cIds[] = $company->getId();
            }
            if (null == $minDtCrea) {
                return $this->createQueryBuilder('t')->where('t.companyId IN (:companyIds)')->andWhere('t.actionEntity NOT IN (:entities)')->orderBy('t.dtCrea', 'ASC')->addOrderBy('t.actionType', 'ASC')->addOrderBy('t.actionEntity', 'ASC')->setParameter('companyIds', $cIds)->setParameter('entities', array(
                    Trace::AE_DOCGROUPSYST,
                    Trace::AE_DOCGROUPAUDIT,
                    Trace::AE_SHAREHOLDER,
                    Trace::AE_PILOT,
                    Trace::AE_CUSER,
                    Trace::AE_CADMIN
                ))->getQuery();
            } else {
                return $this->createQueryBuilder('t')->where('t.companyId IN (:companyIds)')->andWhere('t.actionEntity NOT IN (:entities)')->andWhere('t.dtCrea >= :minDate')->orderBy('t.dtCrea', 'ASC')->addOrderBy('t.actionType', 'ASC')->addOrderBy('t.actionEntity', 'ASC')->setParameter('companyIds', $cIds)->setParameter('entities', array(
                    Trace::AE_DOCGROUPSYST,
                    Trace::AE_DOCGROUPAUDIT,
                    Trace::AE_SHAREHOLDER,
                    Trace::AE_PILOT,
                    Trace::AE_CUSER,
                    Trace::AE_CADMIN
                ))->setParameter('minDate', $minDtCrea)->getQuery();
            }
        }
    }

    /**
     * Get All Entities
     *
     * @param User $user
     *
     * @param \DateTime $minDtCrea
     *
     * @return mixed|\Doctrine\DBAL\Driver\Statement|array|NULL
     */
    public function getAllByAdmin(User $user, \DateTime $minDtCrea = null)
    {
        return $this->getAllByAdminQuery($user, $minDtCrea)->execute();
    }

    /**
     * Get Query for All Entities
     *
     * @param User $entity
     *
     * @return \Doctrine\ORM\Query
     */
    public function getAllByUserQuery(User $entity)
    {
        return $this->createQueryBuilder('t')->where('t.actionEntity = :entityType')->andWhere('t.actionId = :aId')->orderBy('t.dtCrea', 'ASC')->addOrderBy('t.actionType', 'ASC')->addOrderBy('t.actionEntity', 'ASC')->setParameter('entityType', Trace::AE_USER)->setParameter('aId', $entity->getId())->getQuery();
    }

    /**
     * Get All Entities
     *
     * @param User $entity
     *
     * @return mixed|\Doctrine\DBAL\Driver\Statement|array|NULL
     */
    public function getAllByUser(User $entity)
    {
        return $this->getAllByUserQuery($entity)->execute();
    }

    /**
     * Get Query for All Entities
     *
     * @param Job $entity
     *
     * @return \Doctrine\ORM\Query
     */
    public function getAllByJobQuery(Job $entity)
    {
        return $this->createQueryBuilder('t')->where('t.actionEntity = :entityType')->andWhere('t.actionId = :aId')->orderBy('t.dtCrea', 'ASC')->addOrderBy('t.actionType', 'ASC')->addOrderBy('t.actionEntity', 'ASC')->setParameter('entityType', Trace::AE_JOB)->setParameter('aId', $entity->getId())->getQuery();
    }

    /**
     * Get All Entities
     *
     * @param Job $entity
     *
     * @return mixed|\Doctrine\DBAL\Driver\Statement|array|NULL
     */
    public function getAllByJob(Job $entity)
    {
        return $this->getAllByJobQuery($entity)->execute();
    }

    /**
     * Get Query for All Entities
     *
     * @param CompanyType $entity
     *
     * @return \Doctrine\ORM\Query
     */
    public function getAllByCompanyTypeQuery(CompanyType $entity)
    {
        return $this->createQueryBuilder('t')->where('t.actionEntity = :entityType')->andWhere('t.actionId = :aId')->orderBy('t.dtCrea', 'ASC')->addOrderBy('t.actionType', 'ASC')->addOrderBy('t.actionEntity', 'ASC')->setParameter('entityType', Trace::AE_TYPE)->setParameter('aId', $entity->getId())->getQuery();
    }

    /**
     * Get All Entities
     *
     * @param CompanyType $entity
     *
     * @return mixed|\Doctrine\DBAL\Driver\Statement|array|NULL
     */
    public function getAllByCompanyType(CompanyType $entity)
    {
        return $this->getAllByCompanyTypeQuery($entity)->execute();
    }

    /**
     * Get Query for All Entities
     *
     * @param Sector $entity
     *
     * @return \Doctrine\ORM\Query
     */
    public function getAllBySectorQuery(Sector $entity)
    {
        return $this->createQueryBuilder('t')->where('t.actionEntity = :entityType')->andWhere('t.actionId = :aId')->orderBy('t.dtCrea', 'ASC')->addOrderBy('t.actionType', 'ASC')->addOrderBy('t.actionEntity', 'ASC')->setParameter('entityType', Trace::AE_SECTOR)->setParameter('aId', $entity->getId())->getQuery();
    }

    /**
     * Get All Entities
     *
     * @param Sector $entity
     *
     * @return mixed|\Doctrine\DBAL\Driver\Statement|array|NULL
     */
    public function getAllBySector(Sector $entity)
    {
        return $this->getAllBySectorQuery($entity)->execute();
    }

    /**
     * Get Query for All Entities
     *
     * @param Company $company
     * @param boolean $showall
     *
     * @return \Doctrine\ORM\Query
     */
    public function getAllByCompanyQuery(Company $company, $showall = true)
    {
        $qb = $this->createQueryBuilder('t')->where('t.companyId = :companyId')->orderBy('t.dtCrea', 'ASC')->addOrderBy('t.actionType', 'ASC')->addOrderBy('t.actionEntity', 'ASC')->setParameter('companyId', $company->getId());
        if ($showall == false) {
            $qb->andWhere('t.actionEntity NOT IN (:entities)');
            $qb->setParameter('entities', array(
                Trace::AE_DOCGROUPSYST,
                Trace::AE_DOCGROUPAUDIT,
                Trace::AE_SHAREHOLDER,
                Trace::AE_PILOT,
                Trace::AE_CUSER,
                Trace::AE_CADMIN
            ));
        }

        return $qb->getQuery();
    }

    /**
     * Get All Entities
     *
     * @param Company $company
     * @param boolean $showall
     *
     * @return mixed|\Doctrine\DBAL\Driver\Statement|array|NULL
     */
    public function getAllByCompany(Company $company, $showall = true)
    {
        return $this->getAllByCompanyQuery($company, $showall)->execute();
    }

    /**
     * Get Query for All Entities
     *
     * @param string $entityId
     *
     * @param string $entityType
     *
     * @return \Doctrine\ORM\Query
     */
    public function getAllByEntityIdQuery($entityId, $entityType)
    {
        return $this->createQueryBuilder('t')->where('t.actionEntity = :entityType OR t.actionEntity2 = :entityType OR t.actionEntity3 = :entityType OR t.actionEntity4 = :entityType')->andWhere('t.actionId = :aId OR t.actionId2 = :aId OR t.actionId3 = :aId OR t.actionId4 = :aId')->orderBy('t.dtCrea', 'ASC')->addOrderBy('t.actionType', 'ASC')->addOrderBy('t.actionEntity', 'ASC')->setParameter('entityType', $entityType)->setParameter('aId', $entityId)->getQuery();
    }

    /**
     * Get All Entities
     *
     * @param string $entityId
     *
     * @param string $entityType
     *
     * @return mixed|\Doctrine\DBAL\Driver\Statement|array|NULL
     */
    public function getAllByEntityId($entityId, $entityType)
    {
        return $this->getAllByEntityIdQuery($entityId, $entityType)->execute();
    }
}


text:
const url = require('url');
const _ = require('lodash');
const testUtils = require('../../utils');
const schema = require('../../../server/data/schema').tables;
const API_URL = '/ghost/api/canary/admin/';

const expectedProperties = {
    // API top level
    posts: ['posts', 'meta'],
    pages: ['pages', 'meta'],
    tags: ['tags', 'meta'],
    users: ['users', 'meta'],
    settings: ['settings', 'meta'],
    subscribers: ['subscribers', 'meta'],
    roles: ['roles'],
    pagination: ['page', 'limit', 'pages', 'total', 'next', 'prev'],
    slugs: ['slugs'],
    slug: ['slug'],
    invites: ['invites', 'meta'],
    themes: ['themes'],
    actions: ['actions', 'meta'],

    action: ['id', 'resource_type', 'actor_type', 'event', 'created_at', 'actor'],

    config: ['version', 'environment', 'database', 'mail', 'labs', 'clientExtensions', 'enableDeveloperExperiments', 'useGravatar'],

    post: _(schema.posts)
        .keys()
        // by default we only return mobildoc
        .without('html', 'plaintext')
        .without('locale')
        .without('page')
        // v2 API doesn't return new type field
        .without('type')
        // deprecated
        .without('author_id', 'author')
        // always returns computed properties
        .concat('url', 'primary_tag', 'primary_author', 'excerpt')
        // returned by default
        .concat('tags', 'authors', 'email')
        // returns meta fields from `posts_meta` schema
        .concat(
            ..._(schema.posts_meta).keys().without('post_id', 'id')
        )
    ,

    page: _(schema.posts)
        .keys()
        // by default we only return mobildoc
        .without('html', 'plaintext')
        .without('locale')
        .without('page')
        // v2 API doesn't return new type field
        .without('type')
        // deprecated
        .without('author_id', 'author')
        // pages are not sent as emails
        .without('send_email_when_published')
        // always returns computed properties
        .concat('url', 'primary_tag', 'primary_author', 'excerpt')
        // returned by default
        .concat('tags', 'authors')
        // returns meta fields from `posts_meta` schema
        .concat(
            ..._(schema.posts_meta).keys()
                .without('post_id', 'id')
                // pages are not sent as emails
                .without('email_subject')
        )
    ,

    user: _(schema.users)
        .keys()
        .without('visibility')
        .without('password')
        .without('locale')
        .concat('url')
    ,
    tag: _(schema.tags)
        .keys()
        // unused field
        .without('parent_id')
    ,
    setting: _(schema.settings)
        .keys()
    ,
    subscriber: _(schema.subscribers)
        .keys()
    ,
    role: _(schema.roles)
        .keys()
    ,
    permission: _(schema.permissions)
        .keys()
    ,
    notification: ['type', 'message', 'status', 'id', 'dismissible', 'location', 'custom'],
    theme: ['name', 'package', 'active'],
    invite: _(schema.invites)
        .keys()
        .without('token')
    ,
    webhook: _(schema.webhooks)
        .keys()
    ,
    email: _(schema.emails)
        .keys(),
    email_preview: ['html', 'subject', 'plaintext']
};

_.each(expectedProperties, (value, key) => {
    if (!value.__wrapped__) {
        return;
    }

    /**
     * @deprecated: x_by
     */
    expectedProperties[key] = value
        .without(
            'created_by',
            'updated_by',
            'published_by'
        )
        .value();
});

module.exports = {
    API: {
        getApiQuery(route) {
            return url.resolve(API_URL, route);
        },

        checkResponse(...args) {
            this.expectedProperties = expectedProperties;
            return testUtils.API.checkResponse.call(this, ...args);
        }
    },

    doAuth(...args) {
        return testUtils.API.doAuth(`${API_URL}session/`, ...args);
    },

    getValidAdminToken(audience) {
        const jwt = require('jsonwebtoken');
        const JWT_OPTIONS = {
            keyid: testUtils.DataGenerator.Content.api_keys[0].id,
            algorithm: 'HS256',
            expiresIn: '5m',
            audience: audience
        };

        return jwt.sign(
            {},
            Buffer.from(testUtils.DataGenerator.Content.api_keys[0].secret, 'hex'),
            JWT_OPTIONS
        );
    }
};


text:
"""
Slices a random subset of a GCToo instance of a user-specified size.
"""
import logging
import numpy
import cmapPy.pandasGEXpress.GCToo as GCToo
import cmapPy.pandasGEXpress.setup_GCToo_logger as setup_logger

__author__ = "Oana Enache"
__email__ = "oana@broadinstitute.org"

logger = logging.getLogger(setup_logger.LOGGER_NAME)

def make_specified_size_gctoo(og_gctoo, num_entries, dim):
    """
	Subsets a GCToo instance along either rows or columns to obtain a specified size.

	Input:
		- og_gctoo (GCToo): a GCToo instance
		- num_entries (int): the number of entries to keep
		- dim (str): the dimension along which to subset. Must be "row" or "col"

	Output:
		- new_gctoo (GCToo): the GCToo instance subsetted as specified.
	"""
    assert dim in ["row", "col"], "dim specified must be either 'row' or 'col'"

    dim_index = 0 if "row" == dim else 1
    assert num_entries <= og_gctoo.data_df.shape[dim_index], ("number of entries must be smaller than dimension being "
            "subsetted - num_entries:  {}  dim:  {}  dim_index:  {}  og_gctoo.data_df.shape[dim_index]:  {}".format(
        num_entries, dim, dim_index, og_gctoo.data_df.shape[dim_index]))

    if dim == "col":
        columns = [x for x in og_gctoo.data_df.columns.values]
        numpy.random.shuffle(columns)
        columns = columns[0:num_entries]
        rows = og_gctoo.data_df.index.values
    else:
        rows = [x for x in og_gctoo.data_df.index.values]
        numpy.random.shuffle(rows)
        rows = rows[0:num_entries]
        columns = og_gctoo.data_df.columns.values

    new_data_df = og_gctoo.data_df.loc[rows, columns]
    new_row_meta = og_gctoo.row_metadata_df.loc[rows]
    new_col_meta = og_gctoo.col_metadata_df.loc[columns]

    logger.debug(
        "after slice - new_col_meta.shape: {}  new_row_meta.shape:  {}".format(new_col_meta.shape, new_row_meta.shape))

    # make & return new gctoo instance
    new_gctoo = GCToo.GCToo(data_df=new_data_df, row_metadata_df=new_row_meta, col_metadata_df=new_col_meta)

    return new_gctoo


text:
<?php

// Language definitions for frequently used strings
$lang_common = array(

// Text orientation and encoding
'lang_direction'					=>	'ltr', // ltr (Left-To-Right) or rtl (Right-To-Left)
'lang_identifier'					=>	'es',

// Number formatting
'lang_decimal_point'				=>	',',
'lang_thousands_sep'				=>	'.',

// Notices
'Bad request'						=>	'Solicitud incorrecta. El enlace que ha seguido es incorrecto o esta desactualizado.',
'No view'							=>	'Usted no tiene permiso para ver estos foros.',
'No permission'						=>	'Usted no tiene permiso para acceder a esta página.',
'Bad referrer'						=>	'HTTP_REFERER inadecuado. Usted se refirió a esta página desde una fuente no autorizada. Si el problema persiste por favor asegúrese de que \'Base URL\' está bien configurada en Admin / Opciones y que está visitando el foro navegando a esa URL. Más información sobre el cheque referentes pueden ser encontrados en la documentación FluxBB.',
'No cookie'							=>	'Usted parece haber entrado con éxito, sin embargo una cookie no se ha establecido. Por favor, compruebe su configuración y en su caso, habilite las cookies para este sitio web.',
'Pun include error'					=>	'No se puede procesar lo que el usuario ha incluido %s desde plantilla %s. No hay tal archivo ni en el directorio de plantillas de usuario ni en el directorio de inclusión.',

// Miscellaneous
'Announcement'						=>	'Anuncio',
'Options'							=>	'Opciones',
'Submit'							=>	'Enviar', // "Name" of submit buttons
'Ban message'						=>	'Estas expulsado de este foro.',
'Ban message 2'						=>	'La expulsión expira a finales de',
'Ban message 3'						=>	'El administrador o moderador que le expulsó le dejó el mensaje siguiente:',
'Ban message 4'						=>	'Por favor, dirija cualquier pregunta al administrador del foro en',
'Never'								=>	'Nunca',
'Today'								=>	'Hoy',
'Yesterday'							=>	'Ayer',
'Info'								=>	'Info', // A common table header
'Go back'							=>	'Volver',
'Maintenance'						=>	'Mantenimiento',
'Redirecting'						=>	'Redireccionando',
'Click redirect'					=>	'Haga clic aquí si no quieres esperar más tiempo (o si su navegador no continua automaticamente)',
'on'								=>	'on', // As in "BBCode is on"
'off'								=>	'off',
'Invalid email'						=>	'La dirección de correo electronico introducida no es valida.',
'Required'							=>	'(Requerido)',
'required field'					=>	'es un campo requerido en este formulario.', // For javascript form validation
'Last post'							=>	'Ultimo mensaje',
'by'								=>	'por', // As in last post by someuser
'New posts'							=>	'Nuevos mensajes', // The link that leads to the first new post
'New posts info'					=>	'Ir al primer nuevo mensaje en este tema.', // The popup text for new posts links
'Username'							=>	'Usuario',
'Password'							=>	'Contraseña',
'Email'								=>	'Correo electronico',
'Send email'						=>	'Enviar correo',
'Moderated by'						=>	'Moderado por',
'Registered'						=>	'Registrado',
'Subject'							=>	'Asunto',
'Message'							=>	'Mensaje',
'Topic'								=>	'Tema',
'Forum'								=>	'Foro',
'Posts'								=>	'Mensajes',
'Replies'							=>	'Respuestas',
'Pages'								=>	'Paginas:',
'Page'								=>	'Pagina %s',
'BBCode'							=>	'BBCode:', // You probably shouldn't change this
'img tag'							=>	'[img] etiqueta:',
'Smilies'							=>	'Emoticonos:',
'and'								=>	'y',
'Image link'						=>	'imagen', // This is displayed (i.e. <image>) instead of images when "Show images" is disabled in the profile
'wrote'								=>	'escribió:', // For [quote]'s
'Mailer'							=>	'Mailer', // As in "MyForums Mailer" in the signature of outgoing emails
'Important information'				=>	'Información importante',
'Write message legend'				=>	'Escribe tu mensaje y envia',
'Previous'							=>	'Anterior',
'Next'								=>	'Siguiente',
'Spacer'							=>	'…', // Ellipsis for paginate

// Title
'Title'								=>	'Título',
'Member'							=>	'Miembro', // Default title
'Moderator'							=>	'Moderador',
'Administrator'						=>	'Administrador',
'Banned'							=>	'Expulsado',
'Guest'								=>	'Invitado',

// Stuff for include/parser.php
'BBCode error no opening tag'		=>	'[/%1$s] se encontro sin un juego [%1$s]',
'BBCode error invalid nesting'		=>	'[%1$s] se abrio sin [%2$s], esto no esta permitido',
'BBCode error invalid self-nesting'	=>	'[%s] se abrio en su interior, esto no esta permitido',
'BBCode error no closing tag'		=>	'[%1$s] se encontró sin un juego [/%1$s]',
'BBCode error empty attribute'		=>	'[%s] la etiqueta tiene una sección vacia atribuida',
'BBCode code problem'				=>	'Esto es un problema con tus [code] etiquetas',
'BBCode list size error'			=>	'La lista es demasiado larga para analizar, por favor, hagaló más pequeño!',

// Stuff for the navigator (top of every page)
'Index'								=>	'Inicio',
'User list'							=>	'Usuarios',
'Rules'								=>	'Reglas',
'Search'							=>	'Buscar',
'Register'							=>	'Registrarse',
'Login'								=>	'Entrar',
'Not logged in'						=>	'No estas registrado.',
'Profile'							=>	'Perfil',
'Logout'							=>	'Salir',
'Logged in as'						=>	'Conectado como',
'Admin'								=>	'Administración',
'Last visit'						=>	'Ultima visita: %s',
'Topic searches'					=>	'Temas:',
'New posts header'					=>	'Nuevos',
'Active topics'						=>	'Activos',
'Unanswered topics'					=>	'Sin respuesta',
'Posted topics'						=>	'Enviados',
'Show new posts'					=>	'Mostrar mensajes nuevos desde la última visita',
'Show active topics'				=>	'Find topics with recent posts.',
'Show unanswered topics'			=>	'Find topics with no replies.',
'Show posted topics'				=>	'Find topics you have posted to.',
'Mark all as read'					=>	'Marcar todos los temas como leidos',
'Mark forum read'					=>	'Marcar este foro como leido',
'Title separator'					=>	' / ',

// Stuff for the page footer
'Board footer'						=>	'Pie de página',
'Search links'						=>	'Buscar enlaces',
'Show recent posts'					=>	'Mostrar temas recientes',
'Show unanswered posts'				=>	'Mostrar temas sin respuesta',
'Show your posts'					=>	'Mostrar tus temas',
'Show subscriptions'				=>	'Mostrar tus temas suscritos',
'Jump to'							=>	'Saltar a',
'Go'								=>	' Ir ', // Submit button in forum jump
'Moderate topic'					=>	'Moderar tema',
'Move topic'						=>	'Mover tema',
'Open topic'						=>	'Abrir tema',
'Close topic'						=>	'Cerrar tema',
'Unstick topic'						=>	'Despegar tema',
'Stick topic'						=>	'Pegar tema',
'Moderate forum'					=>	'Moderar foro',
'Powered by'						=>	'Powered by %s',

// Debug information
'Debug table'						=>	'Depurar la información',
'Querytime'							=>	'Generado en %1$s segundos, %2$s consultas ejecutadas',
'Memory usage'						=>	'Memoria usada: %1$s',
'Peak usage'						=>	'(Pico: %1$s)',
'Query times'						=>	'Tiempo (s)',
'Query'								=>	'Consulta',
'Total query time'					=>	'Tiempo total de consulta: %s',

// Email related notifications
'New user notification'				=>	'Alerta - Nuevo registrado',
'New user message'					=>	'User \'%s\' registrado en el foro en %s',
'Banned email notification'			=>	'Alerta - Correo de expulsado detectado',
'Banned email register message'		=>	'Usuario \'%s\' registrado con correo de expulsado: %s',
'Banned email change message'		=>	'Usuario \'%s\' cambio a correo de expulsado: %s',
'Banned email post message'			=>	'Usuario \'%s\' publicó con correo de expulsado: %s',
'Duplicate email notification'		=>	'Alerta - Detectado correo duplicado',
'Duplicate email register message'	=>	'Usuario \'%s\' registrado con una dirección de correo electrónico que también pertenece a: %s',
'Duplicate email change message'	=>	'Usuario \'%s\' cambiado a una dirección de correo electrónico que también pertenece a: %s',
'Report notification'				=>	'Report(%d) - \'%s\'',
'Report message 1'					=>	'Usuario \'%s\' ha reportado el siguiente mensaje: %s',
'Report message 2'					=>	'Razón: %s',

'User profile'						=>	'Perfil de usuario: %s',
'Post URL'							=>	'Mensaje URL: %s',
'Email signature'					=>	'Foro Remitente'."\n".'(No responda a este mensaje)',

// For extern.php RSS feed
'RSS description'					=>	'Los temas mas recientes en %s.',
'RSS description topic'				=>	'Los mensajes mas recientes en %s.',
'RSS reply'							=>	'Re: ', // The topic subject will be appended to this string (to signify a reply)
'RSS active topics feed'			=>	'RSS temas activos feed',
'Atom active topics feed'			=>	'Atom temas activos feed',
'RSS forum feed'					=>	'RSS foro feed',
'Atom forum feed'					=>	'Atom foro feed',
'RSS topic feed'					=>	'RSS tema feed',
'Atom topic feed'					=>	'Atom tema feed',

// Admin related stuff in the header
'New reports'						=>	'Tienes nuevos reportes',
'Maintenance mode enabled'			=>	'Modo mantenimiento esta activado!',

);


text:
/**
 * Collection of actions for AWS access control policies.  Actions describe how
 * AWS resources are being accessed or modified when an AWS access control policy
 * is evaluated for an incoming request.
 */
package com.amazonaws.auth.policy.actions;


text:
require "serverspec"

# Required by serverspec
set :backend, :exec

describe package("filebeat") do
  it { should be_installed }
end

describe service("filebeat") do
  it { should be_enabled }
  it { should be_running }
end


text:
import Immutable from 'immutable';
import actionTypes from '../actions/actionTypes';

export const link = (state = Immutable.Map(), { type, payload }) => {
  switch (type) {
    default:
      return state;
  }
};


text:
/**
 * On-Deploy Scripts Framework.
 */
@org.osgi.annotation.versioning.Version("1.1.0")
package com.adobe.acs.commons.ondeploy;