text:
<repo_name>yapa5475/Credit-Data-Analysis<file_sep>/README.md
# Credit-Data-Analysis
Analysis of credit data (GermanCredit.csv)
<file_sep>/MIS 510 Portfolio Project Option 1.Rmd
---
title: "MIS 510 Porfolio Project 1"
author: "<NAME>"
date: "7/4/2021"
output: word_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Data Import

```{r}
GermanCredit.df <- read.csv("C:/Users/yashp/Google Drive/MIS-510/Portfolio Project/GermanCredit.csv", header=TRUE)
```

## Data Exploration

Data exploration functions are useful for extracting specific information around the data. The following five functions give insight into the Banks data.

```{r}
# The summary() function outputs summary statistics for all the variables in the banks data frame.
summary(GermanCredit.df)

# The mean function returns the average for all the variables in the banks data frame.
data.frame(mean=sapply(GermanCredit.df, mean, na.rm=TRUE))

# The median function returns the median value for all the variables in the banks data frame.
data.frame(median=sapply(GermanCredit.df, median, na.rm=TRUE))

# The sd functions returns the standard deviation value for all the variables in the banks data frame.
data.frame(sd=sapply(GermanCredit.df, sd, na.rm=TRUE))

# The range functions returns the range for all the variables in the banks data frame.
data.frame(range=sapply(GermanCredit.df, range, na.rm=TRUE))

# The length functions returns the length for all the variables in the banks data frame.
data.frame(length=sapply(GermanCredit.df, length))
```

## Divide data

The data is divided in to two partitions, one for training and one for validation. This can be done using the sample() function. The following code shown aims to randomly partition the data in to two data sets.

```{r}
# partition data in to training (60%) and validation (40%) using sample() function
# first randomly sample 60% of the data and put them into the training set
train.rows <- sample(rownames(GermanCredit.df), dim(GermanCredit.df)[1]*0.6)
train.data <- GermanCredit.df[train.rows,]

# next, assign the rows that are not already in the training row in to the validation data
valid.rows <- setdiff(rownames(GermanCredit.df), train.rows)
valid.data <- GermanCredit.df[valid.rows, ]
```

## Explore Classification Models

First, logistic regression will be used to evaluate the data. A logistic regression is appropriate when the outcome variable is categorical, in other words has set of potential values. The end result classifies the record into one of the classes based on the predictor variables (Shumeli, et al. 2018)

```{r}
# Divide data into training and validation partitions
# randomly sample 60% of the rows for training, the remaining 40% for validation
train.rows <- sample(rownames(GermanCredit.df), dim(GermanCredit.df)[1]*0.6)

train.data <- GermanCredit.df[train.rows,]

# assign rows not in train into validation
valid.rows <- setdiff(rownames(GermanCredit.df), train.rows)
valid.data <- GermanCredit.df[valid.rows,]
```

## Logistic Regression

A logistic regression will be run on the training AND validation data separately. First, below is a logistic regression for the training data.

```{r}
# Model amount as a function of the other attributes for training data

logit.reg <- glm(as.factor(AMOUNT) ~ ., data = train.data, family = "binomial")

options(scipen = 999)
summary(logit.reg)
```

Next, below is the logistic regression for the validation data.

```{r}
# Model amount as a function of the other attributes for validation data

logit.reg <- glm(AMOUNT ~ ., data = valid.data)

options(scipen = 999)
summary(logit.reg)
```

## Classification Tree

Similarly to the logistic regression, the classification tree will be conducted on the training AND validation data individually. First, below is a classification tree for the training data.

```{r}
# Classification tree

library(rpart)
library(rpart.plot)

# classification tree for training data
class.tree <- rpart(AMOUNT ~., data = train.data)
prp(class.tree, type = 1, extra = 1, split.font = 1, varlen = -10)
```

Next, below is the classification tree for the validation data.

```{r}
# classification tree for validation data
class.tree <- rpart(AMOUNT ~., data = valid.data)
prp(class.tree, type = 1, extra = 1, split.font = 1, varlen = -10)
```

## Analysis

This portfolio project was an exercise on data exploration, data mining, and visualization. In going through this exercise, there were several skills that I gained and lessons that I learned. One of those skills was learning how to partition data. Shumeli, et al. (2018) identified partitioning the data as one of the core strategies in data mining algorithms. I found this to be relatively simple in R. First, I identified the partition using the dim() function and passing in 0.6 (which identifies the percent of the data which will be put in the first partition - 60%). That partition of data was put in to the train.data partition. The remaining data was put into the valid.data segment.

The next part of this portfolio project is the data mining techniques. I conducted a logistic regression and made a classification tree on the partitioned data. The logistic regression was done using the logit() function on both the validation and test data. The as.factor() function was used to encode the amount variable as a factor. Next, a classification tree was done on the partitioned data using the "class.tree" function. A classification tree is significant in its ability to have recursive partitioning of the predictor variables, and due to the pruning methodology. As a result of the classification tree, any record can be assigned a class by dropping it down the tree until it reaches a terminal node (Shumeli, et al., 2018).

Overall, this portfolio project was a good exercise in data mining and visualization.It was mostly simple to do, and provided for a learning experience on data exploration, logistic regression, and visualization.

<NAME>., <NAME>., <NAME>., <NAME>., and <NAME>. (2018). Data mining for business analytics: Concepts, techniques, and applications in R. Wiley Publishing. ISBN: 9781118879337.

languages: RMarkdown Markdown

repo_language: RMarkdown


text:
<repo_name>dawg-at-irya/histograms-and-KDEs<file_sep>/README.md
# histograms-and-KDEs
Estimating the density distributions of data using histograms and KDEs: some caveats and tips

branch_name: refs/heads/master

repo_language: Markdown

repo_name: dawg-at-irya/histograms-and-KDEs


text:
<repo_name>arti040/delightful-click<file_sep>/README.md
# Delightful-click
Amazingly awesome button on-click effects for your app! ;-)

Demo:
-----
http://arti040.github.io/delightful-click


text:
<repo_name>mrdavenz/LinkedIn-OAuth-Sample-Client<file_sep>/OAuthStarterKit/LinkedInDialog.h
//
//  LinkedInDialog.h
//  Peoplebank App
//
//  Created by <NAME> on 9/09/12.
//  Copyright (c) 2012 Alive. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <CoreFoundation/CoreFoundation.h>

#import "JSONKit.h"
#import "OAConsumer.h"
#import "OAMutableURLRequest.h"
#import "OADataFetcher.h"
#import "OATokenManager.h"

@protocol LinkedInDialogDelegate;

@interface LinkedInDialog : UIView<UIWebViewDelegate, UIScrollViewDelegate>{

  __unsafe_unretained id<LinkedInDialogDelegate> _delegate;
  //  NSString *_params; //Permissions //TODO: change var name

  NSString * _serverURL;
  NSURL* _loadingURL;
  UIWebView* _webView;
  UIActivityIndicatorView* _spinner;
  UIButton* _closeButton;
  UIInterfaceOrientation _orientation;
  BOOL _showingKeyboard;
  BOOL _isViewInvisible;

  UIView* _modalBackgroundView;

  IBOutlet UIActivityIndicatorView *activityIndicator;
  IBOutlet UITextField *addressBar;

  // Theses ivars could be made into a provider class
  // Then you could pass in different providers for Twitter, LinkedIn, etc
  NSString *apikey;
  NSString *secretkey;
  NSString *requestTokenURLString;
  NSURL *requestTokenURL;
  NSString *accessTokenURLString;
  NSURL *accessTokenURL;
  NSString *userLoginURLString;
  NSURL *userLoginURL;
  NSString *linkedInCallbackURL;
}

@property(nonatomic, retain) OAToken *requestToken;
@property(nonatomic, retain) OAToken *accessToken;
@property(nonatomic, retain) NSDictionary *profile;
@property(nonatomic, retain) OAConsumer *consumer;
- (void)initLinkedInApi;
- (void)requestTokenFromProvider;
- (void)allowUserToLogin;
- (void)accessTokenFromProvider;
//
@property(nonatomic,assign) id<LinkedInDialogDelegate> delegate;
@property(nonatomic, retain) NSString* params;

- (NSString *) getStringFromUrl: (NSString*) url needle:(NSString *) needle;

- (void)show;

/**
 * Displays the first page of the dialog.
 *
 * Do not ever call this directly.  It is intended to be overriden by subclasses.
 */
- (void)load;

/**
 * Displays a URL in the dialog.
 */
- (void)loadURL:(NSString*)url
            get:(NSDictionary*)getParams;

/**
 * Hides the view and notifies delegates of success or cancellation.
 */
- (void)dismissWithSuccess:(BOOL)success animated:(BOOL)animated;

/**
 * Hides the view and notifies delegates of an error.
 */
- (void)dismissWithError:(NSError*)error animated:(BOOL)animated;

/**
 * Subclasses may override to perform actions just prior to showing the dialog.
 */
- (void)dialogWillAppear;

/**
 * Subclasses may override to perform actions just after the dialog is hidden.
 */
- (void)dialogWillDisappear;

/**
 * Subclasses should override to process data returned from the server in a 'fbconnect' url.
 *
 * Implementations must call dismissWithSuccess:YES at some point to hide the dialog.
 */
- (void)dialogDidSucceed:(NSURL *)url;

/**
 * Subclasses should override to process data returned from the server in a 'fbconnect' url.
 *
 * Implementations must call dismissWithSuccess:YES at some point to hide the dialog.
 */
- (void)dialogDidCancel:(NSURL *)url;

@end

@protocol LinkedInDialogDelegate <NSObject>

@optional

/**
 * Called when the dialog succeeds and is about to be dismissed.
 */
- (void)dialogDidComplete:(LinkedInDialog *)dialog;

/**
 * Called when the dialog succeeds with a returning url.
 */
- (void)dialogCompleteWithUrl:(NSURL *)url;

/**
 * Called when the dialog get canceled by the user.
 */
- (void)dialogDidNotCompleteWithUrl:(NSURL *)url;

/**
 * Called when the dialog is cancelled and is about to be dismissed.
 */
- (void)dialogDidNotComplete:(LinkedInDialog *)dialog;

/**
 * Called when dialog failed to load due to an error.
 */
- (void)dialog:(LinkedInDialog*)dialog didFailWithError:(NSError *)error;

/**
 * Asks if a link touched by a user should be opened in an external browser.
 *
 * If a user touches a link, the default behavior is to open the link in the Safari browser,
 * which will cause your app to quit.  You may want to prevent this from happening, open the link
 * in your own internal browser, or perhaps warn the user that they are about to leave your app.
 * If so, implement this method on your delegate and return NO.  If you warn the user, you
 * should hold onto the URL and once you have received their acknowledgement open the URL yourself
 * using [[UIApplication sharedApplication] openURL:].
 */
