text:
package org.araneaframework.http.util;

import java.lang.reflect.Field;
import org.araneaframework.Environment;
import org.araneaframework.core.Assert;
import org.araneaframework.core.annotation.EnvironmentEntry;
import org.araneaframework.core.util.ExceptionUtil;
import org.araneaframework.framework.ConfirmationContext;
import org.araneaframework.framework.ContinuationContext;
import org.araneaframework.framework.ExpiringServiceContext;
import org.araneaframework.framework.FlowContext;
import org.araneaframework.framework.LocalizationContext;
import org.araneaframework.framework.ManagedServiceContext;
import org.araneaframework.framework.MessageContext;
import org.araneaframework.framework.SystemFormContext;
import org.araneaframework.framework.ThreadContext;
import org.araneaframework.framework.TopServiceContext;
import org.araneaframework.http.PopupWindowContext;
import org.araneaframework.http.StateVersioningContext;
import org.araneaframework.http.UpdateRegionContext;

/**
 * Utility class that provides shortcuts for accessing some {@link Environment}
 * entries.
 *
 * @author Alar Kvell (alar@araneaframework.org)
 * @since 1.1
 */
public abstract class EnvironmentUtil {

  public static TopServiceContext getTopServiceContext(Environment env) {
    return env.getEntry(TopServiceContext.class);
  }

  public static TopServiceContext requireTopServiceContext(Environment env) {
    return env.requireEntry(TopServiceContext.class);
  }

  public static String getTopServiceId(Environment env) {
    TopServiceContext topServiceContext = getTopServiceContext(env);
    return topServiceContext == null ? null : topServiceContext.getCurrentId();
  }

  public static String requireTopServiceId(Environment env) {
    return requireTopServiceContext(env).getCurrentId();
  }

  public static ThreadContext getThreadContext(Environment env) {
    return env.getEntry(ThreadContext.class);
  }

  public static ThreadContext requireThreadContext(Environment env) {
    return env.requireEntry(ThreadContext.class);
  }

  public static String getThreadServiceId(Environment env) {
    ThreadContext threadContext = getThreadContext(env);
    return threadContext == null ? null : threadContext.getCurrentId();
  }

  public static String requireThreadServiceId(Environment env) {
    return requireThreadContext(env).getCurrentId();
  }

  // THESE ARE NOT CONNECTED TO SYSTEM FORM
  public static LocalizationContext getLocalizationContext(Environment env) {
    return env.getEntry(LocalizationContext.class);
  }

  public static LocalizationContext requireLocalizationContext(Environment env) {
    return env.requireEntry(LocalizationContext.class);
  }

  public static FlowContext getFlowContext(Environment env) {
    return env.getEntry(FlowContext.class);
  }

  public static FlowContext requireFlowContext(Environment env) {
    return env.requireEntry(FlowContext.class);
  }

  public static MessageContext getMessageContext(Environment env) {
    return env.getEntry(MessageContext.class);
  }

  public static MessageContext requireMessageContext(Environment env) {
    return env.requireEntry(MessageContext.class);
  }

  public static SystemFormContext getSystemFormContext(Environment env) {
    return env.getEntry(SystemFormContext.class);
  }

  public static SystemFormContext requireSystemFormContext(Environment env) {
    return env.requireEntry(SystemFormContext.class);
  }

  public static UpdateRegionContext getUpdateRegionContext(Environment env) {
    return env.getEntry(UpdateRegionContext.class);
  }

  public static UpdateRegionContext requireUpdateRegionContext(Environment env) {
    return env.requireEntry(UpdateRegionContext.class);
  }

  public static PopupWindowContext getPopupWindowContext(Environment env) {
    return env.getEntry(PopupWindowContext.class);
  }

  public static PopupWindowContext requirePopupWindowContext(Environment env) {
    return env.requireEntry(PopupWindowContext.class);
  }

  public static StateVersioningContext getStateVersioningContext(Environment env) {
    return env.getEntry(StateVersioningContext.class);
  }

  public static StateVersioningContext requireStateVersioningContext(Environment env) {
    return env.requireEntry(StateVersioningContext.class);
  }

  public static ContinuationContext getContinuationContext(Environment env) {
    return env.getEntry(ContinuationContext.class);
  }

  // Environment item retrieve methods mostly for Aranea core:
  public static ManagedServiceContext requireManagedService(Environment env) {
    return env.requireEntry(ManagedServiceContext.class);
  }

  public static ExpiringServiceContext getExpiringServiceContext(Environment env) {
    return env.getEntry(ExpiringServiceContext.class);
  }

  public static ConfirmationContext getConfirmationContext(Environment env) {
    return env.getEntry(ConfirmationContext.class);
  }

  public static ConfirmationContext requireConfirmationContext(Environment env) {
    return env.requireEntry(ConfirmationContext.class);
  }

  /**
   * Injects appropriate environment entries to the fields of given object, if the field has annotation {@link EnvironmentEntry}.
   * The annotation can provide the environment entry key or the type of the field will be used. If the annotation
   * declares that the dependency is mandatory and the entry is not found, an exception will be thrown.
   * <p>
   * The parameters to this method must not be null!
   *
   * @param env The environment to use for entries lookup.
   * @param object The object that may contain fields with the {@link EnvironmentEntry} annotation.
   * @since 2.0
   */
  public static void injectEnvironmentEntries(Environment env, Object object) {
    Assert.notNullParam(EnvironmentUtil.class, env, "env");
    Assert.notNullParam(EnvironmentUtil.class, object, "object");

    for (Field field : object.getClass().getDeclaredFields()) {
      if (field.isAnnotationPresent(EnvironmentEntry.class)) {
        EnvironmentEntry data = field.getAnnotation(EnvironmentEntry.class);
        Class<?> type = data.value();
        if (type == null) {
          type = field.getType();
        }
        Object entry = data.required() ? env.requireEntry(type) : env.getEntry(type);
        try {
          field.setAccessible(true);
          field.set(object, entry);
        } catch (Exception e) {
          ExceptionUtil.uncheckException(e);
        }
      }
    }
  }
}


text:
module ActiveRecord
  class Base
    def self.od_update(args)
      cattr_accessor :on_duplicate_update
      self.on_duplicate_update = (args.respond_to?('each')?args:[args])
    end

    def self.od_replace(args)
      cattr_accessor :on_duplicate_replace
      self.on_duplicate_replace = (args.respond_to?('each')?args:[args])
    end

    def save
      if (self.respond_to?('on_duplicate_replace') or self.respond_to?('on_duplicate_update')) and self.new_record?
        od_create_or_update
      else
        create_or_update
      end
    end

    private

    def od_create_or_update()
      if self.id.nil? && connection.prefetch_primary_key?(self.class.table_name)
        self.id = connection.next_sequence_value(self.class.sequence_name)
      end

      quoted_attributes = attributes_with_quotes
      if quoted_attributes.empty?
        statement = connection.empty_insert_statement(self.class.table_name)
      else
        statement = "INSERT INTO #{self.class.quoted_table_name} " +
          "(#{quoted_column_names.join(', ')}) " +
          "VALUES(#{quoted_attributes.values.join(', ')})"
        ondupli = ""
        if self.respond_to?('on_duplicate_replace')
          self.on_duplicate_replace.each do |item|
            if item!='' and self.changed.include?(item.to_s)
              ondupli +=", `#{item}`=#{quoted_attributes[item.to_s]}"
            end
          end
        end
        if self.respond_to?('on_duplicate_update')
          self.on_duplicate_update.each do |item|
            if item!='' and self.changed?
              if quoted_attributes[item.to_s]!='NULL'
                ondupli +=", `#{item}`=`#{item}`+#{quoted_attributes[item.to_s]}"
              end
            end
          end
        end
        if ondupli!=''
          statement += " ON DUPLICATE KEY UPDATE #{ondupli.slice(1..-1)}"
        end
      end
      connection.insert_sql(statement, "#{self.class.name} Create")
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.Azure.CognitiveServices.Vision.Face;
using Microsoft.Azure.CognitiveServices.Vision.Face.Models;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System.Collections.Generic;
using System.IO;
using Xunit;

namespace FaceSDK.Tests
{
    public class FaceDetectionTests : BaseTests
    {
        [Fact]
        public void FaceDetectionWithAttributes()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "FaceDetectionWithAttributes");

