text:
package city.transportation;

import gui.WorldViewBuilding;

import java.util.ArrayList;
import java.util.List;

import city.Place;
import city.transportation.interfaces.Commuter;

public class BusStopObject extends Place {
	List<Commuter> _waitList = new ArrayList<Commuter>();
	List<Commuter> _suicideList = new ArrayList<Commuter>();
	List<Commuter> _carCrashList = new ArrayList<Commuter>();

	public BusStopObject(String name, WorldViewBuilding worldViewBuilding) {
		super(name, worldViewBuilding);
		// TODO Auto-generated constructor stub
	}

	public synchronized void addCommuterRole(Commuter person){
		System.out.println("Added person to waitlist");
		_waitList.add(person);
	}

	public synchronized int addMyselfToDeathList(Commuter person){
		System.out.println("Someone want to commit suicide pretty soon " + _suicideList.size());
		_suicideList.add(person);
		return _suicideList.size();
	}

	public synchronized int addMyselfToCrashList(Commuter person){
		System.out.println("Someone want to hit bus pretty soon " + _carCrashList.size());
		_carCrashList.add(person);
		return _carCrashList.size();
	}

	public synchronized void removeCommuterRole(Commuter person){
		_waitList.remove(person);
	}

	public synchronized void removeDeadPeople(Commuter person){
		_suicideList.remove(person);
	}

	public List<Commuter> getList(){
		return _waitList;
	}

	public List<Commuter> getSuicideList(){
		return _suicideList;
	}

	public List<Commuter> getCarCrashList(){
		return _carCrashList;
	}
}


text:
@interface LPYNumberPad() <UIInputViewAudioFeedback>
{
    BOOL _clearButtonLongPressGesture;

    struct {
        unsigned int textInputSupportsShouldChangeTextInRange:1;
        unsigned int delegateSupportsTextFieldShouldChangeCharactersInRange:1;
        unsigned int delegateSupportsTextViewShouldChangeTextInRange:1;
    } _delegateFlags;
}

// 所有数字按钮
@property (nonatomic, copy) NSArray *numberButtons;
// 左边按钮
@property (nonatomic, strong) LPYNumberButton *leftButton;
// delegate
@property (nonatomic, weak) id<LPYNumberPadDelegate> delegate;
// 自动检测文本输入
@property (nonatomic, weak) UIResponder<UITextInput> *textInput;
// 键盘样式
@property (nonatomic, strong) Class<LPYNumberPadStyle> styleClass;
// 记录上一次触摸
@property (nonatomic, strong) UITouch *lastTouch;
@end

@implementation LPYNumberPad

+ (instancetype)numberPadWithDelegate:(id<LPYNumberPadDelegate>)delegate {
    return [self numberPadWithDelegate:delegate numberPadStyleClass:nil];
}

+ (instancetype)numberPadWithDelegate:(id<LPYNumberPadDelegate>)delegate numberPadStyleClass:(Class<LPYNumberPadStyle>)styleClass {
    return [[self alloc] initWithDelegate:delegate numberPadStyleClass:styleClass];
}

- (instancetype)initWithDelegate:(id<LPYNumberPadDelegate>)delegate numberPadStyleClass:(Class<LPYNumberPadStyle>)styleClass {
    self = [super initWithFrame:CGRectZero];
    if (self) {
        self.styleClass = styleClass;
        self.frame = [self.styleClass numberPadFrame];
        self.autoresizingMask = UIViewAutoresizingFlexibleHeight; // 支持旋转
        self.backgroundColor = [self.styleClass numberPadBackgroundColor];
        [self addNotificationsObservers];

        self.delegate = delegate;

        NSMutableArray *numbersButtons = [NSMutableArray array];
        for (int i = 0; i < 11; i++) {
            LPYNumberButton *numberButton = [self numberButton:i];
            [self addSubview:numberButton];
            [numbersButtons addObject:numberButton];
        }
        self.numberButtons = numbersButtons;

        // leftButton
        self.leftButton = [self functionButton];
        self.leftButton.titleLabel.font = [self.styleClass functionButtonFont];
        [self.leftButton setTitleColor:[self.styleClass functionButtonTextColor] forState:UIControlStateNormal];
        [self.leftButton addTarget:self action:@selector(btn_LeftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        self.leftButton.userInteractionEnabled = NO;
        [self addSubview:self.leftButton];

        // clearButton
        self.clearButton = [self functionButton];
        [self.clearButton setImage:[self.styleClass clearFunctionButtonImage] forState:UIControlStateNormal];
        [self.clearButton addTarget:self action:@selector(btn_ClearClick) forControlEvents:UIControlEventTouchUpInside];

        UILongPressGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureRecognizerAction:)];
        longPressGestureRecognizer.cancelsTouchesInView = NO;
        [self.clearButton addGestureRecognizer:longPressGestureRecognizer];
        [self addSubview:self.clearButton];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    int rows = 4;
    int sections = 3;
    CGFloat sep = [self.styleClass separator];
    CGFloat left = 0.0f;
    CGFloat top = 0.0f;
#if defined(__LP64__) && __LP64__
    CGFloat buttonHeight = trunc((CGRectGetHeight(self.bounds) - sep * (rows - 1)) / rows) + sep;
#else
    CGFloat buttonHeight = truncf((CGRectGetHeight(self.bounds) - sep * (rows - 1)) / rows) + sep;
#endif
    CGSize buttonSize = CGSizeMake((CGRectGetWidth(self.bounds) - sep * (sections - 1)) / sections, buttonHeight);

    // 1-9
    for (int i = 1; i < self.numberButtons.count - 1; i++) {
        LPYNumberButton *numberButton = self.numberButtons[i];
        numberButton.frame = CGRectMake(left, top, buttonSize.width, buttonSize.height);

        if (i % sections == 0) {
            left = 0.0f;
            top += buttonSize.height + sep;
        } else {
            left += buttonSize.width + sep;
        }
    }

    // leftButton
    left = 0.0f;
    self.leftButton.frame = CGRectMake(left, top, buttonSize.width, buttonSize.height);

    // 0
    left += buttonSize.width + sep;
    UIButton *zeroButton = [self.numberButtons firstObject];
    zeroButton.frame = CGRectMake(left, top, buttonSize.width, buttonSize.height);

    // clearButton
    left += buttonSize.width + sep;
    self.clearButton.frame = CGRectMake(left, top, buttonSize.width, buttonSize.height);
}

#pragma mark leftButton
- (void)btn_LeftButtonClick:(id)sender {
    if (!self.textInput) {
        return;
    }

    if ([self.delegate respondsToSelector:@selector(numberPad:functionButtonAction:textInput:)]) {
        [self.delegate numberPad:self functionButtonAction:sender textInput:self.textInput];
    }
}

#pragma mark - UIInputViewAudioFeedback
- (BOOL)enableInputClicksWhenVisible {
    return YES;
}

#pragma mark - clearButton
- (void)longPressGestureRecognizerAction:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        _clearButtonLongPressGesture = YES;
        [self clearButtonActionLongPress];
    } else if (longPress.state == UIGestureRecognizerStateEnded) {
        _clearButtonLongPressGesture = NO;
    }
}

- (void)clearButtonActionLongPress {
    if (_clearButtonLongPressGesture) {
        if ([self.textInput hasText]) {
            [[UIDevice currentDevice] playInputClick];

            [self btn_ClearClick];
            // delay like in iOS keyboard
            [self performSelector:@selector(clearButtonActionLongPress) withObject:nil afterDelay:0.1f];
        } else {
            _clearButtonLongPressGesture = NO;
        }
    }
}

