text:
package org.auraframework.integration.test.adapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;

import org.auraframework.adapter.LocalizationAdapter;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.expression.PropertyReference;
import org.auraframework.impl.AuraImplTestCase;
import org.auraframework.impl.adapter.LocaleValueProvider;
import org.auraframework.impl.adapter.LocaleValueProvider.LocalizedLabel;
import org.auraframework.impl.expression.PropertyReferenceImpl;
import org.auraframework.service.DefinitionService;
import org.auraframework.service.LocalizationService;
import org.auraframework.system.AuraContext;
import org.auraframework.throwable.quickfix.InvalidExpressionException;
import org.auraframework.util.test.annotation.UnAdaptableTest;
import org.junit.Before;
import org.junit.Test;

@UnAdaptableTest
public class LocaleValueProviderTest extends AuraImplTestCase {
    private enum LocaleProperty {
        language(LocaleValueProvider.LANGUAGE),
        country(LocaleValueProvider.COUNTRY),
        variant(LocaleValueProvider.VARIANT),
        langLocale(LocaleValueProvider.LANGUAGE_LOCALE),
        numberFormat(LocaleValueProvider.NUMBER_FORMAT),
        percentFormat(LocaleValueProvider.PERCENT_FORMAT),
        currencyFormat(LocaleValueProvider.CURRENCY_FORMAT),
        dateFormat(LocaleValueProvider.DATE_FORMAT),
        datetimeFormat(LocaleValueProvider.DATETIME_FORMAT),
        timeFormat(LocaleValueProvider.TIME_FORMAT),
        timezone(LocaleValueProvider.TIME_ZONE),
        currencyCode(LocaleValueProvider.CURRENCY_CODE),
        decimal(LocaleValueProvider.DECIMAL),
        grouping(LocaleValueProvider.GROUPING),
        currency(LocaleValueProvider.CURRENCY),
        zero(LocaleValueProvider.ZERO_DIGIT);

        private PropertyReferenceImpl propRef;

        LocaleProperty(String name) {
            propRef = new PropertyReferenceImpl(name, null);
        }

        public PropertyReference getRef() {
            return propRef;
        }
    }

    @Inject
    private LocalizationAdapter localizationAdapter;

    @Inject
    DefinitionService definitionService;

    @Inject
    private LocalizationService localizationService;

    @Override
    @Before
    public void setUp() throws Exception {
        super.setUp();
    }

    @Test
    public void testValidateLocaleProperty() throws Exception {
        LocaleValueProvider lvp = new LocaleValueProvider(localizationService, localizationAdapter, definitionService);
        for (LocaleProperty lp : LocaleProperty.values()) {
            lvp.validate(lp.getRef());
        }

        PropertyReference property = new PropertyReferenceImpl("badProperty", null);
        try {
            lvp.validate(property);
            fail("Expected InvalidExpressionException for " + property);
        } catch (InvalidExpressionException e) {
            assertEquals("No property on $Locale for key: " + property,
                    e.getMessage());
        }

    }

    // semi-integration test checks that value provider is created and validated
    // on component
    @Test
    public void testInvalidLocalePropertyInMarkup() throws Exception {
        try {
            DefDescriptor<ComponentDef> desc = addSourceAutoCleanup(
                    ComponentDef.class,
                    "<aura:component>{!$Locale.badProperty}</aura:component>");

            instanceService.getInstance(desc, null);
            fail("Expected an InvalidExpressionException");
        } catch (InvalidExpressionException e) {
            assertEquals("No property on $Locale for key: badProperty",
                    e.getMessage());
        }
    }

    // Setting some locales for testing
    @Test
    public void testCurrency() throws Exception {
        HashMap<String, Object> defaultLocaleProperties = new HashMap<>();
        defaultLocaleProperties.put(LocaleValueProvider.LANGUAGE, "en");
        defaultLocaleProperties.put(LocaleValueProvider.COUNTRY, "US");
        defaultLocaleProperties.put(LocaleValueProvider.CURRENCY_FORMAT, "¤#,##0.00");
        defaultLocaleProperties.put(LocaleValueProvider.CURRENCY_CODE, "USD");
        defaultLocaleProperties.put(LocaleValueProvider.CURRENCY, "$");
        assertLocaleProperties(Arrays.asList(Locale.US), defaultLocaleProperties);

        HashMap<String, Object> jaLocaleProperties = new HashMap<>();
        jaLocaleProperties.put(LocaleValueProvider.LANGUAGE, "ja");
        jaLocaleProperties.put(LocaleValueProvider.COUNTRY, "JP");
        jaLocaleProperties.put(LocaleValueProvider.CURRENCY_FORMAT, "¤#,##0");
        jaLocaleProperties.put(LocaleValueProvider.CURRENCY_CODE, "JPY");
        jaLocaleProperties.put(LocaleValueProvider.CURRENCY, "¥");
        assertLocaleProperties(Arrays.asList(Locale.JAPAN), jaLocaleProperties);

        HashMap<String, Object> ukLocaleProperties = new HashMap<>();
        ukLocaleProperties.put(LocaleValueProvider.LANGUAGE, "en");
        ukLocaleProperties.put(LocaleValueProvider.COUNTRY, "GB");
        ukLocaleProperties.put(LocaleValueProvider.CURRENCY_FORMAT, "¤#,##0.00");
        ukLocaleProperties.put(LocaleValueProvider.CURRENCY_CODE, "GBP");
        ukLocaleProperties.put(LocaleValueProvider.CURRENCY, "£");
        assertLocaleProperties(Arrays.asList(Locale.UK), ukLocaleProperties);
    }

    /**
     * this test when we pass more than one locals to current context, we only honor the FIRST one.
     */
    @Test
    public void testMultiLocale() {
        HashMap<String, Object> localeProperties = new HashMap<>();
        createLocaleProperties_ENZA(localeProperties);
        assertLocaleProperties(Arrays.asList(new Locale("en", "ZA"), Locale.US), localeProperties);
    }

    /**
     * tests for number and percent formats for US, South Africa(ZA) and France
     * http://en.wikipedia.org/wiki/ISO_3166-2
     */
    @Test
    public void testNumberAndPercentFormats() {
        HashMap<String, Object> localeProperties = new HashMap<>();
        createLocaleProperties_ENUS(localeProperties);
        assertLocaleProperties(Arrays.asList(Locale.US), localeProperties);

        localeProperties.clear();
        createLocaleProperties_ENZA(localeProperties);
        assertLocaleProperties(Arrays.asList(new Locale("en", "ZA")), localeProperties);

        localeProperties.clear();
        createLocaleProperties_FRFR(localeProperties);
        assertLocaleProperties(Arrays.asList(new Locale("fr", "FR")), localeProperties);

        localeProperties.clear();
        createLocaleProperties_ENCA(localeProperties);
        assertLocaleProperties(Arrays.asList(new Locale("en", "CA")), localeProperties);
    }

    private void assertLocaleProperties(List<Locale> localeList, Map<String, Object> localeProperties) {
        AuraContext context = contextService.getCurrentContext();
        context.setRequestedLocales(localeList);
        LocaleValueProvider lvp = new LocaleValueProvider(localizationService, localizationAdapter, definitionService);
        String countryName = localeList == null ? "" : localeList.get(0).getCountry();
        for (Map.Entry<String, Object> entry : localeProperties.entrySet()) {
            assertLocaleProperty(lvp, entry.getKey(), entry.getValue(), countryName);
        }
    }

    private void assertLocaleProperty(LocaleValueProvider lvp, String propName, Object expected, String countryName) {
        PropertyReference ref = LocaleProperty.valueOf(propName).getRef();
        Object actual = lvp.getValue(ref);
        assertEquals("Unexpected value : " + propName+" of country: "+countryName, expected, actual);
    }

    private void createLocaleProperties_ENZA(HashMap<String, Object> localeProperties) {
        localeProperties.put(LocaleValueProvider.LANGUAGE, "en");
        localeProperties.put(LocaleValueProvider.COUNTRY, "ZA");
        localeProperties.put(LocaleValueProvider.CURRENCY_FORMAT, "¤#,##0.00");  // Patterns shouldn't localize
        localeProperties.put(LocaleValueProvider.GROUPING, "\u00A0");
        localeProperties.put(LocaleValueProvider.DECIMAL, ",");
        localeProperties.put(LocaleValueProvider.NUMBER_FORMAT, "#,##0.###");
        localeProperties.put(LocaleValueProvider.PERCENT_FORMAT, "#,##0%");
        localeProperties.put(LocaleValueProvider.LANGUAGE_LOCALE, "en_ZA");
        localeProperties.put(LocaleValueProvider.ZERO_DIGIT, "0");
        return;
    }

    private void createLocaleProperties_FRFR(HashMap<String, Object> localeProperties) {
        localeProperties.put(LocaleValueProvider.LANGUAGE, "fr");
        localeProperties.put(LocaleValueProvider.COUNTRY, "FR");
        localeProperties.put(LocaleValueProvider.CURRENCY_FORMAT, "#,##0.00 ¤");  // Patterns shouldn't localize
        localeProperties.put(LocaleValueProvider.GROUPING, "\u00A0");
        localeProperties.put(LocaleValueProvider.DECIMAL, ",");
        localeProperties.put(LocaleValueProvider.NUMBER_FORMAT, "#,##0.###");
        localeProperties.put(LocaleValueProvider.PERCENT_FORMAT, "#,##0 %");
        localeProperties.put(LocaleValueProvider.LANGUAGE_LOCALE, "fr_FR");
        localeProperties.put(LocaleValueProvider.ZERO_DIGIT, "0");
        return;
    }

    private void createLocaleProperties_ENUS(HashMap<String, Object> localeProperties) {
         localeProperties.put(LocaleValueProvider.LANGUAGE, "en");
         localeProperties.put(LocaleValueProvider.COUNTRY, "US");
         localeProperties.put(LocaleValueProvider.CURRENCY_FORMAT, "¤#,##0.00");  // Patterns shouldn't localize
         localeProperties.put(LocaleValueProvider.GROUPING, ",");
         localeProperties.put(LocaleValueProvider.DECIMAL, ".");
         localeProperties.put(LocaleValueProvider.NUMBER_FORMAT, "#,##0.###");
         localeProperties.put(LocaleValueProvider.PERCENT_FORMAT, "#,##0%");
         localeProperties.put(LocaleValueProvider.LANGUAGE_LOCALE, "en_US");
         localeProperties.put(LocaleValueProvider.ZERO_DIGIT, "0");
        return;
    }

    private void createLocaleProperties_ENCA(HashMap<String, Object> localeProperties) {
        localeProperties.put(LocaleValueProvider.LANGUAGE, "en");
        localeProperties.put(LocaleValueProvider.COUNTRY, "CA");
        localeProperties.put(LocaleValueProvider.CURRENCY_FORMAT, "¤#,##0.00");  // Patterns shouldn't localize
        localeProperties.put(LocaleValueProvider.GROUPING, ",");
        localeProperties.put(LocaleValueProvider.DECIMAL, ".");
        localeProperties.put(LocaleValueProvider.NUMBER_FORMAT, "#,##0.###");
        localeProperties.put(LocaleValueProvider.PERCENT_FORMAT, "#,##0%");
        localeProperties.put(LocaleValueProvider.LANGUAGE_LOCALE, "en_CA");
        localeProperties.put(LocaleValueProvider.ZERO_DIGIT, "0");
        localeProperties.put(LocaleValueProvider.CURRENCY_CODE, "CAD");
        return;
    }

