text:
__attribute__((unused)) static void OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_initWithNSString_withInt_(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *self, NSString *__name, jint __ordinal);

J2OBJC_INITIALIZED_DEFN(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat)

NSString *OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_MODE_KEY;

@implementation OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat

+ (NSString *)MODE_KEY {
  return OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_MODE_KEY;
}

J2OBJC_IGNORE_DESIGNATED_BEGIN
- (instancetype)init {
  OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_init(self);
  return self;
}
J2OBJC_IGNORE_DESIGNATED_END

- (instancetype)initWithOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode:(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *)mode {
  OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_initWithOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_(self, mode);
  return self;
}

- (OrgApacheLuceneCodecsStoredFieldsReader *)fieldsReaderWithOrgApacheLuceneStoreDirectory:(OrgApacheLuceneStoreDirectory *)directory
                                                       withOrgApacheLuceneIndexSegmentInfo:(OrgApacheLuceneIndexSegmentInfo *)si
                                                        withOrgApacheLuceneIndexFieldInfos:(OrgApacheLuceneIndexFieldInfos *)fn
                                                         withOrgApacheLuceneStoreIOContext:(OrgApacheLuceneStoreIOContext *)context {
  NSString *value = JreRetainedLocalValue([((OrgApacheLuceneIndexSegmentInfo *) nil_chk(si)) getAttributeWithNSString:OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_MODE_KEY]);
  if (value == nil) {
    @throw create_JavaLangIllegalStateException_initWithNSString_(JreStrcat("$$$$", @"missing value for ", OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_MODE_KEY, @" for segment: ", si->name_));
  }
  OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *mode = OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_valueOfWithNSString_(value);
  return [((OrgApacheLuceneCodecsStoredFieldsFormat *) nil_chk([self implWithOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode:mode])) fieldsReaderWithOrgApacheLuceneStoreDirectory:directory withOrgApacheLuceneIndexSegmentInfo:si withOrgApacheLuceneIndexFieldInfos:fn withOrgApacheLuceneStoreIOContext:context];
}

- (OrgApacheLuceneCodecsStoredFieldsWriter *)fieldsWriterWithOrgApacheLuceneStoreDirectory:(OrgApacheLuceneStoreDirectory *)directory
                                                       withOrgApacheLuceneIndexSegmentInfo:(OrgApacheLuceneIndexSegmentInfo *)si
                                                         withOrgApacheLuceneStoreIOContext:(OrgApacheLuceneStoreIOContext *)context {
  NSString *previous = JreRetainedLocalValue([((OrgApacheLuceneIndexSegmentInfo *) nil_chk(si)) putAttributeWithNSString:OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_MODE_KEY withNSString:[((OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *) nil_chk(mode_)) name]]);
  if (previous != nil) {
    @throw create_JavaLangIllegalStateException_initWithNSString_(JreStrcat("$$$$$$$$", @"found existing value for ", OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_MODE_KEY, @" for segment: ", si->name_, @"old=", previous, @", new=", [mode_ name]));
  }
  return [((OrgApacheLuceneCodecsStoredFieldsFormat *) nil_chk([self implWithOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode:mode_])) fieldsWriterWithOrgApacheLuceneStoreDirectory:directory withOrgApacheLuceneIndexSegmentInfo:si withOrgApacheLuceneStoreIOContext:context];
}

- (OrgApacheLuceneCodecsStoredFieldsFormat *)implWithOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode:(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *)mode {
  switch ([mode ordinal]) {
    case OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_Enum_BEST_SPEED:
    return create_OrgApacheLuceneCodecsCompressingCompressingStoredFieldsFormat_initWithNSString_withOrgApacheLuceneCodecsCompressingCompressionMode_withInt_withInt_withInt_(@"Lucene50StoredFieldsFast", JreLoadStatic(OrgApacheLuceneCodecsCompressingCompressionMode, FAST), JreLShift32(1, 14), 128, 1024);
    case OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_Enum_BEST_COMPRESSION:
    return create_OrgApacheLuceneCodecsCompressingCompressingStoredFieldsFormat_initWithNSString_withOrgApacheLuceneCodecsCompressingCompressionMode_withInt_withInt_withInt_(@"Lucene50StoredFieldsHigh", JreLoadStatic(OrgApacheLuceneCodecsCompressingCompressionMode, HIGH_COMPRESSION), 61440, 512, 1024);
    default:
    @throw create_JavaLangAssertionError_init();
  }
}

- (void)dealloc {
  RELEASE_(mode_);
  [super dealloc];
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x1, -1, -1, -1, -1, -1, -1 },
    { NULL, NULL, 0x1, -1, 0, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneCodecsStoredFieldsReader;", 0x1, 1, 2, 3, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneCodecsStoredFieldsWriter;", 0x1, 4, 5, 3, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneCodecsStoredFieldsFormat;", 0x0, 6, 0, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(init);
  methods[1].selector = @selector(initWithOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode:);
  methods[2].selector = @selector(fieldsReaderWithOrgApacheLuceneStoreDirectory:withOrgApacheLuceneIndexSegmentInfo:withOrgApacheLuceneIndexFieldInfos:withOrgApacheLuceneStoreIOContext:);
  methods[3].selector = @selector(fieldsWriterWithOrgApacheLuceneStoreDirectory:withOrgApacheLuceneIndexSegmentInfo:withOrgApacheLuceneStoreIOContext:);
  methods[4].selector = @selector(implWithOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode:);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "MODE_KEY", "LNSString;", .constantValue.asLong = 0, 0x19, -1, 7, -1, -1 },
    { "mode_", "LOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode;", .constantValue.asLong = 0, 0x10, -1, -1, -1, -1 },
  };
  static const void *ptrTable[] = { "LOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode;", "fieldsReader", "LOrgApacheLuceneStoreDirectory;LOrgApacheLuceneIndexSegmentInfo;LOrgApacheLuceneIndexFieldInfos;LOrgApacheLuceneStoreIOContext;", "LJavaIoIOException;", "fieldsWriter", "LOrgApacheLuceneStoreDirectory;LOrgApacheLuceneIndexSegmentInfo;LOrgApacheLuceneStoreIOContext;", "impl", &OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_MODE_KEY };
  static const J2ObjcClassInfo _OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat = { "Lucene50StoredFieldsFormat", "org.apache.lucene.codecs.lucene50", ptrTable, methods, fields, 7, 0x11, 5, 2, -1, 0, -1, -1, -1 };
  return &_OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat;
}

+ (void)initialize {
  if (self == [OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat class]) {
    JreStrongAssign(&OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_MODE_KEY, JreStrcat("$$", [OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_class_() getSimpleName], @".mode"));
    J2OBJC_SET_INITIALIZED(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat)
  }
}