- (BOOL)dialog:(LinkedInDialog*)dialog shouldOpenURLInExternalBrowser:(NSURL *)url;

@end<file_sep>/OAuthStarterKit/LinkedIn.h
//
//  ALMLinkedIn.h
//  Peoplebank App
//
//  Created by <NAME> on 6/09/12.
//  www.alivemobile.com.au
//

#import <Foundation/Foundation.h>
#import "OAConsumer.h"
#import "OAMutableURLRequest.h"
#import "OADataFetcher.h"
#import "OATokenManager.h"
#import "OAuthLoginView.h"
#import "LinkedInLoginDialog.h"

@protocol LinkedInSessionDelegate <NSObject>
/*
 * Called when the user successfully logged in.
 */
@required
- (void) liDidLogin;

/*
 * Called when the user dismissed the dialog without logging in.
 */
- (void) liDidNotLogin:(BOOL)cancelled;

/**
 * Called after the access token was extended. If your application has any
 * references to the previous access token (for example, if your application
 * stores the previous access token in persistent storage), your application
 * should overwrite the old access token with the new one in this method.
 * See extendAccessToken for more details.
 */
- (void) liDidExtendToken: (NSString*)accessToken
                expiresAt: (NSDate*)expiresAt;

/**
 * Called when the user logged out.
 */
- (void) liDidLogout;

/**
 * Called when the current session has expired. This might happen when:
 *  - the access token expired
 *  - the app has been disabled
 *  - the user revoked the app's permissions
 *  - the user changed his or her password
 */

- (void) liSessionInvalidated;

@end

@interface LinkedIn : NSObject<LinkedInLoginDialogDelegate, LinkedInDialogDelegate>{
  NSArray*  _permissions;
  NSDate*   _expirationDate;

  NSMutableSet* _requests;

  NSURL *requestURL;
}

@property(nonatomic, assign) id<LinkedInSessionDelegate> sessionDelegate;

@property (nonatomic, strong) OAConsumer *consumer;
@property (nonatomic, strong) OAToken *accessToken;
@property (nonatomic, copy) NSDate* expirationDate;
//@property (nonatomic, retain) OAuthLoginView *oAuthLoginView;
@property (nonatomic, retain) LinkedInLoginDialog *loginDialog;

- (id)initWithDelegate:(id<LinkedInSessionDelegate>)delegate;

//- (void)logout:(id<LinkedInSessionDelegate>)delegate;

- (BOOL)isSessionValid;

- (void)authorize:(NSString *)permissions;

- (void)requestWithGraphPath: (NSString *) graphPath
                   andParams: (NSArray *) params
               andHttpMethod: (NSString *) httpMethod
                 andDelegate: (id <NSObject>) delegate;

- (void) updateStatus : (NSString *) status
         withGraphPath: (NSString *) graphPath
             andParams: (NSArray *) params
         andHttpMethod: (NSString *) httpMethod
           andDelegate: (id <NSObject>) delegate;

@end
<file_sep>/OAuthStarterKit/LinkedInLoginDialog.h
//
//  LinkedInLoginDialog.h
//  Peoplebank App
//
//  Created by <NAME> on 9/09/12.
//  Copyright (c) 2012 Alive. All rights reserved.
//

#import "LinkedInDialog.h"

@protocol LinkedInLoginDialogDelegate;

/**
 * Do not use this interface directly, instead, use authorize in Facebook.h
 *
 * Linkedin Login Dialog interface for start the linkedin webView login dialog.
 * It start pop-ups prompting for credentials and permissions.
 */

@interface LinkedInLoginDialog : LinkedInDialog {
  id<LinkedInLoginDialogDelegate> _loginDelegate;
}

- (id)initWithParams :(NSString*) params
             delegate:(id <LinkedInLoginDialogDelegate>) delegate;

@end

///////////////////////////////////////////////////////////////////////////////////////////////////

@protocol LinkedInLoginDialogDelegate <NSObject>

- (void)liDialogLogin:(NSString*)token expirationDate:(NSDate*)expirationDate;

- (void)liDialogNotLogin:(BOOL)cancelled;

@end

<file_sep>/OAuthStarterKit/LinkedInDialog.m
/*
*
* LinkedInDialog.m
* PBProto
*
* Created by <NAME> on 9/09/12.
* Code based off the FBConnect API
*
* Copyright (c) 2012 Alive. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0

* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#import "LinkedInDialog.h"
#import "JSON.h"

#define API_KEY_LENGTH 12
#define SECRET_KEY_LENGTH 16

///////////////////////////////////////////////////////////////////////////////////////////////////
// global

static CGFloat kBorderGray[4] = {0.3, 0.3, 0.3, 0.8};
static CGFloat kBorderBlack[4] = {0.3, 0.3, 0.3, 1};

static CGFloat kTransitionDuration = 0.3;

static CGFloat kPadding = 0;
static CGFloat kBorderWidth = 20;

///////////////////////////////////////////////////////////////////////////////////////////////////

static BOOL LIIsDeviceIPad() {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
  if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    return YES;
  }
#endif
  return NO;
}

@implementation LinkedInDialog

@synthesize delegate = _delegate,
            params   = _params;

- (void)addRoundedRectToPath:(CGContextRef)context rect:(CGRect)rect radius:(float)radius {
  CGContextBeginPath(context);
  CGContextSaveGState(context);

  if (radius == 0) {
    CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGContextAddRect(context, rect);
  } else {
    rect = CGRectOffset(CGRectInset(rect, 0.5, 0.5), 0.5, 0.5);
    CGContextTranslateCTM(context, CGRectGetMinX(rect)-0.5, CGRectGetMinY(rect)-0.5);
    CGContextScaleCTM(context, radius, radius);
    float fw = CGRectGetWidth(rect) / radius;
    float fh = CGRectGetHeight(rect) / radius;

    CGContextMoveToPoint(context, fw, fh/2);
    CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
    CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
    CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
    CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
  }

  CGContextClosePath(context);
  CGContextRestoreGState(context);
}

- (void)drawRect:(CGRect)rect fill:(const CGFloat*)fillColors radius:(CGFloat)radius {
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();

  if (fillColors) {
    CGContextSaveGState(context);
    CGContextSetFillColor(context, fillColors);
    if (radius) {
      [self addRoundedRectToPath:context rect:rect radius:radius];
      CGContextFillPath(context);
    } else {
      CGContextFillRect(context, rect);
    }
    CGContextRestoreGState(context);
  }

  CGColorSpaceRelease(space);
}

- (void)strokeLines:(CGRect)rect stroke:(const CGFloat*)strokeColor {
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();

  CGContextSaveGState(context);
  CGContextSetStrokeColorSpace(context, space);
  CGContextSetStrokeColor(context, strokeColor);
  CGContextSetLineWidth(context, 1.0);

  {
    CGPoint points[] = {{rect.origin.x+0.5, rect.origin.y-0.5},
      {rect.origin.x+rect.size.width, rect.origin.y-0.5}};
    CGContextStrokeLineSegments(context, points, 2);
  }
  {
    CGPoint points[] = {{rect.origin.x+0.5, rect.origin.y+rect.size.height-0.5},
      {rect.origin.x+rect.size.width-0.5, rect.origin.y+rect.size.height-0.5}};
    CGContextStrokeLineSegments(context, points, 2);
  }
  {
    CGPoint points[] = {{rect.origin.x+rect.size.width-0.5, rect.origin.y},
      {rect.origin.x+rect.size.width-0.5, rect.origin.y+rect.size.height}};
    CGContextStrokeLineSegments(context, points, 2);
  }
  {
    CGPoint points[] = {{rect.origin.x+0.5, rect.origin.y},
      {rect.origin.x+0.5, rect.origin.y+rect.size.height}};
    CGContextStrokeLineSegments(context, points, 2);
  }

  CGContextRestoreGState(context);

  CGColorSpaceRelease(space);
}

- (BOOL)shouldRotateToOrientation:(UIInterfaceOrientation)orientation {
  if (orientation == _orientation) {
    return NO;
  } else {
    return orientation == UIInterfaceOrientationPortrait
    || orientation == UIInterfaceOrientationPortraitUpsideDown
    || orientation == UIInterfaceOrientationLandscapeLeft
    || orientation == UIInterfaceOrientationLandscapeRight;
  }
}

- (CGAffineTransform)transformForOrientation {
  UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  if (orientation == UIInterfaceOrientationLandscapeLeft) {
    return CGAffineTransformMakeRotation(M_PI*1.5);
  } else if (orientation == UIInterfaceOrientationLandscapeRight) {
    return CGAffineTransformMakeRotation(M_PI/2);
  } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
    return CGAffineTransformMakeRotation(-M_PI);
  } else {
    return CGAffineTransformIdentity;
  }
}

- (void)sizeToFitOrientation:(BOOL)transform {
  if (transform) {
    self.transform = CGAffineTransformIdentity;
  }

  CGRect frame = [UIScreen mainScreen].applicationFrame;
  CGPoint center = CGPointMake(
                               frame.origin.x + ceil(frame.size.width/2),
                               frame.origin.y + ceil(frame.size.height/2));

  CGFloat scale_factor = 1.0f;
  if (LIIsDeviceIPad()) {
    // On the iPad the dialog's dimensions should only be 60% of the screen's
    scale_factor = 0.6f;
  }

  CGFloat width = floor(scale_factor * frame.size.width) - kPadding * 2;
  CGFloat height = floor(scale_factor * frame.size.height) - kPadding * 2;

  _orientation = [UIApplication sharedApplication].statusBarOrientation;
  if (UIInterfaceOrientationIsLandscape(_orientation)) {
    self.frame = CGRectMake(kPadding, kPadding, height, width);
  } else {
    self.frame = CGRectMake(kPadding, kPadding, width, height);
  }
  self.center = center;

  if (transform) {
    self.transform = [self transformForOrientation];
  }
}

- (void)updateWebOrientation {
  UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  if (UIInterfaceOrientationIsLandscape(orientation)) {
    [_webView stringByEvaluatingJavaScriptFromString:
     @"document.body.setAttribute('orientation', 90);"];
  } else {
    [_webView stringByEvaluatingJavaScriptFromString:
     @"document.body.removeAttribute('orientation');"];
  }
}

- (void)bounce1AnimationStopped {
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:kTransitionDuration/2];
  [UIView setAnimationDelegate:self];
  [UIView setAnimationDidStopSelector:@selector(bounce2AnimationStopped)];
  self.transform = CGAffineTransformScale([self transformForOrientation], 0.9, 0.9);
  [UIView commitAnimations];
}

- (void)bounce2AnimationStopped {
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:kTransitionDuration/2];
  self.transform = [self transformForOrientation];
  [UIView commitAnimations];
}

- (NSURL*)generateURL:(NSString*)baseURL params:(NSDictionary*)params {
  if (params) {
    NSMutableArray* pairs = [NSMutableArray array];
    for (NSString* key in params.keyEnumerator) {
      NSString* value = [params objectForKey:key];
      NSString* escaped_value = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(
                                                                                NULL, /* allocator */
                                                                                (__bridge CFStringRef)value,
                                                                                NULL, /* charactersToLeaveUnescaped */
                                                                                (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                kCFStringEncodingUTF8);

      [pairs addObject:[NSString stringWithFormat:@"%@=%@", key, escaped_value]];
    }

    NSString* query = [pairs componentsJoinedByString:@"&"];
    NSString* url = [NSString stringWithFormat:@"%@?%@", baseURL, query];
    return [NSURL URLWithString:url];
  } else {
    return [NSURL URLWithString:baseURL];
  }
}

