#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#ifndef _WIN32
#include <ctype.h>
#endif

#include "../../structures.h"
#define LDAP_DEPRECATED 1
#include <ldap.h>

int         already_loaded = 0;

static struct auth myalwaysauth;
static struct commands ldap_serv_auth_handler;
static struct commands ldap_access_handler;
static struct commands ldap_sbase_handler;
static struct commands ldap_userenv_handler;
static struct commands ldap_trafgroup_handler;
static struct commands ldap_attrsgroup_handler;
static struct commands ldap_dircount_handler;

static char   *attrs[] = { NULL, NULL};
static char   *ldap_group_attr;
static char   *ldap_access;
static char   *ldap_sbase;
static char   *ldap_serv;
static char   *ldap_user;
static char   *ldap_pass;
static char   *ldap_userenv;
       int     ldap_userenv_size;
static char   *ldap_trafgroup;
static char   *ldap_dircount;
static int     usercaselow = 0;

struct pluginlink * mypluginlink;
struct schedule myschedule;

#ifndef _WIN32
void lower (char *string)
{
 int length, i;

 length = strlen(string);
 for (i=0; i<length; i++)
 {
    string[i] = tolower(string[i]);
 }
}
#endif

/* -------------------------------------------------------------------------- */
int savecounters(void)
{
 struct trafcount *tc=mypluginlink->conf->trafcounter;
 struct trafcount *tcd;
 struct counter_record wcounter;
 FILE *f;
 unsigned char *tmpbuf,pat_file[]="%s%s.lc";

 /* timetoexit !=0 - будем завершаться.*/
 while (tc != NULL)
  {
    tcd = tc;
    tc = tc->next;
    f=NULL;
    if(strcmp(tcd->comment,"ldapcounters")==0) {
      tmpbuf=malloc(strlen(pat_file)+strlen(ldap_dircount)+strlen(tcd->ace->users->user));
      sprintf(tmpbuf,pat_file,ldap_dircount,tcd->ace->users->user);
      f=fopen(tmpbuf,"w+b");
      fseek(f,0,SEEK_SET);
      fprintf(f,"%"PRINTF_INT64_MODIFIER"u %lu %lu\n",tcd->traf64,
					(unsigned long)tcd->cleared,(unsigned long)tcd->updated);

      fclose(f);
      free(tmpbuf);

     }
  }

 /*return 1 delete job , return 0 no delete job*/
 if (mypluginlink->conf->needreload !=0 )
  {
    return (0);
  }

 return (0);
}

/* --------------------------------------------------------------------------*/
static int ldapfunc(struct clientparam *param)
 {

  LDAP		*ld = NULL;
  LDAPMessage	*res = NULL;
  int    rc = -1;
  char   tmpbuf[1024];

  /* test proxy user auth ------------------------*/
  if(!param->username || !param->password) return 4;
  if(strlen(param->password)==0) return 4;

  /* init ldap ---------------------- */
  ld = ldap_init( ldap_serv, 389 );
  if ( ld == NULL )
   {
    param->srv->logfunc(param,"Error ldap_init: No init lib ldap");
    /*ldap_perror( ld, "Error ldap_init" ); */
    return 7;
   }

  /* this code for Active Directory LDAP catalog :(
   detail see documentation for plugin  */
  if (usercaselow  > 0)
  #ifdef _WIN32
   { CharLower(param->username); }
  #else
   { lower(param->username);  }
  #endif

  /* create user for test auth */
  sprintf(tmpbuf,"%.200s=%.200s,%.200s",attrs[0],param->username,ldap_userenv);

  rc = ldap_bind_s( ld, tmpbuf, param->password, LDAP_AUTH_SIMPLE );

  if ( rc != LDAP_SUCCESS )
    {
     param->srv->logfunc(param,"Error ldap_bind: No connect ldap catalog");
     ldap_unbind_s(ld);
     return 7;
    }

  ldap_unbind_s(ld);

  ld = ldap_init( ldap_serv, 389 );

  if ( ld == NULL )
   {
    param->srv->logfunc(param,"Error ldap_init: No init lib ldap");
    /*ldap_perror( ld, "Error ldap_init" ); */
    return 7;
   }

  rc = ldap_bind_s( ld, ldap_user, ldap_pass, LDAP_AUTH_SIMPLE );

   if ( rc != LDAP_SUCCESS )
    {
     param->srv->logfunc(param, "Error ldap_bind: Not authorize in ldap\
     catalog,  checked option \'ldapconnect\' ");
     ldap_unbind_s(ld);
     return 7;
    }

  /* test enter user in filter ------------------------------
     create filter for search*/

  sprintf(tmpbuf,"(&(%.200s=%.200s)(%.200s=%.200s))",attrs[0],param->username,
                                      ldap_group_attr,ldap_access);

  /* search */
  rc = ldap_search_s( ld, ldap_sbase, LDAP_SCOPE_SUBTREE,
				tmpbuf, attrs, 0, &res );

  rc=ldap_count_entries(ld,res);

  ldap_msgfree(res);
  ldap_unbind_s(ld);

  /* user not found */
  if (rc == 0)
    {  return 5;  }

  return 0;
 }

/* --------------------------------------------------------------------------
 handle command ldapserv */
int h_ldapconnect(int argc, unsigned char ** argv)
{
 LDAP		*ld = NULL;

 if (argc < 2)
  {
   fprintf(stderr, "Error in ldapconnect: See documentation of ldapauth plugin.\n");
   return 1;
  }

 ldap_serv=strdup(argv[1]);
 ldap_user=strdup(argv[2]);

 ld = ldap_init( ldap_serv, 389 );
 ldap_unbind_s(ld);

 if (argc == 4)
  {
   ldap_pass= strdup(argv[3]);
   }
 else
  {
   ldap_pass=NULL;
  }

 return 0;
}
/* --------------------------------------------------------------------------
 handle command ldapaccess */
int h_access(int argc, unsigned char ** argv)
{
 if (argc < 1)
  {
   fprintf(stderr, "Error in ldapaccess: See documentation of ldapauth plugin.\n");
   return 1;
  }
 ldap_access=strdup(argv[1]);
 return 0;
}
/* --------------------------------------------------------------------------
 handle command ldapsbase
 searching base */
int h_sbase(int argc, unsigned char ** argv)
{
 if (argc < 1)
  {
   fprintf(stderr, "Error in ldapsbase: See documentation of ldapauth plugin.\n");
   return 1;
  }
  ldap_sbase=strdup(argv[1]);
 return 0;
}
/* --------------------------------------------------------------------------
 handle command ldapuserenv */
int h_userenv(int argc, unsigned char ** argv)
{
 if (argc < 1)
  {
   fprintf(stderr, "Error in ldapsbase: See documentation of ldapauth plugin.\n");
   return 1;
  }
  ldap_userenv=strdup(argv[1]);
  return 0;
}
/* --------------------------------------------------------------------------
 handle command ldaptrafgroup */
int h_trafgroup(int argc, unsigned char ** argv)
{
  struct trafcount *newtrafcount;
  struct bandlim *newbandlim;
  static struct ace *newace;
  static struct userlist *newuserlist;
  struct counter_record rcounter;

  LDAP		*ld = NULL;
  LDAPMessage	*res = NULL;
  LDAPMessage	*msg = NULL;
  BerElement 	*ber = NULL;
  int    rc = -1;
  char   *tmpbuf,pat_file[]="%s%s.lc",pat_group[]="(%s=%s)";
  char   *getattr,**vals,buf[256];
  ROTATION   rtype;
  unsigned long traflimit;
  int bandwidth ;

  FILE *f;

  if (argc < 3)
  {
   fprintf(stderr, "Error in ldaptrafgroup: See documentation of ldapauth plugin.\n");
   return 1;
  }

  ld = ldap_init( ldap_serv, 389 );

  if ( ld == NULL )
   {
    fprintf(stderr,"Error in ldaptrafgroup: ldap_init: No init lib ldap");
    return 7;
   }

  rc = ldap_bind_s( ld, ldap_user, ldap_pass, LDAP_AUTH_SIMPLE );

   if ( rc != LDAP_SUCCESS )
    {
     fprintf(stderr, "Error in ldaptrafgroup: ldap_bind: Not authorize in ldap\
     catalog,  checked option \'ldapconnect\' ");
     ldap_unbind_s(ld);
     return 7;
    }

  /* type traf limit */
  if(strcmp(argv[2],"MONTHLY")==0||strcmp(argv[2],"monthly")==0)
  {rtype=MONTHLY;}

  if(strcmp(argv[2],"DAILY")==0||strcmp(argv[2],"daily")==0)
  {rtype=DAILY;}

  if(strcmp(argv[2],"WEEKLY")==0||strcmp(argv[2],"weekly")==0)
  {rtype=WEEKLY;}

  traflimit = atol((char *)argv[3]);
  bandwidth = atoi((char *)argv[4]);

  /* name ldap group */
  tmpbuf=malloc(strlen(pat_group)+strlen(ldap_group_attr)+strlen(argv[1]));
  sprintf(tmpbuf,pat_group,ldap_group_attr,argv[1]);
  rc = ldap_search_s( ld, ldap_sbase, LDAP_SCOPE_SUBTREE,
                                        			tmpbuf, attrs, 0, &res );
  free(tmpbuf);

  rc=ldap_count_entries(ld,res);

  /* users found */
  if (rc > 0)
     {
       msg=ldap_first_entry(ld, res);
       getattr=ldap_first_attribute(ld, msg, &ber);

       while (rc > 0)
        {
         vals=ldap_get_values(ld, msg, getattr);
         if (vals != NULL && vals[0] != NULL )
           {

             /* -------------bandlim----------
             create user list 	    */
             newuserlist = (*mypluginlink->mallocfunc)(sizeof (struct userlist));
             if (usercaselow  > 0)
                #ifdef _WIN32
                { CharLower(vals[0]); }
                #else
                { lower(vals[0]); }
                #endif

             newuserlist->user = (*mypluginlink->strdupfunc)(vals[0]);
             newuserlist->next = NULL;
             /*create user rule */
             newace = (*mypluginlink->mallocfunc)(sizeof (struct ace));
             memset(newace, 0, sizeof(struct ace));
             newace->users = newuserlist;
             newace->action = BANDLIM;
             /*create user bandlim */
             newbandlim =(*mypluginlink->mallocfunc)(sizeof (struct bandlim));
             memset(newbandlim, 0, sizeof(struct bandlim));
             newbandlim->rate = bandwidth;
             newbandlim->ace = newace;
             newbandlim->next = mypluginlink->conf->bandlimiter;
             mypluginlink->conf->bandlimiter = newbandlim;

             /* -------------counters----------
             create user list */
             newuserlist = (*mypluginlink->mallocfunc)(sizeof (struct userlist));
             if (usercaselow  > 0)
                #ifdef _WIN32
                { CharLower(vals[0]); }
                #else
                { lower(vals[0]);  }
                #endif
             newuserlist->user = (*mypluginlink->strdupfunc)(vals[0]);
             newuserlist->next = NULL;
             /*create user rule */
             newace = (*mypluginlink->mallocfunc)(sizeof (struct ace));
             memset(newace, 0, sizeof(struct ace));
             newace->users = newuserlist;
             newace->action = COUNTIN;
             /*create user counter */
             newtrafcount =(*mypluginlink->mallocfunc)(sizeof (struct trafcount));
             memset(newtrafcount, 0, sizeof(struct trafcount));
             newtrafcount->ace = newace;
             newtrafcount->type=rtype;
             newtrafcount->traflim64  = traflimit;
             newtrafcount->comment=(*mypluginlink->strdupfunc)("ldapcounters");
             newtrafcount->number=0;
             tmpbuf=malloc(strlen(pat_file)+strlen(ldap_dircount)+strlen(vals[0]));
             sprintf(tmpbuf,pat_file,ldap_dircount,vals[0]);
             f=NULL;
             f=fopen(tmpbuf,"rb");
             if(f!=NULL)
              {

               fseek(f,0,SEEK_SET);
               fgets(buf, 256, f);
  	       sscanf(buf,"%"PRINTF_INT64_MODIFIER"u %lu %lu\n",&rcounter.traf64,
				&rcounter.cleared, &rcounter.updated);

               newtrafcount->traf64=rcounter.traf64;
               newtrafcount->cleared=rcounter.cleared;
               newtrafcount->updated=rcounter.updated;
               fclose(f);
              }
             free(tmpbuf);

             newtrafcount->next = mypluginlink->conf->trafcounter;
             mypluginlink->conf->trafcounter = newtrafcount;

             ldap_value_free(vals);
           }
          msg=ldap_next_entry(ld, msg);
         rc--;
        }

   }/* end if (rc > 0) */

  ldap_unbind_s(ld);

  return 0;
}
/* --------------------------------------------------------------------------
 handle command ldapattrsgroup */
