text:
package manon.service.app.impl;

import manon.util.basetest.AbstractIT;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;

class TrxDemoServiceIT extends AbstractIT {

    @Test
    void errorShouldRollbackTransaction() {
        //GIVEN some users in db
        long nbUsersBefore = userService.count();

        //WHEN create 1 user then throw an Error in the same transaction
        Assertions.assertThatThrownBy(() -> trxDemoService.createSampleUserThenFail(Error.class))
            .isInstanceOf(Error.class);

        //THEN Error should rollback transaction
        long nbUsersAfter = userService.count();
        Assertions.assertThat(nbUsersAfter).isEqualTo(nbUsersBefore);
    }

    @Test
    void runtimeExceptionShouldRollbackTransaction() {
        //GIVEN some users in db
        long nbUsersBefore = userService.count();

        //WHEN create 1 user then throw a RuntimeException in the same transaction
        Assertions.assertThatThrownBy(() -> trxDemoService.createSampleUserThenFail(RuntimeException.class))
            .isInstanceOf(RuntimeException.class);

        //THEN RuntimeException should rollback transaction
        long nbUsersAfter = userService.count();
        Assertions.assertThat(nbUsersAfter).isEqualTo(nbUsersBefore);
    }

    @Test
    void exceptionShouldNotRollbackTransaction() {
        //GIVEN some users in db
        long nbUsersBefore = userService.count();

        //WHEN create 1 user then throw an Exception in the same transaction
        Assertions.assertThatThrownBy(() -> trxDemoService.createSampleUserThenFail(Exception.class))
            .isInstanceOf(Exception.class);

        //THEN Exception should NOT rollback transaction
        long nbUsersAfter = userService.count();
        Assertions.assertThat(nbUsersAfter).isEqualTo(nbUsersBefore + 1);
    }
}


text:
package org.daisy.pipeline.job;

import java.util.function.Consumer;

public interface StatusNotifier {

	/**
	 * Get notified of changes in job status.
	 */
	public void listen(Consumer<Job.Status> listener);
	public void unlisten(Consumer<Job.Status> listener);

}

redpajama_set_name: RedPajamaGithub


text:
$script:DSCModuleName      = 'xSystemSecurity'
$script:DSCResourceName    = 'MSFT_xFileSystemAccessRule'

[String] $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
     (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
    & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\'))
}

Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force
$TestEnvironment = Initialize-TestEnvironment `
    -DSCModuleName $script:DSCModuleName `
    -DSCResourceName $script:DSCResourceName `
    -TestType Unit

Import-Module (Join-Path $script:moduleRoot "\DSCResources\$script:DSCResourceName\$script:DSCResourceName.psm1") -Force

try
{
    Describe "xFileSystemAccessRule" {
        InModuleScope -ModuleName $script:DSCResourceName {

            Mock Set-Acl {}
            Mock Test-Path { return $true }

            Context "No permissions exist for a user, but should" {
                $testParams = @{
                    Path = "$($env:SystemDrive)\TestFolder"
                    Identity = "NT AUTHORITY\NETWORK SERVICE"
                    Rights = @("Read","Synchronize")
                }
                Mock Get-Acl {
                    return @{
                        Access = @()
                    } | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru `
                      | Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru
                }

                It "should return absent from the get method" {
                    (Get-TargetResource @testParams).Ensure | Should Be "Absent"
                }

                It "should return false from the test method" {
                    Test-TargetResource @testParams | Should Be $false
                }

                It "should add the permission in the set method" {
                    Set-TargetResource @testParams
                    Assert-MockCalled -CommandName Set-Acl
                }
            }

            Context "A permission exists and should, but the rights are incorrect" {
                $testParams = @{
                    Path = "$($env:SystemDrive)\TestFolder"
                    Identity = "NT AUTHORITY\NETWORK SERVICE"
                    Rights = @("Read","Synchronize")
                }
                Mock Get-Acl {
                    return @{
                        Access = @(
                            @{
                                IdentityReference = $testParams.Identity
                                FileSystemRights = [System.Security.AccessControl.FileSystemRights]::FullControl
                            }
                        )
                    } | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru `
                      | Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru
                }

                It "should return present from the get method" {
                    (Get-TargetResource @testParams).Ensure | Should Be "Present"
                }

                It "should return false from the test method" {
                    Test-TargetResource @testParams | Should Be $false
                }

                It "should add the permission in the set method" {
                    Set-TargetResource @testParams
                    Assert-MockCalled -CommandName Set-Acl
                }
            }

            Context "A permission exists and should, including correct rights" {
                $testParams = @{
                    Path = "$($env:SystemDrive)\TestFolder"
                    Identity = "NT AUTHORITY\NETWORK SERVICE"
                    Rights = @("Read","Synchronize")
                }
                Mock Get-Acl {
                    return @{
                        Access = @(
                            @{
                                IdentityReference = $testParams.Identity
                                FileSystemRights = [System.Security.AccessControl.FileSystemRights]$testParams.Rights
                            }
                        )
                    } | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru `
                      | Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru
                }

                It "should return present from the get method" {
                    (Get-TargetResource @testParams).Ensure | Should Be "Present"
                }

                It "should return true from the test method" {
                    Test-TargetResource @testParams | Should Be $true
                }
            }

            Context "A permission exists that shouldn't" {
                $testParams = @{
                    Path = "$($env:SystemDrive)\TestFolder"
                    Identity = "NT AUTHORITY\NETWORK SERVICE"
                    Ensure = "Absent"
                }
                Mock Get-Acl {
                    return @{
                        Access = @(
                            @{
                                IdentityReference = $testParams.Identity
                                FileSystemRights = [System.Security.AccessControl.FileSystemRights]::FullControl
                            }
                        )
                    } | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru `
                      | Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru
                }

                It "should return present from the get method" {
                    (Get-TargetResource @testParams).Ensure | Should Be "Present"
                }

                It "should return false from the test method" {
                    Test-TargetResource @testParams | Should Be $false
                }

                It "should add the permission in the set method" {
                    Set-TargetResource @testParams
                    Assert-MockCalled -CommandName Set-Acl
                }
            }

            Context "A permission doesn't exist and shouldn't" {
                $testParams = @{
                    Path = "$($env:SystemDrive)\TestFolder"
                    Identity = "NT AUTHORITY\NETWORK SERVICE"
                    Ensure = "Absent"
                }
                Mock Get-Acl {
                    return @{
                        Access = @()
                    } | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru `
                      | Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru
                }

                It "should return absent from the get method" {
                    (Get-TargetResource @testParams).Ensure | Should Be "Absent"
                }

                It "should return true from the test method" {
                    Test-TargetResource @testParams | Should Be $true
                }
            }

            Mock Test-Path { return $false }

            Context "A path doesn't exist" {
                $testParams = @{
                    Path = "$($env:SystemDrive)\TestFolder"
                    Identity = "NT AUTHORITY\NETWORK SERVICE"
                    Rights = @("Read","Synchronize")
                }

                It "should throw from the get method" {
                    { Get-TargetResource @testParams } | Should Throw
                }

                It "should throw from the test method" {
                    { Test-TargetResource @testParams } | Should Throw
                }

                It "should throw from the set method" {
                    { Set-TargetResource @testParams } | Should Throw
                }
            }
        }
    }
}
finally
{
    Restore-TestEnvironment -TestEnvironment $TestEnvironment
}


text:
package weka.classifiers.bayes.net;

import weka.core.FastVector;

// Referenced classes of package weka.classifiers.bayes.net:
//            EditableBayesNet

class > extends > {

    static final long serialVersionUID = 1L;
    final EditableBayesNet this$0;

