text:
@interface ReceiveViewController ()
<
UINavigationControllerDelegate,
UITableViewDelegate,
UITableViewDataSource,
UITextFieldDelegate
>

@property (nonatomic, strong) UIView *noOrderView;
@property (nonatomic, strong) UIView *noNetWorkingView;
@property (nonatomic, strong) UIView *noSearchResultView;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, strong) OrderModel *orderModel;
@property (nonatomic, strong) NSMutableArray *dicList;

@property (nonatomic, strong) UITableView *searchResultTableView;
@property (nonatomic, strong) UIView *searchResultView;
@property (nonatomic, strong) UITextField *textfield;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *searchButton;
@property (nonatomic, strong) UIView *whiteView;
@property (nonatomic, strong) NSMutableArray *searchResultList;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger searchPage;
@property (nonatomic, strong) UIActivityIndicatorView *activityView;
@property (nonatomic, strong) UIActivityIndicatorView *searchActivityView;

@property (nonatomic, strong) AFHTTPSessionManager *manager;
@property (nonatomic, assign, getter = isSelected) BOOL selected;
@property (nonatomic, assign) NSInteger flag;
@end

@implementation ReceiveViewController

- (UIActivityIndicatorView *)activityView {
    if (!_activityView) {
        _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activityView.center = CGPointMake(self.view.center.x, self.view.center.y - 40);
    }
    return _activityView;
}

- (UIActivityIndicatorView *)searchActivityView {
    if (!_searchActivityView) {
        _searchActivityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _searchActivityView.center = CGPointMake(self.view.center.x, self.view.center.y - 40);
    }
    return _searchActivityView;
}

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

        self.tabBarItem.title = @"待接收";
        self.tabBarItem.image = [UIImage imageNamed:@"drawable_no_select_djs"];
        self.tabBarItem.selectedImage = [UIImage imageNamed:@"drawable_select_djs.png"];
        self.selected = NO;
    }
    return self;
}

- (NSMutableArray *)dicList {
    if (!_dicList) {
        _dicList = [NSMutableArray array];
    }
    return _dicList;
}

- (NSMutableArray *)searchResultList {
    if (!_searchResultList) {
        _searchResultList = [NSMutableArray array];
    }
    return _searchResultList;
}

- (UITableView *)tableView {
    if (!_tableView) {

        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,SearchBarHeight, Width, Height - StatusBarAndNavigationBarHeight - TabbarHeight - SearchBarHeight) style:UITableViewStylePlain];
        _tableView.tag = 300;
        _tableView.tableFooterView = [[UIView alloc]init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.alpha = 0;
        __weak typeof(self) weakSelf = self;
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [weakSelf loadMoreData];
        }];

    }
    return _tableView;
}

- (UITableView *)searchResultTableView {
    if (!_searchResultTableView) {

        _searchResultTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,SearchBarHeight, Width, Height - StatusBarAndNavigationBarHeight - TabbarHeight - SearchBarHeight) style:UITableViewStylePlain];
        _searchResultTableView.tag = 500;
        _searchResultTableView.tableFooterView = [[UIView alloc]init];
        _searchResultTableView.delegate = self;
        _searchResultTableView.dataSource = self;
        _searchResultTableView.alpha = 0;
        __weak typeof(self) weakSelf = self;
        _searchResultTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [weakSelf loadMoreSearchData];
        }];

    }
    return _searchResultTableView;
}

- (UIView *)searchResultView {

    if (!_searchResultView) {

        _searchResultView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Width, Height - StatusBarAndNavigationBarHeight - TabbarHeight)];
        _searchResultView.backgroundColor = [UIColor whiteColor];
        _searchResultView.alpha = 0;

        UIView *containerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Width, SearchBarHeight)];
        containerView.backgroundColor = color(235, 235, 235, 1);
        [_searchResultView addSubview:containerView];

        self.whiteView = [[UIView alloc]initWithFrame:CGRectMake(8, 7, Width - 16, SearchBarHeight - 14)];
        self.whiteView.backgroundColor = [UIColor whiteColor];
        self.whiteView.layer.cornerRadius = 5;
        self.whiteView.layer.masksToBounds = YES;
        [containerView addSubview:self.whiteView];

        self.searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.searchButton setTitle:@" 客户姓名/客户电话" forState:UIControlStateNormal];
        [self.searchButton setTitleColor:color(100, 100, 100, 1) forState:UIControlStateNormal];

        CGFloat fontSize;
        if (iPhone6 || iPhone6_plus) {
            fontSize = 16;
        }else{
            fontSize = 14;
        }
        self.searchButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        self.searchButton.titleLabel.font = font(fontSize);
        self.searchButton.backgroundColor = [UIColor whiteColor];
        self.searchButton.frame = CGRectMake(8, 7, Width - 60, SearchBarHeight - 14);
        self.searchButton.layer.cornerRadius = 5;
        self.searchButton.layer.masksToBounds = YES;
        [containerView addSubview:self.searchButton];

        self.textfield = [[UITextField alloc]initWithFrame:CGRectMake(8, 7, Width - 60, SearchBarHeight - 14)];
        self.textfield.backgroundColor = [UIColor clearColor];
        self.textfield.clearsOnBeginEditing = YES;
        self.textfield.keyboardType = UIKeyboardTypeWebSearch;
        self.textfield.delegate = self;
        //监听textfield的text时时变化
        self.textfield.font = font(fontSize);
        [self.textfield addTarget:self action:@selector(editingChanged:) forControlEvents:UIControlEventEditingChanged];
        [containerView addSubview:self.textfield];

        self.cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [self.cancelButton setTitleColor:beautifulBlueColor forState:UIControlStateNormal];
        [self.cancelButton setTitleColor:color(240, 240, 240, 1) forState:UIControlStateHighlighted];
        [self.cancelButton addTarget:self action:@selector(cancelButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        CGFloat fontsize;
        if (iPhone6 || iPhone6_plus) {
            fontsize = 18;
        }else{
            fontsize = 16;
        }
        self.cancelButton.titleLabel.font = font(fontsize);
        self.cancelButton.frame = CGRectMake(Width, 7, 60, 30);
        [_searchResultView addSubview:self.cancelButton];

        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, SearchBarHeight - 0.7, Width, 0.7)];
        line.backgroundColor = color(210, 210, 210, 1);
        [_searchResultView addSubview:line];
        [_searchResultView addSubview:self.searchActivityView];
    }
    return _searchResultView;
}

- (void)editingChanged:(UITextField *)sender {
    if (![sender.text isEqualToString:@""]) {
        self.searchButton.titleLabel.text = @"";
    }else{
        self.searchButton.titleLabel.text = @" 客户姓名/客户电话";
    }

    if (self.searchResultList.count) {
        [self.searchResultList removeAllObjects];
    }
}

- (UIView *)noOrderView {
    if (!_noOrderView) {
        _noOrderView = [[UIView alloc]initWithFrame:CGRectMake(0, SearchBarHeight, Width, Height - StatusBarAndNavigationBarHeight - TabbarHeight - SearchBarHeight)];
        _noOrderView.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"loding_wrong"]];
        imageView.center = CGPointMake(Width/2, _noOrderView.center.y - imageView.bounds.size.height/2 - 25);
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, Width, 50)];
        label.center = _noOrderView.center;
        label.text = @"无待接收订单";
        label.font = font(18);
        label.textAlignment = NSTextAlignmentCenter;
        [_noOrderView addSubview:imageView];
        [_noOrderView addSubview:label];

    }
    return _noOrderView;
}

- (UIView *)noNetWorkingView {

    if (!_noNetWorkingView) {
        _noNetWorkingView = [[UIView alloc]initWithFrame:CGRectMake(0, SearchBarHeight, Width, Height - StatusBarAndNavigationBarHeight - TabbarHeight - SearchBarHeight)];
        _noNetWorkingView.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"loding_wrong"]];
        imageView.center = CGPointMake(Width/2, _noNetWorkingView.center.y - imageView.bounds.size.height/2 - 25);
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, Width, 50)];
        label.center = _noNetWorkingView.center;
        label.text = @"请检查网络";
        label.font = font(18);
        label.textAlignment = NSTextAlignmentCenter;
        [_noNetWorkingView addSubview:imageView];
        [_noNetWorkingView addSubview:label];

    }
    return _noNetWorkingView;
}

- (UIView *)noSearchResultView {
    if (!_noSearchResultView) {
        _noSearchResultView = [[UIView alloc]initWithFrame:CGRectMake(0, SearchBarHeight, Width, Height - StatusBarAndNavigationBarHeight - TabbarHeight - SearchBarHeight)];
        _noSearchResultView.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"loding_wrong"]];
        imageView.center = CGPointMake(Width/2, _noSearchResultView.center.y - imageView.bounds.size.height/2 - 25);
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, Width, 50)];
        label.center = _noSearchResultView.center;
        label.text = @"无搜索结果";
        label.font = font(18);
        label.textAlignment = NSTextAlignmentCenter;
        [_noSearchResultView addSubview:imageView];
        [_noSearchResultView addSubview:label];
    }
    return _noSearchResultView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setNaviTitle];
    [self setSearchButton];
    [self.view addSubview:self.activityView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(badgeValueChanged:) name:kBadgeValueChanged object:nil];
}

- (void)badgeValueChanged:(NSNotification *)noti {
    UIViewController *receiveVC = [self.tabBarController viewControllers][1];
    UIViewController *completeVC = [self.tabBarController viewControllers][2];
    UIViewController *robVC = [self.tabBarController viewControllers][3];
    UIViewController *allorderVC = [self.tabBarController viewControllers][4];

    UserModel *userModel = [UserModel readUserModel];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
#if Environment_Mode == 1
    NSString *countString = [NSString stringWithFormat:@"%@Task.ashx?action=gettaskcount&comid=%ld&uid=%ld&provinceid=%ld&cityid=%ld&districtid=%ld",HomeURL,(long)userModel.comid,(long)userModel.uid,(long)userModel.provinceid,(long)userModel.cityid,(long)userModel.districtid];
#elif Environment_Mode == 2
    NSString *countString = [NSString stringWithFormat:@"%@Task.ashx?action=gettaskcount&comid=%ld&uid=%ld&handler_name=%@&provinceid=%ld&cityid=%ld&districtid=%ld",HomeURL,(long)userModel.comid,(long)userModel.uid,userModel.name,(long)userModel.provinceid,(long)userModel.cityid,(long)userModel.districtid];
    countString = [countString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
#endif
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [manager GET:countString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSString *allString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSArray *countList = [allString componentsSeparatedByString:@","];

        [[NSUserDefaults standardUserDefaults] setObject:countList forKey:@"countList"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if (((NSArray *)[[NSUserDefaults standardUserDefaults] objectForKey:@"countList"]).lastObject) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kupdateBadgeNum object:nil];
        }
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][1] isEqualToString:@"0"]) {

            receiveVC.tabBarItem.badgeValue = nil;
        }else{
            receiveVC.tabBarItem.badgeValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][1];
        }

        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][2] isEqualToString:@"0"]) {
            completeVC.tabBarItem.badgeValue = nil;
        }else{
            completeVC.tabBarItem.badgeValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][2];
        }

