text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xbyg_plus.silicon">

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:roundIcon="@drawable/icon"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activity.LogoActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.MainActivity"
            android:configChanges="orientation|screenSize"></activity>

        <service android:name=".service.InstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".service.NotificationService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <receiver android:name=".service.NotificationService$BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <meta-data
            android:name="io.fabric.ApiKey"
            android:value="98fbd85ed2c8b25f6642860628167c756463726a" />
    </application>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>


text:
use strict;
use warnings;
use utf8;

use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::Utils::SearchStreamHandler;
use Google::Ads::GoogleAds::V12::Resources::AdGroupAsset;
use Google::Ads::GoogleAds::V12::Resources::Asset;
use Google::Ads::GoogleAds::V12::Resources::CampaignAsset;
use Google::Ads::GoogleAds::V12::Common::Money;
use Google::Ads::GoogleAds::V12::Common::PromotionAsset;
use Google::Ads::GoogleAds::V12::Enums::ExtensionTypeEnum qw(PROMOTION);
use
  Google::Ads::GoogleAds::V12::Services::AdGroupAssetService::AdGroupAssetOperation;
use Google::Ads::GoogleAds::V12::Services::AssetService::AssetOperation;
use
  Google::Ads::GoogleAds::V12::Services::CampaignAssetService::CampaignAssetOperation;
use
  Google::Ads::GoogleAds::V12::Services::GoogleAdsService::SearchGoogleAdsStreamRequest;
use Google::Ads::GoogleAds::V12::Utils::ResourceNames;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);

# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id  = "INSERT_CUSTOMER_ID_HERE";
my $feed_item_id = "INSERT_FEED_ITEM_ID_HERE";

sub migrate_promotion_feed_to_asset {
  my ($api_client, $customer_id, $feed_item_id) = @_;

  # Get the GoogleAdsService client.
  my $google_ads_service = $api_client->GoogleAdsService();

  my $extension_feed_item_resource_name =
    Google::Ads::GoogleAds::V12::Utils::ResourceNames::extension_feed_item(
    $customer_id, $feed_item_id);

  # Get the target extension feed item.
  my $extension_feed_item =
    get_extension_feed_item($google_ads_service, $customer_id, $feed_item_id);

  # Get all campaign IDs associated with the extension feed item.
  my @campaign_ids =
    get_targeted_campaign_ids($google_ads_service, $customer_id,
    $extension_feed_item_resource_name);

  # Get all ad group IDs associated with the extension feed item.
  my @ad_group_ids =
    get_targeted_ad_group_ids($google_ads_service, $customer_id,
    $extension_feed_item_resource_name);

  # Create a new Promotion asset that matches the target extension feed item.
  my $promotion_asset_resource_name =
    create_promotion_asset_from_feed($api_client, $customer_id,
    $extension_feed_item);

  # Associate the new Promotion asset with the same campaigns as the original.
  associate_asset_with_campaigns($api_client, $customer_id,
    $promotion_asset_resource_name,
    @campaign_ids);

  # Associate the new Promotion asset with the same ad groups as the original.
  associate_asset_with_ad_groups($api_client, $customer_id,
    $promotion_asset_resource_name,
    @ad_group_ids);

  return 1;
}

# Gets the requested Promotion-type extension feed item.
#
# Note that extension feed items pertain to feeds that were created by Google.
# Use FeedService to instead retrieve a user-created Feed.
sub get_extension_feed_item {
  my ($google_ads_service, $customer_id, $feed_item_id) = @_;

  # Create a query that will retrieve the requested Promotion-type extension
  # feed item and ensure that all fields are populated.
  my $extension_feed_item_query = "
        SELECT
            extension_feed_item.id,
            extension_feed_item.ad_schedules,
            extension_feed_item.device,
            extension_feed_item.status,
            extension_feed_item.start_date_time,
            extension_feed_item.end_date_time,
            extension_feed_item.targeted_campaign,
            extension_feed_item.targeted_ad_group,
            extension_feed_item.promotion_feed_item.discount_modifier,
            extension_feed_item.promotion_feed_item.final_mobile_urls,
            extension_feed_item.promotion_feed_item.final_url_suffix,
            extension_feed_item.promotion_feed_item.final_urls,
            extension_feed_item.promotion_feed_item.language_code,
            extension_feed_item.promotion_feed_item.money_amount_off.amount_micros,
            extension_feed_item.promotion_feed_item.money_amount_off.currency_code,
            extension_feed_item.promotion_feed_item.occasion,
            extension_feed_item.promotion_feed_item.orders_over_amount.amount_micros,
            extension_feed_item.promotion_feed_item.orders_over_amount.currency_code,
            extension_feed_item.promotion_feed_item.percent_off,
            extension_feed_item.promotion_feed_item.promotion_code,
            extension_feed_item.promotion_feed_item.promotion_end_date,
            extension_feed_item.promotion_feed_item.promotion_start_date,
            extension_feed_item.promotion_feed_item.promotion_target,
            extension_feed_item.promotion_feed_item.tracking_url_template
        FROM extension_feed_item
        WHERE
            extension_feed_item.extension_type = 'PROMOTION'
            AND extension_feed_item.id = $feed_item_id
        LIMIT 1";

  my $fetched_extension_feed_item;

  # Issue a search request to get the extension feed item contents.
  my $search_stream_request =
    Google::Ads::GoogleAds::V12::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
    ->new({
      customerId => $customer_id,
      query      => $extension_feed_item_query
    });

  my $search_stream_handler =
    Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
      service => $google_ads_service,
      request => $search_stream_request
    });

  $search_stream_handler->process_contents(
    sub {
      my $google_ads_row = shift;
      $fetched_extension_feed_item = $google_ads_row->{extensionFeedItem};
    });

  # Create a query to retrieve any URL customer parameters attached to the
  # feed item.
  my $url_custom_parameters_query = "
        SELECT feed_item.url_custom_parameters
        FROM feed_item
        WHERE feed_item.id = $feed_item_id";

  # Issue a search request to get any URL custom parameters.
  $search_stream_request =
    Google::Ads::GoogleAds::V12::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
    ->new({
      customerId => $customer_id,
      query      => $url_custom_parameters_query
    });

  $search_stream_handler =
    Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
      service => $google_ads_service,
      request => $search_stream_request
    });

  $search_stream_handler->process_contents(
    sub {
      my $google_ads_row = shift;
      push
        @{$fetched_extension_feed_item->{promotionFeedItem}{urlCustomParameters}
        }, @{$google_ads_row->{feedItem}{urlCustomParameters}};
    });

  printf "Retrieved details for ad extension with ID %d.\n",
    $fetched_extension_feed_item->{id};

  return $fetched_extension_feed_item;
}

# Finds and returns all of the campaigns that are associated with the specified
# Promotion extension feed item.
# [START migrate_promotion_feed_to_asset_1]
sub get_targeted_campaign_ids {
  my ($google_ads_service, $customer_id, $extension_feed_item_resource_name) =
    @_;

  my @campaign_ids;

  my $query = "
        SELECT campaign.id, campaign_extension_setting.extension_feed_items
        FROM campaign_extension_setting
        WHERE campaign_extension_setting.extension_type = 'PROMOTION'
          AND campaign.status != 'REMOVED'";

  my $search_stream_request =
    Google::Ads::GoogleAds::V12::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
    ->new({
      customerId => $customer_id,
      query      => $query
    });

  my $search_stream_handler =
    Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
      service => $google_ads_service,
      request => $search_stream_request
    });

  $search_stream_handler->process_contents(
    sub {
      my $google_ads_row = shift;

      # Add the campaign ID to the list of IDs if the extension feed item
      # is associated with this extension setting.
      if (grep { $_ eq $extension_feed_item_resource_name }
        @{$google_ads_row->{campaignExtensionSetting}{extensionFeedItems}})
      {
        printf
          "Found matching campaign with ID $google_ads_row->{campaign}{id}.\n";
        push @campaign_ids, $google_ads_row->{campaign}{id};
      }
    });

  return @campaign_ids;
}
# [END migrate_promotion_feed_to_asset_1]

# Finds and returns all of the ad groups that are associated with the specified
# Promotion extension feed item.
sub get_targeted_ad_group_ids {
  my ($google_ads_service, $customer_id, $extension_feed_item_resource_name) =
    @_;

  my @ad_group_ids;

  my $query = "
        SELECT ad_group.id, ad_group_extension_setting.extension_feed_items
        FROM ad_group_extension_setting
        WHERE ad_group_extension_setting.extension_type = 'PROMOTION'
          AND ad_group.status != 'REMOVED'";

  my $search_stream_request =
    Google::Ads::GoogleAds::V12::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
    ->new({
      customerId => $customer_id,
      query      => $query
    });

  my $search_stream_handler =
    Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
      service => $google_ads_service,
      request => $search_stream_request
    });

  $search_stream_handler->process_contents(
    sub {
      my $google_ads_row = shift;

      # Add the ad group ID to the list of IDs if the extension feed item
      # is associated with this extension setting.
      if (grep { $_ eq $extension_feed_item_resource_name }
        @{$google_ads_row->{adGroupExtensionSetting}{extensionFeedItems}})
      {
        printf
          "Found matching ad group with ID $google_ads_row->{adGroup}{id}.\n";
        push @ad_group_ids, $google_ads_row->{adGroup}{id};
      }
    });

  return @ad_group_ids;
}