int h_attrsgroup(int argc, unsigned char ** argv)
{
 if (argc < 1)
  {
   fprintf(stderr, "Error in ldapattr: See documentation of ldapauth plugin.\n");
   return 1;
  }
  attrs[0]=strdup(argv[1]);
  ldap_group_attr=strdup(argv[2]);

  if(argc == 4)
   { usercaselow=atoi(argv[3]); }

  return 0;
}
/* --------------------------------------------------------------------------
 handle command ldapdircount */
int h_dircount(int argc, unsigned char ** argv)
{
 if (argc < 1)
  {
   fprintf(stderr, "Error in ldapdircount: See documentation of ldapauth plugin.\n");
   return 1;
  }
  ldap_dircount=strdup(argv[1]);
  return 0;
}

/*------------------------------- MAIN --------------------------------------
 start plugin init  */

#ifdef WATCOM
#pragma aux start "*" parm caller [ ] value struct float struct routine [eax] modify [eax ecx edx]
#undef PLUGINCALL
#define PLUGINCALL
#endif

PLUGINAPI int PLUGINCALL start(struct pluginlink * pluginlink,
					 int argc, char** argv)

{

 if (already_loaded != 0)
   {
    free(ldap_access);
    free(ldap_sbase);
    free(ldap_serv);
    free(ldap_user);
    free(ldap_pass);
    free(ldap_userenv);
    free(ldap_dircount);
    free(ldap_group_attr);
    free(attrs[0]);
    return (0);
   }

   already_loaded = 1;

    mypluginlink=pluginlink;

    ldap_access=NULL;
    ldap_sbase=NULL;
    ldap_serv=NULL;
    ldap_user=NULL;
    ldap_pass=NULL;
    ldap_userenv=NULL;
    ldap_trafgroup=NULL;
    ldap_dircount=NULL;
    ldap_group_attr=NULL;

    myalwaysauth.authenticate = ldapfunc;
    myalwaysauth.authorize = pluginlink->checkACL;
    myalwaysauth.desc = "ldap";
    myalwaysauth.next = pluginlink->authfuncs->next;
    pluginlink->authfuncs->next = &myalwaysauth;

    /* add command: ldapconnect ipserv user_serv pass_serv  */
    ldap_serv_auth_handler.minargs = 3;
    ldap_serv_auth_handler.maxargs = 4;
    ldap_serv_auth_handler.command = "ldapconnect";
    ldap_serv_auth_handler.handler = h_ldapconnect;
    ldap_serv_auth_handler.next = pluginlink->commandhandlers->next;
    pluginlink->commandhandlers->next = &ldap_serv_auth_handler;

    /* add command:  ldapaccess cn=internet,cn=users,dc=domain,dc=ru  */
    ldap_access_handler.minargs = 2;
    ldap_access_handler.maxargs = 2;
    ldap_access_handler.command = "ldapaccess";
    ldap_access_handler.handler = h_access;
    ldap_access_handler.next = pluginlink->commandhandlers->next;
    pluginlink->commandhandlers->next = &ldap_access_handler;

    /* add command: ldapsbase cn=users,dc=domain,dc=ru  */
    ldap_sbase_handler.minargs = 2;
    ldap_sbase_handler.maxargs = 2;
    ldap_sbase_handler.command = "ldapsbase";
    ldap_sbase_handler.handler = h_sbase;
    ldap_sbase_handler.next = pluginlink->commandhandlers->next;
    pluginlink->commandhandlers->next = &ldap_sbase_handler;

    /* add command: ldapuserenv (cn=users,dc=domain,dc=ru)  */
    ldap_userenv_handler.minargs = 2;
    ldap_userenv_handler.maxargs = 2;
    ldap_userenv_handler.command = "ldapuserenv";
    ldap_userenv_handler.handler = h_userenv;
    ldap_userenv_handler.next = pluginlink->commandhandlers->next;
    pluginlink->commandhandlers->next = &ldap_userenv_handler;

    /* add command: ldaptrafgroup cn=traf500,cn=users,dc=domain,dc=ru M 500 333 */
    ldap_trafgroup_handler.minargs = 5;
    ldap_trafgroup_handler.maxargs = 5;
    ldap_trafgroup_handler.command = "ldaptrafgroup";
    ldap_trafgroup_handler.handler = h_trafgroup;
    ldap_trafgroup_handler.next = pluginlink->commandhandlers->next;
    pluginlink->commandhandlers->next = &ldap_trafgroup_handler;

    /* add command: ldapattr cn memberOf usercaselow=1 */
    ldap_attrsgroup_handler.minargs = 3;
    ldap_attrsgroup_handler.maxargs = 4;
    ldap_attrsgroup_handler.command = "ldapattr";
    ldap_attrsgroup_handler.handler = h_attrsgroup;
    ldap_attrsgroup_handler.next = pluginlink->commandhandlers->next;
    pluginlink->commandhandlers->next = &ldap_attrsgroup_handler;

    /* add command: ldapdircount c:\3proxy\ */
    ldap_dircount_handler.minargs = 2;
    ldap_dircount_handler.maxargs = 2;
    ldap_dircount_handler.command = "ldapdircount";
    ldap_dircount_handler.handler = h_dircount;
    ldap_dircount_handler.next = pluginlink->commandhandlers->next;
    pluginlink->commandhandlers->next = &ldap_dircount_handler;

    /*create job shedule for processing reload, save counters to file */
    memset(&myschedule,0,sizeof(struct schedule));
    myschedule.type=MINUTELY;
    myschedule.function=savecounters;
    myschedule.next = *pluginlink->schedule;
    *pluginlink->schedule=&myschedule;

    return 0;
}

{'repo_name': 'z3APA3A/3proxy', 'stars': '1623', 'repo_language': 'C', 'file_name': '3proxy.cfg.sample', 'mime_type': 'text/plain', 'hash': -6634201418370539432, 'source_dataset': 'data'}


// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: Encryption.proto

package org.apache.hadoop.hbase.protobuf.generated;