- (void)addObservers {
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(deviceOrientationDidChange:)
                                               name:@"UIDeviceOrientationDidChangeNotification" object:nil];

  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(keyboardWillShow:) name:@"UIKeyboardWillShowNotification"
                                             object:nil];

  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(keyboardWillHide:) name:@"UIKeyboardWillHideNotification"
                                             object:nil];
}

- (void)removeObservers {
  [[NSNotificationCenter defaultCenter] removeObserver:self
                                                  name:@"UIDeviceOrientationDidChangeNotification" object:nil];
  [[NSNotificationCenter defaultCenter] removeObserver:self
                                                  name:@"UIKeyboardWillShowNotification" object:nil];
  [[NSNotificationCenter defaultCenter] removeObserver:self
                                                  name:@"UIKeyboardWillHideNotification" object:nil];
}

- (void)postDismissCleanup {
  [self removeObservers];
  [self removeFromSuperview];
  [_modalBackgroundView removeFromSuperview];
}

- (void)dismiss:(BOOL)animated {
  [self dialogWillDisappear];

  // If the dialog has been closed, then we need to cancel the order to open it.
  // This happens in the case of a frictionless request, see webViewDidFinishLoad for details
  [NSObject cancelPreviousPerformRequestsWithTarget:self
                                           selector:@selector(showWebView)
                                             object:nil];

  _loadingURL = nil;

  if (animated) {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:kTransitionDuration];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(postDismissCleanup)];
    self.alpha = 0;
    [UIView commitAnimations];
  } else {
    [self postDismissCleanup];
  }
}

- (void)cancel {
  [self dialogDidCancel:nil];
}

- (id)init {
  if ((self = [super initWithFrame:CGRectZero])) {
    _delegate = nil;
    _loadingURL = nil;
    _showingKeyboard = NO;

    self.backgroundColor = [UIColor clearColor];
    self.autoresizesSubviews = YES;
    self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.contentMode = UIViewContentModeRedraw;

    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(kPadding, kPadding, 480, 480)];
    _webView.delegate = self;
    _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self addSubview:_webView];

    UIImage* closeImage = [UIImage imageNamed:@"FBDialog.bundle/images/close.png"];

    UIColor* color = [UIColor colorWithRed:167.0/255 green:184.0/255 blue:216.0/255 alpha:1];
    _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_closeButton setImage:closeImage forState:UIControlStateNormal];
    [_closeButton setTitleColor:color forState:UIControlStateNormal];
    [_closeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [_closeButton addTarget:self action:@selector(cancel)
           forControlEvents:UIControlEventTouchUpInside];

    // To be compatible with OS 2.x
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= __IPHONE_2_2
    _closeButton.font = [UIFont boldSystemFontOfSize:12];
#else
    _closeButton.titleLabel.font = [UIFont boldSystemFontOfSize:12];
#endif

    _closeButton.showsTouchWhenHighlighted = YES;
    _closeButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin
    | UIViewAutoresizingFlexibleBottomMargin;
    [self addSubview:_closeButton];

    _spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:
                UIActivityIndicatorViewStyleWhiteLarge];
    if ([_spinner respondsToSelector:@selector(setColor:)]) {
      [_spinner setColor:[UIColor grayColor]];
    } else {
      [_spinner setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    }
    _spinner.autoresizingMask =
    UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin
    | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    [self addSubview:_spinner];
    _modalBackgroundView = [[UIView alloc] init];
  }
  return self;
}

- (void)drawRect:(CGRect)rect {
  [self drawRect:rect fill:kBorderGray radius:0];

  CGRect webRect = CGRectMake(
                              ceil(rect.origin.x + kBorderWidth), ceil(rect.origin.y + kBorderWidth)+1,
                              rect.size.width - kBorderWidth*2, _webView.frame.size.height+1);

  [self strokeLines:webRect stroke:kBorderBlack];
}

- (void)showWebView {
  UIWindow* window = [UIApplication sharedApplication].keyWindow;
  if (!window) {
    window = [[UIApplication sharedApplication].windows objectAtIndex:0];
  }
  _modalBackgroundView.frame = window.frame;
  [_modalBackgroundView addSubview:self];
  [window addSubview:_modalBackgroundView];

  self.transform = CGAffineTransformScale([self transformForOrientation], 0.001, 0.001);
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:kTransitionDuration/1.5];
  [UIView setAnimationDelegate:self];
  [UIView setAnimationDidStopSelector:@selector(bounce1AnimationStopped)];
  self.transform = CGAffineTransformScale([self transformForOrientation], 1.1, 1.1);
  [UIView commitAnimations];

  [self dialogWillAppear];
  [self addObservers];
}

// Show a spinner during the loading time for the dialog. This is designed to show
// on top of the webview but before the contents have loaded.
- (void)showSpinner {
  [_spinner sizeToFit];
  [_spinner startAnimating];
  _spinner.center = _webView.center;
}

- (void)hideSpinner {
  [_spinner stopAnimating];
  _spinner.hidden = YES;
}

- (void)deviceOrientationDidChange:(void*)object {
  UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  if (!_showingKeyboard && [self shouldRotateToOrientation:orientation]) {
    [self updateWebOrientation];

    CGFloat duration = [UIApplication sharedApplication].statusBarOrientationAnimationDuration;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:duration];
    [self sizeToFitOrientation:YES];
    [UIView commitAnimations];
  }
}

- (NSString *) getStringFromUrl: (NSString*) url needle:(NSString *) needle {
  NSString * str = nil;
  NSRange start = [url rangeOfString:needle];
  if (start.location != NSNotFound) {
    // confirm that the parameter is not a partial name match
    unichar c = '?';
    if (start.location != 0) {
      c = [url characterAtIndex:start.location - 1];
    }
    if (c == '?' || c == '&' || c == '#') {
      NSRange end = [[url substringFromIndex:start.location+start.length] rangeOfString:@"&"];
      NSUInteger offset = start.location+start.length;
      str = end.location == NSNotFound ?
      [url substringFromIndex:offset] :
      [url substringWithRange:NSMakeRange(offset, end.location)];
      str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
  }
  return str;
}

- (id)initWithURL: (NSString *) serverURL
           params: (NSString *) params
  isViewInvisible: (BOOL)isViewInvisible
         delegate: (id <LinkedInDialogDelegate>) delegate {

  self = [self init];
  _serverURL = serverURL;
  _params = params;
  _delegate = delegate;
  _isViewInvisible = isViewInvisible;

  return self;
}

- (void)load {
  [self loadURL: _serverURL
            get: _params];
}

- (void)loadURL:(NSString*)url get:(NSDictionary*)getParams
{
  _loadingURL = [self generateURL:url params:getParams];
  NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:_loadingURL];

  [_webView loadRequest:request];
}

- (void)show {
  //  [self load];
  [self sizeToFitOrientation: YES];

  //CGFloat innerWidth = self.frame.size.width - (kBorderWidth+1)*2;
  CGFloat innerWidth = self.frame.size.width - (kBorderWidth * 2);
  [_closeButton sizeToFit];

  _closeButton.frame = CGRectMake(2, 2, 29, 29);

  [self addSubview: _closeButton];

  _webView.frame = CGRectMake(
                              kBorderWidth,
                              kBorderWidth,
                              innerWidth,
                              self.frame.size.height - (kBorderWidth * 2));

  [_webView setContentStretch: _webView.frame];

  if ([apikey length] < API_KEY_LENGTH || [secretkey length] < SECRET_KEY_LENGTH)
  {
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle: @"OAuth Starter Kit"
                          message: @"You must add your apikey and secretkey.  See the project file readme.txt"
                          delegate: nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil];
    [alert show];

    // Notify parent and close this view
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"loginViewDidFinish"
     object:self];

    [self.delegate dialog: self didFailWithError: nil];
  }

  if (!_isViewInvisible) {
    [self showSpinner];
    [self showWebView];
  }

  [self requestTokenFromProvider];
}

- (void)dismissWithSuccess:(BOOL)success animated:(BOOL)animated {
  if (success) {
    if ([_delegate respondsToSelector:@selector(dialogDidComplete:)]) {
      [_delegate dialogDidComplete:self];
    }
  } else {
    if ([_delegate respondsToSelector:@selector(dialogDidNotComplete:)]) {
      [_delegate dialogDidNotComplete:self];
    }
  }

  [self dismiss:animated];
}

- (void)dismissWithError:(NSError*)error animated:(BOOL)animated {
  if ([_delegate respondsToSelector:@selector(dialog:didFailWithError:)]) {
    [_delegate dialog:self didFailWithError:error];
  }

  [self dismiss:animated];
}

- (void)dialogWillAppear {
}

- (void)dialogWillDisappear {
}

- (void)dialogDidSucceed:(NSURL *)url {

  if ([_delegate respondsToSelector:@selector(dialogCompleteWithUrl:)]) {
    [_delegate dialogCompleteWithUrl:url];
  }
  [self dismissWithSuccess:YES animated:YES];
}

- (void)dialogDidCancel:(NSURL *)url {
  if ([_delegate respondsToSelector:@selector(dialogDidNotCompleteWithUrl:)]) {
    [_delegate dialogDidNotCompleteWithUrl:url];
  }
  [self dismissWithSuccess:NO animated:YES];
}

// New methods

//
// OAuth step 1a:
//
// The first step in the the OAuth process to make a request for a "request token".
// Yes it's confusing that the work request is mentioned twice like that, but it is whats happening.
//
- (void)requestTokenFromProvider
{
  OAMutableURLRequest *request =  [[OAMutableURLRequest alloc] initWithURL: requestTokenURL
                                                                  consumer: self.consumer
                                                                     token: nil
                                                                  callback: linkedInCallbackURL
                                                         signatureProvider: nil] ;

  [request setHTTPMethod:@"POST"];

  OARequestParameter * scopeParameter=[OARequestParameter requestParameter:@"scope" value:@"r_fullprofile r_contactinfo r_emailaddress"];

  [request setParameters:[NSArray arrayWithObject:scopeParameter]];

  OADataFetcher *fetcher = [[OADataFetcher alloc] init];

  [fetcher fetchDataWithRequest:request
                       delegate:self
              didFinishSelector:@selector(requestTokenResult:didFinish:)
                didFailSelector:@selector(requestTokenResult:didFail:)];
}

