text:
//
//  NSDate+PisenKit.m
//  PisenKit
//
//  Created by 杨胜超 on 16/6/30.
//  Copyright © 2016年 Pisen. All rights reserved.
//

#import "NSDate+PisenKit.h"

#define PSK_STD_MINUTE    60
#define PSK_STD_HOUR      (60 * PSK_STD_MINUTE)
#define PSK_STD_DAY       (24 * PSK_STD_HOUR)
#define PSK_STD_WEEK      (7  * PSK_STD_DAY)

#if IOS8_OR_LATER
    #define PSK_CalendarUnitYear        NSCalendarUnitYear
#else
    #define PSK_CalendarUnitYear        NSYearCalendarUnit
#endif
#if IOS8_OR_LATER
    #define PSK_CalendarUnitMonth       NSCalendarUnitMonth
#else
    #define PSK_CalendarUnitMonth       NSMonthCalendarUnit
#endif
#if IOS8_OR_LATER
    #define PSK_CalendarUnitDay         NSCalendarUnitDay
#else
    #define PSK_CalendarUnitDay         NSDayCalendarUnit
#endif
#if IOS8_OR_LATER
    #define PSK_CalendarUnitHour        NSCalendarUnitHour
#else
    #define PSK_CalendarUnitHour        NSHourCalendarUnit
#endif
#if IOS8_OR_LATER
    #define PSK_CalendarUnitMinute      NSCalendarUnitMinute
#else
    #define PSK_CalendarUnitMinute      NSMinuteCalendarUnit
#endif
#if IOS8_OR_LATER
    #define PSK_CalendarUnitSecond      NSCalendarUnitSecond
#else
    #define PSK_CalendarUnitSecond      NSSecondCalendarUnit
#endif
#if IOS8_OR_LATER
    #define PSK_CalendarUnitWeekday     NSCalendarUnitWeekday
#else
    #define PSK_CalendarUnitWeekday     NSWeekdayCalendarUnit
#endif
#if IOS8_OR_LATER
    #define PSK_CalendarUnitWeekOfYear  NSCalendarUnitWeekOfYear
#else
    #define PSK_CalendarUnitWeekOfYear  NSWeekOfYearCalendarUnit
#endif

#define CALENDAR_UNITS      (PSK_CalendarUnitYear | PSK_CalendarUnitMonth | PSK_CalendarUnitDay | PSK_CalendarUnitHour | PSK_CalendarUnitMinute | PSK_CalendarUnitSecond | PSK_CalendarUnitWeekday | PSK_CalendarUnitWeekOfYear)
#define DATE_COMPONENTS     [[NSCalendar currentCalendar] components:CALENDAR_UNITS fromDate:self]

//==============================================================================
//
//  常用方法
//
//==============================================================================
@implementation NSDate (PisenKit)
- (NSInteger)psk_hour {
    return [DATE_COMPONENTS hour];
}
- (NSInteger)psk_minute {
    return [DATE_COMPONENTS minute];
}
- (NSInteger)psk_seconds {
    return [DATE_COMPONENTS second];
}
- (NSInteger)psk_day {
    return [DATE_COMPONENTS day];
}
- (NSInteger)psk_month {
    return [DATE_COMPONENTS month];
}
- (NSInteger)psk_weekday {
    return [DATE_COMPONENTS weekday];
}
- (NSInteger)psk_weekOfYear {
    return [DATE_COMPONENTS weekOfYear];
}
- (NSInteger)psk_nthWeekday {
    return [DATE_COMPONENTS weekdayOrdinal];
}
- (NSInteger)psk_year {
    return [DATE_COMPONENTS year];
}

#pragma mark Relative Dates
+ (NSDate *)psk_dateNow {
    return CURRENT_DATE;
}
+ (NSDate *)psk_dateTomorrow {
    return [NSDate psk_dateFromNowAfterDays:1];
}
+ (NSDate *)psk_dateYesterday {
    return [NSDate psk_dateFromNowBeforeDays:1];
}
+ (NSDate *)psk_dateAfterTomorrow {
    return [NSDate psk_dateFromNowAfterDays:2];
}
+ (NSDate *)psk_dateBeforeYesterday {
    return [NSDate psk_dateFromNowBeforeDays:2];
}
+ (NSDate *)psk_dateFromNowAfterDays:(NSInteger)days {
    return [self _psk_dateWithSecondReference:CURRENT_DATE second:PSK_STD_DAY * days];
}
+ (NSDate *)psk_dateFromNowBeforeDays:(NSInteger)days {
    return [self _psk_dateWithSecondReference:CURRENT_DATE second:-PSK_STD_DAY * days];
}
+ (NSDate *)psk_dateFromNowAfterHours:(NSInteger)hours {
    return [self _psk_dateWithSecondReference:CURRENT_DATE second:PSK_STD_HOUR * hours];
}
+ (NSDate *)psk_dateFromNowBeforeHours:(NSInteger)hours {
    return [self _psk_dateWithSecondReference:CURRENT_DATE second:-PSK_STD_HOUR * hours];
}
+ (NSDate *)psk_dateFromNowAfterMinutes:(NSInteger)minutes {
    return [self _psk_dateWithSecondReference:CURRENT_DATE second:PSK_STD_MINUTE * minutes];
}
+ (NSDate *)psk_dateFromNowBeforeMinutes:(NSInteger)minutes {
    return [self _psk_dateWithSecondReference:CURRENT_DATE second:-PSK_STD_MINUTE * minutes];
}

#pragma mark - Convert with format
+ (NSDate *)psk_dateFromTimeStamp:(NSString *)timeStamp {
    return [self psk_dateFromTimeInterval:[timeStamp longLongValue]];
}
+ (NSDate *)psk_dateFromTimeInterval:(NSTimeInterval)timeInterval {
    if (timeInterval > 1000000000.0f * 1000.0f) {//判断单位是秒还是毫秒
        timeInterval = timeInterval / 1000.0f;
    }
    return [NSDate dateWithTimeIntervalSince1970:timeInterval];
}
+ (NSDate *)psk_dateFromString:(NSString *)string withFormat:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    return [dateFormatter dateFromString:string];
}
+ (NSString *)psk_stringFromTimeStamp:(NSString *)timeStamp withFormat:(NSString *)format {
    return [[self psk_dateFromTimeStamp:timeStamp] psk_stringWithFormat:format];
}
+ (NSString *)psk_convertDateString:(NSString *)dataString fromFormat:(NSString *)fromFormat toFormat:(NSString *)toFormat {
    NSDate *date = [NSDate psk_dateFromString:dataString withFormat:fromFormat];
    return [date psk_stringWithFormat:toFormat];
}
- (NSString *)psk_stringWithFormat:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    return [dateFormatter stringFromDate:self];
}

#pragma mark Comparing Dates
- (BOOL)psk_isEqualToDateIgnoringTime:(NSDate *)date {
    NSDateComponents *components1 = [[NSCalendar currentCalendar] components:CALENDAR_UNITS fromDate:self];
    NSDateComponents *components2 = [[NSCalendar currentCalendar] components:CALENDAR_UNITS fromDate:date];
    return (([components1 year] == [components2 year]) &&
            ([components1 month] == [components2 month]) &&
            ([components1 day] == [components2 day]));
}
- (BOOL)psk_isToday {
    return [self psk_isEqualToDateIgnoringTime:CURRENT_DATE];
}
- (BOOL)psk_isTomorrow {
    return [self psk_isEqualToDateIgnoringTime:[NSDate psk_dateTomorrow]];
}
- (BOOL)psk_isYesterday {
    return [self psk_isEqualToDateIgnoringTime:[NSDate psk_dateYesterday]];
}
- (BOOL)psk_isAfterTomorrow {
    return [self psk_isEqualToDateIgnoringTime:[NSDate psk_dateAfterTomorrow]];
}
- (BOOL)psk_isBeforeYesterday {
    return [self psk_isEqualToDateIgnoringTime:[NSDate psk_dateBeforeYesterday]];
}
- (BOOL)psk_isSameWeekAsDate:(NSDate *)date {
    NSDateComponents *components1 = [[NSCalendar currentCalendar] components:CALENDAR_UNITS fromDate:self];
    NSDateComponents *components2 = [[NSCalendar currentCalendar] components:CALENDAR_UNITS fromDate:date];
    if ([components1 weekOfYear] != [components2 weekOfYear]) {
        return NO;
    }
    return (fabs([self timeIntervalSinceDate:date]) < PSK_STD_WEEK);
}
- (BOOL)psk_isThisWeek {
    return [self psk_isSameWeekAsDate:CURRENT_DATE];
}
- (BOOL)psk_isNextWeek {
    NSDate *newDate = [NSDate _psk_dateWithSecondReference:self second:PSK_STD_WEEK];
    return [self psk_isSameWeekAsDate:newDate];
}
- (BOOL)psk_isLastWeek {
    NSDate *newDate = [NSDate _psk_dateWithSecondReference:self second:-PSK_STD_WEEK];
    return [self psk_isSameWeekAsDate:newDate];
}
- (BOOL)psk_isSameYearAsDate:(NSDate *)date {
    NSDateComponents *components1 = [[NSCalendar currentCalendar] components:PSK_CalendarUnitYear fromDate:self];
    NSDateComponents *components2 = [[NSCalendar currentCalendar] components:PSK_CalendarUnitYear fromDate:date];
    return ([components1 year] == [components2 year]);
}
- (BOOL)psk_isThisYear {
    return [self psk_isSameYearAsDate:CURRENT_DATE];
}
- (BOOL)psk_isNextYear {
    NSDateComponents *components1 = [[NSCalendar currentCalendar] components:PSK_CalendarUnitYear fromDate:self];
    NSDateComponents *components2 = [[NSCalendar currentCalendar] components:PSK_CalendarUnitYear fromDate:CURRENT_DATE];

    return ([components1 year] == ([components2 year] + 1));
}
- (BOOL)psk_isLastYear {
    NSDateComponents *components1 = [[NSCalendar currentCalendar] components:PSK_CalendarUnitYear fromDate:self];
    NSDateComponents *components2 = [[NSCalendar currentCalendar] components:PSK_CalendarUnitYear fromDate:CURRENT_DATE];

    return ([components1 year] == ([components2 year] - 1));
}
- (BOOL)psk_isEarlierThanDate:(NSDate *)date {
    return ([self earlierDate:date] == self);
}
- (BOOL)psk_isLaterThanDate:(NSDate *)date {
    return ([self laterDate:date] == self);
}

