text:
/* eslint-disable require-jsdoc */

const Constants = require('../../constants');
const DeviceProfiles = require('../../data/DeviceProfiles');

class Wap {
  constructor(header, data) {
    this.data = data;
    header = header.trim();
    if (header.startsWith('"')) {
      header = header.split(',');
      header = header[0].replace(/^"+/, '').replace(/"+$/, '');
    }
    const result = DeviceProfiles.identify(header);
    if (result) {
      this.data.device.manufacturer = result[0];
      this.data.device.model = result[1];
      this.data.device.identified |= Constants.id.MATCH_PROF;
      if (result[2] && (!this.data.os.name || this.data.os.name !== result[2])) {
        this.data.os.name = result[2];
        this.data.os.version = null;
        this.data.engine.name = null;
        this.data.engine.version = null;
      }
      if (result[3]) {
        this.data.device.type = result[3];
      }
    }
  }
}

module.exports = Wap;


text:
var packageName = 'angularui:angular-ui-router'; // https://atmospherejs.com/angularui/angular-ui-router
var where = 'client'; // where to install: 'client' or 'server'. For both, pass nothing.
var version = '0.2.15';

Package.describe({
  name: packageName,
  version: version,
  summary: 'angular-ui-router (official): Flexible routing with nested views in AngularJS',
  git: 'git@github.com:angular-ui/ui-router.git',
  documentation: null
});

Package.onUse(function(api) {
  api.versionsFrom(['METEOR@0.9.0', 'METEOR@1.0']);

  api.use('angular:angular@1.0.8', where);

  api.addFiles('release/angular-ui-router.js', where);
});

redpajama_set_name: RedPajamaGithub


text:
#ifndef	_SPAMILTER_IFI_H_
#define	_SPAMILTER_IFI_H_

	#define	IFI_NAME	16			/* same as IFNAMSIZ in <net/if.h> */
	#define	IFI_HADDR	8			/* allow for 64-bit EUI-64 in future */
	#define	IFI_ALIAS	1			/* ifi_addr is an alias */

	struct ifi_info
	{
		char ifi_name[IFI_NAME];		/* interface name, null terminated */
		u_char ifi_haddr[IFI_HADDR];		/* hardware address */
		u_short ifi_hlen;			/* #bytes in hardware address: 0, 6, 8 */
		short ifi_flags;			/* IFF_xxx constants from <net/if.h> */
		short ifi_myflags;			/* our own IFI_xxx flags */
		struct sockaddr  *ifi_addr;		/* primary address */
		struct sockaddr  *ifi_brdaddr;		/* broadcast address */
		struct sockaddr  *ifi_dstaddr;		/* destination address */
#ifdef SIOCGIFNETMASK
		struct sockaddr  *ifi_netmask;		/* netmask */
#endif
		struct ifi_info  *ifi_next;		/* next of these structures */
	};

	/* function prototypes */
	struct ifi_info	*get_ifi_info(int, int);
	void free_ifi_info(struct ifi_info *);

	int ifi_islocalipAf(int afType, const char *pIn);
	int ifi_islocalnetAf(int afType, const char *pIn, const char *pDbPath);

#endif


text:
require 'spec_helper'
require 'data_tiering/sync/monitor'
require 'data_tiering/sync/sync_log'

describe DataTiering::Sync::Monitor do

  let(:time)   { Time.parse("12pm, 1st January 2020") }
  let(:switch) {
    s = DataTiering::Switch.new
    s.stub(:current_active_number => 1)
    s
  }

  subject { described_class.new(switch) }

  describe 'monitor' do

    before do
      Time.stub :current => time
      DataTiering::Sync::SyncLog.create!(
        :table_name => 'properties_secondary_1',
        :started_at => time - 20.seconds,
        :finished_at => time - 5.seconds
      )
    end

    it 'reports the most stale sync log for an active table' do
      subject.monitor
      subject.staleness.should == 20
    end

    it 'ignores the staleness of inactive tables' do
      DataTiering::Sync::SyncLog.create!(
        :table_name => 'properties_secondary_0',
        :started_at => time - 60.seconds,
        :finished_at => time - 55.seconds
      )

      subject.monitor
      subject.staleness.should == 20
    end

    it 'reports a big number on any exception' do
      subject.stub(:calculate_staleness).and_raise("some exception")

      subject.monitor
      subject.staleness.should == 10_000
    end

  end

end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Text;

namespace R2RDump
{
    ///
    /// If COR_ILMETHOD_SECT_HEADER::Kind() = CorILMethod_Sect_EHTable then the attribute
    /// is a list of exception handling clauses.  There are two formats, fat or small
    ///
    [Flags]
    public enum CorExceptionFlag
    {
        COR_ILEXCEPTION_CLAUSE_NONE,                    // This is a typed handler
        COR_ILEXCEPTION_CLAUSE_OFFSETLEN = 0x0000,      // Deprecated
        COR_ILEXCEPTION_CLAUSE_DEPRECATED = 0x0000,     // Deprecated
        COR_ILEXCEPTION_CLAUSE_FILTER = 0x0001,         // If this bit is on, then this EH entry is for a filter
        COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002,        // This clause is a finally clause
        COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004,          // Fault clause (finally that is called on exception only)
        COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008,     // duplicated clause. This clause was duplicated to a funclet which was pulled out of line

        COR_ILEXCEPTION_CLAUSE_KIND_MASK = COR_ILEXCEPTION_CLAUSE_FILTER | COR_ILEXCEPTION_CLAUSE_FINALLY | COR_ILEXCEPTION_CLAUSE_FAULT,
    }

    ///
    /// This class represents a single exception handling clause. It basically corresponds
    /// to IMAGE_COR_ILMETHOD_SECT_EH_CLAUSE_FAT in
    /// src\inc\corhdr.h.
    ///
    public class EHClause
    {
        ///
        /// Length of the serialized EH clause in the PE image.
        ///
        public const int Length = 6 * sizeof(uint);

        ///
        /// Flags describing the exception handler.
        ///
        CorExceptionFlag Flags;

        ///
        /// Starting offset of the try block
        ///
        public uint TryOffset;

        ///
        /// End offset of the try block
        ///
        public uint TryEnd;

        ///
        /// Offset of the exception handler for the try block
        ///
        public uint HandlerOffset;

        ///
        /// End offset of the exception handler
        ///
        public uint HandlerEnd;

        ///
        /// For type-based exception handlers, this is the type token.
        /// For filter-based exception handlers, this is the filter offset.
        ///
        public uint ClassTokenOrFilterOffset;

        ///
        /// Textual representation of the class represented by the class token.
        ///
        public string ClassName;

        ///
        /// Read the EH clause from a given file offset in the PE image.
        ///
        /// <param name="reader">R2R image reader<param>
        /// <param name="offset">Offset of the EH clause in the image</param>
        public EHClause(R2RReader reader, int offset)
        {
            Flags = (CorExceptionFlag)BitConverter.ToUInt32(reader.Image, offset + 0 * sizeof(uint));
            TryOffset = BitConverter.ToUInt32(reader.Image, offset + 1 * sizeof(uint));
            TryEnd = BitConverter.ToUInt32(reader.Image, offset + 2 * sizeof(uint));
            HandlerOffset = BitConverter.ToUInt32(reader.Image, offset + 3 * sizeof(uint));
            HandlerEnd = BitConverter.ToUInt32(reader.Image, offset + 4 * sizeof(uint));
            ClassTokenOrFilterOffset = BitConverter.ToUInt32(reader.Image, offset + 5 * sizeof(uint));

            if ((Flags & CorExceptionFlag.COR_ILEXCEPTION_CLAUSE_KIND_MASK) == CorExceptionFlag.COR_ILEXCEPTION_CLAUSE_NONE)
            {
                ClassName = MetadataNameFormatter.FormatHandle(reader.MetadataReader, MetadataTokens.Handle((int)ClassTokenOrFilterOffset));
            }
        }

        ///
        /// Emit a textual representation of the EH info to a given text writer.
        ///
        /// <param name="writer">Output writer for the textual representation</param>
        /// <param name="methodRva">Starting RVA of the runtime function is used to display the try / handler info as RVA intervals</param>
        public void WriteTo(TextWriter writer, int methodRva)
        {
            writer.Write($@"Flags {(uint)Flags:X2} ");
            writer.Write($@"TryOff {TryOffset:X4} (RVA {(TryOffset + methodRva):X4}) ");
            writer.Write($@"TryEnd {TryEnd:X4} (RVA {(TryEnd + methodRva):X4}) ");
            writer.Write($@"HndOff {HandlerOffset:X4} (RVA {(HandlerOffset + methodRva):X4}) ");
            writer.Write($@"HndEnd {HandlerEnd:X4} (RVA {(HandlerEnd + methodRva):X4}) ");
            writer.Write($@"ClsFlt {ClassTokenOrFilterOffset:X4}");

            switch (Flags & CorExceptionFlag.COR_ILEXCEPTION_CLAUSE_KIND_MASK)
            {
                case CorExceptionFlag.COR_ILEXCEPTION_CLAUSE_NONE:
                    writer.Write($" CATCH: {0}", ClassName ?? "null");
                    break;

                case CorExceptionFlag.COR_ILEXCEPTION_CLAUSE_FILTER:
                    writer.Write($" FILTER (RVA {0:X4})", ClassTokenOrFilterOffset + methodRva);
                    break;

                case CorExceptionFlag.COR_ILEXCEPTION_CLAUSE_FINALLY:
                    writer.Write(" FINALLY");
                    break;

                case CorExceptionFlag.COR_ILEXCEPTION_CLAUSE_FAULT:
                    writer.Write(" FAULT");
                    break;

                default:
                    throw new NotImplementedException(Flags.ToString());
            }

            if ((Flags & CorExceptionFlag.COR_ILEXCEPTION_CLAUSE_DUPLICATED) != (CorExceptionFlag)0)
            {
                writer.Write(" DUPLICATED");
            }
        }
    }

    ///
    /// This class represents EH info for a single runtime function. EH info
    /// is located using the map from runtime functions to EH clause lists in
    /// the READYTORUN_SECTION_EXCEPTION_INFO header table.
    ///
    public class EHInfo
    {
        ///
        /// RVA of the EH info in the PE image.
        ///
        public readonly int EHInfoRVA;

