text:
@interface WebViewController() <UISearchBarDelegate, WKNavigationDelegate>

@property (weak, nonatomic) IBOutlet UIButton *genericpasswordFillButton;
@property (weak, nonatomic) IBOutlet UIView *webViewContainer;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (strong, nonatomic) WKWebView *webView;

@end

@implementation WebViewController

#pragma mark - Life Cycle

- (void)viewDidLoad {
	[self.genericpasswordFillButton setHidden:![[GenericPasswordExtension sharedExtension] isAppExtensionAvailable]];

	WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
	self.webView = [[WKWebView alloc] initWithFrame:self.webViewContainer.bounds configuration:configuration];
	self.webView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
	self.webView.navigationDelegate = self;
	[self.webViewContainer addSubview:self.webView];

	NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"welcome" ofType:@"html"];
	NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
	[self.webView loadHTMLString:htmlString baseURL:nil];
}

#pragma mark - Actions

- (IBAction)fillUsingGenericPassword:(id)sender {
	[[GenericPasswordExtension sharedExtension] fillLoginIntoWebView:self.webView forViewController:self sender:sender completion:^(BOOL success, NSError *error) {
		if (!success) {
			NSLog(@"Failed to fill login in webview: <%@>", error);
		}
	}];
}

- (IBAction)goBack:(id)sender {
	WKNavigation *navigation = [self.webView goBack];

	if (!navigation) {
		NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"welcome" ofType:@"html"];
		NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
		[self.webView loadHTMLString:htmlString baseURL:nil];

	}
}

- (IBAction)goForward:(id)sender {
	[self.webView goForward];
}

#pragma mark - UISearchBarDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
	[self loadURLString:searchBar.text];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
	[self loadURLString:searchBar.text];
}

- (void)handleSearch:(UISearchBar *)searchBar {
	[self loadURLString:searchBar.text];
	[searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
	[self loadURLString:searchBar.text];
	[searchBar resignFirstResponder];
}

#pragma mark - Convenience Methods

- (void)loadURLString:(NSString *)URLString {
	if (![URLString hasPrefix:@"http"]) {
		URLString = [NSString stringWithFormat:@"https://%@", URLString];
	}

	NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:URLString]];
	[self.webView loadRequest:request];

	self.searchBar.text = URLString;
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
	self.searchBar.text = webView.URL.absoluteString;

	if ([self.searchBar.text isEqualToString:@"about:blank"]) {
		self.searchBar.text = @"";
	}
}

@end


text:
$| = 1;
use strict;

# Print command line.
print "Command: $0";
foreach my $arg (@ARGV){
   print " $arg";
}
print "\n\n";

use Getopt::Long ':config',
                  'no_auto_abbrev', # Impossible to use -s for --source.
                  'no_ignore_case'  # Case sensitive options.
;

# Use perl modules from here or BASEGENFILESPATH/script/perllib
# use lib "fullpath/genfiles/script/perllib";
use lib ".";
use PerlTools;
use PerlWASPTools;
use POIObject;

use vars qw( $opt_help $opt_verbose $opt_quiet
             $opt_setPosFromPrevSource
             $opt_setSourceInUse
             $opt_setSourceNotInUse
             $opt_setPOICategoryFromPOIType
             $opt_rmPoisOfSource
             $opt_rmStaticOfSource
             $opt_rmCategoriesOfSource
             $opt_rmEntryPtsOfSource
             $opt_setSourceProductRights
             $opt_poiSource
             $opt_poiCountry
             $opt_poiIdMin
             $opt_poiIdMax
             $opt_setNullValidTo
             $opt_noUpdateValidTo
             $opt_exportPOIsWithNoPos
             $opt_geocFile
             $opt_importPosFromGeocodeResult
);
GetOptions('help|h',
           'verbose|v',
           'quiet',
           # Function options
           'setPosFromPrevSource',
           'setSourceInUse',
           'setSourceNotInUse',
           'setPOICategoryFromPOIType',
           'rmPoisOfSource',
           'rmStaticOfSource',
           'rmCategoriesOfSource',
           'rmEntryPtsOfSource',
           'setSourceProductRights',
           # Indata options
           'poiSource=s',
           'poiCountry=s',
           'poiIdMin=s',
           'poiIdMax=s',
           'setNullValidTo',
           'noUpdateValidTo',
           'exportPOIsWithNoPos',
           'geocFile=s',
           'importPosFromGeocodeResult',
           ) or die "Use -help for help.";

# Print help message.
if ( $opt_help ){
   print "USAGE poi_admin COMMAND_OPTION [PARAMETER_OPTIONS]

COMMAND OPTIONS:

-setPosFromPrevSource
Valid parameters:  -poiSource
Takes all POIs of source -poiSource with no symbol coordinates and sets the
symbol coordinate to the symbol coordinate from corresponding POI of prevoius
POI source. Symbol coordinate = POIMain.lat and POIMain.lon.

-setSourceInUse
Function -setSourceInUse sets inUse value for the source -poiSource to true. It has to have one of the following mandatory options -noUpdateValidTo or -setNullValidTo set.
If option -setNullValidTo is defined, it will set validToVersion to NULL for all pois of the source.
If validToVersion should not be set (modified), give the option -noUpdateValidTo.

-setSourceNotInUse
Function -setSourceNotInUse compares current -poiSource with next source of product. The comparision is done per country of -poiSource.
If validFromVersion is equal, it sets inUse to false.
If validFromVersion differs, validToVersion of -poiSource and current country will be set to validFromVersion of next source - 1 (minus one).
The option -setSourceNotInUse can have additional option -noUpdateValidTo which will only set inUse to false on all records of the source, and keep validToVersion unchanged.

-setPOICategoryFromPOIType
Function -setPOICategoryFromPOIType will check POIs for source -poiSource and if POI has no category set, will try to set a category from POIType.

-rmPoisOfSource
Removes all POI data from the database of POIs with source matching the POI source given by mandatory option -poiSource and country given by mandatory option -poiCountry. Use optional option -poiIdMin and/or -poiIdMax, if you want to remove only the latest added POIs of a source.

-rmStaticOfSource
Removes all static POI data from the POIStatic table  POIs with source matching the POI source given by mandatory option -poiSource and country given by mandatory option -poiCountry.

-rmCategoriesOfSource
Removes all Category POI data from the POICategories table  POIs with source matching the POI source given by mandatory option -poiSource and country given by mandatory option -poiCountry.

-rmEntryPtsOfSource
Removes all entry points from the POIEntryPoints table  POIs with source matching the POI source given by mandatory option -poiSource and country given by mandatory option -poiCountry.

-setSourceProductRights
Sets the defaultMapRight for all POIs in a source according to the product it belongs to.

-exportPOIsWithNoPos
Exports POIs in source -poiSource and country -poiCountry that don't have coordinates, to a geocoding file \"-geocFile\".

-importPosFromGeocodeResult
Reads geocoded file -geocFile and for POIs with coordinates, updates POI if it has no coordinates for source -poiSource and country -poiCountry.

PARAMETER OPTIONS:

-poiSource POI_SOURCE_WASP_NAME
Give the WASP name of the POI source.

-poiCountry POI_COUNTRY_ISO3166_1_ALPHA2
Give the ISo 3166-1 Alfa 2 code of the country. Give value \"xx\" for all countries.

-poiIdMin WASP_ID
The ID of POIMain.ID. The lowest ID of the WASP database that will be affected. Only a few command options take this parameter option.

-poiIdMax WASP_ID
The ID of POIMain.ID. The largest ID of the WASP database that will be affected. Only a few command options take this parameter option.

-geocFile filename
Filename to write file to geocode to / to read coordinates from.

";
   exit;
}

# Print methods
##############################################################################
if ( defined($opt_quiet) && defined($opt_verbose) ){
   errprint("Can't combine -verbose and -quiet options.");
   exit 1;
}
sub dprint1(@){
   if ( ! $opt_quiet ){
      dbgprint(@_);
   }
};
sub dprint2(@){
   if ( $opt_verbose ){
      my @printArray = ();
      foreach my $elm (@_) {
         push @printArray, split("\n", $elm);
      }
      foreach my $row (@printArray) {
         $row =~ s/^/[v] /;
         $row =~ s/$/\n/;
      }
      if (scalar(@printArray) > 0 ){
         # Remove last new line.
         chomp ($printArray[scalar(@printArray-1)]);
      }
      dbgprint(@printArray);
   }
};

# Some variables set from parameter options
my $sourceID;
my $sourceName;
my $sourceID2;
my $sourceName2;
my $productID;
my $productName;
my $productTrustSrcRef;
my $prevSourceID;
my $prevSourceName;
my $countryID;
my $countryName;
my $geocFile;
my $waspDbh = db_connect();

#Handle parameter options
##############################################################################
if ( $opt_setPosFromPrevSource ||
     $opt_rmPoisOfSource ||
     $opt_rmStaticOfSource ||
     $opt_rmCategoriesOfSource ||
     $opt_rmEntryPtsOfSource ||
     $opt_setSourceInUse ||
     $opt_setSourceNotInUse ||
     $opt_setPOICategoryFromPOIType ||
     $opt_setSourceProductRights ||
     $opt_exportPOIsWithNoPos ||
     $opt_importPosFromGeocodeResult ){
   if (!defined($opt_poiSource)){
      errprint "Missing value for -poiSource";
      die;
   }

   # Fetch POI source ID and product.
   my $query =
       "SELECT POISources.ID, source, productID,".
       " productName, trustedSourceRef" .
       " FROM POISources, POIProducts WHERE source = '$opt_poiSource' AND" .
       " productID = POIProducts.ID";
   dprint2 $query;
   my $sth = $waspDbh->prepare( $query );
   $sth->execute() or die "Could not execute query";
   if ( $sth->rows == 0 ){
      dprint1("Query: $query");
      errprint("Invalid --poiSource: $opt_poiSource");
      exit 1;
   }
   elsif ( $sth->rows > 1 ){
      # This is very strange
      dprint1("Query: $query");
      errprint("Ambigous --poiSource: $opt_poiSource");
      exit 1;
   }
   ($sourceID,
    $sourceName,
    $productID,
    $productName,
    $productTrustSrcRef ) = $sth->fetchrow();
   dprint1 "POI source:  $sourceName ($sourceID)";
   dprint1 "POI product: $productName ($productID)";

   ($prevSourceID, $prevSourceName) = getPrevPoiSource($waspDbh,
                                                       $sourceID);
}
if ( $opt_rmPoisOfSource || $opt_rmStaticOfSource ||
      $opt_rmCategoriesOfSource || $opt_rmEntryPtsOfSource ||
      $opt_exportPOIsWithNoPos || $opt_importPosFromGeocodeResult ){
   # Handle country.
   if (!defined($opt_poiCountry)){
      errprint("Missing option -poiCountry");
      die;
   }
   if ( $opt_poiCountry eq "xx" ){
      # Country code xx means all countries.
      $countryID = 0xffffffff;
      $countryName = "All countries";
   }
   else {
      my $upperCaseCountryCode = uc($opt_poiCountry);
      my $query =
          "SELECT ID, country" .
          " FROM POICountries WHERE iso3166_1_alpha2 = '$upperCaseCountryCode';";
      dprint2 $query;
      my $sth = $waspDbh->prepare( $query );
      $sth->execute() or die "Could not execute query";
      if ( $sth->rows == 0 ){
         dprint1("Query: $query");
         errprint("Invalid -poiCountry: $opt_poiCountry");
         exit 1;
      }
      elsif ( $sth->rows > 1 ){
         # This is very strange
         dprint1("Query: $query");
         errprint("Ambigous -poiCountry: $opt_poiCountry");
         exit 1;
      }
      ($countryID, $countryName) = $sth->fetchrow();
   }
   dprint1 "POI country: $countryName ($countryID)";
}

# check input geocFile
if ( $opt_exportPOIsWithNoPos || $opt_importPosFromGeocodeResult ) {
   if (defined $opt_geocFile and $opt_geocFile ne '') {
      if ($opt_exportPOIsWithNoPos) {
         if (!-e $opt_geocFile) {
            $geocFile = $opt_geocFile;
         } else {
            errprint("File $opt_geocFile exists, use new filename\n");
            exit 1;
         }
      } elsif ($opt_importPosFromGeocodeResult) {
         if (!-e $opt_geocFile) {
            errprint("Can not find file with coordinates: $opt_geocFile. Exiting.\n");
            exit 1;
         } else {
            $geocFile = $opt_geocFile;
         }
      }
   } else {
      errprint("Need input on filename for geocode file\n");
      exit 1;
    }
}

# Handle commands.
##############################################################################
#=============================================================================
if ( $opt_setPosFromPrevSource ){
   # Check sanity
   if ( ! defined $sourceID ){
      errprint "No source, exits";
      exit 1;
   }
   if ( ! defined $prevSourceID ){
      errprint "No previous source, exits";
      exit 1;
   }
   if ( ! defined $productTrustSrcRef ){
      errprint "This product has not a trusted source ref, it is vital for ".
          "this operation, exits";
      exit 1;
   }

   # Fetch the IDs of POIs with no symbol coordinate.
   my @poiIdAndStatics = ();
   my $query =
       "SELECT POIMain.ID, POIStatic.staticID".
       " FROM POIMain, POIStatic".
       " WHERE".
       " POIMain.source = $sourceID AND".
       " POIMain.lat IS NULL AND".
       " POIMain.lon IS NULL AND".
       " POIMain.ID = POIStatic.poiID;";
   dprint2 $query;
   my $sth = $waspDbh->prepare( $query );
   $sth->execute() or die "Failed: $query";;
   my $nbrNoPosPOIs = $sth->rows;
   dprint1 "Found ". $nbrNoPosPOIs . " POIs with no position.";
   while ( (my $poiID, my $staticID) = $sth->fetchrow()) {
      my %poiIdAndStatic = ('poiID' => $poiID,
                            'staticID' => $staticID);
      push(@poiIdAndStatics, \%poiIdAndStatic);
   }

   # Find the corresponding POIs from previous source and set the symbol
   # coordinate from it.
   my $nbrPositionsSet = 0;
   foreach my $poiIdAndStatic (sort(@poiIdAndStatics)){
      $query =
          "SELECT POIMain.ID, POIMain.lat, POIMain.lon".
          " FROM POIMain, POIStatic".
          " WHERE".
          " POIStatic.staticID = $poiIdAndStatic->{'staticID'} AND".
          " POIMain.source = $prevSourceID AND".
          " POIMain.lat IS NOT NULL AND".
          " POIMain.lon IS NOT NULL AND".
          " POIMain.deleted != 1 AND".
       " POIMain.ID = POIStatic.poiID;";

      dprint2 $query;
      $sth = $waspDbh->prepare( $query );
      $sth->execute() or die "Failed: $query";;
      if ( $sth->rows == 0 ){
         dprint1("No prev source POI for WASP ID: $poiIdAndStatic->{'poiID'}");
      }
      elsif ( $sth->rows > 1 ){
         # This is very strange
         dprint1("Query: $query");
         dprint1("Dumping ambigues hits");
         while ( (my $poiID, my $lat, my $lon) = $sth->fetchrow()) {
            dprint1("  $poiID");
         }
         errprint("Ambigous prev source POI for WASP ID: ".
                  "$poiIdAndStatic->{'poiID'}");
         exit 1;
      }
      else {
         # All is fine
         (my $poiID,
          my $lat,
          my $lon ) = $sth->fetchrow();
         $nbrPositionsSet++;
         $query = "UPDATE POIMain".
             " SET lat = $lat, lon = $lon".
             " WHERE ID = $poiIdAndStatic->{'poiID'}";
         $sth = $waspDbh->prepare( $query );
         $sth->execute() or die "Failed: $query";;
         dprint1("Old ID: $poiID, new ID: $poiIdAndStatic->{'poiID'},".
                 " Updated pos:($lat,$lon)");
      }
   }
   dprint1 "Set position on " . $nbrPositionsSet . " of ". $nbrNoPosPOIs;
}
#
#
#
#=============================================================================
elsif ( $opt_setSourceProductRights ){
   timeprint "";
   timeprint "Updating rights in POIMain from defaultMapRight for their product.";
   if (!defined($sourceID) || !defined($sourceName)){
      errprint "Something wrong with mandatory option -poiSource";
      exit 1;
   }
   if (!defined($productID) || !defined($productName)){
      errprint "Something wrong with poiProduct";
      exit 1;
   }
   my $query = "SELECT defaultMapRight FROM POIProducts WHERE " .
         "ID = ?";
   dprint2 $query;
   my $sth = $waspDbh->prepare( $query );
   $sth->execute($productID) or die "Failed: $query";;
   if ( $sth->rows == 0 ){
      dprint1("Query: $query");
      errprint("Invalid poiProduct: $productName");
      exit 1;
   }
   elsif ( $sth->rows > 1 ){
      # This is very strange
      dprint1("Query: $query");
      errprint("Ambigous -poiProduct: $productName");
      exit 1;
   }
   my ($defaultMapRight) = $sth->fetchrow();

   timeprint "Updates value of rights of the POIs.";
   $query =
       "UPDATE POIMain".
       " SET rights = '$defaultMapRight', lastModified = now()".
       " WHERE source = $sourceID and rights != '$defaultMapRight';";
   dprint2 $query;
   $sth = $waspDbh->prepare( $query );
   $sth->execute() or die "Failed: $query";;
   timeprint "Done!";

}
#
#
#
#=============================================================================
elsif ( $opt_setPOICategoryFromPOIType ) {
   timeprint "";
   timeprint "Adding categories to POICategories using values in POIType.";
   if (!defined($sourceID) || !defined($sourceName)){
      errprint "Something wrong with mandatory option -poiSource";
      exit 1;
   }
   my $query = "SELECT ID, typeID FROM POIMain left join POITypes " .
         " on POIMain.ID = POITypes.poiID WHERE " .
         "source = $sourceID";
   my $catQuery = "SELECT catID FROM POICategories WHERE poiID = ?";
   my $catSth = $waspDbh->prepare( $catQuery );
   my $sth = $waspDbh->prepare( $query );
   my $insertQuery = "INSERT INTO POICategories set poiID=?, catID=?";
   my $insertSth = $waspDbh->prepare( $insertQuery );
   $sth->execute() or die "Failed: $query";
   while (my ($poiID, $typeID) = $sth->fetchrow()) {
      $catSth->execute($poiID) or die "Failed $catQuery, $poiID";
      if ($catSth->rows == 0) {
         my $categoryID = getPOICatFromPOIType($waspDbh, $typeID);
         if (defined $categoryID) {
            $insertSth->execute($poiID, $categoryID) or die "Failed $insertQuery";
            dprint1("$insertQuery");
            dprint1("\tfound category, poiID=$poiID, typeID=$typeID, category=$categoryID");
         }
      } else {
         dprint1("POI with ID $poiID already has a category. Skipping.");
      }
   }
}
#
#
#
#=============================================================================
elsif ( $opt_rmPoisOfSource ){
   timeprint "";
   timeprint "Removing POIs from database.";
   if (!defined($sourceID) || !defined($sourceName)){
      errprint "Something wrong with mandatory option -poiSource";
      exit 1;
   }
   if (!defined($countryID) || !defined($countryName)){
      errprint "Something wrong with mandatory option -poiCountry";
      exit 1;
   }
   my $deleteMode = "allTables";
   handleDeletePOIsFromSource($sourceID,
                              $sourceName,
                              $countryID,
                              $deleteMode,
                              $opt_poiIdMin,
                              $opt_poiIdMax);
}
#
#
#
#=============================================================================
elsif ( $opt_rmStaticOfSource ){
   timeprint "";
   timeprint "Removing static from POIStatic.";
   if (!defined($sourceID) || !defined($sourceName)){
      errprint "Something wrong with mandatory option -poiSource";
      exit 1;
   }
   if (!defined($countryID) || !defined($countryName)){
      errprint "Something wrong with mandatory option -poiSource";
      exit 1;
   }
   my $deleteMode = "onlyStatic";
   handleDeletePOIsFromSource($sourceID, $sourceName, $countryID, $deleteMode);
}
#
#
#
#=============================================================================
elsif ( $opt_rmCategoriesOfSource ){
   timeprint "";
   timeprint "Removing categories from POICategories.";
   if (!defined($sourceID) || !defined($sourceName)){
      errprint "Something wrong with mandatory option -poiSource";
      exit 1;
   }
   if (!defined($countryID) || !defined($countryName)){
      errprint "Something wrong with mandatory option -poiSource";
      exit 1;
   }
   my $deleteMode = "onlyCategories";
   handleDeletePOIsFromSource($sourceID, $sourceName, $countryID, $deleteMode);
}
#
#
#
#=============================================================================
elsif ( $opt_rmEntryPtsOfSource ){
   timeprint "";
   timeprint "Removing entry points from POIEntryPoints.";
   if (!defined($sourceID) || !defined($sourceName)){
      errprint "Something wrong with mandatory option -poiSource";
      exit 1;
   }
   if (!defined($countryID) || !defined($countryName)){
      errprint "Something wrong with mandatory option -poiSource";
      exit 1;
   }
   my $deleteMode = "onlyEntryPts";
   handleDeletePOIsFromSource($sourceID, $sourceName, $countryID, $deleteMode);
}
#
#
#
#=============================================================================
elsif ( $opt_setSourceInUse || $opt_setSourceNotInUse ){
   # Handle in parameters.
   if (!defined($sourceID) || !defined($sourceName)){
      errprint "Something wrong with mandatory option -poiSource";
      exit 1;
   }
   my $inUseVal = 0;
   my $inUseStr = "false";
   my $update_valid_to = 0;
   my $valid_to_value;
   my $valid_to_statement = "";
   my $nextSourceID;
   my $nextSourceName;
   my @countriesOfSource;
   my $thisCountryValidFromVersion;
   my $nextCountryValidFromVersion;
   my $newValidToVersion;
   my $update_in_use_query;
   my $update_valid_to_query;
   my $update_in_use_sth;
   my $update_valid_to_sth;
   my $inUseProblem = 0;
   my %update_inuse_hash;
   my %update_validto_hash;
   my $something_to_change = 0;

   if ( $opt_setSourceInUse && $opt_setSourceNotInUse ){
      errprint "Cannot set both -setSourceInUse and -setSourceNotInUse at".
          " the same time";
      exit 1;
   }
   if ($opt_setSourceInUse) {
      if ($opt_setNullValidTo && $opt_noUpdateValidTo) {
         errprint "Cannot select both -setNullValidTo and -noUpdateValidTo " .
            "at the same time";
         exit 1;
      }
      if (!$opt_setNullValidTo && !$opt_noUpdateValidTo) {
         errprint "When doing -setSourceInUse, need to give option " .
            "-setNullValidTo or -noUpdateValidTo";
         exit 1;
      }
   }
   # print and get current values of inUse
   my ($currentInUse, $all_inuse_value) = getInUseInfoFromSource($waspDbh, $sourceID);

   if ( $opt_setSourceInUse ){
      if ($opt_setNullValidTo || $opt_noUpdateValidTo) {
         $inUseVal = 1;
         $inUseStr = "true";

         if ($all_inuse_value == 1) {
            errprint "You want to set inUse to $inUseStr but it is already $inUseVal. Exiting.";
            exit 1;
         }

         if ($opt_setNullValidTo) {
            $update_valid_to = 1;
            $valid_to_value = "NULL";
            $valid_to_statement = "validToVersion = $valid_to_value, ";
         }
         # selection is to set inUse to true
         dbgprint "You have selected to set inUse to $inUseStr ";
         if ($update_valid_to) {
            dbgprint "and $valid_to_statement for source $sourceID.";
         }
      }
      # This continues below, after the elsif

   } elsif ($opt_setSourceNotInUse) {

      if (! $opt_noUpdateValidTo) {
         @countriesOfSource = getCountriesOfSource($waspDbh, $sourceID);
         if (scalar(@countriesOfSource) > 0) {
            ($nextSourceID, $nextSourceName) = getNextPoiSource($waspDbh, $sourceID);
            if (defined $nextSourceID) {
               dbgprint "Will set validToVersion per country.";
               timeprint "";

               $update_in_use_query = "UPDATE POIMain SET inUse = $inUseVal, " .
                  "lastModified=now() WHERE " .
                  "source = $sourceID AND country = ?";
               $update_in_use_sth = $waspDbh->prepare($update_in_use_query) or die "Could not prepare query: $update_in_use_query";

               $update_valid_to_query = "UPDATE POIMain SET " .
                  "validToVersion = ?, lastModified=now() WHERE " .
                  "source = $sourceID AND country = ?";
               $update_valid_to_sth = $waspDbh->prepare($update_valid_to_query) or die "Could not prepare query: $update_valid_to_query";

               foreach my $countryID (@countriesOfSource) {
                  my (@currInUse) = getInUseFromSourceAndCountry($waspDbh, $sourceID, $countryID);
                  my $amount_of_elements = scalar(@currInUse);
                  if ($amount_of_elements > 1) {
                     $inUseProblem = 1;
                  }
                  $thisCountryValidFromVersion =
                     getMostFrequentValidFromVersionOfSourceAndCountry($waspDbh, $sourceID, $countryID);
                  $nextCountryValidFromVersion =
                     getMostFrequentValidFromVersionOfSourceAndCountry($waspDbh, $nextSourceID, $countryID);

                  if (defined $thisCountryValidFromVersion and defined $nextCountryValidFromVersion) {

                     if ($thisCountryValidFromVersion != $nextCountryValidFromVersion) {

                        $newValidToVersion = $nextCountryValidFromVersion - 1;
                        dbgprint "validFromVersion of source $sourceName ($thisCountryValidFromVersion) " .
                           "and $nextSourceName ($nextCountryValidFromVersion) differ. " .
                           "Will set validToVersion of source $sourceID in country $countryID to ".
                           "$newValidToVersion.";
                        if ($currentInUse->{$countryID}->{'validToVersion'} eq $newValidToVersion) {
                           dbgprint "   Wanting to set same validToVersion as it is now. Won't change.";
                        } else {
                           # store new value
                           $update_validto_hash{$countryID}{'validToVersion'} = $newValidToVersion;
                           $something_to_change = 1;
                        }

                     } else {
                        dbgprint "validFromVersion of source $sourceName ($thisCountryValidFromVersion) " .
                           "and $nextSourceName ($nextCountryValidFromVersion) for country $countryID don't differ. ";
                        if ($inUseVal == $currentInUse->{$countryID}->{'inUse'}) {
                              dbgprint "   Wanting to set same inUse as it is now ($inUseVal). Won't change.";

                        } else {
                           # store new value
                           $update_inuse_hash{$countryID}{'inUse'} = $inUseStr;
                              dbgprint "   Will set inUse to $inUseStr.";
                           $something_to_change = 1;
                        }
                     }
                  } else {
                     dbgprint "One validFromVersion is undefined for country $countryID. Will set inUse to $inUseStr.";

                     if ($inUseVal == $currentInUse->{$countryID}->{'inUse'}) {
                        dbgprint "   Wanting to set same inUse as it is now ($inUseVal). Won't change.";
                     } else {
                        # the pois of this country can have in use set to false
                        # as one of the validFromVersions is undefined
                        # store new value
                        $update_inuse_hash{$countryID}{'inUse'} = $inUseStr;
                        $something_to_change = 1;
                     }
                  }
               }
               if ($inUseProblem) {
                  errprint "One or more countries have more than one inUse value. This is incorrect. Exiting.";
                  exit 1;
               }

               if (!$something_to_change) {
                  errprint "No changes to make. Exiting.";
                  exit 1;
               } else {
                  dbgprint "";
                  dbgprint "Will do updates. Press ctrl-c to skip.";
                  dbgprint "";
                  # Give some time for breaking the script.
                  for (my $i=10; $i > -1; $i = $i-1){
                     sleep(1);
                     print $i . " sec to continue. " . "\n\10\10\10\15";
                  }
                  print "\n";
                  timeprint "Continues";

                  foreach $countryID (keys %update_inuse_hash) {
                     dbgprint "here we would update inUse ($update_in_use_query) for country $countryID";
                     $update_in_use_sth->execute($countryID) or die "Could not execute query: $update_in_use_query";
                  }
                  foreach $countryID (keys %update_validto_hash) {
                     $newValidToVersion = $update_validto_hash{$countryID}{'validToVersion'};
                     dbgprint "here we would update validTo ($update_valid_to_query)";
                     dbgprint "validTo=$update_validto_hash{$countryID}{'validToVersion'} where country = $countryID";
                     $update_valid_to_sth->execute($newValidToVersion, $countryID) or die "Could not execute query: $update_valid_to_query";
                  }

                  $update_in_use_sth->finish();
                  $update_valid_to_sth->finish();
                  timeprint "Done!";
                  exit;
               }
            } else {
               errprint "Did not find nextSourceID for this source $sourceID. Exiting.";
               exit 1;
            }
         } else {
            errprint "Seems source has no POIs, as no countries were found. Exiting.";
            exit 1;
         }
      } else {
         if ($all_inuse_value == 0) {
            errprint "You want to set inUse to $inUseVal but it is already $inUseVal. Exiting.";
            exit 1;
         }
         # continues below
      }
   }

   timeprint "";
   timeprint "Setting in use to $inUseStr.";
   if ($update_valid_to) {
      timeprint "Setting $valid_to_statement";
   }
   timeprint "Start by counting POIs to update.";
   my $query =
       "SELECT count(*) FROM POIMain".
       " WHERE source = $sourceID;";
   dprint2 $query;
   my $sth = $waspDbh->prepare( $query );
   $sth->execute() or die "Failed: $query";
   (my $nbrPOIs) = $sth->fetchrow();
   timeprint "Will update inUse value of $nbrPOIs POIs.";

   $query =
       "UPDATE POIMain".
       " SET inUse = $inUseVal, $valid_to_statement lastModified = now()".
       " WHERE source = $sourceID;";
   dbgprint $query;

   # Give some time for breaking the script.
   for (my $i=10; $i > -1; $i = $i-1){
      sleep(1);
      print $i . " sec to continue. " . "\n\10\10\10\15";
   }
   print "\n";
   timeprint "Continues";

   timeprint "Updates value of in use flag of the POIs.";
   $sth = $waspDbh->prepare( $query );
   $sth->execute() or die "Failed: $query";
   timeprint "Done!";
}
#
#
#
#=============================================================================
elsif ( $opt_exportPOIsWithNoPos ){
   my $nbrToGeoc = 0;
   my $tmpGeocFile = $geocFile . ".1";
   timeprint "";
   timeprint "Will export POIs with no coordinates\n";
   # Check sanity
   if ( ! defined $sourceID ){
      errprint "No source, exits";
      exit 1;
   }
   if ( ! defined $countryID ) {
      errprint "No country, exits";
      exit 1;
   }
   if ($countryID == 0xffffffff) {
      errprint "Please take one country at a time, geocoding will be easier\n";
      exit 1;
   }

   my $query = "SELECT ID FROM POIMain WHERE source = $sourceID AND " .
               "country = $countryID AND (lat = '' or lat is NULL) ORDER BY ID";
   my $sth = $waspDbh->prepare($query) or die "Cannot prepare query \"$query\"\n";
   $sth->execute() or die "Cannot execute query \"$query\"\n";
   while ((my $poiid) = $sth->fetchrow()) {
      # Build a POI object
      my $poiObject = POIObject->newObject( );
      $poiObject->setDBH($waspDbh);

      $poiObject->{m_id} = $poiid;
      # read poi from WASP
      $poiObject->readFromWASP();

      my $prioStreetNumberCombination = 1;
      $poiObject->writeGeocodeFile( $geocFile, $prioStreetNumberCombination );
      $nbrToGeoc += 1;
   }

   if ($nbrToGeoc < 1) {
      dbgprint("No POIs without coordinates were found\n");
      dbgprint("Exiting\n");
      exit 1;
   }
   dbgprint "Wrote $nbrToGeoc pois to geocode file $geocFile";
   dbgprint "Now sorting on zip area...";
   `sort -t";" -k5 -o$tmpGeocFile $geocFile`;
   `mv $tmpGeocFile $geocFile`;
   dbgprint "Done!";
}
#
#
#
#=============================================================================
elsif ( $opt_importPosFromGeocodeResult ) {
   timeprint "";
   timeprint "Will import coordinates for POIs with no coordinates\n";
   my $nbrRows = 0;
   my $updatedCoords = 0;
   my $hasCoords = 0;
   my $alreadyHasCoords = 0;
   # Check sanity
   if ( ! defined $sourceID ){
      errprint "No source, exits";
      exit 1;
   }
   if ( ! defined $countryID ) {
      errprint "No country, exits";
      exit 1;
   }
   if ($countryID == 0xffffffff) {
      errprint "Please take one country at a time, geocoding will be easier\n";
      exit 1;
   }
   my $selectQuery = "SELECT ID, lat, lon FROM POIMain WHERE sourceReference = ? " .
               " AND source = $sourceID\n";
   my $updateQuery = "UPDATE POIMain set lastModified=now(), lat=?, lon=? where ID=?";
   my $sth = $waspDbh->prepare($selectQuery);
   my $sthUpdate = $waspDbh->prepare($updateQuery);
   # example geocoded row:
   # 10933297;united kingdom;Knutsford Road 73;WA4 1AB;Warrington;636817919;-30427866;
   open (COORDS, "< $geocFile")
          or die "Could not open file with coordinates";
   while (<COORDS>) {
      $nbrRows++;
      chomp;
      my $line = $_;
      my (@row) = split(/;/, $line);
      if ($row[1] eq 'united kingdom') {
         $row[1] = "england";
      }
      if (!defined getCountryIDFromName($waspDbh, $row[1])) {
         errprint "Check format of geocoded file. Country name not valid\n";
         exit 1;
      }
      if ( (!defined $row[0]) or ($row[0] eq '') ) {
         errprint "Line has no source reference. Exiting\n";
      }
      if (defined $row[5] and defined $row[6]) {
         if ( ($row[5] =~ m/^-?\d+$/) and ($row[6] =~ m/^-?\d+$/) ) {
            print "POI srcRef $row[0], in $row[1]\n";
            $hasCoords++;
            $sth->execute($row[0]);
            my ($poiID, $lat, $lon) = $sth->fetchrow();
            if (defined $poiID) {
               print "poi found in db with poiID $poiID\n";
               if (!defined $lat or $lat eq '') {
                  timeprint "Will update coord in WASP";
                  timeprint "$updateQuery, $row[5], $row[6], $poiID\n";
                  $sthUpdate->execute( $row[5], $row[6], $poiID);
                  $updatedCoords++;
               } else {
                  $alreadyHasCoords++;
               }
            }
         } else {
            print "Coordinates don't seem like correct mc2. Will not update.\n";
         }
      } else {
         print "Coordinates are not defined! Cannot update.\n";
      }
   }
   timeprint "Updated coordinates for $updatedCoords of $hasCoords POIs with coordinates in geocoded file.";
   timeprint "In WASP $alreadyHasCoords POIs already had coordinates.";
   timeprint "File had $nbrRows rows\n";
   timeprint "Done!";
}
#
#
#
#=============================================================================
else {
   print "\nNo command given, use -help to see your options.\n\n";
}

# Methods
##############################################################################

# This action deletes all POIs from a given source. Dangerous.
sub handleDeletePOIsFromSource {
   my $sourceID = $_[0];
   my $sourceName = $_[1];
   my $countryID = $_[2];
   my $deleteMode = $_[3];
   my $poiIdMin = $_[4];
   my $poiIdMax = $_[5];

   if ( !defined($sourceID) ) {
      die "handleDeletePOIsFromSource: No source given\n";
   }
   if ( !defined($countryID) ) {
      die "handleDeletePOIsFromSource: No country given\n";
   }
   if (!defined($sourceName)) {
      die "handleDeletePOIsFromSource: No valid source defined\n";
   }
   if ( !defined($deleteMode) ) {
      die "handleDeletePOIsFromSource: No delete mode given";
   }
   if ( defined($poiIdMin) ){
      dprint1 "Using min PIO ID: $poiIdMin";
   }
   if ( defined($poiIdMax) ){
      dprint1 "Using max PIO ID: $poiIdMax";
   }
   my $deleteEP = 0;
   my $deleteInfo = 0;
   my $deleteTypes = 0;
   my $deleteNames = 0;
   my $deleteStatic = 0;
   my $deleteCategories = 0;
   my $deleteMain = 0;
   if  ($deleteMode eq "onlyInfo") {
      $deleteInfo = 1;
   } elsif ($deleteMode eq "allTables") {
      $deleteEP = 1;
      $deleteInfo = 1;
      $deleteTypes = 1;
      $deleteNames = 1;
      $deleteStatic = 1;
      $deleteCategories = 1;
      $deleteMain = 1;
   } elsif ($deleteMode eq "onlyStatic") {
      $deleteStatic = 1;
   } elsif ($deleteMode eq "onlyCategories") {
      $deleteCategories = 1;
   } elsif ($deleteMode eq "onlyEntryPts") {
      $deleteEP = 1;
   } else {
      die "handleDeletePOIsFromSource: unknown deleteMode $deleteMode";
   }

   my $allCountries;
   if ($countryID == 0xffffffff) {
      $allCountries = 1;
   }

   dprint1 "Delete from POIs with source $sourceName ($sourceID) in country ".
       "$countryName ($countryID)";
   dprint1 "Delete from tables: ";
   if ($deleteEP) {     dprint1 "  POIEntryPoints";}
   if ($deleteInfo) {   dprint1 "  POIInfo";}
   if ($deleteTypes) {  dprint1 "  POITypes";}
   if ($deleteNames) {  dprint1 "  POINames";}
   if ($deleteStatic) { dprint1 "  POIStatic";}
   if ($deleteCategories) { dprint1 "  POICategories";}
   if ($deleteMain) {   dprint1 "  POIMain";}
   dprint1 "";
   dprint1 "Counting number pois - Press ctrl-c to interrupt";

   # Handle special options.
   my $countryQueryEnd;
   if (!$allCountries) {
      $countryQueryEnd = " AND country=$countryID";
   } else {
      $countryQueryEnd = "";
   }
   my $poiIdMinQuery = "";
   if ( defined($poiIdMin) ){
      $poiIdMinQuery = " AND POIMain.ID >= $poiIdMin ";
   }
   my $poiIdMaxQuery = "";
   if ( defined($poiIdMax) ){
      $poiIdMaxQuery = " AND POIMain.ID <= $poiIdMax ";
   }

   #Get number of POIs to be deleted
   my $countQuery = "select count(ID) from POIMain " .
                    "where source=$sourceID" . $poiIdMinQuery. $poiIdMaxQuery. $countryQueryEnd;
   dprint1 "$countQuery";
   my $sth2 = $waspDbh->prepare($countQuery);
   $sth2->execute;
   my $count = $sth2->fetchrow();
   if ( $count == 0 ) {
      dprint1 "Found $count POIs to delete";
      die "No pois to delete - exit\n";
   }
   dprint1 "Found $count POIs of which data will be deleted,".
       " press ctrl-c NOW to interrupt.";
   for (my $i=10; $i > -1; $i = $i-1){
      sleep(1);
      print $i . " sec to continue. " . "\n\10\10\10\15";
   }
   print "\n";
   dprint1 "Continues";

   #Delete POIs
   dprint1 "Starts deleting data of POIs, too late to interrupt";
   if ( $deleteEP ) {
      dprint1 "Starts deleting with poi entry points";
      my $deleteEntryQuery = "DELETE POIEntryPoints FROM POIEntryPoints, " .
                             "POIMain WHERE POIMain.ID=POIEntryPoints.poiID " .
                             "AND source=$sourceID" .
                             $poiIdMinQuery .
                             $poiIdMaxQuery .
                             $countryQueryEnd;
      dprint1 $deleteEntryQuery;
      my $sth3 = $waspDbh->prepare($deleteEntryQuery);
      $sth3->execute or die "Failed DELETE POIEntryPoints";
      dprint1 "Poi entry points deleted";
   }
   if ( $deleteInfo ) {
      dprint1 "Starts deleting poi info";
      my $deleteInfoQuery = "DELETE POIInfo FROM POIInfo, " .
                            "POIMain WHERE POIMain.ID=POIInfo.poiID " .
                            "AND source=$sourceID" .
                            $poiIdMinQuery .
                            $poiIdMaxQuery .
                            $countryQueryEnd;
      dprint1 $deleteInfoQuery;
      my $sth4 = $waspDbh->prepare($deleteInfoQuery);
      $sth4->execute or die "Failed DELETE POIInfo";
      dprint1 "Poi info deleted";
   }
   if ( $deleteTypes ) {
      dprint1 "Starts deleting poi types";
      my $deleteTypesQuery = "DELETE POITypes FROM POITypes, " .
                             "POIMain WHERE POIMain.ID=POITypes.poiID " .
                             "AND source=$sourceID" .
                             $poiIdMinQuery .
                             $poiIdMaxQuery .
                             $countryQueryEnd;
      dprint1 $deleteTypesQuery;
      my $sth5 = $waspDbh->prepare($deleteTypesQuery);
      $sth5->execute or die "Failed DELETE POITypes";
      dprint1 "Poi types deleted";
   }
   if ( $deleteNames ) {
      dprint1 "Starts deleting poi names";
      my $deleteNamesQuery = "DELETE POINames FROM POINames, " .
                             "POIMain WHERE POIMain.ID=POINames.poiID " .
                             "AND source=$sourceID" .
                             $poiIdMinQuery .
                             $poiIdMaxQuery .
                             $countryQueryEnd;
      dprint1 $deleteNamesQuery;
      my $sth6 = $waspDbh->prepare($deleteNamesQuery);
      $sth6->execute or die "Failed DELETE POINames";
      dprint1 "Poi names deleted";
   }
   if ( $deleteStatic ) {
      dprint1 "Starts deleting poi static";
      my $deleteStaticQuery = "DELETE POIStatic".
          " FROM POIStatic, POIMain".
          " WHERE".
          " POIMain.ID=POIStatic.poiID AND".
          " source=$sourceID" .
          $poiIdMinQuery .
          $poiIdMaxQuery .
          $countryQueryEnd;
      dprint1 $deleteStaticQuery;
      my $sth7 = $waspDbh->prepare($deleteStaticQuery);
      $sth7->execute or die "Failed DELETE POIStatic";
      dprint1 "Poi static deleted";
   }
   if ( $deleteCategories ) {
      dprint1 "Starts deleting poi categories";
      my $deleteCategoriesQuery = "DELETE POICategories".
          " FROM POICategories, POIMain".
          " WHERE".
          " POIMain.ID=POICategories.poiID AND".
          " source=$sourceID" .
          $poiIdMinQuery .
          $poiIdMaxQuery .
          $countryQueryEnd;
      dprint1 $deleteCategoriesQuery;
      my $sth8 = $waspDbh->prepare($deleteCategoriesQuery);
      $sth8->execute or die "Failed DELETE POICategories";
      dprint1 "Poi categories deleted";
   }
   if ( $deleteMain ) {
      dprint1 "Starts deleting poi main";
      my $deleteMainQuery = "DELETE FROM POIMain " .
                            "WHERE source=$sourceID" .
                             $poiIdMinQuery .
                             $poiIdMaxQuery .
                             $countryQueryEnd;
      dprint1 $deleteMainQuery;
      my $sth10 = $waspDbh->prepare($deleteMainQuery);
      $sth10->execute or die "Failed DELETE POIMain";
      dprint1 "Poi main deleted";
   }
   dprint1 "Data of all " . $count .
       " POIs deleted from source=$sourceName countryID=$countryID";
} #handleDeletePOIsFromSource

redpajama_set_name: RedPajamaGithub


text:
from .gosubl import gs
from . import gstest
import sublime
import sublime_plugin
import webbrowser

DOMAIN = 'GsEV'

class EV(sublime_plugin.EventListener):
	def on_pre_save(self, view):
		view.run_command('gs_fmt')
		sublime.set_timeout(lambda: do_set_gohtml_syntax(view), 0)

	def on_post_save(self, view):
		sublime.set_timeout(lambda: do_post_save(view), 0)

	def on_activated(self, view):
		win = view.window()
		if win is not None:
			active_view = win.active_view()
			if active_view is not None:
				sublime.set_timeout(lambda: do_sync_active_view(active_view), 0)

		sublime.set_timeout(lambda: do_set_gohtml_syntax(view), 0)

	def on_load(self, view):
		sublime.set_timeout(lambda: do_set_gohtml_syntax(view), 0)

class GsOnLeftClick(sublime_plugin.TextCommand):
	def run(self, edit):
		view = self.view
		if gs.is_go_source_view(view):
			view.run_command('gs9o_open', {
				"run": [".actuate", "-button=left"],
				"focus_view": False,
				"show_view": False,
			})
		elif view.score_selector(gs.sel(view).begin(), "text.9o") > 0:
			view.window().run_command("gs9o_open_selection")

class GsOnRightClick(sublime_plugin.TextCommand):
	def run(self, edit):
		view = self.view
		if gs.is_go_source_view(view):
			view.run_command('gs9o_open', {
				"run": [".actuate", "-button=right"],
				"focus_view": False,
				"show_view": False,
			})

def do_post_save(view):
	if not gs.is_pkg_view(view):
		return

	for c in gs.setting('on_save', []):
		cmd = c.get('cmd', '')
		args = c.get('args', {})
		msg = 'running on_save command %s' % cmd
		tid = gs.begin(DOMAIN, msg, set_status=False)
		try:
			view.run_command(cmd, args)
		except Exception as ex:
			gs.notice(DOMAIN, 'Error %s' % ex)
		finally:
			gs.end(tid)

def do_sync_active_view(view):
	fn = view.file_name() or ''
	gs.set_attr('active_fn', fn)

	if fn:
		gs.set_attr('last_active_fn', fn)
		if fn.lower().endswith('.go'):
			gs.set_attr('last_active_go_fn', fn)

	win = view.window()
	if win is not None and view in win.views():
		m = {}
		psettings = view.settings().get('GoSublime')
		if psettings and gs.is_a(psettings, {}):
			m = gs.mirror_settings(psettings)
		gs.set_attr('last_active_project_settings', gs.dval(m, {}))

		gs.sync_settings()

def do_set_gohtml_syntax(view):
	fn = view.file_name()
	xl = gs.setting('gohtml_extensions', [])
	if xl and fn and fn.lower().endswith(tuple(xl)):
		view.set_syntax_file(gs.tm_path('gohtml'))


text:
require 'custom_errors'

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :store_location,
                :assign_footer_page_links

  include CustomErrors

  # To prevent infinite redirect loops, only requests from white listed
  # controllers are available in the "after sign-in redirect" feature
  def white_listed
    %w(
        application
        contributors
        organisations
        pages
    )
  end
  # Devise wiki suggests we need to make this return nil for the after_inactive_signup_path_for to be called in registrationscontroller
  # https://github.com/plataformatec/devise/wiki/How-To%3a-Change-the-redirect-path-after-destroying-a-session-i.e.-signing-out
  #Also documented on last stackoverflow answer here:
  #http://stackoverflow.com/questions/21571569/devise-after-sign-up-path-for-not-being-called
  def stored_location

  end
  def request_controller_is(white_listed)
    white_listed.include? request.params['controller']
  end

  def request_verb_is_get?
    request.env['REQUEST_METHOD'] == 'GET'
  end

  # Stores the URL if permitted
  def store_location
    if request_controller_is(white_listed) && request_verb_is_get?
      session[:previous_url] = request.path
    end
  end

  # Devise hook
  # Returns the users to the page they were viewing before signing in
  def after_sign_in_path_for(resource)
    set_flash_warning_reminder_to_update_details resource
    return edit_user_path id: current_user.id if session[:pending_organisation_id]
    return organisation_path(current_user.organisation) if current_user.organisation
    return session[:previous_url] if session[:previous_url]
    return organisation_path(Organisation.find(current_user.pending_organisation_id)) if current_user.pending_organisation_id
    root_path
  end

  # Devise Invitable hook
  # Since users are invited to be org admins, we're delivering them to their page
  def after_accept_path_for(resource)
    return organisation_path(current_user.organisation) if current_user.organisation
    root_path
  end

  def allow_cookie_policy
    response.set_cookie 'cookie_policy_accepted', {
        value: 'true',
        path: '/',
        expires: 1.year.from_now.utc
    }
    #respond_to do |format|
    #  format.html redirect_to root_path
    #  format.json { render :nothing => true, :status => 200 }
    #end

    redirect_to request.referer || '/'
  end

  private

  # Enforces superadmin-only limits
  # http://railscasts.com/episodes/20-restricting-access
  def authorize
    unless superadmin?
      flash[:error] = t('authorize.superadmin')
      redirect_to root_path
      false
    end
  end

  def superadmin?
    current_user.try :superadmin?
  end

  def assign_footer_page_links
    @footer_page_links = Page.visible_links
  end

  def set_flash_warning_reminder_to_update_details usr
    if usr.organisation and not usr.organisation.has_been_updated_recently?
      msg = render_to_string(partial: "shared/call_to_action", locals: {org: usr.organisation}).html_safe
      if flash[:warning]
        flash[:warning] << msg
      else
        flash[:warning] = msg
      end
    end
  end
end


text:
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any styles
 * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
 * file per style scope.
 *
 *= require_tree .
 *= require refinery/formatting
 *= require refinery/theme
 *= require jquery-ui
 *= require foundation-icon-fonts/foundation-icons
 *= require owl-carousel/owl-carousel/owl.carousel
 *= require owl-carousel/owl-carousel/owl.theme
 *= require library/foundation.min
 *= require c3/c3.min
 *= require_self
 */


text:
using System.Collections.Generic;

namespace SolrNet.Utils {
    /// <summary>
    /// Helper KeyValuePair constructor
    /// </summary>
    public static class KV {
        /// <summary>
        /// Helper KeyValuePair constructor
        /// </summary>
        /// <typeparam name="K"></typeparam>
        /// <typeparam name="V"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static KeyValuePair<K, V> Create<K, V>(K key, V value) {
            return new KeyValuePair<K, V>(key, value);
        }
    }
}


text:
package sqlline;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * List of all database connections in the current sqlline session.
 */
class DatabaseConnections implements Iterable<DatabaseConnection> {
  private final List<DatabaseConnection> connections = new ArrayList<>();
  private int index = -1;

  public DatabaseConnection current() {
    if (index != -1) {
      return connections.get(index);
    }

    return null;
  }

  public int size() {
    return connections.size();
  }

  public Iterator<DatabaseConnection> iterator() {
    return connections.iterator();
  }

  public void remove() {
    if (index != -1) {
      connections.remove(index);
    }

    while (index >= connections.size()) {
      index--;
    }
  }

  public void removeConnection(DatabaseConnection connection) {
    if (connections.indexOf(connection) != -1) {
      connections.remove(connection);
      index--;
    }
  }

  public void setConnection(DatabaseConnection connection) {
    if (connections.indexOf(connection) == -1) {
      connections.add(connection);
    }

    index = connections.indexOf(connection);
  }

  public int getIndex() {
    return index;
  }

  public boolean setIndex(int index) {
    if (index < 0 || index >= connections.size()) {
      return false;
    }

    this.index = index;
    return true;
  }
}

// End DatabaseConnections.java


text:
#pragma once

#include <memory>
#include <set>
#include <string>
#include <vector>

#include "abstract_rule.hpp"
#include "operators/operator_scan_predicate.hpp"
#include "statistics/table_statistics.hpp"
#include "types.hpp"

namespace hyrise {

class AbstractLQPNode;
class ChunkStatistics;
class AbstractExpression;
class StoredTableNode;
class PredicateNode;
class Table;

/**
 * For a given LQP, this rule determines the set of chunks that can be pruned from a table.
 * To calculate the sets of pruned chunks, it analyzes the predicates of PredicateNodes in a given LQP.
 * The resulting pruning information is stored inside the StoredTableNode objects.
 */
class ChunkPruningRule : public AbstractRule {
 public:
  std::string name() const override;

 protected:
  void _apply_to_plan_without_subqueries(const std::shared_ptr<AbstractLQPNode>& lqp_root) const override;

  using PredicatePruningChain = std::vector<std::shared_ptr<PredicateNode>>;

  static std::vector<PredicatePruningChain> _find_predicate_pruning_chains_by_stored_table_node(
      const std::shared_ptr<StoredTableNode>& stored_table_node);

  std::set<ChunkID> _compute_exclude_list(const PredicatePruningChain& predicate_pruning_chain,
                                          const std::shared_ptr<StoredTableNode>& stored_table_node) const;

  // Check whether any of the statistics objects available for this Segment identify the predicate as prunable
  static bool _can_prune(const BaseAttributeStatistics& base_segment_statistics,
                         const PredicateCondition predicate_condition, const AllTypeVariant& variant_value,
                         const std::optional<AllTypeVariant>& variant_value2);

  static std::shared_ptr<TableStatistics> _prune_table_statistics(const TableStatistics& old_statistics,
                                                                  OperatorScanPredicate predicate,
                                                                  size_t num_rows_pruned);

  static std::set<ChunkID> _intersect_chunk_ids(const std::vector<std::set<ChunkID>>& chunk_id_sets);

 private:
  /**
   * Caches intermediate results.
   * Mutable because it needs to be called from the _apply_to_plan_without_subqueries function, which is const.
   */
  using StoredTableNodePredicateNodePair = std::pair<std::shared_ptr<StoredTableNode>, std::shared_ptr<PredicateNode>>;
  mutable std::unordered_map<StoredTableNodePredicateNodePair, std::set<ChunkID>,
                             boost::hash<StoredTableNodePredicateNodePair>>
      _excluded_chunk_ids_by_predicate_node_cache;
};

}  // namespace hyrise


text:
#ifndef SCENE_H
#define SCENE_H

#include "../../3dogs.h"
#include "static.h"

/**
  *  @class    Scene
  *  @brief    Daten und Methoden der OpenGL Szene
  */
class Scene {

public:

    /**
      *   @fn       Scene(aStatic)
      *   @brief    Konstruktur mit Uebergabe einer Instanz
      *             der statischen Daten
      *   @param    aStatic Instanz mit den statischen Daten der OpenGL Szene
      */
    Scene(Static &aStatic);

    /**
      *   @fn       ~Scene
      *   @brief    Dekonstruktur
      */
    ~Scene(void);

    /**
      *   @fn       calcAngles(Static &aStatic)
      *   @brief    Winkel fuer naechsten Schritt berechnen
      *             Modifiziert die statischen Variablen aAngle1, aAngle2 !
      *             Suche nach numerischen IDs
      *   @param    aStatic
      */
    static void calcAngles(Static &aStatic);

    /**
      *   @fn       calcAnglesByNames(Static &aStatic)
      *   @brief    Winkel fuer naechsten Schritt berechnen
      *             Modifiziert die statischen Variablen aAngle1, aAngle2 !
      *             Suche nach alphanumerischen Namen ( ineffizient,
      *             aber fuer Benutzerinteraktion u.U. nuetzlich )
      *   @param    aStatic
      */
    static void calcAnglesByNames(Static &aStatic);

    /**
      *   @fn       calc(Static &aStatic)
      *   @brief    Berechnungen durchfuehren
      *             Wird nicht mehr aufgerufen
      *             Wird nicht mehr benoetigt !
      *   @param    aStatic
      */
    static void calc(Static &aStatic);

protected:

    /**
      *   @fn       init(Static &aStatic)
      *   @brief    Aktuelle Szene
      *             Daten anlegen, Initialisierung
      *   @param    aStatic
      */
    void init(Static &aStatic);

    /**
      *   @fn       init2(Static &aStatic)
      *   @brief    Nicht-aktuelle Szene
      *             Daten anlegen, Initialisierung
      *   @param    aStatic
      */
    void init2(Static &aStatic);

    /**
      *   @fn       chessboard(ZQueue *aQueue, int aSize)
      *   @brief    Schachbrett anlegen
      *             Darstellungsreihenfolge in der DisplayListe festlegen
      *   @param    aQueue Feld in die die OpenGL-Objekte des Schachbretts kopiert werden
      *   @param    aSize Groesse des Schachbretts
      */
    void chessboard(ZQueue *aQueue, int aSize);

    //void chessboard( Vektor< VektorElement<ZCmd *>, ZCmd *>
    //                 *aQueue, int aSize);
};
#endif // SCENE_H


text:
import {CompileShallowModuleMetadata, identifierName} from '../compile_metadata';
import {InjectableCompiler} from '../injectable_compiler';
import {mapLiteral} from '../output/map_util';
import * as o from '../output/output_ast';
import {OutputContext} from '../util';

import {R3DependencyMetadata, R3FactoryTarget, compileFactoryFunction} from './r3_factory';
import {Identifiers as R3} from './r3_identifiers';
import {R3Reference, convertMetaToOutput, jitOnlyGuardedExpression, mapToMapExpression} from './util';

export interface R3NgModuleDef {
  expression: o.Expression;
  type: o.Type;
  additionalStatements: o.Statement[];
}

/**
 * Metadata required by the module compiler to generate a module def (`ɵmod`) for a type.
 */
export interface R3NgModuleMetadata {
  /**
   * An expression representing the module type being compiled.
   */
  type: R3Reference;

  /**
   * An expression representing the module type being compiled, intended for use within a class
   * definition itself.
   *
   * This can differ from the outer `type` if the class is being compiled by ngcc and is inside
   * an IIFE structure that uses a different name internally.
   */
  internalType: o.Expression;

  /**
   * An expression intended for use by statements that are adjacent (i.e. tightly coupled) to but
   * not internal to a class definition.
   *
   * This can differ from the outer `type` if the class is being compiled by ngcc and is inside
   * an IIFE structure that uses a different name internally.
   */
  adjacentType: o.Expression;

  /**
   * An array of expressions representing the bootstrap components specified by the module.
   */
  bootstrap: R3Reference[];

  /**
   * An array of expressions representing the directives and pipes declared by the module.
   */
  declarations: R3Reference[];

  /**
   * An array of expressions representing the imports of the module.
   */
  imports: R3Reference[];

  /**
   * An array of expressions representing the exports of the module.
   */
  exports: R3Reference[];

  /**
   * Whether to emit the selector scope values (declarations, imports, exports) inline into the
   * module definition, or to generate additional statements which patch them on. Inline emission
   * does not allow components to be tree-shaken, but is useful for JIT mode.
   */
  emitInline: boolean;

  /**
   * Whether to generate closure wrappers for bootstrap, declarations, imports, and exports.
   */
  containsForwardDecls: boolean;

  /**
   * The set of schemas that declare elements to be allowed in the NgModule.
   */
  schemas: R3Reference[]|null;

  /** Unique ID or expression representing the unique ID of an NgModule. */
  id: o.Expression|null;
}

/**
 * Construct an `R3NgModuleDef` for the given `R3NgModuleMetadata`.
 */
export function compileNgModule(meta: R3NgModuleMetadata): R3NgModuleDef {
  const {
    internalType,
    type: moduleType,
    bootstrap,
    declarations,
    imports,
    exports,
    schemas,
    containsForwardDecls,
    emitInline,
    id
  } = meta;

  const additionalStatements: o.Statement[] = [];
  const definitionMap = {
    type: internalType
  } as{
    type: o.Expression,
    bootstrap: o.Expression,
    declarations: o.Expression,
    imports: o.Expression,
    exports: o.Expression,
    schemas: o.LiteralArrayExpr,
    id: o.Expression
  };

  // Only generate the keys in the metadata if the arrays have values.
  if (bootstrap.length) {
    definitionMap.bootstrap = refsToArray(bootstrap, containsForwardDecls);
  }

  // If requested to emit scope information inline, pass the declarations, imports and exports to
  // the `ɵɵdefineNgModule` call. The JIT compilation uses this.
  if (emitInline) {
    if (declarations.length) {
      definitionMap.declarations = refsToArray(declarations, containsForwardDecls);
    }

    if (imports.length) {
      definitionMap.imports = refsToArray(imports, containsForwardDecls);
    }

    if (exports.length) {
      definitionMap.exports = refsToArray(exports, containsForwardDecls);
    }
  }

  // If not emitting inline, the scope information is not passed into `ɵɵdefineNgModule` as it would
  // prevent tree-shaking of the declarations, imports and exports references.
  else {
    const setNgModuleScopeCall = generateSetNgModuleScopeCall(meta);
    if (setNgModuleScopeCall !== null) {
      additionalStatements.push(setNgModuleScopeCall);
    }
  }

  if (schemas && schemas.length) {
    definitionMap.schemas = o.literalArr(schemas.map(ref => ref.value));
  }

  if (id) {
    definitionMap.id = id;
  }

  const expression = o.importExpr(R3.defineNgModule).callFn([mapToMapExpression(definitionMap)]);
  const type = new o.ExpressionType(o.importExpr(R3.NgModuleDefWithMeta, [
    new o.ExpressionType(moduleType.type), tupleTypeOf(declarations), tupleTypeOf(imports),
    tupleTypeOf(exports)
  ]));

  return {expression, type, additionalStatements};
}

/**
 * Generates a function call to `ɵɵsetNgModuleScope` with all necessary information so that the
 * transitive module scope can be computed during runtime in JIT mode. This call is marked pure
 * such that the references to declarations, imports and exports may be elided causing these
 * symbols to become tree-shakeable.
 */
function generateSetNgModuleScopeCall(meta: R3NgModuleMetadata): o.Statement|null {
  const {adjacentType: moduleType, declarations, imports, exports, containsForwardDecls} = meta;

  const scopeMap = {} as{
    declarations: o.Expression,
    imports: o.Expression,
    exports: o.Expression,
  };

  if (declarations.length) {
    scopeMap.declarations = refsToArray(declarations, containsForwardDecls);
  }

  if (imports.length) {
    scopeMap.imports = refsToArray(imports, containsForwardDecls);
  }

  if (exports.length) {
    scopeMap.exports = refsToArray(exports, containsForwardDecls);
  }

  if (Object.keys(scopeMap).length === 0) {
    return null;
  }

  // setNgModuleScope(...)
  const fnCall = new o.InvokeFunctionExpr(
      /* fn */ o.importExpr(R3.setNgModuleScope),
      /* args */[moduleType, mapToMapExpression(scopeMap)]);

  // (ngJitMode guard) && setNgModuleScope(...)
  const guardedCall = jitOnlyGuardedExpression(fnCall);

  // function() { (ngJitMode guard) && setNgModuleScope(...); }
  const iife = new o.FunctionExpr(
      /* params */[],
      /* statements */[guardedCall.toStmt()]);

  // (function() { (ngJitMode guard) && setNgModuleScope(...); })()
  const iifeCall = new o.InvokeFunctionExpr(
      /* fn */ iife,
      /* args */[]);

  return iifeCall.toStmt();
}

export interface R3InjectorDef {
  expression: o.Expression;
  type: o.Type;
  statements: o.Statement[];
}

export interface R3InjectorMetadata {
  name: string;
  type: R3Reference;
  internalType: o.Expression;
  deps: R3DependencyMetadata[]|null;
  providers: o.Expression|null;
  imports: o.Expression[];
}

export function compileInjector(meta: R3InjectorMetadata): R3InjectorDef {
  const result = compileFactoryFunction({
    name: meta.name,
    type: meta.type,
    internalType: meta.internalType,
    typeArgumentCount: 0,
    deps: meta.deps,
    injectFn: R3.inject,
    target: R3FactoryTarget.NgModule,
  });
  const definitionMap = {
    factory: result.factory,
  } as{factory: o.Expression, providers: o.Expression, imports: o.Expression};

  if (meta.providers !== null) {
    definitionMap.providers = meta.providers;
  }

  if (meta.imports.length > 0) {
    definitionMap.imports = o.literalArr(meta.imports);
  }

  const expression = o.importExpr(R3.defineInjector).callFn([mapToMapExpression(definitionMap)]);
  const type =
      new o.ExpressionType(o.importExpr(R3.InjectorDef, [new o.ExpressionType(meta.type.type)]));
  return {expression, type, statements: result.statements};
}

// TODO(alxhub): integrate this with `compileNgModule`. Currently the two are separate operations.
export function compileNgModuleFromRender2(
    ctx: OutputContext, ngModule: CompileShallowModuleMetadata,
    injectableCompiler: InjectableCompiler): void {
  const className = identifierName(ngModule.type) !;

  const rawImports = ngModule.rawImports ? [ngModule.rawImports] : [];
  const rawExports = ngModule.rawExports ? [ngModule.rawExports] : [];

  const injectorDefArg = mapLiteral({
    'factory':
        injectableCompiler.factoryFor({type: ngModule.type, symbol: ngModule.type.reference}, ctx),
    'providers': convertMetaToOutput(ngModule.rawProviders, ctx),
    'imports': convertMetaToOutput([...rawImports, ...rawExports], ctx),
  });

  const injectorDef = o.importExpr(R3.defineInjector).callFn([injectorDefArg]);

  ctx.statements.push(new o.ClassStmt(
      /* name */ className,
      /* parent */ null,
      /* fields */[new o.ClassField(
          /* name */ 'ɵinj',
          /* type */ o.INFERRED_TYPE,
          /* modifiers */[o.StmtModifier.Static],
          /* initializer */ injectorDef, )],
      /* getters */[],
      /* constructorMethod */ new o.ClassMethod(null, [], []),
      /* methods */[]));
}

function accessExportScope(module: o.Expression): o.Expression {
  const selectorScope = new o.ReadPropExpr(module, 'ɵmod');
  return new o.ReadPropExpr(selectorScope, 'exported');
}

function tupleTypeOf(exp: R3Reference[]): o.Type {
  const types = exp.map(ref => o.typeofExpr(ref.type));
  return exp.length > 0 ? o.expressionType(o.literalArr(types)) : o.NONE_TYPE;
}

function refsToArray(refs: R3Reference[], shouldForwardDeclare: boolean): o.Expression {
  const values = o.literalArr(refs.map(ref => ref.value));
  return shouldForwardDeclare ? o.fn([], [new o.ReturnStatement(values)]) : values;
}


text:
GkGameAnimation::GkGameAnimation(GkAnimatedTexture *animatedTexture, int x, int y, bool active, bool loop, bool visible, bool flipX, bool flipY, float framesPerSecond, int width, int height)
{
	this->SetAnimatedTexture(animatedTexture, framesPerSecond);
	this->x = x;
	this->y = y;
	this->width = width;
	this->height = height;
	this->framesPerSecond = framesPerSecond != 0.0f ? framesPerSecond : animatedTexture != 0 ? animatedTexture->framesPerSecond : 0.0f;
	this->active = active && (animatedTexture != NULL);
	this->loop = loop && (animatedTexture != NULL);
	this->visible = visible && (animatedTexture != NULL);
	this->flipX = flipX;
	this->flipY = flipY;
}

GkGameAnimation::~GkGameAnimation(void)
{
}

void GkGameAnimation::SetAnimatedTexture(GkAnimatedTexture *animatedTexture, float framesPerSecond)
{
	this->animatedTexture = animatedTexture;
	this->framesPerSecond = framesPerSecond != 0.0f ? framesPerSecond : animatedTexture != 0 ? animatedTexture->framesPerSecond : 0.0f;
	this->ResetAnimation(this->active);
}

void GkGameAnimation::Process(GkGame *game)
{
	if (!(this->active && this->visible))
		return;

	if (this->flipX)
		this->flipX = true;

	this->currentFrame += this->framesPerSecond * game->timer->tickTime;

	if (this->currentFrame > this->animatedTexture->numFrames)
	{
		if (this->loop)
		{
			int intFrame = (int)this->currentFrame;
			float fracFrame = this->currentFrame - intFrame;
			this->currentFrame = intFrame % this->animatedTexture->numFrames + fracFrame;
		}
		else
		{
			this->EndAnimation();
		}
	}

	if (this->currentFrame < 0)
	{
		if (this->loop)
		{
			int intFrame = (int)this->currentFrame;
			float fracFrame = this->currentFrame - intFrame;
			this->currentFrame = (this->animatedTexture->numFrames - 1 - intFrame) % this->animatedTexture->numFrames + fracFrame;
		}
		else
		{
			this->EndAnimation();
		}
	}
}

void GkGameAnimation::Draw(GkGame *game)
{
	if (!this->visible)
		return;

	GkTexture *frame = this->animatedTexture->frames[(int)this->currentFrame];
	int width = this->width != 0 ? this->width : frame->width;
	int height = this->height != 0 ? this->height : frame->height;
	if (this->flipX)
		if (this->flipY)
			game->graphicsDevice->Draw(this->x + width, this->y + height, -width, -height, 0, 0, frame->width,frame->height, frame);
		else
			game->graphicsDevice->Draw(this->x + width, this->y, -width, height, 0, 0, frame->width, frame->height, frame);
	else
		if (this->flipY)
			game->graphicsDevice->Draw(this->x, this->y + height, width, -height, 0, 0, frame->width, frame->height, frame);
		else
			game->graphicsDevice->Draw(this->x, this->y, width, height, 0, 0, frame->width, frame->height, frame);
}

bool GkGameAnimation::GetBoundaries(int *x1, int *y1, int *x2, int*y2)
{
	*x1 = this->x;
	*y1 = this->y;
	*x2 = this->x + this->animatedTexture->frames[0]->width;
	*y2 = this->y + this->animatedTexture->frames[0]->height;

	return true;
}

void GkGameAnimation::ResetAnimation(bool start)
{
	this->currentFrame = this->framesPerSecond < 0 ? this->animatedTexture != 0 ? (float)(this->animatedTexture->numFrames - 1) : 0.0f : 0.0f;
	this->active = start;
}

void GkGameAnimation::EndAnimation()
{
	this->currentFrame = this->framesPerSecond < 0 ? 0.0f : this->animatedTexture != 0 ? (float)(this->animatedTexture->numFrames - 1) : 0.0f;
	this->active = false;
}


text:
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/bootmem.h>
#include <linux/spinlock.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <asm/cacheflush.h>
#include <asm/io.h>
#include <asm/bfin-global.h>

static spinlock_t dma_page_lock;
static unsigned int *dma_page;
static unsigned int dma_pages;
static unsigned long dma_base;
static unsigned long dma_size;
static unsigned int dma_initialized;

void dma_alloc_init(unsigned long start, unsigned long end)
{
	spin_lock_init(&dma_page_lock);
	dma_initialized = 0;

	dma_page = (unsigned int *)__get_free_page(GFP_KERNEL);
	memset(dma_page, 0, PAGE_SIZE);
	dma_base = PAGE_ALIGN(start);
	dma_size = PAGE_ALIGN(end) - PAGE_ALIGN(start);
	dma_pages = dma_size >> PAGE_SHIFT;
	memset((void *)dma_base, 0, DMA_UNCACHED_REGION);
	dma_initialized = 1;

	printk(KERN_INFO "%s: dma_page @ 0x%p - %d pages at 0x%08lx\n", __FUNCTION__,
	       dma_page, dma_pages, dma_base);
}

static inline unsigned int get_pages(size_t size)
{
	return ((size - 1) >> PAGE_SHIFT) + 1;
}

static unsigned long __alloc_dma_pages(unsigned int pages)
{
	unsigned long ret = 0, flags;
	int i, count = 0;

	if (dma_initialized == 0)
		dma_alloc_init(_ramend - DMA_UNCACHED_REGION, _ramend);

	spin_lock_irqsave(&dma_page_lock, flags);

	for (i = 0; i < dma_pages;) {
		if (dma_page[i++] == 0) {
			if (++count == pages) {
				while (count--)
					dma_page[--i] = 1;
				ret = dma_base + (i << PAGE_SHIFT);
				break;
			}
		} else
			count = 0;
	}
	spin_unlock_irqrestore(&dma_page_lock, flags);
	return ret;
}

static void __free_dma_pages(unsigned long addr, unsigned int pages)
{
	unsigned long page = (addr - dma_base) >> PAGE_SHIFT;
	unsigned long flags;
	int i;

	if ((page + pages) > dma_pages) {
		printk(KERN_ERR "%s: freeing outside range.\n", __FUNCTION__);
		BUG();
	}

	spin_lock_irqsave(&dma_page_lock, flags);
	for (i = page; i < page + pages; i++) {
		dma_page[i] = 0;
	}
	spin_unlock_irqrestore(&dma_page_lock, flags);
}

void *dma_alloc_coherent(struct device *dev, size_t size,
			 dma_addr_t * dma_handle, gfp_t gfp)
{
	void *ret;

	ret = (void *)__alloc_dma_pages(get_pages(size));

	if (ret) {
		memset(ret, 0, size);
		*dma_handle = virt_to_phys(ret);
	}

	return ret;
}
EXPORT_SYMBOL(dma_alloc_coherent);

void
dma_free_coherent(struct device *dev, size_t size, void *vaddr,
		  dma_addr_t dma_handle)
{
	__free_dma_pages((unsigned long)vaddr, get_pages(size));
}
EXPORT_SYMBOL(dma_free_coherent);

/*
 * Dummy functions defined for some existing drivers
 */

dma_addr_t
dma_map_single(struct device *dev, void *ptr, size_t size,
	       enum dma_data_direction direction)
{
	BUG_ON(direction == DMA_NONE);

	invalidate_dcache_range((unsigned long)ptr,
			(unsigned long)ptr + size);

	return (dma_addr_t) ptr;
}
EXPORT_SYMBOL(dma_map_single);

int
dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
	   enum dma_data_direction direction)
{
	int i;

	BUG_ON(direction == DMA_NONE);

	for (i = 0; i < nents; i++)
		invalidate_dcache_range(sg_dma_address(&sg[i]),
					sg_dma_address(&sg[i]) +
					sg_dma_len(&sg[i]));

	return nents;
}
EXPORT_SYMBOL(dma_map_sg);

void dma_unmap_single(struct device *dev, dma_addr_t dma_addr, size_t size,
		enum dma_data_direction direction)
{
	BUG_ON(direction == DMA_NONE);
}
EXPORT_SYMBOL(dma_unmap_single);

void dma_unmap_sg(struct device *dev, struct scatterlist *sg,
		int nhwentries, enum dma_data_direction direction)
{
	BUG_ON(direction == DMA_NONE);
}
EXPORT_SYMBOL(dma_unmap_sg);


text:
@interface AddTopicViewController : UIViewController

@end


text:
"""
asyncnntp.py - An asynchronous NNTP client.
"""
import asyncore
import asynchat
import collections
import logging
import nntplib
import socket
import sys
import thread
import time

try:
    import ssl
except ImportError:
    _have_ssl = False
else:
    _have_ssl = True

CRLF = '\r\n'

SSL_PORTS = [443, 563]

LONG_RESP_CODES = ('100',      # HELP
                   '101',      # CAPABILITIES
                   '211',      # LISTGROUP (also GROUP, but *not* multi-line)
                   '215',      # LIST
                   '220',      # ARTICLE
                   '221',      # HEAD
                   '222',      # BODY
                   '224',      # OVER
                   '225',      # HDR
                   '230',      # NEWNEWS
                   '231',      # NEWGROUPS
                   '282')      # ???

LONG_RESP_COMMANDS = ('HELP',
                      'CAPABILITIES',
                      'LISTGROUP',
                      'LIST',
                      'ARTICLE',
                      'HEAD',
                      'BODY',
                      'OVER',
                      'HDR',
                      'NEWNEWS',
                      'NEWGROUPS')

COMMANDS = {
    "DATE":         ("111",),
    "HELP":         ("100",),
    "NEWGROUPS":    ("231",),
    "NEWNEWS":      ("230",),
    "LIST":         ("215",),
}

def loop_forever(target=None, *args, **kwargs):
    """
    Runs ``asyncore.loop`` in a separate thread. ``target`` should be a function
    to be called during the loop (can also be None).  ``args`` and ``kwargs``
    should be valid arguments to ``asyncore.loop``.  This function will return
    control to the calling thread.
    """
    def loop():
        while True:
            asyncore.loop(*args, **kwargs)
            if target:
                target()
    thread.start_new_thread(loop, ())

class Request:
    """

    """
    def __init__(self, nntp, command, *args, **kwargs):
        self.command          = command.upper()
        self.args             = args
        self.response_code    = None
        self.response_message = ""
        self.response_data    = []
        self.multiline        = self.command in LONG_RESP_COMMANDS
        self.lines            = None
        self.logger           = logging.getLogger("NNTP::Request")
        self.callbacks        = kwargs.get("callbacks", None)
        self.nntp             = nntp

    def __repr__(self):
        return "<%s>" % str(self)

    def __str__(self):
        return "Request: %s %s" % (self.command, " ".join(self.args))

    def getline(self):
        """
        Returns a fully formatted request, including terminating characters.
        """
        cmd = [self.command]
        for arg in self.args:
            if arg:
                cmd.append(str(arg))
        return " ".join(cmd).strip()+CRLF

    def getterminator(self):
        """
        Returns the appropriate terminator for the given request, depending on
        whether a single-line or multi-line response is expected.
        """
        if self.multiline:
            return "%s.%s" % (CRLF,CRLF)
        return CRLF

    def get_callbacks(self):
        return self.callbacks or ("on_%s" % "_".join(self.command.lower().split()),)

    def handle_data(self, data):
        """
        Called when data has been received from the socket.
        """
        self.logger.debug("handle_data()")
        self.response_data.append(data)

    def finish(self):
        """
        Called once all data has been received.
        """
        self.logger.debug("%s -> finish()" % self)
        self.lines = ''.join(self.response_data).split(CRLF)

        if len(self.lines) < 1:
            raise nntplib.NNTPDataError("No data received")

        self.response_code, self.response_message = self.lines[0][:3], \
                                                    self.lines[0][3:].strip()

        self.logger.debug("code = %s" % self.response_code)
        self.logger.debug("msg  = %s" % self.response_message)

class NNTP(asynchat.async_chat):
    """

    """
    def __init__(self, host, port=119, user=None, password=None,
                 readermode=None, usenetrc=True, use_ssl=None,
                 interactive=False):

        self.host        = host
        self.port        = port
        self.__username  = user
        self.__password  = password
        self.logger      = logging.getLogger('NNTP')
        self.interactive = interactive

        self.use_ssl = use_ssl
        if self.use_ssl is None:
            self.use_ssl = port in SSL_PORTS
        self.established = not self.use_ssl

        self._request = None
        self._fifo    = asynchat.fifo()

        asynchat.async_chat.__init__(self)

        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)

        self.connect((host, port))

        self._connected = False
        self.welcome    = ""

    def reconnect(self):
        self.socket.close()
        del self.socket

        if hasattr(self, "_socket"):
            self._socket.close()
            del self._socket

        self.established = not self.use_ssl
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((self.host, self.port))

    def _handshake(self):
        try:
            self.socket.do_handshake()
        except ssl.SSLError as err:
            self.logger.debug("SSL handshake not complete")
            self.want_read = self.want_write = False
            if err.args[0] == ssl.SSL_ERROR_WANT_READ:
                self.want_read = True
            elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
                self.want_write = True
            else:
                raise
        else:
            self.logger.debug("SSL handshake complete")
            self.want_read = self.want_write = True
            self.established = True

    def _do_callback(self, callbacks, *args, **kwargs):
        if isinstance(callbacks, basestring):
            callbacks = (callbacks,)

        if not isinstance(callbacks, collections.Iterable):
            self.logger.error("Callbacks is not an iterable")
            return

        for callback in callbacks:
            if not callback:
                continue

            if isinstance(callback, basestring):
                # Try internal callback first
                _name = "_%s" % callback
                if hasattr(self, _name):
                    self.logger.debug("Calling %s()" % _name)
                    getattr(self, _name)(*args, **kwargs)

                # Then try user-defined callback
                if hasattr(self, callback):
                    self.logger.debug("Calling %s()" % callback)
                    getattr(self, callback)(*args, **kwargs)

            elif callable(callback):
                callback(*args, **kwargs)

    def handle_connect(self):
        """
        If SSL has been requested, this method will wrap the socket in SSL.  If
        SSL has been requested but is not available a ``ValueError`` will be
        raised.
        """
        self.logger.debug('handle_connect()')

        # Default terminator
        self.set_terminator(CRLF)

        # See if we need to wrap the socket in SSL
        if self.use_ssl:
            if not _have_ssl:
                self.logger.error("SSL requested but not available")
                raise ValueError("SSL not available")

            self.logger.debug('Wrapping in SSL')
            self._socket = self.socket
            self.socket = ssl.wrap_socket(self._socket,
                                          do_handshake_on_connect=False)

    def handle_write(self):
        """
        Overload the default ``handle_read`` method to support SSL handshake.
        """
        if self.established:
            return self.initiate_send()
        self._handshake()

    def recv(self, buffer_size):
        """
        The default ``recv`` function does not support SSL sockets which
        sometimes will fail when they appear readable but in fact aren't ready
        to be read yet.  This get's around that issue by catching the error.  If
        SSL isn't available (or enabled) then this behaves just like the default
        implementation.
        """
        try:
            return asynchat.async_chat.recv(self, buffer_size)
        except Exception as e:
            if _have_ssl:
                if isinstance(e, ssl.SSLError) and e.args[0] == ssl.SSL_ERROR_WANT_READ:
                    return ''
            raise e

    def _handle_read(self):
        """
        We can't use the default ``handle_read`` here because it doesn't support
        SSL sockets.  This fix is from: http://bugs.python.org/issue16976
        """
        try:
            data = self.recv (self.ac_in_buffer_size)
        except socket.error, why:
            self.handle_error()
            return

        if hasattr(self.socket, 'ssl_version'):
        # Fix for SSL wrapped sockets, checks if there is any data pending in
        # the SSL Socket's internal buffer and recv's it before contining.
            ssl_data_remainder = ''
            amount_of_data_left_over = self.socket.pending()
            while amount_of_data_left_over > 0:
                # while the ssl socket still has some data pending
                try:
                    # get the remaining data
                    ssl_data_remainder += self.recv(amount_of_data_left_over)
                except socket.error, why:
                    self.handle_error()
                    return
                # check if there is anymore remaining
                amount_of_data_left_over = self.socket.pending()
            data += ssl_data_remainder  # add the remainder to the data
        self.ac_in_buffer = self.ac_in_buffer + data

        # Continue to search for self.terminator in self.ac_in_buffer,
        # while calling self.collect_incoming_data.  The while loop
        # is necessary because we might read several data+terminator
        # combos with a single recv(4096).

        while self.ac_in_buffer:
            lb = len(self.ac_in_buffer)
            terminator = self.get_terminator()
            if not terminator:
                # no terminator, collect it all
                self.collect_incoming_data (self.ac_in_buffer)
                self.ac_in_buffer = ''
            elif isinstance(terminator, int) or isinstance(terminator, long):
                # numeric terminator
                n = terminator
                if lb < n:
                    self.collect_incoming_data (self.ac_in_buffer)
                    self.ac_in_buffer = ''
                    self.terminator = self.terminator - lb
                else:
                    self.collect_incoming_data (self.ac_in_buffer[:n])
                    self.ac_in_buffer = self.ac_in_buffer[n:]
                    self.terminator = 0
                    self.found_terminator()
            else:
                # 3 cases:
                # 1) end of buffer matches terminator exactly:
                #    collect data, transition
                # 2) end of buffer matches some prefix:
                #    collect data to the prefix
                # 3) end of buffer does not match any prefix:
                #    collect data
                terminator_len = len(terminator)
                index = self.ac_in_buffer.find(terminator)
                if index != -1:
                    # we found the terminator
                    if index > 0:
                        # don't bother reporting the empty string
                        # (source of subtle bugs)
                        self.collect_incoming_data (self.ac_in_buffer[:index])
                    self.ac_in_buffer = self.ac_in_buffer[index+terminator_len:]
                    # This does the Right Thing if the terminator
                    # is changed here.
                    self.found_terminator()
                else:
                    # check for a prefix of the terminator
                    index = asynchat.find_prefix_at_end (self.ac_in_buffer, terminator)
                    if index:
                        if index != lb:
                            # we found a prefix, collect up to the prefix
                            self.collect_incoming_data (self.ac_in_buffer[:-index])
                            self.ac_in_buffer = self.ac_in_buffer[-index:]
                        break
                    else:
                        # no prefix, collect it all
                        self.collect_incoming_data (self.ac_in_buffer)
                        self.ac_in_buffer = ''

    def handle_read(self):
        """
        Overload the default ``handle_read`` method to support SSL handshake
        and also use the custom ``_handle_read`` method.
        """
        if self.established:
            return self._handle_read()
        self._handshake()

    def collect_incoming_data(self, data):
        self.logger.debug('collect_incoming_data() -> (%d)', len(data))

        #print "data =", `data`
        if self._request is None:
            notempty, self._request = self._fifo.pop()

        if self._request is None:
            # If we still don't have a request, then we need to construct one
            self._request = Request(self, "UNKNOWN")

        self._request.handle_data(data)

    def found_terminator(self):
        #if self.interactive:
        #    time.sleep(0.3)

        self.logger.debug('found_terminator()')

        # This should never happen
        if not self._request:
            self.logger.error('No request found')
            return

        # Finish the request
        self._request.finish()

        # Reset request
        request = self._request
        self._request = None

        # Reset terminator
        self.set_terminator(CRLF)

        if request.command == "UNKNOWN":
            # An "UNKNOWN" request means that we received an unsolicited
            # response from the server.  This happens on initial connection
            # to the server.  Some servers also disconnect the client due to
            # idleness
            code = request.response_code
            if code in ("200", "201"):
                self._do_callback("on_connect", request)
            elif code == "400":
                # XXX: Is this general enough?
                self._do_callback("on_disconnect", request)
            else:
                self.logger.warn("UNKNOWN Request; code %s" % request.response_code)

        # Get the name of the callback and try to call it
        callbacks = request.get_callbacks()
        self._do_callback(callbacks, request)

        # Send the next request in the FIFO
        self.sendrequest()

    def addrequest(self, request):
        """
        Adds a :class:`Request` to the request FIFO.  If there isn't a currently
        pending request then this will also initiate the request.
        """
        self._fifo.push(request)
        if self._request is None:
            self.sendrequest()

    def sendrequest(self):
        """
        Gets the next :class:`Request` from the request FIFO and sends the
        command to the server.
        """
        #if not self._connected:
        #    # We're not ready yet
        #    return

        _, request = self._fifo.pop()

        if request:
            self._request = request

            terminator = self._request.getterminator()

            self.logger.debug("terminator = %s" % `terminator`)
            self.set_terminator(terminator)

            line = self._request.getline()
            self.logger.debug("sending command: %s" % line.strip())
            self.push(line)

    def ready(self):
        return self._connected

    def verbose(self, stream=sys.stdout, level=logging.DEBUG,
                format="[%(levelname)-8s] %(message)s"):
        logging.basicConfig(stream=stream, level=level, format=format)

    ############################################################################
    # Client functions
    ############################################################################
    def username(self, username, callback=None):
        """
        Send an
        `AUTHINFO USER <https://tools.ietf.org/html/rfc2980#section-3.1.1>`_
        command with the given ``username``.

        :callback: ``on_username``
        """
        self.addrequest(Request(self, "AUTHINFO", "USER", username,
                                callbacks=(callback, "on_username")))

    def password(self, password, callback=None):
        """
        Send an
        `AUTHINFO PASS <https://tools.ietf.org/html/rfc2980#section-3.1.1>`_
        command with the given ``password``.

        :callback: ``on_username``.
        """
        self.addrequest(Request(self, "AUTHINFO", "PASS", password,
                                callbacks=(callback, "on_password")))

    def capabilities(self, callback=None):
        """
        Send a `CAPABILITIES <https://tools.ietf.org/html/rfc3977#section-5.2>`_
        command.

        :callback: `on_capabilities`
        """
        self.addrequest(Request(self, "CAPABILITIES",
                                callbacks=(callback, "on_capabilities")))

    def mode_reader(self, callback=None):
        """
        Send a `MODE READER <https://tools.ietf.org/html/rfc3977#section-5.3>`_
        command.

        :callback: ``on_mode_reader``
        """
        self.addrequest(Request(self, "MODE READER",
                                callbacks=(callback, "on_mode_reader")))

    def quit(self, callback=None):
        """
        Send a `QUIT <https://tools.ietf.org/html/rfc3977#section-5.4>`_
        command.

        :callback: ``on_quit``
        """
        self.addrequest(Request(self, "QUIT",
                                callbacks=(callback, "on_quit")))

    def group(self, name, callback=None):
        """
        Send a `GROUP <https://tools.ietf.org/html/rfc3977#section-6.1.1>`_
        command, where ``name`` is a `string` of the desired group.

        :callback: ``do_group``
        """
        self.addrequest(Request(self, "GROUP", name,
                                callbacks=(callback, "on_group")))

    def listgroup(self, group=None, range=None, callback=None):
        """
        Send a `LISTGROUP <https://tools.ietf.org/html/rfc3977#section-6.1.2>`_
        command.  If ``group`` is provided, then that group will be selected,
        otherwise the previously selected group will be used.  See link for
        format of ``range``.

        :callback: ``on_listgroup``
        """
        self.addrequest(Request(self, "LISTGROUP", group, range,
                                callbacks=(callback, "on_listgroup")))

    def last(self, callback=None):
        """
        Send a `LAST <https://tools.ietf.org/html/rfc3977#section-6.1.3>`_
        command.

        :callback: ``on_last``
        """
        self.addrequest(Request(self, "LAST",
                                callbacks=(callback, "on_last")))

    def next(self, callback=None):
        """
        Send a `NEXT <https://tools.ietf.org/html/rfc3977#section-6.1.4>`_
        command.

        :callback: ``on_next``
        """
        self.addrequest(Request(self, "NEXT",
                                callbacks=(callback, "on_next")))

    def article(self, article, callback=None):
        """
        Send a `ARTICLE <https://tools.ietf.org/html/rfc3977#section-6.2.1>`_
        command.  If a group has been selected (via a prior call to
        :func:`group`), then ``article`` can be an integer.  Alternativley,
        ``article`` can be a unique message-id string of the format
        ``<message-id>``.

        :callback: ``on_article``
        """
        self.addrequest(Request(self, "ARTICLE", article,
                                callbacks=(callback, "on_article")))

    def head(self, article, callback=None):
        """
        Send a `HEAD <https://tools.ietf.org/html/rfc3977#section-6.2.2>`_
        command.  See :func:`article` for a description of allowable forms for
        ``article``.

        :callback: ``on_head``
        """
        self.addrequest(Request(self, "HEAD", article,
                                callbacks=(callback, "on_head")))

    def body(self, article, callback=None):
        """
        Send a `BODY <https://tools.ietf.org/html/rfc3977#section-6.2.3>`_
        command.  See :func:`article` for a description of allowable forms for
        ``article``.

        :callback: ``on_body``
        """
        self.addrequest(Request(self, "BODY", article,
                                callbacks=(callback, "on_body")))

    def stat(self, article, callback=None):
        """
        Send a `STAT <https://tools.ietf.org/html/rfc3977#section-6.2.4>`_
        command.  See :func:`article` for a description of allowable forms for
        ``article``.

        :callback: ``on_stat``
        """
        self.addrequest(Request(self, "STAT", article,
                                callbacks=(callback, "on_stat")))

    def date(self, callback=None):
        """
        Send a `DATE <https://tools.ietf.org/html/rfc3977#section-7.1>`_
        command.

        :callback: ``on_date``
        """
        self.addrequest(Request(self, "DATE",
                                callbacks=(callback, "on_date")))

    def list(self, callback=None):
        """
        Send a `LIST <https://tools.ietf.org/html/rfc3977#section-7.6.1>`_
        command.

        :callback: ``on_list``
        """
        self.addrequest(Request(self, "LIST",
                                callbacks=(callback, "on_list")))

    ############################################################################
    # Internal callback functions
    ############################################################################
    def _on_connect(self, request):
        self.welcome = request.response_message

        # If we were given a username, try to authenticate
        if self.__username:
            self.username(self.__username)
        else:
            self._connected = True
            self._do_callback("on_ready")

    def _on_quit(self, request):
        self._connected = False

    def _on_disconnect(self, request):
        self._connected = False

    def _on_username(self, request):
        if request.response_code == "381":
            # Password is required
            if self.__password:
                self.password(self.__password)
            else:
                self.logger.error("Password required but not provided")
        elif request.response_code == "281":
            self._connected = True
            self._do_callback("on_ready")

    def _on_password(self, request):
        if request.response_code == "281":
            self._connected = True
            self._do_callback("on_ready")