#pragma mark Adjusting Dates
- (NSDate *)psk_dateAfterDays:(NSInteger)days {
    return [NSDate _psk_dateWithSecondReference:self second:PSK_STD_DAY * days];
}
- (NSDate *)psk_dateBeforeDays:(NSInteger)days {
    return [NSDate _psk_dateWithSecondReference:self second:-PSK_STD_DAY * days];
}
- (NSDate *)psk_dateAfterHours:(NSInteger)hours {
    return [NSDate _psk_dateWithSecondReference:self second:PSK_STD_HOUR * hours];
}
- (NSDate *)psk_dateBeforeHours:(NSInteger)hours {
    return [NSDate _psk_dateWithSecondReference:self second:-PSK_STD_HOUR * hours];
}
- (NSDate *)psk_dateAfterMinutes:(NSInteger)minutes {
    return [NSDate _psk_dateWithSecondReference:self second:PSK_STD_MINUTE * minutes];
}
- (NSDate *)psk_dateBeforeMinutes:(NSInteger)minutes {
    return [NSDate _psk_dateWithSecondReference:self second:-PSK_STD_MINUTE * minutes];
}
- (NSDate *)psk_dateAtStartOfDay {
    NSDateComponents *components = [[NSCalendar currentCalendar] components:CALENDAR_UNITS fromDate:self];
    [components setHour:0];
    [components setMinute:0];
    [components setSecond:0];
    return [[NSCalendar currentCalendar] dateFromComponents:components];
}

#pragma mark Retrieving Intervals
- (NSInteger)psk_minutesAfterDate:(NSDate *)date {
    NSTimeInterval ti = [self timeIntervalSinceDate:date];
    return (NSInteger)(ti / PSK_STD_MINUTE);
}
- (NSInteger)psk_minutesBeforeDate:(NSDate *)date {
    NSTimeInterval ti = [date timeIntervalSinceDate:self];
    return (NSInteger)(ti / PSK_STD_MINUTE);
}
- (NSInteger)psk_hoursAfterDate:(NSDate *)date {
    NSTimeInterval ti = [self timeIntervalSinceDate:date];
    return (NSInteger)(ti / PSK_STD_HOUR);
}
- (NSInteger)psk_hoursBeforeDate:(NSDate *)date {
    NSTimeInterval ti = [date timeIntervalSinceDate:self];
    return (NSInteger)(ti / PSK_STD_HOUR);
}
- (NSInteger)psk_daysAfterDate:(NSDate *)date {
    NSTimeInterval ti = [self timeIntervalSinceDate:date];
    return (NSInteger)(ti / PSK_STD_DAY);
}
- (NSInteger)psk_daysBeforeDate:(NSDate *)date {
    NSTimeInterval ti = [date timeIntervalSinceDate:self];
    return (NSInteger)(ti / PSK_STD_DAY);
}

#pragma mark - format the date to string
- (NSString *)psk_chineseWeekDay {
    NSString *weekDay = @"";
    NSInteger day = self.psk_weekday;
    if (1 == day) {
        weekDay = @"星期日";
    }
    else if (2 == day) {
        weekDay = @"星期一";
    }
    else if (3 == day) {
        weekDay = @"星期二";
    }
    else if (4 == day) {
        weekDay = @"星期三";
    }
    else if (5 == day) {
        weekDay = @"星期四";
    }
    else if (6 == day) {
        weekDay = @"星期五";
    }
    else {
        weekDay = @"星期六";
    }
    return weekDay;
}
- (NSString *)psk_timeStamp {
    return [NSString stringWithFormat:@"%.0f", [self timeIntervalSince1970]];
}
- (NSString *)psk_chineseMonth {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM"];
    int i_month = 0;
    NSString *theMonth = [dateFormatter stringFromDate:self];
    if ([[theMonth substringToIndex:0] isEqualToString:@"0"]) {
        i_month = [[theMonth substringFromIndex:1] intValue];
    }
    else {
        i_month = [theMonth intValue];
    }

    if (i_month == 1) {
        return @"一";
    }
    else if (i_month == 2) {
        return @"二";
    }
    else if (i_month == 3) {
        return @"三";
    }
    else if (i_month == 4) {
        return @"四";
    }
    else if (i_month == 5) {
        return @"五";
    }
    else if (i_month == 6) {
        return @"六";
    }
    else if (i_month == 7) {
        return @"七";
    }
    else if (i_month == 8) {
        return @"八";
    }
    else if (i_month == 9) {
        return @"九";
    }
    else if (i_month == 10) {
        return @"十";
    }
    else if (i_month == 11) {
        return @"十一";
    }
    else if (i_month == 12) {
        return @"十二";
    }
    else {
        return @"";
    }
}
- (NSString *)psk_constellation {
    NSString *retStr = @"";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM"];
    int i_month = 0;
    NSString *theMonth = [dateFormatter stringFromDate:self];
    if ([[theMonth substringToIndex:0] isEqualToString:@"0"]) {
        i_month = [[theMonth substringFromIndex:1] intValue];
    }
    else {
        i_month = [theMonth intValue];
    }

    [dateFormatter setDateFormat:@"dd"];
    int i_day = 0;
    NSString *theDay = [dateFormatter stringFromDate:self];
    if ([[theDay substringToIndex:0] isEqualToString:@"0"]) {
        i_day = [[theDay substringFromIndex:1] intValue];
    }
    else {
        i_day = [theDay intValue];
    }
    switch (i_month) {
        case 1:
            if (i_day >= 20 && i_day <= 31) {
                retStr = @"水瓶座";
            }
            if (i_day >= 1 && i_day <= 19) {
                retStr = @"摩羯座";
            }
            break;

        case 2:
            if (i_day >= 1 && i_day <= 18) {
                retStr = @"水瓶座";
            }
            if (i_day >= 19 && i_day <= 31) {
                retStr = @"双鱼座";
            }
            break;

        case 3:
            if (i_day >= 1 && i_day <= 20) {
                retStr = @"双鱼座";
            }
            if (i_day >= 21 && i_day <= 31) {
                retStr = @"白羊座";
            }
            break;

        case 4:
            if (i_day >= 1 && i_day <= 19) {
                retStr = @"白羊座";
            }
            if (i_day >= 20 && i_day <= 31) {
                retStr = @"金牛座";
            }
            break;

        case 5:
            if (i_day >= 1 && i_day <= 20) {
                retStr = @"金牛座";
            }
            if (i_day >= 21 && i_day <= 31) {
                retStr = @"双子座";
            }
            break;

        case 6:
            if (i_day >= 1 && i_day <= 21) {
                retStr = @"双子座";
            }
            if (i_day >= 22 && i_day <= 31) {
                retStr = @"巨蟹座";
            }
            break;

        case 7:
            if (i_day >= 1 && i_day <= 22) {
                retStr = @"巨蟹座";
            }
            if (i_day >= 23 && i_day <= 31) {
                retStr = @"狮子座";
            }
            break;

        case 8:
            if (i_day >= 1 && i_day <= 22) {
                retStr = @"狮子座";
            }
            if (i_day >= 23 && i_day <= 31) {
                retStr = @"处女座";
            }
            break;

        case 9:
            if (i_day >= 1 && i_day <= 22) {
                retStr = @"处女座";
            }
            if (i_day >= 23 && i_day <= 31) {
                retStr = @"天秤座";
            }
            break;

        case 10:
            if (i_day >= 1 && i_day <= 23) {
                retStr = @"天秤座";
            }
            if (i_day >= 24 && i_day <= 31) {
                retStr = @"天蝎座";
            }
            break;

        case 11:
            if (i_day >= 1 && i_day <= 21) {
                retStr = @"天蝎座";
            }
            if (i_day >= 22 && i_day <= 31) {
                retStr = @"射手座";
            }
            break;

        case 12:
            if (i_day >= 1 && i_day <= 21) {
                retStr = @"射手座";
            }
            if (i_day >= 21 && i_day <= 31) {
                retStr = @"摩羯座";
            }
            break;
    }
    return retStr;
}

#pragma mark - 过去了多长时间
+ (NSString *)psk_timePassedByStartTimeStamp:(NSString *)timeStamp {
    if ( ! timeStamp || ! [timeStamp isKindOfClass:[NSString class]] || ! [timeStamp longLongValue]) {
        return @"";
    }
    NSDate *startDate= [NSDate psk_dateFromTimeStamp:timeStamp];
    return [self psk_timePassedByStartDate:startDate];
}
+ (NSString *)psk_timePassedByStartDate:(NSDate *)startDate {
    RETURN_EMPTY_WHEN_OBJECT_IS_EMPTY(startDate);
    NSDate *endDate = CURRENT_DATE;
    //异常时间处理
    if ([startDate psk_isLaterThanDate:endDate]) {
        return [startDate psk_stringWithFormat:kDateFormat1];
    }
    NSDateComponents *dateComponents = [NSDate psk_componentsFromDate1:startDate toDate:endDate];
    //如果>=365d
    if (dateComponents.day >= 365) {
        return [startDate psk_stringWithFormat:kDateFormat5];
    }
    //如果>=30d && <365d
    if (dateComponents.day >= 30 && dateComponents.day < 365) {
        return [startDate psk_stringWithFormat:@"M月d日"];
    }
    //如果>=1d  && <30d
    if (dateComponents.day >= 1 && dateComponents.day < 30) {
        return [NSString stringWithFormat:@"%ld天前", (long)dateComponents.day];
    }
    //如果>=1h  && <24h
    if (dateComponents.hour >= 1 && dateComponents.hour < 24) {
        return [NSString stringWithFormat:@"%ld小时前", (long)dateComponents.hour];
    }
    //如果>=1m  && <60m
    if (dateComponents.minute >= 1 && dateComponents.minute < 60) {
        return [NSString stringWithFormat:@"%ld分钟前", (long)dateComponents.minute];
    }
    return @"刚刚";//1分钟以内
}
+ (NSString *)psk_timePassedByStartDate1:(NSDate *)startDate {
    if ([startDate psk_isThisYear]) {
        if ([startDate psk_isToday]) {
            return [NSString stringWithFormat:@"今天 %@", [startDate psk_stringWithFormat:kDateFormat13]];
        }
        else if ([startDate psk_isYesterday]) {
            return [NSString stringWithFormat:@"昨天 %@", [startDate psk_stringWithFormat:kDateFormat13]];
        }
        else if ([startDate psk_isBeforeYesterday]) {
            return [NSString stringWithFormat:@"前天 %@", [startDate psk_stringWithFormat:kDateFormat13]];
        }
        else {
            return [startDate psk_stringWithFormat:kDateFormat15];
        }
    }
    else {
        return [startDate psk_stringWithFormat:kDateFormat7];
    }
}
+ (NSString *)psk_timePassedByStartDate2:(NSDate *)startDate {
    NSDateComponents *dateComponents = [NSDate psk_componentsFromDate:startDate toDate:CURRENT_DATE];
    if (dateComponents.day > 0) {
        return [NSString stringWithFormat:@"%ld天 %02ld:%02ld:%02ld", (long)dateComponents.day,
                (long)dateComponents.hour, (long)dateComponents.minute, (long)dateComponents.second];
    }
    else if (dateComponents.hour > 0) {
        return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",
                (long)dateComponents.hour, (long)dateComponents.minute, (long)dateComponents.second];
    }
    else {
        return [NSString stringWithFormat:@"%02ld:%02ld", (long)dateComponents.minute, (long)dateComponents.second];
    }
}