- (void)requestTokenResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
  if (ticket.didSucceed == NO)
    return;

  NSLog(@"Step 2: requestTokenResult");

  NSString *responseBody = [[NSString alloc] initWithData:data
                                                 encoding:NSUTF8StringEncoding];

  NSLog(@"responseBody: %@", responseBody);

  self.requestToken = [[OAToken alloc] initWithHTTPResponseBody:responseBody];

  [self allowUserToLogin];
}

- (void)requestTokenResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
  NSLog(@"%@",[error description]);
}

//
// OAuth step 2:
//
// Show the user a browser displaying the LinkedIn login page.
// They type username/password and this is how they permit us to access their data
// We use a UIWebView for this.
//
// Sending the token information is required, but in this one case OAuth requires us
// to send URL query parameters instead of putting the token in the HTTP Authorization
// header as we do in all other cases.
//
- (void)allowUserToLogin
{
  NSString *userLoginURLWithToken = [NSString stringWithFormat:@"%@?oauth_token=%@",
                                     userLoginURLString, self.requestToken.key];

  userLoginURL = [NSURL URLWithString:userLoginURLWithToken];

  NSLog(@"Firing off URL: %@", userLoginURL.absoluteString);

  NSURLRequest *request = [NSMutableURLRequest requestWithURL: userLoginURL];

  NSError *error;
//
//  [_webView setAutoresizesSubviews: YES];
//  [_webView setClearsContextBeforeDrawing: YES];
//  [_webView setOpaque: YES];
//  [_webView setScalesPageToFit: YES];
//  [_webView setContentMode: UIViewContentModeScaleToFill];

  NSString *string = [NSString stringWithContentsOfURL: userLoginURL
                                              encoding: NSStringEncodingConversionAllowLossy
                                                 error: &error];

  [_webView loadHTMLString: string
                   baseURL:userLoginURL];
  //[_webView loadRequest:request];
}

//
// OAuth step 3:
//
// This method is called when our webView browser loads a URL, this happens 3 times:
//
//      a) Our own [webView loadRequest] message sends the user to the LinkedIn login page.
//
//      b) The user types in their username/password and presses 'OK', this will submit
//         their credentials to LinkedIn
//
//      c) LinkedIn responds to the submit request by redirecting the browser to our callback URL
//         If the user approves they also add two parameters to the callback URL: oauth_token and oauth_verifier.
//         If the user does not allow access the parameter user_refused is returned.
//
//      Example URLs for these three load events:
//          a) https://www.linkedin.com/uas/oauth/authorize?oauth_token=<token value>
//
//          b) https://www.linkedin.com/uas/oauth/authorize/submit   OR
//             https://www.linkedin.com/uas/oauth/authenticate?oauth_token=<token value>&trk=uas-continue
//
//          c) hdlinked://linkedin/oauth?oauth_token=<token value>&oauth_verifier=63600     OR
//             hdlinked://linkedin/oauth?user_refused
//
//
//  We only need to handle case (c) to extract the oauth_verifier value
//
//- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
//{
//	NSURL *url = request.URL;
//	NSString *urlString = url.absoluteString;
//
//  addressBar.text = urlString;
//  [activityIndicator startAnimating];
//
//  BOOL requestForCallbackURL = ([urlString rangeOfString:linkedInCallbackURL].location != NSNotFound);
//  if ( requestForCallbackURL )
//  {
//    BOOL userAllowedAccess = ([urlString rangeOfString:@"user_refused"].location == NSNotFound);
//    if ( userAllowedAccess )
//    {
//      [self.requestToken setVerifierWithUrl:url];
//      [self accessTokenFromProvider];
//    }
//    else
//    {
//      // User refused to allow our app access
//      // Notify parent and close this view
//      [[NSNotificationCenter defaultCenter]
//       postNotificationName:@"loginViewDidFinish"
//       object:self
//       userInfo:nil];
//
//      //      [self dismissModalViewControllerAnimated:YES];
//    }
//  }
//  else
//  {
//    // Case (a) or (b), so ignore it
//  }
//	return YES;
//}

//
// OAuth step 4:
//
- (void)accessTokenFromProvider
{
  NSLog(@"accessTokenFromProvider");

  OAMutableURLRequest *request =
  [[OAMutableURLRequest alloc] initWithURL:accessTokenURL
                                   consumer:self.consumer
                                      token:self.requestToken
                                   callback:nil
                          signatureProvider:nil];

  [request setHTTPMethod:@"POST"];

  OADataFetcher *fetcher = [[OADataFetcher alloc] init];

  OARequestParameter * scopeParameter=[OARequestParameter requestParameter:@"scope" value:@"r_fullprofile r_contactinfo r_emailaddress"];

  [request setParameters:[NSArray arrayWithObject:scopeParameter]];

  [fetcher fetchDataWithRequest:request
                       delegate:self
              didFinishSelector:@selector(accessTokenResult:didFinish:)
                didFailSelector:@selector(accessTokenResult:didFail:)];
}

- (void)accessTokenResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
  NSString *responseBody = [[NSString alloc] initWithData:data
                                                 encoding:NSUTF8StringEncoding];

  BOOL problem = ([responseBody rangeOfString:@"oauth_problem"].location != NSNotFound);

  if ( problem )
  {
    NSLog(@"Request access token failed.");
    NSLog(@"%@",responseBody);
  }
  else
  {
    self.accessToken = [[OAToken alloc] initWithHTTPResponseBody:responseBody];
  }
  // Notify parent and close this view
  [[NSNotificationCenter defaultCenter]
   postNotificationName:@"loginViewDidFinish"
   object:self];
}

//
//  This api consumer data could move to a provider object
//  to allow easy switching between LinkedIn, Twitter, etc.
//
- (void)initLinkedInApi
{
  apikey = kLinkedInApiKey;
  secretkey = kLinkedInApiSecret;

  self.consumer = [[OAConsumer alloc] initWithKey: apikey
                                           secret: secretkey
                                            realm: @"http://api.linkedin.com/"];

  requestTokenURLString = @"https://api.linkedin.com/uas/oauth/requestToken";
  accessTokenURLString  = @"https://api.linkedin.com/uas/oauth/accessToken";
  userLoginURLString    = @"https://www.linkedin.com/uas/oauth/authorize";
  linkedInCallbackURL   = @"hdlinked://linkedin/oauth";

  requestTokenURL = [NSURL URLWithString:requestTokenURLString];
  accessTokenURL  = [NSURL URLWithString:accessTokenURLString];
  userLoginURL    = [NSURL URLWithString:userLoginURLString];
}

#pragma mark -
#pragma mark UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType {

  NSLog(@"Step 3::webView");

  NSURL *url = request.URL;
	NSString *urlString = url.absoluteString;

  addressBar.text = urlString;
  [activityIndicator startAnimating];

  BOOL requestForCallbackURL = ([urlString rangeOfString:linkedInCallbackURL].location != NSNotFound);
  if ( requestForCallbackURL )
  {
    NSLog(@"url contains callback: hdlinked");

    BOOL userAllowedAccess = ([urlString rangeOfString:@"user_refused"].location == NSNotFound);
    if ( userAllowedAccess )
    {
      [self.requestToken setVerifierWithUrl:url];
      [self accessTokenFromProvider];
    }
    else
    {
      // User refused to allow our app access
      // Notify parent and close this view
      [[NSNotificationCenter defaultCenter]
       postNotificationName:@"loginViewDidFinish"
       object:self
       userInfo:nil];
    }
    //return NO;

  }
  else
  {
    // Case (a) or (b), so ignore it

     }
	return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {

  NSLog(@"webViewDidFinishLoad");

  if (_isViewInvisible) {
    // if our cache asks us to hide the view, then we do, but
    // in case of a stale cache, we will display the view in a moment
    // note that showing the view now would cause a visible white
    // flash in the common case where the cache is up to date
    [self performSelector:@selector(showWebView) withObject:nil afterDelay:.05];
  } else {
    [self hideSpinner];
  }
  [self updateWebOrientation];

  [self zoomToFit];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
  // 102 == WebKitErrorFrameLoadInterruptedByPolicyChange
  // -999 == "Operation could not be completed", note -999 occurs when the user clicks away before
  // the page has completely loaded, if we find cases where we want this to result in dialog failure
  // (usually this just means quick-user), then we should add something more robust here to account
  // for differences in application needs
  NSLog(@"didFailLoadWithError: %@", error.debugDescription);
  if (!(([error.domain isEqualToString:@"NSURLErrorDomain"] && error.code == -999) ||
        ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102))) {
    [self dismissWithError:error animated:YES];
  }
}

#pragma mark -
#pragma mark UIKeyboardNotifications

- (void)keyboardWillShow:(NSNotification*)notification {

  _showingKeyboard = YES;

  if (LIIsDeviceIPad()) {
    // On the iPad the screen is large enough that we don't need to
    // resize the dialog to accomodate the keyboard popping up
    return;
  }

  UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  if (UIInterfaceOrientationIsLandscape(orientation)) {
    _webView.frame = CGRectInset(_webView.frame,
                                 -(kPadding + kBorderWidth),
                                 -(kPadding + kBorderWidth));
  }

  [_webView.scrollView scrollRectToVisible: CGRectMake(0, _webView.frame.size.height, 280, 1) animated:YES];
}

- (void)keyboardWillHide:(NSNotification*)notification {
  _showingKeyboard = NO;

  if (LIIsDeviceIPad()){
    return;
  }
  UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  if (UIInterfaceOrientationIsLandscape(orientation)) {
    _webView.frame = CGRectInset(_webView.frame,
                                 kPadding + kBorderWidth,
                                 kPadding + kBorderWidth);
  }
}

-(void)zoomToFit
{
  //[self runJS];

  [self resize];

  //<meta name="viewport" content="width=device-width; minimum-scale=1.0; maximum-scale=1.0; user-scalable=no">
}

- (void)resize{
  CGSize contentSize = _webView.scrollView.contentSize;
  CGSize viewSize = self.bounds.size;

  float rw = 280 / contentSize.width;

  _webView.scrollView.minimumZoomScale = rw;
  //_webView.scrollView.maximumZoomScale = rw;
  _webView.scrollView.zoomScale = rw;

  [_webView setScalesPageToFit: YES];

  _webView.scrollView.delegate = self;
}

