text:
<!DOCTYPE html>

    <title>Kingfisher Class Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>

Kingfisher Docs (78% documented)

View on GitHub

Install in Dash

        Kingfisher Reference

        Kingfisher Class Reference

            Classes

                AnimatedImageView

                ImageCache

                – CacheCheckResult

                ImageDownloader

                ImagePrefetcher

                Kingfisher

                KingfisherManager

                RetrieveImageTask

            Global Variables

                KingfisherDiskCacheCleanedHashKey

                KingfisherErrorDomain

                KingfisherErrorStatusCodeKey

            Enums

                CacheType

                ContentMode

                ImageProcessItem

                ImageTransition

                ImageTransition

                IndicatorType

                KingfisherError

                KingfisherOptionsInfoItem

            Extensions

                CGSize

                Collection

                Data

                Notification

                – Name

                String

                URL

            Functions

                >>(_:_:)

            Protocols

                AuthenticationChallengeResponsable

                CIImageProcessor

                CacheSerializer

                ImageDownloadRequestModifier

                ImageDownloaderDelegate

                ImageProcessor

                Indicator

                KingfisherCompatible

                Placeholder

                Resource

            Structs

                AnyModifier

                BlackWhiteProcessor

                BlurImageProcessor

                CGSizeProxy

                ColorControlsProcessor

                CroppingImageProcessor

                DataProxy

                DefaultCacheSerializer

                DefaultImageProcessor

                Filter

                FormatIndicatedCacheSerializer

                ImageResource

                OverlayImageProcessor

                RectCorner

                ResizingImageProcessor

                RetrieveImageDownloadTask

                RoundCornerImageProcessor

                StringProxy

                TintImageProcessor

            Typealiases

                ImageDownloaderCompletionHandler

                ImageDownloaderProgressBlock

                KingfisherOptionsInfo

                PrefetcherCompletionHandler

                PrefetcherProgressBlock

                RetrieveImageDiskTask

                Transformer

Kingfisher

Undocumented

                    base

Undocumented

                        Show on GitHub

                    init(_:)

Undocumented

                        Show on GitHub

                    normalized

Normalize the image. This method does nothing in OS X.

                    normalized

Normalize the image. This method will try to redraw an image with orientation and scale considered.

Declaration

Swift

public var normalized: Image

Return Value

The normalized image with orientation set to up and correct scale.

                        Show on GitHub

PNG

                    pngRepresentation()

Undocumented

                        Show on GitHub

JPEG

                    jpegRepresentation(compressionQuality:)

Undocumented

                        Show on GitHub

GIF

                    gifRepresentation()

Undocumented

                        Show on GitHub

Round Corner

                    image(withRoundRadius:fit:roundingCorners:backgroundColor:)

Create a round corner image based on self.

Note

This method only works for CG-based image.

Declaration

Swift

public func image(withRoundRadius radius: CGFloat,
                      fit size: CGSize,
                      roundingCorners corners: RectCorner = .all,
                      backgroundColor: Color? = nil) -> Image

Parameters

                                radius

The round corner radius of creating image.

                                size

The target size of creating image.

                                corners

The target corners which will be applied rounding.

                                backgroundColor

The background color for the output image

Return Value

An image with round corner of self.

                        Show on GitHub

Resize

                    resize(to:)

Resize self to an image of new size.

Note

This method only works for CG-based image.

Declaration

Swift

public func resize(to size: CGSize) -> Image

Parameters

                                size

The target size.

Return Value

An image with new size.

                        Show on GitHub

                    resize(to:for:)

Resize self to an image of new size, respecting the content mode.

Declaration

Swift

public func resize(to size: CGSize, for contentMode: ContentMode) -> Image

Parameters

                                size

The target size.

                                contentMode

Content mode of output image should be.

Return Value

An image with new size.

                        Show on GitHub

                    crop(to:anchorOn:)

Undocumented

                        Show on GitHub

Blur

                    blurred(withRadius:)

Create an image with blur effect based on self.

Note

This method only works for CG-based image.

Declaration

Swift

public func blurred(withRadius radius: CGFloat) -> Image

Parameters

                                radius

The blur radius should be used when creating blur effect.

Return Value

An image with blur effect applied.

                        Show on GitHub

Overlay

                    overlaying(with:fraction:)

Create an image from self with a color overlay layer.

Note

This method only works for CG-based image.

Declaration

Swift

public func overlaying(with color: Color, fraction: CGFloat) -> Image

Parameters

                                color

The color should be use to overlay.

                                fraction

Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.

Return Value

An image with a color overlay applied.

                        Show on GitHub

Tint

                    tinted(with:)

Create an image from self with a color tint.

Declaration

Swift

public func tinted(with color: Color) -> Image

Parameters

                                color

The color should be used to tint self

Return Value

An image with a color tint applied.

                        Show on GitHub

Color Control

                    adjusted(brightness:contrast:saturation:inputEV:)

Create an image from self with color control.

Declaration

Swift

public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image

Parameters

                                brightness

Brightness changing to image.

                                contrast

Contrast changing to image.

                                saturation

Saturation changing to image.

                                inputEV

InputEV changing to image.

Return Value

An image with color control applied.

                        Show on GitHub

                    apply(_:)

Apply a Filter containing CIImage transformer to self.

Note

Only CG-based images are supported. If any error happens during transforming, self will be returned.

Declaration

Swift

public func apply(_ filter: Filter) -> Image

Parameters

                                filter

The filter used to transform self.

Return Value

A transformed image by input Filter.

                        Show on GitHub

                    shared

Undocumented

                        Show on GitHub

                    setImage(with:placeholder:options:progressBlock:completionHandler:)

Set an image with a resource, a placeholder image, options, progress handler and completion handler.

Note

Both the progressBlock and completionHandler will be invoked in main thread.
The CallbackDispatchQueue specified in optionsInfo will not be used in callbacks of this method.

If resource is nil, the placeholder image will be set and
completionHandler will be called with both error and image being nil.

Declaration

Swift

public func setImage(with resource: Resource?,
                         placeholder: Placeholder? = nil,
                         options: KingfisherOptionsInfo? = nil,
                         progressBlock: DownloadProgressBlock? = nil,
                         completionHandler: CompletionHandler? = nil) -> RetrieveImageTask

Parameters

                                resource

Resource object contains information such as cacheKey and downloadURL.

                                placeholder

A placeholder image when retrieving the image at URL.

                                options

A dictionary could control some behaviors. See KingfisherOptionsInfo for more.

                                progressBlock

Called when the image downloading progress gets updated.

                                completionHandler

Called when the image retrieved and set.

Return Value

A task represents the retrieving process.

                        Show on GitHub

                    cancelDownloadTask()

Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.

Declaration

Swift

public func cancelDownloadTask()

                        Show on GitHub

                    webURL

Get the image URL binded to this image view.

Declaration

Swift

public var webURL: URL?

                        Show on GitHub

                    indicatorType

Holds which indicator type is going to be used.
Default is .none, means no indicator will be shown.

Declaration

Swift

public var indicatorType: IndicatorType

                        Show on GitHub

                    indicator

Holds any type that conforms to the protocol Indicator.
The protocol Indicator has a view property that will be shown when loading an image.
It will be nil if indicatorType is .none.

Declaration

Swift

public fileprivate(set) var indicator: Indicator?

                        Show on GitHub

                    placeholder

Undocumented

                        Show on GitHub

                    setImage(with:for:placeholder:options:progressBlock:completionHandler:)

Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and
completion handler.

Note

Both the progressBlock and completionHandler will be invoked in main thread.
The CallbackDispatchQueue specified in optionsInfo will not be used in callbacks of this method.

If resource is nil, the placeholder image will be set and
completionHandler will be called with both error and image being nil.

Declaration

Swift

public func setImage(with resource: Resource?,
                         for state: UIControlState,
                         placeholder: UIImage? = nil,
                         options: KingfisherOptionsInfo? = nil,
                         progressBlock: DownloadProgressBlock? = nil,
                         completionHandler: CompletionHandler? = nil) -> RetrieveImageTask

Parameters

                                resource

Resource object contains information such as cacheKey and downloadURL.

                                state

The state that uses the specified image.

                                placeholder

A placeholder image when retrieving the image at URL.

                                options

A dictionary could control some behaviors. See KingfisherOptionsInfo for more.

                                progressBlock

Called when the image downloading progress gets updated.

                                completionHandler

Called when the image retrieved and set.

Return Value

A task represents the retrieving process.

                        Show on GitHub

                    cancelImageDownloadTask()

Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.

Declaration

Swift

public func cancelImageDownloadTask()

                        Show on GitHub

                    setBackgroundImage(with:for:placeholder:options:progressBlock:completionHandler:)

Set the background image to use for a specified state with a resource,
a placeholder image, options progress handler and completion handler.

Note

Both the progressBlock and completionHandler will be invoked in main thread.
The CallbackDispatchQueue specified in optionsInfo will not be used in callbacks of this method.

If resource is nil, the placeholder image will be set and
completionHandler will be called with both error and image being nil.

Declaration

Swift

public func setBackgroundImage(with resource: Resource?,
                                   for state: UIControlState,
                                   placeholder: UIImage? = nil,
                                   options: KingfisherOptionsInfo? = nil,
                                   progressBlock: DownloadProgressBlock? = nil,
                                   completionHandler: CompletionHandler? = nil) -> RetrieveImageTask

Parameters

                                resource

Resource object contains information such as cacheKey and downloadURL.

                                state

The state that uses the specified image.

                                placeholder

A placeholder image when retrieving the image at URL.

                                options

A dictionary could control some behaviors. See KingfisherOptionsInfo for more.

                                progressBlock

Called when the image downloading progress gets updated.

                                completionHandler

Called when the image retrieved and set.

Return Value

A task represents the retrieving process.

                        Show on GitHub

                    cancelBackgroundImageDownloadTask()

Cancel the background image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.

Declaration

Swift

public func cancelBackgroundImageDownloadTask()

                        Show on GitHub

                    webURL(for:)

Get the image URL binded to this button for a specified state.

Declaration

Swift

public func webURL(for state: UIControlState) -> URL?

Parameters

                                state

The state that uses the specified image.

Return Value

Current URL for image.

                        Show on GitHub

                    backgroundWebURL(for:)

Get the background image URL binded to this button for a specified state.

Declaration

Swift

public func backgroundWebURL(for state: UIControlState) -> URL?

Parameters

                                state

The state that uses the specified background image.

Return Value

Current URL for background image.

                        Show on GitHub

© 2017 Wei Wang. All rights reserved. (Last updated: 2017-09-28)

Generated by jazzy ♪♫ v0.8.3, a Realm project.


text:
#ifndef RMF_INTERNAL_SINGLE_AVRO_FILE_H
#define RMF_INTERNAL_SINGLE_AVRO_FILE_H

#include "AllJSON.h"
#include <boost/shared_ptr.hpp>
#include <string>
#include <utility>
#include <vector>

#include "AvroKeysAndCategories.h"
#include "RMF/ID.h"
#include "RMF/config.h"
#include "RMF/constants.h"
#include "RMF/enums.h"
#include "RMF/infrastructure_macros.h"
#include "RMF/internal/SharedData.h"

RMF_ENABLE_WARNINGS

namespace RMF {
namespace avro_backend {

class SingleAvroFile : public AvroKeysAndCategories {
  RMF_avro_backend::All all_;
  bool dirty_;
  bool text_;

