text:
SpecBegin(CDTQIndexUpdater)

    describe(@"cloudant query", ^{

        __block NSString *factoryPath;
        __block CDTDatastoreManager *factory;
        __block CDTDatastore *ds;

        beforeEach(^{
            // Create a new CDTDatastoreFactory at a temp path

            NSString *tempDirectoryTemplate = [NSTemporaryDirectory()
                stringByAppendingPathComponent:@"cloudant_sync_ios_tests.XXXXXX"];
            const char *tempDirectoryTemplateCString =
                [tempDirectoryTemplate fileSystemRepresentation];
            char *tempDirectoryNameCString =
                (char *)malloc(strlen(tempDirectoryTemplateCString) + 1);
            strcpy(tempDirectoryNameCString, tempDirectoryTemplateCString);

            char *result = mkdtemp(tempDirectoryNameCString);
            expect(result).to.beTruthy();

            factoryPath = [[NSFileManager defaultManager]
                stringWithFileSystemRepresentation:tempDirectoryNameCString
                                            length:strlen(result)];
            free(tempDirectoryNameCString);

            NSError *error;
            factory = [[CDTDatastoreManager alloc] initWithDirectory:factoryPath error:&error];

            ds = [factory datastoreNamed:@"test" error:nil];
        });

        afterEach(^{
            // Delete the databases we used

            factory = nil;
            NSError *error;
            [[NSFileManager defaultManager] removeItemAtPath:factoryPath error:&error];
        });

        describe(@"when generating DELETE index entries statements", ^{

            it(@"returns nil for no _id", ^{
                CDTQSqlParts *parts =
                    [CDTQIndexUpdater partsToDeleteIndexEntriesForDocId:nil fromIndex:@"anIndex"];
                expect(parts).to.beNil();
            });

            it(@"returns nil for no index name", ^{
                CDTQSqlParts *parts =
                    [CDTQIndexUpdater partsToDeleteIndexEntriesForDocId:@"123" fromIndex:nil];
                expect(parts).to.beNil();
            });

            it(@"returns correctly for document", ^{
                CDTQSqlParts *parts =
                    [CDTQIndexUpdater partsToDeleteIndexEntriesForDocId:@"123"
                                                              fromIndex:@"anIndex"];
                NSString *sql = @"DELETE FROM _t_cloudant_sync_query_index_anIndex WHERE _id = ?;";
                expect(parts.sqlWithPlaceholders).to.equal(sql);
                expect(parts.placeholderValues).to.equal(@[ @"123" ]);
            });

        });

        describe(@"when generating INSERT statements", ^{

            it(@"returns correctly for single field", ^{
                CDTMutableDocumentRevision *rev = [CDTMutableDocumentRevision revision];
                rev.docId = @"id123";
                rev.body = @{ @"name" : @"mike" };
                CDTDocumentRevision *saved = [ds createDocumentFromRevision:rev error:nil];
                CDTQSqlParts *parts = [CDTQIndexUpdater partsToIndexRevision:saved
                                                                     inIndex:@"anIndex"
                                                              withFieldNames:@[ @"name" ]][0];

                NSString *sql = @"INSERT INTO _t_cloudant_sync_query_index_anIndex "
                                 "( \"_id\", \"_rev\", \"name\" ) VALUES ( ?, ?, ? );";
                expect(parts.sqlWithPlaceholders).to.equal(sql);
                expect(parts.placeholderValues).to.equal(@[ @"id123", saved.revId, @"mike" ]);
            });

            it(@"returns correctly for two fields", ^{
                CDTMutableDocumentRevision *rev = [CDTMutableDocumentRevision revision];
                rev.docId = @"id123";
                rev.body = @{ @"name" : @"mike", @"age" : @12 };
                CDTDocumentRevision *saved = [ds createDocumentFromRevision:rev error:nil];
                CDTQSqlParts *parts =
                    [CDTQIndexUpdater partsToIndexRevision:saved
                                                   inIndex:@"anIndex"
                                            withFieldNames:@[ @"age", @"name" ]][0];

                NSString *sql = @"INSERT INTO _t_cloudant_sync_query_index_anIndex "
                                 "( \"_id\", \"_rev\", \"age\", \"name\" ) VALUES ( ?, ?, ?, ? );";
                expect(parts.sqlWithPlaceholders).to.equal(sql);
                expect(parts.placeholderValues).to.equal(@[ @"id123", saved.revId, @12, @"mike" ]);
            });

            it(@"returns correctly for multiple fields", ^{
                CDTMutableDocumentRevision *rev = [CDTMutableDocumentRevision revision];
                rev.docId = @"id123";
                rev.body = @{
                    @"name" : @"mike",
                    @"age" : @12,
                    @"pet" : @"cat",
                    @"car" : @"mini",
                    @"ignored" : @"something"
                };
                CDTDocumentRevision *saved = [ds createDocumentFromRevision:rev error:nil];
                CDTQSqlParts *parts =
                    [CDTQIndexUpdater partsToIndexRevision:saved
                                                   inIndex:@"anIndex"
                                            withFieldNames:@[ @"age", @"name", @"pet", @"car" ]][0];

                NSString *sql = @"INSERT INTO _t_cloudant_sync_query_index_anIndex "
                                 "( \"_id\", \"_rev\", \"age\", \"name\", \"pet\", \"car\" ) "
                                 "VALUES ( ?, ?, ?, ?, ?, ? );";
                expect(parts.sqlWithPlaceholders).to.equal(sql);
                expect(parts.placeholderValues)
                    .to.equal(@[ @"id123", saved.revId, @12, @"mike", @"cat", @"mini" ]);
            });

            it(@"returns correctly for missing fields", ^{
                CDTMutableDocumentRevision *rev = [CDTMutableDocumentRevision revision];
                rev.docId = @"id123";
                rev.body = @{ @"name" : @"mike", @"pet" : @"cat", @"ignored" : @"something" };
                CDTDocumentRevision *saved = [ds createDocumentFromRevision:rev error:nil];
                CDTQSqlParts *parts =
                    [CDTQIndexUpdater partsToIndexRevision:saved
                                                   inIndex:@"anIndex"
                                            withFieldNames:@[ @"age", @"name", @"pet", @"car" ]][0];

                NSString *sql = @"INSERT INTO _t_cloudant_sync_query_index_anIndex "
                                 "( \"_id\", \"_rev\", \"name\", \"pet\" ) VALUES ( ?, ?, ?, ? );";
                expect(parts.sqlWithPlaceholders).to.equal(sql);
                expect(parts.placeholderValues)
                    .to.equal(@[ @"id123", saved.revId, @"mike", @"cat" ]);
            });

            it(@"still indexes a blank row if no fields", ^{
                CDTMutableDocumentRevision *rev = [CDTMutableDocumentRevision revision];
                rev.docId = @"id123";
                rev.body = @{ @"name" : @"mike", @"pet" : @"cat", @"ignored" : @"something" };
                CDTDocumentRevision *saved = [ds createDocumentFromRevision:rev error:nil];
                CDTQSqlParts *parts =
                    [CDTQIndexUpdater partsToIndexRevision:saved
                                                   inIndex:@"anIndex"
                                            withFieldNames:@[ @"car", @"van" ]][0];
                NSString *sql = @"INSERT INTO _t_cloudant_sync_query_index_anIndex "
                                 "( \"_id\", \"_rev\" ) VALUES ( ?, ? );";
                expect(parts.sqlWithPlaceholders).to.equal(sql);
                expect(parts.placeholderValues).to.equal(@[ @"id123", saved.revId ]);
            });

            context(@"when indexing arrays", ^{

                it(@"indexes a single array field", ^{
                    CDTMutableDocumentRevision *rev = [CDTMutableDocumentRevision revision];
                    rev.docId = @"id123";
                    rev.body = @{ @"name" : @"mike", @"pet" : @[ @"cat", @"dog", @"parrot" ] };
                    CDTDocumentRevision *saved = [ds createDocumentFromRevision:rev error:nil];
                    NSArray *statements =
                        [CDTQIndexUpdater partsToIndexRevision:saved
                                                       inIndex:@"anIndex"
                                                withFieldNames:@[ @"name", @"pet" ]];
                    expect(statements.count).to.equal(3);

                    CDTQSqlParts *parts;
                    NSString *sql;

                    parts = statements[0];
                    sql = @"INSERT INTO _t_cloudant_sync_query_index_anIndex "
                           "( \"_id\", \"_rev\", \"pet\", \"name\" ) VALUES ( ?, ?, ?, ? );";
                    expect(parts.sqlWithPlaceholders).to.equal(sql);
                    expect(parts.placeholderValues)
                        .to.equal(@[ @"id123", saved.revId, @"cat", @"mike" ]);

                    parts = statements[1];
                    sql = @"INSERT INTO _t_cloudant_sync_query_index_anIndex "
                           "( \"_id\", \"_rev\", \"pet\", \"name\" ) VALUES ( ?, ?, ?, ? );";
                    expect(parts.sqlWithPlaceholders).to.equal(sql);
                    expect(parts.placeholderValues)
                        .to.equal(@[ @"id123", saved.revId, @"dog", @"mike" ]);

                    parts = statements[2];
                    sql = @"INSERT INTO _t_cloudant_sync_query_index_anIndex "
                           "( \"_id\", \"_rev\", \"pet\", \"name\" ) VALUES ( ?, ?, ?, ? );";
                    expect(parts.sqlWithPlaceholders).to.equal(sql);
                    expect(parts.placeholderValues)
                        .to.equal(@[ @"id123", saved.revId, @"parrot", @"mike" ]);
                });

                it(@"indexes a single array field in subdoc", ^{
                    CDTMutableDocumentRevision *rev = [CDTMutableDocumentRevision revision];
                    rev.docId = @"id123";
                    rev.body = @{ @"name" : @"mike", @"pet" : @{@"species" : @[ @"cat", @"dog" ]} };
                    CDTDocumentRevision *saved = [ds createDocumentFromRevision:rev error:nil];
                    NSArray *statements =
                        [CDTQIndexUpdater partsToIndexRevision:saved
                                                       inIndex:@"anIndex"
                                                withFieldNames:@[ @"name", @"pet.species" ]];
                    expect(statements.count).to.equal(2);

                    CDTQSqlParts *parts;
                    NSString *sql;

                    parts = statements[0];
                    sql =
                        @"INSERT INTO _t_cloudant_sync_query_index_anIndex "
                         "( \"_id\", \"_rev\", \"pet.species\", \"name\" ) VALUES ( ?, ?, ?, ? );";
                    expect(parts.sqlWithPlaceholders).to.equal(sql);
                    expect(parts.placeholderValues)
                        .to.equal(@[ @"id123", saved.revId, @"cat", @"mike" ]);

                    parts = statements[1];
                    sql =
                        @"INSERT INTO _t_cloudant_sync_query_index_anIndex "
                         "( \"_id\", \"_rev\", \"pet.species\", \"name\" ) VALUES ( ?, ?, ?, ? );";
                    expect(parts.sqlWithPlaceholders).to.equal(sql);
                    expect(parts.placeholderValues)
                        .to.equal(@[ @"id123", saved.revId, @"dog", @"mike" ]);
                });

                it(@"rejects multiple array fields", ^{
                    CDTMutableDocumentRevision *rev = [CDTMutableDocumentRevision revision];
                    rev.docId = @"id123";
                    rev.body = @{
                        @"name" : @"mike",
                        @"pet" : @[ @"cat", @"dog", @"parrot" ],
                        @"pet2" : @[ @"cat", @"dog", @"parrot" ]
                    };
                    CDTDocumentRevision *saved = [ds createDocumentFromRevision:rev error:nil];
                    NSArray *statements =
                        [CDTQIndexUpdater partsToIndexRevision:saved
                                                       inIndex:@"anIndex"
                                                withFieldNames:@[ @"name", @"pet", @"pet2" ]];
                    expect(statements).to.beNil();
                });

                it(@"returns correctly for empty array field", ^{
                    // Treat an empty array field the same as a missing field.
                    // Only the "name" field should be included as a result of this test.
                    CDTMutableDocumentRevision *rev = [CDTMutableDocumentRevision revision];
                    rev.docId = @"id123";
                    rev.body = @{ @"name" : @"mike", @"pet" : @[] };
                    CDTDocumentRevision *saved = [ds createDocumentFromRevision:rev error:nil];
                    NSArray *statements = [CDTQIndexUpdater partsToIndexRevision:saved
                                                                         inIndex:@"anIndex"
                                                                  withFieldNames:@[ @"age",
                                                                                @"name",
                                                                                @"pet" ] ];
                    expect(statements.count).to.equal(1);
                    CDTQSqlParts *parts = statements[0];

                    NSString *sql = @"INSERT INTO _t_cloudant_sync_query_index_anIndex "
                                     "( \"_id\", \"_rev\", \"name\" ) VALUES ( ?, ?, ? );";
                    expect(parts.sqlWithPlaceholders).to.equal(sql);
                    expect(parts.placeholderValues).to.equal(@[ @"id123", saved.revId, @"mike" ]);
                });

                it(@"returns correctly for empty array in a subdoc", ^{
                    CDTMutableDocumentRevision *rev = [CDTMutableDocumentRevision revision];
                    rev.docId = @"id123";
                    rev.body = @{ @"name" : @"mike", @"pet" : @{@"species" : @[] } };
                    CDTDocumentRevision *saved = [ds createDocumentFromRevision:rev error:nil];
                    NSArray *statements = [CDTQIndexUpdater partsToIndexRevision:saved
                                                                         inIndex:@"anIndex"
                                                                  withFieldNames:@[@"age",
                                                                                @"name",
                                                                                @"pet.species"]];
                    expect(statements.count).to.equal(1);
                    CDTQSqlParts *parts = statements[0];

                    NSString *sql = @"INSERT INTO _t_cloudant_sync_query_index_anIndex "
                                     "( \"_id\", \"_rev\", \"name\" ) VALUES ( ?, ?, ? );";
                    expect(parts.sqlWithPlaceholders).to.equal(sql);
                    expect(parts.placeholderValues).to.equal(@[ @"id123", saved.revId, @"mike" ]);
                });

            });

        });

        describe(@"when setting sequence numbers", ^{

            __block CDTDatastore *ds;
            __block CDTQIndexManager *im;

            beforeEach(^{
                ds = [factory datastoreNamed:@"test" error:nil];
                expect(ds).toNot.beNil();

                CDTMutableDocumentRevision *rev = [CDTMutableDocumentRevision revision];

                rev.docId = @"mike12";
                rev.body = @{ @"name" : @"mike", @"age" : @12, @"pet" : @"cat" };
                [ds createDocumentFromRevision:rev error:nil];

                rev.docId = @"mike23";
                rev.body = @{ @"name" : @"mike", @"age" : @23, @"pet" : @"parrot" };
                [ds createDocumentFromRevision:rev error:nil];

                rev.docId = @"mike34";
                rev.body = @{ @"name" : @"mike", @"age" : @34, @"pet" : @"dog" };
                [ds createDocumentFromRevision:rev error:nil];

                rev.docId = @"john72";
                rev.body = @{ @"name" : @"john", @"age" : @34, @"pet" : @"fish" };
                [ds createDocumentFromRevision:rev error:nil];

                rev.docId = @"fred34";
                rev.body = @{ @"name" : @"fred", @"age" : @43, @"pet" : @"snake" };
                [ds createDocumentFromRevision:rev error:nil];

                rev.docId = @"fred12";
                rev.body = @{ @"name" : @"fred", @"age" : @12 };
                [ds createDocumentFromRevision:rev error:nil];

                im = [CDTQIndexManager managerUsingDatastore:ds error:nil];
                expect(im).toNot.beNil();

            });

            it(@"sets correct sequence number", ^{

                expect([im ensureIndexed:@[ @"age", @"pet", @"name" ] withName:@"basic"])
                    .toNot.beNil();

                FMDatabaseQueue *queue =
                    (FMDatabaseQueue *)[im performSelector:@selector(database)];

                CDTQIndexUpdater *updater =
                    [[CDTQIndexUpdater alloc] initWithDatabase:queue datastore:ds];
                expect([updater sequenceNumberForIndex:@"basic"]).to.equal(6);

                expect([updater updateAllIndexes:[im listIndexes]]).to.beTruthy();

                expect([updater sequenceNumberForIndex:@"basic"]).to.equal(6);

            });

            it(@"sets correct sequence number after update", ^{
                expect([im ensureIndexed:@[ @"age", @"pet", @"name" ] withName:@"basic"])
                    .toNot.beNil();
                FMDatabaseQueue *queue =
                    (FMDatabaseQueue *)[im performSelector:@selector(database)];
                CDTQIndexUpdater *updater =
                    [[CDTQIndexUpdater alloc] initWithDatabase:queue datastore:ds];

                CDTMutableDocumentRevision *rev = [CDTMutableDocumentRevision revision];
                rev.docId = @"newdoc";
                rev.body = @{ @"name" : @"fred", @"age" : @12 };
                [ds createDocumentFromRevision:rev error:nil];

                expect([updater updateAllIndexes:[im listIndexes]]).to.beTruthy();

                expect([updater sequenceNumberForIndex:@"basic"]).to.equal(7);

            });

            describe(@"when using a text index", ^{
                it(@"sets correct sequence number", ^{

                    expect([im ensureIndexed:@[ @"pet", @"name" ]
                                    withName:@"basic"
                                        type:@"text"]).toNot.beNil();

                    FMDatabaseQueue *queue =
                        (FMDatabaseQueue *)[im performSelector:@selector(database)];

                    CDTQIndexUpdater *updater =
                    [[CDTQIndexUpdater alloc] initWithDatabase:queue datastore:ds];
                    expect([updater sequenceNumberForIndex:@"basic"]).to.equal(6);

                    expect([updater updateAllIndexes:[im listIndexes]]).to.beTruthy();

                    expect([updater sequenceNumberForIndex:@"basic"]).to.equal(6);

                });

                it(@"sets correct sequence number after update", ^{
                    expect([im ensureIndexed:@[ @"pet", @"name" ]
                                    withName:@"basic"
                                        type:@"text"]).toNot.beNil();
                    FMDatabaseQueue *queue =
                        (FMDatabaseQueue *)[im performSelector:@selector(database)];
                    CDTQIndexUpdater *updater =
                        [[CDTQIndexUpdater alloc] initWithDatabase:queue datastore:ds];

                    CDTMutableDocumentRevision *rev = [CDTMutableDocumentRevision revision];
                    rev.docId = @"newdoc";
                    rev.body = @{ @"name" : @"fred", @"age" : @12 };
                    [ds createDocumentFromRevision:rev error:nil];

                    expect([updater updateAllIndexes:[im listIndexes]]).to.beTruthy();

                    expect([updater sequenceNumberForIndex:@"basic"]).to.equal(7);

                });
            });

        });
    });