        ///
        /// Starting RVA of the corresponding runtime function.
        ///
        public readonly int MethodRVA;

        ///
        /// List of EH clauses for the runtime function.
        ///
        public readonly EHClause[] EHClauses;

        ///
        /// Construct the EH info for a given runtime method by reading it from a given offset
        /// in the R2R PE executable. The offset is located by looking up the starting
        /// IP address of the runtime function in the READYTORUN_SECTION_EXCEPTION_INFO table.
        /// The length of the
        ///
        /// <param name="reader">R2R PE image reader</param>
        /// <param name="ehInfoRva">RVA of the EH info</param>
        /// <param name="methodRva">Starting RVA of the runtime function</param>
        /// <param name="offset">File offset of the EH info</param>
        /// <param name="clauseCount">Number of EH info clauses</param>
        public EHInfo(R2RReader reader, int ehInfoRva, int methodRva, int offset, int clauseCount)
        {
            EHInfoRVA = ehInfoRva;
            MethodRVA = methodRva;
            EHClauses = new EHClause[clauseCount];
            for (int clauseIndex = 0; clauseIndex < clauseCount; clauseIndex++)
            {
                EHClauses[clauseIndex] = new EHClause(reader, offset + clauseIndex * EHClause.Length);
            }
        }

        ///
        /// Emit the textual representation of the EH info into a given writer.
        ///
        public void WriteTo(TextWriter writer)
        {
            foreach (EHClause ehClause in EHClauses)
            {
                ehClause.WriteTo(writer, MethodRVA);
                writer.WriteLine();
            }
        }
    }

    ///
    /// Location of the EH clauses for a single runtime function
    ///
    public class EHInfoLocation
    {
        ///
        /// RVA of the EH clause list in the R2R PE image
        ///
        public readonly int EHInfoRVA;

        ///
        /// Number of EH clauses
        ///
        public readonly int ClauseCount;

        public EHInfoLocation(int ehInfoRva, int clauseCount)
        {
            EHInfoRVA = ehInfoRva;
            ClauseCount = clauseCount;
        }
    }

    ///
    /// Lookup table maps IP RVAs to EH info.
    ///
    public class EHLookupTable
    {
        ///
        /// Map from runtime function RVA's to EH info location in the R2R PE file.
        ///
        public readonly Dictionary<int, EHInfoLocation> RuntimeFunctionToEHInfoMap;

        ///
        /// Reads the EH info lookup table from the PE image.
        ///
        /// <param name="image">R2R PE image</param>
        /// <param name="offset">Starting offset of the EH info in the PE image</param>
        /// <param name="length">Byte length of the EH info</param>
        public EHLookupTable(byte[] image, int offset, int length)
        {
            RuntimeFunctionToEHInfoMap = new Dictionary<int, EHInfoLocation>();

            int rva1 = BitConverter.ToInt32(image, offset);
            int eh1 = BitConverter.ToInt32(image, offset + sizeof(uint));

            while ((length -= 2 * sizeof(uint)) >= 8)
            {
                offset += 2 * sizeof(uint);
                int rva2 = BitConverter.ToInt32(image, offset);
                int eh2 = BitConverter.ToInt32(image, offset + sizeof(uint));

                RuntimeFunctionToEHInfoMap.Add(rva1, new EHInfoLocation(eh1, (eh2 - eh1) / EHClause.Length));

                rva1 = rva2;
                eh1 = eh2;
            }
        }
    }
}


text:
static void *PanGesterContext = &PanGesterContext;

@interface LoopScrollView()<UIGestureRecognizerDelegate>

@property (nonatomic, assign) NSInteger pageCount;

@end

@implementation LoopScrollView

+ (LoopScrollView *)loopScrllViewWithImageArray:(NSArray *)imageArray frame:(CGRect)frame setImageBlock:(void (^)(UIButton *, NSString *))setImageBlock
{
    LoopScrollView *loop = [[LoopScrollView alloc] initWithFrame:frame];
    loop.imageArray = [NSMutableArray arrayWithArray:imageArray];
    loop.contentArray = [[NSMutableArray alloc] init];
    loop.setImageBlock = setImageBlock;
    loop.pageCount = imageArray.count;
    [loop configueScrollView];
    return loop;
}

- (void)setIsLoop:(BOOL)isLoop
{
    _isLoop = isLoop;
    self.scrollView.isLoop = isLoop;
}

#pragma mark - 设置scrollview
- (void)configueScrollView
{
    self.scrollView = [[MyScrollView alloc] initWithFrame:self.bounds];
    [self addSubview:self.scrollView];
    self.isLoop = YES;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    self.scrollView.delegate = self;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.pageCount = self.pageCount;
    self.scrollView.nowIndex = 0;
    NSInteger sizeNumber = 3;
    if (self.pageCount <= 1)
    {
        sizeNumber = 1;
    }
    self.scrollView.contentSize = CGSizeMake(sizeNumber * Width(self), 0);
    CGFloat contentofSetX = Width(self);
    if (self.pageCount == 1)
    {
        contentofSetX = 0;
    }
    self.scrollView.contentOffset = CGPointMake(contentofSetX,0);
    self.currentIndex = 0;
    [self setScrollViewContent];
}

#pragma mark - 设置pageControl
- (void)configuePageControlNormalColor:(UIColor *)normalColor selectColor:(UIColor *)selectColor  marginWithBottom:(CGFloat)bottomMargin
{
    self.pageControl = [UIPageControl alloc];
    CGSize pageControlSize = [self.pageControl sizeForNumberOfPages:self.imageArray.count];
    self.pageControl = [self.pageControl initWithFrame:CGRectMake(0, 0, pageControlSize.width, pageControlSize.height)];
    self.pageControl.numberOfPages = self.imageArray.count;
    self.pageControl.currentPageIndicatorTintColor = selectColor;
    self.pageControl.pageIndicatorTintColor = normalColor;
    CGPoint pageControlCenter = self.pageControl.center;
    pageControlCenter.x = Width(self) / 2;
    pageControlCenter.y = Height(self) - bottomMargin - Height(self.pageControl) / 2;
    self.pageControl.center = pageControlCenter;
    [self addSubview:self.pageControl];
}

#pragma mark - 设置titleLabel
//TODO: 应该添加方便设置label位置的方法 类pageControl
- (void)setTitleWithTitleArray:(NSArray *)titleArray Frame:(CGRect)frame textColor:(UIColor *)textColor fontSize:(CGFloat)fontSize
{
    self.titleArray = [NSMutableArray arrayWithArray:titleArray];
    self.titleLabelArray = [[NSMutableArray alloc] init];
    for(int i = 0; i < self.contentArray.count; i++){

        UIButton *btn = [self.contentArray objectAtIndex:i];
        [btn addTarget:self action:@selector(clickView:) forControlEvents:(UIControlEventTouchUpInside)];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:frame];
        [titleLabel setTextColor:textColor];
        titleLabel.font = [UIFont systemFontOfSize:fontSize];
        [self.titleLabelArray addObject:titleLabel];
        [btn addSubview:titleLabel];
    }
    NSInteger firstIndex = [self validIndex:-1];
    NSMutableArray *contentTitleArray = [self getNowTitleArrayWithIndexArray:@[NSNumberValue(firstIndex),@0,@1]];
    [self setContentTitleWithArray:contentTitleArray];
}

- (NSMutableArray *)getNowImageArrayWithIndexArray:(NSArray *)array
{
    NSAssert(self.imageArray.count > 0, @"图片数组不能为空");
    NSMutableArray *contentImageArray = [[NSMutableArray alloc] init];
    [contentImageArray addObject:[self.imageArray objectAtIndex:[[array objectAtIndex:0] integerValue]]];
    if (self.pageCount > 1)
    {
        [contentImageArray addObject:[self.imageArray objectAtIndex:[[array objectAtIndex:1] integerValue]]];
        if (self.pageCount == 2)
        {
            [contentImageArray addObject:[self.imageArray objectAtIndex:[[array objectAtIndex:0] integerValue]]];
        }
    }
    if (self.pageCount > 2)
    {
        [contentImageArray addObject:[self.imageArray objectAtIndex:[[array objectAtIndex:2] integerValue]]];
    }
    return contentImageArray;
}

- (NSMutableArray *)getNowTitleArrayWithIndexArray:(NSArray *)array
{
    NSMutableArray *contentTitleArray = [[NSMutableArray alloc] init];
    [contentTitleArray addObject:[self.titleArray objectAtIndex:[[array objectAtIndex:0] integerValue]]];
    if (self.pageCount > 1)
    {
        [contentTitleArray addObject:[self.titleArray objectAtIndex:[[array objectAtIndex:1] integerValue]]];
        if (self.pageCount == 2)
        {
            [contentTitleArray addObject:[self.titleArray objectAtIndex:[[array objectAtIndex:0] integerValue]]];
        }
    }
    if (self.pageCount > 2)
    {
        [contentTitleArray addObject:[self.titleArray objectAtIndex:[[array objectAtIndex:2] integerValue]]];
    }
    return contentTitleArray;
}

- (void)setScrollViewContent
{
    CGFloat selfWidth = CGRectGetWidth(self.frame);
    CGFloat selfHeight = CGRectGetHeight(self.frame);
    NSInteger firstIndex = [self validIndex:-1];
    NSMutableArray *contentImageArray = [self getNowImageArrayWithIndexArray:@[NSNumberValue(firstIndex),@0,@1]];
    NSInteger loopCount = 3;
    if (self.pageCount < 2)
    {
        loopCount = self.pageCount;
    }
    for (int i = 0; i < loopCount; i++) {

        UIButton *view = [[UIButton alloc] init];
        view.adjustsImageWhenHighlighted = NO;
        view.tag = i;
        view.frame = CGRectMake(i * selfWidth, 0, selfWidth, selfHeight);
        [self.contentArray addObject:view];
        [self.scrollView addSubview:view];
    }
    [self setContentViewImageWithArray:contentImageArray];
}

- (NSString *)imagePathWithImageName:(NSString *)imageName
{
    NSString *ext = [imageName pathExtension];
    NSString *prefix = [imageName stringByDeletingPathExtension];
    return [[NSBundle mainBundle] pathForResource:prefix ofType:ext];
}