                IFaceAPI client = GetFaceClient(HttpMockServer.CreateInstance());
                using (FileStream stream = new FileStream(Path.Combine("TestImages", "detection2.jpg"), FileMode.Open))
                {
                    IList<DetectedFace> faceList = client.Face.DetectInStreamAsync(
                        stream,
                        true,
                        true,
                        new List<FaceAttributeTypes>()
                            {
                            FaceAttributeTypes.Accessories,
                            FaceAttributeTypes.Age,
                            FaceAttributeTypes.Blur,
                            FaceAttributeTypes.Emotion,
                            FaceAttributeTypes.Exposure,
                            FaceAttributeTypes.FacialHair,
                            FaceAttributeTypes.Gender,
                            FaceAttributeTypes.Glasses,
                            FaceAttributeTypes.Hair,
                            FaceAttributeTypes.HeadPose,
                            FaceAttributeTypes.Makeup,
                            FaceAttributeTypes.Noise,
                            FaceAttributeTypes.Occlusion,
                            FaceAttributeTypes.Smile
                            }
                        ).Result;

                    Assert.Equal(1, faceList.Count);
                    var face = faceList[0];

                    // Ensure face rectangle coordinates return correctly
                    Assert.True(face.FaceRectangle.Top > 0);
                    Assert.True(face.FaceRectangle.Left > 0);
                    Assert.True(face.FaceRectangle.Width > 0);
                    Assert.True(face.FaceRectangle.Height > 0);

                    // Ensure face ID return correctly
                    Assert.True(face.FaceId.Length > 0);

                    // Ensure attributes match image
                    Assert.True(face.FaceAttributes.Hair.Invisible);
                    Assert.True(face.FaceAttributes.HeadPose.Roll != 0);
                    Assert.True(face.FaceAttributes.HeadPose.Yaw > 0);
                    Assert.Equal(Gender.Male, face.FaceAttributes.Gender);
                    Assert.True(face.FaceAttributes.Age > 0);
                    Assert.True(face.FaceAttributes.FacialHair.Beard > 0);
                    Assert.True(face.FaceAttributes.FacialHair.Moustache > 0);
                    Assert.True(face.FaceAttributes.FacialHair.Sideburns > 0);
                    Assert.True(face.FaceAttributes.Glasses == GlassesTypes.ReadingGlasses);
                    Assert.False(face.FaceAttributes.Makeup.EyeMakeup);
                    Assert.False(face.FaceAttributes.Makeup.LipMakeup);
                    Assert.True(face.FaceAttributes.Emotion.Neutral > 0.9);
                    Assert.True(face.FaceAttributes.Occlusion.ForeheadOccluded);
                    Assert.False(face.FaceAttributes.Occlusion.EyeOccluded);
                    Assert.False(face.FaceAttributes.Occlusion.MouthOccluded);
                    Assert.True(face.FaceAttributes.Accessories.Count > 0);
                    var accessories = face.FaceAttributes.Accessories;
                    Assert.Equal("glasses", accessories[0].Type, true, true, true);
                    Assert.True(accessories[0].Confidence > 0.9);
                    Assert.Equal("headwear", accessories[1].Type, true, true, true);
                    Assert.True(accessories[0].Confidence > 0.9);
                    Assert.Equal(BlurLevels.Low, face.FaceAttributes.Blur.BlurLevel);
                    Assert.Equal(ExposureLevels.GoodExposure, face.FaceAttributes.Exposure.ExposureLevel);
                    Assert.Equal(NoiseLevels.Medium, face.FaceAttributes.Noise.NoiseLevel);

                    // Ensure face landmarks are de-serialized correctly.
                    var landMarks = face.FaceLandmarks;
                    Assert.True(landMarks.PupilLeft.X > 0);
                    Assert.True(landMarks.PupilLeft.Y > 0);
                    Assert.True(landMarks.PupilRight.X > 0);
                    Assert.True(landMarks.PupilRight.Y > 0);
                    Assert.True(landMarks.NoseTip.X > 0);
                    Assert.True(landMarks.NoseTip.Y > 0);
                    Assert.True(landMarks.MouthLeft.X > 0);
                    Assert.True(landMarks.MouthLeft.Y > 0);
                    Assert.True(landMarks.MouthRight.X > 0);
                    Assert.True(landMarks.MouthRight.Y > 0);
                    Assert.True(landMarks.EyebrowLeftOuter.X > 0);
                    Assert.True(landMarks.EyebrowLeftInner.Y > 0);
                    Assert.True(landMarks.EyeLeftOuter.X > 0);
                    Assert.True(landMarks.EyeLeftOuter.Y > 0);
                    Assert.True(landMarks.EyeLeftTop.X > 0);
                    Assert.True(landMarks.EyeLeftTop.Y > 0);
                    Assert.True(landMarks.EyeLeftBottom.X > 0);
                    Assert.True(landMarks.EyeLeftBottom.Y > 0);
                    Assert.True(landMarks.EyeLeftInner.X > 0);
                    Assert.True(landMarks.EyeLeftInner.Y > 0);
                    Assert.True(landMarks.EyebrowRightInner.X > 0);
                    Assert.True(landMarks.EyebrowRightInner.Y > 0);
                    Assert.True(landMarks.EyebrowRightOuter.X > 0);
                    Assert.True(landMarks.EyebrowRightOuter.Y > 0);
                    Assert.True(landMarks.EyeRightInner.X > 0);
                    Assert.True(landMarks.EyeRightInner.Y > 0);
                    Assert.True(landMarks.EyeRightTop.X > 0);
                    Assert.True(landMarks.EyeRightTop.Y > 0);
                    Assert.True(landMarks.EyeRightBottom.X > 0);
                    Assert.True(landMarks.EyeRightBottom.Y > 0);
                    Assert.True(landMarks.EyeRightOuter.X > 0);
                    Assert.True(landMarks.EyeRightOuter.Y > 0);
                    Assert.True(landMarks.NoseRootLeft.X > 0);
                    Assert.True(landMarks.NoseRootLeft.Y > 0);
                    Assert.True(landMarks.NoseRootRight.X > 0);
                    Assert.True(landMarks.NoseRootRight.Y > 0);
                    Assert.True(landMarks.NoseLeftAlarTop.X > 0);
                    Assert.True(landMarks.NoseLeftAlarTop.Y > 0);
                    Assert.True(landMarks.NoseRightAlarTop.X > 0);
                    Assert.True(landMarks.NoseRightAlarTop.Y > 0);
                    Assert.True(landMarks.NoseLeftAlarOutTip.X > 0);
                    Assert.True(landMarks.NoseLeftAlarOutTip.Y > 0);
                    Assert.True(landMarks.NoseRightAlarOutTip.X > 0);
                    Assert.True(landMarks.NoseRightAlarOutTip.Y > 0);
                    Assert.True(landMarks.UpperLipTop.X > 0);
                    Assert.True(landMarks.UpperLipTop.Y > 0);
                    Assert.True(landMarks.UpperLipBottom.X > 0);
                    Assert.True(landMarks.UpperLipBottom.Y > 0);
                    Assert.True(landMarks.UnderLipTop.X > 0);
                    Assert.True(landMarks.UnderLipTop.Y > 0);
                    Assert.True(landMarks.UnderLipBottom.X > 0);
                    Assert.True(landMarks.UnderLipBottom.Y > 0);
                }
            }
        }

        [Fact]
        public void FaceDetectionNoFace()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "FaceDetectionNoFace");

                IFaceAPI client = GetFaceClient(HttpMockServer.CreateInstance());
                using (FileStream stream = new FileStream(Path.Combine("TestImages", "NoFace.jpg"), FileMode.Open))
                {
                    IList<DetectedFace> faceList = client.Face.DetectInStreamAsync(stream).Result;
                    Assert.Equal(0, faceList.Count);
                }
            }
        }
    }
}


