text:
//
//  TrendViewController.m
//  SportsCircle
//
//  Created by 劉瑋軒 on 2015/7/15.
//  Copyright (c) 2015年 SportsCircle. All rights reserved.
//

#import "TrendViewController.h"
#import <QuartzCore/QuartzCore.h>
#import <Parse/Parse.h>
#import "TrendTableViewCell.h"
#import <ParseUI/ParseUI.h>
#import "PersonalPageViewController.h"
#import "readPostViewController.h"
#import "UIView+WZLBadge.h"
#import "LBHamburgerButton.h"
#import "DKCircleButton.h"
#import "endRecordingTableViewController.h"
#import "myPostImageView.h"

@interface TrendViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
{
    NSDictionary *postWallDictionary;
    NSArray *postWallArray;
    NSMutableArray *datas;
    UIRefreshControl *refreshControl;
    PFImageView *userImage;
    PFUser *currentUser;
    int notidicationNumber; /**< 消息通知數量 */
    PFObject *postWallObject;
    NSString *selectObjectId;
    //TrendTableViewCell *cell;
}
@property (weak, nonatomic) IBOutlet UIView *theListView;
@property (strong, nonatomic) IBOutlet UIView *theTrendView;
@property (weak, nonatomic) IBOutlet DKCircleButton *goButton;
@property (weak, nonatomic) IBOutlet UIButton *notidicationButton;  /**< 消息通知按鈕 */
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) LBHamburgerButton* buttonHamburgerCloseSmall;

@end

@implementation TrendViewController

- (NSInteger) plusWithNumber1:(NSInteger)numbe1 number2:(NSInteger)number2 {

    return numbe1 + number2;

}

- (void)viewDidLoad {
    [super viewDidLoad];

    //push設定user pointer
    PFInstallation *installation = [PFInstallation currentInstallation];
    installation[@"user"] = [PFUser currentUser];
    [installation saveInBackground];

    [self didConfirmBeFriend];
    [self initPauseButton];

    self.tableView.delaysContentTouches = NO;   //取消tabeViewCell Button的延遲
//    UIBarButtonItem *list=[[UIBarButtonItem alloc]initWithTitle:@"List" style:UIBarButtonItemStylePlain target:self action:@selector (barListBtnPressed:)];
    //創造一個UIBBtn.選擇plain的style(另一個也長一樣).selector為把某個方法包裝成一個變數.:為名稱的一部分必加
    [self initHamburgerButton];

    UIBarButtonItem *hamburgerButton = [[UIBarButtonItem alloc]initWithCustomView:_buttonHamburgerCloseSmall];

    self.navigationItem.leftBarButtonItem=hamburgerButton;

    //手勢操作
    UISwipeGestureRecognizer *toRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(toRight)];
    toRight.direction = UISwipeGestureRecognizerDirectionRight;
    [_theTrendView addGestureRecognizer:toRight];

    UISwipeGestureRecognizer *toLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(toLeft)];
    toLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [_theTrendView addGestureRecognizer:toLeft];

    UITapGestureRecognizer *toTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toTap)];
    [_theTrendView addGestureRecognizer:toTap];
        toTap.delegate = self;

    //允許ImageView接受使用者互動
    _theTrendView.userInteractionEnabled = YES;

    self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"動態首頁" style:UIBarButtonItemStylePlain target:nil action:nil];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    //返回到grayViewControllor的按鈕名稱改為中文~返回~

    _theListView.hidden=YES;
    _tableView.delegate=self;
    _tableView.dataSource=self;

    //if (!datas) {
    //    datas = [[NSMutableArray alloc] init];
    //}

    //[self fetchDataFromParse];
   // [[PFUser currentUser] refreshInBackgroundWithBlock:nil];

    UIView *refreshView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    [self.tableView insertSubview:refreshView atIndex:0]; //the tableView is a IBOutlet

    refreshControl = [[UIRefreshControl alloc] init];
    refreshControl.tintColor = [UIColor redColor];
    [refreshControl addTarget:self action:@selector(reloadDatas) forControlEvents:UIControlEventValueChanged];
    NSMutableAttributedString *refreshString = [[NSMutableAttributedString alloc] initWithString:@"Pull To Refresh"];
    [refreshString addAttributes:@{NSForegroundColorAttributeName : [UIColor grayColor]} range:NSMakeRange(0, refreshString.length)];
    refreshControl.attributedTitle = refreshString;
    [refreshView addSubview:refreshControl];

    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:57.0f/255.0f green:88.0f/255.0f blue:100.0f/255.0f alpha:1]];

    userImage = [PFImageView new];

    //[list setTintColor:[UIColor whiteColor]];
    //[cell.contentView.layer setBorderColor:[UIColor redColor].CGColor];
    //[cell.contentView.layer setBorderWidth:10.0];

    self.tableView.separatorColor=[UIColor whiteColor];

}
-(void)reloadDatas
{
    //update here...
    NSLog(@"update");
    PFQuery *query = [PFQuery queryWithClassName:@"WallPost"];
    [query addDescendingOrder:@"createdAt"];
    postWallArray = [NSArray new];
    postWallArray = [query findObjects];
    postWallDictionary = [NSDictionary new];
    [self.tableView reloadData];
    [refreshControl endRefreshing];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    PFQuery *query = [PFQuery queryWithClassName:@"WallPost"];
    [query addDescendingOrder:@"createdAt"];
    postWallArray = [NSArray new];
    postWallArray = [query findObjects];
    postWallDictionary = [NSDictionary new];

    //query為指向sc類別
    //[query whereKey:@"user" equalTo:currentUser];
    //類別為sc且key為user時value為currentUser
    //userSchedules = [query findObjects];//抓出資料有兩筆
    //NSDictionary *userSchedulesA=userSchedules[0];//cheatMode
    //NSDictionary *userSchedulesB=userSchedules[1];//cheatMode
    //每一筆為NSDictionary
    //NSLog(@"this id is: %@",userSchedulesA[@"scheduleDetail"]);
    //NSLog(@"this id is: %@",userSchedulesB[@"scheduleDetail"]);
    //[self fetchDataFromParse];
    [self.tableView reloadData];
}
/*
-(void)fetchDataFromParse
{
    for (int i=0 ;i<postWallArray.count ; i++) {
        [datas insertObject:postWallArray atIndex:0];
        //使用者新增幾筆就會出現幾列
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        //這裏要改為filename
        [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}
*/
-(IBAction) barListBtnPressed:(id)sender{
    //按下listBtn時
    [_buttonHamburgerCloseSmall switchState];

    CATransition *transition=[CATransition animation];
    //catransition為Q的一個物件
    transition.duration=0.3;
    //動畫時間長度
    transition.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    //動畫效果為進出緩慢中間快速
    transition.type=kCATransitionPush;
    //動畫效果為
    if (_theListView.isHidden) {
        _theListView.hidden=NO;
        transition.subtype=kCATransitionFromLeft;
    }else{
        _theListView.hidden=YES;
        transition.subtype=kCATransitionFromRight;
    }//subtype為動畫方向
    [_theListView.layer addAnimation:transition forKey:nil];
    //layer為比UIView更低階的uiview元件.可研究CAlayer

    //當theListView展開時 goButton無效
    if (_theListView.isHidden) {
        _goButton.userInteractionEnabled = YES;
    }else {
        _goButton.userInteractionEnabled = NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)backTotrendView:(UIStoryboardSegue *)segue//啟動逃生門所需.透過這個標記去回到login.白色的字可以改.後面的segue可以填香蕉
{
    NSLog(@"back to trendView");
}

-(void) toRight{
    if (_theListView.isHidden) {
        [self barListBtnPressed:nil];
    }
}

-(void) toLeft{
    if (!_theListView.isHidden) {
        [self barListBtnPressed:nil];
    }else{
        [self showMapBtnPressed:nil];//theListView未顯示時 右滑出現map
    }
}

-(void)toTap {
    if (!_theListView.isHidden) {
        [self barListBtnPressed:nil];
    }
}

- (IBAction)showMapBtnPressed:(id)sender {
    //在theListView展開時按下showMapBtnPressed需要把theListView一起隱藏
    //若使用segue到下一頁 無法達成此要求 所以這裡手動進入下一頁
    if (!_theListView.isHidden) {
        [self barListBtnPressed:nil];
    }
    UIViewController *mapViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"mapViewController"];
    [self showViewController:mapViewController sender:self];
    //[self performSegueWithIdentifier:@"showMapSegue" sender:nil];
}

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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return postWallArray.count;
}