# Create a Promotion asset that copies values from the specified extension feed
# item.
# [START migrate_promotion_feed_to_asset]
sub create_promotion_asset_from_feed {
  my ($api_client, $customer_id, $extension_feed_item) = @_;

  my $promotion_feed_item = $extension_feed_item->{promotionFeedItem};

  # Create the Promotion asset.
  my $asset = Google::Ads::GoogleAds::V12::Resources::Asset->new({
      name => "Migrated from feed item #" . $extension_feed_item->{id},
      trackingUrlTemplate => $promotion_feed_item->{trackingUrlTemplate},
      finalUrlSuffix      => $promotion_feed_item->{finalUrlSuffix},
      promotionAsset      =>
        Google::Ads::GoogleAds::V12::Common::PromotionAsset->new({
          promotionTarget     => $promotion_feed_item->{promotionTarget},
          discountModifier    => $promotion_feed_item->{discountModifier},
          redemptionStartDate => $promotion_feed_item->{promotionStartDate},
          redemptionEndDate   => $promotion_feed_item->{promotionEndDate},
          occasion            => $promotion_feed_item->{occasion},
          languageCode        => $promotion_feed_item->{languageCode}})});

  push @{$asset->{finalUrls}}, @{$promotion_feed_item->{finalUrls}};

  # Copy optional fields if present in the existing extension.
  if (defined($extension_feed_item->{adSchedules})) {
    push @{$asset->{promotionAsset}{adScheduleTargets}},
      @{$extension_feed_item->{adSchedules}};
  }

  if (defined($promotion_feed_item->{finalMobileUrls})) {
    push @{$asset->{finalMobileUrls}},
      @{$promotion_feed_item->{finalMobileUrls}};
  }

  if (defined($promotion_feed_item->{urlCustomParameters})) {
    push @{$asset->{urlCustomParameters}},
      @{$promotion_feed_item->{urlCustomParameters}};
  }

  # Either percentOff or moneyAmountOff must be set.
  if (defined($promotion_feed_item->{percentOff})) {
    # Adjust the percent off scale when copying.
    $asset->{promotionAsset}{percentOff} =
      $promotion_feed_item->{percentOff} / 100;
  } else {
    $asset->{promotionAsset}{moneyAmountOff} =
      Google::Ads::GoogleAds::V12::Common::Money->new({
        amountMicros => $promotion_feed_item->{moneyAmountOff}{amountMicros},
        currencyCode => $promotion_feed_item->{moneyAmountOff}{currencyCode}});
  }

  # Either promotionCode or ordersOverAmount must be set.
  if (defined($promotion_feed_item->{promotionCode})) {
    $asset->{promotionAsset}{promotionCode} =
      $promotion_feed_item->{promotionCode};
  } else {
    $asset->{promotionAsset}{ordersOverAmount} =
      Google::Ads::GoogleAds::V12::Common::Money->new({
        amountMicros => $promotion_feed_item->{ordersOverAmount}{amountMicros},
        currencyCode => $promotion_feed_item->{ordersOverAmount}{currencyCode}}
      );
  }

  # Set the start and end dates if set in the existing extension.
  if (defined($extension_feed_item->{startDateTime})) {
    $asset->{promotionAsset}{startDate} =
      substr($extension_feed_item->{startDateTime},
      0, index($extension_feed_item->{startDateTime}, ' '));
  }

  if (defined($extension_feed_item->{endDateTime})) {
    $asset->{promotionAsset}{endDate} =
      substr($extension_feed_item->{endDateTime},
      0, index($extension_feed_item->{endDateTime}, ' '));
  }

  # Build an operation to create the Promotion asset.
  my $operation =
    Google::Ads::GoogleAds::V12::Services::AssetService::AssetOperation->new({
      create => $asset
    });

  # Issue the request and return the resource name of the new Promotion asset.
  my $response = $api_client->AssetService()->mutate({
      customerId => $customer_id,
      operations => [$operation]});

  printf
    "Created Promotion asset with resource name '%s'.\n",
    $response->{results}[0]{resourceName};

  return $response->{results}[0]{resourceName};
}
# [END migrate_promotion_feed_to_asset]

# Associates the specified Promotion asset with the specified campaigns.
# [START migrate_promotion_feed_to_asset_2]
sub associate_asset_with_campaigns {
  my ($api_client, $customer_id, $promotion_asset_resource_name, @campaign_ids)
    = @_;

  if (scalar(@campaign_ids) == 0) {
    printf "Asset was not associated with any campaigns.\n";
    return ();
  }

  my $operations = [];

  foreach my $campaign_id (@campaign_ids) {
    my $campaign_asset =
      Google::Ads::GoogleAds::V12::Resources::CampaignAsset->new({
        asset     => $promotion_asset_resource_name,
        fieldType => PROMOTION,
        campaign => Google::Ads::GoogleAds::V12::Utils::ResourceNames::campaign(
          $customer_id, $campaign_id
        )});

    my $operation =
      Google::Ads::GoogleAds::V12::Services::CampaignAssetService::CampaignAssetOperation
      ->new({
        create => $campaign_asset
      });

    push @$operations, $operation;
  }

  my $response = $api_client->CampaignAssetService()->mutate({
    customerId => $customer_id,
    operations => $operations
  });

  foreach my $result (@{$response->{results}}) {
    printf "Created campaign asset with resource name '%s'.\n",
      $result->{resourceName};
  }
}
# [END migrate_promotion_feed_to_asset_2]

# Associates the specified Promotion asset with the specified ad groups.
sub associate_asset_with_ad_groups {
  my ($api_client, $customer_id, $promotion_asset_resource_name, @ad_group_ids)
    = @_;

  if (scalar(@ad_group_ids) == 0) {
    printf "Asset was not associated with any ad groups.\n";
    return ();
  }

  my $operations = [];

  foreach my $ad_group_id (@ad_group_ids) {
    my $ad_group_asset =
      Google::Ads::GoogleAds::V12::Resources::AdGroupAsset->new({
        asset     => $promotion_asset_resource_name,
        fieldType => PROMOTION,
        adGroup => Google::Ads::GoogleAds::V12::Utils::ResourceNames::ad_group(
          $customer_id, $ad_group_id
        )});

    my $operation =
      Google::Ads::GoogleAds::V12::Services::AdGroupAssetService::AdGroupAssetOperation
      ->new({
        create => $ad_group_asset
      });

    push @$operations, $operation;
  }

  my $response = $api_client->AdGroupAssetService()->mutate({
    customerId => $customer_id,
    operations => $operations
  });

  foreach my $result (@{$response->{results}}) {
    printf "Created ad group asset with resource name '%s'.\n",
      $result->{resourceName};
  }
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();

# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);

# Parameters passed on the command line will override any parameters set in code.
GetOptions(
  "customer_id=s"  => \$customer_id,
  "feed_item_id=i" => \$feed_item_id
);

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2)
  if not check_params($customer_id, $feed_item_id);

# Call the example.
migrate_promotion_feed_to_asset($api_client, $customer_id =~ s/-//gr,
  $feed_item_id);

=pod

=head1 NAME

migrate_promotion_feed_to_asset

=head1 DESCRIPTION

This code example retrieves the full details of a Promotion Feed-based extension
and creates a matching Promotion asset-based extension. The new Asset-based
extension will then be associated with the same campaigns and ad groups as the
original Feed-based extension.

Once copied, you should remove the Feed-based extension; see
remove_entire_sitelink_campaign_extension_setting.pl for an example.

=head1 SYNOPSIS

migrate_promotion_feed_to_asset.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -feed_item_id               ID of the ExtensionFeedItem to migrate.

=cut

redpajama_set_name: RedPajamaGithub


text:
title:  "Innerlike vertroue op die beloftes"
date:  17/06/2021
---

'n Verhaal word vertel van die beroemde Kardinaal Bellarmine, die bekende Katolieke apologeet wat regdeur sy lewe teen die boodskap van regverdiging deur toegerekende geregtigheid alleenlik, geveg het. Op sy sterfbed was die kruisbeelde en die verdienstes van die heiliges aan hom voorgehou om aan hom sekerheid en gerusstelling te bring voor hy sou sterf. Maar Bellarmine het gesê, "Neem dit weg. Ek dink dit is veiliger om op die verdienstes van Christus te vertrou."

Vir baie mense wat aan die einde van hulle lewens kom en dan terugkyk, lyk hulle dade en hulle werke vrugteloos en nikswerd om verlossing by 'n heilige God te verdien nie, en daarom die geregtigheid van Christus nodig het. Maar die goeie nuus is dat ons nie hoef te wag vir ons naderende dood voordat ons sekuriteit by die Here kan hê nie. Die hele verbond is steeds op die gewaarborgde beloftes van God gegrond, beloftes wat ons lewens nou kan verbeter.

**Slaan die volgende verse na en beantwoord die vraag wat by elkeen gevra word in die konteks van die ontwikkeling, instandhouding en versterking van jou verbondsverhouding met God:**

`Psalm 34:9 (Hoe kan jy God se goedheid smaak?)`

`Matthéüs 11:30 (Wat is dit wat Christus vir ons gedoen het wat hierdie juk sag maak?)`

`Romeine 5:1 (Wat het regverdiging met vrede te doen?)`

`Filippense 2:7, 8 (Hoeveel het jy uit Christus se ondervinding gebaat?)`

Ondersoek jou lewe biddend en vra jouself watter dinge doen ek wat my verhouding met God versterk, en watter dinge breek dit af? Watter veranderinge moet ek maak?


text:
import Node from './Node.js';
import Scope from './Scope.js';
import extractNames from './extractNames.js';
import breaksExecution from '../analysis/breaksExecution.js';

const shouldPreserveAfterReturn = {
	FunctionDeclaration: true,
	VariableDeclaration: true,
	ClassDeclaration: true
};

const allowsBlockLessStatement = {
	BlockStatement: true,
	ForStatement: true,
	ForInStatement: true,
	ForOfStatement: true,
	IfStatement: true,
	WhileStatement: true
};

function endsWithCurlyBrace ( statement ) { // TODO can we just use getRightHandSide?
	if ( statement.type === 'IfStatement' ) {
		if ( statement.rewriteAsSequence ) return false;

		if ( statement.alternate ) {
			if ( statement.alternate.type === 'IfStatement' ) {
				return endsWithCurlyBrace( statement.alternate );
			}

			if ( statement.alternate.type !== 'BlockStatement' ) return false;
			if ( statement.alternate.canRemoveCurlies() ) return false;

			return true;
		}

		return statement.consequent.type === 'BlockStatement' && !statement.consequent.canRemoveCurlies();
	}

	if ( /^(?:For(?:In|Of)?|While)Statement/.test( statement.type ) ) {
		return statement.body.type === 'BlockStatement' && !statement.body.canRemoveCurlies();
	}

	if ( statement.type === 'SwitchStatement' ) return true;

	return /(?:Class|Function)Declaration/.test( statement.type );
}

function isVarDeclaration ( node ) {
	return node.kind === 'var';
}

export default class BlockStatement extends Node {
	attachScope ( program, parent ) {
		this.parentIsFunction = /Function/.test( this.parent.type );

		if ( this.parentIsFunction ) {
			this.scope = parent;
		} else {
			this.scope = new Scope({
				block: true,
				parent
			});
		}

		for ( let i = 0; i < this.body.length; i += 1 ) {
			this.body[i].attachScope( program, this.scope );
		}
	}

