text:
@interface MultiPlayerViewController ()
    @property(strong, nonatomic)MPCHandler *mpcHandler; // Multi Peer Connection handler
    @property(strong, nonatomic)NSMutableDictionary* tableviewData;
    @property(strong, nonatomic)NSMutableArray* gameViewData;
    @property(strong, nonatomic)NSMutableArray* others;
@end

@implementation MultiPlayerViewController
// lazy inits
-(NSMutableDictionary*)tableviewData
{
    if(_tableviewData==nil)
        _tableviewData = [NSMutableDictionary new];
    return _tableviewData;
}
-(NSMutableArray*)gameViewData
{
    if(_gameViewData==nil)
        _gameViewData = [NSMutableArray new];
    return _gameViewData;
}
-(NSMutableArray*)others
{
    if(_others==nil){
        _others = [NSMutableArray new];
        [_others addObject:@{@"strategy_name" : [NSString stringWithFormat:@"You - %@",self.myStrategy.name],@"boiled_rule":[self.myStrategy ruleBoiler]}];
    }
    return _others;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Start the game server aka multi peer connectivity
    [self startmpcHandler];
    // place a stop button on the top right in the tool bar
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Stop" style:UIBarButtonItemStylePlain target:self action:@selector(stopStartTheGame:)];
    // register the game nib as in the local tournament
    [self.gamePlayTableView registerNib:[GameRoundTableViewCell nib] forCellReuseIdentifier:GameRoundCellIdentifier];

}

- (IBAction)stopStartTheGame:(id)sender
{
    // if the stop button is pressed then we need to kill the tournament and present the results view
    NSLog(@"StopStart The Game NOW");

    [self killmpcHandler];
    [self.navigationItem setRightBarButtonItem:nil animated:YES];
    [self performSegueWithIdentifier:@"resultsSegue" sender:self];
}
// if we press the back button we should stop the game and remove the notification listener
- (void)viewWillDisappear:(BOOL)animated
{
    [self killmpcHandler];
    self.tableviewData = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:kRecievedStrategyNotification];

}
// helper method for starting mpc
-(void)startmpcHandler
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(remoteDataRecieved:)
                                                 name:kRecievedStrategyNotification
                                               object:nil];
    // stop retain cycles and start the server
    __weak MultiPlayerViewController *weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
        MPCHandler* handler = [[MPCHandler alloc]initWithStrategy:self.myStrategy];
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            [weakSelf setMpcHandler:handler];
        });
    });
}
// helper method to stop the mpc handler
-(void)killmpcHandler
{
    __weak MultiPlayerViewController *weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
        [weakSelf.mpcHandler stop];
        [weakSelf setMpcHandler:nil];
    });
    [[NSNotificationCenter defaultCenter] removeObserver:kRecievedStrategyNotification];
}
// one list of remote strategies and a list of playoffs
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(tableView == self.remotePlayersTableView)
        return 1;
    else
        return self.gameViewData.count;
}
//same as local tournament, the numeber strategies/remote players and the number games that have been played
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(tableView == self.remotePlayersTableView)
        return self.tableviewData.count;
    else
        return [[[self.gameViewData objectAtIndex:section] objectForKey:@"rounds"] count];
}
// set the title for the header in a given section, "Remote strategies" or the strategy vs strategy
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(tableView == self.remotePlayersTableView){
        return @"Remote Strategies";
    }else{
        return [NSString stringWithFormat:@"Game %d: %@ vs %@",(int)section+1,[[self.gameViewData objectAtIndex:section] objectForKey:@"strategy_1"],[[self.gameViewData objectAtIndex:section] objectForKey:@"strategy_2"]];
    }
}
// respond to clicking on a table view cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // we add the strategy (remote)
    if(tableView == self.remotePlayersTableView){
        NSLog(@"I Want that Strategy");

        NSArray *keys = [self.tableviewData allKeys];
        NSString *name = [keys objectAtIndex:indexPath.row];
        name = [name stringByAppendingString:@" - "];
        name = [name stringByAppendingString:[[self.tableviewData objectForKey:[keys objectAtIndex:indexPath.row]] objectForKey:@"strategy_name"]];

        // needs to be on the same thread for autosave.
        // find out if we need to replace or insert into the database, we dont want to strategies with the same name
        __block BOOL replace;
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            MStrategy *newStrategy = [MStrategy strategyForName:name];
            replace = YES;
            if(!newStrategy){
                newStrategy = [NSEntityDescription insertNewObjectForEntityForName:@"MStrategy"
                                                            inManagedObjectContext:appD.document.managedObjectContext];
                replace = NO;
            }
            newStrategy.name = name;

            for(NSDictionary* rule in [[self.tableviewData objectForKey:[keys objectAtIndex:indexPath.row]] objectForKey:@"ruleset"]){
                MRule *mrule = [NSEntityDescription insertNewObjectForEntityForName:@"MRule"
                                                             inManagedObjectContext:appD.document.managedObjectContext];
                mrule.strategy = newStrategy;
                mrule.response = [rule objectForKey:@"response"];
                mrule.position = [rule objectForKey:@"position"];
            }
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Added Strategy"
                                                                message:replace?@"This strategy has been updated.":@"This strategy has been added."
                                                               delegate:self cancelButtonTitle:@"Close"
                                                      otherButtonTitles:nil];
                dispatch_async(dispatch_get_main_queue(), ^(void) {
                    [alert show];
                    [self.gamePlayTableView deselectRowAtIndexPath:indexPath animated:YES];
                });
            });
        });

    }else{
        // present the results of a game i.e. the game inspector
        [self performSegueWithIdentifier:@"inspectRound" sender:self];
    }
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == self.remotePlayersTableView){
        // set the cell to the remote players strategy name and the device broadcast as the subtitle
        UITableViewCell *cell;
        static NSString *kCellIdentifier = @"detailedCell";
        cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];

        if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellIdentifier];

        NSArray *keys = [self.tableviewData allKeys];
        NSString *name = [keys objectAtIndex:indexPath.row];
        NSString *strategy = [[self.tableviewData objectForKey:name] objectForKey:@"strategy_name"];
        [cell.textLabel setText:strategy];
        [cell.detailTextLabel setText:name];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
        [button setUserInteractionEnabled:NO];
        cell.accessoryView = button;
        return cell;
    }else{
        // set the values for the game cell. this is the same as in the local tournement.
        // This shouldnt need commenting as the variables are named well.
        GameRoundTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:GameRoundCellIdentifier forIndexPath:indexPath];
        if(cell == nil){
            cell = [[GameRoundTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:GameRoundCellIdentifier];
        }

        cell.strategyOneLabel.text = [self.gameViewData[indexPath.section] objectForKey:@"strategy_1"];
        cell.strategyTwoLabel.text = [self.gameViewData[indexPath.section] objectForKey:@"strategy_2"];

        NSArray* payoffArray = [[[self.gameViewData[indexPath.section] objectForKey:@"rounds"] objectAtIndex:indexPath.row] objectForKey:@"payoffs"];

        cell.rewardsLabel.text = [NSString stringWithFormat:@"%@ times",[[payoffArray objectAtIndex:0]objectAtIndex:0]];
        cell.punshmentsLabel.text = [NSString stringWithFormat:@"%@ times",[[payoffArray objectAtIndex:0]objectAtIndex:3]];
        cell.strategyOneSuckerTemptedLabel.text = [NSString stringWithFormat:@"%@/%@",
                                                   [[payoffArray objectAtIndex:0]objectAtIndex:1],
                                                   [[payoffArray objectAtIndex:0]objectAtIndex:2]];

        cell.strategyTwoSuckerTemptedLabel.text = [NSString stringWithFormat:@"%@/%@",
                                                   [[payoffArray objectAtIndex:1]objectAtIndex:1],
                                                   [[payoffArray objectAtIndex:1]objectAtIndex:2]];

        int p1score = [[[self.gameViewData[indexPath.section] objectForKey:@"rounds"][indexPath.row] objectForKey:@"p1score"] intValue];
        int p2score = [[[self.gameViewData[indexPath.section] objectForKey:@"rounds"][indexPath.row] objectForKey:@"p2score"] intValue];
        [cell.trophyOneImage setHidden:(BOOL)(p1score<p2score)];
        [cell.trophyTwoImage setHidden:(BOOL)(p1score>p2score)];
        [cell.drawLabel setText:(p1score==p2score)?@"Draw":@"Winner"];
        return cell;
    }

}
// we define a winner or a draw in the footer
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if(tableView == self.remotePlayersTableView){ return nil; }
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
    footer.backgroundColor = [UIColor blackColor];

    UILabel *lbl = [[UILabel alloc]initWithFrame:footer.frame];
    lbl.backgroundColor = [UIColor clearColor];

    int result = [[[self.gameViewData objectAtIndex:section] objectForKey:@"result"] integerValue];
    if(result == GameResultStateDraw){
        lbl.text = @"Draw";
    }else{
        NSString* winner = [[self.gameViewData objectAtIndex:section] objectForKey:(result == GameResultStatePlayerOneWinner)?@"strategy_1":@"strategy_2"];
        lbl.text = [NSString stringWithFormat:@"%@ Wins",winner];
    }
    lbl.textAlignment = NSTextAlignmentCenter;
    lbl.textColor = [UIColor whiteColor];
    [footer addSubview:lbl];

    return footer;
}

// manuualy need to set the size of a footer should one exist
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if(self.remotePlayersTableView == tableView) return 0;
    return 30.0;
}
// foots group and float by default which gets confusing
- (BOOL) allowsFooterViewsToFloat {
    return NO;
}
// we must manually define the size of our cells
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(tableView == self.remotePlayersTableView) return 44;
    else return 117;

}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // present the round inspector if a game cell is pressed
    if([segue.identifier isEqual:@"inspectRound"]){
        NSIndexPath *indexPath = [self.gamePlayTableView indexPathForSelectedRow];
        [self.gamePlayTableView deselectRowAtIndexPath:indexPath animated:NO];
        [(IndividualGameReviewViewController*)segue.destinationViewController
         setRoundData:[[self.gameViewData[indexPath.section] objectForKey:@"rounds"] objectAtIndex:indexPath.row]];
        [(IndividualGameReviewViewController*)segue.destinationViewController
         setStrategyNames:@[[self.gameViewData[indexPath.section] objectForKey:@"strategy_1"],[self.gameViewData[indexPath.section] objectForKey:@"strategy_2"]]];
    }else if([segue.identifier isEqual:@"resultsSegue"]){
        // show the ordered results
        NSMutableDictionary *winners = [NSMutableDictionary new];

        for(int section = 0; section<self.gameViewData.count; section++ ){
            for(int row = 0; row<[[self.gameViewData[section] objectForKey:@"rounds"] count]; row++ ){
                int p1score = [[[self.gameViewData[section] objectForKey:@"rounds"][row] objectForKey:@"p1score"] intValue];
                int p2score = [[[self.gameViewData[section] objectForKey:@"rounds"][row] objectForKey:@"p2score"] intValue];

                if([winners objectForKey:[self.gameViewData[section] objectForKey:@"strategy_1"]]){
                    [winners setObject:[NSNumber numberWithLong:p1score+[[[winners objectForKey:self.gameViewData[section]] objectForKey:@"strategy_1"] longValue]]
                                forKey:[self.gameViewData[section] objectForKey:@"strategy_1"]];
                }else{
                    [winners setObject:@(p1score)
                                forKey:[self.gameViewData[section] objectForKey:@"strategy_1"]];
                }

                if([winners objectForKey:[self.gameViewData[section] objectForKey:@"strategy_2"]]){
                    [winners setObject:[NSNumber numberWithLong:p2score+[[[winners objectForKey:self.gameViewData[section]] objectForKey:@"strategy_2"] longValue]]
                                forKey:[self.gameViewData[section] objectForKey:@"strategy_2"]];
                }else{
                    [winners setObject:@(p2score)
                                forKey:[self.gameViewData[section] objectForKey:@"strategy_2"]];
                }
            }
        }
        // sort the winners anad losers
        NSArray *orderedWinners;

        orderedWinners = [winners keysSortedByValueUsingComparator: ^(id obj1, id obj2) {

            if ([obj1 unsignedLongValue] < [obj2 unsignedLongValue]) return (NSComparisonResult)NSOrderedDescending;
            if ([obj1 unsignedLongValue] > [obj2 unsignedLongValue]) return (NSComparisonResult)NSOrderedAscending;
            return (NSComparisonResult)NSOrderedSame;
        }];

        [(ResultPopUpViewController*)segue.destinationViewController setWinners:orderedWinners];
    }

}

