text:
<?php

class iHomefinderAdmin {

	private static $instance;

	private function __construct() {

	}

	public static function getInstance() {
		if(!isset(self::$instance)) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public function checkError() {

		$pageName = iHomefinderUtility::getInstance()->getRequestVar("page");

		//Check for valid plugin registration
		//Do not check for registration on the registration page.
		if($pageName !== iHomefinderConstants::PAGE_ACTIVATE && !$this->isActivated()) {
			?>

					<a href="admin.php?page=<?php echo iHomefinderConstants::PAGE_ACTIVATE ?>" class="button button-primary">Activate Your Optima Express Account
					   Get an unlimited free trial or paid subscription for your MLS

			<?php
		}

		if(get_option(iHomefinderConstants::COMPATIBILITY_CHECK_ENABLED, true) !== "false") {
			$errors = array();
			//check if permalink structure is set
			$permalinkStructure = get_option("permalink_structure", null);
			if(empty($permalinkStructure)) {
				$errors[] = "WordPress permalink settings are set as default (Error 404)";
			}
			$remoteRequest = new iHomefinderRequestor();
			$remoteRequest
				->addParameter("method", "handleRequest")
				->addParameter("viewType", "json")
				->addParameter("requestType", "compatibility-check")
			;
			$remoteRequest->setCacheExpiration(60*60*24);
			$remoteResponse = $remoteRequest->remoteGetRequest();
			if(!empty($remoteResponse)) {
				$content = null;
				if(iHomefinderLayoutManager::getInstance()->isResponsive()) {
					$content = (string) $remoteResponse->getJson();
				} else {
					$content = json_encode($remoteResponse->getResponse());
				}
				if(!empty($content)) {
					$compatibility = json_decode($content, true);
					if(!empty($compatibility) && is_array($compatibility)) {
						//check plugins
						if(array_key_exists("Plugin", $compatibility)) {
							$incompatiblePlugins = $compatibility["Plugin"];
							$plugins = get_plugins();
							foreach($plugins as $pluginPath => $plugin) {
								if(is_plugin_active($pluginPath)) {
									$pluginName = $plugin["Name"];
									if(is_array($pluginName) && array_key_exists($pluginName, $incompatiblePlugins)) {
										$message = $incompatiblePlugins[$pluginName];
										if($message !== null) {
											$errors[] = "" . $pluginName . " (" . $message . ")";
										}
									}
								}
							}
						}
						//check theme
						if(array_key_exists("Theme", $compatibility)) {
							$theme = wp_get_theme();
							$themeName = $theme->get("Name");
							$incompatibleThemes = $compatibility["Theme"];
							if(is_array($incompatibleThemes) && array_key_exists($themeName, $incompatibleThemes)) {
								$message = $incompatibleThemes[$themeName];
								if($message !== null) {
									$errors[] = "" . $themeName . " (" . $message . ")";
								}
							}
						}
					}
				}
			}
			//check error count
			if(count($errors) > 0) {
				?>

						<?php echo count($errors) ?> compatibility issue<?php if(count($errors) > 1) { ?>s<?php } ?>:

					<form style="float: right; margin-top: 5px;" method="post" action="options.php">
						<?php settings_fields(iHomefinderConstants::OPTION_GROUP_COMPATIBILITY_CHECK); ?>
						<input type="hidden" value="false" name="<?php echo iHomefinderConstants::COMPATIBILITY_CHECK_ENABLED; ?>" />
						<button class="button-secondary" type="submit">Dismiss compatibility warnings</button>
					</form>

						<?php foreach($errors as $error) { ?>

								<?php echo $error; ?>

						<?php } ?>

				<?php
			}
		}
	}

	public function createAdminMenu() {
		$permissions = iHomefinderPermissions::getInstance();
		add_menu_page("Optima Express", "Optima Express", "manage_options", iHomefinderConstants::PAGE_INFORMATION, array(iHomefinderAdminInformation::getInstance(), "getPage"));
		add_submenu_page(iHomefinderConstants::PAGE_INFORMATION, "Information", "Information", "manage_options", iHomefinderConstants::PAGE_INFORMATION, array(iHomefinderAdminInformation::getInstance(), "getPage"));
		add_submenu_page(iHomefinderConstants::PAGE_INFORMATION, "Register", "Register", "manage_options", iHomefinderConstants::PAGE_ACTIVATE, array(iHomefinderAdminActivate::getInstance(), "getPage"));
		add_submenu_page(iHomefinderConstants::PAGE_INFORMATION, "IDX Control Panel", "IDX Control Panel", "manage_options", iHomefinderConstants::PAGE_IDX_CONTROL_PANEL, array(iHomefinderAdminControlPanel::getInstance(), "getPage"));
		add_submenu_page(iHomefinderConstants::PAGE_INFORMATION, "IDX Pages", "IDX Pages", "manage_options", iHomefinderConstants::PAGE_IDX_PAGES, array(iHomefinderAdminPageConfig::getInstance(), "getPage"));
		add_submenu_page(iHomefinderConstants::PAGE_INFORMATION, "Configuration", "Configuration", "manage_options", iHomefinderConstants::PAGE_CONFIGURATION, array(iHomefinderAdminConfiguration::getInstance(), "getPage"));
		if($permissions->isAgentBioWidgetEnabled()) {
			add_submenu_page(iHomefinderConstants::PAGE_INFORMATION, "Bio Widget", "Bio Widget", "manage_options", iHomefinderConstants::PAGE_BIO, array(iHomefinderAdminBio::getInstance(), "getPage"));
		}
		if($permissions->isSocialEnabled()) {
			add_submenu_page(iHomefinderConstants::PAGE_INFORMATION, "Social Widget", "Social Widget", "manage_options", iHomefinderConstants::PAGE_SOCIAL, array(iHomefinderAdminSocial::getInstance(), "getPage"));
		}
		add_submenu_page(iHomefinderConstants::PAGE_INFORMATION, "Email Branding", "Email Branding", "manage_options", iHomefinderConstants::PAGE_EMAIL_BRANDING, array(iHomefinderAdminEmail::getInstance(), "getPage"));
		if($permissions->isCommunityPagesEnabled()) {
			add_submenu_page(iHomefinderConstants::PAGE_INFORMATION, "Community Pages", "Community Pages", "manage_options", iHomefinderConstants::PAGE_COMMUNITY_PAGES, array(iHomefinderAdminCommunityPages::getInstance(), "getPage"));
		}
		if($permissions->isSeoCityLinksEnabled()) {
			add_submenu_page(iHomefinderConstants::PAGE_INFORMATION, "SEO City Links", "SEO City Links", "manage_options", iHomefinderConstants::PAGE_SEO_CITY_LINKS, array(iHomefinderAdminSeoCityLinks::getInstance(), "getPage"));
		}
	}

	/**
	 * Create register option groups and associated options.
	 * Later use settings_fields in the forms to populate the options.
	 */
	public function registerSettings() {
		//compatibility check shows on all dashboard pages
		register_setting(iHomefinderConstants::OPTION_GROUP_COMPATIBILITY_CHECK, iHomefinderConstants::COMPATIBILITY_CHECK_ENABLED);
		//admin pages
		iHomefinderAdminActivate::getInstance()->registerSettings();
		iHomefinderAdminPageConfig::getInstance()->registerSettings();
		iHomefinderAdminConfiguration::getInstance()->registerSettings();
		iHomefinderAdminBio::getInstance()->registerSettings();
		iHomefinderAdminSocial::getInstance()->registerSettings();
		iHomefinderAdminEmail::getInstance()->registerSettings();
		iHomefinderAdminSeoCityLinks::getInstance()->registerSettings();
	}

	public function addScripts() {
		$pages = array(
			iHomefinderConstants::PAGE_INFORMATION,
			iHomefinderConstants::PAGE_ACTIVATE,
			iHomefinderConstants::PAGE_IDX_CONTROL_PANEL,
			iHomefinderConstants::PAGE_IDX_PAGES,
			iHomefinderConstants::PAGE_CONFIGURATION,
			iHomefinderConstants::PAGE_BIO,
			iHomefinderConstants::PAGE_SOCIAL,
			iHomefinderConstants::PAGE_EMAIL_BRANDING,
			iHomefinderConstants::PAGE_COMMUNITY_PAGES,
			iHomefinderConstants::PAGE_SEO_CITY_LINKS
		);
		if(array_key_exists("page", $_GET)) {
			$page = $_GET["page"];
			$result = array_search($page, $pages);
			if($result !== false && $result >= 0) {
				wp_enqueue_script("jquery");
				wp_enqueue_script("jquery-ui-core");
				wp_enqueue_script("jquery-ui-autocomplete", "", array("jquery-ui-widget", "jquery-ui-position"));
				wp_enqueue_script("jquery-ui-accordion", "", array("jquery-ui-widget", "jquery-ui-position"));
				wp_enqueue_style("thickbox");
				wp_enqueue_script("jquery-textrange", plugins_url("js/jquery-textrange.js", __FILE__), array("jquery"), iHomefinderConstants::VERSION);
			}
		}
		wp_enqueue_script("oe-dashboard", plugins_url("js/dashboard.js", __FILE__), array("jquery", "editor", "media-upload", "thickbox"), iHomefinderConstants::VERSION);
		wp_enqueue_style("oe-dashboard", plugins_url("css/dashboard.css", __FILE__), null, iHomefinderConstants::VERSION);
	}

	/**
	 * @deprecated - use activateAuthenticationToken instead
	 */
	public function updateAuthenticationToken() {
		$this->activateAuthenticationToken();
	}

	public function activateAuthenticationToken($activationToken = null) {
		if(!empty($activationToken)) {
			update_option(iHomefinderConstants::ACTIVATION_TOKEN_OPTION, $activationToken);
		}
		$authenticationInfo = $this->getAuthenticationInfo();
		if($authenticationInfo !== null) {
			if(property_exists($authenticationInfo, "authenticationToken")) {
				$authenticationToken = (string) $authenticationInfo->authenticationToken;
				$this->setAuthenticationToken($authenticationToken);
			}
			if(property_exists($authenticationInfo, "permissions")) {
				$permissions = $authenticationInfo->permissions;
				iHomefinderPermissions::getInstance()->initialize($permissions);
			}
			update_option(iHomefinderConstants::IS_ACTIVATED_OPTION, "true");
			//We need to flush the rewrite rules, if any permalinks have been updated.
			//Only flush in the admin screens, because that is the only point where urls patterns may change.
			iHomefinderRewriteRules::getInstance()->flushRules();
			//clear the cache
			iHomefinderCacheUtility::getInstance()->deleteItems();
			//update menu with any new available menu items
			iHomefinderMenu::getInstance()->updateMenu();
		}
	}

	public function deleteAuthenticationToken() {
		delete_option(iHomefinderConstants::AUTHENTICATION_TOKEN_OPTION);
	}

	public function getAuthenticationToken() {
		$authenticationToken = get_option(iHomefinderConstants::AUTHENTICATION_TOKEN_OPTION, null);
		return $authenticationToken;
	}

	public function setAuthenticationToken($authenticationToken) {
		update_option(iHomefinderConstants::AUTHENTICATION_TOKEN_OPTION, $authenticationToken);
	}

	public function previouslyActivated() {
		return get_option(iHomefinderConstants::IS_ACTIVATED_OPTION, false);
	}

	public function isActivated() {
		$result = false;
		$authenticationToken = $this->getAuthenticationToken();
		if(!empty($authenticationToken)) {
			$result = true;
		}
		return $result;
	}

	private function getAuthenticationInfo() {
		$activationToken = get_option(iHomefinderConstants::ACTIVATION_TOKEN_OPTION, null);
		if(empty($activationToken)) {
			return null;
		}
		$urlFactory = iHomefinderUrlFactory::getInstance();
		$ajaxBaseUrl = urlencode($urlFactory->getAjaxBaseUrl());
		$listingsSearchResultsUrl = urlencode($urlFactory->getListingsSearchResultsUrl(true));
		$listingsSearchFormUrl = urlencode($urlFactory->getListingsSearchFormUrl(true));
		$listingDetailUrl = urlencode($urlFactory->getListingDetailUrl(true));
		$featuredSearchResultsUrl = urlencode($urlFactory->getFeaturedSearchResultsUrl(true));
		$hotsheetSearchResultsUrl = urlencode($urlFactory->getHotsheetSearchResultsUrl(true));
		$organizerLoginUrl = urlencode($urlFactory->getOrganizerLoginUrl(true));
		$organizerLogoutUrl = urlencode($urlFactory->getOrganizerLogoutUrl(true));
		$organizerLoginSubmitUrl = urlencode($urlFactory->getOrganizerLoginSubmitUrl(true));
		$organizerEditSavedSearchUrl = urlencode($urlFactory->getOrganizerEditSavedSearchUrl(true));
		$organizerEditSavedSearchSubmitUrl = urlencode($urlFactory->getOrganizerEditSavedSearchSubmitUrl(true));
		$organizerDeleteSavedSearchSubmitUrl = urlencode($urlFactory->getOrganizerDeleteSavedSearchSubmitUrl(true));
		$organizerViewSavedSearchUrl = urlencode($urlFactory->getOrganizerViewSavedSearchUrl(true));
		$organizerViewSavedSearchListUrl = urlencode($urlFactory->getOrganizerViewSavedSearchListUrl(true));
		$organizerViewSavedListingListUrl = urlencode($urlFactory->getOrganizerViewSavedListingListUrl(true));
		$organizerDeleteSavedListingUrl = urlencode($urlFactory->getOrganizerDeleteSavedListingUrl(true));
		$organizerResendConfirmationEmailUrl = urlencode($urlFactory->getOrganizerResendConfirmationEmailUrl(true));
		$organizerActivateSubscriberUrl = urlencode($urlFactory->getOrganizerActivateSubscriberUrl(true));
		$organizerSendSubscriberPasswordUrl = urlencode($urlFactory->getOrganizerSendSubscriberPasswordUrl(true));
		$listingsAdvancedSearchFormUrl = urlencode($urlFactory->getListingsAdvancedSearchFormUrl(true));
		$organizerHelpUrl = urlencode($urlFactory->getOrganizerHelpUrl(true));
		$organizerEditSubscriberUrl = urlencode($urlFactory->getOrganizerEditSubscriberUrl(true));
		$contactFormUrl = urlencode($urlFactory->getContactFormUrl(true));
		$valuationFormUrl = urlencode($urlFactory->getValuationFormUrl(true));
		$listingSoldDetailUrl = urlencode($urlFactory->getListingSoldDetailUrl(true));
		$openHomeSearchFormUrl = urlencode($urlFactory->getOpenHomeSearchFormUrl(true));
		$soldFeaturedListingUrl = urlencode($urlFactory->getSoldFeaturedListingUrl(true));
		$supplementalListingUrl = urlencode($urlFactory->getSupplementalListingUrl(true));
		$officeListUrl = urlencode($urlFactory->getOfficeListUrl(true));
		$officeDetailUrl = urlencode($urlFactory->getOfficeDetailUrl(true));
		$agentBioListUrl = urlencode($urlFactory->getAgentListUrl(true));
		$agentBioDetailUrl = urlencode($urlFactory->getAgentDetailUrl(true));
		$mapSearchUrl = urlencode($urlFactory->getMapSearchFormUrl(true));
		$cssOverride = urlencode(get_option(iHomefinderConstants::CSS_OVERRIDE_OPTION, null));
		$layoutType = urlencode(iHomefinderLayoutManager::getInstance()->getLayoutType());
		$colorScheme = urlencode(iHomefinderLayoutManager::getInstance()->getColorScheme());
		$mobileSiteYn = get_option(iHomefinderConstants::OPTION_MOBILE_SITE_YN, null);
		$emailDisplayType = get_option(iHomefinderConstants::EMAIL_DISPLAY_TYPE_OPTION, null);
		$emailHeader = urlencode(iHomefinderAdminEmail::getInstance()->getHeader());
		$emailFooter = urlencode(iHomefinderAdminEmail::getInstance()->getFooter());
		$emailPhotoUrl = get_option(iHomefinderConstants::EMAIL_PHOTO_OPTION, null);
		$emailLogoUrl = get_option(iHomefinderConstants::EMAIL_LOGO_OPTION, null);
		$emailName = get_option(iHomefinderConstants::EMAIL_NAME_OPTION, null);
		$emailCompany = get_option(iHomefinderConstants::EMAIL_COMPANY_OPTION, null);
		$emailPhone = get_option(iHomefinderConstants::EMAIL_PHONE_OPTION, null);
		$emailAddressLine1 = get_option(iHomefinderConstants::EMAIL_ADDRESS_LINE1_OPTION, null);
		$emailAddressLine2 = get_option(iHomefinderConstants::EMAIL_ADDRESS_LINE2_OPTION, null);

		$emailBrandingType = null;
		switch($emailDisplayType) {
			case iHomefinderAdminEmail::EMAIL_DISPLAY_TYPE_CUSTOM_IMAGES_VALUE;
			case iHomefinderAdminEmail::EMAIL_DISPLAY_TYPE_DEFAULT_VALUE;
			$emailBrandingType = "basic";
				break;
			case iHomefinderAdminEmail::EMAIL_DISPLAY_TYPE_CUSTOM_HTML_VALUE;
				$emailBrandingType = "custom";
				break;
		}

		$remoteRequest = new iHomefinderRequestor();
		$remoteRequest
			->addParameter("method", "handleRequest")
			->addParameter("requestType", "activate")
			->addParameter("viewType", "json")
			->addParameter("activationToken", $activationToken)
			->addParameter("ajaxBaseUrl", $ajaxBaseUrl)
			->addParameter("type", "wordpress")
			->addParameter("listingSearchResultsUrl", $listingsSearchResultsUrl)
			->addParameter("listingSearchByAddressResultsUrl", $listingsSearchResultsUrl)
			->addParameter("listingSearchByListingIdResultsUrl", $listingsSearchResultsUrl)
			->addParameter("listingSearchFormUrl", $listingsSearchFormUrl)
			->addParameter("listingDetailUrl", $listingDetailUrl)
			->addParameter("featuredSearchResultsUrl", $featuredSearchResultsUrl)
			->addParameter("hotsheetSearchResultsUrl", $hotsheetSearchResultsUrl)
			->addParameter("organizerLoginUrl", $organizerLoginUrl)
			->addParameter("organizerLogoutUrl", $organizerLogoutUrl)
			->addParameter("organizerLoginSubmitUrl", $organizerLoginSubmitUrl)
			->addParameter("organizerEditSavedSearchUrl", $organizerEditSavedSearchUrl)
			->addParameter("organizerEditSavedSearchSubmitUrl", $organizerEditSavedSearchSubmitUrl)
			->addParameter("organizerDeleteSavedSearchSubmitUrl", $organizerDeleteSavedSearchSubmitUrl)
			->addParameter("organizerViewSavedSearchUrl", $organizerViewSavedSearchUrl)
			->addParameter("organizerViewSavedSearchListUrl", $organizerViewSavedSearchListUrl)
			->addParameter("organizerViewSavedListingListUrl", $organizerViewSavedListingListUrl)
			->addParameter("organizerDeleteSavedListingUrl", $organizerDeleteSavedListingUrl)
			->addParameter("organizerResendConfirmationEmailUrl", $organizerResendConfirmationEmailUrl)
			->addParameter("organizerActivateSubscriberUrl", $organizerActivateSubscriberUrl)
			->addParameter("organizerSendSubscriberPasswordUrl", $organizerSendSubscriberPasswordUrl)
			->addParameter("listingAdvancedSearchFormUrl", $listingsAdvancedSearchFormUrl)
			->addParameter("organizerHelpUrl", $organizerHelpUrl)
			->addParameter("organizerEditSubscriberUrl", $organizerEditSubscriberUrl)
			->addParameter("contactFormUrl", $contactFormUrl)
			->addParameter("valuationFormUrl", $valuationFormUrl)
			->addParameter("listingSoldDetailUrl", $listingSoldDetailUrl)
			->addParameter("openHomeSearchFormUrl", $openHomeSearchFormUrl)
			->addParameter("soldFeaturedListingUrl", $soldFeaturedListingUrl)
			->addParameter("supplementalListingUrl", $supplementalListingUrl)
			->addParameter("officeListUrl", $officeListUrl)
			->addParameter("officeDetailUrl", $officeDetailUrl)
			->addParameter("agentBioListUrl", $agentBioListUrl)
			->addParameter("agentBioDetailUrl", $agentBioDetailUrl)
			->addParameter("mapSearchUrl", $mapSearchUrl)
			->addParameter("cssOverride", $cssOverride)
			->addParameter("layoutType", $layoutType)
			->addParameter("colorScheme", $colorScheme)
			->addParameter("mobileSiteYn", $mobileSiteYn)
			->addParameter("emailBrandingType", $emailBrandingType)
			->addParameter("emailHeader", $emailHeader)
			->addParameter("emailFooter", $emailFooter)
			->addParameter("emailPhotoUrl", $emailPhotoUrl)
			->addParameter("emailLogoUrl", $emailLogoUrl)
			->addParameter("emailName", $emailName)
			->addParameter("emailCompany", $emailCompany)
			->addParameter("emailPhone", $emailPhone)
			->addParameter("emailAddressLine1", $emailAddressLine1)
			->addParameter("emailAddressLine2", $emailAddressLine2)
		;

		$remoteResponse = $remoteRequest->remotePostRequest();

		return $remoteResponse->getResponse();

	}

}


text:
list(APPEND CMAKE_MODULE_PATH ${cookoff_path}/scripts ${cookoff_path}/modules)
include(AddCPP11Flags)

redpajama_set_name: RedPajamaGithub


text:
#include "common_audio/channel_buffer.h"
#include "common_audio/include/audio_util.h"
#include "common_audio/wav_file.h"
#include "modules/audio_processing/audio_buffer.h"
#include "modules/audio_processing/intelligibility/intelligibility_enhancer.h"
#include "modules/audio_processing/noise_suppression_impl.h"
#include BOSS_WEBRTC_U_rtc_base__criticalsection_h //original-code:"rtc_base/criticalsection.h"
#include BOSS_WEBRTC_U_rtc_base__flags_h //original-code:"rtc_base/flags.h"

using std::complex;

namespace webrtc {
namespace {

DEFINE_string(clear_file, "speech.wav", "Input file with clear speech.");
DEFINE_string(noise_file, "noise.wav", "Input file with noise data.");
DEFINE_string(out_file, "proc_enhanced.wav", "Enhanced output file.");
DEFINE_bool(help, false, "Print this message.");

int int_main(int argc, char* argv[]) {
  if (rtc::FlagList::SetFlagsFromCommandLine(&argc, argv, true)) {
    return 1;
  }
  if (FLAG_help) {
    rtc::FlagList::Print(nullptr, false);
    return 0;
  }
  if (argc != 1) {
    printf("\n\nInput files must be little-endian 16-bit signed raw PCM.\n");
    return 0;
  }

  WavReader in_file(FLAG_clear_file);
  WavReader noise_file(FLAG_noise_file);
  WavWriter out_file(FLAG_out_file, in_file.sample_rate(),
                     in_file.num_channels());
  rtc::CriticalSection crit;
  NoiseSuppressionImpl ns(&crit);
  IntelligibilityEnhancer enh(in_file.sample_rate(), in_file.num_channels(), 1u,
                              NoiseSuppressionImpl::num_noise_bins());
  ns.Initialize(noise_file.num_channels(), noise_file.sample_rate());
  ns.Enable(true);
  const size_t in_samples = noise_file.sample_rate() / 100;
  const size_t noise_samples = noise_file.sample_rate() / 100;
  std::vector<float> in(in_samples * in_file.num_channels());
  std::vector<float> noise(noise_samples * noise_file.num_channels());
  ChannelBuffer<float> in_buf(in_samples, in_file.num_channels());
  ChannelBuffer<float> noise_buf(noise_samples, noise_file.num_channels());
  AudioBuffer capture_audio(noise_samples, noise_file.num_channels(),
                            noise_samples, noise_file.num_channels(),
                            noise_samples);
  AudioBuffer render_audio(in_samples, in_file.num_channels(), in_samples,
                           in_file.num_channels(), in_samples);
  StreamConfig noise_config(noise_file.sample_rate(),
                            noise_file.num_channels());
  StreamConfig in_config(in_file.sample_rate(), in_file.num_channels());
  while (in_file.ReadSamples(in.size(), in.data()) == in.size() &&
         noise_file.ReadSamples(noise.size(), noise.data()) == noise.size()) {
    FloatS16ToFloat(noise.data(), noise.size(), noise.data());
    FloatS16ToFloat(in.data(), in.size(), in.data());
    Deinterleave(in.data(), in_buf.num_frames(), in_buf.num_channels(),
                 in_buf.channels());
    Deinterleave(noise.data(), noise_buf.num_frames(), noise_buf.num_channels(),
                 noise_buf.channels());
    capture_audio.CopyFrom(noise_buf.channels(), noise_config);
    render_audio.CopyFrom(in_buf.channels(), in_config);
    ns.AnalyzeCaptureAudio(&capture_audio);
    ns.ProcessCaptureAudio(&capture_audio);
    enh.SetCaptureNoiseEstimate(ns.NoiseEstimate(), 1);
    enh.ProcessRenderAudio(&render_audio);
    render_audio.CopyTo(in_config, in_buf.channels());
    Interleave(in_buf.channels(), in_buf.num_frames(), in_buf.num_channels(),
               in.data());
    FloatToFloatS16(in.data(), in.size(), in.data());
    out_file.WriteSamples(in.data(), in.size());
  }

  return 0;
}

}  // namespace
}  // namespace webrtc

int main(int argc, char* argv[]) {
  return webrtc::int_main(argc, argv);
}


text:
'use strict';

module.exports = function (app, engine) {
    return {
        name: 'render',
        async: false,
        filter: (str, context) => engine.renderString(str, context || {}),
    };
};


text:
A super tiny HTTP server toolkit targeting embedded devices.

## Goals

* Tiny (small memory footprint)
* Fast (small CPU footprint)
* No Heap Usage (uses no run-time memory allocation)
* Modular (optional middleware)
* Well Tested

## Current Status

* Parse method
* Parse path
* Parse parameters
* Parse headers
* Lots of tests
* Responses
* Routing Engine

## Using

The HTTP Parser is stable, and can be used as-is.  It will parse the request
into a `method`, `path`, `parameters`, and `headers`.

It also has the ability to manage responses, as well as a built-in request
router that makes it easier to build applications with.

`Tiny-HTTP` is opinionated, and uses unsigned 8 bit integers in the form of
`uint8_t`.  It is also meant to work in as many environments as possible, and
thus has a more `C` style to it.  It is currently usable on any POSIX
compatible system (Unix/Linux/OSX), as well as the ESP8266 when using the
Arduino environment.

### Building

```
$ make
```

### Testing

```
$ make test
```

### Embedding

To use, simply include the aspects of the project that you want to use,
`Request`, `Response`, and `Routing`.

From there, link against `libtinyhttp.a`:

```
$ gcc httpd.c -ltinyhttp -o httpd
```

### Request

A `Request` contains a `method`, `path`, `parameters`, and `headers`.  If an
error occurs, or an unsupported method is sent, `method` is set to `HTTP_ERROR`.

* `method` - `uint8_t` method (`HTTP_GET`, `HTTP_POST`, `HTTP_PUT`, `HTTP_ERROR`)
* `path` - `uint8_t *` path or NULL on error
* `params` - `uint8_t **` array of parameters NULL terminated (`foo=bar`)
* `headers` - `uint8_t **` array of headers NULL terminated (`Content-type: application/json`)

#### parse_request(uint8_t \*req)

Parses a request, returning a `Request` object.

_param_ req - `uint8_t *` buffer containing the full request
_returns_ Request - `Request *` request that contains a `Request` object.

_example_:

```
uint8_t buf[128] = "GET /foo?bar=baz HTTP/1.1\r\n\r\n";

Request *request = http_parser(buf);

Serial.println((char *) request->path); // /foo
Serial.println((char *) request->params[0]); // bar=baz
```

### Response

A Response allows for setting of headers, response codes, and writing of
content back to the browser.

#### response_create

Creates a `Response` that should be passed to all subsequent `request` calls.

_Parameters_:

* socket - uint8_t (POSIX)
* client - WiFiClient (ESP8266)

_Example:_

```
Response *response = response_create(client);
```

#### response->code

One of `200`, `404`, or `500` (defaults to `200`).  Content type cannot be
set once `response_write` has been run.

_Example:_

```
response->code = 404;
```

#### response_set_content_type

Sets the `Content-type` header - defaults to `text/html`.  Content type cannot
be set once `response_write` has been run.

_Parameters:_

* response - pointer to Response object
* type - type of content to send

_Example:_

```
response_set_content_type(response, "application/json");
```

#### response_set_header

Sets a header.  Headers cannot be set once `response_write` has been run.

_Parameters:_

* response - pointer to Response object
* header - well-formed header to send

_Example:_

```
response_set_header(response, "X-Powered-By: Awesomeness");
```

#### response_write

Sends data to the client.  Once a `response_write` has been run, no more headers
can be set, this starts sending data to the client immediately, as well as
the content type and status.

_Parameters:_

* response - pointer to Response object
* data - data to send

_Example:_

```
response_write(response, "Pong!");
```

### Router

The request router manages route state, as well as turning control over to
a method to execute.  Once a router is set up, it is simply a matter of
sending the whole request string to the router, and letting the router do
all of the work for you.

Only one route will be matched, and a `500` error will be returned on error
parsing a request, as well as a `404` error if no routes are found.

#### router_create

Returns a new `Router`.

_Example:_

```
Router *router = router_create();
```

#### router_add_route

Adds a route to the router for dispensation.

_Parameters:_

* router - pointer to Router object
* route - route to match against
* method - function to call when the route is matched

_Example:_

```
void pong_responder (Request *request, Response *response) {
  response_set_content_type("application/json");
  response_write("{ \"status\": \"pong\" }");
}

Router *setup_routes ( ) {
  Router *router = router_create();

  router_add_route(router, "/ping", ping_responder);

  return router;
}

void run_routes (Router *router, WiFiClient client, uint8_t *req) {
  route(client, router, req);
}
```


text:
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="2dp"
    android:layout_marginBottom="2dp"
    android:fastScrollEnabled="false"
    android:transcriptMode="alwaysScroll"
    android:divider="@null"
    android:scrollbars="none">
</ListView>


text:
import { IController } from 'angular';

import { PageType } from '../../../services/documentation.service';

class EditPageConfigurationComponentController implements IController {
  page: any;