@end

void OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_init(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat *self) {
  OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_initWithOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_(self, JreLoadEnum(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode, BEST_SPEED));
}

OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat *new_OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_init() {
  J2OBJC_NEW_IMPL(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat, init)
}

OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat *create_OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_init() {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat, init)
}

void OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_initWithOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat *self, OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *mode) {
  OrgApacheLuceneCodecsStoredFieldsFormat_init(self);
  JreStrongAssign(&self->mode_, OrgLukhnosPortmobileUtilObjects_requireNonNullWithId_(mode));
}

OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat *new_OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_initWithOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *mode) {
  J2OBJC_NEW_IMPL(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat, initWithOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_, mode)
}

OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat *create_OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_initWithOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *mode) {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat, initWithOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_, mode)
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat)

J2OBJC_INITIALIZED_DEFN(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode)

OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_values_[2];

@implementation OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode

+ (OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *)BEST_SPEED {
  return JreEnum(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode, BEST_SPEED);
}

+ (OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *)BEST_COMPRESSION {
  return JreEnum(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode, BEST_COMPRESSION);
}

+ (IOSObjectArray *)values {
  return OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_values();
}

+ (OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *)valueOfWithNSString:(NSString *)name {
  return OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_valueOfWithNSString_(name);
}

- (OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_Enum)toNSEnum {
  return (OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_Enum)[self ordinal];
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, "[LOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode;", 0x9, -1, -1, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode;", 0x9, 0, 1, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(values);
  methods[1].selector = @selector(valueOfWithNSString:);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "BEST_SPEED", "LOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode;", .constantValue.asLong = 0, 0x4019, -1, 2, -1, -1 },
    { "BEST_COMPRESSION", "LOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode;", .constantValue.asLong = 0, 0x4019, -1, 3, -1, -1 },
  };
  static const void *ptrTable[] = { "valueOf", "LNSString;", &JreEnum(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode, BEST_SPEED), &JreEnum(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode, BEST_COMPRESSION), "LOrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat;", "Ljava/lang/Enum<Lorg/apache/lucene/codecs/lucene50/Lucene50StoredFieldsFormat$Mode;>;" };
  static const J2ObjcClassInfo _OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode = { "Mode", "org.apache.lucene.codecs.lucene50", ptrTable, methods, fields, 7, 0x4019, 2, 2, 4, -1, -1, 5, -1 };
  return &_OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode;
}

+ (void)initialize {
  if (self == [OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode class]) {
    size_t objSize = class_getInstanceSize(self);
    size_t allocSize = 2 * objSize;
    uintptr_t ptr = (uintptr_t)calloc(allocSize, 1);
    id e;
    for (jint i = 0; i < 2; i++) {
      ((void)(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_values_[i] = e = objc_constructInstance(self, (void *)ptr)), ptr += objSize);
      OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_initWithNSString_withInt_(e, JreEnumConstantName(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_class_(), i), i);
    }
    J2OBJC_SET_INITIALIZED(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode)
  }
}

@end

void OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_initWithNSString_withInt_(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *self, NSString *__name, jint __ordinal) {
  JavaLangEnum_initWithNSString_withInt_(self, __name, __ordinal);
}

IOSObjectArray *OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_values() {
  OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_initialize();
  return [IOSObjectArray arrayWithObjects:OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_values_ count:2 type:OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_class_()];
}

OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_valueOfWithNSString_(NSString *name) {
  OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_initialize();
  for (int i = 0; i < 2; i++) {
    OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *e = OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_values_[i];
    if ([name isEqual:[e name]]) {
      return e;
    }
  }
  @throw create_JavaLangIllegalArgumentException_initWithNSString_(name);
  return nil;
}

OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode *OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_fromOrdinal(NSUInteger ordinal) {
  OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_initialize();
  if (ordinal >= 2) {
    return nil;
  }
  return OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode_values_[ordinal];
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneCodecsLucene50Lucene50StoredFieldsFormat_Mode)


text:
#import "WXComponentFactory.h"
#import "WXAssert.h"
#import "WXLog.h"
#import "WXCoreBridge.h"
#import "WXComponent.h"
#import <objc/runtime.h>

@interface WXComponentBaseType : NSObject

@property (nonatomic, strong) NSString* type;
@property (nonatomic, strong) Class clazz;

@end

@implementation WXComponentBaseType

@end

@implementation WXComponentConfig

- (instancetype)initWithName:(NSString *)name class:(NSString *)clazz pros:(NSDictionary *)pros
{
    if (self = [super initWithName:name class:clazz]) {
        _properties = pros;
    }

    return self;
}

- (BOOL)isValid
{
    if (self.name == nil || self.clazz == nil) {
        return NO;
    }
    return YES;
}

@end

@implementation WXComponentFactory
{
    NSMutableArray<WXComponentBaseType*> *_baseTypes;
    NSMutableDictionary *_componentConfigs;
    NSLock *_configLock;
}

#pragma mark Life Cycle

+ (instancetype)sharedInstance {
    static id _sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[self alloc] init];
    });
    return _sharedInstance;
}

- (instancetype)init
{
    if(self = [super init]){
        _baseTypes = [NSMutableArray array];
        _componentConfigs = [NSMutableDictionary dictionary];
        _configLock = [[NSLock alloc] init];
    }
    return self;
}

#pragma mark Public

+ (Class)classWithComponentName:(NSString *)name
{
    WXComponentConfig *config = [self configWithComponentName:name];
    if(!config || !config.clazz) {
        return nil;
    }

    return NSClassFromString(config.clazz);
}

+ (WXComponentConfig *)configWithComponentName:(NSString *)name
{
    return [[self sharedInstance] configWithComponentName:name];
}

+ (void)registerBaseType:(NSString *)typeName withClass:(Class)clazz
{
    [[self sharedInstance] registerBaseType:typeName withClass:clazz];
}

+ (void)registerComponent:(NSString *)name withClass:(Class)clazz withPros:(NSDictionary *)pros
{
    [[self sharedInstance] registerComponent:name withClass:clazz withPros:pros];
}

+ (void)registerComponents:(NSArray *)components
{
    [[self sharedInstance] registerComponents:components];
}

+ (void)unregisterAllComponents
{
    [[self sharedInstance] unregisterAllComponents];
}

+ (NSDictionary *)componentConfigs {
    return [[self sharedInstance] getComponentConfigs];
}

+ (SEL)methodWithComponentName:(NSString *)name withMethod:(NSString *)method
{
    return [[self sharedInstance] _methodWithComponetName:name withMethod:method];
}

+ (NSMutableDictionary *)componentMethodMapsWithName:(NSString *)name
{
    return [[self sharedInstance] _componentMethodMapsWithName:name];
}