public final class EncryptionProtos {
  private EncryptionProtos() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
  }
  public interface WrappedKeyOrBuilder
      extends com.google.protobuf.MessageOrBuilder {

    // required string algorithm = 1;
    /**
     * required string algorithm = 1;
     */
    boolean hasAlgorithm();
    /**
     * required string algorithm = 1;
     */
    java.lang.String getAlgorithm();
    /**
     * required string algorithm = 1;
     */
    com.google.protobuf.ByteString
        getAlgorithmBytes();

    // required uint32 length = 2;
    /**
     * required uint32 length = 2;
     */
    boolean hasLength();
    /**
     * required uint32 length = 2;
     */
    int getLength();

    // required bytes data = 3;
    /**
     * required bytes data = 3;
     */
    boolean hasData();
    /**
     * required bytes data = 3;
     */
    com.google.protobuf.ByteString getData();

    // optional bytes iv = 4;
    /**
     * optional bytes iv = 4;
     */
    boolean hasIv();
    /**
     * optional bytes iv = 4;
     */
    com.google.protobuf.ByteString getIv();

    // optional bytes hash = 5;
    /**
     * optional bytes hash = 5;
     */
    boolean hasHash();
    /**
     * optional bytes hash = 5;
     */
    com.google.protobuf.ByteString getHash();
  }
  /**
   * Protobuf type {@code WrappedKey}
   */
  public static final class WrappedKey extends
      com.google.protobuf.GeneratedMessage
      implements WrappedKeyOrBuilder {
    // Use WrappedKey.newBuilder() to construct.
    private WrappedKey(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
      super(builder);
      this.unknownFields = builder.getUnknownFields();
    }
    private WrappedKey(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }

    private static final WrappedKey defaultInstance;
    public static WrappedKey getDefaultInstance() {
      return defaultInstance;
    }

    public WrappedKey getDefaultInstanceForType() {
      return defaultInstance;
    }

    private final com.google.protobuf.UnknownFieldSet unknownFields;
    @java.lang.Override
    public final com.google.protobuf.UnknownFieldSet
        getUnknownFields() {
      return this.unknownFields;
    }
    private WrappedKey(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      initFields();
      int mutable_bitField0_ = 0;
      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
          com.google.protobuf.UnknownFieldSet.newBuilder();
      try {
        boolean done = false;
        while (!done) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              done = true;
              break;
            default: {
              if (!parseUnknownField(input, unknownFields,
                                     extensionRegistry, tag)) {
                done = true;
              }
              break;
            }
            case 10: {
              bitField0_ |= 0x00000001;
              algorithm_ = input.readBytes();
              break;
            }
            case 16: {
              bitField0_ |= 0x00000002;
              length_ = input.readUInt32();
              break;
            }
            case 26: {
              bitField0_ |= 0x00000004;
              data_ = input.readBytes();
              break;
            }
            case 34: {
              bitField0_ |= 0x00000008;
              iv_ = input.readBytes();
              break;
            }
            case 42: {
              bitField0_ |= 0x00000010;
              hash_ = input.readBytes();
              break;
            }
          }
        }
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.setUnfinishedMessage(this);
      } catch (java.io.IOException e) {
        throw new com.google.protobuf.InvalidProtocolBufferException(
            e.getMessage()).setUnfinishedMessage(this);
      } finally {
        this.unknownFields = unknownFields.build();
        makeExtensionsImmutable();
      }
    }
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.internal_static_WrappedKey_descriptor;
    }

    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.internal_static_WrappedKey_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey.class, org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey.Builder.class);
    }

    public static com.google.protobuf.Parser<WrappedKey> PARSER =
        new com.google.protobuf.AbstractParser<WrappedKey>() {
      public WrappedKey parsePartialFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
        return new WrappedKey(input, extensionRegistry);
      }
    };

    @java.lang.Override
    public com.google.protobuf.Parser<WrappedKey> getParserForType() {
      return PARSER;
    }

    private int bitField0_;
    // required string algorithm = 1;
    public static final int ALGORITHM_FIELD_NUMBER = 1;
    private java.lang.Object algorithm_;
    /**
     * required string algorithm = 1;
     */
    public boolean hasAlgorithm() {
      return ((bitField0_ & 0x00000001) == 0x00000001);
    }
    /**
     * required string algorithm = 1;
     */
    public java.lang.String getAlgorithm() {
      java.lang.Object ref = algorithm_;
      if (ref instanceof java.lang.String) {
        return (java.lang.String) ref;
      } else {
        com.google.protobuf.ByteString bs =
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          algorithm_ = s;
        }
        return s;
      }
    }
    /**
     * required string algorithm = 1;
     */
    public com.google.protobuf.ByteString
        getAlgorithmBytes() {
      java.lang.Object ref = algorithm_;
      if (ref instanceof java.lang.String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        algorithm_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    // required uint32 length = 2;
    public static final int LENGTH_FIELD_NUMBER = 2;
    private int length_;
    /**
     * required uint32 length = 2;
     */
    public boolean hasLength() {
      return ((bitField0_ & 0x00000002) == 0x00000002);
    }
    /**
     * required uint32 length = 2;
     */
    public int getLength() {
      return length_;
    }

    // required bytes data = 3;
    public static final int DATA_FIELD_NUMBER = 3;
    private com.google.protobuf.ByteString data_;
    /**
     * required bytes data = 3;
     */
    public boolean hasData() {
      return ((bitField0_ & 0x00000004) == 0x00000004);
    }
    /**
     * required bytes data = 3;
     */
    public com.google.protobuf.ByteString getData() {
      return data_;
    }

    // optional bytes iv = 4;
    public static final int IV_FIELD_NUMBER = 4;
    private com.google.protobuf.ByteString iv_;
    /**
     * optional bytes iv = 4;
     */
    public boolean hasIv() {
      return ((bitField0_ & 0x00000008) == 0x00000008);
    }
    /**
     * optional bytes iv = 4;
     */
    public com.google.protobuf.ByteString getIv() {
      return iv_;
    }

    // optional bytes hash = 5;
    public static final int HASH_FIELD_NUMBER = 5;
    private com.google.protobuf.ByteString hash_;
    /**
     * optional bytes hash = 5;
     */
    public boolean hasHash() {
      return ((bitField0_ & 0x00000010) == 0x00000010);
    }
    /**
     * optional bytes hash = 5;
     */
    public com.google.protobuf.ByteString getHash() {
      return hash_;
    }

    private void initFields() {
      algorithm_ = "";
      length_ = 0;
      data_ = com.google.protobuf.ByteString.EMPTY;
      iv_ = com.google.protobuf.ByteString.EMPTY;
      hash_ = com.google.protobuf.ByteString.EMPTY;
    }
    private byte memoizedIsInitialized = -1;
    public final boolean isInitialized() {
      byte isInitialized = memoizedIsInitialized;
      if (isInitialized != -1) return isInitialized == 1;

      if (!hasAlgorithm()) {
        memoizedIsInitialized = 0;
        return false;
      }
      if (!hasLength()) {
        memoizedIsInitialized = 0;
        return false;
      }
      if (!hasData()) {
        memoizedIsInitialized = 0;
        return false;
      }
      memoizedIsInitialized = 1;
      return true;
    }

    public void writeTo(com.google.protobuf.CodedOutputStream output)
                        throws java.io.IOException {
      getSerializedSize();
      if (((bitField0_ & 0x00000001) == 0x00000001)) {
        output.writeBytes(1, getAlgorithmBytes());
      }
      if (((bitField0_ & 0x00000002) == 0x00000002)) {
        output.writeUInt32(2, length_);
      }
      if (((bitField0_ & 0x00000004) == 0x00000004)) {
        output.writeBytes(3, data_);
      }
      if (((bitField0_ & 0x00000008) == 0x00000008)) {
        output.writeBytes(4, iv_);
      }
      if (((bitField0_ & 0x00000010) == 0x00000010)) {
        output.writeBytes(5, hash_);
      }
      getUnknownFields().writeTo(output);
    }

    private int memoizedSerializedSize = -1;
    public int getSerializedSize() {
      int size = memoizedSerializedSize;
      if (size != -1) return size;

      size = 0;
      if (((bitField0_ & 0x00000001) == 0x00000001)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(1, getAlgorithmBytes());
      }
      if (((bitField0_ & 0x00000002) == 0x00000002)) {
        size += com.google.protobuf.CodedOutputStream
          .computeUInt32Size(2, length_);
      }
      if (((bitField0_ & 0x00000004) == 0x00000004)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(3, data_);
      }
      if (((bitField0_ & 0x00000008) == 0x00000008)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(4, iv_);
      }
      if (((bitField0_ & 0x00000010) == 0x00000010)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(5, hash_);
      }
      size += getUnknownFields().getSerializedSize();
      memoizedSerializedSize = size;
      return size;
    }

    private static final long serialVersionUID = 0L;
    @java.lang.Override
    protected java.lang.Object writeReplace()
        throws java.io.ObjectStreamException {
      return super.writeReplace();
    }

    @java.lang.Override
    public boolean equals(final java.lang.Object obj) {
      if (obj == this) {
       return true;
      }
      if (!(obj instanceof org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey)) {
        return super.equals(obj);
      }
      org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey other = (org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey) obj;

      boolean result = true;
      result = result && (hasAlgorithm() == other.hasAlgorithm());
      if (hasAlgorithm()) {
        result = result && getAlgorithm()
            .equals(other.getAlgorithm());
      }
      result = result && (hasLength() == other.hasLength());
      if (hasLength()) {
        result = result && (getLength()
            == other.getLength());
      }
      result = result && (hasData() == other.hasData());
      if (hasData()) {
        result = result && getData()
            .equals(other.getData());
      }
      result = result && (hasIv() == other.hasIv());
      if (hasIv()) {
        result = result && getIv()
            .equals(other.getIv());
      }
      result = result && (hasHash() == other.hasHash());
      if (hasHash()) {
        result = result && getHash()
            .equals(other.getHash());
      }
      result = result &&
          getUnknownFields().equals(other.getUnknownFields());
      return result;
    }

    private int memoizedHashCode = 0;
    @java.lang.Override
    public int hashCode() {
      if (memoizedHashCode != 0) {
        return memoizedHashCode;
      }
      int hash = 41;
      hash = (19 * hash) + getDescriptorForType().hashCode();
      if (hasAlgorithm()) {
        hash = (37 * hash) + ALGORITHM_FIELD_NUMBER;
        hash = (53 * hash) + getAlgorithm().hashCode();
      }
      if (hasLength()) {
        hash = (37 * hash) + LENGTH_FIELD_NUMBER;
        hash = (53 * hash) + getLength();
      }
      if (hasData()) {
        hash = (37 * hash) + DATA_FIELD_NUMBER;
        hash = (53 * hash) + getData().hashCode();
      }
      if (hasIv()) {
        hash = (37 * hash) + IV_FIELD_NUMBER;
        hash = (53 * hash) + getIv().hashCode();
      }
      if (hasHash()) {
        hash = (37 * hash) + HASH_FIELD_NUMBER;
        hash = (53 * hash) + getHash().hashCode();
      }
      hash = (29 * hash) + getUnknownFields().hashCode();
      memoizedHashCode = hash;
      return hash;
    }

    public static org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey parseFrom(
        com.google.protobuf.ByteString data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey parseFrom(
        com.google.protobuf.ByteString data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey parseFrom(byte[] data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey parseFrom(
        byte[] data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey parseFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey parseFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }
    public static org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey parseDelimitedFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input);
    }
    public static org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey parseDelimitedFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input, extensionRegistry);
    }
    public static org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey parseFrom(
        com.google.protobuf.CodedInputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey parseFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }

    public static Builder newBuilder() { return Builder.create(); }
    public Builder newBuilderForType() { return newBuilder(); }
    public static Builder newBuilder(org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey prototype) {
      return newBuilder().mergeFrom(prototype);
    }
    public Builder toBuilder() { return newBuilder(this); }

    @java.lang.Override
    protected Builder newBuilderForType(
        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
      Builder builder = new Builder(parent);
      return builder;
    }
    /**
     * Protobuf type {@code WrappedKey}
     */
    public static final class Builder extends
        com.google.protobuf.GeneratedMessage.Builder<Builder>
       implements org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKeyOrBuilder {
      public static final com.google.protobuf.Descriptors.Descriptor
          getDescriptor() {
        return org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.internal_static_WrappedKey_descriptor;
      }

      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
          internalGetFieldAccessorTable() {
        return org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.internal_static_WrappedKey_fieldAccessorTable
            .ensureFieldAccessorsInitialized(
                org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey.class, org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey.Builder.class);
      }

      // Construct using org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey.newBuilder()
      private Builder() {
        maybeForceBuilderInitialization();
      }

      private Builder(
          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
        super(parent);
        maybeForceBuilderInitialization();
      }
      private void maybeForceBuilderInitialization() {
        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
        }
      }
      private static Builder create() {
        return new Builder();
      }

      public Builder clear() {
        super.clear();
        algorithm_ = "";
        bitField0_ = (bitField0_ & ~0x00000001);
        length_ = 0;
        bitField0_ = (bitField0_ & ~0x00000002);
        data_ = com.google.protobuf.ByteString.EMPTY;
        bitField0_ = (bitField0_ & ~0x00000004);
        iv_ = com.google.protobuf.ByteString.EMPTY;
        bitField0_ = (bitField0_ & ~0x00000008);
        hash_ = com.google.protobuf.ByteString.EMPTY;
        bitField0_ = (bitField0_ & ~0x00000010);
        return this;
      }

      public Builder clone() {
        return create().mergeFrom(buildPartial());
      }

      public com.google.protobuf.Descriptors.Descriptor
          getDescriptorForType() {
        return org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.internal_static_WrappedKey_descriptor;
      }

      public org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey getDefaultInstanceForType() {
        return org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey.getDefaultInstance();
      }

      public org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey build() {
        org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey result = buildPartial();
        if (!result.isInitialized()) {
          throw newUninitializedMessageException(result);
        }
        return result;
      }

      public org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey buildPartial() {
        org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey result = new org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey(this);
        int from_bitField0_ = bitField0_;
        int to_bitField0_ = 0;
        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
          to_bitField0_ |= 0x00000001;
        }
        result.algorithm_ = algorithm_;
        if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
          to_bitField0_ |= 0x00000002;
        }
        result.length_ = length_;
        if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
          to_bitField0_ |= 0x00000004;
        }
        result.data_ = data_;
        if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
          to_bitField0_ |= 0x00000008;
        }
        result.iv_ = iv_;
        if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
          to_bitField0_ |= 0x00000010;
        }
        result.hash_ = hash_;
        result.bitField0_ = to_bitField0_;
        onBuilt();
        return result;
      }

      public Builder mergeFrom(com.google.protobuf.Message other) {
        if (other instanceof org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey) {
          return mergeFrom((org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey)other);
        } else {
          super.mergeFrom(other);
          return this;
        }
      }

      public Builder mergeFrom(org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey other) {
        if (other == org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey.getDefaultInstance()) return this;
        if (other.hasAlgorithm()) {
          bitField0_ |= 0x00000001;
          algorithm_ = other.algorithm_;
          onChanged();
        }
        if (other.hasLength()) {
          setLength(other.getLength());
        }
        if (other.hasData()) {
          setData(other.getData());
        }
        if (other.hasIv()) {
          setIv(other.getIv());
        }
        if (other.hasHash()) {
          setHash(other.getHash());
        }
        this.mergeUnknownFields(other.getUnknownFields());
        return this;
      }

      public final boolean isInitialized() {
        if (!hasAlgorithm()) {

          return false;
        }
        if (!hasLength()) {

          return false;
        }
        if (!hasData()) {

          return false;
        }
        return true;
      }

      public Builder mergeFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws java.io.IOException {
        org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey parsedMessage = null;
        try {
          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
          parsedMessage = (org.apache.hadoop.hbase.protobuf.generated.EncryptionProtos.WrappedKey) e.getUnfinishedMessage();
          throw e;
        } finally {
          if (parsedMessage != null) {
            mergeFrom(parsedMessage);
          }
        }
        return this;
      }
      private int bitField0_;

      // required string algorithm = 1;
      private java.lang.Object algorithm_ = "";
      /**
       * required string algorithm = 1;
       */
      public boolean hasAlgorithm() {
        return ((bitField0_ & 0x00000001) == 0x00000001);
      }
      /**
       * required string algorithm = 1;
       */
      public java.lang.String getAlgorithm() {
        java.lang.Object ref = algorithm_;
        if (!(ref instanceof java.lang.String)) {
          java.lang.String s = ((com.google.protobuf.ByteString) ref)
              .toStringUtf8();
          algorithm_ = s;
          return s;
        } else {
          return (java.lang.String) ref;
        }
      }
      /**
       * required string algorithm = 1;
       */
      public com.google.protobuf.ByteString
          getAlgorithmBytes() {
        java.lang.Object ref = algorithm_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b =
              com.google.protobuf.ByteString.copyFromUtf8(
                  (java.lang.String) ref);
          algorithm_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * required string algorithm = 1;
       */
      public Builder setAlgorithm(
          java.lang.String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000001;
        algorithm_ = value;
        onChanged();
        return this;
      }
      /**
       * required string algorithm = 1;
       */
      public Builder clearAlgorithm() {
        bitField0_ = (bitField0_ & ~0x00000001);
        algorithm_ = getDefaultInstance().getAlgorithm();
        onChanged();
        return this;
      }
      /**
       * required string algorithm = 1;
       */
      public Builder setAlgorithmBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000001;
        algorithm_ = value;
        onChanged();
        return this;
      }

      // required uint32 length = 2;
      private int length_ ;
      /**
       * required uint32 length = 2;
       */
      public boolean hasLength() {
        return ((bitField0_ & 0x00000002) == 0x00000002);
      }
      /**
       * required uint32 length = 2;
       */
      public int getLength() {
        return length_;
      }
      /**
       * required uint32 length = 2;
       */
      public Builder setLength(int value) {
        bitField0_ |= 0x00000002;
        length_ = value;
        onChanged();
        return this;
      }
      /**
       * required uint32 length = 2;
       */
      public Builder clearLength() {
        bitField0_ = (bitField0_ & ~0x00000002);
        length_ = 0;
        onChanged();
        return this;
      }

      // required bytes data = 3;
      private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY;
      /**
       * required bytes data = 3;
       */
      public boolean hasData() {
        return ((bitField0_ & 0x00000004) == 0x00000004);
      }
      /**
       * required bytes data = 3;
       */
      public com.google.protobuf.ByteString getData() {
        return data_;
      }
      /**
       * required bytes data = 3;
       */
      public Builder setData(com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000004;
        data_ = value;
        onChanged();
        return this;
      }
      /**
       * required bytes data = 3;
       */
      public Builder clearData() {
        bitField0_ = (bitField0_ & ~0x00000004);
        data_ = getDefaultInstance().getData();
        onChanged();
        return this;
      }

      // optional bytes iv = 4;
      private com.google.protobuf.ByteString iv_ = com.google.protobuf.ByteString.EMPTY;
      /**
       * optional bytes iv = 4;
       */
      public boolean hasIv() {
        return ((bitField0_ & 0x00000008) == 0x00000008);
      }
      /**
       * optional bytes iv = 4;
       */
      public com.google.protobuf.ByteString getIv() {
        return iv_;
      }
      /**
       * optional bytes iv = 4;
       */
      public Builder setIv(com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000008;
        iv_ = value;
        onChanged();
        return this;
      }
      /**
       * optional bytes iv = 4;
       */
      public Builder clearIv() {
        bitField0_ = (bitField0_ & ~0x00000008);
        iv_ = getDefaultInstance().getIv();
        onChanged();
        return this;
      }

      // optional bytes hash = 5;
      private com.google.protobuf.ByteString hash_ = com.google.protobuf.ByteString.EMPTY;
      /**
       * optional bytes hash = 5;
       */
      public boolean hasHash() {
        return ((bitField0_ & 0x00000010) == 0x00000010);
      }
      /**
       * optional bytes hash = 5;
       */
      public com.google.protobuf.ByteString getHash() {
        return hash_;
      }
      /**
       * optional bytes hash = 5;
       */
      public Builder setHash(com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000010;
        hash_ = value;
        onChanged();
        return this;
      }
      /**
       * optional bytes hash = 5;
       */
      public Builder clearHash() {
        bitField0_ = (bitField0_ & ~0x00000010);
        hash_ = getDefaultInstance().getHash();
        onChanged();
        return this;
      }

      // @@protoc_insertion_point(builder_scope:WrappedKey)
    }

    static {
      defaultInstance = new WrappedKey(true);
      defaultInstance.initFields();
    }

    // @@protoc_insertion_point(class_scope:WrappedKey)
  }

  private static com.google.protobuf.Descriptors.Descriptor
    internal_static_WrappedKey_descriptor;
  private static
    com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internal_static_WrappedKey_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\n\020Encryption.proto\"W\n\nWrappedKey\022\021\n\talgo" +
      "rithm\030\001 \002(\t\022\016\n\006length\030\002 \002(\r\022\014\n\004data\030\003 \002(" +
      "\014\022\n\n\002iv\030\004 \001(\014\022\014\n\004hash\030\005 \001(\014BC\n*org.apach" +
      "e.hadoop.hbase.protobuf.generatedB\020Encry" +
      "ptionProtosH\001\240\001\001"
    };
    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
      new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
        public com.google.protobuf.ExtensionRegistry assignDescriptors(
            com.google.protobuf.Descriptors.FileDescriptor root) {
          descriptor = root;
          internal_static_WrappedKey_descriptor =
            getDescriptor().getMessageTypes().get(0);
          internal_static_WrappedKey_fieldAccessorTable = new
            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
              internal_static_WrappedKey_descriptor,
              new java.lang.String[] { "Algorithm", "Length", "Data", "Iv", "Hash", });
          return null;
        }
      };
    com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
        }, assigner);
  }

  // @@protoc_insertion_point(outer_class_scope)
}