-(void)remoteDataRecieved:(NSNotification *)notification
{
    //NSLog(@"Recieved data: %@",notification.userInfo);

    // this method is called when a remote strategy is recieved
    // the remote strategy is added to the left side table
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        NSString *deviceName = [notification.userInfo objectForKey:@"device_name"];
        BOOL replace = [self.tableviewData objectForKey:deviceName] != nil;
        [self.tableviewData setObject:notification.userInfo forKey:deviceName];
        if(replace){
            NSArray *keys = [self.tableviewData allKeys];
            for(int i=0; i<keys.count; i++){
                if([keys[i] isEqualToString:deviceName]){
                    [self.remotePlayersTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
                    break;
                }
            }
        }else{
            [self.remotePlayersTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.tableviewData.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    });
    // a call is made to ensure that the new strategy plays every other already revcieved strategy, then the results are added to the tableview.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
        NSDictionary *remotePlayer = @{@"strategy_name" : [NSString stringWithFormat:@"%@ - %@",[notification.userInfo objectForKey:@"device_name"],[notification.userInfo objectForKey:@"strategy_name"]],@"boiled_rule":[notification.userInfo objectForKey:@"boiled_rule"]};
        NSArray *games = [Game play:remotePlayer againstArray:[self.others copy]];
        [self.others addObject:remotePlayer];
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            for(NSDictionary* game in games){
                [self.gameViewData addObject:game];
                [self.gamePlayTableView insertSections:[NSIndexSet indexSetWithIndex:self.gameViewData.count-1] withRowAnimation: UITableViewRowAnimationFade];
            }
        });
    });
}

@end


text:
Sök efter resa

        Välj avgång, destination och från vilken dag flyget ska giltigt. Tryck sedan på 'Sök'.

      <form class="form-inline" ng-submit="recommend.searchFlights()">

          <select class="form-control" ng-model="recommend.departure" ng-change="recommend.getDestinations()">
            <option value="" disabled selected>Välj avgång</option>
            <option ng-repeat="departure in recommend.departures" ng-value="departure.ACR">{{departure.Name}}</option>
          </select>
          <select class="form-control" ng-model="recommend.destination">
            <option value="" disabled selected>Välj destination</option>
            <option ng-repeat="destination in recommend.destinations" ng-value="destination.ACR">{{destination.Name}}</option>
          </select>

          <input class="form-control" type="text" ng-model="today" placeholder="Avgång: YYYY-MM-DD" required>

        <input class="btn btn-info" type="submit" value="Sök">
      </form>

Boka resa

        Välj kund och biljett-klass. Tryck sedan på 'Boka'-knappen på ditt val.

      <select ng-model="recommend.currentCustomer">
        <option value="" disabled selected>Välj kund</option>
        <option ng-repeat="customer in recommend.customers" ng-value="customer.CustomerID">
          {{customer.Name}}
        </option>
      </select>

          Avgång(lokal tid)
          Landar(lokal tid)
          Avgår ifrån
          Destination
          Första klass
          Business klass
          Ekonomi klass

          {{flight.TakeOff | date}}
          {{flight.Landing | date}}
          {{flight.Departure}}
          {{flight.Destination}}

            <input class="radio radio-inline" type="radio" name="group{{flight.FlightID}}" ng-model="recommend.flight[flight.FlightID].class" ng-change="recommend.setSeats(recommend.flight[flight.FlightID], flight.FirstClassSeats)" value="2">
            {{flight.StandardPriceFirstClass}}:- {{flight.FirstClassSeats}}

            <input class="radio radio-inline" type="radio" name="group{{flight.FlightID}}" ng-model="recommend.flight[flight.FlightID].class" ng-change="recommend.setSeats(recommend.flight[flight.FlightID], flight.BusinessSeats)"  value="1">
            {{flight.StandardPriceBusiness}}:- {{flight.BusinessSeats}}

            <input class="radio radio-inline" type="radio" name="group{{flight.FlightID}}" ng-model="recommend.flight[flight.FlightID].class" ng-change="recommend.setSeats(recommend.flight[flight.FlightID], flight.CoachSeats)" value="0">
            {{flight.StandardPriceCoach}}:- {{flight.CoachSeats}}

          <button class="btn btn-info btn-small" ng-disabled="!recommend.flight[flight.FlightID].class || !recommend.currentCustomer || recommend.flight[flight.FlightID].seats <= 0" ng-click="recommend.bookFlight(flight.FlightID, recommend.currentCustomer, recommend.flight[flight.FlightID].class)">Boka</button>

redpajama_set_name: RedPajamaGithub


text:
A simple plugin that turns arrays into nice lists.

Turns things like `['Boston', 'Chicago', 'Detroit']` into Boston, Chicago or Detroit

```
{# Input #}
{{ ['Boston', 'Chicago', 'Detroit'] | make_list('and') }}

{# Returns #}
Boston, Chicago and Detroit
```


text:
<?php
/**
 * @author MGriesbach@gmail.com
 * @license http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link http://github.com/MSeven/cakephp_queue
 */
App::uses('AppShell', 'Console/Command');

/**
 * Execute a Local command on the server.
 *
 */
class QueueExecuteTask extends AppShell {

	/**
	 * Adding the QueueTask Model
	 *
	 * @var array
	 */
	public $uses = array(
		'Queue.QueuedTask'
	);

	/**
	 * @var QueuedTask
	 */
	public $QueuedTask;

	/**
	 * Timeout for run, after which the Task is reassigned to a new worker.
	 *
	 * @var integer
	 */
	public $timeout = 0;

	/**
	 * Number of times a failed instance of this task should be restarted before giving up.
	 *
	 * @var integer
	 */
	public $retries = 1;

	/**
	 * Stores any failure messages triggered during run()
	 *
	 * @var string
	 */
	public $failureMessage = '';

	/**
	 * @var boolean
	 */
	public $autoUnserialize = true;

	/**
	 * Add functionality.
	 * Will create one example job in the queue, which later will be executed using run();
	 */
	public function add() {
		$this->out('CakePHP Queue Execute task.');
		$this->hr();
		if (count($this->args) < 2) {
			$this->out('This will run an shell command on the Server.');
			$this->out('The task is mainly intended to serve as a kind of buffer for programm calls from a cakephp application.');
			$this->out(' ');
			$this->out('Call like this:');
			$this->out('	cake queue add execute *command* *param1* *param2* ...');
			$this->out(' ');
		} else {

			$data = array(
				'command' => $this->args[1],
				'params' => array_slice($this->args, 2)
			);
			if ($this->QueuedTask->createJob('Execute', $data)) {
				$this->out('Job created');
			} else {
				$this->err('Could not create Job');
			}

		}
	}

	/**
	 * Run function.
	 * This function is executed, when a worker is executing a task.
	 * The return parameter will determine, if the task will be marked completed, or be requeued.
	 *
	 * @param array $data The array passed to QueuedTask->createJob()
	 * @return boolean Success
	 */
	public function run($data) {
		$command = escapeshellcmd($data['command']) . ' ' . implode(' ', $data['params']);
		$this->out('Executing: ' . $command);
		exec($command, $output, $status);
		$this->out(' ');
		$this->out($output);
		return (!$status);
	}

}


text:
#ifndef __itkMetaImageMaskConverter_h
#define __itkMetaImageMaskConverter_h

//
// to avoid an Internal Compiler Error in Visual Studio 6.0
//
#include "metaImage.h"
#include "itkImageMaskSpatialObject.h"
#include "itkMetaConverterBase.h"

namespace itk
{

/** \class MetaImageMaskConverter
 *  \brief converts between MetaObject<->SpatialObject
 *  \sa MetaConverterBase
 *  \ingroup ITK-SpatialObjects
 */
template< unsigned int NDimensions = 3 >
class ITK_EXPORT MetaImageMaskConverter :
    public MetaImageConverter< NDimensions, unsigned char, ImageMaskSpatialObject< NDimensions > >
{
public:
  /** Standard class typedefs */
  typedef MetaImageMaskConverter                           Self;
  typedef MetaImageConverter< NDimensions, unsigned char > Superclass;
  typedef SmartPointer< Self >                             Pointer;
  typedef SmartPointer< const Self >                       ConstPointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(MetaImageMaskConverter, MetaImageConverter);

protected:
  virtual const char *GetMetaObjectSubType()
  {
    return "Mask";
  }
  MetaImageMaskConverter() {}
  ~MetaImageMaskConverter() {}

private:
  MetaImageMaskConverter(const Self &);   //purposely not implemented
  void operator=(const Self &);       //purposely not implemented
};

} // end namespace itk

#endif


text:
WINRT_EXPORT namespace winrt {

namespace Windows::ApplicationModel::Wallet::System {

struct WINRT_EBO WalletItemSystemStore :
    Windows::ApplicationModel::Wallet::System::IWalletItemSystemStore,
    impl::require<WalletItemSystemStore, Windows::ApplicationModel::Wallet::System::IWalletItemSystemStore2>
{
    WalletItemSystemStore(std::nullptr_t) noexcept {}
};

struct WalletManagerSystem
{
    WalletManagerSystem() = delete;
    static Windows::Foundation::IAsyncOperation<Windows::ApplicationModel::Wallet::System::WalletItemSystemStore> RequestStoreAsync();
};

}

}


text:
import errno
import glob
import os
import sys
import django
import subprocess

from pymongo import ReadPreference, MongoClient
from mongoengine import connect

sys.path.insert(0, os.path.dirname(__file__))

# calculated paths for django and the site
# used as starting points for various other paths
DJANGO_ROOT = os.path.dirname(os.path.realpath(django.__file__))
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))

# Version
CRITS_VERSION = '4-master'

#the following gets the current git hash to be displayed in the footer and
#hides it if it is not a git repo
try:
    HIDE_GIT_HASH = False
    #get the short hand of current git hash
    GIT_HASH = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).strip()
    #get the long hand of the current git hash
    GIT_HASH_LONG = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip()
    #get the git branch
    GIT_BRANCH = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip()
except:
    #if it is not a git repo, clear out all values and hide them
    GIT_HASH = ''
    GIT_HASH_LONG = ''
    HIDE_GIT_HASH = True
    GIT_BRANCH = ''

APPEND_SLASH = True
TEST_RUN = False

# Set to DENY|SAMEORIGIN|ALLOW-FROM uri
# Default: SAMEORIGIN
# More details: https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options
#X_FRAME_OPTIONS = 'ALLOW-FROM https://www.example.com'

# Setup for runserver or Apache
if 'runserver' in sys.argv:
    DEVEL_INSTANCE = True
    SERVICE_MODEL = 'thread'
    SESSION_COOKIE_SECURE = False
    CSRF_COOKIE_SECURE = False
    LOGIN_URL = "/login/"
