text:
import semver from "semver";
import type { Targets } from "@babel/helper-compilation-targets";

import { version as coreVersion } from "../../";
import { assertSimpleType } from "../caching";
import type {
  CacheConfigurator,
  SimpleCacheConfigurator,
  SimpleType,
} from "../caching";

import type { AssumptionName, CallerMetadata } from "../validation/options";

import type * as Context from "../cache-contexts";

type EnvFunction = {
  (): string;
  <T>(extractor: (babelEnv: string) => T): T;
  (envVar: string): boolean;
  (envVars: Array<string>): boolean;
};

type CallerFactory = (
  extractor: (callerMetadata: CallerMetadata | undefined) => unknown,
) => SimpleType;
type TargetsFunction = () => Targets;
type AssumptionFunction = (name: AssumptionName) => boolean | undefined;

export type ConfigAPI = {
  version: string;
  cache: SimpleCacheConfigurator;
  env: EnvFunction;
  async: () => boolean;
  assertVersion: typeof assertVersion;
  caller?: CallerFactory;
};

export type PresetAPI = {
  targets: TargetsFunction;
  addExternalDependency: (ref: string) => void;
} & ConfigAPI;

export type PluginAPI = {
  assumption: AssumptionFunction;
} & PresetAPI;

export function makeConfigAPI<SideChannel extends Context.SimpleConfig>(
  cache: CacheConfigurator<SideChannel>,
): ConfigAPI {
  // TODO(@nicolo-ribaudo): If we remove the explicit type from `value`
  // and the `as any` type cast, TypeScript crashes in an infinite
  // recursion. After upgrading to TS4.7 and finishing the noImplicitAny
  // PR, we should check if it still crashes and report it to the TS team.
  const env: EnvFunction = ((
    value: string | string[] | (<T>(babelEnv: string) => T),
  ) =>
    cache.using(data => {
      if (typeof value === "undefined") return data.envName;
      if (typeof value === "function") {
        return assertSimpleType(value(data.envName));
      }
      return (Array.isArray(value) ? value : [value]).some(entry => {
        if (typeof entry !== "string") {
          throw new Error("Unexpected non-string value");
        }
        return entry === data.envName;
      });
    })) as any;

  const caller = (cb: {
    (CallerMetadata: CallerMetadata | undefined): SimpleType;
  }) => cache.using(data => assertSimpleType(cb(data.caller)));

  return {
    version: coreVersion,
    cache: cache.simple(),
    // Expose ".env()" so people can easily get the same env that we expose using the "env" key.
    env,
    async: () => false,
    caller,
    assertVersion,
  };
}

export function makePresetAPI<SideChannel extends Context.SimplePreset>(
  cache: CacheConfigurator<SideChannel>,
  externalDependencies: Array<string>,
): PresetAPI {
  const targets = () =>
    // We are using JSON.parse/JSON.stringify because it's only possible to cache
    // primitive values. We can safely stringify the targets object because it
    // only contains strings as its properties.
    // Please make the Record and Tuple proposal happen!
    JSON.parse(cache.using(data => JSON.stringify(data.targets)));

  const addExternalDependency = (ref: string) => {
    externalDependencies.push(ref);
  };

  return { ...makeConfigAPI(cache), targets, addExternalDependency };
}

export function makePluginAPI<SideChannel extends Context.SimplePlugin>(
  cache: CacheConfigurator<SideChannel>,
  externalDependencies: Array<string>,
): PluginAPI {
  const assumption = (name: string) =>
    cache.using(data => data.assumptions[name]);

  return { ...makePresetAPI(cache, externalDependencies), assumption };
}

function assertVersion(range: string | number): void {
  if (typeof range === "number") {
    if (!Number.isInteger(range)) {
      throw new Error("Expected string or integer value.");
    }
    range = `^${range}.0.0-0`;
  }
  if (typeof range !== "string") {
    throw new Error("Expected string or integer value.");
  }

  if (semver.satisfies(coreVersion, range)) return;

  const limit = Error.stackTraceLimit;

  if (typeof limit === "number" && limit < 25) {
    // Bump up the limit if needed so that users are more likely
    // to be able to see what is calling Babel.
    Error.stackTraceLimit = 25;
  }

  const err = new Error(
    `Requires Babel "${range}", but was loaded with "${coreVersion}". ` +
      `If you are sure you have a compatible version of @babel/core, ` +
      `it is likely that something in your build process is loading the ` +
      `wrong version. Inspect the stack trace of this error to look for ` +
      `the first entry that doesn't mention "@babel/core" or "babel-core" ` +
      `to see what is calling Babel.`,
  );

  if (typeof limit === "number") {
    Error.stackTraceLimit = limit;
  }

  throw Object.assign(err, {
    code: "BABEL_VERSION_UNSUPPORTED",
    version: coreVersion,
    range,
  });
}


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Conduit</title>

    <link rel="apple-touch-icon" sizes="180x180" href="/assets/icons/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/assets/icons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/assets/icons/favicon-16x16.png">
    <link rel="manifest" href="/assets/site.webmanifest">
    <link rel="mask-icon" href="/assets/icons/safari-pinned-tab.svg" color="#5bbad5">
    <meta name="msapplication-TileColor" content="#da532c">
    <meta name="theme-color" content="#ffffff">

    <!-- Import Ionicon icons & Google Fonts our Bootstrap theme relies on -->
    <script src="elm.js"></script>
  </head>
  <body>
    <script>
      // var storageKey = "store";
      // var flags = localStorage.getItem(storageKey);
      var app = Elm.Main.init({flags: {}});

      //app.ports.storeCache.subscribe(function(val) {

      //  if (val === null) {
      //    localStorage.removeItem(storageKey);
       // } else {
       //   localStorage.setItem(storageKey, JSON.stringify(val));
      //  }

        // Report that the new session was stored succesfully.
       // setTimeout(function() { app.ports.onStoreChange.send(val); }, 0);
     // });

      // Whenever localStorage changes in another tab, report it if necessary.
      //window.addEventListener("storage", function(event) {
        //if (event.storageArea === localStorage && event.key === storageKey) {
        //  app.ports.onStoreChange.send(event.newValue);
       // }
      //}, false);
    </script>
  </body>
</html>

redpajama_set_name: RedPajamaGithub


text:
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { NgArrayPipesModule } from 'angular-pipes';
import { PlannerListModule, WorkItemDetailModule } from 'fabric8-planner';
import { Fabric8WitModule } from 'ngx-fabric8-wit';
import { FeatureFlagModule } from 'ngx-feature-flag';
import { WidgetsModule } from 'ngx-widgets';
import { LoadingWidgetModule } from '../../dashboard-widgets/loading-widget/loading-widget.module';
import { WorkItemWidgetRoutingModule } from './work-item-widget-routing.module';
import { WorkItemWidgetComponent } from './work-item-widget.component';

@NgModule({
  imports: [
    RouterModule,
    CommonModule,
    FormsModule,
    LoadingWidgetModule,
    WidgetsModule,
    PlannerListModule,
    NgArrayPipesModule,
    WorkItemWidgetRoutingModule,
    WorkItemDetailModule,
    Fabric8WitModule,
    FeatureFlagModule,
  ],
  declarations: [WorkItemWidgetComponent],
  exports: [WorkItemWidgetComponent],
})
export class WorkItemWidgetModule {}


text:
#ifndef FullImageSearch_HPP
#define FullImageSearch_HPP

// Custom
#include <Helpers/Helpers.h>

// ITK
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkImage.h"

/**
  * This class returns all vertices in the image. . It is intended to degenerate
  * InpaintingAlgorithmWithLocalSearch by searching the entire image for the source
  * patch (the same behavior as InpaintingAlgorithm).
  */
template <typename TVertexDescriptorType>
struct FullImageSearch
{
  itk::ImageRegion<2> FullRegion;

  typedef std::vector<TVertexDescriptorType> VectorType;

  VectorType Vertices;

  FullImageSearch(const itk::ImageRegion<2>& fullRegion) : FullRegion(fullRegion)
  {
    // We have to create a dummy image with the specified region in order to use the region iterator
    typedef itk::Image<int, 2> ImageType;
    ImageType::Pointer image = ImageType::New();
    image->SetRegions(this->FullRegion);
    image->Allocate();

    this->Vertices.resize(this->FullRegion.GetNumberOfPixels());
    unsigned int counter = 0;
    itk::ImageRegionConstIteratorWithIndex<ImageType> imageIterator(image, this->FullRegion);
    while(!imageIterator.IsAtEnd())
    {
      TVertexDescriptorType vert = Helpers::ConvertFrom<TVertexDescriptorType, itk::Index<2> > (imageIterator.GetIndex());
      this->Vertices[counter] = vert;
      counter++;
      ++imageIterator;
    }
  }

  VectorType operator()(const TVertexDescriptorType& center)
  {
    // Do nothing but return the result, we already composed the vector of all vertices in the constructor
    return this->Vertices;
  }

};

#endif


text:
//
//  MyBaseLayout.m
//  MyLayout
//
//  Created by apple on 15/6/14.
//  Copyright (c) 2015年 欧阳大哥. All rights reserved.
//

#import "MyBaseLayout.h"
#import "MyLayoutInner.h"
#import <objc/runtime.h>

const char * const ASSOCIATEDOBJECT_KEY_MYLAYOUT_SIZECLASSES = "ASSOCIATEDOBJECT_KEY_MYLAYOUT_SIZECLASSES";
const char * const ASSOCIATEDOBJECT_KEY_MYLAYOUT_ABSPOS = "ASSOCIATEDOBJECT_KEY_MYLAYOUT_ABSPOS";

@implementation UIView(MyLayoutExt)

-(MyLayoutPos*)leftPos
{

    MyLayoutPos *pos = self.myCurrentSizeClass.leftPos;
    pos.view = self;
    return pos;
}

-(MyLayoutPos*)topPos
{
    MyLayoutPos *pos = self.myCurrentSizeClass.topPos;
    pos.view = self;
    return pos;
}

-(MyLayoutPos*)rightPos
{

    MyLayoutPos *pos = self.myCurrentSizeClass.rightPos;
    pos.view = self;
    return pos;

}

-(MyLayoutPos*)bottomPos
{

    MyLayoutPos *pos = self.myCurrentSizeClass.bottomPos;
    pos.view = self;
    return pos;

}

#ifdef MY_USEOLDMETHODDEF