- (void)btn_ClearClick {
    if (!self.textInput) {
        return;
    }

    if (_delegateFlags.textInputSupportsShouldChangeTextInRange) {
        UITextRange *textRange = self.textInput.selectedTextRange;

        if ([textRange.start isEqual:textRange.end]) {
            UITextPosition *newStart = [self.textInput positionFromPosition:textRange.start inDirection:UITextLayoutDirectionLeft offset:1];
            textRange = [self.textInput textRangeFromPosition:newStart toPosition:textRange.end];
        }

        if ([self.textInput shouldChangeTextInRange:textRange replacementText:@""]) {
            [self.textInput deleteBackward];
        }
    } else if (_delegateFlags.delegateSupportsTextFieldShouldChangeCharactersInRange) {
        NSRange selectedRange = [[self class] selectedRange:self.textInput];
        if (selectedRange.length == 0 && selectedRange.location > 0) {
            selectedRange.location--;
            selectedRange.length = 1;
        }

        UITextField *textField = (UITextField *)self.textInput;
        if ([textField.delegate textField:textField shouldChangeCharactersInRange:selectedRange replacementString:@""]) {
            [self.textInput deleteBackward];
        }
    } else if (_delegateFlags.delegateSupportsTextViewShouldChangeTextInRange) {
        NSRange selectedRange = [[self class] selectedRange:self.textInput];
        if (selectedRange.length == 0 && selectedRange.location > 0) {
            selectedRange.location--;
            selectedRange.length = 2;
        }

        UITextView *textView = (UITextView *)self.textInput;
        if ([textView.delegate textView:textView shouldChangeTextInRange:selectedRange replacementText:@""]) {
            [self.textInput deleteBackward];
        }
    } else {
        [self.textInput deleteBackward];
    }
}

#pragma mark - UIResponder
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [[UIDevice currentDevice] playInputClick];

    if (self.lastTouch) {
        [self performLastTouchAction];
    }

    // 禁止多点触碰
    self.lastTouch = [touches anyObject];

    CGPoint location = [self.lastTouch locationInView:self];
    for (LPYNumberButton *btn in self.numberButtons) {
        if (CGRectContainsPoint(btn.frame, location)) {
            btn.highlighted = YES;
        } else {
            btn.highlighted = NO;
            [btn lpy_touchesCancelled:touches withEvent:event];
        }
    }
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (!self.lastTouch || ![touches containsObject:self.lastTouch]) {
        return;
    }

    CGPoint location = [self.lastTouch locationInView:self];

    if (!CGRectContainsPoint(self.clearButton.frame, location)) {
        LPYNumberButton *clearButton = (id)self.clearButton;
        [clearButton lpy_touchesCancelled:touches withEvent:event];

        // 禁止清除按钮长按操作
        _clearButtonLongPressGesture = NO;
    }

    if (!CGRectContainsPoint(self.leftButton.frame, location)) {
        [self.leftButton lpy_touchesCancelled:touches withEvent:event];
    }

    for (LPYNumberButton *btn in self.numberButtons) {
        btn.highlighted = CGRectContainsPoint(btn.frame, location);
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (!self.lastTouch || ![touches containsObject:self.lastTouch]) {
        return;
    }

    [self performLastTouchAction];

    self.lastTouch = nil;
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.leftButton.highlighted = NO;
    self.clearButton.highlighted = NO;

    for (LPYNumberButton *btn in self.numberButtons) {
        btn.highlighted = NO;
    }

    self.lastTouch = nil;
}

- (void)performLastTouchAction {
    CGPoint location = [self.lastTouch locationInView:self];

    for (LPYNumberButton *btn in self.numberButtons) {
        btn.highlighted = NO;
        if (CGRectContainsPoint(btn.frame, location)) {
            [self btn_NumberButtonClick:btn];
        }
    }
}

- (void)btn_NumberButtonClick:(UIButton *)sender {
    if (!self.textInput) {
        return;
    }

    NSString *text = sender.currentTitle;

    if (_delegateFlags.textInputSupportsShouldChangeTextInRange) {
        if ([self.textInput shouldChangeTextInRange:self.textInput.selectedTextRange replacementText:text]) {
            [self.textInput insertText:text];
        }
    } else if (_delegateFlags.delegateSupportsTextFieldShouldChangeCharactersInRange) {
        NSRange selectedRange = [[self class] selectedRange:self.textInput];
        UITextField *textField = (UITextField *)self.textInput;
        if ([textField.delegate textField:textField shouldChangeCharactersInRange:selectedRange replacementString:text]) {
            [self.textInput insertText:text];
        }
    } else if (_delegateFlags.delegateSupportsTextViewShouldChangeTextInRange) {
        NSRange selectedRange = [[self class] selectedRange:self.textInput];
        UITextView *textView = (UITextView *)self.textInput;
        if ([textView.delegate textView:textView shouldChangeTextInRange:selectedRange replacementText:text]) {
            [self.textInput insertText:text];
        }
    } else {
        [self.textInput insertText:text];
    }
}

+ (NSRange)selectedRange:(id<UITextInput>)textInput {
    UITextRange *textRange = [textInput selectedTextRange];

    NSInteger startOffset = [textInput offsetFromPosition:textInput.beginningOfDocument toPosition:textRange.start];
    NSInteger endOffset = [textInput offsetFromPosition:textInput.beginningOfDocument toPosition:textRange.end];

    return NSMakeRange(startOffset, endOffset - startOffset);
}

