text:
require "rails_helper"

RSpec.describe MostRecentlyUsedSearcher do
  describe "#recently_used_facilities" do
    let(:account) { create(:setup_account, owner: user) }
    let(:facilities) { products.map(&:facility) }
    let(:limit) { 5 }
    let(:products) { create_list(:setup_item, 6) }
    let(:user) { create(:user) }
    let(:recently_used_facilities) { MostRecentlyUsedSearcher.new(user).recently_used_facilities(limit) }

    context "when the user has no orders" do
      it { expect(recently_used_facilities).to be_empty }
    end

    context "when the user has orders" do
      let!(:old_order) { create(:setup_order, :purchased, account: account, product: products.first, user: user, ordered_at: 1.week.ago) }
      let!(:new_order) { create(:setup_order, :purchased, account: account, product: products.second, user: user, ordered_at: 1.day.ago) }
      let!(:unpurchased_order) { create(:setup_order, account: account, product: products.third, user: user) }

      it "returns facilities that the user has ordered from" do
        expect(recently_used_facilities).to contain_exactly(new_order.facility, old_order.facility)
      end

      context "when there are orders in more facilities than the limit" do
        before(:each) do
          products.each_with_index do |product, i|
            create(:setup_order, :purchased, account: account, product: product, user: user, ordered_at: i.days.ago)
          end
        end

        it "returns only 5 facilities" do
          expect(recently_used_facilities.length).to eq 5
        end
      end

    end
  end

  describe "#recently_used_products" do
    let(:account) { create(:setup_account, owner: user) }
    let(:facilities) { products.map(&:facility) }
    let(:limit) { 5 }
    let(:products) { create_list(:setup_item, 6) }
    let(:user) { create(:user) }
    let(:recently_used_products) { MostRecentlyUsedSearcher.new(user).recently_used_products(limit) }

    context "when the user has no orders" do
      it { expect(recently_used_products).to be_empty }
    end

    context "when the user has orders" do
      let!(:old_order) { create(:setup_order, :purchased, account: account, product: products.first, user: user, ordered_at: 1.week.ago) }
      let!(:new_order) { create(:setup_order, :purchased, account: account, product: products.second, user: user, ordered_at: 1.day.ago) }
      let!(:unpurchased_order) { create(:setup_order, account: account, product: products.third, user: user) }

      it "returns products that the user has ordered" do
        expect(recently_used_products).to contain_exactly(new_order.order_details.first.product, old_order.order_details.first.product)
      end

      context "when there are more recently used products than the limit" do
        before(:each) do
          products.each_with_index do |product, i|
            create(:setup_order, :purchased, account: account, product: product, user: user, ordered_at: i.days.ago)
          end
        end

        it "returns only 5 products" do
          expect(recently_used_products.length).to eq 5
        end
      end

    end
  end

end


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/attestation/tpm_challenge_key.h"

#include <memory>
#include <string>
#include <utility>

#include "base/bind.h"
#include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
#include "chrome/browser/ash/attestation/tpm_challenge_key_result.h"
#include "chrome/browser/ash/attestation/tpm_challenge_key_subtle.h"
#include "chrome/common/pref_names.h"
#include "chromeos/ash/components/dbus/constants/attestation_constants.h"
#include "components/pref_registry/pref_registry_syncable.h"

class Profile;
class AttestationFlow;

namespace ash {
namespace attestation {

//========================= TpmChallengeKeyFactory =============================

TpmChallengeKey* TpmChallengeKeyFactory::next_result_for_testing_ = nullptr;

// static
std::unique_ptr<TpmChallengeKey> TpmChallengeKeyFactory::Create() {
  if (UNLIKELY(next_result_for_testing_)) {
    std::unique_ptr<TpmChallengeKey> result(next_result_for_testing_);
    next_result_for_testing_ = nullptr;
    return result;
  }

  return std::make_unique<TpmChallengeKeyImpl>();
}

// static
void TpmChallengeKeyFactory::SetForTesting(
    std::unique_ptr<TpmChallengeKey> next_result) {
  // unique_ptr itself cannot be stored in a static variable because of its
  // complex destructor.
  next_result_for_testing_ = next_result.release();
}

//=========================== TpmChallengeKeyImpl ==============================

void TpmChallengeKey::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterBooleanPref(prefs::kAttestationEnabled, false);
}

TpmChallengeKeyImpl::TpmChallengeKeyImpl() {
  tpm_challenge_key_subtle_ = TpmChallengeKeySubtleFactory::Create();
}

TpmChallengeKeyImpl::TpmChallengeKeyImpl(
    AttestationFlow* attestation_flow_for_testing,
    MachineCertificateUploader* certificate_uploader_for_testing) {
  tpm_challenge_key_subtle_ = std::make_unique<TpmChallengeKeySubtleImpl>(
      attestation_flow_for_testing, certificate_uploader_for_testing);
}

TpmChallengeKeyImpl::~TpmChallengeKeyImpl() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}

void TpmChallengeKeyImpl::BuildResponse(
    AttestationKeyType key_type,
    Profile* profile,
    TpmChallengeKeyCallback callback,
    const std::string& challenge,
    bool register_key,
    const std::string& key_name,
    const absl::optional<std::string>& signals) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(callback_.is_null());
  DCHECK(!callback.is_null());

  // For device key: if |register_key| is true, |key_name| should not be empty.
  DCHECK((key_type != KEY_DEVICE) || (register_key == !key_name.empty()))
      << "Invalid arguments: " << register_key << " " << !key_name.empty();

  register_key_ = register_key;
  challenge_ = challenge;
  callback_ = std::move(callback);

  // Empty |key_name| means that some default name will be used.
  tpm_challenge_key_subtle_->StartPrepareKeyStep(
      key_type, /*will_register_key=*/register_key_, key_name, profile,
      base::BindOnce(&TpmChallengeKeyImpl::OnPrepareKeyDone,
                     weak_factory_.GetWeakPtr()),
      signals);
}

void TpmChallengeKeyImpl::OnPrepareKeyDone(
    const TpmChallengeKeyResult& prepare_key_result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!prepare_key_result.IsSuccess()) {
    std::move(callback_).Run(prepare_key_result);
    return;
  }

  tpm_challenge_key_subtle_->StartSignChallengeStep(
      challenge_, base::BindOnce(&TpmChallengeKeyImpl::OnSignChallengeDone,
                                 weak_factory_.GetWeakPtr()));
}

void TpmChallengeKeyImpl::OnSignChallengeDone(
    const TpmChallengeKeyResult& sign_challenge_result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!register_key_ || !sign_challenge_result.IsSuccess()) {
    std::move(callback_).Run(sign_challenge_result);
    return;
  }

  tpm_challenge_key_subtle_->StartRegisterKeyStep(
      base::BindOnce(&TpmChallengeKeyImpl::OnRegisterKeyDone,
                     weak_factory_.GetWeakPtr(), sign_challenge_result));
}

void TpmChallengeKeyImpl::OnRegisterKeyDone(
    const TpmChallengeKeyResult& challenge_response,
    const TpmChallengeKeyResult& register_key_result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // If StartRegisterKeyStep failed, |register_key_result| contains an error
  // about it.
  if (!register_key_result.IsSuccess()) {
    std::move(callback_).Run(register_key_result);
    return;
  }

  // All steps succeeded, return the final result. The challenge response that
  // is expected from |BuildResponse| was received in |OnSignChallengeDone|, so
  // return it now.
  std::move(callback_).Run(challenge_response);
}

}  // namespace attestation
}  // namespace ash

redpajama_set_name: RedPajamaGithub


text: {{index .Map "search_list"}}


text:
.nicEdit-componentImg {
    background-image: url("/admin/cms/article/editor/ext/page_video.gif");
    background-color: #FFFFCC;
    background-position: center center;
    background-repeat: no-repeat;
    border: 1px dotted #CC0000;
}
.nicEdit-alinousInnerImg {
    background-image: url("/admin/cms/article/editor/ext/alinous.gif");
    background-color: #FFFFCC;
    background-position: center center;
    background-repeat: no-repeat;
    border: 1px dotted #CC0000;
}
.nicEdit-anchor {
	background-image: url("/admin/cms/article/editor/ext/anchor.png");
	background-repeat: no-repeat;
	background-position: left center;
	padding: 0px 0px 0px 16px;
}

.nicEdit-span {
	background-color: #FFFFCC;
	padding: 0;
	border: 1px dotted #CC0000;
}

#wysiwyg {
	width: 100%;
	background-color:#ffffff;
	padding: 0;
	margin: 0;
	min-height: 0;

}

#wysiwyg h1{
	font-weight: bold;
	background: #ffffff;
	width: auto;
	border: 0px solid;
	margin: 12px 0 12px 0;
	padding: 0;
	font-size: 32px;
}

#wysiwyg h2{
	font-weight: bold;
	background: #ffffff;
	border: 0px solid;
	margin: 12px 0 12px 0;
	padding: 0;
	font-size: 24px;
}

#wysiwyg h3{
	font-weight: bold;
	background: #ffffff;
	border: 0px solid;
	margin: 12px 0 12px 0;
	padding: 0;
	font-size: 20px;
}

#wysiwyg p{
	margin-top: 0px;
	margin: 20px 0 20px 0;
	padding: 0;

	line-height: 150%;
}


text:
raise 'This recipe does not support Windows' if node['platform_family'] == 'windows'

if node['push_jobs']['package_url'] && node['push_jobs']['package_checksum']
  package_url      = node['push_jobs']['package_url']
  package_file     = PushJobsHelper.package_file(node['push_jobs']['package_url'])
  package_checksum = node['push_jobs']['package_checksum']

  remote_file "#{Chef::Config[:file_cache_path]}/#{package_file}" do
    source package_url
    checksum package_checksum
    mode 00644
  end

else
  Chef::Log.info("['push_jobs']['package_url'] and ['push_jobs']['package_checksum'] not set. Chef Push client will be installed from CHEF's public repositories.")
end

chef_ingredient 'push-client' do
  version node['push_jobs']['package_version']
  package_source "#{Chef::Config[:file_cache_path]}/#{package_file}" if package_url
end

include_recipe 'push-jobs::config'
include_recipe 'push-jobs::service'


text:
/* eslint-disable @typescript-eslint/naming-convention */
import type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core'
import * as Types from '../../../../model/graphql/types.generated'

import {
  RoleSelection_UnmanagedRole_Fragment,
  RoleSelection_ManagedRole_Fragment,
  RoleSelectionFragmentDoc,
} from './RoleSelection.generated'

export type containers_Admin_RolesAndPolicies_gql_RolesQueryVariables = Types.Exact<{
  [key: string]: never
}>

