text:
namespace solar {

	bool win32_keyboard_device::is_virtual_key_down(int vk) {
		return (::GetAsyncKeyState(vk) & 0x8000) != 0;
	}

	win32_keyboard_device::win32_keyboard_device() {
	}

	win32_keyboard_device::~win32_keyboard_device() {
		ASSERT(_event_handlers.empty());
	}

	bool win32_keyboard_device::handle_wnd_proc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
		UNUSED_PARAMETER(hwnd);

		bool handled = false;

		switch (message) {
			case WM_KEYDOWN:
			case WM_SYSKEYDOWN: {
				handled = on_key_down(wparam, lparam);
				break;
			}

			case WM_KEYUP:
			case WM_SYSKEYUP: {
				handled = on_key_up(wparam, lparam);
				break;
			}

			case WM_CHAR:
			case WM_SYSCHAR: {
				handled = on_char_received(wparam, lparam);
				break;
			}
		}

		return handled;
	}

	void win32_keyboard_device::add_event_handler(keyboard_device_event_handler* handler) {
		push_back_and_verify_not_found(_event_handlers, handler);
	}

	void win32_keyboard_device::remove_event_handler(keyboard_device_event_handler* handler) {
		find_and_erase(_event_handlers, handler);
	}

	bool win32_keyboard_device::is_alt_down() const {
		return is_virtual_key_down(VK_MENU);
	}

	bool win32_keyboard_device::is_ctrl_down() const {
		return is_virtual_key_down(VK_CONTROL);
	}

	bool win32_keyboard_device::is_shift_down() const {
		return is_virtual_key_down(VK_SHIFT);
	}

	bool win32_keyboard_device::on_key_down(WPARAM wparam, LPARAM lparam) {
		keyboard_key key = get_keyboard_key_from_wparam(wparam);
		if (key != keyboard_key::invalid) {
			//http://stackoverflow.com/questions/6176566/get-30th-bit-of-the-lparam-param-in-wm-keydown-message
			bool was_down = ((lparam & 0x40000000) != 0);
			if (!was_down) {
				for (auto event_handler : _event_handlers) {
					event_handler->on_key_down(key);
				}
			}
			return true;
		}
		return false;
	}

	bool win32_keyboard_device::on_key_up(WPARAM wparam, LPARAM lparam) {
		UNUSED_PARAMETER(lparam);

		keyboard_key key = get_keyboard_key_from_wparam(wparam);
		if (key != keyboard_key::invalid) {
			for (auto event_handler : _event_handlers) {
				event_handler->on_key_up(key);
			}
			return true;
		}
		return false;
	}

	bool win32_keyboard_device::on_char_received(WPARAM wparam, LPARAM lparam) {
		UNUSED_PARAMETER(lparam);

		wchar_t char_code = (wchar_t)wparam;
		if (char_code >= L' ') {
			for (auto event_handler : _event_handlers) {
				event_handler->on_char_received(char_code);
			}
			return true;
		}
		return false;
	}

	keyboard_key win32_keyboard_device::get_keyboard_key_from_wparam(WPARAM wparam) const {
		switch (wparam) {
			case VK_BACK: return keyboard_key::BACKSPACE;
			case VK_TAB: return keyboard_key::TAB;
			case VK_RETURN: return keyboard_key::ENTER;
			case VK_SHIFT: return keyboard_key::SHIFT;
			case VK_CONTROL: return keyboard_key::CTRL;
			case VK_PAUSE: return keyboard_key::PAUSE;
			case VK_ESCAPE: return keyboard_key::ESCAPE;
			case VK_SPACE: return keyboard_key::SPACE;
			case VK_PRIOR: return keyboard_key::PAGE_UP;
			case VK_NEXT: return keyboard_key::PAGE_DOWN;
			case VK_END: return keyboard_key::END;
			case VK_HOME: return keyboard_key::HOME;
			case VK_UP: return keyboard_key::UP;
			case VK_DOWN: return keyboard_key::DOWN;
			case VK_LEFT: return keyboard_key::LEFT;
			case VK_RIGHT: return keyboard_key::RIGHT;
			case VK_INSERT: return keyboard_key::INSERT;
			case VK_DELETE: return keyboard_key::DEL;
			case VK_HELP: return keyboard_key::HELP;
			case VK_OEM_1: return keyboard_key::SEMI_COLON;
			case VK_OEM_PLUS: return keyboard_key::PLUS;
			case VK_OEM_COMMA: return keyboard_key::COMMA;
			case VK_OEM_MINUS: return keyboard_key::MINUS;
			case VK_OEM_PERIOD: return keyboard_key::PERIOD;
			case VK_OEM_2: return keyboard_key::FORWARD_SLASH;
			case VK_OEM_3: return keyboard_key::TILDE;
			case VK_OEM_4: return keyboard_key::OPEN_BRACKET;
			case VK_OEM_5: return keyboard_key::BACK_SLASH;
			case VK_OEM_6: return keyboard_key::CLOSE_BRACKET;
			case VK_OEM_7: return keyboard_key::QUOTE;
			case VK_SNAPSHOT: return keyboard_key::PRINT_SCREEN;
			case VK_SCROLL: return keyboard_key::SCROLL_LOCK;
			case VK_F1: return keyboard_key::F1;
			case VK_F2: return keyboard_key::F2;
			case VK_F3: return keyboard_key::F3;
			case VK_F4: return keyboard_key::F4;
			case VK_F5: return keyboard_key::F5;
			case VK_F6: return keyboard_key::F6;
			case VK_F7: return keyboard_key::F7;
			case VK_F8: return keyboard_key::F8;
			case VK_F9: return keyboard_key::F9;
			case VK_F10: return keyboard_key::F10;
			case VK_F11: return keyboard_key::F11;
			case VK_F12: return keyboard_key::F12;
			case '0': return keyboard_key::N0;
			case '1': return keyboard_key::N1;
			case '2': return keyboard_key::N2;
			case '3': return keyboard_key::N3;
			case '4': return keyboard_key::N4;
			case '5': return keyboard_key::N5;
			case '6': return keyboard_key::N6;
			case '7': return keyboard_key::N7;
			case '8': return keyboard_key::N8;
			case '9': return keyboard_key::N9;
			case 'A': return keyboard_key::A;
			case 'B': return keyboard_key::B;
			case 'C': return keyboard_key::C;
			case 'D': return keyboard_key::D;
			case 'E': return keyboard_key::E;
			case 'F': return keyboard_key::F;
			case 'G': return keyboard_key::G;
			case 'H': return keyboard_key::H;
			case 'I': return keyboard_key::I;
			case 'J': return keyboard_key::J;
			case 'K': return keyboard_key::K;
			case 'L': return keyboard_key::L;
			case 'M': return keyboard_key::M;
			case 'N': return keyboard_key::N;
			case 'O': return keyboard_key::O;
			case 'P': return keyboard_key::P;
			case 'Q': return keyboard_key::Q;
			case 'R': return keyboard_key::R;
			case 'S': return keyboard_key::S;
			case 'T': return keyboard_key::T;
			case 'U': return keyboard_key::U;
			case 'V': return keyboard_key::V;
			case 'W': return keyboard_key::W;
			case 'X': return keyboard_key::X;
			case 'Y': return keyboard_key::Y;
			case 'Z': return keyboard_key::Z;
			default: break;
		}

		return keyboard_key::invalid;
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Sonata\MediaBundle\Tests\Admin;

use PHPUnit\Framework\TestCase;
use Sonata\MediaBundle\Admin\GalleryHasMediaAdmin;

class GalleryHasMediaAdminTest extends TestCase
{
    private $mediaAdmin;

    protected function setUp()
    {
        $this->mediaAdmin = new GalleryHasMediaAdmin(
            null,
            'Sonata\MediaBundle\Entity\BaseGallery',
            'SonataMediaBundle:GalleryAdmin'
        );
    }

    public function testItIsInstantiable()
    {
        $this->assertNotNull($this->mediaAdmin);
    }
}


text:
use router::Router;
use handlers;
use base::framework::user_required;

pub fn gen_router() -> Router {
    let mut router = Router::new();
    router.get("/", handlers::home::index);
    router.get("/user/register", handlers::user::register_load);
    router.post("/user/register", handlers::user::register);
    router.post("/user/github/register", handlers::user::github_register);
    router.get("/user/login", handlers::user::login_load);
    router.post("/user/login", handlers::user::login);
    router.post("/user/github/bind", handlers::user::github_login);
    router.post("/user/logout", handlers::user::logout);
    router.get("/article/new", user_required(handlers::article::new_load));
    router.post("/article/new", user_required(handlers::article::new));
    router.get("/article/:article_id", handlers::article::show);
    router.get("/article/:article_id/edit", user_required(handlers::article::edit_load));
    router.post("/article/:article_id/edit", user_required(handlers::article::edit));
    router.get("/category/:category_id", handlers::home::category);
    router.get("/user/:user_id", handlers::user::show);
    router.get("/user/:user_id/comments", handlers::user::show_comments);
    router.get("/user/:user_id/messages", user_required(handlers::user::show_messages));
    router.post("/comment/new", user_required(handlers::comment::new));
    router.get("/rss", handlers::home::rss);
    router.get("/news", handlers::home::news);
    router.get("/auth/github/callback", handlers::user::github_callback);
    router
}


text:
@interface WCProperty ()

@property (nonatomic, strong) NSDateFormatter * dateFormatter;

@end

@implementation WCProperty

-(instancetype) init {
    self = [super init];
    if (self) {

    }
    return self;
}

+ (instancetype) propertyFactory: (icalproperty *) p {
    WCProperty * property;
    switch ( icalproperty_isa(p)) {
        case ICAL_ORGANIZER_PROPERTY:
        case ICAL_OWNER_PROPERTY:
        case ICAL_ATTENDEE_PROPERTY:
            property = [[WCPerson alloc] init];
            break;
        case ICAL_LOCATION_PROPERTY:
            property = [[WCLoc alloc] init];
            break;
        case ICAL_GEO_PROPERTY:
            property = [[WCGeo alloc] init];
            break;
        default:
            property = [[WCProperty alloc] init];
            break;
    }
    return property;
}

+(instancetype) propertyWithIcalProperty: (icalproperty *) p {

    WCProperty * property = [WCProperty propertyFactory:p];

    if (property) {

        property.parameters = [property parametersWithIcalProperty: p];

        property.kind = icalproperty_isa(p);

        icalvalue* v =  icalproperty_get_value (p);

        property.valueKind = icalvalue_isa(v);

        if (ICAL_XLICERROR_PROPERTY == property.kind) {
            NSLog(@"Error: %d, %@", property.kind, [property stringFromValue:v]);

        }

        switch (property.valueKind) {

            case ICAL_DATETIME_VALUE:
                property.value = [property datetimeFromValue: v parameters: property.parameters];
                break;

            case ICAL_INTEGER_VALUE:
                property.value = [property numberFromIntValue: v];
                break;

            case ICAL_DATE_VALUE:
                property.value = [property dateFromValue: v];
                break;

            case ICAL_RECUR_VALUE:
                property.value = [property recurFromValue: v];
                break;

            case ICAL_UTCOFFSET_VALUE:
                property.value = [property utcoffsetFromValue: v];
                break;

            case ICAL_PERIOD_VALUE:
                property.value = [property periodFromValue:v];
                break;

            case ICAL_DURATION_VALUE:
                property.value = [property durationFromValue: v];
                break;

            case ICAL_REQUESTSTATUS_VALUE:
                property.value = [property requeststatusFromValue: v];
                break;

            case ICAL_X_VALUE:
                property.value = [property stringFromValue: v];
                break;

            case ICAL_NO_VALUE:
                property.value = nil;
                break;
            case ICAL_GEO_VALUE:
                property.value = [property geoFromValue:v];
                break;

            case ICAL_ACTION_VALUE:
            case ICAL_ATTACH_VALUE:
            case ICAL_CALADDRESS_VALUE:
            case ICAL_STATUS_VALUE:
            case ICAL_CLASS_VALUE:
            case ICAL_URI_VALUE:
            case ICAL_TEXT_VALUE:
            case ICAL_STRING_VALUE:
            case ICAL_TRANSP_VALUE:
            case ICAL_METHOD_VALUE:
                property.value = [property stringFromValue: v];
                break;

            default:
                property.value = [property stringFromValue: v];
                break;
        }

        if(property.kind == ICAL_X_PROPERTY){
            property.propertyName = [[NSString alloc] initWithCString:icalproperty_get_x_name(p) encoding:NSUTF8StringEncoding];
        }else {
            property.propertyName = [[NSString alloc] initWithCString:icalproperty_get_property_name(p) encoding:NSUTF8StringEncoding];
        }

    }

    return property;

}

-(NSDictionary *) parametersWithIcalProperty: (icalproperty *) p {

    NSMutableDictionary * parameters = [[NSMutableDictionary alloc] init];

    icalparameter *pm = icalproperty_get_first_parameter(p, ICAL_ANY_PARAMETER);

    while (pm) {

        NSString * keyvaluepair = [NSString stringWithCString:icalparameter_as_ical_string(pm)
                                                     encoding:NSUTF8StringEncoding];

        NSArray * arr = [keyvaluepair componentsSeparatedByString:@"="];

        if (arr.count > 1) {
            [parameters setObject: arr[1] forKey:arr[0]];
        }

        pm = icalproperty_get_next_parameter(p, ICAL_ANY_PARAMETER);

    }

    return [NSDictionary dictionaryWithDictionary:parameters];

}

#pragma mark - Value Primatives

-(NSDate *) datetimeFromValue: (icalvalue *) v parameters: (NSDictionary *) parameters {
    struct icaltimetype t = icalvalue_get_datetime(v);

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear:t.year];
    [components setMonth: t.month];
    [components setDay:t.day];

    [components setHour:t.hour];
    [components setMinute: t.minute];
    [components setSecond: t.second];

    if (t.is_utc) {
        [components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    }
    else {

        NSString * tzid = parameters[@"TZID"];
        if (tzid) {
            NSTimeZone * tz = [NSTimeZone timeZoneWithName:tzid];
            [components setTimeZone: tz];
        }
        else {
            [components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

        }
    }

    // t.is_daylight
    // t.is_date
    NSDate * date =[calendar dateFromComponents: components];
    return date;

}

-(NSDate *) dateFromValue: (icalvalue *) v {
    return [self.dateFormatter dateFromString: [self stringFromValue:v]];
}

-(icaltimetype ) icaltimetypeFromObject:(id) date isDate:(BOOL) isDate {
    icaltimetype   t = icaltime_null_time();
    if ([date isKindOfClass:[NSDate class]]) {
        unsigned unitFlags = (isDate) ? NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay :
        NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond |NSCalendarUnitTimeZone ;

        NSCalendar * calendar = [NSCalendar currentCalendar];
        [calendar setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
        NSDateComponents *components = [calendar components:unitFlags fromDate:date];
        t.year =  (int)[components year];
        t.month = (int)[components month];
        t.day =   (int)[components day];
        t.hour =  (int)[components hour];
        t.minute = (int)[components minute];
        t.second = (int)[components second];

        t.is_date = isDate;

        icaltime_set_timezone(&t, icaltimezone_get_utc_timezone());
    }
    else {
        NSLog(@"Error: invalid date format");
    }
    return t;
}

-(NSNumber *) numberFromIntValue: (icalvalue *) v {

    return [NSNumber numberWithInt: icalvalue_get_integer(v)];

}

-(NSString *) stringFromValue: (icalvalue *) v {
    return [NSString stringWithCString: icalvalue_as_ical_string(v) encoding: NSUTF8StringEncoding];
}

- (NSDictionary*)geoFromValue:(icalvalue *) v {

    NSString* geoValue = [NSString stringWithCString: icalvalue_as_ical_string(v) encoding: NSUTF8StringEncoding];
    NSArray* tmp = [geoValue componentsSeparatedByString:@";"];
    return @{@"lat":[tmp firstObject],@"lon":[tmp lastObject]};
}

-(NSDictionary *) recurFromValue: (icalvalue *) v {
    struct icalrecurrencetype ical_recur = icalvalue_get_recur(v);

    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

    [dictionary setObject:[NSNumber numberWithInt:ical_recur.freq] forKey:@"freq"];
    [dictionary setObject:[self datetimeFromTimeType:ical_recur.until] forKey:@"until"];
    [dictionary setObject:[NSNumber numberWithInt:ical_recur.count] forKey:@"count"];
    [dictionary setObject:[NSNumber numberWithShort:ical_recur.interval] forKey:@"interval"];
    [dictionary setObject:[NSNumber numberWithInt:ical_recur.week_start] forKey:@"week_start"];
    [dictionary setObject:[self arrayFromCShortArray:ical_recur.by_second count:ICAL_BY_SECOND_SIZE] forKey:@"by_second"];
    [dictionary setObject:[self arrayFromCShortArray:ical_recur.by_minute count:ICAL_BY_MINUTE_SIZE] forKeyedSubscript:@"by_minute"];
    [dictionary setObject:[self arrayFromCShortArray:ical_recur.by_hour count:ICAL_BY_HOUR_SIZE] forKeyedSubscript:@"by_hour"];
    [dictionary setObject:[self arrayFromCShortArray:ical_recur.by_day count:ICAL_BY_DAY_SIZE] forKeyedSubscript:@"by_day"];
    [dictionary setObject:[self arrayFromCShortArray:ical_recur.by_month_day count:ICAL_BY_MONTHDAY_SIZE] forKeyedSubscript:@"by_month_day"];
    [dictionary setObject:[self arrayFromCShortArray:ical_recur.by_year_day count:ICAL_BY_YEARDAY_SIZE] forKeyedSubscript:@"by_year_day"];
    [dictionary setObject:[self arrayFromCShortArray:ical_recur.by_week_no count:ICAL_BY_WEEKNO_SIZE] forKeyedSubscript:@"by_week_no"];
    [dictionary setObject:[self arrayFromCShortArray:ical_recur.by_month count:ICAL_BY_MONTH_SIZE] forKeyedSubscript:@"by_month"];
    [dictionary setObject:[self arrayFromCShortArray:ical_recur.by_set_pos count:ICAL_BY_SETPOS_SIZE] forKeyedSubscript:@"by_set_pos"];
    if (ical_recur.rscale) {
        [dictionary setObject:[NSString stringWithCString: ical_recur.rscale encoding: NSUTF8StringEncoding] forKey:@"rscale"];
    }
    [dictionary setObject:[NSNumber numberWithInt:ical_recur.skip] forKey:@"skip"];

    return dictionary;
}

-(struct icalrecurrencetype) icalrecurrencetypeFromObject:(id) recur {
    struct icalrecurrencetype ical_recur = icalrecurrencetype_from_string("");

    ical_recur.freq = [recur[@"freq"] intValue];
    ical_recur.until = [self icaltimetypeFromObject:recur[@"until"] isDate:NO];
    ical_recur.count = [recur[@"count"] intValue];
    ical_recur.interval = [recur[@"interval"] intValue];
    ical_recur.week_start = (icalrecurrencetype_weekday)[recur[@"week_start"] intValue];
    [self cshortArrayFromArray:recur[@"by_second"] cshortArray:ical_recur.by_second];
    [self cshortArrayFromArray:recur[@"by_minute"] cshortArray:ical_recur.by_minute];
    [self cshortArrayFromArray:recur[@"by_hour"] cshortArray:ical_recur.by_hour];
    [self cshortArrayFromArray:recur[@"by_day"] cshortArray:ical_recur.by_day];
    [self cshortArrayFromArray:recur[@"by_month_day"] cshortArray:ical_recur.by_month_day];
    [self cshortArrayFromArray:recur[@"by_year_day"] cshortArray:ical_recur.by_year_day];
    [self cshortArrayFromArray:recur[@"by_week_no"] cshortArray:ical_recur.by_week_no];
    [self cshortArrayFromArray:recur[@"by_month"] cshortArray:ical_recur.by_month];
    [self cshortArrayFromArray:recur[@"by_set_pos"] cshortArray:ical_recur.by_set_pos];
    if (recur[@"rscale"]) {
        ical_recur.rscale = (char *)[recur[@"rscale"] cStringUsingEncoding:NSUTF8StringEncoding];
    }
    ical_recur.skip = [recur[@"skip"] intValue];

    return ical_recur;
}

-(NSNumber *) utcoffsetFromValue: (icalvalue *) v {
    int ical_utcoffset = icalvalue_get_utcoffset(v);

    return [NSNumber numberWithInt:ical_utcoffset];
}

-(NSDictionary *) periodFromValue: (icalvalue *) v {
    struct icalperiodtype ical_period = icalvalue_get_period(v);

    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

    [dictionary setObject:[self datetimeFromTimeType:ical_period.start] forKeyedSubscript:@"start"];
    [dictionary setObject:[self datetimeFromTimeType:ical_period.end] forKeyedSubscript:@"end"];
    [dictionary setObject:[self durationFromDurationType:ical_period.duration] forKeyedSubscript:@"duration"];

    return dictionary;
}

-(struct icalperiodtype) icalperiodtypeFromObject:(id) period {
    struct icalperiodtype ical_period = icalperiodtype_null_period();

    ical_period.start = [self icaltimetypeFromObject:period[@"start"] isDate:NO];
    ical_period.end = [self icaltimetypeFromObject:period[@"end"] isDate:NO];
    ical_period.duration = [self icaldurationtypeFromObject:period[@"duration"]];

    return ical_period;
}

-(NSDictionary *) durationFromValue: (icalvalue *) v {
    struct icaldurationtype ical_duration = icalvalue_get_duration(v);

    return [self durationFromDurationType:ical_duration];
}

-(struct icaldurationtype) icaldurationtypeFromObject:(id) duration {
    struct icaldurationtype ical_duration = icaldurationtype_from_int([duration[@"is_neg"] intValue]);

    ical_duration.is_neg = [duration[@"is_neg"] intValue];
    ical_duration.weeks = [duration[@"weeks"] intValue];
    ical_duration.days = [duration[@"days"] intValue];
    ical_duration.hours = [duration[@"hours"] intValue];
    ical_duration.minutes = [duration[@"minutes"] intValue];
    ical_duration.seconds = [duration[@"seconds"] intValue];

    return ical_duration;
}

-(NSDictionary *) requeststatusFromValue: (icalvalue *) v {
    struct icalreqstattype ical_reqstat = icalvalue_get_requeststatus(v);

    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

    [dictionary setObject:[NSNumber numberWithInteger:ical_reqstat.code] forKey:@"code"];

    if (ical_reqstat.debug) {
        [dictionary setObject:[NSString stringWithCString: ical_reqstat.debug encoding: NSASCIIStringEncoding] forKey:@"debug"];
    }

    if (ical_reqstat.desc) {
        [dictionary setObject:[NSString stringWithCString: ical_reqstat.desc encoding: NSASCIIStringEncoding] forKey:@"desc"];
    }

    return dictionary;
}

- (struct icalgeotype) icalgeotypeFromObject:(id)geo{
    struct icalgeotype ical_geo;
    if(!geo){
        ical_geo.lon = 0.0;
        ical_geo.lat = 0.0;
    }else {
        ical_geo.lat = [geo[@"lat"] floatValue];
        ical_geo.lon = [geo[@"lon"] floatValue];
    }
    return ical_geo;
}

-(struct icalreqstattype) icalreqstattypeFromObject:(id) reqstat {
    struct icalreqstattype ical_reqstat;

    ical_reqstat.code = [reqstat[@"code"] intValue];
    ical_reqstat.debug = [reqstat[@"debug"] cStringUsingEncoding:NSUTF8StringEncoding];
    ical_reqstat.desc = [reqstat[@"desc"] cStringUsingEncoding:NSUTF8StringEncoding];

    return ical_reqstat;
}

#pragma mark - custom accessors
-(NSDateFormatter *) dateFormatter {
    if (!_dateFormatter) {
        self.dateFormatter = [[NSDateFormatter alloc] init];
        self.dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
        self.dateFormatter.dateFormat = @"yyyyMMdd";
    }
    return _dateFormatter;
}

#pragma mark - Serialize

-(icalvalue *) icalBuildValue {
    icalvalue * value;
    switch (self.valueKind) {

        case ICAL_DATETIME_VALUE:
            value = icalvalue_new_datetime([self icaltimetypeFromObject: self.value isDate: NO]);
            break;

        case ICAL_INTEGER_VALUE:
            value = icalvalue_new_integer( [self integerFromObject: self.value]);
            break;

        case ICAL_DATE_VALUE:

            value = icalvalue_new_date([self icaltimetypeFromObject:self.value isDate:YES]);
            break;

        case ICAL_RECUR_VALUE:

            value = icalvalue_new_recur([self icalrecurrencetypeFromObject:self.value]);
            break;

        case ICAL_UTCOFFSET_VALUE:

            value = icalvalue_new_utcoffset([(NSNumber *)self.value intValue]);
            break;

        case ICAL_PERIOD_VALUE:

            value = icalvalue_new_period([self icalperiodtypeFromObject:self.value]);
            break;

        case ICAL_DURATION_VALUE:

            value = icalvalue_new_duration([self icaldurationtypeFromObject:self.value]);
            break;

        case ICAL_REQUESTSTATUS_VALUE:

            value = icalvalue_new_requeststatus([self icalreqstattypeFromObject:self.value]);
            break;
        case ICAL_GEO_VALUE:
            value = icalvalue_new_geo([self icalgeotypeFromObject:self.value]);
            break;

        case ICAL_NO_VALUE:

            value = NULL;
            break;

        case ICAL_ACTION_VALUE:
        case ICAL_ATTACH_VALUE:
        case ICAL_CALADDRESS_VALUE:
        case ICAL_STATUS_VALUE:
        case ICAL_CLASS_VALUE:
        case ICAL_URI_VALUE:
        case ICAL_TEXT_VALUE:
        case ICAL_STRING_VALUE:
        case ICAL_TRANSP_VALUE:
        case ICAL_METHOD_VALUE:
        case ICAL_X_VALUE:
            value = icalvalue_new_from_string(self.valueKind, [self cstringFromObject:self.value]);
            break;

        default:
             value = icalvalue_new_string([(NSString *)self.value cStringUsingEncoding:(NSUTF8StringEncoding)]);
            break;
    }

    return value;
}
-(icalproperty *) icalBuildProperty{

    icalproperty * ical_property = NULL;
    if  (self.kind == ICAL_X_PROPERTY){
        ical_property = icalproperty_new (ICAL_X_PROPERTY);
        icalproperty_set_x_name (ical_property, [self.propertyName UTF8String]);
    }else {
        ical_property = icalproperty_new(self.kind);
    }
    icalproperty_set_value(ical_property, [self icalBuildValue]);

    for (NSString * key in self.parameters) {
        NSString * value = self.parameters[key];

        icalparameter * ical_parameter =
            icalparameter_new_from_string([self cstringFromObject:[NSString stringWithFormat:@"%@=%@", key, value]]);

        icalproperty_add_parameter(ical_property, ical_parameter);

    }

    return ical_property;

}

- (NSString*)stringForRecurrence{
    icalvalue* value = icalvalue_new_recur([self icalrecurrencetypeFromObject:self.value]);
    char *ruleC = (char *)icalvalue_as_ical_string(value);
    NSString* rrlueString = @"";
    if (ruleC != NULL) {
        rrlueString = [NSString stringWithCString:ruleC encoding:NSUTF8StringEncoding];
    }
    return rrlueString;
}

#pragma mark - Helper Methods
-(const char *) cstringFromObject: (id) string {
    if ([string isKindOfClass:[NSString class]]) {
           return [(NSString *)string cStringUsingEncoding:NSUTF8StringEncoding];
    }
    else {
        NSLog(@"Error: unknown type");
        return "";
    }
}

-(int) integerFromObject: (id) number {
    int result = 0;
    if ([number isKindOfClass:[NSNumber class]]) {
        result = [(NSNumber *) number intValue];
    }
    return result;
}

#pragma mark - NSObject Overides
- (NSString *)description {
    return [NSString stringWithFormat:@"<%@: %p> Value: %@, Kind:%d, ValueKind: %d, Parameters: %@",
            NSStringFromClass([self class]), self, self.value, self.kind, self.valueKind, self.parameters];
}

- (instancetype)copyWithZone:(NSZone *)zone {
    WCProperty *object = [[[self class] allocWithZone:zone] init];

    if (object) {

        object.kind = self.kind;
        object.valueKind = self.valueKind;

        if ([self.value respondsToSelector:@selector(copyWithZone:)]) {
            object.value = [(id) self.value copyWithZone:zone];
        }
        else {
            object.value = self.value;
        }

        object.parameters = [[NSDictionary alloc] initWithDictionary:self.parameters copyItems:YES];

    }

    return object;
}
-(BOOL) isEqual: (WCProperty *) property {

    if (self.kind != property.kind) {
        return NO;
    }
    if (self.valueKind != property.valueKind) {
        return NO;
    }

    if ([self.value isKindOfClass:[NSString class]]) {
        if (![(NSString *)self.value isEqualToString: (NSString *) property.value ]) {
            return NO;
        }

    } else if ([self.value isKindOfClass:[NSDate class]]) {
        if (![(NSDate *) self.value isEqualToDate:(NSDate *) property.value]) {
            return NO;
        }
    }
    else {
        if (![self.value isEqual:property.value]) {
            return NO;
        }
    }

    if (![self.parameters isEqualToDictionary:property.parameters]) {
        return NO;
    }

    return YES;
}

-(NSObject *) datetimeFromTimeType: (icaltimetype) t {
    if ((int)icaltime_as_timet(t) == 0) {
        return [NSNull null];
    }

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear:t.year];
    [components setMonth: t.month];
    [components setDay:t.day];

    [components setHour:t.hour];
    [components setMinute: t.minute];
    [components setSecond: t.second];

    if (t.is_utc) {
        [components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    }
    else {
        NSString * tzid = icaltime_get_tzid(t) ? [NSString stringWithCString: icaltime_get_tzid(t) encoding: NSUTF8StringEncoding] : nil;
        if (tzid) {
            NSTimeZone * tz = [NSTimeZone timeZoneWithName:tzid];
            [components setTimeZone: tz];
        }
        else {
            [components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

        }
    }

    NSDate * date =[calendar dateFromComponents: components];
    return date;
}

-(NSDictionary *) durationFromDurationType: (struct icaldurationtype) ical_duration {
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

    [dictionary setObject:[NSNumber numberWithInt:ical_duration.is_neg] forKey:@"is_neg"];
    [dictionary setObject:[NSNumber numberWithInteger:ical_duration.weeks] forKey:@"weeks"];
    [dictionary setObject:[NSNumber numberWithInteger:ical_duration.days] forKey:@"days"];
    [dictionary setObject:[NSNumber numberWithInteger:ical_duration.hours] forKey:@"hours"];
    [dictionary setObject:[NSNumber numberWithInteger:ical_duration.minutes] forKey:@"minutes"];
    [dictionary setObject:[NSNumber numberWithInteger:ical_duration.seconds] forKey:@"seconds"];

    return dictionary;
}

-(NSArray *) arrayFromCShortArray: (short *)cshortArray count: (int)count {
    NSMutableArray *array = [NSMutableArray array];

    for (int i = 0; i < count; i++) {
        NSNumber *number = [[NSNumber alloc] initWithShort:cshortArray[i]];
        [array addObject:number];
    }

    return array;
}

-(void) cshortArrayFromArray: (NSArray *)array cshortArray: (short *)cshortArray {
    for (int i = 0; i < array.count; ++i) {
        cshortArray[i] = [[array objectAtIndex:i] shortValue];
    }
}

@end


text:
package org.keycloak.admin.client.resource;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.keycloak.representations.idm.authorization.RegexPolicyRepresentation;

/**
 * @author Yoshiyuki Tabata
 */
public interface RegexPoliciesResource {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    Response create(RegexPolicyRepresentation representation);

}


text:
var RxOld = require('rx');
var RxNew = require('../../../../index');

module.exports = function (suite) {
  var oldRepeatWithImmediateScheduler = RxOld.Observable.range(0, 25, RxOld.Scheduler.immediate).repeat(5);
  var newRepeatWithImmediateScheduler = RxNew.Observable.range(0, 25).repeat(5);

  function _next(x) { }
  function _error(e) { }
  function _complete() { }
  return suite
      .add('old repeat() with immediate scheduler', function () {
        oldRepeatWithImmediateScheduler.subscribe(_next, _error, _complete);
      })
      .add('new repeat() with immediate scheduler', function () {
        newRepeatWithImmediateScheduler.subscribe(_next, _error, _complete);
      });
};


text:
package overlay

import (
	"encoding/binary"
	"fmt"
	"net"
	"sync"

	"github.com/docker/libnetwork/config"
	"github.com/docker/libnetwork/datastore"
	"github.com/docker/libnetwork/driverapi"
	"github.com/docker/libnetwork/idm"
	"github.com/docker/libnetwork/netlabel"
	"github.com/docker/libnetwork/types"
	"github.com/hashicorp/serf/serf"
)

const (
	networkType  = "overlay"
	vethPrefix   = "veth"
	vethLen      = 7
	vxlanIDStart = 256
	vxlanIDEnd   = 1000
)

type driver struct {
	eventCh      chan serf.Event
	notifyCh     chan ovNotify
	exitCh       chan chan struct{}
	ifaceName    string
	neighIP      string
	peerDb       peerNetworkMap
	serfInstance *serf.Serf
	networks     networkTable
	store        datastore.DataStore
	ipAllocator  *idm.Idm
	vxlanIdm     *idm.Idm
	sync.Once
	sync.Mutex
}

var (
	bridgeSubnet, bridgeIP *net.IPNet
	once                   sync.Once
	bridgeSubnetInt        uint32
)

func onceInit() {
	var err error
	_, bridgeSubnet, err = net.ParseCIDR("172.21.0.0/16")
	if err != nil {
		panic("could not parse cid 172.21.0.0/16")
	}

	bridgeSubnetInt = binary.BigEndian.Uint32(bridgeSubnet.IP.To4())

	ip, subnet, err := net.ParseCIDR("172.21.255.254/16")
	if err != nil {
		panic("could not parse cid 172.21.255.254/16")
	}

	bridgeIP = &net.IPNet{
		IP:   ip,
		Mask: subnet.Mask,
	}
}

// Init registers a new instance of overlay driver
func Init(dc driverapi.DriverCallback) error {
	once.Do(onceInit)

	c := driverapi.Capability{
		Scope: driverapi.GlobalScope,
	}

	return dc.RegisterDriver(networkType, &driver{
		networks: networkTable{},
		peerDb: peerNetworkMap{
			mp: map[types.UUID]peerMap{},
		},
	}, c)
}

// Fini cleans up the driver resources
func Fini(drv driverapi.Driver) {
	d := drv.(*driver)

	if d.exitCh != nil {
		waitCh := make(chan struct{})

		d.exitCh <- waitCh

		<-waitCh
	}
}

func (d *driver) Config(option map[string]interface{}) error {
	var onceDone bool
	var err error

	d.Do(func() {
		onceDone = true

		if ifaceName, ok := option[netlabel.OverlayBindInterface]; ok {
			d.ifaceName = ifaceName.(string)
		}

		if neighIP, ok := option[netlabel.OverlayNeighborIP]; ok {
			d.neighIP = neighIP.(string)
		}

		provider, provOk := option[netlabel.KVProvider]
		provURL, urlOk := option[netlabel.KVProviderURL]

		if provOk && urlOk {
			cfg := &config.DatastoreCfg{
				Client: config.DatastoreClientCfg{
					Provider: provider.(string),
					Address:  provURL.(string),
				},
			}
			d.store, err = datastore.NewDataStore(cfg)
			if err != nil {
				err = fmt.Errorf("failed to initialize data store: %v", err)
				return
			}
		}

		d.vxlanIdm, err = idm.New(d.store, "vxlan-id", vxlanIDStart, vxlanIDEnd)
		if err != nil {
			err = fmt.Errorf("failed to initialize vxlan id manager: %v", err)
			return
		}

		d.ipAllocator, err = idm.New(d.store, "ipam-id", 1, 0xFFFF-2)
		if err != nil {
			err = fmt.Errorf("failed to initalize ipam id manager: %v", err)
			return
		}

		err = d.serfInit()
		if err != nil {
			err = fmt.Errorf("initializing serf instance failed: %v", err)
		}

	})

	if !onceDone {
		return fmt.Errorf("config already applied to driver")
	}

	return err
}

func (d *driver) Type() string {
	return networkType
}


text:
ccflags-y += -I${srctree}/samples/include

obj-y = test-rand32.o


text:
from logbook import FileHandler
from zipline.finance.blotter import ORDER_STATUS

from six import itervalues

def setup_logger(test, path='test.log'):
    test.log_handler = FileHandler(path)
    test.log_handler.push_application()

def teardown_logger(test):
    test.log_handler.pop_application()
    test.log_handler.close()

def drain_zipline(test, zipline):
    output = []
    transaction_count = 0
    msg_counter = 0
    # start the simulation
    for update in zipline:
        msg_counter += 1
        output.append(update)
        if 'daily_perf' in update:
            transaction_count += \
                len(update['daily_perf']['transactions'])

    return output, transaction_count

def assert_single_position(test, zipline):

    output, transaction_count = drain_zipline(test, zipline)

    if 'expected_transactions' in test.zipline_test_config:
        test.assertEqual(
            test.zipline_test_config['expected_transactions'],
            transaction_count
        )
    else:
        test.assertEqual(
            test.zipline_test_config['order_count'],
            transaction_count
        )

    # the final message is the risk report, the second to
    # last is the final day's results. Positions is a list of
    # dicts.
    closing_positions = output[-2]['daily_perf']['positions']

    # confirm that all orders were filled.
    # iterate over the output updates, overwriting
    # orders when they are updated. Then check the status on all.
    orders_by_id = {}
    for update in output:
        if 'daily_perf' in update:
            if 'orders' in update['daily_perf']:
                for order in update['daily_perf']['orders']:
                    orders_by_id[order['id']] = order

    for order in itervalues(orders_by_id):
        test.assertEqual(
            order['status'],
            ORDER_STATUS.FILLED,
            "")

    test.assertEqual(
        len(closing_positions),
        1,
        "Portfolio should have one position."
    )

    sid = test.zipline_test_config['sid']
    test.assertEqual(
        closing_positions[0]['sid'],
        sid,
        "Portfolio should have one position in " + str(sid)
    )

    return output, transaction_count

class ExceptionSource(object):

    def __init__(self):
        pass

    def get_hash(self):
        return "ExceptionSource"

    def __iter__(self):
        return self

    def next(self):
        5 / 0

    def __next__(self):
        5 / 0

class ExceptionTransform(object):

    def __init__(self):
        self.window_length = 1
        pass

    def get_hash(self):
        return "ExceptionTransform"

    def update(self, event):
        assert False, "An assertion message"


text:
namespace {

class TestContextURLRequestContextGetter : public net::URLRequestContextGetter {
 public:
  explicit TestContextURLRequestContextGetter(net::URLRequestContext* context)
      : context_(context),
        null_task_runner_(new base::NullTaskRunner) {
  }

  virtual net::URLRequestContext* GetURLRequestContext() OVERRIDE {
    return context_;
  }

  virtual scoped_refptr<base::SingleThreadTaskRunner>
      GetNetworkTaskRunner() const OVERRIDE {
    return null_task_runner_;
  }

 private:
  virtual ~TestContextURLRequestContextGetter() {}

  net::URLRequestContext* context_;
  scoped_refptr<base::SingleThreadTaskRunner> null_task_runner_;
};

}  // namespace

namespace content {

TestBrowserContext::TestBrowserContext() {
  EXPECT_TRUE(browser_context_dir_.CreateUniqueTempDir());
}

TestBrowserContext::~TestBrowserContext() {
}

base::FilePath TestBrowserContext::TakePath() {
  return browser_context_dir_.Take();
}

void TestBrowserContext::SetSpecialStoragePolicy(
    quota::SpecialStoragePolicy* policy) {
  special_storage_policy_ = policy;
}

base::FilePath TestBrowserContext::GetPath() {
  return browser_context_dir_.path();
}

bool TestBrowserContext::IsOffTheRecord() const {
  return false;
}

DownloadManagerDelegate* TestBrowserContext::GetDownloadManagerDelegate() {
  return NULL;
}

net::URLRequestContextGetter* TestBrowserContext::GetRequestContext() {
  if (!request_context_.get()) {
    request_context_ = new TestContextURLRequestContextGetter(
        GetResourceContext()->GetRequestContext());
  }
  return request_context_.get();
}

net::URLRequestContextGetter*
TestBrowserContext::GetRequestContextForRenderProcess(int renderer_child_id) {
  return NULL;
}

net::URLRequestContextGetter* TestBrowserContext::GetMediaRequestContext() {
  return NULL;
}

net::URLRequestContextGetter*
TestBrowserContext::GetMediaRequestContextForRenderProcess(
    int renderer_child_id) {
  return NULL;
}

net::URLRequestContextGetter*
TestBrowserContext::GetMediaRequestContextForStoragePartition(
    const base::FilePath& partition_path,
    bool in_memory) {
  return NULL;
}

ResourceContext* TestBrowserContext::GetResourceContext() {
  if (!resource_context_)
    resource_context_.reset(new MockResourceContext());
  return resource_context_.get();
}

GeolocationPermissionContext*
    TestBrowserContext::GetGeolocationPermissionContext() {
  return NULL;
}

SpeechRecognitionPreferences*
    TestBrowserContext::GetSpeechRecognitionPreferences() {
  return NULL;
}

quota::SpecialStoragePolicy* TestBrowserContext::GetSpecialStoragePolicy() {
  return special_storage_policy_.get();
}

}  // namespace content


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}dj-trans{% endblock %}</title>
    {% block extra-head %}{% endblock %}
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>


text:
namespace {

// BaseWindowFinder -----------------------------------------------------------

// Base class used to locate a window. This is intended to be used with the
// various win32 functions that iterate over windows.
//
// A subclass need only override ShouldStopIterating to determine when
// iteration should stop.
class BaseWindowFinder {
 public:
  // Creates a BaseWindowFinder with the specified set of HWNDs to ignore.
  explicit BaseWindowFinder(const std::set<HWND>& ignore) : ignore_(ignore) {}
  virtual ~BaseWindowFinder() {}

 protected:
  static BOOL CALLBACK WindowCallbackProc(HWND hwnd, LPARAM lParam) {
    // Cast must match that in as_lparam().
    BaseWindowFinder* finder = reinterpret_cast<BaseWindowFinder*>(lParam);
    if (finder->ignore_.find(hwnd) != finder->ignore_.end())
      return TRUE;

    return finder->ShouldStopIterating(hwnd) ? FALSE : TRUE;
  }

  LPARAM as_lparam() {
    // Cast must match that in WindowCallbackProc().
    return reinterpret_cast<LPARAM>(static_cast<BaseWindowFinder*>(this));
  }

  // Returns true if iteration should stop, false if iteration should continue.
  virtual bool ShouldStopIterating(HWND window) = 0;

 private:
  const std::set<HWND>& ignore_;

  DISALLOW_COPY_AND_ASSIGN(BaseWindowFinder);
};

// TopMostFinder --------------------------------------------------------------

// Helper class to determine if a particular point of a window is not obscured
// by another window.
class TopMostFinder : public BaseWindowFinder {
 public:
  // Returns true if |window| is the topmost window at the location
  // |screen_loc|, not including the windows in |ignore|.
  static bool IsTopMostWindowAtPoint(HWND window,
                                     const gfx::Point& screen_loc,
                                     const std::set<HWND>& ignore) {
    TopMostFinder finder(window, screen_loc, ignore);
    return finder.is_top_most_;
  }

  virtual bool ShouldStopIterating(HWND hwnd) {
    if (hwnd == target_) {
      // Window is topmost, stop iterating.
      is_top_most_ = true;
      return true;
    }

    if (!IsWindowVisible(hwnd)) {
      // The window isn't visible, keep iterating.
      return false;
    }

    RECT r;
    if (!GetWindowRect(hwnd, &r) || !PtInRect(&r, screen_loc_.ToPOINT())) {
      // The window doesn't contain the point, keep iterating.
      return false;
    }

    LONG ex_styles = GetWindowLong(hwnd, GWL_EXSTYLE);
    if (ex_styles & WS_EX_TRANSPARENT || ex_styles & WS_EX_LAYERED) {
      // Mouse events fall through WS_EX_TRANSPARENT windows, so we ignore them.
      //
      // WS_EX_LAYERED is trickier. Apps like Switcher create a totally
      // transparent WS_EX_LAYERED window that is always on top. If we don't
      // ignore WS_EX_LAYERED windows and there are totally transparent
      // WS_EX_LAYERED windows then there are effectively holes on the screen
      // that the user can't reattach tabs to. So we ignore them. This is a bit
      // problematic in so far as WS_EX_LAYERED windows need not be totally
      // transparent in which case we treat chrome windows as not being obscured
      // when they really are, but this is better than not being able to
      // reattach tabs.
      return false;
    }

    // hwnd is at the point. Make sure the point is within the windows region.
    if (GetWindowRgn(hwnd, tmp_region_.Get()) == ERROR) {
      // There's no region on the window and the window contains the point. Stop
      // iterating.
      return true;
    }

    // The region is relative to the window's rect.
    BOOL is_point_in_region = PtInRegion(tmp_region_.Get(),
        screen_loc_.x() - r.left, screen_loc_.y() - r.top);
    tmp_region_ = CreateRectRgn(0, 0, 0, 0);
    // Stop iterating if the region contains the point.
    return !!is_point_in_region;
  }

 private:
  TopMostFinder(HWND window,
                const gfx::Point& screen_loc,
                const std::set<HWND>& ignore)
      : BaseWindowFinder(ignore),
        target_(window),
        screen_loc_(screen_loc),
        is_top_most_(false),
        tmp_region_(CreateRectRgn(0, 0, 0, 0)) {
    EnumWindows(WindowCallbackProc, as_lparam());
  }

  // The window we're looking for.
  HWND target_;

  // Location of window to find.
  gfx::Point screen_loc_;

  // Is target_ the top most window? This is initially false but set to true
  // in ShouldStopIterating if target_ is passed in.
  bool is_top_most_;

  base::win::ScopedRegion tmp_region_;

  DISALLOW_COPY_AND_ASSIGN(TopMostFinder);
};

// WindowFinder ---------------------------------------------------------------

// Helper class to determine if a particular point contains a window from our
// process.
class LocalProcessWindowFinder : public BaseWindowFinder {
 public:
  // Returns the hwnd from our process at screen_loc that is not obscured by
  // another window. Returns NULL otherwise.
  static HWND GetProcessWindowAtPoint(const gfx::Point& screen_loc,
                                      const std::set<HWND>& ignore) {
    LocalProcessWindowFinder finder(screen_loc, ignore);
    // Windows 8 has a window that appears first in the list of iterated
    // windows, yet is not visually on top of everything.
    // TODO(sky): figure out a better way to ignore this window.
    if (finder.result_ &&
        ((base::win::OSInfo::GetInstance()->version() >=
          base::win::VERSION_WIN8) ||
         TopMostFinder::IsTopMostWindowAtPoint(finder.result_, screen_loc,
                                               ignore))) {
      return finder.result_;
    }
    return NULL;
  }

 protected:
  virtual bool ShouldStopIterating(HWND hwnd) {
    RECT r;
    if (IsWindowVisible(hwnd) && GetWindowRect(hwnd, &r) &&
        PtInRect(&r, screen_loc_.ToPOINT())) {
      result_ = hwnd;
      return true;
    }
    return false;
  }

 private:
  LocalProcessWindowFinder(const gfx::Point& screen_loc,
                           const std::set<HWND>& ignore)
      : BaseWindowFinder(ignore),
        screen_loc_(screen_loc),
        result_(NULL) {
    EnumThreadWindows(GetCurrentThreadId(), WindowCallbackProc, as_lparam());
  }

  // Position of the mouse.
  gfx::Point screen_loc_;

  // The resulting window. This is initially null but set to true in
  // ShouldStopIterating if an appropriate window is found.
  HWND result_;

  DISALLOW_COPY_AND_ASSIGN(LocalProcessWindowFinder);
};

// DockToWindowFinder ---------------------------------------------------------

// Helper class for creating a DockInfo from a specified point.
class DockToWindowFinder : public BaseWindowFinder {
 public:
  // Returns the DockInfo for the specified point. If there is no docking
  // position for the specified point the returned DockInfo has a type of NONE.
  static DockInfo GetDockInfoAtPoint(const gfx::Point& screen_loc,
                                     const std::set<HWND>& ignore) {
    DockToWindowFinder finder(screen_loc, ignore);
    if (!finder.result_.window() ||
        !TopMostFinder::IsTopMostWindowAtPoint(finder.result_.window(),
                                               finder.result_.hot_spot(),
                                               ignore)) {
      finder.result_.set_type(DockInfo::NONE);
    }
    return finder.result_;
  }

 protected:
  virtual bool ShouldStopIterating(HWND hwnd) {
    BrowserView* window = BrowserView::GetBrowserViewForNativeWindow(hwnd);
    RECT bounds;
    if (!window || !IsWindowVisible(hwnd) ||
        !GetWindowRect(hwnd, &bounds)) {
      return false;
    }

    // Check the three corners we allow docking to. We don't currently allow
    // docking to top of window as it conflicts with docking to the tab strip.
    if (CheckPoint(hwnd, bounds.left, (bounds.top + bounds.bottom) / 2,
                   DockInfo::LEFT_OF_WINDOW) ||
        CheckPoint(hwnd, bounds.right - 1, (bounds.top + bounds.bottom) / 2,
                   DockInfo::RIGHT_OF_WINDOW) ||
        CheckPoint(hwnd, (bounds.left + bounds.right) / 2, bounds.bottom - 1,
                   DockInfo::BOTTOM_OF_WINDOW)) {
      return true;
    }
    return false;
  }

 private:
  DockToWindowFinder(const gfx::Point& screen_loc,
                     const std::set<HWND>& ignore)
      : BaseWindowFinder(ignore),
        screen_loc_(screen_loc) {
    gfx::Rect work_area = gfx::Screen::GetMonitorNearestPoint(
        screen_loc).bounds();
    if (!work_area.IsEmpty()) {
      result_.set_monitor_bounds(work_area);
      EnumThreadWindows(GetCurrentThreadId(), WindowCallbackProc, as_lparam());
    }
  }

  bool CheckPoint(HWND hwnd, int x, int y, DockInfo::Type type) {
    bool in_enable_area;
    if (DockInfo::IsCloseToPoint(screen_loc_, x, y, &in_enable_area)) {
      result_.set_in_enable_area(in_enable_area);
      result_.set_window(hwnd);
      result_.set_type(type);
      result_.set_hot_spot(gfx::Point(x, y));
      // Only show the hotspot if the monitor contains the bounds of the popup
      // window. Otherwise we end with a weird situation where the popup window
      // isn't completely visible.
      return result_.monitor_bounds().Contains(result_.GetPopupRect());
    }
    return false;
  }

  // The location to look for.
  gfx::Point screen_loc_;

  // The resulting DockInfo.
  DockInfo result_;

  DISALLOW_COPY_AND_ASSIGN(DockToWindowFinder);
};

}  // namespace

// DockInfo -------------------------------------------------------------------

// static
DockInfo DockInfo::GetDockInfoAtPoint(const gfx::Point& screen_point,
                                      const std::set<HWND>& ignore) {
  if (factory_)
    return factory_->GetDockInfoAtPoint(screen_point, ignore);

  // Try docking to a window first.
  DockInfo info = DockToWindowFinder::GetDockInfoAtPoint(screen_point, ignore);
  if (info.type() != DockInfo::NONE)
    return info;

  // No window relative positions. Try monitor relative positions.
  const gfx::Rect& m_bounds = info.monitor_bounds();
  int mid_x = m_bounds.x() + m_bounds.width() / 2;
  int mid_y = m_bounds.y() + m_bounds.height() / 2;

  bool result =
      info.CheckMonitorPoint(screen_point, mid_x, m_bounds.y(),
                             DockInfo::MAXIMIZE) ||
      info.CheckMonitorPoint(screen_point, mid_x, m_bounds.bottom(),
                             DockInfo::BOTTOM_HALF) ||
      info.CheckMonitorPoint(screen_point, m_bounds.x(), mid_y,
                             DockInfo::LEFT_HALF) ||
      info.CheckMonitorPoint(screen_point, m_bounds.right(), mid_y,
                             DockInfo::RIGHT_HALF);

  return info;
}

HWND DockInfo::GetLocalProcessWindowAtPoint(const gfx::Point& screen_point,
                                            const std::set<HWND>& ignore) {
  if (factory_)
    return factory_->GetLocalProcessWindowAtPoint(screen_point, ignore);
  return
      LocalProcessWindowFinder::GetProcessWindowAtPoint(screen_point, ignore);
}

bool DockInfo::GetWindowBounds(gfx::Rect* bounds) const {
  RECT window_rect;
  if (!window() || !GetWindowRect(window(), &window_rect))
    return false;
  *bounds = gfx::Rect(window_rect);
  return true;
}

void DockInfo::SizeOtherWindowTo(const gfx::Rect& bounds) const {
  if (IsZoomed(window())) {
    // We're docking relative to another window, we need to make sure the
    // window we're docking to isn't maximized.
    ShowWindow(window(), SW_RESTORE | SW_SHOWNA);
  }
  SetWindowPos(window(), HWND_TOP, bounds.x(), bounds.y(), bounds.width(),
               bounds.height(), SWP_NOACTIVATE | SWP_NOOWNERZORDER);
}


text:
ACCEPTED

#### According to
Euro+Med Plantbase

#### Published in
null

#### Original name
Hieracium baeticum subsp. palomerae Zahn

### Remarks
null


text:
#import "ORKTowerOfHanoiTowerView.h"
#import "ORKActiveStepView.h"
#import "ORKSkin.h"
#import "ORKAccessibility.h"
#import "ORKHelpers.h"

static const CGFloat DiskHeight = 10;
static const CGFloat DiskSpacing = 8;
static const CGFloat BaseSpacing = 10;

@implementation ORKTowerOfHanoiTowerView {
    NSInteger _maximumNumberOfDisks;
    UIView *_base;
    NSMutableArray *_diskViews;
    NSMutableArray *_diskSizes;
    NSMutableArray *_variableConstraints;
}

#pragma mark - Init

- (instancetype)initWithFrame:(CGRect)frame maximumNumberOfDisks:(NSUInteger)maximumNumberOfDisks {
    self = [super initWithFrame:frame];
    if (self) {
        _maximumNumberOfDisks = maximumNumberOfDisks;
        _base = [[UIView alloc] initWithFrame:CGRectZero];
        _base.backgroundColor = [UIColor ork_midGrayTintColor];
        [_base setTranslatesAutoresizingMaskIntoConstraints:NO];
        _base.layer.cornerRadius = 2.5;
        _base.layer.masksToBounds = YES;
        _diskViews = [NSMutableArray new];
        _diskSizes = [NSMutableArray new];
        [self addSubview:_base];
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userDidTapTower)]];
    }
    return self;
}