{'repo_name': 'apache/trafodion', 'stars': '226', 'repo_language': 'C++', 'file_name': 'wms-site.xml', 'mime_type': 'text/xml', 'hash': -8639368172046981294, 'source_dataset': 'data'}


<!DOCTYPE html>

    <meta charset="utf-8">
    <title>src/equations/FrictionEquation.js - p2.js</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="icon" href="../assets/favicon.ico">

            API Docs for: 0.7.1

APIs

Classes

Modules

                            <input type="search" id="api-filter" placeholder="Type to filter APIs">

AABB

AngleLockEquation

Body

Box

Broadphase

Capsule

Circle

Constraint

ContactEquation

ContactMaterial

Convex

DistanceConstraint

Equation

EventEmitter

FrictionEquation

GearConstraint

GSSolver

Heightfield

Island

IslandManager

IslandNode

Line

LinearSpring

LockConstraint

Material

NaiveBroadphase

Narrowphase

Object pooling utility.

OverlapKeeper

OverlapKeeperRecord

Particle

Plane

PrismaticConstraint

Ray

RaycastResult

RevoluteConstraint

RotationalLockEquation

RotationalSpring

RotationalVelocityEquation

SAPBroadphase

Shape

Solver

Spring

TopDownVehicle

TupleDictionary

Utils

vec2

WheelConstraint

World

                    Show:

                        <input type="checkbox" id="api-show-inherited" checked>
                        Inherited

                        <input type="checkbox" id="api-show-protected">
                        Protected

                        <input type="checkbox" id="api-show-private">
                        Private

                        <input type="checkbox" id="api-show-deprecated">
                        Deprecated

File: src/equations/FrictionEquation.js

var vec2 = require('../math/vec2')
,   Equation = require('./Equation')
,   Utils = require('../utils/Utils');

module.exports = FrictionEquation;

/**
 * Constrains the slipping in a contact along a tangent
 *
 * @class FrictionEquation
 * @constructor
 * @param {Body} bodyA
 * @param {Body} bodyB
 * @param {Number} slipForce
 * @extends Equation
 */
function FrictionEquation(bodyA, bodyB, slipForce){
    Equation.call(this, bodyA, bodyB, -slipForce, slipForce);

    /**
     * Relative vector from center of body A to the contact point, world oriented.
     * @property contactPointA
     * @type {Array}
     */
    this.contactPointA = vec2.create();

    /**
     * Relative vector from center of body B to the contact point, world oriented.
     * @property contactPointB
     * @type {Array}
     */
    this.contactPointB = vec2.create();

    /**
     * Tangent vector that the friction force will act along. World oriented.
     * @property t
     * @type {Array}
     */
    this.t = vec2.create();

    /**
     * ContactEquations connected to this friction equation. The contact equations can be used to rescale the max force for the friction. If more than one contact equation is given, then the max force can be set to the average.
     * @property contactEquations
     * @type {ContactEquation}
     */
    this.contactEquations = [];

    /**
     * The shape in body i that triggered this friction.
     * @property shapeA
     * @type {Shape}
     * @todo Needed? The shape can be looked up via contactEquation.shapeA...
     */
    this.shapeA = null;

    /**
     * The shape in body j that triggered this friction.
     * @property shapeB
     * @type {Shape}
     * @todo Needed? The shape can be looked up via contactEquation.shapeB...
     */
    this.shapeB = null;

    /**
     * The friction coefficient to use.
     * @property frictionCoefficient
     * @type {Number}
     */
    this.frictionCoefficient = 0.3;
}
FrictionEquation.prototype = new Equation();
FrictionEquation.prototype.constructor = FrictionEquation;

/**
 * Set the slipping condition for the constraint. The friction force cannot be
 * larger than this value.
 * @method setSlipForce
 * @param  {Number} slipForce
 */
FrictionEquation.prototype.setSlipForce = function(slipForce){
    this.maxForce = slipForce;
    this.minForce = -slipForce;
};

/**
 * Get the max force for the constraint.
 * @method getSlipForce
 * @return {Number}
 */
FrictionEquation.prototype.getSlipForce = function(){
    return this.maxForce;
};