export type containers_Admin_RolesAndPolicies_gql_RolesQuery = {
  readonly __typename: 'Query'
} & {
  readonly roles: ReadonlyArray<
    | ({ readonly __typename: 'UnmanagedRole' } & RoleSelection_UnmanagedRole_Fragment)
    | ({ readonly __typename: 'ManagedRole' } & RoleSelection_ManagedRole_Fragment)
  >
  readonly defaultRole: Types.Maybe<
    | ({ readonly __typename: 'UnmanagedRole' } & Pick<Types.UnmanagedRole, 'id'>)
    | ({ readonly __typename: 'ManagedRole' } & Pick<Types.ManagedRole, 'id'>)
  >
}

export const containers_Admin_RolesAndPolicies_gql_RolesDocument = {
  kind: 'Document',
  definitions: [
    {
      kind: 'OperationDefinition',
      operation: 'query',
      name: { kind: 'Name', value: 'containers_Admin_RolesAndPolicies_gql_Roles' },
      selectionSet: {
        kind: 'SelectionSet',
        selections: [
          {
            kind: 'Field',
            name: { kind: 'Name', value: 'roles' },
            selectionSet: {
              kind: 'SelectionSet',
              selections: [
                {
                  kind: 'FragmentSpread',
                  name: { kind: 'Name', value: 'RoleSelection' },
                },
              ],
            },
          },
          {
            kind: 'Field',
            name: { kind: 'Name', value: 'defaultRole' },
            selectionSet: {
              kind: 'SelectionSet',
              selections: [
                { kind: 'Field', name: { kind: 'Name', value: '__typename' } },
                {
                  kind: 'InlineFragment',
                  typeCondition: {
                    kind: 'NamedType',
                    name: { kind: 'Name', value: 'UnmanagedRole' },
                  },
                  selectionSet: {
                    kind: 'SelectionSet',
                    selections: [{ kind: 'Field', name: { kind: 'Name', value: 'id' } }],
                  },
                },
                {
                  kind: 'InlineFragment',
                  typeCondition: {
                    kind: 'NamedType',
                    name: { kind: 'Name', value: 'ManagedRole' },
                  },
                  selectionSet: {
                    kind: 'SelectionSet',
                    selections: [{ kind: 'Field', name: { kind: 'Name', value: 'id' } }],
                  },
                },
              ],
            },
          },
        ],
      },
    },
    ...RoleSelectionFragmentDoc.definitions,
  ],
} as unknown as DocumentNode<
  containers_Admin_RolesAndPolicies_gql_RolesQuery,
  containers_Admin_RolesAndPolicies_gql_RolesQueryVariables
>

export { containers_Admin_RolesAndPolicies_gql_RolesDocument as default }


text:
package com.googlecode.jmxtrans.model.output.support.pool;

import javax.annotation.Nonnull;
import java.io.Flushable;
import java.io.IOException;

public class NeverFlush implements FlushStrategy {
	@Override
	public void flush(@Nonnull Flushable flushable) throws IOException {
		// NeverFlush never does anything
	}
}


text:
//
//  EmojiNormalMethod.m
//  thirdTest
//
//  Created by mac on 15/4/8.
//  Copyright (c) 2015年 iDveOS. All rights reserved.
//

/**
 *  onview 废弃 tabbar会挡住
 *  toolView 和 emoji 放到window 上,
 *  需要在viewdisapper中调用 isRemoveWhenVCDisappear ,清空
 *  @return <#return value description#>
 */

#import "EmojiNormalMethod.h"

#define Skip_Keyboard_Hidden_Action_Notification @"Skip_Keyboard_Hidden_Action_Notification"

@interface EmojiNormalMethod()<Emoji_Keyboard_ToolViewDelegate>
{
    CGRect showKeyboard;
    UIView *onView;
    __block BOOL skip;
}
@property (nonatomic,strong)NSArray * firstResponderArr;//那些控件,需要显示emoji
@end

@implementation EmojiNormalMethod

- (instancetype)initWithBecomeFirstResponder:(NSArray *)sender{
    self = [super init];
    if (self) {
        _firstResponderArr = sender;
        [self registerNotification];

    }
    return self;
}
- (instancetype)initWithBecomeFirstResponder:(NSArray *)sender onView:(UIView *)view{
    self = [super init];
    if (self) {
        onView = view;
        _firstResponderArr = sender;
        [self registerNotification];
    }
    return self;
}
- (void)registerNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(becomeFirstResponderNotification:)
                                                 name:UITextFieldTextDidBeginEditingNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(becomeFirstResponderNotification:)
                                                 name:UITextViewTextDidBeginEditingNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboarkHidden:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(skipKeyboard)
                                                 name:Skip_Keyboard_Hidden_Action_Notification
                                               object:nil];

}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UITextFieldTextDidBeginEditingNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UITextViewTextDidBeginEditingNotification
                                                  object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:Skip_Keyboard_Hidden_Action_Notification
                                                  object:nil];

}

- (void)ishidden{
    [UIView animateWithDuration:0.2
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         _toolView.transform = CGAffineTransformMakeTranslation(0,0);
                         [_toolView.emojiView ishidden];

                     } completion:^(BOOL finished) {

                     }];

}