	canRemoveCurlies () {
		return allowsBlockLessStatement[ this.parent.type ] && ( this.canSequentialise() || ( this.body.length > 0 && this.body.every( isVarDeclaration ) ) );
	}

	// TODO memoize
	canSequentialise () {
		for ( let i = 0; i < this.body.length; i += 1 ) {
			const node = this.body[i];
			if ( !node.skip && !node.canSequentialise() ) return false; // TODO what if it's a block with a late-activated declaration...
		}

		return true;
	}

	// TODO what is this about?
	findVarDeclarations ( varsToHoist ) {
		this.body.forEach( node => {
			if ( node.type === 'VariableDeclaration' && node.kind === 'var' ) {
				node.declarations.forEach( declarator => {
					extractNames( declarator.id ).forEach( identifier => {
						varsToHoist[ identifier.name ] = true;
					});
				});
			} else {
				node.findVarDeclarations( varsToHoist );
			}
		});
	}

	getLeftHandSide () {
		if ( this.body.length > 0 && ( this.canSequentialise() || this.body.every( isVarDeclaration ) ) ) {
			return this.body[0].getLeftHandSide();
		}
		return this;
	}

	getRightHandSide () {
		if ( this.body.length > 0 && ( this.canSequentialise() || this.body.every( isVarDeclaration ) ) ) {
			return this.body[this.body.length - 1].getRightHandSide();
		}
		return this;
	}

	initialise ( program, scope ) {
		let executionIsBroken = false;
		let maybeReturnNode;
		let hasDeclarationsAfterBreak = false;

		let canCollapseReturns = this.parentIsFunction;
		let returnStatements = [];

		for ( let i = 0; i < this.body.length; i += 1 ) {
			const node = this.body[i];

			if ( executionIsBroken ) {
				if ( shouldPreserveAfterReturn[ node.type ] ) {
					hasDeclarationsAfterBreak = true;
					node.initialise( program, this.scope || scope );
				}

				continue;
			}

			maybeReturnNode = breaksExecution( node );
			if ( maybeReturnNode ) executionIsBroken = true;

			node.initialise( program, this.scope || scope );

			if ( canCollapseReturns ) {
				if ( node.preventsCollapsedReturns( returnStatements ) ) {
					canCollapseReturns = false;
				} else {
					// console.log( `${node.type} preventsCollapsedReturns`)
				}
			}
		}

		this.collapseReturnStatements = canCollapseReturns && returnStatements.length;
		this.returnStatements = returnStatements;

		// if `return` is the last line of a function, remove it
		if ( maybeReturnNode && this.parentIsFunction && !hasDeclarationsAfterBreak ) {
			// TODO also capture `return undefined` and `return void 0` etc?
			if ( !maybeReturnNode.argument ) {
				maybeReturnNode.skip = true;
			}
		}
	}

	// TODO remove block.isEmpty() in favour of block.skip — this is a hangover from
	// when variables could get activated after we'd finished initialising a block
	isEmpty () {
		for ( let i = 0; i < this.body.length; i += 1 ) {
			const node = this.body[i];
			if ( !node.skip ) return false;
		}

		return true;
	}

	minify ( code, chars ) {
		if ( this.scope ) {
			this.scope.mangle( code, chars );
		}

		let insertedVarDeclaration = '';

		if ( this.parentIsFunction || this.parent.type === 'Root' ) {
			// if there are any vars inside removed blocks, they need
			// to be declared here
			const hoisted = [];
			this.scope.hoistedVars.forEach( name => {
				const hoistedVar = this.scope.declarations[name];
				if ( hoistedVar.activated ) {
					hoisted.push( hoistedVar.alias || hoistedVar.name );
				}
			});

			if ( hoisted.length ) {
				// see if there's an existing var declaration we can glom these onto
				const varDeclaration = this.scope.varDeclarationNodes.find( node => {
					while ( node !== this ) {
						if ( node.skip ) return false;
						node = node.parent;
					}

					return true;
				});

				if ( varDeclaration ) {
					varDeclaration.rideAlongs = hoisted;
				} else {
					insertedVarDeclaration = `var ${hoisted.join(',')};`;
				}
			}
		}

		const sequentialise = !this.parentIsFunction && this.canSequentialise();
		const removeCurlies = this.canRemoveCurlies();
		const separator = sequentialise ? ',' : ';';

		// remove leading whitespace
		let lastEnd = ( this.parent.type === 'Root' || removeCurlies ) ? this.start : this.start + 1;
		const end = ( this.parent.type === 'Root' || removeCurlies ) ? this.end : this.end - 1;

		const statements = this.body.filter( statement => !statement.skip );
		let lastStatement;

		if ( statements.length ) {
			let nextSeparator = ( ( this.scope && this.scope.useStrict && ( !this.scope.parent || !this.scope.parent.useStrict ) ) ?
				'"use strict";' :
				'' ) + insertedVarDeclaration;

			for ( let i = 0; i < statements.length; i += 1 ) {
				const statement = statements[i];

				statement.minify( code, chars );

				if ( !statement.collapsed ) {
					if ( statement.start > lastEnd ) code.remove( lastEnd, statement.start );

					if ( nextSeparator ) {
						code.appendLeft( lastStatement ? lastStatement.getRightHandSide().end : lastEnd, nextSeparator );
					}

					if ( statement.removed ) {
						nextSeparator = '';
					} else {
						nextSeparator = endsWithCurlyBrace( statement ) ? '' : separator;
					}
				}

				lastEnd = statement.end;

				// remove superfluous semis (TODO is this necessary?)
				while ( code.original[ lastEnd - 1 ] === ';' ) lastEnd -= 1;

				if ( statement.removed ) {
					nextSeparator = '';
				} else {
					nextSeparator = endsWithCurlyBrace( statement ) ? '' : separator;
				}

				lastStatement = statement;
			}

			if ( end > lastEnd ) code.remove( lastEnd, end );
		} else {
			// empty block
			if ( removeCurlies || this.parent.type === 'Root' ) {
				code.remove( this.start, this.end );
			} else if ( this.end > this.start + 2 ) {
				code.remove( this.start + 1, this.end - 1 );
			}
		}
	}

	// TODO make this work!
	// minifyWithCollapsedReturnStatements ( code, statements ) {
	// 	if ( this.returnStatements.length === 1 ) {
	// 		const returnStatement = this.returnStatements[0];

	// 		if ( returnStatement.parent === this ) {
	// 			// case 1 – a single top-level return with no argument
	// 			if ( !returnStatement.argument ) {
	// 				// does this already get skipped above?
	// 				throw new Error( 'TODO single return statement without arg' );
	// 			}

	// 			// case 2 – a single top-level return with an argument
	// 			else {
	// 				throw new Error( 'TODO single return statement with arg' );
	// 			}
	// 		}

	// 		else {
	// 			// case 3 – a single conditional return with no argument
	// 			if ( !returnStatement.argument ) {
	// 				returnStatement.skip = true;
	// 			}

	// 			// case 4 – a single conditional return with an argument
	// 			else {
	// 				throw new Error( 'TODO single return statement with arg' );
	// 			}
	// 		}
	// 	}

	// 	else {
	// 		throw new Error( 'TODO multiple return statements' );
	// 	}

	// 	statements.forEach( statement => {
	// 		statement.minify( code, chars );
	// 	});
	// }
}


text:
layout: page
title: 404 - Page not found
---

页面已经不存在了.. [去首页看看吧]({{ site.baseurl }}/).

[<img src="{{ site.baseurl }}/images/404.jpg" alt="Constructocat by https://github.com/jasoncostello" style="width: 400px;"/>]({{ site.baseurl }}/)


text:
package net.ruippeixotog.scalafbp.component.core

import scala.concurrent.duration._

import spray.json._

import net.ruippeixotog.scalafbp.component.{ AutoTerminateSpec, ComponentSpec }

class RepeatDelayedSpec extends ComponentSpec with AutoTerminateSpec {
  val component = RepeatDelayed

  "A RepeatDelayed component" should {

    "not repeat anything until the delay is known" in new ComponentInstance {
      RepeatDelayed.inPort.send(JsNumber(3))
      RepeatDelayed.outPort must emitNothing
    }

    "forward every packet it receives to the out port with a delay" in new ComponentInstance {
      RepeatDelayed.delayPort.send(500)

      RepeatDelayed.inPort.send(JsNumber(2))
      within(250.millis, 750.millis) {
        RepeatDelayed.outPort must emit(JsNumber(2))
      }

      RepeatDelayed.inPort.send(JsNumber(3))
      RepeatDelayed.inPort.send(JsString("Hello"))
      within(250.millis, 750.millis) {
        RepeatDelayed.outPort must emitAllOf(JsNumber(3), JsString("Hello"))
      }
    }

    "always use the latest delay value for delaying input packets" in new ComponentInstance {
      RepeatDelayed.delayPort.send(1500)
      RepeatDelayed.inPort.send(JsNumber(1))
      RepeatDelayed.delayPort.send(500)
      RepeatDelayed.inPort.send(JsNumber(2))
      RepeatDelayed.delayPort.send(1000)
      RepeatDelayed.inPort.send(JsNumber(3))

      RepeatDelayed.outPort must emit(JsNumber(2))
      RepeatDelayed.outPort must emit(JsNumber(3))
      RepeatDelayed.outPort must emit(JsNumber(1))
    }

    terminateItselfWhenAllInPortsAreClosed
    terminateItselfWhenAllOutPortsAreClosed
  }
}


text:
@interface YSCZoomScrollView ()
@property (nonatomic, strong) UIImageView *photoImageView;
@end

@implementation YSCZoomScrollView
- (void)awakeFromNib {
    [super awakeFromNib];
    self.photoImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    self.photoImageView.backgroundColor = [UIColor clearColor];
    self.photoImageView.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:self.photoImageView];

    self.backgroundColor = [UIColor clearColor];
    self.minimumZoomScale = 1.0;
    self.maximumZoomScale = 3.0;
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    self.delegate = self;
    self.userInteractionEnabled = YES;
}
//这里需要根据image的大小动态计算imageView的大小
- (void)setImage:(UIImage *)image {
    self.photoImageView.image = image;
    CGFloat imageWidth = MIN(SCREEN_WIDTH, image.size.width);
    CGFloat imageHeight = image.size.height * imageWidth / image.size.width;
    if (imageHeight > SCREEN_HEIGHT) {
        imageHeight = SCREEN_HEIGHT;
        imageWidth = image.size.width * imageHeight / image.size.height;
    }
    CGRect frame = self.photoImageView.frame;
    frame.size = CGSizeMake(imageWidth, imageHeight);
    self.photoImageView.frame = frame;
    self.photoImageView.center = CGPointMake(SCREEN_WIDTH / 2.0f, SCREEN_HEIGHT / 2.0f);//center的设置必须在size设置之后!
}