  shouldShowOpenApiDocFormat = false;
  settings: any;

  constructor(private readonly Constants: any) {
    'ngInject';
  }

  isSwagger(): boolean {
    return PageType.SWAGGER === this.page.type;
  }
  isMarkdownTemplate(): boolean {
    return PageType.MARKDOWN_TEMPLATE === this.page.type;
  }

  $onInit() {
    this.settings = this.Constants.env.settings;

    this.shouldShowOpenApiDocFormat =
      this.settings &&
      this.settings.openAPIDocViewer &&
      this.settings.openAPIDocViewer.openAPIDocType.swagger.enabled &&
      this.settings.openAPIDocViewer.openAPIDocType.redoc.enabled;

    if (this.page.type === 'SWAGGER' && !this.page.configuration.viewer) {
      if (this.settings && this.settings.openAPIDocViewer) {
        this.page.configuration.viewer = this.settings.openAPIDocViewer.openAPIDocType.defaultType;
      }
    }
  }

  openApiFormatLabel(format: string) {
    if (this.settings && this.settings.openAPIDocViewer && format === this.settings.openAPIDocViewer.openAPIDocType.defaultType) {
      return `${format} (Default)`;
    } else {
      return format;
    }
  }

  toggleEntrypointAsServer() {
    if (this.page.configuration.entrypointsAsServers === undefined) {
      // Enable adding context-path automatically only the first time user decides to use entrypoint url.
      this.page.configuration.entrypointAsBasePath = 'true';
    }
  }