FrictionEquation.prototype.computeB = function(a,b,h){
    var bi = this.bodyA,
        bj = this.bodyB,
        ri = this.contactPointA,
        rj = this.contactPointB,
        t = this.t,
        G = this.G;

    // G = [-t -rixt t rjxt]
    // And remember, this is a pure velocity constraint, g is always zero!
    G[0] = -t[0];
    G[1] = -t[1];
    G[2] = -vec2.crossLength(ri,t);
    G[3] = t[0];
    G[4] = t[1];
    G[5] = vec2.crossLength(rj,t);

    var GW = this.computeGW(),
        GiMf = this.computeGiMf();

    var B = /* - g * a  */ - GW * b - h*GiMf;

    return B;
};

{'repo_name': 'schteppe/p2.js', 'stars': '2205', 'repo_language': 'JavaScript', 'file_name': 'WebGLRenderer.js', 'mime_type': 'text/plain', 'hash': 6818014795125270508, 'source_dataset': 'data'}


{'repo_name': 'MinecraftForge/MinecraftForge', 'stars': '3990', 'repo_language': 'Java', 'file_name': 'gradle-wrapper.properties', 'mime_type': 'text/plain', 'hash': 5757142972790315559, 'source_dataset': 'data'}


//===-- GraphWriter.cpp - Implements GraphWriter support routines ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements misc. GraphWriter support routines.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/GraphWriter.h"
#include "llvm/Config/config.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
using namespace llvm;

static cl::opt<bool> ViewBackground("view-background", cl::Hidden,
  cl::desc("Execute graph viewer in the background. Creates tmp file litter."));

std::string llvm::DOT::EscapeString(const std::string &Label) {
  std::string Str(Label);
  for (unsigned i = 0; i != Str.length(); ++i)
  switch (Str[i]) {
    case '\n':
      Str.insert(Str.begin()+i, '\\');  // Escape character...
      ++i;
      Str[i] = 'n';
      break;
    case '\t':
      Str.insert(Str.begin()+i, ' ');  // Convert to two spaces
      ++i;
      Str[i] = ' ';
      break;
    case '\\':
      if (i+1 != Str.length())
        switch (Str[i+1]) {
          case 'l': continue; // don't disturb \l
          case '|': case '{': case '}':
            Str.erase(Str.begin()+i); continue;
          default: break;
        }
    case '{': case '}':
    case '<': case '>':
    case '|': case '"':
      Str.insert(Str.begin()+i, '\\');  // Escape character...
      ++i;  // don't infinite loop
      break;
  }
  return Str;
}

/// \brief Get a color string for this node number. Simply round-robin selects
/// from a reasonable number of colors.
StringRef llvm::DOT::getColorString(unsigned ColorNumber) {
  static const int NumColors = 20;
  static const char* Colors[NumColors] = {
    "aaaaaa", "aa0000", "00aa00", "aa5500", "0055ff", "aa00aa", "00aaaa",
    "555555", "ff5555", "55ff55", "ffff55", "5555ff", "ff55ff", "55ffff",
    "ffaaaa", "aaffaa", "ffffaa", "aaaaff", "ffaaff", "aaffff"};
  return Colors[ColorNumber % NumColors];
}

std::string llvm::createGraphFilename(const Twine &Name, int &FD) {
  FD = -1;
  SmallString<128> Filename;
  error_code EC = sys::fs::createTemporaryFile(Name, "dot", FD, Filename);
  if (EC) {
    errs() << "Error: " << EC.message() << "\n";
    return "";
  }

  errs() << "Writing '" << Filename << "'... ";
  return Filename.str();
}

// Execute the graph viewer. Return true if successful.
static bool LLVM_ATTRIBUTE_UNUSED
ExecGraphViewer(StringRef ExecPath, std::vector<const char*> &args,
                StringRef Filename, bool wait, std::string &ErrMsg) {
  if (wait) {
    if (sys::ExecuteAndWait(ExecPath, &args[0],nullptr,nullptr,0,0,&ErrMsg)) {
      errs() << "Error: " << ErrMsg << "\n";
      return false;
    }
    sys::fs::remove(Filename);
    errs() << " done. \n";
  }
  else {
    sys::ExecuteNoWait(ExecPath, &args[0],nullptr,nullptr,0,&ErrMsg);
    errs() << "Remember to erase graph file: " << Filename.str() << "\n";
  }
  return true;
}

void llvm::DisplayGraph(StringRef FilenameRef, bool wait,
                        GraphProgram::Name program) {
  std::string Filename = FilenameRef;
  wait &= !ViewBackground;
  std::string ErrMsg;
#if HAVE_GRAPHVIZ
  std::string Graphviz(LLVM_PATH_GRAPHVIZ);

  std::vector<const char*> args;
  args.push_back(Graphviz.c_str());
  args.push_back(Filename.c_str());
  args.push_back(nullptr);

  errs() << "Running 'Graphviz' program... ";
  if (!ExecGraphViewer(Graphviz, args, Filename, wait, ErrMsg))
    return;

#elif HAVE_XDOT
  std::vector<const char*> args;
  args.push_back(LLVM_PATH_XDOT);
  args.push_back(Filename.c_str());

  switch (program) {
  case GraphProgram::DOT:   args.push_back("-f"); args.push_back("dot"); break;
  case GraphProgram::FDP:   args.push_back("-f"); args.push_back("fdp"); break;
  case GraphProgram::NEATO: args.push_back("-f"); args.push_back("neato");break;
  case GraphProgram::TWOPI: args.push_back("-f"); args.push_back("twopi");break;
  case GraphProgram::CIRCO: args.push_back("-f"); args.push_back("circo");break;
  }

  args.push_back(0);

  errs() << "Running 'xdot.py' program... ";
  if (!ExecGraphViewer(LLVM_PATH_XDOT, args, Filename, wait, ErrMsg))
    return;

#elif (HAVE_GV && (HAVE_DOT || HAVE_FDP || HAVE_NEATO || \
                   HAVE_TWOPI || HAVE_CIRCO))
  std::string PSFilename = Filename + ".ps";
  std::string prog;

  // Set default grapher
#if HAVE_CIRCO
  prog = LLVM_PATH_CIRCO;
#endif
#if HAVE_TWOPI
  prog = LLVM_PATH_TWOPI;
#endif
#if HAVE_NEATO
  prog = LLVM_PATH_NEATO;
#endif
#if HAVE_FDP
  prog = LLVM_PATH_FDP;
#endif
#if HAVE_DOT
  prog = LLVM_PATH_DOT;
#endif

  // Find which program the user wants
#if HAVE_DOT
  if (program == GraphProgram::DOT)
    prog = LLVM_PATH_DOT;
#endif
#if (HAVE_FDP)
  if (program == GraphProgram::FDP)
    prog = LLVM_PATH_FDP;
#endif
#if (HAVE_NEATO)
  if (program == GraphProgram::NEATO)
    prog = LLVM_PATH_NEATO;
#endif
#if (HAVE_TWOPI)
  if (program == GraphProgram::TWOPI)
    prog = LLVM_PATH_TWOPI;
#endif
#if (HAVE_CIRCO)
  if (program == GraphProgram::CIRCO)
    prog = LLVM_PATH_CIRCO;
#endif

  std::vector<const char*> args;
  args.push_back(prog.c_str());
  args.push_back("-Tps");
  args.push_back("-Nfontname=Courier");
  args.push_back("-Gsize=7.5,10");
  args.push_back(Filename.c_str());
  args.push_back("-o");
  args.push_back(PSFilename.c_str());
  args.push_back(0);

  errs() << "Running '" << prog << "' program... ";

  if (!ExecGraphViewer(prog, args, Filename, wait, ErrMsg))
    return;

  std::string gv(LLVM_PATH_GV);
  args.clear();
  args.push_back(gv.c_str());
  args.push_back(PSFilename.c_str());
  args.push_back("--spartan");
  args.push_back(0);

  ErrMsg.clear();
  if (!ExecGraphViewer(gv, args, PSFilename, wait, ErrMsg))
    return;

#elif HAVE_DOTTY
  std::string dotty(LLVM_PATH_DOTTY);

  std::vector<const char*> args;
  args.push_back(dotty.c_str());
  args.push_back(Filename.c_str());
  args.push_back(0);

// Dotty spawns another app and doesn't wait until it returns
#if defined (__MINGW32__) || defined (_WINDOWS)
  wait = false;
#endif
  errs() << "Running 'dotty' program... ";
  if (!ExecGraphViewer(dotty, args, Filename, wait, ErrMsg))
    return;
#else
  (void)Filename;
  (void)ErrMsg;
#endif
}

{'repo_name': 'christinaa/LLVM-VideoCore4', 'stars': '146', 'repo_language': 'C++', 'file_name': 'Makefile', 'mime_type': 'text/plain', 'hash': -5604458367873521039, 'source_dataset': 'data'}


package com.mapbox.rctmgl.location;

/**
 * Created by nickitaliano on 12/13/17.
 */

public class UserTrackingState {
    // The map view not yet tracked the user location
    public static final int POSSIBLE = 0;

    // The map view has begun to move to the first user location
    public static final int BEGAN = 1;

    // The map views begins a significant transition
    public static final int SIGNIFICANT_TRANSITION = 2;

    // The map view has finished moving to the user location
    public static final int CHANGED = 3;
}

{'repo_name': 'react-native-mapbox-gl/maps', 'stars': '611', 'repo_language': 'JavaScript', 'file_name': 'react-native.mock.js', 'mime_type': 'text/plain', 'hash': -4444052973797674508, 'source_dataset': 'data'}


/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

module.exports = function(arrays) {
  const result = new Set(arrays[0]);

  let i,j, array;
  for (i = 1; i < arrays.length; i++) {
    array = arrays[i];
    for (j = 0; j < array.length; j++) {
      result.add(array[j]);
    }
  }

  return Array.from(result);
};

{'repo_name': 'facebook/jscodeshift', 'stars': '5415', 'repo_language': 'JavaScript', 'file_name': 'retain-first-comment.md', 'mime_type': 'text/plain', 'hash': -7313644671742252594, 'source_dataset': 'data'}


Tab Session Manager

창과 탭의 상태를 저장하고 복원합니다. 자동 저장도 지원합니다.

페이팔로 후원하기

후원하기

새 탭에서 세션 목록 열기

저장

현재 세션을 저장

세션 이름 입력

세션 저장

모든 창 저장

현재 창만 저장

범주 필터

정렬

전체

수동 저장

자동 저장

최신순

오래된 순

오름차순

내림차순

Search by session or tab name

검색

검색 초기화

열기

삭제

이 세션을 삭제할까요?

세션 삭제됨.

세션 창 삭제됨.

세션 탭 삭제됨.

복원

세션 삭제 실패.

세션 창 삭제 실패.

세션 탭 삭제 실패.

세션 저장됨.

세션 저장 실패.

취소

태그 추가

태그 제거

세부 정보

창

여러 창

탭

여러 탭

세션이 없습니다.

하단 우측 버튼을 눌러 세션을 저장해봐요.

일치하는 결과가 없습니다.

선택된 세션이 없습니다.

메뉴

메뉴 닫기

닫기

이름 바꾸기

세션 이름 바꾸기

세션 열기

새 창에서 열기

새 창에서 세션 열기.

현재 창에서 열기

현재 창에서 세션을 엽니다. 비활성화된 여러 창과 모든 탭이 닫힙니다.

현재 창에 추가

모든 탭을 현재 창에 추가 합니다. 만약 세션이 여러 창을 포함한다면, 새 창에서 열립니다.

세션 수정

현재 세션으로 바꾸기

현재 창으로 바꾸기

현재 창 추가하기