#if Environment_Mode == 1
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][3] isEqualToString:@"0"]) {
            robVC.tabBarItem.badgeValue = nil;
        }else{
            robVC.tabBarItem.badgeValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][3];
        }
#elif Environment_Mode == 2
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][4] isEqualToString:@"0"]) {
            robVC.tabBarItem.badgeValue = nil;
        }else{
            robVC.tabBarItem.badgeValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][4];
        }
#endif

        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][0] isEqualToString:@"0"]) {
            allorderVC.tabBarItem.badgeValue = nil;
        }else{
            allorderVC.tabBarItem.badgeValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][0];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];
}

- (void)setSearchButton {

    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchButton setTitle:@" 客户姓名/客户电话" forState:UIControlStateNormal];
    searchButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [searchButton setTitleColor:color(150, 150, 150, 1) forState:UIControlStateNormal];
    [searchButton setTitleColor:color(200, 200, 200, 0.8) forState:UIControlStateHighlighted];
    [searchButton addTarget:self action:@selector(searchButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    searchButton.layer.cornerRadius = 5;
    searchButton.layer.masksToBounds = YES;

    CGFloat fontSize;
    if (iPhone6 || iPhone6_plus) {
        fontSize = 16;
    }else{
        fontSize = 14;
    }

    searchButton.titleLabel.font = font(fontSize);
    searchButton.backgroundColor = color(235, 235, 235, 1);
    searchButton.frame = CGRectMake(8, 7, Width - 16, SearchBarHeight - 14);
    [self.view addSubview:searchButton];

    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, SearchBarHeight - 0.7, Width, 0.7)];
    line.backgroundColor = color(210, 210, 210, 1);
    [self.view addSubview:line];

}

- (void)searchButtonClicked:(UIButton *)sender {
    [self.view addSubview:self.searchResultView];
    self.flag = 1;
    [UIView animateWithDuration:0.4 animations:^{
        self.searchResultView.alpha = 1;

        CGRect frame = self.whiteView.frame;
        frame.size.width = Width - 60;
        self.whiteView.frame = frame;
        self.cancelButton.frame = CGRectMake(Width - 55, 7, 60, 30);
        [self.textfield becomeFirstResponder];
    } completion:^(BOOL finished) {

    }];
}

- (void)cancelButtonClicked:(UIButton *)sender {
    self.searchPage = 1;
    self.flag = 0;

    [UIView animateWithDuration:0.5 animations:^{
        self.tableView.alpha = 1;
        self.searchResultView.alpha = 0;
        [self.textfield resignFirstResponder];
        CGRect frame = self.whiteView.frame;
        frame.size.width = Width - 16;
        self.whiteView.frame = frame;
        self.cancelButton.frame = CGRectMake(Width, 7, 60, 30);

    } completion:^(BOOL finished) {
        [self.searchResultView removeFromSuperview];
        self.searchResultView = nil;
    }];

}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [viewController viewWillAppear:animated];

}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [viewController viewDidDisappear:animated];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.dicList.count) {
        [self.dicList removeAllObjects];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (_noOrderView) {
        [self.noOrderView removeFromSuperview];
        self.noOrderView = nil;
    }
    if (_noNetWorkingView) {
        [self.noNetWorkingView removeFromSuperview];
        self.noNetWorkingView = nil;
    }
    self.flag = 0;
    self.page = 1;
    self.searchPage = 1;
    [self setBadgeValue];
    [self.activityView startAnimating];
    [self loadNewDate];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.manager.operationQueue cancelAllOperations];
    if (_searchResultView) {
        CGRect frame = self.whiteView.frame;
        frame.size.width = Width - 16;
        self.whiteView.frame = frame;
        self.cancelButton.frame = CGRectMake(Width, 7, 60, 30);
        [self.searchResultView removeFromSuperview];
        self.searchResultView = nil;
    }

    if (_noOrderView) {
        [self.noOrderView removeFromSuperview];
        self.noOrderView = nil;
    }
    if (_noNetWorkingView) {
        [self.noNetWorkingView removeFromSuperview];
        self.noNetWorkingView = nil;
    }

    [self.tableView removeFromSuperview];
    self.tableView = nil;
    if (self.dicList.count) {
        [self.dicList removeAllObjects];
    }
}

- (void)viewDidDisappear:(BOOL)animated {

    [super viewDidDisappear:animated];
    [self.manager.operationQueue cancelAllOperations];
    if (self.dicList.count) {
        [self.dicList removeAllObjects];
        self.dicList = nil;
    }
}

- (void)loadNewDate {
    [self netWorking];
}

- (void)loadMoreData {
    self.page ++;
    [self netWorking];
}

- (void)netWorking {

    self.manager = [AFHTTPSessionManager manager];
    UserModel *userModel = [UserModel readUserModel];
#if Environment_Mode == 1
    NSString *URL = [NSString stringWithFormat:@"%@Task.ashx?action=getlist&comid=%ld&uid=%ld&state=4&page=%ld&query=&provinceid=%ld&cityid=%ld&districtid=%ld",HomeURL,(long)userModel.comid,(long)userModel.uid,(long)self.page,(long)userModel.provinceid,(long)userModel.cityid,(long)userModel.districtid];
#elif Environment_Mode == 2
    NSString *URL = [NSString stringWithFormat:@"%@Task.ashx?action=getlist&comid=%ld&uid=%ld&handler_name=%@&state=4&page=%ld&query=&provinceid=%ld&cityid=%ld&districtid=%ld",HomeURL,(long)userModel.comid,(long)userModel.uid, userModel.name, (long)self.page,(long)userModel.provinceid,(long)userModel.cityid,(long)userModel.districtid];
    URL = [URL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
#endif
    self.manager.requestSerializer.timeoutInterval = 5;

    [self.manager GET:URL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"ResponseInfo"][0][@"PageCount"] forKey:@"PageCount"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self.activityView stopAnimating];
        for (NSDictionary *dic in responseObject[@"task"]) {
            OrderModel *ordelModel = [OrderModel orderFromDictionary:dic];
            [self.dicList addObject:ordelModel];
        }

        if (!self.dicList.count) {
            [self.view addSubview:self.noOrderView];
            return ;
        }
        [self.view addSubview:self.tableView];
        if (self.flag != 1) {
            [UIView animateWithDuration:0.3 animations:^{
                self.tableView.alpha = 1;
            }];
        }
        [self.tableView reloadData];

        if ([responseObject[@"ResponseInfo"][0][@"PageNow"] integerValue] == [responseObject[@"ResponseInfo"][0][@"PageRowCount"] integerValue]) {
            [self.tableView.mj_footer endRefreshing];
            self.tableView.mj_footer.hidden = YES;
            return ;
        }else {
            self.tableView.mj_footer.hidden = NO;
        }

        [self.tableView.mj_footer endRefreshing];

        return ;

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error.userInfo);
        [self.manager.operationQueue cancelAllOperations];
        [self.tableView.mj_footer endRefreshing];
        [self.activityView stopAnimating];

        [self.view addSubview:self.noNetWorkingView];
        self.tableView.mj_footer.hidden = YES;
        return ;
    }];
}

#pragma mark - UITableViewDelegate And DataSource -

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (tableView.tag == 300) {
        NSInteger count = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PageCount"] integerValue];
        if (self.dicList.count <= count) {
            return self.dicList.count;
        }else {
            return count;
        }
    }else{
        return self.searchResultList.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
#if Environment_Mode == 1
    static NSString *identifier = @"Cell";
    MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"MainTableViewCell" owner:self options:nil].lastObject;
    }

    if (tableView.tag == 300) {
        self.orderModel = self.dicList[indexPath.row];
    }else{
        self.orderModel = self.searchResultList[indexPath.row];
    }

    cell.acceptDateLabel.text = self.orderModel.acceptDate;
    cell.dateLabel.text = self.orderModel.date;

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ %@",self.orderModel.serviceType, self.orderModel.productType]];

    [attributedString addAttributes:@{NSForegroundColorAttributeName:color(248, 89, 34, 1)}range:[self.orderModel.serviceType rangeOfString:self.orderModel.serviceType]];
    cell.productTypeLabel.attributedText = attributedString;
    cell.nameLabel.text = self.orderModel.name;
    cell.phoneLabel.text = self.orderModel.phone;
    cell.locationLabel.text = self.orderModel.location;
    cell.assessLabel.text = self.orderModel.assess;
    cell.priceLabel.text = self.orderModel.price;
    cell.areaLabel.text = self.orderModel.area;
    cell.robButton.hidden = YES;
#elif Environment_Mode == 2
    static NSString *identifier = @"Cell";
    CSMainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"CSMainTableViewCell" owner:self options:nil].lastObject;

    }

    if (tableView.tag == 300) {
        self.orderModel = self.dicList[indexPath.row];
    }else{
        self.orderModel = self.searchResultList[indexPath.row];
    }

    cell.dateLabel.text = self.orderModel.date;

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ %@",self.orderModel.serviceType, self.orderModel.productType]];

    [attributedString addAttributes:@{NSForegroundColorAttributeName:color(248, 89, 34, 1)} range:[self.orderModel.serviceType rangeOfString:self.orderModel.serviceType]];
    cell.productTypeLabel.attributedText = attributedString;
    cell.nameLabel.text = self.orderModel.name;
    cell.phoneLabel.text = self.orderModel.phone;
    cell.locationLabel.text = self.orderModel.location;
    cell.assessLabel.text = self.orderModel.assess;
    cell.areaLabel.text = self.orderModel.area;

#endif
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isSelected) {
        return;
    }else {

        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        DetailViewController *detailVC = [[DetailViewController alloc] init];
        detailVC.hidesBottomBarWhenPushed = YES;

        if (tableView.tag == 300) {
            self.orderModel = self.dicList[indexPath.row];
        }else{
            self.orderModel = self.searchResultList[indexPath.row];
        }
        detailVC.ID = self.orderModel.ID;
        detailVC.state = [self.orderModel.state integerValue];

        detailVC.name = self.orderModel.name;
        detailVC.phone = self.orderModel.phone;
        detailVC.from = [NSString stringWithFormat:@"来源:%@",self.orderModel.fromUserName];
        detailVC.fromPhone = [NSString stringWithFormat:@"厂商电话:%@",self.orderModel.fromUserPhone];
        detailVC.price = [NSString stringWithFormat:@"价格:%@",self.orderModel.price];
        detailVC.location = self.orderModel.location;

        detailVC.productType = self.orderModel.productType;
        detailVC.model = self.orderModel.model;
        detailVC.buyDate = self.orderModel.buyDate;
        detailVC.productCode = self.orderModel.productCode;
        detailVC.orderCode = self.orderModel.orderCode;
        detailVC.inOut = self.orderModel.inOut;

        detailVC.serviceType = self.orderModel.serviceType;
        detailVC.appointment = self.orderModel.appointment;
        detailVC.servicePs = self.orderModel.postScript;
        detailVC.chargeBackContent = self.orderModel.chargeBackContent;
        detailVC.waiterName = self.orderModel.WaiterName;
        detailVC.fromUserID = self.orderModel.FromUserID;
        detailVC.fromUserName = self.orderModel.fromUserName;
        detailVC.toUserID = self.orderModel.ToUserID;
        detailVC.toUserName = self.orderModel.ToUserName;
        detailVC.BuyerFullAddress_Incept = self.orderModel.BuyerFullAddress_Incept;
        detailVC.payMoneyStr = self.orderModel.PayMoney;
        detailVC.priceStr = self.orderModel.price;
        detailVC.overPs = self.orderModel.FinishRemark;

#if Environment_Mode == 1
        self.selected = YES;
        NSString *url = [NSString stringWithFormat:@"%@/Common.ashx?action=get_finish_require&&comid=%@",HomeURL,detailVC.fromUserID];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            detailVC.settleAccount = str;
            self.selected = NO;
            [self.navigationController pushViewController:detailVC animated:YES];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            self.selected = NO;
        }];