text:
package org.apache.camel.component.aws2.lambda;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.camel.BindToRegistry;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.lambda.model.CreateAliasResponse;
import software.amazon.awssdk.services.lambda.model.CreateEventSourceMappingResponse;
import software.amazon.awssdk.services.lambda.model.CreateFunctionResponse;
import software.amazon.awssdk.services.lambda.model.DeleteAliasResponse;
import software.amazon.awssdk.services.lambda.model.DeleteEventSourceMappingResponse;
import software.amazon.awssdk.services.lambda.model.DeleteFunctionResponse;
import software.amazon.awssdk.services.lambda.model.GetAliasResponse;
import software.amazon.awssdk.services.lambda.model.GetFunctionRequest;
import software.amazon.awssdk.services.lambda.model.GetFunctionResponse;
import software.amazon.awssdk.services.lambda.model.ListAliasesResponse;
import software.amazon.awssdk.services.lambda.model.ListEventSourceMappingsResponse;
import software.amazon.awssdk.services.lambda.model.ListFunctionsResponse;
import software.amazon.awssdk.services.lambda.model.ListTagsResponse;
import software.amazon.awssdk.services.lambda.model.ListVersionsByFunctionResponse;
import software.amazon.awssdk.services.lambda.model.PublishVersionResponse;
import software.amazon.awssdk.services.lambda.model.TagResourceResponse;
import software.amazon.awssdk.services.lambda.model.UntagResourceResponse;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class LambdaProducerTest extends CamelTestSupport {

    @BindToRegistry("awsLambdaClient")
    AmazonLambdaClientMock clientMock = new AmazonLambdaClientMock();

    @EndpointInject("mock:result")
    private MockEndpoint mock;

    @Test
    public void lambdaCreateFunctionTest() {

        Exchange exchange = template.send("direct:createFunction", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(Lambda2Constants.RUNTIME, "nodejs6.10");
                exchange.getIn().setHeader(Lambda2Constants.HANDLER, "GetHelloWithName.handler");
                exchange.getIn().setHeader(Lambda2Constants.DESCRIPTION, "Hello with node.js on Lambda");
                exchange.getIn().setHeader(Lambda2Constants.ROLE, "arn:aws:iam::643534317684:role/lambda-execution-role");

                ClassLoader classLoader = getClass().getClassLoader();
                File file = new File(
                        classLoader.getResource("org/apache/camel/component/aws2/lambda/function/node/GetHelloWithName.zip")
                                .getFile());
                FileInputStream inputStream = new FileInputStream(file);
                exchange.getIn().setBody(inputStream);
            }
        });

        CreateFunctionResponse result = (CreateFunctionResponse) exchange.getMessage().getBody();
        assertEquals("GetHelloWithName", result.functionName());
        assertEquals("Hello with node.js on Lambda", result.description());
        assertNotNull(result.functionArn());
        assertNotNull(result.codeSha256());
    }

    @Test
    public void lambdaDeleteFunctionTest() {

        Exchange exchange = template.send("direct:deleteFunction", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {

            }
        });
        assertNotNull(exchange.getMessage().getBody(DeleteFunctionResponse.class));
    }

    @Test
    public void lambdaGetFunctionTest() {

        Exchange exchange = template.send("direct:getFunction", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {

            }
        });
        GetFunctionResponse result = (GetFunctionResponse) exchange.getMessage().getBody();
        assertEquals("GetHelloWithName", result.configuration().functionName());
    }

    @Test
    public void lambdaGetFunctionPojoTest() {

        Exchange exchange = template.send("direct:getFunctionPojo", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
                exchange.getIn().setBody(GetFunctionRequest.builder().functionName("GetHelloWithName").build());
            }
        });
        GetFunctionResponse result = (GetFunctionResponse) exchange.getMessage().getBody();
        assertEquals("GetHelloWithName", result.configuration().functionName());
    }

    @Test
    public void lambdaListFunctionsTest() {
        Exchange exchange = template.send("direct:listFunctions", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {

            }
        });

        ListFunctionsResponse result = (ListFunctionsResponse) exchange.getMessage().getBody();
        assertEquals(1, result.functions().size());
        assertEquals("GetHelloWithName", result.functions().get(0).functionName());
    }

    @Test
    public void lambdaInvokeFunctionTest() {
        Exchange exchange = template.send("direct:invokeFunction", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
                exchange.getIn().setBody("{\"name\":\"Camel\"}");
            }
        });

        assertNotNull(exchange.getMessage().getBody(String.class));
        assertEquals("{\"Hello\":\"Camel\"}", exchange.getMessage().getBody(String.class));
    }

    @Test
    public void lambdaCreateEventSourceMappingTest() throws Exception {
        Exchange exchange = template.send("direct:createEventSourceMapping", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
                exchange.getIn().setHeader(Lambda2Constants.EVENT_SOURCE_ARN,
                        "arn:aws:sqs:eu-central-1:643534317684:testqueue");
                exchange.getIn().setHeader(Lambda2Constants.EVENT_SOURCE_BATCH_SIZE, 100);
            }
        });
        assertMockEndpointsSatisfied();

        CreateEventSourceMappingResponse result = exchange.getMessage().getBody(CreateEventSourceMappingResponse.class);
        assertEquals("arn:aws:lambda:eu-central-1:643534317684:function:GetHelloWithName", result.functionArn());
    }

    @Test
    public void lambdaDeleteEventSourceMappingTest() throws Exception {
        Exchange exchange = template.send("direct:deleteEventSourceMapping", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
                exchange.getIn().setHeader(Lambda2Constants.EVENT_SOURCE_UUID, "a1239494949382882383");
            }
        });
        assertMockEndpointsSatisfied();

        DeleteEventSourceMappingResponse result = exchange.getMessage().getBody(DeleteEventSourceMappingResponse.class);
        assertTrue(result.state().equalsIgnoreCase("Deleting"));
    }

    @Test
    public void lambdaListEventSourceMappingTest() throws Exception {
        Exchange exchange = template.send("direct:listEventSourceMapping", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
            }
        });
        assertMockEndpointsSatisfied();

        ListEventSourceMappingsResponse result = exchange.getMessage().getBody(ListEventSourceMappingsResponse.class);
        assertEquals("arn:aws:lambda:eu-central-1:643534317684:function:GetHelloWithName",
                result.eventSourceMappings().get(0).functionArn());
    }

    @Test
    public void lambdaListTagsTest() throws Exception {

        Exchange exchange = template.send("direct:listTags", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
                exchange.getIn().setHeader(Lambda2Constants.RESOURCE_ARN,
                        "arn:aws:lambda:eu-central-1:643534317684:function:GetHelloWithName");
            }
        });
        assertMockEndpointsSatisfied();

        ListTagsResponse result = (ListTagsResponse) exchange.getMessage().getBody();
        assertEquals("lambda-tag", result.tags().get("test"));
    }

    @Test
    public void tagResourceTest() throws Exception {

        Exchange exchange = template.send("direct:tagResource", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
                Map<String, String> tags = new HashMap<>();
                tags.put("test", "added-tag");
                exchange.getIn().setHeader(Lambda2Constants.RESOURCE_ARN,
                        "arn:aws:lambda:eu-central-1:643534317684:function:GetHelloWithName");
                exchange.getIn().setHeader(Lambda2Constants.RESOURCE_TAGS, tags);
            }
        });
        assertMockEndpointsSatisfied();

        TagResourceResponse result = (TagResourceResponse) exchange.getMessage().getBody();
        assertNotNull(result);
    }

    @Test
    public void untagResourceTest() throws Exception {

        Exchange exchange = template.send("direct:untagResource", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
                List<String> tagKeys = new ArrayList<>();
                tagKeys.add("test");
                exchange.getIn().setHeader(Lambda2Constants.RESOURCE_ARN,
                        "arn:aws:lambda:eu-central-1:643534317684:function:GetHelloWithName");
                exchange.getIn().setHeader(Lambda2Constants.RESOURCE_TAG_KEYS, tagKeys);
            }
        });
        assertMockEndpointsSatisfied();

        UntagResourceResponse result = (UntagResourceResponse) exchange.getMessage().getBody();
        assertNotNull(result);
    }

    @Test
    public void publishVersionTest() throws Exception {

        Exchange exchange = template.send("direct:publishVersion", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
                exchange.getIn().setHeader(Lambda2Constants.VERSION_DESCRIPTION, "This is my description");
            }
        });
        assertMockEndpointsSatisfied();

        PublishVersionResponse result = (PublishVersionResponse) exchange.getMessage().getBody();
        assertNotNull(result);
        assertEquals("GetHelloWithName", result.functionName());
        assertEquals("This is my description", result.description());
    }

    @Test
    public void listVersionsTest() throws Exception {

        Exchange exchange = template.send("direct:listVersions", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
                exchange.getIn().setHeader(Lambda2Constants.VERSION_DESCRIPTION, "This is my description");
            }
        });
        assertMockEndpointsSatisfied();

        ListVersionsByFunctionResponse result = (ListVersionsByFunctionResponse) exchange.getMessage().getBody();
        assertNotNull(result);
        assertEquals("GetHelloWithName", result.versions().get(0).functionName());
        assertEquals("1", result.versions().get(0).version());
    }

    @Test
    public void createAliasTest() throws Exception {

        Exchange exchange = template.send("direct:createAlias", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
                exchange.getIn().setHeader(Lambda2Constants.FUNCTION_ALIAS_DESCRIPTION, "an alias");
                exchange.getIn().setHeader(Lambda2Constants.FUNCTION_ALIAS_NAME, "alias");
                exchange.getIn().setHeader(Lambda2Constants.FUNCTION_VERSION, "1");
            }
        });
        assertMockEndpointsSatisfied();

        CreateAliasResponse result = (CreateAliasResponse) exchange.getMessage().getBody();
        assertNotNull(result);
        assertEquals("an alias", result.description());
        assertEquals("alias", result.name());
        assertEquals("1", result.functionVersion());
    }

    @Test
    public void deleteAliasTest() throws Exception {

        Exchange exchange = template.send("direct:deleteAlias", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
                exchange.getIn().setHeader(Lambda2Constants.FUNCTION_ALIAS_NAME, "alias");
            }
        });
        assertMockEndpointsSatisfied();

        DeleteAliasResponse result = (DeleteAliasResponse) exchange.getMessage().getBody();
        assertNotNull(result);
    }

    @Test
    public void getAliasTest() throws Exception {

        Exchange exchange = template.send("direct:getAlias", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
                exchange.getIn().setHeader(Lambda2Constants.FUNCTION_ALIAS_NAME, "alias");
            }
        });
        assertMockEndpointsSatisfied();

        GetAliasResponse result = (GetAliasResponse) exchange.getMessage().getBody();
        assertNotNull(result);
        assertEquals("an alias", result.description());
        assertEquals("alias", result.name());
        assertEquals("1", result.functionVersion());
    }

    @Test
    public void listAliasesTest() throws Exception {

        Exchange exchange = template.send("direct:listAliases", ExchangePattern.InOut, new Processor() {
            @Override
            public void process(Exchange exchange) {
                exchange.getIn().setHeader(Lambda2Constants.FUNCTION_VERSION, "1");
            }
        });
        assertMockEndpointsSatisfied();

        ListAliasesResponse result = (ListAliasesResponse) exchange.getMessage().getBody();
        assertNotNull(result);
        assertEquals("an alias", result.aliases().get(0).description());
        assertEquals("alias", result.aliases().get(0).name());
        assertEquals("1", result.aliases().get(0).functionVersion());
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from("direct:createFunction")
                        .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=createFunction")
                        .to("mock:result");

                from("direct:getFunction")
                        .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=getFunction")
                        .to("mock:result");

                from("direct:getFunctionPojo").to(
                        "aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=getFunction&pojoRequest=true")
                        .to("mock:result");

                from("direct:listFunctions")
                        .to("aws2-lambda://myFunction?awsLambdaClient=#awsLambdaClient&operation=listFunctions")
                        .to("mock:result");

                from("direct:invokeFunction")
                        .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=invokeFunction")
                        .to("mock:result");

                from("direct:deleteFunction")
                        .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=deleteFunction")
                        .to("mock:result");

                from("direct:updateFunction")
                        .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=updateFunction")
                        .to("mock:result");

                from("direct:listTags").to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=listTags")
                        .to("mock:result");

                from("direct:tagResource")
                        .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=tagResource")
                        .to("mock:result");

                from("direct:untagResource")
                        .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=untagResource")
                        .to("mock:result");

                from("direct:publishVersion")
                        .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=publishVersion")
                        .to("mock:result");

                from("direct:listVersions")
                        .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=listVersions")
                        .to("mock:result");

                from("direct:createEventSourceMapping").to(
                        "aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=createEventSourceMapping")
                        .to("mock:result");

                from("direct:deleteEventSourceMapping").to(
                        "aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=deleteEventSourceMapping")
                        .to("mock:result");

                from("direct:listEventSourceMapping")
                        .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=listEventSourceMapping")
                        .to("mock:result");

                from("direct:createAlias")
                        .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=createAlias")
                        .to("mock:result");

                from("direct:deleteAlias")
                        .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=deleteAlias")
                        .to("mock:result");

                from("direct:getAlias").to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=getAlias")
                        .to("mock:result");

                from("direct:listAliases")
                        .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=listAliases")
                        .to("mock:result");
            }
        };
    }
}


text:
import Ember from 'ember';
import jobMixin from 'ember-data-offline/mixins/job';

export default Ember.Object.extend(jobMixin, {
  task() {
    return Ember.$.ajax(this.get('params'));
  },
});


text:
package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"net/textproto"
	"os"
	"path"
	"strings"
	"time"
)

func main() {
	var (
		destinationAddr = flag.String("dest", "http://localhost:8080", "destination instance to which the file shall be uploaded")
		mimeType        = flag.String("mimetype", "application/octet-stream", "MIME type of file")
		inputFile       = flag.String("file", "", "file to upload")
		drawerName      = flag.String("drawer", "", "drawer name")
		auth            = flag.String("auth", "", "authentication information, provided as username:password")
	)

	flag.Parse()

	if *inputFile == "" {
		fmt.Println("No input file provided!")
		flag.Usage()
		return
	}

	if *drawerName == "" {
		fmt.Println("No drawer name provided!")
		flag.Usage()
		return
	}

	f, err := os.Open(*inputFile)
	if err != nil {
		fmt.Printf("Error: couldn't open %s: %v\n", *inputFile, err)
		return
	}

	var mpBuf bytes.Buffer
	mw := multipart.NewWriter(&mpBuf)
	mw.SetBoundary("cabinet-upload-" + time.Now().Format("20060102150405999999999"))

	mimeHeaders := make(textproto.MIMEHeader)
	mimeHeaders.Set("Content-Type", *mimeType)

	pw, err := mw.CreatePart(mimeHeaders)
	if err != nil {
		fmt.Printf("Error: couldn't create multipart data: %v\n", err)
		return
	}

	if _, err := io.Copy(pw, f); err != nil {
		fmt.Printf("Error: couldn't add file content to multipart data: %v\n", err)
		return
	}

	if err := mw.Close(); err != nil {
		fmt.Printf("Error: couldn't finish up multipart data: %v\n", err)
		return
	}

	basename := path.Base(*inputFile)
	baseParts := strings.Split(basename, ".")
	extension := baseParts[len(baseParts)-1]

	req, err := http.NewRequest("POST", *destinationAddr+"/api/upload?drawer="+*drawerName+"&ext="+extension, &mpBuf)
	if err != nil {
		fmt.Printf("Error: couldn't create request: %v\n", err)
		return
	}
	req.Header.Set("Content-Type", mw.FormDataContentType())
	if *auth != "" {
		elems := strings.Split(*auth, ":")
		if len(elems) != 2 {
			fmt.Println("Error: authentication information must be in the format username:password!")
			return
		}
		req.SetBasicAuth(elems[0], elems[1])
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Printf("Error: upload failed: %v\n", err)
		return
	}
	if resp.StatusCode != http.StatusOK {
		fmt.Print("Error: upload failed: ")
		io.Copy(os.Stdout, resp.Body)
		return
	}

	filenames := []string{}

	if err := json.NewDecoder(resp.Body).Decode(&filenames); err != nil {
		fmt.Printf("Decoding response failed: %v\n", err)
		return
	}

	for _, fn := range filenames {
		fmt.Println(fn)
	}
}


text:
using System;