- (void) runJS{
  NSLog(@"load js");

  NSString *path = [[NSBundle mainBundle] pathForResource:@"resizeweb" ofType:@"js"];
  NSError *error = nil;
  NSString *jsCode = [NSString stringWithContentsOfFile: path
                                               encoding: NSUTF8StringEncoding
                                                  error: &error];
  if (error) {
    NSLog(@"error: %@", error.debugDescription);
  }
  [_webView stringByEvaluatingJavaScriptFromString:jsCode];
}

#pragma mark -
#pragma mark UIScrollViewDelegate

- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
  NSLog(@"scrollViewDidZoom");
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
  return nil;
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view{
  [self resize];
}

@end
<file_sep>/OAuthStarterKit/LinkedInLoginDialog.m
//
//  LinkedInLoginDialog.m
//  Peoplebank App
//
//  Created by <NAME> on 9/09/12.
//  Copyright (c) 2012 Alive. All rights reserved.
//

#import "LinkedInLoginDialog.h"

@implementation LinkedInLoginDialog

- (id)initWithParams :(NSString*) params
             delegate:(id <LinkedInLoginDialogDelegate>) delegate{

  self = [super init];
  self.params = params;
  _loginDelegate = delegate;

  [self initLinkedInApi];

  return self;
}

- (void) dialogDidSucceed:(NSURL*)url {
  NSString *q = [url absoluteString];
  NSString *token = [self getStringFromUrl:q needle:@"access_token="];
  NSString *expTime = [self getStringFromUrl:q needle:@"expires_in="];
  NSDate *expirationDate =nil;

  if (expTime != nil) {
    int expVal = [expTime intValue];
    if (expVal == 0) {
      expirationDate = [NSDate distantFuture];
    } else {
      expirationDate = [NSDate dateWithTimeIntervalSinceNow:expVal];
    }
  }

  if ((token == (NSString *) [NSNull null]) || (token.length == 0)) {
    [self dialogDidCancel:url];
    [self dismissWithSuccess:NO animated:YES];
  } else {
    if ([_loginDelegate respondsToSelector:@selector(fbDialogLogin:expirationDate:)]) {
//      [_loginDelegate fbDialogLogin:token expirationDate:expirationDate];
    }
    [self dismissWithSuccess:YES animated:YES];
  }
}

/**
 * Override FBDialog : to call with the login dialog get canceled
 */
- (void)dialogDidCancel:(NSURL *)url {
  [self dismissWithSuccess: NO
                  animated: YES];

  if ([_loginDelegate respondsToSelector:@selector(fbDialogNotLogin:)]) {
//    [_loginDelegate fbDialogNotLogin:YES];
  }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
  if (!(([error.domain isEqualToString:@"NSURLErrorDomain"] && error.code == -999) ||
        ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102))) {
    [super webView:webView didFailLoadWithError:error];
    if ([_loginDelegate respondsToSelector:@selector(fbDialogNotLogin:)]) {
//      [_loginDelegate fbDialogNotLogin:NO];
    }
  }
}

@end
<file_sep>/OAuthStarterKit/LinkedIn.m
//
//  ALMLinkedIn.m
//  Peoplebank App
//
//  Created by <NAME> on 6/09/12.
//  Copyright (c) 2012 Alive. All rights reserved.
//

#import "LinkedIn.h"

static NSString* kProviderBaseURL = @"http://api.linkedin.com/";
static NSString* kRedirectURL = @"hdlinked://linkedin/oauth";

static NSString* kAPIKey = kLinkedInApiKey;
static NSString* kAPISecretKey = kLinkedInApiSecret;

@interface LinkedIn ()

// private properties
@property(nonatomic, retain) NSArray* permissions;

@end

@implementation LinkedIn

@synthesize permissions = _permissions,
          expirationDate = _expirationDate;

- (void) updateStatus : (NSString *) status
         withGraphPath: (NSString *) graphPath
             andParams: (NSArray *) params
         andHttpMethod: (NSString *) httpMethod
           andDelegate: (id <LinkedInSessionDelegate>) delegate{

  NSString *stringGraphPath = @"v1/";
  NSString *fullURL = [kProviderBaseURL stringByAppendingString: [stringGraphPath stringByAppendingString: graphPath]];

  requestURL = [NSURL URLWithString: fullURL];

  //self.sessionDelegate = delegate;

  if ([self isSessionValid]) {
    if (self.consumer != nil) {
      OAMutableURLRequest *request =
      [[OAMutableURLRequest alloc] initWithURL: requestURL
                                      consumer: self.consumer
                                         token: self.accessToken
                                      callback: nil
                             signatureProvider: nil];

      NSMutableDictionary *permsDict = [NSMutableDictionary dictionary];

      [permsDict setValue: @"anyone" forKey: @"code"];

      NSMutableDictionary *shareJSONDict = [NSMutableDictionary dictionary];

      [shareJSONDict setValue: permsDict forKey: @"visibility"];

      [shareJSONDict setValue: status forKey: @"comment"];

      [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

      NSString *updateString = [shareJSONDict JSONString];

      [request setHTTPBodyWithString:updateString];
      [request setHTTPMethod:@"POST"];

      OADataFetcher *fetcher = [[OADataFetcher alloc] init];

      [fetcher fetchDataWithRequest: request
                           delegate: self.sessionDelegate
                  didFinishSelector: @selector(postUpdateApiCallResult:didFinish:)
                    didFailSelector: @selector(postUpdateApiCallResult:didFail:)];
    }
    else{
      OAMutableURLRequest *request =
      [[OAMutableURLRequest alloc] initWithURL: requestURL
                                      consumer: self.loginDialog.consumer
                                         token: self.loginDialog.accessToken
                                      callback: nil
                             signatureProvider: nil];

      NSMutableDictionary *permsDict = [NSMutableDictionary dictionary];

      [permsDict setValue: @"anyone" forKey: @"code"];

      NSMutableDictionary *shareJSONDict = [NSMutableDictionary dictionary];
      [shareJSONDict setValue: permsDict forKey: @"visibility"];
      [shareJSONDict setValue: status forKey: @"comment"];

      [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

      NSString *updateString = [shareJSONDict JSONString];

      [request setHTTPBodyWithString:updateString];
      [request setHTTPMethod:@"POST"];

      OADataFetcher *fetcher = [[OADataFetcher alloc] init];

      [fetcher fetchDataWithRequest: request
                           delegate: self.sessionDelegate
                  didFinishSelector: @selector(postUpdateApiCallResult:didFinish:)
                    didFailSelector: @selector(postUpdateApiCallResult:didFail:)];
    }
  }
  else{
    NSString *paramsString = [[NSMutableString alloc] init];

    for (NSString *param in params)
      paramsString = [paramsString stringByAppendingFormat: @" %@", param];

    NSRange range = NSMakeRange(0, 1);

    [paramsString stringByReplacingCharactersInRange: range
                                          withString: @""]; //Remove leading space.

    NSLog(@"Requesting Linkedin Permissions: %@", paramsString);

    [self authorize: paramsString];
  }
}

- (void)postUpdateApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
  // The next thing we want to do is call the network updates
  NSLog(@"postUpdateApiCallResult");
}

- (void)postUpdateApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
  NSLog(@"%@",[error description]);
}

- (void)requestWithGraphPath: (NSString *) graphPath
                   andParams: (NSArray *) params
               andHttpMethod: (NSString *) httpMethod
                 andDelegate: (id <LinkedInSessionDelegate>) delegate{

  NSString *stringGraphPath = @"v1/";
  NSString *fullURL = [kProviderBaseURL stringByAppendingString: [stringGraphPath stringByAppendingString: graphPath]];

  requestURL = [NSURL URLWithString: fullURL];

  if ([self isSessionValid]){
    [self apiCall];
  }
  else{
    NSString *paramsString = [[NSMutableString alloc] init];

    for (NSString *param in params)
      paramsString = [paramsString stringByAppendingFormat: @" %@", param];

    NSRange range = NSMakeRange(0, 1);

    [paramsString stringByReplacingCharactersInRange: range
                                          withString: @""]; //Remove leading space.

    NSLog(@"Requesting Linkedin Permissions: %@", paramsString);

    [self authorize: paramsString]; //@"r_fullprofile r_contactinfo r_emailaddress"
  }
}

- (void)authorize:(NSString *)permissions{
  NSLog(@"authorize: %@", permissions);

  self.loginDialog = [[LinkedInLoginDialog alloc] initWithParams: permissions
                                                        delegate: self];

  // register to be told when the login is finished
  [[NSNotificationCenter defaultCenter] addObserver: self
                                           selector: @selector(loginViewDidFinish:)
                                               name: @"loginViewDidFinish"
                                             object: self.loginDialog];

  [self.loginDialog show];
}

-(void) loginViewDidFinish:(NSNotification*)notification
{
  self.accessToken = self.loginDialog.accessToken;

  [self saveAccessTokenDetails];

	[[NSNotificationCenter defaultCenter] removeObserver:self];

  [self apiCall];
}

- (void) saveAccessTokenDetails{
  NSMutableDictionary *accessTokenParamsDict = [NSMutableDictionary dictionary];
  if (self.accessToken.key)       [accessTokenParamsDict setObject: self.accessToken.key forKey: @"key"];
  if (self.accessToken.secret)    [accessTokenParamsDict setObject: self.accessToken.secret forKey: @"secret"];
  if (self.accessToken.session)   [accessTokenParamsDict setObject: self.accessToken.session forKey: @"session"];
  if (self.accessToken.verifier)  [accessTokenParamsDict setObject: self.accessToken.verifier forKey: @"verifier"];
  if (self.accessToken.duration)  [accessTokenParamsDict setObject: self.accessToken.duration forKey: @"duration"];
  if (self.accessToken.attributes)[accessTokenParamsDict setObject: self.accessToken.attributes forKey: @"attributes"];

  [accessTokenParamsDict setObject: [NSDate date]
                            forKey: @"date"];  // date created

  [accessTokenParamsDict setObject: [NSNumber numberWithBool: self.accessToken.forRenewal]
                            forKey: @"forRenewal"];

  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

  if ([defaults objectForKey: @"kAccessToken"])
    [defaults removeObjectForKey: @"kAccessToken"];

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

  if (self.loginDialog.consumer.key) [consumerDict setObject: self.loginDialog.consumer.key
                                                      forKey: @"key"];

  if (self.loginDialog.consumer.secret) [consumerDict setObject: self.loginDialog.consumer.secret
                                                         forKey: @"secret"];

  if (self.loginDialog.consumer.realm) [consumerDict setObject: self.loginDialog.consumer.realm
                                                        forKey: @"realm"];

  [defaults setObject: accessTokenParamsDict
               forKey: @"kAccessToken"];

  [defaults setObject: consumerDict
               forKey: @"kConsumer"];
}