#pragma mark - UIView

- (void)updateConstraints {
    [NSLayoutConstraint deactivateConstraints:_variableConstraints];
    [_variableConstraints removeAllObjects];

    if (!_variableConstraints) {
        _variableConstraints = [NSMutableArray new];
    }

    CGFloat height = (DiskHeight * _maximumNumberOfDisks) + (DiskSpacing * _maximumNumberOfDisks);

    [_variableConstraints addObject:[NSLayoutConstraint constraintWithItem:self
                                                                 attribute:NSLayoutAttributeHeight
                                                                 relatedBy:NSLayoutRelationGreaterThanOrEqual
                                                                    toItem:nil
                                                                 attribute:NSLayoutAttributeNotAnAttribute
                                                                multiplier:1.0
                                                                  constant:height + BaseSpacing]];

    [_variableConstraints addObject:[NSLayoutConstraint constraintWithItem:_base
                                                                 attribute:NSLayoutAttributeWidth
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self
                                                                 attribute:NSLayoutAttributeWidth
                                                                multiplier:1.0
                                                                  constant:0.0]];

    [_variableConstraints addObject:[NSLayoutConstraint constraintWithItem:_base
                                                                 attribute:NSLayoutAttributeHeight
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:nil
                                                                 attribute:NSLayoutAttributeNotAnAttribute
                                                                multiplier:1.0
                                                                  constant:2]];

    [_variableConstraints addObject:[NSLayoutConstraint constraintWithItem:_base
                                                                 attribute:NSLayoutAttributeCenterX
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self
                                                                 attribute:NSLayoutAttributeCenterX
                                                                multiplier:1.0
                                                                  constant:0.0]];

    [_variableConstraints addObject:[NSLayoutConstraint constraintWithItem:_base
                                                                 attribute:NSLayoutAttributeBottom
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self
                                                                 attribute:NSLayoutAttributeCenterY
                                                                multiplier:1.0
                                                                  constant:(height * 0.5) + BaseSpacing]];

    UIView *topDisk;
    for (NSInteger index = 0 ; index < _diskSizes.count ; index++) {
        UIView *disk = _diskViews[index];
        CGFloat divide = 1.0 / _maximumNumberOfDisks;
        CGFloat multiply = [(NSNumber *)_diskSizes[index] floatValue] * divide;

        [_variableConstraints addObject:[NSLayoutConstraint constraintWithItem:disk
                                                                     attribute:NSLayoutAttributeCenterX
                                                                     relatedBy:NSLayoutRelationEqual
                                                                        toItem:self
                                                                     attribute:NSLayoutAttributeCenterX
                                                                    multiplier:1.0
                                                                      constant:0.0]];

        [_variableConstraints addObject:[NSLayoutConstraint constraintWithItem:disk
                                                                     attribute:NSLayoutAttributeWidth
                                                                     relatedBy:NSLayoutRelationEqual
                                                                        toItem:_base
                                                                     attribute:NSLayoutAttributeWidth
                                                                    multiplier:multiply
                                                                      constant:0.0]];

        [_variableConstraints addObject:[NSLayoutConstraint constraintWithItem:disk
                                                                     attribute:NSLayoutAttributeHeight
                                                                     relatedBy:NSLayoutRelationEqual
                                                                        toItem:nil
                                                                     attribute:NSLayoutAttributeNotAnAttribute
                                                                    multiplier:1.0
                                                                      constant:DiskHeight]];

        if (index == 0) {
            [_variableConstraints addObject:[NSLayoutConstraint constraintWithItem:disk
                                                                         attribute:NSLayoutAttributeBottom
                                                                         relatedBy:NSLayoutRelationEqual
                                                                            toItem:self
                                                                         attribute:NSLayoutAttributeCenterY
                                                                        multiplier:1.0
                                                                          constant:height * 0.5]];
        } else {
            [_variableConstraints addObject:[NSLayoutConstraint constraintWithItem:disk
                                                                         attribute:NSLayoutAttributeBottom
                                                                         relatedBy:NSLayoutRelationEqual
                                                                            toItem:topDisk
                                                                         attribute:NSLayoutAttributeTop
                                                                        multiplier:1.0
                                                                          constant:-DiskSpacing]];
        }
        topDisk = disk;
    }
    [NSLayoutConstraint activateConstraints:_variableConstraints];
    [super updateConstraints];
}