#pragma mark - 数字按钮
- (LPYNumberButton *)numberButton:(int)number {
    LPYNumberButton *btn = [LPYNumberButton buttonWithBackgroundColor:[self.styleClass numberButtonBackgroundColor] highlightedColor:[self.styleClass numberButtonHighlightedColor]];
    [btn setTitleColor:[self.styleClass numberButtonTextColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [self.styleClass numberButtonFont];
    [btn setTitle:[NSString stringWithFormat:@"%d", number] forState:UIControlStateNormal];
    return btn;
}

- (LPYNumberButton *)functionButton {
    LPYNumberButton *btn = [LPYNumberButton buttonWithBackgroundColor:[self.styleClass functionButtonBackgroundColor] highlightedColor:[self.styleClass functionButtonHighlightedColor]];
    btn.exclusiveTouch = YES;
    return btn;
}

#pragma mark - 通知
- (void)addNotificationsObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidBeginEditing:) name:UITextViewTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidEndEditing:) name:UITextFieldTextDidEndEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidEndEditing:) name:UITextViewTextDidEndEditingNotification object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)textDidBeginEditing:(NSNotification *)notification {
    if (![notification.object conformsToProtocol:@protocol(UITextInput)]) {
        return;
    }

    UIResponder<UITextInput> *textInput = notification.object;

    if (textInput.inputView && self == textInput.inputView) {
        self.textInput = textInput;

        _delegateFlags.textInputSupportsShouldChangeTextInRange = NO;
        _delegateFlags.delegateSupportsTextFieldShouldChangeCharactersInRange = NO;
        _delegateFlags.delegateSupportsTextViewShouldChangeTextInRange = NO;

        if ([self.textInput respondsToSelector:@selector(shouldChangeTextInRange:replacementText:)]) {
            _delegateFlags.textInputSupportsShouldChangeTextInRange = YES;
        } else if ([self.textInput isKindOfClass:[UITextField class]]) {
            id<UITextFieldDelegate> delegate = [(UITextField *)self.textInput delegate];

            if ([delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
                _delegateFlags.delegateSupportsTextFieldShouldChangeCharactersInRange = YES;
            }
        } else if ([self.textInput isKindOfClass:[UITextView class]]) {
            id<UITextViewDelegate> delegate = [(UITextView *)self.textInput delegate];

            if ([delegate respondsToSelector:@selector(textView:shouldChangeTextInRange:replacementText:)]) {
                _delegateFlags.delegateSupportsTextViewShouldChangeTextInRange = YES;
            }
        }
    }
}

- (void)textDidEndEditing:(NSNotification *)notification {
    self.textInput = nil;
}

#pragma mark - 默认赋值
- (void)setStyleClass:(Class<LPYNumberPadStyle>)styleClass {
    if (styleClass) {
        _styleClass = styleClass;
    } else {
        _styleClass = [LPYNumberPadDefaultStyle class];
    }
}

- (UIButton *)leftFunctionButton {
    return self.leftButton;
}
@end

redpajama_set_name: RedPajamaGithub


text:
from kqml import KQMLModule

def test_init():
    """Tests whether KQMLModule can be initialized."""
    KQMLModule(testing=True, name='testmodule')


text:
package org.apache.calcite.config;

import org.apache.calcite.avatica.util.Casing;
import org.apache.calcite.avatica.util.Quoting;

/** Named, built-in lexical policy. A lexical policy describes how
 * identifiers are quoted, whether they are converted to upper- or
 * lower-case when they are read, and whether they are matched
 * case-sensitively. */
public enum Lex {
  /** Lexical policy similar to Oracle. The case of identifiers enclosed in
   * double-quotes is preserved; unquoted identifiers are converted to
   * upper-case; after which, identifiers are matched case-sensitively. */
  ORACLE(Quoting.DOUBLE_QUOTE, Casing.TO_UPPER, Casing.UNCHANGED, true),

  /** Lexical policy similar to MySQL. (To be precise: MySQL on Windows;
   * MySQL on Linux uses case-sensitive matching, like the Linux file system.)
   * The case of identifiers is preserved whether or not they quoted;
   * after which, identifiers are matched case-insensitively.
   * Back-ticks allow identifiers to contain non-alphanumeric characters. */
  MYSQL(Quoting.BACK_TICK, Casing.UNCHANGED, Casing.UNCHANGED, false),

  /** Lexical policy similar to Microsoft SQL Server.
   * The case of identifiers is preserved whether or not they are quoted;
   * after which, identifiers are matched case-insensitively.
   * Brackets allow identifiers to contain non-alphanumeric characters. */
  SQL_SERVER(Quoting.BRACKET, Casing.UNCHANGED, Casing.UNCHANGED, false),

  /** Lexical policy similar to Java.
   * The case of identifiers is preserved whether or not they are quoted;
   * after which, identifiers are matched case-sensitively.
   * Unlike Java, back-ticks allow identifiers to contain non-alphanumeric
   * characters. */
  JAVA(Quoting.BACK_TICK, Casing.UNCHANGED, Casing.UNCHANGED, true);

  public final Quoting quoting;
  public final Casing unquotedCasing;
  public final Casing quotedCasing;
  public final boolean caseSensitive;

  Lex(Quoting quoting,
      Casing unquotedCasing,
      Casing quotedCasing,
      boolean caseSensitive) {
    this.quoting = quoting;
    this.unquotedCasing = unquotedCasing;
    this.quotedCasing = quotedCasing;
    this.caseSensitive = caseSensitive;
  }
}

// End Lex.java


text:
package jmud.command;

import jmud.Player;
import jmud.PlayerChannel;
import jmud.Room;
import jmud.item.Item;

/**
 * Executable command Look
 *
 * @author Chris maguire
 * @version 0.1
 */

/*
 * Class: Look
 * Purpose: Extends the Command class to provide
 *          the functionality for a player to look
 *          at something
 */
public class Get extends Command {

    private PlayerChannel playerChannel;
    private Player player;
    private Room room;
    private String strTarget;

    /**
     * Construct a Get command
     *
     * @param pc     The PlayerChannel to send the results too
     * @param r      The current room
     * @param target target to look at, if null or empty string, looks at current room
     */
    public Get(PlayerChannel pc, Room r, String target) {
        this.playerChannel = pc;
        this.player = pc.getPlayer();
        this.room = r;
        this.strTarget = target.trim();
    }

    /**
     * The logic that this command encapsulates
     * <p/>
     * If the item exists, get it.
     */
    public boolean exec() {
        StringBuilder strbMessage = new StringBuilder();
        Item item;

        // DEBUG: has the command been called
        //System.out.println("Get.exec() called");

        // check if there is an item or not
        if(strTarget == null || strTarget.length() == 0) {
            strbMessage.append("You must specify an item to get")
                .append(CRLF);
            // check if the player has a free hand
        } else if(!player.hasFreeGrabber()) {
            strbMessage.append("You need a free hand to grab that.")
                .append(CRLF);
            // make sure the item is in the room
        } else if(room.getItem(strTarget) == null || (item = room.remove(room.getItem(strTarget))) == null) {
            strbMessage.append("You don't see a ")
                .append(strTarget)
                .append(CRLF);
            // nothing failed, we got the item
        } else {
            player.grab(item);
            strbMessage.append("You get the ")
                .append(item.getName())
                .append(CRLF);
        }

        // tack on the player's prompt even though the engine is supposed to handle the
        // prompt.
        strbMessage.append(player.getPrompt());

        // now send back what we found to the player
        try {
            playerChannel.sendMessage(strbMessage.toString());
        } catch(Exception e) {
            System.out.println("Couldn't print room desc and exits to " + player.getName());
        }

        return true;
    }

}


text:
enum SHADER_TYPE { V_F, V_G_F, V_G_T_F };

class ShaderProgram {
public:
  ShaderProgram();
  ~ShaderProgram();
  static ShaderProgram *Load(const std::string &name);
  GLuint program;

protected:
};


text:
/**
 * @class baqend.binding.ManagedFactory
 */
var ManagedFactory = {};
Object.defineProperty(ManagedFactory, 'methods', {
  /**
   * Methods that are added to object instances
   * This property is an alias for this factories type prototype
   * @type object
   */
  get: function() {
    return this.prototype;
  }
});

Object.extend(ManagedFactory, /** @lends baqend.binding.ManagedFactory */ {
  /**
   * Creates a new ManagedFactory for the given type
   * @param {baqend.metamodel.ManagedType} managedType The metadata of type T
   * @param {baqend.EntityManager} db
   * @return {baqend.binding.ManagedFactory} A new object factory to created instances of T
   */
  create: function(managedType, db) {
    var self = this;
    var factory = function Factory() {
      return factory.newInstance.apply(factory, arguments);
    };

    Object.cloneOwnProperties(factory, self);

    //lets instanceof work properly
    factory.prototype = managedType.typeConstructor.prototype;
    factory._managedType = managedType;
    factory._db = db;

    return factory;
  },

  /**
   * Creates a new instance of the factory type
   * @param {Object<*>} properties A hash of initial properties
   * @param {...*} arguments Constructor arguments used for instantiation
   * @return {baqend.binding.Managed} A new created instance of T
   */
  newInstance: function(properties) {
    var typeInstance = this._managedType.create();
    this.prototype.constructor.apply(typeInstance, arguments);
    typeInstance._metadata.db = this._db;
    return typeInstance;
  },

  /**
   * Adds methods to instances of this factories type
   * @param {object} methods The methods to add
   */
  addMethods: function(methods) {
    Object.extend(this.methods, methods);
  },

  /**
   * Add a method to instances of this factories type
   * @param {string} name The method name to add
   * @param {function} fn The Method to add
   */
  addMethod: function(name, fn) {
    this.methods[name] = fn;
  }
});

module.exports = ManagedFactory;


text:
function StationList(urls, stationMax) {

    var self = this;

    this.addStation = function (uri) {
        if (this.stations.length < this.max) {
            var station = new Station(this.stations.length, uri);
            this.stations.push(station);
            station.setOnRemoveListener(self.removeStation);
        } else {
            // TODO
        }
    };

    this.removeStation = function (index) {
        var removedStation = self.stations[index];
        removedStation.remove();
        for ( var i = index + 1; i < self.stations.length; i++ ) {
            var station = self.stations[i];
            station.setLabel( i + " - " );
            self.stations[i - 1] = station;
            station.index = i - 1;
        }
        self.stations.pop();
    };

    this.getURIList = function() {
        var list = [];
        for (var i = 0; i < self.stations.length; i++) {
            list.push(self.stations[i].getURI());
        }
        return list;
    };

    $( "#station-list" ).sortable({
        start: function(event, ui) {
            var start_pos = ui.item.index();
            ui.item.data( "start_pos", start_pos );
        },

        stop: function(event, ui) {
            var startPos = ui.item.data( "start_pos" ) - 1;
            var index = ui.item.index() - 1;

            var movedStation = self.stations[startPos];

            if (startPos < index) {
                for (var i = startPos + 1; i <= index; i++) {
                    var station = self.stations[i];
                    self.stations[i - 1] = station;
                    station.index = i - 1;
                    $("label", station.widget).text( i + " - " );
                }
            } else {
                for (var i = startPos - 1; i >= index; i--) {
                    var station = self.stations[i];
                    self.stations[i + 1] = station;
                    station.index = i + 1;
                    $("label", station.widget).text( (i + 2) + " - " );
                }
            }

            self.stations[index] = movedStation;
            $( "label", movedStation.widget ).text( (index + 1) + " - " );

            sendStationList(self.getURIList(), function() {
               // TODO error handling
            });
        },

        update: function(event, ui) {
            $( "#sortable li" ).removeClass( "highlights" );
        }
    });

    this.stations = [];
    this.max = stationMax;
    for (var i = 0; i < urls.length; i++) {
        this.addStation(urls[i]);
    }

    $( "#station-list" ).disableSelection();
}


text:
import TypeConverter from './TypeConverter';

class ArrayConverter extends TypeConverter {
    private converter: TypeConverter;
    private static SEPARATOR = '1-';

    constructor(converter: TypeConverter, key: string) {
        super(key, converter.name + 'array');
        this.converter = converter;
    }

    convertFrom(val: string | string[], separable: boolean): any {
        var arr = [];
        if (typeof val === 'string') {
            if (!separable) {
                var vals = val.split(ArrayConverter.SEPARATOR);
                for (var i = 0; i < vals.length; i++) {
                    if (vals[i].length !== 0)
                        arr.push(this.converter.convertFrom(vals[i].replace(/0-/g, '-')));
                    else
                        throw new Error('Empty string is not a valid array item');
                }
            } else {
                if (val.length !== 0)
                    arr.push(this.converter.convertFrom(val));
                else
                    throw new Error('Empty string is not a valid array item');
            }
        } else {
            for(var i = 0; i < val.length; i++) {
                if (val[i].length !== 0)
                    arr.push(this.converter.convertFrom(val[i]));
                else
                    throw new Error('Empty string is not a valid array item');
            }
        }
        return arr;
    }

    convertTo(val: any[]): { val: string, arrayVal?: string[] } {
        var vals = [];
        var arr = [];
        for (var i = 0; i < val.length; i++) {
            if (val[i] != null && val[i].toString()) {
                var convertedValue = this.converter.convertTo(val[i]).val;
                arr.push(convertedValue);
                vals.push(convertedValue.replace(/-/g, '0-'));
            } else {
                throw new Error('Invalid navigation data, arrays cannnot contain null, undefined or empty string');
            }
        }
        return { val: vals.join(ArrayConverter.SEPARATOR), arrayVal: arr };
    }
}
export default ArrayConverter;


text:
package gwt.material.design.client.base.mixin;

import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.HasEnabled;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import gwt.material.design.client.base.MaterialWidget;
import gwt.material.design.client.base.helper.StyleHelper;
import gwt.material.design.client.constants.CssName;

/**
 * @author Ben Dol
 * @author kevzlou7979
 */
public class EnabledMixin<T extends Widget & HasEnabled> extends AbstractMixin<T> implements HasEnabled {
    private static final String DISABLED = "disabled";

    private HandlerRegistration handler;

    public EnabledMixin(final T widget) {
        super(widget);
    }

    @Override
    public void setUiObject(T uiObject) {
        super.setUiObject(uiObject);

        // Clean up previous handler
        if (handler != null) {
            handler.removeHandler();
            handler = null;
        }
    }

    @Override
    public boolean isEnabled() {
        return !uiObject.getElement().hasAttribute("disabled");
    }

    @Override
    public void setEnabled(boolean enabled) {
        if (!uiObject.isAttached() && handler == null) {
            handler = uiObject.addAttachHandler(event -> {
                if (event.isAttached()) {
                    applyEnabled(enabled, uiObject);
                } else if (handler != null) {
                    handler.removeHandler();
                    handler = null;
                }
            });
        } else {
            applyEnabled(enabled, uiObject);
        }
    }

    public void setEnabled(MaterialWidget widget, boolean enabled) {
        setEnabled(enabled);
        for (Widget child : widget.getChildren()) {
            if (child instanceof MaterialWidget) {
                ((MaterialWidget) child).setEnabled(enabled);
                setEnabled((MaterialWidget) child, enabled);
            }
        }
    }

    private void applyEnabled(boolean enabled, UIObject obj) {
        if (enabled) {
            obj.removeStyleName(CssName.DISABLED);
            obj.getElement().removeAttribute(DISABLED);
        } else {
            obj.addStyleName(CssName.DISABLED);
            obj.getElement().setAttribute(DISABLED, "");
        }
    }
}


text:
Media objects

		Usage: mediaItem($source, $content, $options), mediaList($list, $options)

Simple media items:

<?php
// Source image
$source = "holder.js/64x64";
// Item content
$content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris id venenatis odio. Phasellus varius vulputate mi suscipit accumsan. Pellentesque tortor dui, placerat nec dolor ut, semper aliquet lectus.';
// Some options
$options = array('url' => '#', 'title' => 'Some title', 'alt' => 'Replacement text');

// Simple media item
echo $Tbs->mediaItem($source, $content);
// With options
echo $Tbs->mediaItem($source, $content, $options);
?>

Nested media items

<?php
//Define your $list as follow (source, content and options ARE needed, as they are passed to mediaItem)
$list = array(
		// Item 1
		array('source' => $source, 'content' => $content, 'options' => $options),
		// Item 2 with sublist
		array('source' => $source, 'content' => $content, 'options' => $options, 'list' => array(
						// Sub item 1
						array('source' => $source, 'content' => $content, 'options' => $options),
						// Sub item 2
						array('source' => $source, 'content' => $content, 'options' => $options),
						// ...
						array('source' => $source, 'content' => $content, 'options' => $options, 'list' => array(
										// Sub list
										array('source' => $source, 'content' => $content, 'options' => $options),
								)
						),
						// Sub item 3
						array('source' => $source, 'content' => $content, 'options' => $options),
				)
		)
);

echo $Tbs->mediaList($list);
?>

Simple media items

		<?php
		// Source image
		$source = "holder.js/64x64";
		// Item content
		$content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris id venenatis odio. Phasellus varius vulputate mi suscipit accumsan. Pellentesque tortor dui, placerat nec dolor ut, semper aliquet lectus.';
		// Some options
		$options = array('url' => '#', 'title' => 'Some title', 'alt' => 'Replacement text');

		// Simple media item
		echo $Tbs->mediaItem($source, $content);
		// With options
		echo $Tbs->mediaItem($source, $content, $options);
		?>

Nested list

		<?php
		//Define your $list as follow (source, content and options ARE needed, as they are passed to mediaItem)
		$list = array(
				// Item 1
				array('source' => $source, 'content' => $content, 'options' => $options),
				// Item 2 with sublist
				array('source' => $source, 'content' => $content, 'options' => $options, 'list' => array(
								// Sub item 1
								array('source' => $source, 'content' => $content, 'options' => $options),
								// Sub item 2
								array('source' => $source, 'content' => $content, 'options' => $options),
								// ...
								array('source' => $source, 'content' => $content, 'options' => $options, 'list' => array(
												// Sub list
												array('source' => $source, 'content' => $content, 'options' => $options),
										)
								),
						    // Sub item 3
								array('source' => $source, 'content' => $content, 'options' => $options),
						)
				)
		);

		echo $Tbs->mediaList($list);
		?>


text:
This retrieves a json string of all of the webforms for this account.

## All Webforms Options

[MadMimi's List Webforms Documentation](https://madmimi.com/developer/list-webforms) should give you an idea
of what you need to send to the API.  In this particular case, it's nothing!

### Method Reference

You do not need to specify any properties for this option.

## Exceptions

The following exceptions may be thrown throughout the duration of a options object - although I don't know why you'd be doing this for this option...

- `MadMimi\Exception\InvalidOptionException` During options object creation, a value in the array of the constructor argument that's key was not defined as a protected property of this options class


text:
<?php

namespace app\controllers;

use Yii;
use app\models\LicZama;
use app\models\LicZamaSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

use app\models\USUARIOS;
use yii\filters\AccessControl;

/**
 * LicZamaController implements the CRUD actions for LicZama model.
 */
class LicZamaController extends Controller
{

    private $__tipoTramite;

    public function tipoDeTramite()
    {
        if(empty($this->__tipoTramite))
        {
            $model = new LicZama();
            $this->__tipoTramite = $model->tipoDeTramite();
        }
        return $this->__tipoTramite;
    }
    public function behaviors()
    {
        $permisos = USUARIOS::permisosTramite($this->tipoDeTramite());
        return [

            'access' => [
                'class' => AccessControl::className(),

                'rules' => [
                    [
                        'actions' => ['index','view'],
                        'allow' =>$permisos[USUARIOS::$LEER],

                    ],
                    [
                        'actions' => ['salvar','create'],
                        'allow' => $permisos[USUARIOS::$CREAR],

                    ],
                    [
                        'actions' => ['update'],
                        'allow' => $permisos[USUARIOS::$ACTUALIZAR],

                    ],
                    [
                        'actions' => ['delete'],
                        'allow' => $permisos[USUARIOS::$BORRAR],

                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all LicZama models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new LicZamaSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single LicZama model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionSalvar() {

        $id=Yii::$app->request->post()['LicZama']['id'];
        $pasoIndex = Yii::$app->request->post()['paso'];
        if (($model = LicZama::findOne($id)) === null)
            $model = new LicZama();
        $model->__salvando = 1;

        \Yii::$app->response->format = 'json';

        if ($model->load(Yii::$app->request->post()) ) {

            if($model->salvarPaso($pasoIndex)) {
                $model->__salvando = 0;
                return $model;
            }
        }

        return null;
    }

    /**
     * Creates a new LicZama model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new LicZama();
            return $this->render('create', [
                'model' => $model,
            ]);
    }

    /**
     * Updates an existing LicZama model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing LicZama model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the LicZama model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return LicZama the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = LicZama::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
package com.intellij.lang.jsgraphql.types.introspection;

import com.intellij.lang.jsgraphql.types.Internal;
import com.intellij.lang.jsgraphql.types.schema.GraphQLSchema;
import com.intellij.lang.jsgraphql.types.schema.GraphQLType;

import java.util.Map;

/**
 * Extracted from {@link com.intellij.lang.jsgraphql.types.schema.DataFetchingEnvironment} to only capture
 * the data really needed for {@link Introspection}
 */
@Internal
public interface IntrospectionDataFetchingEnvironment {

    <T> T getSource();

    Map<String, Object> getArguments();

    GraphQLSchema getGraphQLSchema();

    <T> T getArgument(String name);

    GraphQLType getParentType();
}


text:
package service

import (
	"context"
	"fmt"
	"sort"
	"time"

	"go-common/app/admin/main/aegis/model"
	"go-common/app/admin/main/aegis/model/net"
	"go-common/library/ecode"
	"go-common/library/log"

	"github.com/jinzhu/gorm"
)

/**
 * 业务下所有需要分发任务的flow,用net+flow中文名拼接
 */
func (s *Service) dispatchFlow(c context.Context, businessID []int64, limitFlow []int64) (res map[int64]map[int64]string, err error) {
	var (
		nets   []*net.Net
		tranID []int64
		dirs   []*net.Direction
		flows  []*net.Flow
	)

	//biz:flow:flow_name
	res = map[int64]map[int64]string{}
	//业务下所有可用网
	if nets, err = s.gorm.NetsByBusiness(c, businessID, false); err != nil {
		log.Error("dispatchFlow s.gorm.NetsByBusiness(%v) error(%v)", businessID, err)
		return
	}
	netID := []int64{}
	netMap := map[int64]*net.Net{}
	for _, item := range nets {
		netID = append(netID, item.ID)
		netMap[item.ID] = item
	}
	//网下所有可用变迁
	if tranID, err = s.tranIDByNet(c, netID, true, false); err != nil {
		log.Error("dispatchFlow s.gorm.TransitionIDByNet(%v) error(%v) businessid(%d)", netID, err, businessID)
		return
	}
	if len(tranID) == 0 {
		return
	}
	//变迁所有可用的被指向的有向线
	if dirs, err = s.gorm.DirectionByTransitionID(c, tranID, net.DirInput, false); err != nil {
		log.Error("dispatchFlow s.gorm.DirectionByTransitionID error(%v) businessid(%d)", err, businessID)
		return
	}
	limitFlowMap := map[int64]int{}
	for _, item := range limitFlow {
		limitFlowMap[item] = 1
	}
	accessFlow := []int64{}
	for _, item := range dirs {
		if len(limitFlowMap) > 0 && limitFlowMap[item.FlowID] <= 0 {
			continue
		}
		accessFlow = append(accessFlow, item.FlowID)
	}
	if len(accessFlow) == 0 {
		return
	}
	//拼接每个节点的中文名
	if flows, err = s.flows(c, accessFlow, false); err != nil {
		log.Error("dispatchFlow s.flows error(%v) businessid(%d)", err, businessID)
		return
	}
	sort.Sort(net.FlowArr(flows))
	for _, item := range flows {
		if item == nil || netMap[item.NetID] == nil {
			continue
		}

		nt := netMap[item.NetID]
		if _, exist := res[nt.BusinessID]; !exist {
			res[nt.BusinessID] = map[int64]string{}
		}
		res[nt.BusinessID][item.ID] = nt.ChName + item.ChName
	}
	return
}

//ShowFlow .
func (s *Service) ShowFlow(c context.Context, id int64) (r *net.ShowFlowResult, err error) {
	var (
		f       *net.Flow
		details map[int64][]*net.TokenBind
		n       *net.Net
	)

	if f, err = s.gorm.FlowByID(c, id); err != nil {
		return
	}
	if details, err = s.gorm.TokenBindByElement(c, []int64{id}, []int8{net.BindTypeFlow}, true); err != nil {
		return
	}
	if n, err = s.gorm.NetByID(c, f.NetID); err != nil {
		return
	}
	r = &net.ShowFlowResult{
		Flow:    f,
		Tokens:  details[id],
		IsStart: n.StartFlowID == id,
	}
	return
}

//GetFlowList .
func (s *Service) GetFlowList(c context.Context, pm *net.ListNetElementParam) (result *net.ListFlowRes, err error) {
	var (
		flowID []int64
		tks    map[int64][]*net.TokenBind
		n      *net.Net
		uid    = []int64{}
		unames map[int64]string
	)

	if result, err = s.gorm.FlowList(c, pm); err != nil {
		return
	}
	if len(result.Result) == 0 {
		return
	}
	for _, item := range result.Result {
		flowID = append(flowID, item.ID)
		uid = append(uid, item.UID)
	}
	if tks, err = s.gorm.TokenBindByElement(c, flowID, []int8{net.BindTypeFlow}, true); err != nil {
		return
	}
	if n, err = s.gorm.NetByID(c, pm.NetID); err != nil {
		return
	}
	if unames, err = s.http.GetUnames(c, uid); err != nil {
		log.Error("GetFlowList s.http.GetUnames error(%v)", err)
		err = nil
	}
	for _, item := range result.Result {
		item.IsStart = item.ID == n.StartFlowID
		item.Username = unames[item.UID]
		for _, bd := range tks[item.ID] {
			item.Tokens = append(item.Tokens, bd.ChName)
		}
	}

	return
}

//GetFlowByNet .
func (s *Service) GetFlowByNet(c context.Context, netID int64) (result map[int64]string, err error) {
	var (
		flows []*net.Flow
	)
	result = map[int64]string{}
	if flows, err = s.gorm.FlowsByNet(c, []int64{netID}); err != nil {
		log.Error("GetFlowByNet s.gorm.FlowsByNet(%d) error(%v)", netID, err)
		return
	}

	for _, item := range flows {
		result[item.ID] = item.ChName
	}
	return
}

func (s *Service) checkFlowUnique(c context.Context, netID int64, name string) (err error, msg string) {
	var exist *net.Flow
	if exist, err = s.gorm.FlowByUnique(c, netID, name); err != nil {
		log.Error("checkFlowUnique s.gorm.FlowByUnique(%d,%s) error(%v)", netID, name, err)
		return
	}
	if exist != nil {
		err = ecode.AegisUniqueAlreadyExist
		msg = fmt.Sprintf(ecode.AegisUniqueAlreadyExist.Message(), "节点", name)
	}
	return
}

func (s *Service) checkStartFlowBind(oldFlow *net.Flow, tokenIDList []int64) (err error, msg string) {
	if oldFlow != nil && !oldFlow.IsAvailable() {
		err = ecode.AegisFlowDisabled
		msg = fmt.Sprintf("%s,不能作为初始节点", ecode.AegisFlowDisabled.Message())
		return
	}
	//第一版动态审核初始接入状态:敏感待审、非敏感待审、高频转发待审,非一个确定性值,而系统不提供条件判断和guard解析,由
	//配置初始节点没有令牌,而业务start时自动传入state支持(后续接入统一初始状态进而条件分状态的逻辑后,去掉state字段,且加上该判断)
	//if len(tokenIDList) == 0 {
	//	err = ecode.AegisFlowNoToken
	//	msg = fmt.Sprintf("%s,不能作为初始节点", ecode.AegisFlowNoToken.Message())
	//}

	return
}

//AddFlow .
func (s *Service) AddFlow(c context.Context, uid int64, f *net.FlowEditParam) (id int64, err error, msg string) {
	var (
		tx       *gorm.DB
		diff     = []string{}
		diffBind string
	)
	if err, msg = s.checkFlowUnique(c, f.NetID, f.Name); err != nil {
		return
	}
	if f.IsStart {
		if err, msg = s.checkStartFlowBind(nil, f.TokenIDList); err != nil {
			return
		}
		diff = append(diff, model.LogFieldTemp(model.LogFieldStartFlow, f.IsStart, false, false))
	}
	flow := &net.Flow{
		NetID:       f.NetID,
		Name:        f.Name,
		ChName:      f.ChName,
		Description: f.Description,
		UID:         uid,
	}

	//db update
	tx, err = s.gorm.BeginTx(c)
	if err != nil {
		log.Error("AddFlow s.gorm.BeginTx error(%v)", err)
		return
	}
	if err = s.gorm.AddItem(c, tx, flow); err != nil {
		tx.Rollback()
		return
	}
	if diffBind, _, err, msg = s.compareFlowBind(c, tx, flow.ID, f.TokenIDList, false); err != nil {
		log.Error("AddFlow s.compareFlowBind error(%v) params(%+v)", err, f)
		tx.Rollback()
		return
	}
	if diffBind != "" {
		diff = append(diff, diffBind)
	}
	if f.IsStart {
		if err = s.gorm.NetBindStartFlow(c, tx, flow.NetID, flow.ID); err != nil {
			tx.Rollback()
			return
		}
	}
	if err = tx.Commit().Error; err != nil {
		log.Error("AddFlow tx.Commit error(%v)", err)
		return
	}

	id = flow.ID

	//日志
	diff = append(diff, model.LogFieldTemp(model.LogFieldChName, f.ChName, "", false))
	diff = append(diff, model.LogFieldTemp(model.LogFieldName, f.Name, "", false))
	oper := &model.NetConfOper{
		OID:    flow.ID,
		Action: model.LogNetActionNew,
		UID:    flow.UID,
		NetID:  flow.NetID,
		ChName: flow.ChName,
		FlowID: flow.ID,
		Diff:   diff,
	}
	s.sendNetConfLog(c, model.LogTypeFlowConf, oper)
	return
}

// UpdateFlow .
func (s *Service) UpdateFlow(c context.Context, uid int64, f *net.FlowEditParam) (err error, msg string) {
	var (
		old         *net.Flow
		n           *net.Net
		startFlowID int64 = -1
		updates           = map[string]interface{}{}
		tx          *gorm.DB
		diff        = []string{}
		diffBind    string
		changedBind []int64
	)
	if old, err = s.gorm.FlowByID(c, f.ID); err != nil {
		log.Error("UpdateFlow s.gorm.FlowByID(%d) error(%v)", f.ID, err)
		return
	}
	if n, err = s.gorm.NetByID(c, old.NetID); err != nil {
		log.Error("UpdateFlow s.gorm.NetByID(%d) error(%v) flowid(%d)", old.NetID, err, f.ID)
		return
	}
	if f.IsStart && n.StartFlowID != f.ID {
		startFlowID = f.ID
	} else if !f.IsStart && n.StartFlowID == f.ID {
		startFlowID = 0
	}

	if f.IsStart {
		if err, msg = s.checkStartFlowBind(old, f.TokenIDList); err != nil {
			return
		}
		diff = append(diff, model.LogFieldTemp(model.LogFieldStartFlow, true, false, true))
	}

	if f.Name != old.Name {
		if err, msg = s.checkFlowUnique(c, old.NetID, f.Name); err != nil {
			return
		}
		diff = append(diff, model.LogFieldTemp(model.LogFieldName, f.Name, old.Name, true))
		old.Name = f.Name
		updates["name"] = f.Name
	}
	if f.ChName != old.ChName {
		diff = append(diff, model.LogFieldTemp(model.LogFieldChName, f.ChName, old.ChName, true))
		old.ChName = f.ChName
		updates["ch_name"] = f.ChName
	}
	if f.Description != old.Description {
		old.Description = f.Description
		updates["description"] = f.Description
	}

	//db update
	tx, err = s.gorm.BeginTx(c)
	if err != nil {
		log.Error("UpdateFlow s.gorm.BeginTx error(%v)", err)
		return
	}
	if len(updates) > 0 {
		if err = s.gorm.UpdateFields(c, tx, net.TableFlow, old.ID, updates); err != nil {
			tx.Rollback()
			return
		}
	}
	if startFlowID >= 0 {
		if err = s.gorm.NetBindStartFlow(c, tx, n.ID, startFlowID); err != nil {
			tx.Rollback()
			return
		}
	}
	if diffBind, changedBind, err, msg = s.compareFlowBind(c, tx, f.ID, f.TokenIDList, true); err != nil {
		log.Error("updateFlow s.compareFlowBind error(%v) params(%+v)", err, f)
		tx.Rollback()
		return
	}
	if diffBind != "" {
		diff = append(diff, diffBind)
	}
	if err = tx.Commit().Error; err != nil {
		log.Error("UpdateFlow tx.Commit error(%v)", err)
		return
	}
	s.delFlowCache(c, old, changedBind)

	//日志
	if len(diff) == 0 {
		return
	}
	oper := &model.NetConfOper{
		OID:    old.ID,
		Action: model.LogNetActionUpdate,
		UID:    uid,
		NetID:  old.NetID,
		ChName: old.ChName,
		FlowID: old.ID,
		Diff:   diff,
	}
	s.sendNetConfLog(c, model.LogTypeFlowConf, oper)
	return
}

//SwitchFlow .
func (s *Service) SwitchFlow(c context.Context, id int64, needDisable bool) (err error) {
	var (
		old    *net.Flow
		n      *net.Net
		dirs   []*net.Direction
		action string
	)
	if old, err = s.gorm.FlowByID(c, id); err != nil {
		log.Error("SwitchFlow s.gorm.FlowByID(%d) error(%v) needDisable(%v)", id, err, needDisable)
		return
	}
	log.Info("SwitchFlow id(%d) needdisable(%v) old-flow(%+v)", id, needDisable, old)
	available := old.IsAvailable()
	if available == !needDisable {
		return
	}

	if needDisable {
		if dirs, err = s.gorm.DirectionByFlowID(c, []int64{id}, 0); err != nil {
			log.Error("SwitchFlow s.gorm.DirectionByFlowID(%d) error(%v)", id, err)
			return
		}
		if len(dirs) > 0 {
			log.Error("SwitchFlow dir by flow(%d) founded", id)
			err = ecode.AegisFlowBinded
			return
		}
		if n, err = s.gorm.NetByID(c, old.NetID); err != nil {
			log.Error("SwitchFlow s.gorm.NetByID(%d) error(%v) flow(%d)", old.NetID, err, id)
			return
		}
		if n.StartFlowID == id {
			log.Error("SwitchFlow net(%d).startflow=flow(%d) founded", n.ID, id)
			err = ecode.AegisFlowBinded
			return
		}
		old.DisableTime = time.Now()
		action = model.LogNetActionDisable
	} else {
		old.DisableTime = net.Recovered
		action = model.LogNetActionAvailable
	}

	if err = s.gorm.UpdateFields(c, nil, net.TableFlow, id, map[string]interface{}{"disable_time": old.DisableTime}); err != nil {
		return
	}
	s.delFlowCache(c, old, nil)

	//日志
	oper := &model.NetConfOper{
		OID:    old.ID,
		Action: action,
		UID:    old.UID,
		NetID:  old.NetID,
		ChName: old.ChName,
		FlowID: old.ID,
	}
	s.sendNetConfLog(c, model.LogTypeFlowConf, oper)
	return
}


text:
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;

namespace Spookify
{
	[Register ("SearchBackgroundView")]
	partial class SearchBackgroundView
	{
		[Outlet]
		[GeneratedCode ("iOS Designer", "1.0")]
		UIImageView LupeImageView { get; set; }

		[Action ("OnShowGenres:")]
		[GeneratedCode ("iOS Designer", "1.0")]
		partial void OnShowGenres (UIButton sender);

		void ReleaseDesignerOutlets ()
		{
			if (LupeImageView != null) {
				LupeImageView.Dispose ();
				LupeImageView = null;
			}
		}
	}
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Tests\Api\Admin;

use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Tests\Api\JsonApiTestCase;
use Symfony\Component\HttpFoundation\Response;

final class ProductVariantsTest extends JsonApiTestCase
{
    /** @test */
    public function it_denies_access_to_a_products_list_for_not_authenticated_user(): void
    {
        $this->loadFixturesFromFiles(['channel.yaml', 'product/product_variant.yaml']);

        $this->client->request('GET', '/api/v2/admin/product-variants/MUG');

        $response = $this->client->getResponse();
        $this->assertSame(Response::HTTP_UNAUTHORIZED, $response->getStatusCode());
    }

    /** @test */
    public function it_gets_all_product_variants(): void
    {
        $this->loadFixturesFromFiles(['channel.yaml', 'product/product_variant.yaml', 'authentication/api_administrator.yaml']);

        $this->client->request(
            'POST',
            '/api/v2/admin/authentication-token',
            [],
            [],
            ['CONTENT_TYPE' => 'application/json', 'HTTP_ACCEPT' => 'application/json'],
            json_encode(['email' => 'api@example.com', 'password' => 'sylius'])
        );

        $token = json_decode($this->client->getResponse()->getContent(), true)['token'];
        $authorizationHeader = self::$container->getParameter('sylius.api.authorization_header');

        $header['HTTP_' . $authorizationHeader] = 'Bearer ' . $token;

        $this->client->request(
            'GET',
            'product-variants/MUG',
            [],
            [],
            array_merge($header, self::CONTENT_TYPE_HEADER)
        );
        $response = $this->client->getResponse();

        $this->assertResponse($response, 'admin/get_product_variants_response', Response::HTTP_OK);
    }

    /** @test */
    public function it_updates_channel_pricing_of_product_variant(): void
    {
        $fixtures = $this->loadFixturesFromFiles(['channel.yaml', 'product/product_variant.yaml', 'authentication/api_administrator.yaml']);

        $this->client->request(
            'POST',
            '/api/v2/admin/authentication-token',
            [],
            [],
            ['CONTENT_TYPE' => 'application/json', 'HTTP_ACCEPT' => 'application/json'],
            json_encode(['email' => 'api@example.com', 'password' => 'sylius'])
        );

        $token = json_decode($this->client->getResponse()->getContent(), true)['token'];
        $authorizationHeader = self::$container->getParameter('sylius.api.authorization_header');

        $header['HTTP_' . $authorizationHeader] = 'Bearer ' . $token;

        /** @var ProductVariantInterface $productVariant */
        $productVariant = $fixtures['product_variant'];
        /** @var ChannelInterface $channel */
        $channel = $fixtures['channel_web'];

        $this->client->request(
            'PUT',
            sprintf('/api/v2/admin/product-variants/%s', $productVariant->getCode()),
            [],
            [],
            array_merge($header, self::CONTENT_TYPE_HEADER),
            json_encode([
                'channelPricings' => ['WEB' => [
                    '@id' => sprintf('/api/v2/admin/channel-pricings/%s', $productVariant->getChannelPricingForChannel($channel)->getId()),
                    'price' => 3000,
                    'originalPrice' => 4000,
                ]]
            ], JSON_THROW_ON_ERROR)
        );

        $this->assertResponse(
            $this->client->getResponse(),
            'admin/put_product_variant_response',
            Response::HTTP_OK
        );
    }

    /** @test */
    public function it_creates_product_variant(): void
    {
        $fixtures = $this->loadFixturesFromFiles(['channel.yaml', 'product/product_variant.yaml', 'authentication/api_administrator.yaml']);

        $this->client->request(
            'POST',
            '/api/v2/admin/authentication-token',
            [],
            [],
            ['CONTENT_TYPE' => 'application/json', 'HTTP_ACCEPT' => 'application/json'],
            json_encode(['email' => 'api@example.com', 'password' => 'sylius'])
        );

        $token = json_decode($this->client->getResponse()->getContent(), true)['token'];
        $authorizationHeader = self::$container->getParameter('sylius.api.authorization_header');

        $header['HTTP_' . $authorizationHeader] = 'Bearer ' . $token;

        /** @var ProductInterface $product */
        $product = $fixtures['product'];

        $this->client->request(
            'POST',
            '/api/v2/admin/product-variants',
            [],
            [],
            array_merge($header, self::CONTENT_TYPE_HEADER),
            json_encode([
                'code' => 'MUG_2',
                'position' => 1,
                'product' => sprintf('/api/v2/admin/products/%s', $product->getCode()),
                'channelPricings' => ['WEB' => [
                    'channelCode' => 'WEB',
                    'price' => 4000,
                    'originalPrice' => 5000,
                    'minimumPrice' => 2000,
                ]]
            ], JSON_THROW_ON_ERROR)
        );

        $this->assertResponse(
            $this->client->getResponse(),
            'admin/post_product_variant_response',
            Response::HTTP_CREATED
        );
    }
}


text:
package gnu.javax.crypto.cipher;

import java.security.InvalidKeyException;

/**
 * Checked exception thrown to indicate that a weak key has been generated and
 * or specified instead of a valid non-weak value.
 */
public class WeakKeyException
    extends InvalidKeyException
{
  public WeakKeyException()
  {
    super();
  }

  public WeakKeyException(String msg)
  {
    super(msg);
  }
}


text:
package HPO

import (
	"database/sql"
	"fmt"
	"strconv"

	"github.com/artonge/Tamalou/Models"
	// Import SQLite drivers
	_ "github.com/mattn/go-sqlite3"
)

var db *sql.DB

// Init DB connection to HPO SQLite DB
func init() {
	var err error
	db, err = sql.Open("sqlite3", "datas/hpo/hpo_annotations.sqlite")
	if err != nil {
		fmt.Println("Error in HPO SQLite init: ", err)
	}
}

// SQLiteQuery - Make a request on HPO SQLite database
// @param query : The query to make
//                Note that the query will be prepend with "SELECT ... FROM ... WHERE "
//                You can use the following fields names :
//                          'disease_db', 'disease_id', 'disease_label', 'sign_id'
// @return results : Array fill with HPOSQLiteStruct
// @return error : Contains an error if one occurs
func SQLiteQuery(diseasesIDs []string) ([]*Models.Disease, error) {
	fullQuery := "SELECT disease_db, disease_id, disease_label, sign_id FROM phenotype_annotation WHERE "

	for _, id := range diseasesIDs {
		fullQuery += "sign_id='" + id + "' OR "
	}

	// Remove the last " OR "
	fullQuery = fullQuery[:len(fullQuery)-len(" OR ")]

	// Make the query
	rows, err := db.Query(fullQuery)
	if err != nil {
		return nil, fmt.Errorf("Error in SQLiteQuery when querying: %v", err)
	}

	// Prepare the resuts array
	diseasesArray := make([]*Models.Disease, 0, 100)

	// Parse rows
	for rows.Next() {
		tmpHPOSQLiteStruct := new(hpoSQLiteStruct)
		tmpDisease := new(Models.Disease)
		err = rows.Scan(
			&tmpHPOSQLiteStruct.DiseaseDB,
			&tmpHPOSQLiteStruct.DiseaseID,
			&tmpHPOSQLiteStruct.DiseaseLabel,
			&tmpHPOSQLiteStruct.SignID,
		)
		if err != nil {
			return nil, fmt.Errorf("Error in SQLiteQuery while scanning a row \n	==> %v\n	==> Error : %v", tmpHPOSQLiteStruct, err)
		}

		tmpDisease.Name = tmpHPOSQLiteStruct.DiseaseLabel
		tmpDisease.Sources = append(tmpDisease.Sources, "HPO")
		switch tmpHPOSQLiteStruct.DiseaseDB {
		case "ORPHA":
			value, err := strconv.ParseFloat(tmpHPOSQLiteStruct.DiseaseID, 64)
			if err != nil {
				return nil, fmt.Errorf("Error in SQLiteQuery while parsing float\n	==> %v\n	==> Error : %v", tmpHPOSQLiteStruct.DiseaseID, err)
			}
			tmpDisease.OrphaID = value
		case "OMIM":
			tmpDisease.OMIMID = tmpHPOSQLiteStruct.DiseaseID
		}
		// Append
		diseasesArray = append(diseasesArray, tmpDisease)
	}

	return diseasesArray, nil
}


text:
import {
	RouteInfo
} from './sidebar.metadata';

export const ROUTES: RouteInfo[] = [{
		path: 'bucketlists',
		title: 'Bucket lists',
		icon: 'dashboard',
		class: ''
	},
	{
		path: 'user',
		title: 'User Profile',
		icon: 'person',
		class: ''
	}
];


text:
\section{Oculus Rift} % (fold)
\label{sec:oculus_rift}

O \textit{Oculus Rift}\cite{oculusVR} é um produto desenvolvido pela Oculus VR\textsuperscript{\textregistered} que foi fundada por Palmer Luckey, um entusiasta em realidade virtual e \textit{nerd} de hardware. A companhia lançou uma campanha no \textit{Kickstarter}\cite{kickstarter}, uma plataforma que permite inventores encontrar patrocinadores, para ajudar a levantar fundos para seu primeiro produto, o \textit{Oculus Rift}, um óculos de imersão virtual bastante inovador para jogos. Com o suporte de gigantes produtoras de jogos eletrônicos como a Valve, Epic Games e Unity, o \textit{Kickstarter} foi o maior sucesso, levantando mais de US\$2,4 milhões em fundos. O time atualmente trabalha fortemente na comercialização do \textit{Oculus Rift}, que promete revolucionar a maneira que as pessoas interagem com conteúdos.

\subsection{Especificações de Hardware}
O \textit{Oculus Rift} é produzido somente em versões de desenvolvimento, não se sabe ao certo quais serão as especificações de hardware para o produto comercializável. A listagem a seguir apresenta as características de hardware do \textit{Oculus Rift DK1} (primeira versão de desenvolvimento):
\begin{itemize}
	\item Especificações da tela:
		\begin{itemize}
			\item Área visível de 7 polegadas
			\item Resolução total de 1280x800, 640x800 para cada olho
			\item Distancia fixa de 64mm entre os centros das lentes
			\item LCD com frequência de 60Hz
			\item HDMI 1.3+
		\end{itemize}
	\item Especificações dos sensores:
		\begin{itemize}
			\item Ate 1000Hz de taxa de amostragem
			\item Giroscópio de três eixos, para sensorear velocidade angular
			\item Magnetômetro de três eixos, para sensoriais campos magnéticos
			\item Acelerômetro de três eixos, para sensorear a aceleração, incluindo a gravitacional
		\end{itemize}
	\item Conexoes:
		\begin{itemize}
			\item USB 2.0 para transmissão de dados dos sensores
			\item HDMI para transmissão de imagens
			\item Fonte de energia para alimentação do óculos
		\end{itemize}
\end{itemize}

%exemplo de uso do glossário
%O \gls{rift}  é um equipamento de realidade virtual para jogos eletrônicos.