text:
@interface YWTextViewController ()<UITextFieldDelegate, UITextViewDelegate>
@property (nonatomic,assign) BOOL pIsTxd;
@property (nonatomic,strong) UITextField *pTxd;
@property (nonatomic,strong) YWTextView *pTxv;
@property (nonatomic,strong) NSString *pPlaceholder;
@property (nonatomic,strong) NSString *pText;
@property (nonatomic,strong) UILabel *pMaxCountLab;
@property (nonatomic,strong) UILabel *pCountLab;
@property (nonatomic,strong) UIButton *pCleanBtn;
@property (nonatomic,assign) NSUInteger pMaxLength;
@property (nonatomic,assign) NSUInteger pMinLength;
@property (nonatomic,assign) YWValidate pValidate;
@end

@implementation YWTextViewController

- (instancetype)initWithTitle:(NSString *)title text:(NSString *)text placeholder:(NSString *)placeholder minLength:(NSUInteger)minLength maxLength:(NSUInteger)maxLength validate:(YWValidate)validate isTxd:(BOOL)isTxd {
    if (self = [super init]) {
        self.title = title.length > 0 ? title : @"请填写";
        _pText = text;
        _pPlaceholder = placeholder.length > 0 ? placeholder : @"...";
        _pIsTxd = isTxd;
        _pMinLength = minLength;
        _pMaxLength = maxLength;
        _pValidate = validate;

        if (validate == YWValidationMobile) {
            _pMaxLength = 11;
        } else if (validate == YWValidationPhone) {
            _pMaxLength = 13;
        }
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [(_pIsTxd ? _pTxd : _pTxv) becomeFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pMaxLength = _pMaxLength > 0 ? _pMaxLength : 200;

    [self yw_addRightBarButtonItemTitle:@"保存"];

    UIView *view = _pIsTxd ? self.pTxd : self.pTxv;

    UIView *bgView = [[UIView alloc] initWithFrame:view.frame];
    bgView.backgroundColor = [UIColor whiteColor];
    [bgView yw_showShadowOpacity:.1 offset:CGSizeMake(0, 1) radius:0];
    [self.contentView addSubview:bgView];

    [self.contentView addSubview:view];

    [self.contentView addSubview:self.pMaxCountLab];
    [_pMaxCountLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_bottom).offset(8);
        make.left.equalTo(@15);
    }];

    [self.contentView addSubview:self.pCountLab];
    [_pCountLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_pMaxCountLab);
        make.left.equalTo(_pMaxCountLab.mas_right);
    }];

    [self.contentView addSubview:self.pCleanBtn];
    [_pCleanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_pMaxCountLab);
        make.right.equalTo(@-15);
    }];
}

- (void)yw_barButtonClick:(UIButton *)barBtn {
    NSString *str = _pIsTxd ? _pTxd.text : _pTxv.text;

    if (_pMinLength!=0 && str.length < _pMinLength) {
        [self yw_showToastTitle:[NSString stringWithFormat:@"字数要大于%zi",_pMinLength]];
        return;
    }

    NSString *error = [str yw_validate:_pValidate];

    if (error.length > 0) {
        [self yw_showToastTitle:error];
        return;
    }

    [_delegate yw_getTextFromTextViewController:str];
    [self yw_back];
}

#pragma mark - delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    UITextRange *selectedRange = [textView markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    //获取高亮部分内容
    //NSString * selectedtext = [textView textInRange:selectedRange];

    //如果有高亮且当前字数开始位置小于最大限制时允许输入
    if (selectedRange && pos) {
        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];
        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);
        return offsetRange.location < _pMaxLength;
    }

    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];

    NSInteger caninputlen = _pMaxLength - comcatstr.length;

    if (caninputlen >= 0) {
        return YES;
    }

    NSInteger len = text.length + caninputlen;
    //防止当text.length + caninputlen < 0时,使得rg.length为一个非法最大正数出错
    NSRange rg = NSMakeRange(0, MAX(len,0));

    if (rg.length > 0) {
        NSString *s = @"";
        //判断是否只普通的字符或asc码(对于中文和表情返回NO)
        BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];
        if (asc) {
            s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错
        } else {
            __block NSInteger idx = 0;
            __block NSString  *trimString = @"";//截取出的字串
            //使用字符串遍历,这个方法能准确知道每个emoji是占一个unicode还是两个
            [text enumerateSubstringsInRange:NSMakeRange(0, [text length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
                NSInteger steplen = substring.length;
                if (idx >= rg.length) {
                    *stop = YES; //取出所需要就break,提高效率
                    return ;
                }

                trimString = [trimString stringByAppendingString:substring];

                idx = idx + steplen;//这里变化了,使用了字串占的长度来作为步长
            }];
            s = trimString;
        }
        //rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)
        [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
        //既然是超出部分截取了,一定是最大限制了。
        _pCountLab.text = @"0";
    }

    return NO;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return [self textView:(id)textField shouldChangeTextInRange:range replacementText:string];
}

- (void)textViewDidChange:(UITextView *)textView {
    UITextRange *selectedRange = [textView markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];

    //如果在变化中是高亮部分在变,就不要计算字符了
    if (selectedRange && pos) {
        return;
    }

    NSString  *nsTextContent = textView.text;
    NSInteger existTextNum = nsTextContent.length;

    if (existTextNum > _pMaxLength) {
        //截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断)
        [textView setText:[nsTextContent substringToIndex:_pMaxLength]];
    }

    //不让显示负数
    NSInteger rest = _pMaxLength - existTextNum;
    _pCountLab.text = [NSString stringWithFormat:@"%zi",MAX(0, rest)];
}

- (void)textFieldDidChange:(UITextField *)sender {
    [self textViewDidChange:(id)sender];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self yw_barButtonClick:nil];
    return NO;
}

#pragma mark - lazy
- (UITextField *)pTxd {
    if (!_pTxd) {
        _pTxd = [[UITextField alloc] initWithFrame:CGRectMake(0, 20, YW_SCREEN_WIDTH, YW_SCREEN_FIT(50.0))];
        _pTxd.clearButtonMode = UITextFieldViewModeWhileEditing;
        _pTxd.tintColor = YW_MAIN_COLOR;
        _pTxd.font = YW_TEXT_FONT;
        _pTxd.textColor = YW_TEXT_COLOR;
        _pTxd.placeholder = _pPlaceholder;
        _pTxd.text = _pText;
        _pTxd.delegate = self;
        _pTxd.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 0)];
        _pTxd.leftViewMode = UITextFieldViewModeAlways;
        _pTxd.tintColor = YW_MAIN_COLOR;
        _pTxd.clearButtonMode = UITextFieldViewModeAlways;
        [_pTxd addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        _pTxd.returnKeyType = UIReturnKeyDone;
    }
    return _pTxd;
}

- (YWTextView *)pTxv {
    if (!_pTxv) {
        _pTxv = [[YWTextView alloc] initWithFrame:CGRectMake(0, 20, YW_SCREEN_WIDTH, ceilf(0.6 * YW_SCREEN_WIDTH))];
        _pTxv.placeholder = _pPlaceholder;
        _pTxv.text = _pText;
        _pTxv.delegate = self;
    }
    return _pTxv;
}

- (UILabel *)pMaxCountLab {
    if (!_pMaxCountLab) {
        _pMaxCountLab = [[UILabel alloc] initWithText:[NSString stringWithFormat:@"最多输入%zi个字/",_pMaxLength] textColor:nil font:nil];
        _pMaxCountLab.backgroundColor = YW_BG_COLOR;
    }
    return _pMaxCountLab;
}

- (UILabel *)pCountLab {
    if (!_pCountLab) {
        _pCountLab = [[UILabel alloc] initWithText:[NSString stringWithFormat:@"%zi",_pMaxLength - _pText.length] textColor:YW_MAIN_COLOR font:nil];
        _pCountLab.backgroundColor = YW_BG_COLOR;
    }
    return _pCountLab;
}

- (UIButton *)pCleanBtn {
    if (!_pCleanBtn) {
        _pCleanBtn = [[UIButton alloc] initWithTitle:@"清空" titleColor:YW_MAIN_COLOR image:nil background:nil];
        _pCleanBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 30, 30, 0);
        [_pCleanBtn addTarget:self action:@selector(cleanTxtInput) forControlEvents:UIControlEventTouchUpInside];
    }
    return _pCleanBtn;
}

- (void)cleanTxtInput {
    _pIsTxd ? (_pTxd.text = nil) : (_pTxv.text = nil);
    _pCountLab.text = [NSString stringWithFormat:@"%zi",_pMaxLength];
}

@end


text:
#include "actor.h"
#include "farchive.h"
#include "templates.h"
#include "cmdlib.h"
#include "i_system.h"
#include "c_dispatch.h"
#include "thingdef/thingdef.h"

// Each state is owned by an actor. Actors can own any number of
// states, but a single state cannot be owned by more than one
// actor. States are archived by recording the actor they belong
// to and the index into that actor's list of states.

// For NULL states, which aren't owned by any actor, the owner
// is recorded as AActor with the following state. AActor should
// never actually have this many states of its own, so this
// is (relatively) safe.

#define NULL_STATE_INDEX	127

//==========================================================================
//
//
//==========================================================================

FArchive &operator<< (FArchive &arc, FState *&state)
{
	const PClass *info;

	if (arc.IsStoring ())
	{
		if (state == NULL)
		{
			arc.UserWriteClass (RUNTIME_CLASS(AActor));
			arc.WriteCount (NULL_STATE_INDEX);
			return arc;
		}

		info = FState::StaticFindStateOwner (state);

		if (info != NULL)
		{
			arc.UserWriteClass (info);
			arc.WriteCount ((DWORD)(state - info->ActorInfo->OwnedStates));
		}
		else
		{
			/* this was never working as intended.
			I_Error ("Cannot find owner for state %p:\n"
					 "%s %c%c %3d [%p] -> %p", state,
					 sprites[state->sprite].name,
					 state->GetFrame() + 'A',
					 state->GetFullbright() ? '*' : ' ',
					 state->GetTics(),
					 state->GetAction(),
					 state->GetNextState());
			*/
		}
	}
	else
	{
		const PClass *info;
		DWORD ofs;

		arc.UserReadClass (info);
		ofs = arc.ReadCount ();
		if (ofs == NULL_STATE_INDEX && info == RUNTIME_CLASS(AActor))
		{
			state = NULL;
		}
		else if (info->ActorInfo != NULL)
		{
			state = info->ActorInfo->OwnedStates + ofs;
		}
		else
		{
			state = NULL;
		}
	}
	return arc;
}

//==========================================================================
//
// Find the actor that a state belongs to.
//
//==========================================================================

const PClass *FState::StaticFindStateOwner (const FState *state)
{
	for (unsigned int i = 0; i < PClass::m_RuntimeActors.Size(); ++i)
	{
		FActorInfo *info = PClass::m_RuntimeActors[i]->ActorInfo;
		if (state >= info->OwnedStates &&
			state <  info->OwnedStates + info->NumOwnedStates)
		{
			return info->Class;
		}
	}

	return NULL;
}

//==========================================================================
//
// Find the actor that a state belongs to, but restrict the search to
// the specified type and its ancestors.
//
//==========================================================================

const PClass *FState::StaticFindStateOwner (const FState *state, const FActorInfo *info)
{
	while (info != NULL)
	{
		if (state >= info->OwnedStates &&
			state <  info->OwnedStates + info->NumOwnedStates)
		{
			return info->Class;
		}
		info = info->Class->ParentClass->ActorInfo;
	}
	return NULL;
}