#pragma mark - UIScrollViewDelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.photoImageView;//contentSize根据该缩放view的size等比例缩放
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {//在缩放过程中,动态设置图片的中心点始终处于屏幕中心
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) /2 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) /2 : 0.0;
    self.photoImageView.center = CGPointMake(scrollView.contentSize.width / 2 + offsetX,
                                             scrollView.contentSize.height / 2 + offsetY);
}
@end


text:
import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({
    selector: 'header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.scss']
})
export class HeaderComponent{
    constructor (private router: Router) {

    }
    ngOnInit() {
        this.router.events.subscribe((evt) => {
            if (!(evt instanceof NavigationEnd)) {
                return;
            }
            window.scrollTo(0, 0)
        });
    }
}


text:
import sys

from neutronclient.common import utils
from neutronclient.neutron.v2_0 import agent
from neutronclient.tests.unit import test_cli20

class CLITestV20Agent(test_cli20.CLITestV20Base):
    def test_list_agents(self):
        contents = {'agents': [{'id': 'myname', 'agent_type': 'mytype',
                                'alive': True}]}
        args = ['-f', 'json']
        resources = "agents"

        cmd = agent.ListAgent(test_cli20.MyApp(sys.stdout), None)
        self._test_list_columns(cmd, resources, contents, args)
        _str = self.fake_stdout.make_string()

        returned_agents = utils.loads(_str)
        self.assertEqual(1, len(returned_agents))
        ag = returned_agents[0]
        self.assertEqual(3, len(ag))
        self.assertIn("alive", ag.keys())

    def test_list_agents_field(self):
        contents = {'agents': [{'alive': True}]}
        args = ['-f', 'json']
        resources = "agents"
        smile = ':-)'

        cmd = agent.ListAgent(test_cli20.MyApp(sys.stdout), None)
        self._test_list_columns(cmd, resources, contents, args)
        _str = self.fake_stdout.make_string()

        returned_agents = utils.loads(_str)
        self.assertEqual(1, len(returned_agents))
        ag = returned_agents[0]
        self.assertEqual(1, len(ag))
        self.assertEqual("alive", ag.keys()[0])
        self.assertEqual(smile, ag.values()[0])


text:
import java.sql.*;
import org.json.JSONObject;
import org.json.JSONArray;

public class CLBase
{
	private Connection c = null;
	private Statement stmt = null;

	public CLBase ()
	{
		try {
			Class.forName("org.sqlite.JDBC");
			c = DriverManager.getConnection("jdbc:sqlite:test.db");
			c.setAutoCommit(false);
			stmt = c.createStatement();
			stmt.executeUpdate("CREATE TABLE IF NOT EXISTS colectivos (id INTEGER, name TEXT, bandera TEXT , linea TEXT, cl Boolean)");
			stmt.executeUpdate("CREATE TABLE IF NOT EXISTS calles (id INTEGER, desc TEXT)");
			stmt.executeUpdate("CREATE TABLE IF NOT EXISTS paradas (idColectivo INTEGER, idCalle INTEGER,idInter INTEGER, parada INTEGER , desc TEXT)");

			stmt.executeUpdate("CREATE TABLE IF NOT EXISTS recorridos (id INTEGER, sentido TEXT , desc TEXT)");
			stmt.executeUpdate("CREATE TABLE IF NOT EXISTS rcdreng (id INTEGER, sentido TEXT , num INTEGER, lat TEXT, lon TEXT)");
			stmt.executeUpdate("CREATE TABLE IF NOT EXISTS colec_rcd (id INTEGER, name TEXT, bandera TEXT , linea TEXT)");

			stmt.executeUpdate("CREATE TABLE IF NOT EXISTS geostreetD (idCalle INTEGER, idInter INTEGER,lat DOUBLE,lng DOUBLE, sin_lat DOUBLE , cos_lat DOUBLE , sin_lng DOUBLE, cos_lng DOUBLE)");

			System.out.println("Opened database successfully");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Opened database failed");
		}
	}

	public void deleteRecorridosTable()
	{
		try {
			String sql = "DELETE FROM colec_rcd;" ;
			stmt.executeUpdate(sql);
			sql = "DELETE FROM recorridos;" ;
			stmt.executeUpdate(sql);
			sql = "DELETE FROM rcdreng;" ;
			stmt.executeUpdate(sql);
		} catch (Exception e) {e.printStackTrace();}
	}

	public void delete_table(String table_name)
	{
		try {
			String sql = "DELETE FROM " + table_name + ";" ; ;
			stmt.executeUpdate(sql);
		} catch (Exception e) {e.printStackTrace();}
	}

	public void deleteTable()
	{
		try {
			String sql = "DELETE FROM calles;" ;
			stmt.executeUpdate(sql);
			sql = "DELETE FROM paradas;" ;
			stmt.executeUpdate(sql);
			sql = "DELETE FROM colectivos;" ;
			stmt.executeUpdate(sql);
		} catch (Exception e) {e.printStackTrace();}
	}

	public void insertCalle(JSONObject o)
	{
		try {
			String sql = "INSERT INTO calles (id,desc) " +
						 "VALUES (" + Integer.toString(o.getInt("id")) + ",'" + o.getString("desc") + "');";
			stmt.executeUpdate(sql);
		} catch (Exception e) {e.printStackTrace();}
	}

	public void insertColectivo(JSONObject o)
	{
		try {
			String sql = "INSERT INTO colectivos (id,name,bandera,linea,cl) " +
						 "VALUES (" + Integer.toString(o.getInt("id")) + ",'" + o.getString("name")
						 + "','" + o.getString("bandera") + "','" + o.getString("linea")  +  "', " + (o.getBoolean("cl")?"1":"0") + " );";
			stmt.executeUpdate(sql);
		} catch (Exception e) {e.printStackTrace();}
	}

	public void insertColec_rcd(JSONObject o)
	{
		try {
			String sql = "INSERT INTO colec_rcd (id,name,bandera,linea) " +
						 "VALUES (" + Integer.toString(o.getInt("id")) + ",'" + o.getString("name")
						 + "','" + o.getString("bandera") + "','" + o.getString("linea")  +  "');";
			stmt.executeUpdate(sql);
		} catch (Exception e) {e.printStackTrace();}
	}

	public void updateColectivo(JSONObject o)
	{
		try {
			String sql = "UPDATE colectivos SET cl = 1,linea = '" + o.getString("linea") +  "' WHERE id = " + Integer.toString(o.getInt("id"));
			stmt.executeUpdate(sql);
		} catch (Exception e) {e.printStackTrace();}
	}

	public void insertParadas(JSONObject o)
	{
		try {
			String sql = "INSERT INTO paradas (idColectivo,idCalle,idInter,parada,desc) " +
						 "VALUES (" + Integer.toString(o.getInt("idColectivo")) + "," + Integer.toString(o.getInt("idCalle"))
						 + "," + Integer.toString(o.getInt("idInter")) + "," + Integer.toString(o.getInt("parada"))  +
						 ",'" + o.getString("desc") + "');";
			stmt.executeUpdate(sql);
		} catch (Exception e) {e.printStackTrace();}
	}

	public void Close()
	{
		try {
			stmt.close();
			c.commit();
			c.close();
		} catch (Exception e) {
			System.out.println("Close Failed");
		}
	}

	public void insertGeostreetD(String idCalle,String idInter,String lat,String lng,String sin_lat,String cos_lat,String sin_lng,String cos_lng)
	{
		try {
			String sql = "INSERT INTO geostreetD " +
						 "VALUES (" + idCalle + "," + idInter + "," + lat + "," + lng + "," + sin_lat + "," + cos_lat + "," + sin_lng + "," + cos_lng +  ");";

			stmt.executeUpdate(sql);
		} catch (Exception e) {e.printStackTrace();}
	}

	// Para los recorridos -------------------------------------------------------------------------------
	// Para los recorridos -------------------------------------------------------------------------------

	public void insertRecorrido(Integer id, String sentido ,String desc)
	{
		try {
			String sql = "INSERT INTO recorridos (id,sentido,desc) " +
						 "VALUES (" + Integer.toString(id) + ",'" + sentido + "','" + desc + "'  );";
			stmt.executeUpdate(sql);
		} catch (Exception e) {e.printStackTrace();}
	}

	public void insertRcdReng(Integer id, String sentido ,Integer num, String lat, String lon)
	{
		try {
			String sql = "INSERT INTO rcdreng (id,sentido,num,lat,lon) " +
						 "VALUES (" + Integer.toString(id) + ",'" + sentido + "'," + Integer.toString(num) +
						 " , '" + lat + "','" + lon +  "');";
			stmt.executeUpdate(sql);
		} catch (Exception e) {e.printStackTrace();}
	}
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace CustomerManager.Model
{
    public class FinancialProfile
    {
        public int FinancialProfileID { get; set; }
        [StringLength(50), Display(Name = "Name")]

        public string Name { get; set; }
        public DateTime creationDate { get; set; }
        public int GroupID { get; set; }
    }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.22 at 10:03:02 PM KST
//

package net.opengis.indoorgml.core.v_1_0;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for typeOfTopoExpressionCodeEnumerationType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="typeOfTopoExpressionCodeEnumerationType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="CONTAINS"/>
 *     <enumeration value="OVERLAPS"/>
 *     <enumeration value="EQUALS"/>
 *     <enumeration value="WITHIN"/>
 *     <enumeration value="CROSSES"/>
 *     <enumeration value="INTERSECTS"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "typeOfTopoExpressionCodeEnumerationType")
@XmlEnum
public enum TypeOfTopoExpressionCodeEnumerationType {

    CONTAINS,
    OVERLAPS,
    EQUALS,
    WITHIN,
    CROSSES,
    INTERSECTS;

    public String value() {
        return name();
    }