#elif Environment_Mode == 2
        [self.navigationController pushViewController:detailVC animated:YES];
#endif

    }

}

#pragma mark - UITextFieldDelegate -
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    if (_noSearchResultView) {
        [self.noSearchResultView removeFromSuperview];
        self.noSearchResultView = nil;
    }

    if (_searchResultTableView) {
        [self.searchResultTableView removeFromSuperview];
        self.searchResultTableView = nil;
    }

    [self.searchActivityView startAnimating];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    UserModel *userModel = [UserModel readUserModel];
#if Environment_Mode == 1
    NSString *URL = [NSString stringWithFormat:@"%@Task.ashx?action=getlist&comid=%ld&uid=%ld&state=4&page=%ld&query=%@&provinceid=%ld&cityid=%ld&districtid=%ld",HomeURL,(long)userModel.comid,(long)userModel.uid,(long)self.page,textField.text,(long)userModel.provinceid,(long)userModel.cityid,(long)userModel.districtid];
#elif Environment_Mode == 2
    NSString *URL = [NSString stringWithFormat:@"%@Task.ashx?action=getlist&comid=%ld&uid=%ld&handler_name=%@&state=4&page=%ld&query=%@&provinceid=%ld&cityid=%ld&districtid=%ld",HomeURL,(long)userModel.comid,(long)userModel.uid, userModel.name, (long)self.page,textField.text,(long)userModel.provinceid,(long)userModel.cityid,(long)userModel.districtid];
#endif
    //297错误,URL中有中文,需转码
    URL = [URL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    manager.requestSerializer.timeoutInterval = 5;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [manager.operationQueue cancelAllOperations];
    });

    [manager GET:URL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [self.searchActivityView stopAnimating];
        if (self.searchResultList.count != 0) {
            [self.searchResultList removeAllObjects];
        }
        for (NSDictionary *dic in responseObject[@"task"]) {
            OrderModel *ordelModel = [OrderModel orderFromDictionary:dic];
            [self.searchResultList addObject:ordelModel];
        }

        if (!self.searchResultList.count) {
            [self.searchResultView addSubview:self.noSearchResultView];
            return ;
        }
        [self.searchResultView addSubview:self.searchResultTableView];
        [UIView animateWithDuration:0.3 animations:^{
            self.searchResultTableView.alpha = 1;
        }];
        [self.searchResultTableView reloadData];

        if ([responseObject[@"ResponseInfo"][0][@"PageNow"] integerValue] == [responseObject[@"ResponseInfo"][0][@"PageRowCount"] integerValue]) {
            [self.searchResultTableView.mj_footer endRefreshing];
            self.searchResultTableView.mj_footer.hidden = YES;
            return ;
        }else {
            self.searchResultTableView.mj_footer.hidden = NO;
        }

        [self.searchResultTableView.mj_footer endRefreshing];

        return ;

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [self.searchResultTableView.mj_footer endRefreshing];

        [self.searchActivityView stopAnimating];
        [self.searchResultView addSubview:self.noNetWorkingView];
        self.searchResultTableView.mj_footer.hidden = YES;
        return ;
    }];

    return YES;
}

- (void)loadMoreSearchData {
    self.searchPage ++;

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    UserModel *userModel = [UserModel readUserModel];
#if Environment_Mode == 1
    NSString *URL = [NSString stringWithFormat:@"%@Task.ashx?action=getlist&comid=%ld&uid=%ld&state=4&page=%ld&query=%@&provinceid=%ld&cityid=%ld&districtid=%ld",HomeURL,(long)userModel.comid,(long)userModel.uid,(long)self.searchPage,self.textfield.text,(long)userModel.provinceid,(long)userModel.cityid,(long)userModel.districtid];
#elif Environment_Mode == 2
    NSString *URL = [NSString stringWithFormat:@"%@Task.ashx?action=getlist&comid=%ld&uid=%ld&handler_name=%@&state=4&page=%ld&query=%@&provinceid=%ld&cityid=%ld&districtid=%ld",HomeURL,(long)userModel.comid,(long)userModel.uid, userModel.name, (long)self.searchPage,self.textfield.text,(long)userModel.provinceid,(long)userModel.cityid,(long)userModel.districtid];
#endif
    //297错误,URL中有中文,需转码
    URL = [URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    manager.requestSerializer.timeoutInterval = 5;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [manager.operationQueue cancelAllOperations];
    });

    [manager GET:URL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [self.searchActivityView stopAnimating];
        for (NSDictionary *dic in responseObject[@"task"]) {
            OrderModel *ordelModel = [OrderModel orderFromDictionary:dic];
            [self.searchResultList addObject:ordelModel];
        }

        if (!self.searchResultList.count) {
            [self.searchResultView addSubview:self.noSearchResultView];
            return ;
        }
        [self.searchResultView addSubview:self.searchResultTableView];
        [self.searchResultTableView reloadData];
        if ([responseObject[@"ResponseInfo"][0][@"PageNow"] integerValue] == [responseObject[@"ResponseInfo"][0][@"PageRowCount"] integerValue]) {
            [self.searchResultTableView.mj_footer endRefreshing];
            self.searchResultTableView.mj_footer.hidden = YES;
            return ;
        }else {
            self.searchResultTableView.mj_footer.hidden = NO;
        }
        [self.searchResultTableView.mj_footer endRefreshing];

        return ;

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [self.searchResultTableView.mj_footer endRefreshing];
        [self.searchActivityView stopAnimating];
        [self.searchResultView addSubview:self.noNetWorkingView];
        self.searchResultTableView.mj_footer.hidden = YES;
        return ;

    }];

}

- (void)setNaviTitle {
    self.navigationItem.title = @"待接收";
}

- (void)setBadgeValue {
    UIViewController *receiveVC = [self.tabBarController viewControllers][1];
    UIViewController *completeVC = [self.tabBarController viewControllers][2];
    UIViewController *robVC = [self.tabBarController viewControllers][3];
    UIViewController *allorderVC = [self.tabBarController viewControllers][4];

    UserModel *userModel = [UserModel readUserModel];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
#if Environment_Mode == 1
    NSString *countString = [NSString stringWithFormat:@"%@Task.ashx?action=gettaskcount&comid=%ld&uid=%ld&provinceid=%ld&cityid=%ld&districtid=%ld",HomeURL,(long)userModel.comid,(long)userModel.uid,(long)userModel.provinceid,(long)userModel.cityid,(long)userModel.districtid];
#elif Environment_Mode == 2
    NSString *countString = [NSString stringWithFormat:@"%@Task.ashx?action=gettaskcount&comid=%ld&uid=%ld&handler_name=%@&provinceid=%ld&cityid=%ld&districtid=%ld",HomeURL,(long)userModel.comid,(long)userModel.uid,userModel.name,(long)userModel.provinceid,(long)userModel.cityid,(long)userModel.districtid];
    countString = [countString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
#endif
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [manager GET:countString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSString *allString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSArray *countList = [allString componentsSeparatedByString:@","];

        [[NSUserDefaults standardUserDefaults] setObject:countList forKey:@"countList"];
        [[NSUserDefaults standardUserDefaults] synchronize];

        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][1] isEqualToString:@"0"]) {

            receiveVC.tabBarItem.badgeValue = nil;
        }else{
            receiveVC.tabBarItem.badgeValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][1];
        }

        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][2] isEqualToString:@"0"]) {
            completeVC.tabBarItem.badgeValue = nil;
        }else{
            completeVC.tabBarItem.badgeValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][2];
        }

#if Environment_Mode == 1
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][3] isEqualToString:@"0"]) {
            robVC.tabBarItem.badgeValue = nil;
        }else{
            robVC.tabBarItem.badgeValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][3];
        }
#elif Environment_Mode == 2
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][4] isEqualToString:@"0"]) {
            robVC.tabBarItem.badgeValue = nil;
        }else{
            robVC.tabBarItem.badgeValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][4];
        }
#endif

        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][0] isEqualToString:@"0"]) {
            allorderVC.tabBarItem.badgeValue = nil;
        }else{
            allorderVC.tabBarItem.badgeValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"countList"][0];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];

}

@end


text:
SELECT concept_id
FROM concept AS c
WHERE c.concept_code = '311670'
  AND c.invalid_reason IS NULL
  AND c.domain_id = 'Drug'

redpajama_set_name: RedPajamaGithub


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_src_wchar_t_cpy_73b.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_src.label.xml
Template File: sources-sink-73b.tmpl.cpp
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource:  Initialize data as a large string
 * GoodSource: Initialize data as a small string
 * Sinks: cpy
 *    BadSink : Copy data to string using wcscpy
 * Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files
 *
 * */

#include "std_testcase.h"
#include <list>

#include <wchar.h>

using namespace std;

namespace CWE122_Heap_Based_Buffer_Overflow__c_src_wchar_t_cpy_73
{

#ifndef OMITBAD

void badSink(list<wchar_t *> dataList)
{
    /* copy data out of dataList */
    wchar_t * data = dataList.back();
    {
        wchar_t dest[50] = L"";
        /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
        wcscpy(dest, data);
        printWLine(data);
        free(data);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<wchar_t *> dataList)
{
    wchar_t * data = dataList.back();
    {
        wchar_t dest[50] = L"";
        /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
        wcscpy(dest, data);
        printWLine(data);
        free(data);
    }
}

#endif /* OMITGOOD */

} /* close namespace */


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

                «

    <p class="styleSans17.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans24.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">'C
Cpptinental
SOURCE-S

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">December 30, 2014

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Industrial Commission of North Dakota Oil & Gas Division
600 East Boulevard, Dept 405 Bismarck, North Dakota 58505
Re: Sorenson 3—16H

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Please charge the Continental Resources, Inc. credit card that is on file with your agency for the application fee of this well.
Please Note: A request for a legal street address has been sent to Ken Halvorson on December 30,
2014 at kenh@co.mountrail.nd.us for this well site location/well facility and the proposed road access to the nearest existing public road in accordance with NDAC 43—02-03-16.
Thank you for your prompt attention to this matter. If you have any questions, you may contact me at (405) 234-9139 or by email at terry.olson@clr.com

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Sincerely,

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">CONTINENTAL RESOURCES, INC.

