text:
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Streams;
using Orleans.Streaming.EventHubs;
using Orleans.Configuration;

namespace Orleans.ServiceBus.Providers
{
    /// <summary>
    /// This class stores EventHub partition checkpointer information (a partition offset) in azure table storage.
    /// </summary>
    public class EventHubCheckpointer : IStreamQueueCheckpointer<string>
    {
        private readonly AzureTableDataManager<EventHubPartitionCheckpointEntity> dataManager;
        private readonly TimeSpan persistInterval;

        private EventHubPartitionCheckpointEntity entity;
        private Task inProgressSave;
        private DateTime? throttleSavesUntilUtc;

        /// <summary>
        /// Indicates if a checkpoint exists
        /// </summary>
        public bool CheckpointExists => entity != null && entity.Offset != EventHubConstants.StartOfStream;

        /// <summary>
        /// Factory function that creates and initializes the checkpointer
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="streamProviderName"></param>
        /// <param name="partition"></param>
        /// <param name="loggerFactory"></param>
        /// <returns></returns>
        public static async Task<IStreamQueueCheckpointer<string>> Create(EventHubStreamOptions options, string streamProviderName, string partition, ILoggerFactory loggerFactory)
        {
            var checkpointer = new EventHubCheckpointer(options, streamProviderName, partition, loggerFactory);
            await checkpointer.Initialize();
            return checkpointer;
        }

        private EventHubCheckpointer(EventHubStreamOptions options, string streamProviderName, string partition, ILoggerFactory loggerFactory)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (string.IsNullOrWhiteSpace(streamProviderName))
            {
                throw new ArgumentNullException(nameof(streamProviderName));
            }
            if (string.IsNullOrWhiteSpace(partition))
            {
                throw new ArgumentNullException(nameof(partition));
            }
            persistInterval = options.CheckpointPersistInterval;
            dataManager = new AzureTableDataManager<EventHubPartitionCheckpointEntity>(options.CheckpointTableName, options.CheckpointConnectionString, loggerFactory);
            entity = EventHubPartitionCheckpointEntity.Create(streamProviderName, options.CheckpointNamespace, partition);
        }

        private Task Initialize()
        {
            return dataManager.InitTableAsync();
        }

        /// <summary>
        /// Loads a checkpoint
        /// </summary>
        /// <returns></returns>
        public async Task<string> Load()
        {
            Tuple<EventHubPartitionCheckpointEntity, string> results =
                await dataManager.ReadSingleTableEntryAsync(entity.PartitionKey, entity.RowKey);
            if (results != null)
            {
                entity = results.Item1;
            }
            return entity.Offset;
        }

        /// <summary>
        /// Updates the checkpoint.  This is a best effort.  It does not always update the checkpoint.
        /// </summary>
        /// <param name="offset"></param>
        /// <param name="utcNow"></param>
        public void Update(string offset, DateTime utcNow)
        {
            // if offset has not changed, do nothing
            if (string.Compare(entity.Offset, offset, StringComparison.Ordinal) == 0)
            {
                return;
            }

            // if we've saved before but it's not time for another save or the last save operation has not completed, do nothing
            if (throttleSavesUntilUtc.HasValue && (throttleSavesUntilUtc.Value > utcNow || !inProgressSave.IsCompleted))
            {
                return;
            }

            entity.Offset = offset;
            throttleSavesUntilUtc = utcNow + persistInterval;
            inProgressSave = dataManager.UpsertTableEntryAsync(entity);
            inProgressSave.Ignore();
        }
    }
}


text:
package com.google.cloud.dialogflow.v2;

import com.google.api.core.BetaApi;
import com.google.cloud.dialogflow.v2.ContextsGrpc.ContextsImplBase;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.Empty;
import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import javax.annotation.Generated;

@BetaApi
@Generated("by gapic-generator-java")
public class MockContextsImpl extends ContextsImplBase {
  private List<AbstractMessage> requests;
  private Queue<Object> responses;

  public MockContextsImpl() {
    requests = new ArrayList<>();
    responses = new LinkedList<>();
  }

  public List<AbstractMessage> getRequests() {
    return requests;
  }

  public void addResponse(AbstractMessage response) {
    responses.add(response);
  }

  public void setResponses(List<AbstractMessage> responses) {
    this.responses = new LinkedList<Object>(responses);
  }

  public void addException(Exception exception) {
    responses.add(exception);
  }

  public void reset() {
    requests = new ArrayList<>();
    responses = new LinkedList<>();
  }

