text:
<instance description="always on speed boost." template="abilities">
	<group name="ability_bag">
		<group name="action_list">
			<list name="end_self_actions">
			</list>
			<list name="end_target_actions">
			</list>
			<list name="start_self_actions">
				<template_reference name="action" value="action\apply_modifiers_action">
					<float name="duration" value="0" />
					<bool name="permanent" value="False" />
					<list name="modifiers">
						<template_reference name="modifier" value="modifiers\posture_speed_modifier">
							<enum name="application_type" value="apply_to_entity" />
							<bool name="exclusive" value="False" />
							<string name="modifier_id" value="" />
							<string name="target_type_name" value="" />
							<enum name="usage_type" value="addition" />
							<float name="value" value="0.75" />
							<instance_reference name="tooltip" value="modifier_tooltip\posture_speed_modifier" />
						</template_reference>
					</list>
					<uniqueid name="id" value="1073747969" />
				</template_reference>
				<template_reference name="action" value="action\ui_unit_modifier_action">
					<bool name="die_with_creator" value="True" />
					<template_reference name="ui_info" value="tables\ui_info">
						<locstring name="screen_name" value="350" mod="95f9ec3171c849d792717e865bd5e612" />
						<locstring name="help_text" value="351" mod="95f9ec3171c849d792717e865bd5e612" />
						<icon name="icon_name" value="Icons_abilities_ability_west_german_jaeger_sprint" />
						<string name="hotkey_name" value="" />
					</template_reference>
					<uniqueid name="id" value="1073747970" />
				</template_reference>
				<template_reference name="action" value="action\requirement_action">
					<bool name="check_self" value="False" />
					<bool name="global_fire_and_forget_on_success" value="False" />
					<bool name="instant_requirement_check" value="False" />
					<bool name="kill_action_on_failed_requirements" value="False" />
					<bool name="no_retrigger" value="False" />
					<bool name="validate_all_sub_actions" value="True" />
					<list name="requirement_table">
						<template_reference name="required" value="requirements\required_not">
							<enum name="reason" value="usage" />
							<locstring name="ui_name" value="0" />
							<list name="requirement_table">
								<template_reference name="required" value="requirements\required_in_state">
									<enum name="reason" value="usage" />
									<locstring name="ui_name" value="0" />
									<bool name="garrisoned" value="True" />
									<bool name="healed" value="False" />
									<float name="in_combat_since" value="5" />
									<bool name="injured" value="False" />
									<bool name="leader" value="False" />
									<bool name="not_moving" value="False" />
									<bool name="not_retreating" value="False" />
									<bool name="pinned" value="True" />
									<bool name="suppressed" value="True" />
								</template_reference>
							</list>
						</template_reference>
					</list>
					<list name="action_table">
					</list>
					<uniqueid name="id" value="1073747972" />
					<bool name="fire_and_forget_non_global" value="False" />
					<template_reference name="ui_help_text" value="tables\help_text_phrase">
						<int name="phrase_order" value="0" />
						<locstring name="phrase" value="0" />
					</template_reference>
				</template_reference>
			</list>
			<list name="start_target_actions">
			</list>
		</group>
		<enum name="activation" value="always_on" />
		<bool name="can_interrupt" value="True" />
		<bool name="can_target_in_fow" value="False" />
		<float name="caster_close_in_distance" value="2" />
		<bool name="casters_can_evacuate" value="False" />
		<group name="cost">
			<float name="action" value="0" />
			<float name="command" value="0" />
			<float name="fuel" value="0" />
			<float name="manpower" value="0" />
			<float name="munition" value="0" />
			<float name="popcap" value="0" />
		</group>
		<string name="cursor_ghost_blueprint" value="" />
		<float name="cursor_ghost_blueprint_angle" value="0" />
		<bool name="disable_combat" value="False" />
		<bool name="disable_when_active" value="False" />
		<float name="duration_time" value="0" />
		<bool name="enable_in_building" value="False" />
		<bool name="enable_in_vehicle" value="False" />
		<bool name="engage_combat" value="False" />
		<float name="entity_busy_time" value="0" />
		<float name="facing_angle" value="5" />
		<bool name="facing_ignore" value="False" />
		<float name="final_close_in_distance" value="0" />
		<bool name="fire_and_forget" value="False" />
		<bool name="garrison_target" value="False" />
		<bool name="has_speech_code" value="True" />
		<float name="initial_delay_time" value="0" />
		<bool name="initial_recharge" value="False" />
		<bool name="is_default_action" value="False" />
		<bool name="move_back" value="False" />
		<float name="move_back_distance" value="0" />
		<float name="range" value="0" />
		<bool name="range_ignore" value="True" />
		<float name="recharge_time" value="0" />
		<bool name="refundable" value="False" />
		<bool name="require_no_shot_block" value="False" />
		<enum name="shared_timer" value="" />
		<bool name="shared_timer_player_wide" value="False" />
		<group name="speech_code_2">
			<string name="code_1" value="" />
			<string name="code_2" value="" />
			<string name="code_3" value="" />
		</group>
		<group name="speech_code_3">
			<string name="code_1" value="spr" />
			<string name="code_2" value="" />
			<string name="code_3" value="" />
		</group>
		<enum name="squad_caster" value="squad" />
		<enum name="target" value="tp_any" />
		<group name="target_special_validation">
			<template_reference name="target_special_validation" value="type_ability_target_type\all">
			</template_reference>
		</group>
		<float name="toggled_recharge_time_off" value="0" />
		<float name="toggled_recharge_time_on" value="0" />
		<group name="ui_cursor">
			<string name="cursor_bad" value="modal_ability_cancel" />
			<string name="cursor_good" value="modal_ability" />
			<string name="cursor_nonmodal_good" value="" />
		</group>
		<group name="ui_info">
			<locstring name="extra_text" value="0" />
			<locstring name="help_text" value="0" />
			<string name="hotkey_name" value="" />
			<icon name="icon_name" value="" />
			<string name="overlay_name" value="" />
			<bool name="reveal_for_decryption" value="False" />
			<locstring name="screen_name" value="0" />
			<icon name="icon_alternate_name" value="" />
			<locstring name="brief_text" value="0" />
			<locstring name="help_text_alternate" value="0" />
			<locstring name="screen_name_alternate" value="0" />
			<locstring name="screen_name_short" value="0" />
		</group>
		<locstring name="ui_usage_txt" value="0" />
		<bool name="validate_actions" value="False" />
		<list name="global_self_actions">
		</list>
		<list name="requirements">
			<template_reference name="required" value="requirements\required_all_in_list">
				<enum name="reason" value="usage" />
				<locstring name="ui_name" value="0" />
				<list name="requirements">
					<template_reference name="requirement" value="requirements\required_not">
						<enum name="reason" value="usage" />
						<locstring name="ui_name" value="0" />
						<list name="requirement_table">
							<template_reference name="required" value="requirements\required_in_state">
								<enum name="reason" value="usage" />
								<locstring name="ui_name" value="0" />
								<bool name="garrisoned" value="True" />
								<bool name="healed" value="False" />
								<float name="in_combat_since" value="5" />
								<bool name="injured" value="False" />
								<bool name="leader" value="False" />
								<bool name="not_moving" value="False" />
								<bool name="not_retreating" value="False" />
								<bool name="pinned" value="True" />
								<bool name="suppressed" value="True" />
							</template_reference>
						</list>
					</template_reference>
					<template_reference name="requirement" value="requirements\required_all_in_list">
						<enum name="reason" value="usage" />
						<locstring name="ui_name" value="0" />
						<list name="requirements">
						</list>
					</template_reference>
				</list>
			</template_reference>
			<template_reference name="required" value="requirements\required_player_upgrade">
				<enum name="reason" value="usage" />
				<locstring name="ui_name" value="0" />
				<bool name="is_present" value="True" />
				<float name="max_completed" value="100" />
				<float name="min_completed" value="1" />
				<instance_reference name="upgrade_name" value="upgrade\german\commander\passive\sprint" />
			</template_reference>
		</list>
		<enum name="ability_super" value="tp_artillery" />
		<int name="ui_position" value="-1" />
		<bool name="ui_mini_map_capture" value="False" />
		<bool name="facing_ignore_during_active" value="False" />
		<instance_reference name="ui_range" value="" />
		<instance_reference name="ui_reticule" value="" />
		<float name="ui_reticule_radius_min" value="1" />
		<float name="ui_reticule_radius_max" value="1" />
		<enum name="pending_ability_out_of_range_behaviour" value="chase" />
		<enum name="ui_group" value="group_primary" />
		<string name="ui_targetable_sm_key" value="" />
		<string name="ui_targetable_on_key" value="" />
		<string name="ui_targetable_off_key" value="" />
		<enum name="ui_targetable_receiver" value="local" />
		<enum name="ui_combine_type" value="intersection" />
		<enum_table name="ui_modal_highlight">
			<bool name="world_sector" value="False" />
			<bool name="map_sector" value="False" />
			<bool name="map_sector_hq_link_extender" value="False" />
		</enum_table>
		<enum name="ui_group_cast_type" value="single" />
		<list name="requirements_target">
		</list>
		<template_reference name="targeted_ability_option" value="options\none">
		</template_reference>
		<enum name="ui_direction_requirement" value="nondirectional" />
		<instance_reference name="cursor_ghost_ebp" value="" />
		<bool name="can_cast_whilst_constructing" value="False" />
		<list name="requirements_self_recharge">
		</list>
		<bool name="ability_super_event_cue" value="False" />
	</group>
	<uniqueid name="pbgid" value="1073741877" />
</instance>


text:
<!DOCTYPE html>
<html>

  {% include head.html %}

  <body>

    {% include header.html %}

        {{ content }}

    {% include footer.html %}
    {% include backToTop.html %}
    <script src="{{"/js/main.js " | prepend: site.cssurl }}" charset="utf-8"></script>
    <script src="{{"/js/smooth-scroll.min.js " | prepend: site.cssurl }}" charset="utf-8"></script>
    <script type="text/javascript">
      smoothScroll.init({
        speed: 500, // Integer. How fast to complete the scroll in milliseconds
        easing: 'easeInOutCubic', // Easing pattern to use
        offset: 20, // Integer. How far to offset the scrolling anchor location in pixels
      });
    </script>
    <!-- <script src="{{"/js/scroll.min.js " | prepend: site.cssurl }}" charset="utf-8"></script> -->
  </body>

</html>

redpajama_set_name: RedPajamaGithub


text:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <mpk/stringlist.h>
#include <mpk/pkgref.h>
#include <mpk/defines.h>

#define MPM_CLIENT_VERSION "0.1.0"

enum COMMAND {
    COMMAND_UNDEFINED,
    COMMAND_VERSION,
    COMMAND_HELP,
    COMMAND_STATUS,
    COMMAND_INSTALL,
    COMMAND_REMOVE,
    COMMAND_RELEASE
};

void show_usage()
{
    fprintf(stderr, "usage: \n"
        "  mpm-client status\n"
        "  mpm-client install [PACKAGE ...]\n"
        "  mpm-client remove [PACKAGE ...]\n"
        "  mpm-client change-release RELEASE\n"
        "  mpm-client help\n"
        "  mpm-client version\n"
    );
}

void show_version()
{
    fprintf(stderr, "MPK Package Management Client Version %s\n",
        MPM_CLIENT_VERSION);
}

enum COMMAND parse_commandline(int argc, char *argv[],
    struct mpk_stringlist *pkgs, const char **param)
{
    enum COMMAND cmd = COMMAND_UNDEFINED;

    if (argc <= 1) {
        return COMMAND_UNDEFINED;
    }

