text:
import {parseAndGetExpression} from '../../../utils';
import {expect} from 'chai';

// also tests JSXOpeningElement and JSXClosingElement
describe('JSXElement', () => {
    it('should return correct type', () => {
        expect(parseAndGetExpression('<a/>').type).to.equal('JSXElement');
    });

    it('allow self closing tag', () => {
        const expression = parseAndGetExpression('< a / >');
        expect(expression.type).to.equal('JSXElement');
        expect(expression.openingElement.type).to.equal('JSXOpeningElement');
        expect(expression.openingElement.name.type).to.equal('JSXIdentifier');
        expect(expression.openingElement.name.name).to.equal('a');
        expect(expression.openingElement.attributes.length).to.equal(0);
        expect(expression.openingElement.selfClosing).to.equal(true);
        expect(expression.closingElement).to.equal(null);
        expect(expression.children.length).to.equal(0);
    });

    it('allow self closing tag containing an attribute without a value', () => {
        const expression = parseAndGetExpression('< a b / >');
        expect(expression.openingElement.attributes.length).to.equal(1);
        expect(expression.openingElement.attributes[0].type).to.equal('JSXAttribute');
        expect(expression.openingElement.attributes[0].name.type).to.equal('JSXIdentifier');
        expect(expression.openingElement.attributes[0].name.name).to.equal('b');
        expect(expression.openingElement.attributes[0].value).to.equal(null);
    });

    it('allow opening and closing tag', () => {
        const expression = parseAndGetExpression('< a >< / a >');
        expect(expression.type).to.equal('JSXElement');
        expect(expression.openingElement.type).to.equal('JSXOpeningElement');
        expect(expression.openingElement.name.type).to.equal('JSXIdentifier');
        expect(expression.openingElement.name.name).to.equal('a');
        expect(expression.openingElement.attributes.length).to.equal(0);
        expect(expression.openingElement.selfClosing).to.equal(false);
        expect(expression.closingElement.type).to.equal('JSXClosingElement');
        expect(expression.openingElement.name.type).to.equal('JSXIdentifier');
        expect(expression.openingElement.name.name).to.equal('a');
        expect(expression.openingElement.attributes.length).to.equal(0);
        expect(expression.children.length).to.equal(0);
    });

    it('allow opening and closing tag with JSXEmptyExpression', () => {
        const expression = parseAndGetExpression('< a >{}< / a >');
        expect(expression.type).to.equal('JSXElement');
        expect(expression.openingElement.type).to.equal('JSXOpeningElement');
        expect(expression.openingElement.name.type).to.equal('JSXIdentifier');
        expect(expression.openingElement.name.name).to.equal('a');
        expect(expression.openingElement.attributes.length).to.equal(0);
        expect(expression.openingElement.selfClosing).to.equal(false);
        expect(expression.closingElement.type).to.equal('JSXClosingElement');
        expect(expression.openingElement.name.type).to.equal('JSXIdentifier');
        expect(expression.openingElement.name.name).to.equal('a');
        expect(expression.openingElement.attributes.length).to.equal(0);
        expect(expression.children.length).to.equal(1);
        expect(expression.children[0].type).to.equal('JSXExpressionContainer');
        expect(expression.children[0].expression.type).to.equal('JSXEmptyExpression');
    });

    it('allow opening and closing tag with JSXText', () => {
        const expression = parseAndGetExpression('< a >asdf< / a >');
        expect(expression.type).to.equal('JSXElement');
        expect(expression.openingElement.type).to.equal('JSXOpeningElement');
        expect(expression.openingElement.name.type).to.equal('JSXIdentifier');
        expect(expression.openingElement.name.name).to.equal('a');
        expect(expression.openingElement.attributes.length).to.equal(0);
        expect(expression.openingElement.selfClosing).to.equal(false);
        expect(expression.closingElement.type).to.equal('JSXClosingElement');
        expect(expression.openingElement.name.type).to.equal('JSXIdentifier');
        expect(expression.openingElement.name.name).to.equal('a');
        expect(expression.openingElement.attributes.length).to.equal(0);
        expect(expression.children.length).to.equal(1);
        expect(expression.children[0].type).to.equal('JSXText');
        expect(expression.children[0].value).to.equal('asdf');

        // check the token is JSXIdentifier
        expect(expression.openingElement.childElements[2].type).to.equal('JSXIdentifier');
        // check the token is JSXText
        expect(expression.children[0].childElements[0].type).to.equal('JSXText');
    });

    it('allow opening and closing tag with StringLiteral', () => {
        const expression = parseAndGetExpression('< a >{"a"}< / a >');
        expect(expression.type).to.equal('JSXElement');
        expect(expression.openingElement.type).to.equal('JSXOpeningElement');
        expect(expression.openingElement.name.type).to.equal('JSXIdentifier');
        expect(expression.openingElement.name.name).to.equal('a');
        expect(expression.openingElement.attributes.length).to.equal(0);
        expect(expression.openingElement.selfClosing).to.equal(false);
        expect(expression.closingElement.type).to.equal('JSXClosingElement');
        expect(expression.openingElement.name.type).to.equal('JSXIdentifier');
        expect(expression.openingElement.name.name).to.equal('a');
        expect(expression.openingElement.attributes.length).to.equal(0);
        expect(expression.children.length).to.equal(1);
        expect(expression.children[0].type).to.equal('JSXExpressionContainer');
        expect(expression.children[0].expression.type).to.equal('StringLiteral');
        expect(expression.children[0].expression.value).to.equal('a');
        expect(expression.children[0].expression.raw).to.equal('"a"');
    });
});

redpajama_set_name: RedPajamaGithub


text:
@implementation NSString (CJExtensions)

- (BOOL)isEmpty
{
    return ![self length];
}

- (BOOL)isEmptyOrWhitespace
{
    return [self isEmpty] || ![[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length];
}

@end

@interface CJFloatingLabelTextField() <UITextFieldDelegate>

@property (nonatomic, strong) UITapGestureRecognizer *tapGestureRecognizer;

@property (nonatomic, assign) BOOL textFieldActive;
@property (nonatomic, assign) BOOL displayLabelShouldShrink;

@property (nonatomic, strong) UIImage *activeImage;
@property (nonatomic, strong) UIImage *inactiveImage;

- (void)setDefaultColors;

@end

@implementation CJFloatingLabelTextField
@synthesize textImageView = _textImageView;
@synthesize displayLabel = _displayLabel;
@synthesize textField = _textField;
@synthesize secureShowHideButton = _secureShowHideButton;
@synthesize bottomBorderView = _bottomBorderView;
@synthesize topBorderView = _topBorderView;

#pragma mark -
#pragma mark - Init Methods
- (id)init
{
    self = [super init];
    if (self)
    {
        [self performSetup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self)
    {
        [self performSetup];
    }
    return self;
}

- (void)performSetup
{
    self.textFieldActive = NO;
    self.displayLabelShouldShrink = NO;
    _secureTextEntry = NO;
    [self setDefaultColors];
    [self setDefaultFonts];

    self.translatesAutoresizingMaskIntoConstraints = NO;

    [self addSubview:self.textImageView];
    [self addSubview:self.displayLabel];
    [self addSubview:self.textField];
    [self addSubview:self.secureShowHideButton];
    [self addSubview:self.topBorderView];
    [self addSubview:self.bottomBorderView];

    self.localizedShowString = NSLocalizedString(@"Show", @"");
    self.localizedHideString = NSLocalizedString(@"Hide", @"");

    self.backgroundColor = self.inActiveBackgroundColor;

    _tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
    [self addGestureRecognizer:self.tapGestureRecognizer];
}

- (void)setDefaultColors
{
    self.inactiveColor = [UIColor grayColor];
    self.activeColor = [UIColor blackColor];
    self.activeBackgroundColor = [UIColor clearColor];
    self.inActiveBackgroundColor = [UIColor clearColor];
    self.borderColor = [UIColor blackColor];
}

- (void)setDefaultFonts
{
    self.textFieldFont = [UIFont boldSystemFontOfSize:14];
    self.labelFont = [UIFont systemFontOfSize:14];
    self.secureShowHideButtonFont = [UIFont systemFontOfSize:14];
}

#pragma mark -
#pragma mark - Secure Show Hide Button Methods
- (void)updateShowHideButtonText:(NSString *)text
{
    NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc] initWithString:text];
    [titleString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [titleString length])];
    [_secureShowHideButton setAttributedTitle:titleString forState:UIControlStateNormal];
}

- (void)showHideButtonSelected:(id)sender
{
    BOOL textShouldShow = !self.textField.secureTextEntry;
    self.textField.secureTextEntry = textShouldShow;
    NSString *text = (textShouldShow) ? self.localizedShowString : self.localizedHideString;
    [self updateShowHideButtonText:text];
}

- (void)setSecureTextEntry:(BOOL)secureTextEntry
{
    _secureTextEntry = secureTextEntry;
    self.textField.secureTextEntry = secureTextEntry;
    NSString *correctString = (self.textField.secureTextEntry) ? self.localizedShowString : self.localizedHideString;
    [self updateShowHideButtonText:correctString];
}

#pragma mark -
#pragma mark - UIView Lifecycle Methods
- (void)updateConstraints
{
    if (self.secureTextEntry)
    {
        [self.secureShowHideButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.mas_centerY);
            make.right.equalTo(self.mas_right).offset(-40);
        }];
    }

    [self.textImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.mas_centerY);
        make.left.equalTo(self.mas_left).offset(10);

        CGFloat imageWidth = (self.textImageView.image) ? 20 : 0;
        make.width.equalTo(@(imageWidth));
        make.height.equalTo(@(imageWidth));
    }];

    [self.topBorderView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top);
        make.left.equalTo(self.mas_left);
        make.right.equalTo(self.mas_right);
        make.height.equalTo(@0.5);
    }];

    [self.bottomBorderView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.mas_bottom);
        make.left.equalTo(self.mas_left);
        make.right.equalTo(self.mas_right);
        make.height.equalTo(@0.5);
    }];

    [self.displayLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        if (self.displayLabelShouldShrink) {
            make.top.equalTo(self.mas_top).offset(10);
            make.left.equalTo(self.textImageView.mas_right).offset(-(self.displayLabel.frame.size.width * 0.195)+10);
        } else {
            make.centerY.equalTo(self.mas_centerY);
            make.left.equalTo(self.textImageView.mas_right).offset(10);
        }

        make.height.equalTo(@20);
    }];

    [self.textField mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.mas_bottom).offset(-5);
        make.left.equalTo(self.textImageView.mas_right).offset(10);
        if (self.displayLabelShouldShrink) {
            MASViewAttribute *rightSide = (self.secureTextEntry) ? self.secureShowHideButton.mas_left : self.mas_right;
            make.right.equalTo(rightSide);
            make.height.equalTo(self.mas_height).offset(-20);
        } else {
            make.right.equalTo(self.textImageView.mas_right).offset(10);
            make.height.equalTo(@0);
        }
    }];

    [super updateConstraints];
}

#pragma mark -
#pragma mark - Getter Setter Overides Methods
- (NSString *)text
{
    return self.textField.text;
}

- (void)setText:(NSString *)text
{
    self.textField.text = text;
}

- (NSString *)labelText
{
    return self.displayLabel.text;
}

- (void)setLabelText:(NSString *)labelText
{
    self.displayLabel.text = labelText;
}

- (NSString *)placeholder
{
    return self.textField.placeholder;
}

- (void)setPlaceholder:(NSString *)placeholder
{
    self.textField.placeholder = placeholder;
}

- (void)setActiveColor:(UIColor *)activeColor
{
    _activeColor = activeColor;
    self.textField.textColor = _activeColor;
}