- (IBAction)addUserImageButtonPressed:(id)sender{
    UIButton *btn = sender;
    NSLog(@"%@",btn.titleLabel.text);
    //PersonalPageViewController *myPersonalPageViewController = [PersonalPageViewController new];
    //[myPersonalPageViewController passData:btn.titleLabel.text];
    //[self presentViewController:myPersonalPageViewController animated:YES completion:nil];
    //[self.navigationController pushViewController:myPersonalPageViewController animated:YES];
    [self performSegueWithIdentifier:@"goPersonalPageFromTrend" sender:btn.titleLabel.text];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellIdentifier=@"TrendCell";
    TrendTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.block = ^(UIAlertController *alert){
        [self presentViewController:alert animated:YES completion:nil];
    };
    cell.userImage.layer.cornerRadius = cell.userImage.bounds.size.width/2;

    /*
    NSDictionary *userSchedulesA=postWallArray[indexPath.row];
    //每一筆為NSDictionary

    //cell.textLabel.text=@"123";
    cell.headImg=userSchedulesA[@"image1"];
    cell.clockImg=userSchedulesA[@"image2"];
    cell.contentImg=userSchedulesA[@"image3"];
    cell.sportImg=userSchedulesA[@"image4"];
    */

    postWallObject = postWallArray[indexPath.row];
    PFImageView *imageView = [PFImageView new];

//    NSURL *url = [[NSBundle mainBundle] URLForResource:@"InternetSlowdown_Day" withExtension:@"gif"];
//    imageView.image = [UIImage animatedImageWithAnimatedGIFData:[NSData dataWithContentsOfURL:url]];

    imageView.image = [UIImage imageNamed:@"loading.jpg"]; // placeholder image
    imageView.file = (PFFile *)postWallObject[@"image1"]; // remote image

    //[imageView loadInBackground];
    cell.postImage.image = imageView.image;
    [imageView loadInBackground:^(UIImage *image,  NSError * error){
        imageView.image = image;
        cell.postImage.image = imageView.image;
    }];

    //NSData *imageData = [imageView.file getData];
    cell.postImage.image = imageView.image;//[UIImage imageWithData:imageData];

    cell.contentLabel.text = postWallObject[@"content"];
    NSString *sportType = postWallObject[@"sportsType"];
    cell.sportTypeImage.image = [UIImage imageNamed:sportType];

    cell.locationLabel.text = postWallObject[@"location"];

    //PFObject *user = [postWallDictionary objectForKey:@"user"];

    PFObject *user = postWallObject[@"user"];

    cell.userName.text = @"";

    [user fetchInBackgroundWithBlock:^(PFObject *user,NSError *error){

        NSString *username = user[@"username"];
        cell.userName.text = username;

        userImage.file = (PFFile *)user[@"userImage"];

        [userImage loadInBackground:^(UIImage *image,NSError *error){
            userImage.image = image;
            cell.userImage.image = userImage.image;
        }];

        cell.userImage.image = userImage.image;

        [cell.contentView.layer setBorderColor:[UIColor whiteColor].CGColor];
        [cell.contentView.layer setBorderWidth:8.0f];

        // add addUserImageButton button
        UIButton *addUserImageButton = [UIButton new];
        addUserImageButton.frame = cell.userImage.frame;
        [addUserImageButton setTitle:username forState:UIControlStateNormal];
        [addUserImageButton setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
        [cell addSubview:addUserImageButton];
        [addUserImageButton addTarget:self
                               action:@selector(addUserImageButtonPressed:)
                     forControlEvents:UIControlEventTouchUpInside];

    }];

    userImage.image = [UIImage imageNamed:@"camera"];

    NSArray *tmpArray = postWallObject[@"like"];
    int number = (int)tmpArray.count;
    if (number == 0) {
        NSString *likesString = [NSString stringWithFormat:@"%d👍🏿",number];
        [cell.likesButton setTitle:likesString forState:UIControlStateNormal];
    }else{
        for (NSString *tmpString in tmpArray)
        {
            if ([tmpString isEqualToString:currentUser.objectId]) {
                NSString *likesString = [NSString stringWithFormat:@"%d👍🏻",number];
                [cell.likesButton setTitle:likesString forState:UIControlStateNormal];
            }else{
                NSString *likesString = [NSString stringWithFormat:@"%d👍🏿",number];
                [cell.likesButton setTitle:likesString forState:UIControlStateNormal];
            }
        }
    }
    [cell setValue:postWallObject.objectId forKey:@"cellObjectId"];

    //TrendTableViewCell *myTrendTableViewCell = [TrendTableViewCell new];
    //[myTrendTableViewCell getCellObjectId:postWallObject.objectId];

    //cell.userImage.image = userImage.image;

    //    PFFile *userImageData = user[@"userImage"];

    //    NSData *userImage = [userImageData getData];
    //    cell.userImage.image = [UIImage imageWithData:userImage];

    //PFObject *postWallObject = postWallArray[indexPath.row];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *postTime = postWallObject.createdAt;
    NSString *strDate = [dateFormatter stringFromDate:postTime];
    cell.timeLabel.text = strDate;

    //以下為usernameLabel新增連結
    UITapGestureRecognizer *singleTap1 =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userNameLabelPressed:)];

    [cell.userName setUserInteractionEnabled:TRUE];
    //[cell.userImage setUserInteractionEnabled:TRUE];
    [cell.userName addGestureRecognizer:singleTap1];
    //[cell.userImage addGestureRecognizer:singleTap2];
    cell.userName.tag = indexPath.row;

    UITapGestureRecognizer *singleTap2 =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(postImagePressed:)];

    [cell.postImage setUserInteractionEnabled:TRUE];
    //[cell.userImage setUserInteractionEnabled:TRUE];
    [cell.postImage addGestureRecognizer:singleTap2];
    //[cell.userImage addGestureRecognizer:singleTap2];
    //cell.postImage.tag = indexPath.row;

    postWallObject = postWallArray[indexPath.row];
    selectObjectId = postWallObject.objectId;
    cell.postImage.ObjectIdStr=selectObjectId;
    return cell;
}
/*
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [datas removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/
/*
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //以下可以辨識點擊哪一行
    UITableViewCell * cell = [_tableView cellForRowAtIndexPath:indexPath];
    NSLog(@"cell title:%@ and row:%li",cell.textLabel.text,indexPath.row);
}
*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    postWallObject = postWallArray[indexPath.row];
    selectObjectId = postWallObject.objectId;
    //    endRecordingTableViewController *detailPostView = [self.storyboard instantiateViewControllerWithIdentifier:@"endRecordingView"];
    //    [self.navigationController showViewController:detailPostView sender:nil];
    [self performSegueWithIdentifier:@"homeGoDetailView" sender:nil];

}
- (void) didConfirmBeFriend{   //確認是否有好友邀請名單

    //init
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];   /**< NSUserDefaults */
    NSMutableDictionary *notidicationDictionary = [NSMutableDictionary new];    /**< 消息通知 */
    NSMutableArray *addFriendArray = [NSMutableArray new];  /**< 所有的待確認好友objectId */

    NSMutableArray *unConfirmfriendsArray = [NSMutableArray new];
    currentUser=[PFUser currentUser];
    PFQuery *query = [PFQuery queryWithClassName:@"Friends"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error){
        NSLog(@"%@",array[0]);
        for (PFObject *pfobject in array) {
            for (NSObject *object in pfobject[@"unFriends"]) {
                if ([[NSString stringWithFormat:@"%@",object] caseInsensitiveCompare:currentUser.objectId]==NSOrderedSame) {
                    PFUser *otherPerson = pfobject[@"user"];
                    [otherPerson fetch];    //取值
                    NSString *tempNameString = otherPerson.username;
                    NSString *tempString = otherPerson.objectId;

                    NSString *tempAddString = [NSString stringWithFormat:@"%@&%@",tempString,tempNameString];
                    [addFriendArray addObject:tempAddString];

                }
                [unConfirmfriendsArray addObject:object];
            }
        }

        notidicationNumber = (int)addFriendArray.count;
        //存檔
        [notidicationDictionary setObject:addFriendArray forKey:@"addFriend"];
        [userDefaults setObject:notidicationDictionary forKey:@"notidicationDictionary"];
        //設定好後只是單純的cache住,要存進硬碟要用,才真正儲存
        [userDefaults synchronize];

        [self showNotidicationBadge:notidicationNumber];
    }];

}

- (void) showNotidicationBadge:(int)number{
    if (number > 0) {
        [_notidicationButton showBadgeWithStyle:WBadgeStyleRedDot value:number animationType:WBadgeAnimTypeScale];
        [_notidicationButton showBadge];
    }
}

- (IBAction)notidicationBtnPressed:(id)sender {
    [_notidicationButton clearBadge];
}

-(void)userNameLabelPressed:(id)sender
{

    [self performSegueWithIdentifier: @"goPersonalPageFromTrend" sender:[sender view]];
}

-(void)postImagePressed:(id)sender{
    if (_theListView.isHidden) {
        [self performSegueWithIdentifier: @"homeGoDetailView" sender:[sender view]];
    }
    [self toTap];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"goPersonalPageFromTrend"])
    {
        //以下是按cell的使用者名字傳輸的資料
        PersonalPageViewController *controller = (PersonalPageViewController *)[segue destinationViewController];

        //NSLog(@"cell.userName.text:%d",[sender isMemberOfClass:[UILabel class]]);

        if ([sender isMemberOfClass:[UILabel class]]) {
            [controller passData:[sender text]];
        }else{
            [controller passData:sender];
        }

    }
    //以下是按個人動態按鈕傳輸的資料
    if ([[segue identifier] isEqualToString:@"goPersonalPageFromTrend2"])
    {
        currentUser = [PFUser currentUser];//抓到目前user的objId
        NSString *Uname = [currentUser objectForKey:@"username"];
        NSLog(@"user: %@",Uname);

        PersonalPageViewController *controller = (PersonalPageViewController *)[segue destinationViewController];
        //NSLog(@"cell.userName.text:%@",[sender text]);

        [controller passData:Uname];
    }
    //進入detail頁面
    if ([[segue identifier] isEqualToString:@"homeGoDetailView"]){
        endRecordingTableViewController *controller = (endRecordingTableViewController *)[segue destinationViewController];

        if ([sender isKindOfClass:[myPostImageView class]]) {
            [controller getObjectID:[sender ObjectIdStr]];

        }else{
            [controller getObjectID:selectObjectId];
            //[controller getObjectID:sender];
        }

    }

}

-(void)initHamburgerButton{
    _buttonHamburgerCloseSmall = [[LBHamburgerButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)
                                                        withHamburgerType:LBHamburgerButtonTypeCloseButton
                                                                lineWidth:20
                                                               lineHeight:20/6
                                                              lineSpacing:2
                                                               lineCenter:CGPointMake(25, 25)
                                                                    color:[UIColor whiteColor]];
    [_buttonHamburgerCloseSmall setCenter:CGPointMake(_buttonHamburgerCloseSmall.center.x + 100, 120)];
    //[_buttonHamburgerCloseSmall setBackgroundColor:[UIColor blackColor]];
    [_buttonHamburgerCloseSmall addTarget:self action:@selector(barListBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
}

-(void) initPauseButton{
    _goButton.titleLabel.font = [UIFont systemFontOfSize:22];
    _goButton.layer.cornerRadius = _goButton.bounds.size.width/2;
    [_goButton setTitleColor:[UIColor colorWithWhite:1 alpha:1.0] forState:UIControlStateNormal];
    [_goButton setTitleColor:[UIColor colorWithWhite:1 alpha:1.0] forState:UIControlStateSelected];
    [_goButton setTitleColor:[UIColor colorWithWhite:1 alpha:1.0] forState:UIControlStateHighlighted];
    _goButton.backgroundColor = [UIColor colorWithRed:57.0f/255.0f green:88.0f/255.0f blue:100.0f/255.0f alpha:1];

    _goButton.layer.shadowColor = [UIColor blackColor].CGColor;
    _goButton.layer.shadowOffset = CGSizeMake(1.0, 1.0);
    _goButton.layer.shadowOpacity = YES;

    _theListView.layer.shadowColor = [UIColor blackColor].CGColor;
    _theListView.layer.shadowOffset = CGSizeMake(1.0, 0);
    _theListView.layer.shadowOpacity = 0.8;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if (_theListView.isHidden) {
        return NO;
    }
    return YES;
}

@end


text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: iam_mfa_device_facts
short_description: List the MFA (Multi-Factor Authentication) devices registered for a user
description:
    - List the MFA (Multi-Factor Authentication) devices registered for a user
version_added: "2.2"
author: Victor Costan (@pwnall)
options:
  user_name:
    description:
      - The name of the user whose MFA devices will be listed
    required: false
    default: null
extends_documentation_fragment:
    - aws
    - ec2
requirements:
    - boto3
    - botocore
'''

RETURN = """
mfa_devices:
    description: The MFA devices registered for the given user
    returned: always
    type: list
    sample:
      - enable_date: "2016-03-11T23:25:36+00:00"
        serial_number: arn:aws:iam::085120003701:mfa/pwnall
        user_name: pwnall
      - enable_date: "2016-03-11T23:25:37+00:00"
        serial_number: arn:aws:iam::085120003702:mfa/pwnall
        user_name: pwnall
"""

EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.

# List MFA devices (more details: http://docs.aws.amazon.com/IAM/latest/APIReference/API_ListMFADevices.html)
iam_mfa_device_facts:
register: mfa_devices

# Assume an existing role (more details: http://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html)
sts_assume_role:
  mfa_serial_number: "{{ mfa_devices.mfa_devices[0].serial_number }}"
  role_arn: "arn:aws:iam::123456789012:role/someRole"
  role_session_name: "someRoleSession"
register: assumed_role
'''

try:
    import boto3
    from botocore.exceptions import ClientError
    HAS_BOTO3 = True
except ImportError:
    HAS_BOTO3 = False

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import (HAS_BOTO3, boto3_conn, camel_dict_to_snake_dict, ec2_argument_spec,
                                      get_aws_connection_info)

def list_mfa_devices(connection, module):
    user_name = module.params.get('user_name')
    changed = False

    args = {}
    if user_name is not None:
        args['UserName'] = user_name
    try:
        response = connection.list_mfa_devices(**args)
    except ClientError as e:
        module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response))

    module.exit_json(changed=changed, **camel_dict_to_snake_dict(response))

def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            user_name=dict(required=False, default=None)
        )
    )

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 required for this module')

    region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
    if region:
        connection = boto3_conn(module, conn_type='client', resource='iam', region=region, endpoint=ec2_url, **aws_connect_kwargs)
    else:
        module.fail_json(msg="region must be specified")

    list_mfa_devices(connection, module)

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaGithub


text:
#include "qscriptclasspropertyiterator.h"

#include "qscriptstring.h"

QT_BEGIN_NAMESPACE

/*!
  \since 4.4
  \class QScriptClassPropertyIterator

  \brief The QScriptClassPropertyIterator class provides an iterator interface for custom Qt Script objects.

  \ingroup script

  This class is only relevant if you have subclassed QScriptClass and
  want to provide enumeration of your custom properties (e.g. when
  objects of your class are used with QScriptValueIterator, or with
  the for-in statement in scripts).

  The object() function returns the Qt Script object the iterator is
  traversing.

  toFront(), hasNext() and next() provide forward iteration.

  toBack(), hasPrevious() and previous() provide backward iteration.

  name(), id() and flags() return information about the last property
  that was jumped over using next() or previous().

  \sa QScriptClass::newIterator(), QScriptValueIterator
*/