namespace Stubby.App.Testing.Assertions
{
    internal class AssertReader
    {
        private string[] _parts;
        private int _index = 0;

        public bool CanRead => _index < _parts.Length;

        public AssertReader(String text)
        {
            if (String.IsNullOrWhiteSpace(text))
            {
                _parts = new string[0];
            }
            else
            {
                _parts = text.ToLowerInvariant().Split(' ', StringSplitOptions.RemoveEmptyEntries);
            }
        }

        public bool TrySkip(string token)
        {
            (bool, bool) result = TryExecute(() => (true, _parts[_index] == token));
            return result.Item2;
        }

        public bool TryParseEnum(Type enumType, out Object enumValue)
        {
            (Object, bool) result = TryExecute(() => Enum.Parse(enumType, _parts[_index], true));
            enumValue = result.Item1;
            return result.Item2;
        }

        internal bool TryParseInt(out int number)
        {
            (int, bool) result = TryExecute(() => int.Parse(_parts[_index]));
            number = result.Item1;
            return result.Item2;
        }

        private (TArg, bool) TryExecute<TArg>(Func<(TArg, bool)> action)
        {
            EnsureCanRead();
            try
            {
                (TArg, bool) result = action();
                if (result.Item2)
                {
                    MoveNext();
                }
                return result;
            }
            catch
            {
                return (default(TArg), false);
            }
        }

        private (TArg, bool) TryExecute<TArg>(Func<TArg> action)
        {
            return TryExecute<TArg>(() => (action(), true));
        }

        private void EnsureCanRead()
        {
            if (!CanRead)
            {
                throw new Exception("Can't read");
            }
        }

        private void MoveNext()
        {
            _index++;
        }
    }
}


text:
@extends('layouts.frontend')

@section('title', 'Welcome')

@section('content')

        @foreach($posts as $post)

getPreview() }})">
                        @if($post->getPreview() == null)

                                Currently no Preview available.

                        @endif

{{ $post->title }}

                        @if($post->excerpt)
                            {!! $post->shortExcerptHtml() !!}

                                slug) }}" target="_blank">Read more

                        @else
                            {!! $post->shortBodyHtml() !!}

                                slug) }}" target="_blank">Read more

                        @endif

        @endforeach

@endsection


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/bind.h"
#include "base/command_line.h"
#include "base/run_loop.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "cc/base/math_util.h"
#include "components/viz/common/gpu/context_provider.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/video_capture_service.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/shell/browser/shell.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/media_switches.h"
#include "media/base/video_frame.h"
#include "media/base/video_frame_metadata.h"
#include "media/capture/mojom/video_capture_types.mojom.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "services/video_capture/public/mojom/constants.mojom.h"
#include "services/video_capture/public/mojom/device_factory.mojom.h"
#include "services/video_capture/public/mojom/producer.mojom.h"
#include "services/video_capture/public/mojom/scoped_access_permission.mojom.h"
#include "services/video_capture/public/mojom/virtual_device.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/khronos/GLES2/gl2ext.h"
#include "ui/compositor/compositor.h"

// ImageTransportFactory::GetInstance is not available on all build configs.
#if defined(USE_AURA) || defined(OS_MACOSX)
#define CAN_USE_IMAGE_TRANSPORT_FACTORY 1
#endif

#if defined(CAN_USE_IMAGE_TRANSPORT_FACTORY)
#include "content/browser/compositor/image_transport_factory.h"

namespace content {

namespace {

class InvokeClosureOnDelete
    : public video_capture::mojom::ScopedAccessPermission {
 public:
  explicit InvokeClosureOnDelete(base::OnceClosure closure)
      : closure_(std::move(closure)) {}

  ~InvokeClosureOnDelete() override { std::move(closure_).Run(); }

 private:
  base::OnceClosure closure_;
};

static const char kVideoCaptureHtmlFile[] = "/media/video_capture_test.html";
static const char kStartVideoCaptureAndVerify[] =
    "startVideoCaptureFromVirtualDeviceAndVerifyUniformColorVideoWithSize(%d, "
    "%d)";

static const char kVirtualDeviceId[] = "/virtual/device";
static const char kVirtualDeviceName[] = "Virtual Device";

static const gfx::Size kDummyFrameCodedSize(320, 200);
static const gfx::Rect kDummyFrameVisibleRect(94, 36, 178, 150);
static const int kDummyFrameRate = 5;

}  // namespace

// Abstraction for logic that is different between exercising
// DeviceFactory.AddTextureVirtualDevice() and
// DeviceFactory.AddSharedMemoryVirtualDevice().
class VirtualDeviceExerciser {
 public:
  virtual ~VirtualDeviceExerciser() {}
  virtual void Initialize() = 0;
  virtual void RegisterVirtualDeviceAtFactory(
      mojo::Remote<video_capture::mojom::DeviceFactory>* factory,
      const media::VideoCaptureDeviceInfo& info) = 0;
  virtual gfx::Size GetVideoSize() = 0;
  virtual void PushNextFrame(base::TimeDelta timestamp) = 0;
  virtual void ShutDown() = 0;
};

// A VirtualDeviceExerciser for exercising
// DeviceFactory.AddTextureVirtualDevice(). It alternates between two texture
// RGB dummy frames, one dark one and one light one.
class TextureDeviceExerciser : public VirtualDeviceExerciser {
 public:
  TextureDeviceExerciser() { DETACH_FROM_SEQUENCE(sequence_checker_); }

  void Initialize() override {
    ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
    CHECK(factory);
    context_provider_ =
        factory->GetContextFactory()->SharedMainThreadContextProvider();
    CHECK(context_provider_);
    gpu::gles2::GLES2Interface* gl = context_provider_->ContextGL();
    CHECK(gl);

    const uint8_t kDarkFrameByteValue = 0;
    const uint8_t kLightFrameByteValue = 200;
    CreateDummyRgbFrame(gl, kDarkFrameByteValue,
                        &dummy_frame_0_mailbox_holder_);
    CreateDummyRgbFrame(gl, kLightFrameByteValue,
                        &dummy_frame_1_mailbox_holder_);
  }

  void RegisterVirtualDeviceAtFactory(
      mojo::Remote<video_capture::mojom::DeviceFactory>* factory,
      const media::VideoCaptureDeviceInfo& info) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    (*factory)->AddTextureVirtualDevice(
        info, virtual_device_.BindNewPipeAndPassReceiver());

    virtual_device_->OnNewMailboxHolderBufferHandle(
        0, media::mojom::MailboxBufferHandleSet::New(
               std::move(dummy_frame_0_mailbox_holder_)));
    virtual_device_->OnNewMailboxHolderBufferHandle(
        1, media::mojom::MailboxBufferHandleSet::New(
               std::move(dummy_frame_1_mailbox_holder_)));
    frame_being_consumed_[0] = false;
    frame_being_consumed_[1] = false;
  }

  gfx::Size GetVideoSize() override { return kDummyFrameCodedSize; }

  void PushNextFrame(base::TimeDelta timestamp) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (frame_being_consumed_[dummy_frame_index_]) {
      LOG(INFO) << "Frame " << dummy_frame_index_ << " is still being consumed";
      return;
    }

    mojo::PendingRemote<video_capture::mojom::ScopedAccessPermission>
        access_permission_proxy;
    mojo::MakeSelfOwnedReceiver<video_capture::mojom::ScopedAccessPermission>(
        std::make_unique<InvokeClosureOnDelete>(
            base::BindOnce(&TextureDeviceExerciser::OnFrameConsumptionFinished,
                           weak_factory_.GetWeakPtr(), dummy_frame_index_)),
        access_permission_proxy.InitWithNewPipeAndPassReceiver());

    media::VideoFrameMetadata metadata;
    metadata.SetDouble(media::VideoFrameMetadata::FRAME_RATE, kDummyFrameRate);
    metadata.SetTimeTicks(media::VideoFrameMetadata::REFERENCE_TIME,
                          base::TimeTicks::Now());

    media::mojom::VideoFrameInfoPtr info = media::mojom::VideoFrameInfo::New();
    info->timestamp = timestamp;
    info->pixel_format = media::PIXEL_FORMAT_ARGB;
    info->coded_size = kDummyFrameCodedSize;
    info->visible_rect = gfx::Rect(kDummyFrameCodedSize);
    info->metadata = metadata.GetInternalValues().Clone();

    frame_being_consumed_[dummy_frame_index_] = true;
    virtual_device_->OnFrameReadyInBuffer(dummy_frame_index_,
                                          std::move(access_permission_proxy),
                                          std::move(info));

    dummy_frame_index_ = (dummy_frame_index_ + 1) % 2;
  }

  void ShutDown() override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    virtual_device_.reset();
    weak_factory_.InvalidateWeakPtrs();
  }

 private:
  void CreateDummyRgbFrame(gpu::gles2::GLES2Interface* gl,
                           uint8_t value_for_all_rgb_bytes,
                           std::vector<gpu::MailboxHolder>* target) {
    const int32_t kBytesPerRGBPixel = 3;
    int32_t frame_size_in_bytes = kDummyFrameCodedSize.width() *
                                  kDummyFrameCodedSize.height() *
                                  kBytesPerRGBPixel;
    std::unique_ptr<uint8_t[]> dummy_frame_data(
        new uint8_t[frame_size_in_bytes]);
    memset(dummy_frame_data.get(), value_for_all_rgb_bytes,
           frame_size_in_bytes);
    for (int i = 0; i < media::VideoFrame::kMaxPlanes; i++) {
      // For RGB formats, only the first plane needs to be filled with an
      // actual texture.
      if (i != 0) {
        target->push_back(gpu::MailboxHolder());
        continue;
      }

      GLuint texture_id = 0;
      gl->GenTextures(1, &texture_id);
      gl->BindTexture(GL_TEXTURE_2D, texture_id);
      gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
      gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
      gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
      gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
      gl->TexImage2D(GL_TEXTURE_2D, 0, GL_RGB, kDummyFrameCodedSize.width(),
                     kDummyFrameCodedSize.height(), 0, GL_RGB, GL_UNSIGNED_BYTE,
                     dummy_frame_data.get());
      gl->BindTexture(GL_TEXTURE_2D, 0);

      gpu::Mailbox mailbox;
      gl->ProduceTextureDirectCHROMIUM(texture_id, mailbox.name);
      gpu::SyncToken sync_token;
      gl->GenSyncTokenCHROMIUM(sync_token.GetData());

      target->push_back(gpu::MailboxHolder(mailbox, sync_token, GL_TEXTURE_2D));
    }
    gl->ShallowFlushCHROMIUM();
    CHECK_EQ(gl->GetError(), static_cast<GLenum>(GL_NO_ERROR));
  }

  void OnFrameConsumptionFinished(int frame_index) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    frame_being_consumed_[frame_index] = false;
  }

  SEQUENCE_CHECKER(sequence_checker_);
  scoped_refptr<viz::ContextProvider> context_provider_;
  mojo::Remote<video_capture::mojom::TextureVirtualDevice> virtual_device_;
  int dummy_frame_index_ = 0;
  std::vector<gpu::MailboxHolder> dummy_frame_0_mailbox_holder_;
  std::vector<gpu::MailboxHolder> dummy_frame_1_mailbox_holder_;
  std::array<bool, 2> frame_being_consumed_;
  base::WeakPtrFactory<TextureDeviceExerciser> weak_factory_{this};
};