    public static TypeOfTopoExpressionCodeEnumerationType fromValue(String v) {
        return valueOf(v);
    }

}


text:
                    <form  class="form" action="javascript:handleEdit()" >

                       <input name="username" id="username" type="text" placeholder="Username" value="<?= $username?>" class="form-control" disabled>

                       <input name="firstname" id="firstname" type="text" placeholder="First Name" value="<?php echo $user->getFirstName();?>" class="form-control" disabled>

                       <input name="lastname" id="lastname" type="text" placeholder="Last Name" value="<?php echo $user->getLastName();?>" class="form-control" disabled>

                       <input name="title" id ="title" type="text" placeholder="Occupation" value="<?php echo $user->getTitle();?>" class="form-control" disabled>

                        <button class="btn pull-right" id="edit">
                          Edit
                        </button>
                        <button class="save_user_info btn pull-right" class ="save_user_info" id="save_user_info" style="display:none;">
                          Save
                        </button>

                    </form>


text:
import React from 'react';
import ReactDOM from 'react-dom';

//Connect Firebase
import * as Config from '../../Team4of5_Service/Config.js';
import * as Issues from '../../Team4of5_Service/Issues.js';

//import css
import './IssueTracker.css'
//import react-bootstrap
import {
    Form,
    FormGroup,
    FormControl,
    ControlLabel,
    HelpBlock,
    Button,
    Modal
} from 'react-bootstrap';

class IssueUpdate extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: '',
            formBtnTxt: 'Update Issue',
            redirectToIssue: false
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);

        //connect with firebase
    }
    getInitialState=()=>{
        return {show: false};
    }
    close=()=> {
   this.setState({ showModal: false });
}

    handleChange(name, event) {
        let items = this.state;
        items[name] = event.target.value;
        this.setState(items);
    }

    handleSubmit(event) {
        if (this.state.completionDate || this.state.status || this.state.priority || this.state.severity) {
            Issues.issueUpdate(this.state.issue_id, this.state.completionDate, this.state.status, this.state.priority, this.state.severity).then((Issue) => {
                console.log(Issue);
            })
        }
        this.state.priority = '';
        this.state.severity = '';
        this.state.completionDate = '';
        this.state.status = '';
        this.state.issue_id = '';

        event.preventDefault();
    }

    render() {
        let close = () => this.setState({show: false});
        return (
            <div className="modal-container" style={{
            marginTop:20
            }}>
                <Button block onClick={() => this.setState({show: true})}>
                    Update Issue
                </Button>
                <Modal id="modleTitle" show={this.state.show} onHide={close} container={this}>
                    <Modal.Header closeButton>
                        <Modal.Title>Please Fill In Issue Information</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <Form onSubmit={this.handleSubmit}>
                            <FormGroup controlId="formControlsText">
                                <ControlLabel>ID</ControlLabel>
                                <FormControl type="text" value={this.state.issue_id} placeholder='enter ID' onChange={this.handleChange.bind(this, 'issue_id')} required/>
                            </FormGroup>

                            <FormGroup controlId="formControlsSelect">

                                <ControlLabel>Status</ControlLabel>

                                <FormControl componentClass="select" value={this.state.status} onChange={this.handleChange.bind(this, 'status')}>

                                    <option value=""></option>
                                    <option value="New">New</option>
                                    <option value="Open">Open</option>
                                    <option value="Assigned">Assigned</option>
                                    <option value="Verified">Verified</option>
                                    <option value="Closed">Closed</option>
                                </FormControl>

                            </FormGroup>
                            <FormGroup controlId="formControlsSelect">
                                <ControlLabel>Priority</ControlLabel>
                                <FormControl componentClass="select" value={this.state.priority} onChange={this.handleChange.bind(this, 'priority')}>

                                    <option value=""></option>
                                    <option value="Immediate">Immediate</option>
                                    <option value="High">High</option>
                                    <option value="Medium">Medium</option>
                                    <option value="Low">Low</option>
                                    <option value="Verified">Verified</option>
                                    <option value="Fix if time">Fix if time</option>
                                </FormControl>
                            </FormGroup>
                            <FormGroup controlId="formControlsSelect">
                                <ControlLabel>Severity</ControlLabel>
                                <FormControl componentClass="select" value={this.state.severity} onChange={this.handleChange.bind(this, 'severity')}>

                                    <option value=""></option>
                                    <option value="Critical">Critical</option>
                                    <option value="High">High</option>
                                    <option value="Medium">Medium</option>
                                    <option value="Low">Low</option>
                                    <option value="None">None</option>
                                </FormControl>
                            </FormGroup>
                            <FormGroup controlId="formControlsText">

                                <ControlLabel>Actual completion date</ControlLabel>

                                <FormControl type="date" value={this.state.completionDate} onChange={this.handleChange.bind(this, 'completionDate')}/>

                            </FormGroup>
                            <input type="submit" className="btn btn-primary" value={this.state.formBtnTxt} />
                        </Form>
                    </Modal.Body>
                     <Modal.Footer>
                            <Button bsStyle="success" onClick={() => {this.setState({show: false}); this.state.severity = ''; this.state.issue_id = ''; this.state.priority = ''; this.state.status = '';  this.state.completionDate = ''; }}>Close</Button>
                     </Modal.Footer>
                </Modal>
            </div>
        );
    }

}
export default IssueUpdate;


text:
import unittest
from logging.handlers import SysLogHandler

import mock
from six import BytesIO
from six.moves.urllib.parse import unquote

from test.unit import FakeLogger
from swift.common.utils import get_logger, split_path
from swift.common.middleware import proxy_logging
from swift.common.swob import Request, Response
from swift.common import constraints
from swift.common.storage_policy import StoragePolicy
from test.unit import patch_policies
from test.unit.common.middleware.helpers import FakeAppThatExcepts

class FakeApp(object):

    def __init__(self, body=None, response_str='200 OK', policy_idx='0'):
        if body is None:
            body = ['FAKE APP']

        self.body = body
        self.response_str = response_str
        self.policy_idx = policy_idx

    def __call__(self, env, start_response):
        try:
            # /v1/a/c or /v1/a/c/o
            split_path(env['PATH_INFO'], 3, 4, True)
            is_container_or_object_req = True
        except ValueError:
            is_container_or_object_req = False

        headers = [('Content-Type', 'text/plain'),
                   ('Content-Length', str(sum(map(len, self.body))))]
        if is_container_or_object_req and self.policy_idx is not None:
            headers.append(('X-Backend-Storage-Policy-Index',
                           str(self.policy_idx)))

        start_response(self.response_str, headers)
        while env['wsgi.input'].read(5):
            pass
        return self.body

class FakeAppNoContentLengthNoTransferEncoding(object):

    def __init__(self, body=None):
        if body is None:
            body = ['FAKE APP']

        self.body = body

    def __call__(self, env, start_response):
        start_response('200 OK', [('Content-Type', 'text/plain')])
        while env['wsgi.input'].read(5):
            pass
        return self.body

class FileLikeExceptor(object):

    def __init__(self):
        pass

    def read(self, len):
        raise IOError('of some sort')

    def readline(self, len=1024):
        raise IOError('of some sort')

class FakeAppReadline(object):

    def __call__(self, env, start_response):
        start_response('200 OK', [('Content-Type', 'text/plain'),
                                  ('Content-Length', '8')])
        env['wsgi.input'].readline()
        return ["FAKE APP"]

def start_response(*args):
    pass

@patch_policies([StoragePolicy(0, 'zero', False)])
class TestProxyLogging(unittest.TestCase):
    def _log_parts(self, app, should_be_empty=False):
        info_calls = app.access_logger.log_dict['info']
        if should_be_empty:
            self.assertEqual([], info_calls)
        else:
            self.assertEqual(1, len(info_calls))
            return info_calls[0][0][0].split(' ')

    def assertTiming(self, exp_metric, app, exp_timing=None):
        timing_calls = app.access_logger.log_dict['timing']
        found = False
        for timing_call in timing_calls:
            self.assertEqual({}, timing_call[1])
            self.assertEqual(2, len(timing_call[0]))
            if timing_call[0][0] == exp_metric:
                found = True
                if exp_timing is not None:
                    self.assertAlmostEqual(exp_timing, timing_call[0][1],
                                           places=4)
        if not found:
            self.assertTrue(False, 'assertTiming: %s not found in %r' % (
                exp_metric, timing_calls))

    def assertTimingSince(self, exp_metric, app, exp_start=None):
        timing_calls = app.access_logger.log_dict['timing_since']
        found = False
        for timing_call in timing_calls:
            self.assertEqual({}, timing_call[1])
            self.assertEqual(2, len(timing_call[0]))
            if timing_call[0][0] == exp_metric:
                found = True
                if exp_start is not None:
                    self.assertAlmostEqual(exp_start, timing_call[0][1],
                                           places=4)
        if not found:
            self.assertTrue(False, 'assertTimingSince: %s not found in %r' % (
                exp_metric, timing_calls))

    def assertNotTiming(self, not_exp_metric, app):
        timing_calls = app.access_logger.log_dict['timing']
        for timing_call in timing_calls:
            self.assertNotEqual(not_exp_metric, timing_call[0][0])

    def assertUpdateStats(self, exp_metrics_and_values, app):
        update_stats_calls = sorted(app.access_logger.log_dict['update_stats'])
        got_metrics_values_and_kwargs = [(usc[0][0], usc[0][1], usc[1])
                                         for usc in update_stats_calls]
        exp_metrics_values_and_kwargs = [(emv[0], emv[1], {})
                                         for emv in exp_metrics_and_values]
        self.assertEqual(got_metrics_values_and_kwargs,
                         exp_metrics_values_and_kwargs)

    def test_log_request_statsd_invalid_stats_types(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        for url in ['/', '/foo', '/foo/bar', '/v1']:
            req = Request.blank(url, environ={'REQUEST_METHOD': 'GET'})
            resp = app(req.environ, start_response)
            # get body
            ''.join(resp)
            self.assertEqual([], app.access_logger.log_dict['timing'])
            self.assertEqual([], app.access_logger.log_dict['update_stats'])

    def test_log_request_stat_type_bad(self):
        for bad_path in ['', '/', '/bad', '/baddy/mc_badderson', '/v1',
                         '/v1/']:
            app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
            app.access_logger = FakeLogger()
            req = Request.blank(bad_path, environ={'REQUEST_METHOD': 'GET'})
            now = 10000.0
            app.log_request(req, 123, 7, 13, now, now + 2.71828182846)
            self.assertEqual([], app.access_logger.log_dict['timing'])
            self.assertEqual([], app.access_logger.log_dict['update_stats'])

    def test_log_request_stat_type_good(self):
        """
        log_request() should send timing and byte-count counters for GET
        requests.  Also, __call__()'s iter_response() function should
        statsd-log time to first byte (calling the passed-in start_response
        function), but only for GET requests.
        """
        stub_times = []

        def stub_time():
            return stub_times.pop(0)

        path_types = {
            '/v1/a': 'account',
            '/v1/a/': 'account',
            '/v1/a/c': 'container',
            '/v1/a/c/': 'container',
            '/v1/a/c/o': 'object',
            '/v1/a/c/o/': 'object',
            '/v1/a/c/o/p': 'object',
            '/v1/a/c/o/p/': 'object',
            '/v1/a/c/o/p/p2': 'object',
        }
        with mock.patch("time.time", stub_time):
            for path, exp_type in path_types.items():
                # GET
                app = proxy_logging.ProxyLoggingMiddleware(
                    FakeApp(body='7654321', response_str='321 Fubar'), {})
                app.access_logger = FakeLogger()
                req = Request.blank(path, environ={
                    'REQUEST_METHOD': 'GET',
                    'wsgi.input': BytesIO(b'4321')})
                stub_times = [18.0, 20.71828182846]
                iter_response = app(req.environ, lambda *_: None)

                self.assertEqual('7654321', ''.join(iter_response))
                self.assertTiming('%s.GET.321.timing' % exp_type, app,
                                  exp_timing=2.71828182846 * 1000)
                self.assertTimingSince(
                    '%s.GET.321.first-byte.timing' % exp_type, app,
                    exp_start=18.0)
                if exp_type == 'object':
                    # Object operations also return stats by policy
                    # In this case, the value needs to match the timing for GET
                    self.assertTiming('%s.policy.0.GET.321.timing' % exp_type,
                                      app, exp_timing=2.71828182846 * 1000)
                    self.assertUpdateStats([('%s.GET.321.xfer' % exp_type,
                                             4 + 7),
                                            ('object.policy.0.GET.321.xfer',
                                            4 + 7)],
                                           app)
                else:
                    self.assertUpdateStats([('%s.GET.321.xfer' % exp_type,
                                            4 + 7)],
                                           app)

                # GET Repeat the test above, but with a non-existent policy
                # Do this only for object types
                if exp_type == 'object':
                    app = proxy_logging.ProxyLoggingMiddleware(
                        FakeApp(body='7654321', response_str='321 Fubar',
                                policy_idx='-1'), {})
                    app.access_logger = FakeLogger()
                    req = Request.blank(path, environ={
                        'REQUEST_METHOD': 'GET',
                        'wsgi.input': BytesIO(b'4321')})
                    stub_times = [18.0, 20.71828182846]
                    iter_response = app(req.environ, lambda *_: None)

                    self.assertEqual('7654321', ''.join(iter_response))
                    self.assertTiming('%s.GET.321.timing' % exp_type, app,
                                      exp_timing=2.71828182846 * 1000)
                    self.assertTimingSince(
                        '%s.GET.321.first-byte.timing' % exp_type, app,
                        exp_start=18.0)
                    # No results returned for the non-existent policy
                    self.assertUpdateStats([('%s.GET.321.xfer' % exp_type,
                                            4 + 7)],
                                           app)

                # GET with swift.proxy_access_log_made already set
                app = proxy_logging.ProxyLoggingMiddleware(
                    FakeApp(body='7654321', response_str='321 Fubar'), {})
                app.access_logger = FakeLogger()
                req = Request.blank(path, environ={
                    'REQUEST_METHOD': 'GET',
                    'swift.proxy_access_log_made': True,
                    'wsgi.input': BytesIO(b'4321')})
                stub_times = [18.0, 20.71828182846]
                iter_response = app(req.environ, lambda *_: None)
                self.assertEqual('7654321', ''.join(iter_response))
                self.assertEqual([], app.access_logger.log_dict['timing'])
                self.assertEqual([],
                                 app.access_logger.log_dict['timing_since'])
                self.assertEqual([],
                                 app.access_logger.log_dict['update_stats'])

                # PUT (no first-byte timing!)
                app = proxy_logging.ProxyLoggingMiddleware(
                    FakeApp(body='87654321', response_str='314 PiTown'), {})
                app.access_logger = FakeLogger()
                req = Request.blank(path, environ={
                    'REQUEST_METHOD': 'PUT',
                    'wsgi.input': BytesIO(b'654321')})
                # (it's not a GET, so time() doesn't have a 2nd call)
                stub_times = [58.2, 58.2 + 7.3321]
                iter_response = app(req.environ, lambda *_: None)
                self.assertEqual('87654321', ''.join(iter_response))
                self.assertTiming('%s.PUT.314.timing' % exp_type, app,
                                  exp_timing=7.3321 * 1000)
                self.assertNotTiming(
                    '%s.GET.314.first-byte.timing' % exp_type, app)
                self.assertNotTiming(
                    '%s.PUT.314.first-byte.timing' % exp_type, app)
                if exp_type == 'object':
                    # Object operations also return stats by policy In this
                    # case, the value needs to match the timing for PUT.
                    self.assertTiming('%s.policy.0.PUT.314.timing' %
                                      exp_type, app,
                                      exp_timing=7.3321 * 1000)
                    self.assertUpdateStats(
                        [('object.PUT.314.xfer', 6 + 8),
                         ('object.policy.0.PUT.314.xfer', 6 + 8)], app)
                else:
                    self.assertUpdateStats(
                        [('%s.PUT.314.xfer' % exp_type, 6 + 8)], app)

                # PUT Repeat the test above, but with a non-existent policy
                # Do this only for object types
                if exp_type == 'object':
                    app = proxy_logging.ProxyLoggingMiddleware(
                        FakeApp(body='87654321', response_str='314 PiTown',
                                policy_idx='-1'), {})
                    app.access_logger = FakeLogger()
                    req = Request.blank(path, environ={
                        'REQUEST_METHOD': 'PUT',
                        'wsgi.input': BytesIO(b'654321')})
                    # (it's not a GET, so time() doesn't have a 2nd call)
                    stub_times = [58.2, 58.2 + 7.3321]
                    iter_response = app(req.environ, lambda *_: None)
                    self.assertEqual('87654321', ''.join(iter_response))
                    self.assertTiming('%s.PUT.314.timing' % exp_type, app,
                                      exp_timing=7.3321 * 1000)
                    self.assertNotTiming(
                        '%s.GET.314.first-byte.timing' % exp_type, app)
                    self.assertNotTiming(
                        '%s.PUT.314.first-byte.timing' % exp_type, app)
                    # No results returned for the non-existent policy
                    self.assertUpdateStats([('object.PUT.314.xfer', 6 + 8)],
                                           app)

    def test_log_request_stat_method_filtering_default(self):
        method_map = {
            'foo': 'BAD_METHOD',
            '': 'BAD_METHOD',
            'PUTT': 'BAD_METHOD',
            'SPECIAL': 'BAD_METHOD',
            'GET': 'GET',
            'PUT': 'PUT',
            'COPY': 'COPY',
            'HEAD': 'HEAD',
            'POST': 'POST',
            'DELETE': 'DELETE',
            'OPTIONS': 'OPTIONS',
        }
        for method, exp_method in method_map.items():
            app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
            app.access_logger = FakeLogger()
            req = Request.blank('/v1/a/', environ={'REQUEST_METHOD': method})
            now = 10000.0
            app.log_request(req, 299, 11, 3, now, now + 1.17)
            self.assertTiming('account.%s.299.timing' % exp_method, app,
                              exp_timing=1.17 * 1000)
            self.assertUpdateStats([('account.%s.299.xfer' % exp_method,
                                   11 + 3)], app)

    def test_log_request_stat_method_filtering_custom(self):
        method_map = {
            'foo': 'BAD_METHOD',
            '': 'BAD_METHOD',
            'PUTT': 'BAD_METHOD',
            'SPECIAL': 'SPECIAL',  # will be configured
            'GET': 'GET',
            'PUT': 'PUT',
            'COPY': 'BAD_METHOD',  # prove no one's special
        }
        # this conf var supports optional leading access_
        for conf_key in ['access_log_statsd_valid_http_methods',
                         'log_statsd_valid_http_methods']:
            for method, exp_method in method_map.items():
                app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {
                    conf_key: 'SPECIAL,  GET,PUT ',  # crazy spaces ok
                })
                app.access_logger = FakeLogger()
                req = Request.blank('/v1/a/c',
                                    environ={'REQUEST_METHOD': method})
                now = 10000.0
                app.log_request(req, 911, 4, 43, now, now + 1.01)
                self.assertTiming('container.%s.911.timing' % exp_method, app,
                                  exp_timing=1.01 * 1000)
                self.assertUpdateStats([('container.%s.911.xfer' % exp_method,
                                       4 + 43)], app)

    def test_basic_req(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[3], 'GET')
        self.assertEqual(log_parts[4], '/')
        self.assertEqual(log_parts[5], 'HTTP/1.0')
        self.assertEqual(log_parts[6], '200')
        self.assertEqual(resp_body, 'FAKE APP')
        self.assertEqual(log_parts[11], str(len(resp_body)))

    def test_basic_req_second_time(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={
            'swift.proxy_access_log_made': True,
            'REQUEST_METHOD': 'GET'})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        self._log_parts(app, should_be_empty=True)
        self.assertEqual(resp_body, 'FAKE APP')

    def test_multi_segment_resp(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(
            ['some', 'chunks', 'of data']), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'swift.source': 'SOS'})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[3], 'GET')
        self.assertEqual(log_parts[4], '/')
        self.assertEqual(log_parts[5], 'HTTP/1.0')
        self.assertEqual(log_parts[6], '200')
        self.assertEqual(resp_body, 'somechunksof data')
        self.assertEqual(log_parts[11], str(len(resp_body)))
        self.assertUpdateStats([('SOS.GET.200.xfer', len(resp_body))], app)

    def test_log_headers(self):
        for conf_key in ['access_log_headers', 'log_headers']:
            app = proxy_logging.ProxyLoggingMiddleware(FakeApp(),
                                                       {conf_key: 'yes'})
            app.access_logger = FakeLogger()
            req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
            resp = app(req.environ, start_response)
            # exhaust generator
            [x for x in resp]
            log_parts = self._log_parts(app)
            headers = unquote(log_parts[14]).split('\n')
            self.assertTrue('Host: localhost:80' in headers)

    def test_access_log_headers_only(self):
        app = proxy_logging.ProxyLoggingMiddleware(
            FakeApp(), {'log_headers': 'yes',
                        'access_log_headers_only': 'FIRST, seCond'})
        app.access_logger = FakeLogger()
        req = Request.blank('/',
                            environ={'REQUEST_METHOD': 'GET'},
                            headers={'First': '1',
                                     'Second': '2',
                                     'Third': '3'})
        resp = app(req.environ, start_response)
        # exhaust generator
        [x for x in resp]
        log_parts = self._log_parts(app)
        headers = unquote(log_parts[14]).split('\n')
        self.assertTrue('First: 1' in headers)
        self.assertTrue('Second: 2' in headers)
        self.assertNotIn('Third: 3', headers)
        self.assertNotIn('Host: localhost:80', headers)

    def test_upload_size(self):
        # Using default policy
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(),
                                                   {'log_headers': 'yes'})
        app.access_logger = FakeLogger()
        req = Request.blank(
            '/v1/a/c/o/foo',
            environ={'REQUEST_METHOD': 'PUT',
                     'wsgi.input': BytesIO(b'some stuff')})
        resp = app(req.environ, start_response)
        # exhaust generator
        [x for x in resp]
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[11], str(len('FAKE APP')))
        self.assertEqual(log_parts[10], str(len('some stuff')))
        self.assertUpdateStats([('object.PUT.200.xfer',
                                 len('some stuff') + len('FAKE APP')),
                                ('object.policy.0.PUT.200.xfer',
                                 len('some stuff') + len('FAKE APP'))],
                               app)

        # Using a non-existent policy
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(policy_idx='-1'),
                                                   {'log_headers': 'yes'})
        app.access_logger = FakeLogger()
        req = Request.blank(
            '/v1/a/c/o/foo',
            environ={'REQUEST_METHOD': 'PUT',
                     'wsgi.input': BytesIO(b'some stuff')})
        resp = app(req.environ, start_response)
        # exhaust generator
        [x for x in resp]
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[11], str(len('FAKE APP')))
        self.assertEqual(log_parts[10], str(len('some stuff')))
        self.assertUpdateStats([('object.PUT.200.xfer',
                                 len('some stuff') + len('FAKE APP'))],
                               app)

    def test_upload_size_no_policy(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(policy_idx=None),
                                                   {'log_headers': 'yes'})
        app.access_logger = FakeLogger()
        req = Request.blank(
            '/v1/a/c/o/foo',
            environ={'REQUEST_METHOD': 'PUT',
                     'wsgi.input': BytesIO(b'some stuff')})
        resp = app(req.environ, start_response)
        # exhaust generator
        [x for x in resp]
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[11], str(len('FAKE APP')))
        self.assertEqual(log_parts[10], str(len('some stuff')))
        self.assertUpdateStats([('object.PUT.200.xfer',
                                 len('some stuff') + len('FAKE APP'))],
                               app)

    def test_upload_line(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeAppReadline(),
                                                   {'log_headers': 'yes'})
        app.access_logger = FakeLogger()
        req = Request.blank(
            '/v1/a/c',
            environ={'REQUEST_METHOD': 'POST',
                     'wsgi.input': BytesIO(b'some stuff\nsome other stuff\n')})
        resp = app(req.environ, start_response)
        # exhaust generator
        [x for x in resp]
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[11], str(len('FAKE APP')))
        self.assertEqual(log_parts[10], str(len('some stuff\n')))
        self.assertUpdateStats([('container.POST.200.xfer',
                               len('some stuff\n') + len('FAKE APP'))],
                               app)

    def test_log_query_string(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'QUERY_STRING': 'x=3'})
        resp = app(req.environ, start_response)
        # exhaust generator
        [x for x in resp]
        log_parts = self._log_parts(app)
        self.assertEqual(unquote(log_parts[4]), '/?x=3')

    def test_client_logging(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'REMOTE_ADDR': '1.2.3.4'})
        resp = app(req.environ, start_response)
        # exhaust generator
        [x for x in resp]
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[0], '1.2.3.4')  # client ip
        self.assertEqual(log_parts[1], '1.2.3.4')  # remote addr

    def test_iterator_closing(self):

        class CloseableBody(object):
            def __init__(self):
                self.closed = False

            def close(self):
                self.closed = True

            def __iter__(self):
                return iter(["CloseableBody"])

        body = CloseableBody()
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(body), {})
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'REMOTE_ADDR': '1.2.3.4'})
        resp = app(req.environ, start_response)
        # exhaust generator
        [x for x in resp]
        self.assertTrue(body.closed)

    def test_proxy_client_logging(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={
            'REQUEST_METHOD': 'GET',
            'REMOTE_ADDR': '1.2.3.4',
            'HTTP_X_FORWARDED_FOR': '4.5.6.7,8.9.10.11'})
        resp = app(req.environ, start_response)
        # exhaust generator
        [x for x in resp]
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[0], '4.5.6.7')  # client ip
        self.assertEqual(log_parts[1], '1.2.3.4')  # remote addr

        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={
            'REQUEST_METHOD': 'GET',
            'REMOTE_ADDR': '1.2.3.4',
            'HTTP_X_CLUSTER_CLIENT_IP': '4.5.6.7'})
        resp = app(req.environ, start_response)
        # exhaust generator
        [x for x in resp]
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[0], '4.5.6.7')  # client ip
        self.assertEqual(log_parts[1], '1.2.3.4')  # remote addr

    def test_facility(self):
        app = proxy_logging.ProxyLoggingMiddleware(
            FakeApp(),
            {'log_headers': 'yes',
             'access_log_facility': 'LOG_LOCAL7'})
        handler = get_logger.handler4logger[app.access_logger.logger]
        self.assertEqual(SysLogHandler.LOG_LOCAL7, handler.facility)

    def test_filter(self):
        factory = proxy_logging.filter_factory({})
        self.assertTrue(callable(factory))
        self.assertTrue(callable(factory(FakeApp())))

    def test_unread_body(self):
        app = proxy_logging.ProxyLoggingMiddleware(
            FakeApp(['some', 'stuff']), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        resp = app(req.environ, start_response)
        # read first chunk
        next(resp)
        resp.close()  # raise a GeneratorExit in middleware app_iter loop
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[6], '499')
        self.assertEqual(log_parts[11], '4')  # write length

    def test_disconnect_on_readline(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeAppReadline(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'wsgi.input': FileLikeExceptor()})
        try:
            resp = app(req.environ, start_response)
            # read body
            ''.join(resp)
        except IOError:
            pass
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[6], '499')
        self.assertEqual(log_parts[10], '-')  # read length

    def test_disconnect_on_read(self):
        app = proxy_logging.ProxyLoggingMiddleware(
            FakeApp(['some', 'stuff']), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'wsgi.input': FileLikeExceptor()})
        try:
            resp = app(req.environ, start_response)
            # read body
            ''.join(resp)
        except IOError:
            pass
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[6], '499')
        self.assertEqual(log_parts[10], '-')  # read length

    def test_app_exception(self):
        app = proxy_logging.ProxyLoggingMiddleware(
            FakeAppThatExcepts(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        try:
            app(req.environ, start_response)
        except Exception:
            pass
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[6], '500')
        self.assertEqual(log_parts[10], '-')  # read length

    def test_no_content_length_no_transfer_encoding_with_list_body(self):
        app = proxy_logging.ProxyLoggingMiddleware(
            FakeAppNoContentLengthNoTransferEncoding(
                # test the "while not chunk: chunk = next(iterator)"
                body=['', '', 'line1\n', 'line2\n'],
            ), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[3], 'GET')
        self.assertEqual(log_parts[4], '/')
        self.assertEqual(log_parts[5], 'HTTP/1.0')
        self.assertEqual(log_parts[6], '200')
        self.assertEqual(resp_body, 'line1\nline2\n')
        self.assertEqual(log_parts[11], str(len(resp_body)))

    def test_no_content_length_no_transfer_encoding_with_empty_strings(self):
        app = proxy_logging.ProxyLoggingMiddleware(
            FakeAppNoContentLengthNoTransferEncoding(
                # test the "while not chunk: chunk = next(iterator)"
                body=['', '', ''],
            ), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[3], 'GET')
        self.assertEqual(log_parts[4], '/')
        self.assertEqual(log_parts[5], 'HTTP/1.0')
        self.assertEqual(log_parts[6], '200')
        self.assertEqual(resp_body, '')
        self.assertEqual(log_parts[11], '-')

    def test_no_content_length_no_transfer_encoding_with_generator(self):

        class BodyGen(object):
            def __init__(self, data):
                self.data = data

            def __iter__(self):
                yield self.data

        app = proxy_logging.ProxyLoggingMiddleware(
            FakeAppNoContentLengthNoTransferEncoding(
                body=BodyGen('abc'),
            ), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[3], 'GET')
        self.assertEqual(log_parts[4], '/')
        self.assertEqual(log_parts[5], 'HTTP/1.0')
        self.assertEqual(log_parts[6], '200')
        self.assertEqual(resp_body, 'abc')
        self.assertEqual(log_parts[11], '3')

    def test_req_path_info_popping(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/v1/something', environ={'REQUEST_METHOD': 'GET'})
        req.path_info_pop()
        self.assertEqual(req.environ['PATH_INFO'], '/something')
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[3], 'GET')
        self.assertEqual(log_parts[4], '/v1/something')
        self.assertEqual(log_parts[5], 'HTTP/1.0')
        self.assertEqual(log_parts[6], '200')
        self.assertEqual(resp_body, 'FAKE APP')
        self.assertEqual(log_parts[11], str(len(resp_body)))

    def test_ipv6(self):
        ipv6addr = '2001:db8:85a3:8d3:1319:8a2e:370:7348'
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        req.remote_addr = ipv6addr
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[0], ipv6addr)
        self.assertEqual(log_parts[1], ipv6addr)
        self.assertEqual(log_parts[3], 'GET')
        self.assertEqual(log_parts[4], '/')
        self.assertEqual(log_parts[5], 'HTTP/1.0')
        self.assertEqual(log_parts[6], '200')
        self.assertEqual(resp_body, 'FAKE APP')
        self.assertEqual(log_parts[11], str(len(resp_body)))

    def test_log_info_none(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        list(app(req.environ, start_response))
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[17], '-')

        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        req.environ['swift.log_info'] = []
        list(app(req.environ, start_response))
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[17], '-')

    def test_log_info_single(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        req.environ['swift.log_info'] = ['one']
        list(app(req.environ, start_response))
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[17], 'one')

    def test_log_info_multiple(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        req.environ['swift.log_info'] = ['one', 'and two']
        list(app(req.environ, start_response))
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[17], 'one%2Cand%20two')

    def test_log_auth_token(self):
        auth_token = 'b05bf940-0464-4c0e-8c70-87717d2d73e8'

        # Default - reveal_sensitive_prefix is 16
        # No x-auth-token header
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[9], '-')
        # Has x-auth-token header
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'HTTP_X_AUTH_TOKEN': auth_token})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[9], 'b05bf940-0464-4c...')

        # Truncate to first 8 characters
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {
            'reveal_sensitive_prefix': '8'})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[9], '-')
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {
            'reveal_sensitive_prefix': '8'})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'HTTP_X_AUTH_TOKEN': auth_token})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[9], 'b05bf940...')

        # Token length and reveal_sensitive_prefix are same (no truncate)
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {
            'reveal_sensitive_prefix': str(len(auth_token))})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'HTTP_X_AUTH_TOKEN': auth_token})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[9], auth_token)

        # No effective limit on auth token
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {
            'reveal_sensitive_prefix': constraints.MAX_HEADER_SIZE})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'HTTP_X_AUTH_TOKEN': auth_token})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[9], auth_token)

        # Don't log x-auth-token
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {
            'reveal_sensitive_prefix': '0'})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[9], '-')
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {
            'reveal_sensitive_prefix': '0'})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'HTTP_X_AUTH_TOKEN': auth_token})
        resp = app(req.environ, start_response)
        resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[9], '...')

        # Avoids pyflakes error, "local variable 'resp_body' is assigned to
        # but never used
        self.assertTrue(resp_body is not None)

    def test_ensure_fields(self):
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        with mock.patch('time.time',
                        mock.MagicMock(
                            side_effect=[10000000.0, 10000001.0])):
            resp = app(req.environ, start_response)
            resp_body = ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(len(log_parts), 21)
        self.assertEqual(log_parts[0], '-')
        self.assertEqual(log_parts[1], '-')
        self.assertEqual(log_parts[2], '26/Apr/1970/17/46/41')
        self.assertEqual(log_parts[3], 'GET')
        self.assertEqual(log_parts[4], '/')
        self.assertEqual(log_parts[5], 'HTTP/1.0')
        self.assertEqual(log_parts[6], '200')
        self.assertEqual(log_parts[7], '-')
        self.assertEqual(log_parts[8], '-')
        self.assertEqual(log_parts[9], '-')
        self.assertEqual(log_parts[10], '-')
        self.assertEqual(resp_body, 'FAKE APP')
        self.assertEqual(log_parts[11], str(len(resp_body)))
        self.assertEqual(log_parts[12], '-')
        self.assertEqual(log_parts[13], '-')
        self.assertEqual(log_parts[14], '-')
        self.assertEqual(log_parts[15], '1.0000')
        self.assertEqual(log_parts[16], '-')
        self.assertEqual(log_parts[17], '-')
        self.assertEqual(log_parts[18], '10000000.000000000')
        self.assertEqual(log_parts[19], '10000001.000000000')
        self.assertEqual(log_parts[20], '-')

    def test_dual_logging_middlewares(self):
        # Since no internal request is being made, outer most proxy logging
        # middleware, log1, should have performed the logging.
        app = FakeApp()
        flg0 = FakeLogger()
        env = {}
        log0 = proxy_logging.ProxyLoggingMiddleware(app, env, logger=flg0)
        flg1 = FakeLogger()
        log1 = proxy_logging.ProxyLoggingMiddleware(log0, env, logger=flg1)

        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        resp = log1(req.environ, start_response)
        resp_body = ''.join(resp)
        self._log_parts(log0, should_be_empty=True)
        log_parts = self._log_parts(log1)
        self.assertEqual(log_parts[3], 'GET')
        self.assertEqual(log_parts[4], '/')
        self.assertEqual(log_parts[5], 'HTTP/1.0')
        self.assertEqual(log_parts[6], '200')
        self.assertEqual(resp_body, 'FAKE APP')
        self.assertEqual(log_parts[11], str(len(resp_body)))

    def test_dual_logging_middlewares_w_inner(self):

        class FakeMiddleware(object):
            """
            Fake middleware to make a separate internal request, but construct
            the response with different data.
            """
            def __init__(self, app, conf):
                self.app = app
                self.conf = conf

            def GET(self, req):
                # Make the internal request
                ireq = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
                resp = self.app(ireq.environ, start_response)
                resp_body = ''.join(resp)
                if resp_body != 'FAKE APP':
                    return Response(request=req,
                                    body="FAKE APP WAS NOT RETURNED",
                                    content_type="text/plain")
                # But our response is different
                return Response(request=req, body="FAKE MIDDLEWARE",
                                content_type="text/plain")

            def __call__(self, env, start_response):
                req = Request(env)
                return self.GET(req)(env, start_response)

        # Since an internal request is being made, inner most proxy logging
        # middleware, log0, should have performed the logging.
        app = FakeApp()
        flg0 = FakeLogger()
        env = {}
        log0 = proxy_logging.ProxyLoggingMiddleware(app, env, logger=flg0)
        fake = FakeMiddleware(log0, env)
        flg1 = FakeLogger()
        log1 = proxy_logging.ProxyLoggingMiddleware(fake, env, logger=flg1)

        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'})
        resp = log1(req.environ, start_response)
        resp_body = ''.join(resp)

        # Inner most logger should have logged the app's response
        log_parts = self._log_parts(log0)
        self.assertEqual(log_parts[3], 'GET')
        self.assertEqual(log_parts[4], '/')
        self.assertEqual(log_parts[5], 'HTTP/1.0')
        self.assertEqual(log_parts[6], '200')
        self.assertEqual(log_parts[11], str(len('FAKE APP')))

        # Outer most logger should have logged the other middleware's response
        log_parts = self._log_parts(log1)
        self.assertEqual(log_parts[3], 'GET')
        self.assertEqual(log_parts[4], '/')
        self.assertEqual(log_parts[5], 'HTTP/1.0')
        self.assertEqual(log_parts[6], '200')
        self.assertEqual(resp_body, 'FAKE MIDDLEWARE')
        self.assertEqual(log_parts[11], str(len(resp_body)))

    def test_policy_index(self):
        # Policy index can be specified by X-Backend-Storage-Policy-Index
        # in the request header for object API
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(policy_idx='1'), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/v1/a/c/o', environ={'REQUEST_METHOD': 'PUT'})
        resp = app(req.environ, start_response)
        ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[20], '1')

        # Policy index can be specified by X-Backend-Storage-Policy-Index
        # in the response header for container API
        app = proxy_logging.ProxyLoggingMiddleware(FakeApp(), {})
        app.access_logger = FakeLogger()
        req = Request.blank('/v1/a/c', environ={'REQUEST_METHOD': 'GET'})

        def fake_call(app, env, start_response):
            start_response(app.response_str,
                           [('Content-Type', 'text/plain'),
                            ('Content-Length', str(sum(map(len, app.body)))),
                            ('X-Backend-Storage-Policy-Index', '1')])
            while env['wsgi.input'].read(5):
                pass
            return app.body

        with mock.patch.object(FakeApp, '__call__', fake_call):
            resp = app(req.environ, start_response)
            ''.join(resp)
        log_parts = self._log_parts(app)
        self.assertEqual(log_parts[20], '1')


text:
layout: post
title: Walking to the Sky
categories:
- Learning
---

An amazing perceptive sculpture by Jonathan Borofsky called " [Walking to the Sky](http://www.borofsky.com/index.php?album=walkingcmu)" It can be found at the Carnegie Mellon University, Pittsburgh.

![](/img/walkingToTheSky.jpg)


text:
#ifndef GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JWT_CREDENTIALS_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JWT_CREDENTIALS_H

#include <grpc/support/port_platform.h>

#include <string>

#include <grpc/support/time.h>

#include "absl/strings/str_format.h"
#include "absl/time/time.h"
#include "src/core/lib/security/credentials/credentials.h"
#include "src/core/lib/security/credentials/jwt/json_token.h"

class grpc_service_account_jwt_access_credentials
    : public grpc_call_credentials {
 public:
  grpc_service_account_jwt_access_credentials(grpc_auth_json_key key,
                                              gpr_timespec token_lifetime);
  ~grpc_service_account_jwt_access_credentials() override;

  bool get_request_metadata(grpc_polling_entity* pollent,
                            grpc_auth_metadata_context context,
                            grpc_credentials_mdelem_array* md_array,
                            grpc_closure* on_request_metadata,
                            grpc_error_handle* error) override;

  void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array,
                                   grpc_error_handle error) override;

  const gpr_timespec& jwt_lifetime() const { return jwt_lifetime_; }
  const grpc_auth_json_key& key() const { return key_; }

  std::string debug_string() override {
    return absl::StrFormat(
        "JWTAccessCredentials{ExpirationTime:%s}",
        absl::FormatTime(absl::FromUnixMicros(
            static_cast<int64_t>(gpr_timespec_to_micros(jwt_lifetime_)))));
  };

 private:
  void reset_cache();

  // Have a simple cache for now with just 1 entry. We could have a map based on
  // the service_url for a more sophisticated one.
  gpr_mu cache_mu_;
  struct {
    grpc_mdelem jwt_md = GRPC_MDNULL;
    char* service_url = nullptr;
    gpr_timespec jwt_expiration;
  } cached_;

  grpc_auth_json_key key_;
  gpr_timespec jwt_lifetime_;
};

// Private constructor for jwt credentials from an already parsed json key.
// Takes ownership of the key.
grpc_core::RefCountedPtr<grpc_call_credentials>
grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
    grpc_auth_json_key key, gpr_timespec token_lifetime);

#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JWT_CREDENTIALS_H */