세션의 복사본 만들기

홈페이지로 등록

홈페이지에서 제외

오류

IndexedDB는 이 브라우저에서 지원되지 않습니다.

Reload extension

문제 해결하기

창 닫으면, 자동 저장

브라우저 끄면, 자동 저장

주기적으로 자동 저장

설정

세션

단축키

정보

일반

자동 저장

스타일

새 창에서 세션 열기

비활성화 시, 세션을 현재 창에 덮어씁니다.

탭 느리게 열기

세션을 열 때, 탭을 클릭하기 전까지는 각 페이지의 내용을 로드하지 않습니다.<br>비활성화 시, 세션이 열릴 때 메모리 사용이 급증합니다.

Use the "discarded" property for lazy loading

이 옵션을 활성화하면 탭을 열 때 성능이 향상됩니다.

느리게 여는 탭의 파비콘은 보여지지 않습니다.

창 위치 복원하기

세션을 열 때 창 위치와 크기를 복원합니다.

시작

브라우저를 켤 때

이전 세션 열기

지난 번에 닫았던 세션 열기

홈페이지 세션 열기

홈페이지로 등록한 세션을 엽니다. 세션 목록의 메뉴에서 홈페이지로 등록할 수 있습니다.

비활성화

주기적으로 세션 자동 저장

매 X분 마다 세션 자동 저장

간격 (분)

최소 0.1

최대 저장 개수

이 방법으로 저장한 세션의 최대 개수

창을 닫을 때 자동 저장

창을 닫을 때 해당 창만 자동 저장

최대 저장 개수

이 방법으로 저장한 세션의 최대 개수

브라우저를 끌 때 자동 저장

Save the session that includes multiple windows that was closed in a row.

최대 저장 개수

이 방법으로 저장한 세션의 최대 개수

페이지 제목을 자동 저장한 세션 이름으로

세션을 자동 저장할 때, 열려있는 페이지의 제목을 세션의 이름으로 등록합니다.

백업

백업 저장

브라우저를 켤 때, 세션의 백업복을 만들어 다운로드 폴더에 저장합니다.

저장 위치

백업본을 저장할 폴더를 지정해주세요. 저장 위치는 브라우저의 다운로드 폴더 내 하위 폴더만 가능합니다.

다운로드 폴더

최대 백업본 저장 개수

백업본의 수가 이 값을 넘는다면, 가장 오래된 것부터 자동 삭제됩니다.

날짜 형식

예시: YYYY.MM.DD HH:mm:ss

사생활 보호 모드의 창도 저장

세션 저장 시, 저장하지 않을 URL 목록

탭 URL이 목록 상에 있다면, 세션에 등록되지 않습니다. "*" 표현도 사용할 수 있습니다.

장치 이름을 세션에 저장

세션 저장 시, 장치 이름을 태그로 등록합니다. 이를 통해 클라우드 동기화를 이용할 때, 다른 장치에서의 세션과 구분할 수 있습니다.

장치 이름

이 장치의 이름을 입력해주세요.

기존 세션에 장치 이름 등록

모든 저장된 세션에 장치 이름 등록

장치 이름 등록

모든 세션에 장치 이름을 등록하겠나요?

비활성화 시, 세션을 저장할 때 사생활 보호 모드 창은 저장하지 않습니다.

Supports Tree Style Tab

Restore tree state of Tree Style Tab.<br>When this option is enabled, it takes time to restore the session.

Delay when tree restoration (millisecond)

To restore the state of the tree, wait time is required to open the tab. Increase this value if the tree is not restored correctly.

세션 이름을 한 줄로만 보이기

세션 목록에서 세션 이름이 한 줄을 넘어가면, 일부 생략하여 한 줄로 보입니다.

클라우드 동기화

클라우드 동기화 활성화 (베타)

Google Drive에 세션을 저장하여 다른 장치와 동기화합니다.

동기화 중

내려받는 중

올리는 중

삭제하는 중

동기화 완료

로그인

로그아웃

자동 저장된 세션을 동기화

클라우드 내 자동 저장된 세션을 올리기 / 내려받기

팝업

열기 버튼을 누르면

열기 버튼을 눌렀을 때의 기본 동작을 선택해주세요.

저장 버튼을 누르면

저장 버튼을 눌렀을 때의 기본 동작을 선택해주세요.

세션 목록에서 열기 / 삭제 버튼 보이기

커서가 세션 목록 상에 있을 때 열기 / 삭제 버튼을 보입니다.

크기

팝업의 크기를 설정해주세요.

너비

높이

사이드바 너비

세션 목록을 새 탭에서 열기

툴바의 버튼을 누르면 세션 목록을 새 창에서 엽니다.

기타

업데이트 후 설정 페이지 열기

Tab Session Manager가 업데이트 되면, 설정 페이지를 표시합니다. 업데이트 내용을 빠르게 알 수 있습니다.

Tab Session Manager 업데이트 완료!

더보기

업데이트 정보를 보려면 클릭해주세요.

디버그 모드 활성화

디버그 모드가 활성화되면, 디버거로 로그가 출력됩니다.

설정 초기화

모든 설정을 기본값으로 복원

초기화

세션 가져오기

컴퓨터 상에 저장한 세션을 불러와 세션 목록에 추가합니다.<br>SessionManager's 세션 파일(.session)도 지원합니다.

찾아보기...

가져오기

지우기

URL 목옥 가져오기

Create a session from list of URLs and add it to the session list.<br>Format: <URL> <page title (optionally)>

세션 내보내기

모든 세션을 컴퓨터에 저장합니다.

내보내기

세션 삭제

모든 세션 삭제

삭제

키보드 단축키

키보드 단축키를 설정합니다.

단축키 입력

Type a letter

Include either Ctrl or Alt

Include either Command, Ctrl or Alt

The letter can not be used

The shortcut can not be used

Open toolbar popup

Save session (only current window)

Save session (all windows)

모든 세션 내보내기

Clear

초기화

도움을 주신 분

라이센스

후원을 통해 응원해주세요

Tab Session Manager을 사용해주셔서 감사합니다.
보내주신 응원은 저희가 계속 만들어나갈 수 있는 큰 힘이 되어줍니다.
Tab Session Manager를 좋아하신다면, 후원을 통한 응원을 고려해주세요.

amazon.co.jp eGift Cards

설치 페이지

설치 페이지

개인정보보호정책

세션을 가져왔습니다.

실패하였습니다.

모든 세션을 삭제합니다. 확실한가요?

세션

이 페이지는 Tab Session Manager로 열릴 수 없습니다.

Copy URL

Copied.

{'repo_name': 'sienori/Tab-Session-Manager', 'stars': '522', 'repo_language': 'JavaScript', 'file_name': 'index.md', 'mime_type': 'text/plain', 'hash': -2468683433027217316, 'source_dataset': 'data'}


# frozen_string_literal: true

describe Facts::Windows::Processors::Models do
  describe '#call_the_resolver' do
    it 'returns a fact' do
      expected_fact = double(Facter::ResolvedFact, name: 'processors.models', value: 'value')
      allow(Facter::Resolvers::Processors).to receive(:resolve).with(:models).and_return('value')
      allow(Facter::ResolvedFact).to receive(:new).with('processors.models', 'value').and_return(expected_fact)

      fact = Facts::Windows::Processors::Models.new
      expect(fact.call_the_resolver).to eq(expected_fact)
    end
  end
end

{'repo_name': 'puppetlabs/facter', 'stars': '553', 'repo_language': 'C++', 'file_name': 'facter.8', 'mime_type': 'text/troff', 'hash': 6061464766602215370, 'source_dataset': 'data'}


using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Moq;
using Xunit;
using PopForums.Configuration;
using PopForums.Models;
using PopForums.Repositories;
using PopForums.Services;

namespace PopForums.Test.Services
{
	public class SearchServiceTests
	{
		private Mock<ISettingsManager> _mockSettingsManager;
		private Mock<ISearchRepository> _mockSearchRepo;
		private Mock<IForumService> _mockForumService;
		private Mock<ISearchIndexQueueRepository> _searchIndexQueueRepo;
		private Mock<IErrorLog> _errorLog;

		private SearchService GetService()
		{
			_mockSearchRepo = new Mock<ISearchRepository>();
			_mockSettingsManager = new Mock<ISettingsManager>();
			_mockForumService = new Mock<IForumService>();
			_searchIndexQueueRepo = new Mock<ISearchIndexQueueRepository>();
			_errorLog = new Mock<IErrorLog>();
			return new SearchService(_mockSearchRepo.Object, _mockSettingsManager.Object, _mockForumService.Object, _searchIndexQueueRepo.Object, _errorLog.Object);
		}

		[Fact]
		public async Task GetJunkWords()
		{
			var words = new List<string>();
			var service = GetService();
			_mockSearchRepo.Setup(s => s.GetJunkWords()).ReturnsAsync(words);
			var result = await service.GetJunkWords();
			_mockSearchRepo.Verify(s => s.GetJunkWords(), Times.Once());
			Assert.Same(words, result);
		}

		[Fact]
		public async Task CreateWord()
		{
			var service = GetService();
			await service.CreateJunkWord("blah");
			_mockSearchRepo.Verify(s => s.CreateJunkWord("blah"), Times.Once());
		}

		[Fact]
		public void DeleteWord()
		{
			var service = GetService();
			service.DeleteJunkWord("blah");
			_mockSearchRepo.Verify(s => s.DeleteJunkWord("blah"), Times.Once());
		}

		[Fact]
		public async Task GetTopicsReturnsValidResponseWithNoResultsWhenSearchTermIsNull()
		{
			var service = GetService();
			_mockForumService.Setup(x => x.GetNonViewableForumIDs(null)).ReturnsAsync(new List<int>());
			_mockSettingsManager.Setup(x => x.Current.TopicsPerPage).Returns(20);

			var result = await service.GetTopics(null, SearchType.Rank, null, false, 1);

			Assert.Empty(result.Item1.Data);
			Assert.True(result.Item1.IsValid);
		}

		[Fact]
		public async Task GetTopicsReturnsValidResponseWithNoResultsWhenSearchTermIsEmpty()
		{
			var service = GetService();
			_mockForumService.Setup(x => x.GetNonViewableForumIDs(null)).ReturnsAsync(new List<int>());
			_mockSettingsManager.Setup(x => x.Current.TopicsPerPage).Returns(20);

			var result = await service.GetTopics(String.Empty, SearchType.Rank, null, false, 1);

			Assert.Empty(result.Item1.Data);
			Assert.True(result.Item1.IsValid);
		}

		[Fact]
		public async Task GetTopicsIsCalledWithTheRightParameters()
		{
			var query = "test";
			var user = new User();
			var noViewIDs = new List<int> {1};
			var service = GetService();
			_mockForumService.Setup(x => x.GetNonViewableForumIDs(user)).ReturnsAsync(noViewIDs);
			_mockSettingsManager.Setup(x => x.Current.TopicsPerPage).Returns(20);
			_mockSearchRepo.Setup(x => x.SearchTopics(query, noViewIDs, SearchType.Rank, 1, 20)).ReturnsAsync(Tuple.Create(new Response<List<Topic>>(new List<Topic>()), 0));

			await service.GetTopics(query, SearchType.Rank, user, false, 1);

			_mockSearchRepo.Verify(x => x.SearchTopics(query, noViewIDs, SearchType.Rank, 1, 20), Times.Once);
		}