    <p class="styleSans21.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">W aur— TeITy L. son
Regulatory Compliance Specialist

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">405-234—9000 www.clr.com

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
// [START kms_destroy_key_version]

using Google.Cloud.Kms.V1;

public class DestroyKeyVersionSample
{
    public CryptoKeyVersion DestroyKeyVersion(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key version name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Call the API.
        CryptoKeyVersion result = client.DestroyCryptoKeyVersion(keyVersionName);

        // Return the result.
        return result;
    }
}
// [END kms_destroy_key_version]


text:
'use strict';

var _commander = require('commander');

var _commander2 = _interopRequireDefault(_commander);

var _package = require('../package.json');

var _commands = require('./commands');

var _config_utils = require('./config_utils.js');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

_commander2.default.version(_package.version);

_commander2.default.command('generate [type] [name]').alias('g').description('generate an entity with the name provided').action(function (type, name, options) {
  var customConfig = (0, _config_utils.readCustomConfig)();
  (0, _commands.generate)(type, name, options, customConfig);
}).on('--help', function () {
  console.log('  Choose from the following generator types:');
  console.log('  component, container, module');
  console.log('');
  console.log('  You need to provide module name for component, and container');
  console.log("  Format your 'name' argument in the form of moduleName:entityName");
  console.log('');
  console.log('  e.g. `bija generate action core:post`');
});

_commander2.default.command('destroy [type] [name]').alias('d').description('delete files generated for the given type and name').action(function (type, name, options) {
  var customConfig = (0, _config_utils.readCustomConfig)();
  (0, _commands.destroy)(type, name, options, customConfig);
});

_commander2.default.parse(process.argv);


text:
import mock
import pytest

from pushkin.sender.nordifier import constants
from pushkin.sender import sender_manager

APN = 'pushkin.sender.senders.ApnNotificationSender'
GCM = 'pushkin.sender.senders.GcmNotificationSender'

@mock.patch('pushkin.sender.sender_manager.config')
def test_sender_manager_init_no_senders_given(mock_config):
    mock_config.enabled_senders.split.return_value=[]
    with pytest.raises(SystemExit) as ex:
        sender_manager.NotificationSenderManager()
    assert ("Nothing to start. At least one sender class "
            "must be specified in config") in str(ex)

@mock.patch(APN)
@mock.patch(GCM)
def test_sender_manager_init_bad_subclass(mock_gcm, mock_apn):
    with pytest.raises(SystemExit) as ex:
        sender_manager.NotificationSenderManager()
    assert ("Failed to load sender") in str(ex)
    assert ("TypeError") in str(ex)  # issubclass(<Mock()>... => TypeError

@mock.patch('pushkin.sender.sender_manager.issubclass',
            create=True, return_value=True)
@mock.patch(APN, PLATFORMS=(2, 5))
@mock.patch(GCM, PLATFORMS=(1, 6))
def test_sender_manager_init(mock_gcm, mock_apn, mock_issub):
    mngr = sender_manager.NotificationSenderManager()
    senders = {APN: mock_apn.return_value, GCM: mock_gcm.return_value}
    sender_names = {1: GCM, 6: GCM, 2: APN, 5: APN}
    assert mngr.sender_by_name == senders
    assert mngr.sender_name_by_platform == sender_names
    mock_gcm.assert_called_once_with(workers=30)
    mock_apn.assert_called_once_with(workers=10)

@mock.patch('pushkin.sender.sender_manager.issubclass',
            create=True, return_value=True)
@mock.patch(APN, PLATFORMS=(2, 5))
@mock.patch(GCM, PLATFORMS=(1, 6))
def test_sender_manager_start(mock_gcm, mock_apn, mock_issub):
    mngr = sender_manager.NotificationSenderManager()
    mngr.notification_post_processor = mock.Mock()
    assert not mngr.sender_by_name[APN].start.called
    assert not mngr.sender_by_name[GCM].start.called
    mngr.start()
    mngr.sender_by_name[APN].start.assert_called_once_with()
    mngr.sender_by_name[GCM].start.assert_called_once_with()
    mngr.notification_post_processor.start.assert_called_once_with()

@mock.patch('pushkin.sender.sender_manager.context')
@mock.patch('pushkin.sender.sender_manager.issubclass',
            create=True, return_value=True)
@mock.patch(APN, PLATFORMS=(2, 5))
@mock.patch(GCM, PLATFORMS=(1, 6))
def test_sender_manager_submit(mock_gcm, mock_apn, mock_issub, mock_context):
    mngr = sender_manager.NotificationSenderManager()
    apn_notification = {'platform': 2, 'login_id': 123, 'message_id': 42}
    gcm_notification = {'platform': 6, 'login_id': 321, 'message_id': 24}
    mngr.submit(apn_notification)
    mngr.submit(gcm_notification)
    mngr.sender_by_name[APN].submit.assert_called_once_with(apn_notification)
    mngr.sender_by_name[GCM].submit.assert_called_once_with(gcm_notification)


text:
package Algorithms;

import java.util.LinkedList;
import java.util.List;

/**
*     Given a set of strings, return the smallest subset that contains prefixes for every string.
    If the list is ['foo', 'foog', 'food', 'asdf'] return ['foo', 'asdf']

    http://www.glassdoor.com/Interview/Facebook-Software-Engineer-Interview-Questions-EI_IE40772.0,8_KO9,26_IP2.htm
*/
public class MinimumPrefix {

    public static List<String> findMinimumPrefix(final String[] input) {
        Trie myTrie = new Trie(input);

        return getAllPrefixes(myTrie);
    }

    public static List<String> getAllPrefixes(final Trie myTrie) {
        List<String> result = new LinkedList<>();

        TrieNode root = myTrie.getRoot();
        for (TrieNode child : root.getChildren()) {
            String curr = getFullPrefix(child);
            if (curr != null && !curr.isEmpty()) {
                result.add(curr);
            }
        }

        return result;
    }

    public static String getFullPrefix(final TrieNode child) {
        if (child == null) {
            return "";
        }

        if (child.terminates()) {
            return "" + child.getChar();
        }

        List<TrieNode> children = child.getChildren();
        if (children == null || children.isEmpty() || children.size() > 1) {
            return "" + child.getChar();
        } else {
            return "" + child.getChar() + getFullPrefix(children.get(0));
        }

    }

    public static void main(String[] args) {
          String[] strings = new String[]{"foo", "foog", "food", "asdf"};
          System.out.println(findMinimumPrefix(strings));
    }
}


text:
//
// $
//

package edu.gemini.spModel.gemini.gsaoi;

import edu.gemini.skycalc.Angle;
import static edu.gemini.skycalc.Angle.Unit.ARCSECS;
import edu.gemini.skycalc.Coordinates;
import edu.gemini.shared.util.immutable.ImList;
import edu.gemini.shared.util.immutable.Option;
import static edu.gemini.spModel.gemini.gsaoi.GsaoiDetectorArray.DETECTOR_GAP_ARCSEC;
import static edu.gemini.spModel.gemini.gsaoi.GsaoiDetectorArray.DETECTOR_SIZE_ARCSEC;

import edu.gemini.spModel.gemini.obscomp.SPSiteQuality;
import edu.gemini.spModel.obs.context.ObsContext;
import edu.gemini.spModel.target.SPTarget;
import edu.gemini.spModel.target.env.GuideProbeTargets;
import edu.gemini.spModel.target.env.TargetEnvironment;
import edu.gemini.spModel.telescope.IssPort;
import junit.framework.TestCase;
import org.junit.Test;

import edu.gemini.shared.util.immutable.None;
import edu.gemini.spModel.core.Site;

/**
 * Test cases for the GsaoiOdgw group.
 */
public class GsaoiOdgwGroupTest extends TestCase {

    private ObsContext baseContext;
    private static final GsaoiOdgw.Group group = GsaoiOdgw.Group.instance;
    private static final double midDetector   = (DETECTOR_GAP_ARCSEC + DETECTOR_SIZE_ARCSEC)/2.0;

    protected void setUp() throws Exception{
        // (OT-8) Account for ODGW hotspot (and convert arcsec value to deg)
        final double d = GsaoiDetectorArray.ODGW_HOTSPOT_OFFSET/3600.;

        final SPTarget base         = new SPTarget(d, d);
        final TargetEnvironment env = TargetEnvironment.create(base);

        final Gsaoi inst = new Gsaoi();
        inst.setPosAngle(0);
        inst.setIssPort(IssPort.SIDE_LOOKING);

        baseContext = ObsContext.create(env, inst, None.<Site>instance(), SPSiteQuality.Conditions.BEST, null, null, None.instance());
    }

    // Selection and adding essentially wrap the GsaoiDetectorArray.getId
    // method with code to map the id to an Odgw or update a TargetEnvironment.
    // Not going to repeat all the GsaoiDetectorArray.getId tests that have
    // to do with calculating which detector array a coordinate falls in.

    @Test
    public void testEmptySelect() {
        // In the gap between detectors for the baseContext.
        final Coordinates coords = new Coordinates(
            new Angle(0, ARCSECS), new Angle(midDetector, ARCSECS)
        );
        assertTrue(group.select(coords, baseContext).isEmpty());
    }

    @Test
    public void testSelect() {
        final Coordinates[] coordsArray = new Coordinates[] {
                new Coordinates(new Angle( midDetector, ARCSECS), new Angle(-midDetector, ARCSECS)), // 1
                new Coordinates(new Angle(-midDetector, ARCSECS), new Angle(-midDetector, ARCSECS)), // 2
                new Coordinates(new Angle(-midDetector, ARCSECS), new Angle( midDetector, ARCSECS)), // 3
                new Coordinates(new Angle( midDetector, ARCSECS), new Angle( midDetector, ARCSECS)), // 4
        };
        for (int i=0; i<4; ++i) {
            final Coordinates coords = coordsArray[i];
            final GsaoiOdgw expected = GsaoiOdgw.values()[i];
            assertEquals(expected, group.select(coords, baseContext).getValue());
        }
    }

    @Test
    public void testEmptyAdd() {
        // In the gap between detectors for the baseContext.
        final Coordinates coords = new Coordinates(
            new Angle(0, ARCSECS), new Angle(midDetector, ARCSECS)
        );

        final SPTarget guideTarget = new SPTarget(coords.getRaDeg(), coords.getDecDeg());
        final TargetEnvironment env = group.add(guideTarget, false, baseContext);

        // Adds an ODGW1 target by default.
        final ImList<GuideProbeTargets> col = env.getOrCreatePrimaryGuideGroup().getAll();
        assertEquals(1, col.size());

        final Option<GuideProbeTargets> gtOpt = env.getPrimaryGuideProbeTargets(GsaoiOdgw.odgw1);
        assertFalse(gtOpt.isEmpty());

        final GuideProbeTargets gt = gtOpt.getValue();
        assertEquals(1, gt.getTargets().size());
        assertEquals(guideTarget, gt.getTargets().head());
    }