class QScriptClassPropertyIteratorPrivate
{
    Q_DECLARE_PUBLIC(QScriptClassPropertyIterator)
public:
    QScriptClassPropertyIteratorPrivate() {}
    virtual ~QScriptClassPropertyIteratorPrivate() {}

    QScriptValue object;

    QScriptClassPropertyIterator *q_ptr;
};

/*!
  Constructs an iterator for traversing \a object.

  Subclasses should ensure that the iterator is set to the front of the
  sequence of properties (before the first property).
*/
QScriptClassPropertyIterator::QScriptClassPropertyIterator(const QScriptValue &object)
    : d_ptr(new QScriptClassPropertyIteratorPrivate)
{
    d_ptr->q_ptr = this;
    d_ptr->object = object;
}

/*!
  \internal
*/
QScriptClassPropertyIterator::QScriptClassPropertyIterator(const QScriptValue &object,
                                           QScriptClassPropertyIteratorPrivate &dd)
    : d_ptr(&dd)
{
    d_ptr->q_ptr = this;
    d_ptr->object = object;
}

/*!
  Destroys the iterator.
*/
QScriptClassPropertyIterator::~QScriptClassPropertyIterator()
{
}

/*!
  Returns the Qt Script object this iterator is traversing.
*/
QScriptValue QScriptClassPropertyIterator::object() const
{
    Q_D(const QScriptClassPropertyIterator);
    return d->object;
}

/*!
  \fn bool QScriptClassPropertyIterator::hasNext() const

  Returns true if there is at least one item ahead of the iterator
  (i.e. the iterator is \e not at the back of the property sequence);
  otherwise returns false.

  \sa next(), hasPrevious()
*/

/*!
  \fn void QScriptClassPropertyIterator::next()

  Advances the iterator by one position.

  Calling this function on an iterator located at the back of the
  container leads to undefined results.

  \sa hasNext(), previous(), name()
*/

/*!
  \fn bool QScriptClassPropertyIterator::hasPrevious() const

  Returns true if there is at least one item behind the iterator
  (i.e. the iterator is \e not at the front of the property sequence);
  otherwise returns false.

  \sa previous(), hasNext()
*/

/*!
  \fn void QScriptClassPropertyIterator::previous()

  Moves the iterator back by one position.

  Calling this function on an iterator located at the front of the
  container leads to undefined results.

  \sa hasPrevious(), next(), name()
*/

/*!
  \fn void QScriptClassPropertyIterator::toFront()

  Moves the iterator to the front of the QScriptValue (before the
  first property).

  \sa toBack(), next()
*/

/*!
  \fn void QScriptClassPropertyIterator::toBack()

  Moves the iterator to the back of the QScriptValue (after the
  last property).

  \sa toFront(), previous()
*/

/*!
  \fn QScriptString QScriptClassPropertyIterator::name() const

  Returns the name of the last property that was jumped over using
  next() or previous().

  \sa id()
*/

/*!
  \fn uint QScriptClassPropertyIterator::id() const

  Returns the id of the last property that was jumped over using
  next() or previous().

  The default implementation returns 0.

  \sa name()
*/
uint QScriptClassPropertyIterator::id() const
{
    return 0;
}

/*!
  Returns the flags of the last property that was jumped over using
  next() or previous().

  The default implementation calls the propertyFlags() function of
  object() with argument name().
*/
QScriptValue::PropertyFlags QScriptClassPropertyIterator::flags() const
{
    return object().propertyFlags(name());
}

QT_END_NAMESPACE


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class energy.usef.brp.workflow.plan.flexorder.acknowledge.FlexOrderAcknowledgementEvent (usef-root-pom 1.3.6 API)</title>
<meta name="date" content="2016-09-29">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
energy.usef.brp.workflow.plan.flexorder.acknowledge.FlexOrderAcknowledgementEvent

Packages that use FlexOrderAcknowledgementEvent

Package
Description

energy.usef.brp.workflow.plan.flexorder.acknowledge

Classes for flex order acknowledgment in the plan phase for the Balance Responsible Party.

Uses of FlexOrderAcknowledgementEvent in energy.usef.brp.workflow.plan.flexorder.acknowledge

Methods in energy.usef.brp.workflow.plan.flexorder.acknowledge with parameters of type FlexOrderAcknowledgementEvent

Modifier and Type
Method and Description

void
BrpFlexOrderAcknowledgementCoordinator.handleEvent(FlexOrderAcknowledgementEvent event)

Handle Event.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016. All rights reserved.


text:
package net.liftweb {
package util {

import _root_.java.util.GregorianCalendar
import _root_.org.specs.runner._
import _root_.org.specs._
import common._

object Title2 extends EnumWithDescription {
    val mr = Value("MR", "Mr")
    val mrs = Value("MRS", "Mrs")
    val dr = Value("DR", "Dr")
    val sir = Value("SirS", "Sir")
}

object T2 extends EnumWithDescription {
    val mr = Value("MR", "Mr")
    val mrs = Value("MRS", "Mrs")
}

class EnumWithDescriptionSpecTest extends JUnit4(EnumWithDescriptionSpec)
object EnumWithDescriptionSpec extends Specification {

    "An enumWithDescription" should {
        "have a name" in {
            val t = T2.valueOf("MR") == Some(T2.mr)
            t must beTrue
        }

        "have a name" in {
            Title2.mr.toString must_== "MR"
        }

        "have a type 1" in {
            Title2.mr mustEqual Title2.mr
        }

        "have a type 2" in {
            Title2.mr mustEqual Title2.valueOf("MR").getOrElse(null)
        }

        "have a type 3" in {
            Title2.dr mustEqual Title2.valueOf("DR").getOrElse(null)
        }

        "have a mr description" in {
            Title2.mr.description must_== "Mr"
        }

        "be able to be created from a string name" in {
            Title2.valueOf("MRS").getOrElse(null) mustEqual Title2.mrs
        }

        "have a mrs description" in {
            Title2.valueOf("MRS").getOrElse(null).description mustMatch "Mrs"
        }
    }

}

}
}


text:
module.exports = function(stager, settings) {

    stager
        //.next('precache')
        //.next('selectLanguage')
        .next('instructions')
        .next('quiz')
        .next('quiz2')
        .repeat('choices', settings.REPEAT)
        .next('final')
        .gameover();

//    stager.skip('instructions');
//    stager.skip('selectLanguage');
//    stager.skip('quiz');
//    stager.skip('quiz2');

    stager.extendStage('choices', {steps: ['decision', 'feedback']});

    stager.extendStage('final', {steps: [
        'totalpayoff',
        'questionnaire1',
        'questionnaire2',
        'questionnaire3',
        'endgame'
    ]})
};


text:
Jumuah assist application build for Android.

## Dev. Information

App is in early development.

## License

Jumuah Assist for Android is available under the MIT license. See the LICENSE file for more info.


text:
{{define "head"}}
<!doctype html>
<html lang="en" xmlns:ng="http://angularjs.org" id="ng-app" ng-app="xrguide">
<head>
    <title>{{.Data.title}}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!--[if lte IE 8]>
    <script src="/js/json2.js"></script>
    <script>
        document.createElement('ng-include');
        document.createElement('ng-pluralize');
        document.createElement('ng-view');

        // Optionally these for CSS
        document.createElement('ng:include');
        document.createElement('ng:pluralize');
        document.createElement('ng:view');
    </script>
    <![endif]-->
	<link rel="stylesheet" href="/css/bootstrap.min.css" />
    <link rel="stylesheet" href="/css/xrguide.css" />
</head>
{{end}}
{{define "body_start"}}
<body>
{{template "nav" .}}
<div id="c" class="container ng-view">
{{end}}
{{define "body_end"}}
</div>
{{end}}


text:
{% extends 'base.html' %}
{% block head %}
  {{super()}}
{% endblock %}
{% block scripts %}
  {{ super() }}
{% endblock %}
{% block header %}
	{{super()}}
{% endblock %}
{% block main %}

        A tradução da documentação ainda será traduzida para o português. Enquanto isso você pode acessar a documentação
        oficial aqui.

{% endblock %}


text:
/*
 * This comment deals with the different types of arc storages.
 *
 * Oryx saves an arc like this. Each arc has an own resourceId. Furthermore it has
 * a key "target" which references the target of the arc. In the case of Colored Petri Nets
 * it can be a transition or a place. But where is the referenceId to the orign of the arc?
 * Somewhere in the JSON you will find a transition or place which has as an outgoingId that arc.
 * So then you know that this transition or place is the origin of the arc.
 *
 * CPN Tools does it a little bit different. Each arc has also an id. But in difference
 * to Oryx CPN Tools saves the orign and the target of the arc in the same tag arc tag. The arc
 * tag has a referenceId to a transition and to a place. Furthermore it has an attribute
 * called "orientation" with the values "PtoT" (Place to Transition), "TtoP" (transition to Place).
 *
 * What is the problem?
 *
 * Using the XMLConvertable let you parse through the whole JSON structure and grap each element
 * one by one. So when I got to the point where I grab the arc element in the JSON I have the
 * target Id. But I don't know nothing about the orign or even the orign Id of the arc.
 *
 * What is the solution?
 *
 * The class CPNArcRelations is responsible for saving the orign and the target to each arc.
 * The class consits of two hashtables, a source table and a target table. Because every arc
 * has only one orgin and only one target, I decide that the arc resourceId is the key in both tables.
 * Source and target table are defined like this:
 * 		resourceId of the arc ---> resourceId of a transition or place.
 *
 * But there is another problem. A resourceId in Oryx is in most cases something like
 * this, "oryx_FCDB338C-3D8D-450F-B27F-B5EA0610F140". But CPN Tools can't do anything with that id.
 * It only understands id like "ID171135".
 *
 * So my algorithm for translating the arc relation into the CPN Tools format consists of three steps.
 * 1. Prepare CPNArcRelations:
 * Before this class is called the algorithm iterates over the JSON structure and
 * grabs all necessary ids to fill the two hashtables. After that is done, every arc is registered in
 * that table.
 * 2. Changing the ids in CPNArcRelations:
 * Like I said before CPN Tools can't understand any resourceId Oryx generates. So the algorithm
 * has to create an id for CPN Tools by it's own. But now every mapped element has another id than
 * this one saved in CPNArcRelations. So CPNArcRelations is useless. Therefore the algorithm changes
 * the resourceId of all places and transitions in CPNArcRelations into ids that CPN Tools can
 * understand.
 * 3. Doing the mapping:
 * When the steps before are done then the mapping of the arcs can begin. Notice that CPNArcRelations
 * is only necessary for the arc mapping. That's the reason why the creation of the arcs starts
 * after every place and transition is mapped.
 *
 * */

package de.hpi.cpn.elements;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.thoughtworks.xstream.XStream;

import de.hpi.cpn.attributes.CPNLittleProperty;
import de.hpi.cpn.attributes.CPNModellingThing;
import de.hpi.cpn.attributes.CPNTextConverter;
import de.hpi.cpn.mapperhelper.CPNArcRelations;
import de.hpi.cpn.mapperhelper.CPNNodePositions;
import de.hpi.cpn.mapperhelper.XMLConvertable;

public class CPNPage extends XMLConvertable
{
	//	Example
	//	<page id="ID6">
	//    <pageattr name="Tutorial"/>
	//	  <place id="ID23568">
	//			...
	//	  </place>
	//			...
	//	</page>

	// Elements which are neither important for the Export nor the Import, but these elements
	// are necessary for XStream otherwise XStream raises an error
	@SuppressWarnings("unused")
	private transient Object auxtag, grouptag, vguidelines, hguidelines;