// A VirtualDeviceExerciser for exercising
// DeviceFactory.AddSharedMemoryVirtualDevice().
// It generates (dummy) I420 frame data by setting all bytes equal to the
// current frame count. Padding bytes are set to 0.
class SharedMemoryDeviceExerciser : public VirtualDeviceExerciser,
                                    public video_capture::mojom::Producer {
 public:
  explicit SharedMemoryDeviceExerciser(
      media::mojom::PlaneStridesPtr strides = nullptr)
      : strides_(std::move(strides)) {}

  // VirtualDeviceExerciser implementation.
  void Initialize() override {}
  void RegisterVirtualDeviceAtFactory(
      mojo::Remote<video_capture::mojom::DeviceFactory>* factory,
      const media::VideoCaptureDeviceInfo& info) override {
    mojo::PendingRemote<video_capture::mojom::Producer> producer;
    static const bool kSendBufferHandlesToProducerAsRawFileDescriptors = false;
    producer_receiver_.Bind(producer.InitWithNewPipeAndPassReceiver());
    (*factory)->AddSharedMemoryVirtualDevice(
        info, std::move(producer),
        kSendBufferHandlesToProducerAsRawFileDescriptors,
        virtual_device_.BindNewPipeAndPassReceiver());
  }
  gfx::Size GetVideoSize() override {
    return gfx::Size(kDummyFrameVisibleRect.width(),
                     kDummyFrameVisibleRect.height());
  }
  void PushNextFrame(base::TimeDelta timestamp) override {
    virtual_device_->RequestFrameBuffer(
        kDummyFrameCodedSize, media::VideoPixelFormat::PIXEL_FORMAT_I420,
        strides_.Clone(),
        base::BindOnce(&SharedMemoryDeviceExerciser::OnFrameBufferReceived,
                       weak_factory_.GetWeakPtr(), timestamp));
  }
  void ShutDown() override {
    virtual_device_.reset();
    producer_receiver_.reset();
    weak_factory_.InvalidateWeakPtrs();
  }

  // video_capture::mojom::Producer implementation.
  void OnNewBuffer(int32_t buffer_id,
                   media::mojom::VideoBufferHandlePtr buffer_handle,
                   OnNewBufferCallback callback) override {
    CHECK(buffer_handle->is_shared_buffer_handle());
    base::UnsafeSharedMemoryRegion region =
        mojo::UnwrapUnsafeSharedMemoryRegion(
            std::move(buffer_handle->get_shared_buffer_handle()));
    CHECK(region.IsValid());
    base::WritableSharedMemoryMapping mapping = region.Map();
    CHECK(mapping.IsValid());
    outgoing_buffer_id_to_buffer_map_.insert(
        std::make_pair(buffer_id, std::move(mapping)));
    std::move(callback).Run();
  }
  void OnBufferRetired(int32_t buffer_id) override {
    outgoing_buffer_id_to_buffer_map_.erase(buffer_id);
  }

 private:
  void OnFrameBufferReceived(base::TimeDelta timestamp, int32_t buffer_id) {
    if (buffer_id == video_capture::mojom::kInvalidBufferId)
      return;

    media::VideoFrameMetadata metadata;
    metadata.SetDouble(media::VideoFrameMetadata::FRAME_RATE, kDummyFrameRate);
    metadata.SetTimeTicks(media::VideoFrameMetadata::REFERENCE_TIME,
                          base::TimeTicks::Now());

    media::mojom::VideoFrameInfoPtr info = media::mojom::VideoFrameInfo::New();
    info->timestamp = timestamp;
    info->pixel_format = media::PIXEL_FORMAT_I420;
    info->coded_size = kDummyFrameCodedSize;
    info->visible_rect = kDummyFrameVisibleRect;
    info->metadata = metadata.GetInternalValues().Clone();
    info->strides = strides_.Clone();

    const base::WritableSharedMemoryMapping& outgoing_buffer =
        outgoing_buffer_id_to_buffer_map_.at(buffer_id);

    static int frame_count = 0;
    frame_count++;
    const uint8_t dummy_value = frame_count % 256;

    // Reset the whole buffer to 0
    memset(outgoing_buffer.memory(), 0, outgoing_buffer.size());

    // Set all bytes affecting |info->visible_rect| to |dummy_value|.
    const int kYStride = info->strides ? info->strides->stride_by_plane[0]
                                       : info->coded_size.width();
    const int kYColsToSkipAtStart = info->visible_rect.x();
    const int kYVisibleColCount = info->visible_rect.width();
    const int kYCodedRowCount = info->coded_size.height();
    const int kYRowsToSkipAtStart = info->visible_rect.y();
    const int kYVisibleRowCount = info->visible_rect.height();

    const int kUStride = info->strides ? info->strides->stride_by_plane[1]
                                       : info->coded_size.width() / 2;
    const int kUColsToSkipAtStart =
        cc::MathUtil::UncheckedRoundDown(info->visible_rect.x(), 2) / 2;
    const int kUVisibleColCount =
        (cc::MathUtil::UncheckedRoundUp(info->visible_rect.right(), 2) / 2) -
        kUColsToSkipAtStart;
    const int kUCodedRowCount = info->coded_size.height() / 2;
    const int kURowsToSkipAtStart =
        cc::MathUtil::UncheckedRoundDown(info->visible_rect.y(), 2) / 2;
    const int kUVisibleRowCount =
        (cc::MathUtil::UncheckedRoundUp(info->visible_rect.bottom(), 2) / 2) -
        kURowsToSkipAtStart;

    const int kVStride = info->strides ? info->strides->stride_by_plane[2]
                                       : info->coded_size.width() / 2;

    uint8_t* write_ptr = outgoing_buffer.GetMemoryAsSpan<uint8_t>().data();
    FillVisiblePortionOfPlane(&write_ptr, dummy_value, kYCodedRowCount,
                              kYRowsToSkipAtStart, kYVisibleRowCount, kYStride,
                              kYColsToSkipAtStart, kYVisibleColCount);
    FillVisiblePortionOfPlane(&write_ptr, dummy_value, kUCodedRowCount,
                              kURowsToSkipAtStart, kUVisibleRowCount, kUStride,
                              kUColsToSkipAtStart, kUVisibleColCount);
    FillVisiblePortionOfPlane(&write_ptr, dummy_value, kUCodedRowCount,
                              kURowsToSkipAtStart, kUVisibleRowCount, kVStride,
                              kUColsToSkipAtStart, kUVisibleColCount);

    virtual_device_->OnFrameReadyInBuffer(buffer_id, std::move(info));
  }

  void FillVisiblePortionOfPlane(uint8_t** write_ptr,
                                 uint8_t fill_value,
                                 int row_count,
                                 int rows_to_skip_at_start,
                                 int visible_row_count,
                                 int col_count,
                                 int cols_to_skip_at_start,
                                 int visible_col_count) {
    const int kColsToSkipAtEnd =
        col_count - visible_col_count - cols_to_skip_at_start;
    const int kRowsToSkipAtEnd =
        row_count - visible_row_count - rows_to_skip_at_start;

    // Skip rows at start
    (*write_ptr) += col_count * rows_to_skip_at_start;
    // Fill rows
    for (int i = 0; i < visible_row_count; i++) {
      // Skip cols at start
      (*write_ptr) += cols_to_skip_at_start;
      // Fill visible bytes
      memset(*write_ptr, fill_value, visible_col_count);
      (*write_ptr) += visible_col_count;
      // Skip cols at end
      (*write_ptr) += kColsToSkipAtEnd;
    }
    // Skip rows at end
    (*write_ptr) += col_count * kRowsToSkipAtEnd;
  }

  media::mojom::PlaneStridesPtr strides_;
  mojo::Receiver<video_capture::mojom::Producer> producer_receiver_{this};
  mojo::Remote<video_capture::mojom::SharedMemoryVirtualDevice> virtual_device_;
  std::map<int32_t /*buffer_id*/, base::WritableSharedMemoryMapping>
      outgoing_buffer_id_to_buffer_map_;
  base::WeakPtrFactory<SharedMemoryDeviceExerciser> weak_factory_{this};
};

// Integration test that obtains a connection to the video capture service. It
// It then registers a virtual device at the service and feeds frames to it. It
// opens the virtual device in a <video> element on a test page and verifies
// that the element plays in the expected dimensions and the pixel content on
// the element changes.
class WebRtcVideoCaptureServiceBrowserTest : public ContentBrowserTest {
 public:
  WebRtcVideoCaptureServiceBrowserTest()
      : virtual_device_thread_("Virtual Device Thread") {
    scoped_feature_list_.InitAndEnableFeature(features::kMojoVideoCapture);
    virtual_device_thread_.Start();
  }

  ~WebRtcVideoCaptureServiceBrowserTest() override {}

  void AddVirtualDeviceAndStartCapture(VirtualDeviceExerciser* device_exerciser,
                                       base::OnceClosure finish_test_cb) {
    DCHECK(virtual_device_thread_.task_runner()->RunsTasksInCurrentSequence());

    main_task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(
            [](mojo::PendingReceiver<video_capture::mojom::DeviceFactory>
                   receiver) {
              GetVideoCaptureService().ConnectToDeviceFactory(
                  std::move(receiver));
            },
            factory_.BindNewPipeAndPassReceiver()));

    media::VideoCaptureDeviceInfo info;
    info.descriptor.device_id = kVirtualDeviceId;
    info.descriptor.set_display_name(kVirtualDeviceName);
    info.descriptor.capture_api = media::VideoCaptureApi::VIRTUAL_DEVICE;

    video_size_ = device_exerciser->GetVideoSize();
    device_exerciser->RegisterVirtualDeviceAtFactory(&factory_, info);