- (void)setContentViewImageWithArray:(NSMutableArray *)imageArray
{
    for(int i = 0; i < imageArray.count; i++){

        UIButton *btn = [self.contentArray objectAtIndex:i];
        NSString *imageName = [imageArray objectAtIndex:i];
        NSString *imagePath = [self imagePathWithImageName:imageName];
        if (self.setImageBlock == nil) {

            [btn setImage:[UIImage imageWithContentsOfFile:imagePath] forState:(UIControlStateNormal)];
        }
        else{

            self.setImageBlock(btn,imageName);
        }
    }
}

- (void)setContentTitleWithArray:(NSMutableArray *)titleArray
{
    for(int i = 0; i < titleArray.count; i++){

        UILabel *label = [self.titleLabelArray objectAtIndex:i];
        label.text = [titleArray objectAtIndex:i];
    }
}

#pragma mark - scrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.pageCount > 1)
    {
        CGFloat x = scrollView.contentOffset.x;
        if (x == 2 * Width(self)) {

            [self scrollToNextPage:YES];
        }
        else if (x == 0){

            [self scrollToNextPage:NO];
        }
    }
}

- (NSInteger)validIndex:(NSInteger)index
{
     NSInteger imageNumbers = self.imageArray.count;
    if (index < 0) {

        index = imageNumbers - 1;
    }
    else if (index > imageNumbers - 1){

        index = 0;
    }
    return index;
}

#pragma mark - next为YES则翻到下一页   NO翻到上一页
- (void)scrollToNextPage:(BOOL)next
{
    NSInteger firstIndex,secondIndex,thridIndex;
    if (next) {

        firstIndex = self.currentIndex;
        secondIndex = [self validIndex:self.currentIndex + 1];
        thridIndex = [self validIndex:secondIndex + 1];
    }
    else{

        thridIndex = self.currentIndex;
        secondIndex = [self validIndex:self.currentIndex - 1];
        firstIndex = [self validIndex:secondIndex - 1];
    }
    NSArray *nowIndexArray = [NSArray arrayWithObjects:NSNumberValue(firstIndex),NSNumberValue(secondIndex),NSNumberValue(thridIndex), nil];

    NSMutableArray *nowImageArray = [self getNowImageArrayWithIndexArray:nowIndexArray];
    [self setContentViewImageWithArray:nowImageArray];
    if (self.titleArray != nil) {

        NSMutableArray *nowTitleArray = [self getNowTitleArrayWithIndexArray:nowIndexArray];
        [self setContentTitleWithArray:nowTitleArray];
    }
    self.currentIndex = secondIndex;
    if([self.delegate respondsToSelector:@selector(viewScrollToPage:)])
    {
        [self.delegate viewScrollToPage:self.currentIndex];
    }
    self.pageControl.currentPage = self.currentIndex;
    self.scrollView.nowIndex = self.currentIndex;
    self.scrollView.contentOffset = CGPointMake(Width(self),0);
}

- (void)beginAutoScroll
{
    [self.scrollView setContentOffset:CGPointMake(2 * Width(self), 0) animated:YES];
}

- (void)startAutoScrollWithInterval:(CGFloat)interval
{
    if (self.pageCount > 1)
    {
        self.autoScrollTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(beginAutoScroll) userInfo:nil repeats:YES];
        self.isAutoLoop = YES;
    }
}

- (void)stopAutoScroll
{
    [self.autoScrollTimer invalidate];
    self.autoScrollTimer = nil;
    self.isAutoLoop = NO;
}

- (void)clickView:(UIButton *)sender
{
    if ([self.delegate respondsToSelector:@selector(clickWithIndex:)]) {

        [self.delegate clickWithIndex:self.currentIndex];
    }
}

- (void)setPageControlPositionTop:(CGFloat)top left:(CGFloat)left
{
    CGRect pageControlFrame = self.pageControl.frame;
    pageControlFrame.origin.x = left;
    pageControlFrame.origin.y = top;
    self.pageControl.frame = pageControlFrame;
}

- (void)setPageControlPositionBottom:(CGFloat)bottom right:(CGFloat)right
{
    CGRect pageControlFrame = self.pageControl.frame;
    pageControlFrame.origin.x = Width(self) - right - Width(self.pageControl);
    pageControlFrame.origin.y = Height(self) - bottom - Height(self.pageControl);
    self.pageControl.frame = pageControlFrame;
}

- (void)releaseSelf
{
    [self stopAutoScroll];
    [self removeFromSuperview];
}

- (void)dealloc
{
    NSLog(@"loop scrollView被释放了");
}

@end


text:
## `Render` Props
A `render` prop is a function prop that a component uses to know what to render.

A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.

```jsx
<DataProvider render={data => (
  <h1>Hello {data.target}</h1>
)}/>
```