SpecEnd


text:
namespace blink {

namespace {

class MockNoStatePrefetchClient : public NoStatePrefetchClient {
 public:
  MockNoStatePrefetchClient(Page& page, bool is_prefetch_only)
      : NoStatePrefetchClient(page, nullptr),
        is_prefetch_only_(is_prefetch_only) {}

 private:
  bool IsPrefetchOnly() override { return is_prefetch_only_; }

  bool is_prefetch_only_;
};

class HTMLDocumentParserTest
    : public PageTestBase,
      public testing::WithParamInterface<ParserSynchronizationPolicy> {
 protected:
  HTMLDocumentParserTest()
      : original_force_synchronous_parsing_for_testing_(
            Document::ForceSynchronousParsingForTesting()) {
    Document::SetForceSynchronousParsingForTesting(Policy() ==
                                                   kForceSynchronousParsing);
  }
  ~HTMLDocumentParserTest() override {
    // Finish the pending tasks which may require the runtime enabled flags,
    // before restoring the flags.
    base::RunLoop().RunUntilIdle();
    Document::SetForceSynchronousParsingForTesting(
        original_force_synchronous_parsing_for_testing_);
  }

  void SetUp() override {
    PageTestBase::SetUp();
    GetDocument().SetURL(KURL("https://example.test"));
  }

  HTMLDocumentParser* CreateParser(HTMLDocument& document) {
    auto* parser =
        MakeGarbageCollected<HTMLDocumentParser>(document, GetParam());
    std::unique_ptr<TextResourceDecoder> decoder(
        BuildTextResourceDecoderFor(&document, "text/html", g_null_atom));
    parser->SetDecoder(std::move(decoder));
    return parser;
  }

 private:
  ParserSynchronizationPolicy Policy() const { return GetParam(); }

  bool original_force_synchronous_parsing_for_testing_;
};

// Calls DocumentParser::Detach() in the destructor. Used to ensure detach is
// called, as otherwise some assertions may be triggered.
class ScopedParserDetacher {
 public:
  explicit ScopedParserDetacher(DocumentParser* parser) : parser_(parser) {}

  explicit ScopedParserDetacher(HTMLDocumentParser* parser)
      : ScopedParserDetacher(static_cast<DocumentParser*>(parser)) {}

  ~ScopedParserDetacher() { parser_->Detach(); }