    main_task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&WebRtcVideoCaptureServiceBrowserTest::
                           OpenVirtualDeviceInRendererAndWaitForPlaying,
                       base::Unretained(this),
                       media::BindToCurrentLoop(base::BindOnce(
                           &WebRtcVideoCaptureServiceBrowserTest::
                               ShutDownVirtualDeviceAndContinue,
                           base::Unretained(this), device_exerciser,
                           std::move(finish_test_cb)))));

    PushDummyFrameAndScheduleNextPush(device_exerciser);
  }

  void PushDummyFrameAndScheduleNextPush(
      VirtualDeviceExerciser* device_exerciser) {
    DCHECK(virtual_device_thread_.task_runner()->RunsTasksInCurrentSequence());
    device_exerciser->PushNextFrame(CalculateTimeSinceFirstInvocation());
    base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&WebRtcVideoCaptureServiceBrowserTest::
                           PushDummyFrameAndScheduleNextPush,
                       weak_factory_.GetWeakPtr(), device_exerciser),
        base::TimeDelta::FromMilliseconds(1000 / kDummyFrameRate));
  }

  void ShutDownVirtualDeviceAndContinue(
      VirtualDeviceExerciser* device_exerciser,
      base::OnceClosure continuation) {
    DCHECK(virtual_device_thread_.task_runner()->RunsTasksInCurrentSequence());
    LOG(INFO) << "Shutting down virtual device";
    device_exerciser->ShutDown();
    factory_.reset();
    weak_factory_.InvalidateWeakPtrs();
    std::move(continuation).Run();
  }

  void OpenVirtualDeviceInRendererAndWaitForPlaying(
      base::OnceClosure finish_test_cb) {
    DCHECK(main_task_runner_->RunsTasksInCurrentSequence());
    embedded_test_server()->StartAcceptingConnections();
    GURL url(embedded_test_server()->GetURL(kVideoCaptureHtmlFile));
    EXPECT_TRUE(NavigateToURL(shell(), url));

    std::string javascript_to_execute = base::StringPrintf(
        kStartVideoCaptureAndVerify, video_size_.width(), video_size_.height());
    std::string result;
    // Start video capture and wait until it started rendering
    ASSERT_TRUE(
        ExecuteScriptAndExtractString(shell(), javascript_to_execute, &result));
    ASSERT_EQ("OK", result);

    std::move(finish_test_cb).Run();
  }

 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    // Note: We are not planning to actually use the fake device, but we want
    // to avoid enumerating or otherwise calling into real capture devices.
    command_line->AppendSwitch(switches::kUseFakeUIForMediaStream);
  }

  void SetUp() override {
    ASSERT_TRUE(embedded_test_server()->InitializeAndListen());
    EnablePixelOutput();
    ContentBrowserTest::SetUp();
  }

  void Initialize() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    main_task_runner_ = base::ThreadTaskRunnerHandle::Get();
  }

  base::Thread virtual_device_thread_;
  scoped_refptr<base::SequencedTaskRunner> main_task_runner_;

 private:
  base::TimeDelta CalculateTimeSinceFirstInvocation() {
    if (first_frame_time_.is_null())
      first_frame_time_ = base::TimeTicks::Now();
    return base::TimeTicks::Now() - first_frame_time_;
  }

  base::test::ScopedFeatureList scoped_feature_list_;
  mojo::Remote<video_capture::mojom::DeviceFactory> factory_;
  gfx::Size video_size_;
  base::TimeTicks first_frame_time_;
  base::WeakPtrFactory<WebRtcVideoCaptureServiceBrowserTest> weak_factory_{
      this};

  DISALLOW_COPY_AND_ASSIGN(WebRtcVideoCaptureServiceBrowserTest);
};

IN_PROC_BROWSER_TEST_F(
    WebRtcVideoCaptureServiceBrowserTest,
    FramesSentThroughTextureVirtualDeviceGetDisplayedOnPage) {
  Initialize();
  auto device_exerciser = std::make_unique<TextureDeviceExerciser>();
  device_exerciser->Initialize();

  base::RunLoop run_loop;
  virtual_device_thread_.task_runner()->PostTask(
      FROM_HERE,
      base::BindOnce(&WebRtcVideoCaptureServiceBrowserTest::
                         AddVirtualDeviceAndStartCapture,
                     base::Unretained(this), device_exerciser.get(),
                     media::BindToCurrentLoop(run_loop.QuitClosure())));
  run_loop.Run();
}

IN_PROC_BROWSER_TEST_F(
    WebRtcVideoCaptureServiceBrowserTest,
    FramesSentThroughSharedMemoryVirtualDeviceGetDisplayedOnPage) {
  Initialize();
  auto device_exerciser = std::make_unique<SharedMemoryDeviceExerciser>();
  device_exerciser->Initialize();

  base::RunLoop run_loop;
  virtual_device_thread_.task_runner()->PostTask(
      FROM_HERE,
      base::BindOnce(&WebRtcVideoCaptureServiceBrowserTest::
                         AddVirtualDeviceAndStartCapture,
                     base::Unretained(this), device_exerciser.get(),
                     media::BindToCurrentLoop(run_loop.QuitClosure())));
  run_loop.Run();
}

IN_PROC_BROWSER_TEST_F(
    WebRtcVideoCaptureServiceBrowserTest,
    PaddedI420FramesSentThroughSharedMemoryVirtualDeviceGetDisplayedOnPage) {
  Initialize();
  auto device_exerciser = std::make_unique<SharedMemoryDeviceExerciser>(
      media::mojom::PlaneStrides::New(
          std::vector<uint32_t>({1024u, 512u, 1024u, 0u})));
  device_exerciser->Initialize();

  base::RunLoop run_loop;
  virtual_device_thread_.task_runner()->PostTask(
      FROM_HERE,
      base::BindOnce(&WebRtcVideoCaptureServiceBrowserTest::
                         AddVirtualDeviceAndStartCapture,
                     base::Unretained(this), device_exerciser.get(),
                     media::BindToCurrentLoop(run_loop.QuitClosure())));
  run_loop.Run();
}

}  // namespace content

#endif  // defined(CAN_USE_IMAGE_TRANSPORT_FACTORY)


text:
'use strict';

const chai = require('chai'),
  expect = chai.expect,
  Support = require(__dirname + '/../../support'),
  DataTypes = require(__dirname + '/../../../../lib/data-types'),
  dialect = Support.getTestDialect(),
  _ = require('lodash');

if ( dialect.match(/^postgres/) ) {
  describe('[POSTGRES] Sequelize', () => {
    function checkTimezoneParsing(baseOptions) {
      const options = _.extend({}, baseOptions, { timezone: 'Asia/Kolkata', timestamps: true });
      const sequelize = Support.createSequelizeInstance(options);

      const tzTable = sequelize.define('tz_table', { foo: DataTypes.STRING });
      return tzTable.sync({force: true}).then(() => {
        return tzTable.create({foo: 'test'}).then(row => {
          expect(row).to.be.not.null;
        });
      });
    }

    it('should correctly parse the moment based timezone', function() {
      return checkTimezoneParsing(this.sequelize.options);
    });

    it('should correctly parse the moment based timezone while fetching hstore oids', function() {
      // reset oids so we need to refetch them
      DataTypes.HSTORE.types.postgres.oids = [];
      DataTypes.HSTORE.types.postgres.array_oids = [];
      return checkTimezoneParsing(this.sequelize.options);
    });

    if ( process.env.DIALECT === 'postgres' ) {

      // This test will only run with node-pg 7.3.0 or greater. node-pg requires node-pg-native 2.0.0 or greater.
      // node-pg-native 2.0.0 breaks a bunch of tests.
      it.skip('should properly pass statement_timeout to postgres', function() {
        const options = _.extend({}, this.sequelize.options, { dialectOptions: { 'statement_timeout': 10 } });
        const sequelize = Support.createSequelizeInstance(options);

        return sequelize.query('SHOW statement_timeout')
          .then( result => {
            const timeout = _.get( result, '[0].statement_timeout' );
            expect(timeout).to.equal('10ms');
          });
      });

      // This test will only run with node-pg 7.3.0 or greater. node-pg requires node-pg-native 2.0.0 or greater.
      // node-pg-native 2.0.0 breaks a bunch of tests.
      it.skip('should properly error when a statement is cancelled due to a statement_timeout', function() {
        const self = this;
        const options = _.extend({}, this.sequelize.options, { dialectOptions: { 'statement_timeout': 10 } });
        const sequelize = Support.createSequelizeInstance(options);

        return sequelize.query('SELECT pg_sleep(1)')
          .then( () => {
            expect.fail('Postgres should have cancelled the query with an error');
          })
          .catch( self.sequelize.DatabaseError, error => {
            expect(error.parent.code).to.equal('57014'); // postgres query_cancelled error
          });
      });
    }

  });
}


text:
$server_name;
$Server_Username;
$Server_Userpassword;

$array=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30

$bCache_Id=$false;
$bServer_Username=$false;
$bServer_UserPassword=$false;
$cacheId;
$bCacheId=$false;
$bSize=$false;
$bServers=$false;
$topology = "local-cache";

$server_name=get-childitem env:computername;
$servers=$server_name.value;
$cmd;

$i=0;

$args | foreach-object { $array[$i]=$_;   $i++ }

if ($args -contains "-?" -or $args -contains "/?" -or $help)
{
@"
NAME
    CreateCache

SYNOPSIS
    Creates cache as per specified cache id.

SYNTAX
    CreateCache.ps1 cache-id /uid server-username /pwd server-password [option[...]].

DETAILED DESCRIPTION
    This script Create cache. This script uses command line tool
	CreateCache.exe of NCache.

PARAMETERS
    /cacheid
        Specifies a unique id of cache to be created on given server.
        A cache with given id is created on the server.

    /uid
        Allows the user to specify server machine username.

    /pwd
        Allows the user to specify server machine password.

	/size cache-size
       Specifies the size(MB) of the cache to be created.

	/s server-name
       Specifies comma separated server name where NCache is installed and 'NCache service' is running.

OPTIONS

    /p port
       Specifies the port if the server channel is not using the default port.
       The default is 8251 for http and 8250 for tcp channels

    /evict-policy eviction-policy
    /e
        Specifies the eviction policy for cache items. Cached items will be
        cleaned from the cache according to the specified policy if the cache
        reaches its limit. Possible values are
            i.   Priority
            ii.  LFU
            iii. LRU (default)

    /ratio eviction-ratio
    /r
        Specifies the eviction ratio(Percentage) for cache items. Cached items will be
        cleaned from the cache according to the specified ratio if the cache
        reaches its limit. Default value is 5 (percent)

    /interval clean-interval
    /i
        Specifies the time interval(seconds) after which cache eviction is called.
        Default clean-interval is 15 (seconds)

    /topology topology-name
    /t
         Specifies the topology in case of clustered cache. Possible values are
             i.   local-cache (default)
             ii.  mirror
             iii. replicated
             iv.  partitioned
             iv.  partitioned-replicas-server

    /replication-strategy
    /rs
        Only in case of 'partition-replicas-server' being the topology, this specifies
        the replication strategy
            i.   async (default)
            ii.  sync

    /cluster-port
    /c
        Specifies the port of the server, at which server listens. Default is 7800

	/def-priority default-priority
    /d
        Specifies the default priority in case of priority based eviction policy is selected.

        Possible values are
            i.   high
            ii.  above-normal
            iii. normal (default)
            iv.  below-normal
            v.   low

    /nologo
        Suppresses display of the logo banner

    /?
	Show this help information.
"@
exit 1
}