    @Test
    public void testAdd() {
        final Coordinates[] coordsArray = new Coordinates[] {
                new Coordinates(new Angle( midDetector, ARCSECS), new Angle(-midDetector, ARCSECS)), // 1
                new Coordinates(new Angle(-midDetector, ARCSECS), new Angle(-midDetector, ARCSECS)), // 2
                new Coordinates(new Angle(-midDetector, ARCSECS), new Angle( midDetector, ARCSECS)), // 3
                new Coordinates(new Angle( midDetector, ARCSECS), new Angle( midDetector, ARCSECS)), // 4
        };
        for (int i=0; i<4; ++i) {
            final Coordinates coords   = coordsArray[i];
            final SPTarget guideTarget = new SPTarget(coords.getRaDeg(), coords.getDecDeg());
            final GsaoiOdgw odgw = GsaoiOdgw.values()[i];

            final TargetEnvironment env = group.add(guideTarget, false, baseContext);

            // Should have just one set of GuideTargets for the new guide star.
            assertEquals(1, env.getOrCreatePrimaryGuideGroup().getAll().size());

            // Should be guide targets for the expected guide window.
            final Option<GuideProbeTargets> gtOpt = env.getPrimaryGuideProbeTargets(odgw);
            assertEquals(1, gtOpt.getValue().getTargets().size());

            // Should be the new target that was added.
            assertEquals(guideTarget, gtOpt.getValue().getTargets().head());
        }
    }

}


text:
Engine.include('/components/component.host.js');
Engine.include('/engine/engine.object2d.js');

Engine.initObject('GameGrid', 'Object2D',
function() {
    var GameGrid = Object2D.extend(
        {
            balls: null,

            constructor: function(player_number, player_color) {
                this.balls = [];
                this.base("GameGrid");

                this.add(HostComponent.create('holder'));
            },

            update: function(renderContext, time) {
                renderContext.pushTransform();

                this.base(renderContext, time);
                renderContext.popTransform();
            },

            addBall: function(obj) {
                this.getComponent('holder').add(obj);
            },

            removeBall: function(obj) {
                this.getComponent('holder').remove(obj);
            },

            getClassName: function() {
                return 'GameGrid';
            }
        });
    return GameGrid;
});


text:
package org.jenkinsci.plugins.dockerhub.notification.webhook;

import org.jenkinsci.plugins.dockerhub.notification.DockerHubWebHook;
import org.jenkinsci.plugins.dockerhub.notification.TriggerStore;
import hudson.model.Result;
import hudson.model.Run;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;

import javax.annotation.Nonnull;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Logger;

/**
 * Data to send as callback to a Docker Hub web hook.
 * See Reference
 */
public class CallbackPayload implements Serializable {
    private static final Logger logger = Logger.getLogger(CallbackPayload.class.getName());
    private static final long serialVersionUID = 7820793734732971287L;
    private final States state;
    private final String description;
    private final String context;
    private final String targetUrl;

    public CallbackPayload(States state, String description, String context, String targetUrl) {
        this.state = state;
        this.description = description;
        this.context = context;
        this.targetUrl = targetUrl;
    }

    public static CallbackPayload from(@Nonnull TriggerStore.TriggerEntry from) {
        Result finalRes = null;
        for (TriggerStore.TriggerEntry.RunEntry entry : from.getEntries()) {
            Run<?, ?> run = entry.getRun();
            if (run != null) {
                Result res = run.getResult();
                if (finalRes == null) {
                    finalRes = res;
                } else if (res.isWorseThan(finalRes)) {
                    finalRes = res;
                }
            }
        }
        if (finalRes != null) {
            return new CallbackPayload(
                    States.from(finalRes),
                    "Build result " + finalRes.toString(),
                    "Jenkins",
                    constructUrl(from.getEntries(), from.getPayload()));
        } else {
            return null;
        }
    }

    private static String constructUrl(@Nonnull List<TriggerStore.TriggerEntry.RunEntry> entries, @Nonnull WebHookPayload payload) {
        Jenkins jenkins = Jenkins.getInstance();
        StringBuilder str = new StringBuilder();
        if (jenkins != null) {
            String rootUrl = jenkins.getRootUrl();
            if (rootUrl != null) {
                str.append(rootUrl);
            } else {
                logger.warning("Jenkins root URL is not configured!");
            }
        }
        return str.append(DockerHubWebHook.URL_NAME).append("/details/").append(payload.sha()).toString();
    }

    public JSONObject toJSON() {
        JSONObject j = new JSONObject();
        j.put("state", state.name());
        j.put("description", description);
        j.put("context", context);
        j.put("target_url", targetUrl);
        return j;
    }

    public States getState() {
        return state;
    }

    public String getDescription() {
        return description;
    }

    public String getContext() {
        return context;
    }

    public String getTargetUrl() {
        return targetUrl;
    }

    @Override
    public String toString() {
        return "CallbackPayload{" +
                "state=" + state +
                ", description='" + description + '\'' +
                ", context='" + context + '\'' +
                ", targetUrl='" + targetUrl + '\'' +
                '}';
    }

    public static enum States {
        success, failure, error;

        public static States from(@Nonnull Result result) {
            if (result == Result.SUCCESS) {
                return success;
            }
            if (result == Result.FAILURE) {
                return error;
            }
            if (result == Result.UNSTABLE) {
                return failure;
            }
            return error;
        }
    }
}


text:
<!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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>My Project: Class Members - Functions</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

My Project

- b -

beidouEnabled()
: OgreControllerBackend

- d -

disableTroposphericCorrection()
: OgreControllerBackend

- e -

enableBeidou()
: OgreControllerBackend

enableChannelMeasurements()
: OgreControllerBackend

enableEphemeris()
: OgreControllerBackend

enableGalileo()
: OgreControllerBackend

enableGalileoE5()
: OgreControllerBackend

enableGalileoE5a()
: OgreControllerBackend

enableGgtoParameters()
: OgreControllerBackend

enableGlonass()
: OgreControllerBackend

enableGnssUtcParameters()
: OgreControllerBackend

enableGps()
: OgreControllerBackend

enableGpsL2()
: OgreControllerBackend

enableGpsL5()
: OgreControllerBackend

enableIonosphereKlobuchar()
: OgreControllerBackend

enableIonosphereNequick()
: OgreControllerBackend

enableOsnma()
: OgreControllerBackend

enablePrintChannelStates()
: OgreControllerBackend

enablePvtCalculation()
: OgreControllerBackend

enableSatelliteInfo()
: OgreControllerBackend

ExternalTrackingIfc()
: ExternalTrackingIfc

- g -

galileoEnabled()
: OgreControllerBackend

getCorrelationValueInterface()
: ExternalTrackingIfc

getOgreVersion()
: OgreControllerBackend

getSystemTime()
: OgreControllerBackend

glonassEnabled()
: OgreControllerBackend

gpsEnabled()
: OgreControllerBackend

- i -

initializeTrk()
: ExternalTrackingIfc

isRunning()
: OgreControllerBackend

- l -

loadEphemeris()
: OgreControllerBackend

loadReceiverPosition()
: OgreControllerBackend

- n -

newAlmanac()
: ExternalTrackingIfc

newChannelMeasurements()
: ExternalTrackingIfc

newCorrelation()
: ExternalTrackingIfc

newEphemerisData()
: ExternalTrackingIfc

newGgtoParameter()
: ExternalTrackingIfc

newGnssUtcParameter()
: ExternalTrackingIfc

newIonosphereKlobuchar()
: ExternalTrackingIfc

newIonosphereNequick()
: ExternalTrackingIfc

newPvtCalculation()
: ExternalTrackingIfc

newSatelliteInfo()
: ExternalTrackingIfc

- o -

OgreControllerBackend()
: OgreControllerBackend

- r -

registerExternalTrackingInterface()
: OgreControllerBackend

registerImuObserver()
: OgreControllerBackend

- s -

saveEphemeris()
: OgreControllerBackend

saveReceiverPosition()
: OgreControllerBackend

setConfiguredSystemTime()
: OgreControllerBackend

setCorrelationValueInterface()
: ExternalTrackingIfc

setDataPilotMode()
: OgreControllerBackend

setIonoCorrMethod()
: OgreControllerBackend

setMaxClockErrorS()
: OgreControllerBackend

setOgrpOutput()
: OgreControllerBackend

setPosFixRate()
: OgreControllerBackend

setSystemClockWithGNSSTime()
: OgreControllerBackend

setTrackingLoopBandwidth()
: OgreControllerBackend

setUseGstGpsDiff()
: OgreControllerBackend

startAndRunReceiver()
: OgreControllerBackend

startReceiver()
: OgreControllerBackend

stopReceiver()
: OgreControllerBackend

- u -

useEstimatedDopplerForAcquisition()
: OgreControllerBackend

- ~ -

~OgreControllerBackend()
: OgreControllerBackend

<address class="footer">
Generated by

 1.8.13
</address>


text:
package com.squareup.okhttp.internal.http;

import com.squareup.okhttp.DelegatingServerSocketFactory;
import com.squareup.okhttp.DelegatingSocketFactory;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.OkUrlFactory;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;

import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import org.junit.Before;
import org.junit.Test;

import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;

import static org.junit.Assert.fail;

public final class ThreadInterruptTest {

  // The size of the socket buffers in bytes.
  private static final int SOCKET_BUFFER_SIZE = 256 * 1024;

  private MockWebServer server;
  private OkHttpClient client;

  @Before public void setUp() throws Exception {
    server = new MockWebServer();
    client = new OkHttpClient();

    // Sockets on some platforms can have large buffers that mean writes do not block when
    // required. These socket factories explicitly set the buffer sizes on sockets created.
    server.setServerSocketFactory(
        new DelegatingServerSocketFactory(ServerSocketFactory.getDefault()) {
          @Override
          protected void configureServerSocket(ServerSocket serverSocket) throws IOException {
            serverSocket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
          }
        });
    client.setSocketFactory(new DelegatingSocketFactory(SocketFactory.getDefault()) {
      @Override
      protected void configureSocket(Socket socket) throws IOException {
        socket.setSendBufferSize(SOCKET_BUFFER_SIZE);
        socket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
      }
    });
  }

  @Test public void interruptWritingRequestBody() throws Exception {
    int requestBodySize = 2 * 1024 * 1024; // 2 MiB

    server.enqueue(new MockResponse()
        .throttleBody(64 * 1024, 125, TimeUnit.MILLISECONDS)); // 500 Kbps
    server.play();

    interruptLater(500);

    HttpURLConnection connection = new OkUrlFactory(client).open(server.getUrl("/"));
    connection.setDoOutput(true);
    connection.setFixedLengthStreamingMode(requestBodySize);
    OutputStream requestBody = connection.getOutputStream();
    byte[] buffer = new byte[1024];
    try {
      for (int i = 0; i < requestBodySize; i += buffer.length) {
        requestBody.write(buffer);
        requestBody.flush();
      }
      fail("Expected thread to be interrupted");
    } catch (InterruptedIOException expected) {
    }

    connection.disconnect();
  }