- (void) apiCall{
  //If cached AccessToken, no need to use the loginDialog recieved settings, get it locally.
  if (self.consumer != nil) {
    OAMutableURLRequest *request =
    [[OAMutableURLRequest alloc] initWithURL: requestURL
                                    consumer: self.consumer
                                       token: self.accessToken
                                    callback: nil
                           signatureProvider: nil];

    [request setValue:@"json" forHTTPHeaderField:@"x-li-format"];

    OADataFetcher *fetcher = [[OADataFetcher alloc] init];

    [fetcher fetchDataWithRequest: request
                         delegate: self.sessionDelegate
                didFinishSelector: @selector(profileApiCallResult:didFinish:)
                  didFailSelector: @selector(profileApiCallResult:didFail:)];
  }
  else{
    OAMutableURLRequest *request =
    [[OAMutableURLRequest alloc] initWithURL: requestURL
                                    consumer: self.loginDialog.consumer
                                       token: self.loginDialog.accessToken
                                    callback: nil
                           signatureProvider: nil];

    [request setValue:@"json" forHTTPHeaderField:@"x-li-format"];

    OADataFetcher *fetcher = [[OADataFetcher alloc] init];

    [fetcher fetchDataWithRequest: request
                         delegate: self.sessionDelegate
                didFinishSelector: @selector(profileApiCallResult:didFinish:)
                  didFailSelector: @selector(profileApiCallResult:didFail:)];
  }
}

- (id)initWithDelegate:(id<LinkedInSessionDelegate>)delegate{
  self = [super init];
  if (self) {
    _requests = [[NSMutableSet alloc] init];
    self.sessionDelegate = delegate;
  }

  return self;
}

/*
  If the access token cannot be verified, show the dialogue box.
 */
- (BOOL)isSessionValid
{
//  return (self.accessToken != nil && self.expirationDate != nil
//          && NSOrderedDescending == [self.expirationDate compare:[NSDate date]]);

  NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

  NSMutableDictionary *dictForToken = [userDefaults objectForKey: @"kAccessToken"];
  NSMutableDictionary *dictForConsumer = [userDefaults objectForKey: @"kConsumer"];

  if (self.accessToken == nil) {
    if (dictForToken) {

      NSNumber *isRenewable = [dictForToken objectForKey:@"forRenewal"];

      self.accessToken = [[OAToken alloc] initWithKey: [dictForToken objectForKey:@"key"]
                                               secret: [dictForToken objectForKey:@"secret"]
                                              session: [dictForToken objectForKey:@"session"]
                                             verifier: [dictForToken objectForKey:@"verifier"]
                                             duration: [dictForToken objectForKey:@"duration"]
                                           attributes: [dictForToken objectForKey:@"attributes"]
                                              created: [dictForToken objectForKey:@"date"]
                                            renewable: isRenewable.boolValue];

      self.consumer = [[OAConsumer alloc] initWithKey: [dictForConsumer objectForKey: @"key"]
                                               secret: [dictForConsumer objectForKey: @"secret"]
                                                realm: [dictForConsumer objectForKey: @"realm"]];
    }
  }

  //TODO: Add check for access token being invalid for some reason...
  return (self.accessToken != nil);
}

#pragma mark -
#pragma mark LinkedInLoginDialogDelegate

- (void)liDialogLogin:(NSString*)token expirationDate:(NSDate*)expirationDate{
  NSLog(@"liDialogLogin");
}

- (void)liDialogNotLogin:(BOOL)cancelled{
  NSLog(@"liDialogNotLogin");
}

#pragma mark -
#pragma mark LinkedInDialogDelegate

- (void)dialogDidComplete:(LinkedInDialog *)dialog{
  NSLog(@"LinkedInDialogDelegate::dialogDidComplete");
}

- (void)dialogCompleteWithUrl:(NSURL *)url{
  NSLog(@"LinkedInDialogDelegate::dialogCompleteWithUrl");
}

- (void)dialogDidNotCompleteWithUrl:(NSURL *)url{
  NSLog(@"LinkedInDialogDelegate::dialogDidNotCompleteWithUrl");
}

- (void)dialogDidNotComplete:(LinkedInDialog *)dialog{
  NSLog(@"LinkedInDialogDelegate::dialogDidNotComplete");
}

- (void)dialog:(LinkedInDialog*)dialog didFailWithError:(NSError *)error{
  NSLog(@"LinkedInDialogDelegate::didFailWithError");
}

- (BOOL)dialog:(LinkedInDialog*)dialog shouldOpenURLInExternalBrowser:(NSURL *)url{
  NSLog(@"LinkedInDialogDelegate::shouldOpenURLInExternalBrowser");
  return NO;
}

@end

repo_language: Objective-C

repo_name: mrdavenz/LinkedIn-OAuth-Sample-Client


text:
<file_sep>vive-Yasuni
===========

Educación Ambiental


text:
<repo_name>YHQQ521/vue-Bam-master<file_sep>/README.md
# vue-el