$i=0;
while($i -lt $args.length)
{
	switch ($array[$i])
	{
		"/cacheid"
		{
			$cacheId=$array[$i+1];
			$i++;
			$bCacheId=$true;
		}
		"/s"
		{
			$servers=$array[$i+1];
			$cmd= $cmd +" /s "+ $servers;
			$i++;
			$bServers=$true;
		}
		"/p"
		{
			$cmd= $cmd + " " + "/p"+$array[$i+1];
			$i++;
		}
		"/size"
		{
			$cmd= $cmd +" /S "+$array[$i+1];
			$i++;
			$bSize=$true;
		}
		"/e"
		{
			$cmd= $cmd + " /e "+$array[$i+1];
			$i++;
		}
		"/r"
		{
			$cmd= $cmd + " /r "+$array[$i+1];
			$i++;
		}
		"/i"
		{
			$cmd= $cmd + " /i "+$array[$i+1];
			$i++;
		}
		"/t"
		{
			$topology=$array[$i+1];
			$cmd= $cmd + " /t "+$array[$i+1];
			$i++;
		}
		"/rs"
		{
			$cmd= $cmd + " /rs "+$array[$i+1];
			$i++;
		}
		"/c"
		{
			$cmd= $cmd + " /c "+$array[$i+1];
			$i++;
		}
		"/d"
		{
			$cmd= $cmd + " /d "+$array[$i+1];
			$i++;
		}
		"/uid"
		{
			$Server_Username=$array[$i+1];
			$i++;
			$bServer_Username=$true;
		}
		"/pwd"
		{
			$Server_Userpassword=$array[$i+1];
			$i++;
			$bServer_UserPassword=$true;
		}
		"/nologo"
		{
			$cmd= $cmd + " /nologo ";
			$i++;
		}
		default
		{
			$i++;
		}
	}
}

$cmd= $cacheID+$cmd;

if($bCacheId -eq $false)
{
    write-host "Argument '/cacheid' for cache-id is missing" -foregroundcolor  RED;
	exit 1;
}

if($bServer_Username -eq $false)
{
    write-host "Argument '/uid' for Server username is missing" -foregroundcolor  RED;
	exit 1;
}

if($bServer_UserPassword -eq $false)
{
    write-host "Argument '/pwd' for Server password is missing" -foregroundcolor  RED;
	exit 1;
}

if($bServers -eq $false)
{
	write-host "Argument '/s' for Server  is missing" -foregroundcolor  RED;
	exit 1;
}
if($bSize -eq $false)
{
	write-host "Argument '/size' for Cache Size is missing" -foregroundcolor  RED;
	exit 1;
}

Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*" -Force
$check=$servers -is [array]

if($check)
	{
	if ($topology -ne "local-cache")
	{
	 winrs -r:$server_name -u:$Server_UserName -p:$Server_UserPassword "Powershell createcache $cmd";
	 $i=1;
	 while($i -lt $servers.length)
	   	  {
		   $command=" addnode $cache_Id /e "+ $servers[0] + " /n " + $servers[$i]
		   winrs -r:$server_name -u:$Server_Username -p:$Server_Userpassword "Powershell $command";
		   $i++
		  }
	}
	else {"Topology can not be local-cache for a Cluster"; 	  }
	}
else{
     $command =" createcache $cmd"
	 winrs -r:$servers -u:$Server_Username -p:$Server_Userpassword "Powershell $command"
	}
" "


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Articles • WestTeam Robotics</title>
    <meta name="description" content="A collection of thoughts, inspiration, mistakes, and other minutia.">
    <meta name="keywords" content="">

	<meta name="twitter:title" content="Articles">
	<meta name="twitter:description" content="A collection of thoughts, inspiration, mistakes, and other minutia.">

	<meta name="twitter:card" content="summary">
	<meta name="twitter:image" content="//westteam.github.io/images/120x120.gif">

	<meta property="og:locale" content="en_US">
	<meta property="og:type" content="article">
	<meta property="og:title" content="Articles">
	<meta property="og:description" content="A collection of thoughts, inspiration, mistakes, and other minutia.">
	<meta property="og:url" content="//westteam.github.io/articles/">
	<meta property="og:site_name" content="WestTeam Robotics">

    <link rel="canonical" href="//westteam.github.io/articles/">

    <link href="//westteam.github.io/atom.xml" type="application/atom+xml" rel="alternate" title="WestTeam Robotics Atom Feed">
    <link href="//westteam.github.io/sitemap.xml" type="application/xml" rel="sitemap" title="Sitemap">

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="cleartype" content="on">

    <link rel="stylesheet" href="//westteam.github.io/css/main.css">

    WestTeam Robotics

WestTeam Robotics

Blog

Robots

Sponsors

About

WestTeam Robotics Table of Contents

Blog

Everything you need to know to get started with Skinny Bones and Jekyll.

Robots

Examples of long form posts.

Sponsors

Examples of media posts perfect for showcasing work, photographs, etc.

About

All about Skinny Bones for Jekyll.

<button type="button" id="js-menu-trigger" class="sliding-menu-button lines-button x2" role="button" aria-label="Toggle Navigation">

</button>

Articles

A collection of thoughts, inspiration, mistakes, and other minutia.

<time datetime="2014-06-23" itemprop="datePublished">June 23, 2014</time>

Author Override

A post to test author overrides using a data file.

<time datetime="2014-06-01" itemprop="datePublished">June 01, 2014</time>

Video Post Test

A post with a YouTube video.

<time datetime="2014-05-30" itemprop="datePublished">May 30, 2014</time>

Image Grids

Demoing the various thumbnail grid styles.

<time datetime="2014-02-17" itemprop="datePublished">February 17, 2014</time>

Welcome to Jekyll!

You'll find this post in your _posts directory - edit this post and re-build (or run with the -w switch) to see your changes!
To add new posts, simply add a ...

<time datetime="2013-05-23" itemprop="datePublished">May 23, 2013</time>

Post with Large Feature Image and Text

Custom written post descriptions are the way to go... if you're not lazy.

<time datetime="2013-05-22" itemprop="datePublished">May 22, 2013</time>

A Post with Images

Examples and code for displaying images in posts.

<time datetime="2012-05-22" itemprop="datePublished">May 22, 2012</time>

Testing Readability with a Bunch of Text

A ton of text to test readability.

<time datetime="2011-03-10" itemprop="datePublished">March 10, 2011</time>

Sample Post Style Guide

Below is just about everything you'll need to style in the theme. Check the source code to see the many embedded elements within paragraphs.

Home

Getting Started

About

Terms

© 2019 WestTeam Robotics.


text:
package org.gradle.model.internal.registry;

import org.gradle.model.internal.core.ModelPromise;
import org.gradle.model.internal.core.ModelReference;
import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor;

abstract class BinderCreationListener extends ModelCreationListener {
    final ModelRuleDescriptor descriptor;
    final ModelReference<?> reference;
    final boolean writable;

    public BinderCreationListener(ModelRuleDescriptor descriptor, ModelReference<?> reference, boolean writable) {
        this.descriptor = descriptor;
        this.reference = reference;
        this.writable = writable;
    }

    boolean isTypeCompatible(ModelPromise promise) {
        return writable ? promise.canBeViewedAsWritable(reference.getType()) : promise.canBeViewedAsReadOnly(reference.getType());
    }

    @Override
    public String toString() {
        return "ModelCreationListener{parent=" + matchParent() + ", path=" + matchPath() + ", scope=" + matchScope() + ", type=" + matchType() + "class=" + getClass().getSimpleName() + '}';
    }
}


text:
import { makeStyles } from '@material-ui/core/styles';
import NavLink from 'components/NavLink';
import { c } from 'ttag';

import logo from 'components/Tutorial/images/logo.svg';

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    width: '100%',
    background: theme.palette.secondary[500],
  },
  top: {
    padding: '63px 0 36px',
  },
  logo: {
    width: 367,

    [theme.breakpoints.down('md')]: {
      width: 300,
    },
  },
  tabWrapper: {
    display: 'flex',
  },
  tab: {
    fontSize: 18,
    fontWeight: 500,
    lineHeight: 1.56,
    letterSpacing: 0.5,
    textDecoration: 'none',
    color: 'white',
    padding: '16px 16px 12px',
    borderBottom: `4px solid ${theme.palette.secondary[500]}`,
    cursor: 'pointer',
  },
  activeTab: {
    color: theme.palette.primary[500],
    borderColor: theme.palette.primary[500],
  },
}));

const TutorialHeader = () => {
  const classes = useStyles();

  return (

        <NavLink
          href="/about"
          className={classes.tab}
          activeClassName={classes.activeTab}
        >
          {c('Tutorial').t`What is Cofacts?`}
        </NavLink>
        <NavLink
          href="/tutorial"
          className={classes.tab}
          activeClassName={classes.activeTab}
        >
          {c('Tutorial').t`How to use it?`}
        </NavLink>

  );
};

export default TutorialHeader;


text:
package io.prodrink.catalog.generated.dto;