  @Test public void interruptReadingResponseBody() throws Exception {
    int responseBodySize = 2 * 1024 * 1024; // 2 MiB

    server.enqueue(new MockResponse()
        .setBody(new byte[responseBodySize])
        .throttleBody(64 * 1024, 125, TimeUnit.MILLISECONDS)); // 500 Kbps
    server.play();

    interruptLater(500);

    HttpURLConnection connection = new OkUrlFactory(client).open(server.getUrl("/"));
    InputStream responseBody = connection.getInputStream();
    byte[] buffer = new byte[1024];
    try {
      while (responseBody.read(buffer) != -1) {
      }
      fail("Expected thread to be interrupted");
    } catch (InterruptedIOException expected) {
    }

    connection.disconnect();
  }

  private void interruptLater(final int delayMillis) {
    final Thread toInterrupt = Thread.currentThread();
    Thread interruptingCow = new Thread() {
      @Override public void run() {
        try {
          sleep(delayMillis);
          toInterrupt.interrupt();
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
      }
    };
    interruptingCow.start();
  }
}


text:
'use babel'

import {CompositeDisposable} from 'atom'
import {Message} from './message-element'

export class BottomPanel {
  constructor(scope) {
    this.subscriptions = new CompositeDisposable
    this.element = document.createElement('linter-panel') // TODO(steelbrain): Make this a `div`
    this.panel = atom.workspace.addBottomPanel({item: this.element, visible: false, priority: 500})
    this.visibility = false
    this.scope = scope
    this.messages = new Map()

    this.subscriptions.add(atom.config.observe('linter.showErrorPanel', value => {
      this.configVisibility = value
      this.setVisibility(true)
    }))
    this.subscriptions.add(atom.workspace.observeActivePaneItem(paneItem => {
      this.paneVisibility = paneItem === atom.workspace.getActiveTextEditor()
      this.setVisibility(true)
    }))
  }
  refresh(scope) {
    this.scope = scope
    for (let message of this.messages) {
      message[1].updateVisibility(scope)
    }
  }
  setMessages({added, removed}) {
    if (removed.length)
      this.removeMessages(removed)
    for (let message of added) {
      const messageElement = Message.fromMessage(message)
      this.element.appendChild(messageElement)
      messageElement.updateVisibility(this.scope)
      this.messages.set(message, messageElement)
    }
  }
  removeMessages(removed) {
    for (let message of removed) {
      if (this.messages.has(message)) {
        this.element.removeChild(this.messages.get(message))
        this.messages.delete(message)
      }
    }
  }
  getVisibility() {
    return this.visibility
  }
  setVisibility(value){
    this.visibility = value && this.configVisibility && this.paneVisibility
    if (this.visibility) {
      this.panel.show()
    } else {
      this.panel.hide()
    }
  }
  dispose() {
    this.subscriptions.dispose()
    this.messages.clear()
    this.panel.destroy()
  }
}


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

<title>DataAnalyzersFactory</title>
<meta name="date" content="2013-10-01">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

edu.cmu.cs.lane.pipeline.dataanalyzer

Class DataAnalyzersFactory

java.lang.Object

edu.cmu.cs.lane.pipeline.dataanalyzer.DataAnalyzersFactory

public class DataAnalyzersFactory
extends java.lang.Object

A factory that creates new analyzers based on the definitions in the options

Author:

zinman

Constructor Summary

Constructors

Constructor and Description

DataAnalyzersFactory()

Method Summary

Methods

Modifier and Type
Method and Description

static AbstractAnalyzer
create(java.lang.String name,
      OptionsGeneral options)

static void
initialize(OptionsGeneral options)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DataAnalyzersFactory

public DataAnalyzersFactory()

Method Detail

initialize

public static void initialize(OptionsGeneral options)

create

public static AbstractAnalyzer create(java.lang.String name,
                      OptionsGeneral options)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
import * as core from '../../core';
import {DEFAULT_INTERPOLATION_CONFIG} from '../../ml_parser/interpolation_config';
import * as o from '../../output/output_ast';
import {ParseLocation, ParseSourceFile, ParseSourceSpan} from '../../parse_util';
import {Identifiers as R3} from '../r3_identifiers';
import {generateForwardRef, R3CompiledExpression} from '../util';
import {DeclarationListEmitMode, R3ComponentMetadata, R3TemplateDependencyKind, R3TemplateDependencyMetadata} from '../view/api';
import {createComponentType} from '../view/compiler';
import {ParsedTemplate} from '../view/template';
import {DefinitionMap} from '../view/util';

import {R3DeclareComponentMetadata, R3DeclareDirectiveDependencyMetadata, R3DeclareNgModuleDependencyMetadata, R3DeclarePipeDependencyMetadata} from './api';
import {createDirectiveDefinitionMap} from './directive';
import {toOptionalLiteralArray} from './util';

export interface DeclareComponentTemplateInfo {
  /**
   * The string contents of the template.
   *
   * This is the "logical" template string, after expansion of any escaped characters (for inline
   * templates). This may differ from the actual template bytes as they appear in the .ts file.
   */
  content: string;

  /**
   * A full path to the file which contains the template.
   *
   * This can be either the original .ts file if the template is inline, or the .html file if an
   * external file was used.
   */
  sourceUrl: string;

  /**
   * Whether the template was inline (using `template`) or external (using `templateUrl`).
   */
  isInline: boolean;

  /**
   * If the template was defined inline by a direct string literal, then this is that literal
   * expression. Otherwise `null`, if the template was not defined inline or was not a literal.
   */
  inlineTemplateLiteralExpression: o.Expression|null;
}

/**
 * Compile a component declaration defined by the `R3ComponentMetadata`.
 */
export function compileDeclareComponentFromMetadata(
    meta: R3ComponentMetadata<R3TemplateDependencyMetadata>, template: ParsedTemplate,
    additionalTemplateInfo: DeclareComponentTemplateInfo): R3CompiledExpression {
  const definitionMap = createComponentDefinitionMap(meta, template, additionalTemplateInfo);

  const expression = o.importExpr(R3.declareComponent).callFn([definitionMap.toLiteralMap()]);
  const type = createComponentType(meta);

  return {expression, type, statements: []};
}

/**
 * Gathers the declaration fields for a component into a `DefinitionMap`.
 */
export function createComponentDefinitionMap(
    meta: R3ComponentMetadata<R3TemplateDependencyMetadata>, template: ParsedTemplate,
    templateInfo: DeclareComponentTemplateInfo): DefinitionMap<R3DeclareComponentMetadata> {
  const definitionMap: DefinitionMap<R3DeclareComponentMetadata> =
      createDirectiveDefinitionMap(meta);

  definitionMap.set('template', getTemplateExpression(template, templateInfo));
  if (templateInfo.isInline) {
    definitionMap.set('isInline', o.literal(true));
  }

  definitionMap.set('styles', toOptionalLiteralArray(meta.styles, o.literal));
  definitionMap.set('dependencies', compileUsedDependenciesMetadata(meta));
  definitionMap.set('viewProviders', meta.viewProviders);
  definitionMap.set('animations', meta.animations);

  if (meta.changeDetection !== undefined) {
    definitionMap.set(
        'changeDetection',
        o.importExpr(R3.ChangeDetectionStrategy)
            .prop(core.ChangeDetectionStrategy[meta.changeDetection]));
  }
  if (meta.encapsulation !== core.ViewEncapsulation.Emulated) {
    definitionMap.set(
        'encapsulation',
        o.importExpr(R3.ViewEncapsulation).prop(core.ViewEncapsulation[meta.encapsulation]));
  }
  if (meta.interpolation !== DEFAULT_INTERPOLATION_CONFIG) {
    definitionMap.set(
        'interpolation',
        o.literalArr([o.literal(meta.interpolation.start), o.literal(meta.interpolation.end)]));
  }

  if (template.preserveWhitespaces === true) {
    definitionMap.set('preserveWhitespaces', o.literal(true));
  }

  return definitionMap;
}

function getTemplateExpression(
    template: ParsedTemplate, templateInfo: DeclareComponentTemplateInfo): o.Expression {
  // If the template has been defined using a direct literal, we use that expression directly
  // without any modifications. This is ensures proper source mapping from the partially
  // compiled code to the source file declaring the template. Note that this does not capture
  // template literals referenced indirectly through an identifier.
  if (templateInfo.inlineTemplateLiteralExpression !== null) {
    return templateInfo.inlineTemplateLiteralExpression;
  }

  // If the template is defined inline but not through a literal, the template has been resolved
  // through static interpretation. We create a literal but cannot provide any source span. Note
  // that we cannot use the expression defining the template because the linker expects the template
  // to be defined as a literal in the declaration.
  if (templateInfo.isInline) {
    return o.literal(templateInfo.content, null, null);
  }

  // The template is external so we must synthesize an expression node with
  // the appropriate source-span.
  const contents = templateInfo.content;
  const file = new ParseSourceFile(contents, templateInfo.sourceUrl);
  const start = new ParseLocation(file, 0, 0, 0);
  const end = computeEndLocation(file, contents);
  const span = new ParseSourceSpan(start, end);
  return o.literal(contents, null, span);
}

function computeEndLocation(file: ParseSourceFile, contents: string): ParseLocation {
  const length = contents.length;
  let lineStart = 0;
  let lastLineStart = 0;
  let line = 0;
  do {
    lineStart = contents.indexOf('\n', lastLineStart);
    if (lineStart !== -1) {
      lastLineStart = lineStart + 1;
      line++;
    }
  } while (lineStart !== -1);

  return new ParseLocation(file, length, line, length - lastLineStart);
}

function compileUsedDependenciesMetadata(meta: R3ComponentMetadata<R3TemplateDependencyMetadata>):
    o.LiteralArrayExpr|null {
  const wrapType = meta.declarationListEmitMode !== DeclarationListEmitMode.Direct ?
      generateForwardRef :
      (expr: o.Expression) => expr;

  return toOptionalLiteralArray(meta.declarations, decl => {
    switch (decl.kind) {
      case R3TemplateDependencyKind.Directive:
        const dirMeta = new DefinitionMap<R3DeclareDirectiveDependencyMetadata>();
        dirMeta.set('kind', o.literal(decl.isComponent ? 'component' : 'directive'));
        dirMeta.set('type', wrapType(decl.type));
        dirMeta.set('selector', o.literal(decl.selector));
        dirMeta.set('inputs', toOptionalLiteralArray(decl.inputs, o.literal));
        dirMeta.set('outputs', toOptionalLiteralArray(decl.outputs, o.literal));
        dirMeta.set('exportAs', toOptionalLiteralArray(decl.exportAs, o.literal));
        return dirMeta.toLiteralMap();
      case R3TemplateDependencyKind.Pipe:
        const pipeMeta = new DefinitionMap<R3DeclarePipeDependencyMetadata>();
        pipeMeta.set('kind', o.literal('pipe'));
        pipeMeta.set('type', wrapType(decl.type));
        pipeMeta.set('name', o.literal(decl.name));
        return pipeMeta.toLiteralMap();
      case R3TemplateDependencyKind.NgModule:
        const ngModuleMeta = new DefinitionMap<R3DeclareNgModuleDependencyMetadata>();
        ngModuleMeta.set('kind', o.literal('ngmodule'));
        ngModuleMeta.set('type', wrapType(decl.type));
        return ngModuleMeta.toLiteralMap();
    }
  });
}


text:
package com.ee.imperator.data.transaction;

import com.ee.imperator.exception.TransactionException;
import com.ee.imperator.game.Cards;
import com.ee.imperator.mission.PlayerMission;
import com.ee.imperator.user.Member;
import com.ee.imperator.user.Player;
import com.ee.imperator.user.Player.State;

public abstract class AbstractPlayerTransaction implements PlayerTransaction {
	public enum Score {
		WIN, LOSS
	}
	protected final Player player;
	private final Cards cards;
	private State state;
	private PlayerMission mission;
	private boolean autoroll;
	private Score score;