    /**
     * Test to verify getValue returns null for undefined property
     * @throws Exception
     */
    @Test
    public void testGetValueUndefinedProperty() throws Exception {
        AuraContext context = contextService.getCurrentContext();
        context.setRequestedLocales(Arrays.asList(Locale.UK));
        LocaleValueProvider lvp = new LocaleValueProvider(localizationService, localizationAdapter, definitionService);
        assertEquals(null,
                lvp.getValue(new PropertyReferenceImpl("ISO3Language", null))); // undefined
                                                                                // property
    }

    /**
     * Test name of months is returned correctly
     */
    @Test
    public void testNameOfMonths() throws Exception {
    HashMap<String, String> expectedMonthNames = new HashMap<>();
        expectedMonthNames.put("Jan", "January");
        expectedMonthNames.put("Feb", "February");
        expectedMonthNames.put("Mar", "March");
        expectedMonthNames.put("Apr", "April");
        expectedMonthNames.put("May", "May");
        expectedMonthNames.put("Jun", "June");
        expectedMonthNames.put("Jul", "July");
        expectedMonthNames.put("Aug", "August");
        expectedMonthNames.put("Sep", "September");
        expectedMonthNames.put("Oct", "October");
        expectedMonthNames.put("Nov", "November");
        expectedMonthNames.put("Dec", "December");
        assertDateLocaleProperties(null, LocaleValueProvider.MONTH_NAME, expectedMonthNames); //en_US

        HashMap<String, String> expectedMonthNamesJP = new HashMap<>();
        expectedMonthNamesJP.put("1", "1月");
        expectedMonthNamesJP.put("2", "2月");
        expectedMonthNamesJP.put("3", "3月");
        expectedMonthNamesJP.put("4", "4月");
        expectedMonthNamesJP.put("5", "5月");
        expectedMonthNamesJP.put("6", "6月");
        expectedMonthNamesJP.put("7", "7月");
        expectedMonthNamesJP.put("8", "8月");
        expectedMonthNamesJP.put("9", "9月");
        expectedMonthNamesJP.put("10", "10月");
        expectedMonthNamesJP.put("11", "11月");
        expectedMonthNamesJP.put("12", "12月");
        assertDateLocaleProperties(Locale.JAPANESE, LocaleValueProvider.MONTH_NAME, expectedMonthNamesJP);

        // Russian differentiates usage of standalone month names and formatting month names
        // NOTE: Other known similar locales: "ca", "cs", "el", "fi", "hr", "it", "it_CH", "lt", "pl", "ru", "sk", "uk"
        HashMap<String, String> expectedMonthNamesRU = new HashMap<>();
        expectedMonthNamesRU.put("Янв.", "Январь");
        expectedMonthNamesRU.put("Февр.", "Февраль");
        expectedMonthNamesRU.put("Март", "Март");
        expectedMonthNamesRU.put("Апр.", "Апрель");
        expectedMonthNamesRU.put("Май", "Май");
        expectedMonthNamesRU.put("Июнь", "Июнь");
        expectedMonthNamesRU.put("Июль", "Июль");
        expectedMonthNamesRU.put("Авг.", "Август");
        expectedMonthNamesRU.put("Сент.", "Сентябрь");
        expectedMonthNamesRU.put("Окт.", "Октябрь");
        expectedMonthNamesRU.put("Нояб.", "Ноябрь");
        expectedMonthNamesRU.put("Дек.", "Декабрь");
        assertDateLocaleProperties(new Locale("ru"), LocaleValueProvider.MONTH_NAME, expectedMonthNamesRU);
    }

    /**
     * Test name of day is returned correctly
     */
    @Test
    public void testNameOfWeekdays() throws Exception {
        HashMap<String, String> expectedDayNames = new HashMap<>();
        expectedDayNames.put("MON", "Monday");
        expectedDayNames.put("TUE", "Tuesday");
        expectedDayNames.put("WED", "Wednesday");
        expectedDayNames.put("THU", "Thursday");
        expectedDayNames.put("FRI", "Friday");
        expectedDayNames.put("SAT", "Saturday");
        expectedDayNames.put("SUN", "Sunday");
        assertDateLocaleProperties(null, LocaleValueProvider.WEEKDAY_NAME, expectedDayNames); //en_US

        HashMap<String, String> expectedDayNamesJP = new HashMap<>();
        expectedDayNamesJP.put("日", "日曜日");
        expectedDayNamesJP.put("月", "月曜日");
        expectedDayNamesJP.put("火", "火曜日");
        expectedDayNamesJP.put("水", "水曜日");
        expectedDayNamesJP.put("木", "木曜日");
        expectedDayNamesJP.put("金", "金曜日");
        expectedDayNamesJP.put("土", "土曜日");
        assertDateLocaleProperties(Locale.JAPANESE, LocaleValueProvider.WEEKDAY_NAME, expectedDayNamesJP);
    }

    /**
     * Test Today label is returned correctly
     */
    @Test
    public void testToday() throws Exception {
        assertTodayLocaleProperty(null, "Today");  // enUS
        assertTodayLocaleProperty(Locale.JAPANESE, "今日");
    }

    @SuppressWarnings("unchecked")
    private void assertDateLocaleProperties(Locale locale, String dateName,
            HashMap<String, String> expectedData) {
        AuraContext context = contextService.getCurrentContext();
        context.setRequestedLocales(locale == null ? null : Arrays.asList(locale));
        LocaleValueProvider lvp = new LocaleValueProvider(localizationService, localizationAdapter, definitionService);

        ArrayList<LocalizedLabel> values = (ArrayList<LocalizedLabel>) lvp.getData().get(dateName);
        if (LocaleValueProvider.MONTH_NAME.equals(dateName)) {
        		assertEquals("Month names must be 13", 13, values.size());
        }
        Set<String> expectedShortNames = expectedData.keySet();
        for (int i=0; i<values.size(); i++) {
            String shortName = values.get(i).getShortName();
            String fullName = values.get(i).getFullName();
            if (shortName != null && !shortName.isEmpty()) {
                assertTrue("Could not find short name '" + shortName + "' in expected short names for locale " + locale,
                    expectedShortNames.contains(shortName));
                assertEquals("Long names for locale " + locale + " do not equal",
                    expectedData.get(shortName), fullName);
            }
        }
    }

    private void assertTodayLocaleProperty(Locale locale, String expectedLabel) {
        AuraContext context = contextService.getCurrentContext();
        context.setRequestedLocales(locale == null ? null : Arrays.asList(locale));
        LocaleValueProvider lvp = new LocaleValueProvider(localizationService, localizationAdapter, definitionService);
        String actualLabel = (String) lvp.getData().get(LocaleValueProvider.TODAY_LABEL);
        assertEquals("Today label for locale " + locale + " is incorrect", expectedLabel, actualLabel);
    }
}


text:
@import AVFoundation;

@interface PKPlayerView ()

@property (strong, nonatomic) UIImageView *playerImageView;

@property (nonatomic, strong) UIImage *previewImage;

@property (nonatomic,weak) AVPlayer *player;

@property (strong, nonatomic) AVPlayerLayer *playerLayer;
@property (strong, nonatomic) AVPlayerItem *playerItem;

@property (assign, nonatomic ,readwrite) BOOL isPlayable;
@property (nonatomic ,assign ,readwrite) BOOL isPlaying;

@property (nonatomic, strong) NSString *videoPath;
@property (nonatomic, strong) NSString *uniqueID;

@property (nonatomic ,assign) BOOL needPlay;

@end

@implementation PKPlayerView

#pragma mark - Initialization

- (instancetype)initWithFrame:(CGRect)frame videoPath:(NSString *)videoPath previewImage:(UIImage *)previewImage {
    NSParameterAssert(videoPath != nil);
    NSParameterAssert(previewImage != nil);

    self = [super initWithFrame:frame];
    if (self) {
        if (videoPath) {
            [self setVideoPath:videoPath];
        }
        _isPlaying = NO;
        _isPlayable = YES;
        _previewImage = previewImage;

        [self addSubview:self.playerImageView];
        [self.playerImageView.layer addSublayer:self.playerLayer];
    }
    return self;
}

- (void)dealloc {
    _videoPath = nil;
    _playerLayer = nil;
    _player = nil;
    _playerItem = nil;
    _previewImage = nil;
    _playerImageView = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Setters

- (void)setVideoPath:(NSString *)videoPath {
    _videoPath = [videoPath copy];
    _playerLayer = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:videoPath] options:nil];
    self.isPlayable = asset.playable;

    NSArray *requestedKeys = @[@"playable"];

    [asset loadValuesAsynchronouslyForKeys:requestedKeys completionHandler: ^{
        dispatch_async( dispatch_get_main_queue(), ^{
            [self prepareToPlayAsset:asset withKeys:requestedKeys];
        });
    }];
}