- (void)isRemoveWhenVCDisappear{
    [UIView animateWithDuration:0.2
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         _toolView.transform = CGAffineTransformMakeTranslation(0,0);
                         [_toolView.emojiView ishidden];

                         [_toolView.emojiView removeFromSuperview];
                         [_toolView removeFromSuperview];
                         _toolView = nil;

                     } completion:^(BOOL finished) {

                     }];
}
- (void)becomeFirstResponderNotification:(NSNotification *)notification{
    id obj = notification.object;

    //如果满足,emoji弹出的toolview
    if ([_firstResponderArr containsObject:obj]) {

        if (!_toolView) {
            _toolView = [[Emoji_Keyboard_ToolView alloc] initWithFrame:CGRectMake(0,
                                                                                CGRectGetHeight([[UIScreen mainScreen] bounds]),
                                                                                CGRectGetWidth([[UIScreen mainScreen] bounds]),
                                                                                40)
                                                             responder:_firstResponderArr
                                                                onView:onView];
            _toolView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:239/255.0 alpha:1.0];
            _toolView.toolDelegate  = self;
            [[UIApplication sharedApplication].keyWindow addSubview:_toolView];
        }

        [UIView animateWithDuration:0.2
                              delay:0
                            options:UIViewAnimationOptionCurveEaseInOut
                         animations:^{
                             _toolView.transform = CGAffineTransformMakeTranslation(0,- CGRectGetHeight(_toolView.frame) - CGRectGetHeight(showKeyboard));

                         } completion:^(BOOL finished) {

                         }];

    }
    else{
        [UIView animateWithDuration:0.2
                              delay:0
                            options:UIViewAnimationOptionCurveEaseInOut
                         animations:^{
                             _toolView.transform = CGAffineTransformMakeTranslation(0,0);
                             [_toolView.emojiView ishidden];
                         } completion:^(BOOL finished) {

                         }];

    }

}
- (void)keyboardShow:(NSNotification *)notification{

    NSDictionary *keyboardUserInfo = notification.userInfo;

    CGRect keyboardRect = [[keyboardUserInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    showKeyboard = keyboardRect;

    for (UIView *view in _firstResponderArr) {
        if (view.isFirstResponder) {
            [UIView animateWithDuration:0.2
                                  delay:0.1
                                options:UIViewAnimationOptionCurveEaseInOut
                             animations:^{
                                 _toolView.transform = CGAffineTransformMakeTranslation(0,- CGRectGetHeight(_toolView.frame) - CGRectGetHeight(keyboardRect));

                             } completion:^(BOOL finished) {

                             }];
            break;
        }
    }
    [_toolView.emojiView ishidden];

}
- (void)keyboarkHidden:(NSNotification *)notification{

    showKeyboard = CGRectZero;
    if (!skip) {

        [UIView animateWithDuration:0.2
                              delay:0
                            options:UIViewAnimationOptionCurveEaseInOut
                         animations:^{
                             _toolView.transform = CGAffineTransformMakeTranslation(0,0);

                         } completion:^(BOOL finished) {

                         }];

    }
    else{
        skip = NO;
    }

}

- (void)skipKeyboard{
    skip = YES;
}

- (void)getEmoji:(NSString *)emoji kit:(id)kit{
    if ([_normalDelegate respondsToSelector:@selector(getNormalEmoji:kit:)]){
        [_normalDelegate getNormalEmoji:emoji kit:kit];
    }
    else{
        if ([kit isKindOfClass:[UITextView class]]) {
            UITextView *tv = kit;
            tv.text = [tv.text stringByAppendingString:emoji];
        }
        else if ([kit isKindOfClass:[UITextField class]]) {
            UITextField *tf = kit;
            tf.text = [tf.text stringByAppendingString:emoji];
        }

    }

}

- (void)emojiDeleteEventOnKit:(id)kit{
    if ([_normalDelegate respondsToSelector:@selector(emojiDeleteEvent:)]){
        [_normalDelegate emojiDeleteEvent:kit];
    }
    else{

        if ([kit isKindOfClass:[UITextView class]]) {
            UITextView *tv = kit;
            if(tv.text.length == 0){
                return;
            }

            NSString *regexStr = @"\\[[a-zA-Z0-9_-]{1,15}\\]";//中括号类型的正则,15为文件名字的长度
            NSRegularExpression *customEmojiRegularExpression = [[NSRegularExpression alloc] initWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:nil];
            NSArray *arr = [customEmojiRegularExpression matchesInString:tv.text
                                                                 options:NSMatchingWithTransparentBounds
                                                                   range:NSMakeRange(0, [tv.text length])];
            if (arr.count > 0) {
                NSTextCheckingResult *result = [arr lastObject];
                NSRange range = result.range;
                NSString *lastStr = [tv.text substringWithRange:range];
                if ([tv.text hasSuffix:lastStr]) {
                    tv.text = [tv.text substringToIndex:tv.text.length - lastStr.length];
                }
                else{
                    tv.text = [tv.text substringToIndex:tv.text.length - 1];
                }
            }
            else{
                tv.text = [tv.text substringToIndex:tv.text.length - 1];
            }

        }
        else if ([kit isKindOfClass:[UITextField class]]) {
            UITextField *tf = kit;

            if(tf.text.length == 0){
                return;
            }

            NSString *regexStr = @"\\[[a-zA-Z0-9_-]{1,15}\\]";//中括号类型的正则,15为文件名字的长度
            NSRegularExpression *customEmojiRegularExpression = [[NSRegularExpression alloc] initWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:nil];
            NSArray *arr = [customEmojiRegularExpression matchesInString:tf.text
                                                                 options:NSMatchingWithTransparentBounds
                                                                   range:NSMakeRange(0, [tf.text length])];
            if (arr.count > 0) {
                NSTextCheckingResult *result = [arr lastObject];
                NSRange range = result.range;
                NSString *lastStr = [tf.text substringWithRange:range];
                if ([tf.text hasSuffix:lastStr]) {
                    tf.text = [tf.text substringToIndex:tf.text.length - lastStr.length];
                }
                else{
                    tf.text = [tf.text substringToIndex:tf.text.length - 1];
                }
            }
            else{
                tf.text = [tf.text substringToIndex:tf.text.length - 1];
            }

        }

    }

}
@end


text:
package org.apache.stratos.keystore.mgt.util;

import org.wso2.carbon.registry.core.service.RegistryService;

public class RegistryServiceHolder {

    private static RegistryService registryService;

    public static RegistryService getRegistryService() {
        return registryService;
    }

    public static void setRegistryService(RegistryService registryService) {
        RegistryServiceHolder.registryService = registryService;
    }
}


text:
package org.wso2.carbon.identity.provider.openid;

public class OpenIDConstants {

    public static final String NS = "http://schema.openid.net";
    public static final String OPENID_URL = "http://specs.openid.net/auth/2.0";
    public static final String ATTR_MODE = "openid.mode";
    public static final String ATTR_IDENTITY = "openid.identity";
    public static final String ATTR_RESPONSE_NONCE = "openid.response_nonce";
    public static final String ATTR_OP_ENDPOINT = "openid.op_endpoint";
    public static final String ATTR_NS = "openid.ns";
    public static final String ATTR_CLAIM_ID = "openid.claimed_id";
    public static final String ATTR_RETURN_TO = "openid.return_to";
    public static final String ATTR_ASSOC_HANDLE = "openid.assoc_handle";
    public static final String ATTR_SIGNED = "openid.signed";
    public static final String ATTR_SIG = "openid.sig";
    public static final String OPENID_IDENTIFIER = "openid_identifier";
    public static final String ASSOCIATE = "associate";
    public static final String CHECKID_SETUP = "checkid_setup";
    public static final String CHECKID_IMMEDIATE = "checkid_immediate";
    public static final String CHECK_AUTHENTICATION = "check_authentication";
    public static final String DISC = "openid-disc";
    public static final String PREFIX = "openid";
    public static final String ASSERTION = "openidAssertion";
    public static final String COMPLETE = "complete";
    public static final String ONLY_ONCE = "Only Once";
    public static final String ONCE = "once";
    public static final String ALWAYS = "always";
    public static final String DENY = "Deny";
    public static final String ACTION = "_action";
    public static final String OPENID_RESPONSE = "id_res";
    public static final String AUTHENTICATED_AND_APPROVED = "authenticatedAndApproved";
    public static final String CANCEL = "cancel";
    public static final String FALSE = "false";
    public static final String PARAM_LIST = "parameterlist";
    public static final String PASSWORD = "password";
    public static final String SERVICE_NAME_STS_OPENID = "sts-openid-ut";
    public static final String SERVICE_NAME_MEX_OPENID = "mex-openid-ut";
    public static final String SERVICE_NAME_MEX_IC_OPENID = "mex-openid-ic";
    public static final String SERVICE_NAME_STS_IC_OPENID = "sts-openid-ic";
    public static final String AUTHENTICATION_RESULT = "AuthenticationResult";

    public static final String UTF_8 = "UTF-8";

    // session attributes
    public static class SessionAttribute {
        public static final String OPENID = "openId";
        public static final String USERNAME = "userName";
        public static final String OPENID_ADMIN_CLIENT = "openid_admin_client";
        public static final String PROFILE = "profile";
        public static final String SELECTED_PROFILE = "selectedProfile";
        public static final String DEFAULT_PROFILE = "default";
        public static final String ACTION = "_action";
        public static final String USER_APPROVED = "userApproved";
        public static final String USER_APPROVED_ALWAYS = "userApprovedAlways";
        public static final String HAS_APPROVED_ALWAYS = "hasApprovedAlways";
        public static final String AUTHENTICATED_OPENID = "authenticatedOpenID";
        public static final String IS_OPENID_AUTHENTICATED = "isOpenIDAuthenticated";

        private SessionAttribute() {
        }
    }

    // request parameters
    public static class RequestParameter {
        public static final String LOGOUT_URL = "logoutUrl";
        public static final String OPENID = "openId";
        public static final String USERNAME = "userName";
        public static final String REMEMBER = "remember";
        public static final String PASSWORD = "password";
        public static final String HAS_APPROVED_ALWAYS = "hasApprovedAlways";
        public static final String SESSION_DATA_KEY = "sessionDataKey";
        public static final String NON_LOGIN = "nonlogin";

        private RequestParameter() {
        }
    }

    // cookies
    public static class Cookie {
        public static final String OPENID_TOKEN = "openidtoken";
        public static final String OPENID_REMEMBER_ME = "openidrememberme";

        private Cookie() {
        }
    }

    public static class PapeAttributes {
        public static final String AUTH_POLICIES = "auth_policies";
        public static final String NIST_AUTH_LEVEL = "nist_auth_level";
        public static final String AUTH_AGE = "auth_age";
        public static final String PHISHING_RESISTANCE =
                "http://schemas.openid.net/pape/policies/2007/06/phishing-resistant";
        public static final String MULTI_FACTOR = "http://schemas.openid.net/pape/policies/2007/06/multi-factor";
        public static final String MULTI_FACTOR_PHYSICAL =
                "http://schemas.openid.net/pape/policies/2007/06/multi-factor-physical";

        private PapeAttributes() {
        }
    }

    public static class SimpleRegAttributes {

        // As per the OpenID Simple Registration Extension 1.0 spec fields
        // below should be included in the Identity Provider's
        // response when "openid.mode" is "id_res"

        public static final String NS_SREG = "http://openid.net/sreg/1.0";
        public static final String NS_SREG_1 = "http://openid.net/extensions/sreg/1.1";
        public static final String SREG = "openid.sreg.";
        public static final String OP_SREG = "openid.ns.sreg";

        public static final String NICK_NAME = "nickname";
        public static final String EMAIL = "email";
        public static final String FULL_NAME = "fullname";
        public static final String DOB = "dob";
        public static final String GENDER = "gender";
        public static final String POSTAL_CODE = "postcode";
        public static final String COUNTRY = "country";
        public static final String LANGUAGE = "language";
        public static final String TIMEZONE = "timezone";

        public static final String FULL_NAME_NS = "http://schema.openid.net/2007/05/claims/fullname";
        public static final String DOB_NS = "http://schema.openid.net/2007/05/claims/dob";
        public static final String GENDER_NS = "http://schema.openid.net/2007/05/claims/gender";
        public static final String LANGUAGE_NS = "http://schema.openid.net/2007/05/claims/language";
        public static final String TIMEZONE_NS = "http://schema.openid.net/2007/05/claims/timezone";

        private SimpleRegAttributes() {
        }
    }

    public static class ExchangeAttributes extends SimpleRegAttributes {

        public static final String NS = "http://axschema.org";
        public static final String NS_AX = "http://openid.net/srv/ax/1.0";
        public static final String EXT = "openid.ns.ext1";
        public static final String MODE = "openid.ext1.mode";
        public static final String TYPE = "openid.ext1.type.";
        public static final String VALUE = "openid.ext1.value.";
        public static final String FETCH_RESPONSE = "fetch_response";

        public static final String NICK_NAME_NS = NS + "/namePerson/friendly";
        public static final String EMAIL_NS = NS + "/contact/email";
        public static final String FULL_NAME_NS = NS + "/namePerson";
        public static final String DOB_NS = NS + "/birthDate";
        public static final String GENDER_NS = NS + "/person/gender";
        public static final String POSTAL_CODE_NS = NS
                                                    + "/contact/postalCode/home";
        public static final String COUNTRY_NS = NS + "/contact/country/home";
        public static final String LANGUAGE_NS = NS + "/pref/language";
        public static final String TIMEZONE_NS = NS + "/pref/timezone";

        private ExchangeAttributes() {
        }
    }

    // OpenID request parameters
    public static class OpenIDRequestParameters {

        public static final String OPENID_REALM = "openid.realm";
        public static final String OPENID_RETURN_TO = "openid.return_to";
        public static final String OPENID_CLAIMED_ID = "openid.claimed_id";
        public static final String OPENID_IDENTITY = "openid.identity";

        private OpenIDRequestParameters() {
        }
    }

    private OpenIDConstants() {
    }
}


text:
<?php

use Phinx\Migration\AbstractMigration;
use Phinx\Db\Adapter\MysqlAdapter;

class AddPaymentData extends AbstractMigration
{
    public function change()
    {
      $table= $this->table('payment');
      $table
        ->addColumn('data', 'blob', [
                      'limit' => MysqlAdapter::BLOB_MEDIUM,
                      'null' => true,
                    ])
        ->save();
    }
}


text:
package com.metamx.tranquility.druid

import com.google.common.base.Charsets
import com.metamx.common.Backoff
import com.metamx.common.scala.Logging
import com.metamx.common.scala.event.WARN
import com.metamx.common.scala.event.emit.emitAlert
import com.metamx.common.scala.untyped.Dict
import com.metamx.common.scala.untyped.str
import com.metamx.emitter.service.ServiceEmitter
import com.metamx.tranquility.druid.TaskClient.timer
import com.metamx.tranquility.finagle.FutureRetry
import com.metamx.tranquility.finagle._
import com.twitter.finagle.Service
import com.twitter.finagle.util.DefaultTimer
import com.twitter.util.Closable
import com.twitter.util.Future
import com.twitter.util.Time
import com.twitter.util.Timer
import java.io.IOException
import org.jboss.netty.handler.codec.http.HttpRequest
import org.jboss.netty.handler.codec.http.HttpResponse
import org.scala_tools.time.Imports._

/**
 * Client for a single Druid task.
 */
class TaskClient(
  val task: TaskPointer,
  client: Service[HttpRequest, HttpResponse],
  dataSource: String,
  quietPeriod: Period,
  retryPeriod: Period,
  indexService: IndexService,
  emitter: ServiceEmitter
) extends Logging with Closable
{
  // Assume tasks start running
  @volatile private[this] var _status: IndexStatus = TaskRunning

  def status_=(newStatus: IndexStatus) = synchronized {
    // Don't allow transitions out of inactive states
    if (active && _status != newStatus) {
      log.info("Task %s status changed from %s -> %s", task.id, _status, newStatus)
      _status = newStatus
    }
  }

  def status = _status

  def active = Seq(TaskRunning, TaskNotFound) contains _status

  def apply(request: HttpRequest): Future[Option[HttpResponse]] = {
    val retryable = IndexService.isTransient(retryPeriod)
    FutureRetry.onErrors(Seq(retryable), Backoff.standard(), DateTime.now + quietPeriod) {
      client(request) map {
        response =>
          val code = response.getStatus.getCode
          val reason = response.getStatus.getReasonPhrase
          if (code / 100 == 2) {
            if (log.isTraceEnabled) {
              log.trace(
                "Sent request to task[%s], serviceKey[%s], got response: %s",
                task.id,
                task.serviceKey,
                response.getContent.toString(Charsets.UTF_8)
              )
            }
            Some(response)
          } else {
            throw new IOException(
              "Failed to send request to task[%s]: %s %s" format(task.id, code, reason)
            )
          }
      } rescue {
        case e: Exception if retryable(e) =>
          // This is a retryable exception.
          (if (!active) {
            // Possibly give up by returning None if the task has completed.
            Future(status)
          } else {
            indexService.status(task.id)
          }) map {
            newStatus =>
              status = newStatus
              if (!active) {
                // Task inactive, let's give up
                emitAlert(
                  log, emitter, WARN, "Loss of Druid redundancy: %s" format dataSource, Dict(
                    "dataSource" -> dataSource,
                    "task" -> task.id,
                    "status" -> client.status.toString
                  )
                )
                None
              } else {
                // Task still active, allow retry
                throw new IOException("Failed to send request to task[%s] (status = %s)" format(task.id, status), e)
              }
          }
      }
    }
  }

  override def close(deadline: Time): Future[Unit] = {
    client.close(deadline)
  }
}

object TaskClient
{
  implicit val timer: Timer = DefaultTimer.twitter
}

case class TaskPointer(id: String, serviceKey: String)
{
  def toMap = Dict(
    "id" -> id,
    "serviceKey" -> serviceKey
  )
}

object TaskPointer
{
  def fromMap(d: Dict): TaskPointer = {
    TaskPointer(
      str(d("id")),
      str(d("serviceKey"))
    )
  }
}


text:
CMoveCommand gMoveCommand;

CMoveCommand::CMoveCommand() {
    return;
}

CMoveCommand::~CMoveCommand() {
    return;
}

void CMoveCommand::Init() {
    memset(this->m_MoveCommandData, 0, sizeof(this->m_MoveCommandData));

    for (int i = 0; i < MAX_MOVE_COMMAND; i++) {
        this->m_MoveCommandData[i].Index = -1;
    }
}

int CMoveCommand::Load(char *filename) {
    this->Init();

    pugi::xml_document file;
    pugi::xml_parse_result res = file.load_file(filename);

    if (res.status != pugi::status_ok) {
        g_Log.MsgBox("%s File Load Error (%s)", filename, res.description());
        return 0;
    }

    int counter = 0;
    pugi::xml_node warpsettings = file.child("WarpSettings");

    for (pugi::xml_node warp = warpsettings.child("Warp"); warp; warp = warp.next_sibling()) {
        this->m_MoveCommandData[counter].Index = warp.attribute("Index").as_int();
        strcpy(this->m_MoveCommandData[counter].Name, warp.attribute("ServerName").as_string());
        strcpy(this->m_MoveCommandData[counter].EngName, warp.attribute("ClientName").as_string());
        this->m_MoveCommandData[counter].NeedLevel = warp.attribute("MinLevel").as_int();
        this->m_MoveCommandData[counter].MaxLevel = warp.attribute("MaxLevel").as_int();
        this->m_MoveCommandData[counter].NeedZen = warp.attribute("ReqMoney").as_int();
        this->m_MoveCommandData[counter].GateNumber = warp.attribute("GateNumber").as_int();

        counter++;

        if (counter >= MAX_MOVE_COMMAND) {
            g_Log.MsgBox("Warp List Limit Reached (60)");
            break;
        }
    }

    return TRUE;
}

int CMoveCommand::LoadMoveLevel(char *filename) {
    memset(this->m_MoveLevel, -1, sizeof(this->m_MoveLevel));

    pugi::xml_document file;
    pugi::xml_parse_result res = file.load_file(filename);

    if (res.status != pugi::status_ok) {
        g_Log.MsgBox("MoveLevel %s File Load Error (%s)", filename, res.description());
        return 0;
    }

    int counter = 0;
    pugi::xml_node movesettings = file.child("MoveSettings");

    for (pugi::xml_node move = movesettings.child("Move"); move; move = move.next_sibling()) {
        this->m_MoveLevel[counter].MoveLevel = move.attribute("Level").as_int();
        this->m_MoveLevel[counter].MapNumber = move.attribute("MapNumber").as_int();
        this->m_MoveLevel[counter].X = move.attribute("StartX").as_int();
        this->m_MoveLevel[counter].Y = move.attribute("StartY").as_int();
        this->m_MoveLevel[counter].TX = move.attribute("EndX").as_int();
        this->m_MoveLevel[counter].TY = move.attribute("EndY").as_int();

        counter++;
    }

    return TRUE;
}

int CMoveCommand::GetMoveLevel(int mapnumber, int x, int y, int Class) {
    for (int i = 0; i < MAX_MOVE_COMMAND; i++) {
        if (this->m_MoveLevel[i].MapNumber == mapnumber) {
            if (x >= this->m_MoveLevel[i].X && x <= this->m_MoveLevel[i].TX && y >= this->m_MoveLevel[i].Y &&
                y <= this->m_MoveLevel[i].TY) {
                if (mapnumber == MAP_INDEX_CALMNESS) {
                    return this->m_MoveLevel[i].MoveLevel;
                }

                if (Class == CLASS_DARKLORD || Class == CLASS_MAGUMSA || Class == CLASS_RAGEFIGHTER) {
                    return this->m_MoveLevel[i].MoveLevel * 2 / 3;
                } else {
                    return this->m_MoveLevel[i].MoveLevel;
                }
            }
        }
    }

    return -1;
}

BOOL CMoveCommand::CheckMainToMove(LPOBJ lpObj) {
    if (BC_MAP_RANGE(lpObj->MapNumber) != FALSE) {
        return FALSE;
    }

    if (CC_MAP_RANGE(lpObj->MapNumber) != FALSE) {
        return FALSE;
    }

    if (lpObj->MapNumber == MAP_INDEX_CHAOSCASTLE_SURVIVAL) {
        return FALSE;
    }

    if (KALIMA_MAP_RANGE(lpObj->MapNumber) != FALSE) {
        return FALSE;
    }

    if (DS_MAP_RANGE(lpObj->MapNumber) != FALSE) {
        return FALSE;
    }

    if (g_ConfigRead.server.GetServerType() != SERVER_CASTLE) {
        if (lpObj->MapNumber == MAP_INDEX_KANTURU_BOSS) {
            return FALSE;
        }
    }

    if (IT_MAP_RANGE(lpObj->MapNumber) != FALSE) {
        if (g_IT_Event.CheckRelics(lpObj->m_Index) != FALSE) {
            return FALSE;
        }
    }

    return TRUE;
}

BOOL CMoveCommand::CheckEquipmentToMove(LPOBJ lpObj, int iTargetMapNumber) {
    if (iTargetMapNumber == MAP_INDEX_ATHLANSE) {
        if (lpObj->m_btInvenPetPos != 0 && lpObj->m_wInvenPet != (WORD) - 1) {
            if (lpObj->pInventory[lpObj->m_btInvenPetPos].m_Type == ITEMGET(13, 2)) {
                return FALSE;
            }

            if (lpObj->pInventory[lpObj->m_btInvenPetPos].m_Type == ITEMGET(13, 3)) {
                return FALSE;
            }
        }
    }

    if (iTargetMapNumber == MAP_INDEX_ICARUS) {
        if ((lpObj->pInventory[lpObj->m_btInvenPetPos].m_Type != ITEMGET(13, 3) &&
             lpObj->pInventory[7].m_Type != ITEMGET(13, 30) &&
             lpObj->pInventory[lpObj->m_btInvenPetPos].m_Type != ITEMGET(13, 37) &&
             lpObj->pInventory[7].m_Type != ITEMGET(12, 36) &&//Season 4.5 addon
             lpObj->pInventory[7].m_Type != ITEMGET(12, 37) &&//Season 4.5 addon
             lpObj->pInventory[7].m_Type != ITEMGET(12, 38) &&//Season 4.5 addon
             lpObj->pInventory[7].m_Type != ITEMGET(12, 39) &&//Season 4.5 addon
             lpObj->pInventory[7].m_Type != ITEMGET(12, 40) &&//Season 4.5 addon
             lpObj->pInventory[7].m_Type != ITEMGET(12, 41) &&//Season 4.5 addon
             lpObj->pInventory[7].m_Type != ITEMGET(12, 42) &&//Season 4.5 addon
             lpObj->pInventory[7].m_Type != ITEMGET(12, 43) &&//Season 4.5 addon
             lpObj->pInventory[7].m_Type != ITEMGET(12, 49) &&//Seaason 6.1 addon
             lpObj->pInventory[7].m_Type != ITEMGET(12, 50) &&
             lpObj->pInventory[lpObj->m_btInvenPetPos].m_Type != ITEMGET(13, 4) &&//Season 4.5 addon
             !(lpObj->pInventory[7].m_Type >= ITEMGET(12, 262) && lpObj->pInventory[7].m_Type <= ITEMGET(12, 265)) &&
             lpObj->pInventory[7].m_Type != ITEMGET(12, 266) && // Season 8
             lpObj->pInventory[7].m_Type != ITEMGET(12, 267) && // Season 8
             lpObj->pInventory[7].m_Type != ITEMGET(12, 268) && // season 9
             !(lpObj->pInventory[7].m_Type >= ITEMGET(12, 130) && lpObj->pInventory[7].m_Type <= ITEMGET(12, 135)) &&
             (lpObj->pInventory[7].m_Type<ITEMGET(12, 0) || lpObj->pInventory[7].m_Type>ITEMGET(12, 6))) ||
            lpObj->pInventory[lpObj->m_btInvenPetPos].m_Type == ITEMGET(13, 2) ||
            lpObj->pInventory[11].m_Type == ITEMGET(13, 10) ||
            lpObj->pInventory[10].m_Type == ITEMGET(13, 10)) {
            return FALSE;
        }

        if (lpObj->m_RecallMon >= 0) {
            GSProtocol.GCRecallMonLife(lpObj->m_Index, 60, 0);
            gObjMonsterCallKill(lpObj->m_Index);
        }
    }

    return TRUE;
}

BOOL CMoveCommand::CheckInterfaceToMove(LPOBJ lpObj) {
    if (lpObj->m_IfState.use == 1) {
        return FALSE;
    }

    if (lpObj->m_bPShopOpen == true) {
        return FALSE;
    }

    return TRUE;
}

int CMoveCommand::FindIndex(LPSTR mapname) {
    for (int i = 0; i < MAX_MOVE_COMMAND; i++) {
        if (this->m_MoveCommandData[i].Index == -1) {
            return -1;
        }

        if (strcmp(mapname, this->m_MoveCommandData[i].Name) == 0 ||
            strcmpi(mapname, this->m_MoveCommandData[i].EngName) == 0) {
            return i;
        }
    }

    return -1;
}

int CMoveCommand::FindIndex(int iMapIndex) {
    for (int i = 0; i < MAX_MOVE_COMMAND; i++) {
        if (this->m_MoveCommandData[i].Index == -1) {
            return -1;
        }

        if (this->m_MoveCommandData[i].Index == iMapIndex) {
            return i;
        }
    }

    return -1;
}

BOOL CMoveCommand::CheckMoveMapBound(int iMapIndex) {
    switch (iMapIndex) {
        case 1:
        case 2:
        case 3:
        case 6:
        case 10:
        case 16:
            return TRUE;
    }

    return FALSE;
}

BOOL CMoveCommand::Move(LPOBJ lpObj, int iMapIndex) {
    int m_number = -1;
    int overlevel = 0;
    int subMoney = 2000;

    int index = this->FindIndex(iMapIndex);

    if (index == -1) {
        g_Log.Add("[MapMove Failed] Invalid Map Index (%s/%s) (Index : %d)", lpObj->AccountID, lpObj->Name, iMapIndex);
        return FALSE;
    }

    int nMoveIndex = this->m_MoveCommandData[index].Index;

    if (g_GensSystem.IsMoveMapBattleZone(nMoveIndex)) {
        if (g_ConfigRead.server.IsNonPvP()) {
            GSProtocol.GCServerMsgStringSend(Lang.GetText(0, 305), lpObj->m_Index, 1);
            return FALSE;
        }

        if (!g_GensSystem.IsUserBattleZoneEnable(lpObj)) {
            GSProtocol.GCServerMsgStringSend(Lang.GetText(0, 499), lpObj->m_Index, 1);
            return FALSE;
        }

        if (IMPERIAL_MAP_RANGE(lpObj->MapNumber) != FALSE) {
            GSProtocol.GCServerMsgStringSend(Lang.GetText(0, 499), lpObj->m_Index, 1);
            return FALSE;
        }

        if (IT_MAP_RANGE(lpObj->MapNumber) != FALSE) {
            GSProtocol.GCServerMsgStringSend(Lang.GetText(0, 499), lpObj->m_Index, 1);
            return FALSE;
        }

        GSProtocol.GCServerMsgStringSend(Lang.GetText(0, 500), lpObj->m_Index, 1);
        g_GensSystem.MoveInBattleZonePartySplit(lpObj);
    }

    if (nMoveIndex == 24) //season 3.0 changed
    {
        if (g_CastleSiegeSync.GetCastleState() == 7) {
            return FALSE;
        }

        if (g_CastleSiegeSync.CheckCastleOwnerMember(lpObj->m_Index) == FALSE &&
            g_CastleSiegeSync.CheckCastleOwnerUnionMember(lpObj->m_Index) == FALSE) {
            return FALSE;
        }
    }

    if (IT_MAP_RANGE(lpObj->MapNumber) != FALSE) //season 3.0 add-on
    {
        if (nMoveIndex == 11 || nMoveIndex == 12 || nMoveIndex == 13 || nMoveIndex == 23) {
            return FALSE;
        }
    }

    if (index == -1) {
        return FALSE;
    }

    int NeedLevel = this->m_MoveCommandData[index].NeedLevel;
    int NeedZen = this->m_MoveCommandData[index].NeedZen;
    int GateNumber = this->m_MoveCommandData[index].GateNumber;

    NeedZen *= g_GensSystem.PkPenaltyAddNeedZenMapMove(lpObj);

    if (g_ConfigRead.data.common.joinmuDisableWarpLevelBenefits == false) {
        if (lpObj->Class == CLASS_DARKLORD || lpObj->Class == CLASS_MAGUMSA || lpObj->Class == CLASS_RAGEFIGHTER) {
            if (NeedLevel > 0) {
                if (GateNumber != 273) //season 3.0 add-on (Swamp of Calmmness)
                {
                    NeedLevel = NeedLevel * 2 / 3;
                }
            }
        }
    }
    if (GateNumber >= 0) {
        if (NeedLevel <= lpObj->Level) {
            if ((lpObj->m_PlayerData->Money - NeedZen) >= 0) {
                if (gObjMoveGate(lpObj->m_Index, GateNumber) != FALSE) {
                    lpObj->m_bPShopRedrawAbs = true;
                    lpObj->m_PlayerData->Money -= NeedZen;

                    g_Log.Add("[%s][%s] [Using Warp to: %s] Success : reduces money %d - %d", lpObj->AccountID,
                              lpObj->Name, this->m_MoveCommandData[index].Name, lpObj->m_PlayerData->Money, NeedLevel);

                    GSProtocol.GCMoneySend(lpObj->m_Index, lpObj->m_PlayerData->Money);

                    if (lpObj->MapNumber == MAP_INDEX_HATCHERY)//Season 4.5 addon
                    {
                        g_RaklionBattleUserMng.DeleteUserData(lpObj->m_Index);
                    }

                    return TRUE;
                }
            } else {
                GSProtocol.GCServerMsgStringSend(Lang.GetText(0, 37), lpObj->m_Index, 1);
            }
        } else {
            char szTemp[256];
            wsprintf(szTemp, Lang.GetText(0, 30), NeedLevel);
            GSProtocol.GCServerMsgStringSend(szTemp, lpObj->m_Index, 1);
        }
    }

    g_Log.Add("[%s][%s] [Using Warp to: %s] Fail GateNumber = %d", lpObj->AccountID, lpObj->Name,
              this->m_MoveCommandData[index].Name, GateNumber);
    return FALSE;

}

int GetKalimaGateLevel(LPOBJ lpObj) {
    if (lpObj->Class == CLASS_MAGUMSA || lpObj->Class == CLASS_DARKLORD || lpObj->Class == CLASS_RAGEFIGHTER) {
        for (int i = 0; i < KALIMA_FLOORS; i++) {
            if (lpObj->Level >= g_sttKALIMAGATE_LEVEL[i].iLOWER_BOUND_MAGUMSA &&
                lpObj->Level <= g_sttKALIMAGATE_LEVEL[i].iUPPER_BOUND_MAGUMSA) {
                return i;
            }
        }
    } else {
        for (int i = 0; i < KALIMA_FLOORS; i++) {
            if (lpObj->Level >= g_sttKALIMAGATE_LEVEL[i].iLOWER_BOUND &&
                lpObj->Level <= g_sttKALIMAGATE_LEVEL[i].iUPPER_BOUND) {
                return i;
            }
        }
    }

    return -1;
}

BOOL CMoveCommand::MoveFree2Kalima(LPOBJ lpObj) {
    int iIdx = GetKalimaGateLevel(lpObj);

    if (iIdx >= 6) {
        iIdx = 5;
    }

    if (iIdx < 0) {
        return FALSE;
    }

    int iGateNumber = iIdx + 88;

    return gObjMoveGate(lpObj->m_Index, iGateNumber);
}

LPMOVE_COMMAND_DATA CMoveCommand::GetMoveCommandData(int nMapIndex) {
    int nIndex = -1;
    for (int i = 0; i < 50; i++) {
        if (m_MoveCommandData[i].Index == nMapIndex) {
            nIndex = i;
            break;
        }
    }
    if (nIndex < 0) return NULL;
    return (LPMOVE_COMMAND_DATA) &m_MoveCommandData[nIndex];
}

LPMOVE_COMMAND_DATA CMoveCommand::GetMoveCommandDataByMapNumber(WORD wMapNumber) {
    int nIndex = -1;
    short x, y, level;
    BYTE mapnum, dir;
    for (int i = 0; i < 50; i++) {
        gGateC.GetGate(m_MoveCommandData[i].GateNumber, x, y, mapnum, dir, level);
        if (mapnum == wMapNumber) {
            nIndex = i;
            break;
        }
    }
    if (nIndex < 0) return NULL;
    return (LPMOVE_COMMAND_DATA) &m_MoveCommandData[nIndex];
}


text:
/*
    Given a pattern and a string str, find if str follows the same pattern.

    Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

    Examples:
    pattern = "abba", str = "dog cat cat dog" should return true.
    pattern = "abba", str = "dog cat cat fish" should return false.
    pattern = "aaaa", str = "dog cat cat dog" should return false.
    pattern = "abba", str = "dog dog dog dog" should return false.
    Notes:
    You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
*/

import java.util.*;

public class WordPattern {
    public static void main(String[] args) {
        if(args.length < 2) {
            System.out.println("Usage: $> java WordPattern <pattern> <input>");
        }

        String pattern = args[0].trim();
        String input = args[1].trim();

        System.out.println(wordPattern(pattern, input));
    }

    public static boolean wordPattern(String pattern, String input) {
        String[] input_array = input.split(" ");

        if(pattern.length() != input_array.length) {
            return false;
        }

        HashMap<Character,String> match = new HashMap<Character,String>();
        for(int i = 0; i < pattern.length(); i++) {
            Character patternChar = new Character(pattern.charAt(i));

            if(match.get(patternChar) == null) {
                // check if this value has been attached to any other key
                for(Map.Entry<Character, String> entry: match.entrySet()) {
                    if(Objects.equals(input_array[i], entry.getValue())) {
                        return false;
                    }
                }

                match.put(patternChar, input_array[i]);
            } else {
                if(!match.get(patternChar).equals(input_array[i])) {
                    return false;
                }
            }
        }

        return true;
    }
}


text:
<!DOCTYPE HTML>

		<meta charset="utf-8">
		<meta http-equiv="refresh" content="1; URL=test-resources/testsuite/testframe.html">
		<title>OpenUI5 Testsuite - You will be redirected in a second!</title>

		OpenUI5 Testsuite - you will be redirected in a second!


text:
class AddAttributesToVClass < ActiveRecord::Migration
  def self.up
    add_column    :virtual_classes, :dyn_keys, :text
  end

  def self.down
    remove_column :virtual_classes, :dyn_keys
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_blacklist"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.musicocracy.fpgk.ui.BlacklistActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/filter_add_btn"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:orientation="vertical">

        <ListView
            android:id="@+id/filter_list_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/filter_add_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_gravity="bottom|end"
        android:src="@android:drawable/ic_input_add" />

</RelativeLayout>


text:
using dBosque.Stub.Client.Socket.Exception;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;

namespace dBosque.Stub.Client.Socket.Parsing
{

    /// <summary>
    /// The SQL command Extractor
    /// </summary>
    internal static class DbCommandTreeExtractor
    {
        static DbCommandTreeExtractor()
        {
            try
            {
                parserMethodInfo = Type.GetType(PARSERTYPE).GetMethod(PARSERMETHOD, new Type[] { typeof(string) });
            }
            catch
            {
                // Parsing not available.
            }
        }

        /// <summary>
        /// Parser information
        /// </summary>
        private static readonly string PARSERTYPE = "Microsoft.SqlServer.Management.SqlParser.Parser.Parser, Microsoft.SqlServer.Management.SqlParser, Version=13.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91";
        private static readonly string PARSERMETHOD = "Parse";
        private static readonly MethodInfo parserMethodInfo;

        /// <summary>
        /// Table element names
        /// </summary>
        private static readonly string[] TABLE =  { "SqlTableRefExpression" };

        /// <summary>
        /// Object element name
        /// </summary>
        private static readonly string[] OBJECT ={ "SqlObjectIdentifier" };

        /// <summary>
        /// Column attribute names
        /// </summary>
        private static readonly string[] COLUMNNAMES = { "ColumnOrPropertyName", "ColumnName" };

        /// <summary>
        /// Variable element names
        /// </summary>
        private static readonly string[] VARIABLES =  { "SqlGlobalScalarVariableRefExpression", "SqlScalarVariableRefExpression" };

        /// <summary>
        /// Column element names
        /// </summary>
        private static readonly string[] COLUMNS = { "SqlColumnRefExpression", "SqlScalarRefExpression" };

        /// <summary>
        /// The Table schemaname
        /// </summary>
        private static readonly string SCHEMANAME = "SchemaName";

        /// <summary>
        /// Object attribute name
        /// </summary>
        private static readonly string OBJECTNAME = "ObjectName";

        /// <summary>
        /// Variable attribute name
        /// </summary>
        private static readonly string VARIABLENAME = "VariableName";

        /// <summary>
        /// Supported statements
        /// </summary>
        private static readonly Dictionary<string, string> STATEMENTS = new Dictionary<string, string>()
        {
            { "SqlSelectStatement","select"},
            { "SqlDeleteStatement","delete"},
            { "SqlInsertStatement","insert"},
            { "SqlUpdateStatement","update"}
        };

        /// <summary>
        /// Extract the commandText from the given sql
        /// </summary>
        /// <param name="sql">The raw sql statement</param>
        /// <returns></returns>
        internal static CommandText Extract(string sql)
        {
            // If no sql given, return the command
            var command = new CommandText() { Raw = sql };
            if (!string.IsNullOrEmpty(sql) && parserMethodInfo != null)
            {
                // Extract the tree
                var doc = ExtractSyntaxTree(sql);
                ExtractTables(command, doc);
                ExtractStatement(command, doc);
                ExtractVariables(command, doc);
            }
            return command;
        }

        /// <summary>
        /// Extract the statement from the commandtree
        /// </summary>
        /// <param name="command">The command to update</param>
        /// <param name="doc">The commandtree</param>
        private static void ExtractStatement(CommandText command, XContainer doc)
        {
            var items = new List<string>();
            foreach (var s in STATEMENTS)
                items.AddRange(doc.Descendants(s.Key).Select(a => s.Value));
            command.Statement = items.First();
        }

        /// <summary>
        /// Extract the tables from the commandtree
        /// </summary>
        /// <param name="command">The command to update</param>
        /// <param name="doc">The commandtree</param>
        private static void ExtractTables(CommandText command, XContainer doc)
        {
            foreach (var t in TABLE)
                foreach (var o in OBJECT)
                    command.Tables.AddRange(doc.Descendants(t).Descendants(o).Select(x => $"{x.Attribute(SCHEMANAME)?.Value??""}.{x.Attribute(OBJECTNAME)?.Value??""}"));
        }

        /// <summary>
        /// Extract the variables from the commandtree
        /// </summary>
        /// <param name="command">The command to update</param>
        /// <param name="doc">The commandtree</param>
        private static void ExtractVariables(CommandText command, XContainer doc)
        {

            foreach (var v in VARIABLES)
            {
                foreach (var x in doc.Descendants(v))
                {
                    var key = x.Attribute(VARIABLENAME)?.Value;
                    var refExpr = x.ElementsBeforeSelf()
                                        .Where(a => COLUMNS.ToList().Contains(a.Name.LocalName))
                                        .Attributes()
                                        .FirstOrDefault(a => COLUMNNAMES.ToList().Contains(a.Name.LocalName))
                                        ?.Value;

                    if (!string.IsNullOrEmpty(refExpr))
                        command.Variables.Add( new Tuple<string, string, string>( key?.Replace("@",""), refExpr, null));
                }
            }
        }

        /// <summary>
        /// Extract the syntax tree from the raw sql
        /// </summary>
        /// <param name="raw">The raw sql statement</param>
        /// <returns></returns>
        private static XDocument ExtractSyntaxTree(string raw)
        {
            var rst = parserMethodInfo.Invoke(null, new object[] { raw }); //Parser.Parse(raw);
            var errors = rst.GetType().GetProperty("Errors").GetValue(rst) as IEnumerable<object>;
            var nonWarnings = errors.Where(a => !((bool)a.GetType().GetProperty("IsWarning").GetValue(a)));
            if (nonWarnings.Any())
            {
                var first = nonWarnings.First();
                throw new CommandTextException(first.GetType().GetProperty("Message").GetValue(first) as string);
            }
            var script = rst.GetType().GetProperty("Script", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(rst);
            var xml = script.GetType().GetProperty("Xml").GetValue(script) as string;
            return XDocument.Parse(xml);
        }
    }
}


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

=pod

=head1 NAME

FeatureSerializer - An abstract serializer for turning EnsEMBL Features into other formats

=head1 SYNOPSIS

my $serializer = new Bio::EnsEMBL::Utils::IO::FeatureSerializer( $filehandle );
$serializer->print_feature_list( \@list_of_features );

=head1 DESCRIPTION

Generic class for serializing features Subclass this class to create a
format-specific serializer. Be sure to implement print_feature at the
bare minimum

=cut

package Bio::EnsEMBL::Utils::IO::FeatureSerializer;

use strict;
use warnings;

use base qw(Bio::EnsEMBL::Utils::IO::Serializer);

# Majority of methods inherited from Serializer

=head2 print_feature

	Arg []     : None
	Description: Abstract method to print a feature.
                     Implemented in derived classes.
        Returntype : None

=cut

sub print_feature {
	throw( "print_feature method not implemented.");
}

=head2 print_feature_list

	Arg [1]    : Listref of Features
	Description: Run print_feature on every feature in the list
        Returntype : None
=cut

sub print_feature_list {
	my $self = shift;
	my $feature_list = shift;
	if (ref($feature_list) eq 'ARRAY') {
		if (scalar(@$feature_list) > 0) {$self->{'achieved_something'} = 1;}
		foreach my $feature (@{$feature_list}) {
			$self->print_feature($feature);
		}
	}
	else {
		throw( "print_feature_list requires a listref as argument" );
	}
}

=head2 print_feature_Iterator

	Arg [1]    : Bio::EnsEMBL::Utils::Iterator
	Description: Automatically spools through an iterator for convenience
	Returntype : None
=cut

sub print_feature_Iterator {
	my $self = shift;
	my $iterator = shift;
	if ($iterator->can('has_next')) {
		$iterator->each(
			sub {
				$self->print_feature($_);
				$self->{'achieved_something'} = 1;
			}
		);
	}
	else {
		throw("Supplied iterator does not look like Bio::EnsEMBL::Utils::Iterator");
	}
}

1;


text:
package Supfam::DolloParsmony;
require Exporter;

=head1 NAME

Supfam::DolloParsmony

=head1 SYNOPSIS

A few useful functions for scripting, like easier dumping and reading in of data
use Supfam::DolloParsmony;

=head1 AUTHOR

Adam Sardar (adam.sardar@bris.ac.uk)

=head1 COPYRIGHT

Copyright 2011 Gough Group, University of Bristol.

=head1 SEE ALSO

Supfam::Config.pm

=head1 DESCRIPTION

=cut

our @ISA       = qw(Exporter AutoLoader);
our @EXPORT    = qw(
					PopulateDolloPStateAssingments
					DolloParsimonyAncestralState
					dolloTraitDecoration
					DOLLOP_Ancestral_Trait_Changes_in_Clade
                  );
our @EXPORT_OK = qw();
our $VERSION   = 1.00;

use strict;
use warnings;

use Data::Dumper;
use Supfam::Utils;
use Supfam::TreeFuncsNonBP;

use threads;
use threads::shared;

sub DolloParsimonyAncestralState{ #No prototyping as the number of arguments can be variable

	my ($TreeHash,$root,$LeafStatesFile,$nthreads,$TraitLabelsArrayRef) = @_;

	my $TraitLabelsProvided = (@_ < 5)?0:1; #Flag for is a list of trait labels provided

	my $TraitLookUp = {};

	my @TraitLabels;

	open LEAFSTATES, "<$LeafStatesFile";

	my $temp = <LEAFSTATES>; #Pass through the first (unimportant) line of phylip traits file detailing the number of traits and number of species

	my ($NumberOfSpecies,$NumberOfTraits) = split(/\s+/,$temp);

	if($TraitLabelsProvided){

		@TraitLabels = @$TraitLabelsArrayRef;
		@{$TraitLookUp}{@TraitLabels}=(0 .. $NumberOfTraits-1); #Create a dictionary that maps trait label to position in the string of position - use substr to get the values out

	}else{

		@TraitLabels = (1 .. $NumberOfTraits);
		@{$TraitLookUp}{@TraitLabels}=(0 .. $NumberOfTraits-1);#Create a dictionary that maps trait label to position in the string of position - use substr to get the values out
	}

	die "Different number of species in input file than in the tree! $NumberOfSpecies in file \n\n" unless ($NumberOfSpecies == scalar(@{$TreeHash->{$root}{'Clade_Leaves'}}));

	my $NodeNameMapper ={};
	@{$NodeNameMapper}{(map{$TreeHash->{$_}{'node_id'}}(@{$TreeHash->{$root}{'all_Descendents'}}),$root)} = (@{$TreeHash->{$root}{'all_Descendents'}},$root); #Creates a dictionary of nodeID to TreeHash nodeID. These will liekly be the same for leaves, but it's a good idea to allow for flexibility

	while (my $line = <LEAFSTATES>){

		chomp $line;

		my ($CurrentNode,$AncestralStates) = split(/\s+/,$line);

		die "Bad Node Name in genome traits input file: $CurrentNode!\n" unless(exists($NodeNameMapper->{$CurrentNode})); # Bit of error checking

		@TraitLabels = (1 .. length($AncestralStates)) unless ($TraitLabelsProvided); #In case Trait labels was left undefined in input

		my $CurrentNodeID = $NodeNameMapper->{$CurrentNode};

		$TreeHash->{$CurrentNodeID}{'DolloPTraitStates'}=$AncestralStates; #A string of binary presecne/abscnece data. Use the 'Trait_String_Poistions_Lookup' entry and substr to extract the data
		$TreeHash->{$CurrentNodeID}{'DolloP_Trait_String_Poistions_Lookup'} = $TraitLookUp; #Have a copy of the trait lookup pointer in every node - it just makes things a little easier and for not much of a memory overhead
	}

close LEAFSTATES;

	##Parsed all the leaf states in. Now to work out all the other information.

	my @TreeLeaves = @{$TreeHash->{$root}{'Clade_Leaves'}};
	my @AllNodes = (@{$TreeHash->{$root}{'all_Descendents'}},$root);

	my (undef,undef,undef,$InternalNodes) = IntUnDiff(\@TreeLeaves,\@AllNodes); #Ignore all but final value returned # InUnDiff returns ($Union,$Intersection,$ListAExclusive,$ListBExclusive)

	print STDERR "Parsed Leaf States\n";

	map{$TreeHash->{$_}{'DolloPTraitStates_TempArray'}= [(undef) x $NumberOfTraits]; $TreeHash->{$_}{'DolloP_Trait_String_Poistions_Lookup'} = $TraitLookUp;}@$InternalNodes;

	#'DolloPTraitStates_TempArray' is a temporay list to store prescence of a trait. Note that undef is used to save on memory. A trait position will be set as one if the trait exists, left as undef if not

	my $TraitDetailsHash = {}; #A hash storing information about which leaves a trait is found in, the MRCA etc.

	foreach my $Trait (keys(%{$TreeHash->{$root}{'DolloP_Trait_String_Poistions_Lookup'}})){

		my $LeavesWithTrait = DolloPLeavesWithTrait($TreeHash,$root,$Trait); #ArrayRef of leaves with given trait.

		my $TraitPosition = $TraitLookUp->{$Trait};

		my $MRCA = FindMRCA($TreeHash,$root,$LeavesWithTrait);

		$TraitDetailsHash->{$Trait}=[$TraitPosition,$LeavesWithTrait,$MRCA];
	}

	my @Jobs = @AllNodes;
	my $JobHash = {};

	my $count=0;

	while(my $Job = shift(@Jobs)){

		my $Index = $count++ % $nthreads ;
		$JobHash->{$Index}=[] unless(exists($JobHash->{$Index}));
		push(@{$JobHash->{$Index}},$Job);
	}

	my @Threads;

	foreach my $iterator (keys(%$JobHash)){

		my $INPUT = {};
		@{$INPUT}{('TreeHash','TratDetails','JobHash','Iterator')} = ($TreeHash,$TraitDetailsHash,$JobHash,$iterator);

		my $Thr = threads->new(\&Parallel_DolloPStates, $INPUT);

		push(@Threads,$Thr);
	}

	map{my $ReturnedResults = $_->join(); map{$TreeHash->{$$_[0]}{'DolloPTraitStates'} = $$_[1];}@$ReturnedResults }@Threads;

	return(1);
}

=pod
=item *DolloParsimonyAncestralState($TreeHash,$root,$LeafStatesFile,$TraitLabelsArrayRef)

An implementation of the dollo parsimony principle to finding ancestral states. Tries to be effecient with memomory, but no promises (particularly when running many threads).

=cut

sub Parallel_DolloPStates($){

	my ($INPUT) = @_;

	my ($TreeHash,$TraitDetailsHash,$JobHash,$iterator) = @{$INPUT}{('TreeHash','TratDetails','JobHash','Iterator')} ;

	my $Returning = [];

	foreach my $Node (@{$JobHash->{$iterator}}){

			my $PASS = {}; #PASS I think stands for parallel assignment
			@{$PASS}{('TreeHash','TraitDetails','Node')}=($TreeHash,$TraitDetailsHash,$Node);

			my $Reults = PopulateDolloPStateAssingments($PASS);
			push(@$Returning,$Reults);
	}

	return $Returning;
}

=pod
=item *Parallel_DolloPStates($TreeHash,$TraitDetailsHash,$JobHash,$iterator)

A quick little wrapper around PopulateDolloPStateAssingments to make parallelisation easier. Please don't call directly.

=cut

sub PopulateDolloPStateAssingments($){

	my ($PASS) = @_;

	my ($TreeHash,$TraitDetailsHash,$node) = @{$PASS}{('TreeHash','TraitDetails','Node')};

	return([$node,$TreeHash->{$node}{'DolloPTraitStates'}]) if($TreeHash->{$node}{'is_Leaf'}); #Leaves already have their states assigned, so return immediately

	my @TempStateArray = (0) x scalar(keys(%$TraitDetailsHash)); #Create an array of zeros that will be updated

	foreach my $trait (keys(%$TraitDetailsHash)){

		my ($TraitPosition,$LeavesWithTrait,$MRCA) = ($TraitDetailsHash->{$trait}[0],$TraitDetailsHash->{$trait}[1],$TraitDetailsHash->{$trait}[2]);

		my @AllDescendents = @{$TreeHash->{$node}{'all_Descendents'}};
		my @CladeLeaves = @{$TreeHash->{$node}{'Clade_Leaves'}};

		next if(grep{m/$MRCA/}@AllDescendents); #If the MRCA of the trait is below this node, then we assume that it must have been created later
		next if (scalar(@$LeavesWithTrait) == 0); #There shoudln't really be any of these if the input file was appropriately formatted, but just in case.

		my (undef,$Intersection,undef,undef) = IntUnDiff($LeavesWithTrait,\@CladeLeaves); # InUnDiff returns ($Union,$Intersection,$ListAExclusive,$ListBExclusive)

		$TempStateArray[$TraitPosition] = 1 if(scalar(@$Intersection)); #i.e. if any leaves below the node being studied have the trait, then we assume it present here.
	}

	my $AncState = join('',@TempStateArray); #Stringlify the states of the node

	my $Results = [$node,$AncState];

	return $Results;
}

=pod
=item *PopulateDolloPStateAssingments($TreeHash,$Node,$TraitPosition,$LeavesWithTrait)

Function to assign dollo parsimony states to a single node, $Node. Please don't call directly.

=cut

sub dolloTraitDecoration($$$$$); #Recursive function
sub dolloTraitDecoration($$$$$){

	my ($TreeHash,$Node,$FILEHANDLE,$LeavesWithTrait,$FormatString) = @_;

	my @NodeLeafDescendents;

	unless($TreeHash->{$Node}{'is_Leaf'}){

		@NodeLeafDescendents = @{$TreeHash->{$Node}{'Clade_Leaves'}};
	}else{

		@NodeLeafDescendents = ($Node);
	}

	my (undef,$Intersection,undef,undef) = IntUnDiff($LeavesWithTrait,\@NodeLeafDescendents);

	if(scalar(@$Intersection)){

		unless($TreeHash->{$Node}{'is_Leaf'}){

			foreach my $Descendent (@{$TreeHash->{$Node}{'each_Descendent'}}){

				dolloTraitDecoration($TreeHash,$Descendent,$FILEHANDLE,$LeavesWithTrait,$FormatString);
			}
		}else{

			return(1);

		}

	}else{

		my $TraitAbsentCladeString = join(' ',map{$TreeHash->{$_}{'node_id'}}@NodeLeafDescendents);

		print $FILEHANDLE $FormatString.$TraitAbsentCladeString."\n";

		return(1);
	}

}

=pod
=item *dolloTraitDecoration($TreeHash,$MRCA,FILEHANDLE,$LeavesWithTrait,$FormatString)

Function to assign dollo parsimony estimate of a single trait on a given tree and output
the clade's recognised to a file FILEHANDLe using the style given in $FormatString.

=cut

=item * DOLLOP_Ancestral_Trait_Changes_in_Clade($TreeCacheHash,$node,$traitlabelsarray)

After running DolloParsimonyAncestralState to calculate dollo parsimony ancestral states, this function will calculate the number of traits that have been created or deleted along each branch.
These are stored in:

	$TreeCacheHash->{$node}{'DOLLOP_Number_Created'}
	$TreeCacheHash->{$node}{'DOLLOP_Number_Deleated'}

Also present for each node are:

	$TreeCacheHash->{$node}{'DOLLOP_Total_Number_Created'}
	$TreeCacheHash->{$node}{'DOLLOP_Total_Number_Deleated'}

=cut

sub DOLLOP_Ancestral_Trait_Changes_in_Clade{ #Left out the prototyping arguments as its a recursive function. Be careful

	my ($TreeCacheHash,$node,$root,$traitlabelsarray) = @_;

	my $TraitLabelsProvided = (@_ < 4)?0:1; #Flag for is a list of trait labels provided - these are the traits that we wish to act upon. If nothign is provided, then all traits will be used
	@$traitlabelsarray = (keys(%{$TreeCacheHash->{$root}{'DolloP_Trait_String_Poistions_Lookup'}})) unless($TraitLabelsProvided); #If no traits were provided, assume that all labels are wanted

	die "No entries in '$TreeCacheHash->{$root}{'DolloP_Trait_String_Poistions_Lookup'}'. Run DolloParsimonyAncestralState first before using this function." unless(exists($TreeCacheHash->{$root}{'DolloP_Trait_String_Poistions_Lookup'}));

	my @AncestorStates;
	my $TraitsPositionsLookup = $TreeCacheHash->{$node}{'DolloP_Trait_String_Poistions_Lookup'}; #All traits are stored as a logn string like 01001010010. We use substr to extract the one we want. This dictionary simply maps from trait to position

	if($node eq $root){

		@AncestorStates = (0) x scalar(@$traitlabelsarray); #If the node is the root, then all prescent traits are assumed to have been created beforehand. So it's ancestor will be all 0's.

	}else{

		my $Ancestor = $TreeCacheHash->{$node}{'ancestor'};
		my $AncestorStateString = $TreeCacheHash->{$Ancestor}{'DolloPTraitStates'};
		@AncestorStates = map{substr($AncestorStateString,$_,1)}(@{$TraitsPositionsLookup}{@$traitlabelsarray});
	}

	my $NodeStateString = $TreeCacheHash->{$node}{'DolloPTraitStates'};
	my @NodeStates = map{substr($NodeStateString,$_,1)}(@{$TraitsPositionsLookup}{@$traitlabelsarray});

	my ($no_creations,$no_deletions) = (0,0);

	foreach my $TraitIndex (0 .. (scalar(@$traitlabelsarray)-1)){

		my ($AncestorState,$NodeState) = ($AncestorStates[$TraitIndex],$NodeStates[$TraitIndex]);

		next if ($AncestorState ~~ '?' || $NodeState ~~ '?');

		die "Only binary states supported  $AncestorState $NodeState \n" unless ( scalar(grep{$_ == $AncestorState}(0,1)) && scalar(grep{$_ == $NodeState}(0,1)));

		if($AncestorState - $NodeState < 0){

			$no_creations ++;

		}elsif($AncestorState - $NodeState > 0){

			$no_deletions ++;
		}
	}

	$TreeCacheHash->{$node}{'DOLLOP_Number_Created'} = $no_creations;
	$TreeCacheHash->{$node}{'DOLLOP_Number_Deleted'} = $no_deletions;
	#This is the number of traits created/deleted along the ancestral branch ABOVE the current node

	unless ($TreeCacheHash->{$node}{'is_Leaf'}){

		my @Children = @{$TreeCacheHash->{$node}{'each_Descendent'}};

		$TreeCacheHash->{$node}{'DOLLOP_Total_Number_Created'} = $no_creations;
		$TreeCacheHash->{$node}{'DOLLOP_Total_Number_Deleted'} = $no_deletions;

		foreach my $Child (@Children){

			 my ($Total_no_creations,$Total_no_deletions) = DOLLOP_Ancestral_Trait_Changes_in_Clade($TreeCacheHash,$Child,$root,$traitlabelsarray);
			#Notice the replacement of $node with $Child.
			#Total_no_X is the number of deletions/ creations in branches BELOW this node.
			#This will be added to the number of deletions along this nodes ancestral branch to give the total in the clade BELOW the branch beneath the ancestor of the node under study

			$TreeCacheHash->{$node}{'DOLLOP_Total_Number_Created'} += $Total_no_creations;
			$TreeCacheHash->{$node}{'DOLLOP_Total_Number_Deleted'} += $Total_no_deletions;
		}

		my ($Total_no_creations,$Total_no_deletions) = ($TreeCacheHash->{$node}{'DOLLOP_Total_Number_Created'},$TreeCacheHash->{$node}{'DOLLOP_Total_Number_Deleted'});

		return($Total_no_creations,$Total_no_deletions);

	}else{

		$TreeCacheHash->{$node}{'DOLLOP_Total_Number_Created'} = $no_creations;
		$TreeCacheHash->{$node}{'DOLLOP_Total_Number_Deleted'} = $no_deletions;

		return($no_creations,$no_deletions);
	}
}

1;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2005-2014 The Kuali Foundation

    Licensed under the Educational Community License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.opensource.org/licenses/ecl2.php

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<data xmlns="ns:workflow" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns:workflow resource:WorkflowData">
  <documentTypes xmlns="ns:workflow/DocumentType" xsi:schemaLocation="ns:workflow/DocumentType resource:DocumentType">
    <documentType>
      <name>DocumentTypeXmlParserTestDoc_BadNextNode</name>
      <description>This document has an invalid nextNode</description>
      <label>DocumentTypeXmlParserTestDoc_BadNextNode</label>
      <postProcessorName>org.kuali.rice.kew.postprocessor.DefaultPostProcessor</postProcessorName>
      <docHandler>_blank</docHandler>
      <superUserGroupName namespace="KR-WKFLW">TestWorkgroup</superUserGroupName>
      <blanketApproveGroupName namespace="KR-WKFLW">TestWorkgroup</blanketApproveGroupName>
      <active>true</active>
      <routePaths>
        <routePath>
          <start name="AdHoc" nextNode="end"/>
        </routePath>
      </routePaths>
      <routeNodes>
        <start name="AdHoc">
          <exceptionGroupName namespace="KR-WKFLW">TestWorkgroup</exceptionGroupName>
          <activationType>S</activationType>
        </start>
        <requests name="end">
          <exceptionGroupName namespace="KR-WKFLW">TestWorkgroup</exceptionGroupName>
          <activationType>S</activationType>
        </requests>
      </routeNodes>
    </documentType>
  </documentTypes>
</data>


text:
package com.intellij.debugger.engine;

import com.intellij.Patches;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.engine.events.SuspendContextCommandImpl;
import com.intellij.debugger.jdi.StackFrameProxyImpl;
import com.intellij.debugger.jdi.ThreadReferenceProxyImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.containers.HashSet;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ThreadReference;
import com.sun.jdi.event.EventSet;
import com.sun.jdi.request.EventRequest;
import org.jetbrains.annotations.NotNull;

import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author lex
 */
public abstract class SuspendContextImpl implements SuspendContext {
  private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.engine.SuspendContextImpl");

  private final DebugProcessImpl myDebugProcess;
  private final int mySuspendPolicy;

  private ThreadReferenceProxyImpl myThread;
  boolean myIsVotedForResume = true;

  protected int myVotesToVote;
  protected Set<ThreadReferenceProxyImpl> myResumedThreads;

  private final EventSet myEventSet;
  private volatile boolean  myIsResumed;

  public ConcurrentLinkedQueue<SuspendContextCommandImpl> myPostponedCommands = new ConcurrentLinkedQueue<SuspendContextCommandImpl>();
  public volatile boolean  myInProgress;
  private final HashSet<ObjectReference>       myKeptReferences = new HashSet<ObjectReference>();
  private EvaluationContextImpl          myEvaluationContext = null;

  SuspendContextImpl(@NotNull DebugProcessImpl debugProcess, int suspendPolicy, int eventVotes, EventSet set) {
    myDebugProcess = debugProcess;
    mySuspendPolicy = suspendPolicy;
    myVotesToVote = eventVotes;
    myEventSet = set;
  }

  public void setThread(ThreadReference thread) {
    assertNotResumed();
    ThreadReferenceProxyImpl threadProxy = myDebugProcess.getVirtualMachineProxy().getThreadReferenceProxy(thread);
    LOG.assertTrue(myThread == null || myThread == threadProxy);
    myThread = threadProxy;
  }

  protected abstract void resumeImpl();

  protected void resume(){
    assertNotResumed();
    DebuggerManagerThreadImpl.assertIsManagerThread();
    try {
      if (!Patches.IBM_JDK_DISABLE_COLLECTION_BUG) {
        for (ObjectReference objectReference : myKeptReferences) {
          try {
            objectReference.enableCollection();
          }
          catch (UnsupportedOperationException e) {
            // ignore: some J2ME implementations does not provide this operation
          }
        }
        myKeptReferences.clear();
      }

      for(SuspendContextCommandImpl cmd = myPostponedCommands.poll(); cmd != null; cmd = myPostponedCommands.poll()) {
        cmd.notifyCancelled();
      }

      resumeImpl();
    }
    finally {
      myIsResumed = true;
    }
  }

  private void assertNotResumed() {
    if (myIsResumed) {
      if (myDebugProcess.isAttached()) {
        LOG.error("Cannot access SuspendContext. SuspendContext is resumed.");
      }
    }
  }

  public EventSet getEventSet() {
    assertNotResumed();
    return myEventSet;
  }

  public DebugProcessImpl getDebugProcess() {
    assertNotResumed();
    return myDebugProcess;
  }

  public StackFrameProxyImpl getFrameProxy() {
    assertNotResumed();
    try {
      return myThread != null && myThread.frameCount() > 0 ? myThread.frame(0) : null;
    }
    catch (EvaluateException e) {
      return null;
    }
  }

  public ThreadReferenceProxyImpl getThread() {
    return myThread;
  }

  public int getSuspendPolicy() {
    assertNotResumed();
    return mySuspendPolicy;
  }

  public void doNotResumeHack() {
    assertNotResumed();
    myVotesToVote = 1000000000;
  }

  public boolean isExplicitlyResumed(ThreadReferenceProxyImpl thread) {
    return myResumedThreads != null ? myResumedThreads.contains(thread) : false;
  }

  public boolean suspends(ThreadReferenceProxyImpl thread) {
    assertNotResumed();
    if(isEvaluating()) {
      return false;
    }
    switch(getSuspendPolicy()) {
      case EventRequest.SUSPEND_ALL:
        return !isExplicitlyResumed(thread);
      case EventRequest.SUSPEND_EVENT_THREAD:
        return thread == getThread();
    }
    return false;
  }

  public boolean isEvaluating() {
    assertNotResumed();
    return myEvaluationContext != null;
  }

  public EvaluationContextImpl getEvaluationContext() {
    return myEvaluationContext;
  }

  public boolean isResumed() {
    return myIsResumed;
  }

  public void setIsEvaluating(EvaluationContextImpl evaluationContext) {
    assertNotResumed();
    myEvaluationContext = evaluationContext;
  }

  public String toString() {
    if (myEventSet != null) {
      return myEventSet.toString();
    }
    return myThread != null ? myThread.toString() : DebuggerBundle.message("string.null.context");
  }

  public void keep(ObjectReference reference) {
    if (!Patches.IBM_JDK_DISABLE_COLLECTION_BUG) {
      final boolean added = myKeptReferences.add(reference);
      if (added) {
        try {
          reference.disableCollection();
        }
        catch (UnsupportedOperationException e) {
          // ignore: some J2ME implementations does not provide this operation
        }
      }
    }
  }

  public void postponeCommand(final SuspendContextCommandImpl command) {
    if (!isResumed()) {
      myPostponedCommands.add(command);
    }
    else {
      command.notifyCancelled();
    }
  }

  public SuspendContextCommandImpl pollPostponedCommand() {
    return myPostponedCommands.poll();
  }
}


text:
package net

import (
	"encoding/json"
	"strconv"
	"time"

	"github.com/cloudfoundry/cli/cf/configuration/coreconfig"
	"github.com/cloudfoundry/cli/cf/errors"
	"github.com/cloudfoundry/cli/cf/terminal"
	"github.com/cloudfoundry/cli/cf/trace"
)

type ccErrorResponse struct {
	Code        int
	Description string
}

const invalidTokenCode = 1000

func cloudControllerErrorHandler(statusCode int, body []byte) error {
	response := ccErrorResponse{}
	json.Unmarshal(body, &response)

	if response.Code == invalidTokenCode {
		return errors.NewInvalidTokenError(response.Description)
	}

	return errors.NewHTTPError(statusCode, strconv.Itoa(response.Code), response.Description)
}

func NewCloudControllerGateway(config coreconfig.Reader, clock func() time.Time, ui terminal.UI, logger trace.Printer) Gateway {
	gateway := newGateway(cloudControllerErrorHandler, config, ui, logger)
	gateway.Clock = clock
	gateway.PollingEnabled = true
	return gateway
}