elif 'test' in sys.argv:
    TEST_RUN = True
    DEVEL_INSTANCE = True
    SERVICE_MODEL = 'thread'
    SESSION_COOKIE_SECURE = False
    CSRF_COOKIE_SECURE = False
    LOGIN_URL = "/login/"
else:
    DEVEL_INSTANCE = False
    SERVICE_MODEL = 'process'
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
    LOGIN_URL = "/login/"

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.dummy'
    }
}

# MongoDB Default Configuration
# Tip: To change database settings, override by using
#      template from config/database_example.py
MONGO_HOST = 'localhost'                          # server to connect to
MONGO_PORT = 27017                                # port MongoD is running on
MONGO_DATABASE = 'crits'                          # database name to connect to
MONGO_SSL = False                                 # whether MongoD has SSL enabled
MONGO_USER = ''                                   # username used to authenticate to mongo (normally empty)
MONGO_PASSWORD = ''                               # password for the mongo user

# File storage backends
S3 = "S3"
GRIDFS = "GRIDFS"

# DB to use for files
FILE_DB = GRIDFS

# S3 buckets
BUCKET_PCAPS = "pcaps"
BUCKET_OBJECTS = "objects"
BUCKET_SAMPLES = "samples"

# Import custom Database config
dbfile = os.path.join(SITE_ROOT, 'config/database.py')
if os.path.exists(dbfile):
    execfile(dbfile)

if TEST_RUN:
    MONGO_DATABASE = 'crits-unittest'

# Read preference to configure which nodes you can read from
# Possible values:
# primary: queries are sent to the primary node in a replicSet
# secondary: queries are allowed if sent to primary or secondary
#            (for single host) or are distributed to secondaries
#            if you are connecting through a router
# More info can be found here:
# http://api.mongodb.org/python/current/api/pymongo/index.html
MONGO_READ_PREFERENCE = ReadPreference.PRIMARY

# MongoDB default collections
COL_ACTORS = "actors"                                     # main collection for actors
COL_ACTOR_IDENTIFIERS = "actor_identifiers"               # main collection for actor identifiers
COL_ACTOR_THREAT_IDENTIFIERS = "actor_threat_identifiers" # actor threat identifiers
COL_ACTOR_THREAT_TYPES = "actor_threat_types"             # actor threat types
COL_ACTOR_MOTIVATIONS = "actor_motivations"               # actor motivations
COL_ACTOR_SOPHISTICATIONS = "actor_sophistications"       # actor sophistications
COL_ACTOR_INTENDED_EFFECTS = "actor_intended_effects"     # actor intended effects
COL_ANALYSIS_RESULTS = "analysis_results"                 # analysis results
COL_AUDIT_LOG = "audit_log"                               # audit log entries
COL_BACKDOOR_DETAILS = "backdoor_details"                 # backdoor information
COL_BUCKET_LISTS = "bucket_lists"                         # bucketlist information
COL_CAMPAIGNS = "campaigns"                               # campaigns list
COL_CERTIFICATES = "certificates"                         # certificates list
COL_COMMENTS = "comments"                                 # comments collection
COL_CONFIG = "config"                                     # config collection
COL_COUNTS = "counts"                                     # general counts for dashboard
COL_DIVISION_DATA = "division_data"                       # information on divisions within company
COL_DOMAINS = "domains"                                   # root domains with FQDNs and IP information
COL_EFFECTIVE_TLDS = "effective_tlds"                     # list of effective TLDs from Mozilla to determine root domains
COL_EMAIL = "email"                                       # main email collection
COL_EVENTS = "events"                                     # main events collection
COL_EVENT_TYPES = "event_types"                           # event types for events
COL_EXPLOIT_DETAILS = "exploit_details"                   # list of CVE's
COL_EXPLOITS = "exploits"                                 # exploit count generated by MapReduce
COL_FILETYPES = "filetypes"                               # list of filetypes in system generated by MapReduce
COL_IDB_ACTIONS = "idb_actions"                           # list of available actions to be taken with indicators
COL_INDICATORS = "indicators"                             # main indicators collection
COL_INTERNAL_LOCATIONS = "internal_locations"             # site locations for company
COL_IPS = "ips"                                           # IPs collection
COL_NOTIFICATIONS = "notifications"                       # notifications collection
COL_OBJECTS = "objects"                                   # objects that are files that have been added
COL_OBJECT_TYPES = "object_types"                         # types of objects that can be added
COL_PCAPS = "pcaps"                                       # main pcaps collection
COL_RAW_DATA = "raw_data"                                 # main raw data collection
COL_RAW_DATA_TYPES = "raw_data_types"                     # list of available raw data types
COL_RELATIONSHIP_TYPES = "relationship_types"             # list of available relationship types
COL_SAMPLES = "sample"                                    # main samples collection
COL_SCREENSHOTS = "screenshots"                           # main screenshots collection
COL_SECTOR_LISTS = "sector_lists"                         # sector lists information
COL_SECTORS = "sectors"                                   # available sectors
COL_SERVICES = "services"                                 # list of services for scanning
COL_SOURCE_ACCESS = "source_access"                       # source access ACL collection
COL_SOURCES = "sources"                                   # source information generated by MapReduce
COL_STATISTICS = "statistics"                             # list of statistics for different objects (campaigns, for example)
COL_TARGETS = "targets"                                   # target information for use in email
COL_USERS = "users"                                       # main users collection
COL_USER_ROLES = "user_roles"                             # main user roles collection
COL_YARAHITS = "yarahits"                                 # yara hit counts for samples

# MongoDB connection pool
if MONGO_USER:
    connect(MONGO_DATABASE, host=MONGO_HOST, port=MONGO_PORT, read_preference=MONGO_READ_PREFERENCE, ssl=MONGO_SSL,
            username=MONGO_USER, password=MONGO_PASSWORD)
else:
    connect(MONGO_DATABASE, host=MONGO_HOST, port=MONGO_PORT, read_preference=MONGO_READ_PREFERENCE, ssl=MONGO_SSL)

# Get config from DB
c = MongoClient(MONGO_HOST, MONGO_PORT, ssl=MONGO_SSL)
db = c[MONGO_DATABASE]
if MONGO_USER:
    db.authenticate(MONGO_USER, MONGO_PASSWORD)
coll = db[COL_CONFIG]
crits_config = coll.find_one({})
if not crits_config:
    crits_config = {}

# Populate settings
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
# NOTE: we are setting ALLOWED_HOSTS to ['*'] by default which will work
#       everywhere but is insecure for production installations (no less secure
#       than setting DEBUG to True). This is done because we can't anticipate
#       the host header for every CRITs install and this should work "out of
#       the box".
ALLOWED_HOSTS =             crits_config.get('allowed_hosts', ['*'])
COMPANY_NAME =              crits_config.get('company_name', 'My Company')
CLASSIFICATION =            crits_config.get('classification', 'unclassified')
CRITS_EMAIL =               crits_config.get('crits_email', '')
CRITS_EMAIL_SUBJECT_TAG =   crits_config.get('crits_email_subject_tag', '')
CRITS_EMAIL_END_TAG =       crits_config.get('crits_email_end_tag', True)
DEBUG =                     crits_config.get('debug', True)
if crits_config.get('email_host', None):
    EMAIL_HOST =            crits_config.get('email_host', None)
if crits_config.get('email_port', None):
    EMAIL_PORT =        int(crits_config.get('email_port', None))
ENABLE_API =                crits_config.get('enable_api', False)
ENABLE_TOASTS =             crits_config.get('enable_toasts', False)
GIT_REPO_URL =              crits_config.get('git_repo_url', '')
HTTP_PROXY =                crits_config.get('http_proxy', None)
INSTANCE_NAME =             crits_config.get('instance_name', 'My Instance')
INSTANCE_URL =              crits_config.get('instance_url', '')
INVALID_LOGIN_ATTEMPTS =    crits_config.get('invalid_login_attempts', 3) - 1
LANGUAGE_CODE =             crits_config.get('language_code', 'en-us')
LDAP_AUTH =                 crits_config.get('ldap_auth', False)
LDAP_SERVER =               crits_config.get('ldap_server', '')
LDAP_USERDN =               crits_config.get('ldap_userdn', '')
LDAP_USERCN =               crits_config.get('ldap_usercn', '')
LOG_DIRECTORY =             crits_config.get('log_directory', os.path.join(SITE_ROOT, '..', 'logs'))
LOG_LEVEL =                 crits_config.get('log_level', 'INFO')
QUERY_CACHING =             crits_config.get('query_caching', False)
RAR_PATH =                  crits_config.get('rar_path', '/usr/bin/unrar')
RT_URL =                    crits_config.get('rt_url', None)
SECURE_COOKIE =             crits_config.get('secure_cookie', True)
SERVICE_DIRS =        tuple(crits_config.get('service_dirs', []))
SERVICE_MODEL =             crits_config.get('service_model', SERVICE_MODEL)
SERVICE_POOL_SIZE =     int(crits_config.get('service_pool_size', 12))
SESSION_TIMEOUT =       int(crits_config.get('session_timeout', 12)) * 60 * 60
SPLUNK_SEARCH_URL =         crits_config.get('splunk_search_url', None)
TEMP_DIR =                  crits_config.get('temp_dir', '/tmp')
TIME_ZONE =                 crits_config.get('timezone', 'America/New_York')
ZIP7_PATH =                 crits_config.get('zip7_path', '/usr/bin/7za')
REMOTE_USER =               crits_config.get('remote_user', False)
PASSWORD_COMPLEXITY_REGEX = crits_config.get('password_complexity_regex', '(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$')
PASSWORD_COMPLEXITY_DESC =  crits_config.get('password_complexity_desc', '8 characters, at least 1 capital, 1 lowercase and 1 number/special')
DEPTH_MAX =                 crits_config.get('depth_max', '10')
TOTAL_MAX =                 crits_config.get('total_max', '250')
REL_MAX =                   crits_config.get('rel_max', '50')
TOTP =                      crits_config.get('totp', False)

COLLECTION_TO_BUCKET_MAPPING = {
    COL_PCAPS: BUCKET_PCAPS,
    COL_OBJECTS: BUCKET_OBJECTS,
    COL_SAMPLES: BUCKET_SAMPLES
}

# check Log Directory
if not os.path.exists(LOG_DIRECTORY):
    LOG_DIRECTORY = os.path.join(SITE_ROOT, '..', 'logs')

# Custom settings for Django
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

# DATE and DATETIME Formats
DATE_FORMAT = 'Y-m-d'
DATETIME_FORMAT = 'Y-m-d H:i:s.u'
PY_DATE_FORMAT = '%Y-%m-%d'
PY_TIME_FORMAT = '%H:%M:%S.%f'
PY_DATETIME_FORMAT = ' '.join([PY_DATE_FORMAT, PY_TIME_FORMAT])
OLD_PY_DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
PY_FORM_DATETIME_FORMATS = [PY_DATETIME_FORMAT, OLD_PY_DATETIME_FORMAT]

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(SITE_ROOT, '../extras/www')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/'

STATIC_ROOT = os.path.join(SITE_ROOT, '../extras/www/static')
STATIC_URL = '/static/'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    #'django.template.loaders.eggs.load_template_source',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
    'django.core.context_processors.static',
    'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',
    'crits.core.views.base_context',
    'crits.core.views.collections',
    'crits.core.views.user_context',
)

ROOT_URLCONF = 'crits.urls'