![passing](https://img.shields.io/badge/build-passing-brightgreen.svg)
![node](https://img.shields.io/badge/node-8.11.1-green.svg)
![yarn](https://img.shields.io/badge/yarn-1.12.3-green.svg)

  使用vue 2.0 + element UI 构建文章管理系统界面

---

## 技术栈
  * **vue-cli** 脚手架直接生成

  * **element-UI** 作为UI框架，配合界面的搭建

  * **webpack** 打包压缩，babel编译Es6/7语法

  * yarn 包管理

  * 前后端分离，[后端项目](https://github.com/HerryLo/koa-mongoDB.git)，[前端管理系统](https://github.com/HerryLo/vue-Bam)

[koa+MongoDB 后端接口](https://github.com/HerryLo/koa-mongoDB.git)

## 功能
| 功能 |  路由地址 |
|:------|:-------|
|登录    | /sign_in   |
|用户管理 | /userAdmin |
|文章管理 | /articleList |
|创建文章 | /writeArt |

## 运行

``` bash
$ git clone https://github.com/HerryLo/BAM.git

// 安装依赖
$ npm install

// 本地开发
$ npm run dev

// 生产构建
$ npm run build
```

同时需要启动[koa+MongoDB](https://github.com/HerryLo/koa-mongoDB.git)提供接口。
<file_sep>/src/components/index.vue
<template>
  <el-container style="height: 100%;">
    <el-aside width="200px" style="background-color: rgb(50, 65, 87);">

    </el-aside>

    <el-container style="height: aoto;">
      <el-header>
        admin
      </el-header>
      <el-main style="background:#eee;">

        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<file_sep>/src/components/user/sign_up.vue
<template>

                <router-link to="/sign_in" >登录</router-link>
                ·
                <router-link id="js-sign-up-btn" to="/sign_up" class="active">注册</router-link>

                <el-input style="width:300px;margin-bottom:10px" v-model="user" placeholder="请输入你的昵称"></el-input>
                <el-input style="width:300px;margin-bottom:10px" v-model="photo" placeholder="请输入手机号或邮箱"></el-input>
                <el-input style="width:300px;margin-bottom:30px" v-model="password" type="<PASSWORD>" placeholder="请设置密码"></el-input>
                <el-row>
                    <el-button style="width:100%" type="primary" success @click="register">注册</el-button>
                </el-row>

</template>

<file_sep>/src/components/article/articleList.vue
<template>

        <el-row type="flex" justify="end">
          <el-col :span="3">
            <el-button type="primary" @click="AddArt" icon="el-icon-edit">添加文章</el-button>
          </el-col>
        </el-row>
        <el-table
        :data="list"
        style="width: 100%">
        <el-table-column
        fixed
        prop="createTime"
        label="创建时间"
        width="200">
        </el-table-column>
        <el-table-column
        prop="userId"
        label="用户ID"
        width="250">
        </el-table-column>
        <el-table-column
        prop="userName"
        label="创建者名称"
        width="150">
        </el-table-column>
        <el-table-column
        prop="title"
        label="标题"
        width="200">
        </el-table-column>
        <el-table-column
        prop="imgUrl"
        label="图片地址"
        width="150">
        </el-table-column>
        <el-table-column
        prop="oneNumber"
        label="查看人数"
        width="150">
        </el-table-column>
        <el-table-column
        fixed="right"
        label="操作"
        width="120">
        <template slot-scope="scope">
            <el-button
            @click.native.prevent="Gorouter(scope.$index, tableData4)"
            type="text"
            size="small">
            编辑
            </el-button>
            <el-button
            @click.native.prevent="deleteRow(scope.$index, tableData4)"
            type="text"
            size="small">
            下架
            </el-button>
        </template>
        </el-table-column>
        </el-table>
        <el-pagination
            style="margin-top: 20px;float:right"
            background
            layout="prev, pager, next"
            :total="totalPage"
            @prev-click="prevClick"
            @next-click="nextClick"
            @current-change="currentChange">
        </el-pagination>

</template>

<file_sep>/src/components/user/userAdmin.vue
<template>

  <el-table
    :data="dataList"
    style="width: 100%;"
    max-height="250"
    cell-class-name="word-style">
    <el-table-column
      fixed
      prop="regtime"
      label="日期"
      width="150">
    </el-table-column>
    <el-table-column
      prop="user"
      label="用户名"
      width="120">
    </el-table-column>
    <el-table-column
      prop="_id"
      label="用户ID"
      width="250">
    </el-table-column>
    <el-table-column
      prop="isadmin"
      label="管理员"
      width="120">
    </el-table-column>
    <el-table-column
      prop="photo"
      label="电话"
      width="120">
    </el-table-column>
    <el-table-column
      fixed="right"
      label="操作"
      width="120">
      <template slot-scope="scope">
        <el-button
          @click.native.prevent="deleteRow(scope.$index, dataList)"
          type="text"
          size="small">
          移除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    style="margin-top: 20px;float:right"
    background
    layout="prev, pager, next"
    :total="1000">
  </el-pagination>

</template>

<file_sep>/src/vuex/mutation.js
import * as types from './mutation_type'

export default {
  [types.NAVSTATE] (state) {
    return state.navState
  }
}
<file_sep>/src/components/user/sign_in.vue
<template>

                <router-link to="/sign_in" class="active">登录</router-link>

                <el-input style="width:300px;margin-bottom:10px" v-model="user" placeholder="请输入用户名"></el-input>
                <el-input style="width:300px;margin-bottom:30px" v-model="password" type="<PASSWORD>" placeholder="请输入密码"></el-input>
                <el-row>
                    <el-button style="width:100%" type="primary" @click="login">登录</el-button>
                </el-row>

</template>

<file_sep>/src/components/article/writArt.vue
<template>

       <el-upload
          class="upload-demo"
          action=""
          :auto-upload="false"
          multiple
          :limit="1"
          :file-list="fileList"
          :before-remove="beforeRemove"
          :on-exceed="handleExceed"
          :on-change="changeFile"
          style="margin-bottom: 20px;">
          <el-button size="small" type="primary">上传图片</el-button>

只能上传jpg/png文件，且不超过500kb

        </el-upload>
       <el-input placeholder="请输入标题" v-model="title">
        <template slot="prepend">标题</template>
       </el-input>
       <el-input
        type="textarea"
        :autosize="{ minRows: 2, maxRows: 4}"
        placeholder="请输入描述内容"
        v-model="desc">
       </el-input>

     <quill-editor
        style="width:800px;height:450px;background:#fff;padding-bottom: 60px;"
        v-model="content"
        ref="myQuillEditor"
        :options="editorOption"
        @blur="onEditorBlur($event)"
        @focus="onEditorFocus($event)"
        @ready="onEditorReady($event)">
      </quill-editor>

        <el-tag
        :key="tag"
        v-for="tag in dynamicTags"
        closable
        :disable-transitions="false"
        @close="handleClose(tag)">
        {{tag}}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm">
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 标签</el-button>

      <el-button @click="submit" type="primary" style="margin-top: 20px;">提交</el-button>

</template>

<file_sep>/src/components/common/asideMenu.vue
<template>

        <el-row style="height: 100%;">
        <el-col :span="4"  style="min-height: 100%; background-color: #324057;width:100%">

            <el-menu
            :default-active="defaultActive"
            background-color="rgb(50, 65, 87)"
            text-color="#fff"
            active-text-color="#ffd04b"
            style="min-height: 100%;"
            theme="dark"
            router>
            <el-submenu index="1">
                <template slot="title">管理员</template>
                <el-menu-item index="userAdmin">用户管理</el-menu-item>
                <el-menu-item index="writeArt">添加文章</el-menu-item>
                <el-menu-item index="articleList">文章列表</el-menu-item>
            </el-submenu>
            </el-menu>
        </el-col>
		</el-row>

</template>

<file_sep>/src/vuex/mutation_type.js
/**
 * 公共头部状态
 */
export const NAVSTATE = 'NAVSTATE'
<file_sep>/src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [{
    path: '/',
    name: 'Index',
    component: resolve => {
      require(['@/components/index'], resolve)
    },
    children: [{
      path: '/writeArt',
      name: 'writeArt',
      component: resolve => {
        require(['@/components/article/writArt'], resolve)
      }
    }, {
      path: '/userAdmin',
      name: 'userAdmin',
      component: resolve => {
        require(['@/components/user/userAdmin'], resolve)
      }
    }, {
      path: '/articleList',
      name: 'articleList',
      component: resolve => {
        require(['@/components/article/articleList'], resolve)
      }
    }]
  }, {
    path: '/sign_in',
    name: 'sign_in',
    component: resolve => {
      require(['@/components/user/sign_in'], resolve)
    }
  }, {
    path: '/sign_up',
    name: 'sign_up',
    component: resolve => {
      require(['@/components/user/sign_up'], resolve)
    }
  }]
})

languages: Markdown Vue JavaScript


text:
<repo_name>pyumbillo75/platzi<file_sep>/funcional-js-00-boilerplate/js/currying.js
const buildSum = a => b => a + b
const tag = t => content => `<${t}>${content}</${t}>`<file_sep>/funcional-js-00-boilerplate/js/highOrderFunctions.js
const array1 = [1, 2, 3]
const array2 = []
const array3 = []
for (let i = 0; i < array1.length; i++) {
    array2.push(array1[i] * 2);

}
array3 = array1.map(item => item * 2)

repo_language: JavaScript


text:
<repo_name>vanems96/ExamenFinalAndroid2<file_sep>/app/src/main/java/com/example/examenfinalandroid/FechaAdapter.java
package com.example.examenfinalandroid;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class FechaAdapter extends RecyclerView.Adapter<FechaAdapter.ViewHolder> {

    List<Fecha> fechas;

    public FechaAdapter(List<Fecha> fechas) {
        this.fechas = fechas;
    }

    @NonNull
    @Override
    public FechaAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fecha_row,parent,false);
        return new FechaAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull FechaAdapter.ViewHolder holder, int position) {

        holder.fecha.setText(fechas.get(position).getFechaMed());
        holder.porcentajeDeGrasa.setText(fechas.get(position).getPorcentajeGra());
        holder.porcentajeMasaMuscular.setText(fechas.get(position).getMasaMuscular());
        holder.pesoEnKilogramos.setText(fechas.get(position).getPesoKg());
        holder.edadMetabolica.setText(fechas.get(position).getEdadMeta());
        holder.idAlumno.setText(fechas.get(position).getIdAlum());

    }

    @Override
    public int getItemCount() {
        return fechas.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView fecha;
        public TextView porcentajeDeGrasa;
        public TextView porcentajeMasaMuscular;
        public TextView pesoEnKilogramos;
        public TextView edadMetabolica;
        public TextView idAlumno;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            fecha = itemView.findViewById(R.id.Fecha);
            porcentajeDeGrasa = itemView.findViewById(R.id.porcentaje_grasa);
            porcentajeMasaMuscular = itemView.findViewById(R.id.porcentaje_masa_muscular);
            pesoEnKilogramos = itemView.findViewById(R.id.peso_kg);
            edadMetabolica = itemView.findViewById(R.id.edad_metabolica);
            idAlumno = itemView.findViewById(R.id.idAlumno);
        }
    }
}

repo_language: Java


text:
<repo_name>niomwungeri-fabrice/udacity-fitness<file_sep>/src/components/UHistoryStack.js
import React from 'react';
import { createStackNavigator } from '@react-navigation/stack';

import UHistory from './UHistory';
import EntryDetails from './UEntryDetails';
import { white } from '../utils/colors';

const Stack = createStackNavigator();

const UHistoryStack = () => {
  return (
    <Stack.Navigator
      screenOptions={{
        headerStyle: {
          backgroundColor: white
        }
      }}
    >
      <Stack.Screen name="History" component={UHistory} />
      <Stack.Screen
        name="Details"
        component={EntryDetails}
        options={({ route }) => {
          const { entryId } = route.params;
          return {
            title: entryId
          };
        }}
      />
    </Stack.Navigator>
  );
};

export default UHistoryStack;
<file_sep>/README.md
# udacity-fitness
A udacity project for Udacity developer NanoDegree
<file_sep>/src/components/UAddEntry.js
import React, { Component } from 'react';
import { CommonActions } from '@react-navigation/native';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Platform
} from 'react-native';

import {
  getMetricMetaInfo,
  timeToString,
  getDailyReminderValue,
  clearLocalNotification,
  setLocalNotification
} from '../utils/helpers';

import { USlider } from './USlider';
import { UStepper } from './UStepper';
import { UDate } from './UDate';
import { Ionicons } from '@expo/vector-icons';
import { UTextButton } from './UTextButton';
import { connect } from 'react-redux';
import { addEntry } from '../redux/actions';
import { white, purple } from '../utils/colors';
import { submitEntry } from '../api';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: white
  },
  row: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center'
  },
  iosSubmitBtn: {
    backgroundColor: purple,
    padding: 10,
    borderRadius: 7,
    height: 45,
    marginLeft: 40,
    marginRight: 40
  },
  androidSubmitBtn: {
    backgroundColor: purple,
    padding: 10,
    paddingLeft: 30,
    paddingRight: 30,
    height: 45,
    borderRadius: 2,
    alignSelf: 'flex-end',
    justifyContent: 'center',
    alignItems: 'center'
  },
  text: {
    color: white,
    fontSize: 22,
    textAlign: 'center'
  },
  center: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 30,
    marginRight: 30
  }
});
const SubmitBtn = ({ onPress }) => {
  return (
    <TouchableOpacity
      style={
        Platform.OS === 'ios' ? styles.iosSubmitBtn : styles.androidSubmitBtn
      }
      onPress={onPress}
    >
      <Text style={styles.text}>Save</Text>
    </TouchableOpacity>
  );
};

class UAddEntry extends Component {
  state = {
    run: 0,
    swim: 0,
    bike: 0,
    eat: 0,
    sleep: 0
  };

  handleSubmit = () => {
    const key = timeToString();
    const entry = this.state;
    this.props.dispatch(
      addEntry({
        [key]: entry
      })
    );
    this.setState({ run: 0, swim: 0, bike: 0, eat: 0, sleep: 0 });

    submitEntry({ key, entry });

    clearLocalNotification().then(setLocalNotification);

    this.toHome();
  };

  handleIncrement = metric => {
    const { max, step } = getMetricMetaInfo(metric);
    this.setState(currState => {
      const count = currState[metric] + step;
      return {
        ...currState,
        [metric]: count > max ? max : count
      };
    });
  };

  handleDecrement = metric => {
    const { step } = getMetricMetaInfo(metric);
    this.setState(currState => {
      const count = currState[metric] - step;
      return {
        ...currState,
        [metric]: count < 0 ? 0 : count
      };
    });
  };

  handleSlide = (metric, value) => {
    this.setState({
      [metric]: value
    });
  };

  handleReset = () => {
    const key = timeToString();
    this.props.dispatch(
      addEntry({
        [key]: getDailyReminderValue()
      })
    );
    this.toHome();
  };
  toHome = () => {
    const { navigation } = this.props;
    return navigation.dispatch(CommonActions.navigate({ name: 'Add Entry' }));
  };
  render() {
    if (this.props.hasLoggedInfo) {
      return (
        <View style={styles.center}>
          <Ionicons
            name={Platform.OS === 'ios' ? 'ios-happy' : 'md-happy'}
            size={100}
          />
          <Text>You have already logged in your info for today</Text>
          <UTextButton style={{ padding: 10 }} onPress={this.handleReset}>
            reset
          </UTextButton>
        </View>
      );
    }

    const allMetrics = getMetricMetaInfo();
    return (
      <View style={styles.container}>
        <UDate date={new Date().toLocaleDateString()} />
        {Object.keys(allMetrics).map(key => {
          const { getIcon, type, ...rest } = allMetrics[key];
          const value = this.state[key];
          return (
            <View key={key} style={styles.row}>
              {getIcon()}
              {type === 'slider' ? (
                <USlider
                  value={value}
                  onChange={value => this.handleSlide(key, value)}
                  {...rest}
                />
              ) : (
                <UStepper
                  value={value}
                  onIncrement={() => this.handleIncrement(key)}
                  onDecrement={() => this.handleDecrement(key)}
                  {...rest}
                />
              )}
            </View>
          );
        })}
        <SubmitBtn onPress={this.handleSubmit} />
      </View>
    );
  }
}

const mapStateToProps = state => {
  const key = timeToString();
  return {
    hasLoggedInfo: state[key] && typeof state[key].today === 'undefined'
  };
};