  usedAsGeneralConditions() {
    return this.page.generalConditions;
  }
}

export const EditPageConfigurationComponent: ng.IComponentOptions = {
  bindings: {
    page: '=',
  },
  template: require('./edit-page-configuration.html'),
  controller: EditPageConfigurationComponentController,
};


text:
module AzPaymentsHelper
  def interkassa_button(ik_request, options={}, &block)
    id = options.fetch(:id, 'interkassa_form')
    title = options.fetch(:title, 'Pay with Interkassa')
    content_tag(:form, :id => id,:name=>id, :action => Interkassa::INTERKASSA_ENDPOINT_URL, :method => :post) do
      result = hidden_field_tag(:ik_shop_id, ik_request.ik_shop_id)+
          text_field_tag(:ik_payment_amount, ik_request.ik_payment_amount)+
          hidden_field_tag(:ik_payment_id, ik_request.ik_payment_id)+
          hidden_field_tag(:ik_payment_desc, ik_request.ik_payment_desc)+
          hidden_field_tag(:ik_paysystem_alias, ik_request.ik_paysystem_alias)+
          hidden_field_tag(:ik_baggage_fields, ik_request.ik_baggage_fields)+
          hidden_field_tag(:ik_success_url, ik_request.ik_success_url)+
          hidden_field_tag(:ik_success_method, ik_request.ik_success_method)+
          hidden_field_tag(:ik_fail_url, ik_request.ik_fail_url)+
          hidden_field_tag(:ik_fail_method, ik_request.ik_fail_method)+
          hidden_field_tag(:ik_status_url, ik_request.ik_status_url)+
          hidden_field_tag(:ik_status_method, ik_request.ik_status_method);
      if block_given?
        result += yield
      else
        result += (' ' + submit_tag(title, :name => nil))
      end
      result
    end
  end
end


text:
'use strict';

var DOM = require('./index');
var resourceLoader = require('jsdom/lib/jsdom/browser/resource-loader');

// -- Patches to JSDOM --

// If JSDOM encounters a JS error, it fires on the element.  We expect it to be
// fires on the Window.  We also want better stack traces.
DOM.languageProcessors.javascript = function (element, buffer, filename) {
  var code = buffer.toString();
  // This may be called without code, e.g. script element that has no body yet
  if (!code) return;

  // Surpress JavaScript validation and execution
  var document = element.ownerDocument;
  var window = document.defaultView;
  var browser = window.top.browser;
  if (browser && !browser.runScripts) return;

  // This may be called without code, e.g. script element that has no body yet
  try {
    window.document._currentScript = element;
    window._evaluate(code, filename);
  } catch (error) {
    if (error.hasOwnProperty('stack')) {
      var cast = new Error(error.message || error.toString());
      cast.stack = error.stack;
      document.raise('error', error.message, { exception: cast });
    } else document.raise('error', error.message, { exception: error });
  } finally {
    window.document._currentScript = null;
  }
};

// HTML5 parser doesn't play well with JSDOM so we need this trickey to sort of
// get script execution to work properly.
//
// Basically JSDOM listend for when the script tag is added to the DOM and
// attemps to evaluate at, but the script has no contents at that point in
// time.  This adds just enough delay for the inline script's content to be
// parsed and ready for processing.
DOM.HTMLScriptElement._init = function () {
  this.addEventListener('DOMNodeInsertedIntoDocument', function () {
    var script = this;
    var document = script.ownerDocument;

    if (script.src)
      // Script has a src attribute, load external resource.
      resourceLoader.load(script, script.src, script._eval);else {
      var filename = script.id ? '' + document.URL + ':#' + script.id : '' + document.URL + ':script';
      // Queue to be executed in order with all other scripts
      var executeInOrder = resourceLoader.enqueue(script, filename, executeInlineScript);
      // There are two scenarios:
      // - script element added to existing document, we should evaluate it
      //   immediately
      // - inline script element parsed, when we get here, we still don't have
      //   the element contents, so we have to wait before we can read and
      //   execute it
      if (document.readyState === 'loading') process.nextTick(executeInOrder);else executeInOrder();
    }

    // Execute inline script
    function executeInlineScript(code, filename) {
      script._eval(script.textContent, filename);
    }
  });
};
//# sourceMappingURL=../dom/scripts.js.map


text:
"""Custom User Manager for user of InaSAFE User Map."""
from builtins import object
from django.contrib.gis.db.models import GeoManager
from django.contrib.auth.models import BaseUserManager
from django.contrib.gis.geos import Point
from django.utils.crypto import get_random_string

class CustomUserManager(BaseUserManager, GeoManager):
    """Custom user manager for user map."""
    class Meta(object):
        """Meta class."""
        app_label = 'user_map'

    def create_user(
            self,
            username=None,
            email=None,
            password=None,
            location=None,
            email_updates=None,
            website='',
            **kwargs):
        """Create and save a User.

        :param username: The name of the user.
        :type username: str

        :param email: The email of the user.
        :type email: str

        :param location: The location of the user in (long, lat)
        :type location: Point

        :param email_updates: The status email_updates of the user.
        :type email_updates: bool

        :param website: The website of the user.
        :type website: str

        :param password: The password of the user.
        :type password: str
        """
        if not username:
            raise ValueError('User must have name.')

        if not email:
            raise ValueError('User must have an email address.')

        if not location:
            raise ValueError('User must have location.')

        if email_updates is None:
            raise ValueError('User must have email_updates status.')