	// These variables are not needed directly for serialization of the XML
	// They are only variables that helps to export / import the files
	private CPNArcRelations arcRelation = new CPNArcRelations();
	private CPNNodePositions nodePositions = new CPNNodePositions();

	private String idattri;
	private CPNPageattr pageattr = new CPNPageattr();
	private ArrayList<CPNPlace> places = new ArrayList<CPNPlace>();
	private ArrayList<CPNTransition> transitions = new ArrayList<CPNTransition>();
	private ArrayList<CPNArc> arcs = new ArrayList<CPNArc>();

	// ---------------------------------------- Mapping ----------------------------------------

	public static void registerMapping(XStream xstream)
	{
		// In the XML the class is represented as a page - tag
		xstream.alias("page", CPNPage.class);

		xstream.useAttributeFor(CPNPage.class, "idattri");
		xstream.aliasAttribute(CPNPage.class, "idattri", "id");

		// In order not to display the places / transitions / arcs tag, but simply show
		// the page tags one after another.
		xstream.addImplicitCollection(CPNPage.class, "places", CPNPlace.class);
		xstream.addImplicitCollection(CPNPage.class, "transitions", CPNTransition.class);
		xstream.addImplicitCollection(CPNPage.class, "arcs", CPNArc.class);

		// Sometimes XStream cannot translate elements into a XML structure.
		// Therefore exists the possibility to create and register a converter for that element.
		xstream.registerConverter(new CPNTextConverter());

		// These instance variables are not needed for the mapping, that's why they are excluded
		xstream.omitField(CPNPage.class, "arcRelation");
		xstream.omitField(CPNPage.class, "nodePositions");

		// Giving all fields a concrete name for the XML
		xstream.aliasField("Aux", CPNPage.class, "auxtag");
		xstream.aliasField("group", CPNPage.class, "grouptag");
		xstream.aliasField("vguidelines", CPNPage.class, "vguidelines");
		xstream.aliasField("hguidelines", CPNPage.class, "hguidelines");

		CPNPageattr.registerMapping(xstream);
		CPNModellingThing.registerMapping(xstream);
		CPNPlace.registerMapping(xstream);
		CPNTransition.registerMapping(xstream);
		CPNArc.registerMapping(xstream);
		CPNLittleProperty.registerMapping(xstream);
	}

	// ----------------------------------- JSON Reader  ----------------------------------------

	public void readJSONpageId(JSONObject modelElement) throws JSONException
	{
		String Id = modelElement.getString("pageId");
		setId(Id);
	}

	public void readJSONproperties(JSONObject modelElement) throws JSONException
	{
		JSONObject properties = new JSONObject(modelElement.getString("properties"));
		this.readJSONtitle(properties);
	}

	public void readJSONtitle(JSONObject modelElement) throws JSONException
	{
		String title = modelElement.getString("title");

		// In order to give the diagram a title
		if (title.isEmpty())
			title = "Exported CPN";

		getPageattr().setName(title);
	}

	public void readJSONchildShapes(JSONObject modelElement) throws JSONException
	{
		// See the comment in the first line

		// Creating a queue
		JSONArray arcs = new JSONArray();

		// Get all childshapes
		JSONArray childShapes = modelElement.optJSONArray("childShapes");

		if (childShapes != null)
		{
			int i;
			for ( i = 0; i < childShapes.length(); i++)
			{
				JSONObject childShape = childShapes.getJSONObject(i);
				String stencil = childShape.getJSONObject("stencil").getString("id");

				// Looking whether it is a transition, place or an arc
				if (CPNTransition.handlesStencil(stencil))
					createTransition(childShape,i);

				else if (CPNPlace.handlesStencil(stencil))
					createPlace(childShape, i);

				// Putting every arc in the queue in order to wait that every
				// place and transition is mapped.
				else if (CPNArc.handlesStencil(stencil))
					arcs.put(childShape);
			}

			// After every place and transition is mapped,
			// we can begin to map the arcs in the queue.
			for (i = 0; i < arcs.length(); i++)
				createArc(arcs.getJSONObject(i), i);

		}
	}

	// -------------------------------- Helper --------------------------------------------

	private void createPlace(JSONObject modelElement, int index) throws JSONException
	{
		// Generating the id for the place.
		// In order to have more space (difference of the ids) between each place element I
		// multiply the index with 10. So the difference of the ids is always 10.
		// The space is needed because each place has childnodes which have also id.
		String resourceId = modelElement.getString("resourceId");
		String placeId = "ID" + (3000 + index * 10);

		// Correct the Hashtable - Entry for that place
		getArcRelation().changePlaceId(resourceId, placeId);
		// Load the position of the place into the NodePositions class
		getNodePositions().newNodePosition(placeId, modelElement);

		CPNPlace place = new CPNPlace();
		place.setId(placeId);
		place.parse(modelElement);

		getPlaces().add(place);
	}

	private void createTransition(JSONObject modelElement, int index) throws JSONException
	{
		// See comments above in createPlace(...)
		String resourceId = modelElement.getString("resourceId");
		String transId = "ID" + (4000 + index * 10);

		getArcRelation().changeTransitionId(resourceId, transId);
		getNodePositions().newNodePosition(transId, modelElement);

		CPNTransition transition = new CPNTransition();
		transition.setId(transId);
		transition.parse(modelElement);

		getTransitions().add(transition);
	}

	private void createArc(JSONObject modelElement, int index) throws JSONException
	{
		String resourceId = modelElement.getString("resourceId");
		// Getting source and target of the arc
		String target = getArcRelation().getTargetValue(resourceId);
		String source = getArcRelation().getSourceValue(resourceId);
		String arcId = "ID" + (5000 + index * 10);

		String transend, placeend, orientation;

		// Setting the orientation of the arc
		if (isTransition(target))
		{
			transend = target;
			placeend = source;
			orientation = "PtoT";
		}
		else
		{
			transend = source;
			placeend = target;
			orientation = "TtoP";
		}

		modelElement.put("transend", transend);
		modelElement.put("placeend", placeend);
		modelElement.put("orientation", orientation);

		CPNArc arc = new CPNArc();

		arc.setId(arcId);
		arc.parse(modelElement);

		arc.positionAnnotation(getNodePositions());
		arc.organizeBendpoints();

		getArcs().add(arc);
	}

	public void prepareArcRelations(JSONObject modelElement) throws JSONException
	{
		getArcRelation().fill(modelElement);
	}

	private boolean isTransition(String Id)
	{
		// I defined that every transition starts with the id number 4...
		char letterafterId = Id.charAt(2);

		return letterafterId == '4';
	}

	// ------------------------------ Accessor ------------------------------------------
    public String getId()
    {
       return this.idattri;
    }
    public void setId(String _id)
    {
       this.idattri = _id;
    }

    public CPNPageattr getPageattr()
    {
       return this.pageattr;
    }
    public void setPageattr(CPNPageattr _pageattr)
    {
       this.pageattr = _pageattr;
    }

    public ArrayList<CPNPlace> getPlaces()
    {
       return this.places;
    }
    public void setPlaces(ArrayList<CPNPlace> _places)
    {
       this.places = _places;
    }
    public void addPlace(CPNPlace _place)
    {
       this.places.add(_place);
    }
    public void removePlace(CPNPlace _place)
    {
       this.places.remove(_place);
    }
    public CPNPlace getPlace( int i)
    {
       return (CPNPlace) this.places.get(i);
    }

    public ArrayList<CPNArc> getArcs()
    {
       return this.arcs;
    }
    public void setArcs(ArrayList<CPNArc> _arcs)
    {
       this.arcs = _arcs;
    }
    public void addArc(CPNArc _arc)
    {
       this.arcs.add(_arc);
    }
    public void removeArc(CPNArc _arc)
    {
       this.arcs.remove(_arc);
    }
    public CPNArc getArc( int i)
    {
       return (CPNArc)this.arcs.get(i);
    }

    public ArrayList<CPNTransition> getTransitions()
    {
       return this.transitions;
    }
    public void setTransitions(ArrayList<CPNTransition> _transs)
    {
       this.transitions = _transs;
    }
    public void addTransition(CPNTransition _trans)
    {
       this.transitions.add(_trans);
    }
    public void removeTransition(CPNTransition _trans)
    {
       this.transitions.remove(_trans);
    }
    public CPNTransition getTrans( int i)
    {
       return (CPNTransition) this.transitions.get(i);
    }

	public void setArcRelation(CPNArcRelations arcRelation)
	{
		this.arcRelation = arcRelation;
	}
	public CPNArcRelations getArcRelation()
	{
		return arcRelation;
	}

	public void setNodePositions(CPNNodePositions nodePositions)
	{
		this.nodePositions = nodePositions;
	}
	public CPNNodePositions getNodePositions()
	{
		return nodePositions;
	}
}


text:
title: Flink Batch Example JAVA
---
## Flink Batch Example JAVA

Apache Flink is an open source stream processing framework with powerful stream- and batch-processing capabilities.

### Prerequisites

* Unix-like environment (Linux, Mac OS X, Cygwin)
* git
* Maven (we recommend version 3.0.4)
* Java 7 or 8
* IntelliJ IDEA or Eclipse IDE

```
git clone https://github.com/apache/flink.git
cd flink
mvn clean package -DskipTests # this will take up to 10 minutes
```

### Datasets

For the batch processing data we'll be using the datasets in here: [datasets](http://files.grouplens.org/datasets/movielens/ml-latest-small.zip)
In this example we'll be using the movies.csv and the ratings.csv, create a new java project and put them in a folder in the application base.

### Example

We're going to make an execution where we retrieve the average rating by movie genre of the entire dataset we have.

**Environment and datasets**

First create a new Java file, I'm going to name it AverageRating.java

The first thing we'll do is to create the execution environment and load the csv files in a dataset. Like this:

```
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<Tuple3<Long, String, String>> movies = env.readCsvFile("ml-latest-small/movies.csv")
  .ignoreFirstLine()
  .parseQuotedStrings('"')
  .ignoreInvalidLines()
  .types(Long.class, String.class, String.class);

DataSet<Tuple2<Long, Double>> ratings = env.readCsvFile("ml-latest-small/ratings.csv")
  .ignoreFirstLine()
  .includeFields(false, true, true, false)
  .types(Long.class, Double.class);
```

There, we are making a dataset with a <Long, String, String> for the movies, ignoring errors, quotes and the header line, and a dataset with <Long, Double> for the movie ratings, also ignoring the header, invalid lines and quotes.

**Flink Processing**

Here we will process the dataset with flink. The result will be in a List of String, Double tuples. where the genre will be in the String and the average rating will be in the double.

First we'll join the ratings dataset with the movies dataset by the moviesId present in each dataset.
With this we'll create a new Tuple  with the movie name, genre and score.
Later, we group this tuple by genre and add the score of all equal genres, finally we divide the score by the total results and we have our desired result.

```
List<Tuple2<String, Double>> distribution = movies.join(ratings)
  .where(0)
  .equalTo(0)
  .with(new JoinFunction<Tuple3<Long, String, String>,Tuple2<Long, Double>, Tuple3<StringValue, StringValue, DoubleValue>>() {
    private StringValue name = new StringValue();
    private StringValue genre = new StringValue();
    private DoubleValue score = new DoubleValue();
    private Tuple3<StringValue, StringValue, DoubleValue> result = new Tuple3<>(name,genre,score);

    @Override
    public Tuple3<StringValue, StringValue, DoubleValue> join(Tuple3<Long, String, String> movie,Tuple2<Long, Double> rating) throws Exception {
      name.setValue(movie.f1);
      genre.setValue(movie.f2.split("\\|")[0]);
      score.setValue(rating.f1);
      return result;
    }
})
  .groupBy(1)
  .reduceGroup(new GroupReduceFunction<Tuple3<StringValue,StringValue,DoubleValue>, Tuple2<String, Double>>() {
    @Override
    public void reduce(Iterable<Tuple3<StringValue,StringValue,DoubleValue>> iterable, Collector<Tuple2<String, Double>> collector) throws Exception {
      StringValue genre = null;
      int count = 0;
      double totalScore = 0;
      for(Tuple3<StringValue,StringValue,DoubleValue> movie: iterable){
        genre = movie.f1;
        totalScore += movie.f2.getValue();
        count++;
      }

      collector.collect(new Tuple2<>(genre.getValue(), totalScore/count));
    }
})
  .collect();
```