- (void)tintColorDidChange {
    [self reloadData];
}

#pragma mark - Public

- (void)reloadData {
    [self updateDisks];
    [self highlightIfNeeded];
    [self indicateTargetIfNeeded];
    [self setNeedsUpdateConstraints];
}

#pragma mark - Private

- (void)userDidTapTower {
    [self.delegate towerOfHanoiTowerViewWasSelected:self];
}

- (void)updateDisks {
    [_diskViews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    ORKRemoveConstraintsForRemovedViews(_variableConstraints, _diskViews);

    [_diskViews removeAllObjects];
    [_diskSizes removeAllObjects];

    NSInteger numberOfDisks = [self.dataSource numberOfDisksInTowerOfHanoiView:self];
    for (NSInteger index = 0 ; index < numberOfDisks ; index++) {
        NSNumber *diskSize = [self.dataSource towerOfHanoiView:self diskAtIndex:index];
        [_diskSizes addObject:diskSize];
        UIView *diskView = [[UIView alloc] initWithFrame:CGRectZero];
        diskView.backgroundColor = [self tintColor];
        diskView.translatesAutoresizingMaskIntoConstraints = NO;
        diskView.layer.cornerRadius = DiskHeight * 0.5;
        diskView.clipsToBounds = YES;
        [self addSubview:diskView];
        [_diskViews addObject:diskView];
    }
}

- (void)highlightIfNeeded {
    if (self.isHighLighted) {
        ((UIView *)_diskViews.lastObject).alpha = 0.2;
    }
}

- (void)indicateTargetIfNeeded {
    if (self.isTargeted) {
        _base.backgroundColor = [self tintColor];
    }
}

#pragma mark - Accessibility

- (BOOL)isAccessibilityElement {
    return YES;
}

- (NSString *)accessibilityLabel {
    NSString *targetDisk = (self.isTargeted ? ORKLocalizedString(@"AX_TOWER_OF_HANOI_TARGET_DISK", nil) : nil);
    return ORKAccessibilityStringForVariables(ORKLocalizedString(@"AX_TOWER_OF_HANOI_TOWER", nil), targetDisk);
}

- (NSString *)accessibilityHint {
    if (!self.isHighLighted && [self.delegate towerOfHanoiHighlightedTowerView] != nil) {
        return ORKLocalizedString(@"AX_TOWER_OF_HANOI_PLACE_DISK", nil);
    }

    BOOL hasDisks = ([self.dataSource numberOfDisksInTowerOfHanoiView:self] > 0);
    return (self.isHighLighted ? nil : (hasDisks ? ORKLocalizedString(@"AX_TOWER_OF_HANOI_SELECT_DISK", nil) : nil));
}

- (UIAccessibilityTraits)accessibilityTraits {
    UIAccessibilityTraits traits = [super accessibilityTraits];
    if (self.isHighLighted) {
        traits |= UIAccessibilityTraitSelected;
    }

    // Don't echo if when a disk is placed.
    if (!self.isHighLighted && UIAccessibilityFocusedElement(UIAccessibilityNotificationVoiceOverIdentifier) == self) {
        traits |= UIAccessibilityTraitStartsMediaSession;
    }

    return traits;
}

- (NSString *)accessibilityValue {

    NSString *disksString = @"";

    for (NSNumber *diskSize in _diskSizes) {
        disksString = ORKAccessibilityStringForVariables(disksString, diskSize.stringValue, @", ");
    }

    NSString *value = (_diskSizes.count > 0 ? [NSString stringWithFormat:ORKLocalizedString(@"AX_TOWER_OF_HANOI_TOWER_CONTAINS", nil), disksString] : ORKLocalizedString(@"AX_TOWER_OF_HANOI_TOWER_EMPTY", nil));

    return value;
}

@end


text:
myvimconf4c
===========

this is my vimrc config for c languge


text:
layout: post
date:	2006-06-15 01:43:00
title:  Somewhat dispirited
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
There is SO much that I don't know...SO much to learn about SO many things...there is a sudden feeling of "how much time do I have left?" and the answer is, "I don't know, but definitely, more than half --or even two-thirds-- of my  life is over"...and I haven't learnt very much.

Well...I suppose I should be grateful that I am healthy, happy, and comfortable enough to sit and worry about such things!


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xliff PUBLIC "-//XLIFF//DTD XLIFF//EN" "http://www.oasis-open.org/committees/xliff/documents/xliff.dtd">
<xliff version="1.0">
  <file source-language="EN" target-language="de" datatype="plaintext" original="messages" date="2012-07-22T12:45:36Z" product-name="messages">
    <header/>
    <body>
      <trans-unit id="2">
        <source>Attachments</source>
        <target>Anlagen</target>
      </trans-unit>
      <trans-unit id="3">
        <source>ZIMs</source>
        <target>ZIMs</target>
      </trans-unit>
      <trans-unit id="4">
        <source>User</source>
        <target>Benutzer_in</target>
      </trans-unit>
      <trans-unit id="5">
        <source>Logout</source>
        <target>Abmelden</target>
      </trans-unit>
      <trans-unit id="6">
        <source>about openZIM</source>
        <target>über openZIM</target>
      </trans-unit>
      <trans-unit id="7">
        <source> </source>
        <target/>
      </trans-unit>
      <trans-unit id="8">
        <source>ANLAGE INFO</source>
        <target>ANLAGE INFO</target>
      </trans-unit>
      <trans-unit id="9">
        <source>ANLAGE INHALT</source>
        <target>ANLAGE INHALT</target>
      </trans-unit>
      <trans-unit id="10">
        <source>ANLAGE BILDER</source>
        <target>ANLAGE BILDER</target>
      </trans-unit>
      <trans-unit id="11">
        <source>ANLAGE ZIM INFO</source>
        <target>ANLAGE ZIM INFO</target>
      </trans-unit>
      <trans-unit id="13">
        <source>ANLAGE ANHÄNGE</source>
        <target>ANLAGE ANHÄNGE</target>
      </trans-unit>
      <trans-unit id="14">
        <source>ZIM DETAILS</source>
        <target>ZIM DETAILS</target>
      </trans-unit>
      <trans-unit id="15">
        <source>Name</source>
        <target/>
      </trans-unit>
      <trans-unit id="16">
        <source>Aktionen</source>
        <target/>
      </trans-unit>
      <trans-unit id="17">
        <source>Edit</source>
        <target>Bearbeiten</target>
      </trans-unit>
      <trans-unit id="18">
        <source>Export</source>
        <target/>
      </trans-unit>
      <trans-unit id="19">
        <source>Zim Liste</source>
        <target/>
      </trans-unit>
      <trans-unit id="20">
        <source>User List</source>
        <target>Benutzer_innen Liste</target>
      </trans-unit>
      <trans-unit id="21">
        <source>Back to List</source>
        <target>Zurück zur Liste</target>
      </trans-unit>
      <trans-unit id="22">
        <source>Delete</source>
        <target>Löschen</target>
      </trans-unit>
      <trans-unit id="23">
        <source>Are you sure?</source>
        <target>Sind Sie sicher?</target>
      </trans-unit>
      <trans-unit id="24">
        <source>Nr.</source>
        <target/>
      </trans-unit>
      <trans-unit id="25">
        <source>Ziel</source>
        <target/>
      </trans-unit>
      <trans-unit id="26">
        <source>Edit Attachment</source>
        <target>Anlage Bearbeiten</target>
      </trans-unit>
      <trans-unit id="27">
        <source>Preview</source>
        <target>Vorschau</target>
      </trans-unit>
      <trans-unit id="28">
        <source>Save</source>
        <target>Speichern</target>
      </trans-unit>
      <trans-unit id="29">
        <source>Edit User</source>
        <target>Benutzer_in bearbeiten</target>
      </trans-unit>
      <trans-unit id="30">
        <source>Tools</source>
        <target>Werkzeuge</target>
      </trans-unit>
      <trans-unit id="31">
        <source>Keinem ZIM zugeordnet.</source>
        <target/>
      </trans-unit>
      <trans-unit id="32">
        <source>Anlagen</source>
        <target/>
      </trans-unit>
      <trans-unit id="33">
        <source>Anlage Suchen/Filtern:</source>
        <target/>
      </trans-unit>
      <trans-unit id="34">
        <source>Backup Erstellen</source>
        <target/>
      </trans-unit>
      <trans-unit id="35">
        <source>Datenbank</source>
        <target/>
      </trans-unit>
      <trans-unit id="36">
        <source>Bilder, Anhänge</source>
        <target/>
      </trans-unit>
      <trans-unit id="37">
        <source>backup now</source>
        <target>Backup</target>
      </trans-unit>
      <trans-unit id="38">
        <source>Edit Zim</source>
        <target>ZIM Bearbeiten</target>
      </trans-unit>
      <trans-unit id="39">
        <source>No attachments found</source>
        <target>Keine Anlagen gefunden</target>
      </trans-unit>
      <trans-unit id="40">
        <source>Remember me</source>
        <target>Angemeldet bleiben</target>
      </trans-unit>
      <trans-unit id="41">
        <source>Username</source>
        <target>Benutzer_in</target>
      </trans-unit>
      <trans-unit id="42">
        <source>Password</source>
        <target>Passwort</target>
      </trans-unit>
      <trans-unit id="43">
        <source>Export Preview</source>
        <target>Export Vorschau</target>
      </trans-unit>
      <trans-unit id="44">
        <source>show chat</source>
         <target>Chat anzeigen</target>
      </trans-unit>
      <trans-unit id="45">
        <source>Your message:</source>
         <target>Nachricht:</target>
      </trans-unit>
      <trans-unit id="46">
        <source>hide chat</source>
        <target>Chat verbergen</target>
      </trans-unit>
    </body>
  </file>
</xliff>


text:
import React, { Component } from 'react';
import SearchBar from './SearchBar';
import Filters from './Filters';

export default class Search extends Component {
	render() {
		return (
			<div>
				<SearchBar />
				<Filters />
			</div>
		);
	}
}


text:
namespace llvm {
  class ARMSubtarget;
  class ARMBaseRegisterInfo;

class ARMBaseInstrInfo : public ARMGenInstrInfo {
  const ARMSubtarget &Subtarget;

protected:
  // Can be only subclassed.
  explicit ARMBaseInstrInfo(const ARMSubtarget &STI);

  void expandLoadStackGuardBase(MachineBasicBlock::iterator MI,
                                unsigned LoadImmOpc, unsigned LoadOpc) const;

  /// Build the equivalent inputs of a REG_SEQUENCE for the given \p MI
  /// and \p DefIdx.
  /// \p [out] InputRegs of the equivalent REG_SEQUENCE. Each element of
  /// the list is modeled as <Reg:SubReg, SubIdx>.
  /// E.g., REG_SEQUENCE vreg1:sub1, sub0, vreg2, sub1 would produce
  /// two elements:
  /// - vreg1:sub1, sub0
  /// - vreg2<:0>, sub1
  ///
  /// \returns true if it is possible to build such an input sequence
  /// with the pair \p MI, \p DefIdx. False otherwise.
  ///
  /// \pre MI.isRegSequenceLike().
  bool getRegSequenceLikeInputs(
      const MachineInstr &MI, unsigned DefIdx,
      SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const override;

  /// Build the equivalent inputs of a EXTRACT_SUBREG for the given \p MI
  /// and \p DefIdx.
  /// \p [out] InputReg of the equivalent EXTRACT_SUBREG.
  /// E.g., EXTRACT_SUBREG vreg1:sub1, sub0, sub1 would produce:
  /// - vreg1:sub1, sub0
  ///
  /// \returns true if it is possible to build such an input sequence
  /// with the pair \p MI, \p DefIdx. False otherwise.
  ///
  /// \pre MI.isExtractSubregLike().
  bool getExtractSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx,
                                  RegSubRegPairAndIdx &InputReg) const override;

  /// Build the equivalent inputs of a INSERT_SUBREG for the given \p MI
  /// and \p DefIdx.
  /// \p [out] BaseReg and \p [out] InsertedReg contain
  /// the equivalent inputs of INSERT_SUBREG.
  /// E.g., INSERT_SUBREG vreg0:sub0, vreg1:sub1, sub3 would produce:
  /// - BaseReg: vreg0:sub0
  /// - InsertedReg: vreg1:sub1, sub3
  ///
  /// \returns true if it is possible to build such an input sequence
  /// with the pair \p MI, \p DefIdx. False otherwise.
  ///
  /// \pre MI.isInsertSubregLike().
  bool
  getInsertSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx,
                            RegSubRegPair &BaseReg,
                            RegSubRegPairAndIdx &InsertedReg) const override;

  /// Commutes the operands in the given instruction.
  /// The commutable operands are specified by their indices OpIdx1 and OpIdx2.
  ///
  /// Do not call this method for a non-commutable instruction or for
  /// non-commutable pair of operand indices OpIdx1 and OpIdx2.
  /// Even though the instruction is commutable, the method may still
  /// fail to commute the operands, null pointer is returned in such cases.
  MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
                                       unsigned OpIdx1,
                                       unsigned OpIdx2) const override;

public:
  // Return whether the target has an explicit NOP encoding.
  bool hasNOP() const;

  virtual void getNoopForElfTarget(MCInst &NopInst) const {
    getNoopForMachoTarget(NopInst);
  }

  // Return the non-pre/post incrementing version of 'Opc'. Return 0
  // if there is not such an opcode.
  virtual unsigned getUnindexedOpcode(unsigned Opc) const =0;

  MachineInstr *convertToThreeAddress(MachineFunction::iterator &MFI,
                                      MachineInstr &MI,
                                      LiveVariables *LV) const override;

  virtual const ARMBaseRegisterInfo &getRegisterInfo() const = 0;
  const ARMSubtarget &getSubtarget() const { return Subtarget; }

  ScheduleHazardRecognizer *
  CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
                               const ScheduleDAG *DAG) const override;

  ScheduleHazardRecognizer *
  CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
                                     const ScheduleDAG *DAG) const override;

  // Branch analysis.
  bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
                     MachineBasicBlock *&FBB,
                     SmallVectorImpl<MachineOperand> &Cond,
                     bool AllowModify = false) const override;
  unsigned removeBranch(MachineBasicBlock &MBB,
                        int *BytesRemoved = nullptr) const override;
  unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
                        MachineBasicBlock *FBB, ArrayRef<MachineOperand> Cond,
                        const DebugLoc &DL,
                        int *BytesAdded = nullptr) const override;

  bool
  reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const override;

  // Predication support.
  bool isPredicated(const MachineInstr &MI) const override;

  ARMCC::CondCodes getPredicate(const MachineInstr &MI) const {
    int PIdx = MI.findFirstPredOperandIdx();
    return PIdx != -1 ? (ARMCC::CondCodes)MI.getOperand(PIdx).getImm()
                      : ARMCC::AL;
  }

  bool PredicateInstruction(MachineInstr &MI,
                            ArrayRef<MachineOperand> Pred) const override;

  bool SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
                         ArrayRef<MachineOperand> Pred2) const override;

  bool DefinesPredicate(MachineInstr &MI,
                        std::vector<MachineOperand> &Pred) const override;

  bool isPredicable(MachineInstr &MI) const override;

  /// GetInstSize - Returns the size of the specified MachineInstr.
  ///
  unsigned getInstSizeInBytes(const MachineInstr &MI) const override;

  unsigned isLoadFromStackSlot(const MachineInstr &MI,
                               int &FrameIndex) const override;
  unsigned isStoreToStackSlot(const MachineInstr &MI,
                              int &FrameIndex) const override;
  unsigned isLoadFromStackSlotPostFE(const MachineInstr &MI,
                                     int &FrameIndex) const override;
  unsigned isStoreToStackSlotPostFE(const MachineInstr &MI,
                                    int &FrameIndex) const override;

  void copyToCPSR(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
                  unsigned SrcReg, bool KillSrc,
                  const ARMSubtarget &Subtarget) const;
  void copyFromCPSR(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
                    unsigned DestReg, bool KillSrc,
                    const ARMSubtarget &Subtarget) const;

  void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
                   const DebugLoc &DL, unsigned DestReg, unsigned SrcReg,
                   bool KillSrc) const override;

  void storeRegToStackSlot(MachineBasicBlock &MBB,
                           MachineBasicBlock::iterator MBBI,
                           unsigned SrcReg, bool isKill, int FrameIndex,
                           const TargetRegisterClass *RC,
                           const TargetRegisterInfo *TRI) const override;

  void loadRegFromStackSlot(MachineBasicBlock &MBB,
                            MachineBasicBlock::iterator MBBI,
                            unsigned DestReg, int FrameIndex,
                            const TargetRegisterClass *RC,
                            const TargetRegisterInfo *TRI) const override;

  bool expandPostRAPseudo(MachineInstr &MI) const override;

  void reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
                     unsigned DestReg, unsigned SubIdx,
                     const MachineInstr &Orig,
                     const TargetRegisterInfo &TRI) const override;

  MachineInstr *duplicate(MachineInstr &Orig,
                          MachineFunction &MF) const override;

  const MachineInstrBuilder &AddDReg(MachineInstrBuilder &MIB, unsigned Reg,
                                     unsigned SubIdx, unsigned State,
                                     const TargetRegisterInfo *TRI) const;

  bool produceSameValue(const MachineInstr &MI0, const MachineInstr &MI1,
                        const MachineRegisterInfo *MRI) const override;

  /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
  /// determine if two loads are loading from the same base address. It should
  /// only return true if the base pointers are the same and the only
  /// differences between the two addresses is the offset. It also returns the
  /// offsets by reference.
  bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2, int64_t &Offset1,
                               int64_t &Offset2) const override;

  /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
  /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads
  /// should be scheduled togther. On some targets if two loads are loading from
  /// addresses in the same cache line, it's better if they are scheduled
  /// together. This function takes two integers that represent the load offsets
  /// from the common base address. It returns true if it decides it's desirable
  /// to schedule the two loads together. "NumLoads" is the number of loads that
  /// have already been scheduled after Load1.
  bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
                               int64_t Offset1, int64_t Offset2,
                               unsigned NumLoads) const override;

  bool isSchedulingBoundary(const MachineInstr &MI,
                            const MachineBasicBlock *MBB,
                            const MachineFunction &MF) const override;

  bool isProfitableToIfCvt(MachineBasicBlock &MBB,
                           unsigned NumCycles, unsigned ExtraPredCycles,
                           BranchProbability Probability) const override;

  bool isProfitableToIfCvt(MachineBasicBlock &TMBB, unsigned NumT,
                           unsigned ExtraT, MachineBasicBlock &FMBB,
                           unsigned NumF, unsigned ExtraF,
                           BranchProbability Probability) const override;

  bool isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
                                 BranchProbability Probability) const override {
    return NumCycles == 1;
  }

  bool isProfitableToUnpredicate(MachineBasicBlock &TMBB,
                                 MachineBasicBlock &FMBB) const override;

  /// analyzeCompare - For a comparison instruction, return the source registers
  /// in SrcReg and SrcReg2 if having two register operands, and the value it
  /// compares against in CmpValue. Return true if the comparison instruction
  /// can be analyzed.
  bool analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
                      unsigned &SrcReg2, int &CmpMask,
                      int &CmpValue) const override;

  /// optimizeCompareInstr - Convert the instruction to set the zero flag so
  /// that we can remove a "comparison with zero"; Remove a redundant CMP
  /// instruction if the flags can be updated in the same way by an earlier
  /// instruction such as SUB.
  bool optimizeCompareInstr(MachineInstr &CmpInstr, unsigned SrcReg,
                            unsigned SrcReg2, int CmpMask, int CmpValue,
                            const MachineRegisterInfo *MRI) const override;

  bool analyzeSelect(const MachineInstr &MI,
                     SmallVectorImpl<MachineOperand> &Cond, unsigned &TrueOp,
                     unsigned &FalseOp, bool &Optimizable) const override;

  MachineInstr *optimizeSelect(MachineInstr &MI,
                               SmallPtrSetImpl<MachineInstr *> &SeenMIs,
                               bool) const override;

  /// FoldImmediate - 'Reg' is known to be defined by a move immediate
  /// instruction, try to fold the immediate into the use instruction.
  bool FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, unsigned Reg,
                     MachineRegisterInfo *MRI) const override;

  unsigned getNumMicroOps(const InstrItineraryData *ItinData,
                          const MachineInstr &MI) const override;

  int getOperandLatency(const InstrItineraryData *ItinData,
                        const MachineInstr &DefMI, unsigned DefIdx,
                        const MachineInstr &UseMI,
                        unsigned UseIdx) const override;
  int getOperandLatency(const InstrItineraryData *ItinData,
                        SDNode *DefNode, unsigned DefIdx,
                        SDNode *UseNode, unsigned UseIdx) const override;

  /// VFP/NEON execution domains.
  std::pair<uint16_t, uint16_t>
  getExecutionDomain(const MachineInstr &MI) const override;
  void setExecutionDomain(MachineInstr &MI, unsigned Domain) const override;

  unsigned
  getPartialRegUpdateClearance(const MachineInstr &, unsigned,
                               const TargetRegisterInfo *) const override;
  void breakPartialRegDependency(MachineInstr &, unsigned,
                                 const TargetRegisterInfo *TRI) const override;

  /// Get the number of addresses by LDM or VLDM or zero for unknown.
  unsigned getNumLDMAddresses(const MachineInstr &MI) const;