Libraries that use `render` props include [React Router](https://reacttraining.com/react-router/web/api/Route/Route-render-methods) and [Downshift](https://github.com/paypal/downshift).

### Use Render Props for Cross-Cutting Concerns
```javascript
class Cat extends React.Component {
  render() {
    const mouse = this.props.mouse;
    return (
      <img src="/cat.jpg" style={{ position: 'absolute', left: mouse.x, top: mouse.y }} />
    );
  }
}

class Mouse extends React.Component {
  constructor(props) {
    super(props);
    this.handleMouseMove = this.handleMouseMove.bind(this);
    this.state = { x: 0, y: 0 };
  }

  handleMouseMove(event) {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (
      <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>

        {/*
          Instead of providing a static representation of what <Mouse> renders,
          use the `render` prop to dynamically determine what to render.
        */}
        {this.props.render(this.state)}
      </div>
    );
  }
}

class MouseTracker extends React.Component {
  render() {
    return (
      <div>
        <h1>Move the mouse around!</h1>
        <Mouse render={mouse => (
          <Cat mouse={mouse} />
        )}/>
      </div>
    );
  }
}
```
Now, instead of effectively cloning the `<Mouse>` component and hard-coding something else in its `render` method to solve for a specific use case, we provide a `render` prop that `<Mouse>` can use to dynamically determine what it renders.

One interesting thing to note about render props is that you can implement most _higher-order components_ (HOC) using a regular component with a render prop. For example, if you would prefer to have a `withMouse` HOC instead of a `<Mouse>` component, you could easily create one using a regular `<Mouse>` with a render prop:
```javascript
// If you really want a HOC for some reason, you can easily
// create one using a regular component with a render prop!
function withMouse(Component) {
  return class extends React.Component {
    render() {
      return (
        <Mouse render={mouse => (
          <Component {...this.props} mouse={mouse} />
        )}/>
      );
    }
  }
}
```

### Using Props Other Than `render`
It's important to remember that just because the pattern is called __render props__ you don't have to use a prop named render to use this pattern. In fact, _any prop that is a function that a component uses to know what to render is technically a "render prop"_.

### Caveats
__Be careful when using Render Props with `React.PureComponent`__

Using a `render` prop can negate (делать недействительным) the advantage that comes from using `React.PureComponent` if you create the function inside a `render` method. This is because the shallow prop comparison will always return `false` for new props, and each `render` in this case will generate a new value for the `render` prop.

For example, continuing with our `<Mouse>` component from above, if `Mouse` were to extend `React.PureComponent` instead of `React.Component`, our example would look like this:
```javascript
class Mouse extends React.PureComponent {
  // Same implementation as above...
}

class MouseTracker extends React.Component {
  render() {
    return (
      <div>
        <h1>Move the mouse around!</h1>

        {/*
          This is bad! The value of the `render` prop will
          be different on each render.
        */}
        <Mouse render={mouse => (
          <Cat mouse={mouse} />
        )}/>
      </div>
    );
  }
}
```

In this example, each time `<MouseTracker>` renders, it generates a new function as the value of the `<Mouse render>` prop, thus negating the effect of `<Mouse>` extending `React.PureComponent` in the first place!

To get around this problem, you can sometimes define the `prop` as an instance method, like so:
```javascript
class MouseTracker extends React.Component {
  // Defined as an instance method, `this.renderTheCat` always
  // refers to *same* function when we use it in render
  renderTheCat(mouse) {
    return <Cat mouse={mouse} />;
  }

  render() {
    return (
      <div>
        <h1>Move the mouse around!</h1>
        <Mouse render={this.renderTheCat} />
      </div>
    );
  }
}
```


text:
using DatenMeister.Plugins;

namespace DatenMeister.WPF.Modules.ObjectOperation
{
    public class ObjectOperationPlugin : IDatenMeisterPlugin
    {
        public void Start(PluginLoadingPosition position)
        {
            GuiObjectCollection.TheOne.ViewExtensionFactories.Add(new ObjectOperationViewExtension());
        }
    }
}


text:
Debug
==

> Debugging is the process of finding and resolving or defects that prevent correct operation of computer software or a system. Debugging tends to be harder when various subsystems are tightly coupled, as changes in one may cause bugs to emerge in another. [Wikipedia](https://en.wikipedia.org/wiki/Debugging)

- [Ubuntu Kernel Debugging Tricks](https://wiki.ubuntu.com/Kernel/KernelDebuggingTricks)

## Kernel Configuration

```sh

    Kernel hacking

        -*- Kernel debugging
        [*]   Magic SysRq key
        -*-   Debug filesystem
        [*]   Detect Soft Lockups
        [ ]   Collect scheduler statistics
        [*]   Debug slab memory allocations
        [*]     Memory leak debugging
        [*]   Mutex debugging, deadlock detection
        [*]   Spinlock debugging
        [*]   Sleep-inside-spinlock checking
        [ ]   kobject debugging
        [ ]   Highmem debugging
        [ ]   Compile the kernel with debug info
```

## Kernel Integration

### Linux Debug Filesystem

> Debugfs exists as a simple way for kernel developers to make information available to user space.  Unlike /proc, which is only meant for information about a process, or sysfs, which has strict one-value-per-file rules, debugfs has no rules at all. [Wikipedia](https://en.wikipedia.org/wiki/Debugfs)

- [Linux Kernel Documentation Debugfs](https://www.kernel.org/doc/Documentation/filesystems/debugfs.txt)
- [Linux Kernel Debugfs](https://www.kernel.org/doc/Documentation/filesystems/debugfs.txt)

```sh
    root@edison:~# mount -t debugfs none /sys/kernel/debug
    mount: none is already mounted or /sys/kernel/debug busy
           none is already mounted on /tmp/temptmpfs
    root@edison:~# ls /sys/kernel/debug/
    asoc                  gpio_debug            pmu_sync_d0ix
    bdi                   hid                   pwm
    bluetooth             hsu                   regmap
    boot_params           ieee80211             regulator
    c_states_stat         ignore_add            remoteproc
    cstate_ignore_add     ignore_remove         s3_ctrl
    cstate_ignore_remove  iio                   sched_features
    debug_feature         intel_scu_oshob       soc_thermal
    disable_emmc_ipanic   kprobes               sst
    dma_buf               mce                   suspend_stats
    dri                   mid_pmu_states        tracing
    dump_cmd              mmc0                  usb
    dump_output           mmc1                  wakeup_sources
    dwc3-device.1         mmc2                  watchdog
    dynamic_debug         pmic_ccsm             x86
    emmc_ipanic           pmu_force_d0i0
    gpio                  pmu_force_d0i3
    root@edison:~#
```

### Linux Magic System Request Key Hacks

> It is a 'magical' key combo you can hit which the kernel will respond to regardless of whatever else it is doing, unless it is completely locked up. [Documentation](https://www.kernel.org/doc/Documentation/sysrq.txt)

- [Linux Magic System Request Key Hacks](https://www.kernel.org/doc/Documentation/sysrq.txt)

### Ftrace

- [Debugging the kernel using Ftrace - Part 1](https://lwn.net/Articles/365835/)

```sh
    root@edison:~# cd /sys/kernel/debug/tracing
    root@edison:/sys/kernel/debug/tracing# cat available_tracers
    blk function_graph wakeup_rt wakeup preemptirqsoff preemptoff irqsoff function nop
    root@edison:/sys/kernel/debug/tracing# echo function > current_tracer
    root@edison:/sys/kernel/debug/tracing# cat current_tracer
    function
```

## Applications / Libraries

### Programs

None


text:
@charset "utf-8";
/* CSS Document */

@import url(http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,400italic,700italic);

	html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
		margin: 0;
		padding: 0;
		border: 0;
		font-size: 100%;
		font: inherit;
		vertical-align: baseline; }
	article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
		display: block; }
	body {
		line-height: 1; }
	ol, ul {
		list-style: none; }
	blockquote, q {
		quotes: none; }
	blockquote:before, blockquote:after,
	q:before, q:after {
		content: '';
		content: none; }
	table {
		border-collapse: collapse;
		border-spacing: 0; }

			body {
		background: #fff;
		font: 14px/21px Arial, sans-serif;
		color: #444;
		-webkit-font-smoothing: antialiased; /* Fix for webkit rendering */
		-webkit-text-size-adjust: 100%;

		-webkit-transition: background-color 0.8s ease-out;
		-moz-transition: background-color 0.8s ease-out;
		-o-transition: background-color 0.8s ease-out;
		transition: background-color 0.8s ease-out;
	}
	h1, h2, h3, h4, h5, h6 {
		color: #222;
		font-family: Georgia, Arial, sans-serif;
		font-weight: normal; }
	h1 a, h2 a, h3 a, h4 a, h5 a, h6 a { font-weight: inherit; }
	h1 { font-size: 46px; line-height: 50px; margin-bottom: 14px;}
	h2 { font-size: 35px; line-height: 40px; margin-bottom: 10px; }
	h3 { font-size: 28px; line-height: 34px; margin-bottom: 6px; }
	h4 { font-size: 21px; line-height: 30px; margin-bottom: 6px; }
	h5 { font-size: 17px; line-height: 24px; }
	h6 { font-size: 14px; line-height: 21px; }
	.subheader { color: #777; }

	p { margin: 0 0 20px 0; }
	p img { margin: 0; }
	p.lead { font-size: 21px; line-height: 27px; color: #777;  }

	em { font-style: italic; }
	strong { font-weight: bold; color: #333; }
	small { font-size: 80%; }

	hr { border: solid #ddd; border-width: 1px 0 0; clear: both; margin: 10px 0 30px; height: 0; }
ul, ol { margin-bottom: 20px; }
	ul { list-style: none outside; }
	ol { list-style: decimal; }
	ol, ul.square, ul.circle, ul.disc { margin-left: 30px; }
	ul.square { list-style: square outside; }
	ul.circle { list-style: circle outside; }
	ul.disc { list-style: disc outside; }
	ul ul, ul ol,
	ol ol, ol ul { margin: 4px 0 5px 30px; font-size: 90%;  }
	ul ul li, ul ol li,
	ol ol li, ol ul li { margin-bottom: 6px; }
	li { line-height: 18px; margin-bottom: 12px; }
	ul.large li { line-height: 21px; }
	li p { line-height: 21px; }

.container                                  { position: relative; width: 1050px; margin: 0 auto; padding: 0; }
    .container .column,
    .container .columns                         { float: left; display: inline; margin-left: 1ddddddddd0px; margin-right: 10px; }
    .row                                        { margin-bottom: 0px; }
    .container .one.column,
    .container .one.columns                     { width: 40px;  }
    .container .two.columns                     { width: 100px; }
    .container .three.columns                   { width: 160px; }
    .container .four.columns                    { width: 220px; }
    .container .five.columns                    { width: 280px; }
    .container .six.columns                     { width: 340px; }
    .container .seven.columns                   { width: 400px; }
    .container .eight.columns                   { width: 460px; }
    .container .nine.columns                    { width: 520px; }
    .container .ten.columns                     { width: 580px; }
    .container .eleven.columns                  { width: 640px; }
    .container .twelve.columns                  { width: 700px; }
    .container .thirteen.columns                { width: 760px; }
    .container .fourteen.columns                { width: 820px; }
    .container .fifteen.columns                 { width: 880px; }
    .container .sixteen.columns                 { width: 1050px; }

    .container .one-third.column                { width: 300px; }
    .container .two-thirds.column               { width: 620px; }

#overview {
	padding-bottom: 0px;
}

#overview h3 {
	font-family: Georgia, Arial, sans-serif;
	font-weight: normal;
    font-style: normal;
	font-size: 36px;
	line-height: 1.2;
	letter-spacing: -0.04em;
	text-rendering: auto;
	color: #333;
	margin-top: -7px;
	margin-bottom: 22px;
}
.webtoolswidget {
	max-width: 100%;
	height: 100%;
}

.webtoolswidget img {
	display: block;
}

#footerLinks li {
	font-weight: bold;
	font-size: 12px;
	display: inline;
	padding-left: 12px;
	margin-left: 0;
	border-right: 1px solid;
	padding-right: 15px;
}

#overview {
	padding-bottom: 0px;
}

#overview h3 {
	font-family: Georgia, Arial, sans-serif;
	font-weight: normal;
    font-style: normal;
	font-size: 36px;
	line-height: 1.2;
	letter-spacing: -0.04em;
	text-rendering: auto;
	color: #333;
	margin-top: -7px;
	margin-bottom: 22px;
}

h1 { font-size: 48px; line-height: 1.2; }
h2 { font-size: 36px; line-height: 1.2; }
h3 { font-size: 24px; line-height: 1.2; }
h4 { font-size: 18px; line-height: 1.2; }
h5 { font-size: 14px; line-height: 1.2; }
h6 { font-size: 12px; line-height: 1.2; }

header {
	padding-top: 0px;
	border-top: 3px solid #000;
}

#logo, #logoDetailView {
	float: left;
	cursor: pointer;
}

#logo img, #logoDetailView img {
	margin-top: 28px;
}

#logo h1, #logoDetailView h1 {
	font-family: Georgia, Arial, sans-serif;
	font-weight: normal;
    font-style: normal;
	font-size: 36px;
	line-height: 1.5;
	letter-spacing: -0.05em;
	text-rendering: optimizeLegibility;
}

#logo h2, #logoDetailView h2 {
	font-family: Georgia, Arial, sans-serif;
	font-weight: normal;
	font-style: italic;
	font-size: 16px;
	line-height: 1.2;
	letter-spacing: -0.07em;
	text-rendering: optimizeLegibility;
	margin-top: -23px;
}
#logo h1, #logoDetailView h1 {
	font-family: "Source Sans Pro", Arial, sans-serif;
	font-weight: 500;
	font-style: normal;
	font-size: 28px;
	line-height: 1.5;
	letter-spacing: 0.02em;
	text-decoration: none;
	text-transform: uppercase;
	text-rendering: optimizeLegibility;
	text-shadow: 0.01em 0.01em #333

}

#logo h2, #logoDetailView h2 {
	font-family: "Source Sans Pro", Arial, sans-serif;
	font-weight: 400;
    font-style: normal;
	font-size: 14px;
	line-height: 1.2;
	letter-spacing: 0;
	text-decoration: none;
	text-transform: none;
	text-rendering: auto;

}

#overview h3 {
	font-family: "Source Sans Pro", Arial, sans-serif;
	font-weight: 300;
    font-style: normal;
	font-size: 40px;
	line-height: 1.2;
	letter-spacing: -0.02em;
	text-decoration: none;
	text-transform: none;
	text-rendering: optimizeLegibility;
}
p, li, .projectInfo p, .projectInfo li {
	font-family: "Source Sans Pro", Arial, sans-serif;
	font-weight: 400;
    font-style: normal;
	font-size: 14px;
	line-height: 1.4;
	letter-spacing: 0;
	text-decoration: none;
	text-transform: none;
	text-rendering: auto;
}

footer p, #footerLinks li {
	font-family: "Source Sans Pro", Arial, sans-serif;
	font-weight: 600;
    font-style: normal;
	font-size: 13px;
	line-height: 1.2;
	letter-spacing: 0;
	text-decoration: none;
	text-transform: none;
	text-rendering: auto;
}

h1, h2, h3, h4, h5, h6 {
	font-family: "Source Sans Pro", Arial, sans-serif;
	font-weight: 700;
	letter-spacing: -0.02em;
	text-transform: none;
}