With this you'll have a working batch processing flink application. Enjoy!.


text:
// ======================================================================
/*!
 * \file
 * \brief Interface of namespace NFmiFileSystem
 */
// ======================================================================

#pragma once

#include "NFmiDef.h"

#include <ctime>   // time_t
#include <list>    // for ListDirectory
#include <string>  // filenames are strings

// Koska Winkkari headerissa
// on makro joka muuttaa funktion nimeä:
//
// #ifdef UNICODE
// #define CreateDirectory  CreateDirectoryW
// #else
// #define CreateDirectory  CreateDirectoryA
// #endif // !UNICODE

#if defined CreateDirectory
#undef CreateDirectory
#endif

// sama juttu CopyFile*:n kanssa
#if defined CopyFile
#undef CopyFile
#endif

namespace NFmiFileSystem
{
// File access checking:

bool FileExists(const std::string &theFile);
bool FileReadable(const std::string &theFile);
bool FileWritable(const std::string &theFile);
bool FileExecutable(const std::string &theFile);
size_t FileSize(const std::string &theFile);
bool FileEmpty(const std::string &theFile);

// Filename completion
const std::string FileComplete(const std::string &theFile, const std::string &theSearchPath);

std::time_t FileAccessTime(const std::string &theFile);
std::time_t FileModificationTime(const std::string &theFile);
std::time_t FileChangedTime(const std::string &theFile);
std::time_t FindFile(const std::string &theFileFilter,
                     bool fSearchNewest,
                     std::string *theFoundFileName);

long FileAge(const std::string &theFile);

bool DirectoryExists(const std::string &theFile);
bool DirectoryReadable(const std::string &theFile);
bool DirectoryWritable(const std::string &theFile);

bool CreateDirectory(const std::string &thePath);
const std::string NewestFile(const std::string &thePath);
std::time_t NewestFileTime(const std::string &thePath);
std::time_t NewestFileTime(const std::list<std::string> &theFileList, const std::string &thePath);
std::string NewestFileName(const std::list<std::string> &theFileList, const std::string &thePath);
std::time_t NewestPatternFileTime(const std::string &thePattern);
std::string NewestPatternFileName(const std::string &thePattern);
std::string FirstPatternFileName(const std::string &thePattern);
std::string PathFromPattern(const std::string &thePattern);
std::string FileNameFromPath(const std::string &theTotalPathAndFileStr);
const std::list<std::string> DirectoryFiles(const std::string &thePath);
const std::list<std::string> PatternFiles(const std::string &thePattern);
const std::list<std::pair<std::string, std::time_t> > PatternFiles(const std::string &thePattern,
                                                                   std::time_t timeLimit);
const std::list<std::string> Directories(const std::string &thePath);

bool RemoveFile(const std::string &theFile);
bool RenameFile(const std::string &theOldFileName, const std::string &theNewFileName);
bool CopyFile(const std::string &theSrcFileName, const std::string &theDstFileName);

bool ReadFile2String(const std::string &theFileName,
                     std::string &theFileContent,
                     long theMaxByteSize = 1024 * 1024 * 500);  // 500 MB
bool ReadFileStart2String(const std::string &theFileName,
                          std::string &theFileContent,
                          long theBytesFromStart);

const std::string TemporaryFile(const std::string &thePath);
const std::string BaseName(const std::string &theName);
const std::string DirName(const std::string &theName);

void CleanDirectory(const std::string &thePath,
                    double theMaxFileAgeInHours,
                    std::list<std::string> *theDeletedFilesOut = 0);
void CleanFilePattern(const std::string &theFilePattern,
                      int theKeepFileCount,
                      std::list<std::string> *theDeletedFilesOut = 0);

std::string FindQueryData(const std::string &thePath);
bool IsCompressed(const std::string &theName);
std::string MakeAbsolutePath(const std::string &theOrigPath,
                             const std::string &theWorkingDirectory);
bool IsAbsolutePath(const std::string &thePath);

void SafeFileSave(const std::string &theFileName, const std::string &theContents);

}  // namespace NFmiFileSystem

// ======================================================================


text:
                {{tag.name}}

        配置标签


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

import java.util.Map;

import org.apache.hadoop.hbase.HBaseInterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceStability;

/**
 * A set of named metrics.
 *
 * @see MetricRegistry#registerAll(MetricSet)
 */
@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.COPROC)
@InterfaceStability.Evolving
public interface MetricSet extends Metric {
    /**
     * A map of metric names to metrics.
     *
     * @return the metrics
     */
    Map<String, Metric> getMetrics();
}


text:
using System.Collections.Generic;
using DotVVM.Framework.Binding;

namespace DotVVM.Framework.Controls
{
    /// <summary>
    /// Adds a general mechanism to suppress PostBack.
    /// </summary>
    public class SuppressPostBackHandler : PostBackHandler
    {
        protected internal override string ClientHandlerName => "suppress";

        protected internal override Dictionary<string, object?> GetHandlerOptions()
        {
            return new Dictionary<string, object?>() {
                ["suppress"] = this.GetValueRaw(SuppressProperty)
            };
        }

        /// <summary>
        /// Gets or sets the condition to suppress a PostBack.
        /// </summary>
        public bool Suppress
        {
            get { return (bool)GetValue(SuppressProperty)!; }
            set { SetValue(SuppressProperty, value); }
        }
        public static readonly DotvvmProperty SuppressProperty
            = DotvvmProperty.Register<bool, SuppressPostBackHandler>(c => c.Suppress, true);
    }
}


text:
FROM ubuntu:16.04
MAINTAINER "Yugandha Deshpande <yugandha@us.ibm.com>"

RUN apt-get update \
	&& apt-get install -y --no-install-recommends \
		bsdmainutils libgomp1 make openmpi-bin ssh
ADD . /tmp/abyss
RUN apt-get install -y --no-install-recommends \
	        wget tar automake g++ libboost-dev libopenmpi-dev libsparsehash-dev \
	&& cd /tmp/ \
	&& wget https://github.com/bcgsc/abyss/releases/download/2.1.0/abyss-2.1.0.tar.gz --no-check-certificate \
	&& tar -zxvf abyss-2.1.0.tar.gz \
	&& cd abyss-2.1.0 \
	&& ./autogen.sh && ./configure --with-mpi=/usr/lib/openmpi \
	&& make install-strip \
	&& rm -rf /tmp/abyss \
	&& apt-get autoremove -y binutils \
		automake g++ libboost-dev libopenmpi-dev libsparsehash-dev

ENV TMPDIR /var/tmp
ENV SHELL=/bin/bash
ENTRYPOINT ["abyss-pe"]
CMD ["help"]


text:
"""
Integrated into :mod:`parse` module.
"""

from __future__ import absolute_import
from .parse_type_test import ParseTypeTestCase
from parse_type import build_type_dict
import parse
import unittest

# -----------------------------------------------------------------------------
# TEST CASE: TestParseTypeWithPatternDecorator
# -----------------------------------------------------------------------------
class TestParseTypeWithPatternDecorator(ParseTypeTestCase):
    """
    Test the pattern decorator for type-converter (parse_type) functions.

        >>> def parse_number(text):
        ...     return int(text)
        >>> parse_number.pattern = r"\d+"

    is equivalent to:

        >>> import parse
        >>> @parse.with_pattern(r"\d+")
        ... def parse_number(text):
        ...     return int(text)

        >>> assert hasattr(parse_number, "pattern")
        >>> assert parse_number.pattern == r"\d+"
    """

    def assert_decorated_with_pattern(self, func, expected_pattern):
        self.assertTrue(callable(func))
        self.assertTrue(hasattr(func, "pattern"))
        self.assertEqual(func.pattern, expected_pattern)

    def assert_converter_call(self, func, text, expected_value):
        value = func(text)
        self.assertEqual(value, expected_value)

    # -- TESTS:
    def test_function_with_pattern_decorator(self):
        @parse.with_pattern(r"\d+")
        def parse_number(text):
            return int(text)

        self.assert_decorated_with_pattern(parse_number, r"\d+")
        self.assert_converter_call(parse_number, "123", 123)

    def test_classmethod_with_pattern_decorator(self):
        choice_pattern = r"Alice|Bob|Charly"
        class C(object):
            @classmethod
            @parse.with_pattern(choice_pattern)
            def parse_choice(cls, text):
                return text

        self.assert_decorated_with_pattern(C.parse_choice, choice_pattern)
        self.assert_converter_call(C.parse_choice, "Alice", "Alice")

    def test_staticmethod_with_pattern_decorator(self):
        choice_pattern = r"Alice|Bob|Charly"
        class S(object):
            @staticmethod
            @parse.with_pattern(choice_pattern)
            def parse_choice(text):
                return text

        self.assert_decorated_with_pattern(S.parse_choice, choice_pattern)
        self.assert_converter_call(S.parse_choice, "Bob", "Bob")

    def test_decorated_function_with_parser(self):
        # -- SETUP:
        @parse.with_pattern(r"\d+")
        def parse_number(text):
            return int(text)

        parse_number.name = "Number" #< For test automation.
        more_types = build_type_dict([ parse_number ])
        schema = "Test: {number:Number}"
        parser = parse.Parser(schema, more_types)

        # -- PERFORM TESTS:
        self.assert_match(parser, "Test: 1",   "number", 1)
        self.assert_match(parser, "Test: 42",  "number", 42)
        self.assert_match(parser, "Test: 123", "number", 123)

        # -- PARSE MISMATCH:
        self.assert_mismatch(parser, "Test: x",    "number")  # Not a Number.
        self.assert_mismatch(parser, "Test: -1",   "number")  # Negative.
        self.assert_mismatch(parser, "Test: a, b", "number")  # List of ...

    def test_decorated_classmethod_with_parser(self):
        # -- SETUP:
        class C(object):
            @classmethod
            @parse.with_pattern(r"Alice|Bob|Charly")
            def parse_person(cls, text):
                return text

        more_types = { "Person": C.parse_person }
        schema = "Test: {person:Person}"
        parser = parse.Parser(schema, more_types)

        # -- PERFORM TESTS:
        self.assert_match(parser, "Test: Alice", "person", "Alice")
        self.assert_match(parser, "Test: Bob",   "person", "Bob")

        # -- PARSE MISMATCH:
        self.assert_mismatch(parser, "Test: ", "person")        # Missing.
        self.assert_mismatch(parser, "Test: BAlice", "person")  # Similar1.
        self.assert_mismatch(parser, "Test: Boby", "person")    # Similar2.
        self.assert_mismatch(parser, "Test: a",    "person")    # INVALID ...

# -----------------------------------------------------------------------------
# MAIN:
# -----------------------------------------------------------------------------
if __name__ == '__main__':
    unittest.main()

# Copyright (c) 2012-2013 by Jens Engel (https://github/jenisys/parse_type)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


text:
package it.unibz.krdb.obda.utils;

import junit.framework.TestCase;

public class LookupTableTest extends TestCase {

	private LookupTable lookupTable = new LookupTable();

	public void setUp() {
		lookupTable.add("Employee.id", 1);
		lookupTable.add("Employee.name", 2);
		lookupTable.add("public.Salary.id", 3);
		lookupTable.add("Salary.id", 3);
		lookupTable.add("id", 3);
		lookupTable.add("public.Salary.amount", 4);
		lookupTable.add("Salary.amount", 4);
		lookupTable.add("amount", 4);
		lookupTable.add("public.Salary.pid", 5);
		lookupTable.add("Salary.pid", 5);
		lookupTable.add("pid", 5);
	}

	public void testPrintTable() {
		System.out.println(lookupTable.toString());
	}