-(CGFloat)leftMargin
{
    return self.myLeftMargin;
}

-(void)setLeftMargin:(CGFloat)leftMargin
{
    self.myLeftMargin = leftMargin;

}

-(CGFloat)topMargin
{
    return self.myTopMargin;
}

-(void)setTopMargin:(CGFloat)topMargin
{
    self.myTopMargin = topMargin;
 }

-(CGFloat)rightMargin
{
    return self.myRightMargin;
}

-(void)setRightMargin:(CGFloat)rightMargin
{
    self.myRightMargin = rightMargin;
}

-(CGFloat)bottomMargin
{
    return self.myBottomMargin;
}

-(void)setBottomMargin:(CGFloat)bottomMargin
{
    self.myBottomMargin = bottomMargin;
}

#endif

-(CGFloat)myLeftMargin
{
    return self.leftPos.margin;
}

-(void)setMyLeftMargin:(CGFloat)leftMargin
{
    self.leftPos.equalTo(@(leftMargin));

}

-(CGFloat)myTopMargin
{
    return self.topPos.margin;
}

-(void)setMyTopMargin:(CGFloat)topMargin
{
    self.topPos.equalTo(@(topMargin));
}

-(CGFloat)myRightMargin
{
    return self.rightPos.margin;
}

-(void)setMyRightMargin:(CGFloat)rightMargin
{
    self.rightPos.equalTo(@(rightMargin));
}

-(CGFloat)myBottomMargin
{
    return self.bottomPos.margin;
}

-(void)setMyBottomMargin:(CGFloat)bottomMargin
{
    self.bottomPos.equalTo(@(bottomMargin));
}

-(CGFloat)myMargin
{
    return self.leftPos.margin;
}

-(void)setMyMargin:(CGFloat)myMargin
{
    self.topPos.equalTo(@(myMargin));
    self.leftPos.equalTo(@(myMargin));
    self.rightPos.equalTo(@(myMargin));
    self.bottomPos.equalTo(@(myMargin));
}

-(MyLayoutDime*)widthDime
{

    MyLayoutDime *dime = self.myCurrentSizeClass.widthDime;
    dime.view = self;
    return dime;

}

-(MyLayoutDime*)heightDime
{

    MyLayoutDime *dime = self.myCurrentSizeClass.heightDime;
    dime.view = self;
    return dime;
}

#ifdef MY_USEOLDMETHODDEF

-(CGFloat)width
{
    return self.myWidth;
}

-(void)setWidth:(CGFloat)width
{
    self.myWidth = width;
}

-(CGFloat)height
{
    return self.myHeight;
}

-(void)setHeight:(CGFloat)height
{
    self.myHeight = height;
}

#endif

-(CGFloat)myWidth
{
    return self.widthDime.measure;
}

-(void)setMyWidth:(CGFloat)width
{
    self.widthDime.equalTo(@(width));
}

-(CGFloat)myHeight
{
    return self.heightDime.measure;
}

-(void)setMyHeight:(CGFloat)height
{
    self.heightDime.equalTo(@(height));
}

-(CGSize)mySize
{
    return CGSizeMake(self.myWidth, self.myHeight);
}

-(void)setMySize:(CGSize)mySize
{
    self.myWidth = mySize.width;
    self.myHeight = mySize.height;
}

-(MyLayoutPos*)centerXPos
{
    MyLayoutPos *pos = self.myCurrentSizeClass.centerXPos;
    pos.view = self;
    return pos;

}

-(MyLayoutPos*)centerYPos
{

    MyLayoutPos *pos = self.myCurrentSizeClass.centerYPos;
    pos.view = self;
    return pos;
}

#ifdef MY_USEOLDMETHODDEF

-(CGFloat)centerXOffset
{
    return self.myCenterXOffset;
}

-(void)setCenterXOffset:(CGFloat)centerXOffset
{
    self.myCenterXOffset = centerXOffset;
}

-(CGFloat)centerYOffset
{
    return self.myCenterYOffset;
}

-(void)setCenterYOffset:(CGFloat)centerYOffset
{
    self.myCenterYOffset = centerYOffset;
}

-(CGPoint)centerOffset
{
    return self.myCenterOffset;
}

-(void)setCenterOffset:(CGPoint)centerOffset
{
    self.myCenterOffset = centerOffset;
}

#endif

-(CGFloat)myCenterXOffset
{
    return self.centerXPos.margin;
}

-(void)setMyCenterXOffset:(CGFloat)centerXOffset
{
    self.centerXPos.equalTo(@(centerXOffset));
}

-(CGFloat)myCenterYOffset
{
    return self.centerYPos.margin;
}

-(void)setMyCenterYOffset:(CGFloat)centerYOffset
{
    self.centerYPos.equalTo(@(centerYOffset));
}

-(CGPoint)myCenterOffset
{
    return CGPointMake(self.myCenterXOffset, self.myCenterYOffset);
}

-(void)setMyCenterOffset:(CGPoint)centerOffset
{
    self.myCenterXOffset = centerOffset.x;
    self.myCenterYOffset = centerOffset.y;
}

-(void)setFlexedHeight:(BOOL)flexedHeight
{
    UIView *lsc = self.myCurrentSizeClass;
    if (lsc.flexedHeight != flexedHeight)
    {
        lsc.flexedHeight = flexedHeight;
        if (self.superview != nil)
            [self.superview setNeedsLayout];
    }
}

-(BOOL)isFlexedHeight
{
    return self.myCurrentSizeClass.isFlexedHeight;
}

-(BOOL)useFrame
{
    return self.myCurrentSizeClass.useFrame;
}

-(void)setUseFrame:(BOOL)useFrame
{
    UIView *lsc = self.myCurrentSizeClass;
    if (lsc.useFrame != useFrame)
    {
        lsc.useFrame = useFrame;
        if (self.superview != nil)
            [ self.superview setNeedsLayout];
    }

}

-(CGRect)estimatedRect
{
    CGRect rect = self.absPos.frame;
    if (rect.origin.x == CGFLOAT_MAX || rect.origin.y == CGFLOAT_MAX)
        return self.frame;
    return rect;
}

-(void)resetMyLayoutSetting
{
    [self resetMyLayoutSettingInSizeClass:MySizeClass_wAny | MySizeClass_hAny];
}

-(void)resetMyLayoutSettingInSizeClass:(MySizeClass)sizeClass
{
    NSMutableDictionary *dict = objc_getAssociatedObject(self, ASSOCIATEDOBJECT_KEY_MYLAYOUT_SIZECLASSES);
    if (dict != nil)
    {
        [dict removeObjectForKey:@(sizeClass)];
    }

}

-(instancetype)fetchLayoutSizeClass:(MySizeClass)sizeClass
{
    return [self fetchLayoutSizeClass:sizeClass copyFrom:0xFF];
}