//==========================================================================
//
//
//==========================================================================

FStateLabel *FStateLabels::FindLabel (FName label)
{
	return const_cast<FStateLabel *>(BinarySearch<FStateLabel, FName> (Labels, NumLabels, &FStateLabel::Label, label));
}

void FStateLabels::Destroy ()
{
	for(int i=0; i<NumLabels;i++)
	{
		if (Labels[i].Children != NULL)
		{
			Labels[i].Children->Destroy();
			free (Labels[i].Children);	// These are malloc'd, not new'd!
			Labels[i].Children=NULL;
		}
	}
}

//===========================================================================
//
// HasStates
//
// Checks whether the actor has special death states.
//
//===========================================================================

bool AActor::HasSpecialDeathStates () const
{
	const FActorInfo *info = GetClass()->ActorInfo;

	if (info->StateList != NULL)
	{
		FStateLabel *slabel = info->StateList->FindLabel (NAME_Death);
		if (slabel != NULL && slabel->Children != NULL)
		{
			for(int i=0;i<slabel->Children->NumLabels;i++)
			{
				if (slabel->Children->Labels[i].State != NULL) return true;
			}
		}
	}
	return false;
}

//==========================================================================
//
// Creates a list of names from a string. Dots are used as separator
//
//==========================================================================

TArray<FName> &MakeStateNameList(const char * fname)
{
	static TArray<FName> namelist(3);
	FName firstpart, secondpart;
	char * c;

	// Handle the old names for the existing death states
	char * name = copystring(fname);
	firstpart = strtok(name, ".");
	switch (firstpart)
	{
	case NAME_Burn:
		firstpart = NAME_Death;
		secondpart = NAME_Fire;
		break;
	case NAME_Ice:
		firstpart = NAME_Death;
		secondpart = NAME_Ice;
		break;
	case NAME_Disintegrate:
		firstpart = NAME_Death;
		secondpart = NAME_Disintegrate;
		break;
	case NAME_XDeath:
		firstpart = NAME_Death;
		secondpart = NAME_Extreme;
		break;
	}

	namelist.Clear();
	namelist.Push(firstpart);
	if (secondpart!=NAME_None) namelist.Push(secondpart);

	while ((c = strtok(NULL, "."))!=NULL)
	{
		FName cc = c;
		namelist.Push(cc);
	}
	delete [] name;
	return namelist;
}

//===========================================================================
//
// FindState (multiple names version)
//
// Finds a state that matches as many of the supplied names as possible.
// A state with more names than those provided does not match.
// A state with fewer names can match if there are no states with the exact
// same number of names.
//
// The search proceeds like this. For the current class, keeping matching
// names until there are no more. If both the argument list and the state
// are out of names, it's an exact match, so return it. If the state still
// has names, ignore it. If the argument list still has names, remember it.
//
//===========================================================================
FState *FActorInfo::FindState (int numnames, FName *names, bool exact) const
{
	FStateLabels *labels = StateList;
	FState *best = NULL;

	if (labels != NULL)
	{
		int count = 0;
		FStateLabel *slabel = NULL;
		FName label;

		// Find the best-matching label for this class.
		while (labels != NULL && count < numnames)
		{
			label = *names++;
			slabel = labels->FindLabel (label);

			if (slabel != NULL)
			{
				count++;
				labels = slabel->Children;
				best = slabel->State;
			}
			else
			{
				break;
			}
		}
		if (count < numnames && exact) return NULL;
	}
	return best;
}

//==========================================================================
//
// Finds the state associated with the given string
//
//==========================================================================

FState *FActorInfo::FindStateByString(const char *name, bool exact)
{
	TArray<FName> &namelist = MakeStateNameList(name);
	return FindState(namelist.Size(), &namelist[0], exact);
}

//==========================================================================
//
// Search one list of state definitions for the given name
//
//==========================================================================

FStateDefine *FStateDefinitions::FindStateLabelInList(TArray<FStateDefine> & list, FName name, bool create)
{
	for(unsigned i = 0; i<list.Size(); i++)
	{
		if (list[i].Label == name) return &list[i];
	}
	if (create)
	{
		FStateDefine def;
		def.Label = name;
		def.State = NULL;
		def.DefineFlags = SDF_NEXT;
		return &list[list.Push(def)];
	}
	return NULL;
}

//==========================================================================
//
// Finds the address of a state label given by name.
// Adds the state label if it doesn't exist
//
//==========================================================================

FStateDefine * FStateDefinitions::FindStateAddress(const char *name)
{
	FStateDefine *statedef = NULL;
	TArray<FName> &namelist = MakeStateNameList(name);
	TArray<FStateDefine> *statelist = &StateLabels;

	for(unsigned i = 0; i < namelist.Size(); i++)
	{
		statedef = FindStateLabelInList(*statelist, namelist[i], true);
		statelist = &statedef->Children;
	}
	return statedef;
}

//==========================================================================
//
// Adds a new state to the curremt list
//
//==========================================================================

void FStateDefinitions::SetStateLabel (const char *statename, FState *state, BYTE defflags)
{
	FStateDefine *std = FindStateAddress(statename);
	std->State = state;
	std->DefineFlags = defflags;
}

//==========================================================================
//
// Adds a new state to the current list
//
//==========================================================================

void FStateDefinitions::AddStateLabel (const char *statename)
{
	intptr_t index = StateArray.Size();
	FStateDefine *std = FindStateAddress(statename);
	std->State = (FState *)(index+1);
	std->DefineFlags = SDF_INDEX;
	laststate = NULL;
	lastlabel = index;
}

//==========================================================================
//
// Returns the index a state label points to. May only be called before
// installing states.
//
//==========================================================================

int FStateDefinitions::GetStateLabelIndex (FName statename)
{
	FStateDefine *std = FindStateLabelInList(StateLabels, statename, false);
	if (std == NULL)
	{
		return -1;
	}
	assert((size_t)std->State <= StateArray.Size() + 1);
	return (int)((ptrdiff_t)std->State - 1);
}

//==========================================================================
//
// Finds the state associated with the given name
// returns NULL if none found
//
//==========================================================================

FState * FStateDefinitions::FindState(const char * name)
{
	FStateDefine * statedef=NULL;

	TArray<FName> &namelist = MakeStateNameList(name);

	TArray<FStateDefine> * statelist = &StateLabels;
	for(unsigned i=0;i<namelist.Size();i++)
	{
		statedef = FindStateLabelInList(*statelist, namelist[i], false);
		if (statedef == NULL) return NULL;
		statelist = &statedef->Children;
	}
	return statedef? statedef->State : NULL;
}

//==========================================================================
//
// Creates the final list of states from the state definitions
//
//==========================================================================

static int STACK_ARGS labelcmp(const void * a, const void * b)
{
	FStateLabel * A = (FStateLabel *)a;
	FStateLabel * B = (FStateLabel *)b;
	return ((int)A->Label - (int)B->Label);
}

FStateLabels * FStateDefinitions::CreateStateLabelList(TArray<FStateDefine> & statelist)
{
	// First delete all empty labels from the list
	for (int i=statelist.Size()-1;i>=0;i--)
	{
		if (statelist[i].Label == NAME_None || (statelist[i].State == NULL && statelist[i].Children.Size() == 0))
		{
			statelist.Delete(i);
		}
	}

	int count=statelist.Size();

	if (count == 0) return NULL;

	FStateLabels * list = (FStateLabels*)M_Malloc(sizeof(FStateLabels)+(count-1)*sizeof(FStateLabel));
	list->NumLabels = count;

	for (int i=0;i<count;i++)
	{
		list->Labels[i].Label = statelist[i].Label;
		list->Labels[i].State = statelist[i].State;
		list->Labels[i].Children = CreateStateLabelList(statelist[i].Children);
	}
	qsort(list->Labels, count, sizeof(FStateLabel), labelcmp);
	return list;
}

//===========================================================================
//
// InstallStates
//
// Creates the actor's state list from the current definition
//
//===========================================================================

void FStateDefinitions::InstallStates(FActorInfo *info, AActor *defaults)
{
	// First ensure we have a valid spawn state.
	FState *state = FindState("Spawn");

	if (state == NULL)
	{
		// A NULL spawn state will crash the engine so set it to something valid.
		SetStateLabel("Spawn", GetDefault<AActor>()->SpawnState);
	}

	if (info->StateList != NULL)
	{
		info->StateList->Destroy();
		M_Free(info->StateList);
	}
	info->StateList = CreateStateLabelList(StateLabels);

	// Cache these states as member veriables.
	defaults->SpawnState = info->FindState(NAME_Spawn);
	defaults->SeeState = info->FindState(NAME_See);
	// Melee and Missile states are manipulated by the scripted marines so they
	// have to be stored locally
	defaults->MeleeState = info->FindState(NAME_Melee);
	defaults->MissileState = info->FindState(NAME_Missile);
}

//===========================================================================
//
// MakeStateDefines
//
// Creates a list of state definitions from an existing actor
// Used by Dehacked to modify an actor's state list
//
//===========================================================================

void FStateDefinitions::MakeStateList(const FStateLabels *list, TArray<FStateDefine> &dest)
{
	dest.Clear();
	if (list != NULL) for(int i=0;i<list->NumLabels;i++)
	{
		FStateDefine def;

		def.Label = list->Labels[i].Label;
		def.State = list->Labels[i].State;
		def.DefineFlags = SDF_STATE;
		dest.Push(def);
		if (list->Labels[i].Children != NULL)
		{
			MakeStateList(list->Labels[i].Children, dest[dest.Size()-1].Children);
		}
	}
}

void FStateDefinitions::MakeStateDefines(const PClass *cls)
{
	StateArray.Clear();
	laststate = NULL;
	laststatebeforelabel = NULL;
	lastlabel = -1;

	if (cls != NULL && cls->ActorInfo != NULL && cls->ActorInfo->StateList != NULL)
	{
		MakeStateList(cls->ActorInfo->StateList, StateLabels);
	}
	else
	{
		StateLabels.Clear();
	}
}

//===========================================================================
//
// AddStateDefines
//
// Adds a list of states to the current definitions
//
//===========================================================================

void FStateDefinitions::AddStateDefines(const FStateLabels *list)
{
	if (list != NULL) for(int i=0;i<list->NumLabels;i++)
	{
		if (list->Labels[i].Children == NULL)
		{
			if (!FindStateLabelInList(StateLabels, list->Labels[i].Label, false))
			{
				FStateDefine def;

				def.Label = list->Labels[i].Label;
				def.State = list->Labels[i].State;
				def.DefineFlags = SDF_STATE;
				StateLabels.Push(def);
			}
		}
	}
}

//==========================================================================
//
// RetargetState(Pointer)s
//
// These functions are used when a goto follows one or more labels.
// Because multiple labels are permitted to occur consecutively with no
// intervening states, it is not enough to remember the last label defined
// and adjust it. So these functions search for all labels that point to
// the current position in the state array and give them a copy of the
// target string instead.
//
//==========================================================================

void FStateDefinitions::RetargetStatePointers (intptr_t count, const char *target, TArray<FStateDefine> & statelist)
{
	for(unsigned i = 0;i<statelist.Size(); i++)
	{
		if (statelist[i].State == (FState*)count && statelist[i].DefineFlags == SDF_INDEX)
		{
			if (target == NULL)
			{
				statelist[i].State = NULL;
				statelist[i].DefineFlags = SDF_STOP;
			}
			else
			{
				statelist[i].State = (FState *)copystring (target);
				statelist[i].DefineFlags = SDF_LABEL;
			}
		}
		if (statelist[i].Children.Size() > 0)
		{
			RetargetStatePointers(count, target, statelist[i].Children);
		}
	}
}