private:
  unsigned getInstBundleLength(const MachineInstr &MI) const;

  int getVLDMDefCycle(const InstrItineraryData *ItinData,
                      const MCInstrDesc &DefMCID,
                      unsigned DefClass,
                      unsigned DefIdx, unsigned DefAlign) const;
  int getLDMDefCycle(const InstrItineraryData *ItinData,
                     const MCInstrDesc &DefMCID,
                     unsigned DefClass,
                     unsigned DefIdx, unsigned DefAlign) const;
  int getVSTMUseCycle(const InstrItineraryData *ItinData,
                      const MCInstrDesc &UseMCID,
                      unsigned UseClass,
                      unsigned UseIdx, unsigned UseAlign) const;
  int getSTMUseCycle(const InstrItineraryData *ItinData,
                     const MCInstrDesc &UseMCID,
                     unsigned UseClass,
                     unsigned UseIdx, unsigned UseAlign) const;
  int getOperandLatency(const InstrItineraryData *ItinData,
                        const MCInstrDesc &DefMCID,
                        unsigned DefIdx, unsigned DefAlign,
                        const MCInstrDesc &UseMCID,
                        unsigned UseIdx, unsigned UseAlign) const;

  int getOperandLatencyImpl(const InstrItineraryData *ItinData,
                            const MachineInstr &DefMI, unsigned DefIdx,
                            const MCInstrDesc &DefMCID, unsigned DefAdj,
                            const MachineOperand &DefMO, unsigned Reg,
                            const MachineInstr &UseMI, unsigned UseIdx,
                            const MCInstrDesc &UseMCID, unsigned UseAdj) const;

  unsigned getPredicationCost(const MachineInstr &MI) const override;

  unsigned getInstrLatency(const InstrItineraryData *ItinData,
                           const MachineInstr &MI,
                           unsigned *PredCost = nullptr) const override;

  int getInstrLatency(const InstrItineraryData *ItinData,
                      SDNode *Node) const override;

  bool hasHighOperandLatency(const TargetSchedModel &SchedModel,
                             const MachineRegisterInfo *MRI,
                             const MachineInstr &DefMI, unsigned DefIdx,
                             const MachineInstr &UseMI,
                             unsigned UseIdx) const override;
  bool hasLowDefLatency(const TargetSchedModel &SchedModel,
                        const MachineInstr &DefMI,
                        unsigned DefIdx) const override;

  /// verifyInstruction - Perform target specific instruction verification.
  bool verifyInstruction(const MachineInstr &MI,
                         StringRef &ErrInfo) const override;

  virtual void expandLoadStackGuard(MachineBasicBlock::iterator MI) const = 0;

  void expandMEMCPY(MachineBasicBlock::iterator) const;