		[Fact]
		public async Task GetTopicsOutsCorrectPagerContextAndValidResult()
		{
			var query = "test";
			var user = new User();
			var noViewIDs = new List<int> { 1 };
			var list = new List<Topic>();
			var service = GetService();
			_mockForumService.Setup(x => x.GetNonViewableForumIDs(user)).ReturnsAsync(noViewIDs);
			_mockSettingsManager.Setup(x => x.Current.TopicsPerPage).Returns(20);
			var count = 50;
			_mockSearchRepo.Setup(x => x.SearchTopics(query, noViewIDs, SearchType.Rank, 21, 20)).ReturnsAsync(Tuple.Create(new Response<List<Topic>>(list), count));

			var (response, pagerContext) = await service.GetTopics(query, SearchType.Rank, user, false, 2);

			Assert.Equal(20, pagerContext.PageSize);
			Assert.Equal(2, pagerContext.PageIndex);
			Assert.Equal(3, pagerContext.PageCount);
			Assert.True(response.IsValid);
			Assert.Same(list, response.Data);
		}

		[Fact]
		public async Task GetTopicsReturnsEmptyResultWithIsValidFalseAndAnemicPagerContext()
		{
			var query = "test";
			var user = new User();
			var noViewIDs = new List<int> { 1 };
			var service = GetService();
			_mockForumService.Setup(x => x.GetNonViewableForumIDs(user)).ReturnsAsync(noViewIDs);
			_mockSettingsManager.Setup(x => x.Current.TopicsPerPage).Returns(20);
			var count = 50;
			_mockSearchRepo.Setup(x => x.SearchTopics(query, noViewIDs, SearchType.Rank, 21, 20)).ReturnsAsync(Tuple.Create(new Response<List<Topic>>(new List<Topic>(), false), count));

			var (response, pagerContext) = await service.GetTopics(query, SearchType.Rank, user, false, 2);

			Assert.Empty(response.Data);
			Assert.False(response.IsValid);
			Assert.Equal(1, pagerContext.PageSize);
			Assert.Equal(1, pagerContext.PageIndex);
			Assert.Equal(1, pagerContext.PageCount);
		}
	}
}

{'repo_name': 'POPWorldMedia/POPForums', 'stars': '134', 'repo_language': 'C#', 'file_name': 'index.md', 'mime_type': 'text/plain', 'hash': 8987866194634458129, 'source_dataset': 'data'}


package bootbox

@native
interface BootboxBaseOptions {
    var title: dynamic /* String | Element */? = noImpl
    var callback: ((result: dynamic /* Boolean | String */) -> Any)? = noImpl
    var onEscape: (() -> dynamic /* Any | Boolean */)? = noImpl
    var show: Boolean? = noImpl
    var backdrop: Boolean? = noImpl
    var closeButton: Boolean? = noImpl
    var animate: Boolean? = noImpl
    var className: String? = noImpl
    var size: String? = noImpl
    var buttons: BootboxButtonMap? = noImpl
}
@native
interface BootboxDialogOptions : BootboxBaseOptions {
    var message: dynamic /* String | Element */
}
@native
interface BootboxAlertOptions : BootboxDialogOptions {
    var callback: (() -> Any)? = noImpl
    override var buttons: BootboxAlertButtonMap? = noImpl
}
@native
interface BootboxConfirmOptions : BootboxDialogOptions {
    var callback: (result: Boolean) -> Any
    override var buttons: BootboxConfirmPromptButtonMap? = noImpl
}
@native
interface BootboxPromptOptions : BootboxBaseOptions {
    var title: String
    var value: String? = noImpl
    var callback: (result: String) -> Any
    override var buttons: BootboxConfirmPromptButtonMap? = noImpl
}
@native
interface BootboxDefaultOptions {
    var locale: String? = noImpl
    var show: Boolean? = noImpl
    var backdrop: Boolean? = noImpl
    var closeButton: Boolean? = noImpl
    var animate: Boolean? = noImpl
    var className: String? = noImpl
}
@native
interface BootboxButton {
    var label: String? = noImpl
    var className: String? = noImpl
    var callback: (() -> Any)? = noImpl
}
@native
interface BootboxButtonMap {
    @nativeGetter
    fun get(key: String): dynamic /* BootboxButton | Function */
    @nativeSetter
    fun set(key: String, value: dynamic /* BootboxButton | Function */)
}
@native
interface BootboxAlertButtonMap : BootboxButtonMap {
    var ok: dynamic /* BootboxButton | Function */
}
@native
interface BootboxConfirmPromptButtonMap : BootboxButtonMap {
    var confirm: dynamic /* BootboxButton | Function */
    var cancel: dynamic /* BootboxButton | Function */
}
@native
interface BootboxLocaleValues {
    var OK: String
    var CANCEL: String
    var CONFIRM: String
}
@native
interface BootboxStatic {
    fun alert(message: String, callback: (() -> Unit)? = null): JQuery
    fun alert(options: BootboxAlertOptions): JQuery
    fun confirm(message: String, callback: (result: Boolean) -> Unit): JQuery
    fun confirm(options: BootboxConfirmOptions): JQuery
    fun prompt(message: String, callback: (result: String) -> Unit): JQuery
    fun prompt(options: BootboxPromptOptions): JQuery
    fun dialog(message: String, callback: ((result: String) -> Unit)? = null): JQuery
    fun dialog(options: BootboxDialogOptions): JQuery
    fun setDefaults(options: BootboxDefaultOptions)
    fun hideAll()
    fun addLocale(name: String, values: BootboxLocaleValues)
    fun removeLocale(name: String)
    fun setLocale(name: String)
}
@native
@module("bootbox")
var bootbox: BootboxStatic = noImpl

{'repo_name': 'Kotlin/ts2kt', 'stars': '327', 'repo_language': 'Kotlin', 'file_name': 'async.d.kt', 'mime_type': 'text/plain', 'hash': -5156154533760419509, 'source_dataset': 'data'}


//
//  TGSegmentMoreBtn.m
//  TGSegment
//
//  Created by targetcloud on 2017/4/18.
//  Copyright © 2017年 targetcloud. All rights reserved.
//

#import "TGSegmentMoreBtn.h"
@interface TGSegmentMoreBtn()
@property (nonatomic, assign) CGFloat radio;
@end

@implementation TGSegmentMoreBtn

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.imageView.contentMode = UIViewContentModeCenter;//UIViewContentModeScaleAspectFill
    }
    return self;
}

-(CGFloat)radio {
    return 0.86;
}

-(CGRect)titleRectForContentRect:(CGRect)contentRect{
    return CGRectMake(0, 1, contentRect.size.width * self.radio, contentRect.size.height);
}

-(CGRect)imageRectForContentRect:(CGRect)contentRect{
    return CGRectMake(contentRect.size.width * self.radio * self.radio, 4, contentRect.size.width * ( 1 - self.radio), contentRect.size.height -4);
}

@end

{'repo_name': 'targetcloud/baisibudejie', 'stars': '341', 'repo_language': 'Objective-C', 'file_name': 'contents.xcworkspacedata', 'mime_type': 'text/xml', 'hash': -3348406706221518880, 'source_dataset': 'data'}


/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

package org.apache.druid.server.coordination.coordination;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingCluster;
import org.apache.druid.curator.PotentiallyGzippedCompressionProvider;
import org.apache.druid.curator.announcement.Announcer;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.segment.TestHelper;
import org.apache.druid.server.coordination.BatchDataSegmentAnnouncer;
import org.apache.druid.server.coordination.ChangeRequestHistory;
import org.apache.druid.server.coordination.ChangeRequestsSnapshot;
import org.apache.druid.server.coordination.DataSegmentChangeRequest;
import org.apache.druid.server.coordination.DruidServerMetadata;
import org.apache.druid.server.coordination.ServerType;
import org.apache.druid.server.initialization.BatchDataSegmentAnnouncerConfig;
import org.apache.druid.server.initialization.ZkPathsConfig;
import org.apache.druid.timeline.DataSegment;
import org.joda.time.Interval;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 */
public class BatchDataSegmentAnnouncerTest
{
  private static final String TEST_BASE_PATH = "/test";
  private static final String TEST_SEGMENTS_PATH = "/test/segments/id";
  private static final Joiner JOINER = Joiner.on("/");
  private static final int NUM_THREADS = 4;

  private TestingCluster testingCluster;
  private CuratorFramework cf;
  private ObjectMapper jsonMapper;
  private TestAnnouncer announcer;
  private SegmentReader segmentReader;
  private BatchDataSegmentAnnouncer segmentAnnouncer;
  private Set<DataSegment> testSegments;

  private final AtomicInteger maxBytesPerNode = new AtomicInteger(512 * 1024);
  private Boolean skipDimensionsAndMetrics;
  private Boolean skipLoadSpec;

  private ExecutorService exec;

  @Before
  public void setUp() throws Exception
  {
    testingCluster = new TestingCluster(1);
    testingCluster.start();

    cf = CuratorFrameworkFactory.builder()
                                .connectString(testingCluster.getConnectString())
                                .retryPolicy(new ExponentialBackoffRetry(1, 10))
                                .compressionProvider(new PotentiallyGzippedCompressionProvider(false))
                                .build();
    cf.start();
    cf.blockUntilConnected();
    cf.create().creatingParentsIfNeeded().forPath(TEST_BASE_PATH);

    jsonMapper = TestHelper.makeJsonMapper();

    announcer = new TestAnnouncer(
        cf,
        Execs.directExecutor()
    );
    announcer.start();

    segmentReader = new SegmentReader(cf, jsonMapper);
    skipDimensionsAndMetrics = false;
    skipLoadSpec = false;
    segmentAnnouncer = new BatchDataSegmentAnnouncer(
        new DruidServerMetadata(
            "id",
            "host",
            null,
            Long.MAX_VALUE,
            ServerType.HISTORICAL,
            "tier",
            0
        ),
        new BatchDataSegmentAnnouncerConfig()
        {
          @Override
          public int getSegmentsPerNode()
          {
            return 50;
          }

          @Override
          public long getMaxBytesPerNode()
          {
            return maxBytesPerNode.get();
          }

          @Override
          public boolean isSkipDimensionsAndMetrics()
          {
            return skipDimensionsAndMetrics;
          }

          @Override
          public boolean isSkipLoadSpec()
          {
            return skipLoadSpec;
          }
        },
        new ZkPathsConfig()
        {
          @Override
          public String getBase()
          {
            return TEST_BASE_PATH;
          }
        },
        announcer,
        jsonMapper
    );

    testSegments = new HashSet<>();
    for (int i = 0; i < 100; i++) {
      testSegments.add(makeSegment(i));
    }

    exec = Execs.multiThreaded(NUM_THREADS, "BatchDataSegmentAnnouncerTest-%d");
  }

  @After
  public void tearDown() throws Exception
  {
    announcer.stop();
    cf.close();
    testingCluster.stop();
    exec.shutdownNow();
  }