TEMPLATE_DIRS = (
    os.path.join(SITE_ROOT, '../documentation'),
    os.path.join(SITE_ROOT, 'core/templates'),
    os.path.join(SITE_ROOT, 'actors/templates'),
    os.path.join(SITE_ROOT, 'core/dashboard/templates'),
    os.path.join(SITE_ROOT, 'campaigns/templates'),
    os.path.join(SITE_ROOT, 'certificates/templates'),
    os.path.join(SITE_ROOT, 'comments/templates'),
    os.path.join(SITE_ROOT, 'config/templates'),
    os.path.join(SITE_ROOT, 'domains/templates'),
    os.path.join(SITE_ROOT, 'emails/templates'),
    os.path.join(SITE_ROOT, 'events/templates'),
    os.path.join(SITE_ROOT, 'indicators/templates'),
    os.path.join(SITE_ROOT, 'ips/templates'),
    os.path.join(SITE_ROOT, 'objects/templates'),
    os.path.join(SITE_ROOT, 'pcaps/templates'),
    os.path.join(SITE_ROOT, 'raw_data/templates'),
    os.path.join(SITE_ROOT, 'relationships/templates'),
    os.path.join(SITE_ROOT, 'samples/templates'),
    os.path.join(SITE_ROOT, 'screenshots/templates'),
    os.path.join(SITE_ROOT, 'services/templates'),
    os.path.join(SITE_ROOT, 'standards/templates'),
    os.path.join(SITE_ROOT, 'stats/templates'),
    os.path.join(SITE_ROOT, 'targets/templates'),
)

STATICFILES_DIRS = (
    os.path.join(SITE_ROOT, 'core/static'),
    os.path.join(SITE_ROOT, 'actors/static'),
    os.path.join(SITE_ROOT, 'dashboards/static'),
    os.path.join(SITE_ROOT, 'campaigns/static'),
    os.path.join(SITE_ROOT, 'certificates/static'),
    os.path.join(SITE_ROOT, 'comments/static'),
    os.path.join(SITE_ROOT, 'domains/static'),
    os.path.join(SITE_ROOT, 'emails/static'),
    os.path.join(SITE_ROOT, 'events/static'),
    os.path.join(SITE_ROOT, 'indicators/static'),
    os.path.join(SITE_ROOT, 'ips/static'),
    os.path.join(SITE_ROOT, 'objects/static'),
    os.path.join(SITE_ROOT, 'pcaps/static'),
    os.path.join(SITE_ROOT, 'raw_data/static'),
    os.path.join(SITE_ROOT, 'relationships/static'),
    os.path.join(SITE_ROOT, 'samples/static'),
    os.path.join(SITE_ROOT, 'screenshots/static'),
    os.path.join(SITE_ROOT, 'services/static'),
    os.path.join(SITE_ROOT, 'config/static'),
    os.path.join(SITE_ROOT, 'targets/static'),
)

INSTALLED_APPS = (
    'crits.core',
    'crits.dashboards',
    'django.contrib.auth',
    'mongoengine.django.mongo_auth',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.staticfiles',
    'crits.actors',
    'crits.campaigns',
    'crits.certificates',
    'crits.domains',
    'crits.emails',
    'crits.events',
    'crits.indicators',
    'crits.ips',
    'crits.objects',
    'crits.pcaps',
    'crits.raw_data',
    'crits.relationships',
    'crits.samples',
    'crits.screenshots',
    'crits.services',
    'crits.stats',
    'crits.targets',
    'tastypie',
    'tastypie_mongoengine',
)

AUTH_USER_MODEL = 'mongo_auth.MongoUser'
MONGOENGINE_USER_DOCUMENT = 'crits.core.user.CRITsUser'

SESSION_ENGINE = 'mongoengine.django.sessions'
AUTHENTICATION_BACKENDS = (
    #'mongoengine.django.auth.MongoEngineBackend',
    'crits.core.user.CRITsAuthBackend',
)
if REMOTE_USER:
    MIDDLEWARE_CLASSES = (
        'django.middleware.common.CommonMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.auth.middleware.RemoteUserMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    )
    AUTHENTICATION_BACKENDS = (
        'crits.core.user.CRITsRemoteUserBackend',
    )

# Handle logging after all custom configuration
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': "%(levelname)s %(asctime)s %(name)s %(message)s"
        },
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'django.utils.log.NullHandler',
        },
        'normal': {
            'level': LOG_LEVEL,
            'class': 'logging.FileHandler',
            'formatter': 'verbose',
            'filename': os.path.join(LOG_DIRECTORY, 'crits.log'),
        },
    },
    'loggers': {
        'django': {
            'handlers': ['null'],
            'propagate': True,
            'level': 'INFO',
        },
        'crits': {
            'handlers': ['normal'],
            'propagate': True,
            'level': 'DEBUG',
        },
    },
}

# Handle creating log directories if they do not exist
for handler in LOGGING['handlers'].values():
    log_file = handler.get('filename')
    if log_file:
        log_dir = os.path.dirname(log_file)
        if not os.path.exists(log_dir):
            try:
                os.makedirs(log_dir)

            except OSError as e:
                # If file exists
                if e.args[0] == errno.EEXIST:
                    pass
                # re-raise on error that is not
                # easy to automatically handle, such
                # as permission errors
                else:
                    raise

# CRITs Types
CRITS_TYPES = {
    'Actor': COL_ACTORS,
    'AnalysisResult': COL_ANALYSIS_RESULTS,
    'Campaign': COL_CAMPAIGNS,
    'Certificate': COL_CERTIFICATES,
    'Comment': COL_COMMENTS,
    'Domain': COL_DOMAINS,
    'Email': COL_EMAIL,
    'Event': COL_EVENTS,
    'Indicator': COL_INDICATORS,
    'IP': COL_IPS,
    'Notification': COL_NOTIFICATIONS,
    'PCAP': COL_PCAPS,
    'RawData': COL_RAW_DATA,
    'Sample': COL_SAMPLES,
    'Screenshot': COL_SCREENSHOTS,
    'Target': COL_TARGETS,
}

# Custom template lists for loading in different places in the UI
SERVICE_NAV_TEMPLATES = ()
SERVICE_CP_TEMPLATES = ()
SERVICE_TAB_TEMPLATES = ()

# discover services
for service_directory in SERVICE_DIRS:
    if os.path.isdir(service_directory):
        sys.path.insert(0, service_directory)
        for d in os.listdir(service_directory):
            abs_path = os.path.join(service_directory, d, 'templates')
            if os.path.isdir(abs_path):
                TEMPLATE_DIRS = TEMPLATE_DIRS + (abs_path,)
                nav_items = os.path.join(abs_path, '%s_nav_items.html' % d)
                cp_items = os.path.join(abs_path, '%s_cp_items.html' % d)
                if os.path.isfile(nav_items):
                    SERVICE_NAV_TEMPLATES = SERVICE_NAV_TEMPLATES + ('%s_nav_items.html' % d,)
                if os.path.isfile(cp_items):
                    SERVICE_CP_TEMPLATES = SERVICE_CP_TEMPLATES + ('%s_cp_items.html' % d,)
                for tab_temp in glob.glob('%s/*_tab.html' % abs_path):
                    head, tail = os.path.split(tab_temp)
                    ctype = tail.split('_')[-2]
                    name = "_".join(tail.split('_')[:-2])
                    SERVICE_TAB_TEMPLATES = SERVICE_TAB_TEMPLATES + ((ctype, name, tail),)

# Allow configuration of the META or HEADER variable is used to find
# remote username when REMOTE_USER is enabled.
REMOTE_USER_META = 'REMOTE_USER'

# The next example could be used for reverse proxy setups
# where your frontend might pass Remote-User: header.
#
# WARNING: If you enable this, be 100% certain your backend is not
# directly accessible and this header could be spoofed by an attacker.
#
# REMOTE_USER_META = 'HTTP_REMOTE_USER'

# Import custom settings if it exists
csfile = os.path.join(SITE_ROOT, 'config/overrides.py')
if os.path.exists(csfile):
    execfile(csfile)


text:
from ..errors import ClientError

class Model(object):
    attr_names = ['id', 'url']

    def __init__(self, attrs={}, url=None, client=None, collection=None):
        self.url = url
        self.client = client
        self.collection = collection
        self.set(attrs)

    def __eq__(self, other):
        return type(self) == type(other) and self.attrs == other.attrs

    def __repr__(self):
        return "<%s: %s>" % (self.__class__.__name__, self.attrs.get("name"))

    def set(self, attrs):
        self.attrs = attrs

        for name in self.attr_names:
            if name in self.attrs:
                setattr(self, name, self.attrs[name])

    def update(self, attrs):
        attrs = self.client.request("PATCH", self.url, data=attrs)
        self.set(attrs)

    def delete(self):
        self.collection.delete(self)

class Collection(object):
    def __init__(self, models=None, client=None, url=None):
        self._models = None
        self.client = client
        self.url = url

        if models:
            self.reset(models)

    @property
    def models(self):
        if self._models is None:
            self.fetch()

        return self._models

    def reset(self, models):
        self._models = map(self.prepare_model, models)

    def fetch(self):
        if self.url:
            self.reset(self.client.request("GET", self.url))
        else:
            raise Exception("fetch() called on %s, but it has no url" % self.__class__.__name__)

    def get(self, key):
        return self.prepare_model(self.client.request("GET", "%s/%s" % (self.url, key)))

    def create(self, attrs=None):
        return self.prepare_model(self.client.request("POST", self.url, data=attrs))

    def delete(self, model):
        self.client.request("DELETE", model.url)

        if self._models:
            self._models.remove(model)

    def prepare_model(self, attrs):
        if isinstance(attrs, Model):
            attrs.client = self.client
            attrs.collection = self
            return attrs
        elif isinstance(attrs, dict):
            return self.model(attrs=attrs, client=self.client, collection=self)
        else:
            raise Exception("Can't create %s from %s" % (self.model.__name__, attrs))

    def __eq__(self, other):
        if isinstance(other, Collection):
            return self.models == other.models
        else:
            return self.models == other

    def __getitem__(self, key):
        if isinstance(key, int):
            return self.models[key]
        else:
            return self.get(key)

    def __repr__(self):
        return str(self.models)

    def __len__(self):
        return len(self.models)


text:
File.open('cohort_as_array.txt', 'w') do |file|

	# Goes through each line of the list of names
	File.foreach('cohort.txt') do |line|
		file.puts "\"#{line.chomp}\","
	end

end


text:
from cloudify import ctx
from cloudify.decorators import operation
import cloudify_nsx.library.nsx_esg_dlr as nsx_esg
import cloudify_nsx.library.nsx_common as common

@operation
def create(**kwargs):
    validation_rules = {
        "esg_id": {
            "required": True
        },
        "network": {
            "required": True
        },
        "next_hop": {
            "required": True
        },
        "vnic": {
            "set_none": True,
            "type": "string"
        },
        "mtu": {
            "set_none": True,
            "type": "string"
        },
        "admin_distance": {
            "set_none": True,
            "type": "string"
        },
        "description": {
            "set_none": True
        }
    }

    use_existing, route = common.get_properties_and_validate(
        'route', kwargs, validation_rules
    )

    resource_id = ctx.instance.runtime_properties.get('resource_id')
    if resource_id:
        ctx.logger.info("Reused %s" % resource_id)
        return

    # credentials
    client_session = common.nsx_login(kwargs)

    resource_id = nsx_esg.esg_route_add(
        client_session,
        route['esg_id'],
        route['network'],
        route['next_hop'],
        route['vnic'],
        route['mtu'],
        route['admin_distance'],
        route['description'])

    ctx.instance.runtime_properties['resource_id'] = resource_id
    ctx.logger.info("created %s" % resource_id)