private:
  /// Modeling special VFP / NEON fp MLA / MLS hazards.

  /// MLxEntryMap - Map fp MLA / MLS to the corresponding entry in the internal
  /// MLx table.
  DenseMap<unsigned, unsigned> MLxEntryMap;

  /// MLxHazardOpcodes - Set of add / sub and multiply opcodes that would cause
  /// stalls when scheduled together with fp MLA / MLS opcodes.
  SmallSet<unsigned, 16> MLxHazardOpcodes;

public:
  /// isFpMLxInstruction - Return true if the specified opcode is a fp MLA / MLS
  /// instruction.
  bool isFpMLxInstruction(unsigned Opcode) const {
    return MLxEntryMap.count(Opcode);
  }

  /// isFpMLxInstruction - This version also returns the multiply opcode and the
  /// addition / subtraction opcode to expand to. Return true for 'HasLane' for
  /// the MLX instructions with an extra lane operand.
  bool isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
                          unsigned &AddSubOpc, bool &NegAcc,
                          bool &HasLane) const;

  /// canCauseFpMLxStall - Return true if an instruction of the specified opcode
  /// will cause stalls when scheduled after (within 4-cycle window) a fp
  /// MLA / MLS instruction.
  bool canCauseFpMLxStall(unsigned Opcode) const {
    return MLxHazardOpcodes.count(Opcode);
  }

  /// Returns true if the instruction has a shift by immediate that can be
  /// executed in one cycle less.
  bool isSwiftFastImmShift(const MachineInstr *MI) const;
};