public final class AdminDrinkDtoOuter {
  private AdminDrinkDtoOuter() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }

  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions(
        (com.google.protobuf.ExtensionRegistryLite) registry);
  }
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_catalog_AdminServiceCallResponse_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_catalog_AdminServiceCallResponse_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_catalog_DeletionRequest_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_catalog_DeletionRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_catalog_DrinkCreationRequest_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_catalog_DrinkCreationRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_catalog_DrinkUpdateRequest_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_catalog_DrinkUpdateRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_catalog_CategoryCreationRequest_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_catalog_CategoryCreationRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_catalog_CategoryUpdateRequest_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_catalog_CategoryUpdateRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_catalog_PropertyCreationRequest_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_catalog_PropertyCreationRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_catalog_PropertyUpdateRequest_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_catalog_PropertyUpdateRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_catalog_PropertyTypeCreationRequest_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_catalog_PropertyTypeCreationRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_catalog_PropertyTypeUpdateRequest_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_catalog_PropertyTypeUpdateRequest_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static  com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\n\027catalog/admin-dto.proto\022\007catalog\032\024cata" +
      "log/domain.proto\"\032\n\030AdminServiceCallResp" +
      "onse\"$\n\017DeletionRequest\022\021\n\tentity_id\030\001 \001" +
      "(\005\"x\n\024DrinkCreationRequest\022\014\n\004name\030\001 \001(\t" +
      "\022\023\n\013category_id\030\002 \001(\005\022\024\n\014property_ids\030\003 " +
      "\003(\005\022\022\n\nimage_urls\030\004 \003(\t\022\023\n\013description\030\005" +
      " \001(\t\"\210\001\n\022DrinkUpdateRequest\022\020\n\010drink_id\030" +
      "\001 \001(\005\022\014\n\004name\030\002 \001(\t\022\023\n\013category_id\030\003 \001(\005" +
      "\022\024\n\014property_ids\030\004 \003(\005\022\022\n\nimage_urls\030\005 \003" +
      "(\t\022\023\n\013description\030\006 \001(\t\"\205\001\n\027CategoryCrea",
      "tionRequest\022\014\n\004name\030\001 \001(\t\022\032\n\022parent_cate" +
      "gory_id\030\002 \001(\005\022-\n\016property_types\030\003 \003(\0132\025." +
      "catalog.PropertyType\022\021\n\timage_url\030\004 \001(\t\"" +
      "\230\001\n\025CategoryUpdateRequest\022\023\n\013category_id" +
      "\030\001 \001(\005\022\014\n\004name\030\002 \001(\t\022\032\n\022parent_category_" +
      "id\030\003 \001(\005\022-\n\016property_types\030\004 \003(\0132\025.catal" +
      "og.PropertyType\022\021\n\timage_url\030\005 \001(\t\"T\n\027Pr" +
      "opertyCreationRequest\022\020\n\010drink_id\030\001 \001(\005\022" +
      "\030\n\020property_type_id\030\002 \001(\005\022\r\n\005value\030\003 \001(\t" +
      "\";\n\025PropertyUpdateRequest\022\023\n\013property_id",
      "\030\001 \001(\005\022\r\n\005value\030\002 \001(\t\"b\n\033PropertyTypeCre" +
      "ationRequest\022\023\n\013category_id\030\001 \001(\005\022\014\n\004nam" +
      "e\030\002 \001(\t\022 \n\004type\030\003 \001(\0162\022.catalog.ValueTyp" +
      "e\"z\n\031PropertyTypeUpdateRequest\022\030\n\020proper" +
      "ty_type_id\030\001 \001(\005\022\023\n\013category_id\030\002 \001(\005\022\014\n" +
      "\004name\030\003 \001(\t\022 \n\004type\030\004 \001(\0162\022.catalog.Valu" +
      "eTypeBL\n!io.prodrink.catalog.generated.d" +
      "toB\022AdminDrinkDtoOuterP\001\252\002\020prodrink.cata" +
      "logb\006proto3"
    };
    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
        new com.google.protobuf.Descriptors.FileDescriptor.    InternalDescriptorAssigner() {
          public com.google.protobuf.ExtensionRegistry assignDescriptors(
              com.google.protobuf.Descriptors.FileDescriptor root) {
            descriptor = root;
            return null;
          }
        };
    com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
          io.prodrink.catalog.generated.domain.DrinkOuter.getDescriptor(),
        }, assigner);
    internal_static_catalog_AdminServiceCallResponse_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_catalog_AdminServiceCallResponse_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_catalog_AdminServiceCallResponse_descriptor,
        new java.lang.String[] { });
    internal_static_catalog_DeletionRequest_descriptor =
      getDescriptor().getMessageTypes().get(1);
    internal_static_catalog_DeletionRequest_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_catalog_DeletionRequest_descriptor,
        new java.lang.String[] { "EntityId", });
    internal_static_catalog_DrinkCreationRequest_descriptor =
      getDescriptor().getMessageTypes().get(2);
    internal_static_catalog_DrinkCreationRequest_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_catalog_DrinkCreationRequest_descriptor,
        new java.lang.String[] { "Name", "CategoryId", "PropertyIds", "ImageUrls", "Description", });
    internal_static_catalog_DrinkUpdateRequest_descriptor =
      getDescriptor().getMessageTypes().get(3);
    internal_static_catalog_DrinkUpdateRequest_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_catalog_DrinkUpdateRequest_descriptor,
        new java.lang.String[] { "DrinkId", "Name", "CategoryId", "PropertyIds", "ImageUrls", "Description", });
    internal_static_catalog_CategoryCreationRequest_descriptor =
      getDescriptor().getMessageTypes().get(4);
    internal_static_catalog_CategoryCreationRequest_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_catalog_CategoryCreationRequest_descriptor,
        new java.lang.String[] { "Name", "ParentCategoryId", "PropertyTypes", "ImageUrl", });
    internal_static_catalog_CategoryUpdateRequest_descriptor =
      getDescriptor().getMessageTypes().get(5);
    internal_static_catalog_CategoryUpdateRequest_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_catalog_CategoryUpdateRequest_descriptor,
        new java.lang.String[] { "CategoryId", "Name", "ParentCategoryId", "PropertyTypes", "ImageUrl", });
    internal_static_catalog_PropertyCreationRequest_descriptor =
      getDescriptor().getMessageTypes().get(6);
    internal_static_catalog_PropertyCreationRequest_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_catalog_PropertyCreationRequest_descriptor,
        new java.lang.String[] { "DrinkId", "PropertyTypeId", "Value", });
    internal_static_catalog_PropertyUpdateRequest_descriptor =
      getDescriptor().getMessageTypes().get(7);
    internal_static_catalog_PropertyUpdateRequest_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_catalog_PropertyUpdateRequest_descriptor,
        new java.lang.String[] { "PropertyId", "Value", });
    internal_static_catalog_PropertyTypeCreationRequest_descriptor =
      getDescriptor().getMessageTypes().get(8);
    internal_static_catalog_PropertyTypeCreationRequest_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_catalog_PropertyTypeCreationRequest_descriptor,
        new java.lang.String[] { "CategoryId", "Name", "Type", });
    internal_static_catalog_PropertyTypeUpdateRequest_descriptor =
      getDescriptor().getMessageTypes().get(9);
    internal_static_catalog_PropertyTypeUpdateRequest_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_catalog_PropertyTypeUpdateRequest_descriptor,
        new java.lang.String[] { "PropertyTypeId", "CategoryId", "Name", "Type", });
    io.prodrink.catalog.generated.domain.DrinkOuter.getDescriptor();
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
@class BaseResponse, NSMutableArray;

@interface BatchGetHeadImgResponse : WXPBGeneratedMessage
{
}

+ (void)initialize;

// Remaining properties
@property(retain, nonatomic) BaseResponse *baseResponse; // @dynamic baseResponse;
@property(nonatomic) unsigned int count; // @dynamic count;
@property(retain, nonatomic) NSMutableArray *imgPairList; // @dynamic imgPairList;

@end


text:
from django import http
from django.conf import settings
from django.shortcuts import redirect, render
from django.contrib.auth.decorators import login_required

from jsonview.decorators import json_view

from airmozilla.base import mozillians

def debugger__(request):  # pragma: no cover
    r = http.HttpResponse()
    r.write('BROWSERID_AUDIENCES=%r\n' % settings.BROWSERID_AUDIENCES)
    r.write('Todays date: 2014-05-21 14:02 PST\n')
    r.write('Request secure? %s\n' % request.is_secure())
    r['Content-Type'] = 'text/plain'
    if request.session.test_cookie_worked():
        r.write('Test cookie worked.\n')
        request.session.delete_test_cookie()
    else:
        request.session.set_test_cookie()
        r.write('Set a test cookie. Refresh to see if it stuck\n')
    return r

def god_mode(request):
    if not (settings.DEBUG and settings.GOD_MODE):
        raise http.Http404()

    if request.method == 'POST':
        from django.contrib.auth.models import User
        user = User.objects.get(email__iexact=request.POST['email'])
        from django.contrib import auth
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        auth.login(request, user)
        return redirect('/')

    context = {}
    return render(request, 'main/god_mode.html', context)

def edgecast_smil(request):
    context = {}
    for key, value in request.GET.items():
        context[key] = value
    response = render(request, 'main/edgecast_smil.xml', context)
    response['Content-Type'] = 'application/smil'
    response['Access-Control-Allow-Origin'] = '*'
    return response

@login_required
@json_view
def curated_groups_autocomplete(request):
    if 'q' not in request.GET:
        return http.HttpResponseBadRequest('q')
    q = request.GET.get('q', '').strip()
    if not q:
        return {'groups': []}

    all_ = mozillians.get_all_groups(name=q)
    ids = [x['id'] for x in all_]
    all_.extend([
        x for x in mozillians.get_all_groups(name_search=q)
        if x['id'] not in ids
    ])

    def describe_group(group):
        if group['member_count'] == 1:
            return '%s (1 member)' % (group['name'],)
        else:
            return (
                '%s (%s members)' % (group['name'], group['member_count'])
            )

    groups = [
        (x['name'], describe_group(x))
        for x in all_
    ]
    # naively sort by how good the match is
    groups.sort(key=lambda x: x[0].lower().find(q.lower()))
    return {'groups': groups}


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

<title>Position.Coordinates (GWT Javadoc)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Deprecated

Help

GWT 2.8.0-rc1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.gwt.geolocation.client

Interface Position.Coordinates

All Known Implementing Classes:

PositionImpl.CoordinatesImpl

Enclosing interface:

Position

@SingleJsoImpl(value=PositionImpl.CoordinatesImpl.class)
public static interface Position.Coordinates

Represents position reported by the browser.

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

double
getAccuracy()

Returns the estimated accuracy reported by the browser, in meters.

java.lang.Double
getAltitude()

Returns the altitude reported by the browser, in meters, above the reference
 ellipsoid, or null if the browser did not report an
 altitude.

java.lang.Double
getAltitudeAccuracy()

Returns the estimated accuracy of the altitude reported by the browser,
 in meters, or null if the browser did not report an
 accuracy.

java.lang.Double
getHeading()

Returns the heading, in degrees from due north, reported by the browser,
 based on previous calls to get the user's position, or null
 if the browser did not report a heading.

double
getLatitude()

Returns the decimal latitude reported by the browser.

double
getLongitude()

Returns the decimal longitude reported by the browser.

java.lang.Double
getSpeed()

Returns the speed, in meters/second, reported by the browser, based on
 previous calls to get the user's position, or null if the
 browser did not report a speed.

Method Detail

getAccuracy

double getAccuracy()

Returns the estimated accuracy reported by the browser, in meters.

getAltitude

java.lang.Double getAltitude()

Returns the altitude reported by the browser, in meters, above the reference
 ellipsoid, or null if the browser did not report an
 altitude.

getAltitudeAccuracy

java.lang.Double getAltitudeAccuracy()

Returns the estimated accuracy of the altitude reported by the browser,
 in meters, or null if the browser did not report an
 accuracy.

getHeading

java.lang.Double getHeading()

Returns the heading, in degrees from due north, reported by the browser,
 based on previous calls to get the user's position, or null
 if the browser did not report a heading.

getLatitude

double getLatitude()

Returns the decimal latitude reported by the browser.

getLongitude

double getLongitude()

Returns the decimal longitude reported by the browser.

getSpeed

java.lang.Double getSpeed()

Returns the speed, in meters/second, reported by the browser, based on
 previous calls to get the user's position, or null if the
 browser did not report a speed.

Skip navigation links

Overview

Package

Class

Use

Deprecated

Help

GWT 2.8.0-rc1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method