  @Override
  public void listContexts(
      ListContextsRequest request, StreamObserver<ListContextsResponse> responseObserver) {
    Object response = responses.poll();
    if (response instanceof ListContextsResponse) {
      requests.add(request);
      responseObserver.onNext(((ListContextsResponse) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method ListContexts, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  ListContextsResponse.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void getContext(GetContextRequest request, StreamObserver<Context> responseObserver) {
    Object response = responses.poll();
    if (response instanceof Context) {
      requests.add(request);
      responseObserver.onNext(((Context) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method GetContext, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  Context.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void createContext(
      CreateContextRequest request, StreamObserver<Context> responseObserver) {
    Object response = responses.poll();
    if (response instanceof Context) {
      requests.add(request);
      responseObserver.onNext(((Context) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method CreateContext, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  Context.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void updateContext(
      UpdateContextRequest request, StreamObserver<Context> responseObserver) {
    Object response = responses.poll();
    if (response instanceof Context) {
      requests.add(request);
      responseObserver.onNext(((Context) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method UpdateContext, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  Context.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void deleteContext(DeleteContextRequest request, StreamObserver<Empty> responseObserver) {
    Object response = responses.poll();
    if (response instanceof Empty) {
      requests.add(request);
      responseObserver.onNext(((Empty) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method DeleteContext, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  Empty.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void deleteAllContexts(
      DeleteAllContextsRequest request, StreamObserver<Empty> responseObserver) {
    Object response = responses.poll();
    if (response instanceof Empty) {
      requests.add(request);
      responseObserver.onNext(((Empty) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method DeleteAllContexts, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  Empty.class.getName(),
                  Exception.class.getName())));
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
module Comparateur
  VERSION = "2.0.2"
end


text:
var http = require('http');
var url = require('url');
var contentType = require('content-type');
function http_request(request, response)
{
	contentType.format({type : "application/json"});
	var requestData = url.parse(request.url, true);
	response.end(JSON.stringify(requestData.query,null , 2));
}
http.createServer(http_request).listen(8222, '127.0.0.1');


text:
/*
 * Description:
 *     What is this file about?
 *
 * Revision history:
 *     Feb., 2016, @imzhenyu (Zhenyu Guo), done in Tron project and copied here
 *     xxxx-xx-xx, author, fix bug about xxx
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace rDSN.Tron.Utility
{
    public class QueryableObjects<T> : IOrderedQueryable<T>
    {
        #region Constructors
        /// <summary>
        /// This constructor is called by the client to create the data source.
        /// </summary>
        public QueryableObjects(QueryProvider provider)
        {
            Provider = provider;
            Expression = Expression.Constant(this);
        }

        /// <summary>
        /// This constructor is called by Provider.CreateQuery().
        /// </summary>
        /// <param name="expression"></param>
        public QueryableObjects(QueryProvider provider, Expression expression)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            if (!typeof(IQueryable<T>).IsAssignableFrom(expression.Type))
            {
                throw new ArgumentOutOfRangeException("expression");
            }

            Provider = provider;
            Expression = expression;
        }
        #endregion

        #region Properties

        public IQueryProvider Provider { get; private set; }
        public Expression Expression { get; private set; }

        public Type ElementType => typeof(T);

        #endregion

        #region Enumerators
        public IEnumerator<T> GetEnumerator()
        {
            return (Provider.Execute<IEnumerable<T>>(Expression)).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return (Provider.Execute<IEnumerable>(Expression)).GetEnumerator();
        }
        #endregion
    }

    public abstract class QueryProvider : IQueryProvider
    {
        public abstract object Execute(Expression expression, bool IsSymbols);

        public IQueryable CreateQuery(Expression expression)
        {
            var elementType = TypeHelper.GetElementType(expression.Type);
            try
            {
                return (IQueryable)Activator.CreateInstance(typeof(QueryableObjects<>).MakeGenericType(elementType), this, expression);
            }
            catch (TargetInvocationException tie)
            {
                throw tie.InnerException;
            }
        }

        public IQueryable<TResult> CreateQuery<TResult>(Expression expression)
        {
            return new QueryableObjects<TResult>(this, expression);
        }

        public object Execute(Expression expression)
        {
            return Execute(expression, false);
        }

        public TResult Execute<TResult>(Expression expression)
        {
            return (TResult)Execute(expression, typeof(TResult).IsSymbols());
        }
    }
}


text:
package org.elasticsearch.xpack.vectors.query;

import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.script.ScoreScript;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;

public class ScoreScriptUtils {

    public static class DenseVectorFunction {
        final ScoreScript scoreScript;
        final float[] queryVector;
        final DenseVectorScriptDocValues docValues;

        public DenseVectorFunction(ScoreScript scoreScript,
                                   List<Number> queryVector,
                                   String field) {
            this(scoreScript, queryVector, field, false);
        }

        /**
         * Constructs a dense vector function.
         *
         * @param scoreScript The script in which this function was referenced.
         * @param queryVector The query vector.
         * @param normalizeQuery Whether the provided query should be normalized to unit length.
         */
        public DenseVectorFunction(ScoreScript scoreScript,
                                   List<Number> queryVector,
                                   String field,
                                   boolean normalizeQuery) {
            this.scoreScript = scoreScript;
            this.docValues = (DenseVectorScriptDocValues) scoreScript.getDoc().get(field);

            if (docValues.dims() != queryVector.size()){
                throw new IllegalArgumentException("The query vector has a different number of dimensions [" +
                    queryVector.size() + "] than the document vectors [" + docValues.dims() + "].");
            }

            this.queryVector = new float[queryVector.size()];
            double queryMagnitude = 0.0;
            for (int i = 0; i < queryVector.size(); i++) {
                float value = queryVector.get(i).floatValue();
                this.queryVector[i] = value;
                queryMagnitude += value * value;
            }
            queryMagnitude = Math.sqrt(queryMagnitude);

            if (normalizeQuery) {
                for (int dim = 0; dim < this.queryVector.length; dim++) {
                    this.queryVector[dim] /= queryMagnitude;
                }
            }
        }

        BytesRef getEncodedVector() {
            try {
                docValues.setNextDocId(scoreScript._getDocId());
            } catch (IOException e) {
                throw ExceptionsHelper.convertToElastic(e);
            }
            BytesRef vector = docValues.getEncodedValue();
            if (vector == null) {
                throw new IllegalArgumentException("A document doesn't have a value for a vector field!");
            }
            return vector;
        }
    }

    // Calculate l1 norm (Manhattan distance) between a query's dense vector and documents' dense vectors
    public static final class L1Norm extends DenseVectorFunction {

        public L1Norm(ScoreScript scoreScript, List<Number> queryVector, String field) {
            super(scoreScript, queryVector, field);
        }

        public double l1norm() {
            BytesRef vector = getEncodedVector();
            ByteBuffer byteBuffer = ByteBuffer.wrap(vector.bytes, vector.offset, vector.length);

            double l1norm = 0;

            for (float queryValue : queryVector) {
                l1norm += Math.abs(queryValue - byteBuffer.getFloat());
            }
            return l1norm;
        }
    }

    // Calculate l2 norm (Euclidean distance) between a query's dense vector and documents' dense vectors
    public static final class L2Norm extends DenseVectorFunction {

        public L2Norm(ScoreScript scoreScript, List<Number> queryVector, String field) {
            super(scoreScript, queryVector, field);
        }

        public double l2norm() {
            BytesRef vector = getEncodedVector();
            ByteBuffer byteBuffer = ByteBuffer.wrap(vector.bytes, vector.offset, vector.length);

            double l2norm = 0;
            for (float queryValue : queryVector) {
                double diff = queryValue - byteBuffer.getFloat();
                l2norm += diff * diff;
            }
            return Math.sqrt(l2norm);
        }
    }

    // Calculate a dot product between a query's dense vector and documents' dense vectors
    public static final class DotProduct extends DenseVectorFunction {

        public DotProduct(ScoreScript scoreScript, List<Number> queryVector, String field) {
            super(scoreScript, queryVector, field);
        }

        public double dotProduct() {
            BytesRef vector = getEncodedVector();
            ByteBuffer byteBuffer = ByteBuffer.wrap(vector.bytes, vector.offset, vector.length);

            double dotProduct = 0;
            for (float queryValue : queryVector) {
                dotProduct += queryValue * byteBuffer.getFloat();
            }
            return dotProduct;
        }
    }

    // Calculate cosine similarity between a query's dense vector and documents' dense vectors
    public static final class CosineSimilarity extends DenseVectorFunction {

        public CosineSimilarity(ScoreScript scoreScript, List<Number> queryVector, String field) {
            super(scoreScript, queryVector, field, true);
        }

        public double cosineSimilarity() {
            BytesRef vector = getEncodedVector();
            ByteBuffer byteBuffer = ByteBuffer.wrap(vector.bytes, vector.offset, vector.length);
            double dotProduct = 0.0;
            for (float queryValue : queryVector) {
                dotProduct += queryValue * byteBuffer.getFloat();
            }
            return dotProduct / docValues.getMagnitude();
        }
    }
}


text:
from __future__ import unicode_literals

from . import index
from . import channel
from . import article

__all__ = ['index', 'channel', 'article']


text:
<?xml version="1.0"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:so="http://purl.obolibrary.org/obo/" xmlns="http://sbols.org/v1#"
   >

   <Collection rdf:about="http://example.com/collection1">
      <displayId>Coll1</displayId>
      <name>Collection1</name>
      <description>A collection may contain multiple components</description>
      <component>
         <DnaComponent rdf:about="http://example.com/dc1">
            <displayId>DC1</displayId>
            <name>DnaComponent1</name>
            <dnaSequence>
               <DnaSequence rdf:about="http://example.com/ds1">
                  <nucleotides>tccctatcagtgat</nucleotides>
               </DnaSequence>
            </dnaSequence>
         </DnaComponent>
      </component>
      <component>
         <DnaComponent rdf:about="http://example.com/dc2">
            <displayId>DC2</displayId>
            <name>DnaComponent2</name>
         </DnaComponent>
      </component>
   </Collection>

</rdf:RDF>


text:
package org.matt1.http.utils;

/**
 *

 * HTTP Response codes
 *

 * @author Matt
 *
 */
public enum HttpStatus {

	/** Ok */
	HTTP200("200 - OK"),

	/** Bad request */
	HTTP400("400 - Bad Request"),

	/** Unauthorised */
	HTTP401("401 - Unauthorised"),

	/** Forbidden */
	HTTP403("402 - Forbidden"),

	/** Not found */
	HTTP404("404 - Not Found"),

	/** Method not allowed */
	HTTP405("405 - Method Not Allowed"),

	/** I'm a teapot - yep, really {@link http://tools.ietf.org/html/rfc2324} */
	HTTP418("418 - I'm a teapot"),

	/** Internal server error */
	HTTP500("500 - Internal Server Error"),

	/** Not implemented */
	HTTP501("501 - Not Implemented"),

	/** Service unavailable */
	HTTP503("503 - Service unavailable");

	private String mDescription;

	HttpStatus(String pDescription) {
		mDescription = pDescription;
	}

	/**
	 *

	 * Gets the textual description of a status code
	 *

	 * @return
	 */
	public String getDescription() {
		return mDescription;
	}

}


text:
from lib.common import helpers

class Module:

    def __init__(self, mainMenu, params=[]):

        self.info = {
            'Name': 'Invoke-Kerberoast',

            'Author': ['@harmj0y', '@machosec'],

            'Description': ('Requests kerberos tickets for all users with a non-null service principal name (SPN) and extracts them into a format ready for John or Hashcat.'),

            'Background' : True,

            'OutputExtension' : None,

            'NeedsAdmin' : False,

            'OpsecSafe' : True,

            'Language' : 'powershell',

            'MinLanguageVersion' : '2',

            'Comments': [
                'https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/',
                'https://gist.github.com/HarmJ0y/53a837fce877e32e18d78acbb08c8fe9'
            ]
        }

        # any options needed by the module, settable during runtime
        self.options = {
            # format:
            #   value_name : {description, required, default_value}
            'Agent' : {
                'Description'   :   'Agent to run module on.',
                'Required'      :   True,
                'Value'         :   ''
            },
            'Identity' : {
                'Description'   :   'Specific SamAccountName, DistinguishedName, SID, or GUID to kerberoast.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'AdminCount' : {
                'Description'   :   'Kerberoast privileged accounts protected by AdminSDHolder.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'Domain' : {
                'Description'   :   'Specifies the domain to use for the query, defaults to the current domain.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'LDAPFilter' : {
                'Description'   :   'Specifies an LDAP query string that is used to filter Active Directory objects.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'SearchBase' : {
                'Description'   :   'The LDAP source to search through, e.g. "LDAP://OU=secret,DC=testlab,DC=local".',
                'Required'      :   False,
                'Value'         :   ''
            },
            'Server' : {
                'Description'   :   'Specifies an Active Directory server (domain controller) to bind to.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'SearchScope' : {
                'Description'   :   'Specifies the scope to search under, Base/OneLevel/Subtree (default of Subtree).',
                'Required'      :   False,
                'Value'         :   ''
            },
            'OutputFormat' : {
                'Description'   :   "Either 'John' for John the Ripper style hash formatting, or 'Hashcat' for Hashcat format.",
                'Required'      :   False,
                'Value'         :   'John'
            }

        }

        # save off a copy of the mainMenu object to access external functionality
        #   like listeners/agent handlers/etc.
        self.mainMenu = mainMenu

        for param in params:
            # parameter format is [Name, Value]
            option, value = param
            if option in self.options:
                self.options[option]['Value'] = value

    def generate(self, obfuscate=False, obfuscationCommand=""):

        moduleName = self.info['Name']

        # read in the common powerview.ps1 module source code
        moduleSource = self.mainMenu.installPath + "/data/module_source/credentials/Invoke-Kerberoast.ps1"
        if obfuscate:
            helpers.obfuscate_module(moduleSource=moduleSource, obfuscationCommand=obfuscationCommand)
            moduleSource = moduleSource.replace("module_source", "obfuscated_module_source")
        try:
            f = open(moduleSource, 'r')
        except:
            print helpers.color("[!] Could not read module source path at: " + str(moduleSource))
            return ""

        moduleCode = f.read()
        f.close()

        script = moduleCode
        scriptEnd = "\nInvoke-Kerberoast "

        for option,values in self.options.iteritems():
            if option.lower() != "agent":
                if values['Value'] and values['Value'] != '':
                    if values['Value'].lower() == "true":
                        # if we're just adding a switch
                        scriptEnd += " -" + str(option)
                    else:
                        scriptEnd += " -" + str(option) + " " + str(values['Value'])

        scriptEnd += '| fl | Out-String | %{$_ + \"`n\"};"`n'+str(moduleName)+' completed!"'
        if obfuscate:
            scriptEnd = helpers.obfuscate(self.mainMenu.installPath, psScript=scriptEnd, obfuscationCommand=obfuscationCommand)
        script += scriptEnd
        return script


text:
package com.vinitello.model;

public interface ModelNPC extends ModelEntity {

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature
{
    public partial class ChangeSignatureTests : AbstractChangeSignatureTests
    {
        [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
        public async Task AddOptionalParameter_ToConstructor()
        {
            var markup = @"
class B
{
    public B() : this(1) { }
    public B$$(int a)
    {
        var q = new B(1);
    }
}

class D : B
{
    public D() : base(1) { }
}";
            var updatedSignature = new[] {
                new AddedParameterOrExistingIndex(0),
                AddedParameterOrExistingIndex.CreateAdded("System.Int32", "x", CallSiteKind.Value, callSiteValue: "100", isRequired: false, defaultValue: "10"),
                AddedParameterOrExistingIndex.CreateAdded("System.Int32", "y", CallSiteKind.Omitted, isRequired: false, defaultValue: "11"),
                AddedParameterOrExistingIndex.CreateAdded("System.Int32", "z", CallSiteKind.Value, callSiteValue: "102", isRequired: false, defaultValue: "12")};
            var updatedCode = @"
class B
{
    public B() : this(1, 100, z: 102) { }
    public B(int a, int x = 10, int y = 11, int z = 12)
    {
        var q = new B(1, 100, z: 102);
    }
}

class D : B
{
    public D() : base(1, 100, z: 102) { }
}";

            await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
        }

        [WorkItem(44126, "https://github.com/dotnet/roslyn/issues/44126")]
        [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
        public async Task AddOptionalParameter_ToConstructor_ImplicitObjectCreation()
        {
            var markup = @"
class B
{
    public B() : this(1) { }
    public B$$(int a)
    {
        B q = new(1);
    }
}

class D : B
{
    public D() : base(1) { }
}";
            var updatedSignature = new[] {
                new AddedParameterOrExistingIndex(0),
                AddedParameterOrExistingIndex.CreateAdded("System.Int32", "x", CallSiteKind.Value, callSiteValue: "100", isRequired: false, defaultValue: "10"),
                AddedParameterOrExistingIndex.CreateAdded("System.Int32", "y", CallSiteKind.Omitted, isRequired: false, defaultValue: "11"),
                AddedParameterOrExistingIndex.CreateAdded("System.Int32", "z", CallSiteKind.Value, callSiteValue: "102", isRequired: false, defaultValue: "12")};
            var updatedCode = @"
class B
{
    public B() : this(1, 100, z: 102) { }
    public B(int a, int x = 10, int y = 11, int z = 12)
    {
        B q = new(1, 100, z: 102);
    }
}

class D : B
{
    public D() : base(1, 100, z: 102) { }
}";

            await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
        public async Task AddOptionalParameter_ToIndexer()
        {
            var markup = @"
class B
{
    public int this$$[int a] { get { return 5; } }

    public void M()
    {
        var d = this[1];
    }
}";
            var updatedSignature = new[] {
                new AddedParameterOrExistingIndex(0),
                AddedParameterOrExistingIndex.CreateAdded("System.Int32", "x", CallSiteKind.Value, callSiteValue: "100", isRequired: false, defaultValue: "10"),
                AddedParameterOrExistingIndex.CreateAdded("System.Int32", "y", CallSiteKind.Omitted, isRequired: false, defaultValue: "11"),
                AddedParameterOrExistingIndex.CreateAdded("System.Int32", "z", CallSiteKind.Value, callSiteValue: "102", isRequired: false, defaultValue: "12")};
            var updatedCode = @"
class B
{
    public int this[int a, int x = 10, int y = 11, int z = 12] { get { return 5; } }

    public void M()
    {
        var d = this[1, 100, z: 102];
    }
}";

            await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
        public async Task AddOptionalParameter_ToAttribute()
        {
            var markup = @"
[My(1)]
class MyAttribute : System.Attribute
{
    public MyAttribute($$int a) { }
}";
            var updatedSignature = new[] {
                new AddedParameterOrExistingIndex(0),
                AddedParameterOrExistingIndex.CreateAdded("System.Int32", "x", CallSiteKind.Value, callSiteValue: "100", isRequired: false, defaultValue: "10"),
                AddedParameterOrExistingIndex.CreateAdded("System.Int32", "y", CallSiteKind.Omitted, isRequired: false, defaultValue: "11"),
                AddedParameterOrExistingIndex.CreateAdded("System.Int32", "z", CallSiteKind.Value, callSiteValue: "102", isRequired: false, defaultValue: "12")};

            // TODO: The = in the attribute is a bug. You cannot specify that the attribute should use : instead in the SyntaxGenerator
            // https://github.com/dotnet/roslyn/issues/43354
            var updatedCode = @"
[My(1, 100, z = 102)]
class MyAttribute : System.Attribute
{
    public MyAttribute(int a, int x = 10, int y = 11, int z = 12) { }
}";

            await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
        }
    }
}


text:
@interface UITabBarController_RNNOptionsTest : XCTestCase

@property(nonatomic, retain) UITabBarController *uut;

@end

@implementation UITabBarController_RNNOptionsTest

- (void)setUp {
    [super setUp];
    self.uut = [OCMockObject partialMockForObject:[UITabBarController new]];
    OCMStub([self.uut tabBar]).andReturn([OCMockObject partialMockForObject:[UITabBar new]]);
}

- (void)test_centerTabItems {
    [[(id)self.uut.tabBar expect] centerTabItems];
    [self.uut centerTabItems];
    [(id)self.uut.tabBar verify];
}

- (void)test_tabBarTranslucent_true {
    [self.uut setTabBarTranslucent:YES];
    XCTAssertTrue(self.uut.tabBar.translucent);
}

- (void)test_tabBarTranslucent_false {
    [self.uut setTabBarTranslucent:NO];
    XCTAssertFalse(self.uut.tabBar.translucent);
}

- (void)test_tabBarHideShadow_default {
    XCTAssertFalse(self.uut.tabBar.clipsToBounds);
}

- (void)test_tabBarHideShadow_true {
    [self.uut setTabBarHideShadow:YES];
    XCTAssertTrue(self.uut.tabBar.clipsToBounds);
}

- (void)test_tabBarHideShadow_false {
    [self.uut setTabBarHideShadow:NO];
    XCTAssertFalse(self.uut.tabBar.clipsToBounds);
}

@end


text:
package com.crackj2ee.jexi.core;

import java.util.*;

/**
 * CharFactory is responsible for create Char object.
 * <b>NOTE</b> it is a singleton pattern.
 *
 * @author Xuefeng
 */
public class CharFactory {

	// Singleton pattern:
	private static CharFactory instance = new CharFactory();

	// To store & cache all Char objects, may up to 65536 objects:
	private Hashtable char_map = new Hashtable();

	// To make sure it cannot be initialized by client directly:
	private CharFactory() {
		// put the static Char object to hash table:
		char_map.put(new Integer(Char.RETURN.charValue()), Char.RETURN);
		char_map.put(new Integer(Char.TABLE.charValue()), Char.TABLE);
		char_map.put(new Integer(Char.SPACE.charValue()), Char.SPACE);
	}

	/**
	 * Get the singleton instance.
	 * @return Char factory.
	 */
	public static CharFactory instance() {
		return instance;
	}

	/**
	 * Create a new Char object by the given char.
	 * Once a Char object is created, it can be
	 * used again and again by the later calls.
	 *
	 * @param c The char value.
	 * @return A Char object.
	 */
	public Char createChar(char c) {
		Char ch = (Char) char_map.get(new Integer(c));
		if( ch!=null )
			return ch;
		ch = new Char(c);
		char_map.put(new Integer(c), ch); // <key, value>
		return ch;
	}
}


text:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;

namespace HttpImageHandler
{
    /// <summary>
    /// Currently makes the request string between the host and .img as image.
    /// </summary>
    public class ImageHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            using(var bitmap = new System.Drawing.Bitmap(context.Server.MapPath("images/image.png")))
            using(var graphics = Graphics.FromImage(bitmap))
            {
                var imageName = context.Request.RawUrl.ToString();
                imageName = imageName.Substring(1, imageName.Length - 5);
                graphics.DrawString(imageName,new Font("Arial",18),new SolidBrush(Color.BlueViolet),new PointF());
                context.Response.ContentType = "image/png";
                bitmap.Save(context.Response.OutputStream, ImageFormat.Png);
            }

            //context.Request.ContentType = "text/plain";
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


text:
package com.zxy.commons.lang.base;

import java.io.Serializable;

import com.zxy.commons.lang.utils.ObjectsUtils;

/**
 * Base model
 *
 *

 * View Source
 *
 * @author zhaoxunyong@qq.com
 * @version 1.0
 * @since 1.0
*/
@SuppressWarnings("PMD")
public abstract class BaseModel implements Serializable {
    private static final long serialVersionUID = -5981694241742540962L;

    @Override
    public String toString() {
        return ObjectsUtils.toString(this);
    }
}


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

<title>BaseLdpHandler (trellis-http 0.3.0 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="date" content="2017-10-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

SEARCH:
<input type="text" id="search" value=" " disabled="disabled">
<input type="reset" id="reset" value=" " disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package org.trellisldp.http.impl

Class BaseLdpHandler

java.lang.Object

org.trellisldp.http.impl.BaseLdpHandler

Direct Known Subclasses:

DeleteHandler, GetHandler, OptionsHandler, PatchHandler, PostHandler, PutHandler

public class BaseLdpHandler
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field
Description

protected static AuditService
audit

protected static java.util.List<ConstraintService>
constraintServices

protected java.util.Map<java.lang.String,java.lang.String>
partitions

protected static org.apache.commons.rdf.api.RDF
rdf

protected LdpRequest
req

protected ResourceService
resourceService

protected static java.util.List<org.apache.commons.rdf.api.RDFSyntax>
SUPPORTED_RDF_TYPES

Constructor Summary

Constructors

Constructor
Description

BaseLdpHandler(java.util.Map<java.lang.String,java.lang.String> partitions,
              LdpRequest req,
              ResourceService resourceService)

A base class for response handling

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method
Description

protected static void
checkCache(javax.ws.rs.core.Request request,
          java.time.Instant modified,
          javax.ws.rs.core.EntityTag etag)

Check the request for a cache-related response

protected static void
checkDeleted(Resource res,
            java.lang.String identifier)

Check if this is a deleted resource, and if so return an appropriate response

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

rdf

protected static final org.apache.commons.rdf.api.RDF rdf

audit

protected static AuditService audit

constraintServices

protected static final java.util.List<ConstraintService> constraintServices

SUPPORTED_RDF_TYPES

protected static final java.util.List<org.apache.commons.rdf.api.RDFSyntax> SUPPORTED_RDF_TYPES

partitions

protected final java.util.Map<java.lang.String,java.lang.String> partitions

req

protected final LdpRequest req

resourceService

protected final ResourceService resourceService

Constructor Detail

BaseLdpHandler

public BaseLdpHandler(java.util.Map<java.lang.String,java.lang.String> partitions,
                      LdpRequest req,
                      ResourceService resourceService)

A base class for response handling

Parameters:

partitions - the partitions

req - the LDP request

resourceService - the resource service

Method Detail

checkDeleted

protected static void checkDeleted(Resource res,
                                   java.lang.String identifier)

Check if this is a deleted resource, and if so return an appropriate response

Parameters:

res - the resource

identifier - the identifier

Throws:

javax.ws.rs.WebApplicationException - a 410 Gone exception

checkCache

protected static void checkCache(javax.ws.rs.core.Request request,
                                 java.time.Instant modified,
                                 javax.ws.rs.core.EntityTag etag)

Check the request for a cache-related response

Parameters:

request - the request

modified - the modified time

etag - the etag

Throws:

javax.ws.rs.WebApplicationException - either a 412 Precondition Failed or a 304 Not Modified, depending on the context.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using namespace persistent;

template <class DataType>
class HashTable;

template <class DataType>
class HashTable : public mutils::ByteRepresentable, public derecho::GroupReference {
private:
    std::map<uint64_t, DataType> table;

public:
    using derecho::GroupReference::group;
    using derecho::GroupReference::subgroup_index;

    void put(uint64_t key, const DataType& value) {
        table[key] = value;
    }

    DataType get(uint64_t key) {
        // for now, create the entry if it doesn't exist
        return table[key];
    }

    void fun(const DataType& v0, const DataType& v1, const DataType& v2) {
        put(0, v0);
        put(1, v1);
        put(2, v2);
    }

    void print() {
        for(auto p : table) {
            std::cout << p.first << " " << p.second << std::endl;
        }
        derecho::Replicated<HashTable<DataType>>& subgroup_handle = group->template get_subgroup<HashTable<DataType>>();
        std::thread temp([&]() {
            subgroup_handle.template ordered_send<RPC_NAME(print)>();
        });
        temp.detach();
    }

    REGISTER_RPC_FUNCTIONS(HashTable, ORDERED_TARGETS(put, get, fun, print));

    HashTable() : table() {}

    HashTable(const std::map<uint64_t, DataType>& table) : table(table) {}

    DEFAULT_SERIALIZATION_SUPPORT(HashTable, table);
};

int main(int argc, char* argv[]) {
    derecho::Conf::initialize(argc, argv);

    std::mutex main_mutex;
    std::condition_variable main_cv;

    bool groups_provisioned = false;
    auto announce_groups_provisioned = [&groups_provisioned, &main_cv, &main_mutex](const derecho::View& view) {
        if(view.is_adequately_provisioned) {
            std::unique_lock<std::mutex> lock(main_mutex);
            groups_provisioned = true;
            main_cv.notify_all();
        }
    };

    derecho::SubgroupInfo subgroup_function{[](
            const std::vector<std::type_index>& subgroup_type_order,
            const std::unique_ptr<derecho::View>& prev_view, derecho::View& curr_view) {
        if(curr_view.num_members < 2) {
            throw derecho::subgroup_provisioning_exception();
        }
        derecho::subgroup_shard_layout_t subgroup_vector(1);
        for(uint i = 0; i < (uint32_t)curr_view.num_members / 2; ++i) {
            subgroup_vector[0].emplace_back(curr_view.make_subview({2 * i, 2 * i + 1}));
        }
        curr_view.next_unassigned_rank = curr_view.num_members;
        derecho::subgroup_allocation_map_t subgroup_allocation;
        subgroup_allocation.emplace(std::type_index(typeid(HashTable<std::string>)),
                                    std::move(subgroup_vector));
        return subgroup_allocation;
    }};

    auto HashTableGenerator = [&](PersistentRegistry*,derecho::subgroup_id_t) { return std::make_unique<HashTable<std::string>>(); };
    derecho::Group<HashTable<std::string>> group({}, subgroup_function, {},
                                                 std::vector<derecho::view_upcall_t>{announce_groups_provisioned},
                                                 HashTableGenerator);

    std::unique_lock<std::mutex> main_lock(main_mutex);
    main_cv.wait(main_lock, [&groups_provisioned]() { return groups_provisioned; });
    std::cout << "Subgroups provisioned" << std::endl;
    auto& subgroup_handle = group.get_subgroup<HashTable<std::string>>();
    uint32_t node_rank = group.get_my_rank();

    if(node_rank == 0) {
        subgroup_handle.ordered_send<RPC_NAME(fun)>("hello", "hi", "bye");
    } else {
        subgroup_handle.ordered_send<RPC_NAME(print)>();
    }
    std::cout << "Entering infinite loop" << std::endl;
    while(true) {
    }
}


text:
description: The template creates a virtual machine running Windows Server in a new virtual network, with a public IP address. Once the machine has deployed, the guest configuration extension is installed and the Azure secure baseline for Windows Server is applied. If the configuration of the machines drifts, you can re-apply the settings by deploying the template again.
page_type: sample
products:
- azure
- azure-resource-manager
urlFragment: vm-windows-baseline
languages:
- json
- bicep
---
# Windows VM with Azure secure baseline.

![Azure Public Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.compute/vm-windows-baseline/PublicLastTestDate.svg)
![Azure Public Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.compute/vm-windows-baseline/PublicDeployment.svg)

![Azure US Gov Last Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.compute/vm-windows-baseline/FairfaxLastTestDate.svg)
![Azure US Gov Last Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.compute/vm-windows-baseline/FairfaxDeployment.svg)

![Best Practice Check](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.compute/vm-windows-baseline/BestPracticeResult.svg)
![Cred Scan Check](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.compute/vm-windows-baseline/CredScanResult.svg)

![Bicep Version](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.compute/vm-windows-baseline/BicepVersion.svg)

[![Deploy To Azure](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazure.svg?sanitize=true)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.compute%2Fvm-windows-baseline%2Fazuredeploy.json)

[![Visualize](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/visualizebutton.svg?sanitize=true)](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.compute%2Fvm-windows-baseline%2Fazuredeploy.json)

This template allows you to deploy a Windows VM with the Azure secure baseline applied. For details about the settings in the baseline,
review the reference documentation.

[Windows secure baseline](https://docs.microsoft.com/azure/governance/policy/samples/guest-configuration-baseline-windows)

General information about how configurations are assigned to machines in Azure is available in documentation.

[Understand the guest configuration feature of Azure Policy](https://docs.microsoft.com/azure/governance/policy/concepts/guest-configuration)

A detailed how to document about assigning configurations to machines, and how to customize configurations from ARM,
is also available.

---

**Common administration ports to log in to the VM directly, are not opened in this template.**
After deploying this machine, it is expected that you will
[deploy applications](https://docs.microsoft.com/azure/devops/pipelines/release/deployment-groups/deploying-azure-vms-deployment-groups)
using a service such as Azure DevOps.

- [Provision agents for deployment groups](https://docs.microsoft.com/azure/devops/pipelines/release/deployment-groups/howto-provision-deployment-group-agents)

To provide ongoing operations for the machine, it is expected you will use the available
Azure management services. You can also view the
[Cloud Adoption Framework](https://docs.microsoft.com/azure/cloud-adoption-framework/manage/azure-server-management/)
for more information about best practices.

- [Azure Automanage](https://docs.microsoft.com/azure/automanage/automanage-virtual-machines)
- [Azure Monitor](https://docs.microsoft.com/azure/azure-monitor/)
- [Azure Update Management](https://docs.microsoft.com/azure/automation/update-management/overview)
- [Azure Automation inventory feature](https://docs.microsoft.com/azure/automation/change-tracking/manage-inventory-vms)
- [Azure Policy's guest configuration feature](https://docs.microsoft.com/azure/governance/policy/concepts/guest-configuration)
- [Azure Backup](https://docs.microsoft.com/azure/backup/)
- [Azure Custom Script extension for Windows](https://docs.microsoft.com/azure/virtual-machines/extensions/custom-script-windows)
- [Azure Run Commands for Windows](https://docs.microsoft.com/azure/virtual-machines/windows/run-command)

If you would prefer to open common ports, modify rules in the network security group
associated with the network adapter for the machine.

- [Network security groups](https://docs.microsoft.com/azure/virtual-network/network-security-groups-overview)

---

[How to create a guest configuration assignment using templates](https://docs.microsoft.com/azure/governance/policy/how-to/guest-configuration-create-assignment)

If you're new to Azure virtual machines, see:

- [Azure Virtual Machines](https://azure.microsoft.com/services/virtual-machines/)
- [Azure Linux Virtual Machines documentation](https://docs.microsoft.com/azure/virtual-machines/linux/)
- [Azure Windows Virtual Machines documentation](https://docs.microsoft.com/azure/virtual-machines/windows/)
- [Template reference](https://docs.microsoft.com/azure/templates/microsoft.compute/allversions)
- [Quickstart templates](https://azure.microsoft.com/resources/templates/?resourceType=Microsoft.Compute&pageNumber=1&sort=Popular)

If you're new to template deployment, see:

- [Azure Resource Manager documentation](https://docs.microsoft.com/azure/azure-resource-manager/)
- [Quickstart: Create a Windows virtual machine using an ARM template](https://docs.microsoft.com/azure/virtual-machines/windows/quick-create-template)

`Tags: Microsoft.Network/networkSecurityGroups, Microsoft.Network/virtualNetworks, Microsoft.Network/publicIPAddresses, Microsoft.Network/networkInterfaces, Microsoft.Compute/virtualMachines, Microsoft.Compute/virtualMachines/extensions, ConfigurationforWindows, Microsoft.GuestConfiguration/guestConfigurationAssignments`


text:
namespace ash {

namespace {

const int64_t kInitialRequestDelayMs = 100;
const int64_t kMaxRequestDelayMs = 300000;  // 5 minutes

#if BUILDFLAG(NSS_SLOTS_SOFTWARE_FALLBACK)
constexpr bool kIsSystemSlotSoftwareFallbackAllowed = true;
#else
constexpr bool kIsSystemSlotSoftwareFallbackAllowed = false;
#endif

// Calculates the delay before running next attempt to initiatialize the TPM
// token, if |last_delay| was the last or initial delay.
base::TimeDelta GetNextRequestDelayMs(base::TimeDelta last_delay) {
  // This implements an exponential backoff, as we don't know in which order of
  // magnitude the TPM token changes it's state.
  base::TimeDelta next_delay = last_delay * 2;

  // Cap the delay to prevent an overflow. This threshold is arbitrarily chosen.
  const base::TimeDelta max_delay = base::Milliseconds(kMaxRequestDelayMs);
  if (next_delay > max_delay)
    next_delay = max_delay;
  return next_delay;
}

}  // namespace

// static
std::unique_ptr<TPMTokenInfoGetter> TPMTokenInfoGetter::CreateForUserToken(
    const AccountId& account_id,
    CryptohomePkcs11Client* userdataauth_client,
    const scoped_refptr<base::TaskRunner>& delayed_task_runner) {
  CHECK(account_id.is_valid());
  return base::WrapUnique(new TPMTokenInfoGetter(
      TYPE_USER, account_id, userdataauth_client, delayed_task_runner));
}

// static
std::unique_ptr<TPMTokenInfoGetter> TPMTokenInfoGetter::CreateForSystemToken(
    CryptohomePkcs11Client* userdataauth_client,
    const scoped_refptr<base::TaskRunner>& delayed_task_runner) {
  return base::WrapUnique(new TPMTokenInfoGetter(
      TYPE_SYSTEM, EmptyAccountId(), userdataauth_client, delayed_task_runner));
}

TPMTokenInfoGetter::~TPMTokenInfoGetter() = default;

void TPMTokenInfoGetter::Start(TpmTokenInfoCallback callback) {
  CHECK(state_ == STATE_INITIAL);
  CHECK(!callback.is_null());

  callback_ = std::move(callback);

  state_ = STATE_STARTED;
  Continue();
}

TPMTokenInfoGetter::TPMTokenInfoGetter(
    TPMTokenInfoGetter::Type type,
    const AccountId& account_id,
    CryptohomePkcs11Client* cryptohome_pkcs11_client,
    const scoped_refptr<base::TaskRunner>& delayed_task_runner)
    : delayed_task_runner_(delayed_task_runner),
      type_(type),
      state_(TPMTokenInfoGetter::STATE_INITIAL),
      account_id_(account_id),
      use_nss_slots_software_fallback_(kIsSystemSlotSoftwareFallbackAllowed),
      tpm_request_delay_(base::Milliseconds(kInitialRequestDelayMs)),
      cryptohome_pkcs11_client_(cryptohome_pkcs11_client) {}

void TPMTokenInfoGetter::Continue() {
  user_data_auth::Pkcs11GetTpmTokenInfoRequest request;
  switch (state_) {
    case STATE_INITIAL:
      NOTREACHED();
      break;
    case STATE_STARTED:
      chromeos::TpmManagerClient::Get()->GetTpmNonsensitiveStatus(
          ::tpm_manager::GetTpmNonsensitiveStatusRequest(),
          base::BindOnce(&TPMTokenInfoGetter::OnGetTpmStatus,
                         weak_factory_.GetWeakPtr()));
      break;
    case STATE_TPM_ENABLED:
    case STATE_NSS_SLOTS_SOFTWARE_FALLBACK:
      // For system token, we don't need to supply the username, and with an
      // empty username, cryptohomed will return the system token information.
      if (type_ == TYPE_USER) {
        request.set_username(
            cryptohome::CreateAccountIdentifierFromAccountId(account_id_)
                .account_id());
      }
      cryptohome_pkcs11_client_->Pkcs11GetTpmTokenInfo(
          request, base::BindOnce(&TPMTokenInfoGetter::OnPkcs11GetTpmTokenInfo,
                                  weak_factory_.GetWeakPtr()));
      break;
    case STATE_DONE:
      NOTREACHED();
  }
}

void TPMTokenInfoGetter::RetryLater() {
  delayed_task_runner_->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&TPMTokenInfoGetter::Continue, weak_factory_.GetWeakPtr()),
      tpm_request_delay_);
  tpm_request_delay_ = GetNextRequestDelayMs(tpm_request_delay_);
}

void TPMTokenInfoGetter::OnGetTpmStatus(
    const ::tpm_manager::GetTpmNonsensitiveStatusReply& reply) {
  if (reply.status() != ::tpm_manager::STATUS_SUCCESS) {
    LOG(WARNING) << "Failed to get tpm status; status: " << reply.status();
    RetryLater();
    return;
  }

  // In case the use_nss_slots_software_fallback_ is true and the TPM is not
  // owned, we continue the token info retrieval for the nss slots in order to
  // fall back to a software-backed initialization.
  if (use_nss_slots_software_fallback_ && !reply.is_owned()) {
    state_ = STATE_NSS_SLOTS_SOFTWARE_FALLBACK;
    Continue();
    return;
  }

  if (!reply.is_enabled()) {
    state_ = STATE_DONE;
    std::move(callback_).Run(absl::nullopt);
    return;
  }

  state_ = STATE_TPM_ENABLED;
  Continue();
}

void TPMTokenInfoGetter::OnPkcs11GetTpmTokenInfo(
    absl::optional<user_data_auth::Pkcs11GetTpmTokenInfoReply> token_info) {
  if (!token_info.has_value() || !token_info->has_token_info() ||
      token_info->token_info().slot() == -1) {
    RetryLater();
    return;
  }

  state_ = STATE_DONE;
  std::move(callback_).Run(token_info->token_info());
}

}  // namespace ash


text:
#include <glog/logging.h>

#include <fstream>
#include <ios>
#include <vector>

#include <process/delay.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/process.hpp>
#include <process/protobuf.hpp>
#include <process/timer.hpp>

#include <stout/foreach.hpp>
#include <stout/numify.hpp>
#include <stout/option.hpp>
#include <stout/try.hpp>

#include "detector/detector.hpp"

#include "logging/logging.hpp"

#include "messages/messages.hpp"

#include "zookeeper/authentication.hpp"
#include "zookeeper/url.hpp"
#include "zookeeper/watcher.hpp"
#include "zookeeper/zookeeper.hpp"

using process::Future;
using process::Process;
using process::Timer;
using process::UPID;
using process::wait; // Necessary on some OS's to disambiguate.

using std::pair;
using std::string;
using std::vector;

namespace mesos {
namespace internal {

// TODO(benh): Make this value configurable via flags and verify that
// it is always LESS THAN the slave heartbeat timeout.
const Seconds ZOOKEEPER_SESSION_TIMEOUT(10.0);

class ZooKeeperMasterDetectorProcess
  : public Process<ZooKeeperMasterDetectorProcess>
{
public:
  ZooKeeperMasterDetectorProcess(
    const zookeeper::URL& url,
    const UPID& pid,
    bool contend,
    bool quiet);

  virtual ~ZooKeeperMasterDetectorProcess();

  virtual void initialize();

  // ZooKeeperMasterDetector implementation.
  int64_t session();

  // ZooKeeper events.
  void connected(bool reconnect);
  void reconnecting();
  void expired();
  void updated(const string& path);
  void created(const string& path);
  void deleted(const string& path);

private:
  // Handles reconnecting "timeouts" by prematurely expiring a session
  // (only used for contending instances). TODO(benh): Remove 'const
  // &' after fixing libprocess.
  void timedout(const int64_t& sessionId);

  // Attempts to detect a master.
  void detectMaster();

  const zookeeper::URL url;
  const ACL_vector acl;

  const UPID pid;
  bool contend;

  Watcher* watcher;
  ZooKeeper* zk;

  bool expire;
  Option<Timer> timer;

  string currentMasterSeq;
  UPID currentMasterPID;
};

MasterDetector::~MasterDetector() {}

Try<MasterDetector*> MasterDetector::create(const string& master,
                                            const UPID& pid,
                                            bool contend,
                                            bool quiet)
{
  if (master == "") {
    if (contend) {
      return new BasicMasterDetector(pid);
    } else {
      return Try<MasterDetector*>::error("Cannot detect master");
    }
  } else if (master.find("zk://") == 0) {
    Try<zookeeper::URL> url = zookeeper::URL::parse(master);
    if (url.isError()) {
      return Try<MasterDetector*>::error(url.error());
    }
    if (url.get().path == "/") {
      return Try<MasterDetector*>::error(
          "Expecting a (chroot) path for ZooKeeper ('/' is not supported)");
    }
    return new ZooKeeperMasterDetector(url.get(), pid, contend, quiet);
  } else if (master.find("file://") == 0) {
    const std::string& path = master.substr(7);
    std::ifstream file(path.c_str());
    if (!file.is_open()) {
      return Try<MasterDetector*>::error(
          "Failed to open file at '" + path + "'");
    }

    std::string line;
    getline(file, line);

    if (!file) {
      file.close();
      return Try<MasterDetector*>::error(
          "Failed to read from file at '" + path + "'");
    }

    file.close();

    return create(line, pid, contend, quiet);
  }

  // Okay, try and parse what we got as a PID.
  process::UPID masterPid = master.find("master@") == 0
    ? process::UPID(master)
    : process::UPID("master@" + master);

  if (!masterPid) {
    return Try<MasterDetector*>::error(
        "Cannot parse '" + std::string(masterPid) + "'");
  }

  return new BasicMasterDetector(masterPid, pid);
}

void MasterDetector::destroy(MasterDetector *detector)
{
  if (detector != NULL)
    delete detector;
}

BasicMasterDetector::BasicMasterDetector(const UPID& _master)
  : master(_master)
{
  // Elect the master.
  NewMasterDetectedMessage message;
  message.set_pid(master);
  process::post(master, message);
}

BasicMasterDetector::BasicMasterDetector(const UPID& _master,
					 const UPID& pid,
					 bool elect)
  : master(_master)
{
  if (elect) {
    // Elect the master.
    NewMasterDetectedMessage message;
    message.set_pid(master);
    process::post(master, message);
  }

  // Tell the pid about the master.
  NewMasterDetectedMessage message;
  message.set_pid(master);
  process::post(pid, message);
}

BasicMasterDetector::BasicMasterDetector(const UPID& _master,
					 const vector<UPID>& pids,
					 bool elect)
  : master(_master)
{
  if (elect) {
    // Elect the master.
    NewMasterDetectedMessage message;
    message.set_pid(master);
    process::post(master, message);
  }

  // Tell each pid about the master.
  foreach (const UPID& pid, pids) {
    NewMasterDetectedMessage message;
    message.set_pid(master);
    process::post(pid, message);
  }
}

BasicMasterDetector::~BasicMasterDetector() {}

ZooKeeperMasterDetectorProcess::ZooKeeperMasterDetectorProcess(
    const zookeeper::URL& _url,
    const UPID& _pid,
    bool _contend,
    bool quiet)
  : url(_url),
    acl(url.authentication.isSome()
        ? zookeeper::EVERYONE_READ_CREATOR_ALL
        : ZOO_OPEN_ACL_UNSAFE),
    pid(_pid),
    contend(_contend),
    watcher(NULL),
    zk(NULL),
    expire(false)
{
  // Set verbosity level for underlying ZooKeeper library logging.
  // TODO(benh): Put this in the C++ API.
  zoo_set_debug_level(quiet ? ZOO_LOG_LEVEL_ERROR : ZOO_LOG_LEVEL_DEBUG);
}

ZooKeeperMasterDetectorProcess::~ZooKeeperMasterDetectorProcess()
{
  delete zk;
  delete watcher;
}

void ZooKeeperMasterDetectorProcess::initialize()
{
  // Doing initialization here allows to avoid the race between
  // instantiating the ZooKeeper instance and being spawned ourself.
  watcher = new ProcessWatcher<ZooKeeperMasterDetectorProcess>(self());
  zk = new ZooKeeper(url.servers, ZOOKEEPER_SESSION_TIMEOUT, watcher);
}

int64_t ZooKeeperMasterDetectorProcess::session()
{
  CHECK_NOTNULL(zk);
  return zk->getSessionId();
}

void ZooKeeperMasterDetectorProcess::connected(bool reconnect)
{
  if (!reconnect) {
    LOG(INFO) << "Master detector (" << pid << ") connected to ZooKeeper ...";

    if (url.authentication.isSome()) {
      const std::string& scheme = url.authentication.get().scheme;
      const std::string& credentials = url.authentication.get().credentials;
      LOG(INFO) << "Authenticating to ZooKeeper using scheme '" << scheme << "'";
      int code = zk->authenticate(scheme, credentials);
      if (code != ZOK) {
        LOG(FATAL) << "Failed to authenticate with ZooKeeper: "
                   << zk->message(code);
      }
    }

    // Assume the path (chroot) being used does not end with a "/".
    CHECK(url.path.at(url.path.length() - 1) != '/');

    // Create znode path (including intermediate znodes) as necessary.
    LOG(INFO) << "Trying to create path '" << url.path << "' in ZooKeeper";

    int code = zk->create(url.path, "", acl, 0, NULL, true);

    // We fail all non-OK return codes except ZNODEEXISTS (since that
    // means the path we were trying to create exists) and ZNOAUTH
    // (since it's possible that the ACLs on 'dirname(url.path)' don't
    // allow us to create a child znode but we are allowed to create
    // children of 'url.path' itself, which will be determined below
    // if we are contending). Note that it's also possible we got back
    // a ZNONODE because we could not create one of the intermediate
    // znodes (in which case we'll abort in the 'else' below since
    // ZNONODE is non-retryable). TODO(benh): Need to check that we
    // also can put a watch on the children of 'url.path'.
    if (code != ZOK && code != ZNODEEXISTS && code != ZNOAUTH) {
      LOG(FATAL) << "Failed to create '" << url.path
                 << "' in ZooKeeper: " << zk->message(code);
    }

    if (contend) {
      // We contend with the pid given in constructor.
      string result;
      int code = zk->create(url.path + "/", pid, acl,
                            ZOO_SEQUENCE | ZOO_EPHEMERAL, &result);

      if (code != ZOK) {
        LOG(FATAL) << "Unable to create ephemeral child of '" << url.path
                   << "' in ZooKeeper: %s" << zk->message(code);
      }

      LOG(INFO) << "Created ephemeral/sequence znode at '" << result << "'";
    }

    // Now determine who the master is (it may be us).
    detectMaster();
  } else {
    LOG(INFO) << "Master detector (" << pid << ")  reconnected ...";

    // Cancel and cleanup the reconnect timer (if necessary).
    if (timer.isSome()) {
      Timer::cancel(timer.get());
      timer = Option<Timer>::none();
    }

    // If we decided to expire the session, make sure we delete the
    // ZooKeeper instance so the session actually expires. We also
    // create a new ZooKeeper instance for clients that want to
    // continue detecting and/or contending (which is likely given
    // that this code is getting executed).
    if (expire) {
      LOG(WARNING) << "Cleaning up after expired ZooKeeper session";

      delete CHECK_NOTNULL(zk);
      delete CHECK_NOTNULL(watcher);

      watcher = new ProcessWatcher<ZooKeeperMasterDetectorProcess>(self());
      zk = new ZooKeeper(url.servers, ZOOKEEPER_SESSION_TIMEOUT, watcher);

      expire = false;
      return;
    }

    // We've reconnected and we didn't prematurely expire the session,
    // but the master might have changed, so we should run an
    // election. TODO(benh): Determine if this is really necessary or
    // if the watch set via 'ZooKeeper::getChildren' in 'detectMaster'
    // is sufficient (it should be).
    detectMaster();
  }
}

void ZooKeeperMasterDetectorProcess::reconnecting()
{
  LOG(INFO) << "Master detector (" << pid << ")  lost connection to ZooKeeper, "
            << "attempting to reconnect ...";

  // ZooKeeper won't tell us of a session expiration until we
  // reconnect, which could occur much much later than the session was
  // actually expired. This can lead to a prolonged split-brain
  // scenario when network partitions occur. Rather than wait for a
  // reconnection to occur (i.e., a network partition to be repaired)
  // we create a local timer and "expire" our session prematurely if
  // we haven't reconnected within the session expiration time
  // out. Later, when we eventually do reconnect we can force the
  // session to be expired if we decided locally to expire.
  timer = process::delay(
      ZOOKEEPER_SESSION_TIMEOUT, self(), &Self::timedout, zk->getSessionId());
}

void ZooKeeperMasterDetectorProcess::expired()
{
  LOG(WARNING) << "Master detector (" << pid << ")  ZooKeeper session expired!";

  // Cancel and cleanup the reconnect timer (if necessary).
  if (timer.isSome()) {
    Timer::cancel(timer.get());
    timer = Option<Timer>::none();
  }

  delete CHECK_NOTNULL(zk);
  delete CHECK_NOTNULL(watcher);

  watcher = new ProcessWatcher<ZooKeeperMasterDetectorProcess>(self());
  zk = new ZooKeeper(url.servers, ZOOKEEPER_SESSION_TIMEOUT, watcher);

  expire = false;
}

void ZooKeeperMasterDetectorProcess::updated(const string& path)
{
  // A new master might have showed up and created a sequence
  // identifier or a master may have died, determine who the master is now!
  detectMaster();
}

void ZooKeeperMasterDetectorProcess::created(const string& path)
{
  LOG(FATAL) << "Unexpected ZooKeeper event (created) for '" << path << "'";
}

void ZooKeeperMasterDetectorProcess::deleted(const string& path)
{
  LOG(FATAL) << "Unexpected ZooKeeper event (deleted) for '" << path << "'";
}

void ZooKeeperMasterDetectorProcess::timedout(const int64_t& sessionId)
{
  CHECK_NOTNULL(zk);
  if (timer.isSome() && zk->getSessionId() == sessionId) {
    LOG(WARNING) << "Timed out waiting to reconnect to ZooKeeper "
                 << "(sessionId=" << std::hex << sessionId << ")";
    timer = Option<Timer>::none();
    expire = true;

    // We only send a NoMasterDetectedMessage if we are a
    // contending detector AND ALSO the current leader.
    // This is because:
    // 1) If we are a non-contending detector (e.g. slave), a zk session
    //    expiration doesn't necessarily mean a new leader (master) is elected
    //    (e.g. the slave is partitioned from the zk server). If the leading
    //    master stays the same (i.e., no leader election), then the
    //    slave should still accept a ShutDownMessage from the master.
    //    If a new master does get elected, the slave would know about it
    //    because it would do a leader detection after it connects/re-connects.
    // 2) If we are a contender but not the leader (e.g. non-leading master),
    //    sending a NoMasterDetectedMessage() is bad because, a partitioned
    //    non-leading master would never know about the leading master that
    //    stays the same (i.e., no leader election) even after it is
    //    connected/reconnected with the ZooKeeper. This is because, the
    //    the master detection code (detectMaster()) will not send a
    //    NewMasterDetectedMessage to the non-leading master as there is no
    //    change in the currentMasterSeq.
    if (contend && currentMasterPID == pid) {
      process::post(pid, NoMasterDetectedMessage());
    }
  }
}

void ZooKeeperMasterDetectorProcess::detectMaster()
{
  vector<string> results;

  int code = zk->getChildren(url.path, true, &results);

  if (code != ZOK) {
    if (zk->retryable(code)) {
      // NOTE: We don't expect a ZNONODE here because 'url.path' is always
      // created in the connected() call. Despite that, we don't do a
      // CHECK (code != ZNONODE) just to be safe in case the zk client library
      // does return the code unexpectedly.
      LOG(ERROR) << "Master detector (" << pid << ")  failed to get masters: "
                 << zk->message(code);
      return; // Try again when we reconnect.
    } else {
      LOG(FATAL) << "Non-retryable ZooKeeper error while getting masters: "
                 << zk->message(code);
    }
  } else {
    LOG(INFO) << "Master detector (" << pid << ")  found " << results.size()
              << " registered masters";
  }

  string masterSeq;
  long min = LONG_MAX;
  foreach (const string& result, results) {
    Try<int> i = numify<int>(result);
    if (i.isError()) {
      LOG(WARNING) << "Unexpected znode at '" << url.path
                   << "': " << i.error();
      continue;
    }
    if (i.get() < min) {
      min = i.get();
      masterSeq = result;
    }
  }

  // No master present (lost or possibly hasn't come up yet).
  if (masterSeq.empty()) {
    LOG(INFO) << "Master detector (" << pid << ") couldn't find any masters";
    process::post(pid, NoMasterDetectedMessage());
  } else if (masterSeq != currentMasterSeq) {
    // Okay, let's fetch the master pid from ZooKeeper.
    string result;
    code = zk->get(url.path + "/" + masterSeq, false, &result, NULL);

    if (code != ZOK) {
      // This is possible because the master might have failed since
      // the invocation of ZooKeeper::getChildren above.
      // It is fine to not send a NoMasterDetectedMessage here because,
      // 1) If this is due to a connection loss or session expiration,
      //    connected() or expired() will be called and the leader detection
      //    code (detectMaster()) will be re-tried.
      // 2) If this is due to no masters present (i.e., code == ZNONODE),
      //    updated() will be called and the detectMaster() will be re-tried.
      if (zk->retryable(code)) {
        LOG(ERROR) << "Master detector failed to fetch new master pid: "
                   << zk->message(code);
      } else {
        LOG(FATAL) << "Non-retryable ZooKeeper error while fetching "
                   << "new master pid: " << zk->message(code);
      }
    } else {
      // Now let's parse what we fetched from ZooKeeper.
      LOG(INFO) << "Master detector (" << pid << ")  got new master pid: "
                << result;

      UPID masterPid = result;

      if (masterPid == UPID()) {
        // TODO(benh): Maybe we should try again then!?!? Parsing
        // might have failed because of DNS, and whoever is using the
        // detector might sit "unconnected" indefinitely!
        LOG(ERROR) << "Failed to parse new master pid!";
        process::post(pid, NoMasterDetectedMessage());
      } else {
        currentMasterSeq = masterSeq;
        currentMasterPID = masterPid;

        NewMasterDetectedMessage message;
        message.set_pid(currentMasterPID);
        process::post(pid, message);
      }
    }
  }
}

ZooKeeperMasterDetector::ZooKeeperMasterDetector(
    const zookeeper::URL& url,
    const UPID& pid,
    bool contend,
    bool quiet)
{
  process = new ZooKeeperMasterDetectorProcess(url, pid, contend, quiet);
  spawn(process);
}

ZooKeeperMasterDetector::~ZooKeeperMasterDetector()
{
  terminate(process);
  wait(process);
  delete process;
}

Future<int64_t> ZooKeeperMasterDetector::session()
{
  return dispatch(process, &ZooKeeperMasterDetectorProcess::session);
}

} // namespace internal {
} // namespace mesos {


text:
package sarama

import "time"

// AlterConfigsResponse is a response type for alter config
type AlterConfigsResponse struct {
	ThrottleTime time.Duration
	Resources    []*AlterConfigsResourceResponse
}

// AlterConfigsResourceResponse is a response type for alter config resource
type AlterConfigsResourceResponse struct {
	ErrorCode int16
	ErrorMsg  string
	Type      ConfigResourceType
	Name      string
}

func (a *AlterConfigsResponse) encode(pe packetEncoder) error {
	pe.putInt32(int32(a.ThrottleTime / time.Millisecond))

	if err := pe.putArrayLength(len(a.Resources)); err != nil {
		return err
	}

	for _, v := range a.Resources {
		if err := v.encode(pe); err != nil {
			return err
		}
	}

	return nil
}

func (a *AlterConfigsResponse) decode(pd packetDecoder, version int16) error {
	throttleTime, err := pd.getInt32()
	if err != nil {
		return err
	}
	a.ThrottleTime = time.Duration(throttleTime) * time.Millisecond

	responseCount, err := pd.getArrayLength()
	if err != nil {
		return err
	}

	a.Resources = make([]*AlterConfigsResourceResponse, responseCount)

	for i := range a.Resources {
		a.Resources[i] = new(AlterConfigsResourceResponse)

		if err := a.Resources[i].decode(pd, version); err != nil {
			return err
		}
	}

	return nil
}

func (a *AlterConfigsResourceResponse) encode(pe packetEncoder) error {
	pe.putInt16(a.ErrorCode)
	err := pe.putString(a.ErrorMsg)
	if err != nil {
		return err
	}
	pe.putInt8(int8(a.Type))
	err = pe.putString(a.Name)
	if err != nil {
		return err
	}
	return nil
}

func (a *AlterConfigsResourceResponse) decode(pd packetDecoder, version int16) error {
	errCode, err := pd.getInt16()
	if err != nil {
		return err
	}
	a.ErrorCode = errCode

	e, err := pd.getString()
	if err != nil {
		return err
	}
	a.ErrorMsg = e

	t, err := pd.getInt8()
	if err != nil {
		return err
	}
	a.Type = ConfigResourceType(t)

	name, err := pd.getString()
	if err != nil {
		return err
	}
	a.Name = name

	return nil
}

func (a *AlterConfigsResponse) key() int16 {
	return 32
}

func (a *AlterConfigsResponse) version() int16 {
	return 0
}

func (a *AlterConfigsResponse) headerVersion() int16 {
	return 0
}

func (a *AlterConfigsResponse) requiredVersion() KafkaVersion {
	return V0_11_0_0
}


text:
package io.github.ketao1989.jdk8;

import java.util.function.Supplier;

/**
 * @author tao.ke Date: 2017/7/23 Time: 下午10:04
 */
public class TemplateProcessor<T> {

  /**
   * 核心的执行方法,获取执行结果
   */
  private Supplier<T> coreProcessor;

  /**
   * 执行参数校验
   */
  private EmptyParamProcessor checkParams = ()->{
    System.out.println("exe......");
  };

  /**
   * 执行事后资源处理等
   */
  private EmptyParamProcessor beforeProcess = ()->{System.out.println("exe......");};

  /**
   * 执行事后资源处理等
   */
  private EmptyParamProcessor afterProcess = ()->{System.out.println("exe......");};

  public TemplateProcessor() {
  }

  public TemplateProcessor<T> buildCoreProcessor(Supplier<T> coreProcessor){
    this.coreProcessor = coreProcessor;
    return this;
  }

  public Supplier<T> getCoreProcessor() {
    return coreProcessor;
  }

  public EmptyParamProcessor getCheckParams() {
    return checkParams;
  }

  public TemplateProcessor<T> buildCheckParams(EmptyParamProcessor checkParams) {
    this.checkParams = checkParams;
    return this;
  }

  public EmptyParamProcessor getBeforeProcess() {
    return beforeProcess;
  }

  public TemplateProcessor<T> buildBeforeProcess(EmptyParamProcessor beforeProcess) {
    this.beforeProcess = beforeProcess;
    return this;
  }

  public EmptyParamProcessor getAfterProcess() {
    return afterProcess;
  }

  public TemplateProcessor<T> buildAfterProcess(EmptyParamProcessor afterProcess) {
    this.afterProcess = afterProcess;
    return this;
  }

  public TemplateProcessor<T> build(){
    return this;
  }

}


text:
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace WPLTests
{
    TEST_CLASS(ErrorTests)
    {
    public:
        TEST_METHOD(TestCannotFindFile)
        {
            wpl::VideoPlayer videoPlayer;

            if(videoPlayer.openVideo("doesntexists.wmv"))
            {
                Assert::Fail(L"Error this file doesnt exist and should return false to indicate failure");
            }
        }
    };
}


text:
/*!
  \file		cpuid.c
  \brief	Provides support for cpu identification.
*/

#include <ace.h>
#include <string.h>
#include <ds/bits.h>
#include <kernel/i386/cpuid.h>
#include <kernel/i386/processor.h>

/*! Executes CPUID instruction and stores the result
	\param raw - buffer to store the result
	\note raw->eax and raw->ecx are used to select the CPUID level
*/
static inline void ExecuteCpuId(CPUID_RESULT_PTR raw)
{
	__asm__ volatile("cpuid"
		:
			"=a" ( raw->eax ),
			"=b" ( raw->ebx ),
			"=c" ( raw->ecx ),
			"=d" ( raw->edx )
		:
			"a" ( raw->eax ),
			"c" ( raw->ecx )
		);
}
/*! Executes CPUID instruction on the current cpu and fills given cpuid_info structure.
	\param cpuid_info - CPUID information will be filled in this structure.
*/
void LoadCpuIdInfo(CPUID_INFO_PTR cpuid_info)
{
	int i,j;
	UINT32 tmp;

	/*initalize the data*/
	memset( cpuid_info, 0, sizeof(CPUID_INFO) );

	/*find the max level and vendor id*/
	cpuid_info->basic.raw.eax = CPUID_STD_VENDOR_ID;
	ExecuteCpuId( &cpuid_info->basic.raw );

	/*correct the vendor string*/
	tmp = cpuid_info->basic.raw.ecx;
	cpuid_info->basic.raw.ecx = cpuid_info->basic.raw.edx;
	cpuid_info->basic.raw.edx = tmp;

	/*loop and load all levels*/
	for(i=1; i <= cpuid_info->basic._.max_std_level && i <= CPUID_MAX_STD_LEVELS; i++ )
	{
		CPUID_RESULT_PTR data;
		switch(i)
		{
			case CPUID_STD_PROCESSOR_TYPE:
				data = &cpuid_info->feature.raw;
				break;
			case CPUID_STD_PROCESSOR_SERIAL_NUMBER:
				data = &cpuid_info->processor_serial_number.raw;
				break;
			case CPUID_STD_CACHE_CONFIGURATION_DESCRIPTORS:
				for (j=0;j<CPUID_MAX_CACHE_CONFIGURATION;j++)
				{
					data = &cpuid_info->cache_configuration_descriptor[j].raw;
					cpuid_info->basic.raw.eax = i;
					cpuid_info->basic.raw.ecx = j;
					ExecuteCpuId( data );
				}
				continue;
			case CPUID_STD_MONITOR_INFORMATION:
				data = &cpuid_info->monitor_information.raw;
				break;
			case CPUID_STD_POWER_MANAGEMENT_INFORMATION:
				data = &cpuid_info->power_management_information.raw;
				break;
			case CPUID_STD_DCA_PARAMETER:
				data = &cpuid_info->dca_information.raw;
				break;
			case CPUID_STD_PERFORMANCE_MONITOR_INFORMATION:
				data = &cpuid_info->performance_monitor_information.raw;
				break;
			default:
				continue;
		};
		data->eax = i;
		ExecuteCpuId( data );
	}
}


text:
Public Class time_distorter_0
    Dim moveable As Boolean = True
    Dim mexlocation, meylocation As Integer
    Dim mewidth, meheight As Integer
    Dim count As Integer
    Dim year As Integer
    Dim maximize As Boolean

    Private Sub programtopbar_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles programtopbar.MouseDown
        If moveable Then
            If e.Button = MouseButtons.Left Then
                programtopbar.Capture = False
                Const WM_NCLBUTTONDOWN As Integer = &HA1S
                Const HTCAPTION As Integer = 2
                Dim msg As Message = _
                    Message.Create(Me.Handle, WM_NCLBUTTONDOWN, _
                        New IntPtr(HTCAPTION), IntPtr.Zero)
                Me.DefWndProc(msg)
            End If
        End If
    End Sub

    Private Sub closebutton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closebutton.Click

    End Sub

    Private Sub pullside_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pullside.Tick
        Me.Width = Cursor.Position.X - Me.Location.X
    End Sub

    Private Sub pullbottom_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pullbottom.Tick
        Me.Height = Cursor.Position.Y - Me.Location.Y
    End Sub

    Private Sub pullbs_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles pullbs.Tick
        Me.Width = Cursor.Position.X - Me.Location.X
        Me.Height = Cursor.Position.Y - Me.Location.Y
    End Sub

    Private Sub Rightpull_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles right.MouseDown
        pullside.Start()
    End Sub

    Private Sub rightpull_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles right.MouseUp
        pullside.Stop()
    End Sub

    Private Sub bottompull_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles bottom.MouseDown
        pullbottom.Start()
    End Sub

    Private Sub buttompull_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles bottom.MouseUp
        pullbottom.Stop()
    End Sub

    Private Sub bspull_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles bottomrightcorner.MouseDown
        pullbs.Start()
    End Sub

    Private Sub bspull_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles bottomrightcorner.MouseUp
        pullbs.Stop()
    End Sub

    Private Sub maximizebutton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles maximizebutton.Click
        If Not maximize Then
            meylocation = Windows95.desktopicons.Height - Me.Height
            mexlocation = Windows95.desktopicons.Width - Me.Width
            mewidth = Me.Width
            meheight = Me.Height
            toprightcorner.Hide()
            topleftcorner.Hide()
            bottomrightcorner.Hide()
            bottomleftcorner.Hide()
            left.Hide()
            top.Hide()
            bottom.Hide()
            right.Hide()
            Dim w, h As Integer
            w = Windows95.desktopicons.Width
            h = Windows95.desktopicons.Height
            Me.Location = New Point(0, 0)
            Me.Size = New Size(w, h)
            moveable = False
            maximizebutton.Image = My.Resources.unmaximizebutton
            maximize = True
        Else
            toprightcorner.Show()
            topleftcorner.Show()
            bottomrightcorner.Show()
            bottomleftcorner.Show()
            left.Show()
            top.Show()
            bottom.Show()
            right.Show()
            Me.Location = New Point(mexlocation, meylocation)
            Me.Size = New Size(mewidth, meheight)
            moveable = True
            maximizebutton.Image = My.Resources.Maximize
            maximize = False
        End If
    End Sub

    Private Sub look_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles look.Tick
        Me.programtopbar.BackColor = Windows95.exampleprogramtopbar.BackColor
        Me.programtopbar.BackgroundImage = Windows95.exampleprogramtopbar.BackgroundImage
        Me.programname.BackColor = Windows95.exampleprogramtext.BackColor
    End Sub

    Private Sub minimizebutton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles minimizebutton.Click
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        waitfor02download = False
        Label3.Show()
        If Label3.Text = "Preparing travel: 180 Seconds" Then
            countdown.Start()
            count2000 = 180
            Button1.Hide()
        End If

    End Sub

    Private Sub labelcurrentyear_Click(sender As Object, e As EventArgs) Handles labelcurrentyear.Click

    End Sub

    Private Sub countdown_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles countdown.Tick
        If count = 145 Then
            WebChat_1999.history.Text = WebChat_1999.history.Text + ("12padams: The most important thing now is preparing for when " & mainname & " gets to the year 2000" & Environment.NewLine)
        End If
        If count = 149 Then
            WebChat_1999.history.Text = WebChat_1999.history.Text + ("12padams: Now we have to stop chatting about who gets to do what now " & Environment.NewLine)
        End If
        If count = 153 Then
            WebChat_1999.history.Text = WebChat_1999.history.Text + ("The Hidden Hacker: Hmm I would prefere to be me then..." & Environment.NewLine)
        End If
        If count = 157 Then
            WebChat_1999.history.Text = WebChat_1999.history.Text + ("12padams: Well accually " & mainname & " will need to go back to 1998 after experiencing all the future tech so..." & Environment.NewLine)
        End If
        If count = 161 Then
            WebChat_1999.history.Text = WebChat_1999.history.Text + ("The Hidden Hacker: Ok... " & mainname & " you should feel happy that you don't have to wait a whole year for results " & Environment.NewLine)
        End If
        If count = 166 Then
            WebChat_1999.history.Text = WebChat_1999.history.Text + ("12padams: Hey hidden hacker... if your doing tests like this they take time... just be patient " & Environment.NewLine)
        End If
        If count = 171 Then
            WebChat_1999.history.Text = WebChat_1999.history.Text + ("The Hidden Hacker: Oh great not another whole year :( " & Environment.NewLine)
        End If
        If count = 174 Then
            WebChat_1999.history.Text = WebChat_1999.history.Text + ("12padams: your wrong... 3 minutes for " & mainname & " and 1 year for us..." & Environment.NewLine)
        End If
        If count = 178 Then
            WebChat_1999.history.Text = WebChat_1999.history.Text + ("The Hidden Hacker: Hmm 3 minutes and we get to see the results to this test " & Environment.NewLine)
        End If
        count2000 = count2000 - 1
        Label3.Text = "Preparing travel: " & count2000 & " Seconds"

        If count2000 = 0 Then

            Label3.Hide()
        End If

        If count2000 = -1 Then

            Label2.Hide()

        End If

        If count2000 = -2 Then Label1.Hide()
        If count2000 = -3 Then

            countdown.Interval = 200
            Windows98.startbutton.Hide()
        End If

        If count2000 = -4 Then Windows98.desktopicons.Hide()
        If count2000 = -5 Then Windows98.taskbar.Hide()
        If count2000 = -6 Then Me.Location = New Point(400, 600)
        If count2000 = -7 Then
            Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
            Me.WindowState = FormWindowState.Maximized
        End If
        If count2000 = -8 Then Me.programtopbar.Hide()
        If count2000 = -9 Then Windows98.Hide()
        If count2000 = -10 Then top.Hide()
        If count2000 = -11 Then left.Hide()
        If count2000 = -12 Then bottom.Hide()
        If count2000 = -13 Then right.Hide()
        If count2000 = -14 Then
            toprightcorner.Hide()
            bottomleftcorner.Hide()
            bottomrightcorner.Hide()
            topleftcorner.Hide()
        End If
        If count2000 = -15 Then
            program.BackColor = Color.Black
            labelcurrentyear.ForeColor = Color.Lime
        End If
        If count2000 = -16 Then
            labelcurrentyear.Text = "1999"
            countdown.Interval = 100
        End If
        If count2000 = -17 Then
            labelcurrentyear.Text = "1999"
        End If
        If count2000 = -18 Then
            labelcurrentyear.Text = "1999"
        End If
        If count2000 = -19 Then
            labelcurrentyear.Text = "1999"
        End If
        If count2000 = -20 Then
            labelcurrentyear.Text = "1999"
        End If
        If count2000 = -21 Then
            labelcurrentyear.Text = "1999"
        End If
        If count2000 = -22 Then
            labelcurrentyear.Text = "1999"
        End If
        If count2000 = -23 Then
            labelcurrentyear.Text = "2000"
        End If
        If count2000 = -24 Then
            labelcurrentyear.Text = "2000"
        End If
        If count2000 = -25 Then
            labelcurrentyear.Text = "2000"
        End If
        If count2000 = -26 Then
            labelcurrentyear.Text = "1900"
        End If
        If count2000 = -27 Then
            labelcurrentyear.Hide()
        End If
        If count2000 = -28 Then
            labelcurrentyear.Show()
        End If
        If count2000 = -29 Then
            labelcurrentyear.Text = "2000"
        End If
        If count2000 = -30 Then
            labelcurrentyear.Text = "1900"
            year = labelcurrentyear.Text
        End If
        If count2000 < -30 And count2000 > -130 Then
            countdown.Interval = 80
            year = year + 1
            labelcurrentyear.Text = year
        End If
        If count2000 = -131 Then labelcurrentyear.Hide()
        If count2000 = -132 Then labelcurrentyear.Show()
        If count2000 = -133 Then labelcurrentyear.Hide()
        If count2000 = -134 Then labelcurrentyear.Show()
        If count2000 = -135 Then
            labelcurrentyear.Text = "2000"
        End If
        If count2000 = -136 Then labelcurrentyear.Hide()
        If count2000 = -137 Then labelcurrentyear.Show()
        If count2000 = -138 Then labelcurrentyear.Hide()
        If count2000 = -139 Then labelcurrentyear.Show()
        If count2000 = -140 Then labelcurrentyear.Text = "2001"
        If count2000 = -141 Then labelcurrentyear.Hide()
        If count2000 = -142 Then labelcurrentyear.Show()
        If count2000 = -143 Then labelcurrentyear.Hide()
        If count2000 = -144 Then labelcurrentyear.Show()
        If count2000 = -145 Then labelcurrentyear.Text = "2002"
        If count2000 = -146 Then labelcurrentyear.Hide()
        If count2000 = -147 Then labelcurrentyear.Show()
        If count2000 = -148 Then labelcurrentyear.Hide()
        If count2000 = -149 Then labelcurrentyear.Show()
        If count2000 = -169 Then Windowsxp2002damaged.Show()
        If count2000 = -170 Then Me.Hide()
    End Sub

    Private Sub time_distorter_0_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Label3.Hide()

    End Sub

End Class


text:
class ofApp : public ofBaseApp{

public:
    ~ofApp();
    void setup();
    void update();
    void draw();

    void downloadStart(float & i);
    void downloadFinish(string & file);
    void downloadProgress(float & i);

    void keyPressed(int key);
    void keyReleased(int key);
    void mouseMoved(int x, int y );
    void mouseDragged(int x, int y, int button);
    void mousePressed(int x, int y, int button);
    void mouseReleased(int x, int y, int button);
    void windowResized(int w, int h);
    void dragEvent(ofDragInfo dragInfo);
    void gotMessage(ofMessage msg);

private:

    ofxEdgerControl edgertronic;
    ofVideoPlayer video;

    bool loaded;
};


text:
\documentclass[a4paper,12pt]{article}
\usepackage{fullpage}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage[utf8]{inputenc}
\usepackage{color}
\usepackage{authblk}
\usepackage{todonotes}
\usepackage{caption}
\usepackage{url}
\usepackage{float}
\usepackage{sectsty}
\usepackage{pdfpages}
\usepackage[section]{placeins}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\textwidth}{#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white}

\usepackage{setspace}
\usepackage[toc,page]{appendix}
\usepackage{framed}
\usepackage{geometry}

\usepackage{alltt}
\usepackage{subfig}

% Change section fonts
\allsectionsfont{\sffamily}

% For code box
\usepackage{xcolor}
\usepackage{listings}
\usepackage{caption}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{%
  \parbox{\textwidth}{\colorbox{gray}{\parbox{\textwidth}{#1#2#3}}\vskip-4pt}}
  \captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white}
  \lstset{frame=lrb,xleftmargin=\fboxsep,xrightmargin=-\fboxsep}
% End code box

\usepackage{cite}

% General parameters, for ALL pages:
\renewcommand{\topfraction}{0.9}	% max fraction of floats at top
\renewcommand{\bottomfraction}{0.8}	% max fraction of floats at bottom
% Parameters for TEXT pages (not float pages):
\setcounter{topnumber}{2}
\setcounter{bottomnumber}{2}
\setcounter{totalnumber}{4} % 2 may work better
\setcounter{dbltopnumber}{2} % for 2-column pages

\addtolength{\topmargin}{0.5in}

\usepackage{fancyvrb}

\usepackage{tikz} \usetikzlibrary{trees}
\usepackage{hyperref} % should always be the last package

% useful colours (use sparingly!):
\newcommand{\blue}[1]{{\color{blue}#1}}
\newcommand{\green}[1]{{\color{green}#1}}
\newcommand{\red}[1]{{\color{red}#1}}

% useful wrappers for algorithmic/Python notation:
\newcommand{\length}[1]{\text{len}(#1)}
\newcommand{\twodots}{\mathinner{\ldotp\ldotp}} % taken from clrscode3e.sty
\newcommand{\Oh}[1]{\mathcal{O}\left(#1\right)}

% useful (wrappers for) math symbols:
\newcommand{\Cardinality}[1]{\left\lvert#1\right\rvert}
\newcommand{\Ceiling}[1]{\left\lceil#1\right\rceil}
\newcommand{\Floor}[1]{\left\lfloor#1\right\rfloor}
\newcommand{\Iff}{\Leftrightarrow}
\newcommand{\Implies}{\Rightarrow}
\newcommand{\Intersect}{\cap}
\newcommand{\Sequence}[1]{\left[#1\right]}
\newcommand{\Set}[1]{\left\{#1\right\}}
\newcommand{\SetComp}[2]{\Set{#1\SuchThat#2}}
\newcommand{\SuchThat}{\mid}
\newcommand{\Tuple}[1]{\langle#1\rangle}
\newcommand{\Union}{\cup}
\usetikzlibrary{positioning,shapes,shadows,arrows}

\renewcommand{\abstractname}{Elfin - URL Shortener}

\title{\textbf{Elfin - URL Shortener}}
\author{Lukas Klingsbo}
\begin{document}
\maketitle

\begin{abstract}
I was given this task by Uprise, as an exercise to show my capabilities.\\
This URL shortener is built with Scala 2.11.7 and the Lift 2.6 Framework.
The result can be seen on \url{http://elfin.se}

\textbf{Disclaimer:} This is the first Lift project that I have
coded so please forgive any horrible breaking of convention
that I might have unintentionally made.
\begin{center}
If you have any questions,\\
feel free to contact me on:\\
\vspace{10pt}
Lukas Klingsbo\\
+46737-42 43 45\\
lukas.klingsbo@gmail.com\\
\end{center}

\section{Background}
The task was to make a scalable URL shortener that deterministically shortened
the URL's fed to it.

\section{Design decisions}
The shortener core code was written with the help of MurmurHash3 which I use
to convert the $URL \Rightarrow Int \Rightarrow String \Rightarrow URL$.

Another design choice that was considered was using an auto incremented value
in a database that was to be converted to a string. This would have yielded
shorter strings and avoided the problem with collisions that occur when using
short hashes. The first design choice was chosen as the exercise stated that
the same link preferably always should produce the same short URL. It also
gives the advantage that the keys does not have to be synchronized on creation
to the distributed KV-store, they still have to be synchronized for fetching
though.

\subsection{Database}
As the task was to make a scalable URL shortener with high availability, the
choice to use a distributed database (in production) was made.
Two Key-Value stores were looked into, Riak and Redis. Redis was choosen simply
because it had better support for Scala. When deploying Redis for production
for this project I recommend using a single master + replicas and then use
Sentinel for automatic failover. Which will make the system scalable and
extremely fault tolerant as there is no sharding, all data will exist on all
of the nodes and when the master goes down a new one is selected to become
master by Sentinel.

As the algorithm for determining short URL's is deterministic as many web
servers as needed can be used individually with a load balancer to scale
the application.

\subsection{Variable Key length}
When using such short hashes that are used here, collisions are
unavoidable (See the pigeonhole principle). So consider how much entropy
you need for the intended usage and set a fixed length of the key before
deploying this application.

\section{Setup}
To try this application you can either use SBT directly or package a WAR
file and deploy it on a web server and java servlet containers like Jetty
or Tomcat. An instance of Redis is also needed to properly run the
application.

\section{Todo}
In a future version the history of shortened URL's should be provided to
the user by linking the URL's to the users session key.

\pagenumbering{gobble} % Remove page numbers (and reset to 1)
\end{abstract}
\end{document}


text:
using System.Collections.Generic;

namespace Binance.Serialization
{
    public interface ISymbolStatisticsSerializer
    {
        /// <summary>
        /// Deserialize JSON to an <see cref="SymbolStatistics"/>.
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        SymbolStatistics Deserialize(string json);

        /// <summary>
        /// Deserialize JSON to multiple <see cref="SymbolStatistics"/> instances.
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        IEnumerable<SymbolStatistics> DeserializeMany(string json);

        /// <summary>
        /// Serialize an <see cref="SymbolStatistics"/> to JSON.
        /// </summary>
        /// <param name="statistics"></param>
        /// <returns></returns>
        string Serialize(SymbolStatistics statistics);
    }
}