static inline
const MachineInstrBuilder &AddDefaultPred(const MachineInstrBuilder &MIB) {
  return MIB.addImm((int64_t)ARMCC::AL).addReg(0);
}

static inline
const MachineInstrBuilder &AddDefaultCC(const MachineInstrBuilder &MIB) {
  return MIB.addReg(0);
}

static inline
const MachineInstrBuilder &AddDefaultT1CC(const MachineInstrBuilder &MIB,
                                          bool isDead = false) {
  return MIB.addReg(ARM::CPSR, getDefRegState(true) | getDeadRegState(isDead));
}

static inline
const MachineInstrBuilder &AddNoT1CC(const MachineInstrBuilder &MIB) {
  return MIB.addReg(0);
}

static inline
bool isUncondBranchOpcode(int Opc) {
  return Opc == ARM::B || Opc == ARM::tB || Opc == ARM::t2B;
}

static inline
bool isCondBranchOpcode(int Opc) {
  return Opc == ARM::Bcc || Opc == ARM::tBcc || Opc == ARM::t2Bcc;
}

static inline
bool isJumpTableBranchOpcode(int Opc) {
  return Opc == ARM::BR_JTr || Opc == ARM::BR_JTm || Opc == ARM::BR_JTadd ||
    Opc == ARM::tBR_JTr || Opc == ARM::t2BR_JT;
}