        user = self.model(
            name=username,
            email=self.normalize_email(email),
            location=location,
            email_updates=email_updates,
            website=website,
            key=get_random_string(),
            **kwargs
        )

        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_superuser(self, name, email, password, **kwargs):
        """Create and save a superuser.

        :param name: The name of the superuser.
        :type name: str

        :param email: The email of the superuser.
        :type email: str

        :param password: The password of the superuser.
        :type password:  str
        """
        # Use predefined location, role, email_updates, is_active, is_admin
        location = Point(106.8, -6.2)

        user = self.create_user(
            name,
            email,
            location=location,
            email_updates=True,
            password=password)
        user.email_updates = True
        user.is_confirmed = True
        user.is_active = True
        user.is_admin = True
        user.is_superuser = True
        user.save(using=self._db)
        return user


text:
var gulp = require('gulp');
var stylus = require('gulp-stylus');
var config= require('../config').stylus;

gulp.task('stylus', function () {
  gulp.src(config.src)
    .pipe(stylus())
    .pipe(gulp.dest(config.dest));
});


text:
;(function(){
	'use strict';

	/**
	* Local Storage
	* @type {Object}
	*/
	jQuery.fn.jplist.dal.services.LocalStorageService = {};

	/**
	* Returns if local storage is supported by the given browser
	* @return {boolean}
	*/
	jQuery.fn.jplist.dal.services.LocalStorageService.supported = function(){

		try{
			return 'localStorage' in window && window['localStorage'] !== null;
		}
		catch(e){
			return false;
		}
	};

	/**
	* Save status objects list to local storage
	* @param {Array.<Object>} statuses - list of status objects
	* @param {string} storageName - local storage name
	*/
	jQuery.fn.jplist.dal.services.LocalStorageService.save = function(statuses, storageName){

		var json;

		//get statuses json
		json = JSON.stringify(statuses);

		//save json in local storage
		window.localStorage[storageName] = json;
	};

	/**
	* Restore status objects list from local storage
	* @param {string} storageName - local storage name
	* @return {Array.<Object>} - list of status objects
	*/
	jQuery.fn.jplist.dal.services.LocalStorageService.restore = function(storageName){

		var json
			,statuses = [];

		//get json from local storage
		json = window.localStorage[storageName];

		if(json){

			//get statuses from json
			statuses = jQuery.parseJSON(json);
		}

		if(!statuses){
			statuses = [];
		}

		return statuses;
	};

})();


text:
import sys
import numpy as np

class ReferenceLine:

    def __init__(self):
        self.rl_is_offroad_cnt = 0
        self.rl_minimum_boundary = sys.float_info.max
        self.rl_kappa_rms_list = []
        self.rl_dkappa_rms_list = []
        self.rl_kappa_max_abs_list = []
        self.rl_dkappa_max_abs_list = []

    def put(self, adc_trajectory):
        for ref_line_debug in adc_trajectory.debug.planning_data.reference_line:
            if ref_line_debug.HasField("is_offroad") and ref_line_debug.is_offroad:
                self.rl_is_offroad_cnt += 1
            if ref_line_debug.HasField("minimum_boundary") and \
                ref_line_debug.minimum_boundary < self.rl_minimum_boundary:
                self.rl_minimum_boundary = ref_line_debug.minimum_boundary
            if ref_line_debug.HasField("kappa_rms"):
                self.rl_kappa_rms_list.append(ref_line_debug.kappa_rms)
            if ref_line_debug.HasField("dkappa_rms"):
                self.rl_dkappa_rms_list.append(ref_line_debug.dkappa_rms)
            if ref_line_debug.HasField("kappa_max_abs"):
                self.rl_kappa_max_abs_list.append(ref_line_debug.kappa_max_abs)
            if ref_line_debug.HasField("dkappa_max_abs"):
                self.rl_dkappa_max_abs_list.append(ref_line_debug.dkappa_max_abs)

    def get(self):
        kappa_rms = 0
        if len(self.rl_kappa_rms_list) > 0:
            kappa_rms = np.average(self.rl_kappa_rms_list)

        dkappa_rms = 0
        if len(self.rl_dkappa_rms_list) > 0:
            dkappa_rms = np.average(self.rl_dkappa_rms_list)

        if self.rl_minimum_boundary > 999:
            self.rl_minimum_boundary = 0

        kappa_max_abs = 0
        if len(self.rl_kappa_max_abs_list) > 0:
            kappa_max_abs = max(self.rl_kappa_max_abs_list)

        dkappa_max_abs = 0
        if len(self.rl_dkappa_max_abs_list) > 0:
            dkappa_max_abs = max(self.rl_dkappa_max_abs_list)

        reference_line = {
            "is_offroad" : self.rl_is_offroad_cnt,
            "minimum_boundary" : self.rl_minimum_boundary,
            "kappa_rms" : kappa_rms,
            "dkappa_rms" : dkappa_rms,
            "kappa_max_abs" : kappa_max_abs,
            "dkappa_max_abs" : dkappa_max_abs
        }
        return reference_line


text:
package ninja.egg82.plugin.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ninja.egg82.patterns.ServiceLocator;
import ninja.egg82.utils.ReflectUtil;

public class PluginReflectUtil {
    // vars

    // constructor
    public PluginReflectUtil() {

    }

    // public
    public static int addServicesFromPackage(String packageName, boolean lazyInitialize) {
        return addServicesFromPackage(packageName, lazyInitialize, true);
    }

    public static int addServicesFromPackage(String packageName, boolean lazyInitialize, boolean recursive) {
        if (packageName == null) {
            throw new IllegalArgumentException("packageName cannot be null.");
        }

        List<Class<Object>> services = ReflectUtil.getClasses(Object.class, packageName, recursive, false, false);
        for (Class<Object> service : services) {
            ServiceLocator.provideService(service, lazyInitialize);
        }
        return services.size();
    }

    public static Map<String, String> getCommandMapFromPackage(String packageName, String classNamePrefix, String classNameSuffix) {
        return getCommandMapFromPackage(packageName, true, classNamePrefix, classNameSuffix);
    }

    public static Map<String, String> getCommandMapFromPackage(String packageName, boolean recursive, String classNamePrefix, String classNameSuffix) {
        if (packageName == null) {
            throw new IllegalArgumentException("packageName cannot be null.");
        }

        if (classNamePrefix == null) {
            classNamePrefix = "";
        } else {
            classNamePrefix = classNamePrefix.toLowerCase();
        }
        if (classNameSuffix == null) {
            classNameSuffix = "";
        } else {
            classNameSuffix = classNameSuffix.toLowerCase();
        }

        HashMap<String, String> retVal = new HashMap<String, String>();
        int minLength = classNamePrefix.length() + classNameSuffix.length();

        List<Class<Object>> commands = ReflectUtil.getClasses(Object.class, packageName, recursive, false, false);
        for (Class<Object> c : commands) {
            String n = c.getSimpleName().toLowerCase();
            String p = c.getName();
            p = p.substring(0, p.lastIndexOf('.'));

            if (n.length() <= minLength) {
                continue;
            }

            String cn = n;
            if (!classNamePrefix.isEmpty()) {
                if (!cn.startsWith(classNamePrefix)) {
                    continue;
                }
                cn = cn.substring(classNamePrefix.length());
            }
            if (!classNameSuffix.isEmpty()) {
                if (!cn.endsWith(classNameSuffix)) {
                    continue;
                }
                cn = cn.substring(0, cn.length() - classNameSuffix.length());
            }

            retVal.put(p + "." + n, cn);
        }

        return retVal;
    }

    // private

}


text:
from locust import events, task, User, runners
from locust_plugins import csvreader  # install locust-plugins first

class DemoUser(User):
    reader: csvreader.CSVDictReader

    @task
    def t(self):
        thing = next(self.reader)
        print(thing)

@events.init.add_listener
def on_locust_init(environment, **_kwargs):
    if not isinstance(environment.runner, runners.MasterRunner):
        DemoUser.reader = csvreader.CSVDictReader(f"mythings_{environment.runner.worker_index}.csv")


text:
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace SudoFont
{
	// This draws a string to a Bitmap.
	public class SudoFontTest
	{
		public static Bitmap CreateBitmapFromString( RuntimeFont font, Bitmap pngBitmap, string testString, int startX, int startY, IFont comparisonFont=null )
		{
			// Get the character positions.
			FontLayout.CharacterLayout[] layouts = FontLayout.LayoutCharacters( font, testString, 0, 0 );

			// Draw the character.
			int extraLineSpacing = 5;

			int width = 1;
			int height = 1;

			if ( layouts.Length > 0 )
			{
				width = layouts[ layouts.Length - 1 ].XOffset + font.LineHeight * 2;
				height = layouts[ layouts.Length - 1 ].YOffset + font.LineHeight;
			}

			if ( comparisonFont != null )
			{
				height += font.LineHeight + extraLineSpacing;
			}

			Color textColor = Color.White;

			Bitmap bitmap = new Bitmap( width, height, PixelFormat.Format32bppArgb );
			using ( Graphics g = Graphics.FromImage( bitmap ) )
			{
				g.Clear( Color.Transparent );

				foreach ( FontLayout.CharacterLayout layout in layouts )
				{
					int sfi = layout.SudoFontIndex;
					Rectangle srcRect = new Rectangle( font.Characters[sfi].PackedX, font.Characters[sfi].PackedY, font.Characters[sfi].PackedWidth, font.Characters[sfi].PackedHeight );
					Rectangle destRect = new Rectangle( layout.XOffset, layout.YOffset, srcRect.Width, srcRect.Height );
					g.DrawImage( pngBitmap, destRect, srcRect, GraphicsUnit.Pixel );
				}

				int curY = startY + font.LineHeight + extraLineSpacing;
				if ( comparisonFont != null )
				{
					comparisonFont.DrawString( g, testString, new SolidBrush( textColor ), new Point( 0, curY ) );
					curY += font.LineHeight + extraLineSpacing;
				}
			}

			return bitmap;
		}

		// This is a test that creates a bitmap using a SudoFont.
		// This can be used as reference for code that uses SudoFonts to rasterize text.
		// If you set comparisonFont, it'll render the same string into the bitmap under the SudoFont output.
		// This is useful for verifying/checking how close SudoFonts compare to .NET Graphics text output.
		public static Bitmap CreateBitmapFromString( string fontFilename, string testString, int startX, int startY, IFont comparisonFont=null )
		{
			try
			{
				// Open the font file.
				using ( BinaryReader reader = new BinaryReader( File.OpenRead( fontFilename ) ) )
				{
					// Load the font.
					RuntimeFont font = new RuntimeFont();
					if ( !font.Load( reader ) )
						return null;

					// Load the associated PNG file.
					Bitmap pngBitmap = new Bitmap( Path.ChangeExtension( fontFilename, null ) + "-texture.png" );

					return CreateBitmapFromString( font, pngBitmap, testString, startX, startY, comparisonFont );
				}
			}
			catch ( Exception )
			{
				return null;
			}
		}
	}
}


text:
"""Basic training loop example for Uncertainty Baselines."""

import os.path

from typing import Any, Callable, Dict, Iterator, Optional, Union
from absl import logging
import robustness_metrics as rm
import tensorflow.compat.v2 as tf
import uncertainty_baselines as ub
import eval as eval_lib  # local file import from experimental.single_model_uncertainty
import loss_util as loss_lib  # local file import from experimental.single_model_uncertainty
from tensorboard.plugins.hparams import api as hp

_TensorDict = Dict[str, tf.Tensor]
_TrainStepFn = Callable[[Iterator[_TensorDict]], _TensorDict]

def _train_step_fn(model: tf.keras.Model,
                   optimizer: tf.keras.optimizers.Optimizer,
                   strategy: tf.distribute.Strategy,
                   metrics: Dict[str, Union[tf.keras.metrics.Metric,
                                            rm.metrics.KerasMetric]],
                   iterations_per_loop: int,
                   focal_loss_gamma: float) -> _TrainStepFn:
  """Return a function to run `iterations_per_loop` train steps."""

  # Note that train_iterator should return batches with the global batch size
  # (num_devices * per_core_batch_size).
  @tf.function
  def train_step(train_iterator: Iterator[_TensorDict]) -> _TensorDict:
    def step(per_replica_inputs: _TensorDict) -> None:
      """The function defining a single training step."""
      features = per_replica_inputs['features']
      labels = per_replica_inputs['labels']

      with tf.GradientTape() as tape:
        logits = model(features, training=True)
        if isinstance(logits, (tuple, list)):
          # If model returns a tuple of (logits, covmat), extract logits
          logits, _ = logits
        if focal_loss_gamma > 0.0:
          loss = loss_lib.compute_focal_loss(
              labels, logits, gamma=focal_loss_gamma)
        else:
          loss = tf.reduce_mean(
              tf.keras.losses.sparse_categorical_crossentropy(
                  y_true=labels, y_pred=logits, from_logits=True))

        regularization_losses = model.losses
        if regularization_losses:
          loss += tf.reduce_sum(regularization_losses)
        # Even though features/labels are the per-core batch size, we divide the
        # loss by the number of replicas here because we average the loss and
        # gradients within each batch but then thew ill be SUMMED across
        # replicas, so this division turns the second sum into a mean. See
        # https://www.tensorflow.org/tutorials/distribute/custom_training#define_the_loss_function.
        # This assumes that the per-core batch size is the same for each replica
        # and step, which will be the case because we use padding.
        scaled_loss = loss / strategy.num_replicas_in_sync

      predictions = tf.nn.softmax(logits, axis=-1)
      for metric in metrics.values():
        if isinstance(metric, tf.keras.metrics.Metric):
          metric.update_state(labels, predictions)  # pytype: disable=attribute-error
        else:
          metric.add_batch(predictions, label=labels)
      grads = tape.gradient(scaled_loss, model.trainable_variables)
      optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
      return

    for metric in metrics.values():
      metric.reset_states()
    # Following the recommendation here, run multiple steps inside this training
    # function wrapped in tf.function for better TPU utilization:
    # https://www.kaggle.com/c/flower-classification-with-tpus/discussion/135443.
    for _ in tf.range(iterations_per_loop):  # Note the use of tf.range.
      ub.utils.call_step_fn(strategy, step, next(train_iterator))
    total_results = {name: value.result() for name, value in metrics.items()}
    # Metrics from Robustness Metrics (like ECE) will return a dict with a
    # single key/value, instead of a scalar.
    total_results = {
        k: (list(v.values())[0] if isinstance(v, dict) else v)
        for k, v in total_results.items()
    }
    return total_results

  return train_step

def _write_summaries(
    train_step_outputs: Dict[str, Any],
    current_step: int,
    train_summary_writer: tf.summary.SummaryWriter,
    hparams: Optional[Dict[str, Any]] = None) -> None:
  """Log metrics every using tf.summary."""
  with train_summary_writer.as_default():
    if hparams:
      hp.hparams(hparams)
    for name, result in train_step_outputs.items():
      tf.summary.scalar(name, result, step=current_step)

def run_train_loop(
    train_dataset_builder: ub.datasets.BaseDataset,
    validation_dataset_builder: Optional[ub.datasets.BaseDataset],
    test_dataset_builder: ub.datasets.BaseDataset,
    batch_size: int,
    eval_batch_size: int,
    model: tf.keras.Model,
    optimizer: tf.keras.optimizers.Optimizer,
    eval_frequency: int,
    log_frequency: int,
    trial_dir: str,
    train_steps: int,
    mode: str,
    strategy: tf.distribute.Strategy,
    metrics: Dict[str, Union[tf.keras.metrics.Metric, rm.metrics.KerasMetric]],
    hparams: Dict[str, Any],
    ood_dataset_builder: Optional[ub.datasets.BaseDataset] = None,
    ood_metrics: Optional[Dict[str, tf.keras.metrics.Metric]] = None,
    focal_loss_gamma: float = 0.0,
    mean_field_factor: float = -1,
    dempster_shafer_ood: bool = False):
  """Train, possibly evaluate the model, and record metrics."""

  checkpoint_manager = None
  last_checkpoint_step = 0
  if trial_dir:
    # TODO(znado): add train_iterator to this once DistributedIterators are
    # checkpointable.
    checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model)
    checkpoint_manager = tf.train.CheckpointManager(
        checkpoint, trial_dir, max_to_keep=None)
    checkpoint_path = tf.train.latest_checkpoint(trial_dir)
    if checkpoint_path:
      last_checkpoint_step = int(checkpoint_path.split('-')[-1])
      if last_checkpoint_step >= train_steps:
        # If we have already finished training, exit.
        logging.info(
            'Training has already finished at step %d. Exiting.', train_steps)
        return
      elif last_checkpoint_step > 0:
        # Restore from where we previously finished.
        checkpoint.restore(checkpoint_manager.latest_checkpoint)
        logging.info('Resuming training from step %d.', last_checkpoint_step)

  train_dataset = train_dataset_builder.load(batch_size=batch_size)
  train_dataset = strategy.experimental_distribute_dataset(train_dataset)
  train_iterator = iter(train_dataset)

  iterations_per_loop = min(eval_frequency, log_frequency)
  # We can only run `iterations_per_loop` steps at a time, because we cannot
  # checkpoint the model inside a tf.function.
  train_step_fn = _train_step_fn(
      model,
      optimizer,
      strategy,
      metrics,
      iterations_per_loop=iterations_per_loop,
      focal_loss_gamma=focal_loss_gamma)
  train_summary_writer = tf.summary.create_file_writer(
      os.path.join(trial_dir, 'train'))

  (test_fn, test_dataset, test_summary_writer, val_fn, val_dataset,
   val_summary_writer, ood_fn, ood_dataset,
   ood_summary_writer) = eval_lib.setup_eval(
       validation_dataset_builder=validation_dataset_builder,
       test_dataset_builder=test_dataset_builder,
       batch_size=eval_batch_size,
       strategy=strategy,
       trial_dir=trial_dir,
       model=model,
       metrics=metrics,
       dempster_shafer_ood=dempster_shafer_ood,
       ood_dataset_builder=ood_dataset_builder,
       ood_metrics=ood_metrics,
       mean_field_factor=mean_field_factor)

  # Each call to train_step_fn will run iterations_per_loop steps.
  num_train_fn_steps = train_steps // iterations_per_loop
  # We are guaranteed that `last_checkpoint_step` will be divisible by
  # `iterations_per_loop` because that is how frequently we checkpoint.
  start_train_fn_step = last_checkpoint_step // iterations_per_loop
  for train_fn_step in range(start_train_fn_step, num_train_fn_steps):
    current_step = train_fn_step * iterations_per_loop
    # Checkpoint at the start of the step, before the training op is run.
    if checkpoint_manager and current_step % eval_frequency == 0:
      checkpoint_manager.save(checkpoint_number=current_step)
    if 'eval' in mode and current_step % eval_frequency == 0:
      eval_lib.run_eval_epoch(
          current_step,
          test_fn,
          test_dataset,
          test_summary_writer,
          val_fn,
          val_dataset,
          val_summary_writer,
          ood_fn,
          ood_dataset,
          ood_summary_writer)  # Only write hparams on the last step.
    train_step_outputs = train_step_fn(train_iterator)
    if current_step % log_frequency == 0:
      _write_summaries(train_step_outputs, current_step, train_summary_writer)
      train_step_outputs_np = {
          k: v.numpy() for k, v in train_step_outputs.items()
      }
      logging.info(
          'Training metrics for step %d: %s',
          current_step,
          train_step_outputs_np)

  if train_steps % iterations_per_loop != 0:
    remainder_train_step_fn = _train_step_fn(
        model,
        optimizer,
        strategy,
        metrics,
        iterations_per_loop=train_steps % iterations_per_loop,
        focal_loss_gamma=focal_loss_gamma)
    train_step_outputs = remainder_train_step_fn(train_iterator)

  # Always evaluate and record metrics at the end of training.
  _write_summaries(train_step_outputs, train_steps, train_summary_writer,
                   hparams)
  train_step_outputs_np = {k: v.numpy() for k, v in train_step_outputs.items()}
  logging.info(
      'Training metrics for step %d: %s', current_step, train_step_outputs_np)
  if 'eval' in mode:
    eval_lib.run_eval_epoch(
        train_steps,
        test_fn,
        test_dataset,
        test_summary_writer,
        val_fn,
        val_dataset,
        val_summary_writer,
        ood_fn,
        ood_dataset,
        ood_summary_writer,
        hparams=hparams)
  # Save checkpoint at the end of training.
  if checkpoint_manager:
    checkpoint_manager.save(checkpoint_number=train_steps)


text:
var CoinbaseExchange = require('coinbase-exchange');
var request = require('request');
var async = require('async');
var crypto = require('crypto');

var Coinbase = function (config) {
    this._request = request;
    this._config = config;
};

var publicClient = new CoinbaseExchange.PublicClient();
var authedClient = new CoinbaseExchange.AuthenticatedClient(
    this._config['coinbase.exchangePublicKey'],
    this._config['coinbase.secret'],
    this._config['coinbase.passphrase']
);

Coinbase.prototype._call = function (reqtype, endpoint, params, callback) {

    if(typeof callback === 'undefined') {
        callback = params;
        params = {};
    }

    var timestamp = Date.now();
    var url = this._config['coinbase.coinbaseBaseUrl'] + endpoint;
    var what;
    if(Object.keys(params).length === 0) {
      what = timestamp + url;
    } else {
      what = timestamp + url + JSON.stringify(params);
    }
    var hmac = crypto.createHmac('sha256', this._config['coinbase.coinbaseAPISecret']).update(what).digest('hex');

    var requestOptions = {};
    requestOptions.url = url;
    requestOptions.method = reqtype;
    if(reqtype == 'POST') {
        requestOptions.json = true;
        requestOptions.body = JSON.stringify(params);
    }
    requestOptions.headers = {
        'Accept': 'application/json',
        'ACCESS-KEY': this._config['coinbase.coinbaseApiKey'],
        'ACCESS-SIGNATURE': hmac,
        'ACCESS-NONCE': timestamp
    };

    this._request(requestOptions, function (err, response, body) {
        if (err) return callback('Coinbase GET error: ' + err);
        return callback(null, body);
    });
};

/* Coinbase Exchange API methods */
// done
Coinbase.prototype.buy = function (amount, price, callback) {
    var buyParams = {
        'price' : price,
        'size' : amount,
        'product_id' : 'BTC-USD'
    };
    authedClient.buy(buyParams, function(err, result) {
        if(err) return callback('Coinbase buy error: ' + err);

        authedClient.getOrder(result.id, function(err, order) {
            var fiat = parseFloat(order.size) * parseFloat(order.price);
            callback(null, {
                'datetime': order.created_at,
                'id': order.id,
                'type': order.side,
                'fiat': fiat,
                'xbt': order.size,
                'fee': order.fill_fees,
                'order_id': result.id
            })
        });
    });
};
// done
Coinbase.prototype.sell = function (amount, price, callback) {
    var sellParams = {
        'price' : price,
        'size' : amount,
        'product_id' : 'BTC-USD'
    };
    authedClient.sell(sellParams, function(err, result) {
        if(err) return callback('Coinbase sell error: ' + err);

        authedClient.getOrder(result.id, function(err, order) {
            var fiat = parseFloat(order.size) * parseFloat(order.price);
            callback(null, {
                'datetime': order.created_at,
                'id': order.id,
                'type': order.side,
                'fiat': fiat,
                'xbt': order.size,
                'fee': order.fill_fees,
                'order_id': result.id
            })
        });
    });
};
// done
Coinbase.prototype.getPrices = function (callback) {

    publicClient.getProductTrades('BTC-USD', function(err, result) {
        if(err) return callback('Coinbase get prices err: ' + err);

        callback(null, {
            buyPrice : result[0].price,
            sellPrice : result[1].price
        });
    });
};

/* Coinbase Wallet API methods */
// done
Coinbase.prototype.getBalance = function (callback) {

    this._call('GET', '/accounts/' + this._config['coinbase.coinbaseAccountID'] + '/balance', function(err, balance) {
        if(err) callback("Coinbase get balance error: " + err);

        balance = JSON.parse(balance);

        var url = this._config['coinbase.coinbaseBaseUrl'] + '/prices/sell';
        this._request(url, function(err, res, body) {
            if(err) callback("Coinbase get balance error: " + err);

            body = JSON.parse(body);
            var fiatrate = parseFloat(body.subtotal.amount);
            fiat = fiatrate * parseFloat(balance.amount);
            callback(null, {
                'btc_available': balance.amount,
                'fiat_available': fiat
            });
        });
    });
};
// done
Coinbase.prototype.getDepositAddress = function (callback) {
    var url = '/accounts/' + this._config['coinbase.coinbaseAccountID'] + '/address';
    this._call('GET', url, function(err, addr) {
        addr = JSON.parse(addr);
        callback(null, {
            'address': addr.address
        });
    });
};
// done
Coinbase.prototype.withdraw = function (amount, address, callback) {
    var url = '/transactions/send_money';
    var txn = {
        "to": address,
        "amount": amount,
        "notes": ""
    };
    this._call('POST', url, txn, function(err, res) {
        if(err) callback('Coinbase withdraw error: ' + err);

        res = JSON.parse(res);
        if(res.success == true) {
            callback(null);
        }
    });
};