#pragma mark - 计算两个时间点之间的距离
+ (NSDateComponents *)psk_componentsFromDate:(NSDate *)startDate toDate:(NSDate *)endDate {
    return [self psk_componentsFromDate:startDate
                                 toDate:endDate
                         withComponents:PSK_CalendarUnitDay | PSK_CalendarUnitHour | PSK_CalendarUnitMinute | PSK_CalendarUnitSecond];
}
+ (NSDateComponents *)psk_componentsFromDate:(NSDate *)startDate toDate:(NSDate *)endDate withComponents:(NSCalendarUnit)unitFlags {
    if ([startDate psk_isLaterThanDate:endDate]) {
        return nil;
    }
    return [[NSCalendar currentCalendar] components:unitFlags fromDate:startDate toDate:endDate options:0];
}
+ (NSDateComponents *)psk_componentsFromDate1:(NSDate *)startDate toDate:(NSDate *)endDate {
    if ([startDate psk_isLaterThanDate:endDate]) {
        return nil;
    }
    NSTimeInterval remainInterval = [endDate timeIntervalSinceDate:startDate];
    NSCalendarUnit unitFlags = PSK_CalendarUnitDay | PSK_CalendarUnitHour | PSK_CalendarUnitMinute | PSK_CalendarUnitSecond;
    NSDateComponents *components = [NSDateComponents new];
    components.year = 0;
    components.month = 0;
    components.day = 0;
    components.hour = 0;
    components.minute = 0;
    components.second = 0;

    //方法一:计算间隔时间是根据从零时间点(1970-01-01)开始的NSDate对象(效率最低!)
    //    NSDate *sinceDate = [NSDate dateFromString:@"1970-01-01" withFormat:@"yyyy-MM-dd"];
    //    NSDate *tempDate = [NSDate dateWithTimeInterval:remainTimeInterval sinceDate:sinceDate];//NOTE:dateWithTimeIntervalSince1970会有时差问题
    //    NSInteger day = [tempDate daysAfterDate:sinceDate];//NOTE:这里不能用tempDate.day
    //    NSInteger hour = tempDate.hour;
    //    NSInteger minute = tempDate.minute;
    //    NSInteger second = tempDate.seconds;

    //方法二:最直接的方法(效率最高!)
    NSInteger day = (NSInteger)(remainInterval / PSK_STD_DAY);
    NSInteger hour = (NSInteger)(remainInterval / PSK_STD_HOUR) - 24 * day;
    NSInteger minute = (NSInteger)(remainInterval / PSK_STD_MINUTE) - 60 * hour - 24 * 60 * day;
    NSInteger second = (NSInteger)remainInterval - 60 * minute - 60 * 60 * hour - 24 * 60 * 60 * day;

    //--------------------设置components START----------------------------------------

    //设置day
    if (PSK_CalendarUnitDay == (PSK_CalendarUnitDay & unitFlags)) {
        [components setDay:day];
    }
    else {
        [components setDay:0];
    }
    //设置hour
    if (PSK_CalendarUnitHour == (PSK_CalendarUnitHour & unitFlags)) {
        NSInteger tempHour = hour;
        if (PSK_CalendarUnitDay != (PSK_CalendarUnitDay & unitFlags)) {
            tempHour += 24 * day;
        }
        [components setHour:tempHour];
    }
    else {
        [components setHour:0];
    }
    //设置minute
    if (PSK_CalendarUnitMinute == (PSK_CalendarUnitMinute & unitFlags)) {
        NSInteger tempMinute = minute;
        if (PSK_CalendarUnitHour != (PSK_CalendarUnitHour & unitFlags)) {
            tempMinute += 60 * hour;
            if (PSK_CalendarUnitDay != (PSK_CalendarUnitDay & unitFlags)) {//只有当hour不存在,才有判断day的必要,下面类似
                tempMinute += 24 * 60 * day;
            }
        }
        [components setMinute:tempMinute];
    }
    else {
        [components setMinute:0];
    }
    //设置second
    if (PSK_CalendarUnitSecond == (PSK_CalendarUnitSecond & unitFlags)) {
        NSInteger tempSecond = second;
        if (PSK_CalendarUnitMinute != (PSK_CalendarUnitMinute & unitFlags)) {
            tempSecond += 60 * minute;
            if (PSK_CalendarUnitHour != (PSK_CalendarUnitHour & unitFlags)) {
                tempSecond += 60 * 60 * hour;
                if (PSK_CalendarUnitDay != (PSK_CalendarUnitDay & unitFlags)) {
                    tempSecond += 24 * 60 * 60 * day;
                }
            }
        }
        [components setSecond:tempSecond];
    }
    else {
        [components setSecond:0];
    }
    //--------------------设置components END----------------------------------------

    return components;
}

#pragma mark - Private Methods
/**
 * 以date为基准,计算前推或后移seconds秒后的date
 */
