text:
-- Clustered Columnstore
drop table if exists dbo.EmptyCCI;

create table dbo.EmptyCCI(
	c1 int );

create clustered columnstore index CCI_EmptyCCI
	on dbo.EmptyCCI;

-- Nonclustered Columnstore on HEAP
drop table if exists dbo.EmptyNCI_Heap;

create table dbo.EmptyNCI_Heap(
	c1 int );

create nonclustered columnstore index CCI_EmptyNCI_Heap
	on dbo.EmptyNCI_Heap (c1);

-- Nonclustered Columnstore on Clustered Index
drop table if exists dbo.EmptyNCI_Clustered;

create table dbo.EmptyNCI_Clustered(
	c1 int not null primary key clustered );

create nonclustered columnstore index NCI_EmptyNCI_Clustered
	on dbo.EmptyNCI_Clustered (c1);

-- **************************************************************************************
-- Clustered Columnstore
drop table if exists dbo.OneRowCCI;

create table dbo.OneRowCCI(
	c1 int );

create clustered columnstore index CCI_OneRowCCI
	on dbo.OneRowCCI;

insert into dbo.OneRowCCI
	values (1)

-- Nonclustered Columnstore on HEAP
drop table if exists dbo.OneRowNCI_Heap;

create table dbo.OneRowNCI_Heap(
	c1 int );

insert into dbo.OneRowNCI_Heap
	values (1)
option( recompile );

create nonclustered columnstore index NCI_OneRowNCI_Heap
	on dbo.OneRowNCI_Heap(c1);

-- Nonclustered Columnstore on Clustered Index
drop table if exists dbo.OneRowNCI_Clustered;

create table dbo.OneRowNCI_Clustered(
	c1 int not null primary key clustered );

insert into dbo.OneRowNCI_Clustered
	values (1)
option( recompile );

create nonclustered columnstore index NCI_OneRowNCI_Clustered
	on dbo.OneRowNCI_Clustered(c1);

-- **************************************************************************************
-- Clustered Columnstore table with an Empty Delta Store
drop table if exists dbo.EmptyDeltaStoreCCI;

create table dbo.EmptyDeltaStoreCCI(
	c1 int );

create clustered columnstore index CCI_EmptyDeltaStoreCCI
	on dbo.EmptyDeltaStoreCCI;

insert into dbo.EmptyDeltaStoreCCI
	values (1);

delete from dbo.EmptyDeltaStoreCCI;

alter index CCI_EmptyDeltaStoreCCI
	on dbo.EmptyDeltaStoreCCI
		Reorganize;

-- **************************************************************************************
-- Clustered Columnstore table with 2 Row Groups - 1 compressed with 1 Row and 1 Delta Store containing 1 row

drop table if exists dbo.RowGroupAndDeltaCCI;

create table dbo.RowGroupAndDeltaCCI(
	c1 int );

create clustered columnstore index CCI_RowGroupAndDeltaCCI
	on dbo.RowGroupAndDeltaCCI;

insert into dbo.RowGroupAndDeltaCCI
	values (1);

alter table dbo.RowGroupAndDeltaCCI
	rebuild;

insert into dbo.RowGroupAndDeltaCCI
	values (2);

-- **************************************************************************************
-- Clustered Columnstore table with 1 compressed Row Group containing 1 row that is deleted

drop table if exists dbo.OneDeletedRowGroupCCI;

create table dbo.OneDeletedRowGroupCCI(
	c1 int );

create clustered columnstore index CCI_OneDeletedRowGroupCCI
	on dbo.OneDeletedRowGroupCCI;

insert into dbo.OneDeletedRowGroupCCI
	values (1);

alter table dbo.OneDeletedRowGroupCCI
	rebuild;

delete from dbo.OneDeletedRowGroupCCI
	where c1 = 1;

-- **************************************************************************************
-- Suggested Tables scenario Test 1: 500.000 rows in a simple table with 1 integer column

drop table if exists dbo.SuggestedTables_Test1;

create table dbo.SuggestedTables_Test1(
	c1 int identity(1,1) not null
) WITH (DATA_COMPRESSION = PAGE);

set nocount on;
declare @i as int;
declare @max as int;
select @max = isnull(max(C1),0) from dbo.SuggestedTables_Test1;
set @i = 1;

begin tran
while @i <= 500000
begin
	insert into dbo.SuggestedTables_Test1
		default values

	set @i+=1;
end;
commit;


text:
package com.amazonaws.services.glue.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetJobRunsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The name of the job definition for which to retrieve all job runs.
     *

     */
    private String jobName;
    /**
     *

     * A continuation token, if this is a continuation call.
     *

     */
    private String nextToken;
    /**
     *

     * The maximum size of the response.
     *

     */
    private Integer maxResults;

    /**
     *

     * The name of the job definition for which to retrieve all job runs.
     *

     *
     * @param jobName
     *        The name of the job definition for which to retrieve all job runs.
     */

    public void setJobName(String jobName) {
        this.jobName = jobName;
    }

    /**
     *

     * The name of the job definition for which to retrieve all job runs.
     *

     *
     * @return The name of the job definition for which to retrieve all job runs.
     */

    public String getJobName() {
        return this.jobName;
    }

    /**
     *

     * The name of the job definition for which to retrieve all job runs.
     *

     *
     * @param jobName
     *        The name of the job definition for which to retrieve all job runs.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetJobRunsRequest withJobName(String jobName) {
        setJobName(jobName);
        return this;
    }

    /**
     *

     * A continuation token, if this is a continuation call.
     *

     *
     * @param nextToken
     *        A continuation token, if this is a continuation call.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * A continuation token, if this is a continuation call.
     *

     *
     * @return A continuation token, if this is a continuation call.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * A continuation token, if this is a continuation call.
     *

     *
     * @param nextToken
     *        A continuation token, if this is a continuation call.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetJobRunsRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     *

     * The maximum size of the response.
     *

     *
     * @param maxResults
     *        The maximum size of the response.
     */

    public void setMaxResults(Integer maxResults) {
        this.maxResults = maxResults;
    }

    /**
     *

     * The maximum size of the response.
     *

     *
     * @return The maximum size of the response.
     */

    public Integer getMaxResults() {
        return this.maxResults;
    }

    /**
     *

     * The maximum size of the response.
     *

     *
     * @param maxResults
     *        The maximum size of the response.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetJobRunsRequest withMaxResults(Integer maxResults) {
        setMaxResults(maxResults);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getJobName() != null)
            sb.append("JobName: ").append(getJobName()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken()).append(",");
        if (getMaxResults() != null)
            sb.append("MaxResults: ").append(getMaxResults());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetJobRunsRequest == false)
            return false;
        GetJobRunsRequest other = (GetJobRunsRequest) obj;
        if (other.getJobName() == null ^ this.getJobName() == null)
            return false;
        if (other.getJobName() != null && other.getJobName().equals(this.getJobName()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        if (other.getMaxResults() == null ^ this.getMaxResults() == null)
            return false;
        if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getJobName() == null) ? 0 : getJobName().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
        return hashCode;
    }

    @Override
    public GetJobRunsRequest clone() {
        return (GetJobRunsRequest) super.clone();
    }

}

redpajama_set_name: RedPajamaGithub


text:
if [ -n "${TRAVIS_TAG}" ]; then
    TARGET=$TRAVIS_TAG
else
    TARGET="commit ${TRAVIS_COMMIT}"
fi

# Set up a temporary folder to prepare distribution files.
TMP=~/tmp
mkdir $TMP
# Copy everything to the this folder first, then clean up.
cp -a dist $TMP/
# Copy all visible root files (LICENSE.txt, README.md, package.json, etc.).
cp -p *.* $TMP/
# No need for .gitignore or build files.
rm $TMP/dist/.gitignore
rm $TMP/gulpfile.js
# Reset the branch so we can switch to prebuilt/module and prebuilt/dist after.
git clean -fdx --quiet # Remove all ignored and untracked files from the build.
git checkout -- . # Reset all tracked files to the original state.

# Create a new orphaned buid/dist branch and switch to it.
git checkout --orphan prebuilt/dist
# Remove and delete all tracked files left after the switch.
git rm -rf --quiet .
# Move the zipped dist file into the branch and commit.
mv $TMP/dist/paperjs.zip .
git add --all *
git commit -m "Prebuilt package for ${TARGET}"
# Push with --force since we're always overriding the previous built version.
git push -u origin prebuilt/dist --force

# Specifically fetch and check out the prebuilt/module branch from origin.
git fetch origin +refs/heads/prebuilt/module:refs/remotes/origin/prebuilt/module
git checkout -b prebuilt/module -t origin/prebuilt/module
# Remove everything so we can fully replace it. Git will create the diffs.
rm -fr *
mv $TMP/* .
git add --all *
git commit -m "Prebuilt module for ${TARGET}"
git push -u origin prebuilt/module
rmdir $TMP


text:
package org.qi4j.library.locking;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import org.qi4j.api.common.AppliesTo;
import org.qi4j.api.concern.ConcernOf;
import org.qi4j.api.injection.scope.This;

/**
 * Applies read-lock to Composite
 */