static inline
bool isIndirectBranchOpcode(int Opc) {
  return Opc == ARM::BX || Opc == ARM::MOVPCRX || Opc == ARM::tBRIND;
}

static inline bool isPopOpcode(int Opc) {
  return Opc == ARM::tPOP_RET || Opc == ARM::LDMIA_RET ||
         Opc == ARM::t2LDMIA_RET || Opc == ARM::tPOP || Opc == ARM::LDMIA_UPD ||
         Opc == ARM::t2LDMIA_UPD || Opc == ARM::VLDMDIA_UPD;
}

static inline bool isPushOpcode(int Opc) {
  return Opc == ARM::tPUSH || Opc == ARM::t2STMDB_UPD ||
         Opc == ARM::STMDB_UPD || Opc == ARM::VSTMDDB_UPD;
}

/// getInstrPredicate - If instruction is predicated, returns its predicate
/// condition, otherwise returns AL. It also returns the condition code
/// register by reference.
ARMCC::CondCodes getInstrPredicate(const MachineInstr &MI, unsigned &PredReg);

unsigned getMatchingCondBranchOpcode(unsigned Opc);

/// Determine if MI can be folded into an ARM MOVCC instruction, and return the
/// opcode of the SSA instruction representing the conditional MI.
unsigned canFoldARMInstrIntoMOVCC(unsigned Reg,
                                  MachineInstr *&MI,
                                  const MachineRegisterInfo &MRI);

/// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether
/// the instruction is encoded with an 'S' bit is determined by the optional
/// CPSR def operand.
unsigned convertAddSubFlagsOpcode(unsigned OldOpc);

/// emitARMRegPlusImmediate / emitT2RegPlusImmediate - Emits a series of
/// instructions to materializea destreg = basereg + immediate in ARM / Thumb2
/// code.
void emitARMRegPlusImmediate(MachineBasicBlock &MBB,
                             MachineBasicBlock::iterator &MBBI,
                             const DebugLoc &dl, unsigned DestReg,
                             unsigned BaseReg, int NumBytes,
                             ARMCC::CondCodes Pred, unsigned PredReg,
                             const ARMBaseInstrInfo &TII, unsigned MIFlags = 0);

void emitT2RegPlusImmediate(MachineBasicBlock &MBB,
                            MachineBasicBlock::iterator &MBBI,
                            const DebugLoc &dl, unsigned DestReg,
                            unsigned BaseReg, int NumBytes,
                            ARMCC::CondCodes Pred, unsigned PredReg,
                            const ARMBaseInstrInfo &TII, unsigned MIFlags = 0);
void emitThumbRegPlusImmediate(MachineBasicBlock &MBB,
                               MachineBasicBlock::iterator &MBBI,
                               const DebugLoc &dl, unsigned DestReg,
                               unsigned BaseReg, int NumBytes,
                               const TargetInstrInfo &TII,
                               const ARMBaseRegisterInfo &MRI,
                               unsigned MIFlags = 0);

/// Tries to add registers to the reglist of a given base-updating
/// push/pop instruction to adjust the stack by an additional
/// NumBytes. This can save a few bytes per function in code-size, but
/// obviously generates more memory traffic. As such, it only takes
/// effect in functions being optimised for size.
bool tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget,
                                MachineFunction &MF, MachineInstr *MI,
                                unsigned NumBytes);

/// rewriteARMFrameIndex / rewriteT2FrameIndex -
/// Rewrite MI to access 'Offset' bytes from the FP. Return false if the
/// offset could not be handled directly in MI, and return the left-over
/// portion by reference.
bool rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
                          unsigned FrameReg, int &Offset,
                          const ARMBaseInstrInfo &TII);

bool rewriteT2FrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
                         unsigned FrameReg, int &Offset,
                         const ARMBaseInstrInfo &TII);

} // End llvm namespace

#endif


text:
<?php
/**
 * WordPress_Tests_VIP_SessionVariableUsageUnitTest
 *
 * PHP version 5
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Shady Sharaf <shady@x-team.com>
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */

class WordPress_Tests_VIP_SessionVariableUsageUnitTest extends AbstractSniffUnitTest
{

	/**
	 * Returns the lines where errors should occur.
	 *
	 * The key of the array should represent the line number and the value
	 * should represent the number of errors that should occur on that line.
	 *
	 * @return array(int => int)
	 */
	public function getErrorList()
	{
		return array(
			3 => 1,
			4 => 1,
			);

	}//end getErrorList()

	/**
	 * Returns the lines where warnings should occur.
	 *
	 * The key of the array should represent the line number and the value
	 * should represent the number of warnings that should occur on that line.
	 *
	 * @return array(int => int)
	 */
	public function getWarningList()
	{
		return array();

	}//end getWarningList()

}//end class

?>


text:
#include "rib_converter_transform.h"
#include "ros/ros.h"
#include "igtlImageMessage.h"

RIBConverterVideo::RIBConverterVideo()
  : RIBConverter<ros_igtl_bridge::igtlvideo>()
{
}

RIBConverterVideo::RIBConverterVideo(ros::NodeHandle *nh)
  : RIBConverter<ros_igtl_bridge::igtlvideo>(nh)
{
}

RIBConverterVideo::RIBConverterVideo(const char* topicPublish, const char* topicSubscribe, ros::NodeHandle *nh)
  : RIBConverter<ros_igtl_bridge::igtlvideo>(topicPublish, topicSubscribe, nh)
{
}

int RIBConverterVideo::onIGTLMessage(igtl::MessageHeader * header)
{
}

void RIBConverterVideo::onROSMessage(const ros_igtl_bridge::igtlvideo::ConstPtr & msg)
{
  cv_bridge::CvImagePtr cv_ptr;

  igtl::Socket::Pointer socket = this->manager->GetSocket();
  if (socket.IsNull())
    {
    return;
    }

  try
    {
    cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
    }
  catch (cv_bridge::Exception& e)
    {
    ROS_ERROR("cv_bridge exception: %s", e.what());
    return;
    }

  cv::Mat img;
  cvtColor(cv_ptr->image,img, CV_RGB2GRAY);

  cv_bridge::CvImage img_bridge;
  sensor_msgs::Image img_msg;

  std_msgs::Header header;
  header.stamp = ros::Time::now();
  img_bridge = cv_bridge::CvImage(header, sensor_msgs::image_encodings::MONO8, img);
  img_bridge.toImageMsg(img_msg);

  sensor_msgs::Image::Ptr msg = boost::make_shared<sensor_msgs::Image>(img_msg);

  /* debug window
     static const char WINDOW[] = "Image window";
     cv::namedWindow(WINDOW);
     cv::imshow(WINDOW, img);
     cv::waitKey(3);
  */

  int   size[]     = {msg->width,msg->height,1};       // image dimension
  float spacing[]  = {1,1,1};     // spacing (mm/pixel)
  int   scalarType = igtl::ImageMessage::TYPE_UINT8;

  igtl::ImageMessage::Pointer imgMsg = igtl::ImageMessage::New();
  imgMsg->SetDimensions(size);
  imgMsg->SetSpacing(spacing);
  imgMsg->SetScalarType(scalarType);
  imgMsg->SetCoordinateSystem(2);
  imgMsg->SetDeviceName("ROS_IGTL_Bridge_Video");
  imgMsg->SetOrigin(0,0,0);
  imgMsg->AllocateScalars();
  //------------------------------------------------------------
  std::cout<< msg->data.size()<<std::endl;
  std::cout<< msg->step<<std::endl;
  std::cout<< msg->height<<std::endl;
  std::cout<< msg->width<<std::endl;

  image_pub.publish(msg);

  memcpy(imgMsg->GetScalarPointer(),(char*)(&msg->data[0]),msg->data.size());

  igtl::Matrix4x4 matrixa;
  igtl::IdentityMatrix(matrixa);
  matrixa[0][0] = -1;
  matrixa[1][1] = -1;

  imgMsg->SetMatrix(matrixa);

  //------------------------------------------------------------
  // Pack and send
  imgMsg->Pack();

  this->socket->Send(imgMsg->GetPackPointer(), imgMsg->GetPackSize());
}


text:
package org.openqa.selenium.lift;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

import org.hamcrest.Description;
import org.jmock.Expectations;
import org.jmock.integration.junit3.MockObjectTestCase;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.lift.find.Finder;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.openqa.selenium.lift.Finders.first;
import static org.openqa.selenium.lift.match.NumericalMatchers.atLeast;

/**
 * Unit test for {@link WebDriverTestContext}.
 *
 * @author rchatley (Robert Chatley)
 *
 */
public class TestContextTest extends MockObjectTestCase {

	WebDriver webdriver = mock(WebDriver.class);
	TestContext context = new WebDriverTestContext(webdriver);
	private WebElement element = mock(WebElement.class);

	public void testIsCreatedWithAWebDriverImplementation() throws Exception {
		new WebDriverTestContext(webdriver);
	}

	public void testCanNavigateToAGivenUrl() throws Exception {

		final String url = "http://www.example.com";

		checking(new Expectations() {{
			one(webdriver).get(url);
		}});

		context.goTo(url);
	}

	@SuppressWarnings("unchecked")
	public void testCanAssertPresenceOfWebElements() throws Exception {

		final Finder<WebElement, WebDriver> finder = mock(Finder.class);

		checking(new Expectations() {{
			one(finder).findFrom(webdriver); will(returnValue(oneElement()));
		}});

		context.assertPresenceOf(finder);
	}

	@SuppressWarnings("unchecked")
	public void testCanCheckQuantitiesOfWebElementsAndThrowsExceptionOnMismatch() throws Exception {

		final Finder<WebElement, WebDriver> finder = mock(Finder.class);

		checking(new Expectations() {{
			allowing(finder).findFrom(webdriver); will(returnValue(oneElement()));
			exactly(2).of(finder).describeTo(with(any(Description.class))); // in producing the error msg
		}});

		try {
			context.assertPresenceOf(atLeast(2), finder);
			fail("should have failed as only one element found");
		} catch (AssertionError error) {
			// expected
			assertThat(error.getMessage(), containsString("a value greater than <1>"));
		}
	}

	@SuppressWarnings("unchecked")
	public void testCanDirectTextInputToSpecificElements() throws Exception {

		final Finder<WebElement, WebDriver> finder = mock(Finder.class);
		final String inputText = "test";

		checking(new Expectations() {{
			one(finder).findFrom(webdriver); will(returnValue(oneElement()));
			one(element).sendKeys(inputText);
		}});

		context.type(inputText, finder);
	}

	@SuppressWarnings("unchecked")
	public void testCanTriggerClicksOnSpecificElements() throws Exception {

		final Finder<WebElement, WebDriver> finder = mock(Finder.class);

		checking(new Expectations() {{
			one(finder).findFrom(webdriver); will(returnValue(oneElement()));
			one(element).click();
		}});

		context.clickOn(finder);
	}

	@SuppressWarnings("unchecked")
	public void testCanTriggerClicksOnFirstElement() throws Exception {

		final Finder<WebElement, WebDriver> finder = mock(Finder.class);

		checking(new Expectations() {{
			one(finder).findFrom(webdriver); will(returnValue(twoElements()));
			one(element).click();
		}});

		context.clickOn(first(finder));
	}

	@SuppressWarnings("unchecked")
	public void testThrowsAnExceptionIfTheFinderReturnsAmbiguousResults() throws Exception {

		final Finder<WebElement, WebDriver> finder = mock(Finder.class);

		checking(new Expectations() {{
			one(finder).findFrom(webdriver); will(returnValue(twoElements()));
		}});

		try {
			context.clickOn(finder);
			fail("should have failed as more than one element found");
		} catch (AssertionError error) {
			// expected
			assertThat(error.getMessage(), containsString("did not know what to click on"));
		}
	}

	private Collection<WebElement> oneElement() {
		return Collections.singleton(element);
	}

	private Collection<WebElement> twoElements() {
		return Arrays.asList(new WebElement[] {element, element});
	}
}