+ (NSMutableDictionary *)componentSelectorMapsWithName:(NSString *)name
{
    return [[self sharedInstance] _componentSelectorMapsWithName:name];
}

#pragma mark Private

- (NSMutableDictionary *)_componentMethodMapsWithName:(NSString *)name
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSMutableArray *methods = [NSMutableArray array];

    [_configLock lock];
    [dict setValue:methods forKey:@"methods"];

    WXComponentConfig *config = _componentConfigs[name];
    void (^mBlock)(id, id, BOOL *) = ^(id mKey, id mObj, BOOL * mStop) {
        [methods addObject:mKey];
    };
    [config.asyncMethods enumerateKeysAndObjectsUsingBlock:mBlock];
    [_configLock unlock];

    return dict;
}

- (NSMutableDictionary *)_componentSelectorMapsWithName:(NSString *)name
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSMutableArray *methods = [NSMutableArray array];

    [_configLock lock];
    [dict setValue:methods forKey:@"methods"];

    WXComponentConfig *config = _componentConfigs[name];
    void (^mBlock)(id, id, BOOL *) = ^(id mKey, id mObj, BOOL * mStop) {
        [methods addObject:mObj];
    };
    [config.asyncMethods enumerateKeysAndObjectsUsingBlock:mBlock];
    [_configLock unlock];

    return dict;
}

- (SEL)_methodWithComponetName:(NSString *)name withMethod:(NSString *)method
{
    WXAssert(name && method, @"Fail to find selector with module name and method, please check if the parameters are correct !");

    NSString *selStr = nil; SEL selector = nil;
    WXComponentConfig *config = nil;

    [_configLock lock];
    config = [_componentConfigs objectForKey:name];
    if (config.asyncMethods) {
        selStr = [config.asyncMethods objectForKey:method];
    }
    if (selStr) {
        selector = NSSelectorFromString(selStr);
    }
    [_configLock unlock];

    return selector;
}

- (NSDictionary *)getComponentConfigs {
    NSMutableDictionary *componentDic = [[NSMutableDictionary alloc] init];
    void (^componentBlock)(id, id, BOOL *) = ^(id mKey, id mObj, BOOL * mStop) {
        WXComponentConfig *componentConfig = (WXComponentConfig *)mObj;
        if ([componentConfig isValid]) {
            NSMutableDictionary *configDic = [[NSMutableDictionary alloc] init];
            [configDic setObject:componentConfig.name forKey:@"name"];
            [configDic setObject:componentConfig.clazz forKey:@"clazz"];
            if (componentConfig.properties) {
                [configDic setObject:componentConfig.properties forKey:@"pros"];
            }
            [componentDic setObject:configDic forKey:componentConfig.name];
        }
    };
    [_componentConfigs enumerateKeysAndObjectsUsingBlock:componentBlock];
    return componentDic;
}

- (WXComponentConfig *)configWithComponentName:(NSString *)name
{
    WXAssert(name, @"Can not find config for a nil component name");

    WXComponentConfig *config = nil;

    [_configLock lock];
    config = [_componentConfigs objectForKey:name];
    if (!config) {
        WXLogWarning(@"No component config for name:%@, use default config", name);
        config = [_componentConfigs objectForKey:@"div"];
    }
    [_configLock unlock];

    return config;
}

- (void)registerBaseType:(NSString *)typeName withClass:(Class)clazz
{
    if ([typeName length] > 0 && clazz != Nil) {
        WXComponentBaseType* typePair = [[WXComponentBaseType alloc] init];
        typePair.type = typeName;
        typePair.clazz = clazz;
        [_baseTypes addObject:typePair];
    }
}

- (void)registerAffineType:(NSString *)typeName withClass:(Class)clazz
{
    // iterates super classes of clazz and check if any super class matches registerd base types
    if ([_baseTypes count] > 0 && [typeName length] > 0 && clazz != Nil) {
        Class supercls = [clazz superclass];
        while (supercls) {
            if (supercls == [WXComponent class]) {
                break;
            }

            for (WXComponentBaseType* typePair in _baseTypes) {
                if (supercls == typePair.clazz) {
                    WXLogInfo(@"Type '%@' is registerd as affine type of '%@' because '%@' is subclass of '%@'.", typeName, typePair.type, clazz, supercls);
                    [WXCoreBridge registerComponentAffineType:typeName asType:typePair.type];
                    return; // done, use the first found affine type
                }
            }
            supercls = [supercls superclass];
        }
    }
}

- (void)registerComponent:(NSString *)name withClass:(Class)clazz withPros:(NSDictionary *)pros
{
    WXAssert(name && clazz, @"name or clazz must not be nil for registering component.");

    WXComponentConfig *config = nil;
    [_configLock lock];
    config = [_componentConfigs objectForKey:name];

    if(config){
        WXLogInfo(@"Overrider component name:%@ class:%@, to name:%@ class:%@",
                  config.name, config.class, name, clazz);
    }

    config = [[WXComponentConfig alloc] initWithName:name class:NSStringFromClass(clazz) pros:pros];
    [_componentConfigs setValue:config forKey:name];
    [config registerMethods];
    [self registerAffineType:name withClass:clazz];
    [_configLock unlock];
}

- (void)registerComponents:(NSArray *)components
{
    WXAssert(components, @"components array must not be nil for registering component.");

    [_configLock lock];
    for(NSDictionary *dict in components){
        NSString *name = dict[@"name"];
        NSString *clazz = dict[@"class"];
        WXAssert(name && clazz, @"name or clazz must not be nil for registering components.");

        WXComponentConfig *config = [[WXComponentConfig alloc] initWithName:name class:clazz pros:nil];
        if(config){
            [_componentConfigs setValue:config forKey:name];
            [config registerMethods];
            [self registerAffineType:name withClass:NSClassFromString(clazz)];
        }
    }
    [_configLock unlock];
}

- (void)unregisterAllComponents
{
    [_configLock lock];
    [_componentConfigs removeAllObjects];
    [_configLock unlock];
}

@end

redpajama_set_name: RedPajamaGithub


text:
package io.datakernel.remotefs;

import io.datakernel.bytebuf.ByteBuf;
import io.datakernel.csp.ChannelConsumer;
import io.datakernel.csp.ChannelSupplier;
import io.datakernel.promise.Promise;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

import static java.util.stream.Collectors.toList;

final class TransformFsClient implements FsClient {
	private final FsClient parent;
	private final Function<String, Optional<String>> into;
	private final Function<String, Optional<String>> from;
	private final Function<String, Optional<String>> globInto;

	TransformFsClient(FsClient parent, Function<String, Optional<String>> into, Function<String, Optional<String>> from, Function<String, Optional<String>> globInto) {
		this.parent = parent;
		this.into = into;
		this.from = from;
		this.globInto = globInto;
	}