    public void redo() {
        try {
            alignRight(m_nodes);
        }
        catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    public String getUndoMsg() {
        return (new StringBuilder()).append("Returning ").append(m_nodes.size()).append(" from aliging nodes to the right.").toString();
    }

    public String getRedoMsg() {
        return (new StringBuilder()).append("Aligning ").append(m_nodes.size()).append(" nodes to the right.").toString();
    }

    public (FastVector fastvector) {
        this$0 = EditableBayesNet.this;
        super(EditableBayesNet.this, fastvector);
    }
}


text:
#include "ros/ros.h"
#include "std_msgs/String.h"

#include <sstream>
#include "math.h"
#include <vector>

#include "StaticPoiConstants.h"
#include "EventTriggerUtility.h"
#include "PerformTaskConstants.h"
#include "FriendRobot.h"
#include "Robot.h"
#include "Poi.h"
#include "StaticPoi.h"
#include "EventNode.h"
#include "elderly_care_simulation/EventTrigger.h"

using namespace elderly_care_simulation;

#include <unistd.h>

#include "gtest/gtest.h"

// Publishers
ros::Publisher eventTriggerPub;

// Subscribers
ros::Subscriber eventTriggerSub;

// Service Clients
ros::ServiceClient performTaskClient;

// Store received messages
std::vector<EventTrigger> receivedEventTriggers;

FriendRobot theFriend;

class FriendRobotTest : public ::testing::Test {

    protected:

        virtual void SetUp() {
            receivedEventTriggers.clear();
            theFriend.currentLocationState = FriendRobot::AT_HOME;
        }

};

/**
 * Tests that the FriendRobot responds correctly to Friend events
 */
TEST_F(FriendRobotTest, friendRespondsToFriendRequests) {

    // Send relevant message to FriendRobot
    EventTrigger msg;
    msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST;
    msg.event_type = EVENT_TRIGGER_EVENT_TYPE_FRIEND;
    eventTriggerPub.publish(msg);

    // Wait until message is received
    ros::Rate loop_rate(10);
    while (receivedEventTriggers.size() == 0) {
        loop_rate.sleep();
        ros::spinOnce();
    }

    ASSERT_EQ(FriendRobot::GOING_TO_RESIDENT, theFriend.currentLocationState);
}

/**
 * Tests that the FriendRobot does not respond to non-Friend events
 */
TEST_F(FriendRobotTest, friendDoesNotRespondToNonFriendRequests) {

    // Send irrelevant message to FriendRobot
    EventTrigger msg;
    msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST;
    msg.event_type = EVENT_TRIGGER_EVENT_TYPE_RELATIVE;
    eventTriggerPub.publish(msg);

    // Wait until message is received
    ros::Rate loop_rate(10);
    while (receivedEventTriggers.size() == 0) {
        loop_rate.sleep();
        ros::spinOnce();
    }

    ASSERT_EQ(FriendRobot::AT_HOME, theFriend.currentLocationState);
}

/**
 * Tests that the FriendRobot sends the correct event reply
 */
TEST_F(FriendRobotTest, friendSendsCorrectEventReply) {

    theFriend.eventTriggerReply();

    // Wait until message is received
    ros::Rate loop_rate(10);
    while (receivedEventTriggers.size() == 0) {
        loop_rate.sleep();
        ros::spinOnce();
    }

    elderly_care_simulation::EventTrigger msg = receivedEventTriggers[0];
    ASSERT_EQ(EVENT_TRIGGER_MSG_TYPE_RESPONSE, msg.msg_type);
    ASSERT_EQ(EVENT_TRIGGER_EVENT_TYPE_FRIEND, msg.event_type);
    ASSERT_EQ(EVENT_TRIGGER_RESULT_SUCCESS, msg.result);
}

// Used to wait for msg is received
void eventTriggerCallback(elderly_care_simulation::EventTrigger msg) {
    receivedEventTriggers.push_back(msg);
}

// Function wrapper for method
void friendEventTriggerCallback(elderly_care_simulation::EventTrigger msg) {
    theFriend.eventTriggerCallback(msg);
}

int main(int argc, char** argv) {

    ros::init(argc, argv, "TestFriendRobot");
    ros::NodeHandle nodeHandle;
    ros::Rate loop_rate(10);

    eventTriggerPub = nodeHandle.advertise<elderly_care_simulation::EventTrigger>("event_trigger",1000, true);
    eventTriggerSub = nodeHandle.subscribe<elderly_care_simulation::EventTrigger>("event_trigger",1000, eventTriggerCallback);

    theFriend.eventTriggerPub = nodeHandle.advertise<elderly_care_simulation::EventTrigger>("event_trigger",1000, true);
    theFriend.eventTriggerSub = nodeHandle.subscribe<elderly_care_simulation::EventTrigger>("event_trigger",1000, friendEventTriggerCallback);

    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
%NPM: zoroaster%

[![Build Status](https://travis-ci.org/contexttesting/zoroaster.svg?branch=master)](https://travis-ci.org/contexttesting/zoroaster)
[![Build status](https://ci.appveyor.com/api/projects/status/1gc2cqf97ty69mfw/branch/master?svg=true)](https://ci.appveyor.com/project/zavr-1/zoroaster/branch/master)

[](https://contexttesting.com) _Zoroaster_ is a modern JavaScript testing framework for _Node.js_. It introduces the concept of test contexts, which aim in helping to provide documentable and re-usable test infrastructure, across spec files in a single package, as well as across packages. It's a completely new and developer-friendly approach to writing tests, which greatly improves productivity, testing experience and the reliability on tests. In addition, it allows to write _ES6_ module syntax without `Babel`.

For example, you can make use of `https-context` to set-up a mock HTTP server with configurable responses and `temp-context` to create and remove a temp directory ready for each test without having to worry about repetitively writing the same code across projects. The way tests are written allows to see IDE suggestions for every method and property available in a context. Because these packages are maintained as separate pieces of software, they are also tested which means that there are less chances of an error in test set-ups which could lead to false-positive results.

[](http://www.crystalinks.com/zoroaster.html)[](http://nodejs.tools) Are you fed up with `mocha` or have you had enough `chai` in your life? Is it not time to say good-bye to the old stereotype that the same software must be used every day? Say no more, _Zoroaster_ is here to save our souls and bring a change.

---

```fs
yarn add -D zoroaster
```

```fs
npm i --save-dev zoroaster
```

%~%

## Table Of Contents

%TOC%

%~%


text:
#ifndef INC_DYNAMICLM_H
#define INC_DYNAMICLM_H

#include <algorithm>
#include <vector>
#include "perfectHash.h"
#include "RandLMCache.h"
#include "types.h"
#include "vocab.h"

/*
 * DynamicLM manipulates LM
 */
using randlm::BitFilter;
using randlm::Cache;

const bool strict_checks_ = false;

//! @todo ask abby2
template<typename T>
class OnlineRLM: public PerfectHash<T>
{
public:
  OnlineRLM(uint16_t MBs, int width, int bucketRange, count_t order,
            Moses::Vocab* v, float qBase = 8): PerfectHash<T>(MBs, width, bucketRange, qBase),
    vocab_(v), bAdapting_(false), order_(order), corpusSize_(0), alpha_(0) {
    UTIL_THROW_IF2(vocab_ == 0, "Vocab object not set");
    //instantiate quantizer class here
    cache_ = new Cache<float>(8888.8888, 9999.9999); // unknown_value, null_value
    alpha_ = new float[order_ + 1];
    for(count_t i = 0; i <= order_; ++i)
      alpha_[i] = i * log10(0.4);
    cerr << "Initialzing auxillary bit filters...\n";
    bPrefix_ = new BitFilter(this->cells_);
    bHit_ = new BitFilter(this->cells_);
  }
  OnlineRLM(FileHandler* fin, count_t order):
    PerfectHash<T>(fin), bAdapting_(true), order_(order), corpusSize_(0) {
    load(fin);
    cache_ = new Cache<float>(8888.8888, 9999.9999); // unknown_value, null_value
    alpha_ = new float[order_ + 1];
    for(count_t i = 0; i <= order_; ++i)
      alpha_[i] = i * log10(0.4);
  }
  ~OnlineRLM() {
    delete[] alpha_;
    if(bAdapting_) delete vocab_;
    else vocab_ = NULL;
    delete cache_;
    delete bPrefix_;
    delete bHit_;
  }
  float getProb(const wordID_t* ngram, int len, const void** state);
  //float getProb2(const wordID_t* ngram, int len, const void** state);
  bool insert(const std::vector<string>& ngram, const int value);
  bool update(const std::vector<string>& ngram, const int value);
  int query(const wordID_t* IDs, const int len);
  int sbsqQuery(const std::vector<string>& ngram, int* len,
                bool bStrict = false);
  int sbsqQuery(const wordID_t* IDs, const int len, int* codes,
                bool bStrict = false);
  void remove(const std::vector<string>& ngram);
  count_t heurDelete(count_t num2del, count_t order = 5);
  uint64_t corpusSize() {
    return corpusSize_;
  }
  void corpusSize(uint64_t c) {
    corpusSize_ = c;
  }
  void clearCache() {
    if(cache_) cache_->clear();
  }
  void save(FileHandler* fout);
  void load(FileHandler* fin);
  void randDelete(int num2del);
  int countHits();
  int countPrefixes();
  int cleanUpHPD();
  void clearMarkings();
  void removeNonMarked();
  Moses::Vocab* vocab_;
protected:
  void markQueried(const uint64_t& index);
  void markQueried(hpdEntry_t& value);
  bool markPrefix(const wordID_t* IDs, const int len, bool bSet);
private:
  const void* getContext(const wordID_t* ngram, int len);
  const bool bAdapting_; // used to signal adaptation of model
  const count_t order_; // LM order
  uint64_t corpusSize_; // total training corpus size
  float* alpha_;  // backoff constant
  Cache<float>* cache_;
  BitFilter* bPrefix_;
  BitFilter* bHit_;
};

template<typename T>
bool OnlineRLM<T>::insert(const std::vector<string>& ngram, const int value)
{
  int len = ngram.size();
  wordID_t wrdIDs[len];
  uint64_t index(this->cells_ + 1);
  for(int i = 0; i < len; ++i)
    wrdIDs[i] = vocab_->GetWordID(ngram[i]);
  index = PerfectHash<T>::insert(wrdIDs, len, value);
  if(value > 1 && len < order_)
    markPrefix(wrdIDs, ngram.size(), true); // mark context
  // keep track of total items from training data minus "<s>"
  if(ngram.size() == 1 && (!bAdapting_)) // hack to not change corpusSize when adapting
    corpusSize_ += (wrdIDs[0] != vocab_->GetBOSWordID()) ? value : 0;
  if(bAdapting_ && (index < this->cells_)) // mark to keep while adapting
    markQueried(index);
  return true;
}

template<typename T>
bool OnlineRLM<T>::update(const std::vector<string>& ngram, const int value)
{
  int len = ngram.size();
  std::vector<wordID_t> wrdIDs(len);
  uint64_t index(this->cells_ + 1);
  hpdEntry_t hpdItr;
  vocab_->MakeOpen();
  for(int i = 0; i < len; ++i)
    wrdIDs[i] = vocab_->GetWordID(ngram[i]);
  // if updating, minimize false positives by pre-checking if context already in model
  bool bIncluded(true);
  if(value > 1 && len < (int)order_)
    bIncluded = markPrefix(&wrdIDs[0], ngram.size(), true); // mark context
  if(bIncluded) { // if context found
    bIncluded = PerfectHash<T>::update2(&wrdIDs[0], len, value, hpdItr, index);
    if(index < this->cells_) {
      markQueried(index);
    } else if(hpdItr != this->dict_.end()) markQueried(hpdItr);
  }

  return bIncluded;
}
template<typename T>
int OnlineRLM<T>::query(const wordID_t* IDs, int len)
{
  uint64_t filterIdx = 0;
  hpdEntry_t hpdItr;
  int value(0);
  value = PerfectHash<T>::query(IDs, len, hpdItr, filterIdx);
  if(value != -1) {
    if(hpdItr != this->dict_.end()) {
      //markQueried(hpdItr);  // mark this event as "hit"
      value -= ((value & this->hitMask_) != 0) ? this->hitMask_ : 0; // check for previous hit marks
    } else {
    	UTIL_THROW_IF2(filterIdx >= this->cells_,
    			"Out of bound: " << filterIdx);
      //markQueried(filterIdx);
    }
  }
  return value > 0 ? value : 0;
}

template<typename T>
bool OnlineRLM<T>::markPrefix(const wordID_t* IDs, const int len, bool bSet)
{
  if(len <= 1) return true; // only do this for for ngrams with context
  static Cache<int> pfCache(-1, -1); // local prefix cache
  int code(0);
  if(!pfCache.checkCacheNgram(IDs, len - 1, &code, NULL)) {
    hpdEntry_t hpdItr;
    uint64_t filterIndex(0);
    code = PerfectHash<T>::query(IDs, len - 1, hpdItr, filterIndex); // hash IDs[0..len-1]
    if(code == -1) { // encountered false positive in pipeline
      cerr << "WARNING: markPrefix(). The O-RLM is *not* well-formed.\n";
      // add all prefixes or return false;
      return false;
    }
    if(filterIndex != this->cells_ + 1) {
      UTIL_THROW_IF2(hpdItr != this->dict_.end(), "Error");
      if(bSet) bPrefix_->setBit(filterIndex); // mark index
      else bPrefix_->clearBit(filterIndex);   // unset index
    } else {
      UTIL_THROW_IF2(filterIndex != this->cells_ + 1, "Error");
      //how to handle hpd prefixes?
    }
    if(pfCache.nodes() > 10000) pfCache.clear();
    pfCache.setCacheNgram(IDs, len - 1, code, NULL);
  }
  return true;
}

template<typename T>
void OnlineRLM<T>::markQueried(const uint64_t& index)
{
  bHit_->setBit(index);
  //cerr << "filter[" << index << "] = " << this->filter_->read(index) << endl;
}

template<typename T>
void OnlineRLM<T>::markQueried(hpdEntry_t& value)
{
  // set high bit of counter to indicate "hit" status
  value->second |= this->hitMask_;
}

template<typename T>
void OnlineRLM<T>::remove(const std::vector<string>& ngram)
{
  wordID_t IDs[ngram.size()];
  for(count_t i = 0; i < ngram.size(); ++i)
    IDs[i] = vocab_->GetWordID(ngram[i]);
  PerfectHash<T>::remove(IDs, ngram.size());
}

template<typename T>
count_t OnlineRLM<T>::heurDelete(count_t num2del, count_t order)
{
  count_t deleted = 0;
  cout << "Deleting " << num2del << " of order "<< order << endl;
  // delete from filter first
  int full = *std::max_element(this->idxTracker_, this->idxTracker_
                               + this->totBuckets_);
  for(; full > 0; --full) // delete from fullest buckets first
    for(int bk = 0; bk < this->totBuckets_; ++bk) {
      if(deleted >= num2del) break;
      if(this->idxTracker_[bk] == full) {        // if full
        uint64_t first = bk * this->bucketRange_,
                 last = first + this->bucketRange_;
        for(uint64_t row = first; row < last; ++row) {  // check each row
          if(!(bHit_->testBit(row) || bPrefix_->testBit(row) )) {
            if(this->filter_->read(row) != 0) {
              PerfectHash<T>::remove(row);  // remove from filter
              ++deleted;
            }
          }
        }
      }
    }
  if(deleted < num2del) {
    // remove from hpd
    cerr << "TODO! HPD deletions\n";
  }
  cerr << "Total deleted = " << deleted << endl;
  return deleted;
}

template<typename T>
int OnlineRLM<T>::sbsqQuery(const std::vector<string>& ngram, int* codes,
                            bool bStrict)
{
  wordID_t IDs[ngram.size()];
  for(count_t i = 0; i < ngram.size(); ++i)
    IDs[i] = vocab_->GetWordID(ngram[i]);
  return sbsqQuery(IDs, ngram.size(), codes, bStrict);
}

template<typename T>
int OnlineRLM<T>::sbsqQuery(const wordID_t* IDs, const int len, int* codes,
                            bool bStrict)
{
  uint64_t filterIdx = 0;
  int val(0), fnd(0);
  hpdEntry_t hpdItr;
  for(int i = len - 1; i >= 0; --i) { // do subsequence filtering
    //if(IDs[i] == Vocab::kOOVWordID) break;
    val = PerfectHash<T>::query(&IDs[i], len - i, hpdItr, filterIdx);
    if(val != -1) { // if event found
      fnd = len - i; // increment found sequence
      if(hpdItr != this->dict_.end()) {
        val -= ((val & this->hitMask_) != 0) ? this->hitMask_ : 0; // account for previous hit marks
      }
    } else if(bStrict) {
      break;
    }
    // add to value array
    codes[i] = val > 0 ? val : 0;
  }
  while(bStrict && (fnd > 1)) { // do checks the other way
    val = PerfectHash<T>::query(&IDs[len - fnd], fnd - 1, hpdItr, filterIdx);
    if(val != -1) break; // if anything found
    else --fnd; // else decrement found
  }

  return fnd;
}

template<typename T>
float OnlineRLM<T>::getProb(const wordID_t* ngram, int len,
                            const void** state)
{
  static const float oovprob = log10(1.0 / (static_cast<float>(vocab_->Size()) - 1));
  float logprob(0);
  const void* context = (state) ? *state : 0;
  // if full ngram and prob not in cache
  if(!cache_->checkCacheNgram(ngram, len, &logprob, &context)) {
    // get full prob and put in cache
    int num_fnd(0), den_val(0);
    int *in = new int[len]; // in[] keeps counts of increasing order numerator
    for(int i = 0; i < len; ++i) in[i] = 0;
    for(int i = len - 1; i >= 0; --i) {
      if(ngram[i] == vocab_->GetkOOVWordID()) break;  // no need to query if OOV
      in[i] = query(&ngram[i], len - i);
      if(in[i] > 0) {
        num_fnd = len - i;
      } else if(strict_checks_) break;
    }
    while(num_fnd > 1) { // get lower order count
      //get sub-context of size one less than length found (exluding target)
      if(((den_val = query(&ngram[len - num_fnd], num_fnd - 1)) > 0) &&
          (den_val >= in[len - num_fnd]) && (in[len - num_fnd] > 0)) {
        break;
      } else --num_fnd; // else backoff to lower ngram order
    }
    if(num_fnd == 1 && (in[len - 1] < 1)) // sanity check for unigrams
      num_fnd = 0;
    switch(num_fnd) { // find prob (need to refactor into precomputation)
    case 0: // OOV
      logprob = alpha_[len] + oovprob;
      break;
    case 1: // unigram found only
      UTIL_THROW_IF2(in[len - 1] <= 0, "Error");
      logprob = alpha_[len - 1] + (corpusSize_ > 0 ?
                                   log10(static_cast<float>(in[len - 1]) / static_cast<float>(corpusSize_)) : 0);
      //logprob = alpha_[len - 1] +
      //log10(static_cast<float>(in[len - 1]) / static_cast<float>(corpusSize_));
      break;
    default:
      UTIL_THROW_IF2(den_val <= 0, "Error");
      //if(subgram == in[len - found]) ++subgram; // avoid returning zero probs????
      logprob = alpha_[len - num_fnd] +
                log10(static_cast<float>(in[len - num_fnd]) / static_cast<float>(den_val));
      break;
    }
    // need unique context
    context = getContext(&ngram[len - num_fnd], num_fnd);
    // put whatever was found in cache
    cache_->setCacheNgram(ngram, len, logprob, context);
  } // end checkCache
  return logprob;
}

template<typename T>
const void* OnlineRLM<T>::getContext(const wordID_t* ngram, int len)
{
  int dummy(0);
  float**addresses = new float*[len];  // only interested in addresses of cache
  UTIL_THROW_IF2(cache_->getCache2(ngram, len, &addresses[0], &dummy) != len,
		  "Error");
  // return address of cache node

  float *addr0 = addresses[0];
  free( addresses );
  return (const void*)addr0;
}

template<typename T>
void OnlineRLM<T>::randDelete(int num2del)
{
  int deleted = 0;
  for(uint64_t i = 0; i < this->cells_; i++) {
    if(this->filter_->read(i) != 0) {
      PerfectHash<T>::remove(i);
      ++deleted;
    }
    if(deleted >= num2del) break;
  }
}

template<typename T>
int OnlineRLM<T>::countHits()
{
  int hit(0);
  for(uint64_t i = 0; i < this->cells_; ++i)
    if(bHit_->testBit(i)) ++hit;
  iterate(this->dict_, itr)
  if((itr->second & this->hitMask_) != 0)
    ++hit;
  cerr << "Hit count = " << hit << endl;
  return hit;
}

template<typename T>
int OnlineRLM<T>::countPrefixes()
{
  int pfx(0);
  for(uint64_t i = 0; i < this->cells_; ++i)
    if(bPrefix_->testBit(i)) ++pfx;
  //TODO::Handle hpdict prefix counts
  cerr << "Prefix count (in filter) = " << pfx << endl;
  return pfx;
}

template<typename T>
int OnlineRLM<T>::cleanUpHPD()
{
  cerr << "HPD size before = " << this->dict_.size() << endl;
  std::vector<string> vDel, vtmp;
  iterate(this->dict_, itr) {
    if(((itr->second & this->hitMask_) == 0) &&  // if not hit during testing
        (Utils::splitToStr(itr->first, vtmp, "¬") >= 3)) {  // and higher order ngram
      vDel.push_back(itr->first);
    }
  }
  iterate(vDel, vitr)
  this->dict_.erase(*vitr);
  cerr << "HPD size after = " << this->dict_.size() << endl;
  return vDel.size();
}

template<typename T>
void OnlineRLM<T>::clearMarkings()
{
  cerr << "clearing all event hits\n";
  bHit_->reset();
  count_t* value(0);
  iterate(this->dict_, itr) {
    value = &itr->second;
    *value -= ((*value & this->hitMask_) != 0) ? this->hitMask_ : 0;
  }
}

template<typename T>
void OnlineRLM<T>::save(FileHandler* fout)
{
  cerr << "Saving ORLM...\n";
  // save vocab
  vocab_->Save(fout);
  fout->write((char*)&corpusSize_, sizeof(corpusSize_));
  fout->write((char*)&order_, sizeof(order_));
  bPrefix_->save(fout);
  bHit_->save(fout);
  // save everything else
  PerfectHash<T>::save(fout);
  cerr << "Finished saving ORLM." << endl;
}

template<typename T>
void OnlineRLM<T>::load(FileHandler* fin)
{
  cerr << "Loading ORLM...\n";
  // load vocab first
  vocab_ = new Moses::Vocab(fin);
  UTIL_THROW_IF2(vocab_ == 0, "Vocab object not set");
  fin->read((char*)&corpusSize_, sizeof(corpusSize_));
  cerr << "\tCorpus size = " << corpusSize_ << endl;
  fin->read((char*)&order_, sizeof(order_));
  cerr << "\tModel order = " << order_ << endl;
  bPrefix_ = new BitFilter(fin);
  bHit_ = new BitFilter(fin);
  // load everything else
  PerfectHash<T>::load(fin);
}

template<typename T>
void OnlineRLM<T>::removeNonMarked()
{
  cerr << "deleting all unused events\n";
  int deleted(0);
  for(uint64_t i = 0; i < this->cells_; ++i) {
    if(!(bHit_->testBit(i) || bPrefix_->testBit(i))
        && (this->filter_->read(i) != 0)) {
      PerfectHash<T>::remove(i);
      ++deleted;
    }
  }
  deleted += cleanUpHPD();
  cerr << "total removed from ORLM = " << deleted << endl;
}

/*
template<typename T>
float OnlineRLM<T>::getProb2(const wordID_t* ngram, int len, const void** state) {
  static const float oovprob = log10(1.0 / (static_cast<float>(vocab_->size()) - 1));
  float log_prob(0);
  const void* context_state(NULL);
  int found;
  int* denom_codes[order_];
  int* num_codes[order_ + 1];
  int denom_found(0);
  cerr << "length=" << len << endl;
  // constrain cache queries using model assumptions
  int denom_len = cache_->getCache(ngram, len - 1, &denom_codes[0], &denom_found);
  cerr << "denom_len = " << denom_len << endl;
  int num_len = cache_->getCache(&ngram[len - denom_len - 1], denom_len + 1,
                                          &num_codes[0], &found);
  cerr << "num_len= " << num_len << endl;
  // keed reducing ngram size until both denominator and numerator are found
  // allowed to leave kUnknownCode in cache because we check for this.
  found = num_len; // guaranteed to be <= denom_len + 1
  // still check for OOV
  for (int i = len - found; i < len; ++i)
    if (ngram[i] == Vocab::kOOVWordID) {
        found = len - i - 1;
    }
  // check for relative estimator
  while(found > 1) {
    if(*denom_codes[found-1] == cache_unk_ &&
      ((*denom_codes[found-1] = query(&ngram[len-found], found-1)) == 0)) {
        //!struct_->query(&ngram[len-*found], *found-1, kMainEventIdx, denom_codes[*found-1])) {
      *num_codes[found] = cache_unk_;
    } else {
      if(*num_codes[found] != cache_unk_ ||
        ((*num_codes[found] = query(&ngram[len-found], found)) <= *denom_codes[found-1]))
        //  struct_->query(&ngram[len-*found], *found, kMainEventIdx,
        //                 num_codes[*found], *denom_codes[*found-1]))
        break;
    }
    --found;
  }
  // didn't find bigram numerator or unigram denominator
  if (found == 1)
    found = *num_codes[1] != cache_unk_
      || ((*num_codes[1] = query(&ngram[len - 1], 1)) != 0);
      //struct_->query(&ngram[len - 1], 1, kMainEventIdx, num_codes[1]);
  // ....
  // return estimate applying correct backoff score (precomputed)
  // store full log prob with complete ngram (even if backed off)
  switch (found) {
  case 0: // no observation: assign prob of 'new word' in training data
    log_prob = alpha_[len] + oovprob;
    //log_prob = stupid_backoff_log10_[len] + uniform_log10prob_;
    break;
  case 1: // unigram over whole corpus
    log_prob = alpha_[len - 1] +
      log10(static_cast<float>(*num_codes[1]) / static_cast<float>(corpusSize_));
    //log_prob = log_quantiser_->getLog10Value(*num_codes[1]) - corpus_size_log10_
    //  + stupid_backoff_log10_[len - 1];  // precomputed
    break;
  default: // otherwise use both statistics and (possibly zero) backoff weight
    log_prob = alpha_[len - found] +
      log10(static_cast<float>(*num_codes[found]) / static_cast<float>(*denom_codes[found-1]));
    //log_prob = log_quantiser_->getLog10Value(*num_codes[*found ])
    //  - log_quantiser_->getLog10Value(*denom_codes[*found - 1])
    //  + stupid_backoff_log10_[len - *found];
  }
  context_state = (const void*)num_codes[found == len ? found - 1 : found];;
  //probCache_->store(len, log_prob, context_state);
  if (state)
    *state = context_state;
  return log_prob;
}
*/

#endif


text:
import { Directive, Host, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { ListWrapper } from '../facade/collection';
import { isBlank, isPresent, normalizeBlank } from '../facade/lang';
const _CASE_DEFAULT = new Object();
// TODO: remove when fully deprecated
let _warned = false;
export class SwitchView {
    constructor(_viewContainerRef, _templateRef) {
        this._viewContainerRef = _viewContainerRef;
        this._templateRef = _templateRef;
    }
    create() { this._viewContainerRef.createEmbeddedView(this._templateRef); }
    destroy() { this._viewContainerRef.clear(); }
}
export class NgSwitch {
    constructor() {
        this._useDefault = false;
        this._valueViews = new Map();
        this._activeViews = [];
    }
    set ngSwitch(value) {
        // Empty the currently active ViewContainers
        this._emptyAllActiveViews();
        // Add the ViewContainers matching the value (with a fallback to default)
        this._useDefault = false;
        var views = this._valueViews.get(value);
        if (isBlank(views)) {
            this._useDefault = true;
            views = normalizeBlank(this._valueViews.get(_CASE_DEFAULT));
        }
        this._activateViews(views);
        this._switchValue = value;
    }
    /** @internal */
    _onCaseValueChanged(oldCase, newCase, view) {
        this._deregisterView(oldCase, view);
        this._registerView(newCase, view);
        if (oldCase === this._switchValue) {
            view.destroy();
            ListWrapper.remove(this._activeViews, view);
        }
        else if (newCase === this._switchValue) {
            if (this._useDefault) {
                this._useDefault = false;
                this._emptyAllActiveViews();
            }
            view.create();
            this._activeViews.push(view);
        }
        // Switch to default when there is no more active ViewContainers
        if (this._activeViews.length === 0 && !this._useDefault) {
            this._useDefault = true;
            this._activateViews(this._valueViews.get(_CASE_DEFAULT));
        }
    }
    /** @internal */
    _emptyAllActiveViews() {
        var activeContainers = this._activeViews;
        for (var i = 0; i < activeContainers.length; i++) {
            activeContainers[i].destroy();
        }
        this._activeViews = [];
    }
    /** @internal */
    _activateViews(views) {
        // TODO(vicb): assert(this._activeViews.length === 0);
        if (isPresent(views)) {
            for (var i = 0; i < views.length; i++) {
                views[i].create();
            }
            this._activeViews = views;
        }
    }
    /** @internal */
    _registerView(value, view) {
        var views = this._valueViews.get(value);
        if (isBlank(views)) {
            views = [];
            this._valueViews.set(value, views);
        }
        views.push(view);
    }
    /** @internal */
    _deregisterView(value, view) {
        // `_CASE_DEFAULT` is used a marker for non-registered cases
        if (value === _CASE_DEFAULT)
            return;
        var views = this._valueViews.get(value);
        if (views.length == 1) {
            this._valueViews.delete(value);
        }
        else {
            ListWrapper.remove(views, view);
        }
    }
}
/** @nocollapse */
NgSwitch.decorators = [
    { type: Directive, args: [{ selector: '[ngSwitch]' },] },
];
/** @nocollapse */
NgSwitch.propDecorators = {
    'ngSwitch': [{ type: Input },],
};
export class NgSwitchCase {
    constructor(viewContainer, templateRef, ngSwitch) {
        // `_CASE_DEFAULT` is used as a marker for a not yet initialized value
        /** @internal */
        this._value = _CASE_DEFAULT;
        this._switch = ngSwitch;
        this._view = new SwitchView(viewContainer, templateRef);
    }
    set ngSwitchCase(value) {
        this._switch._onCaseValueChanged(this._value, value, this._view);
        this._value = value;
    }
    set ngSwitchWhen(value) {
        if (!_warned) {
            _warned = true;
            console.warn('*ngSwitchWhen is deprecated and will be removed. Use *ngSwitchCase instead');
        }
        this._switch._onCaseValueChanged(this._value, value, this._view);
        this._value = value;
    }
}
/** @nocollapse */
NgSwitchCase.decorators = [
    { type: Directive, args: [{ selector: '[ngSwitchCase],[ngSwitchWhen]' },] },
];
/** @nocollapse */
NgSwitchCase.ctorParameters = [
    { type: ViewContainerRef, },
    { type: TemplateRef, },
    { type: NgSwitch, decorators: [{ type: Host },] },
];
/** @nocollapse */
NgSwitchCase.propDecorators = {
    'ngSwitchCase': [{ type: Input },],
    'ngSwitchWhen': [{ type: Input },],
};
export class NgSwitchDefault {
    constructor(viewContainer, templateRef, sswitch) {
        sswitch._registerView(_CASE_DEFAULT, new SwitchView(viewContainer, templateRef));
    }
}
/** @nocollapse */
NgSwitchDefault.decorators = [
    { type: Directive, args: [{ selector: '[ngSwitchDefault]' },] },
];
/** @nocollapse */
NgSwitchDefault.ctorParameters = [
    { type: ViewContainerRef, },
    { type: TemplateRef, },
    { type: NgSwitch, decorators: [{ type: Host },] },
];
//# sourceMappingURL=ng_switch.js.map


text:
<!DOCTYPE html>

  <base href="/">
  <meta charset="utf-8">
  <title>js-data + ReactJS</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <meta name="fragment" content="!"/>
  <meta name="Description" content="js-data example app"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="http://bootswatch.com/yeti/bootstrap.css" rel="stylesheet" type="text/css"/>
  <link href="http://bootswatch.com/assets/css/bootswatch.min.css" rel="stylesheet" type="text/css"/>
  <link rel="shortcut icon" href="/favicon.ico">


text: With B37 reference on a 16-core machine


text:
package org.apache.flink.schema.registry.test;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.formats.avro.registry.confluent.ConfluentRegistryAvroDeserializationSchema;
import org.apache.flink.formats.avro.registry.confluent.ConfluentRegistryAvroSerializationSchema;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;

import example.avro.User;
import org.apache.avro.specific.SpecificRecordBase;

import java.util.Properties;

/**
 * A simple example that shows how to read from and write to Kafka with Confluent Schema Registry.
 * This will read AVRO messages from the input topic, parse them into a POJO type via checking the
 * Schema by calling Schema registry. Then this example publish the POJO type to kafka by converting
 * the POJO to AVRO and verifying the schema. --input-topic test-input --output-string-topic
 * test-output --output-avro-topic test-avro-output --output-subject --bootstrap.servers
 * localhost:9092 --schema-registry-url http://localhost:8081 --group.id myconsumer
 */
public class TestAvroConsumerConfluent {

    public static void main(String[] args) throws Exception {
        // parse input arguments
        final ParameterTool parameterTool = ParameterTool.fromArgs(args);

        if (parameterTool.getNumberOfParameters() < 6) {
            System.out.println(
                    "Missing parameters!\n"
                            + "Usage: Kafka --input-topic <topic> --output-string-topic <topic> --output-avro-topic <topic> "
                            + "--bootstrap.servers <kafka brokers> "
                            + "--schema-registry-url <confluent schema registry> --group.id <some id>");
            return;
        }
        Properties config = new Properties();
        config.setProperty("bootstrap.servers", parameterTool.getRequired("bootstrap.servers"));
        config.setProperty("group.id", parameterTool.getRequired("group.id"));
        String schemaRegistryUrl = parameterTool.getRequired("schema-registry-url");

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<User> input =
                env.addSource(
                        new FlinkKafkaConsumer<>(
                                        parameterTool.getRequired("input-topic"),
                                        ConfluentRegistryAvroDeserializationSchema.forSpecific(
                                                User.class, schemaRegistryUrl),
                                        config)
                                .setStartFromEarliest());

        SingleOutputStreamOperator<String> mapToString =
                input.map((MapFunction<User, String>) SpecificRecordBase::toString);

        FlinkKafkaProducer<String> stringFlinkKafkaProducer =
                new FlinkKafkaProducer<>(
                        parameterTool.getRequired("output-string-topic"),
                        new SimpleStringSchema(),
                        config);
        mapToString.addSink(stringFlinkKafkaProducer);

        FlinkKafkaProducer<User> avroFlinkKafkaProducer =
                new FlinkKafkaProducer<>(
                        parameterTool.getRequired("output-avro-topic"),
                        ConfluentRegistryAvroSerializationSchema.forSpecific(
                                User.class,
                                parameterTool.getRequired("output-subject"),
                                schemaRegistryUrl),
                        config);
        input.addSink(avroFlinkKafkaProducer);

        env.execute("Kafka Confluent Schema Registry AVRO Example");
    }
}


text:
{% if "generated" in sourcename %}

{% else %}

{% endif %}

       {{ _("Support ArviZ") }}


text:
package com.google.template.soy.jssrc.internal;

import com.google.common.collect.Sets;
import com.google.template.soy.exprtree.AbstractExprNodeVisitor;
import com.google.template.soy.exprtree.ExprNode;
import com.google.template.soy.exprtree.ExprNode.ParentExprNode;
import com.google.template.soy.exprtree.FunctionNode;
import com.google.template.soy.jssrc.restricted.SoyLibraryAssistedJsSrcFunction;
import com.google.template.soy.shared.restricted.SoyFunction;
import com.google.template.soy.soytree.SoyFileNode;
import com.google.template.soy.soytree.SoytreeUtils;

import java.util.SortedSet;

/**
 * A visitor to generate a set of Closure JS library names required by the function plugins used by
 * this template.
 *
 */
final class GenFunctionPluginRequiresVisitor {

  /** Set storage for the i18n namespaces */
  private SortedSet<String> requiredJsLibNames;

  SortedSet<String> exec(SoyFileNode soyFile) {
    requiredJsLibNames = Sets.newTreeSet();

    GenFunctionPluginRequiresHelperVisitor helperVisitor =
        new GenFunctionPluginRequiresHelperVisitor();

    SoytreeUtils.execOnAllV2Exprs(soyFile, helperVisitor);

    return requiredJsLibNames;
  }

  private final class GenFunctionPluginRequiresHelperVisitor
     extends AbstractExprNodeVisitor<SortedSet<String>> {

    @Override protected void visitFunctionNode(FunctionNode node) {
      SoyFunction soyFunction = node.getSoyFunction();
      if (soyFunction instanceof SoyLibraryAssistedJsSrcFunction) {
        requiredJsLibNames.addAll(
            ((SoyLibraryAssistedJsSrcFunction) soyFunction).getRequiredJsLibNames());
      }
      visitChildren(node);
    }

    @Override protected void visitExprNode(ExprNode node) {
      if (node instanceof ParentExprNode) {
        visitChildren((ParentExprNode) node);
      }
    }
  }
}


text:
namespace courgette {

namespace {

class TestLabelManager : public LabelManager {
 public:
  void SetLabels(const LabelVector& labels) {
    labels_ = labels;
  };
};

void CheckLabelManagerContent(LabelManager* label_manager,
                              const std::map<RVA, int32_t>& expected) {
  EXPECT_EQ(expected.size(), label_manager->Labels().size());
  for (const auto& rva_and_count : expected) {
    Label* label = label_manager->Find(rva_and_count.first);
    EXPECT_TRUE(label != nullptr);
    EXPECT_EQ(rva_and_count.first, label->rva_);
    EXPECT_EQ(rva_and_count.second, label->count_);
  }
}

// Instantiates a LabelVector with |n| instances. The |rva_| fields are assigned
// 0, ..., |n| - 1. The other fields are uninitialized.
LabelVector CreateLabelVectorBasic(size_t n) {
  LabelVector labels;
  labels.reserve(n);
  for (size_t i = 0; i < n; ++i)
    labels.push_back(Label(i));
  return labels;
}

// Instantiates a list of Labels, one per character |ch| in |encoded_index|.
// - |rva_| is assigned 0, 1, 2, ...
// - |count_| is assigned 1.
// - |index_| depends on |ch|: '.' => kNoIndex, 'A' => 0, ..., 'Z' => 25.
// Each letter (except '.') can appear at most once in |encoded_index|.
// For example, |encoded_index| = "A.E" initializes 3 Labels:
//   [{rva_: 0, count_: 1, index_: 0},
//    {rva_: 1, count_: 1, index_: kNoIndex},
//    {rva_: 2, count_: 1, index_: 4}].
LabelVector CreateLabelVectorWithIndexes(const std::string& encoded_index) {
  LabelVector labels;
  size_t n = encoded_index.size();
  labels.reserve(n);
  std::set<char> used_ch;
  for (size_t i = 0; i < n; ++i) {
    int index = Label::kNoIndex;
    char ch = encoded_index[i];
    if (ch != '.') {
      // Sanity check for test case.
      if (ch < 'A' || ch > 'Z' || used_ch.find(ch) != used_ch.end())
        NOTREACHED() << "Malformed test case: " << encoded_index;
      used_ch.insert(ch);
      index = ch - 'A';
    }
    labels.push_back(Label(i, index, 1));
  }
  return labels;
}

// Returns a string encoding for |index_| assignments for |label_| instances,
// with kNoIndex => '.', 0 => 'A', ..., '25' => 'Z'. Fails if any |index_|
// does not fit the above.
std::string EncodeLabelIndexes(const LabelVector& labels) {
  std::string encoded;
  encoded.reserve(labels.size());
  for (const Label& label : labels) {
    if (label.index_ == Label::kNoIndex)
      encoded += '.';
    else if (label.index_ >= 0 && label.index_ <= 'Z' - 'A')
      encoded += static_cast<char>(label.index_ + 'A');
    else
      NOTREACHED();
  }
  return encoded;
}

}  // namespace

TEST(LabelManagerTest, GetLabelIndexBound) {
  LabelVector labels0;
  EXPECT_EQ(0, LabelManager::GetLabelIndexBound(labels0));

  LabelVector labels1_uninit = CreateLabelVectorBasic(1);
  ASSERT_EQ(1U, labels1_uninit.size());
  EXPECT_EQ(0, LabelManager::GetLabelIndexBound(labels1_uninit));

  LabelVector labels1_init = CreateLabelVectorBasic(1);
  ASSERT_EQ(1U, labels1_init.size());
  labels1_init[0].index_ = 99;
  EXPECT_EQ(100, LabelManager::GetLabelIndexBound(labels1_init));

  LabelVector labels6_mixed = CreateLabelVectorBasic(6);
  ASSERT_EQ(6U, labels6_mixed.size());
  labels6_mixed[1].index_ = 5;
  labels6_mixed[2].index_ = 2;
  labels6_mixed[4].index_ = 15;
  labels6_mixed[5].index_ = 7;
  EXPECT_EQ(16, LabelManager::GetLabelIndexBound(labels6_mixed));
}

TEST(LabelManagerTest, Basic) {
  static const RVA kTestTargetsRaw[] = {
    0x04000010,
    0x04000030,
    0x04000020,
    0x04000010,  // Redundant.
    0xFEEDF00D,
    0x04000030,  // Redundant.
    0xFEEDF00D,  // Redundant.
    0x00000110,
    0x04000010,  // Redundant.
    0xABCD1234
  };
  std::vector<RVA> test_targets(std::begin(kTestTargetsRaw),
                                std::end(kTestTargetsRaw));
  TrivialRvaVisitor visitor(test_targets);

  // Preallocate targets, then populate.
  TestLabelManager label_manager;
  label_manager.Read(&visitor);

  static const std::pair<RVA, int32_t> kExpected1Raw[] = {
      {0x00000110, 1}, {0x04000010, 3}, {0x04000020, 1},
      {0x04000030, 2}, {0xABCD1234, 1}, {0xFEEDF00D, 2}};
  std::map<RVA, int32_t> expected1(std::begin(kExpected1Raw),
                                   std::end(kExpected1Raw));

  CheckLabelManagerContent(&label_manager, expected1);

  // Expect to *not* find labels for various RVAs that were never added.
  EXPECT_EQ(nullptr, label_manager.Find(RVA(0x00000000)));
  EXPECT_EQ(nullptr, label_manager.Find(RVA(0x0400000F)));
  EXPECT_EQ(nullptr, label_manager.Find(RVA(0x04000011)));
  EXPECT_EQ(nullptr, label_manager.Find(RVA(0x5F3759DF)));
  EXPECT_EQ(nullptr, label_manager.Find(RVA(0xFEEDFFF0)));
  EXPECT_EQ(nullptr, label_manager.Find(RVA(0xFFFFFFFF)));

  // Remove Labels with |count_| < 2.
  label_manager.RemoveUnderusedLabels(2);
  static const std::pair<RVA, int32_t> kExpected2Raw[] = {
      {0x04000010, 3}, {0x04000030, 2}, {0xFEEDF00D, 2}};
  std::map<RVA, int32_t> expected2(std::begin(kExpected2Raw),
                                   std::end(kExpected2Raw));
  CheckLabelManagerContent(&label_manager, expected2);
}

TEST(LabelManagerTest, Single) {
  const RVA kRva = 12U;
  for (int dup = 1; dup < 8; ++dup) {
    // Test data: |dup| copies of kRva.
    std::vector<RVA> test_targets(dup, kRva);
    TrivialRvaVisitor visitor(test_targets);
    TestLabelManager label_manager;
    label_manager.Read(&visitor);
    EXPECT_EQ(1U, label_manager.Labels().size());  // Deduped to 1 Label.

    Label* label = label_manager.Find(kRva);
    EXPECT_NE(nullptr, label);
    EXPECT_EQ(kRva, label->rva_);
    EXPECT_EQ(dup, label->count_);

    for (RVA rva = 0U; rva < 16U; ++rva) {
      if (rva != kRva)
        EXPECT_EQ(nullptr, label_manager.Find(rva));
    }
  }
}

TEST(LabelManagerTest, Empty) {
  std::vector<RVA> empty_test_targets;
  TrivialRvaVisitor visitor(empty_test_targets);
  TestLabelManager label_manager;
  label_manager.Read(&visitor);
  EXPECT_EQ(0U, label_manager.Labels().size());
  for (RVA rva = 0U; rva < 16U; ++rva)
    EXPECT_EQ(nullptr, label_manager.Find(rva));
}

TEST(LabelManagerTest, EmptyAssign) {
  TestLabelManager label_manager_empty;
  label_manager_empty.DefaultAssignIndexes();
  label_manager_empty.UnassignIndexes();
  label_manager_empty.AssignRemainingIndexes();
}

TEST(LabelManagerTest, TrivialAssign) {
  for (size_t size = 0; size < 20; ++size) {
    TestLabelManager label_manager;
    label_manager.SetLabels(CreateLabelVectorBasic(size));

    // Sanity check.
    for (size_t i = 0; i < size; ++i)
      EXPECT_EQ(Label::kNoIndex, label_manager.Labels()[i].index_);

    // Default assign.
    label_manager.DefaultAssignIndexes();
    for (size_t i = 0; i < size; ++i)
      EXPECT_EQ(static_cast<int>(i), label_manager.Labels()[i].index_);

    // Heuristic assign, but since everything's assigned, so no change.
    label_manager.AssignRemainingIndexes();
    for (size_t i = 0; i < size; ++i)
      EXPECT_EQ(static_cast<int>(i), label_manager.Labels()[i].index_);

    // Unassign.
    label_manager.UnassignIndexes();
    for (size_t i = 0; i < size; ++i)
      EXPECT_EQ(Label::kNoIndex, label_manager.Labels()[i].index_);
  }
}

// Tests SimpleIndexAssigner fill strategies independently.
TEST(LabelManagerTest, SimpleIndexAssigner) {
  using SimpleIndexAssigner = LabelManager::SimpleIndexAssigner;
  // See CreateLabelVectorWithIndexes() explanation on how we encode LabelVector
  // |index_| values as a string.
  const struct TestCase {
    const char* input;
    const char* expect_forward;
    const char* expect_backward;
    const char* expect_in;
  } kTestCases[] = {
    {"", "", "", ""},
    {".", "A", "A", "A"},
    {"....", "ABCD", "ABCD", "ABCD"},
    {"A...", "ABCD", "ABCD", "ABCD"},
    {".A..", ".ABC", ".ACD", "BACD"},
    {"...A", "...A", "...A", "BCDA"},
    {"C...", "CD.A", "C..D", "CABD"},
    {".C..", "ACD.", "BC.D", "ACBD"},
    {"...C", "AB.C", ".ABC", "ABDC"},
    {"D...", "D.AB", "D...", "DABC"},
    {".D..", "AD..", "CD..", "ADBC"},
    {"...D", "ABCD", "ABCD", "ABCD"},
    {"Z...", "Z.AB", "Z...", "ZABC"},
    {".Z..", "AZ..", "YZ..", "AZBC"},
    {"...Z", "ABCZ", "WXYZ", "ABCZ"},
    {"..AZ..", "..AZ..", "..AZ..", "BCAZDE"},
    {"..ZA..", "..ZABC", "XYZA..", "BCZADE"},
    {"A....Z", "ABCDEZ", "AVWXYZ", "ABCDEZ"},
    {"Z....A", "Z....A", "Z....A", "ZBCDEA"},
    {"..CD..", "ABCDEF", "ABCDEF", "ABCDEF"},
    {"..DC..", "ABDC..", "..DCEF", "ABDCEF"},
    {"..MN..", "ABMN..", "KLMN..", "ABMNCD"},
    {"..NM..", "ABNM..", "..NM..", "ABNMCD"},
    {".B.D.F.", "ABCDEFG", "ABCDEFG", "ABCDEFG"},
    {".D.G.J.", "ADEGHJ.", "CDFGIJ.", "ADBGCJE"},
    {".D.Z.J.", "ADEZ.JK", "CDYZIJ.", "ADBZCJE"},
    {".B..E..", "ABCDEFG", "ABCDEFG", "ABCDEFG"},
    {".B..D..", "ABC.DEF", "AB.CDFG", "ABCEDFG"},
  };
  const int kNumFuns = 3;
  // TestCase member variable pointers to enable iteration.
  const char* TestCase::*expect_ptr[kNumFuns] = {
    &TestCase::expect_forward,
    &TestCase::expect_backward,
    &TestCase::expect_in
  };
  // SimpleIndexAssigner member function pointers to enable iteration.
  void (SimpleIndexAssigner::*fun_ptrs[kNumFuns])() = {
    &SimpleIndexAssigner::DoForwardFill,
    &SimpleIndexAssigner::DoBackwardFill,
    &SimpleIndexAssigner::DoInFill
  };
  for (const auto& test_case : kTestCases) {
    // Loop over {forward fill, backward fill, infill}.
    for (int i = 0; i < kNumFuns; ++i) {
      std::string expect = test_case.*(expect_ptr[i]);
      LabelVector labels = CreateLabelVectorWithIndexes(test_case.input);
      SimpleIndexAssigner assigner(&labels);
      (assigner.*(fun_ptrs[i]))();
      std::string result = EncodeLabelIndexes(labels);
      EXPECT_EQ(expect, result);
    }
  }
}

// Tests integrated AssignRemainingIndexes().
TEST(LabelManagerTest, AssignRemainingIndexes) {
  const struct {
    const char* input;
    const char* expect;
  } kTestCases[] = {
    // Trivial.
    {"", ""},
    {"M", "M"},
    {"ABCDEFG", "ABCDEFG"},
    {"THEQUICKBROWNFXJMPSVLAZYDG", "THEQUICKBROWNFXJMPSVLAZYDG"},
    // Forward fill only.
    {".", "A"},
    {".......", "ABCDEFG"},
    {"....E..", "ABCDEFG"},  // "E" is at right place.
    {".D.B.H.F.", "ADEBCHIFG"},
    {"ZN....", "ZNOPQR"},  // "Z" exists, so 'OPQR" are defined.
    {"H.D...A..", "HIDEFGABC"},
    {"...K.DE..H..Z", "ABCKLDEFGHIJZ"},  // "Z" exists, so "L" defined.
    // Infill only.
    {"E.", "EA"},
    {"...A", "BCDA"},
    {"Z...A", "ZBCDA"},
    {"AN...", "ANBCD"},
    {"...AZ", "BCDAZ"},
    {"....AC", "BDEFAC"},
    {"ED...C...B....A", "EDFGHCIJKBLMNOA"},
    // Forward fill and infill.
    {"E..", "EBA"},  // Forward: "A"; in: "B".
    {"Z....", "ZDABC"},  // Forward: "ABC"; in: "D".
    {".E.....", "AEFGBCD"},  // Forward: "A", "FG"; in: "BCD".
    {"....C..", "ABFGCDE"},  // Forward: "AB", "DE"; in: "FG".
    {"...Z...", "ABCZDEF"},  // Forward: "ABC"; in: "DEF".
    {"...A...", "EFGABCD"},  // Forward: "BCD"; in: "EFG".
    // Backward fill only.
    {".CA", "BCA"},
    {"...ZA", "WXYZA"},
    {"BA...Z", "BAWXYZ"},
    {"ANM..Z....L...T", "ANMXYZHIJKLQRST"},
    {"....G..Z...LAH", "CDEFGXYZIJKLAH"},
    // Forward fill and backward fill.
    {"..ZA..", "XYZABC"},  // Forward: "BC"; backward: "XY".
    {".....ZD", "ABCXYZD"},  // Forward: "ABC"; backward: "XY".
    {"DA.....", "DABCEFG"},  // Forward: "BC"; backward: "EFG".
    // Backward fill and infill.
    {"G....DA", "GEFBCDA"},  // Backward: "BC"; in: "EF".
    {"..ZBA..", "XYZBACD"},  // Backward: "XY"; in: "CD".
    // All.
    {".....ZED.", "ABCXYZEDF"},  // Forward: "ABC"; backward: "XY"; in: "F".
    {".....GD.", "ABCHFGDE"},  // Forward: "ABC", "E"; backward: "F"; in: "H".
    {"..FE..GD..", "ABFECHGDIJ"}, // Forward: "AB"; backward: "IJ"; in: "CH".
  };
  for (const auto& test_case : kTestCases) {
    TestLabelManager label_manager;
    label_manager.SetLabels(CreateLabelVectorWithIndexes(test_case.input));

    label_manager.AssignRemainingIndexes();
    std::string result = EncodeLabelIndexes(label_manager.Labels());
    EXPECT_EQ(test_case.expect, result);
  }
}

}  // namespace courgette


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__float_fgets_74a.cpp
Label Definition File: CWE369_Divide_by_Zero__float.label.xml
Template File: sources-sinks-74a.tmpl.cpp
*/
/*
 * @description
 * CWE: 369 Divide by Zero
 * BadSource: fgets Read data from the console using fgets()
 * GoodSource: A hardcoded non-zero number (two)
 * Sinks:
 *    GoodSink: Check value of or near zero before dividing
 *    BadSink : Divide a constant by data
 * Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files
 *
 * */

#include "std_testcase.h"
#include <map>

#include <math.h>

#define CHAR_ARRAY_SIZE 20

using namespace std;

namespace CWE369_Divide_by_Zero__float_fgets_74
{

#ifndef OMITBAD

/* bad function declaration */
void badSink(map<int, float> dataMap);

void bad()
{
    float data;
    map<int, float> dataMap;
    /* Initialize data */
    data = 0.0F;
    {
        char inputBuffer[CHAR_ARRAY_SIZE];
        /* POTENTIAL FLAW: Use a value input from the console using fgets() */
        if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL)
        {
            /* Convert to float */
            data = (float)atof(inputBuffer);
        }
        else
        {
            printLine("fgets() failed.");
        }
    }
    /* Put data in a map */
    dataMap[0] = data;
    dataMap[1] = data;
    dataMap[2] = data;
    badSink(dataMap);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(map<int, float> dataMap);

static void goodG2B()
{
    float data;
    map<int, float> dataMap;
    /* Initialize data */
    data = 0.0F;
    /* FIX: Use a hardcoded number that won't a divide by zero */
    data = 2.0F;
    /* Put data in a map */
    dataMap[0] = data;
    dataMap[1] = data;
    dataMap[2] = data;
    goodG2BSink(dataMap);
}

/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(map<int, float> dataMap);

static void goodB2G()
{
    float data;
    map<int, float> dataMap;
    /* Initialize data */
    data = 0.0F;
    {
        char inputBuffer[CHAR_ARRAY_SIZE];
        /* POTENTIAL FLAW: Use a value input from the console using fgets() */
        if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL)
        {
            /* Convert to float */
            data = (float)atof(inputBuffer);
        }
        else
        {
            printLine("fgets() failed.");
        }
    }
    dataMap[0] = data;
    dataMap[1] = data;
    dataMap[2] = data;
    goodB2GSink(dataMap);
}

void good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE369_Divide_by_Zero__float_fgets_74; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif