text:
package test

import org.scalaquery.session.Database
import org.scalaquery.session.Database.threadLocalSession
import org.scalaquery.ql.basic.BasicDriver.Implicit._
import scala.collection.mutable.Set
import scala.io.Source
import class_instance_extractor.ClassInstanceList

object CICounter {
  def main(args: Array[String]) {
    println(new java.io.File("").getAbsolutePath())
    val roleClassSet = Set[String]()
    var source = Source.fromFile("refined_class_list_from_role.txt", "utf-8")
    for (cls <- source.getLines()) {
      roleClassSet.add(cls)
    }
    println(roleClassSet.size)
    val typeClassSet = Set[String]()
    source = Source.fromFile("refined_class_list_from_type.txt", "utf-8")
    for (cls <- source.getLines()) {
      typeClassSet.add(cls)
    }
    println(typeClassSet.size)

    var roleCICnt = 0
    var typeCICnt = 0
    val refinedDB = Database.forURL(url = "jdbc:sqlite:refined_class_instance_list2.db", driver = "org.sqlite.JDBC")
    refinedDB withSession {

      val q = for { result <- ClassInstanceList }
        yield result.jwoClass ~ result.jwoInstance
      for ((jwoClass, jwoInstance) <- q.list) {
        if (roleClassSet.contains(jwoClass)) {
          roleCICnt += 1
        }
        if (typeClassSet.contains(jwoClass)) {
          typeCICnt += 1
        }
      }
    }
    println(roleCICnt)
    println(typeCICnt)
  }
}


text:
class DownloadStartedAnimationTest : public InProcessBrowserTest {
 public:
  DownloadStartedAnimationTest() {
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(DownloadStartedAnimationTest);
};

IN_PROC_BROWSER_TEST_F(DownloadStartedAnimationTest,
                       InstantiateAndImmediatelyClose) {
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  DownloadStartedAnimation::Show(web_contents);
  chrome::CloseWindow(browser());
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

import Dispatcher     from "../dispatcher";
import Constants      from "../constants";
import StoreCommon    from "./store_common";
import assign         from "object-assign";
import Api            from "../actions/api";

var _statements = [];
var _lastFlushTime = 0;
// Time to wait between queue flushes, in ms
var _waitTime = 4000;

// Send all statements in the queue
function flushQueue(forcibly){
	// Have a buffer window before flushing queue again, unless forcibly == true (used when submitting assessment and we want all statements absolutely sent)
	if (Date.now() - _lastFlushTime > _waitTime || forcibly == true) {
		//console.log("stores/xapi:14 flushing queue, forcibly: "+forcibly,_statements);
		// Put the current time in the url so that if this request hasn't finished before the queue is flushed again, it won't get cancelled (since this Api.request code cancels pending requests with the same url).
		Api.post(Constants.FLUSH_STATEMENT_QUEUE, "api/xapi?"+Date.now(), {"statements":_statements});
		_lastFlushTime = Date.now();
		_statements = [];
		return true;
	}
	//console.log("stores/xapi:25 queue not flushed.");
	return false;
}

// Add a statement to the queue
function enqueueStatement(statement){
	_statements.push(statement);
	//console.log("stores/xapi:25 current queue",_statements);
}

// Extend Xapi Store with EventEmitter to add eventing capabilities
var XapiStore = assign({}, StoreCommon, {

  // Return current statement queue
  currentStatementQueue(){
    return _statements;
  }

});

// Register callback with Dispatcher
Dispatcher.register(function(payload) {
  var action = payload.action;

  //console.log("stores/xapi:43",payload);

  switch(action){
    case Constants.FLUSH_STATEMENT_QUEUE:
    	flushQueue(payload.forcibly);
	break;

    case Constants.ENQUEUE_STATEMENT:
	enqueueStatement(payload.statement);
	break;

    default:
      return true;
  }

  // If action was responded to, emit change event
  XapiStore.emitChange();

  return true;

});

export default XapiStore;


text:
<?php
declare(strict_types=1);

namespace stubbles\log\ioc;
use bovigo\callmap\NewInstance;
use stubbles\log\LogEntry;
use stubbles\log\entryfactory\LogEntryFactory;

use function bovigo\assert\assert;
use function bovigo\assert\predicate\isNotSameAs;
use function bovigo\assert\predicate\isSameAs;
/**
 * Test for stubbles\log\ioc\LoggerProvider.
 *
 * @group  ioc
 */
class LoggerProviderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * instance to test
     *
     * @type  LoggerProvider
     */
    private $loggerProvider;
    /**
     * mocked log entry factory
     *
     * @type  \bovigo\callmap\Proxy
     */
    private $logEntryFactory;

    /**
     * set up the test environment
     */
    public function setUp()
    {
        $this->logEntryFactory = NewInstance::of(LogEntryFactory::class);
        $this->loggerProvider  = new LoggerProvider($this->logEntryFactory);
    }

    /**
     * @test
     */
    public function createdLoggerUsesGivenLogEntryFactory()
    {
        $logger   = $this->loggerProvider->get();
        $logEntry = new LogEntry('testTarget', $logger);
        $this->logEntryFactory->mapCalls(['create' => $logEntry]);
        assert( $logger->createLogEntry('testTarget'), isSameAs($logEntry));
    }

    /**
     * @test
     */
    public function createsDifferentInstancesForDifferentNames()
    {
        assert(
                $this->loggerProvider->get('foo'),
                isNotSameAs($this->loggerProvider->get())
        );
    }

    /**
     * @test
     */
    public function returnsSameInstanceForSameName()
    {
        assert($this->loggerProvider->get(), isSameAs($this->loggerProvider->get()));
    }
}


text:
namespace bl { extern class Node; };

using namespace bl;

namespace resize {
	void load();

	extern char* plugin_name;

	struct ResizeEvent {
		int w;
		int h;
		Node* node;
	};
}


text:
#import "TML.h"
#import "TMLAnalytics.h"
#import "TMLConfiguration.h"
#import "TMLLanguage.h"

#ifndef TMLServiceHost
#define TMLServiceHost @"https://api.translationexchange.com"
#endif

#ifndef TMLTranslationCenterHost
#define TMLTranslationCenterHost @"https://translation-center.translationexchange.com"
#endif

NSString * const TMLApplicationKeyDefaultsKey = @"applicationKey";
NSString * const TMLDefaultLocaleDefaultsKey = @"defaultLocale";
NSString * const TMLCurrentLocaleDefaultsKey = @"currentLocale";
NSString * const TMLPreviousLocaleDefaultsKey = @"previousLocale";
NSString * const TMLTranslationEnabledDefaultsKey = @"translationEnabled";

@interface TMLConfiguration () {
    NSCalendar *calendar;
    NSDateFormatter *dateFormatter;
}
@end

@implementation TMLConfiguration

#pragma mark - Init

- (instancetype)init {
    return [self initWithApplicationKey:nil accessToken:nil];
}

- (instancetype)initWithApplicationKey:(NSString *)applicationKey accessToken:(NSString *)accessToken {
    if (self = [super init]) {
        self.applicationKey = applicationKey;
        self.accessToken = accessToken;
        [self setupDefaultContextRules];
        [self setupDefaultTokens];
        [self setupLocalization];
        self.apiURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@/v1", TMLServiceHost]];
        self.translationCenterURL = [NSURL URLWithString:TMLTranslationCenterHost];
        self.localizeNIBStrings = YES;
        self.automaticallyReloadDataBackedViews = YES;
#if DEBUG
        self.analyticsEnabled = NO;
#else
        self.analyticsEnabled = YES;
#endif
    }
    return self;
}

#pragma mark - Validation

- (BOOL)isValidConfiguration {
    return self.applicationKey.length > 0 && self.apiURL != nil;
}

- (void)invalidate {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:TMLDefaultLocaleDefaultsKey];
    [defaults removeObjectForKey:TMLCurrentLocaleDefaultsKey];
    [defaults removeObjectForKey:TMLTranslationEnabledDefaultsKey];
}

#pragma mark - Persistence

- (id) persistentValueForKey:(NSString *)key {
    return [[NSUserDefaults standardUserDefaults] valueForKey:key];
}

- (void)setPersistentValue:(id)value forKey:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (key == nil) {
        [defaults removeObjectForKey:key];
    }
    else {
        [defaults setValue:value forKey:key];
    }
    [defaults synchronize];
}

- (NSString *)description {
    return [NSString stringWithFormat:@"%@ (currentLocale: %@; defaultLocalte: %@)", [super description], self.currentLocale, self.defaultLocale];
}

#pragma mark - Accessors

- (void)setAccessToken:(NSString *)accessToken {
    if (_accessToken == accessToken
        || [_accessToken isEqualToString:accessToken] == YES) {
        return;
    }

    if (accessToken.length == 0) {
        _accessToken = nil;
    }
    else {
        _accessToken = accessToken;
    }
}

- (void)setApplicationKey:(NSString *)applicationKey {
    if (_applicationKey == applicationKey
        || [_applicationKey isEqualToString:applicationKey] == YES) {
        return;
    }

    if (applicationKey.length == 0) {
        _applicationKey = nil;
    }
    else {
        _applicationKey = applicationKey;
    }
}

- (BOOL)isTranslationEnabled {
    return ([[self persistentValueForKey:TMLTranslationEnabledDefaultsKey] boolValue]
            && self.accessToken.length > 0);
}

- (void)setTranslationEnabled:(BOOL)translationEnabled {
    [self willChangeValueForKey:@"translationEnabled"];
    [self setPersistentValue:@(translationEnabled) forKey:TMLTranslationEnabledDefaultsKey];
    [self didChangeValueForKey:@"translationEnabled"];
}

- (void)setAutomaticallyReloadTableViewsWithReusableLocalizedStrings:(BOOL)automaticallyReloadTableViewsWithReusableLocalizedStrings {
    self.automaticallyReloadDataBackedViews = automaticallyReloadTableViewsWithReusableLocalizedStrings;
}

- (BOOL)automaticallyReloadTableViewsWithReusableLocalizedStrings {
    return self.automaticallyReloadDataBackedViews;
}

#pragma mark - Locales

- (NSString *) deviceLocale {
    NSLocale *locale = [NSLocale currentLocale];
    NSString *deviceLocale = [locale localeIdentifier];
    deviceLocale = [deviceLocale componentsSeparatedByString:@"_"][0];
    return deviceLocale;
}