	public void testAlternativeName() {
		String altName = lookupTable.lookup("Employee.name");
		assertEquals(altName, "t2");

		altName = lookupTable.lookup("public.Salary.amount");
		assertEquals(altName, "t4");

		altName = lookupTable.lookup("Salary.amount");
		assertEquals(altName, "t4");

		altName = lookupTable.lookup("amount");
		assertEquals(altName, "t4");

		altName = lookupTable.lookup("Salary.pid");
		assertEquals(altName, "t5");
	}

	public void testEntryOverride() {
		lookupTable.add("public.Position.tid", 6);
		lookupTable.add("Position.tid", 6);
		lookupTable.add("tid", 6);

		String altName = lookupTable.lookup("Salary.id");
		assertEquals(altName, "t3");

		altName = lookupTable.lookup("tid");  // i.e., Salary.id
		assertEquals(altName, "t6");
	}

	public void testRenaming() {
		boolean flag = lookupTable.asEqualTo("public.Salary.id", "public.Position.id");
		assertFalse(flag);

		flag = lookupTable.asEqualTo("Salary.pid", "Employee.id");
		assertTrue(flag);

		String altName = lookupTable.lookup("Salary.pid");
		String altName2 = lookupTable.lookup("Employee.id");
		assertEquals(altName, altName2);
	}

	public void testEntryDeleting() {
		System.out.println("Before deletions:");
		System.out.println(lookupTable.toString());

		lookupTable.remove("Employee.id");
		String name = lookupTable.lookup("Employee.id");
		assertEquals(name, null);

		lookupTable.remove("public.Salary.id");
		name = lookupTable.lookup("Salary.id");
		assertEquals(name, "t3");

		lookupTable.remove(new String[] {"public.Salary.pid", "Salary.pid", "pid"});
		System.out.println("After deletions:");
		System.out.println(lookupTable.toString());
	}

	public void testAddingWithReference() {
		lookupTable.add("security_id", "Employee.id");
		String name = lookupTable.lookup("security_id");
		assertEquals(name, "t1");

		lookupTable.add("monthly_salary", "public.Salary.amount");
		name = lookupTable.lookup("monthly_salary");
		assertEquals(name, "t4");
	}
}


text:
layout: leaf-node
title: "Project-Based Learning"
title-url: "http://www.learnnc.org/lp/pages/4753"
author: "Heather Coffey"
groups: pedagogical-styles
categories: project-based-learning
topics: introductory-resources
summary: >
    This is a brief backgrounder on Project Based Learning. The topics covered are the
    history of PBL, a definition of PBL, and way to implement PBL in a classroom environment.
    It also includes references.
cite: >
    Coffey, H. & Learn NC. (2017, April 24). Project-based Learning. Learn NC, University of North Carolina.
    Retrieved from http://www.learnnc.org/lp/pages/4753
pub-date: 2017-04-24
added-date: 2017-04-24
resource-type: external-page
---


text:
"""
Unit tests for robot (dependency resolution).

@author: Toon Willems (Ghent University)
"""

import os
import re
import shutil
import tempfile
from copy import deepcopy
from test.framework.utilities import EnhancedTestCase, init_config
from unittest import TestLoader
from unittest import main as unittestmain

import easybuild.framework.easyconfig.tools as ectools
import easybuild.tools.robot as robot
from easybuild.framework.easyconfig.tools import skip_available
from easybuild.tools import config, modules
from easybuild.tools.build_log import EasyBuildError
from easybuild.tools.filetools import read_file, write_file
from easybuild.tools.github import fetch_github_token
from easybuild.tools.robot import resolve_dependencies
from test.framework.utilities import find_full_path

# test account, for which a token is available
GITHUB_TEST_ACCOUNT = 'easybuild_test'

ORIG_MODULES_TOOL = modules.modules_tool
ORIG_ECTOOLS_MODULES_TOOL = ectools.modules_tool
ORIG_ROBOT_MODULES_TOOL = robot.modules_tool
ORIG_MODULE_FUNCTION = os.environ.get('module', None)

class MockModule(modules.ModulesTool):
    """ MockModule class, allows for controlling what modules_tool() will return """
    COMMAND = 'echo'
    VERSION_OPTION = '1.0'
    VERSION_REGEXP = r'(?P<version>\d\S*)'
    # redirect to stderr, ignore 'echo python' ($0 and $1)
    COMMAND_SHELL = ["bash", "-c", "echo $2 $3 $4 1>&2"]

    avail_modules = []

    def available(self, *args):
        """Dummy implementation of available."""
        return self.avail_modules

    def show(self, modname):
        """Dummy implementation of show, which includes full path to (available or hidden) module files."""
        if modname in self.avail_modules or os.path.basename(modname).startswith('.'):
            txt =  '  %s:' % os.path.join('/tmp', modname)
        else:
            txt = 'Module %s not found' % modname
        return txt

def mock_module(mod_paths=None):
    """Get mock module instance."""
    return MockModule(mod_paths=mod_paths)