 private:
  UntracedMember<DocumentParser> parser_;
};

}  // namespace

INSTANTIATE_TEST_SUITE_P(HTMLDocumentParserTest,
                         HTMLDocumentParserTest,
                         testing::Values(kForceSynchronousParsing,
                                         kAllowDeferredParsing));

TEST_P(HTMLDocumentParserTest, StopThenPrepareToStopShouldNotCrash) {
  auto& document = To<HTMLDocument>(GetDocument());
  DocumentParser* parser = CreateParser(document);
  ScopedParserDetacher detacher(parser);
  const char kBytes[] = "<html>";
  parser->AppendBytes(kBytes, sizeof(kBytes));
  // These methods are not supposed to be called one after the other, but in
  // practice it can happen (e.g. if navigation is aborted).
  parser->StopParsing();
  parser->PrepareToStopParsing();
}

TEST_P(HTMLDocumentParserTest, HasNoPendingWorkAfterStopParsing) {
  auto& document = To<HTMLDocument>(GetDocument());
  HTMLDocumentParser* parser = CreateParser(document);
  DocumentParser* control_parser = static_cast<DocumentParser*>(parser);
  ScopedParserDetacher detacher(control_parser);
  const char kBytes[] = "<html>";
  control_parser->AppendBytes(kBytes, sizeof(kBytes));
  control_parser->StopParsing();
  EXPECT_FALSE(parser->HasPendingWorkScheduledForTesting());
}

TEST_P(HTMLDocumentParserTest, HasNoPendingWorkAfterStopParsingThenAppend) {
  auto& document = To<HTMLDocument>(GetDocument());
  HTMLDocumentParser* parser = CreateParser(document);
  DocumentParser* control_parser = static_cast<DocumentParser*>(parser);
  ScopedParserDetacher detacher(control_parser);
  const char kBytes1[] = "<html>";
  control_parser->AppendBytes(kBytes1, sizeof(kBytes1));
  control_parser->StopParsing();
  const char kBytes2[] = "<head>";
  control_parser->AppendBytes(kBytes2, sizeof(kBytes2));
  EXPECT_FALSE(parser->HasPendingWorkScheduledForTesting());
}

TEST_P(HTMLDocumentParserTest, HasNoPendingWorkAfterDetach) {
  auto& document = To<HTMLDocument>(GetDocument());
  HTMLDocumentParser* parser = CreateParser(document);
  DocumentParser* control_parser = static_cast<DocumentParser*>(parser);
  const char kBytes[] = "<html>";
  control_parser->AppendBytes(kBytes, sizeof(kBytes));
  control_parser->Detach();
  EXPECT_FALSE(parser->HasPendingWorkScheduledForTesting());
}

TEST_P(HTMLDocumentParserTest, AppendPrefetch) {
  auto& document = To<HTMLDocument>(GetDocument());
  ProvideNoStatePrefetchClientTo(
      *document.GetPage(), MakeGarbageCollected<MockNoStatePrefetchClient>(
                               *document.GetPage(), true));
  EXPECT_TRUE(document.IsPrefetchOnly());
  HTMLDocumentParser* parser = CreateParser(document);
  ScopedParserDetacher detacher(parser);

  const char kBytes[] = "<httttttt";
  parser->AppendBytes(kBytes, sizeof(kBytes));
  // The bytes are forwarded to the preload scanner, not to the tokenizer.
  HTMLParserScriptRunnerHost* script_runner_host =
      parser->AsHTMLParserScriptRunnerHostForTesting();
  EXPECT_TRUE(script_runner_host->HasPreloadScanner());
  // Finishing should not cause parsing to start (verified via an internal
  // DCHECK).
  EXPECT_FALSE(parser->DidPumpTokenizerForTesting());
  static_cast<DocumentParser*>(parser)->Finish();
  EXPECT_FALSE(parser->DidPumpTokenizerForTesting());
  // Cancel any pending work to make sure that RuntimeFeatures DCHECKs do not
  // fire.
  static_cast<DocumentParser*>(parser)->StopParsing();
}

TEST_P(HTMLDocumentParserTest, AppendNoPrefetch) {
  auto& document = To<HTMLDocument>(GetDocument());
  EXPECT_FALSE(document.IsPrefetchOnly());
  // Use ForceSynchronousParsing to allow calling append().
  HTMLDocumentParser* parser = CreateParser(document);
  ScopedParserDetacher detacher(parser);

  const char kBytes[] = "<htttttt";
  parser->AppendBytes(kBytes, sizeof(kBytes));
  test::RunPendingTasks();
  // The bytes are forwarded to the tokenizer.
  HTMLParserScriptRunnerHost* script_runner_host =
      parser->AsHTMLParserScriptRunnerHostForTesting();
  EXPECT_EQ(script_runner_host->HasPreloadScanner(),
            GetParam() == kAllowDeferredParsing);
  EXPECT_TRUE(parser->DidPumpTokenizerForTesting());
  // Cancel any pending work to make sure that RuntimeFeatures DCHECKs do not
  // fire.
  static_cast<DocumentParser*>(parser)->StopParsing();
}

}  // namespace blink

redpajama_set_name: RedPajamaGithub