	@Override
	public Promise<ChannelConsumer<ByteBuf>> upload(@NotNull String name, long offset, long revision) {
		Optional<String> transformed = into.apply(name);
		if (!transformed.isPresent()) {
			return Promise.ofException(BAD_PATH);
		}
		return parent.upload(transformed.get(), offset, revision);
	}

	@Override
	public Promise<ChannelSupplier<ByteBuf>> download(@NotNull String name, long offset, long length) {
		Optional<String> transformed = into.apply(name);
		if (!transformed.isPresent()) {
			return Promise.ofException(FILE_NOT_FOUND);
		}
		return parent.download(transformed.get(), offset, length);
	}

	@Override
	public Promise<Void> move(@NotNull String name, @NotNull String target, long targetRevision, long tombstoneRevision) {
		return renamingOp(name, target, (from, to) -> parent.move(from, to, targetRevision, tombstoneRevision));
	}

	@Override
	public Promise<Void> moveDir(@NotNull String name, @NotNull String target, long targetRevision, long tombstoneRevision) {
		return renamingOp(name, target, (from, to) -> parent.moveDir(from, to, targetRevision, tombstoneRevision));
	}

	@Override
	public Promise<Void> copy(@NotNull String name, @NotNull String target, long targetRevision) {
		return renamingOp(name, target, (from, to) -> parent.copy(from, to, targetRevision));
	}

	private Promise<Void> renamingOp(String filename, String newFilename, BiFunction<String, String, Promise<Void>> original) {
		Optional<String> transformed = into.apply(filename);
		Optional<String> transformedNew = into.apply(newFilename);
		if (!transformed.isPresent() || !transformedNew.isPresent()) {
			return Promise.ofException(BAD_PATH);
		}
		return original.apply(transformed.get(), transformedNew.get());
	}

	@Override
	public Promise<List<FileMetadata>> listEntities(@NotNull String glob) {
		return parent.listEntities(globInto.apply(glob).orElse("**"))
				.map(transformList(glob));
	}

	@Override
	public Promise<List<FileMetadata>> list(@NotNull String glob) {
		return parent.list(globInto.apply(glob).orElse("**"))
				.map(transformList(glob));
	}

	private Function<List<FileMetadata>, List<FileMetadata>> transformList(String glob) {
		Predicate<String> pred = RemoteFsUtils.getGlobStringPredicate(glob);
		return list -> list.stream()
				.map(meta ->
						from.apply(meta.getName())
								.map(name -> FileMetadata.of(name, meta.getSize(), meta.getTimestamp(), meta.getRevision())))
				.filter(meta -> meta.isPresent() && pred.test(meta.get().getName()))
				.map(Optional::get)
				.collect(toList());
	}

	@Override
	public Promise<FileMetadata> getMetadata(@NotNull String name) {
		Optional<String> transformed = into.apply(name);
		return transformed.map(s ->
				parent.getMetadata(s)
						.map(meta -> {
							if (meta == null) {
								return null;
							}
							return from.apply(meta.getName())
									.map(meta::withName)
									.orElse(null);
						})).orElse(Promise.of(null));
	}

	@Override
	public Promise<Void> ping() {
		return parent.ping();
	}

	@Override
	public Promise<Void> delete(@NotNull String name, long revision) {
		Optional<String> transformed = into.apply(name);
		if (!transformed.isPresent()) {
			return Promise.complete();
		}
		return parent.delete(transformed.get(), revision);
	}

	@Override
	public FsClient transform(@NotNull Function<String, Optional<String>> into, @NotNull Function<String, Optional<String>> from, @NotNull Function<String, Optional<String>> globInto) {
		if (into == this.from && from == this.into) { // huh
			return parent;
		}
		return new TransformFsClient(parent,
				name -> into.apply(name).flatMap(this.into),
				name -> this.from.apply(name).flatMap(from),
				name -> globInto.apply(name).flatMap(this.globInto)
		);
	}
}