class RobotTest(EnhancedTestCase):
    """ Testcase for the robot dependency resolution """

    def setUp(self):
        """Set up test."""
        super(RobotTest, self).setUp()
        self.github_token = fetch_github_token(GITHUB_TEST_ACCOUNT)

    def xtest_resolve_dependencies(self):
        """ Test with some basic testcases (also check if he can find dependencies inside the given directory """

        # replace Modules class with something we have control over
        config.modules_tool = mock_module
        ectools.modules_tool = mock_module
        robot.modules_tool = mock_module
        os.environ['module'] = "() {  eval `/bin/echo $*`\n}"

        base_easyconfig_dir = find_full_path(os.path.join("test", "framework", "easyconfigs"))
        self.assertTrue(base_easyconfig_dir)

        easyconfig = {
            'spec': '_',
            'full_mod_name': 'name/version',
            'short_mod_name': 'name/version',
            'dependencies': []
        }
        build_options = {
            'allow_modules_tool_mismatch': True,
            'robot_path': None,
            'validate': False,
        }
        init_config(build_options=build_options)
        res = resolve_dependencies([deepcopy(easyconfig)])
        self.assertEqual([easyconfig], res)

        easyconfig_dep = {
            'ec': {
                'name': 'foo',
                'version': '1.2.3',
                'versionsuffix': '',
                'toolchain': {'name': 'dummy', 'version': 'dummy'},
            },
            'spec': '_',
            'short_mod_name': 'foo/1.2.3',
            'full_mod_name': 'foo/1.2.3',
            'dependencies': [{
                'name': 'gzip',
                'version': '1.4',
                'versionsuffix': '',
                'toolchain': {'name': 'dummy', 'version': 'dummy'},
                'dummy': True,
                'hidden': False,
            }],
            'parsed': True,
        }
        build_options.update({'robot': True, 'robot_path': base_easyconfig_dir})
        init_config(build_options=build_options)
        res = resolve_dependencies([deepcopy(easyconfig_dep)])
        # dependency should be found, order should be correct
        self.assertEqual(len(res), 2)
        self.assertEqual('gzip/1.4', res[0]['full_mod_name'])
        self.assertEqual('foo/1.2.3', res[-1]['full_mod_name'])

        # hidden dependencies are found too, but only retained if they're not available (or forced to be retained
        hidden_dep = {
            'name': 'toy',
            'version': '0.0',
            'versionsuffix': '-deps',
            'toolchain': {'name': 'dummy', 'version': 'dummy'},
            'dummy': True,
            'hidden': True,
        }
        easyconfig_moredeps = deepcopy(easyconfig_dep)
        easyconfig_moredeps['dependencies'].append(hidden_dep)
        easyconfig_moredeps['hiddendependencies'] = [hidden_dep]

        # toy/.0.0-deps is available and thus should be omitted
        res = resolve_dependencies([deepcopy(easyconfig_moredeps)])
        self.assertEqual(len(res), 2)
        full_mod_names = [ec['full_mod_name'] for ec in res]
        self.assertFalse('toy/.0.0-deps' in full_mod_names)

        res = resolve_dependencies([deepcopy(easyconfig_moredeps)], retain_all_deps=True)
        self.assertEqual(len(res), 4)  # hidden dep toy/.0.0-deps (+1) depends on (fake) ictce/4.1.13 (+1)
        self.assertEqual('gzip/1.4', res[0]['full_mod_name'])
        self.assertEqual('foo/1.2.3', res[-1]['full_mod_name'])
        full_mod_names = [ec['full_mod_name'] for ec in res]
        self.assertTrue('toy/.0.0-deps' in full_mod_names)
        self.assertTrue('ictce/4.1.13' in full_mod_names)

        # here we have included a dependency in the easyconfig list
        easyconfig['full_mod_name'] = 'gzip/1.4'

        ecs = [deepcopy(easyconfig_dep), deepcopy(easyconfig)]
        build_options.update({'robot_path': None})
        init_config(build_options=build_options)
        res = resolve_dependencies(ecs)
        # all dependencies should be resolved
        self.assertEqual(0, sum(len(ec['dependencies']) for ec in res))

        # this should not resolve (cannot find gzip-1.4.eb), both with and without robot enabled
        ecs = [deepcopy(easyconfig_dep)]
        msg = "Irresolvable dependencies encountered"
        self.assertErrorRegex(EasyBuildError, msg, resolve_dependencies, ecs)

        # test if dependencies of an automatically found file are also loaded
        easyconfig_dep['dependencies'] = [{
            'name': 'gzip',
            'version': '1.4',
            'versionsuffix': '',
            'toolchain': {'name': 'GCC', 'version': '4.6.3'},
            'dummy': True,
            'hidden': False,
        }]
        ecs = [deepcopy(easyconfig_dep)]
        build_options.update({'robot_path': base_easyconfig_dir})
        init_config(build_options=build_options)
        res = resolve_dependencies([deepcopy(easyconfig_dep)])

        # GCC should be first (required by gzip dependency)
        self.assertEqual('GCC/4.6.3', res[0]['full_mod_name'])
        self.assertEqual('foo/1.2.3', res[-1]['full_mod_name'])

        # make sure that only missing stuff is built, and that available modules are not rebuilt
        # monkey patch MockModule to pretend that all ingredients required for goolf-1.4.10 toolchain are present
        MockModule.avail_modules = [
            'GCC/4.7.2',
            'OpenMPI/1.6.4-GCC-4.7.2',
            'OpenBLAS/0.2.6-gompi-1.4.10-LAPACK-3.4.2',
            'FFTW/3.3.3-gompi-1.4.10',
            'ScaLAPACK/2.0.2-gompi-1.4.10-OpenBLAS-0.2.6-LAPACK-3.4.2',
        ]

        easyconfig_dep['dependencies'] = [{
            'name': 'goolf',
            'version': '1.4.10',
            'versionsuffix': '',
            'toolchain': {'name': 'dummy', 'version': 'dummy'},
            'dummy': True,
            'hidden': False,
        }]
        ecs = [deepcopy(easyconfig_dep)]
        res = resolve_dependencies(ecs)

        # there should only be two retained builds, i.e. the software itself and the goolf toolchain as dep
        self.assertEqual(len(res), 2)
        # goolf should be first, the software itself second
        self.assertEqual('goolf/1.4.10', res[0]['full_mod_name'])
        self.assertEqual('foo/1.2.3', res[1]['full_mod_name'])

        # force doesn't trigger rebuild of all deps, but listed easyconfigs for which a module is available are rebuilt
        build_options.update({'force': True})
        init_config(build_options=build_options)
        easyconfig['full_mod_name'] = 'this/is/already/there'
        MockModule.avail_modules.append('this/is/already/there')
        ecs = [deepcopy(easyconfig_dep), deepcopy(easyconfig)]
        res = resolve_dependencies(ecs)

        # there should only be three retained builds, foo + goolf dep and the additional build (even though a module is available)
        self.assertEqual(len(res), 3)
        # goolf should be first, the software itself second
        self.assertEqual('this/is/already/there', res[0]['full_mod_name'])
        self.assertEqual('goolf/1.4.10', res[1]['full_mod_name'])
        self.assertEqual('foo/1.2.3', res[2]['full_mod_name'])

        # build that are listed but already have a module available are not retained without force
        build_options.update({'force': False})
        init_config(build_options=build_options)
        newecs = skip_available(ecs)  # skip available builds since force is not enabled
        res = resolve_dependencies(newecs)
        self.assertEqual(len(res), 2)
        self.assertEqual('goolf/1.4.10', res[0]['full_mod_name'])
        self.assertEqual('foo/1.2.3', res[1]['full_mod_name'])

        # with retain_all_deps enabled, all dependencies ae retained
        build_options.update({'retain_all_deps': True})
        init_config(build_options=build_options)
        ecs = [deepcopy(easyconfig_dep)]
        newecs = skip_available(ecs)  # skip available builds since force is not enabled
        res = resolve_dependencies(newecs)
        self.assertEqual(len(res), 9)
        self.assertEqual('GCC/4.7.2', res[0]['full_mod_name'])
        self.assertEqual('goolf/1.4.10', res[-2]['full_mod_name'])
        self.assertEqual('foo/1.2.3', res[-1]['full_mod_name'])

        build_options.update({'retain_all_deps': False})
        init_config(build_options=build_options)

        # provide even less goolf ingredients (no OpenBLAS/ScaLAPACK), make sure the numbers add up
        MockModule.avail_modules = [
            'GCC/4.7.2',
            'OpenMPI/1.6.4-GCC-4.7.2',
            'gompi/1.4.10',
            'FFTW/3.3.3-gompi-1.4.10',
        ]

        easyconfig_dep['dependencies'] = [{
            'name': 'goolf',
            'version': '1.4.10',
            'versionsuffix': '',
            'toolchain': {'name': 'dummy', 'version': 'dummy'},
            'dummy': True,
            'hidden': False,
        }]
        ecs = [deepcopy(easyconfig_dep)]
        res = resolve_dependencies([deepcopy(easyconfig_dep)])

        # there should only be two retained builds, i.e. the software itself and the goolf toolchain as dep
        self.assertEqual(len(res), 4)
        # goolf should be first, the software itself second
        self.assertEqual('OpenBLAS/0.2.6-gompi-1.4.10-LAPACK-3.4.2', res[0]['full_mod_name'])
        self.assertEqual('ScaLAPACK/2.0.2-gompi-1.4.10-OpenBLAS-0.2.6-LAPACK-3.4.2', res[1]['full_mod_name'])
        self.assertEqual('goolf/1.4.10', res[2]['full_mod_name'])
        self.assertEqual('foo/1.2.3', res[3]['full_mod_name'])

        config.modules_tool = ORIG_MODULES_TOOL
        ectools.modules_tool = ORIG_ECTOOLS_MODULES_TOOL
        robot.modules_tool = ORIG_ROBOT_MODULES_TOOL
        if ORIG_MODULE_FUNCTION is not None:
            os.environ['module'] = ORIG_MODULE_FUNCTION
        else:
            if 'module' in os.environ:
                del os.environ['module']

    def test_det_easyconfig_paths(self):
        """Test det_easyconfig_paths function (without --from-pr)."""
        fd, dummylogfn = tempfile.mkstemp(prefix='easybuild-dummy', suffix='.log')
        os.close(fd)

        test_ecs_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'easyconfigs')

        test_ec = 'toy-0.0-deps.eb'
        shutil.copy2(os.path.join(test_ecs_path, test_ec), self.test_prefix)
        shutil.copy2(os.path.join(test_ecs_path, 'ictce-4.1.13.eb'), self.test_prefix)
        self.assertFalse(os.path.exists(test_ec))

        args = [
            os.path.join(test_ecs_path, 'toy-0.0.eb'),
            test_ec,  # relative path, should be resolved via robot search path
            # PR for foss/2015a, see https://github.com/hpcugent/easybuild-easyconfigs/pull/1239/files
            #'--from-pr=1239',
            '--dry-run',
            '--debug',
            '--robot',
            '--robot-paths=%s' % self.test_prefix,  # override $EASYBUILD_ROBOT_PATHS
            '--unittest-file=%s' % self.logfile,
            '--github-user=%s' % GITHUB_TEST_ACCOUNT,  # a GitHub token should be available for this user
            '--tmpdir=%s' % self.test_prefix,
        ]
        outtxt = self.eb_main(args, logfile=dummylogfn, raise_error=True)

        modules = [
            (test_ecs_path, 'toy/0.0'),  # specified easyconfigs, available at given location
            (self.test_prefix, 'ictce/4.1.13'),  # dependency, found in robot search path
            (self.test_prefix, 'toy/0.0-deps'),  # specified easyconfig, found in robot search path
        ]
        for path_prefix, module in modules:
            ec_fn = "%s.eb" % '-'.join(module.split('/'))
            regex = re.compile(r"^ \* \[.\] %s.*%s \(module: %s\)$" % (path_prefix, ec_fn, module), re.M)
            self.assertTrue(regex.search(outtxt), "Found pattern %s in %s" % (regex.pattern, outtxt))

    def test_det_easyconfig_paths_from_pr(self):
        """Test det_easyconfig_paths function, with --from-pr enabled as well."""
        if self.github_token is None:
            print "Skipping test_from_pr, no GitHub token available?"
            return

        fd, dummylogfn = tempfile.mkstemp(prefix='easybuild-dummy', suffix='.log')
        os.close(fd)

        test_ecs_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'easyconfigs')

        test_ec = 'toy-0.0-deps.eb'
        shutil.copy2(os.path.join(test_ecs_path, test_ec), self.test_prefix)
        shutil.copy2(os.path.join(test_ecs_path, 'ictce-4.1.13.eb'), self.test_prefix)
        self.assertFalse(os.path.exists(test_ec))

        gompi_2015a_txt = '\n'.join([
            "easyblock = 'Toolchain'",
            "name = 'gompi'",
            "version = '2015a'",
            "versionsuffix = '-test'",
            "homepage = 'foo'",
            "description = 'bar'",
            "toolchain = {'name': 'dummy', 'version': 'dummy'}",
        ])
        write_file(os.path.join(self.test_prefix, 'gompi-2015a-test.eb'), gompi_2015a_txt)
        # put gompi-2015a.eb easyconfig in place that shouldn't be considered (paths via --from-pr have precedence)
        write_file(os.path.join(self.test_prefix, 'gompi-2015a.eb'), gompi_2015a_txt)

        args = [
            os.path.join(test_ecs_path, 'toy-0.0.eb'),
            test_ec,  # relative path, should be resolved via robot search path
            # PR for foss/2015a, see https://github.com/hpcugent/easybuild-easyconfigs/pull/1239/files
            '--from-pr=1239',
            'FFTW-3.3.4-gompi-2015a.eb',
            'gompi-2015a-test.eb',  # relative path, available in robot search path
            '--dry-run',
            '--robot',
            '--robot=%s' % self.test_prefix,
            '--unittest-file=%s' % self.logfile,
            '--github-user=%s' % GITHUB_TEST_ACCOUNT,  # a GitHub token should be available for this user
            '--tmpdir=%s' % self.test_prefix,
        ]
        outtxt = self.eb_main(args, logfile=dummylogfn, raise_error=True)

        from_pr_prefix = os.path.join(self.test_prefix, '.*', 'files_pr1239')
        modules = [
            (test_ecs_path, 'toy/0.0'),  # specified easyconfigs, available at given location
            (self.test_prefix, 'ictce/4.1.13'),  # dependency, found in robot search path
            (self.test_prefix, 'toy/0.0-deps'),  # specified easyconfig, found in robot search path
            (self.test_prefix, 'gompi/2015a-test'),  # specified easyconfig, found in robot search path
            (from_pr_prefix, 'FFTW/3.3.4-gompi-2015a'),  # part of PR easyconfigs
            (from_pr_prefix, 'gompi/2015a'),  # part of PR easyconfigs
            (test_ecs_path, 'GCC/4.9.2'),  # dependency for PR easyconfigs, found in robot search path
        ]
        for path_prefix, module in modules:
            ec_fn = "%s.eb" % '-'.join(module.split('/'))
            regex = re.compile(r"^ \* \[.\] %s.*%s \(module: %s\)$" % (path_prefix, ec_fn, module), re.M)
            self.assertTrue(regex.search(outtxt), "Found pattern %s in %s" % (regex.pattern, outtxt))

def suite():
    """ returns all the testcases in this module """
    return TestLoader().loadTestsFromTestCase(RobotTest)

if __name__ == '__main__':
    unittestmain()


text:
package org.apache.catalina.util;

import org.junit.Assert;
import org.junit.Test;

public class TestURLEncoder {

    private static final String SPACE = " ";
    private static final String DOLLAR = "$";
    private static final String AMPERSAND = "&";
    private static final String AMPERSAND_ENCODED = "%26";

    @Test
    public void testClone() {
        URLEncoder original = new URLEncoder();
        URLEncoder clone = (URLEncoder) original.clone();

        // Ensure encode as space is not shared
        original.setEncodeSpaceAsPlus(true);
        Assert.assertNotEquals(original.encode(SPACE, "UTF-8"), clone.encode(SPACE, "UTF-8"));

        // Ensure safe characters is not shared
        original.addSafeCharacter('$');
        Assert.assertNotEquals(original.encode(DOLLAR, "UTF-8"), clone.encode(DOLLAR, "UTF-8"));
    }

    @Test
    public void testRemoveSafeCharacter() {
        URLEncoder xml = (URLEncoder) URLEncoder.DEFAULT.clone();
        // This should not encode '&'
        Assert.assertEquals(AMPERSAND, xml.encode(AMPERSAND, "UTF-8"));
        xml.removeSafeCharacter('&');
        Assert.assertEquals(AMPERSAND_ENCODED, xml.encode(AMPERSAND, "UTF-8"));
    }
}


text:
using RestSharp;
using System;
using Xunit;

namespace SampleApplication.FunctionalTests
{
    public class UnitTest1
    {
        [Fact]
        public void CallFuntion1WithParams()
        {
            var client = new RestClient("https://sampleapp-dev.azurewebsites.net/");
            var request = new RestRequest("api/Function1?code=Sa3tAomy3oZaG4I9Ska14wkUnsdFVbvS7YB2eSLaA7hL9vmKXgRs1w==&name=Bill", Method.GET);
            var result = client.Execute(request);
            Assert.Equal("\"Hello Bill! Welcome to Azure Functions!\"", result.Content);
        }

        [Fact]
        public void CallFuntion1WithoutParams()
        {
            var client = new RestClient("https://sampleapp-dev.azurewebsites.net/");
            var request = new RestRequest("api/Function1?code=Sa3tAomy3oZaG4I9Ska14wkUnsdFVbvS7YB2eSLaA7hL9vmKXgRs1w==", Method.GET);
            var result = client.Execute(request);
            Assert.Equal("\"Hello there! Welcome to Azure Functions!\"", result.Content);
        }
    }
}


text:
import { isObject } from '../isObject';

describe('Core.isObject', () => {
  test('checks if a value is an object (excludes arrays)', () => {
    expect(isObject({})).toBeTruthy();
    expect(isObject({ foo: 'bar' })).toBeTruthy();
    expect(isObject(() => null)).toBeFalsy();
    expect(isObject([])).toBeFalsy();
    expect(isObject('a')).toBeFalsy();
    expect(isObject(1)).toBeFalsy();
    expect(isObject(null)).toBeFalsy();
    expect(isObject(undefined)).toBeFalsy();
  });
});


text:
package mockit;

import static org.junit.Assert.*;
import org.junit.*;

public class ComplexVerificationsTest
{
   public static class A
   {
      @SuppressWarnings("UnusedParameters")
      public void process(Object[] inputData) {}
      public int result() { return 1; }
   }

   public static class B { public int foo() { return -2; } }
   public static class C { public int bar() { return 3; } }

   final Object[] input = new Object[3];

   int testedMethod()
   {
      // Requirement 1: instantiations occur (a) first, (b) once per class.
      A a = new A();
      B b = new B();
      C c = new C();

      // Requirement 2: a.process is (a) called first, (b) only once.
      a.process(input);

      // Requirement 3: b.foo and c.bar are called (a) between the calls to A, and (b) input.length times each.
      //noinspection UnusedDeclaration
      for (Object in : input) {
         // Requirement 4: b.foo and c.bar are called in any order relative to each other.
         b.foo();
         c.bar();
      }

      // Requirement 5: a.result is (a) called last, (b) only once.
      return a.result();

      // Requirement 6: no other invocations occur on (a) A, (b) B, or (c) C.
   }

   @Test
   public void usingStrictExpectationsOnly(@Mocked final A a, @Mocked final B b, @Mocked final C c)
   {
      new StrictExpectations() {{
         // Meets requirement 1:
         new A();
         new B();
         new C();

         // Meets requirement 2:
         a.process(input);
      }};

      new StrictExpectations(input.length) {{
         // Meets requirement 3 but NOT 4:
         b.foo();
         c.bar();
      }};

      new StrictExpectations() {{
         // Meets requirement 5:
         a.result(); result = 42;
      }};

      assertEquals(42, testedMethod());

      // Requirement 6 is met since all classes are mocked strictly.
   }

   @Test
   public void usingStrictAndNotStrictMockedTypes(@Mocked final A a, @Mocked final B b, @Mocked final C c)
   {
      new StrictExpectations() {{
         // Meets requirements 1 and 2.
         new A();
         a.process(input);

         // Meets requirement 5.
         a.result(); result = 42;
      }};

      new Expectations() {{
         // Meets requirements 1 and 2.
         new B(); times = 1;
         new C(); times = 1;

         // Meets requirement 3b and 4, but NOT 3a.
         b.foo(); times = input.length;
         c.bar(); times = input.length;
      }};

      assertEquals(42, testedMethod());

      // Meets requirement 6.
      new FullVerifications() {};
   }

   @Test
   public void usingNotStrictExpectationsOnly(@Mocked final A a, @Mocked final B b, @Mocked final C c)
   {
      new Expectations() {{
         // Meets requirements 1b and 5b.
         new A(); times = 1;
         new B(); times = 1;
         new C(); times = 1;
         a.result(); result = 42; times = 1;
      }};

      assertEquals(42, testedMethod());

      new VerificationsInOrder() {{
         // Meets requirements 1a, 2, 3a, and 5a.
         unverifiedInvocations(); // accounts for the instantiations of A, B, and C
         a.process(input); times = 1;
         unverifiedInvocations(); // accounts for the calls to "foo" and "bar"
         a.result();
      }};

      new FullVerifications(a) {{
         // Meets requirement 6a.
         a.process(input);
      }};

      new FullVerifications(input.length, b, c) {{
         // Meets requirements 3b, 4, 6b and 6c.
         b.foo();
         c.bar();
      }};
   }

   @Test
   public void usingNotStrictExpectationsOnlyWithoutDuplicateInvocations(
      @Mocked final A a, @Mocked final B b, @Mocked final C c)
   {
      new Expectations() {{
         // Meets requirements 1b and 5b.
         new A(); times = 1;
         new B(); times = 1;
         new C(); times = 1;
         a.result(); result = 42; times = 1;
      }};

      assertEquals(42, testedMethod());

      new VerificationsInOrder() {{
         // Meets requirements 1a, 2, 3a, and 5a.
         unverifiedInvocations(); // accounts for the instantiations of A, B, and C
         a.process(input); times = 1;
         unverifiedInvocations(); // accounts for the calls to "foo" and "bar"
         a.result(); // this duplication is inevitable without resorting to strict expectations, so it's ok
      }};

      new FullVerifications(input.length) {{
         // Meets requirements 3b, 4, and 6.
         b.foo();
         c.bar();
      }};
   }

   @Test
   public void testFewerRequirementsUsingNotStrictExpectationsOnly(
      @Mocked final A a, @Mocked final B b, @Mocked final C c)
   {
      // Requirements to meet: only 1b, 3b, 4, 6b and 6c.

      new Expectations() {{
         // Meets requirement 1b.
         new A(); times = 1;
         new B(); times = 1;
         new C(); times = 1;
         a.result(); result = 42;

         // Meets requirements 3b and 4.
         b.foo(); times = input.length;
         c.bar(); times = input.length;
      }};

      assertEquals(42, testedMethod());

      // Meets requirements 6b and 6c.
      new FullVerifications(b, c) {};
   }
}


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Cref_status_perkawinan extends Back_end {

    public $model = 'model_ref_status_perkawinan';

    public function __construct() {
        parent::__construct('kelola_pustaka_status_perkawinan', 'Pustaka Data Status Perkawinan');
    }

    public function index() {
        parent::index();
        $this->set("bread_crumb", array(
            "#" => $this->_header_title
        ));
    }

    public function detail($id = FALSE) {
        parent::detail($id, array(
            "status_perkawinan",
            "kode_status_perkawinan",
            "keyword",
        ));

        $this->set("bread_crumb", array(
            "back_end/" . $this->_name => $this->_header_title,
            "#" => 'Pendaftaran ' . $this->_header_title
        ));
//        $this->add_jsfiles(array("avant/plugins/form-jasnyupload/fileinput.min.js"));
    }

    public function get_like() {
        $keyword = $this->input->post("keyword");

        $skpd_found = $this->{$this->model}->get_like($keyword);

        $this->to_json($skpd_found);
    }

}

?>


text:
package com.google.zxing.client.android.encode;

import java.util.List;
import java.util.regex.Pattern;

import android.telephony.PhoneNumberUtils;

/**
 * 根据MECARD格式对联系人信息进行编码
 *
 * @author lijian
 * @date 2017-9-4 下午10:52:22
 */
final class MECARDContactEncoder extends ContactEncoder {

	private static final char TERMINATOR = ';';

	@Override
	public String[] encode(List<String> names, String organization,
			List<String> addresses, List<String> phones,
			List<String> phoneTypes, List<String> emails, List<String> urls,
			String note) {
		StringBuilder newContents = new StringBuilder(100);
		newContents.append("MECARD:");

		StringBuilder newDisplayContents = new StringBuilder(100);

		Formatter fieldFormatter = new MECARDFieldFormatter();

		appendUpToUnique(newContents, newDisplayContents, "N", names, 1,
				new MECARDNameDisplayFormatter(), fieldFormatter, TERMINATOR);

		append(newContents, newDisplayContents, "ORG", organization,
				fieldFormatter, TERMINATOR);

		appendUpToUnique(newContents, newDisplayContents, "ADR", addresses, 1,
				null, fieldFormatter, TERMINATOR);

		appendUpToUnique(newContents, newDisplayContents, "TEL", phones,
				Integer.MAX_VALUE, new MECARDTelDisplayFormatter(),
				fieldFormatter, TERMINATOR);

		appendUpToUnique(newContents, newDisplayContents, "EMAIL", emails,
				Integer.MAX_VALUE, null, fieldFormatter, TERMINATOR);

		appendUpToUnique(newContents, newDisplayContents, "URL", urls,
				Integer.MAX_VALUE, null, fieldFormatter, TERMINATOR);

		append(newContents, newDisplayContents, "NOTE", note, fieldFormatter,
				TERMINATOR);

		newContents.append(';');

		return new String[] { newContents.toString(),
				newDisplayContents.toString() };
	}

	private static class MECARDFieldFormatter implements Formatter {
		private static final Pattern RESERVED_MECARD_CHARS = Pattern
				.compile("([\\\\:;])");
		private static final Pattern NEWLINE = Pattern.compile("\\n");

		@Override
		public CharSequence format(CharSequence value, int index) {
			return ':' + NEWLINE.matcher(
					RESERVED_MECARD_CHARS.matcher(value).replaceAll("\\\\$1"))
					.replaceAll("");
		}
	}

	private static class MECARDTelDisplayFormatter implements Formatter {
		private static final Pattern NOT_DIGITS = Pattern.compile("[^0-9]+");

		@Override
		public CharSequence format(CharSequence value, int index) {
			return NOT_DIGITS.matcher(
					PhoneNumberUtils.formatNumber(value.toString()))
					.replaceAll("");
		}
	}

	private static class MECARDNameDisplayFormatter implements Formatter {
		private static final Pattern COMMA = Pattern.compile(",");

		@Override
		public CharSequence format(CharSequence value, int index) {
			return COMMA.matcher(value).replaceAll("");
		}
	}

}


text:
const LifeforcePlugin = require("../utils/LifeforcePlugin.js");
const geoip = require("geoip-country");

//const serverhostname = "http://localhost:16001";
const serverhostname = "https://api.repkam09.com";

class MetaEndpoints extends LifeforcePlugin {
  constructor(restifyserver, logger, name) {
    super(restifyserver, logger, name);
    this.apiMap = [
      {
        path: "/api/about",
        type: "get",
        handler: handleAboutApi,
        cacheTTL: 86400
      },
      {
        path: "/",
        type: "get",
        handler: handleAboutApi,
        cacheTTL: 86400
      },
      {
        path: "/api/gettest",
        type: "get",
        handler: handleGetTest
      },
      {
        path: "/api/posttest",
        type: "post",
        handler: handlePostTest
      },
      {
        path: "/api/getip",
        type: "get",
        handler: handleGetIp
      },
      {
        path: "/api/geoip",
        type: "get",
        handler: getGeoIpCountry
      }
    ];
  }
}

function handleGetIp(req, res, next) {
  var clientip = "unknown";
  if (req.headers["x-forwarded-for"]) {
    clientip = req.headers["x-forwarded-for"];
  } else if (req.connection.remoteAddress) {
    clientip = req.connection.remoteAddress;
  }
  res.send(200, { ip: clientip });
  return next();
}

function getGeoIpCountry(req, res, next) {
  var clientip = "unknown";
  if (req.headers["x-forwarded-for"]) {
    clientip = req.headers["x-forwarded-for"];
  } else if (req.connection.remoteAddress) {
    clientip = req.connection.remoteAddress;
  }

  var geo = geoip.lookup(clientip);
  res.send(200, { geodata: geo });
  return next();
}

function handleAboutApi(req, res, next) {
  return this.setResponse(req, next, 200, this.restifyserver.getAbout());
}

function handleGetTest(req, res, next) {
  res.send(200, "You have made a GET request! OK!");
}

function handlePostTest(req, res, next) {
  if (req.body) {
    res.send(200, req.body);
  } else {
    if (req.params) {
      res.send(200, req.params);
    } else {
      res.send(
        200,
        "You dont seem to have POSTed anything. But we got the request."
      );
    }
  }
  next();
}

module.exports = MetaEndpoints;


text:
package com.sjl.dsl4xml.sax;

import com.sjl.dsl4xml.*;
import com.sjl.dsl4xml.support.*;

public class TextHandler {

	private ValueSetter setter;
	private String field;
	private StringBuilder chars;

	public TextHandler(String aFieldName) {
		field = aFieldName;
		chars = new StringBuilder();
	}

	public void handle(char[] aChars, int aStart, int aLength, Context aContext) {
		chars.append(aChars, aStart, aLength);
	}

	public void complete(Context aContext) {
		Object _currentContext = aContext.peek();
		try {
			ValueSetter _vs = getSetter(aContext, _currentContext.getClass(), field);
			_vs.invoke(field, _currentContext, chars.toString());
			chars.setLength(0);
		} catch (ParsingException anExc) {
			throw anExc;
		} catch (Exception anExc) {
			throw new ParsingException(anExc);
		}
	}

	private ValueSetter getSetter(Context aContext, Class<?> aClass, String aFieldName) {
		if (setter == null) {
			setter = new ValueSetter(aContext, aClass, aFieldName);
		}
		return setter;
	}
}