text:
Implementation of the methods described in the paper: [Seeing Through Noise: Speaker Separation and Enhancement using Visually-derived Speech](http://www.vision.huji.ac.il/speaker-separation) by Aviv Gabbay, Ariel Ephrat, Tavi Halperin and Shmuel Peleg.

## Speaker Separation and Enhancement Demo

## Usage
### Dependencies
* python >= 2.7
* [mediaio](https://github.com/avivga/mediaio)
* [face-detection](https://github.com/avivga/face-detection)
* keras >= 2.0.4
* numpy >= 1.12.1
* dlib >= 19.4.0
* opencv >= 3.2.0

## Citing
If you find this project useful for your research, please cite
```
@inproceedings{gabbay2018seeing,
  author    = {Aviv Gabbay and
               Ariel Ephrat and
               Tavi Halperin and
               Shmuel Peleg},
  title     = {Seeing Through Noise: Visually Driven Speaker Separation And Enhancement},
  booktitle = {{ICASSP}},
  pages     = {3051--3055},
  publisher = {{IEEE}},
  year      = {2018}
}
```


text:
var ConfigurableSwatchesList = {
    swatchesByProduct: {},

    init: function()
    {
        var that = this;
        jQuery('.configurable-swatch-list li').each(function() {
            var $current_product = jQuery(this).closest('li.item');
            var image_type  = 'grid_image';
            if($current_product.parent('.products-grid').length > 0){
                image_type  = 'grid_image';
            }
            if($current_product.parent('.products-list').length > 0){
                image_type  = 'list_image';
            }
            that.initSwatch(this,$current_product,image_type);
            var $swatch = jQuery(this);

            if ($swatch.hasClass('filter-match')) {
                that.handleSwatchSelect($swatch,$current_product,image_type);
            }
        });
    },

    initSwatch: function(swatch,$product,image_type)
    {
        var that = this;
        var $swatch = jQuery(swatch);
        var productId;
        if (productId = $swatch.data('product-id')) {
            if (typeof(this.swatchesByProduct[productId]) == 'undefined') {
                this.swatchesByProduct[productId] = [];
            }
            this.swatchesByProduct[productId].push($swatch);

            $swatch.find('a').on('click', function() {
                that.handleSwatchSelect($swatch,$product,image_type);
                return false;
            });
        }
    },

    handleSwatchSelect: function($swatch,$product,image_type)
    {
        var productId = $swatch.data('product-id');
        var label;
        if (label = $swatch.data('option-label')) {
            ConfigurableMediaImages.swapListImageByOption(productId, label,$product,image_type);
        }

        jQuery.each(this.swatchesByProduct[productId], function(key, $productSwatch) {
            $productSwatch.removeClass('selected');
        });

        $swatch.addClass('selected');
    }
} ;

jQuery(document).on('configurable-media-images-init', function(){
    ConfigurableSwatchesList.init();
});


text:
title: "Hiding behind a decorative fan"
excerpt: "PaperFaces portrait of @khollybell drawn with Paper for iOS on an iPad."
image:
  path: &image /assets/images/paperfaces-khollybell-twitter.jpg
  feature: *image
  thumbnail: /assets/images/paperfaces-khollybell-twitter-150.jpg
categories: [paperfaces]
tags: [portrait, illustration, Paper for iOS]
---

PaperFaces portrait of [@khollybell](https://twitter.com/khollybell).

{% include_cached boilerplate/paperfaces.md %}


text:
'use strict';

/**
 * Dependencies
 */
const del = require('del');
const build = require('../build');

/**
 * Clean the build destination folder
 */
module.exports = function clean() {
  return del(build.DEST_RELEASE, {dot: true});
};


text:
module TrackerApi
  module Resources
    class Me
      include Virtus.model

      attribute :id, Integer
      attribute :name, String
      attribute :initials, String
      attribute :username, String
      attribute :time_zone, TrackerApi::Resources::TimeZone
      attribute :api_token, String
      attribute :has_google_identity, Boolean
      attribute :project_ids, Array[Integer]
      attribute :projects, [TrackerApi::Resources::MembershipSummary]
      attribute :workspace_ids, Array[Integer]
      attribute :email, String
      attribute :receives_in_app_notifications, Boolean
      attribute :kind, String
    end
  end
end


text:
#region License

// Copyright (c) 2007 - 2014, Northwestern University, Vladimir Kleper, Skip Talbot
// and Pattanasak Mongkolwat.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
//   Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
//   Neither the name of the National Cancer Institute nor Northwestern University
//   nor the names of its contributors may be used to endorse or promote products
//   derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#endregion

using System;
using System.Drawing;
using ClearCanvas.Common;
using ClearCanvas.ImageViewer.Graphics;
using ClearCanvas.ImageViewer.InputManagement;
using ClearCanvas.ImageViewer.Mathematics;
using ClearCanvas.ImageViewer.InteractiveGraphics;

namespace AIM.Annotation.Tools
{
	///
	/// Interactive builder class that interprets mouse clicks as ordered
	/// vertices to setup a closed <see cref="IPointsGraphic"/>.
	///
	/// <remarks>
	/// This builder takes input until the the maximum number of
	/// vertices is reached, the user clicks near the first point
	/// or the user double clicks anywhere, after which the graphic is complete
	/// and control is released. A visual cue is shown when the cursor is close
	/// enough to the first point to snap and close the polygon.
	/// </remarks>
	public class InteractivePolygonClickFreeGraphicBuilder : InteractiveGraphicBuilder
	{
		private readonly int _maximumVertices;
		private float _snapRadius = 9f;
		private int _numberOfPointsAnchored = 0;
		private bool _stopTF = false;

		private SnapPointGraphic _snapPoint;

		///
		/// Constructs an interactive builder for the specified graphic.
		///
		/// <param name="pointsGraphic">The graphic to be interactively built.</param>
		public InteractivePolygonClickFreeGraphicBuilder(IPointsGraphic pointsGraphic)
			: this(int.MaxValue, pointsGraphic) { }

		///
		/// Constructs an interactive builder for the specified graphic.
		///
		/// <param name="maximumVertices">The maximum number of vertices to accept.</param>
		/// <param name="pointsGraphic">The graphic to be interactively built.</param>
		/// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="maximumVertices"/> is less than 3.</exception>
		public InteractivePolygonClickFreeGraphicBuilder(int maximumVertices, IPointsGraphic pointsGraphic)
			: base(pointsGraphic)
		{
			Platform.CheckArgumentRange(maximumVertices, 3, int.MaxValue, "maximumVertices");
			_maximumVertices = maximumVertices;
		}

		///
		/// Gets the graphic that the builder is operating on.
		///
		public new IPointsGraphic Graphic
		{
			get { return (IPointsGraphic)base.Graphic; }
		}

		///
		/// Gets or the sets the radius of the snap-to feature in destination pixels.
		///
		public float SnapRadius
		{
			get { return _snapRadius; }
			set { _snapRadius = value; }
		}

		///
		/// Resets any internal state of the builder, allowing the same graphic to be rebuilt.
		///
		public override void Reset()
		{
			InstallSnapPointGraphic(false);
			_numberOfPointsAnchored = 0;
			base.Reset();
		}

		///
		/// Rolls back the internal state of the builder by one mouse click, allowing the same graphic to be rebuilt by resuming from an earlier state.
		///
		protected override void Rollback()
		{
			InstallSnapPointGraphic(false);
			_numberOfPointsAnchored = Math.Max(_numberOfPointsAnchored - 1, 0);
		}

		///
		/// Called when the builder is cancelling building the <see cref="InteractiveGraphicBuilder.Graphic"/> due to user cancellation.
		///
		protected override void OnGraphicCancelled()
		{
			base.OnGraphicCancelled();
			InstallSnapPointGraphic(false);
		}

		///
		/// Called when the builder is done building the <see cref="InteractiveGraphicBuilder.Graphic"/>.
		///
		protected override void OnGraphicComplete()
		{
			InstallSnapPointGraphic(false);
			base.OnGraphicComplete();
		}

		///
		/// Passes user input to the builder when <see cref="IMouseButtonHandler.Start"/> is called on the owning tool.
		///
		/// <param name="mouseInformation">The user input data.</param>
		/// <returns>True if the builder did something as a result of the call, and hence would like to receive capture; False otherwise.</returns>
		public override bool Start(IMouseInformation mouseInformation)
		{
			_numberOfPointsAnchored++;

			// We just started creating
			if (_numberOfPointsAnchored == 1)
			{
				this.Graphic.CoordinateSystem = CoordinateSystem.Destination;
				this.Graphic.Points.Add(mouseInformation.Location);
				this.Graphic.Points.Add(mouseInformation.Location);
				this.Graphic.ResetCoordinateSystem();
			}
			// We're done creating
			else if (_numberOfPointsAnchored >= 5 && mouseInformation.ClickCount >= 2)
			{
				this.Graphic.CoordinateSystem = CoordinateSystem.Destination;
				try
				{
					this.Graphic.Points.RemoveAt(--_numberOfPointsAnchored);
					this.Graphic.Points[--_numberOfPointsAnchored] = this.Graphic.Points[0];
				}
				finally
				{
					this.Graphic.ResetCoordinateSystem();
				}

				this.NotifyGraphicComplete();
			}
			// We're done creating
			else if (_numberOfPointsAnchored >= 4 && AtOrigin(mouseInformation.Location) && mouseInformation.ClickCount == 1)
			{
				this.NotifyGraphicComplete();
			}
			// We're done creating
			else if (_numberOfPointsAnchored >= 3 && _numberOfPointsAnchored >= _maximumVertices && mouseInformation.ClickCount == 1)
			{
				this.Graphic.CoordinateSystem = CoordinateSystem.Destination;
				this.Graphic.Points.Add(this.Graphic.Points[0]);
				this.Graphic.ResetCoordinateSystem();
				this.NotifyGraphicComplete();
			}
			// We're in the middle of creating
			else if (_numberOfPointsAnchored >= 2 && mouseInformation.ClickCount == 1)
			{
				this.Graphic.CoordinateSystem = CoordinateSystem.Destination;
				this.Graphic.Points.Add(mouseInformation.Location);
				this.Graphic.ResetCoordinateSystem();

			}
			else if (mouseInformation.ClickCount > 1)
			{
				// removes the extra click if the user multi-clicks and it doesn't otherwise have any meaning
				_numberOfPointsAnchored--;
			}
			return true;
		}

		///
		/// Passes user input to the builder when <see cref="IMouseButtonHandler.Track"/> is called on the owning tool.
		///
		/// <param name="mouseInformation">The user input data.</param>
		/// <returns>True if the builder handled the message; False otherwise.</returns>
		public override bool Track(IMouseInformation mouseInformation)
		{

			this.Graphic.CoordinateSystem = CoordinateSystem.Destination;

			if (_numberOfPointsAnchored >= 7 && AtOrigin(mouseInformation.Location))
			{
				this.Graphic.Points[_numberOfPointsAnchored] = this.Graphic.Points[0];
				InstallSnapPointGraphic(true);
				this.Graphic.ResetCoordinateSystem();
				this.NotifyGraphicComplete();
				_stopTF = false;
				this.Stop(mouseInformation);
			}
			else
			{
				if (Vector.Distance(this.Graphic.Points[_numberOfPointsAnchored], mouseInformation.Location) > _snapRadius / 3)
				{
					_stopTF = true;
					this.Graphic.Points[_numberOfPointsAnchored] = mouseInformation.Location;
					InstallSnapPointGraphic(false);
					_numberOfPointsAnchored++;
					this.Graphic.Points.Add(mouseInformation.Location);
					this.Graphic.ResetCoordinateSystem();
				}
			}
			this.Graphic.ResetCoordinateSystem();
			this.Graphic.Draw();
			return true;
		}

		///
		/// Passes user input to the builder when <see cref="IMouseButtonHandler.Stop"/> is called on the owning tool.
		///
		/// <param name="mouseInformation">The user input data.</param>
		/// <returns>True if the tool should not release capture; False otherwise.</returns>
		public override bool Stop(IMouseInformation mouseInformation)
		{
			return _stopTF;
		}

		private bool AtOrigin(PointF point)
		{
			this.Graphic.CoordinateSystem = CoordinateSystem.Destination;
			double distanceToOrigin = Vector.Distance(this.Graphic.Points[0], point);
			this.Graphic.ResetCoordinateSystem();
			return distanceToOrigin < _snapRadius / 3;
		}

		private void InstallSnapPointGraphic(bool install)
		{
			IPointsGraphic subject = this.Graphic;
			CompositeGraphic parent = subject.ParentGraphic as CompositeGraphic;
			if (parent == null)
				return;

			if (install && subject.Points.Count > 0)
			{
				if (_snapPoint == null)
					_snapPoint = new SnapPointGraphic();

				if (!parent.Graphics.Contains(_snapPoint))
					parent.Graphics.Add(_snapPoint);

				_snapPoint.CoordinateSystem = subject.CoordinateSystem;
				_snapPoint.Location = subject.Points[0];
				_snapPoint.ResetCoordinateSystem();

				parent.Draw();
			}
			else if (_snapPoint != null && parent.Graphics.Contains(_snapPoint))
			{
				parent.Graphics.Remove(_snapPoint);
				parent.Draw();
			}
		}

		///
		/// A graphic for indicating that the cursor is close enough to an existing point to snap to it.
		///
		private class SnapPointGraphic : CompositeGraphic
		{
			private readonly InvariantEllipsePrimitive _circle;
			private PointF _location;

			internal SnapPointGraphic()
			{
				_circle = new InvariantEllipsePrimitive();
				_circle.Color = Color.Tomato;
				_circle.InvariantTopLeft = new PointF(-6, -6);
				_circle.InvariantBottomRight = new PointF(6, 6);

				this.Graphics.Add(_circle);
			}

			protected override void Dispose(bool disposing)
			{
				_circle.Dispose();
				base.Dispose(disposing);
			}

			///
			/// Gets the coordinates of the point.
			///
			public PointF Location
			{
				get
				{
					if (base.CoordinateSystem == CoordinateSystem.Source)
						return _location;
					else
						return base.SpatialTransform.ConvertToDestination(_location);
				}
				internal set
				{
					if (!FloatComparer.AreEqual(this.Location, value))
					{
						Platform.CheckMemberIsSet(base.SpatialTransform, "SpatialTransform");

						if (base.CoordinateSystem == CoordinateSystem.Source)
							_location = value;
						else
							_location = base.SpatialTransform.ConvertToSource(value);

						_circle.Location = this.Location;
					}
				}
			}

			///
			/// Gets or sets the radius of the snap graphic.
			///
			public float Radius
			{
				get { return _circle.InvariantBottomRight.X; }
				set
				{
					_circle.InvariantTopLeft = new PointF(-value, -value);
					_circle.InvariantBottomRight = new PointF(value, value);
				}
			}

			///
			/// Gets or sets the colour of the snap graphic.
			///
			public Color Color
			{
				get { return _circle.Color; }
				set { _circle.Color = value; }
			}

			///
			/// Performs a hit test on the snap graphic at given point.
			///
			/// <param name="point">The mouse position in destination coordinates.</param>
			/// <returns>
			/// True if <paramref name="point"/> is inside the snap graphic's radius, false otherwise.
			/// </returns>
			public override bool HitTest(Point point)
			{
				base.CoordinateSystem = CoordinateSystem.Source;
				bool result = FloatComparer.IsLessThan((float)Vector.Distance(base.SpatialTransform.ConvertToSource(point), this.Location), this.Radius);
				base.ResetCoordinateSystem();

				return result;
			}
		}
	}
}


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2014 the National Renewable Energy Laboratory and Sandia Corporation
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Listing Body Info
fprintf('\nList of Body: ');
fprintf('Number of Bodies = %u \n',simu.numWecBodies)
for i=1:simu.numWecBodies
     if body(i).fixed==0
        fprintf('\n\t***** Body Number %G, Name: %s *****\n',i,body(i).name)
        fprintf('\tBody CG                          (m) = [%G,%G,%G]\n',body(i).cg)
        fprintf('\tBody Mass                       (kg) = %G \n',body(i).mass);
        fprintf('\tBody Diagonal MOI              (kgm2)= [%G,%G,%G]\n',body(i).momOfInertia)
     else
        fprintf('\n\t***** Body Number %G, Name: %s (fixed to the global reference frame) *****\n',i,body(i).name)
     end
end
clear i;


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_XML_XPATH_EVALUATOR_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_XML_XPATH_EVALUATOR_H_

#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"

namespace blink {

class ExceptionState;
class Node;
class ScriptValue;
class XPathExpression;
class XPathNSResolver;
class XPathResult;

class XPathEvaluator final : public ScriptWrappable {
  DEFINE_WRAPPERTYPEINFO();

 public:
  static XPathEvaluator* Create() {
    return MakeGarbageCollected<XPathEvaluator>();
  }

  XPathEvaluator() = default;

  XPathExpression* createExpression(const String& expression,
                                    XPathNSResolver*,
                                    ExceptionState&);
  XPathNSResolver* createNSResolver(Node* node_resolver);
  XPathResult* evaluate(const String& expression,
                        Node* context_node,
                        XPathNSResolver*,
                        uint16_t type,
                        const ScriptValue&,
                        ExceptionState&);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_XML_XPATH_EVALUATOR_H_


text:
+++
date = "2020-12-06T11:11:11+02:00"
title = "Utilize the File Structure to Decide When to Use Vue.js Slots"
description = "Learn how you can decide when to use slots in Vue.js components based on the file structure of your project."
intro = "I recently discovered that we can let the file structure of our projects guide us to find out which components we should inject into other components via slots and which components we can import directly..."
draft = false
categories = ["Development"]
tags = ["JavaScript", "Vue"]
images = ["/images/c_pad,b_rgb:EFEFEF,f_auto,q_auto,w_1014,h_510/v1542158522/blog/2020-12-06/file-structure-slots"]
+++

One of my biggest aha moments in the last couple of months was when I realized that Loose Coupling makes the most sense when dependencies trigger side-effects.

So my first principle for when to use Dependency Injection is:

> *Always* inject dependencies that trigger side effects.

I recently discovered that we can let the file structure of our projects guide us to find out which components we should inject into other components via slots and which components we can import directly.

> *Never* import components from a parent directory.

But keep in mind that in programming, there are no absolute truths. So take `always` and `never` with a grain of salt. Depending on several factors, e.g., your application's size and complexity, Dependency Injection might be overkill.

If you sometimes struggle to determine if you should use a slot or import a component directly, this article is for you. We will learn how we can utilize the file structure to help us decide when to use slots.

## Let the File Structure Determine Whether We Should Use Slots

Imagine the following tree structure:

```bash
├─ base
│  ├─ BaseCard.vue
│  └─ ...
├─ ProductDetails.vue
└─ ...
```

If we want to build a card component that displays product details, what we shouldn't do, is modify the `BaseCard` component.

```html
<!-- /base/BaseCard.vue -->
<template>
  <div class="BaseCard">
    <!-- Don't do this! -->
    <ProductDetails/>
  </div>
</template>
```

Instead we apply the Inversion of Control principle.

```diff
 <template>
   <div class="BaseCard">
-    <ProductDetails/>
+    <slot/>
   </div>
 </template>
```

Slots in Vue.js components are a form of Dependency Injection; instead of tightly coupling a specific component by importing and rendering it directly inside another component, we can use a slot to decouple both components.

**Generic base components should never rely on components with specific functionality.** But it's not always that straightforward. In some instances, you might wonder if you should apply the rules of loose coupling and use slots or if tightly coupling two or more components is the better approach.

We can use the file structure to make it easier to develop rules that guide us in making decisions about tight and loose coupling. In the example above, we can see that `BaseCard` is nested one level deeper than `ProductDetails`. If we follow this pattern with other types of components, we can make the following rule:

> *Never* import components from a parent directory.

For example, the `BaseCard` component is not allowed to import any parent directory component. But the `ProductDetails` component is allowed to import any `Base` component it wants.

## Domain-Driven Design

Suppose we want to build our applications using the [Domain-Driven Design](https://vueschool.io/articles/vuejs-tutorials/domain-driven-design-in-nuxt-apps/) paradigm; in that case, we can create a `modules` directory containing components and all other code specific to a particular module or feature.

```bash
├─ base
│  ├─ BaseCard.vue
│  └─ ...
├─ modules
│  ├─ products
│  │  ├─ ProductDetails.vue
│  │  └─ ...
│  └─ ...
└─ ...
```

All components at the root level of our file tree are allowed to use both `Base` components and components inside the `modules` directory (another possible name is `features`). But `Base` components are only allowed to import components within their scope. If a module needs the `BaseCard` component, we need to inject it via a slot or other means of dependency injection.

That way, we get the following benefits:

- completely decoupled components;
- shareable modules (across projects or micro frontends);
- components are explicit about which dependencies they need;
- components do not rely on a specific implementation (style) of a dependency but only on a specific *interface*.

The three types of components:

- `Base` components are the most generic building blocks of our applications. They should be easily reusable across projects. (e.g. `BaseButton`, `BaseCard`, `BaseDialog`)
- Root level components can be generic or specific, but they are always project-specific. (e.g. `TheHeader`, `TheSidebar`, `PromoBlackFriday`)
- Module components are specific to a certain feature (e.g. `ProductList`, `ArticleBody`, `ShoppingCartTotal`).

Do you want to learn more about advanced Vue.js techniques?

      Register for the Newsletter of my upcoming book: Advanced Vue.js Application Architecture.

## Exceptions

If we decide to follow this principle, I'd say that we should always follow the rule of not importing components from a parent directory except for `Base` components. In the case of those generic building blocks, we **might** decide to break the rule. But only if it makes sense for the app we're building. By default, there should not be an exception for `Base` components.

Exceptions, in the other direction, are always acceptable. If it makes sense for an individual component to provide slots for other components on the same level or even nested deeper than the component, it is ok to do so.

Keep in mind that exceptions are always hard to document, and especially for larger teams, too many exceptions can lead to chaos.

## Wrapping It Up

Following this principle can be helpful for certain types of projects. But keep in mind that this highly depends on the circumstances. You can decide to use it because it helps you and your team make architecture decisions faster, but you can also determine that it is not worth it for the project you're working on.


text:
#pragma once

#include <cstdint>
#include <sstream>
#include <iostream>
#define __cdecl

#include "nosal.h"
#include "safeint3.hpp"

#define CPPREST_NOEXCEPT noexcept

#define novtable /* no novtable equivalent */
#define __declspec(x) __attribute__ ((x))

// ignore these:
#define dllimport

#include <stdint.h>
#include <assert.h>

#define __assume(x) do { if (!(x)) __builtin_unreachable(); } while (false)

typedef wchar_t utf16char;
typedef std::wstring utf16string;
typedef std::wstringstream utf16stringstream;
typedef std::wostringstream utf16ostringstream;
typedef std::wostream utf16ostream;
typedef std::wistream utf16istream;
typedef std::wistringstream utf16istringstream;

#define CASABLANCA_UNREFERENCED_PARAMETER(x) (void)x
#define _ASSERTE(x) assert(x)

#ifdef CASABLANCA_DEPRECATION_NO_WARNINGS
#define CASABLANCA_DEPRECATED(x)
#else
#define CASABLANCA_DEPRECATED(x) __attribute__((deprecated(x)))
#endif


text:
@interface RYCuteView : UIView

@end


text:
package org.apache.spark.sql.execution.datasources.oap.index

import java.io.{DataInput, EOFException}

import scala.collection.JavaConverters._
import scala.collection.mutable.ArrayBuffer

import org.apache.hadoop.conf.Configuration
import org.roaringbitmap.{FastAggregation, RoaringBitmap}

import org.apache.spark.sql.execution.datasources.oap.filecache.{BitmapFiberId, FiberCache}
import org.apache.spark.sql.execution.datasources.oap.index.impl.IndexFileReaderImpl
import org.apache.spark.sql.types.StructType

private[oap] class BitmapReaderV1(
    fileReader: IndexFileReaderImpl,
    intervalArray: ArrayBuffer[RangeInterval],
    internalLimit: Int,
    keySchema: StructType,
    conf: Configuration)
    extends BitmapReader(fileReader, intervalArray, keySchema, conf) with Iterator[Int] {

  @transient private var bmRowIdIterator: Iterator[Integer] = _
  private var empty: Boolean = _
  private var bmNullListCache: FiberCache = _

  override def hasNext: Boolean = !empty && bmRowIdIterator.hasNext
  override def next(): Int = bmRowIdIterator.next()
  override def toString: String = "BitmapReaderV1"

  override def clearCache(): Unit = {
    super.clearCache()
    if (bmNullListCache != null) {
      bmNullListCache.release
    }
  }

  private def getDesiredBitmap(fc: FiberCache): RoaringBitmap = {
    val stream = new BitmapDataInputStream(fc)
    val entry = new RoaringBitmap()
    // Below is directly reading from byte array rather than deserializing into java object.
    entry.deserialize(stream)
    entry
  }

  private def getDesiredBitmapArray(): ArrayBuffer[RoaringBitmap] = {
    val keySeq = readBmUniqueKeyList(bmUniqueKeyListCache)
    intervalArray.flatMap{
      case range if !range.isNullPredicate =>
        val (startIdx, endIdx) = getKeyIdx(keySeq, range)
        if (startIdx == -1 || endIdx == -1) {
          // range not fond in cur bitmap, return empty for performance consideration
          Seq.empty
        } else {
          (startIdx until (endIdx + 1)).map(idx => {
            val curIdxOffset = getIdxOffset(bmOffsetListCache, 0L, idx)
            val entrySize = getIdxOffset(bmOffsetListCache, 0L, idx + 1) - curIdxOffset
            val entryFiber = BitmapFiberId(() => fileReader.readFiberCache(curIdxOffset, entrySize),
              fileReader.getName, BitmapIndexSectionId.entryListSection, idx)
            val entryCache = fiberCacheManager.get(entryFiber)
            val entry = getDesiredBitmap(entryCache)
            entryCache.release
            entry
          })
        }
      case range if range.isNullPredicate =>
        bmNullListCache = fiberCacheManager.get(bmNullListFiber)
        if (bmNullListCache.size != 0) {
          Seq(getDesiredBitmap(bmNullListCache))
        } else {
          Seq.empty
        }
    }
  }

  def initRowIdIterator(): Unit = {
    try {
      initDesiredSegments()
      val bitmapArray = getDesiredBitmapArray
      if (bitmapArray.nonEmpty) {
        if (internalLimit > 0) {
          // Get N items from each index.
          bmRowIdIterator =
            bitmapArray.flatMap(bm => bm.iterator.asScala.take(internalLimit)).iterator
        } else {
          bmRowIdIterator =
            bitmapArray.reduceLeft(FastAggregation.or(_, _)).iterator.asScala
        }
        empty = false
      } else {
        empty = true
      }
    } finally {
      clearCache()
    }
  }
}

// Below class is used to directly decode bitmap from FiberCache(either offheap/onheap memory).
private[oap] class BitmapDataInputStream(bitsStream: FiberCache) extends DataInput {

 private val bitsSize: Int = bitsStream.size.toInt
 // The current position to read from FiberCache.
 private var pos: Int = 0

 // The reading byte order is big endian.
 override def readShort(): Short = {
   val curPos = pos
   pos += 2
   (((bitsStream.getByte(curPos) & 0xFF) << 8) |
     ((bitsStream.getByte(curPos + 1) & 0xFF)) & 0xFFFF).toShort
 }

 override def readInt(): Int = {
   val curPos = pos
   pos += 4
   ((bitsStream.getByte(curPos) & 0xFF) << 24) |
     ((bitsStream.getByte(curPos + 1) & 0xFF) << 16) |
     ((bitsStream.getByte(curPos + 2) & 0xFF) << 8) |
     (bitsStream.getByte(curPos + 3) & 0xFF)
 }

 override def readLong(): Long = {
   val curPos = pos
   pos += 8
   ((bitsStream.getByte(curPos) & 0xFF).toLong << 56) |
     ((bitsStream.getByte(curPos + 1).toLong & 0xFF) << 48) |
     ((bitsStream.getByte(curPos + 2).toLong & 0xFF) << 40) |
     ((bitsStream.getByte(curPos + 3).toLong & 0xFF) << 32) |
     ((bitsStream.getByte(curPos + 4).toLong & 0xFF) << 24) |
     ((bitsStream.getByte(curPos + 5).toLong & 0xFF) << 16) |
     ((bitsStream.getByte(curPos + 6).toLong & 0xFF) << 8) |
     (bitsStream.getByte(curPos + 7).toLong & 0xFF)
 }

 override def readFully(readBuffer: Array[Byte], offset: Int, length: Int): Unit = {
   if (length < 0) {
     throw new IndexOutOfBoundsException("read length is inlegal for bitmap index.\n")
   }
   var curPos = pos
   pos += length
   if (pos > bitsSize - 1) {
     throw new EOFException("read is ending of file for bitmap index.\n")
   }
   (offset until (offset + length)).foreach(idx => {
     readBuffer(idx) = bitsStream.getByte(curPos)
     curPos += 1
   })
 }

 override def skipBytes(n: Int): Int = {
   pos += n
   n
 }

 // Below are not needed by roaring bitmap, just implement them for DataInput interface.
 override def readBoolean(): Boolean = {
   val curPos = pos
   pos += 1
   if (bitsStream.getByte(curPos).toInt != 0) true else false
 }

 override def readByte(): Byte = {
   val curPos = pos
   pos += 1
   bitsStream.getByte(curPos)
 }

 override def readUnsignedByte(): Int = {
   readByte().toInt
 }

 override def readUnsignedShort(): Int = {
   readShort().toInt
 }

 override def readChar(): Char = {
   readShort().toChar
 }

 override def readDouble(): Double = {
   readLong().toDouble
 }

 override def readFloat(): Float = {
   readInt().toFloat
 }

 override def readFully(readBuffer: Array[Byte]): Unit = {
   readFully(readBuffer, 0, readBuffer.length)
 }

 override def readLine(): String = {
   throw new UnsupportedOperationException("Bitmap doesn't need this." +
     "It's inlegal to use it in bitmap!!!")
 }

 override def readUTF(): String = {
   throw new UnsupportedOperationException("Bitmap doesn't need this." +
     "It' inlegal to use it in bitmap!!!")
 }
}


text:
package it.netknights.piauthenticator.interfaces;

import it.netknights.piauthenticator.utils.SecretKeyWrapper;

public interface PresenterUtilInterface {
    SecretKeyWrapper getWrapper();
}


text:
def primes(limit):
    numbers = range(2, limit)
    primes = []
    while len(numbers) != 0:
        p = numbers[0]
        primes.append(p)
        numbers = [n for n in numbers if n % p != 0]
    return primes

candidates =  [n for n in range(2, 775147) if 600851475143 % n == 0]
p = primes(100000) #The sieve is inefficient for sqrt(600851475143) as the limit
candidates = [n for n in candidates if n in p or n > 100000]
print candidates


text:
<?php

namespace Keboola\StorageApi;

/**
 * @param int $maxJobPollWaitSeconds
 * @return callable
 */
function createSimpleJobPollDelay($maxJobPollWaitSeconds = 20)
{
    return function ($tries) use ($maxJobPollWaitSeconds) {
        return min(pow(2, $tries), $maxJobPollWaitSeconds);
    };
}


text:
package gw.lang.parser.statements;

import gw.lang.parser.IStatement;

public interface INoOpStatement extends IStatement
{
}


text:
package com.jmb.springfactory.dao.productionorder;

import java.util.stream.Stream;

import com.jmb.springfactory.dao.GenericMySQLService;
import com.jmb.springfactory.exceptions.NotFoundException;
import com.jmb.springfactory.exceptions.PersistenceLayerException;
import com.jmb.springfactory.model.entity.ProductionOrder;
import com.jmb.springfactory.model.enumeration.StatusEnum;

public interface ProductionOrderMySQL extends GenericMySQLService<ProductionOrder, Integer> {

    Stream<ProductionOrder> findAllByScheduleId(Integer scheduleId);

    ProductionOrder save(ProductionOrder order, Integer scheduleId) throws PersistenceLayerException, NotFoundException;

    Stream<ProductionOrder> findAllByScheduleIdAndGroupIdAndStatus(Integer groupId, StatusEnum status);

}


text:
function [Y, G, A] = mlpOut(model, X);

% MLPOUT Output of an MLP model.
%
%	Description:
%
%	Y = MLPOUT(MODEL, X) gives the output of a multi-layer perceptron
%	model, for single hidden layer models the function is a wrapper for
%	mlpfwd.
%	 Returns:
%	  Y - the output.
%	 Arguments:
%	  MODEL - the model for which the output is required.
%	  X - the input data for which the output is required.
%
%	[Y, G] = MLPOUT(MODEL, X) gives the output of a multi-layer
%	perceptron model.
%	 Returns:
%	  Y - the output.
%	  G - the hidden layer activations.
%	 Arguments:
%	  MODEL - the model for which the output is required.
%	  X - the input data for which the output is required.
%
%
%	See also
%	MLPFWD, MLP, MODELOUT

%	Copyright (c) 2006, 2007 Neil D. Lawrence

if length(model.hiddenDim)==1
  if nargout > 1
    if nargout > 2
      [Y, G, A] = mlpfwd(model, X);
    else
      [Y, G] = mlpfwd(model, X);
    end
  else
    Y = mlpfwd(model, X);
  end
else
  ndata = size(x, 1);
  G{1} = tanh(X*model.w{1} + repmat(model.b{1}, numData, 1));
  A{1} = G{1}*model.w{2} + repmat(model.b{2}, numData, 1);
  for i = 2:length(model.numHidden)
    G{i} = tanh(A{i-1});
    A{i} = G{i}*model.w{i+1} + repmat(model.b{i+1}, numData, 1);
  end
  switch model.outfn

   case 'linear'
    y = A{end};

   otherwise
    error('Output function not implemented in multiple hidden layer model.')

  end
end


text:
import * as React from 'react';

export class FooterHelp extends React.Component<any, any> {
  render() {
    return (

Select

    );
  }
}


text:
/**
 * Player actor class.
 *
 * @namespace Asteroids
 * @class Asteroids.Player
 */
(function()
{
   Asteroids.Player = function(p, v, h)
   {
      Asteroids.Player.superclass.constructor.call(this, p, v);
      this.heading = h;
      this.energy = this.ENERGY_INIT;

      // setup SpriteActor values - used for shield sprite
      this.animImage = g_shieldImg;
      this.animLength = this.SHIELD_ANIM_LENGTH;

      // setup weapons
      this.primaryWeapons = [];

      return this;
   };

   extend(Asteroids.Player, Game.SpriteActor,
   {
      MAX_PLAYER_VELOCITY: 8.0,
      PLAYER_RADIUS: 9,
      SHIELD_RADIUS: 14,
      SHIELD_ANIM_LENGTH: 100,
      SHIELD_MIN_PULSE: 20,
      ENERGY_INIT: 400,
      THRUST_DELAY_MS: 100,
      BOMB_RECHARGE_MS: 800,
      BOMB_ENERGY: 80,

      /**
       * Player heading
       */
      heading: 0.0,

      /**
       * Player energy (shield and bombs)
       */
      energy: 0,

      /**
       * Player shield active counter
       */
      shieldCounter: 0,

      /**
       * Player 'alive' flag
       */
      alive: true,

      /**
       * Primary weapon list
       */
      primaryWeapons: null,

      /**
       * Bomb fire recharging counter
       */
      bombRecharge: 0,

      /**
       * Engine thrust recharge counter
       */
      thrustRecharge: 0,

      /**
       * True if the engine thrust graphics should be rendered next frame
       */
      engineThrust: false,

      /**
       * Time that the player was killed - to cause a delay before respawning the player
       */
      killedOn: 0,

      /**
       * Power up setting - can fire when shielded
       */
      fireWhenShield: false,

      /**
       * Player rendering method
       *
       * @param ctx {object} Canvas rendering context
       */
      onRender: function onRender(ctx)
      {
         var headingRad = this.heading * RAD;

         // render engine thrust?
         if (this.engineThrust)
         {
            ctx.save();
            ctx.translate(this.position.x, this.position.y);
            ctx.rotate(headingRad);
            ctx.globalAlpha = 0.5 + Rnd() * 0.5;
            if (BITMAPS)
            {
               ctx.globalCompositeOperation = "lighter";
               ctx.fillStyle = Asteroids.Colours.PLAYER_THRUST;
            }
            else
            {
               ctx.shadowColor = ctx.strokeStyle = Asteroids.Colours.PLAYER_THRUST;
            }
            ctx.beginPath();
            ctx.moveTo(-5, 8);
            ctx.lineTo(5, 8);
            ctx.lineTo(0, 18 + Rnd() * 6);
            ctx.closePath();
            if (BITMAPS) ctx.fill();
            else ctx.stroke();
            ctx.restore();
            this.engineThrust = false;
         }

         // render player graphic
         if (BITMAPS)
         {
            var size = (this.PLAYER_RADIUS * 2) + 6;
            // normalise the player heading to 0-359 degrees
            // then locate the correct frame in the sprite strip - an image for each 4 degrees of rotation
            var normAngle = Floor(this.heading) % 360;
            if (normAngle < 0)
            {
               normAngle = 360 + normAngle;
            }
            ctx.save();
            ctx.drawImage(g_playerImg, 0, Floor(normAngle / 4) * 64, 64, 64, this.position.x - (size / 2), this.position.y - (size / 2), size, size);
            ctx.restore();
         }
         else
         {
            ctx.save();
            ctx.shadowColor = ctx.strokeStyle = "#fff";
            ctx.translate(this.position.x, this.position.y);
            ctx.rotate(headingRad);
            ctx.beginPath();
            ctx.moveTo(-6, 8);
            ctx.lineTo(6, 8);
            ctx.lineTo(0, -8);
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
         }

         // shield up? if so render a shield graphic around the ship
         if (this.shieldCounter > 0 && this.energy > 0)
         {
            if (BITMAPS)
            {
               // render shield graphic bitmap
               ctx.save();
               ctx.translate(this.position.x, this.position.y);
               ctx.rotate(headingRad);
               this.renderSprite(ctx, -this.SHIELD_RADIUS-1, -this.SHIELD_RADIUS-1, (this.SHIELD_RADIUS * 2) + 2);
               ctx.restore();
            }
            else
            {
               // render shield as a simple circle around the ship
               ctx.save();
               ctx.translate(this.position.x, this.position.y);
               ctx.rotate(headingRad);
               ctx.shadowColor = ctx.strokeStyle = Asteroids.Colours.PLAYER_SHIELD;
               ctx.beginPath();
               ctx.arc(0, 2, this.SHIELD_RADIUS, 0, TWOPI, true);
               ctx.closePath();
               ctx.stroke();
               ctx.restore();
            }

            this.shieldCounter--;
            this.energy -= 1.5;
         }
      },

      /**
       * Execute player forward thrust request
       */
      thrust: function thrust()
      {
         // now test we did not thrust too recently, based on time since last thrust
         // request - ensures same thrust at any framerate
         if (GameHandler.frameStart - this.thrustRecharge > this.THRUST_DELAY_MS)
         {
            // update last thrust time
            this.thrustRecharge = GameHandler.frameStart;

            // generate a small thrust vector
            var t = new Vector(0.0, !iOS ? -0.5 : -1.25);

            // rotate thrust vector by player current heading
            t.rotate(this.heading * RAD);

            // add player thrust vector to position
            this.vector.add(t);

            // player can't exceed maximum velocity - scale vector down if
            // this occurs - do this rather than not adding the thrust at all
            // otherwise the player cannot turn and thrust at max velocity
            if (this.vector.length() > this.MAX_PLAYER_VELOCITY)
            {
               this.vector.scale(this.MAX_PLAYER_VELOCITY / this.vector.length());
            }
         }
         // mark so that we know to render engine thrust graphics
         this.engineThrust = true;
      },

      /**
       * Execute player active shield request
       * If energy remaining the shield will be briefly applied - or until key is release
       */
      activateShield: function activateShield()
      {
         // ensure shield stays up for a brief pulse between key presses!
         if (this.energy >= this.SHIELD_MIN_PULSE)
         {
            this.shieldCounter = this.SHIELD_MIN_PULSE;
         }
      },

      isShieldActive: function isShieldActive()
      {
         return (this.shieldCounter > 0 && this.energy > 0);
      },

      radius: function radius()
      {
         return (this.isShieldActive() ? this.SHIELD_RADIUS : this.PLAYER_RADIUS);
      },

      expired: function expired()
      {
         return !(this.alive);
      },

      kill: function kill()
      {
         this.alive = false;
         this.killedOn = GameHandler.frameStart;
      },

      /**
       * Fire primary weapon(s)
       * @param bulletList {Array} to add bullet(s) to on success
       */
      firePrimary: function firePrimary(bulletList)
      {
         var playedSound = false;
         // attempt to fire the primary weapon(s)
         // first ensure player is alive and the shield is not up
         if (this.alive && (!this.isShieldActive() || this.fireWhenShield))
         {
            for (var w in this.primaryWeapons)
            {
               var b = this.primaryWeapons[w].fire();
               if (b)
               {
                  if (isArray(b))
                  {
                     for (var i=0; i<b.length; i++)
                     {
                        bulletList.push(b[i]);
                     }
                  }
                  else
                  {
                     bulletList.push(b);
                  }
                  if (!playedSound)
                  {
                     GameHandler.playSound("laser");
                     playedSound = true;
                  }
               }
            }
         }
      },

      /**
       * Fire secondary weapon.
       * @param bulletList {Array} to add bullet to on success
       */
      fireSecondary: function fireSecondary(bulletList)
      {
         // attempt to fire the secondary weapon and generate bomb object if successful
         // first ensure player is alive and the shield is not up
         if (this.alive && (!this.isShieldActive() || this.fireWhenShield) && this.energy > this.BOMB_ENERGY)
         {
            // now test we did not fire too recently
            if (GameHandler.frameStart - this.bombRecharge > this.BOMB_RECHARGE_MS)
            {
               // ok, update last fired time and we can now generate a bomb
               this.bombRecharge = GameHandler.frameStart;

               // decrement energy supply
               this.energy -= this.BOMB_ENERGY;

               // generate a vector rotated to the player heading and then add the current player
               // vector to give the bomb the correct directional momentum
               var t = new Vector(0.0, -3.0);
               t.rotate(this.heading * RAD);
               t.add(this.vector);

               bulletList.push(new Asteroids.Bomb(this.position.clone(), t));
            }
         }
      },

      onUpdate: function onUpdate()
      {
         // slowly recharge the shield - if not active
         if (!this.isShieldActive() && this.energy < this.ENERGY_INIT)
         {
            this.energy += 0.1;
         }
      },

      reset: function reset(persistPowerUps)
      {
         // reset energy, alive status, weapons and power up flags
         this.alive = true;
         if (!persistPowerUps)
         {
            this.primaryWeapons = [];
            this.primaryWeapons["main"] = new Asteroids.PrimaryWeapon(this);
            this.fireWhenShield = false;
         }
         this.energy = this.ENERGY_INIT + this.SHIELD_MIN_PULSE;  // for shield as below

         // active shield briefly
         this.activateShield();
      }
   });
})();


text:
package com.intuso.utilities.properties.api;

import com.intuso.utilities.collection.ManagedCollectionFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class WriteableMapPropertyRepository extends PropertyRepository {

    private final Map<String, String> values;

    public static WriteableMapPropertyRepository newEmptyRepository(ManagedCollectionFactory managedCollectionFactory) {
        return newEmptyRepository(managedCollectionFactory, null);
    }

    public static WriteableMapPropertyRepository newEmptyRepository(ManagedCollectionFactory managedCollectionFactory, PropertyRepository parent) {
        return new WriteableMapPropertyRepository(managedCollectionFactory, parent, new HashMap<String, String>());
    }

    public WriteableMapPropertyRepository(ManagedCollectionFactory managedCollectionFactory, Map<String, String> values) {
        this(managedCollectionFactory, null, values);
    }

    public WriteableMapPropertyRepository(ManagedCollectionFactory managedCollectionFactory, PropertyRepository parent, Map<String, String> values) {
        super(managedCollectionFactory, parent);
        this.values = values;
    }

    @Override
    protected final Set<String> _keySet() {
        return values.keySet();
    }

    @Override
    protected final String _get(String key) {
        return values.get(key);
    }

    @Override
    protected final void _set(String key, String value) {
        values.put(key, value);
    }

    @Override
    protected final void _remove(String key) {
        values.remove(key);
    }
}


text:
/**
 * Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
 * All rights reserved. Use is subject to license terms and conditions.
 */

package au.csiro.snorocket.core;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import au.csiro.snorocket.core.util.IConceptSet;
import au.csiro.snorocket.core.util.SparseConceptSet;

public class TestSparseConceptSet extends TestIConceptSet {

    @Before
    public void setUp() throws Exception {
    }

    @Override
    IConceptSet createSet(int capacity) {
        return new SparseConceptSet(capacity);
    }

    @Override
    boolean supportsRemove() {
        return false;
    }

    @Test
    public void testNonpresentLargeValue() {
        int limit = 10;
        SparseConceptSet set = new SparseConceptSet();
        for (int i = 0; i < limit; i++) {
            set.add(i);
        }
        assertTrue(set.contains(limit - 1));
        assertFalse(set.contains(limit));
        assertFalse(set.contains(limit + 1));
    }

}


text:
published: true
title: Septuagésime
---
**Dimanche 31 janvier 2021, messe de 16h30**

![Circumdederunt.jpg]({{site.baseurl}}/images/Circumdederunt.jpg)

*Quoniam non in finem oblivio erit pauperis, patientia pauperum non peribit in aeternum*
Le pauvre ne sera pas oublié pour toujours, son attente ne sera pas vaine à jamais.

**Introït : Circumdederunt me**

**Graduel : Adjutor in opportunitatibus**

**Trait : De profundis**

**Offertoire : Media vita**
Alternance polyphonique de John Sheppard 1515-1558

**Consécration : O salutaris Hostia**
d'après Robert White 1538-1574

**Communion : Illumina faciem tuam**
Heinrich Isaac 1450-1517 Choralis Constantinus

**Au dernier évangile : Alma redemptoris Mater**

**Sortie : Benedicamus Domino**
d'après Thomas Tallis 1505-1585


text:
package org.mimosaframework.core.json.parser.deserializer;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

import org.mimosaframework.core.json.parser.DefaultModelParser;
import org.mimosaframework.core.json.parser.ParseContext;
import org.mimosaframework.core.json.util.FieldInfo;
import org.mimosaframework.core.json.parser.ModelToken;
import org.mimosaframework.core.json.parser.ParserConfig;

public class DefaultFieldDeserializer extends FieldDeserializer {

    private ObjectDeserializer fieldValueDeserilizer;

    public DefaultFieldDeserializer(ParserConfig mapping, Class<?> clazz, FieldInfo fieldInfo){
        super(clazz, fieldInfo);
    }

    public ObjectDeserializer getFieldValueDeserilizer(ParserConfig config) {
        if (fieldValueDeserilizer == null) {
            fieldValueDeserilizer = config.getDeserializer(fieldInfo.fieldClass, fieldInfo.fieldType);
        }

        return fieldValueDeserilizer;
    }

    @Override
    public void parseField(DefaultModelParser parser, Object object, Type objectType, Map<String, Object> fieldValues) {
        if (fieldValueDeserilizer == null) {
            fieldValueDeserilizer = parser.getConfig().getDeserializer(fieldInfo);
        }

        Type fieldType = fieldInfo.fieldType;
        if (objectType instanceof ParameterizedType) {
            ParseContext objContext = parser.getContext();
            objContext.type = objectType;
            fieldType= FieldInfo.getFieldType(this.clazz, objectType, fieldType);
        }

        // ContextObjectDeserializer
        Object value;
        if (fieldValueDeserilizer instanceof JavaBeanDeserializer) {
            JavaBeanDeserializer javaBeanDeser = (JavaBeanDeserializer) fieldValueDeserilizer;
            value = javaBeanDeser.deserialze(parser, fieldType, fieldInfo.name, fieldInfo.parserFeatures);
        } else {
            if (this.fieldInfo.format != null
                    && fieldValueDeserilizer instanceof ContextObjectDeserializer
                    ) {
                value = ((ContextObjectDeserializer)fieldValueDeserilizer) //
                        .deserialze(parser, fieldType, fieldInfo.name, fieldInfo.format, fieldInfo.parserFeatures);
            } else {
                value = fieldValueDeserilizer.deserialze(parser, fieldType, fieldInfo.name);
            }
        }
        if (parser.getResolveStatus() == DefaultModelParser.NeedToResolve) {
            DefaultModelParser.ResolveTask task = parser.getLastResolveTask();
            task.fieldDeserializer = this;
            task.ownerContext = parser.getContext();
            parser.setResolveStatus(DefaultModelParser.NONE);
        } else {
            if (object == null) {
                fieldValues.put(fieldInfo.name, value);
            } else {
                setValue(object, value);
            }
        }
    }

    public int getFastMatchToken() {
        if (fieldValueDeserilizer != null) {
            return fieldValueDeserilizer.getFastMatchToken();
        }

        return ModelToken.LITERAL_INT;
    }
}


text:
package com.amihaiemil.versioneye;

import java.util.List;

import javax.json.Json;
import javax.json.JsonObject;

import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;

/**
 * Unit tests for {@link JsonVulnerability}.
 * @author Mihai Andronache (amihaiemil@gmail.com)
 * @version $Id$
 * @since 1.0.0
 */
public final class JsonVulnerabilityTestCase {

    /**
     * JsonVulnerability can return the language.
     */
    @Test
    public void returnsLanguage() {
        final Vulnerability vln = new JsonVulnerability(
            Json.createObjectBuilder().add("language", "Ruby").build()
        );
        MatcherAssert.assertThat(vln.language(), Matchers.is("Ruby"));
    }

    /**
     * JsonVulnerability can return the name id.
     */
    @Test
    public void returnsNameId() {
        final Vulnerability vln = new JsonVulnerability(
            Json.createObjectBuilder().add("name_id", "nametest").build()
        );
        MatcherAssert.assertThat(vln.nameId(), Matchers.is("nametest"));
    }

    /**
     * JsonVulnerability can return the prod key.
     */
    @Test
    public void returnsProdKey() {
        final Vulnerability vln = new JsonVulnerability(
            Json.createObjectBuilder().add("prod_key", "prod/key").build()
        );
        MatcherAssert.assertThat(vln.prodKey(), Matchers.is("prod/key"));
    }

    /**
     * JsonVulnerability can return the platform.
     */
    @Test
    public void returnsPlatform() {
        final Vulnerability vln = new JsonVulnerability(
            Json.createObjectBuilder().add("platform", "Windows").build()
        );
        MatcherAssert.assertThat(vln.platform(), Matchers.is("Windows"));
    }

    /**
     * JsonVulnerability can return the framework.
     */
    @Test
    public void returnsFramework() {
        final Vulnerability vln = new JsonVulnerability(
            Json.createObjectBuilder().add("framework", "Spring").build()
        );
        MatcherAssert.assertThat(vln.framework(), Matchers.is("Spring"));
    }

    /**
     * JsonVulnerability can return the description.
     */
    @Test
    public void returnsDescription() {
        final Vulnerability vln = new JsonVulnerability(
            Json.createObjectBuilder().add("description", "testdesc").build()
        );
        MatcherAssert.assertThat(vln.description(), Matchers.is("testdesc"));
    }

    /**
     * JsonVulnerability can return the summary.
     */
    @Test
    public void returnsSummary() {
        final Vulnerability vln = new JsonVulnerability(
            Json.createObjectBuilder().add("summary", "somesummary").build()
        );
        MatcherAssert.assertThat(vln.summary(), Matchers.is("somesummary"));
    }

    /**
     * JsonVulnerability can return the author.
     */
    @Test
    public void returnsAuthor() {
        final Vulnerability vln = new JsonVulnerability(
            Json.createObjectBuilder().add("author", "amihaiemil").build()
        );
        MatcherAssert.assertThat(vln.author(), Matchers.is("amihaiemil"));
    }

    /**
     * JsonVulnerability can return the publish date.
     */
    @Test
    public void returnsPublishDate() {
        final Vulnerability vln = new JsonVulnerability(
            Json.createObjectBuilder().add("publish_date", "21.04.2009").build()
        );
        MatcherAssert.assertThat(vln.publishDate(), Matchers.is("21.04.2009"));
    }

    /**
     * JsonVulnerability can return 0 affected version.
     */
    @Test
    public void returnsZeroAffectedVersion() {
        final Vulnerability vln = new JsonVulnerability(
            Json.createObjectBuilder()
                .add("affected_versions", Json.createArrayBuilder())
                .build()
        );
        MatcherAssert.assertThat(vln.affectedVersions(), Matchers.hasSize(0));
    }

    /**
     * JsonVulnerability can return one affected version.
     */
    @Test
    public void returnsOneAffectedVersion() {
        final Vulnerability vln = new JsonVulnerability(
            Json.createObjectBuilder()
                .add("affected_versions", Json.createArrayBuilder().add("1"))
                .build()
        );
        final List<String> affected = vln.affectedVersions();
        MatcherAssert.assertThat(affected, Matchers.hasSize(1));
        MatcherAssert.assertThat(affected.get(0), Matchers.is("1"));
    }

    /**
     * JsonVulnerability can return more affected version.
     */
    @Test
    public void returnsMoreAffectedVersions() {
        final Vulnerability vln = new JsonVulnerability(
            Json.createObjectBuilder()
                .add(
                    "affected_versions",
                    Json.createArrayBuilder()
                        .add("1")
                        .add("2")
                        .add("3")
                    )
                .build()
        );
        final List<String> affected = vln.affectedVersions();
        MatcherAssert.assertThat(affected, Matchers.hasSize(3));
        MatcherAssert.assertThat(affected.get(0), Matchers.is("1"));
        MatcherAssert.assertThat(affected.get(1), Matchers.is("2"));
        MatcherAssert.assertThat(affected.get(2), Matchers.is("3"));
    }

    /**
     * JsonVulenrability returns the Json it has behind.
     */
    @Test
    public void returnsJson() {
        final JsonObject json = Json.createObjectBuilder()
            .add("some", "vulnerability")
            .add("jsonFormat", true)
            .build();
        final Vulnerability vln = new JsonVulnerability(json);
        MatcherAssert.assertThat(vln.json(), Matchers.equalTo(json));
    }
}


text:
using System;
using System.Linq;
using Dangl.WebDocumentation.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace Dangl.WebDocumentation.Tests.Models
{
    public class DatabaseInitializationTestsFixture : IDisposable
    {
        public DatabaseInitializationTestsFixture()
        {
            var services = new ServiceCollection();
            services.AddEntityFrameworkInMemoryDatabase()
                .AddDbContext<ApplicationDbContext>(o => o.UseInMemoryDatabase(Guid.NewGuid().ToString()));

            var serviceProvider = services.BuildServiceProvider();

            Context = serviceProvider.GetService<ApplicationDbContext>();
            Context.Database.EnsureCreated();
        }

        public ApplicationDbContext Context { get; }

        public void Dispose()
        {
            Context.Database.EnsureDeleted();
        }
    }

    public class DatabaseInitializationTests : IClassFixture<DatabaseInitializationTestsFixture>
    {
        public DatabaseInitializationTests(DatabaseInitializationTestsFixture fixture)
        {
            Context = fixture.Context;
        }

        private ApplicationDbContext Context { get; }

        [Fact]
        public void EnsureContextNotNull()
        {
            Assert.NotNull(Context);
        }

        [Fact]
        public void DatabaseHasNoRoles()
        {
            Assert.Empty(Context.Roles);
        }

        [Fact]
        public void DatabaseHasNoDuplicatedRoles()
        {
            Assert.Equal(Context.Roles.Count(), Context.Roles.Select(role => role.Name).Distinct().Count());
        }
    }
}


text:
<?php
/**
 * Form templates
 *
 * @package    phpMyAdmin-setup
 * @author     Piotr Przybylski <piotrprz@gmail.com>
 * @license    http://www.gnu.org/licenses/gpl.html GNU GPL 2.0
 * @version    $Id: FormDisplay.tpl.php 11874 2008-11-13 19:21:34Z crackpl $
 */

/**
 * Displays top part of the form
 *
 * @param string $action         default: $_SERVER['REQUEST_URI']
 * @param string $method         'post' or 'get'
 * @param array  $hidden_fields  array of form hidden fields (key: field name)
 */
function display_form_top($action = null, $method = 'post', $hidden_fields = null)
{
    static $has_check_page_refresh = false;

    if ($action === null) {
        $action = $_SERVER['REQUEST_URI'];
    }
    if ($method != 'post') {
        $method = 'get';
    }
?>
<form method="<?php echo $method ?>" action="<?php echo htmlspecialchars($action) ?>">
<?php
    // we do validation on page refresh when browser remembers field values,
    // add a field with known value which will be used for checks
    if (!$has_check_page_refresh) {
        $has_check_page_refresh = true;
        echo '<input type="hidden" name="check_page_refresh" id="check_page_refresh"'
            . ' value="" />' . "\n";
    }
    echo PMA_generate_common_hidden_inputs() . "\n";
    echo PMA_getHiddenFields((array)$hidden_fields);
}

/**
 * Displays form tabs which are given by an array indexed by fieldset id
 * ({@link display_fieldset_top}), with values being tab titles.
 *
 * @param array $tabs
 */
function display_tabs_top($tabs) {
?>

<?php foreach ($tabs as $tab_id => $tab_name): ?>

<a href="#<?php echo $tab_id ?>"><?php echo $tab_name ?>

<?php endforeach; ?>

<?php
}

/**
 * Displays top part of a fieldset
 *
 * @param string $title
 * @param string $description
 * @param array  $errors
 * @param array  $attributes
 */
function display_fieldset_top($title = '', $description = '', $errors = null, $attributes = array())
{
    $attributes = array_merge(array('class' => 'optbox'), $attributes);
    foreach ($attributes as $k => &$attr) {
        $attr = $k . '="' . htmlspecialchars($attr) . '"';
    }

    echo '<fieldset ' . implode(' ', $attributes) . '>';
    echo '<legend>' . $title . '</legend>';
    if (!empty($description)) {
        echo '
' . $description . '
';
    }
    // this must match with displayErrors() in scripts.js
    if (is_array($errors) && count($errors) > 0) {
        echo '
';
        foreach ($errors as $error) {
            echo '
' . $error . '
';
        }
        echo '
';
    }
?>

<?php
}

/**
 * Displays input field
 *
 * $opts keys:
 * o doc - (string) documentation link
 * o errors - error array
 * o setvalue - (string) shows button allowing to set poredefined value
 * o show_restore_default - (boolean) whether show "restore default" button
 * o values - key - value paris for <select> fields
 * o values_escaped - (boolean) tells whether values array is already escaped (defaults to false)
 * o values_disabled -  (array)list of disabled values (keys from values)
 * o wiki - (string) wiki link
 *
 * @param string $path
 * @param string $name
 * @param string $description
 * @param string $type
 * @param mixed  $value
 * @param bool   $value_is_default
 * @param array  $opts
 */
function display_input($path, $name, $description = '', $type, $value, $value_is_default = true, $opts = null)
{
    $field_class = $value_is_default ? '' : ' class="custom"';
    $name_id = 'name="' . $path . '" id="' . $path . '"';
?>

        <label for="<?php echo htmlspecialchars($path) ?>"><?php echo $name ?>
        <?php if (!empty($opts['doc']) || !empty($opts['wiki'])): ?>

            <?php if (!empty($opts['doc'])) { ?><a href="<?php echo $opts['doc']  ?>" target="documentation"><img class="icon" src="../<?php echo $GLOBALS['cfg']['ThemePath'] ?>/original/img/b_help.png" width="11" height="11" alt="Doc" title="<?php echo $GLOBALS['strDocu'] ?>" /><?php } ?>
            <?php if (!empty($opts['wiki'])){ ?><a href="<?php echo $opts['wiki'] ?>" target="wiki"><img class="icon" src="../<?php echo $GLOBALS['cfg']['ThemePath'] ?>/original/img/b_info.png" width="11" height="11" alt="Wiki" title="Wiki" /><?php } ?>

        <?php endif; ?>
        <?php if (!empty($description)) { ?><?php echo $description ?><?php } ?>

    <?php
    switch ($type) {
        case 'text':
            echo '<input type="text" size="50" ' . $name_id . $field_class
                . ' value="' . htmlspecialchars($value) . '" />';
          break;
        case 'checkbox':
            echo '<input type="checkbox" ' . $name_id
              . ($value ? ' checked="checked"' : '') . ' />';
          break;
        case 'select':
            echo '<select ' . $name_id . $field_class . '>';
            $escape = !(isset($opts['values_escaped']) && $opts['values_escaped']);
            $values_disabled = isset($opts['values_disabled'])
                ? array_flip($opts['values_disabled']) : array();
            foreach ($opts['values'] as $opt_value => $opt_name) {
                // set names for boolean values
                if (is_bool($opt_name)) {
                    $opt_name = $GLOBALS['strSetup' . ($opt_value ? 'True' : 'False')];
                }
                // cast boolean values to integers
                $display_value = is_bool($opt_value) ? (int) $opt_value : $opt_value;
                // escape if necessary
                if ($escape) {
                    $display = htmlspecialchars($opt_name);
                    $display_value = htmlspecialchars($display_value);
                } else {
                    $display = $opt_name;
                }
                // compare with selected value
                // boolean values are cast to integers when used as array keys
                $selected = is_bool($value)
                    ? (int) $value === $opt_value
                    : $opt_value === $value;
                echo '<option value="' . $display_value . '"'
                    . ($selected ? ' selected="selected"' : '')
                    . (isset($values_disabled[$opt_value]) ? ' disabled="disabled"' : '')
                    . '>' . $display . '</option>';
            }
            echo '</select>';
            break;
        case 'list':
            echo '<textarea cols="40" rows="5" ' . $name_id . $field_class . '>'
                . htmlspecialchars(implode("\n", $value))
                . '</textarea>';
            break;
    }
    if (isset($opts['setvalue']) && $opts['setvalue']) {
        ?>
        <a class="set-value" href="#<?php echo "$path={$opts['setvalue']}" ?>" title="<?php echo sprintf($GLOBALS['strSetupSetValue'], htmlspecialchars($opts['setvalue'])) ?>" style="display:none"><img alt="set-value" src="../<?php echo $GLOBALS['cfg']['ThemePath'] ?>/original/img/b_edit.png" width="16" height="16" />
        <?php
    }
    if (isset($opts['show_restore_default']) && $opts['show_restore_default']) {
        ?>
        <a class="restore-default" href="#<?php echo $path ?>" title="<?php echo $GLOBALS['strSetupRestoreDefaultValue'] ?>" style="display:none"><img alt="restore-default" src="../<?php echo $GLOBALS['cfg']['ThemePath'] ?>/original/img/s_reload.png" width="16" height="16" />
        <?php
    }
    // this must match with displayErrors() in scripts.js
    if (isset($opts['errors']) && !empty($opts['errors'])) {
        echo "\n
";
        foreach ($opts['errors'] as $error) {
            echo '
' . htmlspecialchars($error) . '
';
        }
        echo '
';
    }
    ?>

<?php
}

/**
 * Displays bottom part of a fieldset
 *
 * @param array $js_array
 */
function display_fieldset_bottom()
{
?>

        <input type="submit" name="submit_save" value="<?php echo $GLOBALS['strSave'] ?>" class="green" />
        <input type="button" name="submit_reset" value="<?php echo $GLOBALS['strReset'] ?>" />

</fieldset>

<?php
}

/**
 * Displays simple bottom part of a fieldset (without submit buttons)
 */
function display_fieldset_bottom_simple()
{
?>

</fieldset>

<?php
}

/**
 * Closes form tabs
 */
function display_tabs_bottom() {
    echo "
\n";
}

/**
 * Displays bottom part of the form
 */
function display_form_bottom()
{
    echo "</form>\n";
}

/**
 * Appends JS validation code to $js_array
 *
 * @param string $field_id
 * @param string $validator
 * @param array  $js_array
 */
function js_validate($field_id, $validator, &$js_array) {
    $js_array[] = "validateField('$field_id', '$validator', true)";
}

/**
 * Displays JavaScript code
 *
 * @param array $js_array
 */
function display_js($js_array) {
    if (empty($js_array)) {
        return;
    }
?>

<?php
}

/**
 * Displays error list
 *
 * @param string $name
 * @param array  $error_list
 */
function display_errors($name, $error_list) {
    echo '
';
    echo '
' . htmlspecialchars($name) . '
';
    foreach ($error_list as $error) {
        echo '
' . htmlspecialchars($error) . '
';
    }
    echo '
';
}
?>