/* Coinbase Exchange + Wallet account ID methods */
// done
Coinbase.prototype.userTransactions = function (callback) {
    var url = '/transactions';
    var price;

    this.getPrices(function(err, prices) {
        if(err) callback('Coinbase user transactions error: ' + err);
        price = prices.sellPrice;

        this._call('GET', url, function(err, txns) {
            if(err) callback('Coinbase error in user transactions: ' + err);

            var userTransactionsByOrderId = [];
            txns = JSON.parse(txns);

            async.each(txns.transactions, function (txn, eachCallback) {
                var amount = parseFloat(txn.transaction.amount.amount);
                var fiat = amount * price;
                userTransactionsByOrderId[order.id] = {
                    datetime: new Date(txn.transaction.created_at),
                    type: 'withdraw',
                    fiat: fiat,
                    xbt: amount,
                    fee: 0
                };
                return eachCallback();
            }, function (err) {
                if (err) return callback('Error processing trade history: ' + err);

                var txnIds = Object.keys(userTransactionsByOrderId);
                var userTransactions = [];
                for (var i = 0; i < txnIds.length; i++) {
                    userTransactions.push({
                        order_id: txnIds[i],
                        datetime: new Date(txn.transaction.created_at),
                        type: 'withdraw',
                        fiat: txnIds[i].fiat,
                        xbt: txnIds[i].xbt,
                        fee: txnIds[i].fee
                    });
                }
                return callback(null, userTransactions);
            });
        });
    });
};

// hard-coded
Coinbase.prototype.getMinimumOrders = function (callback) {
    return callback(null, { minimumBuy: 0.005, minimumSell: 0.005 });
};
// hard-coded
Coinbase.prototype.getRequiredConfirmations = function () {
    return 6;
};

var coinbase = null;
module.exports = {

    getInstance: function (config) {

        if (coinbase === null) {
            return new Coinbase(config);
        }

        return coinbase;
    },
    clearInstance: function () {
        coinbase = null;
    }
};


text:
"""Abstract class for AES."""

class AES(object):
    def __init__(self, key, mode, IV, implementation):
        if len(key) not in (16, 24, 32):
            raise AssertionError()
        if mode != 2:
            raise AssertionError()
        if len(IV) != 16:
            raise AssertionError()
        self.isBlockCipher = True
        self.block_size = 16
        self.implementation = implementation
        if len(key)==16:
            self.name = "aes128"
        elif len(key)==24:
            self.name = "aes192"
        elif len(key)==32:
            self.name = "aes256"
        else:
            raise AssertionError()

    #CBC-Mode encryption, returns ciphertext
    #WARNING: *MAY* modify the input as well
    def encrypt(self, plaintext):
        assert(len(plaintext) % 16 == 0)

    #CBC-Mode decryption, returns plaintext
    #WARNING: *MAY* modify the input as well
    def decrypt(self, ciphertext):
        assert(len(ciphertext) % 16 == 0)


text:
namespace Microsoft.AspNet.WebApi.HALSupport.Interfaces.Models
{
    /// <summary>
    /// Extension point to provide custom resolution for a value.
    /// </summary>
    public interface IValueResolver
    {
        /// <summary>
        /// Resolves the value.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <returns>The resolved value</returns>
        object Resolve(object sender);

        /// <summary>
        /// Resolves the value.
        /// </summary>
        /// <typeparam name="T">The type to resolve to</typeparam>
        /// <param name="sender">The sender.</param>
        /// <returns>The resolved value</returns>
        T Resolve<T>(object sender);

        /// <summary>
        /// Resolves the value.
        /// </summary>
        /// <typeparam name="T">The type to resolve to</typeparam>
        /// <param name="sender">The sender.</param>
        /// <param name="value">The value.</param>
        /// <returns><c>true</c> if the resolving was successful, <c>false</c> otherwise.</returns>
        bool Resolve<T>(object sender, out T value);
    }
}


text:
package cz.kec.wls.feedcombiner.datastore.impl;

import cz.kec.wls.feedcombiner.datastore.DaoFactory;
import cz.kec.wls.feedcombiner.datastore.InMemoryDataStore;
import cz.kec.wls.feedcombiner.model.CombinedFeed;
import cz.kec.wls.feedcombiner.utils.JSONUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 * Testing of InMemoryDataStore implementation.
 *
 * @author Daniel Kec <daniel at kecovi.cz>
 */
public class InMemoryDataStoreSingletonTest {

    private static final String SAVED_IN_MEMORY_STORE =
"rO0ABXNyACZqYXZhLnV0aWwuY29uY3VycmVudC5Db25jdXJyZW50SGFzaE1hcGSZ3hKdhyk9AwAD\n" +
"SQALc2VnbWVudE1hc2tJAAxzZWdtZW50U2hpZnRbAAhzZWdtZW50c3QAMVtMamF2YS91dGlsL2Nv\n" +
"bmN1cnJlbnQvQ29uY3VycmVudEhhc2hNYXAkU2VnbWVudDt4cAAAAA8AAAAcdXIAMVtMamF2YS51\n" +
"dGlsLmNvbmN1cnJlbnQuQ29uY3VycmVudEhhc2hNYXAkU2VnbWVudDtSdz9BMps5dAIAAHhwAAAA\n" +
"EHNyAC5qYXZhLnV0aWwuY29uY3VycmVudC5Db25jdXJyZW50SGFzaE1hcCRTZWdtZW50HzZMkFiT\n" +
"KT0CAAFGAApsb2FkRmFjdG9yeHIAKGphdmEudXRpbC5jb25jdXJyZW50LmxvY2tzLlJlZW50cmFu\n" +
"dExvY2tmVagsLMhq6wIAAUwABHN5bmN0AC9MamF2YS91dGlsL2NvbmN1cnJlbnQvbG9ja3MvUmVl\n" +
"bnRyYW50TG9jayRTeW5jO3hwc3IANGphdmEudXRpbC5jb25jdXJyZW50LmxvY2tzLlJlZW50cmFu\n" +
"dExvY2skTm9uZmFpclN5bmNliDLnU3u/CwIAAHhyAC1qYXZhLnV0aWwuY29uY3VycmVudC5sb2Nr\n" +
"cy5SZWVudHJhbnRMb2NrJFN5bmO4HqKUqkRafAIAAHhyADVqYXZhLnV0aWwuY29uY3VycmVudC5s\n" +
"b2Nrcy5BYnN0cmFjdFF1ZXVlZFN5bmNocm9uaXplcmZVqEN1P1LjAgABSQAFc3RhdGV4cgA2amF2\n" +
"YS51dGlsLmNvbmN1cnJlbnQubG9ja3MuQWJzdHJhY3RPd25hYmxlU3luY2hyb25pemVyM9+vua1t\n" +
"b6kCAAB4cAAAAAA/QAAAc3EAfgAFc3EAfgAJAAAAAD9AAABzcQB+AAVzcQB+AAkAAAAAP0AAAHNx\n" +
"AH4ABXNxAH4ACQAAAAA/QAAAc3EAfgAFc3EAfgAJAAAAAD9AAABzcQB+AAVzcQB+AAkAAAAAP0AA\n" +
"AHNxAH4ABXNxAH4ACQAAAAA/QAAAc3EAfgAFc3EAfgAJAAAAAD9AAABzcQB+AAVzcQB+AAkAAAAA\n" +
"P0AAAHNxAH4ABXNxAH4ACQAAAAA/QAAAc3EAfgAFc3EAfgAJAAAAAD9AAABzcQB+AAVzcQB+AAkA\n" +
"AAAAP0AAAHNxAH4ABXNxAH4ACQAAAAA/QAAAc3EAfgAFc3EAfgAJAAAAAD9AAABzcQB+AAVzcQB+\n" +
"AAkAAAAAP0AAAHNxAH4ABXNxAH4ACQAAAAA/QAAAdAAtS0VZU0VUX0tFWV9NSUlDZGdJQkFEQU5C\n" +
"Z2txaGtpRzl3MEJBUUVGQUFTQ0Ftc3IANWN6LmtlYy53bHMuZmVlZGNvbWJpbmVyLmRhdGFzdG9y\n" +
"ZS5pbXBsLkluTWVtb3J5S2V5U2V0r6iitNzp+gUCAAB4cgAoamF2YS51dGlsLmNvbmN1cnJlbnQu\n" +
"Q29weU9uV3JpdGVBcnJheVNldEu90JKQFWnXAgABTAACYWx0ACtMamF2YS91dGlsL2NvbmN1cnJl\n" +
"bnQvQ29weU9uV3JpdGVBcnJheUxpc3Q7eHBzcgApamF2YS51dGlsLmNvbmN1cnJlbnQuQ29weU9u\n" +
"V3JpdGVBcnJheUxpc3R4XZ/VRquQwwMAAHhwdwQAAAABdAAEdGVzdHhxAH4AM3NyACpjei5rZWMu\n" +
"d2xzLmZlZWRjb21iaW5lci5tb2RlbC5Db21iaW5lZEZlZWTBcZ4mwcTzLQIABUwAC2Rlc2NyaXB0\n" +
"aW9udAASTGphdmEvbGFuZy9TdHJpbmc7TAALZW5jb2RlZE5hbWVxAH4ANUwAB2VudHJpZXN0ABBM\n" +
"amF2YS91dGlsL0xpc3Q7TAAEbmFtZXEAfgA1TAAEdXJpc3EAfgA2eHB0AAp0ZXN0IHBvcGlzcQB+\n" +
"ADNzcgATamF2YS51dGlsLkFycmF5TGlzdHiB0h2Zx2GdAwABSQAEc2l6ZXhwAAAAAHcEAAAAAHhx\n" +
"AH4AM3NxAH4AOQAAAAV3BAAAAAVzcgAMamF2YS5uZXQuVVJJrAF4LkOeSasDAAFMAAZzdHJpbmdx\n" +
"AH4ANXhwdAAmaHR0cDovL3d3dy5yZWRkaXQuY29tL3Ivd29ybGRuZXdzLy5yc3N4c3EAfgA8dAAh\n" +
"aHR0cDovL3d3dy5yZWRkaXQuY29tL3IvamF2YS8ucnNzeHNxAH4APHQAIWh0dHA6Ly93d3cuYnV6\n" +
"emZlZWQuY29tL2luZGV4LnhtbHhzcQB+ADx0ACpodHRwOi8vZmVlZHMuZHpvbmUuY29tL2phdmFs\n" +
"b2JieS9mcm9udHBhZ2V4c3EAfgA8dABGaHR0cDovL2ZlZWRzLmRlbGljaW91cy5jb20vdjIvcnNz\n" +
"L09yYWNsZVRlY2hub2xvZ3lOZXR3b3JrL290bmhlYWRsaW5lc3h4cHB4";

    private CombinedFeed savedCombinedFeed;

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
        this.savedCombinedFeed = new CombinedFeed("test", "test popis");
        List<URI> uris = savedCombinedFeed.getUris();
        uris.add(URI.create("http://www.reddit.com/r/worldnews/.rss"));
        uris.add(URI.create("http://www.reddit.com/r/java/.rss"));
        uris.add(URI.create("http://www.buzzfeed.com/index.xml"));
        uris.add(URI.create("http://feeds.dzone.com/javalobby/frontpage"));
        uris.add(URI.create("http://feeds.delicious.com/v2/rss/OracleTechnologyNetwork/otnheadlines"));
    }

    /**
     * Test of getInstance method, of class InMemoryDataStoreSingleton.
     */
    @Test
    public void testGetInstance() {
        System.out.println("getInstance");
        DaoFactory.getCombinedFeedDao().deleteAllCombinedFeeds();//polution from other tests
        InMemoryDataStoreSingleton result = InMemoryDataStoreSingleton.getInstance();
        assertNotNull(result);
    }

    /**
     * Test of put method, of class InMemoryDataStoreSingleton.
     */
    @Test(expected=ClassCastException.class)
    public void testGetClassCast() {
        System.out.println("put");
        String key = "testGetClassCast";
        String data = "data";
        InMemoryDataStore instance = InMemoryDataStoreSingleton.getInstance();
        assertNull(instance.put(key, data));
        assertEquals("data",instance.get(key, String.class));
        Serializable result = instance.get(key, Integer.class);
        fail("Should throw ClassCastException");
    }

    /**
     * Test of put method, of class InMemoryDataStoreSingleton.
     */
    @Test
    public void testPutGetOldValue() {
        System.out.println("testPutGetOldValue");
        String key = "testPutGetOldValue";
        String data = "data";
        String data2 = "data2";
        InMemoryDataStoreSingleton instance = InMemoryDataStoreSingleton.getInstance();
        assertNull(instance.put(key, data));
        assertEquals(data,instance.put(key, data2));
        assertEquals(data2,instance.get(key, String.class));
    }

    /**
     * Test of put method, of class InMemoryDataStoreSingleton.
     */
    @Test(expected=Exception.class)
    public void testPutWithKeyNull() {
        System.out.println("testPutGetOldValue");
        String key = null;
        String data = "data";
        InMemoryDataStoreSingleton instance = InMemoryDataStoreSingleton.getInstance();
        instance.put(key, data);
    }

    /**
     * Test of get method, of class InMemoryDataStoreSingleton.
     */
    @Test
    public void testGet() {
        System.out.println("testGet");
        InMemoryDataStoreSingleton instance = InMemoryDataStoreSingleton.getInstance();
        Object result = instance.get("key",String.class);
        assertNull(result);
    }

    /**
     * Test of get method, of class InMemoryDataStoreSingleton.
     */
    @Test
    public void testGetNull() {
        System.out.println("testGetNull");
        InMemoryDataStoreSingleton instance = InMemoryDataStoreSingleton.getInstance();
        Object result = instance.get("key",String.class);
        assertNull(result);
    }

    /**
     * Test of save method, testing if output stream is not closing
     */
    @Test
    public void testSave() throws Exception {
        System.out.println("testSave");
        DaoFactory.getCombinedFeedDao().deleteAllCombinedFeeds();//its singleton other tests can polute it
        DaoFactory.getCombinedFeedDao().createCombinedFeed(savedCombinedFeed);
        CloseAwareOutputStream out = new CloseAwareOutputStream();
        Assert.assertFalse(out.isClosed);
        InMemoryDataStoreSingleton inMemoryDataStore = InMemoryDataStoreSingleton.getInstance();
        inMemoryDataStore.save(out);
        Assert.assertFalse(out.isClosed);
        out.close();
        Assert.assertTrue(out.isClosed);
        //System.out.println(new String(Base64.encodeBase64Chunked(out.toByteArray())));
        Assert.assertArrayEquals(Base64.decodeBase64(SAVED_IN_MEMORY_STORE), out.toByteArray());
    }

    /**
     * Test of load method, , testing if input stream is not closing
     * @throws java.lang.Exception
     */
    @Test
    public void testLoad() throws Exception {
        System.out.println("testLoad");
        CloseAwareInputStream is = new CloseAwareInputStream(Base64.decodeBase64(SAVED_IN_MEMORY_STORE));
        InMemoryDataStoreSingleton inMemoryDataStore = InMemoryDataStoreSingleton.getInstance();
        DaoFactory.getCombinedFeedDao().deleteAllCombinedFeeds();//polution from other tests
        inMemoryDataStore.load(is);
        Assert.assertFalse(is.isClosed);
        is.close();
        Assert.assertTrue(is.isClosed);

        CombinedFeed combinedFeed = DaoFactory.getCombinedFeedDao().getAllCombinedFeeds().get(0);
        assertEquals(JSONUtils.toJSON(savedCombinedFeed), JSONUtils.toJSON(combinedFeed));
    }

    /**
     * Used for testing if inputstream has been closed
     */
    private static class CloseAwareInputStream extends ByteArrayInputStream{
        private boolean isClosed = false;

        public CloseAwareInputStream(byte[] buf) {
            super(buf);
        }

        @Override
        public void close() throws IOException {
            super.close();
            this.isClosed = true;
        }

        public boolean isClosed() {
            return isClosed;
        }
    }
    /**
     * Used for testing if outputstream has been closed
     */
    private static class CloseAwareOutputStream extends ByteArrayOutputStream{
        private boolean isClosed = false;

        @Override
        public void close() throws IOException {
            super.close();
            this.isClosed = true;
        }

        public boolean isClosed() {
            return isClosed;
        }
    }
}


text:
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook

class TestCompareXLSXFiles(ExcelComparisonTest):
    """
    Test file created by XlsxWriter against a file created by Excel.

    """

    def setUp(self):

        self.set_filename('chart_gap04.xlsx')

    def test_create_file(self):
        """Test the creation of a simple XlsxWriter file."""

        workbook = Workbook(self.got_filename)

        worksheet = workbook.add_worksheet()
        chart = workbook.add_chart({'type': 'column'})

        chart.axis_ids = [45938176, 59715584]
        chart.axis2_ids = [62526208, 59718272]

        data = [[1, 2, 3, 4, 5],
                [6, 8, 6, 4, 2]]

        worksheet.write_column('A1', data[0])
        worksheet.write_column('B1', data[1])

        chart.add_series({'values': '=Sheet1!$A$1:$A$5',
                          'gap': 51,
                          'overlap': 12})
        chart.add_series({'values': '=Sheet1!$B$1:$B$5',
                          'y2_axis': 1,
                          'gap': 251,
                          'overlap': -27})

        worksheet.insert_chart('E9', chart)

        workbook.close()

        self.assertExcelEqual()


text:
CREATE TABLE users(
	id INTEGER AUTO_INCREMENT,
	first_name VARCHAR(30),
	last_name VARCHAR(30),
    email VARCHAR(60),
    password VARCHAR(20),
    is_locked INTEGER,
    is_verified INTEGER,
    created_at DATETIME,
    updated_at DATETIME,
    last_accessed DATETIME,
    img_url VARCHAR(100),
    PRIMARY KEY (id, email),
    UNIQUE KEY users_email_unique (EMAIL)
)ENGINE=INNODB;

CREATE TABLE tasks (
	id INTEGER AUTO_INCREMENT,
	user_id INTEGER,
	name VARCHAR(30),
	info TEXT,
	task_date DATE,
	start_time TIME,
	end_time TIME,
	status INTEGER,
	created_at DATETIME,
	updated_at DATETIME,
	is_deleted INTEGER,
	PRIMARY KEY(id),
	FOREIGN KEY fk_task (user_id) REFERENCES users (id)
) ENGINE=INNODB;

CREATE TABLE task_status (
	id INTEGER,
	status VARCHAR(30)
) ENGINE=INNODB;

CREATE TABLE group_tasks (
	id INTEGER AUTO_INCREMENT,
	task_id INTEGER,
	shared_with INTEGER,
	is_deleted INTEGER,
	created_at DATETIME,
	updated_at DATETIME,
	PRIMARY KEY (id),
	FOREIGN KEY fk_task_id (task_id) REFERENCES tasks (id),
	FOREIGN KEY fk_contributor (shared_with) REFERENCES users (id)
)ENGINE=INNODB;

CREATE TABLE friends (
	user_id INTEGER,
	friend_id INTEGER,
	status INTEGER,
	created_at DATETIME,
	is_deleted INTEGER,
	PRIMARY KEY (user_id, friend_id),
	FOREIGN KEY fk_user_id (user_id) REFERENCES users (id),
	FOREIGN KEY fk_friend_id (friend_id) REFERENCES users (id)
)ENGINE=INNODB;

CREATE TABLE friends_status (
	id INTEGER,
	status VARCHAR(30)
) ENGINE=INNODB;

CREATE TABLE task_media (
	id INTEGER AUTO_INCREMENT,
	task_id INTEGER,
	user_id INTEGER,
	file_url VARCHAR(100),
	is_deleted INTEGER,
	created_at DATETIME,
	updated_at DATETIME,
	PRIMARY KEY (id),
	FOREIGN KEY fk_task_id_media (task_id) REFERENCES tasks (id),
	FOREIGN KEY fk_contributor_media (user_id) REFERENCES users (id)
) ENGINE=INNODB;

CREATE TABLE location (
    id int AUTO_INCREMENT NOT NULL,
    name VARCHAR(60) NOT NULL ,
    address VARCHAR(80) NOT NULL ,
    lat DECIMAL(10, 8) NOT NULL,
    lng DECIMAL(11, 8) NOT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE recover (
	id INTEGER,
	used INTEGER,
    token VARCHAR(100),
    expr_date DATETIME,
    PRIMARY KEY (id, token),
) ENGINE=INNODB;


text:
package sample.dms;

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

import org.springframework.util.Assert;

/**
 * @author Ben Alex
 *
 */
public abstract class AbstractElement {
	/** The name of this token (a filename or directory segment name */
	private String name;

	/** The parent of this token (a directory, or null if referring to root) */
	private AbstractElement parent;

	/** The database identifier for this object (null if not persisted) */
	private Long id;

	/**
	 * Constructor to use to represent a root element. A root element has an id of -1.
	 */
	protected AbstractElement() {
		this.name = "/";
		this.parent = null;
		this.id = -1L;
	}

	/**
	 * Constructor to use to represent a non-root element.
	 *
	 * @param name name for this element (required, cannot be "/")
	 * @param parent for this element (required, cannot be null)
	 */
	protected AbstractElement(String name, AbstractElement parent) {
		Assert.hasText(name, "Name required");
		Assert.notNull(parent, "Parent required");
		Assert.notNull(parent.getId(),
				"The parent must have been saved in order to create a child");
		this.name = name;
		this.parent = parent;
	}

	public Long getId() {
		return id;
	}

	/**
	 * @return the name of this token (never null, although will be "/" if root, otherwise
	 * it won't include separators)
	 */
	public String getName() {
		return name;
	}

	public AbstractElement getParent() {
		return parent;
	}

	/**
	 * @return the fully-qualified name of this element, including any parents
	 */
	public String getFullName() {
		List<String> strings = new ArrayList<>();
		AbstractElement currentElement = this;
		while (currentElement != null) {
			strings.add(0, currentElement.getName());
			currentElement = currentElement.getParent();
		}

		StringBuilder sb = new StringBuilder();
		String lastCharacter = null;
		for (String token : strings) {
			if (!"/".equals(lastCharacter) && lastCharacter != null) {
				sb.append("/");
			}
			sb.append(token);
			lastCharacter = token.substring(token.length() - 1);
		}
		return sb.toString();
	}
}


text:
<?php

namespace PurpleBooth\WeatherApp\Test\Context;

use Behat\Behat\Context\Context;
use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;

/**
 * Defines application features from the specific context.
 */
class ApiContext implements Context, SnippetAcceptingContext
{

    /**
     * @var \Behat\MinkExtension\Context\MinkContext
     */
    private $minkContext;

    /**
     * Set the mink context
     *
     * @param BeforeScenarioScope $scope The event
     *
     * @BeforeScenario
     */
    public function gatherContexts(BeforeScenarioScope $scope)
    {
        $environment = $scope->getEnvironment();

        /** @var \Behat\MinkExtension\Context\MinkContext minkContext */
        $this->minkContext = $environment->getContext('Behat\MinkExtension\Context\MinkContext');
    }

    /**
     * @When I request the weather from the API for postcode :postcode
     *
     * @param string $postcode The postcode
     */
    public function iRequestTheWeatherFromTheApiForPostcode($postcode)
    {
        $this->minkContext->visit('/api/v1/' . urlencode($postcode));
    }

    /**
     * @Then the response should contain the weather :weather
     *
     * @param string $weather The expected weather
     *
     * @throws \Exception
     */
    public function theResponseShouldContainTheWeather2($weather)
    {
        if (!$this->minkContext->getSession()->getPage()->hasContent(json_encode(['description' => $weather]))) {
            throw new \Exception("No weather");
        }
    }
}


text:
package grumpy

import (
	"reflect"
	"sync"
)

var (
	// GeneratorType is the object representing the Python 'generator' type.
	GeneratorType = newBasisType("generator", reflect.TypeOf(Generator{}), toGeneratorUnsafe, ObjectType)
)

type generatorState int

const (
	generatorStateCreated generatorState = iota
	generatorStateReady
	generatorStateRunning
	generatorStateDone
)

// Generator represents Python 'generator' objects.
type Generator struct {
	Object
	mutex sync.Mutex
	state generatorState
	frame *Frame
	fn    func(*Object) (*Object, *BaseException)
}

// NewGenerator returns a new Generator object that runs the given Block b.
func NewGenerator(f *Frame, fn func(*Object) (*Object, *BaseException)) *Generator {
	f.taken = true // Claim the frame from being returned.

	// The code generator basically gives us the Frame, so we can tare it
	// off and prevent a parasitic `taken` from creeping up the frames.
	f.back = nil

	return &Generator{Object: Object{typ: GeneratorType}, frame: f, fn: fn}
}

func toGeneratorUnsafe(o *Object) *Generator {
	return (*Generator)(o.toPointer())
}

func (g *Generator) resume(f *Frame, sendValue *Object) (*Object, *BaseException) {
	var raised *BaseException
	g.mutex.Lock()
	oldState := g.state
	switch oldState {
	case generatorStateCreated:
		if sendValue != None {
			raised = f.RaiseType(TypeErrorType, "can't send non-None value to a just-started generator")
		} else {
			g.state = generatorStateRunning
		}
	case generatorStateReady:
		g.state = generatorStateRunning
	case generatorStateRunning:
		raised = f.RaiseType(ValueErrorType, "generator already executing")
	case generatorStateDone:
		raised = f.Raise(StopIterationType.ToObject(), nil, nil)
	}
	g.mutex.Unlock()
	// Concurrent attempts to transition to running state will raise here
	// so it's guaranteed that only one thread will proceed to execute the
	// block below.
	if raised != nil {
		return nil, raised
	}
	g.frame.pushFrame(f)
	result, raised := g.fn(sendValue)
	g.mutex.Lock()
	if result == nil && raised == nil {
		raised = f.Raise(StopIterationType.ToObject(), nil, nil)
	}
	if raised == nil {
		g.frame.PopCheckpoint()
		g.state = generatorStateReady
	} else {
		g.state = generatorStateDone
	}
	g.mutex.Unlock()
	return result, raised
}

// ToObject upcasts g to an Object.
func (g *Generator) ToObject() *Object {
	return &g.Object
}

func generatorIter(f *Frame, o *Object) (*Object, *BaseException) {
	return o, nil
}

func generatorNext(f *Frame, o *Object) (*Object, *BaseException) {
	return toGeneratorUnsafe(o).resume(f, None)
}

func generatorSend(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
	if raised := checkMethodArgs(f, "send", args, GeneratorType, ObjectType); raised != nil {
		return nil, raised
	}
	return toGeneratorUnsafe(args[0]).resume(f, args[1])
}

func initGeneratorType(dict map[string]*Object) {
	dict["send"] = newBuiltinFunction("send", generatorSend).ToObject()
	GeneratorType.flags &= ^(typeFlagBasetype | typeFlagInstantiable)
	GeneratorType.slots.Iter = &unaryOpSlot{generatorIter}
	GeneratorType.slots.Next = &unaryOpSlot{generatorNext}
}


text:
namespace _01.GenerateRandomNumberHtmlControls {

    public partial class ViewSwitcher {
    }
}


text:
Function New-OutputFile {
<#

    .SYNOPSIS
    Function intended for preparing a PowerShell object for output files like reports or logs.

    .DESCRIPTION
    Function intended for preparing a PowerShell custom object what contains e.g. file name for output/create files like reports or log. The name is prepared based on prefix, middle name part, suffix, date, etc. with verification if provided path exist and is it writable.

    Returned object contains properties
    - OutputFilePath - to use it please check examples - as a [System.IO.FileInfo]
    - ExitCode
    - ExitCodeDescription

    Exit codes and descriptions
    - 0 = "Everything is fine :-)"
    - 1 = "Provided parent path <PATH> doesn't exist"
    - 2 = "The result name contains unacceptable chars"
    - 3 = "Provided patch <PATH> is not writable"
    - 4 = "The file <PATH>\\<FILE_NAME> already exist - can be overwritten"
    - 5 = "The file <PATH>\\<FILE_NAME> already exist - can't be overwritten"
    - 6 = "The file <PATH>\\<FILE_NAME> already exist - can be overwritten due to used the Force switch"

    .PARAMETER ParentPath
    The folder path what will be used as the parent path for the new created object.
    When non existing path will be provided the error code will be returned.

    By default output files are stored in the current path.

    .PARAMETER OutputFileNamePrefix
    Prefix used for creating output files name

    .PARAMETER OutputFileNameMidPart
    Part of the name which will be used in midle of output file name

    .PARAMETER OutputFileNameSuffix
    Part of the name which will be used at the end of output file name

    .PARAMETER IncludeDateTimePartInOutputFileName
    Set to TRUE if report file name should contains part based on date and time - format yyyyMMdd-HHmm is used

    .PARAMETER DateTimePartInOutputFileName
    Set to date and time which should be used in output file name, by default current date and time is used

    .PARAMETER DateTimePartFormat
    Format string used to format date and time in output file name.

    .PARAMETER OutputFileNameExtension
    Set to extension which need to be used for output file, by default ".txt" is used

    .PARAMETER NamePartsSeparator
    A char used to separate parts in the name, by default "-" is used

    .PARAMETER BreakIfError
    Break function execution if parameters provided for output file creation are not correct or destination file path is not writables

    .PARAMETER Force
    If used the function Doesn't ask for an overwrite decission, assumes that the file can be overwritten

    .EXAMPLE

    PS \> (Get-Item env:COMPUTERNAME).Value
    WXDX75

    PS \> $FileNeeded = @{
        ParentPath = 'C:\USERS\UserName\';
        OutputFileNamePrefix = 'Messages';
        OutputFileNameMidPart = (Get-Item env:COMPUTERNAME).Value;
        IncludeDateTimePartInOutputFileName = $true;
        BreakIfError = $true
    }

    PS \> $PerServerReportFileMessages = New-OutputFile @FileNeeded

    PS \> $PerServerReportFileMessages | Format-List

    OutputFilePath      : C:\users\UserName\Messages-WXDX75-20151021-001205.txt
    ExitCode            : 0
    ExitCodeDescription : Everything is fine :-)

    PS \> New-Item -Path $PerServerReportFileMessages.OutputFilePath -ItemType file

    Directory: C:\USERS\UserName

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    -a----       21/10/2015     00:12              0 Messages-WXDX75-20151021-001205.txt

    The file created on provided parameters.
    Under preparation the file name is created, provided part of names are used, and availability of name (if the file exist now) is checked.

    .EXAMPLE

    $FileNeeded = @{
        ParentPath = 'C:\USERS\UserName\';
        OutputFileNamePrefix = 'Messages';
        OutputFileNameMidPart = 'COMPUTERNAME';
        IncludeDateTimePartInOutputFileName = $false;
        OutputFileNameExtension = "csv";
        OutputFileNameSuffix = "failed"
    }

    PS \> $PerServerReportFileMessages = New-OutputFile @FileNeeded

    PS \> $PerServerReportFileMessages.OutputFilePath | Select-Object -Property Name,Extension,Directory | Format-List

    Name      : Messages-COMPUTERNAME-failed.csv
    Extension : .csv
    Directory : C:\USERS\UserName

    PS \> ($PerServerReportFileMessages.OutputFilePath).gettype()

    IsPublic IsSerial Name                                     BaseType
    -------- -------- ----                                     --------
    True     True     FileInfo                                 System.IO.FileSystemInfo

    PS \> Test-Path ($PerServerReportFileMessages.OutputFilePath)
    False

    The funciton return object what contain the property named OutputFilePath what is the object of type System.IO.FileSystemInfo.

    File is not created. Only the object in the memory is prepared.

    .OUTPUTS
    System.Object[]

    .LINK
    https://github.com/it-praktyk/New-OutputObject

    .LINK
    https://www.linkedin.com/in/sciesinskiwojciech

    .NOTES
    AUTHOR: Wojciech Sciesinski, wojciech[at]sciesinski[dot]net
    KEYWORDS: PowerShell, File, FileSystem

    CURRENT VERSION
    - 0.9.12 - 2018-05-01

    HISTORY OF VERSIONS
    https://github.com/it-praktyk/New-OutputObject/CHANGELOG.md

    LICENSE
    Copyright (c) 2016 Wojciech Sciesinski
    This function is licensed under The MIT License (MIT)
    Full license text: https://opensource.org/licenses/MIT

    #>

    [cmdletbinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions','')]
    [OutputType([System.Object[]])]
    param (
        [parameter(Mandatory = $false)]
        [String]$ParentPath = ".",
        [parameter(Mandatory = $false)]
        [String]$OutputFileNamePrefix = "Output",
        [parameter(Mandatory = $false)]
        [String]$OutputFileNameMidPart = $null,
        [parameter(Mandatory = $false)]
        [String]$OutputFileNameSuffix = $null,
        [parameter(Mandatory = $false)]
        [Bool]$IncludeDateTimePartInOutputFileName = $true,
        [parameter(Mandatory = $false)]
        [Nullable[DateTime]]$DateTimePartInOutputFileName = $null,
        [Parameter(Mandatory = $false)]
        [String]$DateTimePartFormat = "yyyyMMdd-HHmmss",
        [parameter(Mandatory = $false)]
        [String]$OutputFileNameExtension = ".txt",
        [parameter(Mandatory = $false)]
        [alias("Separator")]
        [String]$NamePartsSeparator = "-",
        [parameter(Mandatory = $false)]
        [Switch]$BreakIfError,
        [parameter(Mandatory = $false)]
        [Switch]$Force
    )

    $params = @{

        ObjectType = 'File'

        ParentPath = $ParentPath

        OutputObjectNamePrefix = $OutputFileNamePrefix

        OutputObjectNameMidPart = $OutputFileNameMidPart

        OutputObjectNameSuffix = $OutputFileNameSuffix

        IncludeDateTimePartInOutputObjectName = $IncludeDateTimePartInOutputFileName

        DateTimePartInOutputObjectName = $DateTimePartInOutputFileName

        DateTimePartFormat = $DateTimePartFormat

        OutputFileNameExtension = $OutputFileNameExtension

        NamePartsSeparator = $NamePartsSeparator

        BreakIfError = $BreakIfError

        Force = $Force

    }

    $Result = New-OutputObject @params

    Return $Result
}


text:
/* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* ====================================================================
 * Copyright (c) 2008 Carnegie Mellon University.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * This work was supported in part by funding from the Defense Advanced
 * Research Projects Agency and the National Science Foundation of the
 * United States of America, and the CMU Sphinx Speech Consortium.
 *
 * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND
 * ANY EXPRESSED 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 CARNEGIE MELLON UNIVERSITY
 * NOR ITS EMPLOYEES 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.
 *
 * ====================================================================
 *
 */

/**
 * @file phone_loop_search.h Fast and rough context-independent
 * phoneme loop search.
 *
 * This exists for the purposes of phoneme lookahead, and thus it
 * actually does not do phoneme recognition (it wouldn't be very
 * accurate anyway).
 */

#ifndef __PHONE_LOOP_SEARCH_H__
#define __PHONE_LOOP_SEARCH_H__

/* SphinxBase headers. */
#include "cmd_ln.h"
#include "logmath.h"
#include "ngram_model.h"
#include "listelem_alloc.h"

/* Local headers. */
#include "pocketsphinx_internal.h"
#include "hmm.h"

/**
 * Phone loop structure.
 */
struct phone_loop_s {
    hmm_t hmm;       /**< Basic HMM structure. */
    int16 ciphone;   /**< Context-independent phone ID. */
    int16 frame;     /**< Last frame this phone was active. */
};
typedef struct phone_loop_s phone_loop_t;

/**
 * Renormalization event.
 */
struct phone_loop_renorm_s {
    int frame_idx;  /**< Frame of renormalization. */
    int32 norm;     /**< Normalization constant. */
};
typedef struct phone_loop_renorm_s phone_loop_renorm_t;

/**
 * Phone loop search structure.
 */
struct phone_loop_search_s {
    ps_search_t base;       /**< Base search structure. */
    hmm_context_t *hmmctx;  /**< HMM context structure. */
    int16 frame;            /**< Current frame being searched. */
    int16 n_phones;         /**< Size of phone array. */
    phone_loop_t *phones;   /**< Array of phone arcs. */

    int32 best_score;       /**< Best Viterbi score in current frame. */
    int32 beam;             /**< HMM pruning beam width. */
    int32 pbeam;            /**< Phone exit pruning beam width. */
    int32 pip;              /**< Phone insertion penalty ("language score"). */
    glist_t renorm;         /**< List of renormalizations. */
};
typedef struct phone_loop_search_s phone_loop_search_t;

ps_search_t *phone_loop_search_init(cmd_ln_t *config,
                                    acmod_t *acmod,
                                    dict_t *dict);

/**
 * Return lookahead heuristic score for a specific phone.
 */
#define phone_loop_search_score(pls,ci) \
    ((pls == NULL) ? 0                                          \
     : (hmm_bestscore(&pls->phones[ci].hmm) - (pls)->best_score))

#endif /* __PHONE_LOOP_SEARCH_H__ */