@operation
def delete(**kwargs):
    use_existing, route = common.get_properties('route', kwargs)

    if use_existing:
        common.remove_properties('route')
        ctx.logger.info("Used existed")
        return

    resource_id = ctx.instance.runtime_properties.get('resource_id')
    if not resource_id:
        common.remove_properties('route')
        ctx.logger.info("Not fully created, skip")
        return

    client_session = common.nsx_login(kwargs)

    common.attempt_with_rerun(
        nsx_esg.esg_route_del,
        client_session=client_session,
        resource_id=resource_id
    )

    ctx.logger.info("delete %s" % resource_id)

    common.remove_properties('route')


text:
import { element } from 'protractor';

/**
 * Note: This Service has a Lot of
 * Corner Cases that are not covered.
 * TODO: Fix This Corrner Cases;
 */
import { Product } from './../models/product';
import { Injectable } from '@angular/core';

@Injectable()
export class VariantRetriverService {
  customSelectedOptions = {};
  currentVariantIds = [];
  variantId = null;
  variant = null;
  currentSelectedOptions: any;
  customOptionTypesHash: any;
  currSelectedOption: any;
  product: Product;
  newCorrespondingOptions: any;

  constructor() {}

  /**
   * Note: Params could have been taken in constructor
   * due to prod-build error for constructor,
   * currently taking params from function;
   * TODO: fix this issue
   * @param:
   * currentSelectedOptions: { tsize: "small", tcolor: "red" }
   * customOptionTypesHash: {tshirt-size: Object, tshirt-color: Object}
   * currSelectedOption: { key: "Small", value: Object } => One that is recently selected;
   * product: Product
   */
  getVariant(
    currentSelectedOptions: any,
    customOptionTypesHash: any,
    currSelectedOption: any,
    product: any
  ) {
    // Set Variables
    this.currentSelectedOptions = currentSelectedOptions;
    this.customOptionTypesHash = customOptionTypesHash;
    this.currSelectedOption = currSelectedOption;
    this.product = product;

    this.setCurrentSelectedOptions();
    this.createCustomSelectedOptions();
    this.setCombinedVariantIds();
    this.getVariantId();
    this.parseVariantId();
    this.getVariantFromProduct();
    this.setCorrespondingOptions();
    return {
      newSelectedoptions: this.currentSelectedOptions,
      variant: this.variant,
      newCorrespondingOptions: this.newCorrespondingOptions
    };
  }

  /**
   * This sets current selected Options by user say (small, red, full-sleves)
   * { tsize: 'small', tcolor: 'red' }
   * if new currSelectedOptionType is tcolor and the value is blue the
   * previous one will get overidden
   * like { tsize: 'small', tcolor: 'red' } => { tsize: 'small', tcolor: 'blue' }
   *
   */
  setCurrentSelectedOptions() {
    const currSelectedOptionType = this.currSelectedOption.value.optionValue
      .option_type.name;
    this.currentSelectedOptions[
      currSelectedOptionType
    ] = this.currSelectedOption.key;
  }

  /**
   * It creates Custom selected Options extracting the options selected by user from
   *  customOptionTypesHash
   * say user selected {tsize: 'small'} this will extract the red option from
   * the global option types hash {'tsize': [small: {etc..}, large: {etc..}, medium: {etc..}]}
   *
   */
  createCustomSelectedOptions() {
    /**
     * currentSelectedOptions: {tsize: 'small', tcolor: 'red'}
     * currentSelectedOptions: {} at first.. keeps
     * filling up on iteration of currentSelectedOptions
     *
     * this.customOptionTypesHash[key][this.currentSelectedOptions[key]] =
     * { optionValue: SomeObject, varaintIds: {etc etc} }
     *
     *
     ** */

    for (const key in this.currentSelectedOptions) {
      if (this.currentSelectedOptions.hasOwnProperty(key)) {
        this.customSelectedOptions[
          this.currentSelectedOptions[key]
        ] = this.customOptionTypesHash[key][this.currentSelectedOptions[key]];
      }
    }
  }
  /**
   * Makes a currentVaraintIds from the set of customSelectedOptions
   * {'small': {OptionValue: Object, variantIds: [etc etc]}, 'red': {...}}
   * @return: array of arrays of varaintIds
   * e.g: [[1,2,3,4], [7,8,9,1]]
   */
  setCombinedVariantIds() {
    let temp = [];
    for (const key in this.customSelectedOptions) {
      // First key may be 'small' so varaiant Ids of small should be.
      // inside temp  = [vIds of small];
      if (this.customSelectedOptions.hasOwnProperty(key)) {
        // Make temp empty for each key;
        temp = [];
        this.customSelectedOptions[key].variantIds.forEach(obj => {
          temp.push(Object.keys(obj)[0]);
        });
        this.currentVariantIds.push(temp);
      }
    }
  }

  /**
   * Gets a Unique variantId from the selectedOptions by user
   * by intersecting the arrays in currentvaraintIds
   * Example: [[1,2,3,4], [1,5,6,7]]
   * returns [1] from which we take first index so it is 1;
   * if the array only contains [[2,3,4]] then it will return
   * the first element i.e 2;
   */
  getVariantId() {
    // As scoped variable is not accessible
    // inside filter function hence the tempArr declaration;
    const tempArr = this.currentVariantIds;
    this.variantId = tempArr.shift().filter(function(v) {
      return tempArr.every(function(a) {
        return a.indexOf(v) !== -1;
      });
    })[0];
  }

  /**
   * Parses Varaint Id if null then sets the first
   * variantId in the array as the varaintId to return;
   */
  parseVariantId() {
    if (this.variantId === null || this.variantId === undefined) {
      this.variantId = this.currSelectedOption.value.variantIds[0];
    }
  }

  /**
   * Gets the Varaint From the Product by using the varaintId;
   * else returns null if not present;
   */
  getVariantFromProduct() {
    const result = this.product.variants.filter(v => {
      return v.id === this.variantId;
    });
    this.variant = result ? result[0] : null;
  }

  /**
   *
   *
   *
   * @memberof VariantRetriverService
   */
  setCorrespondingOptions() {
    const vIds: Array<any> = this.currSelectedOption.value.variantIds;
    const newObj = {};
    vIds.forEach((obj: Object) => {
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          obj[key].forEach((oType: Object) => {
            for (const jkey in oType) {
              if (newObj[jkey] !== undefined) {
                newObj[jkey].push(oType[jkey]);
              } else {
                newObj[jkey] = Array.of(oType[jkey]);
              }
            }
          });
        }
      }
    });
    this.newCorrespondingOptions = newObj;
  }
}


text:
import React from 'react';
import AMUIReact from 'amazeui-react';

import ReactCSSTransitionGroup from 'react-addons-css-transition-group'

export default {
  BaseUrl: 'http://bilibili-service.daoapp.io',
  //分类
  Sorts: {
    1: '动画',
    13: '番剧',
    3: '音乐',
    129: '舞蹈',
    4: '游戏',
    36: '科技',
    5: '娱乐',
    119: '鬼畜'
  },
  //首页排序
  IndexList: ['动画', '音乐', '番剧', '舞蹈', '游戏', '科技', '娱乐', '鬼畜'],
  //读条部件
  LoadingWidght: React.createClass({
    render: function () {
      return

读条中

;
    }
  }),
  //启动界面
  StartWidght: React.createClass({
    render: function () {
      return (

          <ReactCSSTransitionGroup transitionName='index' transitionEnterTimeout={0} transitionLeaveTimeout={0}
                                   transitionAppear={true} transitionAppearTimeout={500}>

          </ReactCSSTransitionGroup>

      );
    }
  }),
  Header: React.createClass({
    render: function () {
      var part = [];
      if (this.props.path != '/') {
        part = {
          link: '#/back',
          icon: 'chevron-left'
        }
      }
      var props = {
        title: 'BiliBili-Html5',
        link: '#/',
        data: {
          left: [part]
        }
      };
      return <AMUIReact.Header {...props} className='am-header-fixed'/>;
    }
  }),
  //错误部件
  ErrorWidght: React.createClass({
    render: function () {
      return

加载失败,刷新下吧~

;
    }
  }),
  BadErrorWidght: React.createClass({
    render: function () {
      return

服务器连接异常,请检查你的网络连接

;
    }
  }),
  NoMoreWidght: React.createClass({
    render: function () {
      return

再怎么找也没有啦~

;
    }
  }),
  LoadingDialog: React.createClass({
    render: function () {
      return <AMUIReact.Modal type="loading" title="正在加载..."/>;
    }
  }),
  //加载按钮
  LoadingButton: React.createClass({
    getInitialState: function () {
      return {
        isLoading: false
      };
    },
    propTypes: {
      loadingText: React.PropTypes.string.isRequired,
      clickHandler: React.PropTypes.func
    },
    getDefaultProps: function () {
      return {
        loadingText: 'Loading',
        clickHandler: function () {
        }
      };
    },
    componentDidUpdate: function (prevProps, prevState) {
      if (this.state.isLoading) {
        this.props.clickHandler.call(this);
        this.setState({isLoading: false});
      }
    },
    handleClick: function () {
      this.setState({isLoading: true});
    },
    render: function () {
      var isLoading = this.state.isLoading;
      return (
        <AMUIReact.Button{...this.props} disabled={isLoading} onClick={!isLoading ? this.handleClick : null}>
          {isLoading ? this.props.loadingText : this.props.children}
        </AMUIReact.Button>
      );
    }
  })
};


text:
/* Contributed by Nicola Pero - Tue Mar  6 23:05:53 CET 2001 */

#include <objc/objc.h>

/* Tests creating a root class and a subclass with a class accessor
   methods and a subclass overriding the superclass' implementation
   but reusing it with super */

@interface RootClass
{
  Class isa;
}
@end

@implementation RootClass
+ initialize { return self; }
@end

static int class_variable = 0;

@interface SubClass : RootClass
+ (void) setState: (int)number;
+ (int) state;
@end

@implementation SubClass
+ (void) setState: (int)number
{
  class_variable = number;
}
+ (int) state
{
  return class_variable;
}
@end

@interface SubSubClass : SubClass
@end

@implementation SubSubClass
+ (int) state
{
  return [super state] + 1;
}
@end

#include "class-tests-1.h"
#define TYPE_OF_OBJECT_WITH_ACCESSOR_METHOD Class
#include "class-tests-2.h"

int main (void)
{
  Class class;
  Class sub_class;

  test_class_with_superclass ("SubClass", "RootClass");
  test_that_class_has_class_method ("SubClass", @selector (setState:));
  test_that_class_has_class_method ("SubClass", @selector (state));

  test_class_with_superclass ("SubSubClass", "SubClass");
  test_that_class_has_class_method ("SubSubClass", @selector (setState:));
  test_that_class_has_class_method ("SubSubClass", @selector (state));

  class = objc_getClass ("SubClass");
  test_accessor_method (class, 0, -1, -1, 1, 1);

  sub_class = objc_getClass ("SubSubClass");
  class_variable = 0;
  test_accessor_method (sub_class, 1, -1, 0, 1, 2);

  return 0;
}


text:
<!DOCTYPE html>

<wicket:panel>

            <form wicket:id="constructionForm" class="row">

                                    <wicket:message key="ConstructionType.kind"/>

                                    <select wicket:id="kind"/>

                                    <wicket:message key="ConstructionType.intent"/>

                                    <select wicket:id="intent"/>

            </form>

</wicket:panel>


text:
#ifndef __vsRulerInterface_h
#define __vsRulerInterface_h

#include <QObject>
#include <QSharedPointer>

#include <qtGlobal.h>

#include <vtkVgVideoFrameMetaData.h>