- (void)setPreviewImage:(UIImage *)previewImage {
    _previewImage = previewImage;
    if (self.playerImageView) {
        self.playerImageView.image = previewImage;
    }
    _playerLayer = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark Prepare to play asset, URL

- (void)prepareToPlayAsset:(AVURLAsset *)asset withKeys:(NSArray *)requestedKeys {
    for (NSString *thisKey in requestedKeys) {
        NSError *error = nil;
        AVKeyValueStatus keyStatus = [asset statusOfValueForKey:thisKey error:&error];
        if (keyStatus == AVKeyValueStatusFailed) {
            NSLog(@"加载失败");
            return;
        }
    }
    if (!asset.playable) {
        NSLog(@"不能播放");
        return;
    }
    self.playerItem = [AVPlayerItem playerItemWithAsset:asset];

    [self creatPlayer];
}

#pragma mark - Public

- (void)play {
    if (!self.playerItem) {
        if (!self.player) {
            self.needPlay = YES;
            return;
        }
    } else {
        [self creatPlayer];
    }

    [self.player play];
    self.isPlaying = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shortVideoItemPlayerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
}

- (void)stop {
    if (self.player) {
        [self.player pause];
        self.isPlaying = NO;
        [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
    }
}

#pragma mark - Private

- (void)creatPlayer {
    self.player = [[PKPlayerManager sharedManager] getAVQueuePlayWithPlayerItem:self.playerItem uniqueID:self.uniqueID];
    self.playerLayer.player = self.player;
    if (self.needPlay) {
        self.needPlay = NO;
        [self play];
    }
}

#pragma mark - Notification

- (void)shortVideoItemPlayerItemDidReachEnd:(NSNotification *)notification{
    AVPlayerItem *item = notification.object;
    if (self.player.currentItem == item) {
        [self.player seekToTime:kCMTimeZero];
        [self.player play];
    }
}

#pragma mark - Getter

- (NSString *)uniqueID {
    if (!_uniqueID) {
        _uniqueID = [NSProcessInfo processInfo].globallyUniqueString;
    }
    return _uniqueID;
}

- (UIImageView *)playerImageView {
    if (!_playerImageView) {
        _playerImageView = [[UIImageView alloc] initWithImage:self.previewImage];
        _playerImageView.backgroundColor = [UIColor blackColor];
        _playerImageView.frame = CGRectMake(0.0f, 0.0f, self.frame.size.width, self.frame.size.height);
        _playerImageView.contentMode = UIViewContentModeScaleAspectFill;
        _playerImageView.clipsToBounds = YES;
    }
    return _playerImageView;
}

- (AVPlayerLayer *)playerLayer {
    if (!_playerLayer) {
        _playerLayer = [AVPlayerLayer layer];
        _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        self.playerLayer.frame = CGRectMake(0.0f, 0.0f, self.frame.size.width, self.frame.size.height);
    }
    return _playerLayer;
}

@end

redpajama_set_name: RedPajamaGithub


text:
namespace google {
namespace cloud {
namespace bigquery_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

class BigQueryReadLogging : public BigQueryReadStub {
 public:
  ~BigQueryReadLogging() override = default;
  BigQueryReadLogging(std::shared_ptr<BigQueryReadStub> child,
                      TracingOptions tracing_options,
                      std::set<std::string> components);

  StatusOr<google::cloud::bigquery::storage::v1::ReadSession> CreateReadSession(
      grpc::ClientContext& context,
      google::cloud::bigquery::storage::v1::CreateReadSessionRequest const&
          request) override;

  std::unique_ptr<google::cloud::internal::StreamingReadRpc<
      google::cloud::bigquery::storage::v1::ReadRowsResponse>>
  ReadRows(std::unique_ptr<grpc::ClientContext> context,
           google::cloud::bigquery::storage::v1::ReadRowsRequest const& request)
      override;

  StatusOr<google::cloud::bigquery::storage::v1::SplitReadStreamResponse>
  SplitReadStream(
      grpc::ClientContext& context,
      google::cloud::bigquery::storage::v1::SplitReadStreamRequest const&
          request) override;

 private:
  std::shared_ptr<BigQueryReadStub> child_;
  TracingOptions tracing_options_;
  std::set<std::string> components_;
};  // BigQueryReadLogging

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
namespace gcpcxxV1 = GOOGLE_CLOUD_CPP_NS;  // NOLINT(misc-unused-alias-decls)
}  // namespace bigquery_internal
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BIGQUERY_INTERNAL_BIGQUERY_READ_LOGGING_DECORATOR_H


text:
cd $(dirname $0)/..
td=$(pwd)
wd=$td/wiki

if [ -d $wd ]; then
	echo "Wiki dir $wd already exists"
	exit 1
fi

origin=$(git remote -v | grep origin | grep fetch | awk '{print $2;}')
echo "Git origin: $origin"

wiki_origin=${origin%%.git}.wiki.git
echo "Wiki origin: $wiki_origin"

git clone $wiki_origin $wd


text:
package main

import (
	"context"
	"flag"
	"fmt"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
)

// CWLGetLogEventsAPI defines the interface for the GetLogEvents function
type CWLGetLogEventsAPI interface {
	GetLogEvents(ctx context.Context, params *cloudwatchlogs.GetLogEventsInput, optFns ...func(*cloudwatchlogs.Options)) (*cloudwatchlogs.GetLogEventsOutput, error)
}

// GetEvents retrieves cloudwatch log events from the specified log group and log stream
// Inputs:
//     ctx is the context of the method call, which includes the Region
//     api is the interface that defines the method call
//     input defines the input arguments to the service call.
// Output:
//     If success, a GetLogEventsOutput object containing the result of the service call and nil
//     Otherwise, nil and an error from the call to GetLogEvents
func GetEvents(ctx context.Context, api CWLGetLogEventsAPI, input *cloudwatchlogs.GetLogEventsInput) (*cloudwatchlogs.GetLogEventsOutput, error) {
	return api.GetLogEvents(ctx, input)
}

func main() {

	logGroupName := flag.String("g", "", "The name of the log group")
	logStreamName := flag.String("s", "", "The name of the log stream")
	flag.Parse()

	if *logGroupName == "" || *logStreamName == "" {
		fmt.Println("You must supply a logGroupName and logStreamName")
		return
	}

	cfg, err := config.LoadDefaultConfig(context.TODO())
	if err != nil {
		panic("configuration error, " + err.Error())
	}

	client := cloudwatchlogs.NewFromConfig(cfg)

	request := &cloudwatchlogs.GetLogEventsInput{
		LogGroupName:  logGroupName,
		LogStreamName: logStreamName,
	}

	response, err := GetEvents(context.TODO(), client, request)
	if err != nil {
		fmt.Println("Could not fetch log events")
		fmt.Println(err)
		return
	}

	fmt.Println("Event messages for stream " + *logStreamName + " in log group  " + *logGroupName)
	for _, event := range response.Events {
		fmt.Println(*event.Message)
	}

}


text:
var assert = require('assert');
var supertest = require('supertest');
var mock = require('../../..');
var status = mock.status;

module.exports = function () {
  var server = mock.server();
  var database = server.database('test');
  var request = supertest(database.url());
  var version = server.options.version;

  afterEach(function () {
    database.done();
  });

  it('should mock a successful delete', function (done) {
    database.delete();

    request
      .delete('')
      .set('Accept', 'application/json')
      .expect(status.OK, { ok: true })
      .expect('Cache-Control', 'must-revalidate')
      .expect('Content-Length', /^\d+$/)
      .expect('Content-Type', 'application/json')
      .expect('Date', server.options.date.toUTCString())
      .expect('Server', `CouchDB/${version} (Erlang/OTP)`)
      .end(done);
  });

  it('should mock a failure because of added ?rev= param', function (done) {
    database.delete({ status: status.BAD_REQUEST });

    request
      .delete('')
      .set('Accept', 'application/json')
      .expect(status.BAD_REQUEST, {
        error:  'bad_request',
        reason: 'You tried to DELETE a database with a ?rev= parameter. Did you mean to DELETE a document instead?'
      })
      .expect('Cache-Control', 'must-revalidate')
      .expect('Content-Length', /^\d+$/)
      .expect('Content-Type', 'application/json')
      .expect('Date', server.options.date.toUTCString())
      .expect('Server', `CouchDB/${version} (Erlang/OTP)`)
      .end(done);
  });

  it('should mock a failure because of security restrictions', function (done) {
    database.delete({ status: status.UNAUTHORIZED });

    request
      .delete('')
      .set('Accept', 'application/json')
      .expect(status.UNAUTHORIZED, {
        error:  'unauthorized',
        reason: 'You are not a server admin.'
      })
      .expect('Cache-Control', 'must-revalidate')
      .expect('Content-Length', /^\d+$/)
      .expect('Content-Type', 'application/json')
      .expect('Date', server.options.date.toUTCString())
      .expect('Server', `CouchDB/${version} (Erlang/OTP)`)
      .end(done);
  });

  it('should mock a failure because the database does not exist', function (done) {
    database.delete({ status: status.NOT_FOUND });

    request
      .delete('')
      .set('Accept', 'application/json')
      .expect(status.NOT_FOUND, {
        error:  'not_found',
        reason: 'missing'
      })
      .expect('Cache-Control', 'must-revalidate')
      .expect('Content-Length', /^\d+$/)
      .expect('Content-Type', 'application/json')
      .expect('Date', server.options.date.toUTCString())
      .expect('Server', `CouchDB/${version} (Erlang/OTP)`)
      .end(done);
  });
};


text:
var Genetics = {
	import: {
		finishUrl: null,
		showProgress: function() {
			var progressDiv = $( "#progress" );
			var remainingTimeDiv = $( "#remaining" );
			$.ajax().done(function(data,textStatus, jqXHR) {
				if( data.total == data.imported ) {
					location.href = Genetics.import.finishUrl;
					return;
				} else {
					progressDiv.removeClass( 'error' ).text( data.imported + " / " + data.total );

					// Compute remaining time: timeElapsed / imported * ( total - imported )
					if( data.imported > 0 ) {
						var timestampStarted = data.description.substring( data.description.indexOf( " / " ) + 3 ) * 1;
						var timeElapsed = new Date().getTime() - timestampStarted;
						remainingTime = timeElapsed / data.imported * ( data.total - data.imported );

						if( remainingTime > 60000 ) {
							remainingTimeDiv.text( "Approximately " + Math.round( remainingTime / 60000 ) + " minute(s) remaining" );
						} else {
							remainingTimeDiv.text( "Approximately " + Math.round( remainingTime / 1000 ) + " seconds remaining" );
						}
					}

					setTimeout( Genetics.import.showProgress, 2000 );
				}
			}).fail(function(jqXHR, textStatus, errorThrown) {
				progressDiv.addClass( 'error' ).text( jqXHR.responseText );
				remainingTimeDiv.text( "" );
				setTimeout( Genetics.import.showProgress, 2000 );
			});
		}
	}
}


text:
/*jslint vars: true, plusplus: true, devel: true, nomen: true,  regexp: true, indent: 4, maxerr: 50 */
/*global define, brackets, $ */

define(function (require, exports, module) {
    "use strict";

    var BracketsFiler   = brackets.getModule("filesystem/impls/filer/BracketsFiler");
    var FileSystemCache = brackets.getModule("filesystem/impls/filer/FileSystemCache");
    var Path            = BracketsFiler.Path;

    var NEEDS_RENAME    = "needs rename";

    function move(src, dest) {
        var deferred = new $.Deferred();
        var fs = BracketsFiler.fs();
        src = src.replace(/\/?$/, "");
        dest = dest.replace(/\/?$/, "");
        var srcNodeName = Path.basename(src);

        if(src === dest || Path.dirname(src) === dest || dest.indexOf(src) === 0) {
            return deferred.resolve();
        }

        fs.readdir(dest, function(err, contents) {
            if(err) {
                return deferred.reject(err);
            }

            if(contents.indexOf(srcNodeName) !== -1) {
                return deferred.reject({ type: NEEDS_RENAME });
            }

            fs.mv(src, dest, function(err) {
                if(err) {
                    return deferred.reject(err);
                }

                fs.rm(src, {recursive: true}, function(err) {
                    if(err) {
                        return deferred.reject(err);
                    }

                    FileSystemCache.refresh(function(err) {
                        if(err) {
                            return deferred.reject(err);
                        }

                        deferred.resolve(dest);
                    });
                });
            });
        });

        return deferred;
    }

    exports.move             = move;
    exports.NEEDS_RENAME     = NEEDS_RENAME;
});


text:
- SMS and coin addresses are not validated.

- should not be able to deposit cash until destination is fully validated, and should not
    be able to go back, since might be no way to "eject" deposit.

- would be nice to make an address validator directive for angular
  <http://www.benlesh.com/2012/12/angular-js-custom-validation-via.html>
    - should decode base58 and check the checksum (last 4 chars)
    - but best if it does not validate prefix. then useful for all sorts of entries.
    - bitcoinjs has this code, but all broken up into 3 packages, and raises assertions


text:
//-----------------------------------------------------------------------
// <copyright file="TestWorldFactory.cs" company="Benjamin Woodall">
//     Copyright Benjamin Woodall 2014. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using Core;
using Core.Data;
using Core.Factories;
using Core.Programmability;
using Core.Resources.Management;
using Game;
using Game.Data;
using Game.Factories;

namespace TestUtilities.Game.Factories
{
    /// Creates instances of IWorld
    public class TestWorldFactory : WorldFactoryBase, IWorldFactory
    {
        /// Initializes a new instance of the TestWorldFactory class
        public TestWorldFactory(
            IResourceLibrary resources,
            IControllerManager controllerManager,
            IControllerFactory[] controllerFactories,
            IEntityFactory entityFactory)
        : base(resources, controllerManager, controllerFactories, entityFactory) { }

        /// Creates an instance of IWorld
        /// <param name="definition">Level definition</param>
        /// <returns>The created IWorld instance</returns>
        public override IWorld Create(LevelDefinition definition)
        {
            return new TestWorld(
                definition,
                this.Resources,
                this.ControllerManager,
                this.ControllerFactories,
                this.EntityFactory);
        }
    }
}


text:
package com.sg.model.slackRq;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;

import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
    "actions",
    "callback_id",
    "team",
    "channel",
    "user",
    "action_ts",
    "message_ts",
    "attachment_id",
    "token",
    "response_url"
})
public class IntMessageRequest {

    @JsonProperty("actions")
    private List<Action> actions = new ArrayList<Action>();
    @JsonProperty("callback_id")
    private String callbackId;
    @JsonProperty("team")
    private Team team;
    @JsonProperty("channel")
    private Channel channel;
    @JsonProperty("user")
    private User user;
    @JsonProperty("action_ts")
    private String actionTs;
    @JsonProperty("message_ts")
    private String messageTs;
    @JsonProperty("attachment_id")
    private String attachmentId;
    @JsonProperty("token")
    private String token;
    @JsonProperty("response_url")
    private String responseUrl;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     *
     * @return
     *     The actions
     */
    @JsonProperty("actions")
    public List<Action> getActions() {
        return actions;
    }

    /**
     *
     * @param actions
     *     The actions
     */
    @JsonProperty("actions")
    public void setActions(List<Action> actions) {
        this.actions = actions;
    }

    /**
     *
     * @return
     *     The callbackId
     */
    @JsonProperty("callback_id")
    public String getCallbackId() {
        return callbackId;
    }

    /**
     *
     * @param callbackId
     *     The callback_id
     */
    @JsonProperty("callback_id")
    public void setCallbackId(String callbackId) {
        this.callbackId = callbackId;
    }

    /**
     *
     * @return
     *     The team
     */
    @JsonProperty("team")
    public Team getTeam() {
        return team;
    }

    /**
     *
     * @param team
     *     The team
     */
    @JsonProperty("team")
    public void setTeam(Team team) {
        this.team = team;
    }

    /**
     *
     * @return
     *     The channel
     */
    @JsonProperty("channel")
    public Channel getChannel() {
        return channel;
    }

    /**
     *
     * @param channel
     *     The channel
     */
    @JsonProperty("channel")
    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    /**
     *
     * @return
     *     The user
     */
    @JsonProperty("user")
    public User getUser() {
        return user;
    }

    /**
     *
     * @param user
     *     The user
     */
    @JsonProperty("user")
    public void setUser(User user) {
        this.user = user;
    }

    /**
     *
     * @return
     *     The actionTs
     */
    @JsonProperty("action_ts")
    public String getActionTs() {
        return actionTs;
    }

    /**
     *
     * @param actionTs
     *     The action_ts
     */
    @JsonProperty("action_ts")
    public void setActionTs(String actionTs) {
        this.actionTs = actionTs;
    }

    /**
     *
     * @return
     *     The messageTs
     */
    @JsonProperty("message_ts")
    public String getMessageTs() {
        return messageTs;
    }

    /**
     *
     * @param messageTs
     *     The message_ts
     */
    @JsonProperty("message_ts")
    public void setMessageTs(String messageTs) {
        this.messageTs = messageTs;
    }

    /**
     *
     * @return
     *     The attachmentId
     */
    @JsonProperty("attachment_id")
    public String getAttachmentId() {
        return attachmentId;
    }

    /**
     *
     * @param attachmentId
     *     The attachment_id
     */
    @JsonProperty("attachment_id")
    public void setAttachmentId(String attachmentId) {
        this.attachmentId = attachmentId;
    }

    /**
     *
     * @return
     *     The token
     */
    @JsonProperty("token")
    public String getToken() {
        return token;
    }

    /**
     *
     * @param token
     *     The token
     */
    @JsonProperty("token")
    public void setToken(String token) {
        this.token = token;
    }

    /**
     *
     * @return
     *     The responseUrl
     */
    @JsonProperty("response_url")
    public String getResponseUrl() {
        return responseUrl;
    }

    /**
     *
     * @param responseUrl
     *     The response_url
     */
    @JsonProperty("response_url")
    public void setResponseUrl(String responseUrl) {
        this.responseUrl = responseUrl;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}


text:
<!doctype html>

    <meta charset="utf-8" />
    <link rel="apple-touch-icon" sizes="76x76" href="../assets/img/apple-icon.png" />
    <link rel="icon" type="image/png" href="../assets/img/favicon.png" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>Material Dashboard PRO by Creative Tim | Premium Bootstrap Admin Template</title>
    <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
    <meta name="viewport" content="width=device-width" />

    <link rel="canonical" href="https://www.creative-tim.com/product/material-dashboard-pro" />

    <meta name="keywords" content="material dashboard, bootstrap material admin, bootstrap material dashboard, material design admin, material design, creative tim, html dashboard, html css dashboard, web dashboard, freebie, free bootstrap dashboard, css3 dashboard, bootstrap admin, bootstrap dashboard, frontend, responsive bootstrap dashboard, premiu material design admin">
    <meta name="description" content="Material Dashboard PRO is a Premium Material Bootstrap Admin with a fresh, new design inspired by Google's Material Design.">

    <meta itemprop="name" content="Material Dashboard PRO by Creative Tim | Premium Bootstrap Admin Template">
    <meta itemprop="description" content="Material Dashboard PRO is a Premium Material Bootstrap Admin with a fresh, new design inspired by Google's Material Design.">
    <meta itemprop="image" content="../../../../s3.amazonaws.com/creativetim_bucket/products/51/opt_mdp_thumbnail.jpg">

    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:site" content="@creativetim">
    <meta name="twitter:title" content="Material Dashboard PRO by Creative Tim | Premium Bootstrap Admin Template">
    <meta name="twitter:description" content="Material Dashboard PRO is a Premium Material Bootstrap Admin with a fresh, new design inspired by Google's Material Design.">
    <meta name="twitter:creator" content="@creativetim">
    <meta name="twitter:image" content="../../../../s3.amazonaws.com/creativetim_bucket/products/51/opt_mdp_thumbnail.jpg">

    <meta property="fb:app_id" content="655968634437471">
    <meta property="og:title" content="Material Dashboard PRO by Creative Tim | Premium Bootstrap Admin Template" />
    <meta property="og:type" content="article" />
    <meta property="og:url" content="http://www.creative-tim.com/product/material-dashboard-pro" />
    <meta property="og:image" content="../../../../s3.amazonaws.com/creativetim_bucket/products/51/opt_mdp_thumbnail.jpg" />
    <meta property="og:description" content="Material Dashboard PRO is a Premium Material Bootstrap Admin with a fresh, new design inspired by Google's Material Design." />
    <meta property="og:site_name" content="Creative Tim" />

    <link href="../assets/css/bootstrap.min.css" rel="stylesheet" />

    <link href="../assets/css/material-dashboard.css" rel="stylesheet" />

    <link href="../assets/css/demo.css" rel="stylesheet" />

    <link href="../../../../maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons" />

                    Creative Tim

                    Ct

                            Tania Andrew

                                    My Profile

                                    Edit Profile

                                    Settings

                            dashboard

Dashboard

                            image

Pages

                                    Pricing

                                    Timeline

                                    Login Page

                                    Register Page

                                    Lock Screen Page

                                    User Profile

                            apps

Components

                                    Buttons

                                    Grid System

                                    Panels

                                    Sweet Alert

                                    Notifications

                                    Icons

                                    Typography

                            content_paste

Forms

                                    Regular Forms

                                    Extended Forms

                                    Validation Forms

                                    Wizard

                            grid_on

Tables

                                    Regular Tables

                                    Extended Tables

                                    DataTables.net

                            place

Maps

                                    Google Maps

                                    Full Screen Map

                                    Vector Map

                            widgets

Widgets

                            timeline

Charts

                            date_range

Calendar

                        <button id="minimizeSidebar" class="btn btn-round btn-white btn-fill btn-just-icon">
                            more_vert
                            view_list
                        </button>

                        <button type="button" class="navbar-toggle" data-toggle="collapse">
                            Toggle navigation

                        </button>
                         Regular Tables

                                    dashboard

Dashboard

                                    notifications
                                    5

                                        Notifications

                                        Mike John responded to your email

                                        You have 5 new tasks

                                        You're now friend with Andrew

                                        Another Notification

                                        Another One

                                    person

Profile

                        <form class="navbar-form navbar-right" role="search">

                                <input type="text" class="form-control" placeholder="Search">

                            <button type="submit" class="btn btn-white btn-round btn-just-icon">
                                search

                            </button>
                        </form>

                                    assignment

Simple Table

                                                Name
                                                Country
                                                City
                                                Salary

                                                    Dakota Rice
                                                    Niger
                                                    Oud-Turnhout
                                                    $36,738

                                                    Minerva Hooper
                                                    Curaçao
                                                    Sinaai-Waas
                                                    $23,789

                                                    Sage Rodriguez
                                                    Netherlands
                                                    Baileux
                                                    $56,142

                                                    Philip Chaney
                                                    Korea, South
                                                    Overland Park
                                                    $38,735

                                                    Doris Greene
                                                    Malawi
                                                    Feldkirchen in Kärnten
                                                    $63,542

                                                    Mason Porter
                                                    Chile
                                                    Gloucester
                                                    $78,615

                                        assignment

Table on Plain Background

Here is a subtitle for this table

                                                ID
                                                Name
                                                Salary
                                                Country
                                                City

                                                    1
                                                    Dakota Rice
                                                    $36,738
                                                    Niger
                                                    Oud-Turnhout

                                                    2
                                                    Minerva Hooper
                                                    $23,789
                                                    Curaçao
                                                    Sinaai-Waas

                                                    3
                                                    Sage Rodriguez
                                                    $56,142
                                                    Netherlands
                                                    Baileux

                                                    4
                                                    Philip Chaney
                                                    $38,735
                                                    Korea, South
                                                    Overland Park

                                                    5
                                                    Doris Greene
                                                    $63,542
                                                    Malawi
                                                    Feldkirchen in Kärnten

                                                    6
                                                    Mason Porter
                                                    $78,615
                                                    Chile
                                                    Gloucester

                                        assignment

Regular Table with Colors

                                                ID
                                                Name
                                                Salary
                                                Country
                                                City

                                                    1
                                                    Dakota Rice (Success)
                                                    $36,738
                                                    Niger
                                                    Oud-Turnhout

                                                    2
                                                    Minerva Hooper
                                                    $23,789
                                                    Curaçao
                                                    Sinaai-Waas

                                                    3
                                                    Sage Rodriguez (Info)
                                                    $56,142
                                                    Netherlands
                                                    Baileux

                                                    4
                                                    Philip Chaney
                                                    $38,735
                                                    Korea, South
                                                    Overland Park

                                                    5
                                                    Doris Greene (Danger)
                                                    $63,542
                                                    Malawi
                                                    Feldkirchen in Kärnten

                                                    6
                                                    Mason Porter
                                                    $78,615
                                                    Chile
                                                    Gloucester

                                                    7
                                                    Mike Chaney (Warning)
                                                    $38,735
                                                    Romania
                                                    Bucharest

                                    Home

                                    Company

                                    Portfolio

                                    Blog

                        ©

                        Creative Tim, made with love for a better web

 Sidebar Filters

Sidebar Background

Sidebar Mini

                                <input type="checkbox" unchecked="">

Sidebar Image

                                <input type="checkbox" checked="">

Images

                        Buy Now

                        Get Free Demo

Thank you for 95 shares!

                    <button id="twitter" class="btn btn-social btn-twitter btn-round"> · 45</button>
                    <button id="facebook" class="btn btn-social btn-facebook btn-round"> ·50</button>


text:
require "rest-client"
require "json"

module Versapay
  class Client
    def initialize(user, password, environment='secure')
      @user = user
      @password = password
      @environment = environment
    end

    attr_reader :user, :password, :environment

    def url
      "https://#{user}:#{password}@#{environment}.versapay.com/api/transactions.json"
    end

    def send(amount, email, message=nil)
      amount_in_cents = (amount.to_f * 100).to_i

      payload = {
        transaction_type: 'send',
        email: email,
        amount_in_cents: amount_in_cents,
        message: message
      }.to_json

      response_hash = nil

      RestClient.post(url, payload, content_type: :json, accept: :json) do |response, request, result, &block|
        unless response.code == 201
          raise "Error: #{JSON.parse(response.body).inspect}"
        end
        response_hash = JSON.parse(response.body)
      end

      response_hash
    end
  end
end


text:
#include "common/router/scoped_rds.h"

#include <memory>

#include "envoy/admin/v3/config_dump.pb.h"
#include "envoy/api/v2/scoped_route.pb.h"
#include "envoy/config/core/v3/config_source.pb.h"
#include "envoy/config/route/v3/scoped_route.pb.h"
#include "envoy/config/route/v3/scoped_route.pb.validate.h"
#include "envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.pb.h"
#include "envoy/service/discovery/v3/discovery.pb.h"

#include "common/common/assert.h"
#include "common/common/cleanup.h"
#include "common/common/logger.h"
#include "common/common/utility.h"
#include "common/config/api_version.h"
#include "common/config/resources.h"
#include "common/config/version_converter.h"
#include "common/init/manager_impl.h"
#include "common/init/watcher_impl.h"
#include "common/router/rds_impl.h"

#include "absl/strings/str_join.h"

// Types are deeply nested under Envoy::Config::ConfigProvider; use 'using-directives' across all
// ConfigProvider related types for consistency.
using Envoy::Config::ConfigProvider;
using Envoy::Config::ConfigProviderInstanceType;
using Envoy::Config::ConfigProviderManager;
using Envoy::Config::ConfigProviderPtr;

namespace Envoy {
namespace Router {
namespace ScopedRoutesConfigProviderUtil {
ConfigProviderPtr create(
    const envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
        config,
    Server::Configuration::ServerFactoryContext& factory_context, Init::Manager& init_manager,
    const std::string& stat_prefix, ConfigProviderManager& scoped_routes_config_provider_manager) {
  ASSERT(config.route_specifier_case() ==
         envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::
             RouteSpecifierCase::kScopedRoutes);

  switch (config.scoped_routes().config_specifier_case()) {
  case envoy::extensions::filters::network::http_connection_manager::v3::ScopedRoutes::
      ConfigSpecifierCase::kScopedRouteConfigurationsList: {
    const envoy::extensions::filters::network::http_connection_manager::v3::
        ScopedRouteConfigurationsList& scoped_route_list =
            config.scoped_routes().scoped_route_configurations_list();
    return scoped_routes_config_provider_manager.createStaticConfigProvider(
        RepeatedPtrUtil::convertToConstMessagePtrContainer<
            envoy::config::route::v3::ScopedRouteConfiguration,
            ProtobufTypes::ConstMessagePtrVector>(scoped_route_list.scoped_route_configurations()),
        factory_context,
        ScopedRoutesConfigProviderManagerOptArg(config.scoped_routes().name(),
                                                config.scoped_routes().rds_config_source(),
                                                config.scoped_routes().scope_key_builder()));
  }
  case envoy::extensions::filters::network::http_connection_manager::v3::ScopedRoutes::
      ConfigSpecifierCase::kScopedRds:
    return scoped_routes_config_provider_manager.createXdsConfigProvider(
        config.scoped_routes().scoped_rds(), factory_context, init_manager, stat_prefix,
        ScopedRoutesConfigProviderManagerOptArg(config.scoped_routes().name(),
                                                config.scoped_routes().rds_config_source(),
                                                config.scoped_routes().scope_key_builder()));
  default:
    // Proto validation enforces that is not reached.
    NOT_REACHED_GCOVR_EXCL_LINE;
  }
}

} // namespace ScopedRoutesConfigProviderUtil

InlineScopedRoutesConfigProvider::InlineScopedRoutesConfigProvider(
    ProtobufTypes::ConstMessagePtrVector&& config_protos, std::string name,
    Server::Configuration::ServerFactoryContext& factory_context,
    ScopedRoutesConfigProviderManager& config_provider_manager,
    envoy::config::core::v3::ConfigSource rds_config_source,
    envoy::extensions::filters::network::http_connection_manager::v3::ScopedRoutes::ScopeKeyBuilder
        scope_key_builder)
    : Envoy::Config::ImmutableConfigProviderBase(factory_context, config_provider_manager,
                                                 ConfigProviderInstanceType::Inline,
                                                 ConfigProvider::ApiType::Delta),
      name_(std::move(name)),
      config_(std::make_shared<ScopedConfigImpl>(std::move(scope_key_builder))),
      config_protos_(std::make_move_iterator(config_protos.begin()),
                     std::make_move_iterator(config_protos.end())),
      rds_config_source_(std::move(rds_config_source)) {}

ScopedRdsConfigSubscription::ScopedRdsConfigSubscription(
    const envoy::extensions::filters::network::http_connection_manager::v3::ScopedRds& scoped_rds,
    const uint64_t manager_identifier, const std::string& name,
    const envoy::extensions::filters::network::http_connection_manager::v3::ScopedRoutes::
        ScopeKeyBuilder& scope_key_builder,
    Server::Configuration::ServerFactoryContext& factory_context, const std::string& stat_prefix,
    envoy::config::core::v3::ConfigSource rds_config_source,
    RouteConfigProviderManager& route_config_provider_manager,
    ScopedRoutesConfigProviderManager& config_provider_manager)
    : DeltaConfigSubscriptionInstance("SRDS", manager_identifier, config_provider_manager,
                                      factory_context),
      Envoy::Config::SubscriptionBase<envoy::config::route::v3::ScopedRouteConfiguration>(
          rds_config_source.resource_api_version()),
      factory_context_(factory_context), name_(name), scope_key_builder_(scope_key_builder),
      scope_(factory_context.scope().createScope(stat_prefix + "scoped_rds." + name + ".")),
      stats_({ALL_SCOPED_RDS_STATS(POOL_COUNTER(*scope_))}),
      rds_config_source_(std::move(rds_config_source)),
      validation_visitor_(factory_context.messageValidationContext().dynamicValidationVisitor()),
      stat_prefix_(stat_prefix), route_config_provider_manager_(route_config_provider_manager) {
  const auto resource_name = getResourceName();
  subscription_ =
      factory_context.clusterManager().subscriptionFactory().subscriptionFromConfigSource(
          scoped_rds.scoped_rds_config_source(), Grpc::Common::typeUrl(resource_name), *scope_,
          *this);

  initialize([scope_key_builder]() -> Envoy::Config::ConfigProvider::ConfigConstSharedPtr {
    return std::make_shared<ScopedConfigImpl>(
        envoy::extensions::filters::network::http_connection_manager::v3::ScopedRoutes::
            ScopeKeyBuilder(scope_key_builder));
  });
}

ScopedRdsConfigSubscription::RdsRouteConfigProviderHelper::RdsRouteConfigProviderHelper(
    ScopedRdsConfigSubscription& parent, std::string scope_name,
    envoy::extensions::filters::network::http_connection_manager::v3::Rds& rds,
    Init::Manager& init_manager)
    : parent_(parent), scope_name_(scope_name),
      route_provider_(std::dynamic_pointer_cast<RdsRouteConfigProviderImpl>(
          parent_.route_config_provider_manager_.createRdsRouteConfigProvider(
              rds, parent_.factory_context_, parent_.stat_prefix_, init_manager))),

      rds_update_callback_handle_(route_provider_->subscription().addUpdateCallback([this]() {
        // Subscribe to RDS update.
        parent_.onRdsConfigUpdate(scope_name_, route_provider_->subscription());
      })) {}

bool ScopedRdsConfigSubscription::addOrUpdateScopes(
    const Protobuf::RepeatedPtrField<envoy::service::discovery::v3::Resource>& resources,
    Init::Manager& init_manager, const std::string& version_info,
    std::vector<std::string>& exception_msgs) {
  bool any_applied = false;
  envoy::extensions::filters::network::http_connection_manager::v3::Rds rds;
  rds.mutable_config_source()->MergeFrom(rds_config_source_);
  absl::flat_hash_set<std::string> unique_resource_names;
  for (const auto& resource : resources) {
    envoy::config::route::v3::ScopedRouteConfiguration scoped_route_config;
    try {
      scoped_route_config =
          MessageUtil::anyConvertAndValidate<envoy::config::route::v3::ScopedRouteConfiguration>(
              resource.resource(), validation_visitor_);
      const std::string scope_name = scoped_route_config.name();
      if (!unique_resource_names.insert(scope_name).second) {
        throw EnvoyException(
            fmt::format("duplicate scoped route configuration '{}' found", scope_name));
      }
      // TODO(stevenzzz): Creating a new RdsRouteConfigProvider likely expensive, migrate RDS to
      // config-provider-framework to make it light weight.
      rds.set_route_config_name(scoped_route_config.route_configuration_name());
      auto rds_config_provider_helper =
          std::make_unique<RdsRouteConfigProviderHelper>(*this, scope_name, rds, init_manager);
      auto scoped_route_info = std::make_shared<ScopedRouteInfo>(
          std::move(scoped_route_config), rds_config_provider_helper->routeConfig());
      // Detect if there is key conflict between two scopes, in which case Envoy won't be able to
      // tell which RouteConfiguration to use. Reject the second scope in the delta form API.
      auto iter = scope_name_by_hash_.find(scoped_route_info->scopeKey().hash());
      if (iter != scope_name_by_hash_.end()) {
        if (iter->second != scoped_route_info->scopeName()) {
          throw EnvoyException(
              fmt::format("scope key conflict found, first scope is '{}', second scope is '{}'",
                          iter->second, scoped_route_info->scopeName()));
        }
      }
      // NOTE: delete previous route provider if any.
      route_provider_by_scope_.insert({scope_name, std::move(rds_config_provider_helper)});
      scope_name_by_hash_[scoped_route_info->scopeKey().hash()] = scoped_route_info->scopeName();
      scoped_route_map_[scoped_route_info->scopeName()] = scoped_route_info;
      applyConfigUpdate([scoped_route_info](ConfigProvider::ConfigConstSharedPtr config)
                            -> ConfigProvider::ConfigConstSharedPtr {
        auto* thread_local_scoped_config =
            const_cast<ScopedConfigImpl*>(static_cast<const ScopedConfigImpl*>(config.get()));
        thread_local_scoped_config->addOrUpdateRoutingScope(scoped_route_info);
        return config;
      });
      any_applied = true;
      ENVOY_LOG(debug, "srds: add/update scoped_route '{}', version: {}",
                scoped_route_info->scopeName(), version_info);
    } catch (const EnvoyException& e) {
      exception_msgs.emplace_back(absl::StrCat("", e.what()));
    }
  }
  return any_applied;
}

std::list<std::unique_ptr<ScopedRdsConfigSubscription::RdsRouteConfigProviderHelper>>
ScopedRdsConfigSubscription::removeScopes(
    const Protobuf::RepeatedPtrField<std::string>& scope_names, const std::string& version_info) {
  std::list<std::unique_ptr<ScopedRdsConfigSubscription::RdsRouteConfigProviderHelper>>
      to_be_removed_rds_providers;
  for (const auto& scope_name : scope_names) {
    auto iter = scoped_route_map_.find(scope_name);
    if (iter != scoped_route_map_.end()) {
      auto rds_config_provider_helper_iter = route_provider_by_scope_.find(scope_name);
      if (rds_config_provider_helper_iter != route_provider_by_scope_.end()) {
        to_be_removed_rds_providers.emplace_back(
            std::move(rds_config_provider_helper_iter->second));
        route_provider_by_scope_.erase(rds_config_provider_helper_iter);
      }
      scope_name_by_hash_.erase(iter->second->scopeKey().hash());
      scoped_route_map_.erase(iter);
      applyConfigUpdate([scope_name](ConfigProvider::ConfigConstSharedPtr config)
                            -> ConfigProvider::ConfigConstSharedPtr {
        auto* thread_local_scoped_config =
            const_cast<ScopedConfigImpl*>(static_cast<const ScopedConfigImpl*>(config.get()));
        thread_local_scoped_config->removeRoutingScope(scope_name);
        return config;
      });
      ENVOY_LOG(debug, "srds: remove scoped route '{}', version: {}", scope_name, version_info);
    }
  }
  return to_be_removed_rds_providers;
}

void ScopedRdsConfigSubscription::onConfigUpdate(
    const Protobuf::RepeatedPtrField<envoy::service::discovery::v3::Resource>& added_resources,
    const Protobuf::RepeatedPtrField<std::string>& removed_resources,
    const std::string& version_info) {
  // NOTE: deletes are done before adds/updates.

  absl::flat_hash_map<std::string, ScopedRouteInfoConstSharedPtr> to_be_removed_scopes;
  // If new route config sources come after the local init manager's initialize() been
  // called, the init manager can't accept new targets. Instead we use a local override which will
  // start new subscriptions but not wait on them to be ready.
  std::unique_ptr<Init::ManagerImpl> noop_init_manager;
  // NOTE: This should be defined after noop_init_manager as it depends on the
  // noop_init_manager.
  std::unique_ptr<Cleanup> resume_rds;
  // if local init manager is initialized, the parent init manager may have gone away.
  if (localInitManager().state() == Init::Manager::State::Initialized) {
    noop_init_manager =
        std::make_unique<Init::ManagerImpl>(fmt::format("SRDS {}:{}", name_, version_info));
    // Pause RDS to not send a burst of RDS requests until we start all the new subscriptions.
    // In the case if factory_context_.init_manager() is uninitialized, RDS is already paused
    // either by Server init or LDS init.
    if (factory_context_.clusterManager().adsMux()) {
      factory_context_.clusterManager().adsMux()->pause(
          Envoy::Config::TypeUrl::get().RouteConfiguration);
    }
    resume_rds = std::make_unique<Cleanup>([this, &noop_init_manager, version_info] {
      // For new RDS subscriptions created after listener warming up, we don't wait for them to
      // warm up.
      Init::WatcherImpl noop_watcher(
          // Note: we just throw it away.
          fmt::format("SRDS ConfigUpdate watcher {}:{}", name_, version_info),
          []() { /*Do nothing.*/ });
      noop_init_manager->initialize(noop_watcher);
      // New RDS subscriptions should have been created, now lift the floodgate.
      // Note in the case of partial acceptance, accepted RDS subscriptions should be started
      // despite of any error.
      if (factory_context_.clusterManager().adsMux()) {
        factory_context_.clusterManager().adsMux()->resume(
            Envoy::Config::TypeUrl::get().RouteConfiguration);
      }
    });
  }

  std::vector<std::string> exception_msgs;
  // Do not delete RDS config providers just yet, in case the to be deleted RDS subscriptions could
  // be reused by some to be added scopes.
  std::list<std::unique_ptr<ScopedRdsConfigSubscription::RdsRouteConfigProviderHelper>>
      to_be_removed_rds_providers = removeScopes(removed_resources, version_info);
  bool any_applied =
      addOrUpdateScopes(added_resources,
                        (noop_init_manager == nullptr ? localInitManager() : *noop_init_manager),
                        version_info, exception_msgs) ||
      !to_be_removed_rds_providers.empty();
  ConfigSubscriptionCommonBase::onConfigUpdate();
  if (any_applied) {
    setLastConfigInfo(absl::optional<LastConfigInfo>({absl::nullopt, version_info}));
  }
  stats_.config_reload_.inc();
  if (!exception_msgs.empty()) {
    throw EnvoyException(fmt::format("Error adding/updating scoped route(s): {}",
                                     absl::StrJoin(exception_msgs, ", ")));
  }
}

void ScopedRdsConfigSubscription::onRdsConfigUpdate(const std::string& scope_name,
                                                    RdsRouteConfigSubscription& rds_subscription) {
  auto iter = scoped_route_map_.find(scope_name);
  ASSERT(iter != scoped_route_map_.end(),
         fmt::format("trying to update route config for non-existing scope {}", scope_name));
  auto new_scoped_route_info = std::make_shared<ScopedRouteInfo>(
      envoy::config::route::v3::ScopedRouteConfiguration(iter->second->configProto()),
      std::make_shared<ConfigImpl>(
          rds_subscription.routeConfigUpdate()->routeConfiguration(), factory_context_,
          factory_context_.messageValidationContext().dynamicValidationVisitor(), false));
  applyConfigUpdate([new_scoped_route_info](ConfigProvider::ConfigConstSharedPtr config)
                        -> ConfigProvider::ConfigConstSharedPtr {
    auto* thread_local_scoped_config =
        const_cast<ScopedConfigImpl*>(static_cast<const ScopedConfigImpl*>(config.get()));
    thread_local_scoped_config->addOrUpdateRoutingScope(new_scoped_route_info);
    return config;
  });
}

// TODO(stevenzzzz): see issue #7508, consider generalizing this function as it overlaps with
// CdsApiImpl::onConfigUpdate.
void ScopedRdsConfigSubscription::onConfigUpdate(
    const Protobuf::RepeatedPtrField<ProtobufWkt::Any>& resources,
    const std::string& version_info) {
  absl::flat_hash_map<std::string, envoy::config::route::v3::ScopedRouteConfiguration>
      scoped_routes;
  absl::flat_hash_map<uint64_t, std::string> scope_name_by_key_hash;
  for (const auto& resource_any : resources) {
    // Throws (thus rejects all) on any error.
    auto scoped_route =
        MessageUtil::anyConvertAndValidate<envoy::config::route::v3::ScopedRouteConfiguration>(
            resource_any, validation_visitor_);
    const std::string scope_name = scoped_route.name();
    auto scope_config_inserted = scoped_routes.try_emplace(scope_name, std::move(scoped_route));
    if (!scope_config_inserted.second) {
      throw EnvoyException(
          fmt::format("duplicate scoped route configuration '{}' found", scope_name));
    }
    const envoy::config::route::v3::ScopedRouteConfiguration& scoped_route_config =
        scope_config_inserted.first->second;
    const uint64_t key_fingerprint = MessageUtil::hash(scoped_route_config.key());
    if (!scope_name_by_key_hash.try_emplace(key_fingerprint, scope_name).second) {
      throw EnvoyException(
          fmt::format("scope key conflict found, first scope is '{}', second scope is '{}'",
                      scope_name_by_key_hash[key_fingerprint], scope_name));
    }
  }
  ScopedRouteMap scoped_routes_to_remove = scoped_route_map_;
  Protobuf::RepeatedPtrField<envoy::service::discovery::v3::Resource> to_add_repeated;
  Protobuf::RepeatedPtrField<std::string> to_remove_repeated;
  for (auto& iter : scoped_routes) {
    const std::string& scope_name = iter.first;
    scoped_routes_to_remove.erase(scope_name);
    auto* to_add = to_add_repeated.Add();
    to_add->set_name(scope_name);
    to_add->set_version(version_info);
    to_add->mutable_resource()->PackFrom(iter.second);
  }

  for (const auto& scoped_route : scoped_routes_to_remove) {
    *to_remove_repeated.Add() = scoped_route.first;
  }
  onConfigUpdate(to_add_repeated, to_remove_repeated, version_info);
}

ScopedRdsConfigProvider::ScopedRdsConfigProvider(
    ScopedRdsConfigSubscriptionSharedPtr&& subscription)
    : MutableConfigProviderCommonBase(std::move(subscription), ConfigProvider::ApiType::Delta) {}

ProtobufTypes::MessagePtr ScopedRoutesConfigProviderManager::dumpConfigs() const {
  auto config_dump = std::make_unique<envoy::admin::v3::ScopedRoutesConfigDump>();
  for (const auto& element : configSubscriptions()) {
    auto subscription = element.second.lock();
    ASSERT(subscription);

    if (subscription->configInfo()) {
      auto* dynamic_config = config_dump->mutable_dynamic_scoped_route_configs()->Add();
      dynamic_config->set_version_info(subscription->configInfo().value().last_config_version_);
      const ScopedRdsConfigSubscription* typed_subscription =
          static_cast<ScopedRdsConfigSubscription*>(subscription.get());
      dynamic_config->set_name(typed_subscription->name());
      const ScopedRouteMap& scoped_route_map = typed_subscription->scopedRouteMap();
      for (const auto& it : scoped_route_map) {
        dynamic_config->mutable_scoped_route_configs()->Add()->PackFrom(
            API_RECOVER_ORIGINAL(it.second->configProto()));
      }
      TimestampUtil::systemClockToTimestamp(subscription->lastUpdated(),
                                            *dynamic_config->mutable_last_updated());
    }
  }

  for (const auto& provider : immutableConfigProviders(ConfigProviderInstanceType::Inline)) {
    const auto protos_info =
        provider->configProtoInfoVector<envoy::config::route::v3::ScopedRouteConfiguration>();
    ASSERT(protos_info != absl::nullopt);
    auto* inline_config = config_dump->mutable_inline_scoped_route_configs()->Add();
    inline_config->set_name(static_cast<InlineScopedRoutesConfigProvider*>(provider)->name());
    for (const auto& config_proto : protos_info.value().config_protos_) {
      inline_config->mutable_scoped_route_configs()->Add()->PackFrom(
          API_RECOVER_ORIGINAL(*config_proto));
    }
    TimestampUtil::systemClockToTimestamp(provider->lastUpdated(),
                                          *inline_config->mutable_last_updated());
  }

  return config_dump;
}

ConfigProviderPtr ScopedRoutesConfigProviderManager::createXdsConfigProvider(
    const Protobuf::Message& config_source_proto,
    Server::Configuration::ServerFactoryContext& factory_context, Init::Manager& init_manager,
    const std::string& stat_prefix, const ConfigProviderManager::OptionalArg& optarg) {
  const auto& typed_optarg = static_cast<const ScopedRoutesConfigProviderManagerOptArg&>(optarg);
  ScopedRdsConfigSubscriptionSharedPtr subscription =
      ConfigProviderManagerImplBase::getSubscription<ScopedRdsConfigSubscription>(
          config_source_proto, init_manager,
          [&config_source_proto, &factory_context, &stat_prefix,
           &typed_optarg](const uint64_t manager_identifier,
                          ConfigProviderManagerImplBase& config_provider_manager)
              -> Envoy::Config::ConfigSubscriptionCommonBaseSharedPtr {
            const auto& scoped_rds_config_source = dynamic_cast<
                const envoy::extensions::filters::network::http_connection_manager::v3::ScopedRds&>(
                config_source_proto);
            return std::make_shared<ScopedRdsConfigSubscription>(
                scoped_rds_config_source, manager_identifier, typed_optarg.scoped_routes_name_,
                typed_optarg.scope_key_builder_, factory_context, stat_prefix,
                typed_optarg.rds_config_source_,
                static_cast<ScopedRoutesConfigProviderManager&>(config_provider_manager)
                    .route_config_provider_manager(),
                static_cast<ScopedRoutesConfigProviderManager&>(config_provider_manager));
          });

  return std::make_unique<ScopedRdsConfigProvider>(std::move(subscription));
}

ConfigProviderPtr ScopedRoutesConfigProviderManager::createStaticConfigProvider(
    ProtobufTypes::ConstMessagePtrVector&& config_protos,
    Server::Configuration::ServerFactoryContext& factory_context,
    const ConfigProviderManager::OptionalArg& optarg) {
  const auto& typed_optarg = static_cast<const ScopedRoutesConfigProviderManagerOptArg&>(optarg);
  return std::make_unique<InlineScopedRoutesConfigProvider>(
      std::move(config_protos), typed_optarg.scoped_routes_name_, factory_context, *this,
      typed_optarg.rds_config_source_, typed_optarg.scope_key_builder_);
}

} // namespace Router
} // namespace Envoy


text:
wercker-box-ubuntu12.04-chef11.4.4
==================================

A wercker box based on Ubuntu 12.04 with Chef 11.4.4 installed.  This is the version of Chef used by AWS Opsworks.

Contributors
============
- [Adam Woods](https://github.com/woodsae) (<adam@woodsae.com>)
- [Enrico Stahn](https://github.com/estahn) (<mail@enricostahn.com>)


text:
package de.tum.p2p.onion.forwarding.netty.handler;

import de.tum.p2p.onion.forwarding.TunnelId;
import de.tum.p2p.onion.forwarding.netty.channel.ClientChannelFactory;
import de.tum.p2p.onion.forwarding.netty.context.RoutingContext;
import de.tum.p2p.proto.message.onion.forwarding.TunnelExtendMessage;
import de.tum.p2p.proto.message.onion.forwarding.composite.TunnelConnect;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.tuple.Pair;

/**
 * {@code TunnelConnectHandler} receives {@link TunnelConnect} payloads revealed
 * from {@code TunnelRelayMessage}, create a {@link TunnelExtendMessage}, connect
 * to the peer to be a new member of the tunnel and forwards the extend request.
 *
 * @author Illia Ovchynnikov <illia.ovchynnikov@gmail.com>
 */
@Slf4j
public class TunnelConnectHandler extends SimpleChannelInboundHandler<Pair<TunnelId, TunnelConnect>> {

    private final RoutingContext routingContext;
    private final ClientChannelFactory clientChannelFactory;

    public TunnelConnectHandler(RoutingContext routingContext, ClientChannelFactory clientChannelFactory) {
        this.routingContext = routingContext;
        this.clientChannelFactory = clientChannelFactory;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Pair<TunnelId, TunnelConnect> tunnelIdConnect)
            throws Exception {
        val tunnelId = tunnelIdConnect.getLeft();
        val connect = tunnelIdConnect.getRight();

        clientChannelFactory.connect(connect.socketDestination()).thenAccept(channel -> {
            routingContext.setNextHop(tunnelId, channel);

            val extendMsg = new TunnelExtendMessage(tunnelId, connect.requestId(),
                connect.sourceKey(), connect.handshake());

            channel.writeAndFlush(extendMsg);
            log.debug("ONION_TUNNEL_EXTEND confirmation with HS has been sent via tunnel {} from {} to {}",
                tunnelId, ctx.channel().localAddress(), ctx.channel().remoteAddress());
        });
    }
}


text:
package org.apache.uima.tools;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.analysis_engine.TypeOrFeature;
import org.apache.uima.analysis_engine.metadata.AnalysisEngineMetaData;
import org.apache.uima.resource.metadata.Capability;

/**
 * A tree view of Annotations and associated features.
 *
 */
public class AnnotationFeaturesViewer extends JPanel implements ActionListener {

  /** The Constant serialVersionUID. */
  private static final long serialVersionUID = -8028169177689821008L;

  /** The Constant ROOT. */
  public static final String ROOT = "Root";

  /** The scroll pane. */
  private JScrollPane scrollPane;

  /** The tree. */
  private JTree tree;

  /** The expand all button. */
  private JButton expandAllButton;

  /** The collapse all button. */
  private JButton collapseAllButton;

  /**
   * Instantiates a new annotation features viewer.
   */
  public AnnotationFeaturesViewer() {

    setLayout(new BorderLayout());

    scrollPane = new JScrollPane();
    // We'll add a tree to this later through a call to populate.

    add(scrollPane, BorderLayout.CENTER);

    JPanel buttonsPanel = new JPanel();

    expandAllButton = new JButton("Expand All");
    expandAllButton.setToolTipText("Expand all tree nodes");
    expandAllButton.addActionListener(this);
    buttonsPanel.add(expandAllButton);

    collapseAllButton = new JButton("Collapse All");
    collapseAllButton.setToolTipText("Collapse all tree nodes");
    collapseAllButton.addActionListener(this);
    buttonsPanel.add(collapseAllButton);

    add(buttonsPanel, BorderLayout.NORTH);
  }

  /**
   * Populate.
   *
   * @param analysisEngine
   *          the analysis engine
   * @param aeMetaData
   *          the ae meta data
   */
  public void populate(AnalysisEngine analysisEngine, AnalysisEngineMetaData aeMetaData) {
    tree = generateTreeView(analysisEngine, aeMetaData);

    tree.setDragEnabled(true); // To allow drag to stylemap table.
    tree.setRootVisible(false);
    tree.setShowsRootHandles(true); // Displays node expansion glyphs.

    TreeSelectionModel selectionModel = tree.getSelectionModel();
    selectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

    DefaultTreeCellRenderer cellRenderer = new DefaultTreeCellRenderer();
    cellRenderer.setLeafIcon(null);
    cellRenderer.setClosedIcon(null);
    cellRenderer.setOpenIcon(null);
    tree.setCellRenderer(cellRenderer);

    scrollPane.getViewport().add(tree, null);
  }

  /**
   * Generate tree view.
   *
   * @param analysisEngine
   *          the analysis engine
   * @param aeMetaData
   *          the ae meta data
   * @return the j tree
   */
  private JTree generateTreeView(AnalysisEngine analysisEngine, AnalysisEngineMetaData aeMetaData) {

    DefaultMutableTreeNode root = new DefaultMutableTreeNode(ROOT);
    // We won't actually see this.

    ArrayList annotationTypes = new ArrayList();
    Capability[] capabilities = aeMetaData.getCapabilities();
    for (int i = 0; i < capabilities.length; i++) {
      TypeOrFeature[] outputs = capabilities[i].getOutputs();

      for (int j = 0; j < outputs.length; j++) {
        if (outputs[j].isType() && !annotationTypes.contains(outputs[j].getName())) {
          annotationTypes.add(outputs[j].getName());
        }
      }
    }

    Iterator it = annotationTypes.iterator();
    while (it.hasNext()) {
      String annotationTypeName = (String) it.next();

      DefaultMutableTreeNode annotationTreeNode = new DefaultMutableTreeNode(annotationTypeName);
      String[] featureNames = analysisEngine.getFeatureNamesForType(annotationTypeName);

      for (int i = 0; i < featureNames.length; i++) {
        DefaultMutableTreeNode featureTreeNode = new DefaultMutableTreeNode(featureNames[i]);
        annotationTreeNode.add(featureTreeNode);
      }

      root.add(annotationTreeNode);
    }

    return new JTree(root);
  }

  /**
   * Gets the selection.
   *
   * @return the selection
   */
  public String getSelection() {
    TreePath treePath = tree.getSelectionPath();
    if (treePath != null) {
      String parentPath = treePath.getParentPath().getLastPathComponent().toString();
      String lastPath = treePath.getLastPathComponent().toString();
      if (parentPath.equals(AnnotationFeaturesViewer.ROOT))
        return lastPath;
      else
        return parentPath + ":" + lastPath;
    } else
      return null;
  }

  /*
   * (non-Javadoc)
   *
   * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
   */
  @Override
  public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    if (source == expandAllButton) {
      for (int i = 0; i < tree.getRowCount(); i++)
        tree.expandRow(i);
    } else if (source == collapseAllButton) {
      for (int i = 0; i < tree.getRowCount(); i++)
        tree.collapseRow(i);
    }
  }
}


text:
<?php

OCP\JSON::checkLoggedIn();
OCP\JSON::callCheck();
$folder = isset($_POST['dir']) ? $_POST['dir'] : '/';

// "empty trash" command
if (isset($_POST['allfiles']) and $_POST['allfiles'] === 'true'){
	$deleteAll = true;
	if ($folder === '/' || $folder === '') {
		OCA\Files_Trashbin\Trashbin::deleteAll();
		$list = array();
	} else {
		$list[] = $folder;
		$folder = dirname($folder);
	}
}
else {
	$deleteAll = false;
	$files = $_POST['files'];
	$list = json_decode($files);
}

$folder = rtrim($folder, '/') . '/';
$error = array();
$success = array();

$i = 0;
foreach ($list as $file) {
	if ($folder === '/') {
		$file = ltrim($file, '/');
		$delimiter = strrpos($file, '.d');
		$filename = substr($file, 0, $delimiter);
		$timestamp =  substr($file, $delimiter+2);
	} else {
		$filename = $folder . '/' . $file;
		$timestamp = null;
	}

	OCA\Files_Trashbin\Trashbin::delete($filename, \OCP\User::getUser(), $timestamp);
	if (OCA\Files_Trashbin\Trashbin::file_exists($filename, $timestamp)) {
		$error[] = $filename;
		OC_Log::write('trashbin','can\'t delete ' . $filename . ' permanently.', OC_Log::ERROR);
	}
	// only list deleted files if not deleting everything
	else if (!$deleteAll) {
		$success[$i]['filename'] = $file;
		$success[$i]['timestamp'] = $timestamp;
		$i++;
	}
}

if ( $error ) {
	$filelist = '';
	foreach ( $error as $e ) {
		$filelist .= $e.', ';
	}
	$l = OC_L10N::get('files_trashbin');
	$message = $l->t("Couldn't delete %s permanently", array(rtrim($filelist, ', ')));
	OCP\JSON::error(array("data" => array("message" => $message,
			                               "success" => $success, "error" => $error)));
} else {
	OCP\JSON::success(array("data" => array("success" => $success)));
}


text:
package se.jonas.xml.locator.data.source.writer.impl;

import java.io.File;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import se.jonas.xml.locator.data.source.domain.Domain;
import se.jonas.xml.locator.data.source.utilities.ServiceUtilities;

public class AbstractWriterImpl<
	T extends Domain> {

	public void writeXml(Class<T> aClass, T result, File file)
			throws JAXBException {
		if (result.getCreated() == null) {
			result.setCreated(new Date());
		}

		result.setUpdated(new Date());

		JAXBContext context = JAXBContext.newInstance(aClass);
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_ENCODING,
				ServiceUtilities.DEFAULT_ENCODING_UTF_8);
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		marshaller.marshal(result, file);
	}

	@SuppressWarnings({ "unchecked" })
	public T readXml(Class<T> aClass, File file) throws JAXBException {
		JAXBContext newInstance = JAXBContext.newInstance(aClass);
		return (T) newInstance.createUnmarshaller().unmarshal(file);
	}

	public String getApplicationHomeDir(String applicationHomeDir) {
		return ServiceUtilities.getApplicationHomeDir(applicationHomeDir);
	}

	public String getSystemUserHome() {
		return ServiceUtilities.getSystemUserHome();
	}
}


text:
<?php

require __DIR__ . '/../vendor/autoload.php';

use Clue\React\Packagist\Api\Client;
use Packagist\Api\Result\Package;
use Clue\React\Buzz\Browser;

$loop = React\EventLoop\Factory::create();
$browser = new Browser($loop);
$client = new Client($browser);

$client->search('packagist')->then(function ($result) {
    var_dump('found ' . count($result) . ' packages matching "packagist"');
    //var_dump($result);
}, function ($error) {
    echo $e;
});

$client->get('clue/phar-composer')->then(function (Package $package) {
    var_dump($package->getName(), $package->getDescription());
});

$client->get('clue/graph')->then(function (Package $package) {
    var_dump($package->getName(), $package->getDescription());
});

$loop->run();


text:
#ifndef QTESTCOREELEMENT_P_H
#define QTESTCOREELEMENT_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <QtTest/private/qtestcorelist_p.h>
#include <QtTest/private/qtestelementattribute_p.h>

QT_BEGIN_NAMESPACE

template <class ElementType>
class QTestCoreElement: public QTestCoreList<ElementType>
{
    public:
        QTestCoreElement( int type = -1 );
        virtual ~QTestCoreElement();

        void addAttribute(const QTest::AttributeIndex index, const char *value);
        QTestElementAttribute *attributes() const;
        const char *attributeValue(QTest::AttributeIndex index) const;
        const char *attributeName(QTest::AttributeIndex index) const;
        const QTestElementAttribute *attribute(QTest::AttributeIndex index) const;

        const char *elementName() const;
        QTest::LogElementType elementType() const;

    private:
        QTestElementAttribute *listOfAttributes;
        QTest::LogElementType type;
};

template<class ElementType>
QTestCoreElement<ElementType>::QTestCoreElement(int t)
    :listOfAttributes(0), type(QTest::LogElementType(t))
{
}

template<class ElementType>
QTestCoreElement<ElementType>::~QTestCoreElement()
{
    delete listOfAttributes;
}

template <class ElementType>
void QTestCoreElement<ElementType>::addAttribute(const QTest::AttributeIndex attributeIndex, const char *value)
{
    if (attributeIndex == -1 || attribute(attributeIndex))
        return;

    QTestElementAttribute *testAttribute = new QTestElementAttribute;
    testAttribute->setPair(attributeIndex, value);
    testAttribute->addToList(&listOfAttributes);
}

template <class ElementType>
QTestElementAttribute *QTestCoreElement<ElementType>::attributes() const
{
    return listOfAttributes;
}

template <class ElementType>
const char *QTestCoreElement<ElementType>::attributeValue(QTest::AttributeIndex index) const
{
    const QTestElementAttribute *attrb = attribute(index);
    if (attrb)
        return attrb->value();

    return 0;
}

template <class ElementType>
const char *QTestCoreElement<ElementType>::attributeName(QTest::AttributeIndex index) const
{
    const QTestElementAttribute *attrb = attribute(index);
    if (attrb)
        return attrb->name();

    return 0;
}

template <class ElementType>
const char *QTestCoreElement<ElementType>::elementName() const
{
    const char *xmlElementNames[] =
    {
        "property",
        "properties",
        "failure",
        "error",
        "testcase",
        "testsuite",
        "benchmark",
        "system-err"
    };

    if (type != QTest::LET_Undefined)
        return xmlElementNames[type];

    return 0;
}

template <class ElementType>
QTest::LogElementType QTestCoreElement<ElementType>::elementType() const
{
    return type;
}

template <class ElementType>
const QTestElementAttribute *QTestCoreElement<ElementType>::attribute(QTest::AttributeIndex index) const
{
    QTestElementAttribute *iterator = listOfAttributes;
    while (iterator) {
        if (iterator->index() == index)
            return iterator;

        iterator = iterator->nextElement();
    }

    return 0;
}

QT_END_NAMESPACE

#endif


text:
title: Segment · Blog
date: 2017-10-16 00:00:00 +0000
related_tools:
- tool/gatsby.md
website: https://segment.com/blog/
repo: ''
creator:
- name:
  role:
  url:
  twitter_username:
images:
- "/uploads/showcase-segment-blog.png"

---
Segment, authors of metalsmith relaunched their blog on Gatsby.


text:
/* jshint node: true */
'use strict';
var fs = require('fs');
var recast = require('recast');
var b = recast.types.builders;

function addToLaunchers(testemJS, listName, launcherName) {
  var list;

  recast.visit(testemJS, {
    // Compare identifiers with a new name to ensure it's unique
    visitProperty: function(path) {
      var key = path.value.key;
      if ((key.type === 'Identifier' && key.name === listName) ||
        (key.type === 'Literal' && key.value === listName)) {
        list = path;
        this.abort();
      }
      return false;
    }
  });

  list.value.value.elements.push(b.literal(launcherName));
}

module.exports = function(fullPath, launcherName, launcher, options) {
  var ast = recast.parse(fs.readFileSync(fullPath, { encoding: 'utf8' }));

  var testemJS = ast.program.body[0];

  var property = null;

  recast.visit(testemJS, {
    // Compare identifiers with a new name to ensure it's unique
    visitProperty: function(path) {
      var key = path.value.key;
      if ((key.type === 'Identifier' && key.name === 'launchers') ||
        (key.type === 'Literal' && key.value === 'launchers')) {
        property = path;
        this.abort();
      }
      return false;
    }
  });

  // TODO Find a better way
  var launcherPattern = recast.parse('a = ' + JSON.stringify(launcher, null, 2))
    .program.body[0].expression.right;
  var launcherProperty = b.property('init', b.identifier(launcherName), launcherPattern);

  if (property) {
    property.value.value.properties.push(launcherProperty);
  } else {
    testemJS.expression.right.properties.push(
      b.property('init', b.identifier('launchers'), b.objectPattern([launcherProperty])
    ));
  }

  if (options.addToCi) {
    addToLaunchers(testemJS, 'launch_in_ci', launcherName);
  }

  if (options.addToDev) {
    addToLaunchers(testemJS, 'launch_in_dev', launcherName);
  }

  fs.writeFileSync(fullPath, recast.print(ast).code, { encoding: 'utf8' });
};


text:
#include "slg/materials/roughmatte.h"

using namespace std;
using namespace luxrays;
using namespace slg;

//------------------------------------------------------------------------------
// Rough matte material
//------------------------------------------------------------------------------

Spectrum RoughMatteMaterial::Evaluate(const HitPoint &hitPoint,
	const Vector &localLightDir, const Vector &localEyeDir, BSDFEvent *event,
	float *directPdfW, float *reversePdfW) const {
	if (directPdfW)
		*directPdfW = fabsf((hitPoint.fromLight ? localEyeDir.z : localLightDir.z) * INV_PI);

	if (reversePdfW)
		*reversePdfW = fabsf((hitPoint.fromLight ? localLightDir.z : localEyeDir.z) * INV_PI);

	*event = DIFFUSE | REFLECT;
	const float s = sigma->GetFloatValue(hitPoint);
	const float sigma2 = s * s;
	const float A = 1.f - (sigma2 / (2.f * (sigma2 + 0.33f)));
	const float B = 0.45f * sigma2 / (sigma2 + 0.09f);
	const float sinthetai = SinTheta(localEyeDir);
	const float sinthetao = SinTheta(localLightDir);
	float maxcos = 0.f;
	if (sinthetai > 1e-4f && sinthetao > 1e-4f) {
		const float dcos = CosPhi(localLightDir) * CosPhi(localEyeDir) +
			SinPhi(localLightDir) * SinPhi(localEyeDir);
		maxcos = max(0.f, dcos);
	}
	return Kd->GetSpectrumValue(hitPoint).Clamp() * (INV_PI * fabsf(localLightDir.z) *
		(A + B * maxcos * sinthetai * sinthetao / max(fabsf(CosTheta(localLightDir)), fabsf(CosTheta(localEyeDir)))));
}

Spectrum RoughMatteMaterial::Sample(const HitPoint &hitPoint,
	const Vector &localFixedDir, Vector *localSampledDir,
	const float u0, const float u1, const float passThroughEvent,
	float *pdfW, float *absCosSampledDir, BSDFEvent *event,
	const BSDFEvent requestedEvent) const {
	if (!(requestedEvent & (DIFFUSE | REFLECT)) ||
			(fabsf(localFixedDir.z) < DEFAULT_COS_EPSILON_STATIC))
		return Spectrum();

	*localSampledDir = Sgn(localFixedDir.z) * CosineSampleHemisphere(u0, u1, pdfW);

	*absCosSampledDir = fabsf(localSampledDir->z);
	if (*absCosSampledDir < DEFAULT_COS_EPSILON_STATIC)
		return Spectrum();

	*event = DIFFUSE | REFLECT;
	const float s = sigma->GetFloatValue(hitPoint);
	const float sigma2 = s * s;
	const float A = 1.f - (sigma2 / (2.f * (sigma2 + 0.33f)));
	const float B = 0.45f * sigma2 / (sigma2 + 0.09f);
	const float sinthetai = SinTheta(localFixedDir);
	const float sinthetao = SinTheta(*localSampledDir);
	float maxcos = 0.f;
	if (sinthetai > 1e-4f && sinthetao > 1e-4f) {
		const float dcos = CosPhi(*localSampledDir) * CosPhi(localFixedDir) +
			SinPhi(*localSampledDir) * SinPhi(localFixedDir);
		maxcos = max(0.f, dcos);
	}
	const float coef = (A + B * maxcos * sinthetai * sinthetao / max(fabsf(CosTheta(*localSampledDir)), fabsf(CosTheta(localFixedDir))));
	if (hitPoint.fromLight)
		return Kd->GetSpectrumValue(hitPoint).Clamp() * (coef * fabsf(localFixedDir.z / localSampledDir->z));
	else
		return Kd->GetSpectrumValue(hitPoint).Clamp() * coef;
}

void RoughMatteMaterial::Pdf(const HitPoint &hitPoint,
		const Vector &localLightDir, const Vector &localEyeDir,
		float *directPdfW, float *reversePdfW) const {
	if (directPdfW)
		*directPdfW = fabsf((hitPoint.fromLight ? localEyeDir.z : localLightDir.z) * INV_PI);

	if (reversePdfW)
		*reversePdfW = fabsf((hitPoint.fromLight ? localLightDir.z : localEyeDir.z) * INV_PI);
}

void RoughMatteMaterial::AddReferencedTextures(boost::unordered_set<const Texture *> &referencedTexs) const {
	Material::AddReferencedTextures(referencedTexs);

	Kd->AddReferencedTextures(referencedTexs);
	sigma->AddReferencedTextures(referencedTexs);
}

void RoughMatteMaterial::UpdateTextureReferences(const Texture *oldTex, const Texture *newTex) {
	Material::UpdateTextureReferences(oldTex, newTex);

	if (Kd == oldTex)
		Kd = newTex;
	if (sigma == oldTex)
		sigma = newTex;
}

Properties RoughMatteMaterial::ToProperties() const  {
	Properties props;

	const string name = GetName();
	props.Set(Property("scene.materials." + name + ".type")("roughmatte"));
	props.Set(Property("scene.materials." + name + ".kd")(Kd->GetName()));
	props.Set(Property("scene.materials." + name + ".sigma")(sigma->GetName()));
	props.Set(Material::ToProperties());

	return props;
}