void FStateDefinitions::RetargetStates (intptr_t count, const char *target)
{
	RetargetStatePointers(count, target, StateLabels);
}

//==========================================================================
//
// ResolveGotoLabel
//
// Resolves any strings being stored in a state's NextState field
//
//==========================================================================

FState *FStateDefinitions::ResolveGotoLabel (AActor *actor, const PClass *mytype, char *name)
{
	const PClass *type=mytype;
	FState *state;
	char *namestart = name;
	char *label, *offset, *pt;
	int v;

	// Check for classname
	if ((pt = strstr (name, "::")) != NULL)
	{
		const char *classname = name;
		*pt = '\0';
		name = pt + 2;

		// The classname may either be "Super" to identify this class's immediate
		// superclass, or it may be the name of any class that this one derives from.
		if (stricmp (classname, "Super") == 0)
		{
			type = type->ParentClass;
			actor = GetDefaultByType (type);
		}
		else
		{
			// first check whether a state of the desired name exists
			const PClass *stype = PClass::FindClass (classname);
			if (stype == NULL)
			{
				I_Error ("%s is an unknown class.", classname);
			}
			if (!stype->IsDescendantOf (RUNTIME_CLASS(AActor)))
			{
				I_Error ("%s is not an actor class, so it has no states.", stype->TypeName.GetChars());
			}
			if (!stype->IsAncestorOf (type))
			{
				I_Error ("%s is not derived from %s so cannot access its states.",
					type->TypeName.GetChars(), stype->TypeName.GetChars());
			}
			if (type != stype)
			{
				type = stype;
				actor = GetDefaultByType (type);
			}
		}
	}
	label = name;
	// Check for offset
	offset = NULL;
	if ((pt = strchr (name, '+')) != NULL)
	{
		*pt = '\0';
		offset = pt + 1;
	}
	v = offset ? strtol (offset, NULL, 0) : 0;

	// Get the state's address.
	if (type==mytype) state = FindState (label);
	else state = type->ActorInfo->FindStateByString(label, true);

	if (state != NULL)
	{
		state += v;
	}
	else if (v != 0)
	{
		I_Error ("Attempt to get invalid state %s from actor %s.", label, type->TypeName.GetChars());
	}
	delete[] namestart;		// free the allocated string buffer
	return state;
}

//==========================================================================
//
// FixStatePointers
//
// Fixes an actor's default state pointers.
//
//==========================================================================

void FStateDefinitions::FixStatePointers (FActorInfo *actor, TArray<FStateDefine> & list)
{
	for(unsigned i=0;i<list.Size(); i++)
	{
		if (list[i].DefineFlags == SDF_INDEX)
		{
			size_t v=(size_t)list[i].State;
			list[i].State = actor->OwnedStates + v - 1;
			list[i].DefineFlags = SDF_STATE;
		}
		if (list[i].Children.Size() > 0) FixStatePointers(actor, list[i].Children);
	}
}

//==========================================================================
//
// ResolveGotoLabels
//
// Resolves an actor's state pointers that were specified as jumps.
//
//==========================================================================

void FStateDefinitions::ResolveGotoLabels (FActorInfo *actor, AActor *defaults, TArray<FStateDefine> & list)
{
	for(unsigned i=0;i<list.Size(); i++)
	{
		if (list[i].State != NULL && list[i].DefineFlags == SDF_LABEL)
		{ // It's not a valid state, so it must be a label string. Resolve it.
			list[i].State = ResolveGotoLabel (defaults, actor->Class, (char *)list[i].State);
			list[i].DefineFlags = SDF_STATE;
		}
		if (list[i].Children.Size() > 0) ResolveGotoLabels(actor, defaults, list[i].Children);
	}
}

//==========================================================================
//
// SetGotoLabel
//
// sets a jump at the current state or retargets a label
//
//==========================================================================

bool FStateDefinitions::SetGotoLabel(const char *string)
{
	// copy the text - this must be resolved later!
	if (laststate != NULL)
	{ // Following a state definition: Modify it.
		laststate->NextState = (FState*)copystring(string);
		laststate->DefineFlags = SDF_LABEL;
		laststatebeforelabel = NULL;
		return true;
	}
	else if (lastlabel >= 0)
	{ // Following a label: Retarget it.
		RetargetStates (lastlabel+1, string);
		if (laststatebeforelabel != NULL)
		{
			laststatebeforelabel->NextState = (FState*)copystring(string);
			laststatebeforelabel->DefineFlags = SDF_LABEL;
			laststatebeforelabel = NULL;
		}
		return true;
	}
	return false;
}

//==========================================================================
//
// SetStop
//
// sets a stop operation
//
//==========================================================================

bool FStateDefinitions::SetStop()
{
	if (laststate != NULL)
	{
		laststate->DefineFlags = SDF_STOP;
		laststatebeforelabel = NULL;
		return true;
	}
	else if (lastlabel >=0)
	{
		RetargetStates (lastlabel+1, NULL);
		if (laststatebeforelabel != NULL)
		{
			laststatebeforelabel->DefineFlags = SDF_STOP;
			laststatebeforelabel = NULL;
		}
		return true;
	}
	return false;
}

//==========================================================================
//
// SetWait
//
// sets a wait or fail operation
//
//==========================================================================

bool FStateDefinitions::SetWait()
{
	if (laststate != NULL)
	{
		laststate->DefineFlags = SDF_WAIT;
		laststatebeforelabel = NULL;
		return true;
	}
	return false;
}

//==========================================================================
//
// SetLoop
//
// sets a loop operation
//
//==========================================================================

bool FStateDefinitions::SetLoop()
{
	if (laststate != NULL)
	{
		laststate->DefineFlags = SDF_INDEX;
		laststate->NextState = (FState*)(lastlabel+1);
		laststatebeforelabel = NULL;
		return true;
	}
	return false;
}

//==========================================================================
//
// AddStates
// adds some state to the current definition set
//
//==========================================================================

bool FStateDefinitions::AddStates(FState *state, const char *framechars)
{
	bool error = false;
	int frame = 0;

	while (*framechars)
	{
		bool noframe = false;

		if (*framechars == '#')
			noframe = true;
		else if (*framechars == '^')
			frame = '\\' - 'A';
		else
			frame = (*framechars & 223) - 'A';

		framechars++;
		if (frame < 0 || frame > 28)
		{
			frame = 0;
			error = true;
		}

		state->Frame = frame;
		state->SameFrame = noframe;
		StateArray.Push(*state);

		// NODELAY flag is not carried past the first state
		state->NoDelay = false;
	}
	laststate = &StateArray[StateArray.Size() - 1];
	laststatebeforelabel = laststate;
	return !error;
}

//==========================================================================
//
// FinishStates
// copies a state block and fixes all state links using the current list of labels
//
//==========================================================================

int FStateDefinitions::FinishStates (FActorInfo *actor, AActor *defaults)
{
	int count = StateArray.Size();

	if (count > 0)
	{
		FState *realstates = new FState[count];
		int i;

		memcpy(realstates, &StateArray[0], count*sizeof(FState));
		actor->OwnedStates = realstates;
		actor->NumOwnedStates = count;

		// adjust the state pointers
		// In the case new states are added these must be adjusted, too!
		FixStatePointers(actor, StateLabels);

		// Fix state pointers that are gotos
		ResolveGotoLabels(actor, defaults, StateLabels);

		for (i = 0; i < count; i++)
		{
			// resolve labels and jumps
			switch (realstates[i].DefineFlags)
			{
			case SDF_STOP:	// stop
				realstates[i].NextState = NULL;
				break;

			case SDF_WAIT:	// wait
				realstates[i].NextState = &realstates[i];
				break;

			case SDF_NEXT:		// next
				realstates[i].NextState = (i < count-1 ? &realstates[i+1] : &realstates[0]);
				break;

			case SDF_INDEX:		// loop
				realstates[i].NextState = &realstates[(size_t)realstates[i].NextState-1];
				break;

			case SDF_LABEL:
				realstates[i].NextState = ResolveGotoLabel(defaults, actor->Class, (char *)realstates[i].NextState);
				break;
			}
		}
	}
	else
	{
		// Fix state pointers that are gotos
		ResolveGotoLabels(actor, defaults, StateLabels);
	}

	return count;
}

//==========================================================================
//
// Prints all state label info to the logfile
//
//==========================================================================

void DumpStateHelper(FStateLabels *StateList, const FString &prefix)
{
	for (int i = 0; i < StateList->NumLabels; i++)
	{
		if (StateList->Labels[i].State != NULL)
		{
			const PClass *owner = FState::StaticFindStateOwner(StateList->Labels[i].State);
			if (owner == NULL)
			{
				Printf(PRINT_LOG, "%s%s: invalid\n", prefix.GetChars(), StateList->Labels[i].Label.GetChars());
			}
			else
			{
				Printf(PRINT_LOG, "%s%s: %s.%d\n", prefix.GetChars(), StateList->Labels[i].Label.GetChars(),
					owner->TypeName.GetChars(), int(StateList->Labels[i].State - owner->ActorInfo->OwnedStates));
			}
		}
		if (StateList->Labels[i].Children != NULL)
		{
			DumpStateHelper(StateList->Labels[i].Children, prefix + '.' + StateList->Labels[i].Label.GetChars());
		}
	}
}

CCMD(dumpstates)
{
	for (unsigned int i = 0; i < PClass::m_RuntimeActors.Size(); ++i)
	{
		FActorInfo *info = PClass::m_RuntimeActors[i]->ActorInfo;
		Printf(PRINT_LOG, "State labels for %s\n", info->Class->TypeName.GetChars());
		DumpStateHelper(info->StateList, "");
		Printf(PRINT_LOG, "----------------------------\n");
	}
}

redpajama_set_name: RedPajamaGithub


text:
React boilerplate, used best practices and focus on performance