@AppliesTo( ReadLock.class )
public class ReadLockConcern
    extends ConcernOf<InvocationHandler>
    implements InvocationHandler
{
    private
    @This
    ReadWriteLock lock;

    @Override
    public Object invoke( Object o, Method method, Object[] objects )
        throws Throwable
    {
        Lock readLock = lock.readLock();
        lock( readLock );
        try
        {
            return next.invoke( o, method, objects );
        }
        finally
        {
            try
            {
                lock.readLock().unlock();
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * Fix for this bug:
     * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6822370
     *
     * @param lock
     */
    protected void lock( Lock lock )
    {
        while(true)
        {
            try
            {
                while( !(lock.tryLock() || lock.tryLock( 1000, TimeUnit.MILLISECONDS )) )
                {
                    // On timeout, try again
                }
                return; // Finally got a lock
            }
            catch( InterruptedException e )
            {
                // Try again
            }
        }
    }
}


text:
countdown_game
==============

A program to create and solve the countdown numbers game.

    usage: countdown_numbers.py [-h] (--choose N N | --numbers N [N ...])
                                [--target TARGET] [--relaxed]

    Plays the Countdown numbers game

    optional arguments:
      -h, --help            show this help message and exit
      --choose N N, -c N N  Number of cards to choose. First the number of low
                            cards. Second is the number of high cards. Total cards
                            chosen must be equal to 6 unless --relaxed is
                            specified. There are a maximum of 4 high cards and 20
                            low cards to choose from.
      --numbers N [N ...], -n N [N ...]
                            Specify cards to use. Number of cards must be 6,
                            unless --relaxed is specified.
      --target TARGET, -t TARGET
                            Must be a number between 100 and 999 unless --relaxed
                            is specified.
      --relaxed, -r         Relaxes the problem constraints so the problem doesn't
                            have to exactly match the Countdown numbers game. That
                            is, have exactly 6 cards and a target between 100 and
                            999.

Compatible with both Python 2 and Python 3, though it runs slightly faster in Python 2.


text:
function [VARIANCE]=estimate_variance(MEANS,VARS)
%estimates the variance using the locfit package

IDX_ZERO=and(VARS>=0,MEANS>0);
VARIANCE =locfit(log(MEANS(IDX_ZERO)),VARS(IDX_ZERO),'family','gamma','acri','cp','deg',2,'maxk',1000);

return


text:
START_ATF_NAMESPACE
    namespace Detail
    {

        Info::_qry_case_amine_mineorector__qry_case_amine_mineore2_ptr _qry_case_amine_mineorector__qry_case_amine_mineore2_next(nullptr);
        Info::_qry_case_amine_mineorector__qry_case_amine_mineore2_clbk _qry_case_amine_mineorector__qry_case_amine_mineore2_user(nullptr);

        Info::_qry_case_amine_mineoresize4_ptr _qry_case_amine_mineoresize4_next(nullptr);
        Info::_qry_case_amine_mineoresize4_clbk _qry_case_amine_mineoresize4_user(nullptr);

        void _qry_case_amine_mineorector__qry_case_amine_mineore2_wrapper(struct _qry_case_amine_mineore* _this)
        {
           _qry_case_amine_mineorector__qry_case_amine_mineore2_user(_this, _qry_case_amine_mineorector__qry_case_amine_mineore2_next);
        };
        int _qry_case_amine_mineoresize4_wrapper(struct _qry_case_amine_mineore* _this)
        {
           return _qry_case_amine_mineoresize4_user(_this, _qry_case_amine_mineoresize4_next);
        };

        ::std::array<hook_record, 2> _qry_case_amine_mineore_functions =
        {
            _hook_record {
                (LPVOID)0x1402d4320L,
                (LPVOID *)&_qry_case_amine_mineorector__qry_case_amine_mineore2_user,
                (LPVOID *)&_qry_case_amine_mineorector__qry_case_amine_mineore2_next,
                (LPVOID)cast_pointer_function(_qry_case_amine_mineorector__qry_case_amine_mineore2_wrapper),
                (LPVOID)cast_pointer_function((void(_qry_case_amine_mineore::*)())&_qry_case_amine_mineore::ctor__qry_case_amine_mineore)
            },
            _hook_record {
                (LPVOID)0x1402d4340L,
                (LPVOID *)&_qry_case_amine_mineoresize4_user,
                (LPVOID *)&_qry_case_amine_mineoresize4_next,
                (LPVOID)cast_pointer_function(_qry_case_amine_mineoresize4_wrapper),
                (LPVOID)cast_pointer_function((int(_qry_case_amine_mineore::*)())&_qry_case_amine_mineore::size)
            },
        };
    }; // end namespace Detail
END_ATF_NAMESPACE


text:
#include "common.hpp"
#include "deputado.hpp"
#include "empresa.hpp"
#include "gasto.hpp"

extern map<string,deputado> deputados;
extern map<string,empresa> empresas;
extern double custoTotal;

deputado::deputado(const string &n,const string &e,const string &p):nome{n},estado{e},partido{p}{}

void deputado::operator+=(const pair<gastoIndividual,string> &in){
	gastos[in.second] += in.first;
	empresas[in.second].clientes.insert(nome);
	empresas[in.second].total += in.first.valor;
	total += in.first.valor;
}

std::ostream& operator<<(std::ostream& os, const deputado& obj){
	return os/* << obj.nome << " " << obj.estado << " " << obj.partido << ": Gasto R$" << obj.total << " em " << obj.gastos << " empresas." << endl*/;
}


text:
/*
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

#import "CMISAtomPubNavigationService.h"
#import "CMISAtomPubBaseService+Protected.h"
#import "CMISAtomFeedParser.h"
#import "CMISHttpUtil.h"
#import "CMISHttpResponse.h"
#import "CMISErrors.h"
#import "CMISURLUtil.h"
#import "CMISObjectList.h"

@implementation CMISAtomPubNavigationService

- (void)retrieveChildren:(NSString *)objectId orderBy:(NSString *)orderBy
                  filter:(NSString *)filter includeRelationShips:(CMISIncludeRelationship)includeRelationship
         renditionFilter:(NSString *)renditionFilter includeAllowableActions:(BOOL)includeAllowableActions
      includePathSegment:(BOOL)includePathSegment skipCount:(NSNumber *)skipCount
                maxItems:(NSNumber *)maxItems
         completionBlock:(void (^)(CMISObjectList *objectList, NSError *error))completionBlock
{
    // Get Down link
    [self loadLinkForObjectId:objectId andRelation:kCMISLinkRelationDown
                      andType:kCMISMediaTypeChildren completionBlock:^(NSString *downLink, NSError *error) {
                          if (error)
                          {
                              log(@"Could not retrieve down link: %@", error.description);
                              completionBlock(nil, error);
                              return;
                          }

                          // Add optional params (CMISUrlUtil will not append if the param name or value is nil)
                          downLink = [CMISURLUtil urlStringByAppendingParameter:kCMISParameterFilter withValue:filter toUrlString:downLink];
                          downLink = [CMISURLUtil urlStringByAppendingParameter:kCMISParameterOrderBy withValue:orderBy toUrlString:downLink];
                          downLink = [CMISURLUtil urlStringByAppendingParameter:kCMISParameterIncludeAllowableActions withValue:(includeAllowableActions ? @"true" : @"false") toUrlString:downLink];
                          downLink = [CMISURLUtil urlStringByAppendingParameter:kCMISParameterIncludeRelationships withValue:[CMISEnums stringForIncludeRelationShip:includeRelationship] toUrlString:downLink];
                          downLink = [CMISURLUtil urlStringByAppendingParameter:kCMISParameterRenditionFilter withValue:renditionFilter toUrlString:downLink];
                          downLink = [CMISURLUtil urlStringByAppendingParameter:kCMISParameterIncludePathSegment withValue:(includePathSegment ? @"true" : @"false") toUrlString:downLink];
                          downLink = [CMISURLUtil urlStringByAppendingParameter:kCMISParameterMaxItems withValue:[maxItems stringValue] toUrlString:downLink];
                          downLink = [CMISURLUtil urlStringByAppendingParameter:kCMISParameterSkipCount withValue:[skipCount stringValue] toUrlString:downLink];

                          // execute the request
                          [HttpUtil invokeGET:[NSURL URLWithString:downLink]
                                  withSession:self.bindingSession
                              completionBlock:^(CMISHttpResponse *httpResponse, NSError *error) {
                                  if (httpResponse) {
                                      if (httpResponse.data == nil) {
                                          NSError *error = [CMISErrors createCMISErrorWithCode:kCMISErrorCodeConnection withDetailedDescription:nil];
                                          completionBlock(nil, error);
                                          return;
                                      }

                                      // Parse the feed (containing entries for the children) you get back
                                      CMISAtomFeedParser *parser = [[CMISAtomFeedParser alloc] initWithData:httpResponse.data];
                                      NSError *internalError = nil;
                                      if ([parser parseAndReturnError:&internalError])
                                      {
                                          NSString *nextLink = [parser.linkRelations linkHrefForRel:kCMISLinkRelationNext];

                                          CMISObjectList *objectList = [[CMISObjectList alloc] init];
                                          objectList.hasMoreItems = (nextLink != nil);
                                          objectList.numItems = parser.numItems;
                                          objectList.objects = parser.entries;
                                          completionBlock(objectList, nil);
                                      }
                                      else
                                      {
                                          NSError *error = [CMISErrors cmisError:internalError withCMISErrorCode:kCMISErrorCodeRuntime];
                                          completionBlock(nil, error);
                                      }
                                  } else {
                                      completionBlock(nil, error);
                                  }
                              }];
                      }];
}

- (void)retrieveParentsForObject:(NSString *)objectId
                           withFilter:(NSString *)filter
             withIncludeRelationships:(CMISIncludeRelationship)includeRelationship
                  withRenditionFilter:(NSString *)renditionFilter
          withIncludeAllowableActions:(BOOL)includeAllowableActions
       withIncludeRelativePathSegment:(BOOL)includeRelativePathSegment
                      completionBlock:(void (^)(NSArray *parents, NSError *error))completionBlock
{
    // Get up link
    [self loadLinkForObjectId:objectId andRelation:kCMISLinkRelationUp completionBlock:^(NSString *upLink, NSError *error) {
        if (upLink == nil) {
            log(@"Failing because the NSString upLink is nil");
            completionBlock([NSArray array], nil); // TODO: shouldn't this return an error if the log talks about 'failing'?
            return;
        }

        // Add optional parameters
        if (filter != nil)
        {
            upLink = [CMISURLUtil urlStringByAppendingParameter:kCMISParameterFilter withValue:filter toUrlString:upLink];
        }
        upLink = [CMISURLUtil urlStringByAppendingParameter:kCMISParameterIncludeAllowableActions withValue:(includeAllowableActions ? @"true" : @"false") toUrlString:upLink];
        upLink = [CMISURLUtil urlStringByAppendingParameter:kCMISParameterIncludeRelationships withValue:[CMISEnums stringForIncludeRelationShip:includeRelationship] toUrlString:upLink];

        if (renditionFilter != nil)
        {
            upLink = [CMISURLUtil urlStringByAppendingParameter:kCMISParameterRenditionFilter withValue:renditionFilter toUrlString:upLink];
        }

        upLink = [CMISURLUtil urlStringByAppendingParameter:kCMISParameterRelativePathSegment withValue:(includeRelativePathSegment ? @"true" : @"false") toUrlString:upLink];

        [HttpUtil invokeGET:[NSURL URLWithString:upLink]
                withSession:self.bindingSession
            completionBlock:^(CMISHttpResponse *httpResponse, NSError *error) {
                if (httpResponse) {
                    CMISAtomFeedParser *parser = [[CMISAtomFeedParser alloc] initWithData:httpResponse.data];
                    NSError *internalError;
                    if (![parser parseAndReturnError:&internalError])
                    {
                        NSError *error = [CMISErrors cmisError:internalError withCMISErrorCode:kCMISErrorCodeRuntime];
                        log(@"Failing because parsing the Atom Feed XML returns an error");
                        completionBlock([NSArray array], error);
                    } else {
                        completionBlock(parser.entries, nil);
                    }
                } else {
                    log(@"Failing because the invokeGET returns an error");
                    completionBlock([NSArray array], error);
                }
            }];
    }];
}

@end


text:
package io.github.hapjava.accessories;

import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback;
import io.github.hapjava.characteristics.impl.windowcovering.PositionStateEnum;
import io.github.hapjava.services.Service;
import io.github.hapjava.services.impl.WindowCoveringService;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;

/** A window covering, like blinds, which can be remotely controlled. */
public interface WindowCoveringAccessory extends HomekitAccessory {
  /**
   * Retrieves the current position
   *
   * @return a future that will contain the position as a value between 0 and 100
   */
  CompletableFuture<Integer> getCurrentPosition();

  /**
   * Retrieves the target position
   *
   * @return a future that will contain the target position as a value between 0 and 100
   */
  CompletableFuture<Integer> getTargetPosition();

  /**
   * Retrieves the state of the position: increasing, decreasing, or stopped
   *
   * @return a future that will contain the current state
   */
  CompletableFuture<PositionStateEnum> getPositionState();

  /**
   * Sets the target position
   *
   * @param position the target position to set, as a value between 1 and 100
   * @return a future that completes when the change is made
   * @throws Exception when the change cannot be made
   */
  CompletableFuture<Void> setTargetPosition(int position) throws Exception;

  /**
   * Subscribes to changes in the current position.
   *
   * @param callback the function to call when the state changes.
   */
  void subscribeCurrentPosition(HomekitCharacteristicChangeCallback callback);

  /**
   * Subscribes to changes in the target position.
   *
   * @param callback the function to call when the state changes.
   */
  void subscribeTargetPosition(HomekitCharacteristicChangeCallback callback);

  /**
   * Subscribes to changes in the position state: increasing, decreasing, or stopped
   *
   * @param callback the function to call when the state changes.
   */
  void subscribePositionState(HomekitCharacteristicChangeCallback callback);

  /** Unsubscribes from changes in the current position. */
  void unsubscribeCurrentPosition();

  /** Unsubscribes from changes in the target position. */
  void unsubscribeTargetPosition();

  /** Unsubscribes from changes in the position state */
  void unsubscribePositionState();

  @Override
  default Collection<Service> getServices() {
    return Collections.singleton(new WindowCoveringService(this));
  }
}


text:
package com.daytoday.app.AulaMagnaApp.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.daytoday.app.AulaMagnaApp.view.NewsViewHolder;
import com.daytoday.app.AulaMagnaApp.R;
import com.daytoday.app.AulaMagnaApp.activities.NewsActivity;
import com.daytoday.app.AulaMagnaApp.manager.News;

import java.util.List;

import io.realm.Realm;
import io.realm.RealmResults;

public class RVAdapter extends RecyclerView.Adapter<NewsViewHolder> {

    private List<News> noticias;
    private LayoutInflater inflater;

    public RVAdapter(Context context, List<News> persons){
        this.noticias = persons;
        this.inflater=LayoutInflater.from(context);
    }

    public RVAdapter(Context context, RealmResults<News> newsRealmResults) {
        this.noticias=newsRealmResults;
        this.inflater=LayoutInflater.from(context);
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public NewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = inflater.inflate(R.layout.item, viewGroup, false);
        return new NewsViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final NewsViewHolder personViewHolder, final int i) {

        final News news = noticias.get(i);
        personViewHolder.setNews(news);

        personViewHolder.itemView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            Intent intent = new Intent(v.getContext(),NewsActivity.class);
            News news = noticias.get(i);
            Realm realm = Realm.getDefaultInstance();
            RealmResults<News> realmResults = realm.where(News.class).findAll();

            for (News loadnews:realmResults) {
                noticias.add(loadnews);
            }
            intent.putExtra("news_id", news.getId());
            v.getContext().startActivity(intent);
            }

        });
      }

    @Override
    public int getItemCount() {
        return noticias.size();
    }
}