	public AbstractPlayerTransaction(Player player) {
		this.player = player;
		cards = new Cards();
		setValues();
	}

	private void setValues() {
		state = player.getState();
		mission = player.getMission();
		autoroll = player.getAutoRoll();
		cards.setArtillery(player.getCards().getArtillery());
		cards.setCavalry(player.getCards().getCavalry());
		cards.setInfantry(player.getCards().getInfantry());
		cards.setJokers(player.getCards().getJokers());
		score = null;
	}

	@Override
	public void revert() throws TransactionException {
		setValues();
	}

	@Override
	public void setState(State state) {
		this.state = state;
	}

	@Override
	public void setMission(PlayerMission mission) {
		this.mission = mission;
	}

	@Override
	public void setAutoRoll(boolean autoroll) {
		this.autoroll = autoroll;
	}

	@Override
	public void addLoss() {
		score = Score.LOSS;
	}

	@Override
	public void addWin() {
		score = Score.WIN;
	}

	protected State getState() {
		return state;
	}

	protected PlayerMission getMission() {
		return mission;
	}

	protected boolean getAutoroll() {
		return autoroll;
	}

	@Override
	public Cards getCards() {
		return cards;
	}

	protected Score getScore() {
		return score;
	}

	/**
	 * Writes changes to underlying player.
	 */
	protected void apply() {
		player.setAutoRoll(autoroll);
		player.setMission(mission);
		player.setState(state);
		player.getCards().setArtillery(cards.getArtillery());
		player.getCards().setCavalry(cards.getCavalry());
		player.getCards().setInfantry(cards.getInfantry());
		player.getCards().setJokers(cards.getJokers());
		Member member = player.getMember();
		if(score == Score.WIN) {
			member.setScore(member.getScore() + player.getGame().getPlayers().size() - 1);
			member.setWins(member.getWins() + 1);
		} else if(score == Score.LOSS) {
			member.setScore(member.getScore() - 1);
			member.setLosses(member.getLosses() + 1);
		}
	}
}


text:
"""
byceps.services.orga_presence.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from __future__ import annotations
from datetime import date, datetime, timedelta, timezone
from itertools import groupby
from typing import Iterator, Sequence
from uuid import UUID
try:
    from zoneinfo import ZoneInfo
except ImportError:
    from backports.zoneinfo import ZoneInfo

from flask import current_app
from sqlalchemy import delete

from ...database import db
from ...typing import PartyID, UserID
from ...util.datetime.range import create_adjacent_ranges, DateTimeRange

from ..party import service as party_service

from .dbmodels import (
    Presence as DbPresence,
    Task as DbTask,
    TimeSlot as DbTimeSlot,
)
from .transfer.models import PresenceTimeSlot, TaskTimeSlot, TimeSlot

def create_presence(
    party_id: PartyID, orga_id: UserID, starts_at: datetime, ends_at: datetime
) -> PresenceTimeSlot:
    """Create a presence for the orga during the party."""
    party = party_service.get_party(party_id)

    presence = DbPresence(
        party_id=party.id, starts_at=starts_at, ends_at=ends_at, orga_id=orga_id
    )
    db.session.add(presence)
    db.session.commit()

    return _presence_to_time_slot(presence)

def delete_time_slot(time_slot_id: UUID) -> None:
    """Delete a time slot."""
    db.session.execute(
        delete(DbTimeSlot)
        .where(DbTimeSlot.id == time_slot_id)
        .execution_options(synchronize_session='fetch')
    )
    db.session.commit()

def get_presences(party_id: PartyID) -> list[PresenceTimeSlot]:
    """Return all presences for that party."""
    presences = db.session \
        .query(DbPresence) \
        .filter_by(party_id=party_id) \
        .options(db.joinedload(DbPresence.orga)) \
        .all()

    return [_presence_to_time_slot(presence) for presence in presences]

def get_tasks(party_id: PartyID) -> list[TaskTimeSlot]:
    """Return all tasks for that party."""
    tasks = db.session \
        .query(DbTask) \
        .filter_by(party_id=party_id) \
        .all()

    return [_task_to_time_slot(task) for task in tasks]

def _presence_to_time_slot(presence: DbPresence) -> PresenceTimeSlot:
    return PresenceTimeSlot.from_(
        presence.id,
        presence.orga,
        presence.starts_at,
        presence.ends_at,
    )

def _task_to_time_slot(task: DbTask) -> TaskTimeSlot:
    return TaskTimeSlot.from_(
        task.id,
        task.title,
        task.starts_at,
        task.ends_at,
    )

# -------------------------------------------------------------------- #

def get_hour_ranges(time_slots: list[TimeSlot]) -> Iterator[DateTimeRange]:
    """Yield hour ranges based on the time slots."""
    time_slot_ranges = [time_slot.range for time_slot in time_slots]
    hour_starts = _get_hour_starts(time_slot_ranges)
    return create_adjacent_ranges(hour_starts)

def _get_hour_starts(dt_ranges: Sequence[DateTimeRange]) -> Iterator[datetime]:
    min_starts_at_utc = _find_earliest_start(dt_ranges)
    max_ends_at_utc = _find_latest_end(dt_ranges)

    # Generate full hours.
    min_starts_at_utc = min_starts_at_utc.replace(
        minute=0, second=0, microsecond=0
    )

    min_starts_at_utc = min_starts_at_utc.replace(tzinfo=timezone.utc)
    max_ends_at_utc = max_ends_at_utc.replace(tzinfo=timezone.utc)

    local_tz = ZoneInfo(current_app.config['TIMEZONE'])
    min_starts_at_local = min_starts_at_utc.astimezone(local_tz)
    max_ends_at_local = max_ends_at_utc.astimezone(local_tz)

    hour_starts = _generate_hour_starts(min_starts_at_local, max_ends_at_local)

    # Remove timezone info for comparability with naive datetimes.
    return (dt.replace(tzinfo=None) for dt in hour_starts)

def _find_earliest_start(dt_ranges: Sequence[DateTimeRange]) -> datetime:
    return min(dt_range.start for dt_range in dt_ranges)

def _find_latest_end(dt_ranges: Sequence[DateTimeRange]) -> datetime:
    return max(dt_range.end for dt_range in dt_ranges)

def _generate_hour_starts(start: datetime, end: datetime) -> Iterator[datetime]:
    one_hour = timedelta(hours=1)
    x = start
    while x <= end:
        yield x
        x += one_hour

def get_days_and_hour_totals(
    hour_ranges: Sequence[DateTimeRange],
) -> Iterator[tuple[date, int]]:
    """Yield (day, relevant hours total) pairs."""

    def get_date(dt_range: DateTimeRange) -> date:
        return dt_range.start.date()

    for day, hour_ranges_for_day in groupby(hour_ranges, key=get_date):
        hour_total = len(list(hour_ranges_for_day))
        yield day, hour_total


text:
.visualize { margin-bottom: 4em; }

/* --------------------------------------------------------------
   Tickets
-------------------------------------------------------------- */
.ticket {
	padding: 3px 4px;
	text-align: right;
	color: #fff;
	font-size: 10px;
	display: inline;
	white-space: nowrap;
	width: 60px;

	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	border-radius: 5px;
}

.ticket.open { background-color: #F90; }
.ticket.closed { background-color: #666; }
.ticket.responded { background-color: #263849; }

/* --------------------------------------------------------------
   Dashboard Tables
-------------------------------------------------------------- */
.support_table .full { width: 70%; font-size: 11px; }
.support_table .who { width: 30%; text-align: right; font-size: 10px; color: #999; }

.info_table .value { width: 25%; font-size: 18px; font-weight: bold; color: #263849; }

.inbox_table .avatar { width: 60px; }
.inbox_table .full { width: 80%; font-size: 11px; }
.inbox_table .who { width: 20%;  text-align: right; font-size: 10px; color: #999; }

img.avatar_img
{
	width: 60px;
	padding: 1px;
	border: 1px solid #CCC;
	-moz-border-radius: 4px;
	-webkit-border-radius: 4px;
	border-radius: 4px;

}

/* --------------------------------------------------------------
   Support Request Page
-------------------------------------------------------------- */
#support-details h1
{
	margin-bottom: 1.15em;
}

#support-details .request-info
{
	background: none repeat scroll 0 0 #F1F1F1;
	color: #333;
	float: left;
	font-size: 11px;
	margin-right: 1.5em;
	margin-bottom: 1.5em;
	width: 180px;
	padding: 15px 0 10px 10px;
	-moz-border-radius: 3px;
	-webkit-border-radius: 3px;
	border-radius: 3px;

	border: 1px solid #DDD;
}

#support-details .request-info ul { margin-left: 16px; }

#support-details .request-info img
{
	width: 35px;
	padding: 1px;
	margin: 0 2px;
	border: 1px solid #AAA;
	-moz-border-radius: 3px;
	-webkit-border-radius: 3px;
	border-radius: 3px;
}

#support-details .request-info strong { color: #111; padding-right: .5em; }

/* --------------------------------------------------------------
   FAQ Page
-------------------------------------------------------------- */
#search-bar
{
	background: #EEE;

	padding: 25px 25px 10px;
	margin: 0 auto;

	-moz-border-radius: 4px;
	-webkit-border-radius: 4px;
	border-radius: 4px;

	border: 1px solid #CCC;

}

#search-bar form
{
	width: 550px;
	position: relative;
	margin: 0 auto;
}

	#search-bar h2 { margin-bottom: .5em; }

	#search-bar input
	{
		width: 430px;
		padding: 7px;
		border: 1px solid #999;
		margin-right: .5em;
		-moz-border-radius: 4px;
		-webkit-border-radius: 4px;
		border-radius: 4px;
	}

	*+html #search-bar input { width: 415px; }

	#search-bar p { font-size: 11px; color: #555; margin-top: 1em; }

	#search-bar .loader
	{
		background: url(./images/loader.gif) no-repeat 0 0;
		width: 16px;
		height: 16px;
		line-height: 500px;
		overflow: hidden;

		position: absolute;
		right: 115px;
		top: 40px;

	}

	.faq { margin-bottom: 3em; }
	.faq li { list-style-type: none; padding: 0; margin: 0; }

	.faq .answer
	{
		border-bottom: 1px dotted #CCC;
		margin: 2.5em 0 2.5em 2em;
	}

	.faq .plus_icon
	{
		color: #F90;
		font-weight: bold;
		font-size: 18px;
		display: inline;
		padding-right: 1em;
	}

	#no_results { color: #C00; display: none; }

/* --------------------------------------------------------------
   Reports Page
-------------------------------------------------------------- */
#big_stats
{
	/* background: #f3f3f3;  */
	width: 100%;
	padding: 0;
	float: left;
	margin-bottom: 3em;
	-moz-border-radius: 6px;
	-webkit-border-radius: 6px;
	border-radius: 6px;
}

	*+html #big_stats { padding-bottom: 2em; }

.stat
{
	width: 29%;
	height: 90px;
	padding: 0 2%;
	float: left;
	position: relative;
	border-left: 1px dotted #CCC;
}

	*+html .stat { height: 100px; }

.stat:first-child { border: none; }

.stat h4
{
	font-size: 12px;
	font-weight: bold;
	text-transform: uppercase;
	color: #999;
	margin-bottom: 1.5em;
}

.stat .value
{
	font-size: 56px;
	font-weight: bold;
	color: #263849;
	line-height: 1em;
}

.stat .view_all
{
	font-size: 11px;
	position: absolute;
	right: 20px;
	bottom: 12px;
}

.reports_table .value { width: 100px; text-align: right; }
	.reports_table .value span { background: #F90; font-size: 11px; font-weight: bold; color: #FFF; width: 40px; text-align: center;  padding: 3px 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; }

.reports_table td { padding: 5px; }

/* --------------------------------------------------------------
   Invoice Page
-------------------------------------------------------------- */
#invoice { border-top: 5px solid #999; }

#invoice h1 { margin-bottom: 1.25em; }
#invoice .total,
#invoice .price { text-align: right; }

#invoice .sub_total,
#invoice .grand_total { text-align: right; border-bottom: none; }

#invoice .sub_total { border-top: 2px solid #666; }
#invoice .grand_total { font-size: 14px; font-weight: bold; }

#invoice .client_details,
#invoice .invoice_details { font-size: 11px; padding: 0; margin: 0 0 3em; float: left; }

	#invoice .invoice_details { float: right; }
	#invoice .client_details li,
	#invoice .invoice_details li { list-style-type: none; }

#invoice .name { font-size: 14px; }

#invoice_actions { padding: 0; margin: 0; }
#invoice_actions li { list-style-type: none; margin-bottom: 1.25em; }
#invoice_actions li a
{
	padding-left: 26px;
}

#invoice_actions .send { background: url(../images/email.png) no-repeat 0 center; }
#invoice_actions .edit { background: url(../images/pencil.png) no-repeat 0 center; }
#invoice_actions .print { background: url(../images/printer.png) no-repeat 0 center; }
#invoice_actions .duplicate { background: url(../images/page_white_copy.png) no-repeat 0 center; }
#invoice_actions .delete { background: url(../images/cross.png) no-repeat 0 center; }
#invoice_actions .change { background: url(../images/page_white_go.png) no-repeat 0 center; }

#invoice_total
{
	background: #AAA;
	font-size: 26px;
	font-weight: bold;
	text-align: center;
	color: #FFF;
	padding: 15px;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	border-radius: 5px;
	margin-bottom: 1.25em;
}

/* --------------------------------------------------------------
   Gallery Page
-------------------------------------------------------------- */
ul.gallery { padding: 0; margin: 0; }

.gallery li
{
	padding: 3px;
	margin: 0;
	background: 0;
	width: 100px;
	height: 100px;

	list-style-type: none;

/*	display: -moz-inline-stack;
    display: inline-block;
    vertical-align: top;
    zoom: 1;
    *display: inline; */

    float: left;

	position: relative;
	margin: 13px 17px 10px 10px;
	border: 1px solid #ccc;
	box-shadow: 0 0 3px rgba(0,0,0,.20);
	-moz-box-shadow: 0 0 3px rgba(0,0,0,.20);
	-webkit-box-shadow: 0 0 3px rgba(0,0,0,.20);

	-moz-border-radius: 4px;
	-webkit-border-radius: 4px;
	border-radius: 4px;
	}

.gallery li:hover { border-color: #888; }

.gallery li .actions
{
	width: 100px;
	height: 100px;
	display: block;
	z-index: 10;
	position: absolute;
	text-align: center;
	left: 0;
	top: 0;
	display: none;
	padding: 3px;

	line-height: 100px;
}

.gallery .actions .btn { padding: 0 5px 2px; }

.gallery .actions .btn,
.gallery .actions .btn:hover { color: #FFF !important; }

.gallery .actions .btn:first-child { margin-top: 20px; margin-bottom: 1em; }

.gallery li:hover .actions { display: block; }

	*+html .gallery .actions .delete { top: -12px; position: relative; }

#gallery_wrapper { text-align: center; }

/* --------------------------------------------------------------
   Calendar Page
-------------------------------------------------------------- */
table.calendar
{
	margin:18px 0 12px;
	clear:both;
	font-size:12px;
	border-collapse:collapse;
}

table.calendar, .calendar td { border:1px solid #bbb; }

table.calendar .day_number
{
	color:#333;
	font-size:12px;
	padding:3px 9px;
	font-weight:bold;
}

table.calendar td .daynum { color: #555; }

table.calendar th
{
	width: 250px;
	height: 10px;
	background: #263849  !important;

	color: #FFF;
	text-shadow: 0 0 1px rgba(0,0,0,.3);
	padding:12px 0;
	text-align:center;
}

table.calendar td
{
	height: 110px;
	width:14.28%;
	color: #114B7D;
	text-align: left;
	vertical-align: top;
	padding:0;
	font-size:12px;
}

table.calendar .event { width: 92%; margin: 0 auto; height: 2em; overflow: hidden; display: block; position: relative; }

table.calendar .event_title
{
	display: inline;
	color: #222;
	font-size: 11px;

	-moz-border-radius: 4px;
	-webkit-border-radius: 4px;
	border-radius: 4px;
	position: relative;
	text-decoration: none;
	z-index: 20;
}

	table.calendar .event_title:hover { color: #222; text-decoration: underline; }

table.calendar .event_time { display: inline; font-size: 11px; font-weight: bold; color: #F90; padding-right: .25em; }

table.calendar .not_current_month { background: #F1F1F1; }

table.calendar .not_current_month .day_number { color: #888; }

h2.calendar_header { font-size: 56px; text-align: center; line-height: 48px; margin-bottom: .5em; margin-top: .25em; }
	h2.calendar_header button { top: -10px; margin: 0 1em; position: relative; }
		h2.calendar_header button:hover { color: #FFF !important; }

		h2.calendar_header button.previous { right: 25px; }
		h2.calendar_header button.next { left: 25px; }

/* --------------------------------------------------------------
   People Page
-------------------------------------------------------------- */
.department { float: left; margin-bottom: 3em; }
.department h2 { font-size: 18px; color: #F90; border-bottom: 1px dotted #CCC; padding-bottom: 4px; margin-bottom: 1.5em; }
.user-card { width: 200px; font-size: 11px; margin: 0 1em 1.5em 0; float: left; }
.user-card img
{
	border: 1px solid #CCC;
	padding: 1px;
	-moz-border-radius: 4px;
	-webkit-border-radius: 4px;
	border-radius: 4px;

}
.user-card .avatar { width: 75px; float: left; }
.user-card .details { width: 115px; float: right; }

#add-user-form { width: 270px; margin: 0 auto; }


text:
using System;

namespace GitHub.Logging
{
    public static class LogHelper
    {
        private static readonly LogAdapterBase nullLogAdapter = new NullLogAdapter();

        private static bool tracingEnabled;
        public static bool TracingEnabled
        {
            get
            {
                return tracingEnabled;
            }
            set
            {
                if (tracingEnabled != value)
                {
                    tracingEnabled = value;
                    Instance.Info("Trace Logging " + (value ? "Enabled" : "Disabled"));
                }
            }
        }

        private static LogAdapterBase logAdapter = nullLogAdapter;

        public static LogAdapterBase LogAdapter
        {
            get { return logAdapter; }
            set { logAdapter = value ?? nullLogAdapter; }
        }

        private static ILogging instance;

        public static ILogging Instance
        {
            get {
                if (instance == null)
                {
                    instance = GetLogger();
                }
                return instance;
            }
            set { instance = value; }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
        public static ILogging GetLogger<T>()
        {
            return GetLogger(typeof(T));
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
        public static ILogging GetLogger(Type type)
        {
            return GetLogger(type.Name);
        }

        public static ILogging GetLogger(string context = null)
        {
            return new LogFacade($"<{context ?? "Global"}>");
        }

        public static void Info(string s)
        {
            Instance.Info(s);
        }

        public static void Debug(string s)
        {
            Instance.Debug(s);
        }

        public static void Trace(string s)
        {
            Instance.Trace(s);
        }

        public static void Warning(string s)
        {
            Instance.Warning(s);
        }

        public static void Error(string s)
        {
            Instance.Error(s);
        }

        public static void Error(Exception exception)
        {
            Instance.Error(exception);
        }

        public static void Info(string format, params object[] objects)
        {
            Instance.Info(format, objects);
        }

        public static void Debug(string format, params object[] objects)
        {
            Instance.Debug(format, objects);
        }

        public static void Trace(string format, params object[] objects)
        {
            Instance.Trace(format, objects);
        }

        public static void Warning(string format, params object[] objects)
        {
            Instance.Warning(format, objects);
        }

        public static void Error(string format, params object[] objects)
        {
            Instance.Error(format, objects);
        }

        public static void Info(Exception ex, string s)
        {
            Instance.Info(ex, s);
        }

        public static void Debug(Exception ex, string s)
        {
            Instance.Debug(ex, s);
        }

        public static void Trace(Exception ex, string s)
        {
            Instance.Trace(ex, s);
        }

        public static void Warning(Exception ex, string s)
        {
            Instance.Warning(ex, s);
        }

        public static void Error(Exception ex, string s)
        {
            Instance.Error(ex, s);
        }
    }
}


text:
import React from 'react'
import { connect } from 'react-redux'

import CardNumberForm from './CardNumberForm'
import AddSkipassButton from './AddSkipassButton'
import Skipass from '../components/Skipass'

const Search = ({ error, skipass, isFetching }) => {
  return (
    <section className='buka-skipass-search__container'>
      <CardNumberForm />
      <Skipass error={error} skipass={skipass} isFetching={isFetching} />
      <AddSkipassButton />
    </section>
  )
}

const mapStateToProps = state => {
  const { skipass, error, isFetching } = state.get('searchSkipass').toJS()

  return {
    error,
    skipass,
    isFetching
  }
}

export default connect(mapStateToProps)(Search)


text:
/**
 * <p>
 *   Artifacts for parsing using a simplified version of the handler interfaces.
 * </p>
 */
package org.attoparser.simple;