#include <vsContour.h>
#include <vsDataSource.h>
#include <vsEventInfo.h>

class QAction;

class vsCore;
class vsMainWindow;
class vsScene;
class vsVideoSource;

class vsRulerInterfacePrivate;

class vsRulerInterface : public QObject
{
  Q_OBJECT

public:
  vsRulerInterface(vsMainWindow*, vsScene*, vsCore*);
  virtual ~vsRulerInterface();

signals:
  void statusMessageAvailable(QString message);

protected slots:
  void setVideoSourceStatus(vsDataSource::Status);
  void setGsdFromMetadata(vtkVgVideoFrameMetaData);

  void toggleRuler(bool);
  void hideRuler();

  void rulerLengthChanged();

protected:
  QTE_DECLARE_PRIVATE_SPTR(vsRulerInterface)

private:
  QTE_DECLARE_PRIVATE(vsRulerInterface)
  Q_DISABLE_COPY(vsRulerInterface)
};

#endif


text:
package org.springframework.web.servlet.view.groovy;

import java.io.IOException;
import java.io.Reader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;

import groovy.text.Template;
import groovy.text.TemplateEngine;
import groovy.text.markup.MarkupTemplateEngine;
import groovy.text.markup.TemplateConfiguration;
import org.codehaus.groovy.control.CompilationFailedException;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;

import org.springframework.beans.DirectFieldAccessor;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.WebApplicationContext;

import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
import static org.mockito.Mockito.mock;

/**
 * @author Brian Clozel
 */
public class GroovyMarkupViewTests {

	private static final String RESOURCE_LOADER_PATH = "classpath*:org/springframework/web/servlet/view/groovy/";

	private WebApplicationContext webAppContext;

	private ServletContext servletContext;