text:
module TokyoMetro::Modules::ToFactory::Api::Convert::Customize::StationTimetable::AdditionalInfos

  def self.set_modules
    ::TokyoMetro::Factory::Generate::Api::StationTimetable::List.class_eval do
      include ::TokyoMetro::Modules::ToFactory::Api::Convert::Customize::StationTimetable::AdditionalInfos::Generate::List
    end
  end

end


text:
function y = square_pos( x )

%SQUARE_POS    Square of positive part.
%   SQUARE_POS(X) is the square of the postive parts of the elements of X;
%   i.e., SQUARE_POS(X)=MAX(X,0).^2. X must be real.
%
%   Disciplined convex programming information:
%       SQUARE_POS(X) is convex and nondecreasing in X. Thus when used in
%       CVX expressions, X must be convex (or affine).

error( nargchk( 1, 1, nargin ) );
if ~isreal( x ),
    error( 'Argument must be real.' );
end

y = square( max( x, 0 ) );

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.Data.Conventions;

namespace DM.Orchard.DynamicForms.Models
{
    public class DynamicFormResponseRecord
    {
        public virtual int Id { get; set; }

        /// <summary>
        /// The type of the activity.
        /// </summary>

        //    public virtual int DynamicFormDefinitionRecord_id { get; set; }

        public virtual int DynamicFormRecord_id { get; set; }
        //public virtual DynamicFormPartRecord DynamicFormRecord { get; set; }
        //public virtual int ContentID { get; set; }
        /// <summary>
        /// The top coordinate of the activity.
        /// </summary>

        [StringLengthMax]
        public virtual string Response { get; set; }

    }
}


text:
package com.leocardz.pix.color.analyzer.core;

/**
 * Created by leocardz on 15/09/2014.
 */

public class ColorAmount {

    private PixelColor color;
    private MutableInt amount;

    public ColorAmount(PixelColor color, MutableInt amount) {
        this.color = color;
        this.amount = amount;
    }

    public PixelColor getColor() {
        return color;
    }

    public Integer getAmount() {
        return amount.get();
    }

}


text:
package de.l3s.eumssi.news;
/**
 * parsing the output from Reddit NER-ed text
 * @author giangbinhtran
 *
 */
public class RedditNER {

	public static void parse(String text) {

	}

}


text:
package io.airlift.http.server;

import com.google.common.util.concurrent.SettableFuture;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.concurrent.Future;

import static com.google.common.util.concurrent.Futures.nonCancellationPropagating;
import static javax.servlet.http.HttpServletResponse.SC_OK;