-(instancetype)fetchLayoutSizeClass:(MySizeClass)sizeClass copyFrom:(MySizeClass)srcSizeClass
{
    NSMutableDictionary *dict = objc_getAssociatedObject(self, ASSOCIATEDOBJECT_KEY_MYLAYOUT_SIZECLASSES);
    if (dict == nil)
    {
        dict = [NSMutableDictionary new];
        objc_setAssociatedObject(self, ASSOCIATEDOBJECT_KEY_MYLAYOUT_SIZECLASSES, dict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    }

    MyLayoutSizeClass *myLayoutSizeClass = (MyLayoutSizeClass*)[dict objectForKey:@(sizeClass)];
    if (myLayoutSizeClass == nil)
    {
        MyLayoutSizeClass *srcLayoutSizeClass = (MyLayoutSizeClass*)[dict objectForKey:@(srcSizeClass)];
        if (srcLayoutSizeClass == nil)
            myLayoutSizeClass = [self createSizeClassInstance];
        else
            myLayoutSizeClass = [srcLayoutSizeClass copy];

        [dict setObject:myLayoutSizeClass forKey:@(sizeClass)];
    }

    return (UIView*)myLayoutSizeClass;

}

@end

@implementation UIView(MyLayoutExtInner)

-(instancetype)myDefaultSizeClass
{
    return [self fetchLayoutSizeClass:MySizeClass_wAny | MySizeClass_hAny];
}

-(instancetype)myCurrentSizeClass
{
    if (self.absPos.sizeClass == nil)
        self.absPos.sizeClass = [self myDefaultSizeClass];

    return self.absPos.sizeClass;
}

-(instancetype)myBestSizeClass:(MySizeClass)sizeClass
{

    MySizeClass wsc = sizeClass & 0x03;
    MySizeClass hsc = sizeClass & 0x0C;
    MySizeClass ori = sizeClass & 0xC0;

    NSMutableDictionary *dict = objc_getAssociatedObject(self, ASSOCIATEDOBJECT_KEY_MYLAYOUT_SIZECLASSES);
    if (dict == nil)
    {
        dict = [NSMutableDictionary new];
        objc_setAssociatedObject(self, ASSOCIATEDOBJECT_KEY_MYLAYOUT_SIZECLASSES, dict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    }

    if ([UIDevice currentDevice].systemVersion.floatValue < 8.0)
    {
        wsc = MySizeClass_wAny;
        hsc = MySizeClass_hAny;
    }

    //first search the most exact SizeClass
    MySizeClass searchSizeClass = wsc | hsc | ori;
    MyLayoutSizeClass *myClass = (MyLayoutSizeClass*)[dict objectForKey:@(searchSizeClass)];
    if (myClass != nil)
        return (UIView*)myClass;

    searchSizeClass = wsc | hsc;
    if (searchSizeClass != sizeClass)
    {
        MyLayoutSizeClass *myClass = (MyLayoutSizeClass*)[dict objectForKey:@(searchSizeClass)];
        if (myClass != nil)
            return (UIView*)myClass;
    }

    searchSizeClass = MySizeClass_wAny | hsc | ori;
    if (ori != 0 && searchSizeClass != sizeClass)
    {
        myClass = (MyLayoutSizeClass*)[dict objectForKey:@(searchSizeClass)];
        if (myClass != nil)
            return (UIView*)myClass;

    }

    searchSizeClass = MySizeClass_wAny | hsc;
    if (searchSizeClass != sizeClass)
    {
        myClass = (MyLayoutSizeClass*)[dict objectForKey:@(searchSizeClass)];
        if (myClass != nil)
            return (UIView*)myClass;
    }

    searchSizeClass = wsc | MySizeClass_hAny | ori;
    if (ori != 0 && searchSizeClass != sizeClass)
    {
        myClass = (MyLayoutSizeClass*)[dict objectForKey:@(searchSizeClass)];
        if (myClass != nil)
            return (UIView*)myClass;
    }

    searchSizeClass = wsc | MySizeClass_hAny;
    if (searchSizeClass != sizeClass)
    {
        myClass = (MyLayoutSizeClass*)[dict objectForKey:@(searchSizeClass)];
        if (myClass != nil)
            return (UIView*)myClass;
    }

    searchSizeClass = MySizeClass_wAny | MySizeClass_hAny | ori;
    if (ori != 0 && searchSizeClass != sizeClass)
    {
        myClass = (MyLayoutSizeClass*)[dict objectForKey:@(searchSizeClass)];
        if (myClass != nil)
            return (UIView*)myClass;
    }

    searchSizeClass = MySizeClass_wAny | MySizeClass_hAny;
    myClass = (MyLayoutSizeClass*)[dict objectForKey:@(searchSizeClass)];
    if (myClass == nil)
    {
        myClass = [self createSizeClassInstance];
        [dict setObject:myClass forKey:@(searchSizeClass)];
    }

    return (UIView*)myClass;

}

-(MyLayoutMeasure*)absPos
{

    MyLayoutMeasure *obj = objc_getAssociatedObject(self, ASSOCIATEDOBJECT_KEY_MYLAYOUT_ABSPOS);
    if (obj == nil)
    {
        obj = [MyLayoutMeasure new];
        objc_setAssociatedObject(self, ASSOCIATEDOBJECT_KEY_MYLAYOUT_ABSPOS, obj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    }

    return obj;
}

-(id)createSizeClassInstance
{
    return [MyLayoutSizeClass new];
}

@end

@implementation MyBorderLineDraw

-(id)init
{
    self = [super init];
    if (self != nil)
    {
        _color = [UIColor blackColor];
        _insetColor = nil;
        _thick = 1;
        _headIndent = 0;
        _tailIndent = 0;
        _dash  = 0;
    }

    return self;
}

-(id)initWithColor:(UIColor *)color
{
    self = [self init];
    if (self != nil)
    {
        _color = color;
    }

    return self;
}

@end

/**绘制线条层委托实现类**/
@interface MyBorderLineLayerDelegate : NSObject

@property(nonatomic ,weak) MyBaseLayout *layout;

-(id)initWithLayout:(MyBaseLayout*)layout;

@end

@implementation MyBorderLineLayerDelegate

-(id)initWithLayout:(MyBaseLayout*)layout
{
    self = [self init];
    if (self != nil)
    {
        _layout = layout;
    }

    return self;
}

-(void)layoutSublayersOfLayer:(CAShapeLayer *)layer
{
    if (self.layout == nil)
        return;

    CGSize layoutSize = self.layout.layer.bounds.size;

    CGRect layerRect;
    CGPoint fromPoint;
    CGPoint toPoint;

    if (layer == self.layout.leftBorderLineLayer)
    {
        layerRect = CGRectMake(0, self.layout.leftBorderLine.headIndent, self.layout.leftBorderLine.thick/2, layoutSize.height - self.layout.leftBorderLine.headIndent - self.layout.leftBorderLine.tailIndent);
        fromPoint = CGPointMake(0, 0);
        toPoint = CGPointMake(0, layerRect.size.height);

    }
    else if (layer == self.layout.rightBorderLineLayer)
    {
        layerRect = CGRectMake(layoutSize.width - self.layout.rightBorderLine.thick / 2, self.layout.rightBorderLine.headIndent, self.layout.rightBorderLine.thick / 2, layoutSize.height - self.layout.rightBorderLine.headIndent - self.layout.rightBorderLine.tailIndent);
        fromPoint = CGPointMake(0, 0);
        toPoint = CGPointMake(0, layerRect.size.height);

    }
    else if (layer == self.layout.topBorderLineLayer)
    {
        layerRect = CGRectMake(self.layout.topBorderLine.headIndent, 0, layoutSize.width - self.layout.topBorderLine.headIndent - self.layout.topBorderLine.tailIndent, self.layout.topBorderLine.thick/2);
        fromPoint = CGPointMake(0, 0);
        toPoint = CGPointMake(layerRect.size.width, 0);
    }
    else if (layer == self.layout.bottomBorderLineLayer)
    {
        layerRect = CGRectMake(self.layout.bottomBorderLine.headIndent, layoutSize.height - self.layout.bottomBorderLine.thick / 2, layoutSize.width - self.layout.bottomBorderLine.headIndent - self.layout.bottomBorderLine.tailIndent, self.layout.bottomBorderLine.thick /2);
        fromPoint = CGPointMake(0, 0);
        toPoint = CGPointMake(layerRect.size.width, 0);
    }
    else
    {
        NSAssert(0, @"oops!");
    }

    //把动画效果取消。
    if (!CGRectEqualToRect(layer.frame, layerRect))
    {

        [CATransaction begin];
        [CATransaction setValue:(id)kCFBooleanTrue
                         forKey:kCATransactionDisableActions];

        if (layer.lineDashPhase == 0)
        {
            layer.path = nil;
        }
        else
        {
            CGMutablePathRef path = CGPathCreateMutable();
            CGPathMoveToPoint(path, nil, fromPoint.x, fromPoint.y);
            CGPathAddLineToPoint(path, nil, toPoint.x,toPoint.y);
            layer.path = path;
            CGPathRelease(path);

        }

        layer.frame = layerRect;

        [CATransaction commit];
    }

}

@end

@interface MyBaseLayout()

@end

IB_DESIGNABLE
@implementation MyBaseLayout
{
    __weak id _target;
    SEL   _action;

    __weak id _touchDownTarget;
    SEL  _touchDownAction;

    __weak id _touchCancelTarget;
    SEL _touchCancelAction;
    BOOL _hasDoCancel;

    UIColor *_oldBackgroundColor;
    UIImage *_oldBackgroundImage;
    BOOL _forbidTouch;
    BOOL _canCallAction;
    CGPoint _beginPoint;
    MyBorderLineLayerDelegate *_layerDelegate;

}

BOOL _hasBegin;

-(void)dealloc
{
}

#pragma  mark -- Public Method

-(void)setPadding:(UIEdgeInsets)padding
{
    MyBaseLayout *lsc = self.myCurrentSizeClass;
    if (!UIEdgeInsetsEqualToEdgeInsets(lsc.padding, padding))
    {
        lsc.padding = padding;
        [self setNeedsLayout];
    }
}

-(UIEdgeInsets)padding
{
    return self.myCurrentSizeClass.padding;
}

-(void)setLeftPadding:(CGFloat)leftPadding
{
    MyBaseLayout *lsc = self.myCurrentSizeClass;
    [self setPadding:UIEdgeInsetsMake(lsc.padding.top, leftPadding, lsc.padding.bottom,lsc.padding.right)];
}

-(CGFloat)leftPadding
{
    return self.myCurrentSizeClass.padding.left;
}

-(void)setTopPadding:(CGFloat)topPadding
{
    MyBaseLayout *lsc = self.myCurrentSizeClass;
    [self setPadding:UIEdgeInsetsMake(topPadding, lsc.padding.left, lsc.padding.bottom,lsc.padding.right)];
}

-(CGFloat)topPadding
{
    return self.myCurrentSizeClass.padding.top;
}

-(void)setRightPadding:(CGFloat)rightPadding
{
    MyBaseLayout *lsc = self.myCurrentSizeClass;
    [self setPadding:UIEdgeInsetsMake(lsc.padding.top, lsc.padding.left, lsc.padding.bottom, rightPadding)];
}

-(CGFloat)rightPadding
{
    return self.myCurrentSizeClass.padding.right;
}

-(void)setBottomPadding:(CGFloat)bottomPadding
{
    MyBaseLayout *lsc = self.myCurrentSizeClass;
    [self setPadding:UIEdgeInsetsMake(lsc.padding.top, lsc.padding.left, bottomPadding, lsc.padding.right)];
}

-(CGFloat)bottomPadding
{
    return self.myCurrentSizeClass.padding.bottom;
}

-(void)setWrapContentHeight:(BOOL)wrapContentHeight
{
    MyBaseLayout *lsc = self.myCurrentSizeClass;

    if (lsc.wrapContentHeight != wrapContentHeight)
    {
        lsc.wrapContentHeight = wrapContentHeight;
        [self setNeedsLayout];
    }
}

-(BOOL)wrapContentHeight
{
    return self.myCurrentSizeClass.wrapContentHeight;
}

-(void)setWrapContentWidth:(BOOL)wrapContentWidth
{
    MyBaseLayout *lsc = self.myCurrentSizeClass;

    if (lsc.wrapContentWidth != wrapContentWidth)
    {
        lsc.wrapContentWidth = wrapContentWidth;
        [self setNeedsLayout];
    }
}

-(BOOL)wrapContentWidth
{
    return self.myCurrentSizeClass.wrapContentWidth;
}

-(void)setHideSubviewReLayout:(BOOL)hideSubviewReLayout
{
    MyBaseLayout *lsc = self.myCurrentSizeClass;

    if (lsc.hideSubviewReLayout != hideSubviewReLayout)
    {
        lsc.hideSubviewReLayout = hideSubviewReLayout;
        [self setNeedsLayout];
    }

}

-(BOOL)hideSubviewReLayout
{
    return self.myCurrentSizeClass.hideSubviewReLayout;
}

-(void)updateBorderLayer:(CAShapeLayer**)ppLayer withBorderLineDraw:(MyBorderLineDraw*)borderLineDraw
{
    if (borderLineDraw == nil)
    {
        if (*ppLayer != nil)
        {
            (*ppLayer).delegate = nil;
            [(*ppLayer) removeFromSuperlayer];
            *ppLayer = nil;
        }
    }
    else
    {
        if (_layerDelegate == nil)
            _layerDelegate = [[MyBorderLineLayerDelegate alloc] initWithLayout:self];

        if ( *ppLayer == nil)
        {
            *ppLayer = [[CAShapeLayer alloc] init];
            (*ppLayer).delegate = _layerDelegate;
            [self.layer addSublayer:*ppLayer];
        }

        //如果是点线则是用path,否则就用背景色
        if (borderLineDraw.dash != 0)
        {
            (*ppLayer).lineDashPhase = borderLineDraw.dash / 2;
            NSNumber *num = @(borderLineDraw.dash);
            (*ppLayer).lineDashPattern = @[num,num];

            (*ppLayer).strokeColor = borderLineDraw.color.CGColor;
            (*ppLayer).lineWidth = borderLineDraw.thick;
            (*ppLayer).backgroundColor = nil;

        }
        else
        {
            (*ppLayer).lineDashPhase = 0;
            (*ppLayer).lineDashPattern = nil;

            (*ppLayer).strokeColor = nil;
            (*ppLayer).lineWidth = 0;
            (*ppLayer).backgroundColor = borderLineDraw.color.CGColor;

        }

        [(*ppLayer) setNeedsLayout];

    }
}

-(void)setBottomBorderLine:(MyBorderLineDraw *)bottomBorderLine
{
    if (_bottomBorderLine != bottomBorderLine)
    {
        _bottomBorderLine = bottomBorderLine;

        CAShapeLayer *borderLayer = _bottomBorderLineLayer;
        [self updateBorderLayer:&borderLayer withBorderLineDraw:_bottomBorderLine];
        _bottomBorderLineLayer = borderLayer;
    }
}

-(void)setTopBorderLine:(MyBorderLineDraw *)topBorderLine
{
    if (_topBorderLine != topBorderLine)
    {
        _topBorderLine = topBorderLine;

        CAShapeLayer *borderLayer = _topBorderLineLayer;
        [self updateBorderLayer:&borderLayer withBorderLineDraw:_topBorderLine];
        _topBorderLineLayer = borderLayer;

    }
}

-(void)setLeftBorderLine:(MyBorderLineDraw *)leftBorderLine
{
    if (_leftBorderLine != leftBorderLine)
    {
        _leftBorderLine = leftBorderLine;

        CAShapeLayer *borderLayer = _leftBorderLineLayer;
        [self updateBorderLayer:&borderLayer withBorderLineDraw:_leftBorderLine];
        _leftBorderLineLayer = borderLayer;
    }
}

-(void)setRightBorderLine:(MyBorderLineDraw *)rightBorderLine
{
    if (_rightBorderLine != rightBorderLine)
    {
        _rightBorderLine = rightBorderLine;

        CAShapeLayer *borderLayer = _rightBorderLineLayer;
        [self updateBorderLayer:&borderLayer withBorderLineDraw:_rightBorderLine];
        _rightBorderLineLayer = borderLayer;
    }

}

-(void)setBoundBorderLine:(MyBorderLineDraw *)boundBorderLine
{
    self.leftBorderLine = boundBorderLine;
    self.rightBorderLine = boundBorderLine;
    self.topBorderLine = boundBorderLine;
    self.bottomBorderLine = boundBorderLine;
}

-(MyBorderLineDraw*)boundBorderLine
{
    return self.leftBorderLine;
}

-(void)setBackgroundImage:(UIImage *)backgroundImage
{
    if (_backgroundImage != backgroundImage)
    {
        _backgroundImage = backgroundImage;
        self.layer.contents = (id)_backgroundImage.CGImage;
    }
}

//只获取计算得到尺寸,不进行真正的布局。
-(CGRect)estimateLayoutRect:(CGSize)size
{
    return [self estimateLayoutRect:size inSizeClass:MySizeClass_wAny | MySizeClass_hAny];
}

-(CGRect)estimateLayoutRect:(CGSize)size inSizeClass:(MySizeClass)sizeClass
{

    self.absPos.sizeClass = [self myBestSizeClass:sizeClass];
    for (UIView *sbv in self.subviews)
    {
        sbv.absPos.sizeClass = [sbv myBestSizeClass:sizeClass];
    }

    BOOL hasSubLayout = NO;
    CGRect rect;
    self.absPos.frame = [self calcLayoutRect:size isEstimate:NO pHasSubLayout:&hasSubLayout sizeClass:sizeClass];
    if (!hasSubLayout)
        rect = self.absPos.frame;
    else
    {
        rect = [self calcLayoutRect:CGSizeZero isEstimate:YES pHasSubLayout:&hasSubLayout sizeClass:sizeClass];
        self.absPos.frame = rect;
    }

    //计算后还原为默认sizeClass
    for (UIView *sbv in self.subviews)
    {
        sbv.absPos.sizeClass = self.myDefaultSizeClass;

    }
    self.absPos.sizeClass = self.myDefaultSizeClass;

    return rect;

}

-(void)setTarget:(id)target action:(SEL)action
{
    _target = target;
    _action = action;
}

-(void)setTouchDownTarget:(id)target action:(SEL)action
{
    _touchDownTarget = target;
    _touchDownAction = action;
}

-(void)setTouchCancelTarget:(id)target action:(SEL)action
{
    _touchCancelTarget = target;
    _touchCancelAction = action;

}

#pragma mark -- touches event

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    if (_target != nil && !_forbidTouch && touch.tapCount == 1 && !_hasBegin)
    {
        _hasBegin = YES;
        _canCallAction = YES;
        _beginPoint = [((UITouch*)[touches anyObject]) locationInView:self];
        if (_highlightedBackgroundColor != nil)
        {
            _oldBackgroundColor = self.backgroundColor;
            self.backgroundColor = _highlightedBackgroundColor;
        }

        if (_highlightedBackgroundImage != nil)
        {
            _oldBackgroundImage = self.backgroundImage;
            self.backgroundImage = _highlightedBackgroundImage;
        }

        _hasDoCancel = NO;
        if (_touchDownTarget != nil && _touchDownAction != nil)
        {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            [_touchDownTarget performSelector:_touchDownAction withObject:self];
#pragma clang diagnostic pop

        }

    }

    [super touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_target != nil && _hasBegin)
    {
        if (_canCallAction)
        {
            CGPoint pt = [((UITouch*)[touches anyObject]) locationInView:self];
            if (fabs(pt.x - _beginPoint.x) > 2 || fabs(pt.y - _beginPoint.y) > 2)
            {
                _canCallAction = NO;

                if (!_hasDoCancel)
                {

                    if (_touchCancelTarget != nil && _touchCancelAction != nil)
                    {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
                        [_touchCancelTarget performSelector:_touchCancelAction withObject:self];
#pragma clang diagnostic pop

                    }

                    _hasDoCancel = YES;

                }

            }
        }
    }

    [super touchesMoved:touches withEvent:event];
}

-(void)doTargetAction:(UITouch*)touch
{
    if (_highlightedBackgroundColor != nil)
    {
        self.backgroundColor = _oldBackgroundColor;
        _oldBackgroundColor = nil;
    }

    if (_highlightedBackgroundImage != nil)
    {
        self.backgroundImage = _oldBackgroundImage;
        _oldBackgroundImage = nil;
    }

    //距离太远则不会处理
    CGPoint pt = [touch locationInView:self];
    if (CGRectContainsPoint(self.bounds, pt) && _action != nil && _canCallAction)
    {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [_target performSelector:_action withObject:self];
#pragma clang diagnostic pop

    }
    else
    {
        if (!_hasDoCancel)
        {
            if (_touchCancelTarget != nil && _touchCancelAction != nil)
            {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
                [_touchCancelTarget performSelector:_touchCancelAction withObject:self];
#pragma clang diagnostic pop

            }

            _hasDoCancel = YES;
        }

    }

    _forbidTouch = NO;

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{

    if (_target != nil && _hasBegin)
    {
        //设置一个延时.
        _forbidTouch = YES;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [self performSelector:@selector(doTargetAction:) withObject:[touches anyObject] afterDelay:0.12];
#pragma clang diagnostic pop

        _hasBegin = NO;
    }

    [super touchesEnded:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{

    if (_target != nil && _hasBegin)
    {
        if (_highlightedBackgroundColor != nil)
        {
            self.backgroundColor = _oldBackgroundColor;
            _oldBackgroundColor = nil;
        }

        if (_highlightedBackgroundImage != nil)
        {
            self.backgroundImage = _oldBackgroundImage;
            _oldBackgroundImage = nil;
        }

        _hasBegin = NO;

        if (!_hasDoCancel)
        {
            if (_touchCancelTarget != nil && _touchCancelAction != nil)
            {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
                [_touchCancelTarget performSelector:_touchCancelAction withObject:self];
#pragma clang diagnostic pop

            }

            _hasDoCancel = YES;

        }

    }

    [super touchesCancelled:touches withEvent:event];
}

#pragma mark -- KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(UIView*)object change:(NSDictionary *)change context:(void *)context
{

    //监控非布局父视图的frame的变化,而改变自身的位置和尺寸
    if (object == self.superview && ![object isKindOfClass:[MyBaseLayout class]])
    {

        if ([keyPath isEqualToString:@"frame"] ||
            [keyPath isEqualToString:@"bounds"] )
        {

            //如果同时设置了左边和右边值则
            if ((self.leftPos.posNumVal != nil && self.rightPos.posNumVal != nil) ||
                [self.widthDime isMatchView:object] ||
                (self.topPos.posNumVal != nil && self.bottomPos.posNumVal != nil) ||
                [self.heightDime isMatchView:object])
            {
                CGRect rectSuper = object.bounds;
                CGRect rectSelf = self.frame;

                if ((self.leftPos.posNumVal != nil && self.rightPos.posNumVal != nil) || [self.widthDime isMatchView:object])
                {
                    //如果是外部视图不支持相对间距。
                    [self calcMatchParentWidth:self.widthDime selfWidth:rectSuper.size.width leftMargin:self.leftPos.margin centerMargin:0  rightMargin:self.rightPos.margin leftPadding:0 rightPadding:0 rect:&rectSelf];
                }

                if ((self.topPos.posNumVal != nil && self.bottomPos.posNumVal != nil) || [self.heightDime isMatchView:object])
                {
                    [self calcMatchParentHeight:self.heightDime selfHeight:rectSuper.size.height topMargin:self.topPos.margin centerMargin:0 bottomMargin:self.bottomPos.margin topPadding:0 bottomPadding:0 rect:&rectSelf];
                }

                rectSelf.size.height = [self.heightDime validMeasure:rectSelf.size.height];
                rectSelf.size.width = [self.widthDime validMeasure:rectSelf.size.width];
                self.frame = rectSelf;

            }
        }

    }

    //监控子视图的frame的变化以便重新进行布局
    if (!_isMyLayouting && [self.subviews containsObject:object])
    {
        if (![object useFrame])
        {
            [self setNeedsLayout];

            //这里添加的原因是有可能子视图取消隐藏后不会绘制自身,所以这里要求子视图重新绘制自身
            if ([keyPath isEqualToString:@"hidden"] && ![change[NSKeyValueChangeNewKey] boolValue])
            {
                [(UIView*)object setNeedsDisplay];
            }
        }
    }

}

#pragma mark -- Override Method

-(id)createSizeClassInstance
{
    return [MyLayoutSizeClassLayout new];
}

-(CGSize)sizeThatFits:(CGSize)size
{
    return [self estimateLayoutRect:size].size;
}

-(void)setHidden:(BOOL)hidden
{
    [super setHidden:hidden];
    if (hidden == NO)
    {
        if (_topBorderLineLayer != nil)
            [_topBorderLineLayer setNeedsLayout];

        if (_bottomBorderLineLayer != nil)
            [_bottomBorderLineLayer setNeedsLayout];

        if (_leftBorderLineLayer != nil)
            [_leftBorderLineLayer setNeedsLayout];

        if (_rightBorderLineLayer != nil)
            [_rightBorderLineLayer setNeedsLayout];
    }
}

- (void)didAddSubview:(UIView *)subview
{
    [super didAddSubview:subview];   //只要加入进来后就修改其默认的实现,而改用我们的实现,这里包括隐藏,调整大小,

    //添加hidden, frame,center的属性通知。
    [subview addObserver:self forKeyPath:@"hidden" options:NSKeyValueObservingOptionNew context:nil];
    [subview addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)willRemoveSubview:(UIView *)subview
{
    [super willRemoveSubview:subview];  //删除后恢复其原来的实现。

    [subview removeObserver:self forKeyPath:@"hidden"];
    [subview removeObserver:self forKeyPath:@"frame"];
}

- (void)willMoveToSuperview:(UIView*)newSuperview
{
    [super willMoveToSuperview:newSuperview];

    //将要添加到父视图时,如果不是MyLayout派生则则跟需要根据父视图的frame的变化而调整自身的位置和尺寸
    if (newSuperview != nil && ![newSuperview isKindOfClass:[MyBaseLayout class]])
    {

        //如果同时设置了左边和右边值则
        if ((self.leftPos.posNumVal != nil && self.rightPos.posNumVal != nil) ||
            [self.widthDime isMatchView:newSuperview] ||
            (self.topPos.posNumVal != nil && self.bottomPos.posNumVal != nil) ||
            [self.heightDime isMatchView:newSuperview])
        {
            CGRect rectSuper = newSuperview.bounds;
            CGRect rectSelf = self.frame;

            if ((self.leftPos.posNumVal != nil && self.rightPos.posNumVal != nil) || [self.widthDime isMatchView:newSuperview])
            {
                self.wrapContentWidth = NO;
                [self calcMatchParentWidth:self.widthDime selfWidth:rectSuper.size.width leftMargin:self.leftPos.margin centerMargin:0  rightMargin:self.rightPos.margin leftPadding:0 rightPadding:0 rect:&rectSelf];
            }

            if ((self.topPos.posNumVal != nil && self.bottomPos.posNumVal != nil) || [self.heightDime isMatchView:newSuperview])
            {
                self.wrapContentHeight = NO;
                [self calcMatchParentHeight:self.heightDime selfHeight:rectSuper.size.height topMargin:self.topPos.margin centerMargin:0 bottomMargin:self.bottomPos.margin topPadding:0 bottomPadding:0 rect:&rectSelf];
            }

            rectSelf.size.height = [self.heightDime validMeasure:rectSelf.size.height];
            rectSelf.size.width = [self.widthDime validMeasure:rectSelf.size.width];

            self.frame = rectSelf;

            //有可能父视图不为空,所以这里先把以前父视图的KVO删除。否则会导致程序崩溃

            if (self.superview != nil && ![self.superview isKindOfClass:[MyBaseLayout class]])
            {
                @try {
                    [self.superview removeObserver:self forKeyPath:@"frame"];

                }
                @catch (NSException *exception) {

                }
                @finally {

                }

                @try {
                    [self.superview removeObserver:self forKeyPath:@"bounds"];

                }
                @catch (NSException *exception) {

                }
                @finally {

                }

            }

            [newSuperview addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
            [newSuperview addObserver:self forKeyPath:@"bounds" options:NSKeyValueObservingOptionNew context:nil];

        }
        else
        {
            CGRect rectSelf = self.frame;
            if (self.widthDime.dimeNumVal != nil)
                rectSelf.size.width = self.widthDime.measure;

            if (self.heightDime.dimeNumVal != nil)
                rectSelf.size.height = self.heightDime.measure;

            if (!CGRectEqualToRect(rectSelf, self.frame))
            {
                self.frame = rectSelf;
            }

        }
    }

    if (newSuperview == nil && self.superview != nil && ![self.superview isKindOfClass:[MyBaseLayout class]])
    {

        @try {
            [self.superview removeObserver:self forKeyPath:@"frame"];

        }
        @catch (NSException *exception) {

        }
        @finally {

        }

        @try {
            [self.superview removeObserver:self forKeyPath:@"bounds"];

        }
        @catch (NSException *exception) {

        }
        @finally {

        }

    }

}

-(void)layoutSubviews
{
    if (!self.autoresizesSubviews)
        return;

    if (self.beginLayoutBlock != nil)
        self.beginLayoutBlock();

    if (!self.isMyLayouting)
    {
        _isMyLayouting = YES;

        if (self.priorAutoresizingMask)
            [super layoutSubviews];

        //得到最佳的sizeClass
        MySizeClass sizeClass;
        if ([UIDevice currentDevice].systemVersion.floatValue < 8)
            sizeClass = MySizeClass_hAny | MySizeClass_wAny;
        else
            sizeClass = (MySizeClass)((self.traitCollection.verticalSizeClass << 2) | self.traitCollection.horizontalSizeClass);

        UIDeviceOrientation ori =   [UIDevice currentDevice].orientation;
        if (UIDeviceOrientationIsPortrait(ori))
            sizeClass |= MySizeClass_Portrait;
        else if (UIDeviceOrientationIsLandscape(ori))
            sizeClass |= MySizeClass_Landscape;
        else;

        self.absPos.sizeClass = [self myBestSizeClass:sizeClass];
        for (UIView *sbv in self.subviews)
        {
            sbv.absPos.sizeClass = [sbv myBestSizeClass:sizeClass];
        }

        //计算布局
        CGRect oldSelfRect = self.frame;
        CGRect newSelfRect = [self calcLayoutRect:CGSizeZero isEstimate:NO pHasSubLayout:nil sizeClass:sizeClass];

        //设置子视图的frame并还原
        for (UIView *sbv in self.subviews)
        {
            if (sbv.absPos.leftPos != CGFLOAT_MAX && sbv.absPos.topPos != CGFLOAT_MAX)
                sbv.frame = sbv.absPos.frame;

            if (sbv.absPos.sizeClass.isHidden)
                sbv.frame = CGRectZero;

            sbv.absPos.sizeClass = [sbv myDefaultSizeClass];
            [sbv.absPos reset];
        }
        self.absPos.sizeClass = [self myDefaultSizeClass];

        //调整自身
        if (!CGRectEqualToRect(oldSelfRect,newSelfRect) && newSelfRect.origin.x != CGFLOAT_MAX)
        {
            self.frame = newSelfRect;
        }

        if (_topBorderLineLayer != nil)
            [_topBorderLineLayer setNeedsLayout];

        if (_bottomBorderLineLayer != nil)
            [_bottomBorderLineLayer setNeedsLayout];

        if (_leftBorderLineLayer != nil)
            [_leftBorderLineLayer setNeedsLayout];

        if (_rightBorderLineLayer != nil)
            [_rightBorderLineLayer setNeedsLayout];

        //这里只用origin.x判断的原因是如果newSelfRect被计算成功则rect中的所有值都不是CGFLOAT_MAX,所以这里选origin.x只是其中一个代表。
        if (newSelfRect.origin.x != CGFLOAT_MAX)
            [self alterScrollViewContentSize:newSelfRect];

        _isMyLayouting = NO;
    }

    if (self.endLayoutBlock != nil)
    {
        self.endLayoutBlock();
        self.beginLayoutBlock = nil;
        self.endLayoutBlock = nil;
    }
}

#pragma mark -- Private Method

-(CGRect)calcLayoutRect:(CGSize)size isEstimate:(BOOL)isEstimate pHasSubLayout:(BOOL*)pHasSubLayout sizeClass:(MySizeClass)sizeClass
{
    CGRect selfRect;
    if (isEstimate)
        selfRect = self.absPos.frame;
    else
    {
        selfRect = self.frame;
        if (size.width != 0)
            selfRect.size.width = size.width;
        if (size.height != 0)
            selfRect.size.height = size.height;
    }

    if (pHasSubLayout != nil)
        *pHasSubLayout = NO;

    return selfRect;

}

-(BOOL)isRelativeMargin:(CGFloat)margin
{
    return margin > 0 && margin < 1;
}

-(void)vertGravity:(MyMarginGravity)vert
        selfHeight:(CGFloat)selfHeight
               sbv:(UIView *)sbv
              rect:(CGRect*)pRect
{
    CGFloat  tm = sbv.topPos.posNumVal.doubleValue;
    CGFloat  cm = sbv.centerYPos.posNumVal.doubleValue;
    CGFloat  bm = sbv.bottomPos.posNumVal.doubleValue;

    CGFloat topMargin;
    CGFloat centerMargin;
    CGFloat bottomMargin;

    CGFloat fixedHeight = self.padding.top + self.padding.bottom;

    if ([self isRelativeMargin:tm])
        topMargin = (selfHeight - fixedHeight) * tm;
    else
        topMargin = tm;

    if ([self isRelativeMargin:cm])
        centerMargin = (selfHeight - fixedHeight) * cm;
    else
        centerMargin = cm;

    if ([self isRelativeMargin:bm])
        bottomMargin = (selfHeight - fixedHeight) * bm;
    else
        bottomMargin = bm;

    topMargin = [sbv.topPos validMargin:topMargin + sbv.topPos.offsetVal];
    centerMargin = [sbv.centerYPos validMargin:centerMargin + sbv.centerYPos.offsetVal];
    bottomMargin = [sbv.bottomPos validMargin:bottomMargin + sbv.bottomPos.offsetVal];

    if (vert == MyMarginGravity_Vert_Fill)
    {

        pRect->origin.y = self.padding.top + topMargin;
        pRect->size.height = [sbv.heightDime validMeasure:selfHeight - self.padding.bottom - bottomMargin - pRect->origin.y];
    }
    else if (vert == MyMarginGravity_Vert_Center)
    {

        pRect->origin.y = (selfHeight - self.padding.top - self.padding.bottom - topMargin - bottomMargin - pRect->size.height)/2 + self.padding.top + topMargin + centerMargin;
    }
    else if (vert == MyMarginGravity_Vert_Window_Center)
    {
        if (self.window != nil)
        {
            pRect->origin.y = (self.window.frame.size.height - topMargin - bottomMargin - pRect->size.height)/2 + topMargin + centerMargin;

            CGPoint pt = pRect->origin;
            pRect->origin.y =  [self.window convertPoint:pt toView:self].y;
        }

    }
    else if (vert == MyMarginGravity_Vert_Bottom)
    {

        pRect->origin.y = selfHeight - self.padding.bottom - bottomMargin - pRect->size.height;
    }
    else if (vert == MyMarginGravity_Vert_Top)
    {
        pRect->origin.y = self.padding.top + topMargin;
    }
    else
    {
        pRect->origin.y = self.padding.top + topMargin;
    }

}

-(void)horzGravity:(MyMarginGravity)horz
         selfWidth:(CGFloat)selfWidth
               sbv:(UIView *)sbv
              rect:(CGRect*)pRect
{
    CGFloat  lm = sbv.leftPos.posNumVal.doubleValue;
    CGFloat  cm = sbv.centerXPos.posNumVal.doubleValue;
    CGFloat  rm = sbv.rightPos.posNumVal.doubleValue;

    CGFloat leftMargin;
    CGFloat centerMargin;
    CGFloat rightMargin;

    CGFloat fixedWidth = self.padding.left + self.padding.right;
    if ([self isRelativeMargin:lm])
        leftMargin = (selfWidth - fixedWidth) * lm;
    else
        leftMargin = lm;

    if ([self isRelativeMargin:cm])
        centerMargin = (selfWidth - fixedWidth) * cm;
    else
        centerMargin = cm;

    if ([self isRelativeMargin:rm])
        rightMargin = (selfWidth - fixedWidth) * rm;
    else
        rightMargin = rm;

    leftMargin = [sbv.leftPos validMargin:leftMargin + sbv.leftPos.offsetVal];
    centerMargin = [sbv.centerXPos validMargin:centerMargin + sbv.centerXPos.offsetVal];
    rightMargin = [sbv.rightPos validMargin:rightMargin + sbv.rightPos.offsetVal];

    if (horz == MyMarginGravity_Horz_Fill)
    {

        pRect->origin.x = self.padding.left + leftMargin;
        pRect->size.width = [sbv.widthDime validMeasure:selfWidth - self.padding.right - rightMargin - pRect->origin.x];
    }
    else if (horz == MyMarginGravity_Horz_Center)
    {
        pRect->origin.x = (selfWidth - self.padding.left - self.padding.right - leftMargin - rightMargin - pRect->size.width)/2 + self.padding.left + leftMargin + centerMargin;
    }
    else if (horz == MyMarginGravity_Horz_Window_Center)
    {
        if (self.window != nil)
        {
            pRect->origin.x = (self.window.frame.size.width - leftMargin - rightMargin - pRect->size.width)/2 + leftMargin + centerMargin;

            CGPoint pt = pRect->origin;
            pRect->origin.x =  [self.window convertPoint:pt toView:self].x;
        }

    }
    else if (horz == MyMarginGravity_Horz_Right)
    {

        pRect->origin.x = selfWidth - self.padding.right - rightMargin - pRect->size.width;
    }
    else if (horz == MyMarginGravity_Horz_Left)
    {
        pRect->origin.x = self.padding.left + leftMargin;
    }
    else
    {
        pRect->origin.x = self.padding.left + leftMargin;
    }
}

-(void)calcMatchParentWidth:(MyLayoutDime*)match selfWidth:(CGFloat)selfWidth leftMargin:(CGFloat)leftMargin centerMargin:(CGFloat)centerMargin rightMargin:(CGFloat)rightMargin leftPadding:(CGFloat)leftPadding rightPadding:(CGFloat)rightPadding rect:(CGRect*)pRect
{

    CGFloat vTotalWidth = 0;

    vTotalWidth = (selfWidth - leftPadding - rightPadding)*match.mutilVal + match.addVal;

    pRect->size.width = [match validMeasure:vTotalWidth - leftMargin - centerMargin - rightMargin];
    pRect->origin.x = (selfWidth - pRect->size.width - leftPadding - rightPadding - leftMargin - rightMargin )/2 + leftPadding + leftMargin + centerMargin;

}

-(void)calcMatchParentHeight:(MyLayoutDime*)match selfHeight:(CGFloat)selfHeight topMargin:(CGFloat)topMargin centerMargin:(CGFloat)centerMargin  bottomMargin:(CGFloat)bottomMargin topPadding:(CGFloat)topPadding bottomPadding:(CGFloat)bottomPadding rect:(CGRect*)pRect
{

    CGFloat vTotalHeight = (selfHeight - topPadding - bottomPadding)*match.mutilVal + match.addVal;

    pRect->size.height = [match validMeasure:vTotalHeight - topMargin - centerMargin - bottomMargin];
    pRect->origin.y = (selfHeight - pRect->size.height - topPadding - bottomPadding - topMargin - bottomMargin )/2 + topPadding + topMargin + centerMargin;

}

-(void)setWrapContentWidthNoLayout:(BOOL)wrapContentWidth
{
    MyBaseLayout *lsc = self.myCurrentSizeClass;
    lsc.wrapContentWidth = wrapContentWidth;
}

-(void)setWrapContentHeightNoLayout:(BOOL)wrapContentHeight
{
    MyBaseLayout *lsc = self.myCurrentSizeClass;
    lsc.wrapContentHeight = wrapContentHeight;
}

- (void)alterScrollViewContentSize:(CGRect)newRect
{
    if (self.adjustScrollViewContentSize && self.superview != nil && [self.superview isKindOfClass:[UIScrollView class]])
    {
        UIScrollView *scrolv = (UIScrollView*)self.superview;
        CGSize contsize = scrolv.contentSize;

        if (contsize.height != newRect.size.height)
            contsize.height = newRect.size.height;
        if (contsize.width != newRect.size.width)
            contsize.width = newRect.size.width;

        scrolv.contentSize = contsize;

    }
}

@end


text:
package com.spring.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by renqun.yuan on 2015/11/27.
 */
@Controller
@RequestMapping("/users")
public class ModelAndViewController {

    @RequestMapping("/queryUser")
    public ModelAndView queryUser() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("queryUser");
        return modelAndView;
    }
}


text:
package com.ctrip.xpipe.redis.proxy.integrate;

import com.ctrip.xpipe.concurrent.AbstractExceptionLogTask;
import com.ctrip.xpipe.redis.proxy.DefaultProxyServer;
import com.ctrip.xpipe.redis.proxy.TestProxyConfig;
import com.google.common.collect.Lists;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import org.junit.*;

import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author chen.zhu
 * <p>
 * May 26, 2018
 */

public class TestTLSWithTwoProxy extends AbstractProxyIntegrationTest {

    private DefaultProxyServer server1, server2;

    private static final String PROXY_HOST = "127.0.0.1";

    private static final int PROXY_PORT1 = randomPort(), PROXY_PORT2 = randomPort();

    @Before
    public void beforeTestMassTCPPacketWithOneProxyServer() throws Exception {
        System.setProperty("server.port", "9992");
        server1 = new DefaultProxyServer().setConfig(new TestProxyConfig().setFrontendTlsPort(-1).setFrontendTcpPort(PROXY_PORT1));
        prepare(server1);
        server1.start();

        server2 = new DefaultProxyServer().setConfig(new TestProxyConfig().setFrontendTlsPort(PROXY_PORT2).setFrontendTcpPort(randomPort()));
        prepareTLS(server2);
        server2.start();
    }

    @After
    public void afterTestMassTCPPacketWithOneProxyServer() throws Exception {
        server1.stop();
        server2.stop();
        System.gc();
        System.gc();
        Thread.sleep(2000);
    }

    @Test
    public void testStability() throws TimeoutException, InterruptedException, ExecutionException {
        int port = randomPort();
        String protocol = generateProxyProtocol(port);
        String message = randomString(10000);

        ChannelFuture clientFuture = clientBootstrap().connect(PROXY_HOST, PROXY_PORT1);

        ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(message.getBytes().length);
        AtomicReference<ByteBuf> byteBufAtomicReference = new AtomicReference<>(byteBuf);
        ChannelFuture receiveServer = startReceiveServer(port, byteBufAtomicReference);

        final String total = protocol + message;
        int index = 2;
        String sendout = total.substring(0, index);
        waitConditionUntilTimeOut(()->clientFuture.channel().isActive(), 100);
        write(clientFuture, sendout);

        for(int i = 0; i < 2; i++) {
            write(clientFuture, total.substring(index, ++index));
        }

        while(index < total.length()) {
            int pivot = 0;
            do {
                pivot = randomInt(index + 1, total.length() + 1);
            } while(pivot > total.length());
            sendout = total.substring(index, pivot);
            write(clientFuture, sendout);
            index = pivot;
            Thread.sleep(5);
        }
        Thread.sleep(1000 * 2);

        receiveServer.channel().close();

        ByteBuf expected = Unpooled.wrappedBuffer(message.getBytes());

        waitConditionUntilTimeOut(() -> {
            int rst = ByteBufUtil.compare(expected, byteBufAtomicReference.get());
            logger.info("[testStability] cmp rst: {}", rst);
            return 0 == rst;
        }, 10000, 1000);
        expected.release();
    }

    @Test
    public void testStabilityWithCompressAndSSL() throws TimeoutException, InterruptedException, ExecutionException {
        ((TestProxyConfig)server1.getConfig()).setCompress(true);
        ((TestProxyConfig)server1.getResourceManager().getProxyConfig()).setCompress(true);
        testStability();
    }

    @Ignore
    @Test
    public void testMultiThreadStabilityWithCompressAndSSL() throws Exception {
        int N = 20;

        ((TestProxyConfig)server1.getConfig()).setCompress(true);
        ((TestProxyConfig)server1.getResourceManager().getProxyConfig()).setCompress(true);

        List<String> samples = Lists.newArrayList();
        List<AtomicReference<ByteBuf>> result = Lists.newArrayList();
        List<String> protocols = Lists.newArrayList();

        for(int i = 0; i < N; i++) {

            String message = randomString(1024 * 10);
            samples.add(message);
            ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.ioBuffer(1024 * 10);
            result.add(new AtomicReference<>(byteBuf));
        }

        for(int i = 0; i < N; i++) {
            int port = randomPort();
            String protocol = generateProxyProtocol(port);
            protocols.add(protocol);
            startReceiveServer(port, result.get(i));
        }

        CountDownLatch latch = new CountDownLatch(N);
        for(int i = 0; i < N; i++) {
            final String total = protocols.get(i) + samples.get(i);

            new Thread(new AbstractExceptionLogTask() {
                @Override
                public void doRun() throws Exception{
                    ChannelFuture clientFuture = clientBootstrap().connect(PROXY_HOST, PROXY_PORT1);
                    int index = 2;
                    String sendout = total.substring(0, index);
                    waitConditionUntilTimeOut(()->clientFuture.channel().isActive(), 200);
                    write(clientFuture, sendout);

                    for(int i = 0; i < 2; i++) {
                        write(clientFuture, total.substring(index, ++index));
                    }

                    while(index < total.length()) {
                        int pivot = 0;
                        do {
                            pivot = randomInt(index + 1, total.length() + 1);
                        } while(pivot > total.length());
                        sendout = total.substring(index, pivot);
                        write(clientFuture, sendout);
                        index = pivot;
                        Thread.sleep(5);
                    }
                    latch.countDown();
                }
            }).start();
        }

        latch.await();
        sleep(10 * 1000);

        for(int i = 0; i < N; i++) {
            Assert.assertEquals(samples.get(i), result.get(i).get().toString(Charset.defaultCharset()));
            result.get(i).get().release();
        }
    }

    @Ignore
    @Test
    //Manullay test
    public void testStabilityWithN() throws TimeoutException, InterruptedException {
        int N = 50;
        int[] port = new int[N];
        String[] protocol = new String[N], message = new String[N], total = new String[N];
        AtomicReference<ByteBuf>[] references = new AtomicReference[N];
        ChannelFuture[] clientFuture = new ChannelFuture[N], receiveServer = new ChannelFuture[N];

        for(int i = 0; i < N; i++) {
            port[i] = randomPort();
            protocol[i] = generateProxyProtocol(port[i]);
            message[i] = randomString(1000);

            clientFuture[i] = clientBootstrap().connect(PROXY_HOST, PROXY_PORT1);

            ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(1024);
            references[i] = new AtomicReference<>(byteBuf);
            receiveServer[i] = startReceiveServer(port[i], references[i]);

            total[i] = protocol[i] + message[i];
        }

        for(int i = 0; i < N; i++) {
            int finalI = i;
            new Thread(new AbstractExceptionLogTask() {
                @Override
                protected void doRun() throws Exception {
                    int index = 2;
                    String sendout = total[finalI].substring(0, index);
                    write(clientFuture[finalI], sendout);

                    for (int j = 0; j < 2; j++) {
                        write(clientFuture[finalI], total[finalI].substring(index, ++index));
                    }

                    while (index < total[finalI].length()) {
                        int pivot = 0;
                        do {
                            pivot = randomInt(index + 1, total[finalI].length() + 1);
                        } while (pivot > total[finalI].length());
                        sendout = total[finalI].substring(index, pivot);
                        write(clientFuture[finalI], sendout);
                        index = pivot;
                        try {
                            Thread.sleep(5);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();

        }

        Thread.sleep(1500 * N/100 + 2000);

        for(int i = 0; i < N; i++) {
            receiveServer[i].channel().close();

            ByteBuf expected = UnpooledByteBufAllocator.DEFAULT.buffer().writeBytes(message[i].getBytes());

            Assert.assertEquals(0, ByteBufUtil.compare(expected, references[i].get()));
        }
    }

    private String generateProxyProtocol(int port) {
        return String.format("+PROXY ROUTE PROXYTLS://127.0.0.1:%d TCP://127.0.0.1:%d;FORWARD_FOR 127.0.0.1:80\r\n", PROXY_PORT2, port);
    }
}


text:
<?php

namespace Kappa\Gravatar;

use Kappa\FileSystem\File;
use Nette\Object;
use Nette\Utils\DateTime;

/**
 * Class CacheStorage
 * @package Kappa\Gravatar
 */
class CacheStorage extends Object
{
	/** @var string */
	private $tempDirectory;

	/** @var string */
	private $publicDir;

	/**
	 * @param string $path
	 * @param string $publicDir
	 * @throws DirectoryNotFoundException
	 */
	public function __construct($path, $publicDir)
	{
		$this->tempDirectory = $path;
		$this->publicDir = $publicDir;
	}

	/**
	 * @param string $url
	 * @return string
	 * @throws DirectoryNotFoundException
	 */
	public function getAvatarCache($url)
	{
		if (!is_dir($this->tempDirectory)) {
			throw new DirectoryNotFoundException("Cache directory '{$this->tempDirectory}' has not been found");
		}
		if (!is_dir($this->publicDir)) {
			throw new DirectoryNotFoundException("Public directory '{$this->publicDir}' has not been found");
		}

		return $this->invalidateAvatarCache($url)->getInfo()->getRelativePath($this->publicDir);
	}

	/**
	 * @param string $url
	 * @return File
	 */
	private function invalidateAvatarCache($url)
	{
		$headers = get_headers($url);
		$lastUpdate = str_replace('Last-Modified: ', '', $headers[8]);
		$datetime = new DateTime($lastUpdate);
		$cacheFile = $this->getCachePath($url);
		if (is_file($cacheFile)) {
			$file = File::open($cacheFile);
			if ($datetime->getTimestamp() > $file->getInfo()->getMTime()) {
				return $this->createAvatarCache($url);
			} else {
				return $file;
			}
		} else {
			return $this->createAvatarCache($url);
		}
	}

	/**
	 * @param string $url
	 * @return File
	 */
	private function createAvatarCache($url)
	{
		$file = File::fromUrl($url, $this->getCachePath($url));

		return $file;
	}

	/**
	 * @param string $url
	 * @return string
	 */
	private function getCachePath($url)
	{
		return $this->tempDirectory . DIRECTORY_SEPARATOR . $this->getCacheName($url) . '.png';
	}

	/**
	 * @param string $url
	 * @return string
	 */
	private function getCacheName($url)
	{
		return md5($url);
	}
}


text:
package mocks

import (
	"testing"

	proto "github.com/hyperledger/fabric-protos-go/gossip"
	"github.com/hyperledger/fabric/gossip/api"
	"github.com/hyperledger/fabric/gossip/common"
	"github.com/hyperledger/fabric/gossip/discovery"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
)

func TestGossipMock(t *testing.T) {
	g := GossipMock{}
	mkChan := func() <-chan *proto.GossipMessage {
		c := make(chan *proto.GossipMessage, 1)
		c <- &proto.GossipMessage{}
		return c
	}
	g.On("Accept", mock.Anything, false).Return(mkChan(), nil)
	a, b := g.Accept(func(o interface{}) bool {
		return true
	}, false)
	require.Nil(t, b)
	require.NotNil(t, a)
	require.Panics(t, func() {
		g.SuspectPeers(func(identity api.PeerIdentityType) bool { return false })
	})
	require.Panics(t, func() {
		g.Send(nil, nil)
	})
	require.Panics(t, func() {
		g.Peers()
	})
	g.On("PeersOfChannel", mock.Anything).Return([]discovery.NetworkMember{})
	require.Empty(t, g.PeersOfChannel(common.ChannelID("A")))

	require.Panics(t, func() {
		g.UpdateMetadata([]byte{})
	})
	require.Panics(t, func() {
		g.Gossip(nil)
	})
	require.NotPanics(t, func() {
		g.UpdateLedgerHeight(0, common.ChannelID("A"))
		g.Stop()
		g.JoinChan(nil, common.ChannelID("A"))
	})
}


text:
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'sub-home',
    templateUrl: './sub-home.html',
})
export class SubHomeComponent implements OnInit {
    private value: string;

    constructor() {
    }

    ngOnInit() {
    }
}


text:
REFACTORING

1. Explain your improvement process, and why you chose each step.

  Well, the first step was understanding the code that was written.  Variables
  named `q` and `ys` (which I still have no idea what it stands for) seemed to
  hold arbitrary values and go through convoluted modifications.

  For example, on line 8:

  `ys = data.sort[q.ceil-1..(3*q).floor]`

  Why would you make a sub-selection using the ceiling of the lower bound but
  the floor of the upper bound?  And why is it `3*q`?  This is in addition to
  the strange `factor` variable (which is a modifier you apply to the upper and
    lower bounds of the IQR), which seemed excessively complicated.

  After reading the Wikipedia article on Interquartile Mean
  (http://en.wikipedia.org/wiki/Interquartile_mean), I began to grasp that `ys`
  is the IQR, which is gathered using an overly complicated means of truncating
  the floored size of each quartile (e.g. for 9 entries, each quartile is 2.25 -
  hence, drop the lowest two and highest two).

  The variable `factor` then, I deduced was the "partial observation"
  multiplier, as it was being applied to the lower and upper bounds.

  Long story short, the biggest task that needed refactoring was the naming
  conventions, just so I could understand what was going on in the code.

  After that, I looked for improvements:

  * `inject(0, :+)` was redundant, it could just be `inject(:+)`,
  * creating the IQR could just be `data.sort[q.floor..-q.floor]`,
  * breaking up the complicated assignment of `mean`,
  * etc.

  Last, I decided to make the program object-oriented because it's more
  readable, a better separation of concerns, and uses only a minuscule amount of
  extra overhead.  On top of that, I decided to gemify it because I could use
  the practice.

    * First, I created a data structure, which is pretty much just a fancy array.
    * The structure should contain the logic for calculating things like IQR,
      IQM, etc. because it holds the data.
    * I added a control class (MeanGenerator) which would handle opening the
      file and putting the items into the data structure.
    * Last, I wrote the main part of the module which would create the
      MeanGenerator using the given file to kick the process off.

  I ran both versions (old and new) and found that one took 10'22.27" whereas
  the other took 10'22.65" - a negligible difference.

  Finally, I added specs.  Probably should have started with specs, but given
  that the only interaction you had with the original code was output, I
  couldn't exactly hook into that.  By making the code object-oriented, I gave
  myself objects to work with so I could stop and verify that the interquartile
  range of the data_set object was really what I expected it to be.

2. What improvements did you make to ensure that future developers could quickly and easily understand this code?

  Well, my philosophy with comments is that your code should be like a circuit
  breaker.  If there were comments above everything, nobody would read them all.
  You're supposed to make the code explain itself, and where that wasn't
  possible (such as explaining what the variable that replaces `factor` stood
  for), I added a brief comment and linked to a page with more info.

  Between sane variable/method names, declaration of methods in a logical order,
  lines under 80 columns, and single-purpose methods, I think that someone could
  look at my code and understand what it does, even if they have never worked
  with interquartile means before.

  Also, tests.  If they want to improve upon the code, they have a test file
  that they can run to make sure nothing breaks.

  To run tests, just do `rspec` in the main directory.


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:background="@drawable/treeview_first_level_clickable_blue_bg"
    android:orientation="vertical">

    <LinearLayout
        android:gravity="center_vertical"
        android:id="@+id/node_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/arrow_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:src="@drawable/treeview_ic_keyboard_arrow_right_white_24px" />

        <ImageView
            android:id="@+id/icon"
            android:layout_marginRight="10dp"
            android:layout_width="75dp"
            android:layout_height="75dp"
            android:layout_weight="0"
            />

        <TextView
            android:id="@+id/node_name_view"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:fontFamily="monospace"
            android:textSize="15sp"
            android:layout_weight="1"
            android:text="Tree Node" />

        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/checkBox"
            android:layout_width="35dp"
            android:layout_height="35dp"
            android:layout_weight="0"
            android:layout_marginRight="10dp" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_alignParentBottom="true"
        android:background="#ffffff"></View>
</RelativeLayout>


text:
package com.crowdmap.java.sdk.service;

import com.crowdmap.java.sdk.json.Comments;
import com.crowdmap.java.sdk.json.Maps;
import com.crowdmap.java.sdk.json.PostTags;
import com.crowdmap.java.sdk.json.Posts;
import com.crowdmap.java.sdk.json.Response;
import com.crowdmap.java.sdk.model.form.PostForm;
import com.crowdmap.java.sdk.service.api.PostInterface;

import retrofit.RestAdapter;
import retrofit.mime.TypedString;

/**
 * Service for interacting with Crowdmap post API
 */
public class PostService extends CrowdmapService<PostService> {

    PostInterface mPostInterface;

    public PostService(RestAdapter restAdapter) {
        super(restAdapter);
        mPostInterface = restAdapter.create(PostInterface.class);
    }

    /**
     * Get all posts across crowdmap - GET /posts
     */
    public Posts getPosts() {
        return mPostInterface.getPosts(limit, offset);
    }

    /**
     * Get a specific post. GET /posts/:post_id
     *
     * @param postId The post ID
     * @return The {@link com.crowdmap.java.sdk.json.Posts} response of the specific post
     */
    public Posts getPosts(long postId) {
        checkId(postId);
        return mPostInterface.getPosts(postId, limit, offset);
    }

    /**
     * Get all of the maps a specific post is featured on. GET /posts/:post_id/maps
     *
     * @param postId The post ID
     * @return The {@link com.crowdmap.java.sdk.json.Maps} response for the specific post
     */
    public Maps getPostMaps(long postId) {
        checkId(postId);
        return mPostInterface.getPostMaps(postId, limit, offset);
    }

    /**
     * Gell all the comments associated with a specific post.
     *
     * GET /posts/:post_id/comments/
     *
     * @param postId The post ID
     * @return The {@link com.crowdmap.java.sdk.json.Comments} response of the specific post
     */
    public Comments getPostComments(long postId) {
        checkId(postId);
        return mPostInterface.getPostComments(postId, limit, offset);
    }

    /**
     * Create a new post as an authenticated user.
     *
     * @param form The post fields to submitted.
     * @return The post created
     */
    //TODO: improve the paramter. Use MapForm field instead
    public Posts createPost(PostForm form,
            String sessionToken) {

        return mPostInterface
                .createPost(form.getMessage(), form.getPublic() ? 1 : 0, form.getLocationName(),
                        form.getLat(), form.getLon(), form.getGeometry(), form.getFsqVenueId(),

                        form.getTweet(), form.getMapId(), form.getExternalUrl(), form.getMedia(),
                        new TypedString(sessionToken));
    }

    public Response deletePost(long postId, String sessionToken) {
        checkId(postId);
        return mPostInterface.deletePost(postId, sessionToken);
    }

    /**
     * Update an existing post
     *
     * @param postId The ID of the post to be updated
     * @param form   The post fields
     * @return The post updated
     */
    public Posts updatePost(long postId, PostForm form,
            String sessionToken) {
        return mPostInterface
                .updatePost(postId, form.getMessage(), form.getPublic() ? 1 : 0, form.getLocationName(),
                        form.getLat(), form.getLon(), form.getGeometry(), form.getFsqVenueId(),

                        form.getTweet(), form.getMapId(), form.getExternalUrl(), form.getMedia(),
                        new TypedString(sessionToken));
    }

    /**
     * Get tags attached to a post
     *
     * @param tag The name of the tag. This can be CSV
     * @return The tags attached to a post
     */
    public PostTags getPostTag(String tag) {
        return mPostInterface.getPostTag(tag, limit, offset);
    }

    /**
     * Like a particular post
     *
     * @param postId The post to like
     * @return The liked posts.
     */
    public Posts likePost(long postId, String sessionToken) {
        checkId(postId);
        return mPostInterface.likePost(postId, sessionToken);
    }

    /**
     * Un-like a particular post
     *
     * @param postId The post to un-like
     * @return The un-liked posts
     */
    public Posts unLikePost(long postId, String sessionToken) {
        return mPostInterface.unLikePost(postId, sessionToken);
    }

    /**
     * Get the comments on a post from the context of a map the post is featured on. GET
     * /posts/:post_id/comments/:map_id
     *
     * @param postId The Post ID
     * @param mapId  The map ID
     * @return The {@link com.crowdmap.java.sdk.json.Comments} response of the specific post
     */
    public Comments getPostComments(long postId, long mapId) {
        checkId(postId);
        checkId(mapId);
        return mPostInterface.getPostComments(postId, mapId, limit, offset);
    }

    /**
     * Add a comment on a post.
     *
     * @param postId  The ID of the post to add the comment to.
     * @param mapId   The map ID
     * @param comment The comment form
     * @return The posted comment
     */
    public Comments postComment(long postId, long mapId, String comment, String sessionToken) {
        checkId(postId);
        checkId(mapId);
        return mPostInterface.postComment(postId, mapId, comment, sessionToken);
    }

    public Comments deletePostComments(long postId, long commentId, String sessionToken) {
        checkId(postId);
        checkId(commentId);
        return mPostInterface.deletePostComments(postId, commentId, sessionToken);
    }

    /**
     * Delete a post from a map
     *
     * @param postId The ID of the post to be deleted.
     * @return Post minus the deleted post
     */
    public Posts deletePostFromMap(long postId, String sessionToken) {
        checkId(postId);
        return mPostInterface.deletePostFromMap(postId, sessionToken);
    }

    /**
     * Add an existing post to a map
     *
     * @return Post
     */
    public Posts createPostMap(long postId, String sessionToken) {
        checkId(postId);
        return mPostInterface.createPostMap(postId, sessionToken);
    }
}


text:
#ifndef _VM_PAGE_H_
#define _VM_PAGE_H_

#include <kernel/spinlock.h>
#include <kernel/list.h>
#include <kernel/vm/vm_types.h>
#include <kernel/vm/vm_object.h>

typedef struct {
    struct vm_page_status_s {           // Status bits indicating the state of this page
        unsigned int wired_count:16;    // How many virtual maps have wired this page
        unsigned int is_referenced:1;   // Has this page been referenced recently
        unsigned int is_dirty:1;        // Has this page been modified
        unsigned int is_active:1;       // Is this page being used i.e. mapped in some virtual map
        unsigned int is_busy:1;         // This page is busy for I/O
    } status;
    list_node_t ll_onode;               // Object/offset hash table bucket linkage
    list_node_t ll_rnode;               // Linked list of resident pages in an object or part of the buddy free list
    vm_object_t *object;                // VM object this page belongs to if any
    vm_offset_t offset;                 // Offset in that VM object that this page refers to
} vm_page_t;

// Initialization of vm_page module after pmap has been initialized and kernel is running in virtual memory mode
void vm_page_init(void);

// Lookup a vm_page given a object and offset
vm_page_t* vm_page_lookup(vm_object_t *object, vm_offset_t offset);

// Allocate or free a contiguous range of pages
vm_page_t* vm_page_alloc_contiguous(size_t num_pages, vm_object_t *object, vm_offset_t offset);
void vm_page_free_contiguous(vm_page_t *pages, size_t num_pages);

// Allocate or free one page
vm_page_t* vm_page_alloc(vm_object_t *object, vm_offset_t offset);
void vm_page_free(vm_page_t *page);

// Increase/decrease the wire count on the page
void vm_page_wire(vm_page_t *page);
void vm_page_unwire(vm_page_t *page);

// Convert a page to a physical address and vice versa
paddr_t vm_page_to_pa(vm_page_t *page);
vm_page_t* vm_page_from_pa(paddr_t pa);

// Reserve pages that have been allocated but not through vm_page_alloc*. This should be used by the virtual memory
// system during boot time initialization to tell the page system what pages are being used by the kernel. These pages
// are wired. These pages should be added to the provided kernel memory object
vm_page_t* vm_page_reserve_pa(paddr_t pa);

#endif // _VM_PAGE_H_


text:
<?php
use DF\Phalcon\Application;

error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);

require __DIR__ . '/../app/bootstrap.php';

try
{
    $application = new \DF\Phalcon\Application($di);
    $application->useImplicitView(true);

    $application->bootstrap()->run();
}
catch(\Exception $e)
{
    \DF\Phalcon\ErrorHandler::handle($e, $di);
}


text:
var Audio, Element,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

Element = require("../js/element");

Audio = (function(_super) {
  __extends(Audio, _super);
  function Audio() { Audio.__super__.constructor.call(this, "audio"); }
  Audio.prototype.reflect = true;
  return Audio;
})(Element);

module.exports = Audio;