[![Build Status](https://travis-ci.org/wearepush/push-starter.svg?branch=master&style=flat-square)](https://travis-ci.org/wearepush/push-starter)
---

---

## [Live Demo](https://push-starter.herokuapp.com) :eyes:

## About

The starter boilerplate includes the following technologies:

| Technology                                                                                | Description                                                     |
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------|
| [Node 16.0.0 LTS](https://nodejs.org/en/)                                         | Node |
| [Redux Dev Tools](https://github.com/zalmoxisus/redux-devtools-extension)         | Redux Dev Tools |
| [React 17](https://github.com/facebook/react)                                     | JavaScript library for building user interfaces  |
| [React Router 6](https://github.com/ReactTraining/react-router)                   | React Router is a complete routing library for React    |
| [Babel](http://babeljs.io)                                                        | Babel is a JavaScript compiler              |
| [Webpack 5](http://webpack.github.io)                                             | Module bundler                       |
| [Universal Webpack](https://www.npmjs.com/package/universal-webpack)              | Helps setting up universal Webpack build: the one that's working both on client and server                                                |
| [Redux](http://redux.js.org/)                                                     | Redux is a predictable state container for JavaScript apps                           |
| [React Router Redux](https://github.com/ReactTraining/react-router/tree/master/packages/react-router-redux)               | Simple bindings to keep react-router and redux in sync                                        |
| [ESLint](http://eslint.org)                                                       | The pluggable linting utility for JavaScript and JSX                                            |
| [Include-media](https://eduardoboucas.github.io/include-media/)                   | Sass library for writing CSS media queries in an easy and maintainable way                               |

## Installation

```bash
rm -rf node_modules
npm install
```

## Running Prod Server

```bash
npm start
```

## Running Dev Server

```bash
npm run dev
```

## Running Tests

```bash
npm run test
```

## Deployment on Heroku

To get this project to work on Heroku, you need to:

1. Add heroku `heroku git:remote -a heroku-app-name`
2. `heroku config:set NODE_ENV=production`
3. `heroku config:set NPM_CONFIG_PRODUCTION=false`
4. `heroku config:set SSL=true`
5. `heroku config:set GOOGLE_ANALITICS_ID=UA-xxxxxxxxx-x` (optional)

## Docker

Run container

```bash
docker-compose up -d
```

Build an image

```bash
docker build -t wearepush/push-starter .
```

## Contributing

We are more than happy to accept external contributions to the project in the form of feedback, bug reports and even better - pull requests :)
If you would like to submit a pull request, please make an effort to follow the guide in [CONTRIBUTING.md](docs/CONTRIBUTING.md).


text:
from os.path import basename

import qiita_db as qdb

with qdb.sql_connection.TRN:
    sql = "SELECT prep_template_id FROM qiita.prep_template"
    qdb.sql_connection.TRN.add(sql)
    all_ids = qdb.sql_connection.TRN.execute_fetchflatten()

    # remove all the bad mapping files
    for prep_template_id in all_ids:
        pt = qdb.metadata_template.prep_template.PrepTemplate(prep_template_id)
        fps = pt.get_filepaths()

        # get the QIIME mapping file, note that the way to figure out what is
        # and what's not a qiime mapping file is to check for the existance of
        # the word qiime in the basename of the file path, hacky but that's
        # the way it is being done in qiita_pet/uimodules/raw_data_tab.py
        mapping_files = [f for f in fps if '_qiime_' in basename(f[1])]

        table = 'prep_template_filepath'
        column = 'prep_template_id'

        # unlink all the qiime mapping files for this prep template object
        for mf in mapping_files:

            # (1) get the ids that we are going to delete.
            # because of the FK restriction, we cannot just delete the ids
            sql = """SELECT filepath_id
                     FROM qiita.{0}
                     WHERE {1}=%s AND filepath_id=%s""".format(table, column)
            qdb.sql_connection.TRN.add(sql, [pt.id, mf[0]])
            ids = qdb.sql_connection.TRN.execute_fetchflatten()

            # (2) delete the entries from the prep_template_filepath table
            sql = """DELETE FROM qiita.{0}
                     WHERE {1}=%s and filepath_id=%s""".format(table, column)
            qdb.sql_connection.TRN.add(sql, [pt.id, mf[0]])

            # (3) delete the entries from the filepath table
            sql = "DELETE FROM qiita.filepath WHERE filepath_id IN %s"
            qdb.sql_connection.TRN.add(sql, [tuple(ids)])

    qdb.sql_connection.TRN.execute()

    # create correct versions of the mapping files
    for prep_template_id in all_ids:

        prep_template_id = prep_template_id[0]
        pt = qdb.metadata_template.prep_template.PrepTemplate(prep_template_id)

        # we can guarantee that all the filepaths will be prep templates so
        # we can just generate the qiime mapping files
        for _, fpt in pt.get_filepaths():
            pt.create_qiime_mapping_file(fpt)


text:
package android.orm.tasks.view;

import android.app.Activity;
import android.orm.tasks.R;
import android.orm.tasks.model.Task;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Checkable;
import android.widget.ListView;

import java.util.Collection;

import static android.widget.AbsListView.CHOICE_MODE_NONE;

public class List extends ListFragment {

    private Controller mController = DUMMY_CONTROLLER;

    private ArrayAdapter<Task> mAdapter;

    private final AdapterView.OnItemLongClickListener mEdit = new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(final AdapterView<?> adapterView,
                                       final View view,
                                       final int position,
                                       final long id) {
            mController.edit(mAdapter.getItem(position));
            return true;
        }
    };

    public static List create() {
        return new List();
    }

    public List() {
        super();
    }

    @Override
    public final void onViewCreated(final View view, final Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        final ListView list = getListView();
        if (list != null) {
            list.setChoiceMode(CHOICE_MODE_NONE);
            list.setOnItemLongClickListener(mEdit);
        }

        setListShown(false);
    }

    @Override
    public final void onListItemClick(final ListView list,
                                      final View view,
                                      final int position,
                                      final long id) {
        super.onListItemClick(list, view, position, id);

        final Task task = mAdapter.getItem(position);
        if (((Checkable) view).isChecked()) {
            mController.open(task);
        } else {
            mController.close(task);
        }
    }

    public final void show(final Collection<Task> tasks) {
        mAdapter.setNotifyOnChange(false);
        mAdapter.clear();
        for (final Task task : tasks) {
            mAdapter.add(task);
        }
        mAdapter.notifyDataSetChanged();

        setListShown(true);
    }

    @Override
    public final void onAttach(final Activity activity) {
        super.onAttach(activity);
        if (!(activity instanceof Controller)) {
            throw new IllegalStateException("Activity must implement TasksList's controller.");
        }
        mController = (Controller) activity;
        mAdapter = new Adapter(activity);
        setListAdapter(mAdapter);
    }

    @Override
    public final void onDetach() {
        setListAdapter(null);
        mAdapter = null;
        mController = DUMMY_CONTROLLER;
        super.onDetach();
    }

    public interface Controller {

        void edit(final Task task);

        void open(final Task task);

        void close(final Task task);
    }

    private static final Controller DUMMY_CONTROLLER = new Controller() {

        @Override
        public void edit(final Task task) {/* do nothing */}

        @Override
        public void open(final Task task) {/* do nothing */}

        @Override
        public void close(final Task task) {/* do nothing */}
    };

    private static class Adapter extends ArrayAdapter<Task> {

        private Adapter(final Activity activity) {
            super(activity, R.layout.list_item);
        }

        @Override
        public final View getView(final int position,
                                  final View convertView,
                                  @NonNull final ViewGroup parent) {
            final ListItem view = (ListItem) super.getView(position, convertView, parent);

            if (view != null) {
                final Task task = getItem(position);
                view.setText(task.getTitle());
                view.setChecked(task.isFinished());
            }

            return view;
        }
    }
}


text:
		The IDM tools should only be used for informational purposes only - IE
		as an indicator that a user may be logged in.

	    Until the login server can start sessions for the end-user, applications
	    using CAS/SSO can tell the UNL template that a user is logged in. This is
	    started by calling the WDN.idm.displayNotice(); method
	    with the username (uid) of the user that is currently logged in.

		Click here to
		call WDN.idm.displayNotice('bbieber2'), indicating Brett Bieber is logged in.

	    By default the logout URL will end the session with the CAS server at
	    login.unl.edu. This URL can be customized so the session with the current
	    application can be ended. To customize the logout URL, use
	    WDN.idm.setLogoutURL('?logout');

Complete Example:

<script type="text/javascript">
    WDN.idm.displayNotice('bbieber2');
    WDN.idm.setLogoutURL('?logout');
</script>

Note

	    Cookies are used to indicate whether log in notification should be
	    displayed to the end user. As a result, this feature will only work for
	    websites containing .unl.edu within the domain portion of the
	    URL.


text: assert(new Boolean(false) / new String("2") === 0)


text:
// Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Linq;

namespace Nuke.Common.Tools.MSpec
{
    public partial class MSpecSettings
    {
        private string GetProcessToolPath()
        {
            return MSpecTasks.GetToolPath();
        }
    }
}


text:
<?xml version="1.0"?>
<ruleset name="Lolita Standards">
    <description>A custom set of code standard rules to check for WordPress themes based on LolitaFramework.</description>

    <!-- Include the WordPress ruleset, with space for exclusions if necessary. -->
    <rule ref="PSR2">
        <exclude name="PSR1.Methods.CamelCapsMethodName.NotCamelCaps" />
    </rule>
</ruleset>


text:
# *ProductGroups* are used for creating and managing sets of products.
# Product group can be either anonymous(adhoc) or named.
#
# Anonymous Product groups are created by combining product scopes generated from url
# in 2 formats:
#
#   /t/*taxons/s/name_of_scope/comma_separated_arguments/name_of_scope_that_doesn_take_any//order
#   */s/name_of_scope/comma_separated_arguments/name_of_scope_that_doesn_take_any//order
#
# Named product groups can be created from anonymous ones, lub from another named scope
# (using ProductGroup.from_url method).
# Named product groups have pernament urls, that don't change even after changes
# to scopes are made, and come in two types.
#
#   /t/*taxons/pg/named_product_group
#   */pg/named_product_group
#
# first one is used for combining named scope with taxons, named product group can
# have #in_taxon or #taxons_name_eq scope defined, result should combine both
# and return products that exist in both taxons.
#
# ProductGroup#dynamic_products returns chain of named scopes generated from order and
# product scopes. So you can do counting, calculations etc, on resulted set of products,
# without retriving all records.
#
# ProductGroup operates on named scopes defined for product in Scopes::Product,
# or generated automatically by Searchlogic
#
class ProductGroup < ActiveRecord::Base
  validates_presence_of :name
  validates_associated :product_scopes

  before_save :set_permalink
  after_save :update_memberships

  has_and_belongs_to_many :cached_products, :class_name => "Product"
  # name
  has_many :product_scopes
  accepts_nested_attributes_for :product_scopes

  # Testing utility: creates new *ProductGroup* from search permalink url.
  # Follows conventions for accessing PGs from URLs, as decoded in routes
  def self.from_url(url)
    pg = nil;
    case url
    when /\/t\/(.+?)\/s\/(.+)/  then taxons = $1; attrs = $2;
    when /\/t\/(.+?)\/pg\/(.+)/ then taxons = $1; pg_name = $2;
    when /(.*?)\/s\/(.+)/       then attrs = $2;
    when /(.*?)\/pg\/(.+)/      then pg_name = $2;
    else                        return(nil)
    end

    if pg_name && opg = ProductGroup.find_by_permalink(pg_name)
      pg = new.from_product_group(opg)
    elsif attrs
      attrs = url.split("/")
      pg = new.from_route(attrs)
    end
    taxon = taxons && taxons.split("/").last
    pg.add_scope("in_taxon", taxon) if taxon

    pg
  end

  def from_product_group(opg)
    self.product_scopes = opg.product_scopes.map{|ps|
      ps = ps.clone;
      ps.product_group_id = nil;
      ps.product_group = self;
      ps
    }
    self
  end

  def from_route(attrs)
    self.order_scope = attrs.pop if attrs.length % 2 == 1
    attrs.each_slice(2) do |scope|
      next unless Product.condition?(scope.first)
      add_scope(scope.first, scope.last.split(","))
    end
    self
  end

  def from_search(search_hash)
    search_hash.each_pair do |scope_name, scope_attribute|
      add_scope(scope_name, scope_attribute)
    end

    self
  end

  def add_scope(scope_name, arguments=[])
    self.product_scopes << ProductScope.new({
        :name => scope_name.to_s,
        :arguments => [*arguments]
      })
    self
  end

  def apply_on(scopish, use_order = true)
    # There's bug in AR, it doesn't merge :order, instead it takes order
    # from first nested_scope so we have to apply ordering FIRST.
    # see #2253 on rails LH
    base_product_scope = scopish
    if use_order && !self.order_scope.blank? && Product.condition?(self.order_scope)
      base_product_scope = base_product_scope.send(self.order_scope)
    end

    return self.product_scopes.reject {|s|
             s.is_ordering?
           }.inject(base_product_scope){|result, scope|
             scope.apply_on(result)
           }
  end

  # returns chain of named scopes generated from order scope and product scopes.
  def dynamic_products(use_order = true)
    apply_on(Product.scoped(nil), use_order)
  end

  # Does the final ordering if requested
  # TODO: move the order stuff out of the above - is superfluous now
  def products(use_order = true)
    cached_group = Product.in_cached_group(self)
    if cached_group.limit(1).blank?
      dynamic_products(use_order)
    elsif !use_order
      cached_group
    else
      product_scopes.select {|s|
        s.is_ordering?
      }.inject(cached_group) {|res,order|
        order.apply_on(res)
      }
    end
  end

  def include?(product)
    res = apply_on(Product.id_equals(product.id), false)
    res.count > 0
  end

  def scopes_to_hash
    result = {}
    self.product_scopes.each do |scope|
      result[scope.name] = scope.arguments
    end
    result
  end

  # generates ProductGroup url
  def to_url
    if (new_record? || name.blank?)
      result = ""
      result+= self.product_scopes.map{|ps|
        [ps.name, ps.arguments.join(",")]
      }.flatten.join('/')
      result+= self.order_scope if self.order_scope

      result
    else
      name.to_url
    end
  end

  def set_permalink
    self.permalink = self.name.to_url
  end

  def update_memberships
    # wipe everything directly to avoid expensive in-rails sorting
    ActiveRecord::Base.connection.execute "DELETE FROM product_groups_products WHERE product_group_id = #{self.id}"

    # and generate the new group entirely in SQL
    ActiveRecord::Base.connection.execute "INSERT INTO product_groups_products #{dynamic_products(false).scoped(:select => "products.id, #{self.id}").to_sql}"
  end

  def generate_preview(size = Spree::Config[:admin_pgroup_preview_size])
    count = self.class.count_by_sql ["SELECT COUNT(*) FROM product_groups_products WHERE product_groups_products.product_group_id = ?", self]

    return count, products.limit(size)
  end

  def to_s
    "<ProductGroup" + (id && "[#{id}]").to_s + ":'#{to_url}'>"
  end

  def order_scope
    if scope = product_scopes.detect {|s| s.is_ordering?}
      scope.name
    end
  end
  def order_scope=(scope_name)
    if scope = product_scopes.detect {|s| s.is_ordering?}
      scope.update_attribute(:name, scope_name)
    else
      self.product_scopes.build(:name => scope_name, :arguments => [])
    end
  end

end


text:
@import UIKit;
#else
@import AppKit;
#endif

#import "MAIEnums.h"
#import "MAIDeclarations.h"

NS_ASSUME_NONNULL_BEGIN

@protocol MAITextStorageProtocol
-(void)addLayoutManager:(id<MAILayoutManagerProtocol>)aLayoutManager;
-(void)removeLayoutManager:(id<MAILayoutManagerProtocol>)aLayoutManager;
-(void)edited:(MAITextStorageEditActions)editedMask range:(NSRange)editedRange changeInLength:(NSInteger)delta;
-(void)processEditing;
-(void)invalidateAttributesInRange:(NSRange)range;
-(void)ensureAttributesAreFixedInRange:(NSRange)range;
@property(readonly, getter=layoutManagers) NSArray<MAILayoutManager*>* layoutManagers;
@property(readonly, getter=editedMask) MAITextStorageEditActions editedMask;
@property(readonly, getter=editedRange) NSRange editedRange;
@property(readonly, getter=changeInLength) NSInteger changeInLength;
@property(nullable, setter=setDelegate:, getter=delegate) id <MAITextStorageDelegate> delegate;
@property(readonly, getter=fixesAttributesLazily) BOOL fixesAttributesLazily;

#if TARGET_OS_IPHONE
#else
#endif

@end

#if TARGET_OS_IPHONE
@interface MAITextStorage : NSTextStorage<MAITextStorageProtocol>
#else
@interface MAITextStorage : NSTextStorage<MAITextStorageProtocol>
#endif
@end

NS_ASSUME_NONNULL_END

#pragma clang diagnostic pop


text:
/**
 * @brief SMTP client test routine
 * @return Error code
 **/

#include "shared.h"
#include "yarrow.h"
#include "alarmSetting.h"
#include "http/http_server.h"
#include "str.h"

error_t sendAlarmMail() {
    error_t error;
    if (appSettings.Notifications[NOTIFICATION_ANALOG].enable) {
        getCurrentTime();

        //Authentication information
        SmtpAuthInfo authInfo;
        authInfo.interface = NULL;
        authInfo.serverName = appSettings.EmailSettings.serverName; //SMTP server name
        authInfo.serverPort = appSettings.EmailSettings.serverPort; //SMTP server port
        authInfo.userName = appSettings.EmailSettings.userName; //User name
        authInfo.password = appSettings.EmailSettings.passWord; //Password
        authInfo.useTls = appSettings.EmailSettings.useTls; //Use STARTTLS rather than implicit TLS
        authInfo.prngAlgo = YARROW_PRNG_ALGO; //PRNG algorithm
        authInfo.prngContext = &appSettings.yarrowContext; //PRNG context

        char* subject;
        subject = pvPortMalloc(256);
        char valueBuffer[10];
        getAnalogInputInString(valueBuffer);
        sprintf(subject, "[%s] analog alarm (%s V)", appSettings.CardName,valueBuffer);

        SmtpMailAddr recipients[4];

        int recipientCount = CreateMailAddressFromString(appSettings.Notifications[NOTIFICATION_ANALOG].mail.recipients, recipients);
        static SmtpMail mail;
        mail.from.name = NULL;
        mail.from.addr = appSettings.EmailSettings.userName;
        mail.from.type = SMTP_RCPT_TYPE_TO;
        mail.recipients = recipients;
        mail.recipientCount = recipientCount; //Recipient count
        mail.dateTime = "NOW"; //Date
        mail.subject = subject; //Subject
        mail.body = "This is an automatically generated mail by the VM204 card";

        error = smtpSendMail(&authInfo, &mail);
        vPortFree(subject);
        int i;
        for (i = 0; i < recipientCount; i++) {
            vPortFree(recipients[i].addr);
        }
    } else {
        return ERROR_NOT_FOUND;
    }
    //Return status code
    return error;
}

int CreateMailAddressFromString(char * string, SmtpMailAddr* recipients) {
    char cpy[255];
    char* cptr;
    int recipient = 0;

    strcpy(cpy, string);
    cptr = strtok(cpy, ";");
    do {
        recipients[recipient].name = NULL;
        recipients[recipient].addr = strDuplicate(cptr);
        recipients[recipient].type = SMTP_RCPT_TYPE_TO;
        recipient++;
        cptr = strtok(NULL, ";");
    } while (cptr != NULL);
    return recipient;
}

error_t sendBootMail() {
    error_t error;

    getCurrentTime();

    //Authentication information
    SmtpAuthInfo authInfo;
    authInfo.interface = NULL;
    authInfo.serverName = appSettings.EmailSettings.serverName; //SMTP server name
    authInfo.serverPort = appSettings.EmailSettings.serverPort; //SMTP server port
    authInfo.userName = appSettings.EmailSettings.userName; //User name
    authInfo.password = appSettings.EmailSettings.passWord; //Password
    authInfo.useTls = appSettings.EmailSettings.useTls; //Use STARTTLS rather than implicit TLS
    authInfo.prngAlgo = YARROW_PRNG_ALGO; //PRNG algorithm
    authInfo.prngContext = &appSettings.yarrowContext; //PRNG context

    char* subject;
    subject = pvPortMalloc(128);

    sprintf(subject, "[%s] %s has booted up on %s (UTC)", appSettings.CardName, appSettings.CardName, formatDate(&appSettings.date, NULL));
    SmtpMailAddr recipients[4];

    int recipientCount = CreateMailAddressFromString(appSettings.Notifications[NOTIFICATION_BOOT].mail.recipients, recipients);
    static SmtpMail mail;
    mail.from.name = NULL;
    mail.from.addr = appSettings.EmailSettings.userName;
    mail.from.type = SMTP_RCPT_TYPE_TO;
    mail.recipients = recipients;
    mail.recipientCount = recipientCount; //Recipient count
    mail.dateTime = "NOW"; //Date
    mail.subject = subject; //Subject
    char ip[16];
    mail.body = pvPortMalloc(128);
    ipv4AddrToString(netGetDefaultInterface()->ipv4Config.addr, ip);
    sprintf(mail.body, "This is an automatically generated mail by the VM204 card\r\n%s", ip);

    error = smtpSendMail(&authInfo, &mail);
    if (subject)
        vPortFree(subject);
    if (mail.body)
        vPortFree(mail.body);
    int i;
    for (i = 0; i < recipientCount; i++) {
        if (recipients[i].addr)
            vPortFree(recipients[i].addr);
    }
    //Return status code
    return error;
}

error_t sendMail(int input, int reason) {
    error_t error;
    SmtpAuthInfo authInfo;
    authInfo.interface = NULL;
    authInfo.serverName = appSettings.EmailSettings.serverName; //SMTP server name
    authInfo.serverPort = appSettings.EmailSettings.serverPort; //SMTP server port
    authInfo.userName = appSettings.EmailSettings.userName; //User name
    authInfo.password = appSettings.EmailSettings.passWord; //Password
    authInfo.useTls = appSettings.EmailSettings.useTls; //Use STARTTLS rather than implicit TLS
    authInfo.prngAlgo = YARROW_PRNG_ALGO; //PRNG algorithm
    authInfo.prngContext = &appSettings.yarrowContext; //PRNG context

    if (appSettings.Notifications[input + 4].enable && (reason == FALLING)) {
        getCurrentTime();
        char* subject;
        subject = pvPortMalloc(128);
        SmtpMailAddr recipients[4];
        int recipientCount = 0;

        sprintf(subject, SUBJECT_INPUT_FALLING, appSettings.CardName, appSettings.IoSettings.inputs[input].Name, formatDate(&appSettings.date, NULL));
        recipientCount = CreateMailAddressFromString(appSettings.Notifications[input + 4].mail.recipients, recipients);

        static SmtpMail mail;
        mail.from.name = NULL;
        mail.from.addr = appSettings.EmailSettings.userName;
        mail.recipients = recipients;
        mail.recipientCount = recipientCount;
        mail.dateTime = "NOW"; //Date
        mail.subject = subject; //Subject
        mail.body = "This is an automatically generated mail by the VM204 card";
        error = smtpSendMail(&authInfo, &mail);
        if (subject)
            vPortFree(subject);
        int i;
        for (i = 0; i < recipientCount; i++) {
            if (recipients[i].addr)
                vPortFree(recipients[i].addr);
        }
    } else if (appSettings.Notifications[input].enable && (reason == RISING)) {
        getCurrentTime();
        char* subject;
        subject = pvPortMalloc(128);
        SmtpMailAddr recipients[4];
        int recipientCount = 0;

        sprintf(subject, SUBJECT_INPUT_RISING, appSettings.CardName, appSettings.IoSettings.inputs[input].Name, formatDate(&appSettings.date, NULL));
        recipientCount = CreateMailAddressFromString(appSettings.Notifications[input].mail.recipients, recipients);

        static SmtpMail mail;
        mail.from.name = NULL;
        mail.from.addr = appSettings.EmailSettings.userName;
        mail.recipients = recipients;
        mail.recipientCount = recipientCount;
        mail.dateTime = "NOW"; //Date
        mail.subject = subject; //Subject
        mail.body = "This is an automatically generated mail by the VM204 card";
        error = smtpSendMail(&authInfo, &mail);
        vPortFree(subject);
        int i;
        for (i = 0; i < recipientCount; i++) {
            vPortFree(recipients[i].addr);
        }
    }

    //Return status code
    return error;
}

error_t sendTestMail(HttpConnection* connection ) {
    char *separator;
    char *property;
    char *value;
    char *p;
    SmtpMailAddr recipients[4];
    error_t error;
    uint_t i;
    uint_t j;
    uint_t n;
    char_t *buffer;

     //Authentication information
    SmtpAuthInfo authInfo;
    authInfo.interface = NULL;
    authInfo.serverName = appSettings.EmailSettings.serverName; //SMTP server name
    authInfo.serverPort = appSettings.EmailSettings.serverPort; //SMTP server port
    authInfo.userName = appSettings.EmailSettings.userName; //User name
    authInfo.password = appSettings.EmailSettings.passWord; //Password
    authInfo.useTls = appSettings.EmailSettings.useTls; //Use STARTTLS rather than implicit TLS
    authInfo.prngAlgo = YARROW_PRNG_ALGO; //PRNG algorithm
    authInfo.prngContext = &appSettings.yarrowContext; //PRNG context

    SmtpMailAddr recipient[1];
    recipient[0].name = NULL;
    recipient[0].addr = strDuplicate(appSettings.EmailSettings.userName);
    recipient[0].type = SMTP_RCPT_TYPE_TO;

    SmtpMail mail;
    mail.from.name = NULL;
    mail.from.addr = strDuplicate(appSettings.EmailSettings.userName);
    mail.from.type = SMTP_RCPT_TYPE_TO;
    mail.recipients = recipient;
    mail.recipientCount = 1; //Recipient count
    mail.dateTime = strDuplicate("NOW"); //Date
    mail.subject = strDuplicate("VM204 Test Mail"); //Subject

    mail.body =  strDuplicate("If you received this mail, everything is OK");

    //Send mail
    error = smtpSendMail(&authInfo, &mail);
    osFreeMem((void *)mail.from.addr);
    osFreeMem((void *)recipient[0].addr);
    osFreeMem((void *)mail.subject);
    osFreeMem((void *)mail.body);

    //Point to the scratch buffer
         buffer = connection->buffer + 384;

         char status[64] = "";

         //Format XML data
         if(error == NO_ERROR)
            strcpy(status,"Mail successfully sent");
         else if(error == ERROR_NAME_RESOLUTION_FAILED)
            strcpy(status,"Cannot resolve SMTP server name");
         else if(error == ERROR_AUTHENTICATION_FAILED)
            strcpy(status,"Authentication failed");
         else if(error == ERROR_UNEXPECTED_RESPONSE)
            strcpy(status,"Unexpected response from SMTP server");
         else
            sprintf(status, "Failed to send mail (error %d)", error);

         createMailStatus(buffer,status);
         n = strlen(buffer);

         //Format HTTP response header
         connection->response.version = connection->request.version;
         connection->response.statusCode = 200;
         connection->response.keepAlive = connection->request.keepAlive;
         connection->response.noCache = TRUE;
         connection->response.contentType = mimeGetType(".json");
         connection->response.chunkedEncoding = FALSE;
         connection->response.contentLength = n;

         //Send the header to the client
         error = httpWriteHeader(connection);
         //Any error to report?
         if(error) return error;

         //Send response body
         error = httpWriteStream(connection, buffer, n);
         //Any error to report?
         if(error) return error;

         //Properly close output stream
         error = httpCloseStream(connection);
         //Any error to report?
         osFreeMem((void *)mail.from.addr);
    osFreeMem((void *)recipient[0].addr);
    osFreeMem((void *)mail.subject);
    osFreeMem((void *)mail.body);
         return error;

}

void createMailStatus(char* buffer,char* status)
{
    sprintf(buffer,"{\"status\":\"%s\"}",status);
}


text:
namespace Rawr
{
    partial class FormEnterWowheadFilter
    {
        /// <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 Windows Form 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.textWowheadFilter = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.lblTextAddItemID = new System.Windows.Forms.Label();
            this.buttonCancel = new System.Windows.Forms.Button();
            this.buttonOK = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // textWowheadFilter
            //
            this.textWowheadFilter.Location = new System.Drawing.Point(12, 38);
            this.textWowheadFilter.Name = "textWowheadFilter";
            this.textWowheadFilter.Size = new System.Drawing.Size(296, 20);
            this.textWowheadFilter.TabIndex = 3;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 22);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(157, 13);
            this.label1.TabIndex = 2;
            this.label1.Text = "qu=4:5;sl=16;cr=82;crs=1;crv=0";
            //
            // lblTextAddItemID
            //
            this.lblTextAddItemID.AutoSize = true;
            this.lblTextAddItemID.Location = new System.Drawing.Point(12, 9);
            this.lblTextAddItemID.Name = "lblTextAddItemID";
            this.lblTextAddItemID.Size = new System.Drawing.Size(181, 13);
            this.lblTextAddItemID.TabIndex = 1;
            this.lblTextAddItemID.Text = "Enter the wowhead filter, for example";
            //
            // buttonCancel
            //
            this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.buttonCancel.Location = new System.Drawing.Point(152, 64);
            this.buttonCancel.Name = "buttonCancel";
            this.buttonCancel.Size = new System.Drawing.Size(75, 23);
            this.buttonCancel.TabIndex = 4;
            this.buttonCancel.Text = "Abbrechen";
            this.buttonCancel.UseVisualStyleBackColor = true;
            //
            // buttonOK
            //
            this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.buttonOK.Location = new System.Drawing.Point(233, 64);
            this.buttonOK.Name = "buttonOK";
            this.buttonOK.Size = new System.Drawing.Size(75, 23);
            this.buttonOK.TabIndex = 0;
            this.buttonOK.Text = "OK";
            this.buttonOK.UseVisualStyleBackColor = true;
            //
            // FormEnterWowheadFilter
            //
            this.AcceptButton = this.buttonOK;
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.CancelButton = this.buttonCancel;
            this.ClientSize = new System.Drawing.Size(320, 99);
            this.Controls.Add(this.textWowheadFilter);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.lblTextAddItemID);
            this.Controls.Add(this.buttonCancel);
            this.Controls.Add(this.buttonOK);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.Name = "FormEnterWowheadFilter";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Importier von RG-Datenbank Filter";
            this.Load += new System.EventHandler(this.FormEnterId_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox textWowheadFilter;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label lblTextAddItemID;
        private System.Windows.Forms.Button buttonCancel;
        private System.Windows.Forms.Button buttonOK;

    }
}


text:
package com.shanli.weixin.mp.recv;

import com.google.gson.Gson;
import com.shanli.weixin.bean.BaseResp;

/**
 * 微信消息基类
 *
 * @author alex
 *
 */
public class UserMsg extends BaseResp {
	private String openid;
	private String appid;
	private UserMsgTypeEnum type;
	private String msgType;
	private String toUserName;
	private String fromUserName;
	private Integer createTime;
	private String msgId;

	/**
	 * 微信用户的OpenID(仅开放平台模式)
	 *
	 * @return the openid
	 */
	public String getOpenid() {
		return openid;
	}

	/**
	 * 微信用户的OpenID(仅开放平台模式)
	 *
	 * @param openid
	 *            the openid to set
	 */
	public void setOpenid(String openid) {
		this.openid = openid;
	}

	/**
	 * 公众号mpAppId(仅开放平台模式)
	 *
	 * @return the appid
	 */
	public String getAppid() {
		return appid;
	}

	/**
	 * 公众号mpAppId(仅开放平台模式)
	 *
	 * @param appid
	 *            the appid to set
	 */
	public void setAppid(String appid) {
		this.appid = appid;
	}

	/**
	 * 消息类型Enum
	 *
	 * @param type
	 */
	public void setType(UserMsgTypeEnum type) {
		this.type = type;
	}

	/**
	 * 消息类型Enum
	 *
	 * @return the type
	 */
	public UserMsgTypeEnum getType() {
		return type;
	}

	/**
	 * 公众号原始ID
	 *
	 * @return the toUserName
	 */
	public String getToUserName() {
		return toUserName;
	}

	/**
	 * 公众号原始ID
	 *
	 * @param toUserName
	 *            the toUserName to set
	 */
	public void setToUserName(String toUserName) {
		this.toUserName = toUserName;
	}

	/**
	 * 发送方帐号(微信用户OpenID)
	 *
	 * @return the fromUserName
	 */
	public String getFromUserName() {
		return fromUserName;
	}

	/**
	 * 发送方帐号(微信用户OpenID)
	 *
	 * @param fromUserName
	 *            the fromUserName to set
	 */
	public void setFromUserName(String fromUserName) {
		this.fromUserName = fromUserName;
	}

	/**
	 * 消息创建时间 unix_timestamp
	 *
	 * @return the createTime
	 */
	public Integer getCreateTime() {
		return createTime;
	}

	/**
	 * 消息创建时间 unix_timestamp
	 *
	 * @param createTime
	 *            the createTime to set
	 */
	public void setCreateTime(Integer createTime) {
		this.createTime = createTime;
	}

	/**
	 * 消息类型
	 *
	 * @return the msgType
	 */
	public String getMsgType() {
		return msgType;
	}

	/**
	 * 消息类型
	 *
	 * @param msgType
	 *            the msgType to set
	 */
	public void setMsgType(String msgType) {
		this.msgType = msgType;
	}

	/**
	 * 消息id
	 *
	 * @return the msgId
	 */
	public String getMsgId() {
		return msgId;
	}

	/**
	 * 消息id
	 *
	 * @param msgId
	 *            the msgId to set
	 */
	public void setMsgId(String msgId) {
		this.msgId = msgId;
	}

	/*
	 * 转换为JSON字符串
	 *
	 */
	@Override
	public String toString() {
		return new Gson().toJson(this);
	}

}


text:
package com.alibaba.otter.manager.biz.config.datacolumnpair;

import java.util.List;
import java.util.Map;

import com.alibaba.otter.manager.biz.common.baseservice.GenericService;
import com.alibaba.otter.shared.common.model.config.data.ColumnPair;

/**
 * 类DataColumnPairService.java的实现描述:TODO 类实现描述
 *
 * @author simon 2012-4-20 下午4:07:47
 */
public interface DataColumnPairService extends GenericService<ColumnPair> {

    public List<ColumnPair> listByDataMediaPairId(Long dataMediaPairId);

    public Map<Long, List<ColumnPair>> listByDataMediaPairIds(Long... dataMediaPairIds);

    public void createBatch(List<ColumnPair> dataColumnPairs);

    public void removeByDataMediaPairId(Long dataMediaPairId);
}


text:
package syscall

import (
	"runtime"
	"unsafe"
)

type SysProcAttr struct {
	Chroot     string      // Chroot.
	Credential *Credential // Credential.
	Ptrace     bool        // Enable tracing.
	Setsid     bool        // Create session.
	// Setpgid sets the process group ID of the child to Pgid,
	// or, if Pgid == 0, to the new child's process ID.
	Setpgid bool
	// Setctty sets the controlling terminal of the child to
	// file descriptor Ctty. Ctty must be a descriptor number
	// in the child process: an index into ProcAttr.Files.
	// This is only meaningful if Setsid is true.
	Setctty bool
	Noctty  bool // Detach fd 0 from controlling terminal
	Ctty    int  // Controlling TTY fd
	// Foreground places the child process group in the foreground.
	// This implies Setpgid. The Ctty field must be set to
	// the descriptor of the controlling TTY.
	// Unlike Setctty, in this case Ctty must be a descriptor
	// number in the parent process.
	Foreground bool
	Pgid       int // Child's process group ID if Setpgid.
}

// Implemented in runtime package.
func runtime_BeforeFork()
func runtime_AfterFork()
func runtime_AfterForkInChild()

// Fork, dup fd onto 0..len(fd), and exec(argv0, argvv, envv) in child.
// If a dup or exec fails, write the errno error to pipe.
// (Pipe is close-on-exec so if exec succeeds, it will be closed.)
// In the child, this function must not acquire any locks, because
// they might have been locked at the time of the fork. This means
// no rescheduling, no malloc calls, and no new stack segments.
// For the same reason compiler does not race instrument it.
// The calls to RawSyscall are okay because they are assembly
// functions that do not grow the stack.
//
//go:norace
func forkAndExecInChild(argv0 *byte, argv, envv []*byte, chroot, dir *byte, attr *ProcAttr, sys *SysProcAttr, pipe int) (pid int, err Errno) {
	// Declare all variables at top in case any
	// declarations require heap allocation (e.g., err1).
	var (
		r1     Pid_t
		err1   Errno
		nextfd int
		i      int
	)

	// guard against side effects of shuffling fds below.
	// Make sure that nextfd is beyond any currently open files so
	// that we can't run the risk of overwriting any of them.
	fd := make([]int, len(attr.Files))
	nextfd = len(attr.Files)
	for i, ufd := range attr.Files {
		if nextfd < int(ufd) {
			nextfd = int(ufd)
		}
		fd[i] = int(ufd)
	}
	nextfd++

	// About to call fork.
	// No more allocation or calls of non-assembly functions.
	runtime_BeforeFork()
	r1, err1 = raw_fork()
	if err1 != 0 {
		runtime_AfterFork()
		return 0, err1
	}

	if r1 != 0 {
		// parent; return PID
		runtime_AfterFork()
		return int(r1), 0
	}

	// Fork succeeded, now in child.

	// Enable tracing if requested.
	if sys.Ptrace {
		err1 = raw_ptrace(_PTRACE_TRACEME, 0, 0, 0)
		if err1 != 0 {
			goto childerror
		}
	}

	// Session ID
	if sys.Setsid {
		err1 = raw_setsid()
		if err1 != 0 {
			goto childerror
		}
	}

	// Set process group
	if sys.Setpgid || sys.Foreground {
		// Place child in process group.
		err1 = raw_setpgid(0, sys.Pgid)
		if err1 != 0 {
			goto childerror
		}
	}

	if sys.Foreground {
		pgrp := Pid_t(sys.Pgid)
		if pgrp == 0 {
			pgrp = raw_getpid()
		}

		// Place process group in foreground.
		_, err1 = raw_ioctl_ptr(sys.Ctty, TIOCSPGRP, unsafe.Pointer(&pgrp))
		if err1 != 0 {
			goto childerror
		}
	}

	// Restore the signal mask. We do this after TIOCSPGRP to avoid
	// having the kernel send a SIGTTOU signal to the process group.
	runtime_AfterForkInChild()

	// Chroot
	if chroot != nil {
		err1 = raw_chroot(chroot)
		if err1 != 0 {
			goto childerror
		}
	}

	// User and groups
	if cred := sys.Credential; cred != nil {
		ngroups := len(cred.Groups)
		var groups unsafe.Pointer
		if ngroups > 0 {
			groups = unsafe.Pointer(&cred.Groups[0])
		}
		if !cred.NoSetGroups {
			err1 = raw_setgroups(ngroups, groups)
			if err1 != 0 {
				goto childerror
			}
		}
		err2 := Setgid(int(cred.Gid))
		if err2 != nil {
			err1 = err2.(Errno)
			goto childerror
		}
		err2 = Setuid(int(cred.Uid))
		if err2 != nil {
			err1 = err2.(Errno)
			goto childerror
		}
	}

	// Chdir
	if dir != nil {
		err1 = raw_chdir(dir)
		if err1 != 0 {
			goto childerror
		}
	}

	// Pass 1: look for fd[i] < i and move those up above len(fd)
	// so that pass 2 won't stomp on an fd it needs later.
	if pipe < nextfd {
		switch runtime.GOOS {
		case "netbsd":
			err1 = raw_dup3(pipe, nextfd, O_CLOEXEC)
			if err1 != 0 {
				goto childerror
			}
		default:
			err1 = raw_dup2(pipe, nextfd)
			if err1 != 0 {
				goto childerror
			}
			raw_fcntl(nextfd, F_SETFD, FD_CLOEXEC)
		}
		pipe = nextfd
		nextfd++
	}
	for i = 0; i < len(fd); i++ {
		if fd[i] >= 0 && fd[i] < int(i) {
			if nextfd == pipe { // don't stomp on pipe
				nextfd++
			}
			switch runtime.GOOS {
			case "netbsd":
				err1 = raw_dup3(fd[i], nextfd, O_CLOEXEC)
				if err1 != 0 {
					goto childerror
				}
			default:
				err1 = raw_dup2(fd[i], nextfd)
				if err1 != 0 {
					goto childerror
				}
				raw_fcntl(nextfd, F_SETFD, FD_CLOEXEC)
			}
			fd[i] = nextfd
			nextfd++
		}
	}

	// Pass 2: dup fd[i] down onto i.
	for i = 0; i < len(fd); i++ {
		if fd[i] == -1 {
			raw_close(i)
			continue
		}
		if fd[i] == int(i) {
			// dup2(i, i) won't clear close-on-exec flag on Linux,
			// probably not elsewhere either.
			_, err1 = raw_fcntl(fd[i], F_SETFD, 0)
			if err1 != 0 {
				goto childerror
			}
			continue
		}
		// The new fd is created NOT close-on-exec,
		// which is exactly what we want.
		err1 = raw_dup2(fd[i], i)
		if err1 != 0 {
			goto childerror
		}
	}

	// By convention, we don't close-on-exec the fds we are
	// started with, so if len(fd) < 3, close 0, 1, 2 as needed.
	// Programs that know they inherit fds >= 3 will need
	// to set them close-on-exec.
	for i = len(fd); i < 3; i++ {
		raw_close(i)
	}

	// Detach fd 0 from tty
	if sys.Noctty {
		_, err1 = raw_ioctl(0, TIOCNOTTY, 0)
		if err1 != 0 {
			goto childerror
		}
	}

	// Set the controlling TTY to Ctty
	if sys.Setctty {
		if TIOCSCTTY == 0 {
			err1 = ENOSYS
			goto childerror
		}
		_, err1 = raw_ioctl(sys.Ctty, TIOCSCTTY, 0)
		if err1 != 0 {
			goto childerror
		}
	}

	// Time to exec.
	err1 = raw_execve(argv0, &argv[0], &envv[0])

childerror:
	// send error code on pipe
	raw_write(pipe, (*byte)(unsafe.Pointer(&err1)), int(unsafe.Sizeof(err1)))
	for {
		raw_exit(253)
	}
}


text:
namespace content {

// The maximum number of bytes allowed in a presentation session message.
CONTENT_EXPORT extern const size_t kMaxPresentationSessionMessageSize;

}  // namespace content

#endif  // CONTENT_PUBLIC_COMMON_PRESENTATION_CONSTANTS_H_


text:
001
017
018    package org.apache.commons.configuration;
019
020    import java.util.Iterator;
021
022    /**
023     * Strict comparator for configurations.
024     *
025     * @since 1.0
026     *
027     * @author <a href="mailto:herve.quiroz@esil.univ-mrs.fr">Herve Quiroz</a>
028     * @author <a href="mailto:shapira@mpi.com">Yoav Shapira</a>
029     * @version $Revision: 439648 $, $Date: 2006-09-02 22:42:10 +0200 (Sa, 02. Sep 2006) $
030     */
031    public class StrictConfigurationComparator implements ConfigurationComparator
032    {
033        /**
034         * Create a new strict comparator.
035         */
036        public StrictConfigurationComparator()
037        {
038        }
039
040        /**
041         * Compare two configuration objects.
042         *
043         * @param a the first configuration
044         * @param b the second configuration
045         * @return true if keys from a are found in b and keys from b are
046         *         found in a and for each key in a, the corresponding value
047         *         is the sale in for the same key in b
048         */
049        public boolean compare(Configuration a, Configuration b)
050        {
051            if (a == null && b == null)
052            {
053                return true;
054            }
055            else if (a == null || b == null)
056            {
057                return false;
058            }
059
060            for (Iterator keys = a.getKeys(); keys.hasNext();)
061            {
062                String key = (String) keys.next();
063                Object value = a.getProperty(key);
064                if (!value.equals(b.getProperty(key)))
065                {
066                    return false;
067                }
068            }
069
070            for (Iterator keys = b.getKeys(); keys.hasNext();)
071            {
072                String key = (String) keys.next();
073                Object value = b.getProperty(key);
074                if (!value.equals(a.getProperty(key)))
075                {
076                    return false;
077                }
078            }
079
080            return true;
081        }
082    }


text:
package com.example.android.activenotifications;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.StatusBarNotification;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.android.common.logger.Log;

/**
 * A fragment that allows notifications to be enqueued.
 */
public class ActiveNotificationsFragment extends Fragment {

    /**
     * The request code can be any number as long as it doesn't match another request code used
     * in the same app.
     */
    private static final int REQUEST_CODE = 2323;

    private static final String TAG = "ActiveNotificationsFragment";

    private static final String NOTIFICATION_GROUP =
            "com.example.android.activenotifications.notification_type";

    private static final int NOTIFICATION_GROUP_SUMMARY_ID = 1;

    private NotificationManager mNotificationManager;

    private TextView mNumberOfNotifications;

    // Every notification needs a unique ID otherwise the previous one would be overwritten. This
    // variable is incremented when used.
    private static int sNotificationId = NOTIFICATION_GROUP_SUMMARY_ID + 1;

    private PendingIntent mDeletePendingIntent;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_notification_builder, container, false);
    }

    @Override
    public void onResume() {
        super.onResume();
        updateNumberOfNotifications();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mNotificationManager = (NotificationManager) getActivity().getSystemService(
                Context.NOTIFICATION_SERVICE);
        mNumberOfNotifications = (TextView) view.findViewById(R.id.number_of_notifications);

        // Supply actions to the button that is displayed on screen.
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.add_notification: {
                        addNotificationAndUpdateSummaries();
                        break;
                    }
                }
            }
        };
        view.findViewById(R.id.add_notification).setOnClickListener(onClickListener);

        // [BEGIN create_pending_intent_for_deletion]
        // Create a PendingIntent to be fired upon deletion of a Notification.
        Intent deleteIntent = new Intent(ActiveNotificationsActivity.ACTION_NOTIFICATION_DELETE);
        mDeletePendingIntent = PendingIntent.getBroadcast(getActivity(),
                REQUEST_CODE, deleteIntent, 0);
        // [END create_pending_intent_for_deletion]
    }

    /**
     * Adds a new {@link Notification} with sample data and sends it to the system.
     * Then updates the current number of displayed notifications for this application and
     * creates a notification summary if more than one notification exists.
     */
    private void addNotificationAndUpdateSummaries() {
        // [BEGIN create_notification]
        // Create a Notification and notify the system.
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(getActivity())
                .setSmallIcon(R.mipmap.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.sample_notification_content))
                .setAutoCancel(true)
                .setDeleteIntent(mDeletePendingIntent)
                .setGroup(NOTIFICATION_GROUP);

        final Notification notification = builder.build();
        mNotificationManager.notify(getNewNotificationId(), notification);
        // [END create_notification]
        Log.i(TAG, "Add a notification");

        updateNotificationSummary();
        updateNumberOfNotifications();
    }

    /**
     * Adds/updates/removes the notification summary as necessary.
     */
    protected void updateNotificationSummary() {
        int numberOfNotifications = getNumberOfNotifications();

        if (numberOfNotifications > 1) {
            // Add/update the notification summary.
            String notificationContent = getString(R.string.sample_notification_summary_content,
                    numberOfNotifications);
            final NotificationCompat.Builder builder = new NotificationCompat.Builder(getActivity())
                    .setSmallIcon(R.mipmap.ic_notification)
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .setSummaryText(notificationContent))
                    .setGroup(NOTIFICATION_GROUP)
                    .setGroupSummary(true);
            final Notification notification = builder.build();
            mNotificationManager.notify(NOTIFICATION_GROUP_SUMMARY_ID, notification);
        } else {
            // Remove the notification summary.
            mNotificationManager.cancel(NOTIFICATION_GROUP_SUMMARY_ID);
        }
    }

    /**
     * Requests the current number of notifications from the {@link NotificationManager} and
     * display them to the user.
     */
    protected void updateNumberOfNotifications() {
        final int numberOfNotifications = getNumberOfNotifications();
        mNumberOfNotifications.setText(getString(R.string.active_notifications,
                numberOfNotifications));
        Log.i(TAG, getString(R.string.active_notifications, numberOfNotifications));
    }

    /**
     * Retrieves a unique notification ID.
     */
    public int getNewNotificationId() {
        int notificationId = sNotificationId++;

        // Unlikely in the sample, but the int will overflow if used enough so we skip the summary
        // ID. Most apps will prefer a more deterministic way of identifying an ID such as hashing
        // the content of the notification.
        if (notificationId == NOTIFICATION_GROUP_SUMMARY_ID) {
            notificationId = sNotificationId++;
        }
        return notificationId;
    }

    private int getNumberOfNotifications() {
        // [BEGIN get_active_notifications]
        // Query the currently displayed notifications.
        final StatusBarNotification[] activeNotifications = mNotificationManager
                .getActiveNotifications();
        // [END get_active_notifications]

        // Since the notifications might include a summary notification remove it from the count if
        // it is present.
        for (StatusBarNotification notification : activeNotifications) {
            if (notification.getId() == NOTIFICATION_GROUP_SUMMARY_ID) {
                return activeNotifications.length - 1;
            }
        }
        return activeNotifications.length;
    }
}


text:
git-rebase-merge
============

A bash script to rebase and merge a Git topic branch to current branch.

### Usage

```sh
# Assuming current branch is master,
# it reabses a list of topic branches on top of master and then merge into master
$ git-rebase-merge topic-branch1 topic-branch2 ...
```

### Install

```sh
$ curl https://raw.github.com/jingweno/git-rebase-merge/master/install | sh
```

### Uninstall

```sh
$ curl https://raw.github.com/jingweno/git-rebase-merge/master/uninstall | sh
```

### License

See LICENSE


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Phebalium gracile C.T.White

### Remarks
null


text:
This tool provides benchmark information for processes.
The tool will gathering metrics from a given command, then average them out over the total runs.

It currently shows only time, process, cpu, and memory used but might be extended in the future.

This tool was created to provide an objective and reproducible way of benchmarking process
performance.

Given a process (or its source code), process inputs and environment, keeping two of these elements
constant while varying the third should allow for meaningful benchmarks over time.

In the context of the DevKit, we publish many CLI tools and have access to their source code.
By tracking tool resource usage we can catch performance regressions or improvements on our CI.

## STABILITY AND SUPPORT DISCLAIMER

This package is not currently stable. Usage, output and API may change at any time.
Support is not ensured.

## Installation

You can install the benchmark tool via `npm install -g benchmark` for a global install, or without
`-g` for a local install.
Installing globally gives you access to the `benchmark` binary in your `PATH`.

## CLI Usage

Call the `benchmark` binary, followed by options, then double dash, then the command to benchmark.

For more information on the available options, run `benchmark --help`:
```
$ benchmark --help
[benchmark] benchmark [options] -- [command to benchmark]

Collects process stats from running the command.

Options:
    --help                    Show this message.
    (... other available options)

Example:
    benchmark --iterations=3 -- node my-script.js
```

## Example

Given the naive implementation of a fibonacci number calculator below:
```
// fibonacci.js
const fib = (n) => n > 1 ? fib(n - 1) + fib(n - 2) : n;
console.log(fib(parseInt(process.argv[2])));
```

Run `benchmark -- node fibonacci.js 40` to benchmark calculating the 40th fibonacci number:

```
$ benchmark -- node fibonacci.js 40
[benchmark] Benchmarking process over 5 iterations, with up to 5 retries.
[benchmark]   node fibonacci.js 40 (at D:\sandbox\latest-project)
[benchmark] Process Stats
[benchmark]   Elapsed Time: 2365.40 ms (2449.00, 2444.00, 2357.00, 2312.00, 2265.00)
[benchmark]   Average Process usage: 1.00 process(es) (1.00, 1.00, 1.00, 1.00, 1.00)
[benchmark]   Peak Process usage: 1.00 process(es) (1.00, 1.00, 1.00, 1.00, 1.00)
[benchmark]   Average CPU usage: 4.72 % (5.03, 4.86, 4.50, 4.50, 4.69)
[benchmark]   Peak CPU usage: 23.40 % (25.00, 23.40, 21.80, 21.80, 25.00)
[benchmark]   Average Memory usage: 22.34 MB (22.32, 22.34, 22.34, 22.35, 22.35)
[benchmark]   Peak Memory usage: 22.34 MB (22.32, 22.34, 22.34, 22.35, 22.35)
```

## Example in watch mode

`watch-script` accepts a node script when using the CLI. When using the API you can provide a `Command` instance.

```
benchmark --verbose --watch-timeout 10000 --watch-matcher "Compiled successfully" --watch-script watch-script.js -- ng serve
[benchmark] Benchmarking process over 5 iterations, with up to 5 retries.
[benchmark]   ng serve (at D:\sandbox\latest-project)
[benchmark] Process Stats
[benchmark]   Elapsed Time: 470.40 ms (820.00, 557.00, 231.00, 509.00, 235.00)
[benchmark]   Average Process usage: 2.00 process(es) (2.00, 2.00, 2.00, 2.00, 2.00)
[benchmark]   Peak Process usage: 2.00 process(es) (2.00, 2.00, 2.00, 2.00, 2.00)
[benchmark]   Average CPU usage: 33.77 % (31.27, 0.00, 101.70, 35.90, 0.00)
[benchmark]   Peak CPU usage: 59.72 % (125.10, 0.00, 101.70, 71.80, 0.00)
[benchmark]   Average Memory usage: 665.49 MB (619.84, 657.17, 669.47, 685.19, 695.76)
[benchmark]   Peak Memory usage: 672.44 MB (639.87, 661.04, 669.47, 689.66, 702.14)
```

## API Usage

You can also use the benchmarking API directly:

```
import { Command, defaultStatsCapture, runBenchmark } from '@angular-devkit/benchmark';

const command = new Command('node', ['fibonacci.js', '40']);
const captures = [defaultStatsCapture];

runBenchmark({ command, command }).subscribe(results => {
  // results is:[{
  //   "name": "Process Stats",
  //   "metrics": [{
  //     "name": "Elapsed Time", "unit": "ms", "value": 1883.6,
  //     "componentValues": [1733, 1957, 1580, 1763, 2385]
  //   }, {
  //     "name": "Average Process usage", "unit": "process(es)", "value": 1,
  //     "componentValues": [1, 1, 1, 1, 1]
  //   }, {
  //     "name": "Peak Process usage", "unit": "process(es)", "value": 1,
  //     "componentValues": [1, 1, 1, 1, 1]
  //   }, {
  //     "name": "Average CPU usage", "unit": "%", "value": 3.0855555555555556,
  //     "componentValues": [1.9625, 1.9500000000000002, 1.9500000000000002, 4.887499999999999, 4.677777777777778]
  //   }, {
  //     "name": "Peak CPU usage", "unit": "%", "value": 19.380000000000003,
  //     "componentValues": [15.7, 15.6, 15.6, 25, 25]
  //   }, {
  //     "name": "Average Memory usage", "unit": "MB", "value": 22.364057600000002,
  //     "componentValues": [22.383104, 22.332416, 22.401024, 22.355968, 22.347776]
  //   }, {
  //     "name": "Peak Memory usage", "unit": "MB", "value": 22.3649792,
  //     "componentValues": [22.384639999999997, 22.335487999999998, 22.401024, 22.355968, 22.347776]
  //   }]
  // }]
});
```

A good example of API usage is the `main` binary itself, found in `./src/main.ts`.
We recommend using TypeScript to get full access to the interfaces included.


text:
Change Log
======

*Jason Gwartz*

v0.4
----

- Fixed a bug where 'repairs this hour' didn't clear and update
- Fixed a bug where multiple 'Cancel' and 'CONFIRM' dialogs would appear
- Fixed a bug which occurred when the TAT would go past midnight
- Added 'handover' functionality to track how many repairs are left at the end of each day
- Added a much-requested feature - the 'next' time estimates are included in the GR window
- Added extra time to Display-type repairs
- Added a rounding time function to accomodate the extra display repair time


text:
Capybara.register_driver :selenium_with_firebug do |app|
  Capybara::Selenium::Driver
  profile = Selenium::WebDriver::Firefox::Profile.new
  profile.add_extension(File.expand_path("../firebug-1.11.4.xpi", __FILE__))
  profile.add_extension(File.expand_path("../firepath-0.9.7-fx.xpi", __FILE__))

  # Prevent "Welcome!" tab
  profile["extensions.firebug.currentVersion"] = "999"

  # Enable for all sites.
  profile["extensions.firebug.allPagesActivation"] = "on"

  # Enable all features.
  ['console', 'net', 'script'].each do |feature|
    profile["extensions.firebug.#{feature}.enableSites"] = true
  end

  profile['intl.accept_languages'] = 'en,en-us'

  Capybara::Selenium::Driver.new(app,
                                 :browser => :firefox,
                                 :profile => profile)
end

Before '@firebug' do
  Capybara.current_driver = :selenium_with_firebug
end


text:
def cria_excecao(classe, mensagem)
  eval "class #{classe}; def initialize; super('#{mensagem}'); end; end"
end

cria_excecao("FeriadoMesInvalidoError < ArgumentError", "O mês deve ser um número e estar entre 01 e 12")
cria_excecao("FeriadoDiaInvalidoError < ArgumentError", "O mês deve ser um número e estar entre 01 e 31")
cria_excecao("FeriadoParserDiretorioInvalidoError < ArgumentError", "Só é possivel fazer parser de um diretorio contendo os arquivos yml.")
cria_excecao("FeriadoParserDiretorioVazioError < ArgumentError", "Não existe nenhum yml no diretorio.")
cria_excecao("FeriadoParserMetodoInvalido < ArgumentError", "Quando for usado o parametro metodo não deve exitir dia nem mês.")