class DummyServlet
        extends HttpServlet
{
    private final SettableFuture<?> sleeping = SettableFuture.create();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException
    {
        response.setStatus(SC_OK);
        if (request.getUserPrincipal() != null) {
            response.getOutputStream().write(request.getUserPrincipal().getName().getBytes());
        }
        response.setHeader("X-Protocol", request.getProtocol());

        try {
            if (request.getParameter("sleep") != null) {
                sleeping.set(null);
                Thread.sleep(Long.parseLong(request.getParameter("sleep")));
            }
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public Future<?> getSleeping()
    {
        return nonCancellationPropagating(sleeping);
    }
}


text:
galpy.util.bovy_coords.sphergal_to_rectgal
===========================================

.. autofunction:: galpy.util.bovy_coords.sphergal_to_rectgal


text:
<?php

Route::get('products/{slug}', 'ProductController@view');
Route::post('cart-add', array(
	'before' => 'csrf',
	'uses' => 'ProductController@cart_add'
));
Route::post('cart-qty', array(
	'before' => 'csrf',
	'uses' => 'ProductController@cart_qty'
));
Route::get('cart-remove/{key}', 'ProductController@cart_remove');
Route::get('cart', 'ProductController@cart');
Route::get('checkout', 'ProductController@checkout');
Route::post('checkout', array(
	'before' => 'csrf',
	'uses' => 'ProductController@charge'
));
Route::get('inventory-fail', 'ProductController@inventory_fail');
Route::get('order-summary', 'ProductController@order_summary');

Route::group(array('prefix'=>admin_uri('orders'), 'before'=>'admin'), function() {
	$controller = 'AdminOrderController';

	Route::get('/', $controller . '@index');
	Route::get('show/{id}', $controller . '@show');
	Route::post('mark-shipped/{id}', array(
		'before' => 'csrf',
		'uses' => $controller . '@mark_shipped'
	));
	Route::post('tracking/{id}', array(
		'before' => 'csrf',
		'uses' => $controller . '@tracking'
	));
	Route::post('send-tracking/{id}', array(
		'before' => 'csrf',
		'uses' => $controller . '@send_tracking'
	));
});

Route::group(array('prefix'=>admin_uri('products'), 'before'=>'admin'), function() {

	$controller = 'AdminProductController';

	Route::get('/', function() {
		Session::reflash();
		return Redirect::to(admin_uri('products/categories'));
	});
	Route::get('add', $controller . '@add');
	Route::post('add', array(
		'before' => 'csrf',
		'uses' => $controller . '@attempt_add'
	));
	Route::get('edit/{id}', $controller . '@edit');
	Route::post('edit/{id}', array(
		'before' => 'csrf',
		'uses' => $controller . '@attempt_edit'
	));
	Route::post('delete/{id}', array(
		'before' => 'csrf',
		'uses' => $controller . '@delete'
	));

	Route::group(array('prefix'=>'categories'), function() {

		$controller = 'AdminProductCategoryController';

		Route::get('/', $controller . '@index');
		Route::get('add', $controller . '@add');
		Route::post('add', array(
			'before' => 'csrf',
			'uses' => $controller . '@attempt_add'
		));
		Route::get('edit/{id}', $controller . '@edit');
		Route::post('edit/{id}', array(
			'before' => 'csrf',
			'uses' => $controller . '@attempt_edit'
		));
		Route::post('delete/{id}', array(
			'before' => 'csrf',
			'uses' => $controller . '@delete'
		));
		Route::post('update-tree', array(
			'uses' => $controller . '@update_tree'
		));
		Route::get('show-products/{id}', $controller . '@show_products');
	});
});


text:
let TestCoverage;
let TestCoverageNoGC;

let nop;
let gen;

!function() {
  function GetCoverage(source) {
    for (var script of %DebugCollectCoverage()) {
      if (script.script === source) return script;
    }
    return undefined;
  };

  function TestCoverageInternal(
      name, source, expectation, collect_garbage, prettyPrintResults) {
    source = source.trim();
    eval(source);
    if (collect_garbage) %CollectGarbage("collect dead objects");
    var covfefe = GetCoverage(source);
    var stringified_result = JSON.stringify(covfefe);
    var stringified_expectation = JSON.stringify(expectation);
    const mismatch = stringified_result != stringified_expectation;
    if (mismatch) {
      console.log(stringified_result.replace(/[}],[{]/g, "},\n {"));
    }
    if (prettyPrintResults) {
      console.log("=== Coverage Expectation ===")
      for (const {start,end,count} of expectation) {
        console.log(`Range [${start}, ${end}) (count: ${count})`);
        console.log(source.substring(start, end));
      }
      console.log("=== Coverage Results ===")
      for (const {start,end,count} of covfefe) {
        console.log(`Range [${start}, ${end}) (count: ${count})`);
        console.log(source.substring(start, end));
      }
      console.log("========================")
    }
    assertEquals(stringified_expectation, stringified_result, name + " failed");
  };

  TestCoverage = function(name, source, expectation, prettyPrintResults) {
    TestCoverageInternal(name, source, expectation, true, prettyPrintResults);
  };

  TestCoverageNoGC = function(name, source, expectation, prettyPrintResults) {
    TestCoverageInternal(name, source, expectation, false, prettyPrintResults);
  };

  nop = function() {};

  gen = function*() {
    yield 1;
    yield 2;
    yield 3;
  };
}();


text:
using System;
using Common.Logging;
using System.Threading;

namespace Spring.Messaging.Listener
{
    public class WaitingHandler
    {
        #region Logging

        private static readonly ILog LOG = LogManager.GetLogger(typeof(WaitingHandler));

        #endregion

        private int messageCount;

        private string stateVariable;

        public WaitingHandler()
        {
            this.stateVariable = "hello";
        }
        public WaitingHandler(string stateVariable)
        {
            this.stateVariable = stateVariable;
        }

        public int MessageCount
        {
            get { return messageCount; }
            set { messageCount = value; }
        }

        public string HandleMessage(string msgTxt)
        {
            LOG.Debug(String.Format("Received text = [{0}]", msgTxt));
            LOG.Debug("constructor set state string  = " + stateVariable);

            Thread.Sleep(10000);

            messageCount++;
            LOG.Debug("Message listener count = " + messageCount);
            return msgTxt + " - processed!";
        }
    }
}


text:
/*
	The whisper file writer

	NOTE:: the whisper file ITSELF takes care of rollups, NOT, so unlike the DB/CSV ones, we DO NOT
	need to bother with the flushes for anything BUT the lowest time

	[acc.agg.writer.metrics]
	driver="whisper"
	dsn="/root/metrics/path"
	[acc.agg.writer.smetrics.options]
		xFilesFactor=0.3
		write_workers=8
		write_queue_length=102400
		writes_per_second=1000 # allowed physical writes per second

*/

package metrics

import (
	"cadent/server/dispatch"
	"cadent/server/stats"
	"cadent/server/writers/indexer"
	"fmt"

	"cadent/server/broadcast"
	sindexer "cadent/server/schemas/indexer"
	smetrics "cadent/server/schemas/metrics"
	"cadent/server/schemas/repr"
	"cadent/server/utils"
	"cadent/server/utils/options"
	"cadent/server/utils/shutdown"
	"errors"
	whisper "github.com/robyoung/go-whisper"
	"golang.org/x/net/context"
	logging "gopkg.in/op/go-logging.v1"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"
)

const (
	WHISPER_METRIC_WORKERS    = 8
	WHISPER_METRIC_QUEUE_LEN  = 1024 * 100
	WHISPER_WRITES_PER_SECOND = 1024
)

var errWhisperNotaDataNode = errors.New("Whisper: RawRenderOne: Not a data node")
var errWhisperNoDataInTimes = errors.New("Whisper: No data between these times")

// the singleton (per DSN) as we really only want one "controller" of writes not many lest we explode the
// IOwait to death

var _WHISP_WRITER_SINGLETON map[string]*WhisperWriter
var _whisp_set_mutex sync.Mutex

// special initer
func init() {
	_WHISP_WRITER_SINGLETON = make(map[string]*WhisperWriter)
}

func _get_whisp_signelton(conf *options.Options) (*WhisperWriter, error) {
	_whisp_set_mutex.Lock()
	defer _whisp_set_mutex.Unlock()
	dsn, err := conf.StringRequired("dsn")
	if err != nil {
		return nil, fmt.Errorf("Metrics: `dsn` /root/path/to/files is needed for whisper config")
	}

	if val, ok := _WHISP_WRITER_SINGLETON[dsn]; ok {
		return val, nil
	}

	writer, err := NewWhisperWriter(conf)
	if err != nil {
		return nil, err
	}
	_WHISP_WRITER_SINGLETON[dsn] = writer
	return writer, nil
}

type WhisperWriter struct {
	WriterBase

	basePath     string
	xFilesFactor float32

	retentions whisper.Retention
	indexer    indexer.Indexer

	cacheOverFlow *broadcast.Listener // on byte overflow of cacher force a write

	shutdown chan bool // when triggered, we skip the rate limiter and go full out till the queue is done

	writeQueue      chan dispatch.IJob
	dispatchQueue   chan chan dispatch.IJob
	writeDispatcher *dispatch.Dispatch
	numWorkers      int
	queueLen        int
	writesPerSecond int // number of actuall writes we will do per second assuming "INF" writes allowed

	write_lock sync.Mutex
	log        *logging.Logger
}

func NewWhisperWriter(conf *options.Options) (*WhisperWriter, error) {
	ws := new(WhisperWriter)
	ws.options = conf
	ws.log = logging.MustGetLogger("metrics.whisper")
	dsn, err := conf.StringRequired("dsn")
	if err != nil {
		return nil, fmt.Errorf("`dsn` /root/path/of/data is needed for whisper config")
	}

	ws.basePath = dsn

	// remove trialing "/"
	if strings.HasSuffix(dsn, "/") {
		ws.basePath = dsn[0 : len(dsn)-1]
	}
	ws.xFilesFactor = float32(conf.Float64("xFilesFactor", 0.3))
	ws.numWorkers = int(conf.Int64("write_workers", WHISPER_METRIC_WORKERS))
	ws.queueLen = int(conf.Int64("write_queue_length", WHISPER_METRIC_QUEUE_LEN))
	ws.writesPerSecond = int(conf.Int64("writes_per_second", WHISPER_WRITES_PER_SECOND))

	info, err := os.Stat(ws.basePath)
	if err != nil {
		return nil, fmt.Errorf("Whisper Metrics: could not find base path %s", err)
	}
	if !info.IsDir() {
		return nil, fmt.Errorf("Whisper Metrics: base path %s is not a directory", ws.basePath)
	}

	_cache, err := conf.ObjectRequired("cache")
	if err != nil {
		return nil, errMetricsCacheRequired
	}
	ws.cacher = _cache.(Cacher)
	_, ok := ws.cacher.(*CacherSingle)
	if !ok {
		return nil, ErrorMustBeSingleCacheType
	}

	ws.shutdown = make(chan bool, 5)
	ws.shutitdown = false

	return ws, nil
}

func (ws *WhisperWriter) getRetentions() (whisper.Retentions, error) {

	retentions := make(whisper.Retentions, 0)
	for _, item := range ws.resolutions {
		timebin := item[0]
		points := item[1]
		retent, err := whisper.ParseRetentionDef(fmt.Sprintf("%ds:%ds", timebin, points))
		if err != nil {
			return retentions, err
		}
		retentions = append(retentions, retent)
	}
	return retentions, nil
}

func (ws *WhisperWriter) getAggregateType(key string) whisper.AggregationMethod {
	agg_type := repr.GuessReprValueFromKey(key)
	switch agg_type {
	case repr.SUM:
		return whisper.Sum
	case repr.MAX:
		return whisper.Max
	case repr.MIN:
		return whisper.Min
	case repr.LAST:
		return whisper.Last
	default:
		return whisper.Average
	}
}

func (ws *WhisperWriter) getxFileFactor(key string) float32 {
	agg_type := repr.GuessReprValueFromKey(key)
	switch agg_type {
	case repr.SUM:
		return 0.0
	case repr.MAX:
		return 0.1
	case repr.MIN:
		return 0.1
	case repr.LAST:
		return 0.1
	default:
		return ws.xFilesFactor
	}
}

func (ws *WhisperWriter) getFilePath(metric string) string {
	if strings.Contains(metric, "/") {
		return metric
	}
	return filepath.Join(ws.basePath, strings.Replace(metric, ".", "/", -1)) + ".wsp"
}

func (ws *WhisperWriter) getFile(metric string) (*whisper.Whisper, error) {
	path := ws.getFilePath(metric)
	_, err := os.Stat(path)
	if err != nil {
		retentions, err := ws.getRetentions()
		if err != nil {
			return nil, err
		}
		agg := ws.getAggregateType(metric)

		// need to make the dirs
		if err = os.MkdirAll(filepath.Dir(path), os.ModeDir|os.ModePerm); err != nil {
			ws.log.Error("Could not make directory: %s", err)
			return nil, err
		}
		stats.StatsdClientSlow.Incr("writer.whisper.metric-creates", 1)
		return whisper.Create(path, retentions, agg, ws.xFilesFactor)
	}

	// need a recover in case files is corrupt and thus start over
	defer func() {
		if r := recover(); r != nil {
			ws.log.Critical("Whisper Failure (panic) %v :: need to remove file", r)
			ws.DeleteByName(metric)
		}
	}()

	return whisper.Open(path)
}

// shutdown the writer, purging all cache to files as fast as we can
func (ws *WhisperWriter) Stop() {
	ws.startstop.Stop(func() {
		shutdown.AddToShutdown()
		defer shutdown.ReleaseFromShutdown()

		ws.log.Warning("Whisper: Shutting down")

		if ws.shutitdown {
			return // already did
		}

		ws.shutitdown = true
		if ws.writeDispatcher != nil {
			ws.writeDispatcher.Shutdown()
		}
		ws.shutdown <- true

		ws.cacher.Stop()

		if ws.cacher == nil {
			ws.log.Warning("Whisper: Shutdown finished, nothing in queue to write")
			return
		}

		//need to cast to get internals
		scache := ws.cacher.(*CacherSingle)

		mets := scache.Queue
		mets_l := len(mets)
		ws.log.Warning("Whisper: Shutting down, exhausting the queue (%d items) and quiting", mets_l)
		// full tilt write out
		did := 0
		for _, queueitem := range mets {
			if did%100 == 0 {
				ws.log.Warning("Whisper: shutdown purge: written %d/%d...", did, mets_l)
			}
			name, points, _ := ws.cacher.GetById(queueitem.metric)
			if points != nil {
				stats.StatsdClient.Incr(fmt.Sprintf("writer.whisper.write.send-to-writers"), 1)
				ws.InsertMulti(name, points)
			}
			did++
		}

		r_cache := GetReadCache()
		if r_cache != nil {
			ws.log.Warning("Whisper: shutdown read cache")
			r_cache.Stop()
		}

		ws.log.Warning("Whisper: shutdown purge: written %d/%d...", did, mets_l)
		ws.log.Warning("Whisper: Shutdown finished ... quiting whisper writer")
	})
}

func (ws *WhisperWriter) Start() {

	/**** start the acctuall disk writer dispatcher queue ***/
	ws.startstop.Start(func() {
		workers := ws.numWorkers
		ws.writeQueue = make(chan dispatch.IJob, ws.queueLen)
		ws.dispatchQueue = make(chan chan dispatch.IJob, workers)
		ws.writeDispatcher = dispatch.NewDispatch(workers, ws.dispatchQueue, ws.writeQueue)
		ws.writeDispatcher.SetRetries(2)
		ws.writeDispatcher.Run()

		ws.cacher.Start()
		go ws.sendToWriters() // fire up queue puller

		// set th overflow chan, and start the listener for that channel
		if ws.cacher.GetOverFlowMethod() == "chan" {
			ws.cacheOverFlow = ws.cacher.GetOverFlowChan()
			go ws.overFlowWrite()
		}
	})

}

// listen to the overflow chan from the cache and attempt to write "now"
func (ws *WhisperWriter) overFlowWrite() {
	for item := range ws.cacheOverFlow.Ch {
		// bail
		if ws.shutitdown {
			return
		}
		statitem := item.(*smetrics.TotalTimeSeries)
		// need to make a list of points from the series
		iter, err := statitem.Series.Iter()
		if err != nil {
			ws.log.Error("error in overflow writer %v", err)
			continue
		}
		pts := make(repr.StatReprSlice, 0)
		for iter.Next() {
			pts = append(pts, iter.ReprValue())
		}
		if iter.Error() != nil {
			ws.log.Error("error in overflow iterator %v", iter.Error())
		}
		ws.log.Debug("Cache overflow force write for %s you may want to do something about that", statitem.Name.Key)
		ws.InsertMulti(statitem.Name, pts)
	}
}

func (ws *WhisperWriter) InsertMulti(metric *repr.StatName, points repr.StatReprSlice) (npts int, err error) {

	whis, err := ws.getFile(metric.Key)
	if err != nil {
		ws.log.Error("Whisper:InsertMetric write error: %s", err)
		stats.StatsdClientSlow.Incr("writer.whisper.update-metric-errors", 1)
		return 0, err
	}

	// convert "points" to a whisper object
	whisp_points := make([]*whisper.TimeSeriesPoint, 0)
	agg_func := repr.GuessReprValueFromKey(metric.Key)
	for _, pt := range points {
		whisp_points = append(whisp_points,
			&whisper.TimeSeriesPoint{
				Time: int(pt.ToTime().Unix()), Value: pt.AggValue(agg_func),
			},
		)
	}

	// need a recover in case files is corrupt and thus start over
	defer func() {
		if r := recover(); r != nil {
			ws.log.Critical("Whisper Failure (panic) '%v' :: Corrupt :: need to remove file: %s", r, metric.Key)
			ws.DeleteByName(metric.Key)
			err = fmt.Errorf("%v", r)
		}
	}()

	if points != nil && len(whisp_points) > 0 {
		stats.StatsdClientSlow.GaugeAvg("writer.whisper.points-per-update", int64(len(points)))
		whis.UpdateMany(whisp_points)
	}
	stats.StatsdClientSlow.Incr("writer.whisper.update-many-writes", 1)

	whis.Close()
	return len(points), err
}

// insert the metrics from the cache
func (ws *WhisperWriter) InsertNext() (int, error) {
	defer stats.StatsdSlowNanoTimeFunc("writer.whisper.update-time-ns", time.Now())

	metric, points := ws.cacher.(*CacherSingle).Pop()
	if metric == nil || points == nil || len(points) == 0 {
		return 0, nil
	}
	return ws.InsertMulti(metric, points)
}

// the "simple" insert one metric at a time model
func (ws *WhisperWriter) InsertOne(stat repr.StatRepr) (int, error) {

	whis, err := ws.getFile(stat.Name.Key)
	if err != nil {
		ws.log.Error("Whisper write error: %s", err)
		stats.StatsdClientSlow.Incr("writer.whisper.metric-errors", 1)
		return 0, err
	}

	err = whis.Update(float64(stat.Sum), int(stat.ToTime().Unix()))
	if err != nil {
		stats.StatsdClientSlow.Incr("writer.whisper.metric-writes", 1)
	}
	whis.Close()
	return 1, err
}

// "write" just adds to the whispercache
func (ws *WhisperWriter) Write(stat *repr.StatRepr) error {

	if ws.shutitdown {
		return nil
	}

	// add to the writeback cache only
	ws.cacher.Add(stat.Name, stat)
	aggFunc := repr.GuessReprValueFromKey(stat.Name.Key)
	// and now add it to the read cache iff it's been activated
	rCache := GetReadCache()
	if rCache != nil {
		// add only the "value" we need count==1 makes some timeseries much smaller in cache
		pVal := stat.AggValue(aggFunc)
		tStat := &repr.StatRepr{
			Time:  stat.Time,
			Sum:   repr.CheckFloat(pVal),
			Count: 1,
			Name:  stat.Name,
		}
		rCache.InsertQueue <- tStat
	}
	//ws.writeQueue <- whisperMetricsJob{Stat: stat, Whis: ws}
	return nil
}

// pop from the cache and send to actual writers
func (ws *WhisperWriter) sendToWriters() error {
	// NOTE: if the writes per second is really high, this is NOT a good idea (using tickers)
	// that said, if you actually have the disk capacity to do 10k/writes per second ..  well damn
	// the extra CPU burn here may not kill you
	sleep_t := float64(time.Second) * (time.Second.Seconds() / float64(ws.writesPerSecond))
	ws.log.Notice("Starting Write limiter every %f nanoseconds (%d writes per second)", sleep_t, ws.writesPerSecond)
	ticker := time.NewTicker(time.Duration(int(sleep_t)))
	defer ticker.Stop()
	for {
		select {
		case <-ticker.C:
			if ws.writeQueue != nil {
				stats.StatsdClient.Incr("writer.whisper.write.send-to-writers", 1)
				ws.writeQueue <- &whisperMetricsJob{Whis: ws}
			}
		case <-ws.shutdown:
			ws.log.Warning("Whisper shutdown received, stopping write loop")
			return nil
		}
	}
}

// the only recourse to handle "corrupt" files is to nuke it and start again
// otherwise panics all around for no good reason
func (ws *WhisperWriter) DeleteByName(name string) (err error) {
	path := ws.getFilePath(name)
	err = os.Remove(path)
	if err != nil {
		return err
	}
	if ws.indexer == nil {
		return nil
	}
	return ws.indexer.Delete(&repr.StatName{Key: name})
}

/****************** Main Writer Interfaces *********************/
type WhisperMetrics struct {
	WriterBase

	writer *WhisperWriter

	log *logging.Logger
}

func NewWhisperMetrics() *WhisperMetrics {
	ws := new(WhisperMetrics)
	ws.log = logging.MustGetLogger("smetrics.whisper")
	return ws
}

func (ws *WhisperMetrics) Driver() string {
	return "whisper"
}

func (ws *WhisperMetrics) Start() {
	ws.writer.Start()
}
func (ws *WhisperMetrics) Stop() {
	ws.writer.Stop()
}

func (ws *WhisperMetrics) Config(conf *options.Options) error {
	gots, err := _get_whisp_signelton(conf)
	if err != nil {
		return err
	}
	ws.writer = gots

	ws.name = conf.String("name", "metrics:whisper:"+ws.writer.basePath)
	return RegisterMetrics(ws.Name(), ws)
}

func (ws *WhisperMetrics) SetIndexer(idx indexer.Indexer) error {
	ws.indexer = idx
	ws.writer.indexer = idx // needed for "delete" actions
	return nil
}

// Resoltuions should be of the form
// [BinTime, TTL]
// we select the BinTime based on the TTL
func (ws *WhisperMetrics) SetResolutions(res [][]int) int {
	ws.resolutions = res
	ws.writer.resolutions = res
	return 1 // ONLY ONE writer needed whisper self-rolls up
}

func (ws *WhisperMetrics) SetCurrentResolution(res int) {
	ws.currentResolution = res
}

// WriteWithOffset the offset is not used here
func (ws *WhisperMetrics) WriteWithOffset(stat *repr.StatRepr, offset *smetrics.OffsetInSeries) error {
	return ws.Write(stat)
}

func (ws *WhisperMetrics) Write(stat *repr.StatRepr) error {
	ws.indexer.Write(*stat.Name) // write an index for the key
	err := ws.writer.Write(stat)

	return err
}

/**** READER ***/

func (ws *WhisperMetrics) GetFromReadCache(metric string, start int64, end int64) (rawd *smetrics.RawRenderItem, got bool) {
	rawd = new(smetrics.RawRenderItem)

	// check read cache
	r_cache := GetReadCache()
	if r_cache == nil {
		stats.StatsdClient.Incr("reader.whisper.render.cache.miss", 1)
		return rawd, false
	}

	t_start := time.Unix(int64(start), 0)
	t_end := time.Unix(int64(end), 0)
	cached_stats, _, _ := r_cache.Get(metric, t_start, t_end)
	var d_points []*smetrics.RawDataPoint
	step := uint32(0)
	if cached_stats != nil && len(cached_stats) > 0 {
		stats.StatsdClient.Incr("reader.whisper.render.cache.hits", 1)
		rawd.AggFunc = repr.GuessReprValueFromKey(metric)

		fT := uint32(0)
		for _, stat := range cached_stats {
			t := uint32(stat.ToTime().Unix())
			d_points = append(d_points, &smetrics.RawDataPoint{
				Sum:   stat.AggValue(rawd.AggFunc),
				Count: 1,
				Time:  t,
			})
			if fT == 0 {
				fT = t
			}
			if step == 0 {
				step = t - fT
			}
		}

		rawd.RealEnd = d_points[len(d_points)-1].Time
		rawd.RealStart = d_points[0].Time
		rawd.Start = rawd.RealStart
		rawd.End = rawd.RealEnd + step
		rawd.Metric = metric
		rawd.Step = step
		rawd.Data = d_points
		return rawd, len(d_points) > 0
	} else {
		stats.StatsdClient.Incr("reader.whisper.render.cache.miss", 1)
	}

	return rawd, false
}

func (ws *WhisperMetrics) RawDataRenderOne(ctx context.Context, metric *sindexer.MetricFindItem, start int64, end int64) (*smetrics.RawRenderItem, error) {
	sp, closer := ws.GetSpan("RawDataRenderOne", ctx)
	sp.LogKV("driver", "WhisperMetrics", "metric", metric.StatName().Key, "uid", metric.UniqueId)
	defer closer()

	defer stats.StatsdSlowNanoTimeFunc("reader.whisper.renderraw.get-time-ns", time.Now())
	rawd := new(smetrics.RawRenderItem)

	if metric.Leaf == 0 {
		//data only
		return rawd, errWhisperNotaDataNode
	}

	rawd.Start = uint32(start)
	rawd.End = uint32(end)
	stat_name := metric.StatName()

	rawd.AggFunc = stat_name.AggType()
	rawd.Step = 1 // just for something in case of errors
	rawd.Metric = metric.Id
	rawd.Id = metric.UniqueId
	rawd.Tags = metric.Tags
	rawd.MetaTags = metric.MetaTags

	//cache check
	// the read cache should have "all" the points from a "start" to "end" if the read cache has been activated for
	// a while.  If not, then it's a partial list (basically the read cache just started)
	cached, got_cache := ws.GetFromReadCache(stat_name.Key, start, end)
	// we assume the "cache" is hot data (by design) so if the num points is "lacking"
	// we know we need to get to the data store (or at least the inflight) for the rest
	// add the "step" here as typically we have the "forward" step of data
	if got_cache && cached.Start <= uint32(start) {
		stats.StatsdClient.Incr("reader.whisper.render.read.cache.hit", 1)
		ws.log.Debug("Read Cache Hit: %s [%d, %d)", metric.Id, start, end)
		// need to set the start end to the ones requested before quantization to create the proper
		// spanning range
		cached.Start = uint32(start)
		cached.End = uint32(end)
		cached.AggFunc = rawd.AggFunc
		return cached, nil
	}

	// try the write inflight cache as nothing is written yet
	inflight_renderitem, err := ws.writer.cacher.GetAsRawRenderItem(stat_name)

	// need at LEAST 2 points to get the proper step size
	if inflight_renderitem != nil && err == nil {
		// move the times to the "requested" ones and quantize the list
		inflight_renderitem.Metric = metric.Id
		inflight_renderitem.Tags = metric.Tags
		inflight_renderitem.MetaTags = metric.MetaTags
		inflight_renderitem.Id = metric.UniqueId
		inflight_renderitem.AggFunc = rawd.AggFunc
		if inflight_renderitem.Start < uint32(start) {
			inflight_renderitem.RealEnd = uint32(end)
			inflight_renderitem.RealStart = uint32(start)
			inflight_renderitem.Start = inflight_renderitem.RealStart
			inflight_renderitem.End = inflight_renderitem.RealEnd
			return inflight_renderitem, err
		}
	}

	path := ws.writer.getFilePath(stat_name.Key)
	whis, err := whisper.Open(path)
	if err != nil {
		ws.writer.log.Error("Could not open file %s", path)
		return inflight_renderitem, err
	}
	defer whis.Close()

	// need a recover in case files is corrupt and thus start over
	var series *whisper.TimeSeries
	/*defer func() {
		if r := recover(); r != nil {
			ws.log.Critical("Read Whisper Failure (panic) %v :: Corrupt :: need to remove file: %s", r, path)
			ws.writer.DeleteByName(path)
			err = r.(error)
		}
	}()*/

	series, err = whis.Fetch(int(start), int(end))

	if err != nil || series == nil {
		if err == nil {
			err = errWhisperNoDataInTimes
		}
		ws.writer.log.Error("Could not get series from %s : error: %v", path, err)
		return rawd, err
	}

	points := series.Points()
	rawd.Data = make([]*smetrics.RawDataPoint, len(points))

	fT := uint32(0)
	stepT := uint32(0)

	for idx, point := range points {
		rawd.Data[idx] = &smetrics.RawDataPoint{
			Count: 1,
			Sum:   point.Value,
			Last:  point.Value,
			Min:   point.Value,
			Max:   point.Value,
			Time:  uint32(point.Time),
		}
		if fT == 0 {
			fT = uint32(point.Time)
		}
		if stepT == 0 {
			stepT = uint32(point.Time) - fT
		}
	}

	rawd.RealEnd = uint32(end)
	rawd.RealStart = uint32(start)
	rawd.Step = stepT

	// grab the "current inflight" from the cache and merge into the main array
	if inflight_renderitem != nil && len(inflight_renderitem.Data) > 1 {
		inflight_renderitem.Step = stepT // need to force this step size
		//merge with any inflight bits (inflight has higher precedence over the file)
		inflight_renderitem.MergeWithResample(rawd, stepT)
		return inflight_renderitem, nil
	}

	return rawd, nil
}

func (ws *WhisperMetrics) RawRender(ctx context.Context, path string, from int64, to int64, tags repr.SortingTags, resample uint32) ([]*smetrics.RawRenderItem, error) {
	sp, closer := ws.GetSpan("RawRender", ctx)
	sp.LogKV("driver", "WhisperMetrics", "path", path, "from", from, "to", to)
	defer closer()

	defer stats.StatsdSlowNanoTimeFunc("reader.whisper.rawrender.get-time-ns", time.Now())

	paths := SplitNamesByComma(path)
	var metrics []*sindexer.MetricFindItem

	render_wg := utils.GetWaitGroup()
	defer utils.PutWaitGroup(render_wg)

	for _, pth := range paths {
		mets, err := ws.indexer.Find(ctx, pth, tags)
		if err != nil {
			ws.log.Error("error in find: %v", err)
			continue
		}
		metrics = append(metrics, mets...)
	}

	rawd := make([]*smetrics.RawRenderItem, len(metrics))

	// ye old fan out technique
	render_one := func(metric *sindexer.MetricFindItem, idx int) {
		defer render_wg.Done()
		_ri, err := ws.RawDataRenderOne(ctx, metric, from, to)

		if err != nil {
			return
		}
		rawd[idx] = _ri
	}

	for idx, metric := range metrics {
		render_wg.Add(1)
		go render_one(metric, idx)
	}
	render_wg.Wait()
	stats.StatsdClientSlow.Incr("reader.whisper.rawrender.metrics-per-request", int64(len(metrics)))

	return rawd, nil
}

func (ws *WhisperMetrics) CacheRender(ctx context.Context, path string, from int64, to int64, tags repr.SortingTags) ([]*smetrics.RawRenderItem, error) {
	return nil, ErrWillNotBeimplemented
}
func (ws *WhisperMetrics) CachedSeries(path string, from int64, to int64, tags repr.SortingTags) (*smetrics.TotalTimeSeries, error) {
	return nil, ErrWillNotBeimplemented
}

/************************************************************************/
/**********  Standard Worker Dispatcher JOB   ***************************/
/************************************************************************/
// insert job queue workers
type whisperMetricsJob struct {
	Whis  *WhisperWriter
	Retry int
}

func (j *whisperMetricsJob) IncRetry() int {
	j.Retry++
	return j.Retry
}
func (j *whisperMetricsJob) OnRetry() int {
	return j.Retry
}

func (j *whisperMetricsJob) DoWork() error {
	_, err := j.Whis.InsertNext()
	if err != nil {
		j.Whis.log.Error("Insert failed for Metric: %v retrying ...", err)
	}
	return err
}


text:
package com.netflix.genie.web.agent.services.impl;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.util.GenieHostInfo;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.properties.AgentRoutingServiceProperties;
import com.netflix.genie.web.util.MetricsUtils;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.listen.Listenable;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.ServiceType;
import org.apache.zookeeper.KeeperException;
import org.springframework.scheduling.TaskScheduler;

import javax.validation.constraints.NotBlank;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Implementation of {@link AgentRoutingService} that relies on Curator's Discovery extension.
 * Rather than the traditional use of this recipe (register a service for the node itself, this class registers one
 * service instance for each agent locally connected.
 *
 * @author mprimi
 * @since 4.0.0
 */
@Slf4j
public class AgentRoutingServiceCuratorDiscoveryImpl implements AgentRoutingService {

    private static final String SERVICE_NAME = "agent_connections";
    private static final String METRICS_PREFIX = "genie.agents.connections.";
    private static final String CONNECTED_AGENTS_GAUGE_NAME = METRICS_PREFIX + "connected.gauge";
    private static final String REGISTERED_AGENTS_GAUGE_NAME = METRICS_PREFIX + "registered.gauge";
    private static final String ZOOKEEPER_SESSION_STATE_COUNTER_NAME = METRICS_PREFIX + "zookeeperSessionState.counter";
    private static final String AGENT_REGISTERED_TIMER_NAME = METRICS_PREFIX + "registered.timer";
    private static final String AGENT_UNREGISTERED_TIMER_NAME = METRICS_PREFIX + "unregistered.timer";
    private static final String AGENT_REFRESH_TIMER_NAME = METRICS_PREFIX + "refreshed.timer";
    private static final String AGENT_CONNECTED_COUNTER_NAME = METRICS_PREFIX + "connected.counter";
    private static final String AGENT_DISCONNECTED_COUNTER_NAME = METRICS_PREFIX + "disconnected.counter";
    private static final String AGENT_LOOKUP_TIMER_NAME = METRICS_PREFIX + "lookup.timer";
    private static final String ZK_CONNECTION_STATE_TAG_NAME = "connectionState";
    private static final String ROUTE_FOUND_TAG_NAME = "found";
    private static final Set<Tag> EMPTY_TAG_SET = ImmutableSet.of();
    private final String localHostname;
    private final ServiceDiscovery<Agent> serviceDiscovery;
    private final TaskScheduler taskScheduler;
    private final MeterRegistry registry;
    private final AgentRoutingServiceProperties properties;
    private final Set<String> connectedAgentsSet;
    private final Map<String, ServiceInstance<Agent>> registeredAgentsMap;
    private final PriorityBlockingQueue<RegisterMutation> registrationQueue;
    private final AtomicReference<Thread> registrationTaskThread;
    private final ThreadFactory threadFactory;

    /**
     * Constructor.
     *
     * @param genieHostInfo                    The genie local host information
     * @param serviceDiscovery                 The service discovery client
     * @param taskScheduler                    The task scheduler
     * @param listenableCuratorConnectionState The listenable curator client connection status
     * @param registry                         The metrics registry
     * @param properties                       The service properties
     */
    public AgentRoutingServiceCuratorDiscoveryImpl(
        final GenieHostInfo genieHostInfo,
        final ServiceDiscovery<Agent> serviceDiscovery,
        final TaskScheduler taskScheduler,
        final Listenable<ConnectionStateListener> listenableCuratorConnectionState,
        final MeterRegistry registry,
        final AgentRoutingServiceProperties properties
    ) {
        this(
            genieHostInfo,
            serviceDiscovery,
            taskScheduler,
            listenableCuratorConnectionState,
            registry,
            properties,
            new ThreadFactory() {
                private final AtomicLong threadCounter = new AtomicLong();

                @Override
                public Thread newThread(final Runnable r) {
                    return new Thread(
                        r,
                        this.getClass().getSimpleName() + "-registration-" + threadCounter.incrementAndGet()
                    );
                }
            }
        );
    }

    @VisibleForTesting
    AgentRoutingServiceCuratorDiscoveryImpl(
        final GenieHostInfo genieHostInfo,
        final ServiceDiscovery<Agent> serviceDiscovery,
        final TaskScheduler taskScheduler,
        final Listenable<ConnectionStateListener> listenableCuratorConnectionState,
        final MeterRegistry registry,
        final AgentRoutingServiceProperties properties,
        final ThreadFactory threadFactory
    ) {
        this.localHostname = genieHostInfo.getHostname();
        this.serviceDiscovery = serviceDiscovery;
        this.taskScheduler = taskScheduler;
        this.registry = registry;
        this.threadFactory = threadFactory;
        this.properties = properties;
        this.registeredAgentsMap = Maps.newConcurrentMap();
        this.connectedAgentsSet = Sets.newConcurrentHashSet();
        this.registrationQueue = new PriorityBlockingQueue<>();
        this.registrationTaskThread = new AtomicReference<>();

        // Create gauge metric for agents connected and registered
        registry.gauge(CONNECTED_AGENTS_GAUGE_NAME, EMPTY_TAG_SET, this.connectedAgentsSet, Set::size);
        registry.gaugeMapSize(REGISTERED_AGENTS_GAUGE_NAME, EMPTY_TAG_SET, this.registeredAgentsMap);

        // Listen for Curator session state changes
        listenableCuratorConnectionState.addListener(this::handleConnectionStateChange);

        // The curator client is passed already connected.
        // See: org.springframework.cloud.zookeeper.ZookeeperAutoConfiguration
        this.startRegistrationThread();
    }

    private void startRegistrationThread() {
        final Thread newThread = this.threadFactory.newThread(this::registrationTask);
        final Thread oldThread = this.registrationTaskThread.getAndSet(newThread);
        if (oldThread != null) {
            oldThread.interrupt();
        }
        newThread.start();
    }

    private void stopRegistrationThread() {
        final Thread thread = this.registrationTaskThread.getAndSet(null);
        if (thread != null) {
            thread.interrupt();
        }
    }

    // Thread task that consumes registration queue items and applies the corresponding mutation with Curator client.
    // This thread is stopped with an interrupt if the client is disconnected.
    private void registrationTask() {
        while (true) {
            try {
                processNextRegistrationMutation();
            } catch (InterruptedException e) {
                break;
            }
        }

        log.debug("Registration thread terminating");
    }

    private void processNextRegistrationMutation() throws InterruptedException {
        RegisterMutation mutation = null;
        try {
            // Blocking
            mutation = this.registrationQueue.take();

            final String jobId = mutation.getJobId();
            // Check if agent is still connected by the time this mutation is taken from the queue to
            // be processed.
            final boolean agentIsConnected = this.connectedAgentsSet.contains(mutation.getJobId());

            if (agentIsConnected) {
                // Register or re-register agent connection
                if (mutation.isRefresh()) {
                    refreshAgentConnection(jobId);
                } else {
                    registerAgentConnection(jobId);
                }

                // Schedule a future refresh for this agent connection
                this.taskScheduler.schedule(
                    () -> this.registrationQueue.add(RegisterMutation.refresh(jobId)),
                    Instant.now().plus(this.properties.getRefreshInterval())
                );

            } else {
                // Unregister agent connection
                unregisterAgentConnection(jobId);
            }

        } catch (InterruptedException e) {
            log.warn("Registration task interrupted", e);
            if (mutation != null) {
                // Re-enqueue mutation that was in-progress when interrupted
                this.registrationQueue.add(mutation);
            }
            throw e;
        }
    }

    private void registerAgentConnection(final String jobId) throws InterruptedException {
        log.debug("Registering route for job: {}", jobId);

        final ServiceInstance<Agent> serviceInstance = new ServiceInstance<>(
            SERVICE_NAME,
            jobId,
            localHostname,
            null,
            null,
            new Agent(jobId),
            Instant.now().getEpochSecond(),
            ServiceType.DYNAMIC,
            null
        );

        Set<Tag> tags = MetricsUtils.newSuccessTagsSet();
        final long start = System.nanoTime();
        try {
            this.serviceDiscovery.registerService(serviceInstance);
            this.registeredAgentsMap.put(jobId, serviceInstance);
        } catch (InterruptedException e) {
            // Ensure interrupt is not swallowed by the generic catch
            log.debug("Interrupted while registering {}", jobId);
            tags = MetricsUtils.newFailureTagsSetForException(e);
            throw e;
        } catch (Exception e) {
            log.error("Failed to register agent executing job: {}", jobId, e);
            tags = MetricsUtils.newFailureTagsSetForException(e);
        } finally {
            this.registry.timer(
                AGENT_REGISTERED_TIMER_NAME,
                tags
            ).record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
        }
    }

    private void refreshAgentConnection(final String jobId) throws InterruptedException {
        log.debug("Refreshing route for job: {}", jobId);

        final ServiceInstance<Agent> serviceInstance = this.registeredAgentsMap.get(jobId);

        if (serviceInstance == null) {
            log.warn("Instance record not found for job {}", jobId);
            this.registerAgentConnection(jobId);
            return;
        }

        Set<Tag> tags = MetricsUtils.newSuccessTagsSet();
        final long start = System.nanoTime();
        try {
            this.serviceDiscovery.updateService(serviceInstance);
        } catch (KeeperException.NoNodeException e) {
            log.warn("Failed to update registration of agent executing job id: {}", jobId);
            // Failed because expected existing node is not present. Create it.
            this.registerAgentConnection(jobId);
        } catch (InterruptedException e) {
            // Ensure interrupt is not swallowed by the generic catch
            log.debug("Interrupted while refreshing {}", jobId);
            tags = MetricsUtils.newFailureTagsSetForException(e);
            throw e;
        } catch (Exception e) {
            log.error("Failed to refresh agent executing job id: {}", jobId);
            tags = MetricsUtils.newFailureTagsSetForException(e);
        } finally {
            this.registry.timer(
                AGENT_REFRESH_TIMER_NAME,
                tags
            ).record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
        }
    }

    private void unregisterAgentConnection(final String jobId) throws InterruptedException {
        final ServiceInstance<Agent> serviceInstance = this.registeredAgentsMap.get(jobId);

        if (serviceInstance == null) {
            log.debug("Skipping unregistration, already removed");
            return;
        }

        log.debug("Unregistering route for job: {}", jobId);

        Set<Tag> tags = MetricsUtils.newSuccessTagsSet();
        final long start = System.nanoTime();
        try {
            this.serviceDiscovery.unregisterService(serviceInstance);
            this.registeredAgentsMap.remove(jobId);
        } catch (InterruptedException e) {
            // Ensure interrupt is not swallowed by the generic catch
            log.debug("Interrupted while unregistering {}", jobId);
            tags = MetricsUtils.newFailureTagsSetForException(e);
            throw e;
        } catch (Exception e) {
            log.error("Failed to unregister agent executing job id: {}", jobId);
            tags = MetricsUtils.newFailureTagsSetForException(e);
        } finally {
            this.registry.timer(
                AGENT_UNREGISTERED_TIMER_NAME,
                tags
            ).record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
        }
    }

    private void handleConnectionStateChange(final CuratorFramework client, final ConnectionState newState) {

        this.registry.counter(
            ZOOKEEPER_SESSION_STATE_COUNTER_NAME,
            Sets.newHashSet(Tag.of(ZK_CONNECTION_STATE_TAG_NAME, newState.name()))
        ).increment();

        log.info("Zookeeper/Curator client: {}", newState);

        switch (newState) {
            case CONNECTED:
            case RECONNECTED:
                startRegistrationThread();
                break;

            case LOST:
            case SUSPENDED:
                stopRegistrationThread();
                break;

            default:
                log.warn("Zookeeper/Curator unhandled connection state: {}", newState);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Optional<String> getHostnameForAgentConnection(@NotBlank final String jobId) {
        log.debug("Looking up agent executing job: {}", jobId);
        if (isAgentConnectionLocal(jobId)) {
            return Optional.of(localHostname);
        }

        final long start = System.nanoTime();
        final Set<Tag> tags = Sets.newHashSet();
        String address = null;

        try {
            final ServiceInstance<Agent> instance = serviceDiscovery.queryForInstance(SERVICE_NAME, jobId);
            if (instance == null) {
                log.debug("Could not find agent connection for job {}", jobId);
            } else {
                address = instance.getAddress();
            }
            MetricsUtils.addSuccessTags(tags);
        } catch (Exception e) {
            log.error("Error looking up agent connection for job {}", jobId, e);
            address = null;
            MetricsUtils.addFailureTagsWithException(tags, e);
        } finally {
            tags.add(Tag.of(ROUTE_FOUND_TAG_NAME, String.valueOf(address != null)));
            this.registry.timer(
                AGENT_LOOKUP_TIMER_NAME,
                tags
            ).record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
        }

        return Optional.ofNullable(address);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isAgentConnectionLocal(@NotBlank final String jobId) {
        return this.connectedAgentsSet.contains(jobId);
    }

    @Override
    public void handleClientConnected(@NotBlank final String jobId) {
        log.debug("Adding to routing table (pending registration): {}", jobId);

        final boolean isNew = this.connectedAgentsSet.add(jobId);
        this.registrationQueue.add(RegisterMutation.update(jobId));

        if (isNew) {
            this.registry.counter(AGENT_CONNECTED_COUNTER_NAME).increment();
        }
    }

    @Override
    public void handleClientDisconnected(@NotBlank final String jobId) {
        log.debug("Removing from routing table (pending un-registration): {}", jobId);

        final boolean removed = this.connectedAgentsSet.remove(jobId);
        this.registrationQueue.add(RegisterMutation.update(jobId));

        if (removed) {
            this.registry.counter(AGENT_DISCONNECTED_COUNTER_NAME).increment();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isAgentConnected(final String jobId) {
        return this.getHostnameForAgentConnection(jobId).isPresent();
    }

    /**
     * Payload for typed {@link ServiceDiscovery}.
     */
    @Getter
    @EqualsAndHashCode
    public static final class Agent {
        // This field is superfluous, but added because serialization fails on empty beans
        private final String jobId;

        // Jackson deserialization requires this dummy constructor
        private Agent() {
            this.jobId = null;
        }

        /**
         * Constructor.
         *
         * @param jobId The job id
         */
        public Agent(@JsonProperty(value = "jobId", required = true) final String jobId) {
            this.jobId = jobId;
        }
    }

    @Getter
    @EqualsAndHashCode
    private static final class RegisterMutation implements Comparable<RegisterMutation> {
        private final String jobId;
        private final boolean refresh;
        private final long timestamp;

        private RegisterMutation(final String jobId, final boolean refresh) {
            this.jobId = jobId;
            this.refresh = refresh;
            this.timestamp = System.nanoTime();
        }

        static RegisterMutation refresh(final String jobId) {
            return new RegisterMutation(jobId, true);
        }

        static RegisterMutation update(final String jobId) {
            return new RegisterMutation(jobId, false);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public int compareTo(final RegisterMutation other) {
            if (this.isRefresh() == other.isRefresh()) {
                final long timestampDifference = this.getTimestamp() - other.getTimestamp();
                if (timestampDifference == 0) {
                    return this.getJobId().compareTo(other.getJobId());
                } else {
                    return timestamp > 0 ? 1 : -1;
                }
            } else {
                return this.isRefresh() ? 1 : -1;
            }
        }
    }
}


text:
'use strict';

module.exports = Cluster;

var fsHelpers = require('../util/fsHelpers');
var clusters = [];

/**
 * A Cluster that manages master and worker processes.  You shouldn't invoke
 * this directly.  Instead you should use Cluster#create.  You've been warned :\
 *
 * @param {number} id
 * @param {Object} model
 * <pre>
 *  Required properties:
 *  workerPath - absolute path to worker.  Workers are started immediately upon
 *  creating a new cluster.
 *
 *  Optional properties:
 *  verifyNewWorkers - if true, the first worker is tested before updating all
 *    workers.  If the first worker fails to load, the update is aborted.  The
 *    default is false.
 *  verifyTimeout - time in milliseconds to take verifying new workers.  The
 *    default is 2000.
 *  workerLimit - Limits the number of workers.  The default value is set by the
 *    number of cores reported by the os.
 * </pre>
 * @constructor
 */
function Cluster(id, model){
  if(!model.workerPath){
    throw new Error('no workerPath given');
  }
  if(!fsHelpers.fileExists(model.workerPath)){
    throw new Error('workerPath: '+model.workerPath + ' is not an existing file.');
  }
  this.id = id;
  this.workerPath = model.workerPath;
}

//prototype methods
Cluster.prototype.shutdown = function(cb){
  process.nextTick(cb.bind(null));
  clusters[this.id] = null;
};

//static methods
Cluster.create = function(model, cb){
  var err = null;
  var index = getClusterIndex();
  try {
    clusters[index] = new Cluster(index, model);
  } catch(e){
    err = e;
  }
  process.nextTick(cb.bind(null, err, index));
};

Cluster.delete = function(id, cb){
  if(clusters[id]){
    clusters[id].shutdown(cb);
    clusters[id] = null;
  } else {
    process.nextTick(cb.bind(null));
  }
};

function getClusterIndex(){
  var proposedIndex = clusters.indexOf(null);
  return proposedIndex < 0 ? clusters.length : proposedIndex;
}


text:
package org.banyan.concurrent.threadpool;

import org.banyan.concurrent.thread.pool.NamedThreadFactory;

import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 调度线程池使用
 */
public class UsingExecutors {

    public static void main(String[] args) {
        usingFixedThreadPool();
    }

    public static void testThread() {
        long st = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            new Thread(new MyThread("testNoThreadPool" + i)).start();
        }
        long cost = System.currentTimeMillis() - st;
        System.out.println("cost:" + cost + " ms");
    }

    public static void testThreadPool() {
        long st = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            ThreadPool.getInstance().start(new MyThread("TestThreadPool" + i));
        }
        long cost = System.currentTimeMillis() - st;
        System.out.println("cost:" + cost + " ms");
    }

    public static void testThreadPool2() {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2, new NamedThreadFactory("Task-1"));

        scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {//测试scheduleAtFixedRate
            AtomicInteger counter = new AtomicInteger(0);

            @Override
            public void run() {
                System.err.println("执行" + counter.incrementAndGet() + "次");
            }
        }, 3000, 2000, TimeUnit.MILLISECONDS);

        scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {//测试scheduleWithFixedDelay
            AtomicInteger counter = new AtomicInteger(0);

            @Override
            public void run() {
                System.err.println("abc执行" + counter.incrementAndGet() + "次");
            }
        }, 3000, 2000, TimeUnit.MILLISECONDS);
    }

    public static void usingSingleThreadExecutor() {
        System.out.println("=== SingleThreadExecutor ===");
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        singleThreadExecutor.execute(() -> System.out.println("Print this."));
        singleThreadExecutor.execute(() -> System.out.println("and this one to."));
        singleThreadExecutor.shutdown();
        try {
            singleThreadExecutor.awaitTermination(4, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("\n\n");
    }

    public static void usingCachedThreadPool() {
        System.out.println("=== CachedThreadPool ===");
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        List<Future<UUID>> uuids = new LinkedList<>();

        for (int i = 0; i < 10; i++) {
            Future<UUID> submitted = cachedThreadPool.submit(() -> {
                UUID randomUUID = UUID.randomUUID();
                System.out.println("UUID " + randomUUID + " from " + Thread.currentThread().getName());
                return randomUUID;
            });
            uuids.add(submitted);
        }

        cachedThreadPool.execute(() -> uuids.forEach((f) -> {
            try {
                System.out.println("Result " + f.get() + " from thread " + Thread.currentThread().getName());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }));
        cachedThreadPool.shutdown();
        try {
            cachedThreadPool.awaitTermination(4, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("\n\n");

    }

    /**
     *
     */
    public static void usingFixedThreadPool() {
        System.out.println("=== FixedThreadPool ===");
        ExecutorService fixedPool = Executors.newFixedThreadPool(4);
        List<Future<UUID>> uuids = new LinkedList<>();

        for (int i = 0; i < 20; i++) {
            Future<UUID> submitted = fixedPool.submit(() -> {
                UUID randomUUID = UUID.randomUUID();
                System.out.println("UUID " + randomUUID + " from " + Thread.currentThread().getName());
                return randomUUID;
            });
            uuids.add(submitted);
        }

        fixedPool.execute(() -> uuids.forEach((f) -> {
            try {
                System.out.println("Result " + f.get() + " from " + Thread.currentThread().getName());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }));

        System.out.println("1111");
//        fixedPool.shutdown();
//        try {
//            fixedPool.awaitTermination(4, TimeUnit.SECONDS);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println("\n\n");
    }

    public static void usingScheduledThreadPool() {
        System.out.println("=== ScheduledThreadPool ===");
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4);
        scheduledThreadPool.scheduleAtFixedRate(
                () -> System.out.println("Print every 2s"), 0, 2, TimeUnit.SECONDS);
        scheduledThreadPool.scheduleWithFixedDelay(
                () -> System.out.println("Print every 2s delay"), 0, 2, TimeUnit.SECONDS);

        try {
            scheduledThreadPool.awaitTermination(6, TimeUnit.SECONDS);
            scheduledThreadPool.shutdown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


text:
export as namespace WaveSurfer;

export = WaveSurfer;

declare class Observer {
    constructor();
    fireEvent(eventName: string, ...args: any[]): void;
    on(eventName: string, callback: (...args: any[]) => void): WaveSurfer.ListenerDescriptor;
    once(eventName: string, callback: (...args: any[]) => void): WaveSurfer.ListenerDescriptor;
    un(eventName: string, callback: (...args: any[]) => void): void;
    unAll(): void;
}

declare class WaveSurfer extends Observer {
    constructor(params: WaveSurfer.WaveSurferParams);
    static util: WaveSurfer.WaveSurferUtil;
    static create(params: WaveSurfer.WaveSurferParams): WaveSurfer;
    // [x: string]: any
    //   pluginName -> WaveSurferPlugin
    //   propertyNameAddedByPlugin -> any
    [x: string]: any;
    util: WaveSurfer.WaveSurferUtil;
    destroy(): void;
    empty(): void;
    getCurrentTime(): number;
    getDuration(): number;
    getPlaybackRate(): number;
    getVolume(): number;
    getMute(): boolean;
    getFilters(): AudioNode[];
    getWaveColor(): string;
    exportPCM(length: number, accuracy: number, noWindow?: boolean, start?: number): string;
    exportImage(format: string, quality: number): string;
    init(): void;
    isPlaying(): boolean;
    isReady(): boolean;
    load(url: string | HTMLMediaElement, peaks?: ReadonlyArray<number> | ReadonlyArray<ReadonlyArray<number>>, preload?: string, duration?: number): void;
    loadBlob(url: Blob | File): void;
    pause(): Promise<void> | undefined;
    play(start?: number, end?: number): Promise<void> | undefined;
    playPause(): Promise<void> | undefined;
    seekAndCenter(progress: number): void;
    seekTo(progress: number): void;
    setHeight(height: number): void;
    setPlaybackRate(rate: number): void;
    setVolume(newVolume: number): void;
    setMute(mute: boolean): void;
    setWaveColor(color: string): void;
    setSinkId(deviceId: string): void;
    skip(offset: number): void;
    skipBackward(seconds?: number): void;
    skipForward(seconds?: number): void;
    stop(): void;
    toggleInteraction(): void;
    toggleMute(): void;
    toggleScroll(): void;
    zoom(pxPerSec?: number): void;
}

declare namespace WaveSurfer {
    class WaveRenderer extends Observer {
        constructor(container: HTMLElement, params: WaveSurferParams);
        height: number;
        width: number;
        wrapper: HTMLElement;
        clearWave(): void;
        createWrapper(): void;
        destroy(): void;
        drawBars(peaks: ReadonlyArray<number> | ReadonlyArray<ReadonlyArray<number>>, channelIndex: number, start: number, end: number): void;
        drawPeaks(peaks: ReadonlyArray<number> | ReadonlyArray<ReadonlyArray<number>>, length: number, start: number, end: number): void;
        drawWave(peaks: ReadonlyArray<number> | ReadonlyArray<ReadonlyArray<number>>, channelIndex: number, start: number, end: number): void;
        getScrollX(): number;
        getWidth(): number;
        handleEvent(e: Event, noPrevent: boolean): number;
        progress(progress: number): void;
        recenter(percent: number): void;
        recenterOnPosition(position: number, immediate: boolean): void;
        resetScroll(): void;
        setHeight(height: number): boolean;
        setWidth(width: number): boolean;
        style(el: HTMLElement, styles: { [x: string]: string }): HTMLElement;
        updateProgress(position: number): void;
        updateSize(): void;
    }

    class WaveSurferPlugin {
        constructor(params: object, ws: WaveSurfer);
        static create(params: object): PluginDefinition;
        init(): void;
        destroy(): void;
    }

    interface WaveSurferUtil {
        ajax(options: { xhr?: XHROptions }): Observer;
        extend(dest: object, ...sources: object[]): object;
        frame(fn: (...args: any[]) => void): (...args: any[]) => number;
        getId(): string;
        max(values: ReadonlyArray<number>): number;
        min(values: ReadonlyArray<number>): number;
        Observer: Observer;
        preventClick(): void;
        requestAnimationFrame(): (fn: (t: number) => void) => number;
        style(el: HTMLElement, styles: { [x: string]: string }): HTMLElement;
    }

    interface WaveSurferParams {
        audioContext?: AudioContext;
        audioRate?: number;
        audioScriptProcessor?: ScriptProcessorNode;
        autoCenter?: boolean;
        backend?: string;
        barHeight?: number;
        barGap?: number;
        closeAudioContext?: boolean;
        container: string | HTMLElement;
        cursorColor?: string;
        cursorWidth?: number;
        fillParent?: boolean;
        forceDecode?: boolean;
        height?: number;
        hideScrollbar?: boolean;
        interact?: boolean;
        loopSelection?: boolean;
        maxCanvasWidth?: number;
        mediaControls?: boolean;
        mediaType?: string;
        minPxPerSec?: number;
        normalize?: boolean;
        partialRender?: boolean;
        pixelRatio?: number;
        plugins?: PluginDefinition[];
        progressColor?: string;
        removeMediaElementOnDestroy?: boolean;
        renderer?: { new(container: HTMLElement, params: WaveSurferParams): WaveRenderer };
        responsive?: boolean | number;
        scrollParent?: boolean;
        skipLength?: number;
        splitChannels?: boolean;
        waveColor?: string;
        xhr?: XHROptions;
    }

    interface PluginDefinition {
        name: string;
        staticProps?: object;
        deferInit?: boolean;
        params: object;
        instance: { new(params: object, ws: WaveSurfer): WaveSurferPlugin };
    }

    interface ListenerDescriptor {
        name: string;
        callback(...args: any[]): void;
        un(): void;
    }

    interface XHROptions {
        requestHeaders?: XHRRequestHeader[];
        withCredentials?: boolean;
    }

    interface XHRRequestHeader {
        key: string;
        value: string;
    }
}


text:
package com.dremio.service.grpc;

import java.util.Map;

import javax.inject.Provider;

import com.google.common.collect.Sets;

import io.grpc.ClientInterceptor;
import io.opentracing.Tracer;

/**
 * gRPC channel factory with multi-tenancy support.
 */
public final class MultiTenantGrpcChannelBuilderFactory extends BaseGrpcChannelBuilderFactory {
  private static final ClientInterceptor mtInterceptor = new MultiTenantClientInterceptor();

  public MultiTenantGrpcChannelBuilderFactory(Tracer tracer, Provider<Map<String, Object>> defaultServiceConfigProvider) {
    super(tracer, Sets.newHashSet(mtInterceptor), defaultServiceConfigProvider);
  }

  public MultiTenantGrpcChannelBuilderFactory(Tracer tracer,
                                              Provider<Map<String, Object>> defaultServiceConfigProvider,
                                              ClientInterceptor interceptor) {
    super(tracer, Sets.newHashSet(mtInterceptor, interceptor), defaultServiceConfigProvider);
  }
}


text:
from StringIO import StringIO
from six.moves.urllib.request import build_opener, HTTPSHandler
from six.moves.urllib.request import Request
from six.moves.urllib.response import addinfourl
from unittest import TestCase

from pysflib import sfjenkins

TEST_COOKIE = "123456789"

class TestHTTPSHandler(HTTPSHandler):
    def https_open(self, req):
        resp = addinfourl(StringIO(req.get_header('Cookie')),
                          "mock message",
                          req.get_full_url())
        resp.code = 200
        resp.msg = "OK"
        return resp

class TestSFJenkins(TestCase):

    @classmethod
    def setupClass(cls):
        cls.jenkins = sfjenkins.SFJenkins('https://jenkins.tests.dom',
                                          cookie=TEST_COOKIE)
        cls.jenkins.crumb = {"crumbRequestField": "DummyField",
                             "crumb": "DummyCrumb", }
        cls.jenkins.opener = build_opener(TestHTTPSHandler())

    def test_access_jenkins_with_cookie(self):
        mock_call = self.jenkins.jenkins_open(Request('https://blop'))
        self.assertEqual("auth_pubtkt=%s" % TEST_COOKIE,
                         mock_call,
                         "Received %s" % mock_call)


text:
FOUNDATION_EXPORT double DTCalendarViewVersionNumber;
FOUNDATION_EXPORT const unsigned char DTCalendarViewVersionString[];


text:
import watson_developer_cloud
import ConfigParser
import io

config = ConfigParser.ConfigParser()
config.read('settings.ini')

text_to_speech = watson_developer_cloud.TextToSpeechV1(username=config.get('bluemix-text_to_speech', 'username'), password=config.get('bluemix-text_to_speech', 'password'))

with io.FileIO('hello_world.wav', 'w') as file:
	file.write(text_to_speech.synthesize(text='Hello world', voice='en-US_AllisonVoice', accept='audio/wav'))