text:
module Foo #:nodoc:
  module Acts #:nodoc:
    module Indexed #:nodoc:
      class SearchIndex

        # root:: Location of index on filesystem.
        # index_depth:: Degree of index partitioning.
        # fields:: Fields or instance methods of ActiveRecord model to be indexed.
        # min_word_size:: Smallest query term that will be run through search.
        def initialize(root, index_depth, fields, min_word_size)
          @root = root
          @fields = fields
          @index_depth = index_depth
          @atoms = {}
          @min_word_size = min_word_size
          @records_size = exists? ? load_record_size : 0
        end

        # Adds +record+ to the index.
        def add_record(record)
          condensed_record = condense_record(record)
          load_atoms(condensed_record)
          add_occurences(condensed_record,record.id)
          @records_size += 1
        end

        # Adds multiple records to the index. Accepts an array of +records+.
        def add_records(records)
          records.each do |r|
            condensed_record = condense_record(r)
            load_atoms(condensed_record)
            add_occurences(condensed_record,r.id)
            @records_size += 1
          end
        end

        # Removes +record+ from the index.
        def remove_record(record)
          atoms = condense_record(record)
          load_atoms(atoms)
          atoms.each do |a|
            @atoms[a].remove_record(record.id) if @atoms.has_key?(a)
            @records_size -= 1
            #p "removing #{record.id} from #{a}"
          end
        end

        def update_record(record_new, record_old)
          # Work out which atoms have modifications.
          # Minimises loading and saving of partitions.
          old_atoms = condense_record(record_old)
          new_atoms = condense_record(record_new)

          # Remove the old version from the appropriate atoms.
          load_atoms(old_atoms)
          old_atoms.each do |a|
            @atoms[a].remove_record(record_new.id) if @atoms.has_key?(a)
          end

          # Add the new version to the appropriate atoms.
          load_atoms(new_atoms)
          # TODO: Make a version of this method that takes the
          # atomised version of the record.
          add_occurences(new_atoms, record_new.id)
        end

        # Saves the current index partitions to the filesystem.
        def save
          prepare
          atoms_sorted = {}
          @atoms.each do |atom_name, records|
            e_p = encoded_prefix(atom_name)
            atoms_sorted[e_p] = {} if !atoms_sorted.has_key?(e_p)
            atoms_sorted[e_p][atom_name] = records
          end
          atoms_sorted.each do |e_p, atoms|
            #p "Saving #{e_p}."
            File.open(File.join(@root + [e_p.to_s]),'w+') do |f|
              Marshal.dump(atoms,f)
            end
          end
          save_record_size
        end

        # Deletes the current model's index from the filesystem.
        #--
        # TODO: Write a public method that will delete all indexes.
        def destroy
          FileUtils.rm_rf(@root)
          true
        end

        # Returns an array of IDs for records matching +query+.
        def search(query)
          load_atoms(cleanup_atoms(query))
          return [] if query.nil?
          queries = parse_query(query.dup)
          positive = run_queries(queries[:positive])
          positive_quoted = run_quoted_queries(queries[:positive_quoted])
          negative = run_queries(queries[:negative])
          negative_quoted = run_quoted_queries(queries[:negative_quoted])

          if !queries[:positive].empty? && !queries[:positive_quoted].empty?
            p = positive.delete_if{ |r_id,w| !positive_quoted.include?(r_id) }
            pq = positive_quoted.delete_if{ |r_id,w| !positive.include?(r_id) }
            results = p.merge(pq) { |r_id,old_val,new_val| old_val + new_val}
          elsif !queries[:positive].empty?
            results = positive
          else
            results = positive_quoted
          end

          negative_results = (negative.keys + negative_quoted.keys)
          results.delete_if { |r_id, w| negative_results.include?(r_id) }
          #p results
          results
        end

        # Returns true if the index root exists on the FS.
        #--
        # TODO: Make a private method called 'root_exists?' which checks for the root directory.
        def exists?
          File.exists?(File.join(@root))
        end

        private

        # Gets the size file from the index.
        def load_record_size
          File.open(File.join(@root + ['size'])) do |f|
            return (Marshal.load(f))
          end
        end

        # Saves the size to the size file.
        def save_record_size
          File.open(File.join(@root + ['size']),'w+') do |f|
            Marshal.dump(@records_size,f)
          end
        end

        # Returns true if the given atom is present.
        def include_atom?(atom)
          @atoms.has_key?(atom)
        end

        # Returns true if all the given atoms are present.
        def include_atoms?(atoms_arr)
          atoms_arr.each do |a|
            return false if !include_atom?(a)
          end
          true
        end

        # Returns true if the given record is present.
        def include_record?(record_id)
          @atoms.each do |atomname, atom|
            return true if atom.include_record?(record_id)
          end
        end

        def add_atom(atom)
          @atoms[atom] = SearchAtom.new if !include_atom?(atom)
        end

        def add_occurences(condensed_record,record_id)
          condensed_record.each_with_index do |atom, i|
            add_atom(atom)
            @atoms[atom].add_position(record_id, i)
            #p "adding #{record.id} to #{atom}"
          end
        end

        def encoded_prefix(atom)
          prefix = atom[0,@index_depth]
          if !@prefix_cache || !@prefix_cache.has_key?(prefix)
            @prefix_cache = {} if !@prefix_cache
            len = atom.length
            if len > 1
              @prefix_cache[prefix] = prefix.split(//).map{|c| encode_character(c)}.join('_')
            else
              @prefix_cache[prefix] = encode_character(atom)
            end
          end
          @prefix_cache[prefix]
        end

        # Allows compatibility with 1.8.6 which has no ord method.
        def encode_character(char)
          if @@has_ord ||= char.respond_to?(:ord)
            char.ord.to_s
          else
            char[0]
          end
        end

        def parse_query(s)

          # Find -"foo bar".
          negative_quoted = []
          while neg_quoted = s.slice!(/-\"[^\"]*\"/)
            negative_quoted << cleanup_atoms(neg_quoted)
          end

          # Find "foo bar".
          positive_quoted = []
          while pos_quoted = s.slice!(/\"[^\"]*\"/)
            positive_quoted << cleanup_atoms(pos_quoted)
          end

          # Find -foo.
          negative = []
          while neg = s.slice!(/-[\S]*/)
            negative << cleanup_atoms(neg).first
          end

          # Find +foo
          positive = []
          while pos = s.slice!(/\+[\S]*/)
            positive << cleanup_atoms(pos).first
          end

          # Find all other terms.
          positive += cleanup_atoms(s,true)

          return {:negative_quoted => negative_quoted, :positive_quoted => positive_quoted, :negative => negative, :positive => positive}
        end

        def run_queries(atoms)
          results = {}
          atoms.uniq.each do |atom|
            interim_results = {}
            if include_atom?(atom)

              interim_results = @atoms[atom].weightings(@records_size)
            end
            if results.empty?
              results = interim_results
            else
              rr = {}
              interim_results.each do |r,w|
                rr[r] = w + results[r] if results[r]
              end
              results = rr
            end
          end
          #p results
          results
        end

        def run_quoted_queries(quoted_atoms)
          results = {}
          quoted_atoms.each do |quoted_atom|
            interim_results = {}
            # Check the index contains all the required atoms.
            # match_atom = first_word_atom
            # for each of the others
            #   return atom containing records + positions where current atom is preceded by following atom.
            # end
            # return records from final atom.
            next if !include_atoms?(quoted_atom)
            matches = @atoms[quoted_atom.first]
            quoted_atom[1..-1].each do |atom_name|
              matches = @atoms[atom_name].preceded_by(matches)
            end
            #results += matches.record_ids

            interim_results = matches.weightings(@records_size)
            if results.empty?
              results = interim_results
            else
              rr = {}
              interim_results.each do |r,w|
                rr[r] = w + results[r] if results[r]
              end
              #p results.class
              results = rr
            end

          end
          return results
        end

        def load_atoms(atoms)
          # Remove duplicates
          # Remove atoms already in index.
          # Calculate prefixes.
          # Remove duplicates
          atoms.uniq.reject{|a| include_atom?(a)}.collect{|a| encoded_prefix(a)}.uniq.each do |name|
            if File.exists?(File.join(@root + [name.to_s]))
              File.open(File.join(@root + [name.to_s])) do |f|
                @atoms.merge!(Marshal.load(f))
              end
            end
          end
        end

        def prepare
          # Makes the RAILS_ROOT/index directory
          Dir.mkdir(File.join(@root[0,2])) if !File.exists?(File.join(@root[0,2]))
          # Makes the RAILS_ROOT/index/ENVIRONMENT directory
          Dir.mkdir(File.join(@root[0,3])) if !File.exists?(File.join(@root[0,3]))
          # Makes the RAILS_ROOT/index/ENVIRONMENT/CLASS directory
          Dir.mkdir(File.join(@root)) if !File.exists?(File.join(@root))
        end

        def cleanup_atoms(s, limit_size=false, min_size = @min_word_size || 3)
          atoms = s.downcase.gsub(/\W/,' ').squeeze(' ').split
          return atoms if !limit_size
          atoms.reject{|w| w.size < min_size}
        end

        def condense_record(record)
          record_condensed = ''
          @fields.each do |f|
            record_condensed += ' ' + record.send(f).to_s if record.send(f)
          end
          cleanup_atoms(record_condensed)
        end

      end
    end
  end
end


text:
import java.util.RandomAccess;

public interface ArrayList<E> extends SimpleList<E>, RandomAccess {

	/**
	 * Sets the element at index i in this list to {@code element}, and returns old element
	 * @param i the index of the element to change
	 * @param element the new object to replace
	 * @return the previous element at index i
	 * @throws IndexOutOfBoundsException if the index is not in range
	 */
	public E set(int i, E element);

	/**
	 * Adds {@code element} to this list at the specified index.
	 * All elements with index greater than {@code i} are shifted right by one place.
	 * @param i the index of where to add the new element
	 * @param element the object to add to the list
	 * @throws IndexOutOfBoundsException if the index is not in range
	 */
	public void add(int i, E element);

	/**
	 * Adds {@code element} to the end of this list
	 * @param element the new object to add to the list
	 */
	public void add(E element);

	/**
	 * Removes and returns the element at index i in this list.
	 * All later elements are shifted up by one place in the list.
	 * @param i the index of the element to remove
	 * @return the element at index i, if it exists
	 * @throws IndexOutOfBoundsException if the index is not in range
	 */
	public E remove(int i);

}


text:
package org.knowm.xchange.anx.v2.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.knowm.xchange.BaseExchange;
import org.knowm.xchange.anx.ANXUtils;
import org.knowm.xchange.anx.v2.ANXAdapters;
import org.knowm.xchange.anx.v2.dto.account.ANXWalletHistoryEntry;
import org.knowm.xchange.anx.v2.dto.account.ANXWithdrawalResponse;
import org.knowm.xchange.anx.v2.dto.account.ANXWithdrawalResponseWrapper;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.dto.account.AccountInfo;
import org.knowm.xchange.dto.account.FundingRecord;
import org.knowm.xchange.exceptions.NotAvailableFromExchangeException;
import org.knowm.xchange.service.account.AccountService;
import org.knowm.xchange.service.trade.params.DefaultWithdrawFundsParams;
import org.knowm.xchange.service.trade.params.RippleWithdrawFundsParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrency;
import org.knowm.xchange.service.trade.params.TradeHistoryParamPaging;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan;
import org.knowm.xchange.service.trade.params.WithdrawFundsParams;

/**
 *

 * XChange service to provide the following to {@link org.knowm.xchange.Exchange}:
 *

 *

 *
ANX specific methods to handle account-related operations

 *

 */
public class ANXAccountService extends ANXAccountServiceRaw implements AccountService {

  /**
   * Constructor
   */
  public ANXAccountService(BaseExchange baseExchange) {

    super(baseExchange);
  }

  @Override
  public AccountInfo getAccountInfo() throws IOException {

    return ANXAdapters.adaptAccountInfo(getANXAccountInfo());
  }

  @Override
  public String withdrawFunds(Currency currency, BigDecimal amount, String address) throws IOException {

    if (amount.scale() > ANXUtils.VOLUME_AND_AMOUNT_MAX_SCALE) {
      throw new IllegalArgumentException("Amount scale exceed " + ANXUtils.VOLUME_AND_AMOUNT_MAX_SCALE);
    }

    if (address == null) {
      throw new IllegalArgumentException("Address cannot be null");
    }

    ANXWithdrawalResponseWrapper wrapper = anxWithdrawFunds(currency.toString(), amount, address);
    return handleWithdrawalResponse(wrapper);
  }

  public String withdrawFunds(Currency currency, BigDecimal amount, String address, String tag) throws IOException {

    if (amount.scale() > ANXUtils.VOLUME_AND_AMOUNT_MAX_SCALE) {
      throw new IllegalArgumentException("Amount scale exceed " + ANXUtils.VOLUME_AND_AMOUNT_MAX_SCALE);
    }

    if (address == null) {
      throw new IllegalArgumentException("Address cannot be null");
    }

    if (tag == null) {
      throw new IllegalArgumentException("destinationTag cannot be null");
    }

    ANXWithdrawalResponseWrapper wrapper = anxWithdrawFunds(currency.toString(), amount, address, tag);
    return handleWithdrawalResponse(wrapper);
  }

  private String handleWithdrawalResponse(ANXWithdrawalResponseWrapper wrapper) {
    ANXWithdrawalResponse response = wrapper.getAnxWithdrawalResponse();

    //eg: {  "result": "error",  "data": {    "message": "min size, params, or available funds problem."  }}
    if (wrapper.getResult().equals("error")) {
      throw new IllegalStateException("Failed to withdraw funds: " + response.getMessage());
    } else if (wrapper.getError() != null) {//does this ever happen?
      throw new IllegalStateException("Failed to withdraw funds: " + wrapper.getError());
    } else {
      return response.getTransactionId();
    }
  }

  @Override
  public String withdrawFunds(WithdrawFundsParams params) throws IOException {

    if (params instanceof RippleWithdrawFundsParams) {
      RippleWithdrawFundsParams rippleWithdrawFundsParams = (RippleWithdrawFundsParams) params;
      return withdrawFunds(rippleWithdrawFundsParams.currency, rippleWithdrawFundsParams.amount, rippleWithdrawFundsParams.address,
          rippleWithdrawFundsParams.tag);
    }
    if (params instanceof DefaultWithdrawFundsParams) {
      DefaultWithdrawFundsParams defaultParams = (DefaultWithdrawFundsParams) params;
      return withdrawFunds(defaultParams.currency, defaultParams.amount, defaultParams.address);
    }
    throw new IllegalStateException("Don't know how to withdraw: " + params);
  }

  @Override
  public String requestDepositAddress(Currency currency, String... args) throws IOException {

    return anxRequestDepositAddress(currency.toString()).getAddress();
  }

  @Override
  public TradeHistoryParams createFundingHistoryParams() {
    throw new NotAvailableFromExchangeException();
  }

  @Override
  public List<FundingRecord> getFundingHistory(TradeHistoryParams params) throws IOException {

    List<FundingRecord> results = new ArrayList<>();

    List<ANXWalletHistoryEntry> walletHistory = getWalletHistory(params);
    for (ANXWalletHistoryEntry entry : walletHistory) {

      if (!entry.getType().equalsIgnoreCase("deposit") && !entry.getType().equalsIgnoreCase("withdraw"))
        continue;

      results.add(ANXAdapters.adaptFundingRecord(entry));
    }
    return results;
  }

  public static class AnxFundingHistoryParams implements TradeHistoryParamCurrency, TradeHistoryParamPaging, TradeHistoryParamsTimeSpan {

    private Currency currency;
    private Integer pageNumber;
    private Integer pageLength;//not supported
    private Date startTime;
    private Date endTime;

    public AnxFundingHistoryParams() {
    }

    public AnxFundingHistoryParams(Currency currency, Date startTime, Date endTime) {
      this.currency = currency;
      this.startTime = startTime;
      this.endTime = endTime;
    }

    @Override
    public void setCurrency(Currency currency) {
      this.currency = currency;
    }

    @Override
    public Currency getCurrency() {
      return currency;
    }

    @Override
    public void setPageLength(Integer pageLength) {
      //not supported, failed quietly
    }

    @Override
    public Integer getPageLength() {
      return pageLength;
    }

    @Override
    public void setPageNumber(Integer pageNumber) {
      if (pageNumber != null && pageNumber == 0)
        throw new IllegalStateException("Pages are '1' indexed");
      this.pageNumber = pageNumber;
    }

    @Override
    public Integer getPageNumber() {
      return pageNumber;
    }

    @Override
    public void setStartTime(Date startTime) {
      this.startTime = startTime;
    }

    @Override
    public Date getStartTime() {
      return startTime;
    }

    @Override
    public void setEndTime(Date endTime) {
      this.endTime = endTime;
    }

    @Override
    public Date getEndTime() {
      return endTime;
    }
  }
}


text:
Blazar Style Commandments
=========================

- Step 1: Read the OpenStack Style Commandments
  https://docs.openstack.org/hacking/latest/
- Step 2: Read on

Blazar Specific Commandments
----------------------------

- [Bl301] Validate that logs are not translated.
- [Bl302] Use LOG.warning() rather than LOG.warn().
- [H904] Delay string interpolations at logging calls.


text:
package com.jmolsmobile.landscapevideocapture.preview;

import android.view.SurfaceHolder;

import com.jmolsmobile.landscapevideocapture.CLog;
import com.jmolsmobile.landscapevideocapture.camera.CameraWrapper;

import java.io.IOException;

public class CapturePreview implements SurfaceHolder.Callback {

	private boolean							mPreviewRunning	= false;
	private final CapturePreviewInterface	mInterface;
	public final CameraWrapper				mCameraWrapper;

	public CapturePreview(CapturePreviewInterface capturePreviewInterface, CameraWrapper cameraWrapper,
			SurfaceHolder holder) {
		mInterface = capturePreviewInterface;
		mCameraWrapper = cameraWrapper;

		initalizeSurfaceHolder(holder);
	}

	@SuppressWarnings("deprecation")
	private void initalizeSurfaceHolder(final SurfaceHolder surfaceHolder) {
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // Necessary for older API's
	}

	@Override
	public void surfaceCreated(final SurfaceHolder holder) {
		// NOP
	}

	@Override
	public void surfaceChanged(final SurfaceHolder holder, final int format, final int width, final int height) {
		if (mPreviewRunning) {
			try {
				mCameraWrapper.stopPreview();
			} catch (final Exception e) {
				e.printStackTrace();
			}
		}

		try {
			mCameraWrapper.configureForPreview(width, height);
			CLog.d(CLog.PREVIEW, "Configured camera for preview in surface of " + width + " by " + height);
		} catch (final RuntimeException e) {
			e.printStackTrace();
			CLog.d(CLog.PREVIEW, "Failed to show preview - invalid parameters set to camera preview");
			mInterface.onCapturePreviewFailed();
			return;
		}

		try {
			mCameraWrapper.enableAutoFocus();
		} catch (final RuntimeException e) {
			e.printStackTrace();
			CLog.d(CLog.PREVIEW, "AutoFocus not available for preview");
		}

		try {
			mCameraWrapper.startPreview(holder);
			setPreviewRunning(true);
		} catch (final IOException e) {
			e.printStackTrace();
			CLog.d(CLog.PREVIEW, "Failed to show preview - unable to connect camera to preview (IOException)");
			mInterface.onCapturePreviewFailed();
		} catch (final RuntimeException e) {
			e.printStackTrace();
			CLog.d(CLog.PREVIEW, "Failed to show preview - unable to start camera preview (RuntimeException)");
			mInterface.onCapturePreviewFailed();
		}
	}

	@Override
	public void surfaceDestroyed(final SurfaceHolder holder) {
		// NOP
	}

	public void releasePreviewResources() {
		if (mPreviewRunning) {
			try {
				mCameraWrapper.stopPreview();
				setPreviewRunning(false);
			} catch (final Exception e) {
				e.printStackTrace();
				CLog.e(CLog.PREVIEW, "Failed to clean up preview resources");
			}
		}
	}

	protected void setPreviewRunning(boolean running) {
		mPreviewRunning = running;
	}

}


text:
description: Information about the user accounts given to competitors.
layout: docs
title: User Accounts
---
These include the [forums](/forum), [IDE](/ide) and, for [team-leaders](/schools/team-leaders),
a [user management interface](/userman) (see [below](#UserManagement)).

### Getting an Account
If you don't yet have an account, you should contact your team-leader,
usually your teacher, who will be able to create one for you.
They will need:

 * Your first and last names
 * Your email address — be sure to give them one you use regularly since
   we will _very_ occasionally send you important information to it
 * Which team you are in (if there is more than one team at your college)

Once your team leader has entered your details into the user management interface
you will receive an email with a link to activate your account.

Please allow at least 10 minutes for the email to be sent,
however if you've been waiting longer than this you should check with your team-leader that the account was created,
and ask them to email <accounts@studentrobotics.org> if the problem remains.

### Forgotten Something?
If you forget your user name or password, you should contact your team-leader,
usually your teacher.
They will be able to tell you the details of your account, or reset your password for you.

### Password Change
If you know your password, but want to change it,
you can do this using the self service side of the [user management page](/userman).

### Other Problems
If your team-leader was unable to resolve your account issue,
you can ask them to [contact us](/about/contactus) for more help.

[User management for Team Leaders](#UserManagement) {#UserManagement}
====================

### Account creation

To create competitor accounts, visit the [user management page](/userman), and
log in. In a column on the left, you'll see a list of users currently
registered for your team.  At the bottom is a link marked 'Register users'.
Click on this, and you'll be presented with a form for competitor user details.
Fill this in (adding rows as appropriate), click submit, and we'll begin the
account creation process.

Once you've submitted this data, you'll receive an email confirming the
registration. We'll also email the competitor to confirm their email
address, and to give them their usernames and passwords. If they don't
confirm their email address within two days, you'll get an email saying
that their registration expired; if this happens, you will need to
re-register them.

### Account maintenance

If you need to update any competitor account data, find their username,
reset their password or so forth, first log into the [user management
page](/userman).

Once there, you should find the competitors name in the list of registered
users on the left, as well as their username. To check or update their details,
click on their name, and their registration details will appear to the right. If
you wish to edit their details, including changing their password, alter the
fields in this window and then click 'Submit'.

We are unable to recover passwords once they have been set. If competitors
forget passwords, please reset their password using the process above. If you
forget your own, please contact <accounts@studentrobotics.org>.


text:
/**
 * External dependencies
 */
import MockDate from 'mockdate';

/**
 * Internal dependencies
 */
import formatDate from '../formatDate';
import { updateSettings, resetSettings } from '../settings';

describe('date/formatDate', () => {
  beforeEach(() => {
    MockDate.set('2020-07-15T22:47:26+00:00');
  });

  afterEach(() => {
    MockDate.reset();
    resetSettings();
  });

  // Uses DEFAULT_DATE_SETTINGS.dateFormat
  it('should return May 2, 2020 with no formatting options', () => {
    const dateString = '2020-05-02T10:47:26';
    const formattedDate = formatDate(dateString);

    expect(formattedDate).toBe('May 2, 2020');
  });

  it('should return "May 2, 2020" with "F j, Y" formatting options', () => {
    updateSettings({
      dateFormat: 'F j, Y',
      gmtOffset: -7,
      timeFormat: 'g:i A',
      timezone: 'America/Los_Angeles',
    });

    const dateString = '2020-05-02T10:47:26';
    const formattedDate = formatDate(dateString);

    expect(formattedDate).toBe('May 2, 2020');
  });

  it('should return "2020-05-02" with "Y-m-d" formatting options', () => {
    updateSettings({
      dateFormat: 'Y-m-d',
      gmtOffset: -7,
      timeFormat: 'g:i A',
      timezone: 'America/Los_Angeles',
    });

    const dateString = '2020-05-02T10:47:26';
    const formattedDate = formatDate(dateString);

    expect(formattedDate).toBe('2020-05-02');
  });

  it('should return 05/02/2020 with m/d/Y formatting options', () => {
    updateSettings({
      dateFormat: 'm/d/Y',
      gmtOffset: -7,
      timeFormat: 'g:i A',
      timezone: 'America/Los_Angeles',
    });

    const dateString = '2020-05-02T10:47:26';
    const formattedDate = formatDate(dateString);

    expect(formattedDate).toBe('05/02/2020');
  });

  it('should return 02/05/2020 with d/m/Y formatting options', () => {
    updateSettings({
      dateFormat: 'd/m/Y',
      gmtOffset: -7,
      timeFormat: 'g:i A',
      timezone: 'America/Los_Angeles',
    });
    const dateString = '2020-05-02T10:47:26';
    const formattedDate = formatDate(dateString);

    expect(formattedDate).toBe('02/05/2020');
  });

  it('should return Sat 05 02 2020 with D m d yy formatting options', () => {
    updateSettings({
      dateFormat: 'D m d yy',
      gmtOffset: -7,
      timeFormat: 'g:i A',
      timezone: 'America/Los_Angeles',
    });

    const dateString = '2020-05-02T10:47:26';
    const formattedDate = formatDate(dateString);

    expect(formattedDate).toBe('Sat 05 02 2020');
  });

  it('should return an empty string when being passed an empty string', () => {
    const formattedDate = formatDate('');

    expect(formattedDate).toBe('');
  });
});


text:
//
// Copyright (c) Microsoft Corporation.    All rights reserved.
//

namespace Microsoft.CortexM0OnMBED
{
    using RT            = Microsoft.Zelig.Runtime;
    using RTOS          = Microsoft.Zelig.Support.mbed;
    using ChipsetModel  = Microsoft.CortexM0OnCMSISCore;

    public abstract class Device : ChipsetModel.Device
    {
        public override void PreInitializeProcessorAndMemory( )
        {
            RT.BugCheck.Raise( RT.BugCheck.StopCode.FailedBootstrap );
        }

        public override void MoveCodeToProperLocation( )
        {
            RT.BugCheck.Raise( RT.BugCheck.StopCode.FailedBootstrap );
        }

        public override void ProcessBugCheck( RT.BugCheck.StopCode code )
        {
            m_bugCheckCode = code;

            RT.TargetPlatform.ARMv6.ProcessorARMv6M.Breakpoint( (uint)code );
        }

        public override unsafe void ProcessLog(string format)
        {
            fixed (char* pS = format)
            {
                uint length = (uint)format.Length;
                RTOS.Utilities.DebugLog0(pS, length);
            }
        }

        public override unsafe void ProcessLog(string format, int p1)
        {
            fixed (char* pS = format)
            {
                uint length = (uint)format.Length;
                RTOS.Utilities.DebugLog1(pS, length, p1);
            }
        }

        public override unsafe void ProcessLog(string format, int p1, int p2)
        {
            fixed (char* pS = format)
            {
                uint length = (uint)format.Length;
                RTOS.Utilities.DebugLog2(pS, length, p1, p2);
            }
        }

        public override unsafe void ProcessLog(string format, int p1, int p2, int p3)
        {
            fixed (char* pS = format)
            {
                uint length = (uint)format.Length;
                RTOS.Utilities.DebugLog3(pS, length, p1, p2, p3);
            }
        }

        public override unsafe void ProcessLog(string format, int p1, int p2, int p3, int p4)
        {
            fixed (char* pS = format)
            {
                uint length = (uint)format.Length;
                RTOS.Utilities.DebugLog4(pS, length, p1, p2, p3, p4);
            }
        }

        public override unsafe void ProcessLog(string format, int p1, int p2, int p3, int p4, int p5)
        {
            fixed (char* pS = format)
            {
                uint length = (uint)format.Length;
                RTOS.Utilities.DebugLog5(pS, length, p1, p2, p3, p4, p5);
            }
        }
    }
}


text:
#pragma once

#include <QtCore/QByteArray>
#include <QtCore/QIODevice>
#include <QtMultimedia/QAudioFormat>
#include <cmath>

/// QIODevice that synthesize sine wave values
class AudioSynthDevice : public QIODevice
{
	Q_OBJECT

public:
	/// Constructor
	AudioSynthDevice(int sampleRate, int sampleSize, QObject *parent = nullptr);

	~AudioSynthDevice() = default;

	/// Provides reading from device
	qint64 readData(char *data, qint64 maxlen);

	/// Opens device, run generation in buffered mode
	void start(int hzFreq);

	/// Close device and reset pose
	void stop();

	/// Stub, because readonly device
	qint64 writeData(const char *data, qint64 len);

	/// Returns amount of available bytes
	qint64 bytesAvailable() const;

private:
	/// Sythesize sine wave values
	int generate(char *data, int lengthBytes);

private:

	/// Internal buffer, used in buffered mode
	QByteArray mBuffer;

	qint64 mPos;

	int mHzFreq;

	const int mSampleRate;

	const int mSampleSize;

	/// Mode of device
	const bool mBuffered { false };

	long long mY1 { 0 };

	long long mY2 { 0 };

	long long mB { 0 };

	static constexpr int M = 1 << 30;

	double mOmega { std::nan("") };
};