+ (NSDate *)_psk_dateWithSecondReference:(NSDate *)date second:(long)seconds {
    NSTimeInterval aTimeInterval = [date timeIntervalSinceReferenceDate] + seconds;
    return [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
}

@end


text:
import {
  moduleFor,
  test
} from 'ember-qunit';

moduleFor('controller:onboarding/library', 'OnboardingLibraryController', {
  // Specify the other units that are required for this test.
  needs: ['controller:current-user']
});

// Replace this with your real tests.
test('it exists', function() {
  var controller = this.subject();
  ok(controller);
});

redpajama_set_name: RedPajamaGithub


text:
Puzzle game

    The 15-puzzle (also called Gem Puzzle, Boss Puzzle, Game of Fifteen, Mystic Square and many others)
    is a sliding puzzle that consists of a frame of numbered square tiles in random order with one tile missing.
    The puzzle also exists in other sizes, particularly the smaller 8-puzzle. If the size is 3×3 tiles, the
    puzzle is called the 8-puzzle or 9-puzzle, and if 4×4 tiles, the puzzle is called the 15puzzle or 16-puzzle named,
    respectively, for the number of tiles and the number of spaces. The object of the puzzle is to place the tiles in
    order by making sliding moves that use the empty space.

    Play Game

    <router-outlet></router-outlet>


text:
package org.apache.servicecomb.foundation.vertx.tcp;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.CompositeByteBuf;
import io.vertx.core.Context;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetSocket;
import io.vertx.core.net.impl.NetSocketImpl;

public class TcpConnection {
  protected String protocol;

  // 压缩算法名字
  protected String zipName;

  protected NetSocket netSocket;

  // context of netSocket
  protected Context context;

  // vertx's wrap for netty is ugly: write always lock first
  // so we save buf in a CAS queue, and notify eventloop thread to do the real write
  //
  // netty:
  // if write caller is not in network IO thread
  // always wrap the write as a task, and put it to IO thread queue(MPSC queue)
  //
  // so this optimization:
  // 1.avoid vertx's lock
  // 2.reduce netty's task schedule
  private Queue<ByteBuf> writeQueue = new ConcurrentLinkedQueue<>();

  private AtomicLong writeQueueSize = new AtomicLong();

  public String getProtocol() {
    return protocol;
  }

  public void setProtocol(String protocol) {
    this.protocol = protocol;
  }

  public String getZipName() {
    return zipName;
  }

  public void setZipName(String zipName) {
    this.zipName = zipName;
  }

  public void setContext(Context context) {
    this.context = context;
  }

  public NetSocket getNetSocket() {
    return netSocket;
  }

  public void initNetSocket(NetSocketImpl netSocket) {
    this.netSocket = netSocket;

    this.context = netSocket.getContext();
  }

  public void write(ByteBuf buf) {
    writeQueue.add(buf);
    long oldSize = writeQueueSize.getAndIncrement();
    if (oldSize == 0) {
      scheduleWrite();
    }
  }

  // notify context thread to write
  protected void scheduleWrite() {
    context.runOnContext(v -> {
      writeInContext();
    });
  }

  protected void writeInContext() {
    CompositeByteBuf cbb = ByteBufAllocator.DEFAULT.compositeBuffer();
    for (; ; ) {
      ByteBuf buf = writeQueue.poll();
      if (buf == null) {
        break;
      }

      writeQueueSize.decrementAndGet();
      cbb.addComponent(true, buf);

      if (cbb.numComponents() == cbb.maxNumComponents()) {
        netSocket.write(Buffer.buffer(cbb));
        cbb = ByteBufAllocator.DEFAULT.compositeBuffer();
      }
    }
    if (cbb.isReadable()) {
      netSocket.write(Buffer.buffer(cbb));
    }
  }
}


text:
/*
 * orderItem viewmodel associated with orderItem.html view
 * and its orderItem**.html sub-views.
 */
(function(angular) {
    'use strict';

    angular.module( "app" ).controller( 'orderItem',
        ['$state', '$stateParams', 'dataservice', 'orderItemOptionTypeVm', 'util', controller] );

    function controller($state, $stateParams, dataservice, orderItemOptionTypeVm, util ) {
        var vm = this;
        dataservice.ready().then(onReady);

        function onReady() {
            var cartOrder    = dataservice.cartOrder;
            var draftOrder   = dataservice.draftOrder;
            var lookups      = dataservice.lookups;

            var info         = getOrderItemInfo( );

            if ( info ) {
                var isDraftOrder = info.orderItem.order === dataservice.draftOrder;
                vm.addToCart     = addToCart;
                vm.isDraftOrder  = isDraftOrder;
                vm.orderItem     = info.orderItem;
                vm.product       = info.product;
                vm.sizeVms       = createSizeVms(info);
                vm.typeVms       = orderItemOptionTypeVm.createVms(info.orderItem);

            } else {
                showMenu();
            }
        /////////////////////
            function addToCart() {
                if (vm.isDraftOrder) {
                    draftOrder.removeItem(vm.orderItem);
                    cartOrder.addItem(vm.orderItem);
                    vm.isDraftOrder = isDraftOrder = false;
                    util.logger.info("Added item to cart");

                    showMenu();
                }
            }

            // Get the OrderItem information base on $stateParams
            function getOrderItemInfo( ) {
                var fromOrder   = $stateParams.orderItemId != null;
                return fromOrder ? getInfoFromOrder() : getInfoByProduct();

                // Get the order item info from the order and orderItem id.
                function getInfoFromOrder( ) {
                    var info = null
                      , orderId = $stateParams.orderId
                      , orderItemIid = +$stateParams.orderItemId;

                    // Todo: in future, could be the orderId of any order
                    var orderItem = orderId == 'cart' ?
                        cartOrder.getSelectedItem(orderItemIid) :
                        draftOrder.getSelectedItem(orderItemIid);

                    if (orderItem){
                        info = {
                            orderItem: orderItem,
                            product: orderItem.product,
                            sizes: lookups.productSizes.byProduct(orderItem.product)
                        }
                    }
                    return info;
                }

                // Get the order item info from the productId.
                function getInfoByProduct() {
                    var prodId = +$stateParams.productId;
                    var product = lookups.products.byId(prodId);
                    if (!product){ return null; }

                    var sizes = lookups.productSizes.byProduct(product);

                    // Find an orderItem on the draft order for the given product.
                    var orderItem =  draftOrder.orderItems.filter(function (oi) {
                            return oi.productId == prodId;
                        })[0];

                    if (!orderItem) {
                        // No existing orderItem for this product
                        // Create a new orderItem
                        orderItem = draftOrder.addNewItem(product);
                        orderItem.productSize = sizes[0]; // defaultSize
                    }

                    return {
                        orderItem: orderItem,
                        product: product,
                        sizes: sizes
                    };
                }
            }
        }

        function createSizeVms(info) {
            var isPremium = info.product.isPremium;
            return info.sizes.map(function (size) {
                return {
                    id: size.id,
                    name: size.name,
                    price: isPremium ? (size.premiumPrice ||size.price) : size.price
                };
            });
        }

        function showMenu(){
            $state.go('app.menu', {productType : $stateParams.productType});
    }
   }

}( this.angular ));


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('nypr-story/segment/message', 'Integration | Component | nypr story/segment/message', {
  integration: true
});

test('it renders', function(assert) {

  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{nypr-story/segment/message}}`);

  assert.equal(this.$().text().trim(), 'Audio not yet available');

  // Template block usage:
  this.render(hbs`
    {{#nypr-story/segment/message}}
      template block text
    {{/nypr-story/segment/message}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});


text:
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using SIL.Extensions;
using SIL.IO;
using SIL.PlatformUtilities;
using SIL.Reporting;

namespace Bloom.MiscUI
{
	public partial class BloomIntegrityDialog : Form
	{
		public BloomIntegrityDialog()
		{
			InitializeComponent();
		}
		///
		/// We've had a number of user reports that suggest that files were either missing or inaccessible.
		/// The idea here is to check a set of files and folders at the start of each launch, and generate
		/// a useful report if anything is missing.
		///
		/// <returns>true if all is well. Application should exit if this returns false.</returns>
		public static bool CheckIntegrity()
		{
			var errors = new StringBuilder();
			var files = new[] { "Bloom.chm", "PdfDroplet.exe", "BloomPdfMaker.exe" };

				string[] dirs;
			if (Platform.IsWindows)
				dirs = new[] { "AndikaNewBasic", "localization", "xslts", "icons" };
			else
				dirs = new[] { "localization", "xslts", "icons" };

			foreach(var fileName in files)
			{
				if(FileLocationUtilities.GetFileDistributedWithApplication(true, fileName) == null)
				{
					//In a code directory, the FileLocator considers the solution the root, so it can't find files in output\debug
					if(!RobustFile.Exists(Path.Combine(FileLocationUtilities.DirectoryOfTheApplicationExecutable, fileName)))
					{
						//maybe it's an exe in distfiles?
						if(fileName.EndsWith(".exe") && RobustFile.Exists(Path.Combine(FileLocationUtilities.DirectoryOfApplicationOrSolution, "DistFiles")))
						{
							continue;
						}
						errors.AppendFormat("
Missing File: {0}
{1}", fileName, Environment.NewLine);
					}
				}
			}
			foreach(var directory in dirs)
			{
				if(FileLocationUtilities.GetDirectoryDistributedWithApplication(true, directory) == null)
				{
					errors.AppendFormat("
Missing Directory: {0}
{1}", directory, Environment.NewLine);
				}
			}
			if(errors.Length == 0)
				return true;

			using(var dlg = new BloomIntegrityDialog())
			{
				const string nonHtmlMessage = "Bloom cannot find some of its own files, and cannot continue. After you submit this report, we will contact you and help you work this out. In the meantime, you can run the Bloom installer again.";
				var messagePath = BloomFileLocator.GetBestLocalizableFileDistributedWithApplication(false, "help", "IntegrityFailureAdvice-en.htm");
				string message;
				if(messagePath == null) // maybe we can't even get at this file we need for a good description of the problem
				{
					message = nonHtmlMessage;
				}
				else
				{
					var installFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
							.CombineForPath(Application.ProductName);
					message = RobustFile.ReadAllText(messagePath).Replace("{{installFolder}}", installFolder);//new
					message = message.Replace("{installFolder}", installFolder);  //old
				}

				message = message + Environment.NewLine + Environment.NewLine + errors;
				dlg.htmlTextBox1.HtmlText = message;
				dlg.ShowDialog();
				Logger.WriteEvent("Bloom Integrity Check Failed: " + message);
				// We would like to do this:
				// ProblemReportApi.ShowProblemDialog(null, "fatal");
				// But that can't work because BloomServer isn't running yet.
			}

			return false; //Force termination of the current process.
		}

		private void _reportButton_Click(object sender, EventArgs e)
		{
			Close();
		}
	}
}


text:
.class Landroid/os/ICancellationSignal$Stub$Proxy;
.super Ljava/lang/Object;
.source "ICancellationSignal.java"

# interfaces
.implements Landroid/os/ICancellationSignal;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/os/ICancellationSignal$Stub;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "Proxy"
.end annotation

# instance fields
.field private mRemote:Landroid/os/IBinder;

# direct methods
.method constructor <init>(Landroid/os/IBinder;)V
    .locals 0
    .parameter "remote"

    .prologue
    .line 61
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 62
    iput-object p1, p0, Landroid/os/ICancellationSignal$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    .line 63
    return-void
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .locals 1

    .prologue
    .line 66
    iget-object v0, p0, Landroid/os/ICancellationSignal$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    return-object v0
.end method

.method public cancel()V
    .locals 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 74
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 76
    .local v0, _data:Landroid/os/Parcel;
    :try_start_0
    const-string v1, "android.os.ICancellationSignal"

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 77
    iget-object v1, p0, Landroid/os/ICancellationSignal$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v2, 0x1

    const/4 v3, 0x0

    const/4 v4, 0x1

    invoke-interface {v1, v2, v0, v3, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 80
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 82
    return-void

    .line 80
    :catchall_0
    move-exception v1

    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v1
.end method

.method public getInterfaceDescriptor()Ljava/lang/String;
    .locals 1

    .prologue
    .line 70
    const-string v0, "android.os.ICancellationSignal"

    return-object v0
.end method


text:
package com.sandwich.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import com.sandwich.koan.KoanMethod;
import com.sandwich.util.io.FileUtils;

public class KoanComparator implements Comparator<KoanMethod> {
	List<String> orderedKeywords;
	Set<String> methodNamesCompared = new HashSet<String>();

	public KoanComparator(String...koans){
		this(Arrays.asList(koans));
	}

	public KoanComparator(Collection<String> koans){
		this.orderedKeywords = new ArrayList<String>(koans);
	}

	public int compare(KoanMethod arg0, KoanMethod arg1) {
		Class<?> declaringClass0 = arg0.getMethod().getDeclaringClass();
		Class<?> declaringClass1 = arg1.getMethod().getDeclaringClass();
		if(declaringClass0 != declaringClass1){
			Logger.getAnonymousLogger().severe("no idea how to handle comparing the classes: " + declaringClass0 + " and: "+declaringClass1);
			return 0;
		}
		String contentsOfOriginalJavaFile = FileUtils.getContentsOfOriginalJavaFile(declaringClass0.getName());
		Integer index0 = Integer.valueOf(	contentsOfOriginalJavaFile.indexOf(arg0.getMethod().getName()));
		Integer index1 = Integer.valueOf(	contentsOfOriginalJavaFile.indexOf(arg1.getMethod().getName()));
		return index0.compareTo(index1);
	}

}


text:
Trophy Modern
-------

Tech this uses [thnx]:

- http://gulpjs.com/
- https://github.com/WebDevStudios/CMB2


text:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Router } from '@angular/router';

// Auth0
import { AuthService } from 'src/app/services/auth.service';

// Other
import { DeviceDetectorService } from 'ngx-device-detector';

// FreeVote
import { LocalDataService } from './../../services/local-data.service';
import { AppDataService } from '../../services/app-data.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  // https://medium.com/better-programming/angular-manipulate-properly-the-dom-with-renderer-16a756508cba
  @ViewChild('tvSlashTag', { static: false }) tvSlashTag: ElementRef;

  public slashTag: string;

  tabIndex = 0;

  survey = false;
  justice = false;
  ballot = false;

  anonimity = false;
  threats = false;
  threads = false;

  isMobile = false;

  privacyUrl = this.localData.siteUrl + 'policy.html';

  constructor(
    private router: Router,
    private deviceService: DeviceDetectorService,
    public localData: LocalDataService,
    public appData: AppDataService,
    public auth: AuthService) {

    this.epicFunction();

  }

  ngOnInit(): void {
    // Don't emit InputSlashTagOnMobile$ here as it triggers error in app.component
    // ExpressionChangedAfterItHasBeenCheckedError
    this.restartSearch();
  }

  epicFunction(): void {
    this.isMobile = this.deviceService.isMobile();
    console.log(this.deviceService.getDeviceInfo(), this.deviceService.isMobile());
  }

  installPwa(): void {
    this.appData.promptEvent.prompt();
  }

  beginInput(): void {
    // Only update if we are on mobile
    if (this.isMobile) {
      this.appData.InputSlashTagOnMobile$.next(true);
    }
  }

  endInput(): void {
    // Only update if we are on mobile
    if (this.isMobile) {
      this.appData.InputSlashTagOnMobile$.next(false);
    }
  }

  restartSearch(): void {

    this.slashTag = '/';

    // Don't start off with focus on input on mobile (Vulcan will never be shown)
    if (!this.isMobile) {
      window.setTimeout(() => {

        const el = this.tvSlashTag.nativeElement;
        el.focus();

        // Place cursor at end
        if (typeof el.selectionStart === 'number') {
          el.selectionStart = el.selectionEnd = el.value.length;
        } else if (typeof el.createTextRange !== 'undefined') {
          const range = el.createTextRange();
          range.collapse(false);
          range.select();
        }
      }, 500);
    }

  }

  slashTagChanged(): void {

    // can't use same kebab function as kebabUri - we need to allow ending "-" while typing
    // .filter - an empty string evaluates to boolean false. It works with all falsy values like 0, false, null, undefined

    if (!this.slashTag) { this.restartSearch(); }

    if (this.slashTag && this.slashTag.length > 1) {

      let lastChar = this.slashTag.charAt(this.slashTag.length - 1);

      const regx = /^[-A-Za-z0-9\s]+$/;
      console.log(lastChar, regx.test(lastChar));

      if (!regx.test(lastChar)) {
        lastChar = '';
        this.slashTag = this.slashTag.slice(0, -1);
      }

      if (lastChar === ' ') { lastChar = '-'; }
      if (lastChar !== '-') { lastChar = ''; }

      let output = this.slashTag.split(' ').filter(item => item).join('-'); // remove double spaces, replace spaces with dash
      output = output.split('-').filter(item => item).join('-'); // remove double-dashes, no dash start or end

      this.slashTag = output + lastChar; // preserve trailing dash while typing
    }
  }

  showTagPoints(): void {

    if (!this.slashTag || this.slashTag === '/') {
      this.restartSearch();
    } else {
      // Remove trailing dash after user finished typing
      let value = this.slashTag;
      if (value[value.length - 1] === '-') { value = value.substr(0, value.length - 1); }
      this.slashTag = value;

      this.localData.PreviousSlashTagSelected = this.slashTag;

      this.router.navigateByUrl('/' + this.slashTag);
      this.slashTag = '';
    }
  }

}


text:
__author__ = 'Viktor Evstratov, George Oblapenko'
import unittest
from krakenous.dataset import DataSet
from krakenous.prerolled import folder_tentacle, convert_multiple_features_numpy, convert_single_feature_numpy,\
    numpy_array_serializer, dump_dataset, numpy_array_deserializer, sync_datasets
import os.path
from os import makedirs, rmdir, remove
import numpy as np
import krakenous.errors

def fake_extractor(add_data, val):
    return val

def a_very_fake_extractor(add_data):
    return 30239

def ext3(add_data):
    return 23930

def list_feature_test(add_data):
    return [1, 3, 4]

def argfeature_test(add_data, i, j=2):
    return i + j

def numpy_feature(add_data):
    return np.zeros(3)

def numpy_feature2(add_data):
    return np.ones(2)

def numpy_feature_md(add_data):
    return np.ones([3, 4, 9])

def string_feature(add_data):
    return 'test string feature'

def id_doubler(add_data):
    return add_data['id'] * 2

def id_heavyside(add_data):
    if add_data['id'] > 5:
        return 1
    else:
        return 0

def folder_creator():
    if not os.path.isdir('testfolder'):
        makedirs('testfolder')
        for i in range(10):
            open('testfolder/' + str(i), 'a').close()

def folder_destroyer():
    for i in range(10):
        remove('testfolder/' + str(i))
    rmdir('testfolder')

class BaseTest(unittest.TestCase):
    def setUp(self):
        self.dataset = DataSet(backend='sqlite', db_path='testsqlite', table_name='test_table')
        if self.dataset.total_records == 0:
            folder_creator()
            self.dataset.populate(folder_tentacle, 'testfolder', 'filename')

    def test_population(self):
        assert self.dataset.total_records == 10

    def test_extraction(self):
        self.dataset.extract_feature_full(fake_extractor, (), 23, overwrite_feature=True)
        assert self.dataset.feature_exists_global('fake_extractor') is True  # the feature exists

    def test_extraction_value(self):
        self.dataset.extract_feature_full(fake_extractor, (), 46, overwrite_feature=True)
        assert self.dataset.single_data_record(1, ('fake_extractor',))['fake_extractor'] == 46
        # the feature value is correct
        self.dataset.extract_feature_full(fake_extractor, (), 'meaning of life', overwrite_feature=True)
        assert self.dataset.single_data_record(1, ('fake_extractor',))['fake_extractor'] == 'meaning of life'
        # feature overwriting works correctly

    def test_insert_single_value(self):
        self.dataset.insert_single(5, 'extra_field', 'extra number', overwrite_existing=True)
        assert self.dataset.feature_exists(5, 'extra_field') is True  # inserts something
        assert self.dataset.feature_exists(4, 'extra_field') is False  # inserts only for the correct id
        self.assertRaises(krakenous.errors.KrakenousException, self.dataset.insert_single,
                          5, 'extra_field', 3333)
        # ^ does not overwrite by accident and raies correct error
        self.dataset.insert_single(5, 'extra_field', 5555, overwrite_existing=True)
        assert self.dataset.single_data_record(5, ('extra_field',))['extra_field'] == 5555
        # overwrite works correctly

    def test_feature_args(self):
        self.dataset.extract_feature_full(argfeature_test, (), 5,
                                          verbose=0, writeback=0,
                                          overwrite_feature=True, j=10)
        assert self.dataset.single_data_record(5, ('argfeature_test',))['argfeature_test'] == 15

    def test_return_single_feature(self):
        self.dataset.extract_feature_full(string_feature, (), overwrite_feature=True)
        feature = self.dataset.single_feature('string_feature')
        assert len(feature) == self.dataset.total_records  # default values work correctly, returns data for all records
        assert feature[0] == 'test string feature'  # returns the correct data value
        feature = self.dataset.single_feature('string_feature', start_id=3)
        assert len(feature) == self.dataset.total_records - 2
        feature = self.dataset.single_feature('string_feature', start_id=4, end_id=7)
        assert len(feature) == 4  # and the start_id, end_id parameters work correctly

    def test_column_selection(self):
        self.dataset.extract_feature_simple(id_doubler, ('id', ))
        feature = self.dataset.single_feature('id_doubler', start_id=1, end_id=3)
        assert feature[0] == 2
        assert feature[2] == 6

    def test_filter(self):
        self.dataset.extract_feature_simple(id_heavyside, ('id',))
        tests = list(self.dataset.yield_data_records(('id_heavyside',), filters={'id_heavyside': 0}))
        assert len(tests) == 5

        tests = list(self.dataset.yield_data_records(('id',), filters={'id': 4}))
        assert len(tests) == 1

        tests = list(self.dataset.yield_data_records(('id',), filters={'id': 114}))
        assert len(tests) == 0

    def test_deserialize(self):
        self.dataset.extract_feature_simple_custom_serializer(numpy_feature_md, (), numpy_array_serializer)
        np_feat = self.dataset.single_data_record(5, ('numpy_feature_md', ),
                                                  {'numpy_feature_md': numpy_array_deserializer})
        assert np_feat['numpy_feature_md'].shape == (3, 4, 9)

    def test_feature_names_and_serialization(self):
        self.dataset.extract_feature_full(a_very_fake_extractor, (), overwrite_feature=True)
        self.dataset.extract_feature_full(list_feature_test, (), overwrite_feature=True)
        self.dataset.extract_feature_full(numpy_feature, (), overwrite_feature=True, serializer=numpy_array_serializer)
        self.dataset.extract_feature_full(string_feature, (), overwrite_feature=True)
        feature_names = self.dataset.feature_names()
        assert 'a_very_fake_extractor' in feature_names
        assert 'string_feature' in feature_names
        assert 'numpy_feature' in feature_names  # the features were returned

    def tearDown(self):
        folder_destroyer()
        remove('testsqlite')

class TestSQLite(BaseTest):
    pass

class TestNumpyConvert(unittest.TestCase):
    def setUp(self):
        """
        This creates a DataSet which uses the shelve backend. It also creates a folder with 10 files (named 0 to 9)
        to use with the folder_tentacle (if a testfolder already exists, this just reaches inside it and grabs what's
        there)
        """
        self.dataset = DataSet(backend='shelve', db_path='testshelve')  # we will use the folder tentacle for testing
        if self.dataset.total_records == 0:
            folder_creator()
            self.dataset.populate(folder_tentacle, 'testfolder', 'filename')
        self.dataset.extract_feature_simple(numpy_feature, ())
        self.dataset.extract_feature_simple(numpy_feature2, ())

    def test_return_single_feature_numpy(self):
        feature = convert_single_feature_numpy(self.dataset, 'numpy_feature')
        assert feature.shape == (self.dataset.total_records, 3,)
        assert feature[0, 1] == 0  # converts a single feature for each record into a single numpy array correctly

    def test_return_multiple_features_numpy(self):
        self.dataset.extract_feature_full(numpy_feature2, (), overwrite_feature=True)
        assert self.dataset.feature_exists_global('numpy_feature2') is True
        feature = convert_multiple_features_numpy(self.dataset, ('numpy_feature', 'numpy_feature2',))
        assert isinstance(feature, np.ndarray) == True
        assert feature.shape == (self.dataset.total_records, 5,)
        assert feature[0, 1] == 0
        assert feature[0, 4] == 1  # converts multiple features for each record into a single numpy array correctly

    def tearDown(self):
        folder_destroyer()
        remove('testshelve.db')

class TestDump(unittest.TestCase):
    def setUp(self):
        """
        This creates a DataSet which uses the shelve backend. It also creates a folder with 10 files (named 0 to 9)
        to use with the folder_tentacle (if a testfolder already exists, this just reaches inside it and grabs what's
        there)
        """
        self.dataset = DataSet(backend='shelve', db_path='testshelve')  # we will use the folder tentacle for testing
        if self.dataset.total_records == 0:
            folder_creator()
            self.dataset.populate(folder_tentacle, 'testfolder', 'filename')
        self.dataset.extract_feature_simple(ext3, ())
        self.dataset.extract_feature_simple(string_feature, ())
        self.dataset.extract_feature_simple(numpy_feature, ())

    def test_full_dump(self):
        new_dataset = DataSet(backend='sqlite', db_path='testsqlite1', table_name='test_table')
        dump_dataset(self.dataset, new_dataset, serializers={'numpy_feature': numpy_array_serializer})
        assert new_dataset.total_records == self.dataset.total_records
        feature_names = new_dataset.feature_names()
        assert 'string_feature' in feature_names
        assert 'ext3' in feature_names
        assert 'numpy_feature' in feature_names

    def tearDown(self):
        folder_destroyer()
        remove('testshelve.db')
        remove('testsqlite1')

class TestSync(unittest.TestCase):
    def setUp(self):
        """
        This creates a DataSet which uses the shelve backend. It also creates a folder with 10 files (named 0 to 9)
        to use with the folder_tentacle (if a testfolder already exists, this just reaches inside it and grabs what's
        there)
        """
        self.dataset1 = DataSet(backend='sqlite', db_path='testsqlite1', table_name='test_table')
        self.dataset2 = DataSet(backend='sqlite', db_path='testsqlite2', table_name='test_table')
        if self.dataset1.total_records == 0:
            folder_creator()
            self.dataset1.populate(folder_tentacle, 'testfolder', 'filename')
            self.dataset2.populate(folder_tentacle, 'testfolder', 'filename')
        self.dataset1.extract_feature_simple(ext3, ())
        self.dataset1.extract_feature_simple(string_feature, ())
        self.dataset2.extract_feature_simple_custom_serializer(numpy_feature, (), numpy_array_serializer)

    def test_syncing(self):
        sync_datasets(self.dataset1, self.dataset2, serializers={'numpy_feature': numpy_array_serializer},
                      deserializers={'numpy_feature': numpy_array_deserializer})
        names1 = self.dataset1.feature_names()
        names2 = self.dataset2.feature_names()
        assert 'numpy_feature' in names1
        assert 'ext3' in names2
        assert 'string_feature' in names2

    def tearDown(self):
        folder_destroyer()
        remove('testsqlite1')
        remove('testsqlite2')

if __name__ == '__main__':
    unittest.main()


text:
package cz.skaut.warehousemanager.soap;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;

@Root(name = "soap:Envelope", strict = false)
public class LoginRefreshResult {

	@Path("soap:Body/LoginUpdateRefreshResponse/LoginUpdateRefreshResult")
	@Element(name = "DateLogout")
	private String dateLogout;

	public String getDateLogout() {
		return dateLogout;
	}
}


text:
{% load static %}
{% block content %}
    {% load core_template_filters %}

                Select a tab below to export Records as full XML Documents, Mapped
                Fields, or Tabular Data. Click
                here for documentation.
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    ×
                </button>

                    Export Documents

                    Export Mapped Fields

                    Export Tabular Data

                            {% if cjob %}
                                <form method="POST"
                                      action="{% url 'export_documents' export_source='job' job_id=cjob.job.id %}">
                            {% else %}
                                {% if published.subset %}
                                    <form method="POST"
                                          action="{% url 'export_documents' export_source='published' subset=published.subset %}">
                                {% else %}
                                    <form method="POST" action="{% url 'export_documents' export_source='published' %}">
                                {% endif %}
                            {% endif %}

                            {% csrf_token %}

                                XML Records per file
                                <input type="text" class="form-control" name="records_per_file" id="records_per_file"
                                       placeholder="e.g. 500 (default)">
                                Optional

                                Select archive file type
                                <select class="form-control" id="archive_type" name="archive_type" required>
                                    <option value="zip">Compressed Zip file</option>
                                    <option value="targz">Compressed Tar file</option>
                                    <option value="tar">Uncompressed Tar file</option>
                                </select>

                                        <input class="form-check-input" type="checkbox" value="true"
                                               id="s3_export_documents" name="s3_export"/
                                        onclick="$('#s3_export_documents_options').fadeToggle();">

                                             Export to Amazon S3
                                            Bucket?

Instead of writing exports to the local filesystem, write exports to Amazon
                                            AWS S3 storage. Some considerations:

S3 buckets must exist prior to export, they will not be
                                                created

Key in bucket must not exist, they will not overwrite

                                            S3 Bucket
                                            <input type="text" class="form-control" name="s3_bucket" id="s3_bucket"
                                                   placeholder="e.g. combine-1">
                                            Must exist,
                                                and have write permissions

                                            S3 Key
                                            <input type="text" class="form-control" name="s3_key" id="s3_key"
                                                   placeholder="e.g. 02_2019_published_records">
                                            Avoid spaces,
                                                punctuation, and special characters

                                            Export as:
                                            <select class="form-control" id="s3_export_type" name="s3_export_type"
                                                    required>
                                                <option value="spark_df">Spark DataFrame</option>
                                                <option value="archive">Archive file</option>
                                            </select>

                            <button type="submit" class="btn btn-success btn-sm">Export Documents </button>

                            </form>

                            {% if cjob %}
                                <form id="export_mapped_fields_form" method="POST"
                                      action="{% url 'export_mapped_fields' export_source='job' job_id=cjob.job.id %}">
                            {% else %}
                                {% if published.subset %}
                                    <form id="export_mapped_fields_form" method="POST"
                                          action="{% url 'export_mapped_fields' export_source='published' subset=published.subset %}">
                                {% else %}
                                    <form id="export_mapped_fields_form" method="POST"
                                          action="{% url 'export_mapped_fields' export_source='published' %}">
                                {% endif %}
                            {% endif %}

                            {% csrf_token %}

                                    Select export format:
                                    <select class="form-control" id="mapped_fields_export_type"
                                            name="mapped_fields_export_type" required>
                                        <option value="json">JSON (line-delimited, recommended)</option>
                                        <option value="csv">CSV (tabular, comma separated)</option>
                                    </select>

                                        Note: Mapped fields exported as .csv are more prone to messy
                                        data due to column delimiters and newline characters that may exist within field
                                        values. Exporting Mapped Fields as JSON handles this more deftly, and is
                                        recommended.

                                        <input class="form-check-input" type="checkbox" value="true" id="kibana_style"
                                               name="kibana_style"/ checked>

                                            Export CSV "Kibana style"?
                                            <button type="button" class="btn btn-outline-info btn-sm"
                                                    onclick="$('#kibana_style_info').fadeToggle();">More Information
                                            </button>

"Kibana style" is referring to the Kibana application for
                                            visualize and analyzing ElasticSearch indexes, and addresses fields that
                                            have multiple values.

For example, consider an ElasticSearch field called
                                            mods_subject_topic, with multiple values of
                                            history, boating, and typing. If
                                            Kibana style is not checked/used -- which is the default
                                            behavior -- this would result in three distinct columns in the generated
                                            .csv file with a number affixed to the field name: mods_subject_topic.0
                                            with the value historyM, mods_subject_topic.1 with
                                            the value boating, and mods_subject_topic.2 with
                                            the value typing. This can handy for analysis, as distinct
                                            values for this field are in distinct columns.

But some pipelines are prepared for fields that are comma separated when
                                            repeating, e.g. Kibana. If checked, the result would be a
                                            single field called mods_subject_topic and a
                                            single, comma separated value of history,boating,typing.

                                    Select archive file type
                                    <select class="form-control" id="archive_type" name="archive_type" required>
                                        <option value="none">Uncompressed</option>
                                        <option value="zip">Compressed Zip file</option>
                                        <option value="targz">Compressed Tar file</option>
                                    </select>

By default, all mapped fields are included in the report, but you may
                                optionally select a smaller subset of fields to export by clicking the button below.

                            {% include 'core/select_mapped_fields.html' %}

                                        <input class="form-check-input" type="checkbox" value="true"
                                               id="s3_export_mapped_fields" name="s3_export"/
                                        onclick="$('#s3_export_mapped_fields_options').fadeToggle();">

                                             Export to Amazon S3
                                            Bucket?

Instead of writing exports to the local filesystem, write exports to Amazon
                                            AWS S3 storage. Some considerations:

S3 buckets must exist prior to export, they will not be
                                                created

Key in bucket must not exist, they will not overwrite

                                            S3 Bucket
                                            <input type="text" class="form-control" name="s3_bucket" id="s3_bucket"
                                                   placeholder="e.g. combine-1">
                                            Must exist,
                                                and have write permissions

                                            S3 Key
                                            <input type="text" class="form-control" name="s3_key" id="s3_key"
                                                   placeholder="e.g. 02_2019_published_records">
                                            Avoid spaces,
                                                punctuation, and special characters

                                            Export as:
                                            <select class="form-control" id="s3_export_type" name="s3_export_type"
                                                    required>
                                                <option value="archive">Archive file</option>
                                            </select>

                            <button id="form_submit_button" type="button" class="btn btn-success btn-sm">Export Mapped
                                Fields </button>

                            </form>

                            {% if cjob %}
                                <form method="POST"
                                      action="{% url 'export_tabular_data' export_source='job' job_id=cjob.job.id %}">
                            {% else %}
                                {% if published.subset %}
                                    <form method="POST"
                                          action="{% url 'export_tabular_data' export_source='published' subset=published.subset %}">
                                {% else %}
                                    <form method="POST"
                                          action="{% url 'export_tabular_data' export_source='published' %}">
                                {% endif %}
                            {% endif %}

                            {% csrf_token %}

                                    Select export format:
                                    <select class="form-control" id="tabular_data_export_type"
                                            name="tabular_data_export_type" required>
                                        <option value="csv">CSV (tabular, comma separated)</option>
                                        <option value="json">JSON (line-delimited)</option>
                                    </select>

                                        Note: Mapped fields exported as .csv are more prone to messy
                                        data due to column delimiters and newline characters that may exist within field
                                        values, but, may be easier to edit outside of Combine before re-ingesting. JSON
                                        "round trips" easier, but can be more difficult to edit.

                                XML Records per file
                                <input type="text" class="form-control" name="records_per_file" id="records_per_file"
                                       placeholder="e.g. 500 (default)">
                                Optional

                                Select archive file type
                                <select class="form-control" id="archive_type" name="archive_type" required>
                                    <option value="zip">Compressed Zip file</option>
                                    <option value="targz">Compressed Tar file</option>
                                    <option value="tar">Uncompressed Tar file</option>
                                </select>

Tabular Data Export Parameters

Select a pre-existing field mapper configuration, or edit the one below, to
                                            be used for exporting tabular data.

                                            Configuration Name
                                            <select class="form-control" id="harvest_field_mapper"
                                                    name="harvest_field_mapper">
                                                {% if orig_fm_config_json %}
                                                    <option value="job_fm_config_json">Configuration used for
                                                        Job: {{ cjob.job.name }}</option>
                                                {% endif %}
                                                <option value="default">Default</option>
                                                {% for fm in field_mappers %}
                                                    <option value='{{ fm.id }}'>{{ fm.name }}</option>
                                                {% endfor %}
                                            </select>

                                        <textarea style="display:none;" rows=10 class="code_style form-control"
                                                  name="fm_export_config_json" id="fm_export_config_json"></textarea>

                                                    <button class="btn btn-outline-success btn-sm"
                                                            onclick="save_current_fm_export_config_json('new'); return false;">
                                                        Save as new configurations
                                                    </button>
                                                    <button style="display:none;"
                                                            class="btn btn-outline-warning btn-sm pre_harvest_fm_config_options"
                                                            onclick="save_current_fm_export_config_json('update'); return false;">
                                                        Update saved configurations
                                                    </button>
                                                    <button style="display:none;"
                                                            class="btn btn-outline-danger btn-sm pre_harvest_fm_config_options"
                                                            onclick="confirm('Are you sure you want to delete these saved Field Mapping configurations?'); save_current_fm_export_config_json('delete'); return false;">
                                                        Delete saved configurations
                                                    </button>
                                                    <button class="btn btn-outline-info btn-sm"
                                                            onclick="$('#fm_harvest_config_help').toggle(); return false;">
                                                        What do these configurations mean?
                                                    </button>

                                                            Parameter
                                                            Type
                                                            Description>

                                                        {% for param,details in xml2kvp_handle.schema.properties.items|dictsort:"0.lower" %}

                                                                {{ param }}
                                                                {{ details.type }}
                                                                {{ details.description }}

                                                        {% endfor %}

                                        <input class="form-check-input" type="checkbox" value="true"
                                               id="s3_export_tabular_data" name="s3_export"/
                                        onclick="$('#s3_export_tabular_data_options').fadeToggle();">

                                             Export to Amazon S3
                                            Bucket?

Instead of writing exports to the local filesystem, write exports to Amazon
                                            AWS S3 storage. Some considerations:

S3 buckets must exist prior to export, they will not be
                                                created

Key in bucket must not exist, they will not overwrite

                                            S3 Bucket
                                            <input type="text" class="form-control" name="s3_bucket" id="s3_bucket"
                                                   placeholder="e.g. combine-1">
                                            Must exist,
                                                and have write permissions

                                            S3 Key
                                            <input type="text" class="form-control" name="s3_key" id="s3_key"
                                                   placeholder="e.g. 02_2019_published_records">
                                            Avoid spaces,
                                                punctuation, and special characters

                                            Export as:
                                            <select class="form-control" id="s3_export_type" name="s3_export_type"
                                                    required>
                                                <option value="spark_df">Spark DataFrame</option>
                                                <option value="archive">Archive file</option>
                                            </select>

                            <button type="submit" class="btn btn-success btn-sm">Export Tabular Data </button>

                            </form>

{% endblock %}


text:
import re

from .codes import codes

class Emoji:
  def __init__(self, const):
    if len(const) == 1:
      self.__fromUnicode(const)
    elif const[0] == ":":
      self.__fromAlias(const)
    else:
      self.__fromEscape(const)
    self.aliases = codes[self.escape]
    self.alias = self.aliases[0]
    self.char = bytes("\\u"+self.escape, "ascii").decode("unicode-escape")[0]
    self.is_supported = hex(ord(self.char))[2:] == self.escape

  def __fromUnicode(self, char):
    escape = hex(ord(char))[2:]
    if escape in codes:
      self.escape = escape
    else:
      raise ValueError

  def __fromAlias(self, alias):
    for k, v in codes.items():
      if alias in v:
        self.escape = k
        break
    else:
      raise ValueError

  def __fromEscape(self, escape):
    if escape in codes.keys():
      self.escape = escape
    else:
      raise ValueError

def replaceAliases(text, trailingSpaces=0, force=False):
  """ Replaces all supported emoji-cheat-sheet aliases in a text with the corresponding emoji. """
  def replAlias(m):
    alias = ":"+m.group(1)+":"
    if not Emoji(alias).is_supported and not force:
      return alias
    try:
      return Emoji(alias).char + trailingSpaces * " "
    except ValueError:
      return alias
  return re.sub(":([^s:]?[\w-]+):", replAlias, text)

def replaceEmoji(text, trailingSpaces=0):
  """ Replaces all emojis with their primary emoji-cheat-sheet alias. """
  i = 0
  while i < len(text):
    escape = hex(ord(text[i]))[2:]
    if escape in codes.keys():
      text = text.replace(text[i] + trailingSpaces*" ", Emoji(escape).alias)
      i += len(Emoji(escape).alias)
    else:
      i += 1
  return text


text:
window.onload = () => {
  document.body.addEventListener('wheel', (e) => {
    chrome.test.sendMessage('Seen wheel event');
  });

  chrome.test.sendMessage('Launched');
};


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

namespace Mozu.Api.Urls.Commerce.Orders
{
	public partial class PackageUrl
	{

		/// <summary>
        /// Get Resource Url for GetAvailablePackageFulfillmentActions
        /// </summary>
        /// <param name="orderId">Unique identifier of the order.</param>
        /// <param name="packageId">Unique identifier of the package for which to retrieve the label.</param>
        /// <returns>
        /// String - Resource Url
        /// </returns>
        public static MozuUrl GetAvailablePackageFulfillmentActionsUrl(string orderId, string packageId)
		{
			var url = "/api/commerce/orders/{orderId}/packages/{packageId}/actions";
			var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
			mozuUrl.FormatUrl( "orderId", orderId);
			mozuUrl.FormatUrl( "packageId", packageId);
			return mozuUrl;
		}

		/// <summary>
        /// Get Resource Url for GetPackageLabel
        /// </summary>
        /// <param name="orderId">Unique identifier of the order.</param>
        /// <param name="packageId">Unique identifier of the package for which to retrieve the label.</param>
        /// <returns>
        /// String - Resource Url
        /// </returns>
        public static MozuUrl GetPackageLabelUrl(string orderId, string packageId)
		{
			var url = "/api/commerce/orders/{orderId}/packages/{packageId}/label";
			var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
			mozuUrl.FormatUrl( "orderId", orderId);
			mozuUrl.FormatUrl( "packageId", packageId);
			return mozuUrl;
		}

		/// <summary>
        /// Get Resource Url for GetPackage
        /// </summary>
        /// <param name="orderId">Unique identifier of the order.</param>
        /// <param name="packageId">Unique identifier of the package for which to retrieve the label.</param>
        /// <param name="responseFields">Use this field to include those fields which are not included by default.</param>
        /// <returns>
        /// String - Resource Url
        /// </returns>
        public static MozuUrl GetPackageUrl(string orderId, string packageId, string responseFields =  null)
		{
			var url = "/api/commerce/orders/{orderId}/packages/{packageId}?responseFields={responseFields}";
			var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
			mozuUrl.FormatUrl( "orderId", orderId);
			mozuUrl.FormatUrl( "packageId", packageId);
			mozuUrl.FormatUrl( "responseFields", responseFields);
			return mozuUrl;
		}

				/// <summary>
        /// Get Resource Url for CreatePackage
        /// </summary>
        /// <param name="orderId">Unique identifier of the order.</param>
        /// <param name="responseFields">Use this field to include those fields which are not included by default.</param>
        /// <returns>
        /// String - Resource Url
        /// </returns>
        public static MozuUrl CreatePackageUrl(string orderId, string responseFields =  null)
		{
			var url = "/api/commerce/orders/{orderId}/packages?responseFields={responseFields}";
			var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
			mozuUrl.FormatUrl( "orderId", orderId);
			mozuUrl.FormatUrl( "responseFields", responseFields);
			return mozuUrl;
		}

				/// <summary>
        /// Get Resource Url for UpdatePackage
        /// </summary>
        /// <param name="orderId">Unique identifier of the order.</param>
        /// <param name="packageId">Unique identifier of the package for which to retrieve the label.</param>
        /// <param name="responseFields">Use this field to include those fields which are not included by default.</param>
        /// <returns>
        /// String - Resource Url
        /// </returns>
        public static MozuUrl UpdatePackageUrl(string orderId, string packageId, string responseFields =  null)
		{
			var url = "/api/commerce/orders/{orderId}/packages/{packageId}?responseFields={responseFields}";
			var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
			mozuUrl.FormatUrl( "orderId", orderId);
			mozuUrl.FormatUrl( "packageId", packageId);
			mozuUrl.FormatUrl( "responseFields", responseFields);
			return mozuUrl;
		}

				/// <summary>
        /// Get Resource Url for DeletePackage
        /// </summary>
        /// <param name="orderId">Unique identifier of the order.</param>
        /// <param name="packageId">Unique identifier of the package for which to retrieve the label.</param>
        /// <returns>
        /// String - Resource Url
        /// </returns>
        public static MozuUrl DeletePackageUrl(string orderId, string packageId)
		{
			var url = "/api/commerce/orders/{orderId}/packages/{packageId}";
			var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
			mozuUrl.FormatUrl( "orderId", orderId);
			mozuUrl.FormatUrl( "packageId", packageId);
			return mozuUrl;
		}

	}
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;

namespace Nemo.Validation
{
    public sealed class CustomValidatorContext
    {
        public CustomValidatorContext(object instance, string propertyName)
            : this(instance, propertyName, null)
        { }

        public CustomValidatorContext(object instance, string propertyName, ValidationAttribute validationAttribute)
        {
            this.Instance = instance;
            this.PropertyName = propertyName;
            this.ValidationAttribute = validationAttribute;
        }

        public object Instance { get; private set; }
        public string PropertyName { get; private set; }
        public ValidationAttribute ValidationAttribute { get; private set; }
    }
}


text:
spring-boot-admin
=================
[![Apache License 2](https://img.shields.io/badge/license-ASF2-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0.txt)
[![Build Status](https://travis-ci.org/codecentric/spring-boot-admin.svg?branch=master)](https://travis-ci.org/codecentric/spring-boot-admin)
[![Coverage Status](https://coveralls.io/repos/codecentric/spring-boot-admin/badge.svg)](https://coveralls.io/r/codecentric/spring-boot-admin)
[![Codacy Badge](https://api.codacy.com/project/badge/grade/8fd7bac6edac417a8451387286fe6917)](https://www.codacy.com/app/joshiste/spring-boot-admin)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/de.codecentric/spring-boot-admin/badge.svg)](https://maven-badges.herokuapp.com/maven-central/de.codecentric/spring-boot-admin/)
[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/codecentric/spring-boot-admin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

This is a simple admin interface for [Spring Boot](http://projects.spring.io/spring-boot/ "Official Spring-Boot website") applications.

This application provides a simple GUI to administrate Spring Boot applications in some ways. At the moment it provides the following features for every registered application.

* Show name/id and version number
* Show health status
* Download main logfile
* Show details, like
 * JVM & memory metrics
 * Counter & gauge metrics
 * Datasource metrics
 * Cache metrics
* View Java, system- & environment-properties
* Support for Spring Clouds postable /env- &/refresh-endpoint
* Easy loglevel management (for Logback only)
* Interact with JMX-beans
* View threaddump
* View traces
* Mail and desktop notification on status change
* Event journal of status changes (non persistent)

## Getting Started

[A quick guide](http://codecentric.github.io/spring-boot-admin/1.3.2/#getting-started) to get started can be found in our docs.

## Reference Guide

[Version 1.3.2](http://codecentric.github.io/spring-boot-admin/1.3.2/)

[Version 1.3.0](http://codecentric.github.io/spring-boot-admin/1.3.0/)

## Screenshots

### Dashboard

[](url "title")

### Details

[](url "title")

### Environment

[](url "title")

### Logging

[](url "title")

### JMX

[](url "title")

### Threads

[](url "title")

### Trace

[](url "title")

### Journal

[](url "title")

## Snapshot builds
You can access snapshot builds from the sonatype repository:
```xml
<snapshotRepository>
 <id>sonatype-nexus-snapshots</id>
 <name>Sonatype Nexus Snapshots</name>
 <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</snapshotRepository>
```

## Build
In order to build spring-boot-admin you need to have node.js and npm on your `PATH`.

```shell
mvn clean package
```

## Set version for next release
```shell
mvn versions:set versions:commit -DnewVersion=1.0.0-SNAPSHOT
```


text:
module Fog
  module Compute
    class Ecloud
      class Real
        basic_request :get_users
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" type="text/css" href="commonltr.css"/>
<title>Pig Editor</title>

Sqoop UI

The Sqoop UI enables transfering data from a relational database
to Hadoop and vice versa. The UI lives uses Apache Sqoop to do this.
See the Sqoop Documentation for more details on Sqoop.

Hue, the open source Big Data UI, has an application that enables transferring data between relational databases and Hadoop. This new application is driven by Sqoop 2 and has several user experience improvements to boot.

Sqoop is a batch data migration tool for transferring data between traditional databases and Hadoop. The first version of Sqoop is a heavy client that drives and oversees data transfer via MapReduce. In Sqoop 2, the majority of the work was moved to a server that a thin client communicates with. Also, any client can communicate with the Sqoop 2 server over its JSON-REST protocol. Sqoop 2 was chosen instead of its predecessors because of its client-server design.

Importing from MySQL to HDFS

The following is the canonical import job example sourced from http://sqoop.apache.org/docs/1.99.2/Sqoop5MinutesDemo.html. In Hue, this can be done in 3 easy steps:

Environment

CDH 4.4 or Hue 3.0.0

MySQL 5.1

Troubleshooting

If the new job button is not appearing, Sqoop2 is probably not starting. Make sure the MySql or other DB connectors are in the /usr/lib/sqoop/lib directory of Sqoop2. Make sure you have these properties in the Sqoop2 Server configuration:

org.apache.sqoop.repository.schema.immutable=false
org.apache.sqoop.connector.autoupgrade=true
org.apache.sqoop.framework.autoupgrade=true

1. Create a Connection

In the Sqoop app, the connection manager is available from the "New Job" wizard. To get to the new job wizard, click on "New Job". There may be a list of connections available if a few have been created before. For the purposes of this demo, we'll go through the process of creating a new connection. Click "Add a new connection" and fill in the blanks with the data below. Then click save to return to the "New Job" wizard!

Connection Parameter                  Value

Name                                  mysql-connection-demo

JDBC Driver Class                     com.mysql.jdbc.Driver

JDBC Connection String                jdbc:mysql://hue-demo/demo

Username                              demo

Password                              demo

Connection form values.

2. Create a Job

After creating a connection, follow the wizard and fill in the blanks with the information below.

Job Wizard Parameter              Value

Name                              mysql-import-job-demo

Type                              IMPORT

Connection                        mysql-connection-demo

Table name                        test

Storage Type                      HDFS

Output format                     TEXT_FILE

Output directory                  /tmp/mysql-import-job-demo

Job wizard form values.

3. Save and Submit the Job

At the end of the Job wizard, click "Save and Run"! The job should automagically start after that and the job dashboard will be displayed. As the job is running, a progress bar below the job listing will be dynamically updated. Links to the HDFS output via the File Browser and Map Reduce logs via Job Browser will be available on the left hand side of the job edit page.

Sum Up

The new Sqoop application enables batch data migration from a more traditional databases to Hadoop and vice versa through Hue. Using Hue, a user can move data between storage systems in a distributed fashion with the click of a button.

I'd like to send out a big thank you to the Sqoop community for the new client-server design!

Both projects are undergoing heavy development and are welcoming external contributions! Have any suggestions? Feel free to tell us what you think through hue-user or @gethue!

Installation and Configuration

The Sqoop UI is one of the applications installed as part of
Hue. For information about installing and configuring Hue, see the Hue Installation
manual.

Starting

Click the Sqoop icon
() in the navigation bar at the top of
the Hue browser page.

Sqoop Jobs

Sqoop UI is oriented around jobs in Apache Sqoop.

Creating a New Job

Click the New job button at the top right.

In the Name field, enter a name.

Choose the type of job: import or export.
   The proceeding form fields will change depending on which type is chosen.

Select a connection, or create one if it does not exist.

Fill in the rest of the fields for the job.
   For importing, the "Table name", "Storage type", "Output format", and "Output directory" are necessary at a minimum.
   For exporting, the "Table name" and "Input directory" are necessary at a minimum.

Click save to finish.

Editing a Job

In the list of jobs, click on the name of the job.

Edit the desired form fields in the job.

Copying a Job

In the list of jobs, click on the name of the job.

On the left hand side of the job editor, there should be a panel containing actions.
   Click Copy.

Removing a Job

In the list of jobs, click on the name of the job.

On the left hand side of the job editor, there should be a panel containing actions.
   Click Delete.

Running a Job

There's a status on each of the items in the job list indicating
the last time a job was ran. The progress of the job should dynamically
update. There's a progress bar at the bottom of each item on the job list
as well.

In the list of jobs, click on the name of the job.

On the left hand side of the job editor, there should be a panel containing actions.
   Click Run.

Creating a New Connection

Click the New job button at the top right.

At the connection field, click the link titled Add a new connection.

Fill in the displayed fields.

Click save to finish.

Editing a Connection

Click the New job button at the top right.

At the connection field, select the connection by name that should be edited.

Click Edit.

Edit the any of the fields.

Click save to finish.

Removing a Connection

Click the New job button at the top right.

At the connection field, select the connection by name that should be deleted.

Click Delete.

NOTE: If this does not work, it's like because a job is using that connection.
      Make sure not jobs are using the connection that will be deleted.

Filtering Sqoop Jobs

The text field in the top, left corner of the Sqoop Jobs page enables fast filtering
of sqoop jobs by name.


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Malaxis steinii Dodson

### Remarks
null


text:
$script:keylighter = Join-Path $PSScriptRoot "../keylighter"

. $PSScriptRoot\keylighter.ps1 $script:keylighter


text:
/** The benchmark is distributed under the Creative Commons,
* Attribution-NonCommercial-NoDerivatives. This license includes the benchmark database
* and its derivatives. For attribution, please cite this page, and our publications below.
* This data is provided free of charge for non-commercial and academic benchmarking and
* experimentation use. If you would like to contribute to the benchmark, please contact us.
* If you believe you intended usage may be restricted by the license,
* please contact us and we can discuss the possibilities.
*/

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import javax.speech.synthesis.Synthesizer;

/**
 * Implements a very simplified version of the Emacspeak speech server.
 */
public class EmacspeakProtocolHandler implements Runnable {

    private Socket socket;

    private BufferedReader reader;

    private DataOutputStream writer;

    private Synthesizer synthesizer;

    private static final String PARENS_STAR_REGEX = "[.]*\\[\\*\\][.]*";

    private int lastSpokenCommandType;

    private static final int NOT_HANDLED_COMMAND = 1;

    private static final int LETTER_COMMAND = 2;

    private static final int QUEUE_COMMAND = 3;

    private static final int TTS_SAY_COMMAND = 4;

    private static final int STOP_COMMAND = 5;

    /**
     * Constructs a Emacspeak ProtocolHandler
     *
     * @param freetts the FreeTTS that this EmacspeakProtocolHandler belongs
     * @param socket the Socket that holds the TCP connection
     */
    public EmacspeakProtocolHandler(Socket socket, Synthesizer synthesizer) {
        setSocket(socket);
        this.synthesizer = synthesizer;
    }

    /**
     * Sets the Socket to be used by this ProtocolHandler.
     *
     * @param socket the Socket to be used
     */
    public void setSocket(Socket socket) {
        this.socket = socket;
        if (socket != null) {
            try {
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                writer = new DataOutputStream(socket.getOutputStream());
            } catch (IOException ioe) {
                ioe.printStackTrace();
                throw new Error();
            }
        }
    }

    /**
     * Returns true if the given input string starts with the given
     * starting and ending sequence.
     *
     * @param start the starting character sequence
     * @param end the ending character sequence
     *
     * @return true if the input string matches the given Pattern;
     *         false otherwise
     */
    private static boolean matches(String start, String end, String input) {
        return (input.startsWith(start) && input.endsWith(end));
    }

    /**
     * Returns the type of the given command.
     *
     * @param command the command from emacspeak
     *
     * @return the command type
     */
    private static int getCommandType(String command) {
        int type = NOT_HANDLED_COMMAND;
        if (matches("l {", "}", command)) {
            type = LETTER_COMMAND;
        } else if (matches("q {", "}", command)) {
            type = QUEUE_COMMAND;
        } else if (matches("tts_say", "}", command)) {
            type = TTS_SAY_COMMAND;
        } else if (command.equals("s")) {
            type = STOP_COMMAND;
        }
        return type;
    }

    /**
     * Returns the text of the given input that is within curly brackets.
     *
     * @param input the input text
     *
     * @return text within curly brackets
     */
    public String textInCurlyBrackets(String input) {
        String result = "";
        if (input.length() > 0) {
            int first = input.indexOf('{');
            int last = input.lastIndexOf('}');
            if (first != -1 && last != -1 && first < last) {
                result = input.substring(first + 1, last);
            }
        }
        return result;
    }

    /**
     * Speaks the given input text.
     *
     * @param input the input text to speak.
     */
    private void speak(String input) {
        String[] parts = input.split(PARENS_STAR_REGEX);
        for (int i = 0; i < parts.length; i++) {
            System.out.println(parts[i]);
            synthesizer.speakPlainText(parts[i], null);
        }
    }

    /**
     * Implements the run() method of Runnable
     */
    public void run() {
        try {
            String command = "";
            while (true) {
                command = reader.readLine();
                if (command != null) {
                    command = command.trim();
                    System.out.println("IN   : " + command);
                    int commandType = getCommandType(command);
                    if (commandType == STOP_COMMAND) {
                        synthesizer.cancelAll();
                    } else if (commandType != NOT_HANDLED_COMMAND) {
                        String content = textInCurlyBrackets(command).trim();
                        speak(content);
                        System.out.println("SPEAK: \"" + content + "\"");
                        lastSpokenCommandType = commandType;
                    } else {
                        System.out.println("SPEAK:");
                    }
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}


text:
dash9/driver.cpp
dash9/dist.cpp
dash9/main.cpp
dash9/pulse.cpp
dash9/speed.cpp