#logo h2, #logoDetailView h2 {
	margin-top: -22px;
	padding-left: 2px;
}

#overview {
	padding-bottom: 10px;
}

#overview h3 {
	margin-top: -8px;
	margin-bottom: 23px;
}

.projectInfo h4 {
	padding-top: 10px;
	padding-bottom: 8px;
}

body { background-color: #ededed; }
header { border-color: #AF1E54; }
#logo h1, #logoDetailView h1 { color: #111111; }
#logo h2, #logoDetailView h2 { color: #222222; }
.currentPage, button.currentPage:hover { color: #a1d7bd !important; }
nav ul li button:hover, nav ul li button:active, nav ul li button:focus, nav ul li a:hover, nav ul li a:active, nav ul li a:focus, #heroNav a:hover, #heroNav a:visited:hover, #heroNav a:active, #heroNav a:focus, #formSubmit:hover, .contentModule a:hover, .contentModule a:visited:hover, .contentModule a:active, .contentModule a:focus { color: #1c6e46; }
hr, .projectInfo h4, .projectNav, .projectInfo, .linedList, .projectInfo li, .projectInfo p:nth-last-child(2), .linedList li, nav, blockquote, #formField, #content #heroNav ul li, #footerLinks li, #heroNav, .contentModule, .eight:nth-child(4n) .contentModule:last-child, .eight:nth-of-type(1) .contentModule:last-child { border-color: #d0d0d0; }
#overview h3 {
	color: #333333;
	font-size: 24px;
	text-align: center;
}
.projectInfo h4 { color: #444444; }
.projectNav { color: #444444; }
.projectNavClose button, .projectNavButtons button, .projectNavEnlarge button, .projectNavCounter, #formSubmit, #formField { color: #444444; }
.projectNav button:hover, .projectNav button:active, .projectNav button:focus { color: #777777; }
.projectNavInactive, button.projectNavInactive, button.projectNavInactive:hover, button.projectNavInactive:active { color: #bbbbbb !important; }
p, li, .projectInfo p, .projectInfo li, blockquote, blockquote p, blockquote cite { color: #444444; }
p strong, .projectInfo strong, li strong { color: #444444; }
footer p { color: #333333; }
footer a { color: #AF1E54; }
h1, h2, h3, h4, h5, h6, #faq p:first-child, .contentModule a, .contentModule a:visited { color: #333333; }
#heroNav a, #heroNav a:visited { color: #AF1E54; }
a, a:visited { color: #AF1E54; }
a:hover, a:active, a:focus {
	color: #AF1E54;
}
#formField { background: #f6f6f6; }
#formField:focus { background: #ffffff; }


text:
<?php
namespace LaravelRocket\Foundation\Facades;

use Illuminate\Support\Facades\Facade;
use LaravelRocket\Foundation\Helpers\DataHelperInterface;

class DataHelper extends Facade
{
    protected static function getFacadeAccessor()
    {
        return DataHelperInterface::class;
    }
}


text:
package mah.ui.input;

/**
 * Created by zgq on 3/1/17.
 */
public class InputConfirmedEvent {
    private final String input;

    public InputConfirmedEvent(String input) {
        this.input = input;
    }

    public String getInput() {
        return input;
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Windows;
using Whathecode.System.Reflection;
using Whathecode.System.Reflection.Extensions;
using Whathecode.System.Windows.DependencyPropertyFactory.Attributes;
using Whathecode.System.Windows.DependencyPropertyFactory.Attributes.Coercion;
using Whathecode.System.Windows.DependencyPropertyFactory.Attributes.Validators;
using Whathecode.System.Windows.Threading;
using Whathecode.System.Linq;

namespace Whathecode.System.Windows.DependencyPropertyFactory
{
	/// <summary>
	///   A dependency property factory to simplify creating and managing dependency properties for a certain type.
	/// </summary>
	/// <typeparam name = "T">A flags enum used to identify the dependency properties.</typeparam>
	/// <author>Steven Jeuris</author>
	public partial class DependencyPropertyFactory<T> : AbstractEnumSpecifiedFactory<T>
	{
		class DependencyPropertyInfo
		{
			public bool IsAttached;
			public string Name;
			public Type Type;
			public FrameworkPropertyMetadata MetaData;
			public bool ReadOnly;
			public T Id;
		}

		const string ConventionEnabledError = "WPF dependency property conventions are enabled and not followed. ";
		const string IdentifierSuffix = "Property";
		const string GetPrefix = "Get";
		const string SetPrefix = "Set";
		readonly bool _enforceWpfConvention = true;

		readonly Dictionary<T, DependencyPropertyKey> _readOnlyProperties = new Dictionary<T, DependencyPropertyKey>();

		/// <summary>
		///   All attached properties collections. They need to be initialized upon first retrieval.
		/// </summary>
		readonly Dictionary<T, Type> _attachedCollectionsTypes = new Dictionary<T, Type>();

		/// <summary>
		///   A list containing the dependency properties.
		///   TODO: Make this a readonly collection. Will be available in .NET 4.5.
		/// </summary>
		public Dictionary<T, DependencyProperty> Properties { get; private set; }

		/// <summary>
		///   Create a new dependency property factory for a specific set of properties.
		///   When naming conventions aren't followed, an exception is thrown.
		///   (http://msdn.microsoft.com/en-us/library/bb613563.aspx)
		///   The type which encloses the type parameter is used as the owner type.
		/// </summary>
		public DependencyPropertyFactory()
			: this( true ) {}

		/// <summary>
		///   Create a new dependency property factory for a specific set of properties.
		///   The type which encloses the type parameter is used as the owner type.
		/// </summary>
		/// <param name = "enforceNamingConventions">
		///   Whether or not to throw exceptions when the naming conventions aren't followed.
		///   See http://msdn.microsoft.com/en-us/library/bb613563.aspx.
		/// </param>
		public DependencyPropertyFactory( bool enforceNamingConventions )
			: this( null, enforceNamingConventions ) {}

		/// <summary>
		///   Create a new dependency property factory for a specific set of properties.
		///   When naming conventions aren't followed, an exception is thrown.
		///   (http://msdn.microsoft.com/en-us/library/bb613563.aspx)
		/// </summary>
		/// <param name = "ownerType">The owner type of the dependency properties.</param>
		public DependencyPropertyFactory( Type ownerType )
			: this( ownerType, true ) {}

		/// <summary>
		///   Create a new dependency property factory for a specific set of properties.
		/// </summary>
		/// <param name = "ownerType">The owner type of the dependency properties.</param>
		/// <param name = "enforceNamingConventions">
		///   Whether or not to throw exceptions when the naming conventions aren't followed.
		///   See http://msdn.microsoft.com/en-us/library/bb613563.aspx.
		/// </param>
		public DependencyPropertyFactory( Type ownerType, bool enforceNamingConventions )
			: this( ownerType, enforceNamingConventions, true ) {}

		/// <summary>
		///   Create a new dependency property factory for a specific set of properties.
		/// </summary>
		/// <param name = "ownerType">The owner type of the dependency properties.</param>
		/// <param name = "enforceNamingConventions">
		///   Whether or not to throw exceptions when the naming conventions aren't followed.
		///   See http://msdn.microsoft.com/en-us/library/bb613563.aspx.
		/// </param>
		/// <param name = "checkForStatic">Whether or not to check whether the factory is static.</param>
		protected DependencyPropertyFactory( Type ownerType, bool enforceNamingConventions, bool checkForStatic )
			: base( ownerType, true )
		{
			Contract.Requires( typeof( T ).IsPublic || typeof( T ).IsNestedPublic );

			Properties = new Dictionary<T, DependencyProperty>();
			_enforceWpfConvention = enforceNamingConventions;

			// When coercion is used, all enum values should be independent flag values, different from 0.
			if ( MatchingAttributes.Any( a => a.Key.GetAttributes<CoercionHandlerAttribute>().Length > 0 ) )
			{
				T none = default( T );
				Type enumType = typeof( T );
				bool correctImplementation =
					enumType.IsFlagsEnum()
					&& EnumHelper<T>.GetValues().All( v => EnumHelper<T>.GetFlaggedValues( v ).Count() == 1 && !v.Equals( none ) );
				if ( !correctImplementation )
				{
					string message = String.Format(
						"In order to use coercion, each enum value of {0} should be an individual flag value, different from 0.", enumType );
					throw new InvalidImplementationException( message );
				}
			}

			// Check whether the factory itself is defined as a static field.
			// TODO: Can part of this logic be moved to ReflectionHelper?
			if ( checkForStatic )
			{
				FieldInfo[] fields = OwnerType.GetFields(
					BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic );
				bool validFactory
					= fields
						.Where( field => field.FieldType == typeof( DependencyPropertyFactory<T> ) && field.IsStatic )
						.Any();
				if ( !validFactory )
				{
					throw new InvalidImplementationException(
						"Incorrect usage of DependencyPropertyFactory in class '" + OwnerType.Name + "'. " +
							"A DependencyPropertyFactory needs to be created as a static field inside it's owner class." );
				}
			}

			// Check whether callback attributes are applied to non-static functions. They should be static!
			var callbackMethods =
				from method in OwnerType.GetMethods( ReflectionHelper.FlattenedClassMembers )
				from attribute in method.GetAttributes<AbstractDependencyPropertyCallbackAttribute>()
				select method;
			if ( !callbackMethods.All( m => m.IsStatic ) )
			{
				throw new InvalidImplementationException(
					"Not all dependency property callback functions are defined as static in type '" + OwnerType.Name + "'." );
			}

			// Create dependency properties.
			var properties =
				from item in MatchingAttributes
				where item.Key is PropertyInfo
				select item;
			foreach ( var item in properties )
			{
				var attribute = (DependencyPropertyAttribute)item.Value[ 0 ];
				CreateDependencyProperty( GetDependencyPropertyInfo( item.Key as PropertyInfo, attribute ) );
			}

			// Create attached properties.
			var attachedProperties =
				from item in MatchingAttributes
				where item.Key is MethodInfo
				from attribute in item.Value
				group new
				{
					MemberInfo = item.Key,
					Attribute = (DependencyPropertyAttribute)attribute
				} by attribute.GetId();
			foreach ( var item in attachedProperties )
			{
				var attachedProperty = item.ToList();
				bool valid = false;
				if ( attachedProperty.Count <= 2 )
				{

					MethodInfo[] methods = attachedProperty.Select( p => (MethodInfo)p.MemberInfo ).ToArray();
					MethodInfo getter = methods.Single( m => m.Name.StartsWith( GetPrefix ) );
					MethodInfo setter = methods.SingleOrDefault( m => m.Name.StartsWith( SetPrefix ) && m.ReturnType == typeof( void ) );

					// Verify whether getter and setter correspond.
					// TODO: Do typechecking of parameters?
					if ( setter != null && getter.Name.Substring( GetPrefix.Length ) == setter.Name.Substring( SetPrefix.Length ) )
					{
						// Extract settings.
						var attributes = attachedProperty.Select( a => a.Attribute ).ToArray();
						var id = (T)attachedProperty.First().Attribute.GetId();
						// TODO: Allow checking whether or not the default value is set or not.
						var defaultValues =
							attributes.Where( a => a.DefaultValue != null ).Select( a => a.DefaultValue ).ToArray();
						var readOnlySettings =
							attributes.Where( a => a.IsReadOnlySet() ).Select( a => a.IsReadOnlySet() ? a.IsReadOnly() : new bool?() ).ToArray();
						if ( !defaultValues.AllEqual() || !readOnlySettings.AllEqual() )
						{
							throw new InvalidImplementationException(
								"All set options of \"" + typeof( DependencyPropertyAttribute )  +
								"\" should correspond with attributes with the same ID." +
								" Preferably only set options on one of the attributes." );
						}

						DependencyPropertyInfo info = GetAttachedDependencyPropertyInfo(
							getter, setter,
							id, defaultValues.FirstOrDefault(), readOnlySettings.FirstOrDefault() );

						// HACK: For collections, use a dependency property with non-matching name so the getter is called the first time,
						//       so it can be initialized and doesn't need to be initialized through XAML.
						if ( info.Type.ImplementsInterface( typeof( ICollection ) ) )
						{
							info.Name = info.Name + "Internal";
							_attachedCollectionsTypes.Add( info.Id, info.Type );
						}

						CreateDependencyProperty( info );
						valid = true;
					}
				}

				if ( !valid )
				{
					throw new InvalidImplementationException(
						"Invalid usage of the attribute " + typeof( DependencyPropertyAttribute ) + ". " +
							"To create an attached property, apply it to a correctly named get and optionally corresponding set method. " );
				}
			}
		}

		DependencyPropertyInfo GetDependencyPropertyInfo( PropertyInfo property, DependencyPropertyAttribute attribute )
		{
			if ( _enforceWpfConvention )
			{
				// Find public dependency property field identifier.
				const BindingFlags identifierModifiers = BindingFlags.Public | BindingFlags.Static;
				string identifierField = property.Name + IdentifierSuffix;
				FieldInfo identifier = OwnerType.GetField( identifierField, identifierModifiers );
				if ( identifier == null || (identifier.FieldType != typeof( DependencyProperty )) )
				{
					throw new InvalidImplementationException(
						ConventionEnabledError +
							"There is no public static dependency property field identifier \"" + identifierField +
								"\" available in the class \"" + OwnerType.Name + "\"." );
				}

				// Verify name when set.
				if ( attribute.Name != null && property.Name != attribute.Name )
				{
					throw new InvalidImplementationException(
						ConventionEnabledError + "The CLR property wrapper '" + property.Name +
							"' doesn't match the name of the dependency property." );
				}
			}

			// Set dependency property parameters.
			Type propertyType = property.PropertyType;
			MethodInfo setMethod = property.GetSetMethod();
			object defaultValue;
			if ( attribute.DefaultValueProvider != null )
			{
				var defaultValueProvider = (IDefaultValueProvider<T>)Activator.CreateInstance( attribute.DefaultValueProvider );
				defaultValue = defaultValueProvider.GetDefaultValue( (T)attribute.GetId(), property.PropertyType );
			}
			else
			{
				defaultValue = attribute.DefaultValue ?? propertyType.CreateDefault();
			}
			if ( defaultValue != null && defaultValue.GetType() != propertyType )
			{
				TypeConverter converter = TypeDescriptor.GetConverter( propertyType );
				if ( converter.CanConvertFrom( defaultValue.GetType() ) )
				{
					var context = new TypeDescriptorContext( propertyType );
					defaultValue = converter.ConvertFrom( context, CultureInfo.CurrentCulture, defaultValue );
				}
			}
			var metaData = new FrameworkPropertyMetadata
			{
				DefaultValue = defaultValue,
				AffectsArrange = attribute.AffectsArrange,
				AffectsMeasure = attribute.AffectsMeasure,
				AffectsParentArrange = attribute.AffectsParentArrange,
				AffectsParentMeasure = attribute.AffectsParentMeasure,
				AffectsRender = attribute.AffectsRender,
				SubPropertiesDoNotAffectRender = attribute.SubPropertiesDoNotAffectRender
			};
			var dependencyPropertyInfo = new DependencyPropertyInfo
			{
				IsAttached = false,
				Name = attribute.Name ?? property.Name,
				Type = propertyType,
				// When no default value is set, use the default value.
				MetaData = metaData,
				// By default, readonly when setter is private.
				ReadOnly = attribute.IsReadOnlySet() ? attribute.IsReadOnly() : (setMethod == null || setMethod.IsPrivate),
				Id = (T)attribute.GetId()
			};

			return dependencyPropertyInfo;
		}

		static DependencyPropertyInfo GetAttachedDependencyPropertyInfo(
			MethodInfo getter, MethodInfo setter,
			T id, object defaultValue, bool? isReadOnly )
		{
			// TODO: Enforce naming conventions.

			Type propertyType = getter.ReturnType;
			var metaData = new FrameworkPropertyMetadata
			{
				// When no default value is set, use the default value.
				DefaultValue = defaultValue ?? propertyType.CreateDefault()
			};
			return new DependencyPropertyInfo
			{
				IsAttached = true,
				Name = getter.Name.Substring( GetPrefix.Length ),
				Type = propertyType,
				MetaData = metaData,
				// By default, readonly when no setter available.
				ReadOnly = isReadOnly ?? setter == null,
				Id = id
			};
		}

		void CreateDependencyProperty( DependencyPropertyInfo info )
		{
			// Find callbacks.
			var changedCallback = (PropertyChangedCallback)CreateCallbackDelegate<DependencyPropertyChangedAttribute>( info.Id );
			var coerceCallback = (CoerceValueCallback)CreateCallbackDelegate<DependencyPropertyCoerceAttribute>( info.Id );
			var validateValueCallback = (ValidateValueCallback)CreateCallbackDelegate<DependencyPropertyValidateAttribute>( info.Id );

			// Find specified handlers through the handler attributes when no callback found yet.
			// TODO: At the moment no handlers for attached properties are implemented.
			if ( !info.IsAttached )
			{
				PropertyInfo property = OwnerType.GetProperty( info.Name );
				if ( validateValueCallback == null )
				{
					ValidationHandlerAttribute handler = property.GetAttributes<ValidationHandlerAttribute>().FirstOrDefault();
					if ( handler != null )
					{
						validateValueCallback = handler.GenericValidation.IsValid;
					}
				}
				if ( coerceCallback == null )
				{
					CoercionHandlerAttribute handler = property.GetAttributes<CoercionHandlerAttribute>().FirstOrDefault();
					if ( handler != null )
					{
						coerceCallback = handler.GenericCoercion.Coerce;
					}
				}
			}

			// Create a correct changed callback when no custom callback specified.
			if ( changedCallback == null )
			{
				var dependentProperties = (
					from a in MatchingAttributes
					let coercion = a.Key.GetAttributes<CoercionHandlerAttribute>().FirstOrDefault()
					where coercion != null
					where EnumHelper<T>
						.GetFlaggedValues( (T)coercion.GenericCoercion.DependentProperties )
						.Contains( info.Id ) // Id of this property.
					select (T)a.Key.GetAttributes<DependencyPropertyAttribute>().First().GetId()
					).ToArray();
				if ( dependentProperties.Length > 0 )
				{
					changedCallback = ( dependencyObject, changedArgs ) =>
					{
						foreach ( var p in dependentProperties )
						{
							dependencyObject.CoerceValue( Properties[ p ] );
						}
					};
				}
			}

			// Apply callbacks to meta data.
			info.MetaData.PropertyChangedCallback = changedCallback;
			info.MetaData.CoerceValueCallback = coerceCallback;

			// Create property.
			if ( info.ReadOnly )
			{
				CreateReadOnlyDependencyProperty(
					info.IsAttached,
					info.Id, info.Name, info.Type,
					info.MetaData,
					validateValueCallback );
			}
			else
			{
				CreateDependencyProperty(
					info.IsAttached,
					info.Id, info.Name, info.Type,
					info.MetaData,
					validateValueCallback );
			}
		}

		/// <summary>
		///   Create a callback delegate for a dependency property.
		/// </summary>
		/// <typeparam name = "TCallbackAttribute">The callback attribute type.</typeparam>
		/// <param name = "id">The ID of the dependency property.</param>
		/// <returns>A delegate which can be used as a callback.</returns>
		Delegate CreateCallbackDelegate<TCallbackAttribute>( object id ) where TCallbackAttribute : AbstractDependencyPropertyCallbackAttribute
		{
			const BindingFlags allStaticMethods =
				BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Static;

			return (
				from method in OwnerType.GetMethods( allStaticMethods )
				let methodAttributes = method.GetAttributes<TCallbackAttribute>()
				where methodAttributes != null && methodAttributes.Length == 1
				let changed = methodAttributes[ 0 ]
				where changed.GetId().Equals( id )
				select Delegate.CreateDelegate( changed.CallbackType, method )
				).FirstOrDefault();
		}

		void CreateDependencyProperty(
			bool isAttached,
			T identifier,
			string name,
			Type propertyType,
			FrameworkPropertyMetadata metaData,
			ValidateValueCallback validateValueCallback )
		{
			DependencyProperty property;
			if ( isAttached )
			{
				property = DependencyProperty.RegisterAttached(
					name,
					propertyType,
					OwnerType,
					metaData,
					validateValueCallback );
			}
			else
			{
				property = DependencyProperty.Register(
					name,
					propertyType,
					OwnerType,
					metaData,
					validateValueCallback );
			}

			Properties.Add( identifier, property );
		}

		void CreateReadOnlyDependencyProperty(
			bool isAttached,
			T identifier,
			string name,
			Type propertyType,
			FrameworkPropertyMetadata metaData,
			ValidateValueCallback validateValueCallback )
		{
			DependencyPropertyKey propertyKey;
			if ( isAttached )
			{
				propertyKey = DependencyProperty.RegisterAttachedReadOnly(
					name,
					propertyType,
					OwnerType,
					metaData,
					validateValueCallback );
			}
			else
			{
				propertyKey = DependencyProperty.RegisterReadOnly(
					name,
					propertyType,
					OwnerType,
					metaData,
					validateValueCallback );
			}
			_readOnlyProperties.Add( identifier, propertyKey );

			DependencyProperty property = propertyKey.DependencyProperty;

			Properties.Add( identifier, property );
		}

		/// <summary>
		///   Returns the dependency property for a given ID.
		/// </summary>
		/// <param name = "id">The ID of the dependency propert. (enum type of the class type parameter)</param>
		/// <returns>The dependency property for the given ID.</returns>
		public DependencyProperty this[ T id ]
		{
			get
			{
				try
				{
					return Properties[ id ];
				}
				catch ( KeyNotFoundException )
				{
					throw new KeyNotFoundException(
						"The dependency property with the key \"" + id + "\" doesn't exist. "
							+ "Did you forget to add a DependencyPropertyAttribute?" );
				}
			}
		}

		/// <summary>
		///   Get the value of a property.
		/// </summary>
		/// <param name = "o">The dependency object from which to get the value.</param>
		/// <param name = "property">The property to get the value from.</param>
		/// <returns>The value from the asked property.</returns>
		public object GetValue( DependencyObject o, T property )
		{
			if ( _attachedCollectionsTypes.ContainsKey( property ) )
			{
				// Check whether collection needs to be initialized.
				object value = o.GetValue( Properties[ property ] );
				if ( value == null )
				{
					value = Activator.CreateInstance( _attachedCollectionsTypes[ property ] );
					SetValue( o, property, value );
				}

				return value;
			}

			return o.GetValue( Properties[ property ] );
		}

		/// <summary>
		///   Set the value of a property, whether it is readonly or not.
		/// </summary>
		/// <param name = "o">The dependency object on which to set the value.</param>
		/// <param name = "property">The property to set.</param>
		/// <param name = "value">The new value for the property.</param>
		public void SetValue( DependencyObject o, T property, object value )
		{
			DependencyPropertyKey key;
			if ( _readOnlyProperties.TryGetValue( property, out key ) )
			{
				DispatcherHelper.SafeDispatch( o.Dispatcher, () => o.SetValue( key, value ) );
			}
			else
			{
				DispatcherHelper.SafeDispatch( o.Dispatcher, () => o.SetValue( Properties[ property ], value ) );
			}
		}

		protected override Type[] GetAttributeTypes()
		{
			return new[] { typeof( DependencyPropertyAttribute ) };
		}
	}
}


text:
#ifndef PETABRICKSSCHEDULER_H
#define PETABRICKSSCHEDULER_H

#include "choicedepgraph.h"

#include <fstream>

namespace petabricks {
class ChoiceGridMap;
class StaticScheduler;
class Schedule;
typedef jalib::JRef<StaticScheduler> StaticSchedulerPtr;
typedef jalib::JRef<Schedule> SchedulePtr;

/**
 * A node and a snapshot of its dynamic dependencies
 */
class ScheduleEntry {
public:
  ScheduleEntry(ChoiceDepGraphNode* node, const ScheduleDependencies& deps)
    : _node(node), _deps(deps)
  {
    filterDeps();
  }

  const ChoiceDepGraphNode& node() const { return _node; }
  ChoiceDepGraphNode& node() { return _node; }

  void printNode(std::ostream& o) const {
    node().printNode(o);
  }
  void printEdge(std::ostream& o) const {
    for(ScheduleDependencies::const_iterator i=_deps.begin(); i!=_deps.end(); ++i){
      if(i->first->isInput()) {
        o << "  input";
      }else{
        o << "  " << i->first->nodename();
      }
      o << " -> "
        << node().nodename()
        << "[ label=\"" << i->second.direction << "\"];\n";
    }
  }
  void filterDeps() {
    ScheduleDependencies tmp;
    for(ScheduleDependencies::const_iterator i=_deps.begin(); i!=_deps.end(); ++i){
      if(i->first->isInput()) {
        continue;
      }
      if(i->first == _node.asPtr()) {
        continue;
      }
      tmp[i->first] = i->second;
    }
    tmp.swap(_deps);
  }

  const ScheduleDependencies& deps() const { return _deps; }
  ScheduleDependencies& deps() { return _deps; }
private:
  ChoiceDepGraphNodePtr _node;
  ScheduleDependencies _deps;
};

/**
 * Contains an order to execute nodes in
 */
class Schedule : public jalib::JRefCounted, public jalib::JPrintable{
  /** Intermediate state used while scheduling */
  struct SchedulingState {
    ChoiceDepGraphNodeSet generated;
    ChoiceDepGraphNodeSet pending;
  };
public:
  Schedule(const RuleChoiceAssignment& choice,
           const ChoiceDepGraphNodeSet& inputs,
           const ChoiceDepGraphNodeSet& intermediates,
           const ChoiceDepGraphNodeSet& outputs)
    : _choiceAssignment(choice)
  {
    initialize(inputs, intermediates, outputs);
  }
  void generateCode(Transform& trans, CodeGenerator& o, RuleFlavor flavor, int n);

  size_t size() const { return _schedule.size(); }

  void print(std::ostream& o) const {
    o << "digraph schedule {\n";
    for(ScheduleT::const_iterator i=_schedule.begin(); i!=_schedule.end(); ++i){
      i->printNode(o);
    }
    for(ScheduleT::const_iterator i=_schedule.begin(); i!=_schedule.end(); ++i){
      i->printEdge(o);
    }
    o << "}\n";
  }

  void writeGraph(const char* filename) {
    std::ofstream of(filename);
    of << *this;
  }
protected:
  void initialize(const ChoiceDepGraphNodeSet& inputs,
                  const ChoiceDepGraphNodeSet& intermediates,
                  const ChoiceDepGraphNodeSet& outputs);
  void depthFirstChoiceDepGraphNode(SchedulingState& state, ChoiceDepGraphNode* n);
private:
  // the ordering
  typedef std::vector<ScheduleEntry> ScheduleT;
  ScheduleT _schedule;
  RuleChoiceAssignment _choiceAssignment;

  std::map<RuleChoiceConsumer*,bool> _copyAssignment;
  std::map<RuleChoiceConsumer*,int> _numOutOnGpu;
};

namespace {
  void reachFirstValidRuleFromHere(ChoiceDepGraphNodeList::iterator& _nodesIt,
                                   ChoiceDepGraphNodeList::iterator& _nodesEnd,
                                   RuleSet::iterator& _rulesIt) {
    if (_rulesIt != (*_nodesIt)->choices().end()) {
        //The rule is already valid
        return;
      }

    //This set of rules is finished! Let's go to the next one
    bool found;
    do {
      found=true;
      _nodesIt++;

      if (_nodesIt == _nodesEnd) {
        //No more rules!!
        break;
      }

      _rulesIt=(*_nodesIt)->choices().begin();

      if (_rulesIt == (*_nodesIt)->choices().end()) {
        found=false;
      }
    } while(!found);
  }
}

/**
 * Create a manage a set of legal schedules
 */
class StaticScheduler : public jalib::JRefCounted,
                        public jalib::JPrintable,
                        public jalib::SrcPosTaggable
{
public:
  class rule_iterator;
  friend class rule_iterator;
  class rule_iterator {
  public:
    rule_iterator(StaticScheduler& scheduler) {
      _nodesEnd = scheduler._allNodes.end();
      _nodesIt = scheduler._allNodes.begin();
      if (_nodesIt == _nodesEnd) {
        //There are no node and therefore no rules
        return;
      }
      else {
        _rulesIt = (*_nodesIt)->choices().begin();
        reachFirstValidRuleFromHere(_nodesIt, _nodesEnd, _rulesIt);
      }
    }

    rule_iterator(ChoiceDepGraphNodeList::iterator nodesIt)
                 : _nodesIt(nodesIt) {}

    void operator++ () {
      if (_nodesIt == _nodesEnd) {
        //The iterator is already at the end. Nothing to do
        return;
      }

      _rulesIt++;
      reachFirstValidRuleFromHere(_nodesIt, _nodesEnd, _rulesIt);
    }

    bool operator== (rule_iterator& that) {
      return _nodesIt==that._nodesIt && (_nodesIt==_nodesEnd
                                         || _rulesIt==that._rulesIt);
    }

    bool operator !=(rule_iterator& that) {
      return ! (*this==that);
    }

    RulePtr operator*() {
      return *_rulesIt;
    }

  private:
    ChoiceDepGraphNodeList::iterator _nodesIt;
    ChoiceDepGraphNodeList::iterator _nodesEnd;
    RuleSet::iterator _rulesIt;
  };

public:
  rule_iterator rule_begin() {
    return rule_iterator(*this);
  }

  rule_iterator rule_end() {
    return rule_iterator(_allNodes.end());
  }

public:
  class CantScheduleException {};

  ChoiceDepGraphNodeSet lookupNode(const MatrixDefPtr& matrix, const SimpleRegionPtr& region);

  StaticScheduler(const ChoiceGridMap& cg, Transform&);

  void markInputMatrix(const MatrixDefPtr& matrix){
    SimpleRegionPtr r = new SimpleRegion(matrix);
    ChoiceDepGraphNodeList& regions = _matrixToNodes[matrix];
    JASSERT(regions.size()==0)(matrix).Text("Rules given for input matrix");
    regions.push_back(new BasicChoiceDepGraphNode(matrix, r, NULL));
    _allNodes.push_back(regions.back());
    _inputsOriginal.insert(regions.back().asPtr());
    regions.back()->markInput();
  }

  void markOutputMatrix(const MatrixDefPtr& matrix){
    ChoiceDepGraphNodeList& lst = _matrixToNodes[matrix];
    JASSERT(lst.size()>0);
    for(ChoiceDepGraphNodeList::iterator i=lst.begin(); i!=lst.end(); ++i){
      _outputsOriginal.insert(i->asPtr());
      (*i)->markOutput();
    }
  }

  void renderGraph(const char* filename, const char* type="png") const;
  void writeGraph(const char* filename) const;
  void writeGraph(FILE* fd) const;

  void generateSchedule();

  void computeIndirectDependencies();
  void mergeCoscheduledNodes(const RuleChoiceAssignment& choice);

  //const ChoiceDepGraphNodeList& schedule() const { return _schedule; }

  void print(std::ostream& o) const {
    o << "digraph staticScheduler {\n";
    for(ChoiceDepGraphNodeList::const_iterator r=_allNodes.begin(); r!=_allNodes.end(); ++r){
      (*r)->printNode(o);
    }
    for(ChoiceDepGraphNodeList::const_iterator r=_allNodes.begin(); r!=_allNodes.end(); ++r){
      (*r)->printEdges(o);
    }
    o << "}\n";
  }

  void generateCode(Transform& trans, CodeGenerator& o, RuleFlavor type);

  void generateGlobalCode(Transform& trans, CodeGenerator& o);

  int size() const { return _allNodes.size() - _inputsOriginal.size(); }

private:

  struct DataDepSetCompare {
    bool operator() (const CoordinateFormula* a, const CoordinateFormula* b) const;
  };

  class DataDependencySet : public std::set<CoordinateFormula*,DataDepSetCompare> {
  public:
    /**
     * Return true if the given dimension is equal to value in al the data
     * dependency vectors in the set
     */
    bool isDimensionDependencyAlwaysEqualTo(size_t dimension, int value) const;
  };

  enum DimensionStatus {
    ALWAYS_MINUS1,
    ALWAYS_ZERO,
    OTHER
  };

  typedef std::map<MatrixDefPtr, DataDependencySet> MatrixDataDependencyMap;

private:
  void removeUselessDimensions();
  void removeUselessDimensions(std::vector<size_t> uselessDimensions,
                               MatrixDefPtr matrix);
  void importDataDepsFromRule(RulePtr& rule,
                              MatrixDataDependencyMap& dataDepsMap);
  std::vector<size_t> findUselessDimensions(
                                    const DataDependencySet matrixDependencies,
                                    const MatrixDefPtr matrix);

  void filterNonSelfDependentAccesses(std::vector<size_t>& uselessDimensions,
                                      const MatrixDefPtr matrix);
  MatrixDataDependencyMap getDataDepsForTemporaryMatrixes ();

  void fixVersionedRegionsType();
private:
  //storage of nodes
  std::map<MatrixDefPtr, ChoiceDepGraphNodeList> _matrixToNodes;
  ChoiceDepGraphNodeList _allNodes;
  ChoiceDepGraphNodeList _metaNodes;

  ChoiceDepGraphNodeSet _inputsOriginal;
  ChoiceDepGraphNodeSet _inputsRemapped;
  ChoiceDepGraphNodeSet _intermediatesOriginal;
  ChoiceDepGraphNodeSet _intermediatesRemapped;
  ChoiceDepGraphNodeSet _outputsOriginal;
  ChoiceDepGraphNodeSet _outputsRemapped;

  //output schedule
  typedef std::vector<SchedulePtr> SchedulesT;
  SchedulesT _schedules;

  RuleChoiceCollection _choices;

  std::string _dbgpath;
};

}

#endif


text:
package org.springframework.data.elasticsearch.core.mapping;

import java.beans.IntrospectionException;

import org.junit.Test;
import org.springframework.data.annotation.Version;
import org.springframework.data.mapping.MappingException;
import org.springframework.data.mapping.model.Property;
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.util.ClassTypeInformation;
import org.springframework.data.util.TypeInformation;
import org.springframework.util.ReflectionUtils;

/**
 * @author Rizwan Idrees
 * @author Mohsin Husen
 * @author Mark Paluch
 */
public class SimpleElasticsearchPersistentEntityTests {

	@Test(expected = IllegalArgumentException.class)
	public void shouldThrowExceptionGivenVersionPropertyIsNotLong() throws NoSuchFieldException, IntrospectionException {
		// given
		TypeInformation typeInformation = ClassTypeInformation.from(EntityWithWrongVersionType.class);
		SimpleElasticsearchPersistentEntity<EntityWithWrongVersionType> entity = new SimpleElasticsearchPersistentEntity<>(
				typeInformation);

		SimpleElasticsearchPersistentProperty persistentProperty = createProperty(entity, "version");

		// when
		entity.addPersistentProperty(persistentProperty);
	}

	@Test(expected = MappingException.class)
	public void shouldThrowExceptionGivenMultipleVersionPropertiesArePresent()
			throws NoSuchFieldException, IntrospectionException {
		// given
		TypeInformation typeInformation = ClassTypeInformation.from(EntityWithMultipleVersionField.class);
		SimpleElasticsearchPersistentEntity<EntityWithMultipleVersionField> entity = new SimpleElasticsearchPersistentEntity<>(
				typeInformation);

		SimpleElasticsearchPersistentProperty persistentProperty1 = createProperty(entity, "version1");

		SimpleElasticsearchPersistentProperty persistentProperty2 = createProperty(entity, "version2");

		entity.addPersistentProperty(persistentProperty1);
		// when
		entity.addPersistentProperty(persistentProperty2);
	}

	private static SimpleElasticsearchPersistentProperty createProperty(SimpleElasticsearchPersistentEntity<?> entity,
			String field) {

		TypeInformation<?> type = entity.getTypeInformation();
		Property property = Property.of(type, ReflectionUtils.findField(entity.getType(), field));
		return new SimpleElasticsearchPersistentProperty(property, entity, SimpleTypeHolder.DEFAULT);

	}

	private class EntityWithWrongVersionType {

		@Version private String version;

		public String getVersion() {
			return version;
		}

		public void setVersion(String version) {
			this.version = version;
		}
	}

	private class EntityWithMultipleVersionField {

		@Version private Long version1;
		@Version private Long version2;

		public Long getVersion1() {
			return version1;
		}

		public void setVersion1(Long version1) {
			this.version1 = version1;
		}

		public Long getVersion2() {
			return version2;
		}

		public void setVersion2(Long version2) {
			this.version2 = version2;
		}
	}
}


text:
extern crate bootstrap_rs as bootstrap;
extern crate polygon;

use bootstrap::window::*;
use polygon::*;

fn main() {
    // Open a window and create the renderer instance.
    let mut window = Window::new("Hello, Triangle!").unwrap();
    let mut renderer = RendererBuilder::new(&window).build();

    'outer: loop {
        while let Some(message) = window.next_message() {
            if let Message::Close = message {
                break 'outer;
            }
        }

        // Render our empty scene.
        renderer.draw();
    }
}


text:
layout: post
title: "Отчет об Evercode Talks №2"
date: 2013-01-05 13:30
comments: true
tags:
- events
- report
author: Roma Lapin
---

Под конец 2012-го мы провели наш [второй Evercode Talks](/evercode-talks-2-announcement/). В этот раз по менее тяжелой теме — микрофреймворки, и всего с двумя докладами. Под конец года не очень хотелось грузить и загружаться.

Приятно, что в этот раз на встречу пришло уже больше людей. Хотя для нас до сих пор загадка, почему их пришло в три раза меньше, чем зарегистрировалось :)

Я рассказал в общем про идею микрофреймворков, что с ними, как и где в докладе "Framework * 10<sup>-6</sup>. WTF?". А Петя затем разложил по полочкам все, что касается микрофреймворков на Ruby.

Очень порадовало, что было много вопросов и обсуждений, причем как и по теме встречи, так и в целом по проведению и участию в мероприятиях и нашей работы в Evercode Lab. Спасибо!

После полученной дозы знаний, многие присоединились к нашему скромному корпоративу в ближайшем баре, где все познакомились уже ближе, а разговоры были уже не только на технические темы :)

Слайды презентаций уже на speakerdeck. А мы все-таки обещаем в ближайшее время организовать место для координации будущих мероприятий, обсуждений и выкладывания материалов и фотографий со встреч.

<script async class="speakerdeck-embed" data-id="317e299039430130ce9f1231381f43f4" data-ratio="1.33333333333333" src="//speakerdeck.com/assets/embed.js"></script>

<script async class="speakerdeck-embed" data-id="8d00207032970130613922000a9d0644" data-ratio="1.2994923857868" src="//speakerdeck.com/assets/embed.js"></script>

Хорошего вам года!


text:
class UserRelationship < ActiveRecord::Base
  include AASM

  belongs_to :user
  belongs_to :follower, class_name: 'User', foreign_key: 'follower_id'
  belongs_to :following, class_name: 'User', foreign_key: 'follower_id'

  has_many :activities, as: :targetable, dependent: :destroy

  before_destroy :delete_mutual_following!

  aasm column: :state do
    state :following, initial: true
    state :followed
  end

  def self.request(user1, user2)
    UserRelationship.transaction do
      UserRelationship.create(user_id: user2.id, follower_id: user1.id, state: 'followed')
      UserRelationship.create(user_id: user1.id, follower_id: user2.id, state: 'following')

      # raise ActiveRecord::Rollback if user1 == user2
    end
  end

  def mutual_following
    # ToDo: Fix this so the first argument is the correct find method
    #
    # If User one visits User two's profile and click the follow button
    # User two should be user_id and User one should be follower_id
    self.class.where({user_id: follower_id, follower_id: user_id}).first
  end

  def delete_mutual_following!
    mutual_following.delete
  end

  # Make a some kind of notification that a user has a new follower
  def send_acceptance_email
    # UserMailer.delay.send_accepted_email(user_id)
  end
end


text:
using System.Web;

namespace WebApiHost
{
    public class WebApiApplication:HttpApplication
    {
        protected void Application_Start()
        {
            Bootstrapper.Start();
        }
    }
}