  boost::shared_ptr<std::vector<char> > buffer_;

  RMF_avro_backend::Data null_frame_data_;
  RMF_avro_backend::Data null_static_frame_data_;

  RMF_avro_backend::Node null_frame_real_data_;

  // begin specific data
 protected:
  const RMF_avro_backend::Data& get_frame_data(Category cat,
                                               FrameID frame) const {
    std::string category = get_name(cat);
    std::map<std::string, std::vector<RMF_avro_backend::Data> >::const_iterator
        it = all_.category.find(category);
    if (it == all_.category.end()) {
      return frame == ALL_FRAMES ? null_static_frame_data_ : null_frame_data_;
    }
    unsigned int index;
    if (frame == ALL_FRAMES)
      index = 0;
    else
      index = frame.get_index() + 1;
    if (it->second.size() <= static_cast<unsigned int>(index)) {
      return frame == ALL_FRAMES ? null_static_frame_data_ : null_frame_data_;
    } else {
      return it->second[index];
    }
  }

  RMF_avro_backend::Data& access_frame_data(Category cat, FrameID frame) {
    std::string category = get_name(cat);
    dirty_ = true;
    unsigned int index;
    if (frame == ALL_FRAMES)
      index = 0;
    else
      index = frame.get_index() + 1;
    while (all_.category[category].size() <= static_cast<unsigned int>(index)) {
      int cur = all_.category[category].size() - 1;
      all_.category[category].push_back(RMF_avro_backend::Data());
      all_.category[category].back().frame = cur;
    }
    return all_.category[category][index];
  }

  const RMF_avro_backend::Node& get_node(NodeID node) const {
    return all_.nodes[node.get_index()];
  }

  const std::vector<RMF_avro_backend::Node>& get_nodes_data() const {
    return all_.nodes;
  }

  RMF_avro_backend::Node& access_node(NodeID node) {
    dirty_ = true;
    if (all_.nodes.size() <= static_cast<unsigned int>(node.get_index())) {
      all_.nodes.resize(node.get_index() + 1);
    }
    return all_.nodes[node.get_index()];
  }

  const RMF_avro_backend::File& get_file() const { return all_.file; }

  RMF_avro_backend::File& access_file() {
    dirty_ = true;
    return all_.file;
  }

  const RMF_avro_backend::Node& get_frame(FrameID i) const {
    if (i.get_index() + 1 >= all_.frames.size()) {
      return null_frame_real_data_;
    }
    return all_.frames[i.get_index() + 1];
  }

  const std::vector<RMF_avro_backend::Node>& get_frames() const {
    return all_.frames;
  }

  RMF_avro_backend::Node& access_frame(FrameID i) {
    dirty_ = true;
    unsigned int index;
    if (i == ALL_FRAMES) {
      index = 0;
    } else {
      index = i.get_index() + 1;
    }
    if (all_.frames.size() <= index) {
      RMF_avro_backend::Node def;
      def.type = "frame";
      all_.frames.resize(index + 1, def);
    }
    return all_.frames[index];
  }
  void initialize_frames();
  void initialize_categories();
  void initialize_node_keys();
  static bool get_is_text(std::string name) {
    return name[name.size() - 1] == 't';
  }

 public:
  unsigned int get_number_of_nodes() const { return all_.nodes.size(); }

  void set_loaded_frame(FrameID frame) {
    null_frame_data_.frame = frame.get_index();
    AvroKeysAndCategories::set_loaded_frame(frame);
  }

  void flush();
  void reload();

  SingleAvroFile(std::string path, bool create, bool read_only);
  SingleAvroFile(boost::shared_ptr<std::vector<char> > buffer, bool create,
                 bool read_only);
  SingleAvroFile();
  ~SingleAvroFile() { flush(); }
  FrameID add_frame(std::string name, FrameType t);
  void add_child_frame(FrameID child_node);
  FrameIDs get_children(FrameID node) const;
  using AvroKeysAndCategories::get_name;
  std::string get_loaded_frame_name() const;
  FrameType get_loaded_frame_type() const;
  unsigned int get_number_of_frames() const;
  std::string get_file_type() const {
    if (text_) {
      return "Single avro version 1 (text)";
    } else {
      return "Single avro version 1 (binary)";
    }
  }
  std::vector<char> get_buffer();
};

}  // namespace avro_backend
} /* namespace RMF */

RMF_DISABLE_WARNINGS

#include "AvroSharedData.impl.h"

#endif /* RMF_INTERNAL_SINGLE_AVRO_FILE_H */

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: 工厂模式
categories: [DesignPattern]
description:
keywords:
---

* content
{:toc}

## 工厂模式

工厂模式在创建型模式当中比较常用, 它并不是一个独立的设计模式, 而是三种功能相近的设计模式的统称, 这三种设计模式分别是**简单工厂模式**, **工厂方法模式**, **抽象工厂模式**