- (NSString *)currentLocale {
    NSString *locale = [self persistentValueForKey:TMLCurrentLocaleDefaultsKey];
    if (locale == nil) {
        return self.defaultLocale;
    }
    return locale;
}

- (void) setCurrentLocale:(NSString *)newLocale {
    [self willChangeValueForKey:@"currentLocale"];
    [self setPersistentValue:newLocale forKey:TMLCurrentLocaleDefaultsKey];
    [self didChangeValueForKey:@"defaultLocale"];
}

- (NSString *)previousLocale {
    NSString *locale = [self persistentValueForKey:TMLPreviousLocaleDefaultsKey];
    if (locale == nil) {
        return self.defaultLocale;
    }
    return locale;
}

- (void)setPreviousLocale:(NSString *)previousLocale {
    [self willChangeValueForKey:@"previousLocale"];
    [self setPersistentValue:previousLocale forKey:TMLPreviousLocaleDefaultsKey];
    [self didChangeValueForKey:@"previousLocale"];
}

- (NSString *)defaultLocale {
    NSString *locale = [self persistentValueForKey:TMLDefaultLocaleDefaultsKey];
    if (locale == nil) {
        locale = [[TMLLanguage defaultLanguage] locale];
    }
    return locale;
}

- (void) setDefaultLocale:(NSString *)newLocale {
    [self willChangeValueForKey:@"defaultLocale"];
    [self setPersistentValue:newLocale forKey:TMLDefaultLocaleDefaultsKey];
    [self didChangeValueForKey:@"defaultLocale"];
}

#pragma mark - Analytics

- (void)setAnalyticsEnabled:(BOOL)analyticsEnabled {
    if (_analyticsEnabled == analyticsEnabled) {
        return;
    }
    _analyticsEnabled = analyticsEnabled;
    [[TMLAnalytics sharedInstance] setEnabled:analyticsEnabled];
}

#pragma mark - Setting up Defaults

- (void) setupDefaultContextRules {
    self.contextRules = [NSMutableDictionary dictionaryWithDictionary: @{
      @"number": @{
              @"variables": [NSMutableDictionary dictionaryWithDictionary: @{}]         // if variable method is not specified, the object itself will be used as value
      },

      @"gender": [NSMutableDictionary dictionaryWithDictionary:@{
              @"variables": [NSMutableDictionary dictionaryWithDictionary:@{
                      @"@gender": @"@gender"                                            // @ - refers to a property of an object, @@ - refers to a method of an object
              }]
      }],

      @"genders": [NSMutableDictionary dictionaryWithDictionary:@{
              @"variables": [NSMutableDictionary dictionaryWithDictionary: @{
                      @"@genders": ^(NSObject *object) {                                // Anonymous functions can also be used
                          NSArray *list = (NSArray *) object;
                          NSMutableArray *genders = [NSMutableArray array];
                          for (NSObject *obj in list) {
                              [genders addObject:[obj valueForKey:@"gender"]];
                          }
                          return genders;
                      }
               }]
      }],

      @"list": [NSMutableDictionary dictionaryWithDictionary:@{
              @"variables": [NSMutableDictionary dictionaryWithDictionary:@{
                      @"@count": ^(NSObject *object) {
                          NSArray *list = (NSArray *) object;
                          return [list count];
                      }
              }]
      }],

      @"date": [NSMutableDictionary dictionaryWithDictionary:@{
              @"variables": [NSMutableDictionary dictionaryWithDictionary:@{}]
      }]
    }];
}