- (void)setInActiveBackgroundColor:(UIColor *)inActiveBackgroundColor
{
    _inActiveBackgroundColor = inActiveBackgroundColor;
    if (!self.textFieldActive) {
        self.backgroundColor = inActiveBackgroundColor;
    }
}

- (void)setActiveBackgroundColor:(UIColor *)activeBackgroundColor
{
    _activeBackgroundColor = activeBackgroundColor;
    if (self.textFieldActive) {
        self.backgroundColor = activeBackgroundColor;
    }
}

- (void)setBorderColor:(UIColor *)borderColor
{
    _borderColor = borderColor;
    self.topBorderView.backgroundColor = borderColor;
    self.bottomBorderView.backgroundColor = borderColor;
}

- (void)setTextFieldFont:(UIFont *)textFieldFont
{
    _textFieldFont = textFieldFont;
    self.textField.font = textFieldFont;
}

- (void)setLabelFont:(UIFont *)labelFont
{
    _labelFont = labelFont;
    self.displayLabel.font = labelFont;
}

- (void)setSecureShowHideButtonFont:(UIFont *)secureShowHideButtonFont
{
    _secureShowHideButtonFont = secureShowHideButtonFont;
    self.secureShowHideButton.titleLabel.font = secureShowHideButtonFont;
}

#pragma mark -
#pragma mark - Lazy Loaded properties
- (UILabel *)displayLabel
{
    if (!_displayLabel)
    {
        _displayLabel = [[UILabel alloc] init];
        _displayLabel.textColor = self.inactiveColor;
        _displayLabel.font = self.labelFont;
    }

    return _displayLabel;
}

- (UITextField *)textField
{
    if (!_textField)
    {
        _textField = [[UITextField alloc] init];
        _textField.delegate = self;
        _textField.font = self.textFieldFont;
    }

    return _textField;
}

- (UIImageView *)textImageView
{
    if (!_textImageView)
    {
        _textImageView = [[UIImageView alloc] initWithImage:self.inactiveImage];
        _textImageView.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _textImageView;
}

- (UIButton *)secureShowHideButton
{
    if (!_secureShowHideButton)
    {
        _secureShowHideButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _secureShowHideButton.tintColor = [UIColor blackColor];
        _secureShowHideButton.backgroundColor = [UIColor clearColor];
        _secureShowHideButton.titleLabel.font = self.secureShowHideButtonFont;
        [_secureShowHideButton addTarget:self action:@selector(showHideButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _secureShowHideButton;
}

- (UIView *)bottomBorderView
{
    if (!_bottomBorderView)
    {
        _bottomBorderView = [[UIView alloc] init];
        _bottomBorderView.hidden = YES;
        _bottomBorderView.backgroundColor = self.borderColor;
    }
    return _bottomBorderView;
}

- (UIView *)topBorderView
{
    if (!_topBorderView)
    {
        _topBorderView = [[UIView alloc] init];
        _topBorderView.hidden = YES;
        _topBorderView.backgroundColor = self.borderColor;
    }
    return _topBorderView;
}

#pragma mark -
#pragma mark - UIGestureRecognizer methods
- (void)tapped:(id)sender
{
    if (self.textFieldActive) return;
    self.textFieldActive = YES;
    self.displayLabelShouldShrink = YES;
    [self.textField becomeFirstResponder];
}

- (void)animateChangeAnimated:(BOOL)animated completion:(void (^)(BOOL finished))completion
{
    CGFloat size = (self.displayLabelShouldShrink) ? 0.6 : 1;

    [self setNeedsUpdateConstraints];

    [self updateConstraintsIfNeeded];

    UIImage *image = (self.textFieldActive) ? self.activeImage : self.inactiveImage;

    [UIView transitionWithView:self.textImageView
                      duration:0.1
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
                        self.textImageView.image = image;
                    } completion:nil];

    CABasicAnimation *ba = [CABasicAnimation animationWithKeyPath:@"transform"];
    ba.duration = 0.2;
    ba.fillMode = kCAFillModeForwards;
    ba.removedOnCompletion = NO;
    ba.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    ba.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(size, size, 1)];
    [self.displayLabel.layer addAnimation:ba forKey:nil];

    [UIView animateWithDuration:0.2
                          delay:0
                        options:UIViewAnimationOptionCurveEaseOut animations:^{
                            [self layoutIfNeeded];
                            [self changeColors];
                        } completion:^(BOOL finished) {
                            if (self.textFieldActive) [self.textField becomeFirstResponder];
                            if (completion) { completion(finished); }
                        }];
}

- (void)setActiveImage:(UIImage *)activeImage inactiveImage:(UIImage *)inactiveImage
{
    self.activeImage = activeImage;
    self.inactiveImage = inactiveImage;

    UIImage *image = (self.textFieldActive) ? self.activeImage : self.inactiveImage;

    self.textImageView.image = image;
}

- (void)shouldShowTopBorder:(BOOL)showTopBorder showBottomBorder:(BOOL)showBottomBorder
{
    self.topBorderView.hidden = !showTopBorder;
    self.bottomBorderView.hidden = !showBottomBorder;
}

- (void)changeColors
{
    self.backgroundColor = (self.textFieldActive) ? self.activeBackgroundColor : self.inActiveBackgroundColor;
    self.textField.textColor = (self.textFieldActive) ? self.activeColor : self.inactiveColor;
    self.displayLabel.textColor = (self.textFieldActive) ? self.activeColor : self.inactiveColor;
}

#pragma mark -
#pragma mark - Animation Methods
- (void)showContentsAnimated:(BOOL)animated completion:(void (^)(BOOL finished))completion
{
    self.textFieldActive = YES;
    self.displayLabelShouldShrink = YES;
    [self animateChangeAnimated:animated completion:completion];
}

- (void)hideContentsAnimated:(BOOL)animated completion:(void (^)(BOOL finished))completion
{
    self.textFieldActive = NO;
    self.displayLabelShouldShrink = NO;
    [self animateChangeAnimated:animated completion:completion];
    [self.textField resignFirstResponder];
}

#pragma mark -
#pragma mark - UITextFieldDelegate Methods
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return ([self.delegate respondsToSelector:@selector(textFieldShouldBeginEditing:)]) ? [self.delegate textFieldShouldBeginEditing:textField] : YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.displayLabelShouldShrink = YES;
    self.textFieldActive = YES;
    [self animateChangeAnimated:YES completion:nil];
    if ([self.delegate respondsToSelector:@selector(textFieldDidBeginEditing:)]) [self.delegate textFieldDidBeginEditing:textField];
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    return ([self.delegate respondsToSelector:@selector(textFieldShouldEndEditing:)]) ? [self.delegate textFieldShouldEndEditing:textField] : YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.textFieldActive = NO;
    self.displayLabelShouldShrink = ([self.textField.text isEmptyOrWhitespace]) ? NO : YES;
    [self animateChangeAnimated:YES completion:nil];

    if ([self.delegate respondsToSelector:@selector(textFieldDidEndEditing:)]) [self.delegate textFieldDidEndEditing:textField];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return ([self.delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) ? [self.delegate textField:textField shouldChangeCharactersInRange:range replacementString:string] : YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    return ([self.delegate respondsToSelector:@selector(textFieldShouldClear:)]) ? [self.delegate textFieldShouldClear:textField] : YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return ([self.delegate respondsToSelector:@selector(textFieldShouldReturn:)]) ? [self.delegate textFieldShouldReturn:textField] : YES;
}

@end


text:
using System;
using Rhino.ServiceBus.Internal;

namespace Rhino.ServiceBus.Impl
{
    public class InstanceSubscriptionInformation
    {
        public Guid InstanceSubscriptionKey { get; set; }
        public IMessageConsumer Consumer { get; set; }
        public Type[] ConsumedMessages { get; set; }

        public void Dispose()
        {
            Consumer = null;
        }
    }
}


text:
/* global LazyLoader, VorbisPictureComment */
/* exported FLACMetadata */
'use strict';

/**
 * Parse metadata for FLAC files (this is very similar to Ogg files, but with a
 * different container format).
 *
 * Format information:
 *   http://flac.sourceforge.net/format.html
 */
var FLACMetadata = (function() {
  // Fields that should be stored as integers, not strings
  var INTFIELDS = [
    'tracknum', 'trackcount', 'discnum', 'disccount'
  ];

  // Map FLAC field names to metadata property names
  var FLACFIELDS = {
    title: 'title',
    artist: 'artist',
    album: 'album',
    tracknumber: 'tracknum',
    tracktotal: 'trackcount',
    discnumber: 'discnum',
    disctotal: 'disccount'
  };

  /**
   * Parse a file and return a Promise with the metadata.
   *
   * @param {BlobView} blobview The audio file to parse.
   * @return {Promise} A Promise returning the parsed metadata object.
   */
  function parse(blobview) {
    // First four bytes are "fLaC" or we wouldn't be here.
    blobview.seek(4);

    return new Promise(function(resolve, reject) {
      var metadata = {};
      metadata.tag_format = 'flac';

      var has_vorbis_comment = false;
      var has_picture = false;

      function processBlock(block) {
        if (!block) {
          resolve(metadata);
          return false;
        }

        if (block.block_type === 4) {
          readAllComments(block.view, metadata);
          has_vorbis_comment = true;
        } else if (block.block_type === 6) {
          LazyLoader.load('js/metadata/vorbis_picture.js').then(() => {
            metadata.picture = VorbisPictureComment.readPicFrame(block.view);
          });
          has_picture = true;
        }

        return (!has_vorbis_comment || !has_picture);
      }

      findMetadataBlocks(blobview, processBlock);
    });
  }

  /**
   * Step over metadata blocks until we find the proper metadata block.
   *
   * @param {BlobView} blobview The BlobView for the file.
   * @param {function} callback The callback to process the block with.
   */
  function findMetadataBlocks(blobview, callback) {
    readMetadataBlockHeader(blobview).then(function(block) {
      if (!callback(block) || block.last) {
        callback(null);
      } else {
        block.view.advance(block.length - block.view.index);
        findMetadataBlocks(block.view, callback);
      }
    }).catch(function(err) {
      console.error('Error finding FLAC metadata:', err);
      callback(null);
    });
  }

  /**
   * Read a metadata block header and fetch its contents from the Blob, plus
   * enough extra data to read the next block's header.
   *
   * @param {BlobView} blobview The BlobView for the file.
   * @return {Promise} A Promise resolving to an object with the following
   *   fields:
   *     {Boolean} last True if this is the last metadata block.
   *     {Number} block_type The block's type, as an integer.
   *     {Number} length The size in bytes of the block's body (excluding the
   *       header).
   *     {BlobView} view The BlobView with the block's data, starting at the
   *       beginning of the metadata block's content (not the header).
   */
  function readMetadataBlockHeader(blobview) {
    return new Promise(function(resolve, reject) {
      var header = blobview.readUnsignedByte();
      var last = (header & 0x80) === 0x80;
      var block_type = header & 0x7F;
      var length = blobview.readUint24(false);

      // Get the contents of this block, plus enough to read the next block's
      // header if necessary.
      blobview.getMore(blobview.viewOffset + blobview.index, length + 4,
                       function(more, err) {
        if (err) {
          reject(err);
          return;
        }

        resolve({
          last: last,
          block_type: block_type,
          length: length,
          view: more
        });
      });
    });
  }

  /**
   * Read all the comments in a metadata header block.
   *
   * @param {BlobView} page The audio file being parsed.
   * @param {Metadata} metadata The (partially filled-in) metadata object.
   */
  function readAllComments(page, metadata) {
    var vendor_string_length = page.readUnsignedInt(true);
    page.advance(vendor_string_length); // skip vendor string

    var num_comments = page.readUnsignedInt(true);
    for (var i = 0; i < num_comments; i++) {
      try {
        var comment = readComment(page);
        if (comment) {
          if (!(comment.field in metadata)) {
            metadata[comment.field] = comment.value;
          } else {
            // We already have a value, so append this new one.
            metadata[comment.field] += ' / ' + comment.value;
          }
        }
      } catch (e) {
        console.warn('Error parsing vorbis comment', e);
      }
    }
  }

  /**
   * Read a single comment field.
   *
   * @param {BlobView} page The audio file being parsed.
   */
  function readComment(page) {
    var comment_length = page.readUnsignedInt(true);
    var comment = page.readUTF8Text(comment_length);
    var equal = comment.indexOf('=');
    if (equal === -1) {
      throw new Error('missing delimiter in comment');
    }

    var fieldname = comment.substring(0, equal).toLowerCase().replace(' ', '');
    var propname = FLACFIELDS[fieldname];
    if (propname) { // Do we care about this field?
      var value = comment.substring(equal + 1);
      if (INTFIELDS.indexOf(propname) !== -1) {
        value = parseInt(value, 10);
      }
      return {field: propname, value: value};
    }
    return null;
  }

  return {
    parse: parse
  };
})();


text:
package org.pentaho.di.imp.rule;

import java.util.List;

import junit.framework.TestCase;

import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.plugins.ImportRulePluginType;
import org.pentaho.di.core.plugins.PluginInterface;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.imp.rules.TransformationHasNoDisabledHopsImportRule;
import org.pentaho.di.trans.TransHopMeta;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.dummytrans.DummyTransMeta;

public class TransformationHasNoDisabledHopsImportRuleIT extends TestCase {

  @Override
  protected void setUp() throws Exception {
    KettleEnvironment.init();
  }

  public void testRule() throws Exception {

    // Create a transformation to test.
    //
    TransMeta transMeta = new TransMeta();

    // Add 3 dummy steps connected with hops.
    //
    StepMeta lastStep = null;
    for ( int i = 0; i < 3; i++ ) {
      DummyTransMeta dummyTransMeta = new DummyTransMeta();
      StepMeta stepMeta = new StepMeta( "dummy" + ( i + 1 ), dummyTransMeta );
      stepMeta.setLocation( 50 + i * 50, 50 );
      stepMeta.setDraw( true );
      transMeta.addStep( stepMeta );
      if ( lastStep != null ) {
        TransHopMeta hop = new TransHopMeta( lastStep, stepMeta );
        transMeta.addTransHop( hop );
      }
      lastStep = stepMeta;
    }

    // Load the plugin to test from the registry.
    //
    PluginRegistry registry = PluginRegistry.getInstance();
    PluginInterface plugin =
      registry.findPluginWithId( ImportRulePluginType.class, "TransformationHasNoDisabledHops" );
    assertNotNull(
      "The 'transformation has no disabled hops' rule could not be found in the plugin registry!", plugin );

    TransformationHasNoDisabledHopsImportRule rule =
      (TransformationHasNoDisabledHopsImportRule) registry.loadClass( plugin );
    assertNotNull(
      "The 'transformation has no disabled hops' class could not be loaded by the plugin registry!", plugin );

    rule.setEnabled( true );

    List<ImportValidationFeedback> feedback = rule.verifyRule( transMeta );
    assertTrue( "We didn't get any feedback from the 'transformation has no disabled hops'", !feedback.isEmpty() );
    assertTrue(
      "An approval ruling was expected",
      feedback.get( 0 ).getResultType() == ImportValidationResultType.APPROVAL );

    transMeta.getTransHop( 0 ).setEnabled( false );

    feedback = rule.verifyRule( transMeta );
    assertTrue( "We didn't get any feedback from the 'transformation has no disabled hops'", !feedback.isEmpty() );
    assertTrue(
      "An error ruling was expected", feedback.get( 0 ).getResultType() == ImportValidationResultType.ERROR );

    rule.setEnabled( false );

    feedback = rule.verifyRule( transMeta );
    assertTrue(
      "We didn't expect any feedback from the 'transformation has no disabled hops' while disabled", feedback
        .isEmpty() );

  }
}


text:
namespace media {

class MEDIA_EXPORT VideoFrame : public StreamSample {
 public:
  enum {
    kMaxPlanes = 3,

    kRGBPlane = 0,

    kYPlane = 0,
    kUPlane = 1,
    kVPlane = 2,
  };

  // Surface formats roughly based on FOURCC labels, see:
  // http://www.fourcc.org/rgb.php
  // http://www.fourcc.org/yuv.php
  // Keep in sync with WebKit::WebVideoFrame!
  enum Format {
    INVALID,     // Invalid format value.  Used for error reporting.
    RGB555,      // 16bpp RGB packed 5:5:5
    RGB565,      // 16bpp RGB packed 5:6:5
    RGB24,       // 24bpp RGB packed 8:8:8
    RGB32,       // 32bpp RGB packed with extra byte 8:8:8
    RGBA,        // 32bpp RGBA packed 8:8:8:8
    YV12,        // 12bpp YVU planar 1x1 Y, 2x2 VU samples
    YV16,        // 16bpp YVU planar 1x1 Y, 2x1 VU samples
    NV12,        // 12bpp YVU planar 1x1 Y, 2x2 UV interleaving samples
    EMPTY,       // An empty frame.
    ASCII,       // A frame with ASCII content. For testing only.
    I420,        // 12bpp YVU planar 1x1 Y, 2x2 UV samples.
    NATIVE_TEXTURE,  // Native texture.  Pixel-format agnostic.
  };

  // Creates a new frame in system memory with given parameters. Buffers for
  // the frame are allocated but not initialized.
  static scoped_refptr<VideoFrame> CreateFrame(
      Format format,
      size_t width,
      size_t height,
      base::TimeDelta timestamp,
      base::TimeDelta duration);

  // Call prior to CreateFrame to ensure validity of frame configuration. Called
  // automatically by VideoDecoderConfig::IsValidConfig().
  static bool IsValidConfig(
      Format format,
      size_t width,
      size_t height);

  // Wraps a native texture of the given parameters with a VideoFrame.  When the
  // frame is destroyed |no_longer_needed.Run()| will be called.
  static scoped_refptr<VideoFrame> WrapNativeTexture(
      uint32 texture_id,
      uint32 texture_target,
      size_t width,
      size_t height,
      base::TimeDelta timestamp,
      base::TimeDelta duration,
      const base::Closure& no_longer_needed);

  // Creates a frame with format equals to VideoFrame::EMPTY, width, height
  // timestamp and duration are all 0.
  static scoped_refptr<VideoFrame> CreateEmptyFrame();

  // Allocates YV12 frame based on |width| and |height|, and sets its data to
  // the YUV equivalent of RGB(0,0,0).
  static scoped_refptr<VideoFrame> CreateBlackFrame(int width, int height);

  Format format() const { return format_; }

  size_t width() const { return width_; }

  size_t height() const { return height_; }

  int stride(size_t plane) const;

  // Returns the number of bytes per row and number of rows for a given plane.
  //
  // As opposed to stride(), row_bytes() refers to the bytes representing
  // visible pixels.
  int row_bytes(size_t plane) const;
  int rows(size_t plane) const;

  // Returns pointer to the buffer for a given plane. The memory is owned by
  // VideoFrame object and must not be freed by the caller.
  uint8* data(size_t plane) const;

  // Returns the ID of the native texture wrapped by this frame.  Only valid to
  // call if this is a NATIVE_TEXTURE frame.
  uint32 texture_id() const;

  // Returns the texture target. Only valid for NATIVE_TEXTURE frames.
  uint32 texture_target() const;

  // StreamSample interface.
  virtual bool IsEndOfStream() const OVERRIDE;

  // Used to keep a running hash of seen frames.  Expects an initialized MD5
  // context.  Calls MD5Update with the context and the contents of the frame.
  void HashFrameForTesting(base::MD5Context* context);

 private:
  // Clients must use the static CreateFrame() method to create a new frame.
  VideoFrame(Format format,
             size_t video_width,
             size_t video_height,
             base::TimeDelta timestamp,
             base::TimeDelta duration);

  virtual ~VideoFrame();

  // Used internally by CreateFrame().
  void AllocateRGB(size_t bytes_per_pixel);
  void AllocateYUV();

  // Used to DCHECK() plane parameters.
  bool IsValidPlane(size_t plane) const;

  // Frame format.
  Format format_;

  // Width and height of surface.
  size_t width_;
  size_t height_;

  // Array of strides for each plane, typically greater or equal to the width
  // of the surface divided by the horizontal sampling period.  Note that
  // strides can be negative.
  int32 strides_[kMaxPlanes];

  // Array of data pointers to each plane.
  uint8* data_[kMaxPlanes];

  // Native texture ID, if this is a NATIVE_TEXTURE frame.
  uint32 texture_id_;
  uint32 texture_target_;
  base::Closure texture_no_longer_needed_;

  DISALLOW_IMPLICIT_CONSTRUCTORS(VideoFrame);
};

}  // namespace media

#endif  // MEDIA_BASE_VIDEO_FRAME_H_


text:
set -e

npm install electron-builder@next
npm install
npm prune


text:
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Xml.Linq;

using BeanIO.Internal.Parser.Format.Xml.Annotations;
using BeanIO.Internal.Util;
using BeanIO.Stream;

namespace BeanIO.Internal.Parser.Format.Xml
{
    internal class XmlMarshallingContext : MarshallingContext
    {
        private readonly Stack<IXmlNode> _groupStack;

        private XDocument _document;

        private XContainer _parent;

        private int _ungroup;

        /// <summary>
        /// Initializes a new instance of the <see cref="XmlMarshallingContext"/> class.
        /// </summary>
        /// <param name="groupDepth">the maximum depth of a group in the parser tree</param>
        /// <param name="nameConversionMode">the name conversion mode</param>
        public XmlMarshallingContext(int groupDepth, ElementNameConversionMode nameConversionMode)
        {
            _groupStack = new Stack<IXmlNode>(groupDepth);
            NameConversionMode = nameConversionMode;
        }

        /// <summary>
        /// Gets or sets a value indicating whether a stream is being marshalled, versus a single document.
        /// </summary>
        public bool IsStreaming { get; set; }

        /// <summary>
        /// Gets the element name conversion mode
        /// </summary>
        public ElementNameConversionMode NameConversionMode { get; }

        /// <summary>
        /// Gets the record object to pass to the <see cref="IRecordWriter"/>
        /// when <see cref="MarshallingContext.WriteRecord"/> is called.
        /// </summary>
        public object RecordObject => Document;

        /// <summary>
        /// Gets the document being marshalled
        /// </summary>
        [SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1513:ClosingBraceMustBeFollowedByBlankLine", Justification = "Reviewed.")]
        public XDocument Document
        {
            get
            {
                return _document;
            }
            private set
            {
                _document = value;
                Parent = value;
            }
        }

        /// <summary>
        /// Gets or sets the parent node to append in the document being marshalled.
        /// </summary>
        public XContainer Parent
        {
            get
            {
                if (_parent == null)
                {
                    _document = new XDocument();
                    _parent = _document;

                    while (_groupStack.Count != 0)
                    {
                        var xml = _groupStack.Pop();

                        var element = new XElement(xml.ToXName(false).ToConvertedName(NameConversionMode));
                        if (!string.IsNullOrEmpty(xml.Prefix))
                            element.SetAttributeValue(XNamespace.Xmlns + xml.Prefix, xml.Namespace);

                        element = XElement.Parse(element.ToString());
                        element.AddAnnotation(new IsGroupElementAnnotation(true));
                        if (!xml.IsNamespaceAware)
                        {
                            element.AddAnnotation(new NamespaceModeAnnotation(NamespaceHandlingMode.IgnoreNamespace));
                        }
                        else if (string.IsNullOrEmpty(xml.Namespace))
                        {
                            element.AddAnnotation(new NamespaceModeAnnotation(NamespaceHandlingMode.DefaultNamespace));
                        }
                        else if (string.Equals(xml.Prefix, string.Empty))
                        {
                            element.AddAnnotation(new NamespaceModeAnnotation(NamespaceHandlingMode.NoPrefix));
                        }

                        _parent.Add(element);

                        _parent = element;
                    }
                }

                return _parent;
            }
            set
            {
                _parent = value;
            }
        }

        /// <summary>
        /// Clear is invoked after each bean object (record or group) is marshalled
        /// </summary>
        public override void Clear()
        {
            Document = null;
        }

        /// <summary>
        /// Writes the current record object to the record writer.
        /// </summary>
        /// <remarks>
        /// This method uses the <see cref="MarshallingContext.ToRecordObject"/>.
        /// </remarks>
        public override void WriteRecord()
        {
            base.Clear();

            for (var i = 0; i != _ungroup; ++i)
                RecordWriter.Write(null);
            _ungroup = 0;

            base.WriteRecord();
        }

        /// <summary>
        /// Adds a group to be marshalled when the next record is written to
        /// the output stream.
        /// </summary>
        /// <param name="node">the group element to add</param>
        public virtual void OpenGroup(IXmlNode node)
        {
            _groupStack.Push(node);
        }

        /// <summary>
        /// Indicates a group element should be closed before marshalling the next record.
        /// </summary>
        /// <param name="node">the <see cref="IXmlNode"/> to close</param>
        public virtual void CloseGroup(IXmlNode node)
        {
            ++_ungroup;
        }

        /// <summary>
        /// Converts a record object to a <see cref="XDocument"/>.
        /// </summary>
        /// <param name="record">the record object to convert</param>
        /// <returns>the <see cref="XDocument"/> result, or null if not supported</returns>
        public override XDocument ToXDocument(object record)
        {
            return (XDocument)record;
        }

        /// <summary>
        /// Creates the record object to pass to the <see cref="IRecordWriter"/>
        /// when <see cref="MarshallingContext.WriteRecord"/> is called.
        /// </summary>
        /// <returns>
        /// The newly created record object.
        /// </returns>
        protected override object ToRecordObject()
        {
            return Document;
        }
    }
}


text:
var common = require('./common');
var fs = require('fs');

//@
//@ ### tail([{'-n', \<num\>},] file [, file ...])
//@ ### tail([{'-n', \<num\>},] file_array)
//@
//@ Examples:
//@
//@ ```javascript
//@ var str = tail({'-n', 1}, 'file*.txt');
//@ var str = tail('file1', 'file2');
//@ var str = tail(['file1', 'file2']); // same as above
//@ ```
//@
//@ Output the last 10 lines of a file (or the last `<num>` if `-n` is
//@ specified)
function _tail(options, files) {
  options = common.parseOptions(options, {
    'n': 'numLines'
  });
  var tail = [];
  var pipe = common.readFromPipe(this);

  if (!files && !pipe)
    common.error('no paths given');

  var idx = 1;
  if (options.numLines === true) {
    idx = 2;
    options.numLines = Number(arguments[1]);
  } else if (options.numLines === false) {
    options.numLines = 10;
  }
  options.numLines = -1 * Math.abs(options.numLines);
  files = [].slice.call(arguments, idx);

  if (pipe)
    files.unshift('-');

  var shouldAppendNewline = false;
  files.forEach(function(file) {
    if (!fs.existsSync(file) && file !== '-') {
      common.error('no such file or directory: ' + file, true);
      return;
    }

    var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8');

    var lines = contents.split('\n');
    if (lines[lines.length-1] === '') {
      lines.pop();
      shouldAppendNewline = true;
    } else {
      shouldAppendNewline = false;
    }

    tail = tail.concat(lines.slice(options.numLines));
  });

  if (shouldAppendNewline)
    tail.push(''); // to add a trailing newline once we join
  return new common.ShellString(tail.join('\n'), common.state.error, common.state.errorCode);
}
module.exports = _tail;


text:
package com.github.dbourdette.otto.web.controller.api;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
    public BadRequestException() {
    }

    public BadRequestException(String s) {
        super(s);
    }

    public BadRequestException(String s, Throwable throwable) {
        super(s, throwable);
    }

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


text:
.PHONY: dist build
install:
	@npm install

dev: install
	@npm run dev

build:
	@npm run build


text:
#ifndef COIN_SOTRANSLATE2DRAGGER_H
#define COIN_SOTRANSLATE2DRAGGER_H

#include <Inventor/draggers/SoDragger.h>
#include <Inventor/tools/SbPimplPtr.h>
#include <Inventor/fields/SoSFVec3f.h>
#include <Inventor/fields/SoSFVec2f.h>

class SoSensor;
class SoFieldSensor;
class SbPlaneProjector;
class SoTranslate2DraggerP;

class COIN_DLL_API SoTranslate2Dragger : public SoDragger {
  typedef SoDragger inherited;

  SO_KIT_HEADER(SoTranslate2Dragger);
  SO_KIT_CATALOG_ENTRY_HEADER(axisFeedbackSwitch);
  SO_KIT_CATALOG_ENTRY_HEADER(feedback);
  SO_KIT_CATALOG_ENTRY_HEADER(feedbackActive);
  SO_KIT_CATALOG_ENTRY_HEADER(feedbackSwitch);
  SO_KIT_CATALOG_ENTRY_HEADER(translator);
  SO_KIT_CATALOG_ENTRY_HEADER(translatorActive);
  SO_KIT_CATALOG_ENTRY_HEADER(translatorSwitch);
  SO_KIT_CATALOG_ENTRY_HEADER(xAxisFeedback);
  SO_KIT_CATALOG_ENTRY_HEADER(yAxisFeedback);

public:
  static void initClass(void);
  SoTranslate2Dragger(void);

  SoSFVec3f translation;
  SoSFVec2f minTranslation;
  SoSFVec2f maxTranslation;

protected:
  virtual ~SoTranslate2Dragger(void);
  virtual SbBool setUpConnections(SbBool onoff, SbBool doitalways = FALSE);
  virtual void setMotionMatrix(const SbMatrix & m);

  static void startCB(void * f, SoDragger * d);
  static void motionCB(void * f, SoDragger * d);
  static void finishCB(void * f, SoDragger * d);
  static void metaKeyChangeCB(void * f, SoDragger * d);
  static void fieldSensorCB(void * f, SoSensor * s);
  static void valueChangedCB(void * f, SoDragger * d);

  void dragStart(void);
  void drag(void);
  void dragFinish(void);

  SoFieldSensor * fieldSensor;
  SbVec3f worldRestartPt;
  SbPlaneProjector * planeProj;

private:
  int constraintState;

private:
  SbVec3f clampMatrix(SbMatrix & m) const;

  SbPimplPtr<SoTranslate2DraggerP> pimpl;

  // NOT IMPLEMENTED:
  SoTranslate2Dragger(const SoTranslate2Dragger & rhs);
  SoTranslate2Dragger & operator = (const SoTranslate2Dragger & rhs);
}; // SoTranslate2Dragger

#endif // !COIN_SOTRANSLATE2DRAGGER_H


text:
exports.Sections = {
	"Kappa Cup Season 3": { column: 5, sort: 4, },
};
exports.Formats = [
	{
		name: "Uber Tier Shift",
		desc: [
			"Pokémon get all their stats boosted/nerfed according to tiers. Uber get -5, UU/BL2 get +5, RU/BL3 get +10, NU/BL4 get +15, PU get +20, and FU and lower get +25.",
			"• Tier Shift",
		],
		section: "Kappa Cup Season 3",
		column: 4,

		mod: 'ubertiershift',
		ruleset: ['Ubers'],
		banlist: [],
	},
	{
		name: "Mix and Mega Doubles",
		section: "Kappa Cup Season 3",

		mod: 'mixandmega',
		gameType: 'doubles',
		ruleset: ['Doubles Ubers'],
		banlist: ['Gengarite', 'Shadow Tag', 'Dynamic Punch', 'Zap Cannon', 'Electrify'],
		onValidateTeam: function (team) {
			let itemTable = {};
			for (let i = 0; i < team.length; i++) {
				let item = this.getItem(team[i].item);
				if (!item) continue;
				if (itemTable[item] && item.megaStone) return ["You are limited to one of each Mega Stone.", "(You have more than one " + this.getItem(item).name + ")"];
				if (itemTable[item] && (item.id === 'blueorb' || item.id === 'redorb')) return ["You are limited to one of each Primal Orb.", "(You have more than one " + this.getItem(item).name + ")"];
				itemTable[item] = true;
			}
		},
		onValidateSet: function (set) {
			let template = this.getTemplate(set.species || set.name);
			let item = this.getItem(set.item);
			if (!item.megaEvolves && item.id !== 'blueorb' && item.id !== 'redorb') return;
			if (template.baseSpecies === item.megaEvolves || (template.baseSpecies === 'Groudon' && item.id === 'redorb') || (template.baseSpecies === 'Kyogre' && item.id === 'blueorb')) return;
			if (template.evos.length) return ["" + template.species + " is not allowed to hold " + item.name + " because it's not fully evolved."];
			let uberStones = ['beedrillite', 'gengarite', 'kangaskhanite', 'mawilite', 'medichamite'];
			if (template.tier === 'Uber' || uberStones.indexOf(item.id) >= 0) return ["" + template.species + " is not allowed to hold " + item.name + "."];
		},
		onBegin: function () {
			let allPokemon = this.p1.pokemon.concat(this.p2.pokemon);
			for (let i = 0, len = allPokemon.length; i < len; i++) {
				let pokemon = allPokemon[i];
				pokemon.originalSpecies = pokemon.baseTemplate.species;
			}
		},
		onSwitchIn: function (pokemon) {
			let oMegaTemplate = this.getTemplate(pokemon.template.originalMega);
			if (oMegaTemplate.exists && pokemon.originalSpecies !== oMegaTemplate.baseSpecies) {
				// Place volatiles on the Pokémon to show its mega-evolved condition and details
				this.add('-start', pokemon, oMegaTemplate.requiredItem || oMegaTemplate.requiredMove, '[silent]');
				let oTemplate = this.getTemplate(pokemon.originalSpecies);
				if (oTemplate.types.length !== pokemon.template.types.length || oTemplate.types[1] !== pokemon.template.types[1]) {
					this.add('-start', pokemon, 'typechange', pokemon.template.types.join('/'), '[silent]');
				}
			}
		},
		onSwitchOut: function (pokemon) {
			let oMegaTemplate = this.getTemplate(pokemon.template.originalMega);
			if (oMegaTemplate.exists && pokemon.originalSpecies !== oMegaTemplate.baseSpecies) {
				this.add('-end', pokemon, oMegaTemplate.requiredItem || oMegaTemplate.requiredMove, '[silent]');
			}
		},
	},
	{
		name: "Uber Alphabet Cup",
		section: "Kappa Cup Season 3",

		searchShow: false,
		ruleset: ['Pokemon', 'Team Preview', 'Standard'],
		banlist: ['Swoobat', 'Ignore Alphabet Moves'],
		onValidateTeam: function (team, format) {
			let letters = {};
			let letter = '';
			for (let i = 0; i < team.length; i++) {
				letter = Tools.getTemplate(team[i]).species.slice(0, 1).toUpperCase();
				if (letter in letters) return ['Your team cannot have more that one Pokémon starting with the letter "' + letter + '".'];
				letters[letter] = 1;
			}
		},
	},
	{
		name: "Ubers Got Talent",
		desc: ["• Got Talent"],
		section: "Kappa Cup Season 3",

		mod: 'gottalent',
		ruleset: ['Ubers'],
		banlist: ['Shuckle', 'Speed Boost'],
	},
	{
		name: "Cross Evolution+",
		section: "Kappa Cup Season 3",

		ruleset: ['Ubers', 'Baton Pass Clause'],
		onValidateTeam: function (team) {
			let nameTable = {};
			for (let i = 0; i < team.length; i++) {
				let name = team[i].name;
				if (name) {
					if (nameTable[name]) {
						return ["Your Pokémon must have different nicknames.", "(You have more than one " + name + ")"];
					}
					nameTable[name] = true;
				}
			}
		},
		// Note: "validateSet" = replace set validation rules. "onValidateSet" = additional set rules.
		// Also, "validateTeam" = completely replace all validation.
		validateSet: function (set, teamHas) {
			let crossTemplate = this.tools.getTemplate(set.name);
			if (!crossTemplate.exists) return this.validateSet(set, teamHas);
			let template = this.tools.getTemplate(set.species);
			if (!template.exists) return ["The Pokemon '" + set.species + "' does not exist."];
			if (!template.evos.length) return ["" + template.species + " cannot cross evolve because it doesn't evolve."];
			if (crossTemplate.species == 'Shedinja' || crossTemplate.species == 'Gyarados') return ["" + template.species + " cannot cross evolve into " + crossTemplate.species + " because it is a banned evolution."];
			if (template.species == 'Scyther' || template.species == 'Sneasel' || template.species == 'Archen') return ["" + template.species + " cannot cross evolve into " + crossTemplate.species + " because it is banned from cross evolving."];
			if (crossTemplate.battleOnly || !crossTemplate.prevo) return ["" + template.species + " cannot cross evolve into " + crossTemplate.species + " because it isn't an evolution."];
			let crossPrevoTemplate = this.tools.getTemplate(crossTemplate.prevo);
			if (!crossPrevoTemplate.prevo !== !template.prevo) return ["" + template.species + " cannot cross into " + crossTemplate.species + " because they are not consecutive evolutionary stages."];

			// Make sure no stat is too high/low to cross evolve to
			let stats = {'hp': 'HP', 'atk': 'Attack', 'def': 'Defense', 'spa': 'Special Attack', 'spd': 'Special Defense', 'spe': 'Speed'};
			for (let statid in template.baseStats) {
				let evoStat = template.baseStats[statid] + crossTemplate.baseStats[statid] - crossPrevoTemplate.baseStats[statid];
				if (evoStat < 1) {
					return ["" + template.species + " cannot cross evolve to " + crossTemplate.species + " because its " + stats[statid] + " would be too low."];
				} else if (evoStat > 255) {
					return ["" + template.species + " cannot cross evolve to " + crossTemplate.species + " because its " + stats[statid] + " would be too high."];
				}
			}

			let mixedTemplate = Object.assign({}, template);
			// Ability test
			let ability = this.tools.getAbility(set.ability);
			if (ability.name !== 'Huge Power' && ability.name !== 'Pure Power' && ability.name !== 'Shadow Tag') mixedTemplate.abilities = crossTemplate.abilities;

			mixedTemplate.learnset = Object.assign({}, template.learnset);
			let newMoves = 0;
			for (let i in set.moves) {
				let move = toId(set.moves[i]);
				if (!this.checkLearnset(move, template)) continue;
				if (this.checkLearnset(move, crossTemplate)) continue;
				if (++newMoves > 2) continue;
				mixedTemplate.learnset[move] = ['6T'];
			}
			return this.validateSet(set, teamHas, mixedTemplate);
		},
		onBegin: function () {
			let allPokemon = this.p1.pokemon.concat(this.p2.pokemon);
			for (let i = 0, len = allPokemon.length; i < len; i++) {
				let pokemon = allPokemon[i];
                                if (pokemon.set.name === pokemon.set.species) continue;
				let crossTemplate = this.getTemplate(pokemon.name);
				if (!crossTemplate.exists) continue;
				try {
				let template = pokemon.baseTemplate;
				let crossPrevoTemplate = this.getTemplate(crossTemplate.prevo);
				let mixedTemplate = Object.assign({}, template);
				mixedTemplate.baseSpecies = mixedTemplate.species = template.species + '-' + crossTemplate.species;
				mixedTemplate.weightkg = Math.max(0.1, template.weightkg + crossTemplate.weightkg - crossPrevoTemplate.weightkg);
				mixedTemplate.nfe = false;

				mixedTemplate.baseStats = {};
				for (let statid in template.baseStats) {
					mixedTemplate.baseStats[statid] = template.baseStats[statid] + crossTemplate.baseStats[statid] - crossPrevoTemplate.baseStats[statid];
				}
				pokemon.hp = pokemon.maxhp = Math.floor(Math.floor(2 * mixedTemplate.baseStats['hp'] + pokemon.set.ivs['hp'] + Math.floor(pokemon.set.evs['hp'] >> 2) + 100) * pokemon.level / 100 + 10);

				mixedTemplate.types = template.types.slice();
				if (crossTemplate.types[0] !== crossPrevoTemplate.types[0]) mixedTemplate.types[0] = crossTemplate.types[0];
				if (crossTemplate.types[1] !== crossPrevoTemplate.types[1]) mixedTemplate.types[1] = crossTemplate.types[1] || crossTemplate.types[0];
				if (mixedTemplate.types[0] === mixedTemplate.types[1]) mixedTemplate.types.length = 1;

				pokemon.baseTemplate = mixedTemplate;
				pokemon.formeChange(mixedTemplate);
				pokemon.crossEvolved = true;
				} catch (e) {
					this.add('-hint', 'Failed to cross evolve ' + pokemon.baseTemplate.species + ' to ' + crossTemplate.species + '. Please report this error so that it can be fixed.');
				}
			}
		},
		onSwitchInPriority: 1,
		onSwitchIn: function (pokemon) {
			if (pokemon.crossEvolved) {
				this.add('-start', pokemon, 'typechange', pokemon.types.join('/'), '[silent]');
			}
		},
	},
	{
		name: "Trademarked-EX",
		section: "Kappa Cup Season 3",

		mod: 'trademark',
		ruleset: ['Ubers'],
		banlist: ['Ignore Illegal Abilities'],

		onValidateTeam: function (team) {
			let abilityTable = {};
			let restrictedCount = 0;
			for (let i = 0; i < team.length; i++) {
				let ability = team[i].ability;
				if (ability && ability.isTrademark) {
					if (abilityTable[name]) {
						return ["Your Pokémon must have different trademarked abilities.", "(You have more than one Pokémon with the " + ability + " trademark)"];
					}
					if (ability === "partingshot" || ability === "batonpass" || ability === "protect" || ability === "spikyshield") {
						restrictedCount++;
					}
					abilityTable[name] = true;
				}
			}
			if (restrictedCount > 1) {
				return ["You can only have one of Parting Shot, Baton Pass, Protect and Spiky Shield as a trademark."];
			}
		},
		onValidateSet: function (set) {
			let bannedTrademarks = [
				'Block', 'Mean Look', 'Spider Web', 'Nature Power', 'Heal Pulse', 'Confuse Ray',
				'Flatter', 'Swagger', 'Teeter Dance', 'Supersonic', 'Sweet Kiss', 'Detect', 'Copycat',
				'Destiny Bond', 'Me First', 'Mimic', 'Mirror Move', 'Sketch', 'Mat Block', 'Skill Swap',
				'Roar', 'Whirlwind', 'Assist',
			];
			let move = this.getMove(set.ability);
			if (!move.exists) {
				let abilities = this.getTemplate(set.species).abilities;
				let legalAbility = false;
				for (let a in abilities) {
					if (abilities[a] === set.ability) {
						legalAbility = true;
					}
				}
				return !legalAbility ? ['' + set.species + ' cannot have ' + set.ability] : [];
			}
			if (bannedTrademarks.includes(move.name)) {
				return [move.name + ' is a banned trademark.', '(' + set.species + ' has ' + move.name + ' as a trademark.)'];
			}
			if (set.species === 'Slaking' || set.species === 'Regigigas' || this.getTemplate(set.species).tier === 'Uber') {
				return [set.species + ' can\'t use trademarked moves.', '(' + set.species + ' has ' + move.name + '.)'];
			}
			if (move.name === 'Roar' || move.name === 'Whirlwind') return ['' + set.species + ' has an illegal trademark ability', '(' + move.name + ' is not allowed as a trademark ability)'];
			if (move.category !== 'Status') return ['You can only trademark status moves', '(' + set.species + '\'s trademark is ' + move.name + ')'];
			if (set.moves.indexOf(move.name) >= 0) return ['You cannot use a move that is trademarked', '(' + set.species + ' has ' + move.name + ' as ability and a move)'];

			let template = this.getTemplate(set.species);
			template = this.getTemplate(template.baseSpecies);
			let added = {};
			let canLearn = set.species === 'Smeargle';
			do {
				// We don't care for how it obtains the move as long as the Pokemon learns it
				added[template.species] = true;
				if (template.learnset[move.id]) {
					canLearn = true;
					break;
				}
				if (template.prevo) {
					template = this.getTemplate(template.prevo);
				}
			} while (template && template.species && !added[template.species]);
			if (!canLearn) {
				return ['' + set.species + ' cannot learn ' + move.name];
			}
		},
	},
	{
		name: 'Classic Stat Switch',
		section: 'Kappa Cup Season 3',

		mod: 'classicstatswitch',
		ruleset: ['Ubers', 'Baton Pass Clause'],
		banlist: ['Azumarill', 'Regirock', 'Regice', 'Mawilite', 'Diancite'],
		onModifyMove: function (move) {
			if (move.category == "Status") return;
			let physicalTypes = [
				'Normal', 'Fighting', 'Flying', 'Ground', 'Rock', 'Bug',
				'Ghost', 'Poison', 'Steel',
			];
			if (physicalTypes.includes(move.type)) {
				move.category = "Physical";
			} else {
				move.category = "Special";
			}
		},
		onModifyMovePriority: -100,
	},
	{
		name: "[Gen 7] Reverse Type Matchup",
		desc: [
			"The Attackers and Defenders on the type chart are reversed.",
		],
		section: "Kappa Cup Season 3",

		mod: 'reverse',
		ruleset: ['Pokemon Plus', 'Standard', 'Swagger Clause', 'Team Preview', 'Mega Rayquaza Clause'],
		banlist: ['Allow Fake'],
	},
	{
		name: "Linked",
		desc: [
			"The first and second moves of Pokémon become linked. These moves are in turn used one after the other.",
			"• Linked",
		],
		section: "Kappa Cup Season 3",

		mod: 'linked',
		ruleset: ['Ubers'],
		banlist: ['Razor Fang', "King's Rock"],

		onValidateTeam: function (team, format) {
			var hasChoice = false;
			for (var i = 0; i < team.length; i++) {
				var item = toId(team[i].item);
				if (!item) continue;
				if (item === 'choiceband' || item === 'choicescarf' || item === 'choicespecs') {
					if (hasChoice) return ["You are limited to one Choice item."];
					hasChoice = true;
				}
			}
		},
		onValidateSet: function (set) {
			if (set.moves && set.moves.length >= 2) {
				var moves = [toId(set.moves[0]), toId(set.moves[1])];
				if (moves.indexOf('craftyshield') >= 0 || moves.indexOf('detect') >= 0 || moves.indexOf('kingsshield') >= 0 || moves.indexOf('protect') >= 0 || moves.indexOf('spikyshield') >= 0) {
					return ["Linking protect moves is banned."];
				}
				if (moves.indexOf('superfang') >= 0 && (moves.indexOf('nightshade') >= 0 || moves.indexOf('seismictoss') >= 0)) {
					return ["Linking Super Fang with Night Shade or Seismic Toss is banned."];
				}
				if (this.getMove(moves[0]).flags['charge'] || this.getMove(moves[1]).flags['charge']) {
					return ["Linking two turn moves is banned."];
				}
			}
		}
	},
];


text:
external help file: PowerShellEditorServices.Commands-help.xml
online version: https://github.com/PowerShell/PowerShellEditorServices/tree/main/module/docs/Set-ScriptExtent.md
schema: 2.0.0
---

# Set-ScriptExtent

## SYNOPSIS

Replaces text at a specified IScriptExtent object.

## SYNTAX

### __AllParameterSets (Default)

```powershell
Set-ScriptExtent [-Text] <PSObject> [-Extent <IScriptExtent>] [<CommonParameters>]
```

### AsString

```powershell
Set-ScriptExtent [-Text] <PSObject> [-AsString] [-Extent <IScriptExtent>] [<CommonParameters>]
```

### AsArray

```powershell
Set-ScriptExtent [-Text] <PSObject> [-AsArray] [-Extent <IScriptExtent>] [<CommonParameters>]
```

## DESCRIPTION

The Set-ScriptExtent function can insert or replace text at a specified position in a file open in PowerShell Editor Services.

You can use the Find-Ast function to easily find the desired extent.

## EXAMPLES

### -------------------------- EXAMPLE 1 --------------------------

```powershell
Find-Ast { 'gci' -eq $_ } | Set-ScriptExtent -Text 'Get-ChildItem'
```

Replaces all instances of 'gci' with 'Get-ChildItem'

### -------------------------- EXAMPLE 2 --------------------------

```powershell
$manifestAst = Find-Ast { 'FunctionsToExport' -eq $_ } | Find-Ast -First
$manifestAst | Set-ScriptExtent -Text (gci .\src\Public).BaseName -AsArray
```

Replaces the current value of FunctionsToExport in a module manifest with a list of files in the Public folder as a string array literal expression.

## PARAMETERS

### -Text

Specifies the text to insert in place of the extent.  Any object can be specified, but will be converted to a string before being passed to PowerShell Editor Services.

```yaml
Type: PSObject
Parameter Sets: (All)
Aliases: Value

Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -AsString

Specifies to insert as a single quoted string expression.

```yaml
Type: SwitchParameter
Parameter Sets: AsString
Aliases:

Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### -AsArray

Specifies to insert as a single quoted string list.  The list is separated by comma and new line, and will be adjusted to a hanging indent.

```yaml
Type: SwitchParameter
Parameter Sets: AsArray
Aliases:

Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### -Extent

Specifies the extent to replace within the editor.

```yaml
Type: IScriptExtent
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: (Find-Ast -AtCursor).Extent
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```

### CommonParameters

This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### System.Management.Automation.Language.IScriptExtent

You can pass ScriptExtent objects to this function.  You can also pass objects with a property named "Extent" such as ASTs from Find-Ast or tokens from Get-Token.

## OUTPUTS

### None

## NOTES

## RELATED LINKS

[Find-Ast](Find-Ast.md)
[ConvertTo-ScriptExtent](ConvertTo-ScriptExtent.md)
[ConvertFrom-ScriptExtent](ConvertFrom-ScriptExtent.md)
[Test-ScriptExtent](Test-ScriptExtent.md)
[Join-ScriptExtent](Join-ScriptExtent.md)


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 337516 $ -->

<refentry xml:id="imagickkernel.frombuiltin" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>ImagickKernel::fromBuiltIn</refname>
  <refpurpose>Description</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <modifier>public</modifier> <modifier>static</modifier> <type>ImagickKernel</type><methodname>ImagickKernel::fromBuiltin</methodname>
   <methodparam><type>string</type><parameter>kernelType</parameter></methodparam>
   <methodparam><type>string</type><parameter>kernelString</parameter></methodparam>
  </methodsynopsis>
  <para>
   Create a kernel from a builtin in kernel. See http://www.imagemagick.org/Usage/morphology/#kernel for examples. Currently the 'rotation' symbols are not supported. Example:
   $diamondKernel = ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DIAMOND, "2");
  </para>

 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <variablelist>
   <varlistentry>
    <term><parameter>kerneltype</parameter></term>
    <listitem>
     <para>
      The type of kernel to build e.g. \Imagick::KERNEL_DIAMOND
     </para>
    </listitem>
   </varlistentry>
   <varlistentry>
    <term><parameter>kernelString</parameter></term>
    <listitem>
     <para>
      A string that describes the parameters e.g. "4,2.5"
     </para>
    </listitem>
   </varlistentry>
  </variablelist>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>

  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
    <example>
      <title> <function>ImagickKernel::fromBuiltin</function></title>
      <programlisting role="php">
      <![CDATA[
<?php

function renderKernel(ImagickKernel $imagickKernel) {
    $matrix = $imagickKernel->getMatrix();

    $imageMargin = 20;

    $tileSize = 20;
    $tileSpace = 4;
    $shadowSigma = 4;
    $shadowDropX = 20;
    $shadowDropY = 0;

    $radius = ($tileSize / 2) * 0.9;

    $rows = count($matrix);
    $columns = count($matrix[0]);

    $imagickDraw = new \ImagickDraw();

    $imagickDraw->setFillColor('#afafaf');
    $imagickDraw->setStrokeColor('none');

    $imagickDraw->translate($imageMargin, $imageMargin);
    $imagickDraw->push();

    ksort($matrix);

    foreach ($matrix as $row) {
        ksort($row);
        $imagickDraw->push();
        foreach ($row as $cell) {
            if ($cell !== false) {
                $color = intval(255 * $cell);
                $colorString = sprintf("rgb(%f, %f, %f)", $color, $color, $color);
                $imagickDraw->setFillColor($colorString);
                $imagickDraw->rectangle(0, 0, $tileSize, $tileSize);
            }
            $imagickDraw->translate(($tileSize + $tileSpace), 0);
        }
        $imagickDraw->pop();
        $imagickDraw->translate(0, ($tileSize + $tileSpace));
    }

    $imagickDraw->pop();

    $width = ($columns * $tileSize) + (($columns - 1) * $tileSpace);
    $height = ($rows * $tileSize) + (($rows - 1) * $tileSpace);

    $imagickDraw->push();
    $imagickDraw->translate($width/2 , $height/2);
    $imagickDraw->setFillColor('rgba(0, 0, 0, 0)');
    $imagickDraw->setStrokeColor('white');
    $imagickDraw->circle(0, 0, $radius - 1, 0);
    $imagickDraw->setStrokeColor('black');
    $imagickDraw->circle(0, 0, $radius, 0);
    $imagickDraw->pop();

    $canvasWidth = $width + (2 * $imageMargin);
    $canvasHeight = $height + (2 * $imageMargin);

    $kernel = new \Imagick();
    $kernel->newPseudoImage(
        $canvasWidth,
        $canvasHeight,
        'canvas:none'
    );

    $kernel->setImageFormat('png');
    $kernel->drawImage($imagickDraw);

    /* create drop shadow on it's own layer */
    $canvas = $kernel->clone();
    $canvas->setImageBackgroundColor(new \ImagickPixel('rgb(0, 0, 0)'));
    $canvas->shadowImage(100, $shadowSigma, $shadowDropX, $shadowDropY);

    $canvas->setImagePage($canvasWidth, $canvasHeight, -5, -5);
    $canvas->cropImage($canvasWidth, $canvasHeight, 0, 0);

    /* composite original text_layer onto shadow_layer */
    $canvas->compositeImage($kernel, \Imagick::COMPOSITE_OVER, 0, 0);
    $canvas->setImageFormat('png');

    return $canvas;
}

function createFromBuiltin($kernelType, $kernelFirstTerm, $kernelSecondTerm, $kernelThirdTerm) {
    $string = '';

    if ($kernelFirstTerm != false && strlen(trim($kernelFirstTerm)) != 0) {
        $string .= $kernelFirstTerm;

        if ($kernelSecondTerm != false && strlen(trim($kernelSecondTerm)) != 0) {
            $string .= ','.$kernelSecondTerm;
            if ($kernelThirdTerm != false && strlen(trim($kernelThirdTerm)) != 0) {
                $string .= ','.$kernelThirdTerm;
            }
        }
    }

    $kernel = ImagickKernel::fromBuiltIn(
        $kernelType,
        $string
    );

    return $kernel;
}

function fromBuiltin($kernelType, $kernelFirstTerm, $kernelSecondTerm, $kernelThirdTerm) {
    $diamondKernel = createFromBuiltin($kernelType, $kernelFirstTerm, $kernelSecondTerm, $kernelThirdTerm);
    $imagick = renderKernel($diamondKernel);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

fromBuiltin(\Imagick::KERNEL_DIAMOND, 2, false, false);

?>
]]>
      </programlisting>
    </example>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
"""
Sqlalchemy models for magma result database
"""
import json
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Float
from sqlalchemy import Boolean
from sqlalchemy import ForeignKey
from sqlalchemy import TypeDecorator

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import relationship, backref
from sqlalchemy.schema import ForeignKeyConstraint
from sqlalchemy.sql import func

Base = declarative_base()

class ReactionSequence(TypeDecorator):
    """List of reactions.

    Reactions are grouped by relation to the current row or molecule:

    * products, reactions which have current row as reactant
    * reactants, reactions which have current row as product

    Reactions is a dict with key as the reaction name and
    the value a dict with keys:

    * nr, number of molecules which are product/reactant
        of current molecule with this reaction
    * nrp, number of molecules which are product/reactant
        of current molecule with this reaction and
        which have been matched to at least one scan

    Example:

    .. code-block:: javascript

          {
            'reactants': {
               'esterase': {'nr': 123, 'nrp': 45}
            },
            'products': {
               'sulfation': {'nr': 678, 'nrp': 90}
            }
          }

    Stored in database as json serialized string.
    """
    impl = String

    def process_bind_param(self, value, dialect):
        if value is not None:
            value = json.dumps(value)
        return value

    def process_result_value(self, value, dialect):
        if value is '':
            value = '{}'
        if value is not None:
            try:
                value = json.loads(value)
            except ValueError:
                value = {}
        return value

class Molecule(Base):
    """Molecule model for molecules table"""
    __tablename__ = 'molecules'
    # Id of a molecule
    molid = Column(Integer, primary_key=True, autoincrement=True)
    # molfile as string
    mol = Column(String)
    # A newline seperated list of reactions
    reactionsequence = Column(ReactionSequence, default={})
    # Inchikey first 14 chars
    inchikey14 = Column(String, unique=True)
    # Smile string
    smiles = Column(String)
    # Molecular formula
    formula = Column(String)
    # Whether molecule was given as query or is a result a of reaction
    predicted = Column(Boolean)
    # Name of molecule
    name = Column(String)
    # Number of lvl1 scans fragments are found for this molecule
    nhits = Column(Integer)
    # Monoisotopic mass
    mim = Column(Float)
    # Number of non-hydrogen atoms
    natoms = Column(Integer)
    # Calculated logP
    logp = Column(Float)
    refscore = Column(Float)
    reference = Column(String)
    # each molecule is fragmented into fragments
    fragments = relationship('Fragment', backref='molecule')

class Reaction(Base):
    """Reaction model for reactions table"""
    __tablename__ = 'reactions'
    # Id of a reaction
    reactid = Column(Integer, primary_key=True, autoincrement=True)
    reactant = Column(Integer, ForeignKey('molecules.molid'))
    product = Column(Integer, ForeignKey('molecules.molid'))
    name = Column(String)

def fill_molecules_reactions_reactants(session, reactions):
    qrnr = session.query(Reaction.product, Reaction.name, func.count('*'))
    qrnr = qrnr.group_by(Reaction.product, Reaction.name)
    for molid, rname, nr in qrnr:
        if molid not in reactions:
            reactions[molid] = {}
        if 'reactants' not in reactions[molid]:
            reactions[molid]['reactants'] = {}
        reactions[molid]['reactants'][rname] = {'nr': nr}

    qrnrp = session.query(Reaction.product, Reaction.name, func.count('*'))
    qrnrp = qrnrp.join(Molecule, Molecule.molid == Reaction.reactant)
    qrnrp = qrnrp.filter(Molecule.nhits > 0)
    qrnrp = qrnrp.group_by(Reaction.product, Reaction.name)
    for molid, rname, nrp in qrnrp:
        # dont need checks for keys because query above is always superset of
        # this query
        reactions[molid]['reactants'][rname]['nrp'] = nrp

def fill_molecules_reactions_products(session, reactions):
    qpnr = session.query(Reaction.reactant, Reaction.name, func.count('*'))
    qpnr = qpnr.group_by(Reaction.reactant, Reaction.name)
    for molid, rname, nr in qpnr:
        if molid not in reactions:
            reactions[molid] = {}
        if 'products' not in reactions[molid]:
            reactions[molid]['products'] = {}
        reactions[molid]['products'][rname] = {'nr': nr}

    qpnrp = session.query(Reaction.reactant, Reaction.name, func.count('*'))
    qpnrp = qpnrp.join(Molecule, Molecule.molid == Reaction.product)
    qpnrp = qpnrp.filter(Molecule.nhits > 0)
    qpnrp = qpnrp.group_by(Reaction.reactant, Reaction.name)
    for molid, rname, nrp in qpnrp:
        # dont need checks for keys because query above is always superset of
        # this query
        reactions[molid]['products'][rname]['nrp'] = nrp

def fill_molecules_reactions(session):
    """Fills the reactionsequence column in the molecules table with
    info from reactions table.

    The molecules query will become to complex when
    reactionsequence is queried from reactions table.
    So we fill reaction sequence with a json serialized struct
    which can be used during rendering.

    from magmaweb.job import JobFactory
    factory = JobFactory('data/jobs')
    session = factory._makeJobSession('58f05077-aad8-4fc9-a497-310495ab8b62')
    from magmaweb.models import fill_molecules_reactionsequence
    fill_molecules_reactionsequence(session)

    """

    reactions = {}
    fill_molecules_reactions_reactants(session, reactions)
    fill_molecules_reactions_products(session, reactions)

    for mol in session.query(Molecule):
        if mol.molid in reactions:
            reaction = reactions[mol.molid]
        else:
            reaction = {}
        mol.reactionsequence = reaction
    session.commit()

class Scan(Base):
    """Scan model for scans table"""
    __tablename__ = 'scans'
    # Id of a scan
    scanid = Column(Integer, primary_key=True)
    # Level of ms, starts with 1
    mslevel = Column(Integer)
    # Retention time on which scan was taken
    rt = Column(Float)
    #: Lowest m/z
    lowmz = Column(Float)
    #: Highest m/z
    highmz = Column(Float)
    #: M/z with highest intensity
    basepeakmz = Column(Float)
    #: Highest intensity
    basepeakintensity = Column(Float)
    totioncurrent = Column(Float)
    # m/z of precursor (which was fragmented resulting in this scan)
    precursormz = Column(Float)
    #: intensity belonging to precursormz
    precursorintensity = Column(Float)
    # Parent scan identifier
    precursorscanid = Column(Integer, ForeignKey('scans.scanid'))
    # Each scan has many peaks
    peaks = relationship('Peak', backref='scan')
    # A scan can have child product scans and a parent precursor scan
    products = relationship('Scan', backref=backref('precursor',
                                                    remote_side=[scanid]))
    # Fragments can be found on a scan
    fragments = relationship('Fragment', backref='scan')

class Peak(Base):
    """Peak model for peaks table"""
    __tablename__ = 'peaks'
    # Scan identifier to which peaks belongs
    scanid = Column(Integer, ForeignKey('scans.scanid'), primary_key=True)
    # m/z of peak (x-coordinate)
    mz = Column(Float, primary_key=True)
    # Intensity of peak (y-coordinate)
    intensity = Column(Float)
    # which molecule is assigned to this peak
    assigned_molid = Column(Integer, ForeignKey('molecules.molid'), index=True)

class Fragment(Base):
    """Fragment model for fragments table"""
    __tablename__ = 'fragments'
    # Fragment identifier
    fragid = Column(Integer, primary_key=True, autoincrement=True)
    # Molecule identifier
    molid = Column(Integer, ForeignKey('molecules.molid'), index=True)
    # Scan identifier
    scanid = Column(Integer, ForeignKey('scans.scanid'), index=True)
    # m/z of peak in scan
    mz = Column(Float)
    # Mass of fragment in Dalton, corrected with h delta
    mass = Column(Float)
    # Score of how good the molecule fragment matches the mass spectras
    score = Column(Float)
    # From which fragment this fragment is a fragment of
    parentfragid = Column(Integer, ForeignKey('fragments.fragid'))
    # Atom indices of molecule which are the fragment
    # is a comma seperated list, starting with 0
    atoms = Column(String)
    deltah = Column(Float)
    # (mz+deltah*1.007825032-mass)/(mz*1e6)  as deltappm
    deltappm = Column(Float)
    smiles = Column(String)
    # molecular formula of fragment
    formula = Column(String)
    # A fragment can have child fragments
    children_backref = backref('parent', remote_side=[fragid])
    children = relationship('Fragment', backref=children_backref,
                            lazy='joined', join_depth=1)
    __table_args__ = (ForeignKeyConstraint(['scanid', 'mz'],
                                           ['peaks.scanid', 'peaks.mz']
                                           ),
                      {}
                      )

class Run(Base):
    """Run model for run table"""
    __tablename__ = 'run'
    # Run identifier
    runid = Column(Integer, primary_key=True, autoincrement=True)
    # Description of the run
    description = Column(String)

    # ms data parsing parameters
    ms_filename = Column(String)
    # abs intensity threshold for storing peaks in database
    abs_peak_cutoff = Column(Float)
    # maximum ms level to be included in the analysis
    max_ms_level = Column(Integer)

    # parameters for matching molecules and fragments with peaks
    ionisation_mode = Column(Integer)
    skip_fragmentation = Column(Boolean)
    # max number of bonds broken in substructures generated from molecules
    max_broken_bonds = Column(Integer)
    # max number of additional neutral water losses
    max_water_losses = Column(Integer)
    # Absolute intensity minimum of lvl1 scan peaks
    # which are matched with molecules
    ms_intensity_cutoff = Column(Float)
    # Ratio of basepeak intensity
    msms_intensity_cutoff = Column(Float)
    # precision for matching a molecule mim to m/z of a peak (in ppm)
    mz_precision = Column(Float)
    # precision for matching a molecule mim to m/z of a peak (in Da)
    mz_precision_abs = Column(Float)
    # precision for matching precursor mz with peak mz in parent scan
    precursor_mz_precision = Column(Float)
    use_all_peaks = Column(Boolean)


text:
require 'aws-sdk'
require 's3_utils/path'
require 's3_utils/generator'
require 's3_utils/method'

module S3Utils
  include Method
end


text:
using System;
using System.IO;
using System.Threading.Tasks;
using Android.Content;
using File = System.IO.File;
using IOException = System.IO.IOException;
using Media.Plugin.Abstractions;

namespace Media.Plugin
{
    /// <summary>
    ///
    /// </summary>
    [Android.Runtime.Preserve(AllMembers = true)]
    public static class MediaFileExtensions
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="self"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static Task<MediaFile> GetMediaFileExtraAsync(this Intent self, Context context)
        {
            if (self == null)
                throw new ArgumentNullException("self");
            if (context == null)
                throw new ArgumentNullException("context");

            string action = self.GetStringExtra("action");
            if (action == null)
                throw new ArgumentException("Intent was not results from MediaPicker", "self");

            var uri = (Android.Net.Uri)self.GetParcelableExtra("MediaFile");
            bool isPhoto = self.GetBooleanExtra("isPhoto", false);
            var path = (Android.Net.Uri)self.GetParcelableExtra("path");

            return MediaPickerActivity.GetMediaFileAsync(context, 0, action, isPhoto, ref path, uri)
                .ContinueWith(t => t.Result.ToTask()).Unwrap();
        }
    }

}


text:
package com.example.office.ui;

import java.util.List;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.example.office.adapters.SearchableAdapter;
import com.example.office.logger.Logger;

/**
 * Inbox fragment containing logic related to managing inbox emails.
 */
public abstract class ListFragment<T, A extends SearchableAdapter<T>> extends BaseFragment {

    /**
     * Adapter for ListView containing items
     */
    protected A mAdapter;

    /**
     * Constructor.
     */
    public ListFragment() {}

    /**
     * Retrieves the list of items to display in the list.
     *
     * @return List of items to display in the list.
     */
    protected abstract List<T> getListData();

    /**
     * Sets up the list. Supposed to init List UI if necessary and fill it with data so it can be displayed.
     */
    protected abstract void initList();

    /**
     * Resource id of the layout used to draw a list item.
     *
     * @return Resource id.
     */
    protected abstract int getListItemLayoutId();

    /**
     * Resource id of the a List view in the layout.
     *
     * @return Resource id.
     */
    protected abstract int getListViewId();

    /**
     * Resource id of the an infinite progress bar that will be shown instead of list.
     *
     * @return Resource id.
     */
    protected abstract int getProgressViewId();

    /**
     * Resource id of the container holding all the view elements of the fragment except for progress bar.
     *
     * @return Resource id.
     */
    protected abstract int getContentContainerId();

    @Override
    protected abstract int getFragmentLayoutId();

    /**
     * Gets/creates singleton adapter used to back the list. If there is none - creates one and instantiates dedicated class field. Should be overridden. Returns instance of {@link ArrayAdapter} by
     * default. Data from {@link #getListData()} is used.
     *
     * @return List adapter, or null in case of error.
     */
    protected A getListAdapterInstance() {
        try {
            return getListAdapterInstance(null);
        } catch (Exception e) {
            Logger.logApplicationException(e, getClass().getSimpleName() + ".getListAdapter(): Error.");
        }
        return null;
    }

    /**
     * Gets/creates singleton adapter used to back the list. If there is none - creates one and instantiates dedicated calss field. Should be overridden. Returns instance of {@link ArrayAdapter} by
     * default. Data from {@link #getListData()} is used if if supplied data is null.
     *
     * @param data Data to back the adapter.
     *
     * @return List adapter, or null in case of error.
     */
    protected abstract A getListAdapterInstance(List<T> data);

    /**
     * Gets/creates singleton view to add as a footer to the list. If there is none - creates one and instantiates dedicated class field.
     *
     * @return Footer view, or null in case of error.
     */
    protected abstract View getListFooterViewInstance();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);

        try {
            // Setting up adapter
            BaseAdapter adapter = getListAdapterInstance();
            final ListView listView = (ListView) rootView.findViewById(getListViewId());
            listView.setAdapter(adapter);

            // Adding footer if any.
            View view = getListFooterViewInstance();
            if (view != null) {
                listView.addFooterView(view);
            }
        } catch (Exception e) {
            Logger.logApplicationException(e, getClass().getSimpleName() + ".onCreateView(): Error.");
        }

        return rootView;
    }

    /**
     * Called by parent activity to propagate coressponding event. Perfroms filtering based on the adapter
     * implementation returned by {@link #getListAdapterInstance()}.
     *
     * @param query Filter query.
     *
     * @return false.
     */
    public boolean onQueryTextChange(String query) {
        try {
            SearchableAdapter<T> adapter = (SearchableAdapter<T>) getListAdapterInstance();
            if (adapter != null && adapter.getFilter() != null) {
                adapter.getFilter().filter(query);
            }
        } catch (Exception e) {
            Logger.logApplicationException(e, getClass().getSimpleName() + "onQueryTextSubmit(): Error.");
        }
        return false;
    }

    /**
     * Toggles between showing either progress indicator or a content pane with actual data.
     *
     * @param isWorkInProgress Progress status.
     * @param showContentProgress Defines if progress bar should be displayed on the content pane of the fragment.
     */
    protected void showWorkInProgress(boolean isWorkInProgress, boolean showContentProgress) {
        try {
            View rootView = getView();
            if ((showContentProgress || !isWorkInProgress) && rootView != null) {
                View progressIndicator = rootView.findViewById(getProgressViewId());
                View contentPane = rootView.findViewById(getListViewId());
                progressIndicator.setVisibility(isWorkInProgress ? View.VISIBLE : View.GONE);
                contentPane.setVisibility(isWorkInProgress ? View.GONE : View.VISIBLE);
            }

            // Separate progress indicator in ActionBar.
            getActivity().setProgressBarIndeterminateVisibility(isWorkInProgress);
        } catch (Exception e) {
            Logger.logApplicationException(e, getClass().getSimpleName() + ".showWorkInProgress(): Error.");
        }
    }

}


text:
class CreateTags < ActiveRecord::Migration
  def up
    PgTools.with_schemas except: 'common' do
      create_table :tags do |t|
        t.string :name
        t.string :bgcolor, limit: 10

        t.timestamps
      end

      add_index :tags, :name
    end
  end
end


text:
namespace CallButler.Manager.Controls
{
    partial class VoicemailDiagramShape
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.roundedCornerPanel1 = new global::Controls.RoundedCornerPanel();
            this.lblNumber = new global::Controls.SmoothLabel();
            this.pbIcon = new System.Windows.Forms.PictureBox();
            this.roundedCornerPanel1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pbIcon)).BeginInit();
            this.SuspendLayout();
            //
            // roundedCornerPanel1
            //
            this.roundedCornerPanel1.BorderSize = 1F;
            this.roundedCornerPanel1.Controls.Add(this.lblNumber);
            this.roundedCornerPanel1.Controls.Add(this.pbIcon);
            this.roundedCornerPanel1.CornerRadius = 10;
            this.roundedCornerPanel1.DisplayShadow = true;
            this.roundedCornerPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.roundedCornerPanel1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.roundedCornerPanel1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
            this.roundedCornerPanel1.Location = new System.Drawing.Point(0, 0);
            this.roundedCornerPanel1.Name = "roundedCornerPanel1";
            this.roundedCornerPanel1.Padding = new System.Windows.Forms.Padding(5, 5, 6, 6);
            this.roundedCornerPanel1.PanelColor = System.Drawing.Color.White;
            this.roundedCornerPanel1.ShadowColor = System.Drawing.Color.LightGray;
            this.roundedCornerPanel1.ShadowOffset = 3;
            this.roundedCornerPanel1.Size = new System.Drawing.Size(407, 54);
            this.roundedCornerPanel1.TabIndex = 3;
            this.roundedCornerPanel1.Text = "roundedCornerPanel1";
            //
            // lblNumber
            //
            this.lblNumber.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.lblNumber.BackColor = System.Drawing.Color.Transparent;
            this.lblNumber.Cursor = System.Windows.Forms.Cursors.Hand;
            this.lblNumber.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblNumber.ForeColor = System.Drawing.Color.DodgerBlue;
            this.lblNumber.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            this.lblNumber.Location = new System.Drawing.Point(43, 14);
            this.lblNumber.Name = "lblNumber";
            this.lblNumber.Size = new System.Drawing.Size(184, 24);
            this.lblNumber.TabIndex = 25;
            this.lblNumber.Text = "Take a voicemail";
            this.lblNumber.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // pbIcon
            //
            this.pbIcon.BackColor = System.Drawing.Color.Transparent;
            this.pbIcon.Image = global::CallButler.Manager.Controls.Properties.Resources.call_greeting_24;
            this.pbIcon.Location = new System.Drawing.Point(13, 14);
            this.pbIcon.Name = "pbIcon";
            this.pbIcon.Size = new System.Drawing.Size(24, 24);
            this.pbIcon.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pbIcon.TabIndex = 1;
            this.pbIcon.TabStop = false;
            //
            // VoicemailDiagramShape
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.roundedCornerPanel1);
            this.Name = "VoicemailDiagramShape";
            this.Size = new System.Drawing.Size(407, 54);
            this.roundedCornerPanel1.ResumeLayout(false);
            this.roundedCornerPanel1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pbIcon)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private global::Controls.RoundedCornerPanel roundedCornerPanel1;
        private global::Controls.SmoothLabel lblNumber;
        private System.Windows.Forms.PictureBox pbIcon;
    }
}


text:
 <#
 * Copyright Microsoft Corporation
 *
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
#>

[CmdletBinding()]
param(
   [parameter(Mandatory=$true)][string]$vmName,
   [parameter(Mandatory=$true)][string]$serviceName,
   [parameter(Mandatory=$true)][string]$domainAdminUsername,
   [parameter(Mandatory=$true)][string]$domainAdminPassword,
   [parameter(Mandatory=$true)][string]$spFarmUsername,
   [parameter(Mandatory=$false)][string]$ScriptFolder = (get-location).Path
)

Import-Module $scriptFolder\SharedComponents\SharedFunctions.psm1 -AsCustomObject -Force -DisableNameChecking -Verbose:$false -ErrorAction Stop

#Get the hosted service WinRM Uri
[System.Uri]$uris = (Get-VMConnection -ServiceName $serviceName -vmName $vmName)
if ($uris -eq $null){return}

$Credential = (Set-Credential -Username $domainAdminUsername -Password $domainAdminPassword)

Write-Host "Starting remote session" -NoNewline
Invoke-Command -ConnectionUri $uris.ToString() -Credential $Credential  `
	-ArgumentList $spFarmUsername `
   -ScriptBlock {
		param($spFarmUsername )

#Region Local Function(s) within the Invoke block

#EndRegion

   Write-Host -ForegroundColor Green "... Started"
   $timeout = New-Object System.TimeSpan -ArgumentList 0, 0, $timeoutsec
   Set-ExecutionPolicy Unrestricted

   #Hide green status bar
   $ProgressPreference = "SilentlyContinue"

   Write-Host "Loading SQLPS module..." -NoNewline
   Import-Module sqlps -OutVariable $Result -WarningAction SilentlyContinue
	Write-Host -ForegroundColor Green "... Complete"

   Write-Host "Adding $($spFarmUsername) to dbcreator/securityadmin roles..." -NoNewline
   Invoke-Sqlcmd -ServerInstance $env:COMPUTERNAME -Database master -Query `
   "
      USE [master]
      IF Not EXISTS (SELECT name FROM master.sys.server_principals WHERE name = '$spFarmUsername')
      BEGIN
      CREATE LOGIN [$spFarmUsername] FROM WINDOWS
         EXEC sp_addsrvrolemember '$spFarmUsername', 'dbcreator'
         EXEC sp_addsrvrolemember '$spFarmUsername', 'securityadmin'
      END
   "
	Write-Host -ForegroundColor Green "... Complete"

	Write-Host "Configuring database options..." -NoNewline
   Invoke-Sqlcmd -ServerInstance $env:COMPUTERNAME -database master -Query `
	"
      USE [master]
		GO
		sp_configure 'show advanced options', 1;RECONFIGURE WITH OVERRIDE;
		GO
		sp_configure 'max degree of parallelism', 1;RECONFIGURE WITH OVERRIDE;
		GO
   "
	Write-Host -ForegroundColor Green "... Complete"

   Write-Host "Restartig MSSQLSERVER service" -NoNewline
	Restart-Service -Name MSSQLSERVER -Force -WarningAction SilentlyContinue
	Write-Host -ForegroundColor Green "... Complete"

}


text:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using JetBat.Client.Metadata.Simple;

namespace JetBat.Silverlight.UI.AttributeEditiors
{
	public static class ObjectAttributeEditorFactory
	{
		public static FrameworkElement CreateAttributeEditor(ObjectAttribute attribute)
		{
			if (Type.GetType(attribute.DataType) == typeof(string))
			{
				return new TextAttributeEditor(attribute)
				{
					Value = null,
					HorizontalContentAlignment = HorizontalAlignment.Stretch
				};
			}
			if (Type.GetType(attribute.DataType) == typeof(Int32))
			{
				return new Int32AttributeEditor(attribute)
				{
					Value = null,
					HorizontalContentAlignment = HorizontalAlignment.Stretch
				};
			}
			if (Type.GetType(attribute.DataType) == typeof(DateTime))
			{
				return new DateTimeAttributeEditor(attribute)
				{
					Value = null,
					HorizontalContentAlignment = HorizontalAlignment.Stretch
				};
			}
			if (Type.GetType(attribute.DataType) == typeof(decimal))
			{
				return new DecimalAttributeEditor(attribute)
				{
					Value = null,
					HorizontalContentAlignment = HorizontalAlignment.Stretch
				};
			}
			if (Type.GetType(attribute.DataType) == typeof(bool))
			{
				return new BooleanAttributeEditor(attribute)
				{
					Value = null,
					HorizontalContentAlignment = HorizontalAlignment.Stretch
				};
			}

			TextBlock textBlock = new TextBlock();
			textBlock.Text = "Unsupported data type " + attribute.DataType;
			return textBlock;
		}

		public static FrameworkElement CreateComplexAttributeEditor(string objectNamespace, string objectName, ObjectComplexAttribute complexAttribute, GetPlainObjectListQualifiedNamespaceDelegate getPlainObjectListQualifiedNamespace)
		{
			string plainObjectListNamespace;
			string plainObjectListName;
			string displayMemberPath;
			Dictionary<string, string> migratedAttributes;
			getPlainObjectListQualifiedNamespace(objectNamespace, objectName, complexAttribute.Name, out plainObjectListNamespace, out plainObjectListName, out displayMemberPath, out migratedAttributes);
			return new ComplexAttributeComboBox(complexAttribute, plainObjectListNamespace, plainObjectListName, displayMemberPath, migratedAttributes) { HorizontalContentAlignment = HorizontalAlignment.Stretch };
		}

		public static IComplexAttributeEditor CreateComplexAttributeEditorDocumentListComboBox(string objectNamespace, string objectName, ObjectComplexAttribute complexAttribute, GetDocumentListQualifiedNamespaceDelegate getDocumentListQualifiedNamespace)
		{
			string documentListNamespace;
			string documentListName;
			string displayMemberPath;
			Dictionary<string, string> migratedAttributes;
			getDocumentListQualifiedNamespace(objectNamespace, objectName, complexAttribute.Name, out documentListNamespace, out documentListName, out displayMemberPath, out migratedAttributes);
			return new ComplexAttributeComboBoxDocumentListView(complexAttribute, documentListNamespace, documentListName, displayMemberPath, migratedAttributes) { HorizontalContentAlignment = HorizontalAlignment.Stretch };
		}
	}
}