![http://www.milky.show/images/designpattern/factory/factory_1.png](http://www.milky.show/images/designpattern/factory/factory_1.png)

![http://www.milky.show/images/designpattern/factory/factory_2.png](http://www.milky.show/images/designpattern/factory/factory_2.png)

```java
ClassA a = new ClassA();
ClassB b = new ClassB();
```

![http://www.milky.show/images/designpattern/factory/factory_3.png](http://www.milky.show/images/designpattern/factory/factory_3.png)

![http://www.milky.show/images/designpattern/factory/factory_4.png](http://www.milky.show/images/designpattern/factory/factory_4.png)

![http://www.milky.show/images/designpattern/factory/factory_5.png](http://www.milky.show/images/designpattern/factory/factory_5.png)

![http://www.milky.show/images/designpattern/factory/factory_6.png](http://www.milky.show/images/designpattern/factory/factory_6.png)

假设我们的业务代码当中, 有一个被广泛引用的"口罩类", 这个类实例需要在许多地方被创建和初始化, 而初始化的代码也比较复杂。

```java
public class Mask {
    //构造函数
    public Mask(){
        // .....
        // 100行初始化代码
    }
}
```

针对这种情况, 我们可以构建一个"口罩工厂"专门负责创建口罩对象, 把口罩的初始化代码迁移到工厂类的创建方法当中:

```java
public class MaskFactory {

    public Mask createMask() {
        Mask mask = new Mask();
        // .....
        // 100行初始化代码
        return mask;
    }
}
```

![http://www.milky.show/images/designpattern/factory/factory_7.png](http://www.milky.show/images/designpattern/factory/factory_7.png)

![http://www.milky.show/images/designpattern/factory/factory_8.png](http://www.milky.show/images/designpattern/factory/factory_8.png)

假设口罩类只是一个抽象接口, 有两个子类"高端口罩"和"低端口罩"分别实现了这个接口:

```java
public interface IMask {
    void show();
}

public class HighEndMask implements IMask {
    @Override
    public void show() {
        System.out.println("我是高端口罩");
    }
}

public class LowEndMask implements IMask {
    @Override
    public void show(){
        System.out.println("我的低端口罩");
    }

}
```

那么口罩工厂该如何创建这两种类型的口罩呢?

很简单, 在创建方法中传入参数(这里的参数是type), 根据参数来做条件判断, 决定创建什么样的口罩:

```java
public class MaskFactory{

    public IMask createMask(String type) {
        IMask mask = null;
        if("高端口罩".equals(type)){
            mask = new HighEndMask();
            // .....
            // HighEndMask的100行初始化代码
        }else if("低端口罩".equals(type)){
            mask =  new LowEndMask();
            // .....
            // LowEndMask的100行初始化代码
        }
        return mask;
    }
}
```

在客户端, 想要创建什么样的口罩对象, 只需传入对应的类型名称:

```java
public class Test {

    public static void main(String[] args) {
        MaskFactory factory = new MaskFactory();
        IMask maskA = factory.createMask("高端口罩");
        IMask maskB = factory.createMask("低端口罩");
        maskA.show();
        maskB.show();
    }
}
```

![http://www.milky.show/images/designpattern/factory/factory_9.png](http://www.milky.show/images/designpattern/factory/factory_9.png)

![http://www.milky.show/images/designpattern/factory/factory_10.png](http://www.milky.show/images/designpattern/factory/factory_10.png)

(注: 所谓面向对象的开放-封闭原则, 就是在程序中对"扩展"开放, 对"修改"封闭。如果每次业务改动都要增加新的if-else, 就涉及对旧有代码的修改, 不但容易出错, 可读性也不好。)

![http://www.milky.show/images/designpattern/factory/factory_11.png](http://www.milky.show/images/designpattern/factory/factory_11.png)

![http://www.milky.show/images/designpattern/factory/factory_12.png](http://www.milky.show/images/designpattern/factory/factory_12.png)

让我们根据这个思路, 重构一下工厂类的逻辑:

```java
public interface IMaskFactory {
    IMask createMask();
}

public class HighEndFactory implements IMaskFactory{

    @Override
    public IMask createMask() {
        IMask mask =  new HighEndMask();
        // .....
        // HighEndMask的100行初始化代码
        return mask;
    }
}

public class LowEndFactory implements IMaskFactory{

    @Override
    public IMask createMask() {
        IMask mask =  new LowEndMask();
        // .....
        //  LowEndMask的100行初始化代码
        return mask;
    }
}
```

在代码中, 工厂类变成了抽象的接口, 高端口罩工厂和低端口罩工厂这两个子类分别实现了该接口。

在客户端, 想要创建什么样的口罩对象, 只需实例化不同的工厂子类, 调用相同的创建方法, 无需再传入参数:

```java
public class Test {

    public static void main(String[] args) {
        IMaskFactory factoryA = new LowEndFactory();
        IMaskFactory factoryB = new HighEndFactory();
        IMask maskA = factoryA.createMask();
        IMask maskB = factoryB.createMask();
        maskA.show();
        maskB.show();
    }
}
```

![http://www.milky.show/images/designpattern/factory/factory_13.png](http://www.milky.show/images/designpattern/factory/factory_13.png)

![http://www.milky.show/images/designpattern/factory/factory_14.png](http://www.milky.show/images/designpattern/factory/factory_14.png)

![http://www.milky.show/images/designpattern/factory/factory_15.png](http://www.milky.show/images/designpattern/factory/factory_15.png)

## 抽象工厂模式

![http://www.milky.show/images/designpattern/factory/factory_16.png](http://www.milky.show/images/designpattern/factory/factory_16.png)

比如, 业务中需要创建口罩、防毒面具、防护服这三种产品, 而每一种产品有包含高端和低端两类, 按照工厂方法模式的解决方案, 需要创建的类如下:

![http://www.milky.show/images/designpattern/factory/factory_17.png](http://www.milky.show/images/designpattern/factory/factory_17.png)

如图所示, 每一个产品类都对应着一个工厂类, 当产品数量很多的时候, 工厂类的数量也会越老越多, 搞得系统非常复杂。

这时候我们该怎么办呢?

![http://www.milky.show/images/designpattern/factory/factory_18.png](http://www.milky.show/images/designpattern/factory/factory_18.png)

![http://www.milky.show/images/designpattern/factory/factory_19.png](http://www.milky.show/images/designpattern/factory/factory_19.png)

![http://www.milky.show/images/designpattern/factory/factory_20.png](http://www.milky.show/images/designpattern/factory/factory_20.png)

![http://www.milky.show/images/designpattern/factory/factory_21.png](http://www.milky.show/images/designpattern/factory/factory_21.png)

首先看一下产品类的代码, 口罩和防护服是两个抽象接口, 分别拥有高端和低端两个实现类:

```java
public interface IMask {
    void showMask();
}

public class LowEndMask implements IMask {
    @Override
    public void showMask(){
        System.out.println("我的低端口罩");
    }
}

public class HighEndMask implements IMask {
    @Override
    public void showMask() {
        System.out.println("我是高端口罩");
    }
}

public interface IProtectiveSuit {
    void showSuit();
}

public class LowEndProtectiveSuit implements IProtectiveSuit {
    @Override
    public void showSuit() {
        System.out.println("我是低端防护服");
    }
}

public class HighEndProtectiveSuit implements IProtectiveSuit {
    @Override
    public void showSuit() {
        System.out.println("我是高端防护服");
    }
}
```

接下来是工厂类, 由于产品分成了高端和低端两大组, 工厂也相应分成了高端工厂和低端工厂, 各自负责组内产品的创建:

```java
public interface IFactory {
    //创建口罩
    IMask createMask();
    //创建防护服
    IProtectiveSuit createSuit();
}

public class LowEndFactory implements IFactory {
    @Override
    public IMask createMask() {
        IMask mask =  new LowEndMask();
        // .....
        //  LowEndMask的100行初始化代码
        return mask;
    }

    @Override
    public IProtectiveSuit createSuit() {
        IProtectiveSuit suit =  new LowEndProtectiveSuit();
        // .....
        //  LowEndProtectiveSuit的100行初始化代码
        return suit;
    }
}

public class HighEndFactory implements IFactory {
    @Override
    public IMask createMask() {
        IMask mask =  new HighEndMask();
        // .....
        // HighEndMask的100行初始化代码
        return mask;
    }

    @Override
    public IProtectiveSuit createSuit() {
        IProtectiveSuit suit =  new HighEndProtectiveSuit();
        // .....
        //  HighEndProtectiveSuit的100行初始化代码
        return suit;
    }
}
```

最后是客户端代码, 通过实例化不同的工厂子类, 调用不同的创建方法, 可以创建出不同的产品:

```java
public class Test {

    public static void main(String[] args) {
        IFactory factoryA = new LowEndFactory();
        IFactory factoryB = new HighEndFactory();
        //创建低端口罩
        IMask maskA = factoryA.createMask();
        //创建高端口罩
        IMask maskB = factoryB.createMask();
        //创建低端防护服
        IProtectiveSuit suitA = factoryA.createSuit();
        //创建高端防护服
        IProtectiveSuit suitB = factoryB.createSuit();

        maskA.showMask();
        maskB.showMask();
        suitA.showSuit();
        suitB.showSuit();
    }
}
```

![http://www.milky.show/images/designpattern/factory/factory_22.png](http://www.milky.show/images/designpattern/factory/factory_22.png)

**简单工厂模式**

简单工厂模式有唯一的工厂类, 工厂类的创建方法根据传入的参数做if-else条件判断, 决定最终创建什么样的产品对象。

**工厂方法模式**

工厂方法模式由多个工厂类实现工厂接口, 利用多态来创建不同的产品对象, 从而避免了冗长的if-else条件判断。

**抽象工厂模式**

抽象工厂模式把产品子类进行分组, 同组中的不同产品由同一个工厂子类的不同方法负责创建, 从而减少了工厂子类的数量。

![http://www.milky.show/images/designpattern/factory/factory_23.png](http://www.milky.show/images/designpattern/factory/factory_23.png)

![http://www.milky.show/images/designpattern/factory/factory_24.png](http://www.milky.show/images/designpattern/factory/factory_24.png)

![http://www.milky.show/images/designpattern/factory/factory_25.png](http://www.milky.show/images/designpattern/factory/factory_25.png)

![http://www.milky.show/images/designpattern/factory/factory_26.png](http://www.milky.show/images/designpattern/factory/factory_26.png)

熟悉spring框架的小伙伴, 一定知道spring的一个重要特性:**依赖注入(DI)**。

通过spring的依赖注入, 开发人员不需要在业务代码中手动实例化bean对象, 也不需要知道任何工厂类。

bean对象从创建到销毁的整个过程, 完全交给spring容器来管理, 用户需要做的仅仅是在xml配置文件中(或使用注解)设置bean的各项属性:

```java
<bean id="userController" class="com.xiaohui.controller.UserController">
    <constructor-arg name="userService" ref="userService"></constructor-arg>
</bean>

<bean id="userService" class="com.xiaohui.service.UserService">
```

根据上面的配置, spring容器会动态创建UserController对象, 并创建UserController所依赖的UserService对象。

如果开发人员希望把userService这个bean对象的实现类换成另一个类, 并不需要改动任何代码, 只需要修改配置文件中对应bean的class属性即可。

![http://www.milky.show/images/designpattern/factory/factory_27.png](http://www.milky.show/images/designpattern/factory/factory_27.png)

![http://www.milky.show/images/designpattern/factory/factory_28.png](http://www.milky.show/images/designpattern/factory/factory_28.png)

在大多数情况下, 我们使用new关键字创建对象, 对象所属的class是在代码中明确定义好的。

但是在少数情况下, 我们需要借助class的元信息(比如完整类名), 在程序运行期间动态创建对象, 这就用到了Java的反射。

当我们在spring配置文件中配置了相应的bean, 启动项目, spring会为我们解析xml配置文件, 并根据bean的不同生命周期, 由spring内部的"工厂"创建出bean对象。

对spring依赖注入原理有兴趣的小伙伴, 可以阅读spring源码中的**BeanFactory**接口, 以及相关的实现类。


text:
import React, { FunctionComponent } from 'react';

import LinkLine from '../../LinkLine';
import i18n from '../i18n';
import { onLinkLineItemClick } from '../SettingsPanel.interface';

export interface LinkLineItemProps extends onLinkLineItemClick {
  name?: string;
  customTitle?: string;
  currentLocale: string;
  show?: boolean;
}

export const LinkLineItem: FunctionComponent<LinkLineItemProps> = ({
  show,
  name,
  customTitle,
  currentLocale,
  onClick,
}) => {
  if (!show) {
    return null;
  }
  return (
    <LinkLine onClick={onClick}>
      {customTitle || i18n.getString(name, currentLocale)}
    </LinkLine>
  );
};


text:
import os
import random
import string
from getpass import getpass

from colorama import init, Fore, Style

from pynubank import NuException
from pynubank.utils.certificate_generator import CertificateGenerator

def generate_random_id() -> str:
    return ''.join(random.choices(string.ascii_lowercase + string.digits, k=12))

def log(message, color=Fore.BLUE):
    print(f'{color}{Style.DIM}[*] {Style.NORMAL}{Fore.LIGHTBLUE_EX}{message}')

def save_cert(cert, name):
    path = os.path.join(os.getcwd(), name)
    with open(path, 'wb') as cert_file:
        cert_file.write(cert.export())

def main():
    init()

    log(f'Starting {Fore.MAGENTA}{Style.DIM}PyNubank{Style.NORMAL}{Fore.LIGHTBLUE_EX} context creation.')

    device_id = generate_random_id()

    log(f'Generated random id: {device_id}')

    cpf = input(f'[>] Enter your CPF(Numbers only): ')
    password = getpass('[>] Enter your password (Used on the app/website): ')

    generator = CertificateGenerator(cpf, password, device_id)

    log('Requesting e-mail code')
    try:
        email = generator.request_code()
    except NuException:
        log(f'{Fore.RED}Failed to request code. Check your credentials!', Fore.RED)
        return

    log(f'Email sent to {Fore.LIGHTBLACK_EX}{email}{Fore.LIGHTBLUE_EX}')
    code = input('[>] Type the code received by email: ')

    cert1, cert2 = generator.exchange_certs(code)

    save_cert(cert1, 'cert.p12')

    print(f'{Fore.GREEN}Certificates generated successfully. (cert.pem)')
    print(f'{Fore.YELLOW}Warning, keep these certificates safe (Do not share or version in git)')

if __name__ == '__main__':
    main()


text:
import numpy as np
import pytest

from pandas import DataFrame, Series, Timestamp, date_range, to_datetime
import pandas.util.testing as tm

@pytest.fixture
def date_range_frame():
    """
    Fixture for DataFrame of ints with date_range index

    Columns are ['A', 'B'].
    """
    N = 50
    rng = date_range('1/1/1990', periods=N, freq='53s')
    return DataFrame({'A': np.arange(N), 'B': np.arange(N)}, index=rng)

class TestFrameAsof:

    def test_basic(self, date_range_frame):
        df = date_range_frame
        N = 50
        df.loc[15:30, 'A'] = np.nan
        dates = date_range('1/1/1990', periods=N * 3, freq='25s')

        result = df.asof(dates)
        assert result.notna().all(1).all()
        lb = df.index[14]
        ub = df.index[30]

        dates = list(dates)
        result = df.asof(dates)
        assert result.notna().all(1).all()

        mask = (result.index >= lb) & (result.index < ub)
        rs = result[mask]
        assert (rs == 14).all(1).all()

    def test_subset(self, date_range_frame):
        N = 10
        df = date_range_frame.iloc[:N].copy()
        df.loc[4:8, 'A'] = np.nan
        dates = date_range('1/1/1990', periods=N * 3,
                           freq='25s')

        # with a subset of A should be the same
        result = df.asof(dates, subset='A')
        expected = df.asof(dates)
        tm.assert_frame_equal(result, expected)

        # same with A/B
        result = df.asof(dates, subset=['A', 'B'])
        expected = df.asof(dates)
        tm.assert_frame_equal(result, expected)

        # B gives df.asof
        result = df.asof(dates, subset='B')
        expected = df.resample('25s', closed='right').ffill().reindex(dates)
        expected.iloc[20:] = 9

        tm.assert_frame_equal(result, expected)

    def test_missing(self, date_range_frame):
        # GH 15118
        # no match found - `where` value before earliest date in index
        N = 10
        df = date_range_frame.iloc[:N].copy()
        result = df.asof('1989-12-31')

        expected = Series(index=['A', 'B'], name=Timestamp('1989-12-31'))
        tm.assert_series_equal(result, expected)

        result = df.asof(to_datetime(['1989-12-31']))
        expected = DataFrame(index=to_datetime(['1989-12-31']),
                             columns=['A', 'B'], dtype='float64')
        tm.assert_frame_equal(result, expected)

    def test_all_nans(self, date_range_frame):
        # GH 15713
        # DataFrame is all nans
        result = DataFrame([np.nan]).asof([0])
        expected = DataFrame([np.nan])
        tm.assert_frame_equal(result, expected)

        # testing non-default indexes, multiple inputs
        N = 150
        rng = date_range_frame.index
        dates = date_range('1/1/1990', periods=N, freq='25s')
        result = DataFrame(np.nan, index=rng, columns=['A']).asof(dates)
        expected = DataFrame(np.nan, index=dates, columns=['A'])
        tm.assert_frame_equal(result, expected)

        # testing multiple columns
        dates = date_range('1/1/1990', periods=N, freq='25s')
        result = DataFrame(np.nan, index=rng,
                           columns=['A', 'B', 'C']).asof(dates)
        expected = DataFrame(np.nan, index=dates, columns=['A', 'B', 'C'])
        tm.assert_frame_equal(result, expected)

        # testing scalar input
        result = DataFrame(np.nan, index=[1, 2], columns=['A', 'B']).asof([3])
        expected = DataFrame(np.nan, index=[3], columns=['A', 'B'])
        tm.assert_frame_equal(result, expected)

        result = DataFrame(np.nan, index=[1, 2], columns=['A', 'B']).asof(3)
        expected = Series(np.nan, index=['A', 'B'], name=3)
        tm.assert_series_equal(result, expected)

    @pytest.mark.parametrize(
        "stamp,expected",
        [(Timestamp('2018-01-01 23:22:43.325+00:00'),
          Series(2.0, name=Timestamp('2018-01-01 23:22:43.325+00:00'))),
         (Timestamp('2018-01-01 22:33:20.682+01:00'),
          Series(1.0, name=Timestamp('2018-01-01 22:33:20.682+01:00'))),
         ]
    )
    def test_time_zone_aware_index(self, stamp, expected):
        # GH21194
        # Testing awareness of DataFrame index considering different
        # UTC and timezone
        df = DataFrame(data=[1, 2],
                       index=[Timestamp('2018-01-01 21:00:05.001+00:00'),
                              Timestamp('2018-01-01 22:35:10.550+00:00')])
        result = df.asof(stamp)
        tm.assert_series_equal(result, expected)


text:
require 'rails_helper'

RSpec.describe Reservation, type: :model do
  describe "with a existing plane" do
    let(:plane){ FactoryGirl.create(:plane) }

    it "Is saved with proper information" do
      reservation = FactoryGirl.create(:reservation)
      expect(reservation).to be_valid
      expect(Reservation.count).to eq(1)
    end

    it "Is not saved when end time is before start time" do
      reservation = Reservation.create reservation_type: "1", start: "2017-06-07 12:42:00", end: "2017-06-07 12:12:00", user_id: 1, plane_id: 1

      expect(reservation).not_to be_valid
      expect(Reservation.count).to eq(0)
    end

    it "Is not saved when start and end time overlap with existing reservation" do
      FactoryGirl.create :reservation, plane: plane
      reservation = FactoryGirl.build(:reservation,
                                      start: DateTime.now + 2.days + 1.hour,
                                      end: DateTime.now + 2.days + 2.hours,
                                      plane: plane)

      expect(reservation).not_to be_valid
      expect(Reservation.count).to eq(1)
    end

    it 'calls publishing method when destroyed' do
      reservation = Reservation.create reservation_type: 'opetus',
                                       start: '2017-05-05 12:00:00',
                                       end: '2017-05-05 14:00:00',
                                       user_id: 1,
                                       plane: plane
      expect(reservation).to receive(:publish_reservation_destroyed).with(no_args)
      reservation.destroy
    end
  end
end


text:
package org.g4studio.core.web.taglib.html;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.g4studio.core.util.G4Constants;

/**
 * Script标签
 * @author XiongChun
 * @since 2010-02-30
 */
public class ScriptTag extends TagSupport {
	private static Log log = LogFactory.getLog(DivTag.class);

    /**
     * 标签开始
     */
    public int doStartTag() throws JspException{
		String begin = "<script type=\"text/javascript\">";
		try {
			pageContext.getOut().write(begin);
		} catch (IOException e) {
			log.error(G4Constants.Exception_Head + e.getMessage());
			e.printStackTrace();
		}
		return super.EVAL_BODY_INCLUDE;
    }

    /**
     * 标签结束
     */
    public int doEndTag() throws JspException{
		try {
			pageContext.getOut().write("</script>");
		} catch (IOException e) {
			log.error(G4Constants.Exception_Head + e.getMessage());
			e.printStackTrace();
		}
    	return super.EVAL_PAGE;
    }

    /**
     * 释放资源
     */
    public void release(){
    	super.release();
    }
}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Composition
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.LanguageServices

Namespace Microsoft.CodeAnalysis.VisualBasic
    <ExportLanguageService(GetType(ICommandLineArgumentsFactoryService), LanguageNames.VisualBasic), [Shared]>
    Friend Class VisualBasicCommandLineArgumentsFactoryService
        Implements ICommandLineArgumentsFactoryService

        Public Function CreateCommandLineArguments(arguments As IEnumerable(Of String), baseDirectory As String, isInteractive As Boolean) As CommandLineArguments Implements ICommandLineArgumentsFactoryService.CreateCommandLineArguments
            Dim parser = If(isInteractive, VisualBasicCommandLineParser.Interactive, VisualBasicCommandLineParser.Default)
            Return parser.Parse(arguments, baseDirectory, RuntimeEnvironment.GetRuntimeDirectory())
        End Function
    End Class
End Namespace


text:
package com.socialize.error;

/**
 * @author Jason Polites
 *
 */
public class AuthCanceledException extends SocializeException {

	private static final long serialVersionUID = 7733086673525453885L;

	public AuthCanceledException() {
		super();
	}

	public AuthCanceledException(String detailMessage, Throwable throwable) {
		super(detailMessage, throwable);
	}

	public AuthCanceledException(String detailMessage) {
		super(detailMessage);
	}

	public AuthCanceledException(Throwable throwable) {
		super(throwable);
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.todddavies.components.progressbar">

    <application />

</manifest>


text:
import styled from 'styled-components';
import get from 'extensions/themeGet';

export default styled.div`
  position: relative;
  padding: ${get('spacing.medium')} 0;
  &::before {
    position: absolute;
    content: '';
    left: 0;
    right: 0;
    top: 0;
    border-top-width: ${get('thicknesses.normal')};
    border-top-style: solid;
    border-top-color: ${get('colors.border.medium')};
  }
`;


text:
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;

namespace Quasar.Communication.Packets.Outgoing.Navigator
{
    class NavigatorCollapsedCategoriesComposer : ServerPacket
    {
        public NavigatorCollapsedCategoriesComposer()
            : base(ServerPacketHeader.NavigatorCollapsedCategoriesMessageComposer)
        {
            base.WriteInteger(0);
        }
    }
}


text:
"""
===============================================================================
DelaunayCubic: Generate semi-random networks based on Delaunay Tessellations and
perturbed cubic lattices
===============================================================================

"""
import OpenPNM
import scipy as sp
import sys
import numpy as np
from OpenPNM.Network.__Delaunay__ import Delaunay
from OpenPNM.Base import logging
logger = logging.getLogger(__name__)

class DelaunayCubic(Delaunay):
    r"""
    This class contains the methods for creating a *Delaunay* network topology
    based connecting pores with a Delaunay tessellation.

    This Subclass of Delaunay generates points on a cubic lattice and then perturbs
    them to prevent degeneracy

    Parameters
    ----------
    name : string
        A unique name for the network

    shape : tuple of ints
        The (i,j,k) size and shape of the network.

    spacing : 3 x 1 array defining the base lattice spacing of the network

    perturbation : float between 0 and 1 controlling the maximum perturbation
        of lattice points as a fraction of the lattice spacing

    arrangement : string
        usage:  'SC'- Simple Cubic (default if left blank)
                'O' - Orthorhombic
                'BCC' - Body Centred Cubic
                'FCC' - Face Centred Cubic
    Examples
    --------
    >>> import OpenPNM
    >>> pn = OpenPNM.Network.DelaunayCubic(shape=[5, 5, 5],
    ...                                    spacing=[4e-5, 4e-5, 4e-5],
    ...                                    jiggle_factor=0.01)
    >>> pn.num_pores()
    125

    """

    def __init__(self, shape=None, spacing=[1, 1, 1],
                 perturbation=0.1, arrangement='SC', **kwargs):
        if shape is not None:
            self._arr = np.atleast_3d(np.empty(shape))
        else:
            self._arr = np.atleast_3d(np.empty([3, 3, 3]))

        # Store original network shape
        self._shape = sp.shape(self._arr)
        # Store network spacing instead of calculating it
        self._spacing = sp.asarray(spacing)
        self._num_pores = np.prod(np.asarray(self._shape))
        self._domain_size = np.asarray(self._shape) * self._spacing
        self._perturbation = perturbation
        self._arrangement = arrangement
        super().__init__(num_pores=self._num_pores,
                         domain_size=self._domain_size,
                         **kwargs)

    def _generate_pores(self, prob=None):
        r"""
        Generate the pores with numbering scheme.
        """

        points = np.array([i for i, v in np.ndenumerate(self._arr)], dtype=float)
        points += 0.5

        # 2D Orthorhombic adjustment - shift even rows back a bit and odd rows
        # forward a bit
        "   0   0   0   "
        " 0   0   0   0 "
        "   0   0   0   "
        if self._arrangement == 'O':
            shift_y = np.array([0, 0.25, 0])
            shift_x = np.array([0.25, 0, 0])
            points[(points[:, 0] % 2 == 0)] -= shift_y
            points[(points[:, 2] % 2 != 0)] -= shift_x
            points[(points[:, 0] % 2 != 0)] += shift_y
            points[(points[:, 2] % 2 == 0)] += shift_x
        # BCC = Body Centre Cubic
        if self._arrangement == 'BCC':
            body_points = []
            for i in range(1, self._shape[0]):
                for j in range(1, self._shape[1]):
                    for k in range(1, self._shape[2]):
                        body_points.append([i, j, k])
            body_points = np.asarray(body_points)
            points = np.concatenate((points, body_points))

        # FCC = Face Centre Cubic
        if self._arrangement == 'FCC':
            face_points = []
            for i in range(1, self._shape[0]):
                for j in range(1, self._shape[1]):
                    for k in range(1, self._shape[2]):
                        left = [i-0.5, j, k]
                        right = [i+0.5, j, k]
                        back = [i, j-0.5, k]
                        front = [i, j+0.5, k]
                        bottom = [i, j, k-0.5]
                        top = [i, j, k+0.5]
                        if left not in face_points:
                            face_points.append(left)
                        if right not in face_points:
                            face_points.append(right)
                        if back not in face_points:
                            face_points.append(back)
                        if front not in face_points:
                            face_points.append(front)
                        if bottom not in face_points:
                            face_points.append(bottom)
                        if top not in face_points:
                            face_points.append(top)
            face_points = np.asarray(face_points)
            points = np.concatenate((points, face_points))

        jiggle = (np.random.rand(len(points), 3)-0.5)*self._perturbation
        points += jiggle
        points *= self._spacing

        self['pore.coords'] = points
        logger.debug(sys._getframe().f_code.co_name + ': End of method')


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('questions', '0030_data_migration'),
    ]

    operations = [
        migrations.RenameField(
            model_name='question',
            old_name='attribute_entity',
            new_name='attribute',
        ),
        migrations.RenameField(
            model_name='questionset',
            old_name='attribute_entity',
            new_name='attribute',
        ),
    ]


text:
layout: post
date: 2016-06-25
title: "Watters - Willowby Willowby Skirt Grace style 55545"
category: Watters - Willowby
tags: [Watters - Willowby]
---
### Watters - Willowby Willowby Skirt Grace style 55545
Just **$349.99**
###

Buy it: [https://www.readybrides.com/en/watters-willowby/14475-watters-skirt-grace-style-55545.html](https://www.readybrides.com/en/watters-willowby/14475-watters-skirt-grace-style-55545.html)


text:
<?php
// autogenerated file 30.09.2013 15:20
// $Id: $
// $Log: $
//
require_once 'EbatNs_FacetType.php';

/**
 * Specifies the various warranty durations being offered.
 *
 * @link http://developer.ebay.com/DevZone/XML/docs/Reference/eBay/types/WarrantyDurationOptionsCodeType.html
 *
 * @property string Months_1
 * @property string Months_3
 * @property string Months_6
 * @property string Years_1
 * @property string Years_2
 * @property string Years_3
 * @property string Years_MoreThan3
 * @property string CustomCode
 */
class WarrantyDurationOptionsCodeType extends EbatNs_FacetType
{
	const CodeType_Months_1 = 'Months_1';
	const CodeType_Months_3 = 'Months_3';
	const CodeType_Months_6 = 'Months_6';
	const CodeType_Years_1 = 'Years_1';
	const CodeType_Years_2 = 'Years_2';
	const CodeType_Years_3 = 'Years_3';
	const CodeType_Years_MoreThan3 = 'Years_MoreThan3';
	const CodeType_CustomCode = 'CustomCode';

	/**
	 * @return
	 */
	function __construct()
	{
		parent::__construct('WarrantyDurationOptionsCodeType', 'urn:ebay:apis:eBLBaseComponents');

	}
}

$Facet_WarrantyDurationOptionsCodeType = new WarrantyDurationOptionsCodeType();

?>


text:
define(['knockout'], function (ko) {

	ko.bindingHandlers.hidden = {
		update: function (element, valueAccessor) {
			ko.bindingHandlers.visible.update(element, function () {
				return !ko.utils.unwrapObservable(valueAccessor());
			});
		}
	};

	ko.bindingHandlers.clickToEdit = {
		init: function (element, valueAccessor) {
			var observable = valueAccessor(),
				span = document.createElement("span"),
				input = document.createElement("input");

			element.appendChild(span);
			element.appendChild(input);

			observable.editing = ko.observable(false);

			ko.applyBindingsToNode(span, {
				text: ko.computed(function() { return (observable() || "").length > 0 ? observable() : "Click to Edit";}),
				hidden: observable.editing,
				click: observable.editing.bind(null, true)
			});

			ko.applyBindingsToNode(input, {
				value: observable,
				visible: observable.editing,
				hasfocus: observable.editing,
				event: {
					keyup: function (data, event) {
						//if user hits enter, set editing to false, which makes field lose focus
						if (event.keyCode === 13) {
							observable.editing(false);
							return false;
						}
						//if user hits escape, push the current observable value back to the field, then set editing to false
						else if (event.keyCode === 27) {
							observable.valueHasMutated();
							observable.editing(false);
							return false;
						}
					}
				}
			});
		}
	};
});


text:
package Armadillo.Core;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;

import Armadillo.Core.Io.FileHelper;
import Armadillo.Core.Io.PathHelper;
import Armadillo.Core.Text.StringHelper;

public class Config
{
	private final static String LOCATION = "Config";
	private String m_strConfigName;
	private boolean m_blnIsInitialized;
	private static Object m_locker = new Object();
	private Configuration m_config;
	private static HashMap<String, Config> m_instanceMap = new HashMap<String, Config>();
	private static String m_strClientName;
	public static final String strDnsName = NetworkHelper.getHostName();

	static
	{
        m_strClientName = strDnsName + "%" +
        		RuntimeHelper.getCurrentJarName() + "%" +
        		RuntimeHelper.getProcessId();
	}

	public static String getClientName()
	{
		try
		{
			return m_strClientName;
		}
		catch(Exception ex)
		{
			Logger.log(ex);
		}
		return "";
	}

	public static String getStringStatic(String strKey)
	{
		Class<?> callingClass = Config.class;
		return getStringStatic(strKey, callingClass);
	}

	public static List<String> getStringListStatic(
			String strKey,
			Class<?> callingClass)
	{
		try
		{
			List<String> list = new ArrayList<String>();
			String strLine = getStringStatic(strKey, callingClass);
			if(StringHelper.IsNullOrEmpty(strLine))
			{
				return list;
			}
			String[] items = strLine.split(Environment.NewLine);
			for(String strTok : items)
			{
				strTok = strTok.trim();
				if(!StringHelper.IsNullOrEmpty(strTok))
				{
					list.add(strTok);
				}
			}
			return list;
		}
		catch(Exception ex)
		{
			Logger.log(ex);
		}
		return new ArrayList<String>();
	}

	public static String getStringStatic(
			String strKey,
			Class<?> callingClass)
	{
		try
		{
			return getConfig(callingClass).getStr(strKey);
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return "";
	}

	public String getStr(String strKey)
	{
		return m_config.getString(strKey);
	}

	public static Config getConfig(Class<?> callingClass)
	{
		synchronized (m_locker)
		{
			Config instanceConfig = m_instanceMap.get(callingClass.getName());
			if (instanceConfig == null)
			{
				instanceConfig = new Config();
				instanceConfig.initialize(callingClass);
				m_instanceMap.put(callingClass.getName(), instanceConfig);
			}
			return instanceConfig;
		}
	}

	public void initialize(Class<?> classRef)
	{
		try
		{
			if (m_blnIsInitialized)
			{
				return;
			}

			String strPackageName = classRef.getPackage().getName();
			m_strConfigName = PathHelper.combinePaths(
					LOCATION,
					strPackageName)
					+ ".xml";

			if (!FileHelper.exists(m_strConfigName))
			{
				throw new Exception("Config file not found [" +
						new File(m_strConfigName).getAbsolutePath()
						+ "]");
			}
			getConfig();
			m_blnIsInitialized = true;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private void getConfig()
	{
		try
		{
			m_config = new XMLConfiguration(m_strConfigName);
		}
		catch (ConfigurationException e)
		{
			e.printStackTrace();
		}
	}

	public static String getHostName() {
		return strDnsName;
	}
}


text:
<?php
require("functions.php");

$obj = $_POST['toDbQuestionnaire'];
$obj = json_decode($obj);

if (isset($obj) && isset($obj->name) && $_SESSION['email']) {
    $Question->createQuestionnaireWithNameAndEmail($obj->name, $_SESSION['email'], $obj->quiz);
    header('Content-Type: application/json');
    echo json_encode("{result: true}");
}


text:
<?php

class AbortAfterHelloAuthProviderClient extends \Thruway\Authentication\AbstractAuthProviderClient {
    /**
     * @return string
     */
    public function getMethodName()
    {
        return 'abortafterhello';
    }

    public function processHello(array $args) {
        return ["FAILURE"];
    }

}


text:
#ifndef __ETCHBYTEREPRESENTATION_H__
#define __ETCHBYTEREPRESENTATION_H__

typedef capu::uint32_t EtchByteRepresentation;

enum {

  ETCH_LITTLE_ENDIAN = 0,
  ETCH_BIG_ENDIAN = 1
};

#endif /* ETCHBYTEREPRESENTATION_H */


text:
package com.brightdairy.personal.brightdairy.popup;

import android.content.Intent;
import android.support.v4.app.FragmentActivity;

import com.brightdairy.personal.brightdairy.R;
import com.brightdairy.personal.brightdairy.activity.LoginSmsActivity;
import com.brightdairy.personal.brightdairy.utils.GlobalConstants;

/**
 * Created by shuangmusuihua on 2016/10/10.
 */

public class DialogPopupHelper
{
    public static void showLoginPopup(final FragmentActivity activity)
    {

        DialogPopup dialogPopup = DialogPopup.newInstance(
                activity.getResources().getString(R.string.need_login),
                activity.getResources().getString(R.string.confirm_login),
                activity.getResources().getString(R.string.cancel_login));

        dialogPopup.setDialogListener(new DialogPopup.DialogListener()
        {
            @Override
            public void onConfirmClick()
            {
                Intent jumpToLogin = new Intent(activity, LoginSmsActivity.class);
                jumpToLogin.putExtra(GlobalConstants.INTENT_FLAG.NEED_RELOGIN, true);
                activity.startActivityForResult(jumpToLogin, GlobalConstants.INTENT_FLAG.RELOGIN_REQ_FLG);
            }

            @Override
            public void onCancelClick()
            {

            }
        });

        dialogPopup.show(activity.getSupportFragmentManager(), "needLogin");
    }

    public static void showInfoNoMoreAction(FragmentActivity activity)
    {
        ShowInfoDialog showInfoDialog = ShowInfoDialog.newInstance(activity.getResources().getString(R.string.point_usage_rule));

        showInfoDialog.show(activity.getSupportFragmentManager(), "showInfoNoMoreAction");
    }
}


text:
<?php

namespace Magento\Framework\Oauth;

/**
 * NonceGeneratorInterface provides methods for generating a nonce for a consumer and validating a nonce to ensure
 * that it is not already used by an existing consumer. Validation will persist the nonce if validation succeeds.
 * A method for generating a current timestamp is also provided by this interface.
 *
 * @api
 */
interface NonceGeneratorInterface
{
    /**
     * Generate a new nonce for the consumer (if consumer is specified).
     *
     * @param ConsumerInterface $consumer
     * @return string The generated nonce value.
     */
    public function generateNonce(ConsumerInterface $consumer = null);

    /**
     * Generate a current timestamp.
     *
     * @return int The time as an int
     */
    public function generateTimestamp();

    /**
     * Validate the specified nonce, which ensures that it can only be used by a single consumer and persist it
     * with the specified consumer and timestamp. This method effectively saves the nonce and marks it as used
     * by the specified consumer.
     *
     * @param ConsumerInterface $consumer
     * @param string $nonce The nonce value.
     * @param int $timestamp The 'oauth_timestamp' value.
     * @return void
     * @throws \Magento\Framework\Oauth\Exception Exceptions are thrown for validation errors.
     */
    public function validateNonce(ConsumerInterface $consumer, $nonce, $timestamp);
}


text:
import datetime

from django.db import models
from django.contrib.sites.managers import CurrentSiteManager
from django.conf import settings
from django.core.cache import cache

SESSION_PAGE_EXPIRE_TIME = 4 * 7 * 24 * 60 * 60
PAGE_CACHE_TIMEOUT = 120

class PageManager(CurrentSiteManager):
    def get_for_id(self, id):
        key = 'page_for_id:%s' % id
        page = cache.get(key)
        if page:
            return page
        page = self.get(pk=id)
        page_cache_timeout = getattr(settings, 'PAGE_CACHE_TIMEOUT', PAGE_CACHE_TIMEOUT)
        cache.set(key, page, timeout=page_cache_timeout)
        return page

    def clone_from_page(self, page, defaults={}, **kwargs):
        """
        Returns cloned page
        """
        # clone and save page
        d = defaults.copy()
        d.update({
            'layout_json': page.layout_json,
            'site': page.site,
            'site_copy': page.site,
            'layout_migrated': page.layout_migrated,
        })
        new_page, created = self.get_or_create(defaults=d, **kwargs)
        if not created:
            return new_page
        new_page.layout = page.layout.clone()
        new_page.save()
        return new_page

class SessionPageManager(PageManager):

    def clean_old_pages(self):
        session_page_expire_time = datetime.timedelta(seconds=getattr(settings, 'SESSION_PAGE_EXPIRE_TIME', SESSION_PAGE_EXPIRE_TIME))
        self.filter(updated__lt=(datetime.datetime.now() - session_page_expire_time)).delete()


text:
<?php

namespace Pin\Customer;

use Pin\RequestInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class Create implements RequestInterface
{
    protected $options;

    public function __construct(array $options = array())
    {
        $resolver = new OptionsResolver();
        $this->setDefaultOptions($resolver);

        $this->options = $resolver->resolve($options);
    }

    protected function setDefaultOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setRequired(array(
                'email'
            ))
            ->setDefined(array(
                'ip_address',
                'card',
                'card_token'
            ))
            ->setAllowedTypes('email', 'string')
            ->setAllowedTypes('card', 'array')
            ->setAllowedTypes('card_token', 'string')
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getMethod()
    {
        return self::METHOD_POST;
    }

    /**
     * {@inheritdoc}
     */
    public function getPath()
    {
        return '/1/customers';
    }

    /**
     * {@inheritdoc}
     */
    public function getData()
    {
        return $this->options;
    }
}


text:
package quickcheck

import scala.annotation.tailrec
import scala.language.implicitConversions

import common._

import org.scalacheck._
import Arbitrary._
import Gen._
import Prop._

abstract class QuickCheckHeap extends Properties("Heap") with IntHeap {

  implicit def toList(h: H): List[A] = {

    @tailrec
    def impl(current: H, acc: List[A] = Nil): List[A] =
      if (isEmpty(current)) acc else impl(deleteMin(current), findMin(current) :: acc)

    impl(h).reverse
  }

  property("min1") = forAll { a: Int =>
    val h = insert(a, empty)
    findMin(h) == a
  }

  property("hint1") = forAll { (a: A, b: A) => BooleanOperators(a < b) ==> {
    val heap = insert(b, insert(a, empty))
    findMin(heap) == a
    }
  }

  property("hint2") = forAll { a: A =>
    val heap = deleteMin(insert(a, empty))
    isEmpty(heap)
  }

  property("hint3") = forAll { h: H =>
    val hlist = h.toList
    hlist == hlist.sorted
  }

  property("hint4") = forAll { (h: H, i: H) =>
    val min = findMin(meld(h, i))
    min == findMin(h) || min == findMin(i)
  }

  property("meld") = forAll { (h: H, i: H) =>
    meld(h, i).toList == (h.toList ++ i.toList).sorted
  }

  lazy val genHeap: Gen[H] = for {
    a <- arbitrary[A]
    h <- oneOf(const(empty), genHeap)
  } yield insert(a, h)

  implicit lazy val arbHeap: Arbitrary[H] = Arbitrary(genHeap)

}


text:
// Copyright © Microsoft Open Technologies, Inc.
//
// All Rights Reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
// ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
// PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache License, Version 2.0 for the specific language
// governing permissions and limitations under the License.

namespace Microsoft.Azure.ActiveDirectory.GraphClient
{
    using System;
    using System.Globalization;
    using System.Linq.Expressions;
    using System.Reflection;
    using Newtonsoft.Json;

    /// <summary>
    /// Helper methods for generating query filter expressions.
    /// </summary>
    public class ExpressionHelper
    {
        /// <summary>
        /// MethodInfo for the compare method on string.
        /// </summary>
        public static readonly MethodInfo CompareMethodInfo = typeof(string).GetMethod(
                "Compare", new Type[] { typeof(string), typeof(string) });

        /// <summary>
        /// Method definition of the StartsWith method.
        /// </summary>
        public static readonly MethodInfo StartsWithMethodInfo = typeof(string).GetMethod(
            "StartsWith", new Type[] { typeof(string) });

        /// <summary>
        /// Validates whether the binary expression is valid for OData query filters.
        /// </summary>
        /// <param name="binaryExpression">Binary expression</param>
        public static void ValidateBinaryExpression(BinaryExpression binaryExpression)
        {
            Utils.ThrowIfNull(binaryExpression, "binaryExpression");
        }

        /// <summary>
        /// Validates whether the binary expression is valid for OData query filters.
        /// </summary>
        /// <param name="binaryExpression">Binary expression</param>
        public static void ValidateLeafExpression(BinaryExpression binaryExpression)
        {
            Utils.ThrowIfNull(binaryExpression, "binaryExpression");

            ExpressionHelper.ValidateLeafNode(binaryExpression.Left);
            ExpressionHelper.ValidateLeafNode(binaryExpression.Right);
        }

        /// <summary>
        /// Validates whether the binary expression is valid AND / OR expression.
        /// </summary>
        /// <param name="binaryExpression">Binary conjuctive expression.</param>
        public static void ValidateConjunctiveExpression(BinaryExpression binaryExpression)
        {
            Utils.ThrowIfNull(binaryExpression, "binaryExpression");

            ExpressionHelper.ValidateConjuctiveNode(binaryExpression.Left);
            ExpressionHelper.ValidateConjuctiveNode(binaryExpression.Right);
        }

        /// <summary>
        /// Validate whether the leaf node is valid.
        /// </summary>
        /// <param name="expression">Expression node.</param>
        public static void ValidateLeafNode(Expression expression)
        {
            Utils.ThrowIfNull(expression, "expression");

            if (expression.NodeType != ExpressionType.MemberAccess &&
                expression.NodeType != ExpressionType.Constant &&
                expression.NodeType != ExpressionType.Call)
            {
                throw new ArgumentException("The expression has an invalid leaf node.");
            }
        }

        /// <summary>
        /// Validate whether the node is a conjuctive node or not.
        /// </summary>
        /// <param name="expression">Expression node.</param>
        /// <remarks>Validates that the node is not a constant expression, but another sub expression.</remarks>
        public static void ValidateConjuctiveNode(Expression expression)
        {
            Utils.ThrowIfNull(expression, "expression");

            if (expression is ConstantExpression)
            {
                throw new ArgumentException("The expression has an invalid conjuctive node.");
            }
        }

        /// <summary>
        /// Creates an equals expression, based on the property name and value.
        /// </summary>
        /// <param name="entityType">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyValue">Property value.</param>
        /// <returns>Equals expression node.</returns>
        public static BinaryExpression CreateEqualsExpression(
            Type entityType, GraphProperty propertyName, object propertyValue)
        {
            return ExpressionHelper.CreateConditionalExpression(
                entityType, propertyName, propertyValue, ExpressionType.Equal);
        }

        /// <summary>
        /// Creates a less than or equals expression, based on the property name and value.
        /// </summary>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyValue">Property value.</param>
        /// <returns>Equals expression node.</returns>
        public static BinaryExpression CreateLessThanEqualsExpression(
            Type entityType, GraphProperty propertyName, object propertyValue)
        {
            return ExpressionHelper.CreateConditionalExpression(
                entityType, propertyName, propertyValue, ExpressionType.LessThanOrEqual);
        }

        /// <summary>
        /// Creates a greater than or equals expression, based on the property name and value.
        /// </summary>
        /// <param name="entityType">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyValue">Property value.</param>
        /// <returns>Equals expression node.</returns>
        public static BinaryExpression CreateGreaterThanEqualsExpression(
            Type entityType, GraphProperty propertyName, object propertyValue)
        {
            return ExpressionHelper.CreateConditionalExpression(
                entityType, propertyName, propertyValue, ExpressionType.GreaterThanOrEqual);
        }

        /// <summary>
        /// Creates a less than or equals expression, based on the property name and value.
        /// </summary>
        /// <param name="entityTpe">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyValue">Property value.</param>
        /// <returns>Equals expression node.</returns>
        /// <remarks>
        /// Conditional expressions supported are Equals, GreaterThanEquals and LessThanEquals
        /// Equals binary expression is supported on all types.
        /// GreaterThanEquals and LessThanEquals are supported in int, long etc.. but not on
        /// strings. To generate these expressions on strings, we need to use the Compare function.
        /// </remarks>
        public static BinaryExpression CreateConditionalExpression(
            Type entityType, GraphProperty propertyName, object propertyValue, ExpressionType expressionType)
        {
            Utils.ThrowIfNull(entityType, "entityType");
            Utils.ThrowIfNullOrEmpty(propertyName, "propertyName");
            Utils.ThrowIfNullOrEmpty(propertyValue, "propertyValue");

            if (expressionType != ExpressionType.Equal &&
                expressionType != ExpressionType.GreaterThanOrEqual &&
                expressionType != ExpressionType.LessThanOrEqual)
            {
                throw new ArgumentException("Unsupported expression type.", "expressionType");
            }

            PropertyInfo propertyInfo;
            MemberExpression memberExpression = ExpressionHelper.GetMemberExpression(
                entityType, propertyName, out propertyInfo);

            Type propertyType = propertyInfo.PropertyType;

            string expectedPropertyTypeFullName = propertyType.FullName;

            // Nullable types have to converted before an Expression can be generated.
            bool isConversionRequired = false;
            if (propertyType.IsGenericType &&
                propertyType.GetGenericTypeDefinition() == typeof (Nullable<>))
            {
                expectedPropertyTypeFullName = propertyType.GetGenericArguments()[0].FullName;
                isConversionRequired = true;
            }

            string propertyValueTypeFullName = propertyValue.GetType().FullName;

            if (!String.Equals(expectedPropertyTypeFullName, propertyValueTypeFullName))
            {
                throw new ArgumentException("Property types do not match.");
            }

            // ge and le are currently supported only on int and strings.
            // TODO: Enable it for DateTime
            if (expressionType == ExpressionType.GreaterThanOrEqual ||
                expressionType == ExpressionType.LessThanOrEqual)
            {
                if (!string.Equals(typeof(string).FullName, expectedPropertyTypeFullName) &&
                    !string.Equals(typeof(int).FullName, expectedPropertyTypeFullName))
                {
                    throw new ArgumentException("Comparison is supported only on string and int values.");
                }
            }

            // Get the method info for Compare and create the expression such that
            // string.compare(propertyName, 'value') <= 0
            Expression methodCallExpression = null;

            if (expectedPropertyTypeFullName.Equals(typeof(string).FullName))
            {
                methodCallExpression = Expression.Call(
                    ExpressionHelper.CompareMethodInfo,
                    memberExpression,
                    Expression.Constant(propertyValue));
            }

            switch (expressionType)
            {
                case ExpressionType.Equal:
                    if (isConversionRequired)
                    {
                        return Expression.Equal(memberExpression, Expression.Constant(propertyValue, propertyType));
                    }

                    return Expression.Equal(memberExpression, Expression.Constant(propertyValue));
                case ExpressionType.LessThanOrEqual:
                    return Expression.LessThanOrEqual(methodCallExpression, Expression.Constant(0));
                case ExpressionType.GreaterThanOrEqual:
                    return Expression.GreaterThanOrEqual(methodCallExpression, Expression.Constant(0));
                default:
                    throw new ArgumentException("Unsupported expression type.");
            }
        }

        /// <summary>
        /// Get the member expression for the given property name.
        /// </summary>
        /// <param name="entityType">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyInfo">Set to the property info.</param>
        /// <returns>Member expression.</returns>
        public static MemberExpression GetMemberExpression(
            Type entityType, GraphProperty propertyName, out PropertyInfo propertyInfo)
        {
            Utils.ThrowIfNull(entityType, "entityType");

            MemberInfo[] memberInfo = entityType.GetMember(propertyName.ToString());
            if (memberInfo == null || memberInfo.Length != 1)
            {
                throw new ArgumentException("Unable to resolve the property in the specified type.");
            }

            propertyInfo = memberInfo[0] as PropertyInfo;

            // Validate that the JsonProperty attribute can be found on this property
            object[] customAttributes = propertyInfo.GetCustomAttributes(
                typeof(JsonPropertyAttribute), true);

            if (customAttributes == null || customAttributes.Length != 1)
            {
                throw new ArgumentException(
                    "Invalid property used in the filter. JsonProperty attribute was not found.");
            }

            // Create a member expression on a dummy object to create a valid expression.
            // BUGBUG: We shouldn't be creating a dummy instance. We should instead be generating the list from
            // a where clause. Like:
            // var users = FROM graphConnection.Users SELECT users WHERE User.DisplayName == 'blah'
            MemberExpression memberExpression = Expression.MakeMemberAccess(
                Expression.Constant(Activator.CreateInstance(entityType)), memberInfo[0]);

            return memberExpression;
        }

        /// <summary>
        /// Creates a simple starts with expression, based on the property name and value.
        /// </summary>
        /// <param name="entityType">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyValue">Property value.</param>
        /// <returns>Equals expression node.</returns>
        public static MethodCallExpression CreateStartsWithExpression(
            Type entityType, GraphProperty propertyName, string propertyValue)
        {
            Utils.ThrowIfNull(entityType, "entityType");
            Utils.ThrowIfNullOrEmpty(propertyName, "propertyName");
            Utils.ThrowIfNullOrEmpty(propertyValue, "propertyValue");

            PropertyInfo propertyInfo;
            MemberExpression memberExpression = ExpressionHelper.GetMemberExpression(
                entityType, propertyName, out propertyInfo);

            Type propertyType = propertyInfo.PropertyType;

            string expectedPropertyTypeFullName = propertyType.FullName;
            string propertyValueTypeFullName = propertyValue.GetType().FullName;

            if (!String.Equals(expectedPropertyTypeFullName, propertyValueTypeFullName))
            {
                throw new ArgumentException("Property types do not match.");
            }

            return Expression.Call(
                memberExpression, "StartsWith", new Type[]{ } , Expression.Constant(propertyValue));
        }

        /// <summary>
        /// Creates a simple any expression, based on the property name and value.
        /// </summary>
        /// <param name="entityType">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyValue">Property value.</param>
        /// <returns>Equals expression node.</returns>
        public static MethodCallExpression CreateAnyExpression(
            Type entityType, GraphProperty propertyName, object propertyValue)
        {
            Utils.ThrowIfNull(entityType, "entityType");
            Utils.ThrowIfNullOrEmpty(propertyName, "propertyName");

            // TODO: Generate an empty Any() filter when the propertyValue is null.
            Utils.ThrowIfNullOrEmpty(propertyValue, "propertyValue");

            PropertyInfo propertyInfo;
            MemberExpression memberExpression = ExpressionHelper.GetMemberExpression(
                entityType, propertyName, out propertyInfo);

            Type propertyType = propertyInfo.PropertyType;
            Type[] genericArguments = propertyType.GetGenericArguments();

            if (!propertyType.IsGenericType ||
                genericArguments == null ||
                genericArguments.Length != 1 ||
                !propertyType.Name.StartsWith(typeof(ChangeTrackingCollection<>).Name))
            {
                throw new ArgumentException("Any expression is not supported on this type.");
            }

            string expectedPropertyTypeFullName = propertyType.GetGenericArguments()[0].FullName;
            string propertyValueTypeFullName = propertyValue.GetType().FullName;

            if (!String.Equals(expectedPropertyTypeFullName, propertyValueTypeFullName))
            {
                throw new ArgumentException("Property types do not match.");
            }

            return Expression.Call(
                memberExpression, "Any", new Type[] { }, Expression.Constant(propertyValue));
        }

        /// <summary>
        /// Create And expressions from the following binary expressions.
        /// </summary>
        /// <param name="left">First expressions.</param>
        /// <param name="right">Second expression.</param>
        /// <returns>Joined binary expression.</returns>
        public static BinaryExpression JoinExpressions(
            Expression left, Expression right, ExpressionType expressionType)
        {
            Utils.ThrowIfNullOrEmpty(left, "left");
            Utils.ThrowIfNullOrEmpty(right, "right");

            switch (expressionType)
            {
                case ExpressionType.And:
                    return Expression.And(left, right);
                case ExpressionType.Or:
                    return Expression.Or(left, right);
                default:
                    throw new ArgumentException("Invalid expressionType");
            }
        }

        /// <summary>
        /// Get the formatted filter value.
        /// </summary>
        /// <param name="filterValue">Raw filter value.</param>
        /// <returns>Formatted filter value.</returns>
        public static string GetFormattedValue(object filterValue)
        {
            if (filterValue is bool)
            {
                return filterValue.ToString().ToLower();
            }

            if (filterValue is Guid)
            {
                return String.Format(
                    CultureInfo.InvariantCulture,
                    "Guid\'{0}\'",
                    filterValue);
            }

            byte[] filterValueAsBytes = filterValue as byte[];
            if (filterValueAsBytes != null)
            {
                return String.Format(
                    CultureInfo.InvariantCulture,
                    "X\'{0}\'",
                    Utils.BinToHexEncode(filterValueAsBytes));
            }

            if (filterValue is DateTime)
            {
                DateTime dateTime = (DateTime)filterValue;
                return String.Format(
                    CultureInfo.InvariantCulture,
                    "DateTime\'{0:s}Z\'",
                    dateTime.ToUniversalTime());
            }

            return "\'" + filterValue + "\'";
        }

        /// <summary>
        /// Get OData operator for the expression type.
        /// </summary>
        /// <param name="expressionType">Expression type.</param>
        /// <returns>OData operator.</returns>
        /// <exception cref="ArgumentException">Unsupported expression type.</exception>
        public static string GetODataOperator(ExpressionType expressionType)
        {
            switch (expressionType)
            {
                case ExpressionType.Equal:
                    return "eq";
                case ExpressionType.GreaterThanOrEqual:
                    return "ge";
                case ExpressionType.LessThanOrEqual:
                    return "le";
                default:
                    throw new ArgumentException("Unsupported expression type");
            }
        }

        /// <summary>
        /// Get the property name from the constant expression.
        /// </summary>
        /// <param name="binaryExpression">Binary expression.</param>
        /// <returns>Property name.</returns>
        /// <exception cref="ArgumentNullException">Null input expression.</exception>
        /// <exception cref="ArgumentException">Not a constant expression.</exception>
        /// <remarks>
        /// Following expressions are supported.
        /// displayName eq 'blah'
        /// Compare(displayName, 'blah') ge 0
        /// </remarks>
        public static string GetPropertyName(BinaryExpression binaryExpression)
        {
            Utils.ThrowIfNull(binaryExpression, "binaryExpression");

            MemberExpression memberExpression = binaryExpression.Left as MemberExpression;

            // Check the RHS for a member expression.
            if (memberExpression == null)
            {
                memberExpression = binaryExpression.Right as MemberExpression;
            }

            if (memberExpression != null)
            {
                return ExpressionHelper.GetPropertyName(memberExpression);
            }

            MethodCallExpression methodCallExpression = binaryExpression.Left as MethodCallExpression;

            if (methodCallExpression == null)
            {
                methodCallExpression = binaryExpression.Right as MethodCallExpression;
            }

            if (methodCallExpression != null)
            {
                // Make sure that we are looking at the 2 argument compare method on a string.
                if (methodCallExpression.Method != ExpressionHelper.CompareMethodInfo)
                {
                    throw new ArgumentException("Unexpected method call in the binary expression.");
                }

                memberExpression = methodCallExpression.Arguments[0] as MemberExpression;

                if (memberExpression == null)
                {
                    memberExpression = methodCallExpression.Arguments[1] as MemberExpression;
                }

                if (memberExpression != null)
                {
                    return ExpressionHelper.GetPropertyName(memberExpression);
                }
            }

            throw new ArgumentException("Unable to extract the propertyName from the expression.");
        }

        /// <summary>
        /// Gets the property name from a member expresion.
        /// </summary>
        /// <param name="memberExpression">Member expression.</param>
        /// <returns>Property name.</returns>
        public static string GetPropertyName(MemberExpression memberExpression)
        {
            Utils.ThrowIfNull(memberExpression, "memberExpression");

            Utils.ThrowArgumentExceptionIfNullOrEmpty(memberExpression.Member, "Invalid MemberInfo");

            object[] customProperties = memberExpression.Member.GetCustomAttributes(
                typeof (JsonPropertyAttribute), true);

            if (customProperties == null || customProperties.Length != 1)
            {
                throw new ArgumentException("JsonProperty attribute was not found.");
            }

            JsonPropertyAttribute jsonPropertyAttribute = customProperties[0] as JsonPropertyAttribute;

            if (jsonPropertyAttribute == null)
            {
                throw new ArgumentException("JsonProperty attribute was not found.");
            }

            return jsonPropertyAttribute.PropertyName;
        }

        /// <summary>
        /// Get the property value from the binary expression.
        /// </summary>
        /// <param name="binaryExpression">Constant expression.</param>
        /// <returns>Property name.</returns>
        /// <exception cref="ArgumentNullException">Null input expression.</exception>
        /// <exception cref="ArgumentException">Not a constant expression.</exception>
        public static string GetPropertyValue(BinaryExpression binaryExpression)
        {
            Utils.ThrowIfNull(binaryExpression, "binaryExpression");

            // Check if this is a compare method.
            // Precedence for Compare method is a MUST as the the constant expression is found in both the cases.
            MethodCallExpression methodCallExpression = binaryExpression.Left as MethodCallExpression;

            if (methodCallExpression == null)
            {
                methodCallExpression = binaryExpression.Right as MethodCallExpression;
            }

            ConstantExpression constantExpression;
            if (methodCallExpression != null)
            {
                // Make sure that we are looking at the 2 argument compare method on a string.
                if (methodCallExpression.Method != ExpressionHelper.CompareMethodInfo)
                {
                    throw new ArgumentException("Unexpected method call in the binary expression.");
                }

                constantExpression = methodCallExpression.Arguments[1] as ConstantExpression;

                if (constantExpression == null)
                {
                    constantExpression = methodCallExpression.Arguments[0] as ConstantExpression;
                }

                if (constantExpression != null)
                {
                    return ExpressionHelper.GetPropertyValue(constantExpression);
                }
            }

            constantExpression = binaryExpression.Right as ConstantExpression;

            if (constantExpression == null)
            {
                constantExpression = binaryExpression.Left as ConstantExpression;
            }

            if (constantExpression != null)
            {
                return ExpressionHelper.GetPropertyValue(constantExpression);
            }

            throw new ArgumentException("Unable to extract the constant property value from expression.");
        }

        /// <summary>
        /// Get the property value from the binary expression.
        /// </summary>
        /// <param name="constantExpression">Constant expression.</param>
        /// <returns>Property name.</returns>
        /// <exception cref="ArgumentNullException">Null input expression.</exception>
        /// <exception cref="ArgumentException">Not a constant expression.</exception>
        public static string GetPropertyValue(ConstantExpression constantExpression)
        {
            Utils.ThrowIfNull(constantExpression, "constantExpression");

            return ExpressionHelper.GetFormattedValue(constantExpression.Value);
        }

        /// <summary>
        /// Get OData conjuctive operator for the expression type.
        /// </summary>
        /// <param name="expressionType">Expression type.</param>
        /// <returns>OData conjuction operator.</returns>
        /// <exception cref="ArgumentException">Unsupported expression type.</exception>
        public static string GetODataConjuctiveOperator(ExpressionType expressionType)
        {
            switch (expressionType)
            {
                case ExpressionType.And:
                    return "and";
                case ExpressionType.Or:
                    return "or";
                default:
                    throw new ArgumentException("Unsupported expression type");
            }
        }
    }
}


text:
package org.joshy.gfx.node.layout.mig;

import java.awt.HeadlessException;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.geom.Point2D;
import java.util.IdentityHashMap;

import org.joshy.gfx.draw.FlatColor;
import org.joshy.gfx.draw.Font;
import org.joshy.gfx.node.Bounds;
import org.joshy.gfx.node.NodeUtils;
import org.joshy.gfx.node.control.Button;
import org.joshy.gfx.node.control.Control;
import org.joshy.gfx.node.control.Label;
import org.joshy.gfx.node.control.ListView;
import org.joshy.gfx.node.control.PopupMenuButton;
import org.joshy.gfx.node.control.ProgressBar;
import org.joshy.gfx.node.control.ScrollPane;
import org.joshy.gfx.node.control.Scrollbar;
import org.joshy.gfx.node.control.Slider;
import org.joshy.gfx.node.control.SpinBox;
import org.joshy.gfx.node.control.TableView;
import org.joshy.gfx.node.control.TextControl;
import org.joshy.gfx.node.control.Textarea;
import org.joshy.gfx.node.control.Textbox;
import org.joshy.gfx.node.control.Togglebutton;
import org.joshy.gfx.node.layout.Container;
import org.joshy.gfx.node.layout.Panel;
import org.joshy.gfx.node.layout.mig.layout.ComponentWrapper;
import org.joshy.gfx.node.layout.mig.layout.ContainerWrapper;
import org.joshy.gfx.node.layout.mig.layout.PlatformDefaults;
import org.joshy.gfx.node.shape.Rectangle;

/**
 * A wrapper to wrap the amino components for usage in miglayout.
 */
public class AminoComponentWrapper implements ComponentWrapper
{
	private static boolean vp = true;

	private final Control c;
	private int compType = TYPE_UNSET;
	private boolean prefCalled = false;

	public AminoComponentWrapper(Control c)
	{
		this.c = c;
	}

	public final int getBaseline(int width, int height)
	{
		return (int) c.getBaseline();
	}

	public final Object getComponent()
	{
		return c;
	}

	/** Cache.
	 */
	private final static IdentityHashMap<Font, Point.Float> FM_MAP = new IdentityHashMap<Font, Point.Float>(4);
	private final static Font SUBST_FONT =  Font.DEFAULT;

	public final float getPixelUnitFactor(boolean isHor)
	{
		switch (PlatformDefaults.getLogicalPixelBase()) {
			case PlatformDefaults.BASE_FONT_SIZE:
				Font font = SUBST_FONT;
				if (c instanceof TextControl) {
					font = ((TextControl)c).getFont();
				}
				Point.Float p = FM_MAP.get(font);
				if (p == null) {
					double fw = font.calculateWidth("X");
					double fh = font.calculateHeight("X");
					p = new Point.Float((float)(fw / 6f), (float)(fh / 13.27734375f));
					FM_MAP.put(font, p);
				}
				return isHor ? p.x : p.y;

			case PlatformDefaults.BASE_SCALE_FACTOR:

				Float s = isHor ? PlatformDefaults.getHorizontalScaleFactor() : PlatformDefaults.getVerticalScaleFactor();
				if (s != null)
					return s.floatValue();
				return (isHor ? getHorizontalScreenDPI() : getVerticalScreenDPI()) / (float) PlatformDefaults.getDefaultDPI();

			default:
				return 1f;
		}
	}

//	/** Cache.
//	 */
//	private final static IdentityHashMap<FontMetrics, Point.Float> FM_MAP2 = new IdentityHashMap<FontMetrics, Point.Float>(4);
//	private final static Font SUBST_FONT2 = new Font("sansserif", Font.PLAIN, 11);
//
//	public float getDialogUnit(boolean isHor)
//	{
//		Font font = c.getFont();
//		FontMetrics fm = c.getFontMetrics(font != null ? font : SUBST_FONT2);
//		Point.Float dluP = FM_MAP2.get(fm);
//		if (dluP == null) {
//			float w = fm.charWidth('X') / 4f;
//			int ascent = fm.getAscent();
//			float h = (ascent > 14 ? ascent : ascent + (15 - ascent) / 3) / 8f;
//
//			dluP = new Point.Float(w, h);
//			FM_MAP2.put(fm, dluP);
//		}
//		return isHor ? dluP.x : dluP.y;
//	}

	public final int getX()
	{
		return (int) c.getTranslateX();
	}

	public final int getY()
	{
		return (int) c.getTranslateY();
	}

	public final int getHeight()
	{
		return (int) c.getHeight();
	}

	public final int getWidth()
	{
		return (int) c.getWidth();
	}

	public final int getScreenLocationX()
	{
		Point2D p = NodeUtils.convertToScreen(c, 0, 0);
		return (int) p.getX();
	}

	public final int getScreenLocationY()
	{
		Point2D p = NodeUtils.convertToScreen(c, 0, 0);
		return (int) p.getY();
	}

	public final int getMinimumHeight(int sz)
	{
		return 10; // TODO rossi 14.12.2010 does amino support this.
	}

	public final int getMinimumWidth(int sz)
	{
		return 10; // TODO rossi 14.12.2010 does amino support this.
	}
	public final int getPreferredHeight(int sz)
	{
		if (prefCalled == false) {
			c.doPrefLayout(); // To defeat a bug where the minimum size is different before and after the first call to getPreferredSize();
			prefCalled = true;
		}

		return (int) c.getHeight();
	}

	public final int getPreferredWidth(int sz)
	{
		if (prefCalled == false) {
			c.doPrefLayout(); // To defeat a bug where the minimum size is different before and after the first call to getPreferredSize();
			prefCalled = true;
		}

		return (int) c.getWidth();
	}

	public final int getMaximumHeight(int sz)
	{
		return Short.MAX_VALUE;
	}

	public final int getMaximumWidth(int sz)
	{
		return Short.MAX_VALUE;
	}

	public final ContainerWrapper getParent()
	{
		Container p = (Container) c.getParent();
		return p != null ? new AminoContainerWrapper(p) : null;
	}

	public final int getHorizontalScreenDPI()
	{
		return PlatformDefaults.getDefaultDPI();
	}

	public final int getVerticalScreenDPI()
	{
		return PlatformDefaults.getDefaultDPI();
	}

	public final int getScreenWidth()
	{
		try {
			return Toolkit.getDefaultToolkit().getScreenSize().width;
		} catch (HeadlessException ex) {
			return 1024;
		}
	}

	public final int getScreenHeight()
	{
		try {
			return Toolkit.getDefaultToolkit().getScreenSize().height;
		} catch (HeadlessException ex) {
			return 768;
		}
	}

	public final boolean hasBaseline()
	{
		return true; // TODO rossi 14.12.2010 is Control.getBaseline reliable yet?
	}

	public final String getLinkId()
	{
		return c.getId();
	}

	public final void setBounds(int x, int y, int width, int height)
	{
		c.setTranslateX(x);
		c.setTranslateY(y);
		c.setWidth(width);
		c.setHeight(height);
	}

	public boolean isVisible()
	{
		return c.isVisible();
	}

	public final int[] getVisualPadding()
	{
		if (vp) {
			Bounds lb = c.getLayoutBounds();
			Bounds vb = c.getVisualBounds();
			return new int[]{
				(int) (lb.getX()-vb.getX()),
				(int) (lb.getY()-vb.getY()),
				(int) (lb.getX2()-vb.getX2()),
				(int) (lb.getY2()-vb.getY2())
			};
		}
		return null;
	}

	public static boolean isVisualPaddingEnabled()
	{
		return vp;
	}

	public static void setVisualPaddingEnabled(boolean b)
	{
		vp = b;
	}

	public final void paintDebugOutline()
	{
		Container container = (Container) ((Control)getComponent()).getParent();
		Rectangle frame = new Rectangle(getX(), getY(), getWidth(), getHeight());
		frame.setFill(new FlatColor(0, 0));
		frame.setStroke(FlatColor.BLUE);
		container.add(frame);
	}

	public int getComponetType(boolean disregardScrollPane)
	{
		if (compType == TYPE_UNSET)
			compType = checkType(disregardScrollPane);

		return compType;
	}

	public int getLayoutHashCode()
	{
		int h = c.getLayoutBounds().hashCode();
		if (c.isVisible()) {
			h += 1324511;
		}
		String id = getLinkId();
		if (id != null) {
			h += id.hashCode();
		}
		return h;

		// Since 2.3 will check the isValid instead everything that affects that can be removed from the layout hashcode.

//		String id = getLinkId();
//		return id != null ? id.hashCode() : 1;
	}

	private final int checkType(boolean disregardScrollPane)
	{
		Control cmp = this.c;
		if (disregardScrollPane) {
			if (cmp instanceof ScrollPane) {
				cmp = (Control) ((ScrollPane)cmp).children().iterator().next();
			}
		}

		if (cmp instanceof Textbox) {
			return TYPE_TEXT_FIELD;
		} else if (cmp instanceof Label) {
			return TYPE_LABEL;
		} else if (cmp instanceof Togglebutton) {
			return TYPE_CHECK_BOX;
		} else if (cmp instanceof Button) {
			return TYPE_BUTTON;
		} else if (cmp instanceof PopupMenuButton) {
			return TYPE_LABEL;
		} else if (cmp instanceof Textarea) {
			return TYPE_TEXT_AREA;
		} else if (cmp instanceof Panel) {
			return TYPE_PANEL;
		} else if (cmp instanceof ListView) {
			return TYPE_LIST;
		} else if (cmp instanceof TableView) {
			return TYPE_TABLE;
//		} else if (c instanceof Separator) {
//			return TYPE_SEPARATOR;
		} else if (cmp instanceof SpinBox) {
			return TYPE_SPINNER;
		} else if (cmp instanceof ProgressBar) {
			return TYPE_PROGRESS_BAR;
		} else if (cmp instanceof Slider) {
			return TYPE_SLIDER;
		} else if (cmp instanceof ScrollPane) {
			return TYPE_SCROLL_PANE;
		} else if (cmp instanceof Scrollbar) {
			return TYPE_SCROLL_BAR;
		} else if (cmp instanceof Container) {
			return TYPE_CONTAINER;
		}
		return TYPE_UNKNOWN;
	}

	public final int hashCode()
	{
		return getComponent().hashCode();
	}

	public final boolean equals(Object o)
	{
		if (o instanceof ComponentWrapper == false)
			return false;

		return getComponent().equals(((ComponentWrapper) o).getComponent());
	}

}


text:
The helper scripts for [crystal-build](https://github.com/pine/crystal-build).

## Requirements

- Ruby `$(cat .ruby-version)`
- Bundler
- GitHub access token

## Usage

```
$ rake setup
$ rake generate
$ rake update
```

## License

BSD © Pine Mizune