	@Before
	public void setup() {
		this.webAppContext = mock(WebApplicationContext.class);
		this.servletContext = new MockServletContext();
		this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.webAppContext);
	}

	@Test
	public void missingGroovyMarkupConfig() throws Exception {
		GroovyMarkupView view = new GroovyMarkupView();
		given(this.webAppContext.getBeansOfType(GroovyMarkupConfig.class, true, false))
				.willReturn(new HashMap<String, GroovyMarkupConfig>());

		view.setUrl("sampleView");
		try {
			view.setApplicationContext(this.webAppContext);
			fail();
		}
		catch (ApplicationContextException ex) {
			assertTrue(ex.getMessage().contains("GroovyMarkupConfig"));
		}
	}

	@Test
	public void customTemplateEngine() throws Exception {

		GroovyMarkupView view = new GroovyMarkupView();
		view.setTemplateEngine(new TestTemplateEngine());
		view.setApplicationContext(this.webAppContext);

		DirectFieldAccessor accessor = new DirectFieldAccessor(view);
		TemplateEngine engine = (TemplateEngine) accessor.getPropertyValue("engine");
		assertNotNull(engine);
		assertEquals(TestTemplateEngine.class, engine.getClass());
	}

	@Test
	public void detectTemplateEngine() throws Exception {

		GroovyMarkupView view = new GroovyMarkupView();

		view.setTemplateEngine(new TestTemplateEngine());
		view.setApplicationContext(this.webAppContext);

		DirectFieldAccessor accessor = new DirectFieldAccessor(view);
		TemplateEngine engine = (TemplateEngine) accessor.getPropertyValue("engine");
		assertNotNull(engine);
		assertEquals(TestTemplateEngine.class, engine.getClass());
	}

	@Test
	public void checkResource() throws Exception {

		GroovyMarkupView view = createViewWithUrl("test.tpl");
		assertTrue(view.checkResource(Locale.US));
	}

	@Test
	public void checkMissingResource() throws Exception {

		GroovyMarkupView view = createViewWithUrl("missing.tpl");
		assertFalse(view.checkResource(Locale.US));
	}

	@Test
	public void checkI18nResource() throws Exception {

		GroovyMarkupView view = createViewWithUrl("i18n.tpl");
		assertTrue(view.checkResource(Locale.FRENCH));
	}

	@Test
	public void checkI18nResourceMissingLocale() throws Exception {

		GroovyMarkupView view = createViewWithUrl("i18n.tpl");
		assertTrue(view.checkResource(Locale.CHINESE));
	}

	@Test
	public void renderMarkupTemplate() throws Exception {

		Map<String, Object> model = new HashMap<>();
		model.put("name", "Spring");
		MockHttpServletResponse response = renderViewWithModel("test.tpl", model, Locale.US);
		assertThat(response.getContentAsString(), Matchers.containsString("
Hello Spring
"));
	}

	@Test
	public void renderI18nTemplate() throws Exception {
		Map<String, Object> model = new HashMap<>();
		model.put("name", "Spring");
		MockHttpServletResponse response = renderViewWithModel("i18n.tpl", model, Locale.FRANCE);
		assertEquals("
Bonjour Spring
", response.getContentAsString());

		response = renderViewWithModel("i18n.tpl", model, Locale.GERMANY);
		assertEquals("
Include German

Hallo Spring
", response.getContentAsString());

		response = renderViewWithModel("i18n.tpl", model, new Locale("es"));
		assertEquals("
Include Default

¡hola Spring
", response.getContentAsString());
	}

	@Test
	public void renderLayoutTemplate() throws Exception {
		Map<String, Object> model = new HashMap<>();
		MockHttpServletResponse response = renderViewWithModel("content.tpl", model, Locale.US);
		assertEquals("<title>Layout example</title>
This is the body
",
				response.getContentAsString());
	}

	private MockHttpServletResponse renderViewWithModel(String viewUrl, Map<String, Object> model, Locale locale) throws Exception {

		GroovyMarkupView view = createViewWithUrl(viewUrl);
		MockHttpServletResponse response = new MockHttpServletResponse();
		MockHttpServletRequest request = new MockHttpServletRequest();
		request.setPreferredLocales(Arrays.asList(locale));
		LocaleContextHolder.setLocale(locale);
		view.renderMergedTemplateModel(model, request, response);
		return response;
	}

	private GroovyMarkupView createViewWithUrl(String viewUrl) throws Exception {

		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(GroovyMarkupConfiguration.class);
		ctx.refresh();

		GroovyMarkupView view = new GroovyMarkupView();
		view.setApplicationContext(ctx);
		view.setUrl(viewUrl);
		view.afterPropertiesSet();
		return view;
	}

	public class TestTemplateEngine extends MarkupTemplateEngine {

		public TestTemplateEngine() {
			super(new TemplateConfiguration());
		}

		@Override
		public Template createTemplate(Reader reader) throws CompilationFailedException, ClassNotFoundException, IOException {
			return null;
		}
	}

	@Configuration
	static class GroovyMarkupConfiguration {

		@Bean
		public GroovyMarkupConfig groovyMarkupConfigurer() {
			GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer();
			configurer.setResourceLoaderPath(RESOURCE_LOADER_PATH);
			return configurer;
		}
	}
}


text:
@import Foundation;

#import "BTAppSwitching.h"
#import "BTAppSwitchErrors.h"

/// Manages the communication with the Coinbase app or browser for authorization
///
/// This is a beta integration option. For details, see https://www.braintreepayments.com/features/coinbase
///
/// @see BTAppSwitching
@interface BTCoinbase : NSObject <BTAppSwitching>

@property (nonatomic, assign) BOOL storeInVault;

/// Dynamically disable Coinbase support on the client-side,
/// e.g. for certain customers, geographies, devices, etc.
///
/// Example:
/// `[BTCoinbase sharedCoinbase].disabled = [CoinbaseOAuth isAppOAuthAuthenticationAvailable] ? NO : YES;`
@property (nonatomic, assign) BOOL disabled;

+ (instancetype)sharedCoinbase;

/// Checks whether the Coinbase app is installed (and accepting app switch authorization)
/// and Braintree is configured for Coinbase app switch. This requires a returnURLScheme
/// to be set and for Coinbase to be enabled in your Braintree Control Panel.
///
/// @param client A BTClient
///
/// @return YES if the Coinbase native app is available for app switch.
///
/// @see `+[Braintree setReturnURLScheme:]`
- (BOOL)providerAppSwitchAvailableForClient:(BTClient *)client;

@end


text:
import pytest
import threading
import requests

from tests.testserver.server import Server, consume_socket_content

from .utils import override_environ

def echo_response_handler(sock):
    """Simple handler that will take request and echo it back to requester."""
    request_content = consume_socket_content(sock, timeout=0.5)

    text_200 = (
        b'HTTP/1.1 200 OK\r\n'
        b'Content-Length: %d\r\n\r\n'
        b'%s'
    ) % (len(request_content), request_content)
    sock.send(text_200)

def test_chunked_upload():
    """can safely send generators"""
    close_server = threading.Event()
    server = Server.basic_response_server(wait_to_close_event=close_server)
    data = iter([b'a', b'b', b'c'])

    with server as (host, port):
        url = 'http://{}:{}/'.format(host, port)
        r = requests.post(url, data=data, stream=True)
        close_server.set()  # release server block

    assert r.status_code == 200
    assert r.request.headers['Transfer-Encoding'] == 'chunked'

def test_chunked_encoding_error():
    """get a ChunkedEncodingError if the server returns a bad response"""

    def incomplete_chunked_response_handler(sock):
        request_content = consume_socket_content(sock, timeout=0.5)

        # The server never ends the request and doesn't provide any valid chunks
        sock.send(b"HTTP/1.1 200 OK\r\n" +
                  b"Transfer-Encoding: chunked\r\n")

        return request_content

    close_server = threading.Event()
    server = Server(incomplete_chunked_response_handler)

    with server as (host, port):
        url = 'http://{}:{}/'.format(host, port)
        with pytest.raises(requests.exceptions.ChunkedEncodingError):
            r = requests.get(url)
        close_server.set()  # release server block

def test_chunked_upload_uses_only_specified_host_header():
    """Ensure we use only the specified Host header for chunked requests."""
    close_server = threading.Event()
    server = Server(echo_response_handler, wait_to_close_event=close_server)

    data = iter([b'a', b'b', b'c'])
    custom_host = 'sample-host'

    with server as (host, port):
        url = 'http://{}:{}/'.format(host, port)
        r = requests.post(url, data=data, headers={'Host': custom_host}, stream=True)
        close_server.set()  # release server block

    expected_header = b'Host: %s\r\n' % custom_host.encode('utf-8')
    assert expected_header in r.content
    assert r.content.count(b'Host: ') == 1

def test_chunked_upload_doesnt_skip_host_header():
    """Ensure we don't omit all Host headers with chunked requests."""
    close_server = threading.Event()
    server = Server(echo_response_handler, wait_to_close_event=close_server)

    data = iter([b'a', b'b', b'c'])

    with server as (host, port):
        expected_host = '{}:{}'.format(host, port)
        url = 'http://{}:{}/'.format(host, port)
        r = requests.post(url, data=data, stream=True)
        close_server.set()  # release server block

    expected_header = b'Host: %s\r\n' % expected_host.encode('utf-8')
    assert expected_header in r.content
    assert r.content.count(b'Host: ') == 1

def test_conflicting_content_lengths():
    """Ensure we correctly throw an InvalidHeader error if multiple
    conflicting Content-Length headers are returned.
    """

    def multiple_content_length_response_handler(sock):
        request_content = consume_socket_content(sock, timeout=0.5)

        sock.send(b"HTTP/1.1 200 OK\r\n" +
                  b"Content-Type: text/plain\r\n" +
                  b"Content-Length: 16\r\n" +
                  b"Content-Length: 32\r\n\r\n" +
                  b"-- Bad Actor -- Original Content\r\n")

        return request_content

    close_server = threading.Event()
    server = Server(multiple_content_length_response_handler)

    with server as (host, port):
        url = 'http://{}:{}/'.format(host, port)
        with pytest.raises(requests.exceptions.InvalidHeader):
            r = requests.get(url)
        close_server.set()

def test_digestauth_401_count_reset_on_redirect():
    """Ensure we correctly reset num_401_calls after a successful digest auth,
    followed by a 302 redirect to another digest auth prompt.

    See https://github.com/psf/requests/issues/1979.
    """
    text_401 = (b'HTTP/1.1 401 UNAUTHORIZED\r\n'
                b'Content-Length: 0\r\n'
                b'WWW-Authenticate: Digest nonce="6bf5d6e4da1ce66918800195d6b9130d"'
                b', opaque="372825293d1c26955496c80ed6426e9e", '
                b'realm="me@kennethreitz.com", qop=auth\r\n\r\n')

    text_302 = (b'HTTP/1.1 302 FOUND\r\n'
                b'Content-Length: 0\r\n'
                b'Location: /\r\n\r\n')

    text_200 = (b'HTTP/1.1 200 OK\r\n'
                b'Content-Length: 0\r\n\r\n')

    expected_digest = (b'Authorization: Digest username="user", '
                       b'realm="me@kennethreitz.com", '
                       b'nonce="6bf5d6e4da1ce66918800195d6b9130d", uri="/"')

    auth = requests.auth.HTTPDigestAuth('user', 'pass')

    def digest_response_handler(sock):
        # Respond to initial GET with a challenge.
        request_content = consume_socket_content(sock, timeout=0.5)
        assert request_content.startswith(b"GET / HTTP/1.1")
        sock.send(text_401)

        # Verify we receive an Authorization header in response, then redirect.
        request_content = consume_socket_content(sock, timeout=0.5)
        assert expected_digest in request_content
        sock.send(text_302)

        # Verify Authorization isn't sent to the redirected host,
        # then send another challenge.
        request_content = consume_socket_content(sock, timeout=0.5)
        assert b'Authorization:' not in request_content
        sock.send(text_401)

        # Verify Authorization is sent correctly again, and return 200 OK.
        request_content = consume_socket_content(sock, timeout=0.5)
        assert expected_digest in request_content
        sock.send(text_200)

        return request_content

    close_server = threading.Event()
    server = Server(digest_response_handler, wait_to_close_event=close_server)

    with server as (host, port):
        url = 'http://{}:{}/'.format(host, port)
        r = requests.get(url, auth=auth)
        # Verify server succeeded in authenticating.
        assert r.status_code == 200
        # Verify Authorization was sent in final request.
        assert 'Authorization' in r.request.headers
        assert r.request.headers['Authorization'].startswith('Digest ')
        # Verify redirect happened as we expected.
        assert r.history[0].status_code == 302
        close_server.set()

def test_digestauth_401_only_sent_once():
    """Ensure we correctly respond to a 401 challenge once, and then
    stop responding if challenged again.
    """
    text_401 = (b'HTTP/1.1 401 UNAUTHORIZED\r\n'
                b'Content-Length: 0\r\n'
                b'WWW-Authenticate: Digest nonce="6bf5d6e4da1ce66918800195d6b9130d"'
                b', opaque="372825293d1c26955496c80ed6426e9e", '
                b'realm="me@kennethreitz.com", qop=auth\r\n\r\n')

    expected_digest = (b'Authorization: Digest username="user", '
                       b'realm="me@kennethreitz.com", '
                       b'nonce="6bf5d6e4da1ce66918800195d6b9130d", uri="/"')

    auth = requests.auth.HTTPDigestAuth('user', 'pass')

    def digest_failed_response_handler(sock):
        # Respond to initial GET with a challenge.
        request_content = consume_socket_content(sock, timeout=0.5)
        assert request_content.startswith(b"GET / HTTP/1.1")
        sock.send(text_401)

        # Verify we receive an Authorization header in response, then
        # challenge again.
        request_content = consume_socket_content(sock, timeout=0.5)
        assert expected_digest in request_content
        sock.send(text_401)

        # Verify the client didn't respond to second challenge.
        request_content = consume_socket_content(sock, timeout=0.5)
        assert request_content == b''

        return request_content

    close_server = threading.Event()
    server = Server(digest_failed_response_handler, wait_to_close_event=close_server)

    with server as (host, port):
        url = 'http://{}:{}/'.format(host, port)
        r = requests.get(url, auth=auth)
        # Verify server didn't authenticate us.
        assert r.status_code == 401
        assert r.history[0].status_code == 401
        close_server.set()

def test_digestauth_only_on_4xx():
    """Ensure we only send digestauth on 4xx challenges.

    See https://github.com/psf/requests/issues/3772.
    """
    text_200_chal = (b'HTTP/1.1 200 OK\r\n'
                     b'Content-Length: 0\r\n'
                     b'WWW-Authenticate: Digest nonce="6bf5d6e4da1ce66918800195d6b9130d"'
                     b', opaque="372825293d1c26955496c80ed6426e9e", '
                     b'realm="me@kennethreitz.com", qop=auth\r\n\r\n')

    auth = requests.auth.HTTPDigestAuth('user', 'pass')

    def digest_response_handler(sock):
        # Respond to GET with a 200 containing www-authenticate header.
        request_content = consume_socket_content(sock, timeout=0.5)
        assert request_content.startswith(b"GET / HTTP/1.1")
        sock.send(text_200_chal)

        # Verify the client didn't respond with auth.
        request_content = consume_socket_content(sock, timeout=0.5)
        assert request_content == b''

        return request_content

    close_server = threading.Event()
    server = Server(digest_response_handler, wait_to_close_event=close_server)

    with server as (host, port):
        url = 'http://{}:{}/'.format(host, port)
        r = requests.get(url, auth=auth)
        # Verify server didn't receive auth from us.
        assert r.status_code == 200
        assert len(r.history) == 0
        close_server.set()

_schemes_by_var_prefix = [
    ('http', ['http']),
    ('https', ['https']),
    ('all', ['http', 'https']),
]

_proxy_combos = []
for prefix, schemes in _schemes_by_var_prefix:
    for scheme in schemes:
        _proxy_combos.append(("{}_proxy".format(prefix), scheme))

_proxy_combos += [(var.upper(), scheme) for var, scheme in _proxy_combos]

@pytest.mark.parametrize("var,scheme", _proxy_combos)
def test_use_proxy_from_environment(httpbin, var, scheme):
    url = "{}://httpbin.org".format(scheme)
    fake_proxy = Server()  # do nothing with the requests; just close the socket
    with fake_proxy as (host, port):
        proxy_url = "socks5://{}:{}".format(host, port)
        kwargs = {var: proxy_url}
        with override_environ(**kwargs):
            # fake proxy's lack of response will cause a ConnectionError
            with pytest.raises(requests.exceptions.ConnectionError):
                requests.get(url)

        # the fake proxy received a request
        assert len(fake_proxy.handler_results) == 1

        # it had actual content (not checking for SOCKS protocol for now)
        assert len(fake_proxy.handler_results[0]) > 0

def test_redirect_rfc1808_to_non_ascii_location():
    path = u'š'
    expected_path = b'%C5%A1'
    redirect_request = []  # stores the second request to the server

    def redirect_resp_handler(sock):
        consume_socket_content(sock, timeout=0.5)
        location = u'//{}:{}/{}'.format(host, port, path)
        sock.send(
            b'HTTP/1.1 301 Moved Permanently\r\n'
            b'Content-Length: 0\r\n'
            b'Location: ' + location.encode('utf8') + b'\r\n'
            b'\r\n'
        )
        redirect_request.append(consume_socket_content(sock, timeout=0.5))
        sock.send(b'HTTP/1.1 200 OK\r\n\r\n')

    close_server = threading.Event()
    server = Server(redirect_resp_handler, wait_to_close_event=close_server)

    with server as (host, port):
        url = u'http://{}:{}'.format(host, port)
        r = requests.get(url=url, allow_redirects=True)
        assert r.status_code == 200
        assert len(r.history) == 1
        assert r.history[0].status_code == 301
        assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')
        assert r.url == u'{}/{}'.format(url, expected_path.decode('ascii'))

        close_server.set()

def test_fragment_not_sent_with_request():
    """Verify that the fragment portion of a URI isn't sent to the server."""
    def response_handler(sock):
        req = consume_socket_content(sock, timeout=0.5)
        sock.send(
            b'HTTP/1.1 200 OK\r\n'
            b'Content-Length: '+bytes(len(req))+b'\r\n'
            b'\r\n'+req
        )

    close_server = threading.Event()
    server = Server(response_handler, wait_to_close_event=close_server)

    with server as (host, port):
        url = 'http://{}:{}/path/to/thing/#view=edit&token=hunter2'.format(host, port)
        r = requests.get(url)
        raw_request = r.content

        assert r.status_code == 200
        headers, body = raw_request.split(b'\r\n\r\n', 1)
        status_line, headers = headers.split(b'\r\n', 1)

        assert status_line == b'GET /path/to/thing/ HTTP/1.1'
        for frag in (b'view', b'edit', b'token', b'hunter2'):
            assert frag not in headers
            assert frag not in body

        close_server.set()

def test_fragment_update_on_redirect():
    """Verify we only append previous fragment if one doesn't exist on new
    location. If a new fragment is encountered in a Location header, it should
    be added to all subsequent requests.
    """

    def response_handler(sock):
        consume_socket_content(sock, timeout=0.5)
        sock.send(
            b'HTTP/1.1 302 FOUND\r\n'
            b'Content-Length: 0\r\n'
            b'Location: /get#relevant-section\r\n\r\n'
        )
        consume_socket_content(sock, timeout=0.5)
        sock.send(
            b'HTTP/1.1 302 FOUND\r\n'
            b'Content-Length: 0\r\n'
            b'Location: /final-url/\r\n\r\n'
        )
        consume_socket_content(sock, timeout=0.5)
        sock.send(
            b'HTTP/1.1 200 OK\r\n\r\n'
        )

    close_server = threading.Event()
    server = Server(response_handler, wait_to_close_event=close_server)

    with server as (host, port):
        url = 'http://{}:{}/path/to/thing/#view=edit&token=hunter2'.format(host, port)
        r = requests.get(url)
        raw_request = r.content

        assert r.status_code == 200
        assert len(r.history) == 2
        assert r.history[0].request.url == url

        # Verify we haven't overwritten the location with our previous fragment.
        assert r.history[1].request.url == 'http://{}:{}/get#relevant-section'.format(host, port)
        # Verify previous fragment is used and not the original.
        assert r.url == 'http://{}:{}/final-url/#relevant-section'.format(host, port)

        close_server.set()


text:
package org.ardulink.connection.proxy;

/**
 * [ardulinktitle] [ardulinkversion]
 *
 * project Ardulink http://www.ardulink.org/
 *
 * [adsense]
 *
 */
public final class NetworkProxyMessages {

	public static final String NUMBER_OF_PORTS = "NUMBER_OF_PORTS=";
	public static final String OK = "OK";
	public static final String KO = "KO";

	private static final String PREFIX = "ardulink:networkproxyserver:";
	public static final String STOP_SERVER_CMD = PREFIX + "stop_server";
	public static final String GET_PORT_LIST_CMD = PREFIX + "get_port_list";
	public static final String CONNECT_CMD = PREFIX + "connect";

}


text:
import networkx as nx
import copy

from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER, DEAD_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.ofproto.ofproto_v1_3 import  OFP_DEFAULT_PRIORITY
from ryu.topology.api import get_all_switch, get_all_link, get_all_host
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet, arp, icmp
from ryu.lib.packet import ether_types
from ryu.lib import hub

'''
###For 2 chapter###
fig 2-6
not install flow entries when packet-in arrival
----test----
Linear topology
ICMP
'''

class ProactiveApp(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]

    def __init__(self, *args, **kwargs):
        super(ProactiveApp, self).__init__(*args, **kwargs)
        self.mac_to_port = {}
        self.discover_thread = hub.spawn(self.pre_install)

        # {dpid:{port:mac,port:mac,...},dpid:{port:mac,port:mac,...},...} only switches'mac
        self.dpids_port_to_mac = dict()
        # [dpid,dpid,...]
        self.dpids = list()

        # {(dpid,port):host_mac,(dpid,port):host_mac,...} only hosts'mac
        self.dpids_port_to_host = dict()
        #[host_mac,host_mac,host_mac,...]
        self.hosts = list()

        #{(src_dpid,dst_dpid):(src_port,dst_port),():(),...}
        self.links_dpid_to_port = dict()
        # [(src_dpid,dst_dpid),(src_dpid,dst_dpid),...]
        self.links = list()

        self.adjacency_matrix = dict()
        self.pre_adjacency_matrix = dict()

        # {
        # (dpid,dpid):{xxx:[dpid,dpid,dpid],xxx:[dpid,dpid,dpid,dpid],...},
        # (dpid,dpid):{xxx:[dpid,dpid,dpid],xxx:[dpid,dpid,dpid,dpid],...},
        # ...}
        self.path_table = dict()

        self.dpid_to_dp = dict()

        self.SLEEP_PERIOD = 2 #seconds

    @set_ev_cls(ofp_event.EventOFPStateChange,[MAIN_DISPATCHER, DEAD_DISPATCHER])
    def state_change_handler(self, ev):
        datapath = ev.datapath
        if ev.state == MAIN_DISPATCHER:
            if not datapath.id in self.dpid_to_dp:
                self.logger.info('register datapath: %04x', datapath.id)
                self.dpid_to_dp[datapath.id] = datapath
        elif ev.state == DEAD_DISPATCHER:
            if datapath.id in self.dpid_to_dp:
                self.logger.info('un register datapath: %04x', datapath.id)
                del self.dpid_to_dp[datapath.id]

    @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
    def switch_features_handler(self, ev):
        datapath = ev.msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        # install table-miss flow entry
        match = parser.OFPMatch()
        actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
                                          ofproto.OFPCML_NO_BUFFER)]
        self.add_flow(datapath, 0, match, actions)

    def add_flow(self, datapath, priority, match, actions, buffer_id=None, idle_timeout=0):
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
                                             actions)]
        if buffer_id:
            mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
                                    priority=priority, match=match,
                                    instructions=inst,idle_timeout=idle_timeout)
        else:
            mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
                                    match=match, instructions=inst,idle_timeout=idle_timeout)
        datapath.send_msg(mod)

    def pre_install(self):
        while True:
            hub.sleep(self.SLEEP_PERIOD)
            self.pre_adjacency_matrix = copy.deepcopy(self.adjacency_matrix)
            self._update_topology()
            self._update_hosts()
            if self.pre_adjacency_matrix != self.adjacency_matrix:
                self.logger.info('***********discover_topology thread: TOPO  UPDATE***********')
                self.path_table = self._get_path_table(self.adjacency_matrix)
                # self.pre_install_flow()

    def _update_topology(self):
        switch_list = get_all_switch(self)
        if len(switch_list) != 0:
            self.dpids_port_to_mac = self._get_dpids_port_to_mac(switch_list)
            self.dpids = self._get_dpids(switch_list) #[dpid,dpid,dpid,...]
        link_dict = get_all_link(self)
        if len(link_dict) != 0:
            self.links_dpid_to_port = self._get_links_dpid_to_port(link_dict)
            self.links = self._get_links(self.links_dpid_to_port) #[(src.dpid,dst.dpid),(src.dpid,dst.dpid),...]
        if self.dpids and self.links:
            self.adjacency_matrix = self._get_adjacency_matrix(self.dpids, self.links)

    def _get_dpids_port_to_mac(self,switch_list):
        table = dict()
        for switch in switch_list:
            dpid = switch.dp.id
            table.setdefault(dpid,{})
            ports = switch.ports
            for port in ports:
                table[dpid][port.port_no] =  port.hw_addr
        return table

    def _get_dpids(self,switch_list):
        dpid_list = list()
        for switch in switch_list:
            dpid_list.append(switch.dp.id)
        return dpid_list

    def _get_links(self,link_ports_table):
        return link_ports_table.keys()

    def _get_links_dpid_to_port(self,link_dict):
        table = dict()
        for link in link_dict.keys():
            src = link.src #ryu.topology.switches.Port
            dst = link.dst
            table[(src.dpid,dst.dpid)] = (src.port_no, dst.port_no)
        return table

    def _get_adjacency_matrix(self,dpids,links):
        graph = dict()
        for src in dpids:
            graph[src] = dict()
            for dst in dpids:
                graph[src][dst] = float('inf')
                if src == dst:
                    graph[src][dst] = 0
                elif (src, dst) in links:
                    graph[src][dst] = 1
        return graph

    def _get_path_table(self, matrix):
        if matrix:
            dpids = matrix.keys()
            g = nx.Graph()
            g.add_nodes_from(dpids)
            for i in dpids:
                for j in dpids:
                    if matrix[i][j] == 1:
                        g.add_edge(i,j,weight=1)
            return self.__graph_to_path(g)

    def __graph_to_path(self,g): # {(i,j):[[],[],...],(i,j):[[],[],[],..],...}
        all_shortest_paths = dict()
        for i in g.nodes():
            for j in g.nodes():
                if i == j:
                    continue
                all_shortest_paths[(i,j)] = list()
                try:
                    nx.shortest_path(g,i,j)
                except nx.exception.NetworkXNoPath:
                    continue
                for each in nx.all_shortest_paths(g,i,j):
                    all_shortest_paths[(i,j)].append(each)
        return all_shortest_paths

    def _update_hosts(self):
        host_list = get_all_host(self)
        if host_list:
            self.dpids_port_to_host = self._get_dpids_port_to_host(host_list)
            self.hosts = self._get_hosts(host_list)

    def _get_dpids_port_to_host(self,host_list):
        table = dict()
        for host in host_list:
            host_mac = host.mac
            host_port = host.port # Port
            dpid = host_port.dpid
            table[(dpid,host_port.port_no)] = host_mac
        return table

    def _get_hosts(self,host_list):
        hosts = list()
        for host in host_list:
            hosts.append(host.mac)
        return hosts

    def pre_install_flow(self):
        print("execute pre-install flow")
        if len(self.hosts) == 2:
            print("host num:",2)
            host1 = self.hosts[0]
            host2 = self.hosts[1]
            self._pre_install_flow(host1,host2)
            self._pre_install_flow(host2,host1)

    def _pre_install_flow(self,host1,host2):
        host1_dpid = None
        host2_dpid = None
        host1_port = None
        host2_port = None
        for dpid_port in self.dpids_port_to_host.keys():
                if self.dpids_port_to_host[dpid_port] == host1:
                    host1_dpid = dpid_port[0]
                    host1_port = dpid_port[1]
                elif self.dpids_port_to_host[dpid_port] == host2:
                    host2_dpid = dpid_port[0]
                    host2_port = dpid_port[1]
        if host1_dpid == host2_dpid:
            datapath = self.dpid_to_dp[host1_dpid]
            parser =  datapath.ofproto_parser
            priority = OFP_DEFAULT_PRIORITY
            match = parser.OFPMatch(in_port=host1_port,eth_dst=host2) # , eth_dst=host2
            actions = [parser.OFPActionOutput(host2_port)]
            self.add_flow(datapath, priority, match, actions,idle_timeout=5)
        else:
            traffic = self.path_table[(host1_dpid,host2_dpid)][0]
            length = len(traffic)
            for i in range(length):
                datapath = self.dpid_to_dp[traffic[i]]
                parser = datapath.ofproto_parser
                priority = OFP_DEFAULT_PRIORITY
                if i == 0:
                    match = parser.OFPMatch(in_port=host1_port,eth_dst=host2) # , eth_dst=host2
                    out_port = self.links_dpid_to_port[(traffic[i],traffic[i+1])][0]
                    actions = [parser.OFPActionOutput(out_port)]
                    self.add_flow(datapath, priority, match, actions, idle_timeout=5)
                elif i == length -1:
                    in_port = self.links_dpid_to_port[(traffic[i-1],traffic[i])][1]
                    match = parser.OFPMatch(in_port=in_port,eth_dst=host2) # , eth_dst=host2
                    actions = [parser.OFPActionOutput(host2_port)]
                    self.add_flow(datapath, priority, match, actions, idle_timeout=5)
                else:
                    in_port = self.links_dpid_to_port[(traffic[i-1],traffic[i])][1]
                    out_port = self.links_dpid_to_port[(traffic[i],traffic[i+1])][0]
                    match = parser.OFPMatch(in_port=in_port,eth_dst=host2) # , eth_dst=host2
                    actions = [parser.OFPActionOutput(out_port)]
                    self.add_flow(datapath, priority, match, actions, idle_timeout=5)

    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def _packet_in_handler(self, ev):
        # If you hit this you might want to increase
        # the "miss_send_length" of your switch
        if ev.msg.msg_len < ev.msg.total_len:
            self.logger.debug("packet truncated: only %s of %s bytes",
                              ev.msg.msg_len, ev.msg.total_len)
        msg = ev.msg
        datapath = msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        in_port = msg.match['in_port']

        pkt = packet.Packet(msg.data)
        eth = pkt.get_protocols(ethernet.ethernet)[0]

        ar = pkt.get_protocol(arp.arp)
        ic = pkt.get_protocol(icmp.icmp)

        if isinstance(ar, arp.arp):
            print("-----arp packet------")
            print("dpid:",datapath.id)
            # print(pkt)
            # for each in self.mac_to_port:
            #     print "dpid:",each
            #     for a in self.mac_to_port[each]:
            #         print "mac:",a,"->","port:",self.mac_to_port[each][a]
        if isinstance(ic, icmp.icmp):
            print("-----icmp packet------")
            print("dpid:",datapath.id)
            # print(pkt)
            # for each in self.mac_to_port:
            #     print "dpid:",each
            #     for a in self.mac_to_port[each]:
            #         print "mac:",a,"->","port:",self.mac_to_port[each][a]

        if eth.ethertype == ether_types.ETH_TYPE_LLDP:
            # ignore lldp packet
            return
        dst = eth.dst
        src = eth.src
        mac_list = ['00:00:00:00:00:01','00:00:00:00:00:02']
        if dst in mac_list and src in mac_list:
            pass
            # self._pre_install_flow(src,dst)

        dpid = datapath.id
        self.mac_to_port.setdefault(dpid, {})

        # self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port)

        # learn a mac address to avoid FLOOD next time.
        self.mac_to_port[dpid][src] = in_port

        if dst in self.mac_to_port[dpid]:
            out_port = self.mac_to_port[dpid][dst]
        else:
            out_port = ofproto.OFPP_FLOOD

        actions = [parser.OFPActionOutput(out_port)]
        data = None
        if msg.buffer_id == ofproto.OFP_NO_BUFFER:
            data = msg.data

        out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,
                                  in_port=in_port, actions=actions, data=data)
        datapath.send_msg(out)


text:
default[:timezone][:zone] = "Europe/London"
default[:timezone][:tz_file] = "/etc/timezone"