export default connect(mapStateToProps)(UAddEntry);
<file_sep>/src/utils/helpers.js
import React from 'react';
import { View, StyleSheet, AsyncStorage } from 'react-native';
import {
  FontAwesome,
  MaterialIcons,
  MaterialCommunityIcons
} from '@expo/vector-icons';
import { red, orange, blue, lightPurple, pink, white } from './colors';
import { Notifications } from 'expo';
import * as Permissions from 'expo-permissions';

const NOTIFICATION_KEY = 'UdaciFitness:notifications';

const styles = StyleSheet.create({
  iconContainer: {
    padding: 5,
    borderRadius: 8,
    width: 50,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 20
  }
});

export function isBetween(num, x, y) {
  if (num >= x && num <= y) {
    return true;
  }

  return false;
}

export function calculateDirection(heading) {
  let direction = '';

  if (isBetween(heading, 0, 22.5)) {
    direction = 'North';
  } else if (isBetween(heading, 22.5, 67.5)) {
    direction = 'North East';
  } else if (isBetween(heading, 67.5, 112.5)) {
    direction = 'East';
  } else if (isBetween(heading, 112.5, 157.5)) {
    direction = 'South East';
  } else if (isBetween(heading, 157.5, 202.5)) {
    direction = 'South';
  } else if (isBetween(heading, 202.5, 247.5)) {
    direction = 'South West';
  } else if (isBetween(heading, 247.5, 292.5)) {
    direction = 'West';
  } else if (isBetween(heading, 292.5, 337.5)) {
    direction = 'North West';
  } else if (isBetween(heading, 337.5, 360)) {
    direction = 'North';
  } else {
    direction = 'Calculating';
  }

  return direction;
}

export function timeToString(time = Date.now()) {
  const date = new Date(time);
  const todayUTC = new Date(
    Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())
  );
  return todayUTC.toISOString().split('T')[0];
}
function setDummyData() {
  const { run, bike, swim, sleep, eat } = getMetricMetaInfo();

  let dummyData = {};
  const timestamp = Date.now();

  for (let i = -183; i < 0; i++) {
    const time = timestamp + i * 24 * 60 * 60 * 1000;
    const strTime = timeToString(time);
    dummyData[strTime] =
      getRandomNumber(3) % 2 === 0
        ? {
            run: getRandomNumber(run.max),
            bike: getRandomNumber(bike.max),
            swim: getRandomNumber(swim.max),
            sleep: getRandomNumber(sleep.max),
            eat: getRandomNumber(eat.max)
          }
        : null;
  }

  AsyncStorage.setItem(CALENDAR_STORAGE_KEY, JSON.stringify(dummyData));

  return dummyData;
}

function setMissingDates(dates) {
  const length = Object.keys(dates).length;
  const timestamp = Date.now();

  for (let i = -183; i < 0; i++) {
    const time = timestamp + i * 24 * 60 * 60 * 1000;
    const strTime = timeToString(time);

    if (typeof dates[strTime] === 'undefined') {
      dates[strTime] = null;
    }
  }

  return dates;
}

export function formatCalendarResults(results) {
  return results === null
    ? setDummyData()
    : setMissingDates(JSON.parse(results));
}

export const getDailyReminderValue = () => {
  return {
    today: "👋 Don't forget to log your data today!"
  };
};

export const getMetricMetaInfo = metric => {
  const info = {
    run: {
      displayName: 'Run',
      max: 50,
      unit: 'miles',
      step: 1,
      type: 'steppers',
      getIcon() {
        return (
          <View style={[styles.iconContainer, { backgroundColor: red }]}>
            <MaterialIcons name="directions-run" color={white} size={35} />
          </View>
        );
      }
    },
    bike: {
      displayName: 'Bike',
      max: 100,
      unit: 'miles',
      step: 1,
      type: 'steppers',
      getIcon() {
        return (
          <View style={[styles.iconContainer, { backgroundColor: blue }]}>
            <MaterialCommunityIcons name="bike" color={white} size={32} />
          </View>
        );
      }
    },
    swim: {
      displayName: 'Swim',
      max: 9900,
      unit: 'meters',
      step: 100,
      type: 'steppers',
      getIcon() {
        return (
          <View
            style={[styles.iconContainer, { backgroundColor: lightPurple }]}
          >
            <MaterialCommunityIcons name="swim" color={white} size={35} />
          </View>
        );
      }
    },
    sleep: {
      displayName: 'Sleep',
      max: 24,
      unit: 'hours',
      step: 1,
      type: 'slider',
      getIcon() {
        return (
          <View style={[styles.iconContainer, { backgroundColor: pink }]}>
            <FontAwesome name="bed" color={white} size={30} />
          </View>
        );
      }
    },
    eat: {
      displayName: 'Eat',
      max: 10,
      unit: 'rating',
      step: 1,
      type: 'slider',
      getIcon() {
        return (
          <View style={[styles.iconContainer, { backgroundColor: orange }]}>
            <MaterialCommunityIcons name="food" color={white} size={35} />
          </View>
        );
      }
    }
  };

  return typeof metric === 'undefined' ? info : info[metric];
};

export function createNotification() {
  return {
    title: 'Log your stats!',
    body: "👋 don't forget to log your stats for today!",
    ios: {
      sound: true
    },
    android: {
      sound: true,
      priority: 'high',
      sticky: false,
      vibrate: true
    }
  };
}

export function clearLocalNotification() {
  return AsyncStorage.removeItem(NOTIFICATION_KEY).then(
    Notifications.cancelAllScheduledNotificationsAsync
  );
}

export function setLocalNotification() {
  AsyncStorage.getItem(NOTIFICATION_KEY)
    .then(JSON.parse)
    .then(data => {
      if (data === null) {
        Permissions.askAsync(Permissions.NOTIFICATIONS).then(({ status }) => {
          if (status === 'granted') {
            Notifications.cancelAllScheduledNotificationsAsync();

            let tomorrow = new Date();
            tomorrow.setDate(tomorrow.getDate());
            tomorrow.setHours(15);
            tomorrow.setMinutes(54);
            Notifications.scheduleLocalNotificationAsync(createNotification(), {
              time: tomorrow,
              repeat: 'day'
            });
            AsyncStorage.setItem(NOTIFICATION_KEY, JSON.stringify(true));
          }
        });
      }
    });
}
<file_sep>/src/components/UEntryDetails.js
import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import { connect } from 'react-redux';
import { UMetricCard } from './UMetricCard';
import { white } from '../utils/colors';
import { UTextButton } from './UTextButton';
import { timeToString, getDailyReminderValue } from '../utils/helpers';
import { addEntry } from '../redux/actions';
import { removeEntry } from '../api';
import { useNavigation } from '@react-navigation/native';
export class UEntryDetails extends Component {
  handleReset = () => {
    console.log('called!!!');
    const { remove, goBack, entryId } = this.props;
    remove();
    goBack();
    removeEntry(entryId);
  };
  shouldComponentUpdate(nextProps) {
    return nextProps.metrics !== null && !nextProps.metrics.today;
  }
  render() {
    const { metrics } = this.props;

    return (
      <View style={styles.container}>
        <UMetricCard metrics={metrics} />
        <UTextButton style={{ padding: 10 }} onPress={this.handleReset}>
          reset
        </UTextButton>
      </View>
    );
  }
}
function mapStateToProps(entries, { route }) {
  const { entryId } = route.params;
  return {
    entries,
    metrics: entries[entryId]
  };
}
function mapDispatchToProps(dispatch, { route }) {
  const { entryId } = route.params;
  const navigation = useNavigation();
  return {
    remove: () =>
      dispatch(
        addEntry({
          [entryId]: timeToString() === entryId ? getDailyReminderValue() : null
        })
      ),
    goBack: () => navigation.goBack()
  };
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: white,
    padding: 10
  }
});

export default connect(mapStateToProps, mapDispatchToProps)(UEntryDetails);
<file_sep>/App.js
import React, { Component } from 'react';
import { View, Platform, StatusBar } from 'react-native';
import Constants from 'expo-constants';

import { createStore } from 'redux';
import { Provider } from 'react-redux';
import entries from './src/redux/reducers';

import { NavigationContainer } from '@react-navigation/native';
import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import UAddEntry from './src/components/UAddEntry';
import { purple, white } from './src/utils/colors';
import { Ionicons, FontAwesome, MaterialIcons } from '@expo/vector-icons';
import UHistoryStack from './src/components/UHistoryStack';
import ULive from './src/components/ULive';
import { setLocalNotification } from './src/utils/helpers';

function AppStatusBar({ backgroundColor, ...props }) {
  return (
    <View style={{ backgroundColor, height: Constants.statusBarHeight }}>
      <StatusBar translucent backgroundColor={backgroundColor} {...props} />
    </View>
  );
}

const Tabs =
  Platform.OS === 'ios'
    ? createBottomTabNavigator()
    : createMaterialTopTabNavigator();
export default class App extends Component {
  componentDidMount() {
    setLocalNotification();
  }
  render() {
    return (
      <Provider store={createStore(entries)}>
        <View style={{ flex: 1 }}>
          <AppStatusBar backgroundColor={purple} barStyle="light-content" />
          <NavigationContainer>
            <Tabs.Navigator
              initialRouteName="UAddEntry"
              screenOptions={({ route }) => ({
                tabBarIcon: ({ color, size }) => {
                  let icon;
                  if (route.name === 'Add Entry') {
                    icon = (
                      <FontAwesome
                        name="plus-square"
                        size={size}
                        color={color}
                      />
                    );
                  } else if (route.name === 'History') {
                    icon = (
                      <Ionicons
                        name="ios-bookmarks"
                        size={size}
                        color={color}
                      />
                    );
                  } else if (route.name === 'Live') {
                    icon = (
                      <MaterialIcons
                        name="directions-walk"
                        size={size}
                        color={color}
                      />
                    );
                  }
                  return icon;
                }
              })}
              tabBarOptions={{
                activeTintColor: Platform.OS === 'ios' ? purple : white,
                style: {
                  height: 80,
                  backgroundColor: Platform.OS === 'ios' ? white : purple,
                  shadowColor: 'rgba(0, 0, 0, 0.24)',
                  shadowOffset: {
                    width: 0,
                    height: 3
                  },
                  shadowRadius: 6,
                  shadowOpacity: 1
                }
              }}
            >
              <Tabs.Screen name="History" component={UHistoryStack} />
              <Tabs.Screen name="Add Entry" component={UAddEntry} />
              <Tabs.Screen name="Live" component={ULive} />
            </Tabs.Navigator>
          </NavigationContainer>
        </View>
      </Provider>
    );
  }
}

languages: Markdown JavaScript

repo_name: niomwungeri-fabrice/udacity-fitness