  @Test
  public void testSingleAnnounce() throws Exception
  {
    Iterator<DataSegment> segIter = testSegments.iterator();
    DataSegment firstSegment = segIter.next();
    DataSegment secondSegment = segIter.next();

    segmentAnnouncer.announceSegment(firstSegment);

    List<String> zNodes = cf.getChildren().forPath(TEST_SEGMENTS_PATH);

    for (String zNode : zNodes) {
      Set<DataSegment> segments = segmentReader.read(JOINER.join(TEST_SEGMENTS_PATH, zNode));
      Assert.assertEquals(segments.iterator().next(), firstSegment);
    }

    segmentAnnouncer.announceSegment(secondSegment);

    for (String zNode : zNodes) {
      Set<DataSegment> segments = segmentReader.read(JOINER.join(TEST_SEGMENTS_PATH, zNode));
      Assert.assertEquals(Sets.newHashSet(firstSegment, secondSegment), segments);
    }

    ChangeRequestsSnapshot<DataSegmentChangeRequest> snapshot = segmentAnnouncer.getSegmentChangesSince(
        new ChangeRequestHistory.Counter(-1, -1)
    ).get();
    Assert.assertEquals(2, snapshot.getRequests().size());
    Assert.assertEquals(2, snapshot.getCounter().getCounter());

    segmentAnnouncer.unannounceSegment(firstSegment);

    for (String zNode : zNodes) {
      Set<DataSegment> segments = segmentReader.read(JOINER.join(TEST_SEGMENTS_PATH, zNode));
      Assert.assertEquals(segments.iterator().next(), secondSegment);
    }

    segmentAnnouncer.unannounceSegment(secondSegment);

    Assert.assertTrue(cf.getChildren().forPath(TEST_SEGMENTS_PATH).isEmpty());

    snapshot = segmentAnnouncer.getSegmentChangesSince(
        snapshot.getCounter()
    ).get();
    Assert.assertEquals(2, snapshot.getRequests().size());
    Assert.assertEquals(4, snapshot.getCounter().getCounter());

    snapshot = segmentAnnouncer.getSegmentChangesSince(
        new ChangeRequestHistory.Counter(-1, -1)
    ).get();
    Assert.assertEquals(0, snapshot.getRequests().size());
    Assert.assertEquals(4, snapshot.getCounter().getCounter());
  }

  @Test
  public void testSkipDimensions() throws Exception
  {
    skipDimensionsAndMetrics = true;
    Iterator<DataSegment> segIter = testSegments.iterator();
    DataSegment firstSegment = segIter.next();

    segmentAnnouncer.announceSegment(firstSegment);

    List<String> zNodes = cf.getChildren().forPath(TEST_SEGMENTS_PATH);

    for (String zNode : zNodes) {
      DataSegment announcedSegment = Iterables.getOnlyElement(segmentReader.read(JOINER.join(TEST_SEGMENTS_PATH, zNode)));
      Assert.assertEquals(announcedSegment, firstSegment);
      Assert.assertTrue(announcedSegment.getDimensions().isEmpty());
      Assert.assertTrue(announcedSegment.getMetrics().isEmpty());
    }

    segmentAnnouncer.unannounceSegment(firstSegment);

    Assert.assertTrue(cf.getChildren().forPath(TEST_SEGMENTS_PATH).isEmpty());
  }

  @Test
  public void testSkipLoadSpec() throws Exception
  {
    skipLoadSpec = true;
    Iterator<DataSegment> segIter = testSegments.iterator();
    DataSegment firstSegment = segIter.next();

    segmentAnnouncer.announceSegment(firstSegment);

    List<String> zNodes = cf.getChildren().forPath(TEST_SEGMENTS_PATH);

    for (String zNode : zNodes) {
      DataSegment announcedSegment = Iterables.getOnlyElement(segmentReader.read(JOINER.join(TEST_SEGMENTS_PATH, zNode)));
      Assert.assertEquals(announcedSegment, firstSegment);
      Assert.assertNull(announcedSegment.getLoadSpec());
    }

    segmentAnnouncer.unannounceSegment(firstSegment);

    Assert.assertTrue(cf.getChildren().forPath(TEST_SEGMENTS_PATH).isEmpty());
  }

  @Test
  public void testSingleAnnounceManyTimes() throws Exception
  {
    int prevMax = maxBytesPerNode.get();
    maxBytesPerNode.set(2048);
    // each segment is about 348 bytes long and that makes 2048 / 348 = 5 segments included per node
    // so 100 segments makes 100 / 5 = 20 nodes
    try {
      for (DataSegment segment : testSegments) {
        segmentAnnouncer.announceSegment(segment);
      }
    }
    finally {
      maxBytesPerNode.set(prevMax);
    }

    List<String> zNodes = cf.getChildren().forPath(TEST_SEGMENTS_PATH);
    Assert.assertEquals(20, zNodes.size());

    Set<DataSegment> segments = Sets.newHashSet(testSegments);
    for (String zNode : zNodes) {
      for (DataSegment segment : segmentReader.read(JOINER.join(TEST_SEGMENTS_PATH, zNode))) {
        Assert.assertTrue("Invalid segment " + segment, segments.remove(segment));
      }
    }
    Assert.assertTrue("Failed to find segments " + segments, segments.isEmpty());
  }

  @Test
  public void testBatchAnnounce() throws Exception
  {
    testBatchAnnounce(true);
  }

  @Test
  public void testMultipleBatchAnnounce() throws Exception
  {
    for (int i = 0; i < 10; i++) {
      testBatchAnnounce(false);
    }
  }

  private void testBatchAnnounce(boolean testHistory) throws Exception
  {
    segmentAnnouncer.announceSegments(testSegments);

    List<String> zNodes = cf.getChildren().forPath(TEST_SEGMENTS_PATH);

    Assert.assertEquals(2, zNodes.size());

    Set<DataSegment> allSegments = new HashSet<>();
    for (String zNode : zNodes) {
      allSegments.addAll(segmentReader.read(JOINER.join(TEST_SEGMENTS_PATH, zNode)));
    }
    Assert.assertEquals(allSegments, testSegments);

    ChangeRequestsSnapshot<DataSegmentChangeRequest> snapshot = null;

    if (testHistory) {
      snapshot = segmentAnnouncer.getSegmentChangesSince(
          new ChangeRequestHistory.Counter(-1, -1)
      ).get();
      Assert.assertEquals(testSegments.size(), snapshot.getRequests().size());
      Assert.assertEquals(testSegments.size(), snapshot.getCounter().getCounter());
    }

    segmentAnnouncer.unannounceSegments(testSegments);

    Assert.assertTrue(cf.getChildren().forPath(TEST_SEGMENTS_PATH).isEmpty());

    if (testHistory) {
      snapshot = segmentAnnouncer.getSegmentChangesSince(
          snapshot.getCounter()
      ).get();
      Assert.assertEquals(testSegments.size(), snapshot.getRequests().size());
      Assert.assertEquals(2 * testSegments.size(), snapshot.getCounter().getCounter());

      snapshot = segmentAnnouncer.getSegmentChangesSince(
          new ChangeRequestHistory.Counter(-1, -1)
      ).get();
      Assert.assertEquals(0, snapshot.getRequests().size());
      Assert.assertEquals(2 * testSegments.size(), snapshot.getCounter().getCounter());
    }
  }

  @Test(timeout = 5000L)
  public void testAnnounceSegmentsWithSameSegmentConcurrently() throws ExecutionException, InterruptedException
  {
    final List<Future> futures = new ArrayList<>(NUM_THREADS);

    for (int i = 0; i < NUM_THREADS; i++) {
      futures.add(
          exec.submit(() -> {
            try {
              segmentAnnouncer.announceSegments(testSegments);
            }
            catch (IOException e) {
              throw new RuntimeException(e);
            }
          })
      );
    }

    for (Future future : futures) {
      future.get();
    }

    // Announcing 100 segments requires 2 nodes because of maxBytesPerNode configuration.
    Assert.assertEquals(2, announcer.numPathAnnounced.size());
    for (ConcurrentHashMap<byte[], AtomicInteger> eachMap : announcer.numPathAnnounced.values()) {
      for (Entry<byte[], AtomicInteger> entry : eachMap.entrySet()) {
        Assert.assertEquals(1, entry.getValue().get());
      }
    }
  }

  @Test(timeout = 5000L)
  public void testAnnounceSegmentWithSameSegmentConcurrently() throws ExecutionException, InterruptedException
  {
    final List<Future> futures = new ArrayList<>(NUM_THREADS);

    final DataSegment segment1 = makeSegment(0);
    final DataSegment segment2 = makeSegment(1);
    final DataSegment segment3 = makeSegment(2);
    final DataSegment segment4 = makeSegment(3);

    for (int i = 0; i < NUM_THREADS; i++) {
      futures.add(
          exec.submit(() -> {
            try {
              segmentAnnouncer.announceSegment(segment1);
              segmentAnnouncer.announceSegment(segment2);
              segmentAnnouncer.announceSegment(segment3);
              segmentAnnouncer.announceSegment(segment4);
            }
            catch (IOException e) {
              throw new RuntimeException(e);
            }
          })
      );
    }

    for (Future future : futures) {
      future.get();
    }

    Assert.assertEquals(1, announcer.numPathAnnounced.size());
    for (ConcurrentHashMap<byte[], AtomicInteger> eachMap : announcer.numPathAnnounced.values()) {
      for (Entry<byte[], AtomicInteger> entry : eachMap.entrySet()) {
        Assert.assertEquals(1, entry.getValue().get());
      }
    }
  }

  private DataSegment makeSegment(int offset)
  {
    return DataSegment.builder()
                      .dataSource("foo")
                      .interval(
                          new Interval(
                              DateTimes.of("2013-01-01").plusDays(offset),
                              DateTimes.of("2013-01-02").plusDays(offset)
                          )
                      )
                      .version(DateTimes.nowUtc().toString())
                      .dimensions(ImmutableList.of("dim1", "dim2"))
                      .metrics(ImmutableList.of("met1", "met2"))
                      .loadSpec(ImmutableMap.of("type", "local"))
                      .size(0)
                      .build();
  }

  private static class SegmentReader
  {
    private final CuratorFramework cf;
    private final ObjectMapper jsonMapper;

    public SegmentReader(CuratorFramework cf, ObjectMapper jsonMapper)
    {
      this.cf = cf;
      this.jsonMapper = jsonMapper;
    }

    public Set<DataSegment> read(String path)
    {
      try {
        if (cf.checkExists().forPath(path) != null) {
          return jsonMapper.readValue(
              cf.getData().forPath(path), new TypeReference<Set<DataSegment>>()
              {
              }
          );
        }
      }
      catch (Exception e) {
        throw new RuntimeException(e);
      }

      return new HashSet<>();
    }
  }

  private static class TestAnnouncer extends Announcer
  {
    private final ConcurrentHashMap<String, ConcurrentHashMap<byte[], AtomicInteger>> numPathAnnounced = new ConcurrentHashMap<>();

    private TestAnnouncer(CuratorFramework curator, ExecutorService exec)
    {
      super(curator, exec);
    }

    @Override
    public void announce(String path, byte[] bytes, boolean removeParentIfCreated)
    {
      numPathAnnounced.computeIfAbsent(path, k -> new ConcurrentHashMap<>()).computeIfAbsent(bytes, k -> new AtomicInteger(0)).incrementAndGet();
      super.announce(path, bytes, removeParentIfCreated);
    }
  }
}

{'repo_name': 'apache/druid', 'stars': '9852', 'repo_language': 'Java', 'file_name': 'HistoricalMetricsMonitorTest.java', 'mime_type': 'text/x-java', 'hash': 2141917626578007879, 'source_dataset': 'data'}