- (void) setupDefaultTokens {
    self.defaultTokens = [NSMutableDictionary dictionaryWithDictionary:@{
        @"html": [NSMutableDictionary dictionaryWithDictionary: @{
               @"data": [NSMutableDictionary dictionaryWithDictionary: @{
                       @"ndash":    @"–",       // –
                       @"mdash":    @"—",       // —
                       @"iexcl":    @"¡",       // ¡
                       @"iquest":   @"¿",      // ¿
                       @"quot":     @""",        // "
                       @"ldquo":    @""",       // "
                       @"rdquo":    @""",       // "
                       @"lsquo":    @"'",       // '
                       @"rsquo":    @"'",       // '
                       @"laquo":    @"«",       // «
                       @"raquo":    @"»",       // »
                       @"nbsp":     @" ",        // space
                       @"lsaquo":   @"‹",      // ‹
                       @"rsaquo":   @"›",      // ›
                       @"br":       @"
",         // line break
                       @"lbrace":   @"{",
                       @"rbrace":   @"}",
                       @"trade":    @"™"        // TM
                }],
               @"decoration": [NSMutableDictionary dictionaryWithDictionary: @{
                       @"strong":   @"{$0}",
                       @"bold":     @"{$0}",
                       @"b":        @"{$0}",
                       @"em":       @"{$0}",
                       @"italic":   @"{$0}",
                       @"i":        @"{$0}",
                       @"link":     @"{$0}",
                       @"br":       @"
{$0}",
                       @"strike":   @"{$0}",
                       @"div":      @"
{$0}
",
                       @"span":     @"{$0}",
                       @"h1":       @"
{$0}
",
                       @"h2":       @"
{$0}
",
                       @"h3":       @"
{$0}
"
                }]
        }],
        @"attributed": [NSMutableDictionary dictionaryWithDictionary: @{
              @"data":  [NSMutableDictionary dictionaryWithDictionary: @{
                      @"ndash":    @"–",        // –
                      @"mdash":    @"–",        // —
                      @"iexcl":    @"¡",        // ¡
                      @"iquest":   @"¿",        // ¿
                      @"quot":     @"\"",       // "
                      @"ldquo":    @""",        // "
                      @"rdquo":    @""",        // "
                      @"lsquo":    @"'",        // '
                      @"rsquo":    @"'",        // '
                      @"laquo":    @"«",        // «
                      @"raquo":    @"»",        // »
                      @"nbsp":     @" ",        // space
                      @"lsaquo":   @"‹",        // ‹
                      @"rsaquo":   @"›",        // ›
                      @"br":       @"\n",       // line break
                      @"lbrace":   @"{",
                      @"rbrace":   @"}",
                      @"trade":    @"™"         // TM
                }],
              @"decoration": [NSMutableDictionary dictionaryWithDictionary: @{
                      @"strong":   @{@"font": @{@"name": @"system", @"size": @14, @"type": @"bold"}},
                      @"bold":     @{@"font": @{@"name": @"system", @"size": @14, @"type": @"bold"}},
                      @"b":        @{@"font": @{@"name": @"system", @"size": @14, @"type": @"bold"}},
                      @"em":       @{@"font": @{@"name": @"system", @"size": @14, @"type": @"bold"}},
                      @"italic":   @{@"font": @{@"name": @"system", @"size": @14, @"type": @"italic"}},
                      @"i":        @{@"font": @{@"name": @"system", @"size": @14, @"type": @"italic"}},
                      @"link":     @"{$0}",
                      @"br":       @"\n{$0}",
                      @"strike":   @{@"strike": @"1"},
                      @"div":      @"{$0}",
                      @"span":     @"{$0}",
                      @"h1":       @{@"font": @{@"name": @"system", @"size": @20, @"type": @"bold"}},
                      @"h2":       @{@"font": @{@"name": @"system", @"size": @18, @"type": @"bold"}},
                      @"h3":       @{@"font": @{@"name": @"system", @"size": @16, @"type": @"bold"}},
            }]
        }]
    }];
}

- (void) setupLocalization {
    self.defaultLocalization = [NSMutableDictionary dictionaryWithDictionary:@{
      @"default_day_names": @[@"Sunday", @"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday"],
      @"default_abbr_day_names": @[@"Sun", @"Mon", @"Tue", @"Wed", @"Thu", @"Fri", @"Sat"],
      @"default_month_names": @[@"January", @"February", @"March", @"April", @"May", @"June", @"July", @"August", @"September", @"October", @"November", @"December"],
      @"default_abbr_month_names": @[@"Jan", @"Feb", @"Mar", @"Apr", @"May", @"Jun", @"Jul", @"Aug", @"Sep", @"Oct", @"Nov", @"Dec"],
      @"custom_date_formats": [NSMutableDictionary dictionaryWithDictionary:@{
        @"default"               : @"mm/d/yyyy",             // 07/4/2008
        @"short_numeric"         : @"mm/d",                  // 07/4
        @"short_numeric_year"    : @"mm/d/yy",               // 07/4/08
        @"long_numeric"          : @"mm/d/yyyy",             // 07/4/2008
        @"verbose"               : @"eeee, MMMM d, yyyy",    // Friday, July  4, 2008
        @"monthname"             : @"MMMM d",                // July 4
        @"monthname_year"        : @"MMMM d, yyyy",          // July 4, 2008
        @"monthname_abbr"        : @"MMMM d",                // Jul 4
        @"monthname_abbr_year"   : @"MMM d, yyyy",           // Jul 4, 2008
        @"date_time"             : @"mm/dd/yyyy at h:m",     // 01/03/1010 at 5:30
    }],
    @"token_mapping": [NSMutableDictionary dictionaryWithDictionary:@{
        @"G": @"{era}",
        @"y": @"{short_year_digit}",
        @"yy": @"{short_year}",
        @"yyyy": @"{year}",
        @"M": @"{month}",
        @"MM": @"{month_padded}",
        @"MMM": @"{short_month_name}",
        @"MMMM": @"{month_name}",
        @"MMMMM": @"{month_letter}",
        @"w": @"{week_of_year}",
        @"ww": @"{week_of_year}",
        @"W": @"{week_num}",
        @"d": @"{day}",
        @"dd": @"{day_padded}",
        @"D": @"{day_of_year}",
        @"DD": @"{day_of_year_padded}",
        @"DDD": @"{day_of_year}",
        @"F": @"{day_of_week_in_month}",
        @"E": @"{day_of_week}",
        @"EE": @"{day_of_week_padded2}",
        @"EEE": @"{day_of_week_padded3}",
        @"EEEE": @"{short_weekday_name}",
        @"EEEE": @"{weekday_name}",
        @"a": @"{am_pm}",
        @"h": @"{hour}",
        @"hh": @"{hour_padded}",
        @"H": @"{hour24}",
        @"HH": @"{hour24_padded}",
        @"m": @"{minute}",
        @"mm": @"{minute_padded}",
        @"s": @"{second}",
        @"ss": @"{second_padded}",
    }]
   }];
}

#pragma mark - Formatting Dates

- (NSString *) customDateFormatForKey: (NSString *) key {
    return [[self.defaultLocalization objectForKey:@"custom_date_formats"] objectForKey:key];
}

- (NSString *) dateTokenNameForKey: (NSString *) key {
    return [[self.defaultLocalization objectForKey:@"token_mapping"] objectForKey:key];
}

- (NSObject *) dateValueForToken: (NSString *) token inDate: (NSDate *) date  {
    if (![self.defaultLocalization objectForKey:@"token_mapping_reversed"]) {
        NSArray *keys = [[self.defaultLocalization objectForKey:@"token_mapping"] allKeys];
        NSMutableDictionary *reversed = [NSMutableDictionary dictionary];
        for (NSString *key in keys) {
            [reversed setObject:key forKey: [[self.defaultLocalization objectForKey:@"token_mapping"] objectForKey:key]];
        }
        [self.defaultLocalization setObject:reversed forKey:@"token_mapping_reversed"];
    }

    NSString *format = [[self.defaultLocalization objectForKey:@"token_mapping_reversed"] objectForKey:token];
    if (!format) return token;

    if (calendar == nil)
        calendar = [NSCalendar currentCalendar];

    // Handle string values
    if ([token isEqualToString:@"{month_name}"]) {
        NSDateComponents *comps = [calendar components:NSCalendarUnitMonth fromDate:date];
        NSString *monthName = [[self.defaultLocalization objectForKey:@"default_month_names"] objectAtIndex:comps.month-1];
        return TMLLocalizedString(monthName, @"Month name", @{}, @{@"locale": @"en"});
    }

    if ([token isEqualToString:@"{short_month_name}"]) {
        NSDateComponents *comps = [calendar components:NSCalendarUnitMonth fromDate:date];
        NSString *monthName = [[self.defaultLocalization objectForKey:@"default_abbr_month_names"] objectAtIndex:comps.month-1];
        return TMLLocalizedString(monthName, @"Abbreviated month name", @{}, @{@"locale": @"en"});
    }

    if ([token isEqualToString:@"{weekday_name}"]) {
        NSDateComponents *comps = [calendar components:NSCalendarUnitWeekday fromDate:date];
        NSString *weekdayName = [[self.defaultLocalization objectForKey:@"default_day_names"] objectAtIndex:comps.weekday];
        return TMLLocalizedString(weekdayName, @"Weekday name", @{}, @{@"locale": @"en"});
    }

    if ([token isEqualToString:@"{short_weekday_name}"]) {
        NSDateComponents *comps = [calendar components:NSCalendarUnitWeekday fromDate:date];
        NSString *weekdayName = [[self.defaultLocalization objectForKey:@"default_abbr_day_names"] objectAtIndex:comps.weekday];
        return TMLLocalizedString(weekdayName, @"Abbreviated weekday name", @{}, @{@"locale": @"en"});
    }

    if (dateFormatter == nil)
        dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:format];
    return [dateFormatter stringFromDate:date];
}

- (id) variableMethodForContext:(NSString *) keyword andVariableName: (NSString *) varName {
    NSDictionary *contextConfig = [self.contextRules objectForKey:keyword];
    if (contextConfig == nil)
        return nil;

    NSDictionary *variables = [contextConfig objectForKey:@"variables"];
    if (variables == nil)
        return nil;

    return [variables objectForKey:varName];
}

- (void) setVariableMethod: (id) method forContext:(NSString *) keyword andVariableName: (NSString *) varName {
    NSMutableDictionary *contextConfig = [self.contextRules objectForKey:keyword];
    if (contextConfig == nil) {
        contextConfig = [NSMutableDictionary dictionary];
        [self.contextRules setObject:contextConfig forKey:keyword];
    }

    NSMutableDictionary *variables = [contextConfig objectForKey:@"variables"];
    if (variables == nil) {
        variables = [NSMutableDictionary dictionary];
        [contextConfig setObject:variables forKey:@"variables"];
    }

    [variables setObject:method forKey:varName];
}

#pragma mark - Default Tokens

- (id) defaultTokenValueForName:(NSString *)name {
    return [self defaultTokenValueForName:name
                                     type:TMLDataTokenType
                                   format:TMLAttributedTokenFormat];
}

- (void) setDefaultTokenValue:(id)value
                      forName:(NSString *)name
{
    [self setDefaultTokenValue:value
                       forName:name
                          type:TMLDataTokenType
                        format:TMLAttributedTokenFormat];
}

- (id) defaultTokenValueForName:(NSString *)name
                           type:(TMLTokenType)type
{
    return [self defaultTokenValueForName:name
                                     type:type
                                   format:TMLAttributedTokenFormat];
}

- (void) setDefaultTokenValue:(id)value
                      forName:(NSString *)name
                         type:(TMLTokenType)type
{
    [self setDefaultTokenValue:value
                       forName:name
                          type:type
                        format:TMLAttributedTokenFormat];
}

- (id) defaultTokenValueForName:(NSString *)name
                           type:(TMLTokenType)type
                         format:(TMLTokenFormat)format
{
    return [[[self.defaultTokens objectForKey:NSStringFromTokenFormat(format)]
             objectForKey:NSStringFromTokenType(type)]
            objectForKey:name];
}

- (void) setDefaultTokenValue:(id)value
                      forName:(NSString *)name
                         type:(TMLTokenType)type
                       format:(TMLTokenFormat)format
{
    NSString *formatString = NSStringFromTokenFormat(format);
    NSMutableDictionary *dictFormat = (NSMutableDictionary *) [self.defaultTokens objectForKey:formatString];
    if (dictFormat == nil) {
        dictFormat = [NSMutableDictionary dictionary];
        [self.defaultTokens setObject:dictFormat forKey:formatString];
    }

    NSString *typeString = NSStringFromTokenType(type);
    NSMutableDictionary *dictType = (NSMutableDictionary *) [dictFormat objectForKey:typeString];
    if (dictType == nil) {
        dictType = [NSMutableDictionary dictionary];
        [dictFormat setObject:dictType forKey:formatString];
    }

    [dictType setObject:value forKey:name];
}

@end


text:
define(
   ({
    _widgetLabel: "Atributová tabulka",
    ok: "OK",
    cancel: "Storno",
    unsupportQueryWarning: "Vrstva musí podporovat operace dané založené na dotazu, aby bylo možné ji zobrazovat ve widgetu Atributová tabulka. Ujistěte se, že je ve službě aktivní možnost dotazování.",
    exportMessage: "Přejete si exportovat data do CSV souboru ?",
    exportFiles: "Exportovat do CSV",
    options: "Možnosti",
    zoomto: "Přiblížit na",
    highlight: "Zvýraznit grafiku",
    selectAll: "Vybrat záznamy na všech stránkách",
    selectPage: "Vybrat záznamy na aktuální stránce",
    clearSelection: "Zrušit výběr",
    filterByExtent: "Filtrovat podle rozsahu mapy",
    refresh: "Obnovit",
    selected: "vybrané",
    transparent: "Režim průhlednosti",
    indicate: "Najít výběr",
    columns: "Zobrazit/Skrýt sloupce",
    selectionSymbol: "Symbol výběru",
    closeMessage: "Skrýt tabulku (znovu ji rozbalit zespodu)",
    dataNotAvailable: "Data nejsou k dispozici!<br>Zkuste to znovu kliknutím na tlačítko [Obnovit].",
    openTableTip: "Otevřít atributovou tabulku",
    closeTableTip: "Skrýt atributovou tabulku"
  })
);


text:
from django.apps import AppConfig

class TaxonomiaConfig(AppConfig):
    name = 'taxonomy'


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>

#include <string>
#include <vector>

#include "base/bind.h"
#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_types.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "crypto/rsa_private_key.h"
#include "crypto/scoped_openssl_types.h"
#include "extensions/common/extension.h"
#include "extensions/test/result_catcher.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "policy/policy_constants.h"
#include "testing/gmock/include/gmock/gmock.h"

using testing::Return;
using testing::_;

namespace {

void IgnoreResult(const base::Closure& callback, const base::Value* value) {
  callback.Run();
}

void StoreBool(bool* result,
               const base::Closure& callback,
               const base::Value* value) {
  value->GetAsBoolean(result);
  callback.Run();
}

void StoreString(std::string* result,
                 const base::Closure& callback,
                 const base::Value* value) {
  value->GetAsString(result);
  callback.Run();
}

void StoreDigest(std::vector<uint8_t>* digest,
                 const base::Closure& callback,
                 const base::Value* value) {
  const base::BinaryValue* binary = nullptr;
  const bool is_binary = value->GetAsBinary(&binary);
  EXPECT_TRUE(is_binary) << "Unexpected value in StoreDigest";
  if (is_binary) {
    const uint8_t* const binary_begin =
        reinterpret_cast<const uint8_t*>(binary->GetBuffer());
    digest->assign(binary_begin, binary_begin + binary->GetSize());
  }

  callback.Run();
}

// See net::SSLPrivateKey::SignDigest for the expected padding and DigestInfo
// prefixing.
bool RsaSign(const std::vector<uint8_t>& digest,
             crypto::RSAPrivateKey* key,
             std::vector<uint8_t>* signature) {
  crypto::ScopedRSA rsa_key(EVP_PKEY_get1_RSA(key->key()));
  if (!rsa_key)
    return false;

  uint8_t* prefixed_digest = nullptr;
  size_t prefixed_digest_len = 0;
  int is_alloced = 0;
  if (!RSA_add_pkcs1_prefix(&prefixed_digest, &prefixed_digest_len, &is_alloced,
                            NID_sha1, digest.data(), digest.size())) {
    return false;
  }
  size_t len = 0;
  signature->resize(RSA_size(rsa_key.get()));
  const int rv =
      RSA_sign_raw(rsa_key.get(), &len, signature->data(), signature->size(),
                   prefixed_digest, prefixed_digest_len, RSA_PKCS1_PADDING);
  if (is_alloced)
    free(prefixed_digest);

  if (rv) {
    signature->resize(len);
    return true;
  } else {
    signature->clear();
    return false;
  }
}

// Create a string that if evaluated in JavaScript returns a Uint8Array with
// |bytes| as content.
std::string JsUint8Array(const std::vector<uint8_t>& bytes) {
  std::string res = "new Uint8Array([";
  for (const uint8_t byte : bytes) {
    res += base::UintToString(byte);
    res += ", ";
  }
  res += "])";
  return res;
}

class CertificateProviderApiTest : public ExtensionApiTest {
 public:
  CertificateProviderApiTest() {}

  void SetUpInProcessBrowserTestFixture() override {
    EXPECT_CALL(provider_, IsInitializationComplete(_))
        .WillRepeatedly(Return(true));
    policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);

    ExtensionApiTest::SetUpInProcessBrowserTestFixture();
  }

  void SetUpOnMainThread() override {
    // Set up the AutoSelectCertificateForUrls policy to avoid the client
    // certificate selection dialog.
    const std::string autoselect_pattern =
        "{\"pattern\": \"*\", \"filter\": {\"ISSUER\": {\"CN\": \"root\"}}}";

    scoped_ptr<base::ListValue> autoselect_policy(new base::ListValue);
    autoselect_policy->AppendString(autoselect_pattern);

    policy::PolicyMap policy;
    policy.Set(policy::key::kAutoSelectCertificateForUrls,
               policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER,
               policy::POLICY_SOURCE_CLOUD, autoselect_policy.release(),
               nullptr);
    provider_.UpdateChromePolicy(policy);

    content::RunAllPendingInMessageLoop();
  }

 protected:
  policy::MockConfigurationPolicyProvider provider_;
};

}  // namespace

IN_PROC_BROWSER_TEST_F(CertificateProviderApiTest, Basic) {
  // Start an HTTPS test server that requests a client certificate.
  net::SpawnedTestServer::SSLOptions ssl_options;
  ssl_options.request_client_certificate = true;
  net::SpawnedTestServer https_server(net::SpawnedTestServer::TYPE_HTTPS,
                                      ssl_options, base::FilePath());
  ASSERT_TRUE(https_server.Start());

  extensions::ResultCatcher catcher;

  const base::FilePath extension_path =
      test_data_dir_.AppendASCII("certificate_provider");
  const extensions::Extension* const extension = LoadExtension(extension_path);
  ui_test_utils::NavigateToURL(browser(),
                               extension->GetResourceURL("basic.html"));

  ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
  VLOG(1) << "Extension registered. Navigate to the test https page.";

  content::WebContents* const extension_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  content::TestNavigationObserver navigation_observer(
      nullptr /* no WebContents */);
  navigation_observer.StartWatchingNewWebContents();
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), https_server.GetURL("client-cert"), NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_NONE);

  content::WebContents* const https_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  VLOG(1) << "Wait for the extension to respond to the certificates request.";
  ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();

  VLOG(1) << "Wait for the extension to receive the sign request.";
  ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();

  VLOG(1) << "Fetch the digest from the sign request.";
  std::vector<uint8_t> request_digest;
  {
    base::RunLoop run_loop;
    extension_contents->GetMainFrame()->ExecuteJavaScriptForTests(
        base::ASCIIToUTF16("signDigestRequest.digest;"),
        base::Bind(&StoreDigest, &request_digest, run_loop.QuitClosure()));
    run_loop.Run();
  }

  VLOG(1) << "Sign the digest using the private key.";
  std::string key_pk8;
  base::ReadFileToString(extension_path.AppendASCII("l1_leaf.pk8"), &key_pk8);

  const uint8_t* const key_pk8_begin =
      reinterpret_cast<const uint8_t*>(key_pk8.data());
  scoped_ptr<crypto::RSAPrivateKey> key(
      crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(
          std::vector<uint8_t>(key_pk8_begin, key_pk8_begin + key_pk8.size())));
  ASSERT_TRUE(key);

  std::vector<uint8_t> signature;
  EXPECT_TRUE(RsaSign(request_digest, key.get(), &signature));

  VLOG(1) << "Inject the signature back to the extension and let it reply.";
  {
    base::RunLoop run_loop;
    const std::string code =
        "replyWithSignature(" + JsUint8Array(signature) + ");";
    extension_contents->GetMainFrame()->ExecuteJavaScriptForTests(
        base::ASCIIToUTF16(code),
        base::Bind(&IgnoreResult, run_loop.QuitClosure()));
    run_loop.Run();
  }

  VLOG(1) << "Wait for the https navigation to finish.";
  navigation_observer.Wait();

  VLOG(1) << "Check whether the server acknowledged that a client certificate "
             "was presented.";
  {
    base::RunLoop run_loop;
    std::string https_reply;
    https_contents->GetMainFrame()->ExecuteJavaScriptForTests(
        base::ASCIIToUTF16("document.body.textContent;"),
        base::Bind(&StoreString, &https_reply, run_loop.QuitClosure()));
    run_loop.Run();
    // Expect the server to return the fingerprint of the client cert that we
    // presented, which should be the fingerprint of 'l1_leaf.der'.
    // The fingerprint can be calculated independently using:
    // openssl x509 -inform DER -noout -fingerprint -in
    //   chrome/test/data/extensions/api_test/certificate_provider/l1_leaf.der
    ASSERT_EQ(
        "got client cert with fingerprint: "
        "2ab3f55e06eb8b36a741fe285a769da45edb2695",
        https_reply);
  }

  // Replying to the same signature request a second time must fail.
  {
    base::RunLoop run_loop;
    const std::string code = "replyWithSignatureSecondTime();";
    bool result = false;
    extension_contents->GetMainFrame()->ExecuteJavaScriptForTests(
        base::ASCIIToUTF16(code),
        base::Bind(&StoreBool, &result, run_loop.QuitClosure()));
    run_loop.Run();
    EXPECT_TRUE(result);
  }
}


text:
#ifndef __X86_ARCH_ASM_MEMORY_H__
#define __X86_ARCH_ASM_MEMORY_H__

#define PHYS_MEM_MAX         0xFFFFFFFF
#define PAGE_OFFSET          0xC0000000
#define KMAP_OFFSET          0xF8000000

#define PAGE_SHIFT           12
#define PAGE_SIZE            (1 << PAGE_SHIFT)
#define PAGE_OFFSET_MASK     (PAGE_SIZE - 1)
#define PGDIR_SHIFT          22
#define PGDIR_SIZE           (1 << PGDIR_SHIFT)
#define PAGE_TABLE_MASK      (PGDIR_SIZE - 1)
#define PTRS_PER_PT          1024
#define PTRS_PER_PGD         1024

#define KERNEL_STACK_ORDER   1
#define KERNEL_STACK_PAGES   (1 << KERNEL_STACK_ORDER)
#define KERNEL_STACK_SIZE    (KERNEL_STACK_PAGES * PAGE_SIZE)
#define KERNEL_STACK_ALIGN   (KERNEL_STACK_PAGES * PAGE_SIZE)

#define PAGE_FRAME(addr)     ((addr) >> PAGE_SHIFT)
#define PAGE_DIR(addr)       ((addr) >> PGDIR_SHIFT)

#define PAGE_FRAMES          (1 + PAGE_FRAME(PHYS_MEM_MAX))
#define PAGE_DIRS            (1 + PAGE_DIR(PHYS_MEM_MAX))

#define LOWMEM_PAGE_FRAME    PAGE_FRAME(PAGE_OFFSET)
#define LOWMEM_PAGE_DIR      PAGE_DIR(PAGE_OFFSET)

#define KMAP_PAGE_FRAME      PAGE_FRAME(KMAP_OFFSET)
#define KMAP_PAGE_DIR        PAGE_DIR(KMAP_OFFSET)

#define LOWMEM_PAGE_FRAMES   (KMAP_PAGE_FRAME - LOWMEM_PAGE_FRAME)
#define LOWMEM_PAGE_DIRS     (KMAP_PAGE_DIR - LOWMEM_PAGE_DIR)

#define KMAP_PAGE_FRAMES     (PAGE_FRAMES - KMAP_PAGE_FRAME)
#define KMAP_PAGE_DIRS       (PAGE_DIRS - KMAP_PAGE_DIR)

#define KERNEL_PAGE_FRAMES   (PAGE_FRAMES - LOWMEM_PAGE_FRAME)
#define KERNEL_PAGE_DIRS     (PAGE_DIRS - LOWMEM_PAGE_DIR)

#endif /*__X86_ARCH_ASM_MEMORY_H__*/


text:
package armdataprotection_test

import (
	"context"
	"log"

	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/dataprotection/armdataprotection"
)

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/dataprotection/resource-manager/Microsoft.DataProtection/stable/2022-04-01/examples/GetOperationStatus.json
func ExampleOperationStatusClient_Get() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armdataprotection.NewOperationStatusClient("0b352192-dcac-4cc7-992e-a96190ccc68c", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	res, err := client.Get(ctx,
		"WestUS",
		"MjkxOTMyODMtYTE3My00YzJjLTg5NjctN2E4MDIxNDA3NjA2OzdjNGE2ZWRjLWJjMmItNDRkYi1hYzMzLWY1YzEwNzk5Y2EyOA==",
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	// TODO: use response item
	_ = res
}


text:
""" Component tests for VPC - Router Operations
"""
#Import Local Modules
import marvin
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import *
from marvin.cloudstackAPI import *
from marvin.lib.utils import *
from marvin.lib.base import *
from marvin.lib.common import *
import datetime

class Services:
    """Test VPC Router services
    """

    def __init__(self):
        self.services = {
                         "account": {
                                    "email": "test@test.com",
                                    "firstname": "Test",
                                    "lastname": "User",
                                    "username": "test",
                                    # Random characters are appended for unique
                                    # username
                                    "password": "password",
                                    },
                         "service_offering": {
                                    "name": "Tiny Instance",
                                    "displaytext": "Tiny Instance",
                                    "cpunumber": 1,
                                    "cpuspeed": 100,
                                    "memory": 128,
                                    'storagetype': 'local'
                                    },
                         "service_offering_new": {
                                    "name": "Small Instance",
                                    "displaytext": "Small Instance",
                                    "cpunumber": 1,
                                    "cpuspeed": 100,
                                    "memory": 256,
                                    "issystem": 'true',
                                    'storagetype': 'local'
                                    },

                         "network_offering": {
                                    "name": 'VPC Network offering',
                                    "displaytext": 'VPC Network off',
                                    "guestiptype": 'Isolated',
                                    "supportedservices": 'Vpn,Dhcp,Dns,SourceNat,PortForwarding,Lb,UserData,StaticNat,NetworkACL',
                                    "traffictype": 'GUEST',
                                    "availability": 'Optional',
                                    "useVpc": 'on',
                                    "serviceProviderList": {
                                            "Vpn": 'VpcVirtualRouter',
                                            "Dhcp": 'VpcVirtualRouter',
                                            "Dns": 'VpcVirtualRouter',
                                            "SourceNat": 'VpcVirtualRouter',
                                            "PortForwarding": 'VpcVirtualRouter',
                                            "Lb": 'VpcVirtualRouter',
                                            "UserData": 'VpcVirtualRouter',
                                            "StaticNat": 'VpcVirtualRouter',
                                            "NetworkACL": 'VpcVirtualRouter'
                                        },
                                },
                         "network_offering_no_lb": {
                                    "name": 'VPC Network offering',
                                    "displaytext": 'VPC Network off',
                                    "guestiptype": 'Isolated',
                                    "supportedservices": 'Vpn,Dhcp,Dns,SourceNat,PortForwarding,UserData,StaticNat,NetworkACL',
                                    "traffictype": 'GUEST',
                                    "availability": 'Optional',
                                    "useVpc": 'on',
                                    "serviceProviderList": {
                                            "Vpn": 'VpcVirtualRouter',
                                            "Dhcp": 'VpcVirtualRouter',
                                            "Dns": 'VpcVirtualRouter',
                                            "SourceNat": 'VpcVirtualRouter',
                                            "PortForwarding": 'VpcVirtualRouter',
                                            "UserData": 'VpcVirtualRouter',
                                            "StaticNat": 'VpcVirtualRouter',
                                            "NetworkACL": 'VpcVirtualRouter'
                                        },
                                },
                         "vpc_offering": {
                                    "name": 'VPC off',
                                    "displaytext": 'VPC off',
                                    "supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Vpn,Lb,UserData,StaticNat',
                                },
                         "redundant_vpc_offering": {
                                    "name": 'Redundant VPC off',
                                    "displaytext": 'Redundant VPC off',
                                    "supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Vpn,Lb,UserData,StaticNat',
                                    "serviceProviderList": {
                                            "Vpn": 'VpcVirtualRouter',
                                            "Dhcp": 'VpcVirtualRouter',
                                            "Dns": 'VpcVirtualRouter',
                                            "SourceNat": 'VpcVirtualRouter',
                                            "PortForwarding": 'VpcVirtualRouter',
                                            "Lb": 'VpcVirtualRouter',
                                            "UserData": 'VpcVirtualRouter',
                                            "StaticNat": 'VpcVirtualRouter',
                                            "NetworkACL": 'VpcVirtualRouter'
                                    },
                                    "serviceCapabilityList": {
                                        "SourceNat": {
                                            "RedundantRouter": 'true'
                                        }
                                    },
                                },
                         "vpc": {
                                 "name": "TestVPC",
                                 "displaytext": "TestVPC",
                                 "cidr": '10.0.0.1/24'
                                 },
                         "network": {
                                  "name": "Test Network",
                                  "displaytext": "Test Network",
                                  "netmask": '255.255.255.0'
                                },
                         "lbrule": {
                                    "name": "SSH",
                                    "alg": "leastconn",
                                    # Algorithm used for load balancing
                                    "privateport": 22,
                                    "publicport": 2222,
                                    "openfirewall": False,
                                    "startport": 2222,
                                    "endport": 2222,
                                    "protocol": "TCP",
                                    "cidrlist": '0.0.0.0/0',
                                },
                         "natrule": {
                                    "privateport": 22,
                                    "publicport": 22,
                                    "startport": 22,
                                    "endport": 22,
                                    "protocol": "TCP",
                                    "cidrlist": '0.0.0.0/0',
                                },
                         "fw_rule": {
                                    "startport": 1,
                                    "endport": 6000,
                                    "cidr": '0.0.0.0/0',
                                    # Any network (For creating FW rule)
                                    "protocol": "TCP"
                                },
                         "http_rule": {
                                    "startport": 80,
                                    "endport": 80,
                                    "cidrlist": '0.0.0.0/0',
                                    "protocol": "TCP"
                                },
                         "virtual_machine": {
                                    "displayname": "Test VM",
                                    "username": "root",
                                    "password": "password",
                                    "ssh_port": 22,
                                    "hypervisor": 'XenServer',
                                    # Hypervisor type should be same as
                                    # hypervisor type of cluster
                                    "privateport": 22,
                                    "publicport": 22,
                                    "protocol": 'TCP',
                                },
                          "ostype": 'CentOS 5.6 (64-bit)',
                         # Cent OS 5.3 (64 bit)
                         "sleep": 60,
                         "timeout": 10,
                         "mode": 'advanced'
                    }

class TestVPCRoutersBasic(cloudstackTestCase):

    @classmethod
    def setUpClass(cls):
        cls.testClient = super(TestVPCRoutersBasic, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()

        cls.services = Services().services
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client)
        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
        cls.template = get_template(
                            cls.api_client,
                            cls.zone.id,
                            cls.services["ostype"]
                            )
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls.services["virtual_machine"]["template"] = cls.template.id

        cls.service_offering = ServiceOffering.create(
                                            cls.api_client,
                                            cls.services["service_offering"]
                                            )
        cls.vpc_off = VpcOffering.create(
                                     cls.api_client,
                                     cls.services["redundant_vpc_offering"]
                                     )
        cls.vpc_off.update(cls.api_client, state='Enabled')
        cls.account = Account.create(
                                     cls.api_client,
                                     cls.services["account"],
                                     admin=True,
                                     domainid=cls.domain.id
                                     )
        cls._cleanup = [cls.account]
        cls._cleanup.append(cls.vpc_off)
        #cls.debug("Enabling the VPC offering created")
        cls.vpc_off.update(cls.api_client, state='Enabled')

        #cls.debug("creating a VPC network in the account: %s" %
                                                   # cls.account.name)
        cls.services["vpc"]["cidr"] = '10.1.1.1/16'
        cls.vpc = VPC.create(
                         cls.api_client,
                         cls.services["vpc"],
                         vpcofferingid=cls.vpc_off.id,
                         zoneid=cls.zone.id,
                         account=cls.account.name,
                         domainid=cls.account.domainid
                         )

        cls._cleanup.append(cls.service_offering)
        return

    @classmethod
    def tearDownClass(cls):
        try:
            #Cleanup resources used
            cleanup_resources(cls.api_client, cls._cleanup)
        except Exception as e:
            raise Exception("Warning: Exception during cleanup : %s" % e)
        return

    def setUp(self):
        self.api_client = self.testClient.getApiClient()

        return

    def tearDown(self):
       return

    def validate_vpc_offering(self, vpc_offering):
        """Validates the VPC offering"""

        self.debug("Check if the VPC offering is created successfully?")
        vpc_offs = VpcOffering.list(
                                    self.api_client,
                                    id=vpc_offering.id
                                    )
        self.assertEqual(
                         isinstance(vpc_offs, list),
                         True,
                         "List VPC offerings should return a valid list"
                         )
        self.assertEqual(
                 vpc_offering.name,
                 vpc_offs[0].name,
                "Name of the VPC offering should match with listVPCOff data"
                )
        self.debug(
                "VPC offering is created successfully - %s" %
                                                        vpc_offering.name)
        return

    def validate_vpc_network(self, network, state=None):
        """Validates the VPC network"""

        self.debug("Check if the VPC network is created successfully?")
        vpc_networks = VPC.list(
                                    self.api_client,
                                    id=network.id
                          )
        self.assertEqual(
                         isinstance(vpc_networks, list),
                         True,
                         "List VPC network should return a valid list"
                         )
        self.assertEqual(
                 network.name,
                 vpc_networks[0].name,
                "Name of the VPC network should match with listVPC data"
                )
        if state:
            self.assertEqual(
                 vpc_networks[0].state,
                 state,
                "VPC state should be '%s'" % state
                )
        self.debug("VPC network validated - %s" % network.name)
        return

    def migrate_router(self, router):
        """ Migrate the router """

        self.debug("Checking if the host is available for migration?")
        hosts = Host.list(self.api_client, zoneid=self.zone.id, type='Routing')

        self.assertEqual(
                         isinstance(hosts, list),
                         True,
                         "List hosts should return a valid list"
                         )
        if len(hosts) < 2:
            raise unittest.SkipTest(
            "No host available for migration. Test requires atleast 2 hosts")

        # Remove the host of current VM from the hosts list
        hosts[:] = [host for host in hosts if host.id != router.hostid]
        host = hosts[0]
        self.debug("Validating if the network rules work properly or not?")

        self.debug("Migrating VM-ID: %s from %s to Host: %s" % (
                                                        router.id,
                                                        router.hostid,
                                                        host.id
                                                        ))
        try:

            #Migrate  the router
            cmd = migrateSystemVm.migrateSystemVmCmd()
            cmd.isAsync = "false"
            cmd.hostid = host.id
            cmd.virtualmachineid = router.id
            self.api_client.migrateSystemVm(cmd)

        except Exception as e:
            self.fail("Failed to migrate instance, %s" % e)

        self.debug("Waiting for Router mgiration ....")
        time.sleep(240)

        #List routers to check state of router
        router_response = list_routers(
                                    self.api_client,
                                    id=router.id
                                    )
        self.assertEqual(
                            isinstance(router_response, list),
                            True,
                            "Check list response returns a valid list"
                        )

        router.hostid = router_response[0].hostid
        self.assertEqual(router.hostid, host.id, "Migration to host %s failed. The router host is"
                         " still %s" % (host.id, router.hostid))
        return

    @attr(tags=["advanced", "intervlan"], required_hardware="false")
    def test_01_stop_start_router_after_creating_vpc(self):
        """ Test to stop and start router after creation of VPC
        """

	    # Validate following:
	    # 1. Create a VPC with cidr - 10.1.1.1/16
	    # 2. Stop the VPC Virtual Router which is created as a result of VPC creation.
	    # 3. Start the Stopped VPC Virtual Router

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)

	    # Stop the VPC Router
        routers = Router.list(
                              self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         True,
                         "List Routers should return a valid list"
                         )
        router = routers[0]
        self.debug("Stopping the router with ID: %s" % router.id)

        #Stop the router
        cmd = stopRouter.stopRouterCmd()
        cmd.id = router.id
        self.api_client.stopRouter(cmd)

	    #List routers to check state of router
        router_response = list_routers(
                                    self.api_client,
                                    id=router.id
                                    )
        self.assertEqual(
                            isinstance(router_response, list),
                            True,
                            "Check list response returns a valid list"
                        )
        #List router should have router in stopped state
        self.assertEqual(
                            router_response[0].state,
                            'Stopped',
                            "Check list router response for router state"
                        )

        self.debug("Stopped the router with ID: %s" % router.id)

	    # Start The Router
        self.debug("Starting the router with ID: %s" % router.id)
        cmd = startRouter.startRouterCmd()
        cmd.id = router.id
        self.api_client.startRouter(cmd)

	    #List routers to check state of router
        router_response = list_routers(
                                    self.api_client,
                                    id=router.id
                                    )
        self.assertEqual(
                            isinstance(router_response, list),
                            True,
                            "Check list response returns a valid list"
                        )
        #List router should have router in running state
        self.assertEqual(
                            router_response[0].state,
                            'Running',
                            "Check list router response for router state"
                        )
        self.debug("Started the router with ID: %s" % router.id)

        return

    @attr(tags=["advanced", "intervlan"], required_hardware="false")
    def test_02_reboot_router_after_creating_vpc(self):
        """ Test to reboot the router after creating a VPC
        """
        # Validate the following
	    # 1. Create a VPC with cidr - 10.1.1.1/16
	    # 2. Reboot the VPC Virtual Router which is created as a result of VPC creation.
        	    # Stop the VPC Router

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)
        routers = Router.list(
                              self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         True,
                         "List Routers should return a valid list"
                         )
        router = routers[0]

        self.debug("Rebooting the router ...")
        #Reboot the router
        cmd = rebootRouter.rebootRouterCmd()
        cmd.id = router.id
        self.api_client.rebootRouter(cmd)

        #List routers to check state of router
        router_response = list_routers(
                                    self.api_client,
                                    id=router.id
                                    )
        self.assertEqual(
                            isinstance(router_response, list),
                            True,
                            "Check list response returns a valid list"
                        )
        #List router should have router in running state and same public IP
        self.assertEqual(
                            router_response[0].state,
                            'Running',
                            "Check list router response for router state"
                        )
        return

    @attr(tags=["advanced", "intervlan"], required_hardware="false")
    def test_03_migrate_router_after_creating_vpc(self):
        """ Test migration of router to another host after creating VPC """

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)

        routers = Router.list(
                              self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         True,
                         "List Routers should return a valid list"
                         )
        self.migrate_router(routers[0])
        return

    @attr(tags=["advanced", "intervlan"], required_hardware="false")
    def test_04_change_service_offerring_vpc(self):
        """ Tests to change service offering of the Router after
            creating a vpc
        """

        # Validate the following
	    # 1. Create a VPC with cidr - 10.1.1.1/16
	    # 2. Change the service offerings of the VPC Virtual Router which is created as a result of VPC creation.

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)

        routers = Router.list(
                              self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         True,
                         "List Routers should return a valid list"
                         )

        #Stop the router
        router = routers[0]
        self.debug("Stopping the router with ID: %s" % router.id)
        cmd = stopRouter.stopRouterCmd()
        cmd.id = router.id
        self.api_client.stopRouter(cmd)

        service_offering = ServiceOffering.create(
                                                  self.api_client,
                                                  self.services["service_offering_new"]
                                                 )
        self.debug("Changing service offering for the Router %s" % router.id)
        try:
            router = Router.change_service_offering(self.api_client,
				                           router.id,
				                           service_offering.id
				                          )
        except:
            self.fail("Changing service offering failed")

        self.debug("Router %s" % router)
        routers = Router.list(
                              self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True
                              )
        router = routers[0]
        self.assertEqual(
                         router.serviceofferingid,
                         service_offering.id,
                         "Changing service offering failed as id is %s and expected"
                         "is %s" % (router.serviceofferingid, service_offering.id)
                        )
        return

    @attr(tags=["advanced", "intervlan"], required_hardware="false")
    def test_05_destroy_router_after_creating_vpc(self):
        """ Test to destroy the router after creating a VPC
	    """
        # Validate the following
	    # 1. Create a VPC with cidr - 10.1.1.1/16
	    # 2. Destroy the VPC Virtual Router which is created as a result of VPC creation.
        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)
        routers = Router.list(
                              self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         True,
                         "List Routers should return a valid list"
                         )

        Router.destroy( self.api_client,
		        id=routers[0].id
		      )
        Router.destroy( self.api_client,
                id=routers[1].id
              )

        routers = Router.list(
                              self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         False,
                         "List Routers should be empty"
                         )
        return

class TestVPCRouterOneNetwork(cloudstackTestCase):

    @classmethod
    def setUpClass(cls):
        cls._cleanup = []
        cls.testClient = super(TestVPCRouterOneNetwork, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()

        cls.services = Services().services
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client)
        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
        cls.template = get_template(
                            cls.api_client,
                            cls.zone.id,
                            cls.services["ostype"]
                            )
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls.services["virtual_machine"]["template"] = cls.template.id

        cls.service_offering = ServiceOffering.create(
                                            cls.api_client,
                                            cls.services["service_offering"]
                                            )
        cls._cleanup.append(cls.service_offering)
        cls.vpc_off = VpcOffering.create(
                                     cls.api_client,
                                     cls.services["redundant_vpc_offering"]
                                     )
        cls.vpc_off.update(cls.api_client, state='Enabled')
        cls._cleanup.append(cls.vpc_off)

        cls.account = Account.create(
                                     cls.api_client,
                                     cls.services["account"],
                                     admin=True,
                                     domainid=cls.domain.id
                                     )
        cls._cleanup.insert(0, cls.account)

        cls.services["vpc"]["cidr"] = '10.1.1.1/16'
        cls.vpc = VPC.create(
                         cls.api_client,
                         cls.services["vpc"],
                         vpcofferingid=cls.vpc_off.id,
                         zoneid=cls.zone.id,
                         account=cls.account.name,
                         domainid=cls.account.domainid
                         )

        cls.nw_off = NetworkOffering.create(
                                            cls.api_client,
                                            cls.services["network_offering"],
                                            conservemode=False
                                            )
        # Enable Network offering
        cls.nw_off.update(cls.api_client, state='Enabled')
        cls._cleanup.append(cls.nw_off)

        # Creating network using the network offering created
        cls.network_1 = Network.create(
                                cls.api_client,
                                cls.services["network"],
                                accountid=cls.account.name,
                                domainid=cls.account.domainid,
                                networkofferingid=cls.nw_off.id,
                                zoneid=cls.zone.id,
                                gateway='10.1.1.1',
                                vpcid=cls.vpc.id
                                )

        # Spawn an instance in that network
        vm_1 = VirtualMachine.create(
                                  cls.api_client,
                                  cls.services["virtual_machine"],
                                  accountid=cls.account.name,
                                  domainid=cls.account.domainid,
                                  serviceofferingid=cls.service_offering.id,
                                  networkids=[str(cls.network_1.id)]
                                  )
        vm_2 = VirtualMachine.create(
                                  cls.api_client,
                                  cls.services["virtual_machine"],
                                  accountid=cls.account.name,
                                  domainid=cls.account.domainid,
                                  serviceofferingid=cls.service_offering.id,
                                  networkids=[str(cls.network_1.id)]
                                  )

        # Spawn an instance in that network
        vm_3 = VirtualMachine.create(
                                  cls.api_client,
                                  cls.services["virtual_machine"],
                                  accountid=cls.account.name,
                                  domainid=cls.account.domainid,
                                  serviceofferingid=cls.service_offering.id,
                                  networkids=[str(cls.network_1.id)]
                                  )

        vms = VirtualMachine.list(
                                  cls.api_client,
                                  account=cls.account.name,
                                  domainid=cls.account.domainid,
                                  listall=True
                                  )

        public_ip_1 = PublicIPAddress.create(
                                cls.api_client,
                                accountid=cls.account.name,
                                zoneid=cls.zone.id,
                                domainid=cls.account.domainid,
                                networkid=cls.network_1.id,
                                vpcid=cls.vpc.id
                                )

        nat_rule = NATRule.create(
                                  cls.api_client,
                                  vm_1,
                                  cls.services["natrule"],
                                  ipaddressid=public_ip_1.ipaddress.id,
                                  openfirewall=False,
                                  networkid=cls.network_1.id,
                                  vpcid=cls.vpc.id
                                  )

        nwacl_nat = NetworkACL.create(
                                         cls.api_client,
                                         networkid=cls.network_1.id,
                                         services=cls.services["natrule"],
                                         traffictype='Ingress'
                                         )

        public_ip_2 = PublicIPAddress.create(
                                cls.api_client,
                                accountid=cls.account.name,
                                zoneid=cls.zone.id,
                                domainid=cls.account.domainid,
                                networkid=cls.network_1.id,
                                vpcid=cls.vpc.id
                                )

        public_ips = PublicIPAddress.list(
                                    cls.api_client,
                                    networkid=cls.network_1.id,
                                    listall=True,
                                    isstaticnat=True,
                                    account=cls.account.name,
                                    domainid=cls.account.domainid
                                  )
        public_ip_3 = PublicIPAddress.create(
                                cls.api_client,
                                accountid=cls.account.name,
                                zoneid=cls.zone.id,
                                domainid=cls.account.domainid,
                                networkid=cls.network_1.id,
                                vpcid=cls.vpc.id
                                )

        lb_rule = LoadBalancerRule.create(
                                    cls.api_client,
                                    cls.services["lbrule"],
                                    ipaddressid=public_ip_3.ipaddress.id,
                                    accountid=cls.account.name,
                                    networkid=cls.network_1.id,
                                    vpcid=cls.vpc.id,
                                    domainid=cls.account.domainid
                                )

        lb_rule.assign(cls.api_client, [vm_3])

        nwacl_lb = NetworkACL.create(
                                cls.api_client,
                                networkid=cls.network_1.id,
                                services=cls.services["lbrule"],
                                traffictype='Ingress'
                                )

        nwacl_internet_1 = NetworkACL.create(
                                cls.api_client,
                                networkid=cls.network_1.id,
                                services=cls.services["http_rule"],
                                traffictype='Egress'
                                )

    @classmethod
    def tearDownClass(cls):
        try:
            #Cleanup resources used
            cleanup_resources(cls.api_client, cls._cleanup)
        except Exception as e:
            raise Exception("Warning: Exception during cleanup : %s" % e)
        return

    def setUp(self):
        self.api_client = self.testClient.getApiClient()
        self.cleanup = []
        return

    def tearDown(self):
        try:
            #Clean up, terminate the created network offerings
            cleanup_resources(self.api_client, self.cleanup)
        except Exception as e:
            raise Exception("Warning: Exception during cleanup : %s" % e)

        return

    def validate_vpc_offering(self, vpc_offering):
        """Validates the VPC offering"""

        self.debug("Check if the VPC offering is created successfully?")
        vpc_offs = VpcOffering.list(
                                    self.api_client,
                                    id=vpc_offering.id
                                    )
        self.assertEqual(
                         isinstance(vpc_offs, list),
                         True,
                         "List VPC offerings should return a valid list"
                         )
        self.assertEqual(
                 vpc_offering.name,
                 vpc_offs[0].name,
                "Name of the VPC offering should match with listVPCOff data"
                )
        self.debug(
                "VPC offering is created successfully - %s" %
                                                        vpc_offering.name)
        return

    def validate_vpc_network(self, network, state=None):
        """Validates the VPC network"""

        self.debug("Check if the VPC network is created successfully?")
        vpc_networks = VPC.list(
                                    self.api_client,
                                    id=network.id
                          )
        self.assertEqual(
                         isinstance(vpc_networks, list),
                         True,
                         "List VPC network should return a valid list"
                         )
        self.assertEqual(
                 network.name,
                 vpc_networks[0].name,
                "Name of the VPC network should match with listVPC data"
                )
        if state:
            self.assertEqual(
                 vpc_networks[0].state,
                 state,
                "VPC state should be '%s'" % state
                )
        self.debug("VPC network validated - %s" % network.name)
        return

    def validate_network_rules(self):
        """ Validate network rules
        """
        vms = VirtualMachine.list(
                                  self.api_client,
                                  account=self.account.name,
                                  domainid=self.account.domainid,
                                  listall=True
                                  )
        public_ips = PublicIPAddress.list(
                                          self.api_client,
                                          account=self.account.name,
                                          domainid=self.account.domainid,
                                          listall=True
                                         )
        for vm, public_ip in zip(vms, public_ips):
            try:
                ssh_1 = vm.get_ssh_client(
                                ipaddress=public_ip.ipaddress.ipaddress)
                self.debug("SSH into VM is successfully")

                self.debug("Verifying if we can ping to outside world from VM?")
                # Ping to outsite world
                res = ssh_1.execute("ping -c 1 www.google.com")
                # res = 64 bytes from maa03s17-in-f20.1e100.net (74.125.236.212):
                # icmp_req=1 ttl=57 time=25.9 ms
                # --- www.l.google.com ping statistics ---
                # 1 packets transmitted, 1 received, 0% packet loss, time 0ms
                # rtt min/avg/max/mdev = 25.970/25.970/25.970/0.000 ms
            except Exception as e:
                self.fail("Failed to SSH into VM - %s, %s" %
                                    (public_ip.ipaddress.ipaddress, e))

            result = str(res)
            self.assertEqual(
                             result.count("1 received"),
                             1,
                             "Ping to outside world from VM should be successful"
                             )

    def migrate_router(self, router):
        """ Migrate the router """

        self.debug("Checking if the host is available for migration?")
        hosts = Host.list(self.api_client, zoneid=self.zone.id, type='Routing')

        self.assertEqual(
                         isinstance(hosts, list),
                         True,
                         "List hosts should return a valid list"
                         )
        if len(hosts) < 2:
            raise unittest.SkipTest(
            "No host available for migration. Test requires atleast 2 hosts")

        # Remove the host of current VM from the hosts list
        hosts[:] = [host for host in hosts if host.id != router.hostid]
        host = hosts[0]
        self.debug("Validating if the network rules work properly or not?")

        self.debug("Migrating VM-ID: %s from %s to Host: %s" % (
                                                        router.id,
                                                        router.hostid,
                                                        host.id
                                                        ))
        try:

            #Migrate  the router
            cmd = migrateSystemVm.migrateSystemVmCmd()
            cmd.isAsync = "false"
            cmd.hostid = host.id
            cmd.virtualmachineid = router.id
            self.api_client.migrateSystemVm(cmd)

        except Exception as e:
            self.fail("Failed to migrate instance, %s" % e)

        self.debug("Waiting for Router mgiration ....")
        time.sleep(240)

        #List routers to check state of router
        router_response = list_routers(
                                    self.api_client,
                                    id=router.id
                                    )
        self.assertEqual(
                            isinstance(router_response, list),
                            True,
                            "Check list response returns a valid list"
                        )

        router.hostid = router_response[0].hostid
        self.assertEqual(router.hostid, host.id, "Migration to host %s failed. The router host is"
                         "still %s" % (host.id, router.hostid))
        return

    @attr(tags=["advanced", "intervlan"], required_hardware="false")
    def test_06_migrate_router_after_addition_of_one_guest_network(self):
        """ Test migrate of router after addition of one guest network
	    """
        # Validations
	    #1. Create a VPC with cidr - 10.1.1.1/16
        #2. Add network1(10.1.1.1/24) to this VPC.
        #3. Deploy vm1,vm2 and vm3 such that they are part of network1.
        #4. Create a PF /Static Nat/LB rule for vms in network1.
        #5. Create ingress network ACL for allowing all the above rules from a public ip range on network1.
        #6. Create egress network ACL for network1 to access google.com.
        #7. Create a private gateway for this VPC and add a static route to this gateway.
        #8. Create a VPN gateway for this VPC and add a static route to this gateway.
        #9. Make sure that all the PF,LB and Static NAT rules work as expected.
        #10. Make sure that we are able to access google.com from all the user Vms.
        #11. Make sure that the newly added private gateway's and VPN gateway's static routes work as expected

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)

        routers = Router.list(
                              self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         True,
                         "List Routers should return a valid list"
                         )
        self.migrate_router(routers[0])
        return

    @attr(tags=["advanced", "intervlan"], required_hardware="false")
    def test_07_chg_srv_off_router_after_addition_of_one_guest_network(self):
        """ Test to change service offering of router after addition of one guest network
	    """
        # Validations
	    #1. Create a VPC with cidr - 10.1.1.1/16
        #2. Add network1(10.1.1.1/24) to this VPC.
        #3. Deploy vm1,vm2 and vm3 such that they are part of network1.
        #4. Create a PF /Static Nat/LB rule for vms in network1.
        #5. Create ingress network ACL for allowing all the above rules from a public ip range on network1.
        #6. Create egress network ACL for network1 to access google.com.
        #7. Create a private gateway for this VPC and add a static route to this gateway.
        #8. Create a VPN gateway for this VPC and add a static route to this gateway.
        #9. Make sure that all the PF,LB and Static NAT rules work as expected.
        #10. Make sure that we are able to access google.com from all the user Vms.
        #11. Make sure that the newly added private gateway's and VPN gateway's static routes work as expected

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)

        routers = Router.list(
                              self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         True,
                         "List Routers should return a valid list"
                         )

        #Stop the router
        router = routers[0]
        self.debug("Stopping the router with ID: %s" % router.id)
        cmd = stopRouter.stopRouterCmd()
        cmd.id = router.id
        self.api_client.stopRouter(cmd)

        service_offering = ServiceOffering.create(
                                                  self.api_client,
                                                  self.services["service_offering_new"]
                                                 )
        self.debug("Changing service offering for the Router %s" % router.id)
        try:
            router = Router.change_service_offering(self.api_client,
				                           router.id,
				                           service_offering.id
				                          )
        except:
            self.fail("Changing service offering failed")

        self.debug("Router %s" % router)
        routers = Router.list(
                              self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True
                              )
        router = routers[0]
        self.assertEqual(
                         router.serviceofferingid,
                         service_offering.id,
                         "Changing service offering failed as id is %s and expected"
                         "is %s" % (router.serviceofferingid, service_offering.id)
                        )
        return

    @attr(tags=["advanced", "intervlan"], required_hardware="false")
    def test_08_destroy_router_after_addition_of_one_guest_network(self):
        """ Test destroy of router after addition of one guest network
        """
        # Validations
	    #1. Create a VPC with cidr - 10.1.1.1/16
        #2. Add network1(10.1.1.1/24) to this VPC.
        #3. Deploy vm1,vm2 and vm3 such that they are part of network1.
        #4. Create a PF /Static Nat/LB rule for vms in network1.
        #5. Create ingress network ACL for allowing all the above rules from a public ip range on network1.
        #6. Create egress network ACL for network1 to access google.com.
        #7. Create a private gateway for this VPC and add a static route to this gateway.
        #8. Create a VPN gateway for this VPC and add a static route to this gateway.
        #9. Make sure that all the PF,LB and Static NAT rules work as expected.
        #10. Make sure that we are able to access google.com from all the user Vms.
        #11. Make sure that the newly added private gateway's and VPN gateway's static routes work as expected

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)

        routers = Router.list(
                              self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         True,
                         "List Routers should return a valid list"
                         )

        Router.destroy( self.api_client,
		        id=routers[0].id
		      )

        Router.destroy( self.api_client,
                id=routers[1].id
              )

        routers = Router.list(
                              self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         False,
                         "List Routers should be empty"
                         )
        return


text:
package com.splendidcode.angular.sample.util.builders;

public class Builders {
   public static TodoBuilder newTodo() {
      return new TodoBuilder();
   }

   public static AuthInfoBuilder newAuthInfo() {
      return new AuthInfoBuilder();
   }

   public static AuthInfoFactoryBuilder newAuthInfoFactory() {
      return new AuthInfoFactoryBuilder();
   }

   public static Pbkdf2UtilsBuilder newPbkdf2Utils() {
      return new Pbkdf2UtilsBuilder();
   }

   public static Pbkdf2OptionsBuilder newPbkdf2Options() {
      return new Pbkdf2OptionsBuilder();
   }
}


text:
import copy

from oslo_log import log as logging

LOG = logging.getLogger(__name__)

def make_user_id(emails=None, launchpad_id=None, gerrit_id=None,
                 member_id=None, github_id=None, ldap_id=None):
    if launchpad_id or emails:
        return launchpad_id or emails[0]
    if gerrit_id:
        return 'gerrit:%s' % gerrit_id
    if member_id:
        return 'member:%s' % member_id
    if github_id:
        return 'github:%s' % github_id
    if ldap_id:
        return 'ldap:%s' % ldap_id

def store_user(runtime_storage_inst, user):
    write_flag = False

    if not user.get('seq'):
        user['seq'] = runtime_storage_inst.inc_user_count()
        LOG.debug('New user: %s', user)
        write_flag = True
    else:
        stored_user = runtime_storage_inst.get_by_key(
            'user:%d' % user.get('seq'))
        if stored_user != user:
            LOG.debug('User updated: %s', user)
            write_flag = True

    if not write_flag:
        return

    runtime_storage_inst.set_by_key('user:%d' % user['seq'], user)
    if user.get('user_id'):
        runtime_storage_inst.set_by_key('user:%s' % user['user_id'], user)
    if user.get('launchpad_id'):
        runtime_storage_inst.set_by_key('user:%s' % user['launchpad_id'], user)
    if user.get('gerrit_id'):
        runtime_storage_inst.set_by_key('user:gerrit:%s' % user['gerrit_id'],
                                        user)
    if user.get('github_id'):
        runtime_storage_inst.set_by_key('user:github:%s' % user['github_id'],
                                        user)
    if user.get('ldap_id'):
        runtime_storage_inst.set_by_key('user:ldap:%s' % user['ldap_id'],
                                        user)
    for email in user.get('emails') or []:
        runtime_storage_inst.set_by_key('user:%s' % email, user)

def load_user(runtime_storage_inst, seq=None, user_id=None, email=None,
              launchpad_id=None, gerrit_id=None, member_id=None,
              github_id=None, ldap_id=None):
    if gerrit_id:
        key = 'gerrit:%s' % gerrit_id
    elif member_id:
        key = 'member:%s' % member_id
    elif github_id:
        key = 'github:%s' % github_id
    elif ldap_id:
        key = 'ldap:%s' % ldap_id
    else:
        key = seq or user_id or launchpad_id or email
    if key:
        return runtime_storage_inst.get_by_key('user:%s' % key)
    return None

def delete_user(runtime_storage_inst, user):
    LOG.debug('Delete user: %s', user)
    runtime_storage_inst.delete_by_key('user:%s' % user['seq'])

def update_user_profile(stored_user, user):
    # update stored_user with user and return it
    if stored_user:
        updated_user = copy.deepcopy(stored_user)
        updated_user.update(user)
        updated_user['emails'] = list(set(stored_user.get('emails', [])) |
                                      set(user.get('emails', [])))
    else:
        updated_user = copy.deepcopy(user)
    updated_user['static'] = True
    return updated_user


text:
package components

import (
	"github.com/flowbase/flowbase"
	"testing"
)

// TestNewMWXMLCreator tests NewMWXMLCreator
func TestNewMWXMLCreator(t *testing.T) {
	flowbase.InitLogDebug()

	mxc := NewMWXMLCreator(true)

	if mxc.InWikiPage == nil {
		t.Error("InWikiPage is not initialized")
	}
	if mxc.OutTemplates == nil {
		t.Error("OutTemplates is not initialized")
	}
	if mxc.OutProperties == nil {
		t.Error("OutProperties is not initialized")
	}
	if mxc.OutPages == nil {
		t.Error("OutPages is not initialized")
	}
	if mxc.UseTemplates != true {
		t.Error("UseTemplates field is initialized wrongly")
	}
}


text:
from neutron.common import constants
from neutron.common import utils
from neutron.plugins.ml2.drivers.linuxbridge.agent import arp_protect
from neutron.tests.common import machine_fixtures
from neutron.tests.common import net_helpers
from neutron.tests.functional import base as functional_base

no_arping = net_helpers.assert_no_arping
arping = net_helpers.assert_arping

class LinuxBridgeARPSpoofTestCase(functional_base.BaseSudoTestCase):

    def setUp(self):
        super(LinuxBridgeARPSpoofTestCase, self).setUp()

        lbfixture = self.useFixture(net_helpers.LinuxBridgeFixture())
        self.addCleanup(setattr, arp_protect, 'NAMESPACE', None)
        arp_protect.NAMESPACE = lbfixture.namespace
        bridge = lbfixture.bridge
        self.source, self.destination, self.observer = self.useFixture(
            machine_fixtures.PeerMachines(bridge, amount=3)).machines
        self.addCleanup(self._ensure_rules_cleaned)

    def _ensure_rules_cleaned(self):
        rules = [r for r in arp_protect.ebtables(['-L']).splitlines()
                 if r and 'Bridge' not in r]
        self.assertEqual([], rules, 'Test leaked ebtables rules')

    def _add_arp_protection(self, machine, addresses, extra_port_dict=None):
        port_dict = {'fixed_ips': [{'ip_address': a} for a in addresses],
                     'device_owner': 'nobody',
                     'mac_address': machine.port.link.address}
        if extra_port_dict:
            port_dict.update(extra_port_dict)
        name = net_helpers.VethFixture.get_peer_name(machine.port.name)
        arp_protect.setup_arp_spoofing_protection(name, port_dict)
        self.addCleanup(arp_protect.delete_arp_spoofing_protection,
                        [name])

    def test_arp_no_protection(self):
        arping(self.source.namespace, self.destination.ip)
        arping(self.destination.namespace, self.source.ip)

    def test_arp_correct_protection(self):
        self._add_arp_protection(self.source, [self.source.ip])
        self._add_arp_protection(self.destination, [self.destination.ip])
        arping(self.source.namespace, self.destination.ip)
        arping(self.destination.namespace, self.source.ip)

    def test_arp_correct_protection_allowed_address_pairs(self):
        smac = self.source.port.link.address
        port = {'mac_address': '00:11:22:33:44:55',
                'allowed_address_pairs': [{'mac_address': smac,
                                           'ip_address': self.source.ip}]}
        # make sure a large number of allowed address pairs works
        for i in range(100000):
            port['allowed_address_pairs'].append(
                {'mac_address': utils.get_random_mac(
                     'fa:16:3e:00:00:00'.split(':')),
                 'ip_address': '10.10.10.10'})
        self._add_arp_protection(self.source, ['1.2.2.2'], port)
        self._add_arp_protection(self.destination, [self.destination.ip])
        arping(self.source.namespace, self.destination.ip)
        arping(self.destination.namespace, self.source.ip)

    def test_arp_fails_incorrect_protection(self):
        self._add_arp_protection(self.source, ['1.1.1.1'])
        self._add_arp_protection(self.destination, ['2.2.2.2'])
        no_arping(self.source.namespace, self.destination.ip)
        no_arping(self.destination.namespace, self.source.ip)

    def test_arp_fails_incorrect_mac_protection(self):
        # a bad mac filter on the source will prevent any traffic from it
        self._add_arp_protection(self.source, [self.source.ip],
                                 {'mac_address': '00:11:22:33:44:55'})
        no_arping(self.source.namespace, self.destination.ip)
        no_arping(self.destination.namespace, self.source.ip)
        # correcting it should make it work
        self._add_arp_protection(self.source, [self.source.ip])
        arping(self.source.namespace, self.destination.ip)

    def test_arp_protection_removal(self):
        self._add_arp_protection(self.source, ['1.1.1.1'])
        self._add_arp_protection(self.destination, ['2.2.2.2'])
        no_arping(self.observer.namespace, self.destination.ip)
        no_arping(self.observer.namespace, self.source.ip)
        name = net_helpers.VethFixture.get_peer_name(self.source.port.name)
        arp_protect.delete_arp_spoofing_protection([name])
        # spoofing should have been removed from source, but not dest
        arping(self.observer.namespace, self.source.ip)
        no_arping(self.observer.namespace, self.destination.ip)

    def test_arp_protection_update(self):
        self._add_arp_protection(self.source, ['1.1.1.1'])
        self._add_arp_protection(self.destination, ['2.2.2.2'])
        no_arping(self.observer.namespace, self.destination.ip)
        no_arping(self.observer.namespace, self.source.ip)
        self._add_arp_protection(self.source, ['192.0.0.0/1'])
        # spoofing should have been updated on source, but not dest
        arping(self.observer.namespace, self.source.ip)
        no_arping(self.observer.namespace, self.destination.ip)

    def test_arp_protection_port_security_disabled(self):
        self._add_arp_protection(self.source, ['1.1.1.1'])
        no_arping(self.observer.namespace, self.source.ip)
        self._add_arp_protection(self.source, ['1.1.1.1'],
                                 {'port_security_enabled': False})
        arping(self.observer.namespace, self.source.ip)

    def test_arp_protection_network_owner(self):
        self._add_arp_protection(self.source, ['1.1.1.1'])
        no_arping(self.observer.namespace, self.source.ip)
        self._add_arp_protection(self.source, ['1.1.1.1'],
                                 {'device_owner':
                                  constants.DEVICE_OWNER_ROUTER_GW})
        arping(self.observer.namespace, self.source.ip)

    def test_arp_protection_dead_reference_removal(self):
        self._add_arp_protection(self.source, ['1.1.1.1'])
        self._add_arp_protection(self.destination, ['2.2.2.2'])
        no_arping(self.observer.namespace, self.destination.ip)
        no_arping(self.observer.namespace, self.source.ip)
        name = net_helpers.VethFixture.get_peer_name(self.source.port.name)
        # This should remove all arp protect rules that aren't source port
        arp_protect.delete_unreferenced_arp_protection([name])
        no_arping(self.observer.namespace, self.source.ip)
        arping(self.observer.namespace, self.destination.ip)


text:
package com.google.security.zynamics.binnavi.Gui.GraphWindows.Panels;

/**
 * This package contains classes that define the standard GUI perspective and the debug GUI
 * perspective of the graph window. The user can switch between these two perspectives like you can
 * switch between perspectives in Eclipse.
 */