    argv++;

    if (strcmp("help", *argv) == 0) {
        cmd = COMMAND_HELP;
    } else if (strcmp("version", *argv) == 0) {
        cmd = COMMAND_VERSION;
    } else if (strcmp("status", *argv) == 0) {
        cmd = COMMAND_STATUS;
    } else if (strcmp("install", *argv) == 0) {
        cmd = COMMAND_INSTALL;
        argv++;
        int cnt = 0;
        for(; *argv; argv++) {
            if (mpk_stringlist_add(pkgs, *argv) != MPK_SUCCESS) {
                cmd = COMMAND_UNDEFINED;
                mpk_stringlist_empty(pkgs);
                break;
            }
            cnt++;
        }
        if (!cnt) {
            cmd = COMMAND_UNDEFINED;
        }
    } else if (strcmp("remove", *argv) == 0) {
        cmd = COMMAND_REMOVE;
        argv++;
        int cnt = 0;
        for(; *argv; argv++) {
            if (mpk_stringlist_add(pkgs, *argv) != MPK_SUCCESS) {
                cmd = COMMAND_UNDEFINED;
                mpk_stringlist_empty(pkgs);
                break;
            }
            cnt++;
        }
        if (!cnt) {
            cmd = COMMAND_UNDEFINED;
        }
    } else if (strcmp("change-release", *argv) == 0) {
        cmd = COMMAND_RELEASE;
        argv++;
        if (!*argv || (*(argv + 1) != 0)) {
            cmd = COMMAND_UNDEFINED;
        } else {
            *param = *argv;
        }
    } else {
        cmd = COMMAND_UNDEFINED;
    }

    return cmd;
}

int install_packages(struct mpk_stringlist *packages)
{
    return MPK_FAILURE;
}

int remove_packages(struct mpk_stringlist *packages)
{
    return MPK_FAILURE;
}

int change_release(const char *release)
{
    return MPK_FAILURE;
}

int main(int argc, char *argv[])
{
    struct mpk_stringlist packages;
    const char *param = NULL;

    if (mpk_stringlist_init(&packages) != MPK_SUCCESS) {
        fprintf(stderr, "mpk_stringlist_init() failed\n");
        return EXIT_FAILURE;
    }

    switch (parse_commandline(argc, argv, &packages, &param)) {
    case COMMAND_STATUS:
        /* TODO: print status from database */
        fprintf(stderr, "command status is not yet implemented\n");
        break;
    case COMMAND_INSTALL:
        if (install_packages(&packages) != MPK_SUCCESS) {
            fprintf(stderr, "install_packages() failed\n");
        }
        break;
    case COMMAND_REMOVE:
        if (remove_packages(&packages) != MPK_SUCCESS) {
            fprintf(stderr, "remove_packages() failed\n");
        }
        break;
    case COMMAND_RELEASE:
        if (change_release(param) != MPK_SUCCESS) {
            fprintf(stderr, "change_release() failed\n");
        }
        break;
    case COMMAND_VERSION:
        show_version();
        break;
    case COMMAND_UNDEFINED:
    default:
        fprintf(stderr, "invalid arguments\n");
    case COMMAND_HELP:
        show_usage();
    }

    mpk_stringlist_empty(&packages);

    return EXIT_SUCCESS;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">

    <com.wikitude.architect.ArchitectView
        android:id="@+id/architectView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <View
        android:id="@+id/dimOverlay"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/dimOverlay" />

    <TextView
        android:id="@+id/hintForUser"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@android:color/white"
        android:textSize="16dp" />

    <ProgressBar
        android:id="@+id/progress"
        style="?android:attr/android:progressBarStyleHorizontal"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="invisible" />

    <ProgressBar
        android:id="@+id/progressSpinner"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

    <Button
        android:id="@+id/switchButton"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_gravity="bottom|center"
        android:layout_marginBottom="20dp"
        android:fontFamily="sans-serif"
        android:text="@string/switch_channel"
        android:textSize="12dp"
        android:visibility="gone" />

    <Button
        android:id="@+id/retryButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/retry"
        android:layout_gravity="bottom|center"
        android:layout_marginBottom="20dp"
        android:textSize="12dp"
        android:visibility="gone" />

    <Button
        android:id="@+id/cancelButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cancel"
        android:layout_gravity="bottom|center"
        android:layout_marginBottom="20dp"
        android:textSize="12dp"
        android:visibility="gone" />
</FrameLayout>


text:
DELIMITER /
CREATE TABLE IACUC_PROCEDURE_CATEGORY (
    PROCEDURE_CATEGORY_CODE DECIMAL(3,0) NOT NULL,
    PROCEDURE_CATEGORY VARCHAR(200) NOT NULL,
    ACTIVE_FLAG CHAR(1) NOT NULL,
    UPDATE_TIMESTAMP DATE NOT NULL,
    UPDATE_USER VARCHAR(60) NOT NULL,
    VER_NBR DECIMAL(8,0) DEFAULT 1 NOT NULL,
    OBJ_ID VARCHAR(36) NOT NULL) ENGINE InnoDB CHARACTER SET utf8 COLLATE utf8_bin
/

ALTER TABLE IACUC_PROCEDURE_CATEGORY
ADD CONSTRAINT PK_IACUC_PROCEDURE_CATEGORY
PRIMARY KEY (PROCEDURE_CATEGORY_CODE)
/

DELIMITER ;


text:
<?xml version="1.0" encoding="UTF-8"?>
<template>
    <param name="clip" type="definition"/>
    <param name="target" type="component"/>
    <elems>
        <component id="target" fillComponent="true" clip-path="url(#${clip})"/>
    </elems>
</template>


text:
//
//  CentralManagerVC.m
//  BlueTooth
//
//  Created by 1512共享 on 16/2/23.
//  Copyright (c) 2016年 shishu. All rights reserved.
//

#import "CentralManager.h"
#import <CoreBluetooth/CoreBluetooth.h>

#define TRANSFER_SERVICE_UUID           @"E20A39F4-73F5-4BC4-A12F-17D1AD07A961"

//对方的账号
#define TRANSFER_CHARACTERISTIC_UUID    @"08590F7E-DB05-467E-8757-72F6FAEB13D4"

@interface CentralManager ()<CBCentralManagerDelegate,CBPeripheralDelegate>
{
    CBCentralManager *manager;
    NSMutableArray *_dicoveredPeripherals;
    CBPeripheral *_testPeripheral;
}

@end

@implementation CentralManager

//1.建立中心角色
//2.扫描外设(discover)
//3.连接外设(connect)
//4.扫描外设中的服务和特征(discover)
//5.与外设做数据交互(explore and interact)
//6.断开连接(disconnect)。

+(id)sharedInstance
{
    static id instance = nil;
    if(instance == nil)
    {
        instance = [[self alloc] init];

    }
    return instance;
}

//
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    // CBCentralManagerStatePoweredOn = 5
    NSLog(@"state = %ld",central.state);
}

#pragma mark - 扫描和扫描事件处理

-(void)startCreateAndScan
{
    //创建中心设备对象
    manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    //开始扫描外设
    //options中的意思是否允许中央设备多次收到曾经监听到的设备的消息,这样来监听外围设备联接的信号强度,以决定是否增大广播强度,为YES时会多耗电
    _dicoveredPeripherals = [[NSMutableArray alloc] init];

    //扫描
    [manager scanForPeripheralsWithServices:nil options:@{ CBCentralManagerScanOptionAllowDuplicatesKey:@NO}];

    NSLog(@"开始扫描");
}

//发现周边设备时执行
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{

    if(![_dicoveredPeripherals containsObject:peripheral])
        [_dicoveredPeripherals addObject:peripheral];

    NSLog(@"dicoveredPeripherals:%@", _dicoveredPeripherals);
    //<CBPeripheral: 0x1780ad800 identifier = 20B955DC-119F-CD1E-3458-2563E9496F54, Name = \"(null)\", state = disconnected>"

    //选择需要的设备,发起链接
    [self connect:peripheral];

}

#pragma mark - 连接操作
//连接指定的设备
-(BOOL)connect:(CBPeripheral *)peripheral
{
    NSLog(@"开始连接");

    [manager connectPeripheral:peripheral
                       options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];

    return YES;
}

//连接上外围设备后我们就要找到外围设备的服务特性
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"已经连接");

    //连接完成后,就停止检测
    [manager stopScan];

    //[self.data setLength:0];
    //确保我们收到的外围设备连接后的回调代理函数

    NSLog(@"开始发现服务");

    peripheral.delegate=self;
    //告诉外围设备,谁与外围设备连接
    //[peripheral discoverServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]];
    [peripheral discoverServices:nil];

}

//断开链接
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"disconnected");
}

#pragma mark - 发现服务操作和处理

//相当于对方的账号
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{

    NSLog(@"已经发现服务");
    if (error) {
        NSLog(@"Errordiscover:%@",error.localizedDescription);
        //[self clearUp];
        return;
    }
    //找到我们想要的特性
    //遍历外围设备的服务
    for (CBService*server in peripheral.services) {
        [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]] forService:server];
    }

}

#pragma mark - 发现特性后的处理, 添加订阅

//当发现传送服务特性后我们要订阅他 来告诉外围设备我们想要这个特性所持有的数据
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{

    if (error) {
        NSLog(@"error  %@",[error localizedDescription]);
        //[self clearUp];
        return;
    }
    //检查特性
    for (CBCharacteristic*characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
            NSLog(@"找到所需特性");

            //有来自外围的特性,找到了,就订阅他
            // 如果第一个参数是yes的话,就是允许代理方法peripheral:didUpdateValueForCharacteristic:error: 来监听 第二个参数 特性是否发生变化
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            //完成后,等待数据传进来
            NSLog(@"订阅成功");

        }
    }

}

//外围设备让我们知道,我们订阅和取消订阅是否发生
-(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error) {
        NSLog(@"error  %@",error.localizedDescription);
    }
    //如果不是我们要特性就退出
    if (![characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
        return;
    }

    if (characteristic.isNotifying) {
        NSLog(@"外围特性通知开始");
    }else{
        NSLog(@"外围设备特性通知结束,也就是用户要下线或者离开%@",characteristic);
        //断开连接
        [manager cancelPeripheralConnection:peripheral];

    }
}

#pragma mark - 特征上数据更新事件处理

//这个函数类似网络请求时候只需收到数据的那个函数
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error) {
        NSLog(@"error~~%@",error.localizedDescription);
        return;
    }
    //characteristic.value 是特性中所包含的数据
    NSString*stringFromData=[[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding];
    NSLog(@"接收到得数据: %@",stringFromData);

    //回传了数据
    self.recivData(characteristic.value);

    /*
     if ([stringFromData isEqualToString:BluetoothEnd]) {
     //完成发送,调用代理进行传递self.data
     NSString*str=[[NSString alloc]initWithData:self.data encoding:NSUTF8StringEncoding];
     //取消订阅
     [peripheral setNotifyValue:NO forCharacteristic:characteristic];
     [self.centralManager cancelPeripheralConnection:peripheral];
     self.blockValue(str);

     }else{
     //数据没有传递完成,继续传递数据
     [self.data appendData:characteristic.value];

     }
     */
}

@end


text: GNU Lesser General Public License v2.1 generator


text:
<wm-card title="smart table">
    <div class="ng2-smart-table-container">
        <ng2-smart-table [settings]="settings" [source]="data"></ng2-smart-table>
    </div>
</wm-card>


text:
package de.fau.cs.mad.kwikshop.android.common;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

import de.fau.cs.mad.kwikshop.common.Group;

@DatabaseTable(tableName = "autoCompletionData")
public class AutoCompletionData {

    /**
     * unique id generated by storage
     */
    @DatabaseField(generatedId = true)
    private int id;

    /**
     * the item name that was entered by a user
     */
    @DatabaseField(canBeNull = false)
    private String name;

    /**
     * the group that was set the last time for that item
     */
    @DatabaseField(foreign = true, foreignAutoRefresh = true)
    private Group group;

    public AutoCompletionData() {
        // Default no-arg constructor for generating Groups, required for ORMLite
    }

    public AutoCompletionData(String name) {
        this.name = name;
    }

    public AutoCompletionData(String name, Group group) {
        this.name = name;
        this.group = group;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Group getGroup() {
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    /**
     * Comparison, if another object is the same as this object.
     * Two AutoCompletionDatas are considered the same, if the name is identical
     */
    @Override
    public boolean equals(Object obj){
        if (obj == null)
            return false;
        if (this == obj)
            return true;
        if (obj.getClass() != this.getClass())
            return false;
        AutoCompletionData autoCompletionData = (AutoCompletionData)obj;
        return this.name.equals(autoCompletionData.getName());
    }

    @Override
    public int hashCode() {
        return this.name.hashCode();
    }
}


text:
subdir=src/backend/utils/init
top_builddir=../../../../..
include $(top_builddir)/src/Makefile.global

TARGETS=postinit

include $(top_srcdir)/src/backend/mock.mk

postinit.t: \
	$(MOCK_DIR)/backend/utils/error/elog_mock.o \
	$(MOCK_DIR)/backend/storage/lmgr/proc_mock.o


text:
package org.ovirt.engine.core.dao;

import static org.mockito.Mockito.mock;

import org.junit.Before;
import org.junit.Test;
import org.ovirt.engine.core.compat.Guid;

/**
 * A sparse test case for {@DiskImageDAOWrapperImpl}
 * intended to fail once we start implementing actual methods
 */
public class DiskImageDAOWrapperImplTest {
    /** The DAO to test */
    private DiskImageDAOWrapperImpl dao;

    @Before
    public void setUp() {
        dao = new DiskImageDAOWrapperImpl();
    }

    @Test (expected=UnsupportedOperationException.class)
    public void testUnimplementedMethods() {
        dao.getAllForVm(mock(Guid.class), mock(Guid.class), true);
    }
}


text:
class Api::UsersController < Api::ApplicationController
  before_filter :set_user, only: [:activities]

  def activities(page: nil)
    @activities = @user.activities
                    .includes(:recipient, :trackable, :user)
                    .order(created_at: :desc)
                    .page(page)
  end

  private

  def set_user
    @user = User.find_by!(username: params[:user_id])
  end
end


text:
OakSingleLineCommentSplitRule :: OakSingleLineCommentSplitRule ()
{
}

OakSingleLineCommentSplitRule :: ~OakSingleLineCommentSplitRule ()
{
}

void OakSingleLineCommentSplitRule :: TrySplit ( const std :: u32string & Source, uint64_t Offset, TokenSplitResult & Result )
{

	if ( Source.size () - Offset < 3 )
	{

		Result.Accepted = false;

		return;

	}

	if ( ( Source.at ( Offset ) != U'/' ) || ( Source.at ( Offset + 1 ) != U'/' ) )
	{

		Result.Accepted = false;

		return;

	}

	Result.Accepted = true;
	Result.Tag = OakTokenTags :: kTokenTag_Comment;

	uint64_t CommentLength = 2;

	while ( CommentLength < ( Source.size () - Offset ) )
	{

		if ( Source.at ( Offset + CommentLength ) == '\n' )
		{

			Result.SplitLength = CommentLength + 1;

			return;

		}

		CommentLength ++;

	}

	Result.SplitLength = Source.size () - Offset;

}


text:
import subprocess
from utils import *

@all_files_in_dir('util_clk_reset')
@all_available_simulators()
def test_mock_uvm_report(datafiles, simulator):
    with datafiles.as_cwd():
        subprocess.check_call(['runSVUnit', '-s', simulator])
        expect_testrunner_pass('run.log')


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">

  <title>PandemoniuM</title>
  <meta http-equiv="content-owner" content="Rubén Béjar">
  <meta http-equiv="keywords" content="heavy metal, metal, power metal, reviews, críticas, discos, albums, cds">
  <meta name="description" content="Página principal de Pandemonium, sitio de las críticas de albums de Heavy Metal escritas por Rubén Béjar.">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <link rel="stylesheet" type="text/css" href="common/pstyle.css">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Rubén Béjar

Bienvenidos a Pandemonium. En estas páginas encontraréis críticas de álbums de heavy metal, alternando
los más recientes con otros más antiguos pero de los que me apetezca escribir una crítica.
Intentaré mantener el sitio lo más actualizado que pueda aunque eso dependerá, entre otras cosas, del
tiempo libre que tenga y de vuestro interés.

Cambios Recientes

24 de Julio de 2007

Cierre y mudanza
 Por diversas razones he decidido que PandemoniuM debía llegar a su
final en su estado actual, pero voy a continuar escribiendo críticas
en mi nuevo blog, que se llama
Gardens of the Sinner. Va a haber algunos cambios, que
están explicados en el
primer post de este blog. PandemoniuM se mantendrá online, aunque sin
tener nuevas actualizaciones, el tiempo que
me dejen, porque las críticas que hay aquí pueden seguir siendo interesantes
para alguien. Un saludo, y nos vemos por mi nuevo blog.

1 de Enero de 2007

Feliz año a todos! Y como pasa el tiempo, más de un mes
sin colgar nada... En fin, aquí va un peso pesado,
aunque con nombre nuevo:
Triumph or
Agony, de los italianos Rhapsody of Fire,
anteriormente conocidos simplemente como Rhapsody.

26 de Noviembre de 2006

Hoy voy con uno que salió a primeros de año, pero que
no había escuchado hasta hace poco:
Inhuman Rampage, del grupo británico Dragonforce.

12 de Noviembre de 2006

Me toca revisar el último disco de una de las bandas alemanas
más importantes del power metal: Blind Guardian, que se
titula A Twist in
the Myth.

15 de Octubre de 2006

Hoy os presento el segundo álbum de la banda danesa Pyramaze, que
se titula Legend of the
Bone Carver.

1 de Octubre de 2006

Estrenamos el mes de Octubre con el segundo disco del grupo italiano
Shining Fury, titulado
Another Life.

17 de Septiembre de 2006

De nuevo una banda alemana en PandemoniuM. Esta vez
es el segundo álbum de los "powermetaleros" Galloglass titulado
Heavenseeker.

3 de Septiembre de 2006

Tras el paréntesis veraniego, he escrito la crítica del último
disco de Vision Divine, que se llama
The Perfect Machine.

23 de Julio de 2006

Hoy he subido la revisión del tercer disco en solitario de
Luca Turilli, titulado
The Infinite Wonders of Creation.

2 de Julio de 2006

Aunque el calor de verano siempre provoca cierta pereza,
he escrito la crítica del tercer álbum del grupo finlandés
Korpiklaani, titulado
Tales Along This Road.

11 de Junio de 2006

Primer disco del grupo sueco Destynation, surgido de las
cenizas de Eternia, que se llama
Rising Up.

4 de Junio de 2006

La banda At Vance sacó el año pasado su sexto disco,
Chained, y tocaba
darle un vistazo para comprobar como han evolucionado
en los últimos años.

21 de Mayo de 2006

Hoy toca revisar el último disco de After Forever,
llamado Remagine.

1 de Mayo de 2006

El séptimo álbum de la banda alemana Edguy ya lleva algunos
meses con nosotros y se titula Rocket Ride.

16 de Abril de 2006

Un nuevo disco de los suecos Falconer, y ya van cuatro,
que se llama
Grime vs Grandeur.

26 de Marzo de 2006

La banda alemana Custard ha sacado su tercer álbum Wheels of Time.
Y aunque al principio de su existencia tocaban thrash, éste último trabajo es sin ninguna duda power metal.

12 de Marzo de 2006

Hay un nuevo disco en el mercado del grupo italiano
Elveking, titulado The Winter Wake.

19 de Febrero de 2006

Aquí va la revisión del primer trabajo del grupo
sueco DivineFirye, Glory thy Name,
editado en Japón en 2004 pero llegado a Europa el pasado verano.

12 de Febrero de 2006

Cuarto álbum de estudio de los italianos Secret Sphere, titulado

Heart and Anger.

4 de Febrero de 2006

Hoy he revisado el primer disco de la banda germano-rumana
Powerwolf, que se llama
Return in Bloodred.

15 de Enero de 2006

Aunque llevemos ya dos semanas de 2006, ¡feliz año a todos!
Para empezar con buen pie, he revisado el último disco de
unos de los pesos pesados del metal alemán, Helloween, que
ya lleva unos cuantos meses en el mercado y que se titula
Keeper of the
Seven Keys - The Legacy.


text:
package org.apache.drill.exec.store.mock;

import java.util.Map;

import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.exec.exception.OutOfMemoryException;
import org.apache.drill.exec.exception.SchemaChangeException;
import org.apache.drill.exec.expr.TypeHelper;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.ops.OperatorContext;
import org.apache.drill.exec.physical.impl.OutputMutator;
import org.apache.drill.exec.record.MaterializedField;
import org.apache.drill.exec.store.AbstractRecordReader;
import org.apache.drill.exec.store.mock.MockGroupScanPOP.MockColumn;
import org.apache.drill.exec.store.mock.MockGroupScanPOP.MockScanEntry;
import org.apache.drill.exec.vector.AllocationHelper;
import org.apache.drill.exec.vector.ValueVector;

public class MockRecordReader extends AbstractRecordReader {
//  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MockRecordReader.class);

  private final MockScanEntry config;
  private final FragmentContext context;
  private ValueVector[] valueVectors;
  private int recordsRead;
  private int batchRecordCount;
  private OperatorContext operatorContext;

  public MockRecordReader(FragmentContext context, MockScanEntry config) {
    this.context = context;
    this.config = config;
  }

  private int getEstimatedRecordSize(MockColumn[] types) {
    int x = 0;
    for (int i = 0; i < types.length; i++) {
      x += TypeHelper.getSize(types[i].getMajorType());
    }
    return x;
  }

  private MaterializedField getVector(String name, MajorType type, int length) {
    assert context != null : "Context shouldn't be null.";
    final MaterializedField f = MaterializedField.create(name, type);
    return f;
  }

  @Override
  public void setup(OperatorContext context, OutputMutator output) throws ExecutionSetupException {
    try {
      final int estimateRowSize = getEstimatedRecordSize(config.getTypes());
      valueVectors = new ValueVector[config.getTypes().length];
      batchRecordCount = 250000 / estimateRowSize;

      for (int i = 0; i < config.getTypes().length; i++) {
        final MajorType type = config.getTypes()[i].getMajorType();
        final MaterializedField field = getVector(config.getTypes()[i].getName(), type, batchRecordCount);
        final Class<? extends ValueVector> vvClass = TypeHelper.getValueVectorClass(field.getType().getMinorType(), field.getDataMode());
        valueVectors[i] = output.addField(field, vvClass);
      }
    } catch (SchemaChangeException e) {
      throw new ExecutionSetupException("Failure while setting up fields", e);
    }
  }

  @Override
  public int next() {
    if (recordsRead >= this.config.getRecords()) {
      return 0;
    }

    final int recordSetSize = Math.min(batchRecordCount, this.config.getRecords() - recordsRead);
    recordsRead += recordSetSize;
    for (final ValueVector v : valueVectors) {
      final ValueVector.Mutator m = v.getMutator();
      m.generateTestData(recordSetSize);
    }

    return recordSetSize;
  }

  @Override
  public void allocate(Map<String, ValueVector> vectorMap) throws OutOfMemoryException {
    try {
      for (final ValueVector v : vectorMap.values()) {
        AllocationHelper.allocate(v, Character.MAX_VALUE, 50, 10);
      }
    } catch (NullPointerException e) {
      throw new OutOfMemoryException();
    }
  }

  @Override
  public void close() {
  }
}


text:
class JoinedVersion < PaperTrail::Version
  default_scope { joins('INNER JOIN widgets ON widgets.id = versions.item_id') }
end


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace PdfiumViewer
{
    /// <summary>
    /// Specifies the mode in which the document should be printed.
    /// </summary>
    /// <remarks>
    /// Printers have a hard margin. This is a (small) margin on which it is not
    /// possible to print. PdfPrintMode specifies whether the page should be
    /// scaled to fit into this margin, or that the margin should be cut off of
    /// the page.
    /// </remarks>
    public enum PdfPrintMode
    {
        /// <summary>
        /// Shrink the print area to fall within the hard printer margin.
        /// </summary>
        ShrinkToMargin,
        /// <summary>
        /// Cut the hard printer margin from the output.
        /// </summary>
        CutMargin
    }
}


text:
layout: page
title: "JavaScript stream_is_local function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/stream_is_local:851
- /functions/view/stream_is_local
- /functions/view/851
- /functions/stream_is_local:851
- /functions/851
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's stream_is_local

{% codeblock stream/stream_is_local.js lang:js https://raw.github.com/kvz/phpjs/master/functions/stream/stream_is_local.js raw on github %}
function stream_is_local (stream_or_url) {
  // http://kevin.vanzonneveld.net
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // *     example 1: stream_is_local('/etc');
  // *     returns 1: true

  if (typeof stream_or_url === 'string') {
    return ((/^(https?|ftps?|ssl|tls):/).test(stream_or_url)) ? false : true; // Need a better check than this
  }
  return stream_or_url.is_local ? true : false;
}
{% endcodeblock %}

 - [view on github](https://github.com/kvz/phpjs/blob/master/functions/stream/stream_is_local.js)
 - [edit on github](https://github.com/kvz/phpjs/edit/master/functions/stream/stream_is_local.js)

### Example 1
This code
{% codeblock lang:js example %}
stream_is_local('/etc');
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
true
{% endcodeblock %}

### Other PHP functions in the stream extension
{% render_partial _includes/custom/stream.html %}


text:
package org.zstack.network.service.eip;

import org.zstack.header.core.workflow.FlowChainProcessor;

/**
 * Created by xing5 on 2016/4/4.
 */
public interface DetachEipFlowChainExtensionPoint {
    FlowChainProcessor createDetachEipFlowChainProcessor(EipStruct struct, String providerType);
}


text:
package alluxio.master.meta;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;

import alluxio.TestLoggerRule;
import alluxio.shell.CommandReturn;
import alluxio.util.OSUtils;
import alluxio.wire.JournalDiskInfo;

import org.apache.log4j.Level;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

public class JournalSpaceMonitorTest {

  private static final String CMD_RETURN_MOCK =
      "Filesystem  Type  1024-blocks      Used Available Capacity Mounted on\n"
          + "/dev/nvme0n1p2  ext4  959863856 145802864 765232784      17% /";

  @Rule
  public TestLoggerRule mLogger = new TestLoggerRule();

  @BeforeClass
  public static void beforeClass() {
    Assume.assumeTrue(OSUtils.isLinux());
  }

  @Test
  public void testNonExistentJournalPath() {
    assertThrows(IllegalArgumentException.class,
        () -> new JournalSpaceMonitor("/nonexistent/path", 10));
  }

  @Test
  public void testSuccessfulInfo() throws IOException  {
    JournalSpaceMonitor monitor = Mockito.spy(
        new JournalSpaceMonitor(Paths.get(".").toAbsolutePath().toString(), 10));
    doReturn(new CommandReturn(0, CMD_RETURN_MOCK)).when(monitor).getRawDiskInfo();
    List<JournalDiskInfo> infos = monitor.getDiskInfo();
    assertEquals(1, infos.size());
    JournalDiskInfo info = infos.get(0);
    assertEquals("/dev/nvme0n1p2", info.getDiskPath());
    assertEquals(959863856L * 1024, info.getTotalAllocatedBytes());
    assertEquals(145802864L * 1024, info.getUsedBytes());
    assertEquals(765232784L * 1024, info.getAvailableBytes());
    assertEquals(83.0, Math.floor(info.getPercentAvailable()), 0.1);
  }

  @Test
  public void testFailedInfo() throws IOException  {
    JournalSpaceMonitor monitor = Mockito.spy(
        new JournalSpaceMonitor(Paths.get(".").toAbsolutePath().toString(), 10));
    doThrow(new IOException("couldnt run")).when(monitor).getRawDiskInfo();
    assertThrows(IOException.class, monitor::getDiskInfo);
  }

  @Test
  public void testLoggingPositive() throws IOException, InterruptedException {
    JournalSpaceMonitor monitor = Mockito.spy(
        new JournalSpaceMonitor(Paths.get(".").toAbsolutePath().toString(), 90));
    doReturn(new CommandReturn(0, CMD_RETURN_MOCK)).when(monitor).getRawDiskInfo();
    monitor.heartbeat();
    assertTrue(mLogger.wasLoggedWithLevel("The journal disk /dev/nvme0n1p2 backing the journal "
        + "has only .* space left", Level.WARN));
  }

  @Test
  public void testLoggingNegative() throws IOException, InterruptedException {
    JournalSpaceMonitor monitor = Mockito.spy(
        new JournalSpaceMonitor(Paths.get(".").toAbsolutePath().toString(), 10));
    doReturn(new CommandReturn(0, CMD_RETURN_MOCK)).when(monitor).getRawDiskInfo();
    monitor.heartbeat();
    assertFalse(mLogger.wasLoggedWithLevel("The journal disk /dev/nvme0n1p2 backing the journal "
        + "has only .* space left", Level.WARN));
  }
}


text:
```sh
PS C:\Users\ctc-lidan\Desktop\Git-Pro-Tutorials> bash
job2017@ADMIN:/mnt/c/Users/ctc-lidan/Desktop/Git-Pro-Tutorials$ touch -h
touch: missing file operand
Try 'touch --help' for more information.

job2017@ADMIN:/mnt/c/Users/ctc-lidan/Desktop/Git-Pro-Tutorials$ touch --help
Usage: touch [OPTION]... FILE...
Update the access and modification times of each FILE to the current time.

A FILE argument that does not exist is created empty, unless -c or -h
is supplied.

A FILE argument string of - is handled specially and causes touch to
change the times of the file associated with standard output.

Mandatory arguments to long options are mandatory for short options too.
  -a                     change only the access time
  -c, --no-create        do not create any files
  -d, --date=STRING      parse STRING and use it instead of current time
  -f                     (ignored)
  -h, --no-dereference   affect each symbolic link instead of any referenced
                         file (useful only on systems that can change the
                         timestamps of a symlink)
  -m                     change only the modification time
  -r, --reference=FILE   use this file's times instead of current time
  -t STAMP               use [[CC]YY]MMDDhhmm[.ss] instead of current time
      --time=WORD        change the specified time:
                           WORD is access, atime, or use: equivalent to -a
                           WORD is modify or mtime: equivalent to -m
      --help     display this help and exit
      --version  output version information and exit

Note that the -d and -t options accept different time-date formats.

Report touch bugs to bug-coreutils@gnu.org
GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
For complete documentation, run: info coreutils 'touch invocation'
job2017@ADMIN:/mnt/c/Users/ctc-lidan/Desktop/Git-Pro-Tutorials$

```


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Create new xmlwriter using source uri for output</title>

XMLWriter::openMemory

XMLWriter::outputMemory

XMLWriter Functions

PHP Manual

XMLWriter::openURI

xmlwriter_open_uri

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::openURI -- xmlwriter_open_uri — Create new xmlwriter using source uri for output

Description

Object oriented style

   bool XMLWriter::openURI
    ( string $uri
   )

Procedural style

   resource xmlwriter_open_uri
    ( string $uri
   )

   Creates a new XMLWriter using
   uri for the output.

Parameters

uri

       The URI of the resource for the output.

Return Values

   Object oriented style: Returns TRUE on success or FALSE on failure.

   Procedural style: Returns a new xmlwriter resource for later use with the
   xmlwriter functions on success, FALSE on error.

See Also

XMLWriter::openMemory() - Create new xmlwriter using memory for string output

XMLWriter::openMemory

XMLWriter::outputMemory

XMLWriter Functions

PHP Manual


text:
package zx.soft.es.web.server;

import java.util.Properties;

import org.restlet.Component;
import org.restlet.data.Protocol;

import zx.soft.es.utils.ConfigUtil;
import zx.soft.es.web.application.SearchApplication;
import zx.soft.es.web.jackson.ReplaceConvert;

/**
 * 搜索服务类
 * 搜索示例:
 *http://192.168.3.22:8085/spider/search?field=content&keywords=hello,大家&size=5
 * @author fgq
 *
 */
public class ESSearchServer {

	private final Component component;
	private final SearchApplication searchApplication;
	private final int PORT;

	public ESSearchServer() {
		Properties props = ConfigUtil.getProps("web-server.properties");
		component = new Component();
		searchApplication = new SearchApplication();
		PORT = Integer.parseInt(props.getProperty("searchapi.port"));
	}

	public static void main(String[] leftArgs) {
		ESSearchServer server = new ESSearchServer();
		server.start();
	}

	private void start() {

		try {
			component.getServers().add(Protocol.HTTP, PORT);
			component.getDefaultHost().attach("/spider", searchApplication);
			ReplaceConvert.configureJacksonConverter();
			component.start();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void stop() {
		try {
			component.stop();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}


text:
package org.apache.hadoop.hbase.regionserver;

import static org.junit.Assert.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.Waiter.Predicate;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Consistency;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.RpcRetryingCallerImpl;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.replication.regionserver.TestRegionReplicaReplicationEndpoint;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.ServerRegionReplicaUtil;
import org.apache.hadoop.hbase.util.Threads;
import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
import org.apache.log4j.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 * Tests failover of secondary region replicas.
 */
@RunWith(Parameterized.class)
@Category(LargeTests.class)
public class TestRegionReplicaFailover {

  private static final Log LOG = LogFactory.getLog(TestRegionReplicaReplicationEndpoint.class);

  static {
    ((Log4JLogger)RpcRetryingCallerImpl.LOG).getLogger().setLevel(Level.ALL);
  }

  private static final HBaseTestingUtility HTU = new HBaseTestingUtility();

  private static final int NB_SERVERS = 3;

  protected final byte[][] families = new byte[][] {HBaseTestingUtility.fam1,
      HBaseTestingUtility.fam2, HBaseTestingUtility.fam3};
  protected final byte[] fam = HBaseTestingUtility.fam1;
  protected final byte[] qual1 = Bytes.toBytes("qual1");
  protected final byte[] value1 = Bytes.toBytes("value1");
  protected final byte[] row = Bytes.toBytes("rowA");
  protected final byte[] row2 = Bytes.toBytes("rowB");

  @Rule public TestName name = new TestName();

  private HTableDescriptor htd;

  /*
   * We are testing with dist log split and dist log replay separately
   */
  @Parameters
  public static Collection<Object[]> getParameters() {
    Object[][] params =
        new Boolean[][] { {false} }; // TODO: enable dist log replay testing after HBASE-13121
    return Arrays.asList(params);
  }

  @Parameterized.Parameter(0)
  public boolean distributedLogReplay;

  @Before
  public void before() throws Exception {
    Configuration conf = HTU.getConfiguration();
    conf.setBoolean(HConstants.REPLICATION_ENABLE_KEY, true);
    conf.setBoolean(ServerRegionReplicaUtil.REGION_REPLICA_REPLICATION_CONF_KEY, true);
    conf.setBoolean(ServerRegionReplicaUtil.REGION_REPLICA_WAIT_FOR_PRIMARY_FLUSH_CONF_KEY, true);
    conf.setInt("replication.stats.thread.period.seconds", 5);
    conf.setBoolean("hbase.tests.use.shortcircuit.reads", false);
    conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, distributedLogReplay);

    HTU.startMiniCluster(NB_SERVERS);
    htd = HTU.createTableDescriptor(
      name.getMethodName().substring(0, name.getMethodName().length()-3));
    htd.setRegionReplication(3);
    HTU.getHBaseAdmin().createTable(htd);
  }

  @After
  public void after() throws Exception {
    HTU.deleteTableIfAny(htd.getTableName());
    HTU.shutdownMiniCluster();
  }

  /**
   * Tests the case where a newly created table with region replicas and no data, the secondary
   * region replicas are available to read immediately.
   */
  @Test(timeout = 60000)
  public void testSecondaryRegionWithEmptyRegion() throws IOException {
    // Create a new table with region replication, don't put any data. Test that the secondary
    // region replica is available to read.
    try (Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
        Table table = connection.getTable(htd.getTableName())) {

      Get get = new Get(row);
      get.setConsistency(Consistency.TIMELINE);
      get.setReplicaId(1);
      table.get(get); // this should not block
    }
  }

  /**
   * Tests the case where if there is some data in the primary region, reopening the region replicas
   * (enable/disable table, etc) makes the region replicas readable.
   * @throws IOException
   */
  @Test(timeout = 60000)
  public void testSecondaryRegionWithNonEmptyRegion() throws IOException {
    // Create a new table with region replication and load some data
    // than disable and enable the table again and verify the data from secondary
    try (Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
        Table table = connection.getTable(htd.getTableName())) {

      HTU.loadNumericRows(table, fam, 0, 1000);

      HTU.getHBaseAdmin().disableTable(htd.getTableName());
      HTU.getHBaseAdmin().enableTable(htd.getTableName());

      HTU.verifyNumericRows(table, fam, 0, 1000, 1);
    }
  }

  /**
   * Tests the case where killing a primary region with unflushed data recovers
   */
  @Test (timeout = 120000)
  public void testPrimaryRegionKill() throws Exception {
    try (Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
        Table table = connection.getTable(htd.getTableName())) {

      HTU.loadNumericRows(table, fam, 0, 1000);

      // wal replication is async, we have to wait until the replication catches up, or we timeout
      verifyNumericRowsWithTimeout(table, fam, 0, 1000, 1, 30000);
      verifyNumericRowsWithTimeout(table, fam, 0, 1000, 2, 30000);

      // we should not have flushed files now, but data in memstores of primary and secondary
      // kill the primary region replica now, and ensure that when it comes back up, we can still
      // read from it the same data from primary and secondaries
      boolean aborted = false;
      for (RegionServerThread rs : HTU.getMiniHBaseCluster().getRegionServerThreads()) {
        for (HRegion r : rs.getRegionServer().getOnlineRegions(htd.getTableName())) {
          if (r.getRegionInfo().getReplicaId() == 0) {
            LOG.info("Aborting region server hosting primary region replica");
            rs.getRegionServer().abort("for test");
            aborted = true;
          }
        }
      }
      assertTrue(aborted);

      // wal replication is async, we have to wait until the replication catches up, or we timeout
      verifyNumericRowsWithTimeout(table, fam, 0, 1000, 0, 30000);
      verifyNumericRowsWithTimeout(table, fam, 0, 1000, 1, 30000);
      verifyNumericRowsWithTimeout(table, fam, 0, 1000, 2, 30000);
    }

    // restart the region server
    HTU.getMiniHBaseCluster().startRegionServer();
  }

  /** wal replication is async, we have to wait until the replication catches up, or we timeout
   */
  private void verifyNumericRowsWithTimeout(final Table table, final byte[] f, final int startRow,
      final int endRow, final int replicaId, final long timeout) throws Exception {
    try {
      HTU.waitFor(timeout, new Predicate<Exception>() {
        @Override
        public boolean evaluate() throws Exception {
          try {
            HTU.verifyNumericRows(table, f, startRow, endRow, replicaId);
            return true;
          } catch (AssertionError ae) {
            return false;
          }
        }
      });
    } catch (Throwable t) {
      // ignore this, but redo the verify do get the actual exception
      HTU.verifyNumericRows(table, f, startRow, endRow, replicaId);
    }
  }

  /**
   * Tests the case where killing a secondary region with unflushed data recovers, and the replica
   * becomes available to read again shortly.
   */
  @Test (timeout = 120000)
  public void testSecondaryRegionKill() throws Exception {
    try (Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
        Table table = connection.getTable(htd.getTableName())) {
      HTU.loadNumericRows(table, fam, 0, 1000);

      // wait for some time to ensure that async wal replication does it's magic
      verifyNumericRowsWithTimeout(table, fam, 0, 1000, 1, 30000);
      verifyNumericRowsWithTimeout(table, fam, 0, 1000, 2, 30000);

      // we should not have flushed files now, but data in memstores of primary and secondary
      // kill the secondary region replica now, and ensure that when it comes back up, we can still
      // read from it the same data
      boolean aborted = false;
      for (RegionServerThread rs : HTU.getMiniHBaseCluster().getRegionServerThreads()) {
        for (HRegion r : rs.getRegionServer().getOnlineRegions(htd.getTableName())) {
          if (r.getRegionInfo().getReplicaId() == 1) {
            LOG.info("Aborting region server hosting secondary region replica");
            rs.getRegionServer().abort("for test");
            aborted = true;
          }
        }
      }
      assertTrue(aborted);

      Threads.sleep(5000);

      HTU.verifyNumericRows(table, fam, 0, 1000, 1);
      HTU.verifyNumericRows(table, fam, 0, 1000, 2);
    }

    // restart the region server
    HTU.getMiniHBaseCluster().startRegionServer();
  }

  /**
   * Tests the case where there are 3 region replicas and the primary is continuously accepting
   * new writes while one of the secondaries is killed. Verification is done for both of the
   * secondary replicas.
   */
  @Test (timeout = 120000)
  public void testSecondaryRegionKillWhilePrimaryIsAcceptingWrites() throws Exception {
    try (Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
        Table table = connection.getTable(htd.getTableName());
        Admin admin = connection.getAdmin()) {
      // start a thread to do the loading of primary
      HTU.loadNumericRows(table, fam, 0, 1000); // start with some base
      admin.flush(table.getName());
      HTU.loadNumericRows(table, fam, 1000, 2000);

      final AtomicReference<Throwable> ex = new AtomicReference<Throwable>(null);
      final AtomicBoolean done = new AtomicBoolean(false);
      final AtomicInteger key = new AtomicInteger(2000);

      Thread loader = new Thread() {
        @Override
        public void run() {
          while (!done.get()) {
            try {
              HTU.loadNumericRows(table, fam, key.get(), key.get()+1000);
              key.addAndGet(1000);
            } catch (Throwable e) {
              ex.compareAndSet(null, e);
            }
          }
        }
      };
      loader.start();

      Thread aborter = new Thread() {
        @Override
        public void run() {
          try {
            boolean aborted = false;
            for (RegionServerThread rs : HTU.getMiniHBaseCluster().getRegionServerThreads()) {
              for (HRegion r : rs.getRegionServer().getOnlineRegions(htd.getTableName())) {
                if (r.getRegionInfo().getReplicaId() == 1) {
                  LOG.info("Aborting region server hosting secondary region replica");
                  rs.getRegionServer().abort("for test");
                  aborted = true;
                }
              }
            }
            assertTrue(aborted);
          } catch (Throwable e) {
            ex.compareAndSet(null, e);
          }
        };
      };

      aborter.start();
      aborter.join();
      done.set(true);
      loader.join();

      assertNull(ex.get());

      assertTrue(key.get() > 1000); // assert that the test is working as designed
      LOG.info("Loaded up to key :" + key.get());
      verifyNumericRowsWithTimeout(table, fam, 0, key.get(), 0, 30000);
      verifyNumericRowsWithTimeout(table, fam, 0, key.get(), 1, 30000);
      verifyNumericRowsWithTimeout(table, fam, 0, key.get(), 2, 30000);
    }

    // restart the region server
    HTU.getMiniHBaseCluster().startRegionServer();
  }

  /**
   * Tests the case where we are creating a table with a lot of regions and replicas. Opening region
   * replicas should not block handlers on RS indefinitely.
   */
  @Test (timeout = 120000)
  public void testLotsOfRegionReplicas() throws IOException {
    int numRegions = NB_SERVERS * 20;
    int regionReplication = 10;
    String tableName = htd.getTableName().getNameAsString() + "2";
    htd = HTU.createTableDescriptor(tableName);
    htd.setRegionReplication(regionReplication);

    // dont care about splits themselves too much
    byte[] startKey = Bytes.toBytes("aaa");
    byte[] endKey = Bytes.toBytes("zzz");
    byte[][] splits = HTU.getRegionSplitStartKeys(startKey, endKey, numRegions);
    HTU.getHBaseAdmin().createTable(htd, startKey, endKey, numRegions);

    try (Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
        Table table = connection.getTable(htd.getTableName())) {

      for (int i = 1; i < splits.length; i++) {
        for (int j = 0; j < regionReplication; j++) {
          Get get = new Get(splits[i]);
          get.setConsistency(Consistency.TIMELINE);
          get.setReplicaId(j);
          table.get(get); // this should not block. Regions should be coming online
        }
      }
    }

    HTU.deleteTableIfAny(TableName.valueOf(tableName));
  }
}


text:
package org.gradle.nativebinaries.toolchain.internal;

import org.gradle.nativebinaries.platform.Platform;
import org.gradle.nativebinaries.toolchain.ToolChain;
import org.gradle.nativebinaries.toolchain.ToolChainRegistry;

public interface ToolChainRegistryInternal extends ToolChainRegistry {
    /**
     * Registers a default ToolChain, which may later be added to the registry via {@link #addDefaultToolChains()}.
     */
    void registerDefaultToolChain(String name, Class<? extends ToolChain> type);

    /**
     * Adds default tool chains to the registry.
     */
    void addDefaultToolChains();

    ToolChain getForPlatform(Platform targetPlatform);
}


text:
class SessionsController < ApplicationController

  def new
  end

  def create
    session[:username] = params[:username]
    redirect_to photos_path
  end

  def destroy
    session[:username] = nil
    redirect_to login_path
  end

end


text:
package org.wso2.carbon.transport.http.netty.contract.websocket;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Sender configuration for WebSocket client connector.
 */
public class WsClientConnectorConfig {

    private final String remoteAddress;
    private List<String> subProtocols;
    private String target = null;
    private int idleTimeoutInSeconds = -1;
    private final Map<String, String> headers = new HashMap<>();

    public WsClientConnectorConfig(String remoteAddress) {
        this.remoteAddress = remoteAddress;
    }

    public WsClientConnectorConfig(String remoteAddress, String target, List<String> subProtocols,
                                   int idleTimeoutInSeconds) {
        this.remoteAddress = remoteAddress;
        this.target = target;
        this.subProtocols = subProtocols;
        this.idleTimeoutInSeconds = idleTimeoutInSeconds;
    }

    /**
     * Get sub protocols as a comma separated values string.
     *
     * @return a string of comma separated values of sub protocols.
     */
    public String getSubProtocolsAsCSV() {
        if (subProtocols == null) {
            return null;
        }

        String subProtocolsAsCSV = "";
        for (String subProtocol : subProtocols) {
            subProtocolsAsCSV = subProtocolsAsCSV.concat(subProtocol + ",");
        }
        subProtocolsAsCSV = subProtocolsAsCSV.substring(0, subProtocolsAsCSV.length() - 1);
        return subProtocolsAsCSV;
    }

    /**
     * Add sub protocols.
     *
     * @param subProtocols a array of sub protocols.
     */
    public void setSubProtocols(String[] subProtocols) {
        if (subProtocols == null || subProtocols.length == 0) {
            this.subProtocols = null;
            return;
        }
        this.subProtocols = Arrays.asList(subProtocols);
    }

    /**
     * Add sub protocols.
     *
     * @param subProtocols a list of sub protocols.
     */
    public void setSubProtocols(List<String> subProtocols) {
        if (subProtocols == null || subProtocols.size() == 0) {
            this.subProtocols = null;
            return;
        }
        this.subProtocols = subProtocols;
    }

    /**
     * Get sub protocols as a String array.
     *
     * @return a String list of sub protocols.
     */
    public List<String> getSubProtocols() {
        return this.subProtocols;
    }

    /**
     * Get the remote address.
     *
     * @return the remote address.
     */
    public String getRemoteAddress() {
        return remoteAddress;
    }

    /**
     * Get the target of the WebSocket incoming messages.
     *
     * @return the target of the WebSocket incoming messages.
     */
    public String getTarget() {
        return target;
    }

    /**
     * Set the target of the WebSocket incoming messages.
     *
     * @param target the target of the WebSocket incoming messages.
     */
    public void setTarget(String target) {
        this.target = target;
    }

    /**
     * Add multiple headers.
     *
     * @param headers Headers map.
     */
    public void addHeaders(Map<String, String> headers) {
        this.headers.putAll(headers);
    }

    /**
     * Add single headers.
     *
     * @param key Key of the header.
     * @param value Value of the header.
     */
    public void addHeader(String key, String value) {
        this.headers.put(key, value);
    }

    /**
     * Get all the headers.
     *
     * @return all the headers as a map.
     */
    public Map<String, String> getHeaders() {
        return headers;
    }

    /**
     * Check whether a header is contained or not.
     *
     * @param key key of the header.
     * @return true of the header is present.
     */
    public boolean containsHeader(String key) {
        return headers.containsKey(key);
    }

    /**
     * Get idle timeout for WebSocket connection.
     *
     * @return the idle timeout in millis seconds.
     */
    public int getIdleTimeoutInMillis() {
        return idleTimeoutInSeconds;
    }

    /**
     * Set the idle timeout for WebSocket connection.
     *
     * @param idleTimeoutInSeconds the idle timeout in milli seconds.
     */
    public void setIdleTimeoutInMillis(int idleTimeoutInSeconds) {
        this.idleTimeoutInSeconds = idleTimeoutInSeconds;
    }
}


text:
package ru.dionisius.interfaces;

import ru.dionisius.model.Board;

/**
 * Interface for all chess figures.
 * X coordinate vertical, Y coordinate horizontal.
 * Coordinates range is 0..7.
 */
public interface Figure {
	/**
	 * Verifies if move for specified figure is possible.
	 * @param board game board.
	 * @param startX starting coordinate X for this figure.
	 * @param startY starting coordinate Y for this figure.
	 * @param finishX end coordinate X for this figure.
	 * @param finishY starting coordinate Y for this figure.
	 * @return true if vove is possible and false if not.
	 */
	boolean isMovePossible(Board board, int startX, int startY, int finishX, int finishY);
	/**
	 * Verifies this figure  if it is white or black.
	 * @return true if white and false if black.
	 */
	boolean isWhite();
	/**
	 * Returns this figure identified symbol.
	 * @return this figure identified symbol.
	 */
	char getSymbol();
}


text:
package com.microsoft.azure.management.automation.v2015_10_31.implementation;

import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.automation.v2015_10_31.Certificates;
import rx.Completable;
import rx.Observable;
import rx.functions.Func1;
import com.microsoft.azure.Page;
import com.microsoft.azure.management.automation.v2015_10_31.Certificate;

class CertificatesImpl extends WrapperImpl<CertificatesInner> implements Certificates {
    private final AutomationManager manager;

    CertificatesImpl(AutomationManager manager) {
        super(manager.inner().certificates());
        this.manager = manager;
    }

    public AutomationManager manager() {
        return this.manager;
    }

    @Override
    public CertificateImpl define(String name) {
        return wrapModel(name);
    }

    private CertificateImpl wrapModel(CertificateInner inner) {
        return  new CertificateImpl(inner, manager());
    }

    private CertificateImpl wrapModel(String name) {
        return new CertificateImpl(name, this.manager());
    }

    @Override
    public Observable<Certificate> listByAutomationAccountAsync(final String resourceGroupName, final String automationAccountName) {
        CertificatesInner client = this.inner();
        return client.listByAutomationAccountAsync(resourceGroupName, automationAccountName)
        .flatMapIterable(new Func1<Page<CertificateInner>, Iterable<CertificateInner>>() {
            @Override
            public Iterable<CertificateInner> call(Page<CertificateInner> page) {
                return page.items();
            }
        })
        .map(new Func1<CertificateInner, Certificate>() {
            @Override
            public Certificate call(CertificateInner inner) {
                return wrapModel(inner);
            }
        });
    }

    @Override
    public Observable<Certificate> getAsync(String resourceGroupName, String automationAccountName, String certificateName) {
        CertificatesInner client = this.inner();
        return client.getAsync(resourceGroupName, automationAccountName, certificateName)
        .map(new Func1<CertificateInner, Certificate>() {
            @Override
            public Certificate call(CertificateInner inner) {
                return wrapModel(inner);
            }
       });
    }

    @Override
    public Completable deleteAsync(String resourceGroupName, String automationAccountName, String certificateName) {
        CertificatesInner client = this.inner();
        return client.deleteAsync(resourceGroupName, automationAccountName, certificateName).toCompletable();
    }

}


text:
<?php
namespace Neos\Flow\Core\Migrations;

use Neos\Flow\Configuration\ConfigurationManager;
use Neos\Flow\Configuration\Source\YamlSource;
use Neos\Utility\Arrays;
use Neos\Utility\Files;

/**
 * The base class for code migrations.
 */
abstract class AbstractMigration
{
    /**
     * @var Manager
     */
    protected $migrationsManager;

    /**
     * @var string
     */
    protected $sourcePackageKey;

    /**
     * @var array
     */
    protected $targetPackageData;

    /**
     * @var array
     */
    protected $operations = array('searchAndReplace' => array(), 'searchAndReplaceRegex' => array(), 'moveFile' => array(), 'deleteFile' => array());

    /**
     * @var array
     */
    protected $notes = array();

    /**
     * @var array
     */
    protected $warnings = array();

    /**
     * @param Manager $manager
     * @param string $packageKey
     */
    public function __construct(Manager $manager, $packageKey)
    {
        $this->migrationsManager = $manager;
        $this->sourcePackageKey = $packageKey;
    }

    /**
     * Resets internal state and sets the target package data.
     *
     * @param array $targetPackageData
     * @return void
     */
    public function prepare(array $targetPackageData)
    {
        $this->operations = array('searchAndReplace' => array(), 'searchAndReplaceRegex' => array(), 'moveFile' => array(), 'deleteFile' => array());
        $this->targetPackageData = $targetPackageData;
    }

    /**
     * Returns the package key this migration comes from.
     *
     * @return string
     */
    public function getSourcePackageKey()
    {
        return $this->sourcePackageKey;
    }

    /**
     * Returns the identifier of this migration, e.g. 'Neos.Flow-20120126163610'.
     *
     * @return string
     */
    abstract public function getIdentifier();

    /**
     * Returns the version of this migration, e.g. '20120126163610'.
     *
     * @return string
     */
    public function getVersionNumber()
    {
        return substr(strrchr(get_class($this), 'Version'), 7);
    }

    /**
     * Returns the first line of the migration class doc comment
     *
     * @return string
     */
    public function getDescription()
    {
        $reflectionClass = new \ReflectionClass($this);
        $lines = explode(chr(10), $reflectionClass->getDocComment());
        foreach ($lines as $line) {
            $line = trim($line);
            if ($line === '' || $line === '/**' || $line === '*' || $line === '*/' || strpos($line, '* @') !== false) {
                continue;
            }
            return preg_replace('/\s*\\/?[\\\\*]*\s?(.*)$/', '$1', $line);
        }
    }

    /**
     * Anything that needs to be done in the migration when migrating
     * into the "up" direction needs to go into this method.
     *
     * It will be called by the Manager upon migration.
     *
     * @return void
     * @api
     */
    abstract public function up();

    /**
     * @return void
     */
    public function execute()
    {
        $this->applySearchAndReplaceOperations();
        $this->applyFileOperations();
    }

    /**
     * This can be used to show a note to the developer.
     *
     * If changes cannot be automated or something needs to be
     * adjusted  manually for other reasons, leave a note for the
     * developer. The notes will be shown together after migrations
     * have been run.
     *
     * @param string $note
     * @return void
     * @see showWarning
     * @api
     */
    protected function showNote($note)
    {
        $this->notes[md5($note)] = $note;
    }

    /**
     * @return boolean
     */
    public function hasNotes()
    {
        return $this->notes !== array();
    }

    /**
     * @return array
     */
    public function getNotes()
    {
        return $this->notes;
    }

    /**
     * This can be used to show a warning to the developer.
     *
     * Similar to showNote, but the output is given a stronger
     * emphasis. The warnings will be shown together after migrations
     * have been run.
     *
     * @param string $warning
     * @return void
     * @see showNote
     * @api
     */
    protected function showWarning($warning)
    {
        $this->warnings[md5($warning)] = $warning;
    }

    /**
     * @return boolean
     */
    public function hasWarnings()
    {
        return $this->warnings !== array();
    }

    /**
     * @return array
     */
    public function getWarnings()
    {
        return $this->warnings;
    }

    /**
     * Does a simple search and replace on all (textual) files. The filter array can be
     * used to give file extensions to limit the operation to.
     *
     * @param string $search
     * @param string $replacement
     * @param array|string $filter either an array with file extensions to consider or the full path to a single file to process
     * @return void
     * @api
     */
    protected function searchAndReplace($search, $replacement, $filter = array('php', 'yaml', 'html'))
    {
        $this->operations['searchAndReplace'][] = array($search, $replacement, $filter, false);
    }

    /**
     * Does a regex search and replace on all (textual) files. The filter array can be
     * used to give file extensions to limit the operation to.
     *
     * The patterns are used as is, no quoting is done. A closure can be given for
     * the $replacement variable. It should return a string and is given an
     * array of matches as parameter.
     *
     * @param string $search
     * @param string|\Closure $replacement
     * @param array|string $filter either an array with file extensions to consider or the full path to a single file to process
     * @return void
     * @api
     */
    protected function searchAndReplaceRegex($search, $replacement, $filter = array('php', 'yaml', 'html'))
    {
        $this->operations['searchAndReplace'][] = array($search, $replacement, $filter, true);
    }

    /**
     * Rename a class from $oldName to $newName.
     *
     * This expects fully qualified class names, so proper refactoring
     * can be done.
     *
     * @param string $oldName
     * @param string $newName
     * @return void
     * @throws \LogicException
     */
    protected function renameClass($oldName, $newName)
    {
        throw new \LogicException('renameClass is not yet implemented, sorry!', 1335525001);
    }

    /**
     * Rename a class method.
     *
     * This expects a fully qualified class name, so proper refactoring
     * can be done.
     *
     * @param string $className the class that contains the method to be renamed
     * @param string $oldMethodName the method to be renamed
     * @param string $newMethodName the new method name
     * @param boolean $withInheritance if true, also rename method on child classes
     * @return void
     * @throws \LogicException
     */
    protected function renameMethod($className, $oldMethodName, $newMethodName, $withInheritance = true)
    {
        throw new \LogicException('renameMethod is not yet implemented, sorry!', 1479293733);
    }

    /**
     * Move a file (or directory) from $oldPath to $newPath.
     *
     * If $oldPath ends with a * everything starting with $oldPath
     * will be moved into $newPath (which then is created as a directory,
     * if it does not yet exist).
     *
     * @param string $oldPath
     * @param string $newPath
     * @return void
     */
    protected function moveFile($oldPath, $newPath)
    {
        $this->operations['moveFile'][] = array($oldPath, $newPath);
    }

    /**
     * Delete a file.
     *
     * @param string $pathAndFileName
     * @return void
     */
    protected function deleteFile($pathAndFileName)
    {
        $this->operations['deleteFile'][] = array($pathAndFileName);
    }

    /**
     * Apply the given processor to the raw results of loading the given configuration
     * type for the package from YAML. If multiple files exist (context configuration)
     * all are processed independently.
     *
     * @param string $configurationType One of ConfigurationManager::CONFIGURATION_TYPE_*
     * @param \Closure $processor
     * @param boolean $saveResult
     * @return void
     */
    protected function processConfiguration($configurationType, \Closure $processor, $saveResult = false)
    {
        if (is_dir($this->targetPackageData['path'] . '/Configuration') === false) {
            return;
        }

        $yamlPathsAndFilenames = Files::readDirectoryRecursively($this->targetPackageData['path'] . '/Configuration', 'yaml', true);
        $configurationPathsAndFilenames = array_filter($yamlPathsAndFilenames,
            function ($pathAndFileName) use ($configurationType) {
                if (strpos(basename($pathAndFileName, '.yaml'), $configurationType) === 0) {
                    return true;
                } else {
                    return false;
                }
            }
        );

        $yamlSource = new YamlSource();
        foreach ($configurationPathsAndFilenames as $pathAndFilename) {
            $originalConfiguration = $configuration = $yamlSource->load(substr($pathAndFilename, 0, -5));
            $processor($configuration);
            if ($saveResult === true && $configuration !== $originalConfiguration) {
                $yamlSource->save(substr($pathAndFilename, 0, -5), $configuration);
            }
        }
    }

    /**
     * Move a settings path from "source" to "destination"; best to be used when package names change.
     *
     * @param string $sourcePath
     * @param string $destinationPath
     */
    protected function moveSettingsPaths($sourcePath, $destinationPath)
    {
        $this->processConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS,
            function (array &$configuration) use ($sourcePath, $destinationPath) {
                $sourceConfigurationValue = Arrays::getValueByPath($configuration, $sourcePath);
                $destinationConfigurationValue = Arrays::getValueByPath($configuration, $destinationPath);

                if ($sourceConfigurationValue !== null) {
                    // source exists, so we need to move source to destination.

                    if ($destinationConfigurationValue !== null) {
                        // target exists as well; we need to MERGE source and target.
                        $destinationConfigurationValue = Arrays::arrayMergeRecursiveOverrule($sourceConfigurationValue, $destinationConfigurationValue);
                    } else {
                        // target does NOT exist; we directly set target = source
                        $destinationConfigurationValue = $sourceConfigurationValue;
                    }

                    // set the config on the new path
                    $configuration = Arrays::setValueByPath($configuration, $destinationPath, $destinationConfigurationValue);

                    // Unset the old configuration
                    $configuration = Arrays::unsetValueByPath($configuration, $sourcePath);

                    // remove empty keys before our removed key (if it exists)
                    $sourcePathExploded = explode('.', $sourcePath);
                    for ($length = count($sourcePathExploded) - 1; $length > 0; $length--) {
                        $temporaryPath = array_slice($sourcePathExploded, 0, $length);
                        $valueAtPath = Arrays::getValueByPath($configuration, $temporaryPath);
                        if (empty($valueAtPath)) {
                            $configuration = Arrays::unsetValueByPath($configuration, $temporaryPath);
                        } else {
                            break;
                        }

                    }
                }
            },
            true
        );
    }

    /**
     * Applies all registered searchAndReplace operations.
     *
     * @return void
     */
    protected function applySearchAndReplaceOperations()
    {
        foreach (Files::getRecursiveDirectoryGenerator($this->targetPackageData['path'], null, true) as $pathAndFilename) {
            $pathInfo = pathinfo($pathAndFilename);
            if (!isset($pathInfo['filename'])) {
                continue;
            }
            if (strpos($pathAndFilename, 'Migrations/Code') !== false) {
                continue;
            }

            foreach ($this->operations['searchAndReplace'] as $operation) {
                list($search, $replacement, $filter, $regularExpression) = $operation;
                if (is_array($filter)) {
                    if ($filter !== array() && (!isset($pathInfo['extension']) || !in_array($pathInfo['extension'], $filter, true))) {
                        continue;
                    }
                } elseif (substr($pathAndFilename, -strlen($filter)) !== $filter) {
                    continue;
                }
                Tools::searchAndReplace($search, $replacement, $pathAndFilename, $regularExpression);
            }
        }
    }

    /**
     * Applies all registered moveFile operations.
     *
     * @return void
     */
    protected function applyFileOperations()
    {
        foreach ($this->operations['moveFile'] as $operation) {
            $oldPath = Files::concatenatePaths(array($this->targetPackageData['path'] . '/' . $operation[0]));
            $newPath = Files::concatenatePaths(array($this->targetPackageData['path'] . '/' . $operation[1]));

            if (substr($oldPath, -1) === '*') {
                $oldPath = substr($oldPath, 0, -1);
                if (!file_exists($oldPath)) {
                    continue;
                }
                if (!file_exists($newPath)) {
                    Files::createDirectoryRecursively($newPath);
                }
                if (!is_dir($newPath)) {
                    continue;
                }
                foreach (Files::getRecursiveDirectoryGenerator($this->targetPackageData['path'], null, true) as $pathAndFilename) {
                    if (substr_compare($pathAndFilename, $oldPath, 0, strlen($oldPath)) === 0) {
                        $relativePathAndFilename = substr($pathAndFilename, strlen($oldPath));
                        if (!is_dir(dirname(Files::concatenatePaths(array($newPath, $relativePathAndFilename))))) {
                            Files::createDirectoryRecursively(dirname(Files::concatenatePaths(array($newPath, $relativePathAndFilename))));
                        }
                        Git::move($pathAndFilename, Files::concatenatePaths(array($newPath, $relativePathAndFilename)));
                    }
                }
            } else {
                $oldPath = Files::concatenatePaths(array($this->targetPackageData['path'] . '/' . $operation[0]));
                $newPath = Files::concatenatePaths(array($this->targetPackageData['path'] . '/' . $operation[1]));
                Git::move($oldPath, $newPath);
            }
        }

        foreach ($this->operations['deleteFile'] as $operation) {
            $filename = Files::concatenatePaths(array($this->targetPackageData['path'] . '/' . $operation[0]));
            if (file_exists($filename)) {
                Git::remove($filename);
            }
        }
    }
}


text:
#include "phd.h"

GuideAlgorithmIdentity::GuideAlgorithmIdentity(Mount *pMount, GuideAxis axis)
    : GuideAlgorithm(pMount, axis)
{
    reset();
}

GuideAlgorithmIdentity::~GuideAlgorithmIdentity(void)
{
}

GUIDE_ALGORITHM GuideAlgorithmIdentity::Algorithm() const
{
    return GUIDE_ALGORITHM_IDENTITY;
}

void GuideAlgorithmIdentity::reset(void)
{
}

// the default algorithm simply returns its input
double GuideAlgorithmIdentity::result(double input)
{
    double dReturn = input;

    return dReturn;
}

ConfigDialogPane *GuideAlgorithmIdentity::GetConfigDialogPane(wxWindow *pParent)
{
    return new GuideAlgorithmIdentityConfigDialogPane(pParent, this);
}

GuideAlgorithmIdentity::
GuideAlgorithmIdentityConfigDialogPane::
GuideAlgorithmIdentityConfigDialogPane(wxWindow *pParent, GuideAlgorithmIdentity *pGuideAlgorithm)
    : ConfigDialogPane(_("Guide Algorithm"), pParent)
{
    m_pGuideAlgorithm = pGuideAlgorithm;
    DoAdd(new wxStaticText(pParent, wxID_ANY, _("Nothing to Configure"),wxPoint(-1,-1),wxSize(-1,-1)));
}

GuideAlgorithmIdentity::
GuideAlgorithmIdentityConfigDialogPane::
~GuideAlgorithmIdentityConfigDialogPane(void)
{
}

void GuideAlgorithmIdentity::
GuideAlgorithmIdentityConfigDialogPane::
LoadValues(void)
{
}

void GuideAlgorithmIdentity::
GuideAlgorithmIdentityConfigDialogPane::
UnloadValues(void)
{
}


text:
package is.hail.expr.ir

import is.hail.annotations.IntervalEndpointOrdering
import is.hail.types.virtual._
import is.hail.utils.{FastSeq, Interval, IntervalEndpoint, _}
import is.hail.variant.{Locus, ReferenceGenome}
import org.apache.spark.sql.Row

object ExtractIntervalFilters {

  val MAX_LITERAL_SIZE = 4096

  case class ExtractionState(rowRef: Ref, keyFields: IndexedSeq[String]) {
    val rowType: TStruct = rowRef.typ.asInstanceOf[TStruct]
    val rowKeyType: TStruct = rowType.select(keyFields)._1
    val firstKeyType: Type = rowKeyType.types.head
    val iOrd: IntervalEndpointOrdering = rowKeyType.ordering.intervalEndpointOrdering

    def isFirstKey(ir: IR): Boolean = ir == GetField(rowRef, rowKeyType.fieldNames.head)

    def isKeyStructPrefix(ir: IR): Boolean = ir match {
      case MakeStruct(fields) => fields
        .iterator
        .map(_._2)
        .zipWithIndex
        .forall { case (fd, idx) => idx < rowKeyType.size && fd == GetField(rowRef, rowKeyType.fieldNames(idx)) }
      case SelectFields(`rowRef`, fields) => keyFields.startsWith(fields)
      case _ => false
    }
  }

  def literalSizeOkay(lit: Literal): Boolean = lit.value.asInstanceOf[Iterable[_]].size <= MAX_LITERAL_SIZE

  def wrapInRow(intervals: Array[Interval]): Array[Interval] = {
    intervals.map { interval =>
      Interval(IntervalEndpoint(Row(interval.left.point), interval.left.sign),
        IntervalEndpoint(Row(interval.right.point), interval.right.sign))
    }
  }

  def minimumValueByType(t: Type): Any = {
    t match {
      case TInt32 => Int.MinValue
      case TInt64 => Long.MinValue
      case TFloat32 => Float.NegativeInfinity
      case TFloat64 => Double.PositiveInfinity
      case TBoolean => false
      case t: TLocus =>
        val rg = t.rg.asInstanceOf[ReferenceGenome]
        Locus(rg.contigs.head, 1)
      case tbs: TBaseStruct => Row.fromSeq(tbs.types.map(minimumValueByType))
    }
  }

  def maximumValueByType(t: Type): Any = {
    t match {
      case TInt32 => Int.MaxValue
      case TInt64 => Long.MaxValue
      case TFloat32 => Float.PositiveInfinity
      case TFloat64 => Double.PositiveInfinity
      case TBoolean => false
      case t: TLocus =>
        val rg = t.rg.asInstanceOf[ReferenceGenome]
        val contig = rg.contigs.last
        Locus(contig, rg.contigLength(contig) - 1)
      case tbs: TBaseStruct => Row.fromSeq(tbs.types.map(maximumValueByType))
    }
  }

  def constValue(x: IR): Any = (x: @unchecked) match {
    case I32(v) => v
    case I64(v) => v
    case F32(v) => v
    case F64(v) => v
    case Str(v) => v
    case Literal(_, v) => v
  }

  def endpoint(value: Any, inclusivity: Int, wrapped: Boolean = true): IntervalEndpoint = {
    IntervalEndpoint(if (wrapped) Row(value) else value, inclusivity)
  }

  def getIntervalFromContig(c: String, rg: ReferenceGenome): Interval = {
    Interval(
      endpoint(Locus(c, 1), -1),
      endpoint(Locus(c, rg.contigLength(c)), -1))
  }

  def openInterval(v: Any, typ: Type, op: ComparisonOp[_], flipped: Boolean = false): Interval = {
    (op: @unchecked) match {
      case _: EQ =>
        Interval(endpoint(v, -1), endpoint(v, 1))
      case GT(_, _) =>
        if (flipped)
          Interval(endpoint(v, 1), endpoint(maximumValueByType(typ), 1)) // key > value
        else
          Interval(endpoint(minimumValueByType(typ), -1), endpoint(v, -1)) // value > key
      case GTEQ(_, _) =>
        if (flipped)
          Interval(endpoint(v, -1), endpoint(maximumValueByType(typ), 1)) // key >= value
        else
          Interval(endpoint(minimumValueByType(typ), -1), endpoint(v, 1)) // value >= key
      case LT(_, _) =>
        if (flipped)
          Interval(endpoint(minimumValueByType(typ), -1), endpoint(v, -1)) // key < value
        else
          Interval(endpoint(v, 1), endpoint(maximumValueByType(typ), 1)) // value < key
      case LTEQ(_, _) =>
        if (flipped)
          Interval(endpoint(minimumValueByType(typ), -1), endpoint(v, 1)) // key <= value
        else
          Interval(endpoint(v, -1), endpoint(maximumValueByType(typ), 1)) // value <= key
    }
  }

  def canGenerateOpenInterval(t: Type): Boolean = t match {
    case _: TNumeric => true
    case TBoolean => true
    case _: TLocus => true
    case ts: TBaseStruct => ts.fields.forall(f => canGenerateOpenInterval(f.typ))
    case _ => false
  }

  def opIsSupported(op: ComparisonOp[_]): Boolean = {
    op match {
      case EQ(_, _) => true
      case _: LTEQ | _: LT | _: GTEQ | _: GT => canGenerateOpenInterval(op.t1)
      case _ => false
    }
  }

  def extractAndRewrite(cond1: IR, es: ExtractionState): Option[(IR, Array[Interval])] = {
    cond1 match {
      case ApplySpecial("lor", _, Seq(l, r), t) =>
        extractAndRewrite(l, es)
          .liftedZip(extractAndRewrite(r, es))
          .flatMap {
            case ((True(), i1), (True(), i2)) =>
              Some((True(), Interval.union(i1 ++ i2, es.iOrd)))
            case _ => None
          }
      case ApplySpecial("land", _, Seq(l, r), t) =>
        val ll = extractAndRewrite(l, es)
        val rr = extractAndRewrite(r, es)
        (ll, rr) match {
          case (Some((ir1, i1)), Some((ir2, i2))) =>
            log.info(s"intersecting list of ${ i1.length } intervals with list of ${ i2.length } intervals")
            val intersection = Interval.intersection(i1, i2, es.iOrd)
            log.info(s"intersect generated ${ intersection.length } intersected intervals")
            Some((invoke("land", t, ir1, ir2), intersection))
          case (Some((ir1, i1)), None) =>
            Some((invoke("land", t, ir1, r), i1))
          case (None, Some((ir2, i2))) =>
            Some((invoke("land", t, l, ir2), i2))
          case (None, None) =>
            None
        }
      case StreamFold(ToStream(lit: Literal, _), False(), acc, value, body) =>
        body match {
          case ApplySpecial("lor", _, Seq(Ref(`acc`, _), ApplySpecial("contains", _, Seq(Ref(`value`, _), k), _)), _) if es.isFirstKey(k) =>
            assert(lit.typ.asInstanceOf[TContainer].elementType.isInstanceOf[TInterval])
            Some((True(),
              Interval.union(constValue(lit).asInstanceOf[Iterable[_]]
                .filter(_ != null)
                .map { v =>
                  val i = v.asInstanceOf[Interval]
                  Interval(
                    IntervalEndpoint(Row(i.left.point), i.left.sign),
                    IntervalEndpoint(Row(i.right.point), i.right.sign))
                }.toArray,
                es.iOrd)))
          case _ => None
        }
      case Coalesce(Seq(x, False())) => extractAndRewrite(x, es)
        .map { case (ir, intervals) => (Coalesce(FastSeq(ir, False())), intervals) }
      case ApplyIR("contains", _, Seq(lit: Literal, Apply("contig", _, Seq(k), _))) if es.isFirstKey(k) =>
        val rg = k.typ.asInstanceOf[TLocus].rg.asInstanceOf[ReferenceGenome]

        val intervals = (lit.value: @unchecked) match {
          case x: IndexedSeq[_] => x.map(elt => getIntervalFromContig(elt.asInstanceOf[String], rg)).toArray
          case x: Set[_] => x.map(elt => getIntervalFromContig(elt.asInstanceOf[String], rg)).toArray
          case x: Map[_, _] => x.keys.map(elt => getIntervalFromContig(elt.asInstanceOf[String], rg)).toArray
        }
        Some((True(), intervals))
      case ApplyIR("contains", _, Seq(lit: Literal, k)) if literalSizeOkay(lit) =>
        val wrap = if (es.isFirstKey(k)) Some(true) else if (es.isKeyStructPrefix(k)) Some(false) else None
        wrap.map { wrapStruct =>
          val intervals = (lit.value: @unchecked) match {
            case x: IndexedSeq[_] => x.map(elt => Interval(
              endpoint(elt, -1, wrapped = wrapStruct),
              endpoint(elt, 1, wrapped = wrapStruct))).toArray
            case x: Set[_] => x.map(elt => Interval(
              endpoint(elt, -1, wrapped = wrapStruct),
              endpoint(elt, 1, wrapped = wrapStruct))).toArray
            case x: Map[_, _] => x.keys.map(elt => Interval(
              endpoint(elt, -1, wrapped = wrapStruct),
              endpoint(elt, 1, wrapped = wrapStruct))).toArray
          }
          (True(), intervals)
        }
      case ApplySpecial("contains", _, Seq(lit: Literal, k), _) =>
        k match {
          case x if es.isFirstKey(x) =>
            val intervals = (lit.value: @unchecked) match {
              case null => Array[Interval]()
              case i: Interval => Array(i)
            }
            Some((True(), wrapInRow(intervals)))
          case x if es.isKeyStructPrefix(x) =>
            val intervals = (lit.value: @unchecked) match {
              case null => Array[Interval]()
              case i: Interval => Array(i)
            }
            Some((True(), intervals))
          case _ => None
        }
      case ApplyComparisonOp(op, l, r) if opIsSupported(op) =>
        val comparisonData = if (IsConstant(l))
          Some((l, r, false))
        else if (IsConstant(r))
          Some((r, l, true))
        else
          None
        comparisonData.flatMap { case (const, k, flipped) =>
          k match {
            case x if es.isFirstKey(x) =>
              // simple key comparison
              Some((True(), Array(openInterval(constValue(const), const.typ, op, flipped))))
            case x if es.isKeyStructPrefix(x) =>
              assert(op.isInstanceOf[EQ])
              val c = constValue(const)
              Some((True(), Array(Interval(endpoint(c, -1), endpoint(c, 1)))))
            case Apply("contig", _, Seq(x), _) if es.isFirstKey(x) =>
              // locus contig comparison
              val intervals = (constValue(const): @unchecked) match {
                case s: String => Array(getIntervalFromContig(s, es.firstKeyType.asInstanceOf[TLocus].rg.asInstanceOf[ReferenceGenome]))
              }
              Some((True(), intervals))
            case Apply("position", _, Seq(x), _) if es.isFirstKey(x) =>
              // locus position comparison
              val pos = constValue(const).asInstanceOf[Int]
              val rg = es.firstKeyType.asInstanceOf[TLocus].rg.asInstanceOf[ReferenceGenome]
              val ord = TTuple(TInt32).ordering
              val intervals = rg.contigs.indices
                .flatMap { i =>
                  openInterval(pos, TInt32, op, flipped).intersect(ord,
                    Interval(endpoint(1, -1), endpoint(rg.contigLength(i), -1)))
                    .map { interval =>
                      Interval(
                        endpoint(Locus(rg.contigs(i), interval.left.point.asInstanceOf[Row].getAs[Int](0)), interval.left.sign),
                        endpoint(Locus(rg.contigs(i), interval.right.point.asInstanceOf[Row].getAs[Int](0)), interval.right.sign))
                    }
                }.toArray

              Some((True(), intervals))
            case _ => None
          }
        }
      case Let(name, value, body) if name != es.rowRef.name =>
        // TODO: thread key identity through values, since this will break when CSE arrives
        // TODO: thread predicates in `value` through `body` as a ref
        extractAndRewrite(body, es)
          .map { case (ir, intervals) => (Let(name, value, ir), intervals) }
      case _ => None
    }
  }

  def extractPartitionFilters(cond: IR, ref: Ref, key: IndexedSeq[String]): Option[(IR, Array[Interval])] = {
    if (key.isEmpty)
      None
    else
      extractAndRewrite(cond, ExtractionState(ref, key))
  }

  def apply(ir0: BaseIR): BaseIR = {
    MapIR.mapBaseIR(ir0, (ir: BaseIR) => {
      (ir match {
        case TableFilter(child, pred) =>
          extractPartitionFilters(pred, Ref("row", child.typ.rowType), child.typ.key)
            .map { case (newCond, intervals) =>
              log.info(s"generated TableFilterIntervals node with ${ intervals.length } intervals:\n  " +
                s"Intervals: ${ intervals.mkString(", ") }\n  " +
                s"Predicate: ${ Pretty(pred) }\n " +
                s"Post: ${ Pretty(newCond) }")
              TableFilter(
                TableFilterIntervals(child, intervals, keep = true),
                newCond)
            }
        case MatrixFilterRows(child, pred) =>
          extractPartitionFilters(pred, Ref("va", child.typ.rowType), child.typ.rowKey)
            .map { case (newCond, intervals) =>
              log.info(s"generated MatrixFilterIntervals node with ${ intervals.length } intervals:\n  " +
                s"Intervals: ${ intervals.mkString(", ") }\n  " +
                s"Predicate: ${ Pretty(pred) }\n " +
                s"Post: ${ Pretty(newCond) }")
              MatrixFilterRows(
                MatrixFilterIntervals(child, intervals, keep = true),
                newCond)
            }

        case _ => None
      }).getOrElse(ir)
    })
  }
}