text:
namespace google {
namespace cloud {
namespace datastream_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

DatastreamMetadata::DatastreamMetadata(std::shared_ptr<DatastreamStub> child)
    : child_(std::move(child)),
      api_client_header_(
          google::cloud::internal::ApiClientHeader("generator")) {}

StatusOr<google::cloud::datastream::v1::ListConnectionProfilesResponse>
DatastreamMetadata::ListConnectionProfiles(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::ListConnectionProfilesRequest const&
        request) {
  SetMetadata(context, "parent=" + request.parent());
  return child_->ListConnectionProfiles(context, request);
}

StatusOr<google::cloud::datastream::v1::ConnectionProfile>
DatastreamMetadata::GetConnectionProfile(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::GetConnectionProfileRequest const& request) {
  SetMetadata(context, "name=" + request.name());
  return child_->GetConnectionProfile(context, request);
}

future<StatusOr<google::longrunning::Operation>>
DatastreamMetadata::AsyncCreateConnectionProfile(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::datastream::v1::CreateConnectionProfileRequest const&
        request) {
  SetMetadata(*context, "parent=" + request.parent());
  return child_->AsyncCreateConnectionProfile(cq, std::move(context), request);
}

future<StatusOr<google::longrunning::Operation>>
DatastreamMetadata::AsyncUpdateConnectionProfile(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::datastream::v1::UpdateConnectionProfileRequest const&
        request) {
  SetMetadata(*context,
              "connection_profile.name=" + request.connection_profile().name());
  return child_->AsyncUpdateConnectionProfile(cq, std::move(context), request);
}

future<StatusOr<google::longrunning::Operation>>
DatastreamMetadata::AsyncDeleteConnectionProfile(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::datastream::v1::DeleteConnectionProfileRequest const&
        request) {
  SetMetadata(*context, "name=" + request.name());
  return child_->AsyncDeleteConnectionProfile(cq, std::move(context), request);
}

StatusOr<google::cloud::datastream::v1::DiscoverConnectionProfileResponse>
DatastreamMetadata::DiscoverConnectionProfile(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::DiscoverConnectionProfileRequest const&
        request) {
  SetMetadata(context, "parent=" + request.parent());
  return child_->DiscoverConnectionProfile(context, request);
}

StatusOr<google::cloud::datastream::v1::ListStreamsResponse>
DatastreamMetadata::ListStreams(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::ListStreamsRequest const& request) {
  SetMetadata(context, "parent=" + request.parent());
  return child_->ListStreams(context, request);
}

StatusOr<google::cloud::datastream::v1::Stream> DatastreamMetadata::GetStream(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::GetStreamRequest const& request) {
  SetMetadata(context, "name=" + request.name());
  return child_->GetStream(context, request);
}

future<StatusOr<google::longrunning::Operation>>
DatastreamMetadata::AsyncCreateStream(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::datastream::v1::CreateStreamRequest const& request) {
  SetMetadata(*context, "parent=" + request.parent());
  return child_->AsyncCreateStream(cq, std::move(context), request);
}

future<StatusOr<google::longrunning::Operation>>
DatastreamMetadata::AsyncUpdateStream(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::datastream::v1::UpdateStreamRequest const& request) {
  SetMetadata(*context, "stream.name=" + request.stream().name());
  return child_->AsyncUpdateStream(cq, std::move(context), request);
}

future<StatusOr<google::longrunning::Operation>>
DatastreamMetadata::AsyncDeleteStream(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::datastream::v1::DeleteStreamRequest const& request) {
  SetMetadata(*context, "name=" + request.name());
  return child_->AsyncDeleteStream(cq, std::move(context), request);
}

StatusOr<google::cloud::datastream::v1::StreamObject>
DatastreamMetadata::GetStreamObject(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::GetStreamObjectRequest const& request) {
  SetMetadata(context, "name=" + request.name());
  return child_->GetStreamObject(context, request);
}

StatusOr<google::cloud::datastream::v1::StreamObject>
DatastreamMetadata::LookupStreamObject(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::LookupStreamObjectRequest const& request) {
  SetMetadata(context, "parent=" + request.parent());
  return child_->LookupStreamObject(context, request);
}

StatusOr<google::cloud::datastream::v1::ListStreamObjectsResponse>
DatastreamMetadata::ListStreamObjects(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::ListStreamObjectsRequest const& request) {
  SetMetadata(context, "parent=" + request.parent());
  return child_->ListStreamObjects(context, request);
}

StatusOr<google::cloud::datastream::v1::StartBackfillJobResponse>
DatastreamMetadata::StartBackfillJob(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::StartBackfillJobRequest const& request) {
  SetMetadata(context, "object=" + request.object());
  return child_->StartBackfillJob(context, request);
}

StatusOr<google::cloud::datastream::v1::StopBackfillJobResponse>
DatastreamMetadata::StopBackfillJob(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::StopBackfillJobRequest const& request) {
  SetMetadata(context, "object=" + request.object());
  return child_->StopBackfillJob(context, request);
}

StatusOr<google::cloud::datastream::v1::FetchStaticIpsResponse>
DatastreamMetadata::FetchStaticIps(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::FetchStaticIpsRequest const& request) {
  SetMetadata(context, "name=" + request.name());
  return child_->FetchStaticIps(context, request);
}

future<StatusOr<google::longrunning::Operation>>
DatastreamMetadata::AsyncCreatePrivateConnection(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::datastream::v1::CreatePrivateConnectionRequest const&
        request) {
  SetMetadata(*context, "parent=" + request.parent());
  return child_->AsyncCreatePrivateConnection(cq, std::move(context), request);
}

StatusOr<google::cloud::datastream::v1::PrivateConnection>
DatastreamMetadata::GetPrivateConnection(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::GetPrivateConnectionRequest const& request) {
  SetMetadata(context, "name=" + request.name());
  return child_->GetPrivateConnection(context, request);
}

StatusOr<google::cloud::datastream::v1::ListPrivateConnectionsResponse>
DatastreamMetadata::ListPrivateConnections(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::ListPrivateConnectionsRequest const&
        request) {
  SetMetadata(context, "parent=" + request.parent());
  return child_->ListPrivateConnections(context, request);
}

future<StatusOr<google::longrunning::Operation>>
DatastreamMetadata::AsyncDeletePrivateConnection(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::datastream::v1::DeletePrivateConnectionRequest const&
        request) {
  SetMetadata(*context, "name=" + request.name());
  return child_->AsyncDeletePrivateConnection(cq, std::move(context), request);
}

future<StatusOr<google::longrunning::Operation>>
DatastreamMetadata::AsyncCreateRoute(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::datastream::v1::CreateRouteRequest const& request) {
  SetMetadata(*context, "parent=" + request.parent());
  return child_->AsyncCreateRoute(cq, std::move(context), request);
}

StatusOr<google::cloud::datastream::v1::Route> DatastreamMetadata::GetRoute(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::GetRouteRequest const& request) {
  SetMetadata(context, "name=" + request.name());
  return child_->GetRoute(context, request);
}

StatusOr<google::cloud::datastream::v1::ListRoutesResponse>
DatastreamMetadata::ListRoutes(
    grpc::ClientContext& context,
    google::cloud::datastream::v1::ListRoutesRequest const& request) {
  SetMetadata(context, "parent=" + request.parent());
  return child_->ListRoutes(context, request);
}

future<StatusOr<google::longrunning::Operation>>
DatastreamMetadata::AsyncDeleteRoute(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::datastream::v1::DeleteRouteRequest const& request) {
  SetMetadata(*context, "name=" + request.name());
  return child_->AsyncDeleteRoute(cq, std::move(context), request);
}

future<StatusOr<google::longrunning::Operation>>
DatastreamMetadata::AsyncGetOperation(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::longrunning::GetOperationRequest const& request) {
  SetMetadata(*context, "name=" + request.name());
  return child_->AsyncGetOperation(cq, std::move(context), request);
}

future<Status> DatastreamMetadata::AsyncCancelOperation(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::longrunning::CancelOperationRequest const& request) {
  SetMetadata(*context, "name=" + request.name());
  return child_->AsyncCancelOperation(cq, std::move(context), request);
}

void DatastreamMetadata::SetMetadata(grpc::ClientContext& context,
                                     std::string const& request_params) {
  context.AddMetadata("x-goog-request-params", request_params);
  SetMetadata(context);
}

void DatastreamMetadata::SetMetadata(grpc::ClientContext& context) {
  context.AddMetadata("x-goog-api-client", api_client_header_);
  auto const& options = internal::CurrentOptions();
  if (options.has<UserProjectOption>()) {
    context.AddMetadata("x-goog-user-project",
                        options.get<UserProjectOption>());
  }
  auto const& authority = options.get<AuthorityOption>();
  if (!authority.empty()) context.set_authority(authority);
}

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace datastream_internal
}  // namespace cloud
}  // namespace google


text:
module ZeevexConcurrency
  VERSION = "0.1.2"
end

redpajama_set_name: RedPajamaGithub


text:
using namespace std;

Panel_Application::Panel_Application() : active_window(true), fullscreen(false), fullscreen_desktop(false), borderless(true), resizable(false)
{

}

Panel_Application::~Panel_Application()
{

}

void Panel_Application::Visualizate_Window()
{
	active_window = !active_window;
}

bool Panel_Application::Is_Active()
{
	return active_window;
}

bool Panel_Application::Draw_Panel_Application()
{
	if (Is_Active())
	{
		ImVec2 size_w;
		float2 pos;
		if (App->Get_Windows_Resized() == false)
		{
			size_w = ImVec2(290.f, 300.f);
			pos = float2(291, 332);
		}
		else
		{
			size_w = ImVec2(380.f, 375.f);
			pos = float2(382, 639);
		}
		ImGui::SetNextWindowPos(ImVec2(App->window->Get_Screen_size().x - pos.x, pos.y));
		ImGui::SetNextWindowSize(size_w);
		ImGui::Begin("Computer");

		//--------------------------------------_FPS_-------------------------------------------
		if (ImGui::CollapsingHeader("FPS"))
		{
			char title[25];
			sprintf_s(title, 25, "Framerate %.1f", App->fps_info->frames[App->fps_info->frames.size() - 1]);
			ImGui::PlotHistogram("##framerate", &App->fps_info->frames[0], App->fps_info->frames.size(), 0, title, 0.0f, 100.0f, ImVec2(310, 100));

			char title2[25];
			sprintf_s(title2, 25, "Milliseconds %0.1f", App->fps_info->ms[App->fps_info->ms.size() - 1]);
			ImGui::PlotHistogram("##milliseconds", &App->fps_info->ms[0], App->fps_info->ms.size(), 0, title2, 0.0f, 40.0f, ImVec2(310, 100));

			if (ImGui::SliderInt("Max FPS", &App->fps_info->max_frames, 0, 100))
			{
				App->Set_Limit_Frames(App->fps_info->max_frames);
			}
		}

		//------------------------------------_HARDWARE_------------------------------------------
		if (ImGui::CollapsingHeader("Hardware"))
		{
			App->hardware->Render_Hardware_Info();
		}

		//------------------------------------_WINDOW_------------------------------------------
		if (ImGui::CollapsingHeader("Window"))
		{
			if (ImGui::Checkbox("FULLSCREEN", &fullscreen))
			{
				if (fullscreen_desktop == true || borderless == true)
				{
					fullscreen_desktop = false;
					App->window->Set_Fullscreen_Desktop_Window(fullscreen_desktop);

				}

				App->window->Set_Fullscreen_Window(fullscreen);
			}

			if (ImGui::Checkbox("FULLSCREEN DESKTOP", &fullscreen_desktop))
			{
				if (fullscreen == true || borderless == true)
				{
					fullscreen = false;
					App->window->Set_Fullscreen_Window(fullscreen);
				}

				App->window->Set_Fullscreen_Desktop_Window(fullscreen_desktop);
			}

			if (ImGui::Checkbox("BORDERLESS", &borderless))
			{
				if (fullscreen == true || fullscreen_desktop == true)
				{
					fullscreen = false;
					App->window->Set_Fullscreen_Window(fullscreen);
					//fullscreen_desktop = false;
					//App->window->Set_Fullscreen_Desktop_Window(fullscreen_desktop);
				}

				App->window->Set_Borderless_Window(borderless);
			}

		}

		if (ImGui::Button("Close"))
		{
			Visualizate_Window();
		}

		ImGui::End();

	}

	return Is_Active();

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width initial-scale=1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <title>Alex Hughes | Project 1</title>
  <meta name="description" content="A simple, whitespace theme for academics. Based on [*folio](https://github.com/bogoli/-folio) design.
">

  <link rel="shortcut icon" href="/assets/img/favicon.ico">

  <link rel="stylesheet" href="/assets/css/main.css">
  <link rel="canonical" href="/projects/1_project/">

        Alex Hughes

        about

        blog

            projects

            publications

            teaching

Project 1

a project with a background image

Every project has a beautiful feature shocase page. It's easy to include images, in a flexible 3-column grid format. Make your photos 1/3, 2/3, or full width.

To give your project a background in the portfolio page, just add the img tag to the front matter like so:

---
layout: page
title: Project
description: a project with a background image
img: /assets/img/12.jpg
---

    Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.

    This image can also have a caption. It's like magic.

You can also put regular text between your rows of images. Say you wanted to write a little bit about your project before you posted the rest of the images. You describe how you toiled, sweated, bled for your project, and then…. you reveal it's glory in the next row of images.

    You can also have artistically styled 2/3 + 1/3 images, like these.

The code is simple. Just add a col class to your image, and another class specifying the width: one, two, or three columns wide. Here's the code for the last row of images above:

<div class="img_row">
  <img class="col two" src="/img/6.jpg"/>
  <img class="col one" src="/img/11.jpg"/>
</div>

    © Copyright 2017 Alex Hughes.
    Powered by Jekyll with al-folio theme. Hosted by GitHub Pages. Photos from Unsplash.

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css">

<link rel="stylesheet" href="/assets/css/font-awesome.min.css">
<link rel="stylesheet" href="/assets/css/academicons.min.css">


text:
module.exports = {
  name: 'type.string',
  init: function(){
    var type = basis.require('basis.type');
    var catchWarnings = basis.require('./helpers/common.js').catchWarnings;

    var nonStringsExceptNull = [
      2,
      {},
      { foo: 'bar' },
      [],
      [1, 2],
      NaN,
      Infinity,
      undefined
    ];
  },
  test: [
    {
      name: 'accepts string',
      test: function(){
        assert(type.string('hello') === 'hello');
        assert(type.string('') === '');
      }
    },
    {
      name: 'is empty string by default',
      test: function(){
        assert(type.string.DEFAULT_VALUE === '');
      }
    },
    {
      name: 'ignores incorrect objects',
      test: function(){
        nonStringsExceptNull.forEach(function(incorrectValue){
          var warned = catchWarnings(function(){
            assert(type.string(incorrectValue, 'previous') === 'previous');
          });

          assert(warned);
        });

        catchWarnings(function(){
          assert(type.string(null, 'previous') === 'previous');
        });
      }
    },
    {
      name: 'ignores previous value if can transform new value',
      test: function(){
        [
          '',
          'basis'
        ].forEach(function(correctValue){
          assert(type.string(correctValue, 'previous') === type.string(correctValue));
        });
      }
    },
    {
      name: 'nullable',
      test: [
        {
          name: 'accepts correct values',
          test: function(){
            [
              '',
              'test'
            ].forEach(function(correctValue){
              assert(type.string.nullable(correctValue, 'prev') === type.string(correctValue));
            });
          }
        },
        {
          name: 'accepts null',
          test: function(){
            assert(type.string.nullable(null, 'prev') === null);
          }
        },
        {
          name: 'is null by default',
          test: function(){
            assert(type.string.nullable.DEFAULT_VALUE === null);
          }
        },
        {
          name: 'ignores incorrect values',
          test: function(){
            nonStringsExceptNull.forEach(function(incorrectValue){
              var warned = catchWarnings(function(){
                assert(type.string.nullable(incorrectValue, 'previous') === 'previous');
              });

              assert(warned);
            });
          }
        },
        {
          name: 'default',
          test: [
            {
              name: 'behaves like nullable version',
              test: function(){
                var transform = type.string.nullable.default('def');

                catchWarnings(function(){
                  nonStringsExceptNull.concat([
                    null,
                    '',
                    'basis'
                  ]).forEach(function(value){
                    assert(transform(value, 'prev') === type.string.nullable(value, 'prev'));
                  });
                });
              }
            },
            {
              name: 'sets default value',
              test: function(){
                assert(type.string.nullable.default('defValue').DEFAULT_VALUE === 'defValue');
              }
            },
            {
              name: 'ignores default value if it is incorrect',
              test: function(){
                var transform;
                var warned = catchWarnings(function(){
                  transform = type.string.nullable.default({});
                });

                assert(warned);
                assert(transform.DEFAULT_VALUE === null);
              }
            }
          ]
        }
      ]
    },
    {
      name: 'default',
      test: [
        {
          name: 'behaves like usual version',
          test: function(){
            var transform = type.string.default('def');

            catchWarnings(function(){
              nonStringsExceptNull.concat([
                null,
                '',
                'basis',
              ]).forEach(function(value){
                assert(transform(value, 'prev') === type.string(value, 'prev'));
              });
            });
          }
        },
        {
          name: 'sets default value',
          test: function(){
            assert(type.string.default('defValue').DEFAULT_VALUE === 'defValue');
          }
        },
        {
          name: 'ignores default value if it is incorrect',
          test: function(){
            var transform;
            var warned = catchWarnings(function(){
              transform = type.string.default(3);
            });

            assert(warned);
            assert(transform.DEFAULT_VALUE === '');
          }
        }
      ]
    }
  ]
};


text:
package amazon_product_metadata_parser.dto;

import java.time.LocalDate;

/**
 * Data Transfer Object for a review.
 * <p>
 * Example: '    2000-7-28  cutomer: A2JW67OY8U6HHK  rating: 5 votes:  10  helpful:   9'
 */
public class ReviewDTO {

  public final LocalDate date;
  public final String    customer;
  public final int       rating;
  public final int       votes;
  public final int       helpful;

  ReviewDTO(LocalDate date, String customer, int rating, int votes, int helpful)
      throws FailedValidationException {
    this.date = date;
    this.customer = customer;
    this.rating = rating;
    this.votes = votes;
    this.helpful = helpful;
    throwExceptionIfInvalid();
  }

  private void throwExceptionIfInvalid() throws FailedValidationException {
    if (null == customer || customer.isEmpty()) {
      throw new FailedValidationException("Customer not defined");
    }
    if (votes < 0) {
      throw new FailedValidationException(String.format("Number of votes (%d) is less than zero",
                                                        votes));
    }
    if (rating < 0) {
      throw new FailedValidationException(String.format("Rating (%d) is less than zero",
                                                        rating));
    }
    if (helpful < 0) {
      throw new FailedValidationException(String.format(
        "Helpful (%d) is less than zero",
        helpful));
    }
    // These fail, so commented out...
    //    if (date.getYear() < 1990 || date.getYear() > 2007) {
    //      throw new FailedValidationException(String.format("Date (%s) is
    // not in acceptable range",
    //                                                        date.toString()));
    //    }
  }

  @Override
  public String toString() {
    return String.format("  Review Date: %s%n", date.toString())
           + String.format("    Review Customer: %s%n", customer)
           + String.format("    Review Rating: %d%n", rating)
           + String.format("    Review Votes: %d%n", votes)
           + String.format("    Review Helpful: %d%n", helpful);
  }
}


text:
package com.intellij.xdebugger.impl.ui.tree.nodes;

import com.intellij.icons.AllIcons;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.xdebugger.XExpression;
import com.intellij.xdebugger.impl.ui.XDebuggerUIConstants;
import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

/**
 * @author nik
 */
public class WatchMessageNode extends MessageTreeNode implements WatchNode {
  private final XExpression myExpression;

  private WatchMessageNode(XDebuggerTree tree, XDebuggerTreeNode parent, @NotNull XExpression expression, final Icon icon) {
    super(tree, parent, true);
    myExpression = expression;
    setIcon(icon);
  }

  @Override
  @NotNull
  public XExpression getExpression() {
    return myExpression;
  }

  public static WatchMessageNode createMessageNode(XDebuggerTree tree, XDebuggerTreeNode parent, XExpression expression) {
    final WatchMessageNode node = new WatchMessageNode(tree, parent, expression, AllIcons.Debugger.Watch);
    node.myText.append(expression.getExpression(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
    return node;
  }

  public static WatchMessageNode createEvaluatingNode(XDebuggerTree tree, XDebuggerTreeNode parent, XExpression expression) {
    final WatchMessageNode node = new WatchMessageNode(tree, parent, expression, AllIcons.Debugger.Watch);
    node.myText.append(expression + " = ...", XDebuggerUIConstants.EVALUATING_EXPRESSION_HIGHLIGHT_ATTRIBUTES);
    return node;
  }

  public static WatchMessageNode createErrorNode(XDebuggerTree tree, XDebuggerTreeNode parent, @NotNull XExpression expression, @NotNull String errorMessage) {
    final WatchMessageNode node = new WatchMessageNode(tree, parent, expression, XDebuggerUIConstants.ERROR_MESSAGE_ICON);
    node.myText.append(expression + " = ", SimpleTextAttributes.REGULAR_ATTRIBUTES);
    node.myText.append(errorMessage, SimpleTextAttributes.ERROR_ATTRIBUTES);
    return node;
  }

  @Override
  public String toString() {
    return myExpression.getExpression();
  }
}


text:
"""A library of solvers for the Poisson equation.

Methods presented here are used to solve the Poisson equation, i.e.
  ∇²p = b,
in a distributed setting.
"""

import functools
from typing import Callable, Optional, Sequence

import numpy as np
from swirl_lm.communication import halo_exchange
from swirl_lm.linalg import base_poisson_solver
from swirl_lm.linalg import poisson_solver_pb2
from swirl_lm.utility import common_ops
from swirl_lm.utility import get_kernel_fn
from swirl_lm.utility import grid_parametrization
from swirl_lm.utility import types
import tensorflow as tf

FlowFieldVal = types.FlowFieldVal
FlowFieldMap = types.FlowFieldMap
_TF_DTYPE = types.TF_DTYPE
_HaloUpdateFn = Callable[[FlowFieldVal], FlowFieldVal]
_PoissonSolverSolution = base_poisson_solver.PoissonSolverSolution

X = base_poisson_solver.X
RESIDUAL_L2_NORM = base_poisson_solver.RESIDUAL_L2_NORM
ITERATIONS = base_poisson_solver.ITERATIONS
VARIABLE_COEFF = base_poisson_solver.VARIABLE_COEFF

NormType = common_ops.NormType

def halo_update_for_compatibility_fn(
    replica_id: tf.Tensor,
    replicas: np.ndarray,
    computation_shape: Sequence[int],
    rhs_mean: tf.Tensor,
    halo_width: int,
    dx: float,
    dy: float,
    dz: float,
) -> _HaloUpdateFn:
  """Updates the halo following the divergence theorem.

  Args:
    replica_id: The index of the current TPU core.
    replicas: A numpy array that maps a replica's grid coordinate to its
      replica_id, e.g. replicas[0, 0, 0] = 0, replicas[0, 0, 1] = 1.
    computation_shape: The dimension of the TPU topology.
    rhs_mean: The mean of the right hand side of the Poisson equation.
    halo_width: The width of the halo layer.
    dx: The grid spacing dimension 0.
    dy: The grid spacing dimension 1.
    dz: The grid spacing dimension 2.

  Returns:
    A function that updates the halos of the input 3D tensor.
  """

  def halo_update_fn(p: FlowFieldVal) -> FlowFieldVal:
    """Updates the halo following the divergence theorem."""
    nz = len(p)
    nx, ny = p[0].get_shape().as_list()
    lx = dx * (nx - 2 * halo_width) * computation_shape[0]
    ly = dy * (ny - 2 * halo_width) * computation_shape[1]
    lz = dz * (nz - 2 * halo_width) * computation_shape[2]

    dtype = p[0].dtype
    new_rhs_mean = tf.cast(rhs_mean, dtype)

    bc_p_x_low = [-new_rhs_mean / 6. * dx * lx * tf.ones(
        (1, ny), dtype=dtype)] * nz
    bc_p_x_high = [new_rhs_mean / 6. * dx * lx * tf.ones(
        (1, ny), dtype=dtype)] * nz
    bc_p_y_low = [-new_rhs_mean / 6. * dy * ly * tf.ones(
        (nx, 1), dtype=dtype)] * nz
    bc_p_y_high = [new_rhs_mean / 6. * dy * ly * tf.ones(
        (nx, 1), dtype=dtype)] * nz
    bc_p_z = new_rhs_mean / 6. * dz * lz * tf.ones((nx, ny), dtype=dtype)

    bc_p = [
        [
            (halo_exchange.BCType.NEUMANN, [
                bc_p_x_low,
            ] * halo_width),
            (halo_exchange.BCType.NEUMANN, [
                bc_p_x_high,
            ] * halo_width),
        ],
        [
            (halo_exchange.BCType.NEUMANN, [
                bc_p_y_low,
            ] * halo_width),
            (halo_exchange.BCType.NEUMANN, [
                bc_p_y_high,
            ] * halo_width),
        ],
        [
            (halo_exchange.BCType.NEUMANN, [
                -bc_p_z,
            ] * halo_width),
            (halo_exchange.BCType.NEUMANN, [
                bc_p_z,
            ] * halo_width),
        ],
    ]
    return halo_exchange.inplace_halo_exchange(
        [p_i for p_i in p],
        dims=(0, 1, 2),
        replica_id=replica_id,
        replicas=replicas,
        replica_dims=(0, 1, 2),
        periodic_dims=(False, False, False),
        boundary_conditions=bc_p,
        width=halo_width)

  return halo_update_fn

class JacobiSolver(base_poisson_solver.PoissonSolver):
  """A library of solving the Poisson equation with weighted Jacobi method."""

  def __init__(
      self,
      params: grid_parametrization.GridParametrization,
      kernel_op: get_kernel_fn.ApplyKernelOp,
      solver_option: poisson_solver_pb2.PoissonSolver,
  ):
    """Initializes the Jacobi solver for the Poisson equation."""
    super().__init__(params, kernel_op, solver_option)

    self._kernel_op.add_kernel({'weighted_sum_121': ([1.0, 2.0, 1.0], 1)})
    self._omega = solver_option.jacobi.omega
    self._num_iters = solver_option.jacobi.max_iterations
    self._halo_width = solver_option.jacobi.halo_width

    self._factor_b = 0.5 / (params.dx**-2 + params.dy**-2 + params.dz**-2)
    self._factor_x = params.dx**2 / self._factor_b
    self._factor_y = params.dy**2 / self._factor_b
    self._factor_z = params.dz**2 / self._factor_b

  def _poisson_step(
      self,
      p: FlowFieldVal,
      rhs: FlowFieldVal,
      halo_update_fn: Callable[[FlowFieldVal], FlowFieldVal],
  ) -> FlowFieldVal:
    """Computes the pressure correction for the next sub-iteration."""
    # Compute the right hand side function for interior points.
    p = halo_update_fn(p)

    p_terms = zip(
        self._kernel_op.apply_kernel_op_x(p, 'kSx'),
        self._kernel_op.apply_kernel_op_y(p, 'kSy'),
        self._kernel_op.apply_kernel_op_z(p, 'kSz', 'kSzsh'),
        rhs)

    p_interior = [(fx / self._factor_x + fy / self._factor_y +
                   fz / self._factor_z - self._factor_b * fb)
                  for fx, fy, fz, fb in p_terms]

    return [
        self._omega * p_interior_i + (1.0 - self._omega) * p_i
        for p_interior_i, p_i in zip(p_interior, p)
    ]

  def _variable_coefficient_poisson_step(
      self,
      p: FlowFieldVal,
      w: FlowFieldVal,
      rhs: FlowFieldVal,
      halo_update_fn: Callable[[FlowFieldVal], FlowFieldVal],
  ) -> FlowFieldVal:
    """Solves the variable coefficient Poisson equation for one step."""
    p = halo_update_fn(p)

    delta2_inv = (1.0 / self._params.dx**2, 1.0 / self._params.dy**2,
                  1.0 / self._params.dz**2)

    # Compute the diagonal factor.
    factor_diag = (
        tf.nest.map_structure(
            lambda ws: 0.5 * delta2_inv[0] * ws,
            self._kernel_op.apply_kernel_op_x(w, 'weighted_sum_121x')),
        tf.nest.map_structure(
            lambda ws: 0.5 * delta2_inv[1] * ws,
            self._kernel_op.apply_kernel_op_y(w, 'weighted_sum_121y')),
        tf.nest.map_structure(
            lambda ws: 0.5 * delta2_inv[2] * ws,
            self._kernel_op.apply_kernel_op_z(w, 'weighted_sum_121z',
                                              'weighted_sum_121zsh')),
    )
    factor_diag_sum = tf.nest.map_structure(lambda a, b, c: a + b + c,
                                            *factor_diag)

    # Compute factors for the off-diagonal terms.
    # pylint: disable=g-long-lambda
    sum_op = (
        lambda f: tf.nest.map_structure(
            lambda fs: 0.5 * delta2_inv[0] * fs,
            self._kernel_op.apply_kernel_op_x(f, 'kSx')),
        lambda f: tf.nest.map_structure(
            lambda fs: 0.5 * delta2_inv[1] * fs,
            self._kernel_op.apply_kernel_op_y(f, 'kSy')),
        lambda f: tf.nest.map_structure(
            lambda fs: 0.5 * delta2_inv[2] * fs,
            self._kernel_op.apply_kernel_op_z(f, 'kSz', 'kSzsh')),
    )
    # pylint: enable=g-long-lambda

    p_factor = [sum_op_i(p) for sum_op_i in sum_op]
    p_sum = tf.nest.map_structure(lambda a, b, c: a + b + c, *p_factor)

    w_p = tf.nest.map_structure(tf.math.multiply, w, p)
    w_p_factor = [sum_op_i(w_p) for sum_op_i in sum_op]
    w_p_sum = tf.nest.map_structure(lambda a, b, c: a + b + c, *w_p_factor)

    rhs_factor = tf.nest.map_structure(
        lambda rhs_i, w_i, p_s, w_p_s: -rhs_i + w_i * p_s + w_p_s, rhs, w,
        p_sum, w_p_sum)

    p_new = tf.nest.map_structure(tf.math.divide, rhs_factor, factor_diag_sum)

    return tf.nest.map_structure(
        lambda p_0, p_n: self._omega * p_n + (1.0 - self._omega) * p_0, p,
        p_new)

  def solve(
      self,
      replica_id: tf.Tensor,
      replicas: np.ndarray,
      rhs: FlowFieldVal,
      p0: FlowFieldVal,
      halo_update_fn: Optional[_HaloUpdateFn] = None,
      internal_dtype: Optional[tf.dtypes.DType] = None,
      additional_states: Optional[FlowFieldMap] = None,
  ) -> _PoissonSolverSolution:
    """Solves the Poisson equation with the Jacobi iterative method.

    Args:
      replica_id: The ID of the replica.
      replicas: A numpy array that maps a replica's grid coordinate to its
        replica_id, e.g. replicas[0, 0, 0] = 0, replicas[0, 0, 1] = 2.
      rhs: A 3D field stored in a list of `tf.Tensor` that represents the right
        hand side tensor `b` in the Poisson equation.
      p0: A 3D field stored in a list of `tf.Tensor` that provides initial guess
        to the Poisson equation.
      halo_update_fn: A function that updates the halo of the input.
      internal_dtype: Which tf.dtype to use {tf.float32, tf.float64}.
        `tf.float32` is the default, mainly to be backward compatible, but
        `tf.float64` is recommended to avoid numerical error accumulation and
        get accurate evaluation of `L_p` norms.
      additional_states: Additional static fields needed in the computation.

    Returns:
      A dict with the following elements:
        1. A 3D tensor of the same shape as `rhs` that stores the solution to
           the Poisson equation.
        2. Number of iterations for the computation
    """
    del internal_dtype

    rhs_mean = common_ops.global_mean(rhs, replicas, (self._halo_width,) * 3)

    halo_update_for_compatibility = halo_update_for_compatibility_fn(
        replica_id, replicas, replicas.shape, rhs_mean, self._halo_width,
        self._params.dx, self._params.dy, self._params.dz)

    halo_update = (
        halo_update_fn if halo_update_fn else halo_update_for_compatibility)

    if additional_states is not None and VARIABLE_COEFF in additional_states:
      p_next = functools.partial(
          self._variable_coefficient_poisson_step,
          w=additional_states[VARIABLE_COEFF],
          rhs=rhs,
          halo_update_fn=halo_update)
    else:
      p_next = functools.partial(
          self._poisson_step, rhs=rhs, halo_update_fn=halo_update)

    i0 = tf.constant(0)
    stop_condition = lambda i, p: i < self._num_iters
    body = lambda i, p: (i + 1, p_next(p))

    iterations, p = tf.while_loop(
        cond=stop_condition, body=body, loop_vars=(i0, p0), back_prop=False)

    return {
        X: halo_update(p),
        ITERATIONS: iterations,
    }


text:
function GoServer(_datatype, _type, _url, datao, onsuccess, lid) {
    var datao = JSON.stringify(datao);
    //  datao = datao.replace(/"/g, "'");
    jQuery.ajax({
        type: _type, url: GetUrlService(_url),
        contentType: 'application/json; charset=utf-8', dataType: _datatype, data: datao,
        success: function (d, s) { if (onsuccess != null) onsuccess(d, s); if (lid != null) lid.find('.loading').remove(); },
        beforeSend: function () { if (lid != null) { l = $('<img class="loading" src="/images/loading.gif">'); lid.append(l); } },
        error: function (xmlHttpRequest, status, err) { if (lid != null) lid.find(".loading").remove(); }
    });
}
function GetUrlService(url) {
    var qs = document.location.search.split('?')[1];
    return url; + "?" + qs;
}
function LoadService(path, datao, onsuccess, lid) { GoServer('json', 'post', path, datao, onsuccess, lid); };

function GetUser() {
    var data = {};
    data.obj = {};
    data.obj.ClPersonal = {};
    data.obj.ClPersonal.PersonalID = uid;
    data.obj.PageSize = 1;
    data.obj.PageIndex = 0;
    LoadService("/WebService/Personal.asmx/GetList", data, function (data, status) {
        if (data != null) {
            $('#txtUserName').val(data.d.Rows[0].UserName);
            $('#txtcodemelli').val(data.d.Rows[0].CodeMelli);
            $('#txtName').val(data.d.Rows[0].Name);
            $('#txtShenasname').val(data.d.Rows[0].ShomarShenasname);
            $('#txtLastName').val(data.d.Rows[0].Family);
            $('#txtFatherName').val(data.d.Rows[0].FatherName);
            $('#txtmobile').val(data.d.Rows[0].Mobile);

            $('#drpSemat').val(data.d.Rows[0].SematID);
            //data.d.Rows[0].personTypeID = 1;//$('#personTypeID').val();
            $('#drpGender').val(data.d.Rows[0].JensiyyatTypeId);
            $('#txtPersonalCode').val(data.d.Rows[0].PersonaliCode);
            $('#txtBirthDate').val(GregorianToPersian(GetDate(data.d.Rows[0].BirthDate)));
            $('#txtSodorLocation').val(data.d.Rows[0].SodorLocation);
            $('#txtTel').val(data.d.Rows[0].Tel);
            $('#drpDegree').val(data.d.Rows[0].DegreeEducation);
            ($('#txtDriverCert').val(GregorianToPersian(GetDate(data.d.Rows[0].DriveCertificateDate))));
            toEnglishNumber($('#txtCrime').val(data.d.Rows[0].Background_crime));
            ($('#txtHealth').val(data.d.Rows[0].Health_Test));
            //data.d.Rows[0].ActivityPermission = $('#drpActivityPermission').val();
            $('#txtAddress').val(data.d.Rows[0].Adress);
            //data.d.Rows[0].OrganID = $('#drpOrgan').val();
            //data.d.Rows[0].CarID = $('#drpOrgan2').val();
        }
        else
            $.notify('خطا در ثبت');
    }, $('#Loading'));
}
$(function () {
    GetUser();
    $(".js_btnSaveInfo").on("click", function () {
        var data = {};
        data.cl = {};

        data.cl.Name=  $('#txtName').val();
        data.cl.ShomarShenasname = $('#txtShenasname').val();

        data.cl.Family = $('#txtLastName').val();
        data.cl.FatherName = $('#txtFatherName').val();
        data.cl.Mobile = $('#txtmobile').val();

        //data.cl.SematID = $('#drpSemat').val();
        //data.d.Rows[0].personTypeID = 1;//$('#personTypeID').val();
        //data.cl.JensiyyatTypeId = $('#drpGender').val();

        data.cl.BirthDate = PTG($('#txtBirthDate').val());
        data.cl.SodorLocation = $('#txtSodorLocation').val();
        data.cl.Tel = $('#txtTel').val();
        data.cl.DegreeEducation = $('#drpDegree').val();
        data.cl.DriveCertificateDate = PTG($('#txtDriverCert').val());
        data.cl.Background_crime = toEnglishNumber($('#txtCrime').val());
        data.cl.Health_Test = $('#txtHealth').val();
        //data.d.Rows[0].ActivityPermission = $('#drpActivityPermission').val();
        data.cl.Adress = $('#txtAddress').val();

        data.cl.PersonalID = uid;
        LoadService("/WebService/Personal.asmx/Edit", data, function (data, status) {
            if (status == "success") {
                $.notify('اطلاعات با موفقیت ثبت شد', 'success');
                //jQuery(grid_selector).trigger("reloadGrid");
                //$("#modalform").modal("hide");
                //$("input:text,input:password").val("");
            }
            else
                $.notify('خطا در ثبت');
        });
    });
});


text:
package com.cloudera.science.matching.graph;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;

import com.google.common.collect.Maps;

/**
 * Maintains the internal state of a vertex in the bipartite graph within a
 * Giraph job.
 */
public class VertexState implements Writable {

  private boolean bidder;
  private Text matchId = new Text();
  private BigDecimal price = BigDecimal.ZERO;
  private Map<Text, BigDecimal> priceIndex = Maps.newHashMap();

  public VertexState() { }

  public VertexState(boolean bidder) {
    this.bidder = bidder;
  }

  public VertexState(boolean bidder, Text matchId, BigDecimal price, Map<Text, BigDecimal> priceIndex) {
    this.bidder = bidder;
    this.matchId = matchId;
    this.price = price;
    this.priceIndex = priceIndex;
  }

  public boolean isBidder() {
    return bidder;
  }

  public Text getMatchId() {
    return matchId;
  }

  public void setMatchId(Text ownerId) {
    this.matchId = ownerId;
  }

  public void clearMatchId() {
    this.matchId = new Text();
  }

  public BigDecimal getPrice() {
    return price;
  }

  public void setPrice(BigDecimal price) {
    this.price = price;
  }

  public Map<Text, BigDecimal> getPriceIndex() {
    return priceIndex;
  }

  @Override
  public void readFields(DataInput in) throws IOException {
    bidder = in.readBoolean();
    if (!bidder) {
      price = new BigDecimal(in.readUTF());
    }
    matchId.readFields(in);
    this.priceIndex = Maps.newHashMap();
    int sz = WritableUtils.readVInt(in);
    for (int i = 0; i < sz; i++) {
      Text vertexId = new Text();
      vertexId.readFields(in);
      String price = in.readUTF();
      priceIndex.put(vertexId, new BigDecimal(price));
    }
  }

  @Override
  public void write(DataOutput out) throws IOException {
    out.writeBoolean(bidder);
    if (!bidder) {
      out.writeUTF(price.toString());
    }
    matchId.write(out);
    WritableUtils.writeVInt(out, priceIndex.size());
    for (Map.Entry<Text, BigDecimal> e : priceIndex.entrySet()) {
      e.getKey().write(out);
      out.writeUTF(e.getValue().toString());
    }
  }
}


text:
package me.hao0.diablo.common.util;

/**
 * Author: haolin
 * Email:  haolin.h0@gmail.com
 */
public interface ClientUris {

    /**
     * Client API prefix
     */
    String CLIENT_API = "/apis";

    /**
     * The uri for routing a server
     */
    String SERVER_ROUTE = "/servers_route";

    /**
     * The uri for client register
     */
    String REGISTER = "/register";

    /**
     * The uri for client un register
     */
    String UN_REGISTER = "/un_register";

    /**
     * The uri for pulling config
     */
    String CONFIG_PULLING = "/configs_pulling";

    /**
     * The uri for fetching a config
     */
    String CONFIG_FETCH = "/configs_fetch";

    /**
     * The uri for fetching configs
     */
    String CONFIG_FETCHES = "/configs_fetches";

    /**
     * The uri for fetching all configs
     */
    String CONFIG_FETCH_ALL = "/configs_fetch_all";
}


text:
```shell
$ git clone --recursive ssh://user@domain.tld/repo.git
$ make update-source
$ make
$ make serve
```

visit: http://localhost:8000


text:
enum class seek_origin {
	begin,
	current,
	end
};

enum class open_mode {
	create,              ///< Create if doesn't exist or overwrite otherwise
	create_new,          ///< Create if doesn't exist
	open,                ///< Open existing
	open_or_create       ///< Open if exists or create new otherwise
};

enum class access_mode {
	read_only,
	read_write
};

namespace cobalt { namespace io {

/// Stream
class stream : public local_ref_counter<stream> {
public:
	using value_type = uint8_t;

	virtual ~stream() noexcept = default;

	virtual size_t read(void* buffer, size_t size, std::error_code& ec) noexcept = 0;
	virtual size_t write(const void* buffer, size_t size, std::error_code& ec) noexcept = 0;
	virtual void flush(std::error_code& ec) const noexcept = 0;
	virtual int64_t seek(int64_t offset, seek_origin origin, std::error_code& ec) noexcept = 0;
	virtual int64_t tell(std::error_code& ec) const noexcept = 0;
	virtual bool eof(std::error_code& ec) const noexcept = 0;

	/// Throw exception on error
	size_t read(void* buffer, size_t size);
	size_t write(const void* buffer, size_t size);
	void flush() const;
	int64_t seek(int64_t offset, seek_origin origin);
	int64_t tell() const;
	bool eof() const;

	bool can_read() noexcept;
	bool can_write() noexcept;
	bool can_seek() noexcept;

	void copy_to(stream& stream, std::error_code& ec) noexcept;
	void copy_to(stream& stream, size_t max_bytes, std::error_code& ec) noexcept;

	void copy_to(stream& stream);
	void copy_to(stream& stream, size_t max_bytes);
};

/// Memory stream
class memory_stream : public stream {
public:
	explicit memory_stream(size_t capacity = 0);
	memory_stream(void* buffer, size_t size) noexcept;
	memory_stream(void* buffer, size_t size, access_mode access) noexcept;

	memory_stream(const memory_stream&) = delete;
	memory_stream& operator=(const memory_stream&) = delete;

	~memory_stream();

	access_mode access() const noexcept;
	void access(access_mode access);

	bool dynamic() const noexcept;

	std::pair<value_type*, size_t> buffer() const noexcept;

	virtual size_t read(void* buffer, size_t size, std::error_code& ec) noexcept override;
	virtual size_t write(const void* buffer, size_t size, std::error_code& ec) noexcept override;
	virtual void flush(std::error_code& ec) const noexcept override;
	virtual int64_t seek(int64_t offset, seek_origin origin, std::error_code& ec) noexcept override;
	virtual int64_t tell(std::error_code& ec) const noexcept override;
	virtual bool eof(std::error_code& ec) const noexcept override;

private:
	size_t read_impl(void* buffer, size_t size, std::error_code& ec, std::true_type) noexcept;
	size_t write_impl(const void* buffer, size_t size, std::error_code& ec, std::true_type) noexcept;
	bool eof_impl(std::error_code& ec, std::true_type) const noexcept;

	size_t read_impl(void* buffer, size_t size, std::error_code& ec, std::false_type) noexcept;
	size_t write_impl(const void* buffer, size_t size, std::error_code& ec, std::false_type) noexcept;
	bool eof_impl(std::error_code& ec, std::false_type) const noexcept;

	int64_t seek_impl(int64_t offset, seek_origin origin, size_t size, std::error_code& ec) noexcept;

private:
	union {
		value_type* _buffer = nullptr;
		std::vector<value_type>* _vec;
	};
	size_t _size = 0;
	size_t _position = 0;
	access_mode _access = access_mode::read_only;
};

/// File stream
class file_stream : public stream {
public:
	file_stream() noexcept = default;

	file_stream(const file_stream&) = delete;
	file_stream& operator=(const file_stream&) = delete;

	~file_stream() noexcept;

	void open(const char* filename, open_mode open_mode, access_mode access, std::error_code& ec) noexcept;
	void open(const char* filename, open_mode open_mode, access_mode access);

	void close(std::error_code& ec) noexcept;
	void close();

	bool valid() const noexcept;

	access_mode access() const noexcept;

	virtual size_t read(void* buffer, size_t size, std::error_code& ec) noexcept override;
	virtual size_t write(const void* buffer, size_t size, std::error_code& ec) noexcept override;
	virtual void flush(std::error_code& ec) const noexcept override;
	virtual int64_t seek(int64_t offset, seek_origin origin, std::error_code& ec) noexcept override;
	virtual int64_t tell(std::error_code& ec) const noexcept override;
	virtual bool eof(std::error_code& ec) const noexcept override;

private:
	FILE* _fp = nullptr;
	access_mode _access = access_mode::read_only;
};

namespace detail {

/// Helper base class for stream adaptors
class stream_holder {
public:
	/// Will not change reference count
	explicit stream_holder(stream& stream);
	/// Will increase reference count
	explicit stream_holder(stream* stream);

	~stream_holder();

	stream* base_stream() const noexcept { return _stream; }

private:
	stream* _stream = nullptr;
	bool _owning = false;
};

} // namespace detail

/// Stream view adapter
class stream_view : public stream, public detail::stream_holder {
public:
	stream_view(stream& stream, int64_t offset, int64_t length);
	stream_view(stream* stream, int64_t offset, int64_t length);

	virtual size_t read(void* buffer, size_t size, std::error_code& ec) noexcept override;
	virtual size_t write(const void* buffer, size_t size, std::error_code& ec) noexcept override;
	virtual void flush(std::error_code& ec) const noexcept override;
	virtual int64_t seek(int64_t offset, seek_origin origin, std::error_code& ec) noexcept override;
	virtual int64_t tell(std::error_code& ec) const noexcept override;
	virtual bool eof(std::error_code& ec) const noexcept override;

private:
	int64_t _offset = 0;
	int64_t _length = 0;
};

/// Copies bytes from current position until eof
/// @return Number of bytes actually read
template <typename OutputIterator>
size_t copy(stream& stream, OutputIterator it, std::error_code& ec) noexcept;

/// Copies bytes from current position until eof
/// Reads up to specified number of bytes
/// @return Number of bytes actually read
template <typename OutputIterator>
size_t copy(stream& stream, OutputIterator it, size_t max_bytes, std::error_code& ec) noexcept;

/// Writes bytes range to stream
/// @return Number of bytes actually written
template <typename InputIterator>
size_t copy(InputIterator begin, InputIterator end, stream& stream, std::error_code& ec) noexcept;

/// Copies bytes from current position until eof
/// Throws on error
/// @return Number of bytes written
template <typename OutputIterator>
size_t copy(stream& stream, OutputIterator it);

/// Reads up to specified number of bytes
/// Throws on error
/// @return Number of bytes actually read
template <typename OutputIterator>
size_t copy(stream& stream, OutputIterator it, size_t max_bytes);

/// Writes bytes range to stream
/// Throws on error
/// @return Number of bytes actually written
template <typename InputIterator>
size_t copy(InputIterator begin, InputIterator end, stream& stream);

/// Binary writer
class binary_writer : public detail::stream_holder {
public:
	explicit binary_writer(stream& stream) noexcept;
	explicit binary_writer(stream* stream);

	void write(uint8_t value, std::error_code& ec) noexcept;
	void write(uint16_t value, std::error_code& ec) noexcept;
	void write(uint32_t value, std::error_code& ec) noexcept;
	void write(uint64_t value, std::error_code& ec) noexcept;
	void write(int8_t value, std::error_code& ec) noexcept;
	void write(int16_t value, std::error_code& ec) noexcept;
	void write(int32_t value, std::error_code& ec) noexcept;
	void write(int64_t value, std::error_code& ec) noexcept;
	void write(float value, std::error_code& ec) noexcept;
	void write(double value, std::error_code& ec) noexcept;
	void write(bool value, std::error_code& ec) noexcept;
	void write_7bit_encoded_int(uint32_t value, std::error_code& ec) noexcept;
	void write_unicode_char(uint32_t value, std::error_code& ec) noexcept;
	void write_c_string(const char* str, std::error_code& ec) noexcept; // zero ended string
	void write_pascal_string(const char* str, std::error_code& ec) noexcept; // length prepended string

	void write(uint8_t value);
	void write(uint16_t value);
	void write(uint32_t value);
	void write(uint64_t value);
	void write(int8_t value);
	void write(int16_t value);
	void write(int32_t value);
	void write(int64_t value);
	void write(float value);
	void write(double value);
	void write(bool value);
	void write_7bit_encoded_int(uint32_t value);
	void write_unicode_char(uint32_t value);
	void write_c_string(const char* str); // zero ended string
	void write_pascal_string(const char* str); // length prepended string
};

/// Binary reader
class binary_reader : public detail::stream_holder {
public:
	explicit binary_reader(stream& stream) noexcept;
	explicit binary_reader(stream* stream);

	uint8_t read_uint8(std::error_code& ec) noexcept;
	uint16_t read_uint16(std::error_code& ec) noexcept;
	uint32_t read_uint32(std::error_code& ec) noexcept;
	uint64_t read_uint64(std::error_code& ec) noexcept;
	int8_t read_int8(std::error_code& ec) noexcept;
	int16_t read_int16(std::error_code& ec) noexcept;
	int32_t read_int32(std::error_code& ec) noexcept;
	int64_t read_int64(std::error_code& ec) noexcept;
	float read_float(std::error_code& ec) noexcept;
	double read_double(std::error_code& ec) noexcept;
	bool read_bool(std::error_code& ec) noexcept;
	uint32_t read_7bit_encoded_int(std::error_code& ec) noexcept;
	uint32_t read_unicode_char(std::error_code& ec) noexcept;
	std::string read_c_string(std::error_code& ec) noexcept; // zero ended string
	std::string read_pascal_string(std::error_code& ec) noexcept; // length prepended string

	uint8_t read_uint8();
	uint16_t read_uint16();
	uint32_t read_uint32();
	uint64_t read_uint64();
	int8_t read_int8();
	int16_t read_int16();
	int32_t read_int32();
	int64_t read_int64();
	float read_float();
	double read_double();
	bool read_bool();
	uint32_t read_7bit_encoded_int();
	uint32_t read_unicode_char();
	std::string read_c_string(); // zero ended string
	std::string read_pascal_string(); // length prepended string
};

/// Bit packed stream writer
class bit_writer {
public:
	explicit bit_writer(stream& stream) noexcept;
	explicit bit_writer(stream* stream) noexcept;

	~bit_writer();

	stream* base_stream() const noexcept { return _writer.base_stream(); }

	/// Write specified number of bits
	void write_bits(uint32_t value, int bits, std::error_code& ec) noexcept;
	/// Write scratched bits to stream and align bit position to byte boundary
	void write_align(std::error_code& ec) noexcept;
	/// Flush scratched bits to stream
	void flush(std::error_code& ec) noexcept;

	void write_bits(uint32_t value, int bits);
	void write_align();
	void flush();

private:
	binary_writer _writer;
	uint64_t _scratch = 0;
	int _scratch_bits = 0;
};

/// Bit packed stream reader
class bit_reader {
public:
	explicit bit_reader(stream& stream) noexcept;
	explicit bit_reader(stream* stream) noexcept;

	~bit_reader() noexcept;

	stream* base_stream() const noexcept { return _reader.base_stream(); }

	/// Read specified number of bits
	uint32_t read_bits(int bits, std::error_code& ec) noexcept;
	/// Align position by the byte boundary
	void read_align(std::error_code& ec) noexcept;

	uint32_t read_bits(int bits);
	void read_align();

private:
	binary_reader _reader;
	uint64_t _scratch = 0;
	int _scratch_bits = 0;
};

}} // namespace cobalt::io

#endif // COBALT_IO_FWD_HPP_INCLUDED


text:
"""Tests and benchmarks for the ResNet50 model, executed eagerly."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import gc
import os
import tempfile
import time

from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf

from tensorflow.python.client import device_lib
from tensorflow.python.eager import context
from tensorflow.python.eager import tape
from tensorflow.python.eager.benchmarks.resnet50 import resnet50
from tensorflow.python.eager.benchmarks.resnet50 import resnet50_test_util

def compute_gradients(model, images, labels, num_replicas=1):
  with tf.GradientTape() as grad_tape:
    logits = model(images, training=True)
    loss = tf.compat.v1.losses.softmax_cross_entropy(
        logits=logits, onehot_labels=labels)
    tf.compat.v2.summary.write('loss', loss)
    if num_replicas != 1:
      loss /= num_replicas

  # TODO(b/110991947): We can mistakenly trace the gradient call in
  # multi-threaded environment. Explicitly disable recording until
  # this is fixed.
  with tape.stop_recording():
    grads = grad_tape.gradient(loss, model.variables)
  return grads

def apply_gradients(model, optimizer, gradients):
  optimizer.apply_gradients(zip(gradients, model.variables))

def _events_from_file(filepath):
  """Returns all events in a single event file.

  Args:
    filepath: Path to the event file.

  Returns:
    A list of all tf.compat.v1.Event protos in the event file.
  """
  records = list(tf.compat.v1.python_io.tf_record_iterator(filepath))
  result = []
  for r in records:
    event = tf.compat.v1.Event()
    event.ParseFromString(r)
    result.append(event)
  return result

def events_from_logdir(logdir):
  """Returns all events in the single eventfile in logdir.

  Args:
    logdir: The directory in which the single event file is sought.

  Returns:
    A list of all tf.compat.v1.Event protos from the single event file.

  Raises:
    AssertionError: If logdir does not contain exactly one file.
  """
  assert tf.io.gfile.exists(logdir)
  files = tf.io.gfile.listdir(logdir)
  assert len(files) == 1, 'Found not exactly one file in logdir: %s' % files
  return _events_from_file(os.path.join(logdir, files[0]))

class ResNet50Test(tf.test.TestCase):

  def _apply(self, defun=False, execution_mode=None):
    device, data_format = resnet50_test_util.device_and_data_format()
    model = resnet50.ResNet50(data_format)
    if defun:
      model.call = tf.function(model.call)
    with tf.device(device), context.execution_mode(execution_mode):
      images, _ = resnet50_test_util.random_batch(2, data_format)
      output = model(images, training=False)
      context.async_wait()
    self.assertEqual((2, 1000), output.shape)

  def test_apply(self):
    self._apply(defun=False)

  def test_apply_async(self):
    self._apply(defun=False, execution_mode=context.ASYNC)

  def test_apply_with_defun(self):
    self._apply(defun=True)

  def test_apply_with_defun_async(self):
    self._apply(defun=True, execution_mode=context.ASYNC)

  def test_apply_no_top(self):
    device, data_format = resnet50_test_util.device_and_data_format()
    model = resnet50.ResNet50(data_format, include_top=False)
    with tf.device(device):
      images, _ = resnet50_test_util.random_batch(2, data_format)
      output = model(images, training=False)
    output_shape = ((2, 2048, 1, 1)
                    if data_format == 'channels_first' else (2, 1, 1, 2048))
    self.assertEqual(output_shape, output.shape)

  def test_apply_with_pooling(self):
    device, data_format = resnet50_test_util.device_and_data_format()
    model = resnet50.ResNet50(data_format, include_top=False, pooling='avg')
    with tf.device(device):
      images, _ = resnet50_test_util.random_batch(2, data_format)
      output = model(images, training=False)
    self.assertEqual((2, 2048), output.shape)

  def test_apply_no_average_pooling(self):
    device, data_format = resnet50_test_util.device_and_data_format()
    model = resnet50.ResNet50(
        data_format, average_pooling=False, include_top=False)
    with tf.device(device):
      images, _ = resnet50_test_util.random_batch(2, data_format)
      output = model(images, training=False)
    output_shape = ((2, 2048, 7, 7) if data_format == 'channels_first' else
                    (2, 7, 7, 2048))
    self.assertEqual(output_shape, output.shape)

  def test_apply_block3_strides(self):
    device, data_format = resnet50_test_util.device_and_data_format()
    model = resnet50.ResNet50(
        data_format, block3_strides=True, include_top=False)
    with tf.device(device):
      images, _ = resnet50_test_util.random_batch(2, data_format)
      output = model(images, training=False)
    output_shape = ((2, 2048, 1, 1) if data_format == 'channels_first' else
                    (2, 1, 1, 2048))
    self.assertEqual(output_shape, output.shape)

  def test_apply_retrieve_intermediates(self):
    device, data_format = resnet50_test_util.device_and_data_format()
    model = resnet50.ResNet50(
        data_format, block3_strides=True, include_top=False)
    intermediates_dict = {}
    with tf.device(device):
      images, _ = resnet50_test_util.random_batch(2, data_format)
      output = model(images, training=False,
                     intermediates_dict=intermediates_dict)
    output_shape = ((2, 2048, 1, 1) if data_format == 'channels_first' else
                    (2, 1, 1, 2048))
    self.assertEqual(output_shape, output.shape)

    if data_format == 'channels_first':
      block_shapes = {
          'block0': (2, 64, 112, 112),
          'block0mp': (2, 64, 55, 55),
          'block1': (2, 256, 55, 55),
          'block2': (2, 512, 28, 28),
          'block3': (2, 1024, 7, 7),
          'block4': (2, 2048, 1, 1),
      }
    else:
      block_shapes = {
          'block0': (2, 112, 112, 64),
          'block0mp': (2, 55, 55, 64),
          'block1': (2, 55, 55, 256),
          'block2': (2, 28, 28, 512),
          'block3': (2, 7, 7, 1024),
          'block4': (2, 1, 1, 2048),
      }
    for (block_name, block) in intermediates_dict.items():
      self.assertEqual(block_shapes[block_name], block.shape)

  def _test_train(self, execution_mode=None):
    device, data_format = resnet50_test_util.device_and_data_format()
    model = resnet50.ResNet50(data_format)
    tf.compat.v2.summary.experimental.set_step(
        tf.compat.v1.train.get_or_create_global_step())
    logdir = tempfile.mkdtemp()
    with tf.compat.v2.summary.create_file_writer(
        logdir, max_queue=0,
        name='t0').as_default(), tf.compat.v2.summary.record_if(True):
      with tf.device(device), context.execution_mode(execution_mode):
        optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1)
        images, labels = resnet50_test_util.random_batch(2, data_format)
        apply_gradients(model, optimizer,
                        compute_gradients(model, images, labels))
        self.assertEqual(320, len(model.variables))
        context.async_wait()
    events = events_from_logdir(logdir)
    self.assertEqual(len(events), 2)
    self.assertEqual(events[1].summary.value[0].tag, 'loss')

  def test_train(self):
    self._test_train()

  def test_train_async(self):
    self._test_train(execution_mode=context.ASYNC)

  def test_no_garbage(self):
    device, data_format = resnet50_test_util.device_and_data_format()
    model = resnet50.ResNet50(data_format)
    optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1)
    with tf.device(device):
      images, labels = resnet50_test_util.random_batch(2, data_format)
      gc.disable()
      # Warm up. Note that this first run does create significant amounts of
      # garbage to be collected. The hope is that this is a build-only effect,
      # and a subsequent training loop will create nothing which needs to be
      # collected.
      apply_gradients(model, optimizer,
                      compute_gradients(model, images, labels))
      gc.collect()
      previous_gc_debug_flags = gc.get_debug()
      gc.set_debug(gc.DEBUG_SAVEALL)
      for _ in range(2):
        # Run twice to ensure that garbage that is created on the first
        # iteration is no longer accessible.
        apply_gradients(model, optimizer,
                        compute_gradients(model, images, labels))
      gc.collect()
      # There should be no garbage requiring collection.
      self.assertEqual(0, len(gc.garbage))
      gc.set_debug(previous_gc_debug_flags)
      gc.enable()

class MockIterator(object):

  def __init__(self, tensors):
    self._tensors = [tf.identity(x) for x in tensors]

  def next(self):
    return self._tensors

class ResNet50Benchmarks(tf.test.Benchmark):

  def _report(self, label, start, num_iters, device, batch_size, data_format,
              num_replicas=1):
    resnet50_test_util.report(self, label, start, num_iters, device,
                              batch_size, data_format, num_replicas=1)

  def _train_batch_sizes(self):
    """Choose batch sizes based on GPU capability."""
    for device in device_lib.list_local_devices():
      # TODO(b/141475121): We need some way to check which batch sizes would
      # work using a public API.
      if tf.DeviceSpec.from_string(device.name).device_type == 'GPU':
        # Avoid OOM errors with larger batch sizes, which seem to cause errors
        # later on even if caught.
        #
        # TODO(allenl): Base this on device memory; memory limit information
        # during the test seems to exclude the amount TensorFlow has allocated,
        # which isn't useful.
        if 'K20' in device.physical_device_desc:
          return (16,)
        if 'P100' in device.physical_device_desc:
          return (16, 32, 64)

      if tf.DeviceSpec.from_string(device.name).device_type == 'TPU':
        return (32,)
    return (16, 32)

  def _force_device_sync(self):
    # If this function is called in the context of a non-CPU device
    # (e.g., inside a 'with tf.device("/gpu:0")' block)
    # then this will force a copy from CPU->NON_CPU_DEVICE->CPU,
    # which forces a sync. This is a roundabout way, yes.
    tf.constant(1.).cpu()

  def _benchmark_eager_apply(self, label, device_and_format, defun=False,
                             execution_mode=None):
    with context.execution_mode(execution_mode):
      device, data_format = device_and_format
      model = resnet50.ResNet50(data_format)
      if defun:
        model.call = tf.function(model.call)
      batch_size = 64
      num_burn = 5
      num_iters = 30
      with tf.device(device):
        images, _ = resnet50_test_util.random_batch(batch_size, data_format)
        for _ in xrange(num_burn):
          model(images, training=False).cpu()
        if execution_mode:
          context.async_wait()
        gc.collect()
        start = time.time()
        for _ in xrange(num_iters):
          model(images, training=False).cpu()
        if execution_mode:
          context.async_wait()
        self._report(label, start, num_iters, device, batch_size, data_format)

  def benchmark_eager_apply_sync(self):
    self._benchmark_eager_apply(
        'eager_apply', resnet50_test_util.device_and_data_format(),
        defun=False)

  def benchmark_eager_apply_async(self):
    self._benchmark_eager_apply(
        'eager_apply_async', resnet50_test_util.device_and_data_format(),
        defun=False, execution_mode=context.ASYNC)

  def benchmark_eager_apply_with_defun(self):
    self._benchmark_eager_apply(
        'eager_apply_with_defun',
        resnet50_test_util.device_and_data_format(), defun=True)

  def _benchmark_eager_train(self,
                             label,
                             make_iterator,
                             device_and_format,
                             defun=False,
                             execution_mode=None):
    with context.execution_mode(execution_mode):
      device, data_format = device_and_format
      for batch_size in self._train_batch_sizes():
        (images, labels) = resnet50_test_util.random_batch(
            batch_size, data_format)
        model = resnet50.ResNet50(data_format)
        optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1)
        apply_grads = apply_gradients
        if defun:
          model.call = tf.function(model.call)
          apply_grads = tf.function(apply_gradients)

        num_burn = 3
        num_iters = 10
        with tf.device(device):
          iterator = make_iterator((images, labels))
          for _ in xrange(num_burn):
            (images, labels) = iterator.next()
            apply_grads(model, optimizer,
                        compute_gradients(model, images, labels))
          if execution_mode:
            context.async_wait()
          self._force_device_sync()
          gc.collect()

          start = time.time()
          for _ in xrange(num_iters):
            (images, labels) = iterator.next()
            apply_grads(model, optimizer,
                        compute_gradients(model, images, labels))
          if execution_mode:
            context.async_wait()
          self._force_device_sync()
          self._report(label, start, num_iters, device, batch_size, data_format)

  def benchmark_eager_train_sync(self):
    self._benchmark_eager_train(
        'eager_train', MockIterator,
        resnet50_test_util.device_and_data_format(), defun=False)

  def benchmark_eager_train_async(self):
    self._benchmark_eager_train(
        'eager_train_async',
        MockIterator,
        resnet50_test_util.device_and_data_format(),
        defun=False,
        execution_mode=context.ASYNC)

  def benchmark_eager_train_with_defun(self):
    self._benchmark_eager_train(
        'eager_train_with_defun', MockIterator,
        resnet50_test_util.device_and_data_format(), defun=True)

  def benchmark_eager_train_datasets(self):

    def make_iterator(tensors):
      with tf.device('/device:CPU:0'):
        ds = tf.data.Dataset.from_tensors(tensors).repeat()
      return iter(ds)

    self._benchmark_eager_train(
        'eager_train_dataset', make_iterator,
        resnet50_test_util.device_and_data_format(), defun=False)

  def benchmark_eager_train_datasets_with_defun(self):

    def make_iterator(tensors):
      with tf.device('/device:CPU:0'):
        ds = tf.data.Dataset.from_tensors(tensors).repeat()
      return iter(ds)

    self._benchmark_eager_train(
        'eager_train_dataset_with_defun', make_iterator,
        resnet50_test_util.device_and_data_format(), defun=True)

if __name__ == '__main__':
  tf.compat.v1.enable_eager_execution()
  tf.test.main()


text:
/*
 * PbAmzJson.cpp
 *
 *  Created on: Aug 29, 2015
 *      Author: jiabin
 */

#include <stdio.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include "../../util/base64.h"
#include "PbAmzJson.h"

using namespace std;
using namespace google::protobuf;
using namespace rapidjson;
using namespace gwc::util;

namespace gwc {
namespace wrapper {
namespace dynamo {

PbAmzJson::PbAmzJson() {
}

PbAmzJson::~PbAmzJson() {
}

int PbAmzJson::Json2str(const rapidjson::Value &json, std::string& str) {
    StringBuffer buffer;
    rapidjson::Writer<StringBuffer> writer(buffer);
    if (false == json.Accept(writer)) {
    	snprintf(lastErr, sizeof(lastErr), "Value::Accept failed");
    	return -1;
    }
    str.append(buffer.GetString(), buffer.GetSize());

    return 0;
}

int PbAmzJson::field2json(const Message &msg, const FieldDescriptor *field, Value &json) {

	if (field->is_repeated()) {
		return field2json_array(msg, field, json);
	} else {
		return field2json_single(msg, field, json);
	}

	return 0;
}

int PbAmzJson::field2json_single(const Message &msg, const FieldDescriptor *field, Value &json) {
	const Reflection *ref = msg.GetReflection();

	json.SetObject();

	char buf[100];

	switch (field->cpp_type()) {
	case FieldDescriptor::CPPTYPE_DOUBLE: {
		int n = snprintf(buf, sizeof(buf), "%.10f", ref->GetDouble(msg, field));
		json.AddMember("N", Value(buf, n, allocator).Move(), allocator);
		break;
	}
	case FieldDescriptor::CPPTYPE_FLOAT: {
		int n = snprintf(buf, sizeof(buf), "%.10f", ref->GetFloat(msg, field));
		json.AddMember("N", Value(buf, n, allocator).Move(), allocator);
		break;
	}
	case FieldDescriptor::CPPTYPE_INT64: {
		int n = snprintf(buf, sizeof(buf), "%ld", ref->GetInt64(msg, field));
		json.AddMember("N", Value(buf, n, allocator).Move(), allocator);
		break;
	}
	case FieldDescriptor::CPPTYPE_UINT64: {
		int n = snprintf(buf, sizeof(buf), "%lu", ref->GetUInt64(msg, field));
		json.AddMember("N", Value(buf, n, allocator).Move(), allocator);
		break;
	}
	case FieldDescriptor::CPPTYPE_INT32: {
		int n = snprintf(buf, sizeof(buf), "%d", ref->GetInt32(msg, field));
		json.AddMember("N", Value(buf, n, allocator).Move(), allocator);
		break;
	}
	case FieldDescriptor::CPPTYPE_UINT32: {
		int n = snprintf(buf, sizeof(buf), "%u", ref->GetUInt32(msg, field));
		json.AddMember("N", Value(buf, n, allocator).Move(), allocator);
		break;
	}
	case FieldDescriptor::CPPTYPE_BOOL: {
		json.AddMember("B", Value(ref->GetBool(msg, field)).Move(), allocator);
		break;
	}
	case FieldDescriptor::CPPTYPE_STRING: {
		string value = ref->GetString(msg, field);
		if (value.empty()) {
			break;
		}
		if (field->type() == FieldDescriptor::TYPE_BYTES) {
			value = bin2base64(value);
		}
		json.AddMember("S", Value(value.data(), value.size(), allocator).Move(), allocator);
		break;
	}
	case FieldDescriptor::CPPTYPE_MESSAGE: {
		Value jv;
		const Message &value = ref->GetMessage(msg, field);
		if (0 != Pb2amzJson(value, jv)) {
			return -1;
		}
		json.AddMember("M", jv, allocator);
		break;
	}
	case FieldDescriptor::CPPTYPE_ENUM: {
		int n = snprintf(buf, sizeof(buf), "%u", ref->GetEnum(msg, field)->number());
		json.AddMember("N", Value(buf, n, allocator).Move(), allocator);
		break;
	}
	default: {
		snprintf(lastErr, sizeof(lastErr), "unknown cpp type");
		return -1;
	}
	}

	return 0;
}

int PbAmzJson::field2json_array(const Message &msg, const FieldDescriptor *field, Value &json) {
	const Reflection *ref = msg.GetReflection();
	json.SetObject();
	size_t arraySize = ref->FieldSize(msg, field);
	if (0 == arraySize) {
		return 0;
	}

	char buf[100];
	Value v(rapidjson::kArrayType);
	switch (field->cpp_type()) {
	case FieldDescriptor::CPPTYPE_DOUBLE:
		for (size_t i = 0; i != arraySize; ++i) {
			int n = snprintf(buf, sizeof(buf), "%.10f", ref->GetRepeatedDouble(msg, field, i));
			v.PushBack(Value(buf, n, allocator).Move(), allocator);
		}
		json.AddMember("NS", v, allocator);
		break;
	case FieldDescriptor::CPPTYPE_FLOAT:
		for (size_t i = 0; i != arraySize; ++i) {
			int n = snprintf(buf, sizeof(buf), "%.10f", ref->GetRepeatedFloat(msg, field, i));
			v.PushBack(Value(buf, n, allocator).Move(), allocator);
		}
		json.AddMember("NS", v, allocator);
		break;
	case FieldDescriptor::CPPTYPE_INT64:
		for (size_t i = 0; i != arraySize; ++i) {
			int n = snprintf(buf, sizeof(buf), "%ld", ref->GetRepeatedInt64(msg, field, i));
			v.PushBack(Value(buf, n, allocator).Move(), allocator);
		}
		json.AddMember("NS", v, allocator);
		break;
	case FieldDescriptor::CPPTYPE_UINT64:
		for (size_t i = 0; i != arraySize; ++i) {
			int n = snprintf(buf, sizeof(buf), "%lu", ref->GetRepeatedUInt64(msg, field, i));
			v.PushBack(Value(buf, n, allocator).Move(), allocator);
		}
		json.AddMember("NS", v, allocator);
		break;
	case FieldDescriptor::CPPTYPE_INT32:
		for (size_t i = 0; i != arraySize; ++i) {
			int n  = snprintf(buf, sizeof(buf), "%d", ref->GetRepeatedInt32(msg, field, i));
			v.PushBack(Value(buf, n, allocator).Move(), allocator);
		}
		json.AddMember("NS", v, allocator);
		break;
	case FieldDescriptor::CPPTYPE_UINT32:
		for (size_t i = 0; i != arraySize; ++i) {
			int n = snprintf(buf, sizeof(buf), "%u", ref->GetRepeatedUInt32(msg, field, i));
			v.PushBack(Value(buf, n, allocator).Move(), allocator);
		}
		json.AddMember("NS", v, allocator);
		break;
	case FieldDescriptor::CPPTYPE_BOOL:
		for (size_t i = 0; i != arraySize; ++i) {
			v.PushBack(Value(ref->GetRepeatedBool(msg, field, i)).Move(), allocator);
		}
		json.AddMember("BS", v, allocator);
		break;
	case FieldDescriptor::CPPTYPE_STRING: {
		for (size_t i = 0; i != arraySize; ++i) {
			string value = ref->GetRepeatedString(msg, field, i);
			if (field->type() == FieldDescriptor::TYPE_BYTES) {
				value = bin2base64(value);
			}
			v.PushBack(Value(value.data(), value.size(), allocator).Move(), allocator);
		}
		json.AddMember("SS", v, allocator);
		break;
	}
	case FieldDescriptor::CPPTYPE_MESSAGE:
		for (size_t i = 0; i != arraySize; ++i) {
			const Message &value = ref->GetRepeatedMessage(msg, field, i);
			Value jv;
			if (0 != Pb2amzJson(value, jv)) {
				return -1;
			}
			v.PushBack(Value(rapidjson::kObjectType).AddMember("M", jv, allocator).Move(), allocator);
		}
		json.AddMember("L", v, allocator);
		break;
	case FieldDescriptor::CPPTYPE_ENUM:
		for (size_t i = 0; i != arraySize; ++i) {
			int n = snprintf(buf, sizeof(buf), "%d", ref->GetRepeatedEnum(msg, field, i)->number());
			v.PushBack(Value(buf, n, allocator).Move(), allocator);
		}
		json.AddMember("NS", v, allocator);
		break;
	default:
		snprintf(lastErr, sizeof(lastErr), "unknown cpp type");
		return -1;
	}

	return 0;
}

int PbAmzJson::Pb2amzJson(const Message& msg, Value& jobj) {
	jobj.SetObject();
	const Descriptor *d = msg.GetDescriptor();
	if (NULL == d) {
		return 0;
	}

	for (int i = 0; i < d->field_count(); i++) {
		const FieldDescriptor *field = d->field(i);
		const Reflection *ref = msg.GetReflection();
		if (field->is_optional() && !ref->HasField(msg, field)) {
			continue;
		} else if (field->is_repeated() && !ref->FieldSize(msg, field)) {
			continue;
		}

		Value name(field->name().c_str(), field->name().size());
		Value value;
		field2json(msg, field, value);

		if (kObjectType == value.GetType()) {
			if (0 == value.MemberCount()) {
				continue;
			}
		} else if (kArrayType == value.GetType()) {
			if (0 == value.Empty()) {
				continue;
			}
		}

		jobj.AddMember(name, value, allocator);
	}

	return 0;
}

int PbAmzJson::Pb2amzJson(const Message& msg, string& jstr) {
	Value json;
	if (0 != Pb2amzJson(msg, json)) {
		return -1;
	}

	return Json2str(json, jstr);
}
//
//int PbAmzJson::Pb2amzJson(const RepeatedField<Message>& repeatedMsg, Value& jobj) {
//	jobj.SetArray();
//
//
////    const Reflection *ref = repeatedMsg..GetReflection();
//
//	for (int i = 0; i < repeatedMsg.size(); ++i) {
//		Message &msg = repeatedMsg.Get(i);
//		Value obj;
//		if (0 != Pb2amzJson(msg, obj)) {
//			return -1;
//		}
//		jobj.PushBack(obj, allocator);
//	}
//
//	return 0;
//}

//int PbAmzJson::Pb2amzJson(const RepeatedField<Message>& repeatedMsg, string& jstr) {
//	Value json;
//	if (0 != Pb2amzJson(repeatedMsg, json)) {
//		return -1;
//	}
//
//	return json2str(json, jstr);
//}

int PbAmzJson::json2field(const Value &json, Message &msg, const FieldDescriptor *field) {
    if (field->is_repeated()) {
    	return json2field_array(json, msg, field);
    } else {
    	return json2field_single(json, msg, field);
    }
}

int PbAmzJson::json2field_single(const Value &json, Message &msg, const FieldDescriptor *field) {
    const Reflection *ref = msg.GetReflection();

    switch (field->cpp_type()) {
        case FieldDescriptor::CPPTYPE_INT32: {
        	int32_t v = 0;
        	if (0 != Amz2int32(json, v)) {
        		return -1;
        	}

            ref->SetInt32(&msg, field, v);

            break;
        }
        case FieldDescriptor::CPPTYPE_UINT32: {
        	uint32_t v = 0;
        	if (0 != Amz2uint32(json, v)) {
        		return -1;
        	}

            ref->SetUInt32(&msg, field, v);
            break;
        }
        case FieldDescriptor::CPPTYPE_INT64: {
        	int64_t v = 0;
        	if (0 != Amz2int64(json, v)) {
        		return -1;
        	}

            ref->SetInt64(&msg, field, v);

            break;
        }
        case FieldDescriptor::CPPTYPE_UINT64: {
        	uint64_t v = 0;
        	if (0 != Amz2uint64(json, v)) {
        		return -1;
        	}

            ref->SetUInt64(&msg, field, v);

            break;
        }
        case FieldDescriptor::CPPTYPE_DOUBLE: {
        	double v = 0;
        	if (0 != Amz2double(json, v)) {
        		return -1;
        	}

            ref->SetDouble(&msg, field, v);

            break;
        }
        case FieldDescriptor::CPPTYPE_FLOAT: {
        	float v = 0;
        	if (0 != Amz2float(json, v)) {
        		return -1;
        	}

            ref->SetFloat(&msg, field, v);

            break;
        }
        case FieldDescriptor::CPPTYPE_BOOL: {
        	bool v;
        	if (0 != Amz2bool(json, v)) {
        		return -1;
        	}

            ref->SetBool(&msg, field, v);
            break;
        }
        case FieldDescriptor::CPPTYPE_STRING: {
        	string v;
        	if (0 != Amz2str(json, v)) {
        		return -1;
        	}

    		if (field->type() == FieldDescriptor::TYPE_BYTES) {
    			v = base642bin(v);
    		}

            ref->SetString(&msg, field, v);

            break;
        }
        case FieldDescriptor::CPPTYPE_MESSAGE: {
        	Value::ConstMemberIterator it = json.FindMember("M");
        	if (json.MemberEnd() == it) {
            	snprintf(lastErr, sizeof(lastErr), "json is not a amz map");
            	return -1;
        	}

            if (it->value.GetType() != rapidjson::kObjectType) {
            	snprintf(lastErr, sizeof(lastErr), "json is not a object");
            	return -1;
            }

            Message &mf = *ref->MutableMessage(&msg, field);
            return AmzJson2pb(it->value, mf);
        }
        case FieldDescriptor::CPPTYPE_ENUM: {
            const EnumValueDescriptor *ev;
        	if (0 != Amz2enum(json, field->enum_type(), ev)) {
        		return -1;
        	}

            ref->SetEnum(&msg, field, ev);

            break;
        }
        default:
        	snprintf(lastErr, sizeof(lastErr), "unknown field type");
        	return -1;
            break;
    }

    return 0;
}

int PbAmzJson::json2field_array(const Value &json, Message &msg, const FieldDescriptor *field) {
	if (rapidjson::kObjectType != json.GetType()) {
		snprintf(lastErr, sizeof(lastErr), "json is not an amz value");
		return -1;
	}

	Value::ConstMemberIterator it = json.MemberBegin();
	for (Value::ConstValueIterator ait = it->value.Begin(); ait != it->value.End(); ++ait) {
		if (0 != json2field_array_elem(*ait, msg, field)) {
			return -1;
		}
	}

	return 0;
}

int PbAmzJson::Amz2int32(const Value &jv, int32_t &rv, bool isSetElem) {
	if (isSetElem) {
		rv = strtol(jv.GetString(), NULL, 0);
		return 0;
	}

	Value::ConstMemberIterator it = jv.FindMember("N");
	if (jv.MemberEnd() == it) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a amz number");
    	return -1;
	}

    if (it->value.GetType() != rapidjson::kStringType) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a number");
    	return -1;
    }

    rv = strtol(it->value.GetString(), NULL, 0);

    return 0;
}

int PbAmzJson::Amz2int64(const Value &jv, int64_t &rv, bool isSetElem) {
	if (isSetElem) {
		rv = strtoll(jv.GetString(), NULL, 0);
		return 0;
	}

	Value::ConstMemberIterator it = jv.FindMember("N");
	if (jv.MemberEnd() == it) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a amz number");
    	return -1;
	}

    if (it->value.GetType() != rapidjson::kStringType) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a number");
    	return -1;
    }

    rv = strtoll(it->value.GetString(), NULL, 0);

    return 0;
}

int PbAmzJson::Amz2uint32(const Value &jv, uint32_t &rv, bool isSetElem) {
	if (isSetElem) {
		rv = strtoul(jv.GetString(), NULL, 0);
		return 0;
	}

	Value::ConstMemberIterator it = jv.FindMember("N");
	if (jv.MemberEnd() == it) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a amz number");
    	return -1;
	}

    if (it->value.GetType() != rapidjson::kStringType) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a number");
    	return -1;
    }

    rv = strtoul(it->value.GetString(), NULL, 0);

    return 0;
}

int PbAmzJson::Amz2uint64(const Value &jv, uint64_t &rv, bool isSetElem) {
	if (isSetElem) {
		rv = strtoull(jv.GetString(), NULL, 0);
		return 0;
	}

	Value::ConstMemberIterator it = jv.FindMember("N");
	if (jv.MemberEnd() == it) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a amz number");
    	return -1;
	}

    if (it->value.GetType() != rapidjson::kStringType) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a number");
    	return -1;
    }

    rv = strtoull(it->value.GetString(), NULL, 0);

    return 0;
}

int PbAmzJson::Amz2float(const Value &jv, float &rv, bool isSetElem) {
	if (isSetElem) {
		rv = strtof(jv.GetString(), NULL);
		return 0;
	}

	Value::ConstMemberIterator it = jv.FindMember("N");
	if (jv.MemberEnd() == it) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a amz number");
    	return -1;
	}

    if (it->value.GetType() != rapidjson::kStringType) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a number");
    	return -1;
    }

    rv = strtof(it->value.GetString(), NULL);

    return 0;
}

int PbAmzJson::Amz2double(const Value &jv, double &rv, bool isSetElem) {
	if (isSetElem) {
		rv = strtod(jv.GetString(), NULL);
		return 0;
	}

	Value::ConstMemberIterator it = jv.FindMember("N");
	if (jv.MemberEnd() == it) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a amz number");
    	return -1;
	}

    if (it->value.GetType() != rapidjson::kStringType) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a number");
    	return -1;
    }

    rv = strtod(it->value.GetString(), NULL);

    return 0;
}

int PbAmzJson::Amz2str(const Value &jv, string &rv, bool isSetElem) {
	if (isSetElem) {
		rv = jv.GetString();
		return 0;
	}

	Value::ConstMemberIterator it = jv.FindMember("S");
	if (jv.MemberEnd() == it) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a amz string");
    	return -1;
	}

    if (it->value.GetType() != rapidjson::kStringType) {
    	snprintf(lastErr, sizeof(lastErr), "json is not a string");
    	return -1;
    }

    rv = it->value.GetString();

    return 0;
}

int PbAmzJson::Amz2bool(const Value &jv, bool &rv, bool isSetElem) {
	if (isSetElem) {
		rv = jv.GetBool();
		return 0;
	}

	Value::ConstMemberIterator it = jv.FindMember("B");
	if (jv.MemberEnd() == it) {
		snprintf(lastErr, sizeof(lastErr), "json is not a amz bool");
		return -1;
	}

	if (it->value.GetType() != rapidjson::kTrueType && it->value.GetType() != rapidjson::kFalseType) {
		snprintf(lastErr, sizeof(lastErr), "json is not a bool");
		return -1;
	}

	rv = it->value.GetBool();

	return 0;
}

int PbAmzJson::Amz2enum(const Value &jv, const EnumDescriptor *ed, const EnumValueDescriptor *&ev, bool isSetElem) {
	if (isSetElem) {

	    if (jv.GetType() != rapidjson::kNumberType && jv.GetType() != rapidjson::kStringType) {
	    	snprintf(lastErr, sizeof(lastErr), "json is neither a number, nor a string");
	    	return -1;
	    }

	    if (jv.GetType() == rapidjson::kNumberType) {
	        ev = ed->FindValueByNumber(strtol(jv.GetString(), NULL, 0));
	    } else if (jv.GetType() == rapidjson::kStringType) {
	        ev = ed->FindValueByName(jv.GetString());
	    } else {
	    	snprintf(lastErr, sizeof(lastErr), "json is not an integer or string");
	    	return -1;
	    }

	    if (!ev) {
	    	snprintf(lastErr, sizeof(lastErr), "eunm value ont found");
	    	return -1;
	    }

		return 0;
	}

	Value::ConstMemberIterator it = jv.FindMember("N");
	if (jv.MemberEnd() == it) {
		it = jv.FindMember("S");
		if (jv.MemberEnd() == it) {
			snprintf(lastErr, sizeof(lastErr), "json is neither a amz number, nor a string");
        	return -1;
		}
	}

    if (it->value.GetType() != rapidjson::kNumberType && it->value.GetType() != rapidjson::kStringType) {
    	snprintf(lastErr, sizeof(lastErr), "json is neither a number, nor a string");
    	return -1;
    }

    if (it->value.GetType() == rapidjson::kNumberType) {
        ev = ed->FindValueByNumber(strtol(it->value.GetString(), NULL, 0));
    } else if (it->value.GetType() == rapidjson::kStringType) {
        ev = ed->FindValueByName(it->value.GetString());
    } else {
    	snprintf(lastErr, sizeof(lastErr), "json is not an integer or string");
    	return -1;
    }

    if (!ev) {
    	snprintf(lastErr, sizeof(lastErr), "eunm value ont found");
    	return -1;
    }

    return 0;
}

int PbAmzJson::json2field_array_elem(const Value &json, Message &msg, const FieldDescriptor *field) {

    const Reflection *ref = msg.GetReflection();

    switch (field->cpp_type()) {
        case FieldDescriptor::CPPTYPE_INT32: {
        	int32_t v = 0;
        	if (0 != Amz2int32(json, v, true)) {
        		return -1;
        	}

            ref->AddInt32(&msg, field, v);

            break;
        }
        case FieldDescriptor::CPPTYPE_UINT32: {
        	uint32_t v = 0;
        	if (0 != Amz2uint32(json, v, true)) {
        		return -1;
        	}

            ref->AddUInt32(&msg, field, v);
            break;
        }
        case FieldDescriptor::CPPTYPE_INT64: {
        	int64_t v = 0;
        	if (0 != Amz2int64(json, v, true)) {
        		return -1;
        	}

            ref->AddInt64(&msg, field, v);

            break;
        }
        case FieldDescriptor::CPPTYPE_UINT64: {
        	uint64_t v = 0;
        	if (0 != Amz2uint64(json, v, true)) {
        		return -1;
        	}

            ref->AddUInt64(&msg, field, v);

            break;
        }
        case FieldDescriptor::CPPTYPE_DOUBLE: {
        	double v = 0;
        	if (0 != Amz2double(json, v, true)) {
        		return -1;
        	}

            ref->AddDouble(&msg, field, v);

            break;
        }
        case FieldDescriptor::CPPTYPE_FLOAT: {
        	float v = 0;
        	if (0 != Amz2float(json, v, true)) {
        		return -1;
        	}

            ref->AddFloat(&msg, field, v);

            break;
        }
        case FieldDescriptor::CPPTYPE_BOOL: {
        	bool v;
        	if (0 != Amz2bool(json, v, true)) {
        		return -1;
        	}

            ref->AddBool(&msg, field, v);
            break;
        }
        case FieldDescriptor::CPPTYPE_STRING: {
        	string v;
        	if (0 != Amz2str(json, v, true)) {
        		return -1;
        	}

    		if (field->type() == FieldDescriptor::TYPE_BYTES) {
    			v = base642bin(v);
    		}

            ref->AddString(&msg, field, v);

            break;
        }
        case FieldDescriptor::CPPTYPE_MESSAGE: {
        	Value::ConstMemberIterator it = json.FindMember("M");
        	if (json.MemberEnd() == it) {
            	snprintf(lastErr, sizeof(lastErr), "json is not a amz map");
            	return -1;
        	}

            if (it->value.GetType() != rapidjson::kObjectType) {
            	snprintf(lastErr, sizeof(lastErr), "json is not a object");
            	return -1;
            }

            Message &mf = *ref->AddMessage(&msg, field);
            return AmzJson2pb(it->value, mf);
        }
        case FieldDescriptor::CPPTYPE_ENUM: {
            const EnumValueDescriptor *ev = 0;
        	if (0 != Amz2enum(json, field->enum_type(), ev, true)) {
        		return -1;
        	}

            ref->AddEnum(&msg, field, ev);

            break;
        }
        default:
        	snprintf(lastErr, sizeof(lastErr), "unknown field type");
        	return -1;
            break;
    }

    return 0;
}

int PbAmzJson::AmzJson2pb(const Value& jobj, Message& msg) {
	msg.Clear();

    if (rapidjson::kObjectType != jobj.GetType()) {
    	snprintf(lastErr, sizeof(lastErr), "Value is not an object, type=%d", jobj.GetType());
        return -1;
    }

    const Descriptor *d = msg.GetDescriptor();
//    const Reflection *ref = msg.GetReflection();

    for (Value::ConstMemberIterator itr = jobj.MemberBegin(); itr != jobj.MemberEnd(); ++itr) {
        const char* name = itr->name.GetString();
        const FieldDescriptor *field = d->FindFieldByName(name);
        if (!field) {
        	continue;
        }

        if (itr->value.GetType() == rapidjson::kNullType) {
            continue;
        }

        if (0 != json2field(itr->value, msg, field)) {
        	return -1;
        }
    }

	return 0;
}

int PbAmzJson::AmzJson2pb(const string& jstr, Message& msg) {
    Document d;
    d.Parse<0>(jstr.c_str());
    if (d.HasParseError()) {
    	snprintf(lastErr, sizeof(lastErr), "json invalid");
    	return -1;
    }

    return AmzJson2pb(d, msg);
}

//int PbAmzJson::AmzJson2pb(const Value& jobj, RepeatedField<Message>& repeatedMsg) {
//	repeatedMsg.Clear();
//
//	if (rapidjson::kArrayType != jobj.GetType()) {
//    	snprintf(lastErr, sizeof(lastErr), "Value is not an array");
//        return -1;
//	}
//
//	for (Value::ConstValueIterator itr = jobj.Begin(); itr != jobj.End(); ++itr) {
//		Message &msg = *(repeatedMsg.Add());
//		if (0 != AmzJson2pb(*itr, msg)) {
//			return -1;
//		}
//	}
//
//	return 0;
//}

//int PbAmzJson::AmzJson2pb(const string& jstr, RepeatedField<Message>& repeatedMsg) {
//    Document d;
//    d.Parse<0>(jstr.c_str());
//    if (d.HasParseError()) {
//    	snprintf(lastErr, sizeof(lastErr), "json invalid");
//    	return -1;
//    }
//
//	return AmzJson2pb(d, repeatedMsg);
//}

}}}


text:
import React from 'react';

const ApplicationContext = React.createContext({
  fetch: () => {
    throw new Error('Fetch method not initialized.');
  },
});

export default ApplicationContext;


text:
layout: project
class: "projectpage template-two"
---

{% include project_description.html %}

{% include project_image_one.html %}

{% include project_image_two.html %}


text:
from concurrence import unittest, Tasklet

class TestTest(unittest.TestCase):
    def testTimeout(self):
        try:
            Tasklet.sleep(4)
            self.fail('expected timeout')
        except TaskletExit:
            pass #caused by timeout

if __name__ == '__main__':
    unittest.main(timeout = 2)


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

using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using static Google.Cloud.Datastore.V1.QueryResultBatch.Types;

namespace Google.Cloud.Datastore.V1
{
    /// <summary>
    /// Creates a stream of responses (synchronous and asynchronous) from a query.
    /// </summary>
    internal class QueryStreamer
    {
        private readonly RunQueryRequest _initialRequest;
        private readonly ApiCall<RunQueryRequest, RunQueryResponse> _apiCall;
        private readonly CallSettings _callSettings;

        internal QueryStreamer(RunQueryRequest initialRequest, ApiCall<RunQueryRequest, RunQueryResponse> apiCall, CallSettings callSettings)
        {
            _initialRequest = GaxPreconditions.CheckNotNull(initialRequest, nameof(initialRequest)).Clone();
            _apiCall = GaxPreconditions.CheckNotNull(apiCall, nameof(apiCall));
            _callSettings = callSettings;
        }

        // The real business logic of this class is all in the following two methods. The rest is pretty much boilerplate.

        private static void ModifyRequest(RunQueryRequest request, RunQueryResponse response)
        {
            // Transition from GQL to structured queries.
            if (response.Query != null)
            {
                request.Query = response.Query;
            }
            // Offset/limit/cursor handling.
            var query = request.Query;
            var batch = response.Batch;
            query.Offset -= batch.SkippedResults;
            if (query.Limit > 0)
            {
                query.Limit -= batch.EntityResults.Count;
            }
            query.StartCursor = batch.EndCursor;
        }

        private static bool MoreResultsAvailable(RunQueryResponse response) =>
            response.Batch.MoreResults == MoreResultsType.NotFinished;

        internal IAsyncEnumerable<RunQueryResponse> Async() => new AsyncQueryEnumerable(this);

        internal IEnumerable<RunQueryResponse> Sync()
        {
            var request = _initialRequest.Clone();
            RunQueryResponse response;
            do
            {
                response = _apiCall.Sync(request, _callSettings);
                yield return response;
                ModifyRequest(request, response);
            } while (MoreResultsAvailable(response));
        }

        private class AsyncQueryEnumerable : IAsyncEnumerable<RunQueryResponse>
        {
            private readonly QueryStreamer _parent;

            internal AsyncQueryEnumerable(QueryStreamer parent)
            {
                _parent = parent;
            }

            public IAsyncEnumerator<RunQueryResponse> GetEnumerator()
                => new AsyncQueryEnumerator(_parent);

            private class AsyncQueryEnumerator : IAsyncEnumerator<RunQueryResponse>
            {
                private readonly QueryStreamer _parent;
                private RunQueryRequest _request;
                private bool _finished;

                public AsyncQueryEnumerator(QueryStreamer _parent)
                {
                    this._parent = _parent;
                    _request = _parent._initialRequest.Clone();
                }

                public RunQueryResponse Current { get; private set; }

                public async Task<bool> MoveNext(CancellationToken cancellationToken)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    if (_finished)
                    {
                        return false;
                    }
                    CallSettings effectiveCallSettings = _parent._callSettings;
                    if (cancellationToken != default(CancellationToken))
                    {
                        effectiveCallSettings = effectiveCallSettings.WithCancellationToken(cancellationToken);
                    }
                    var response = await _parent._apiCall.Async(_request, effectiveCallSettings);
                    _finished = !MoreResultsAvailable(response);
                    ModifyRequest(_request, response);
                    Current = response;
                    return true;
                }

                public void Dispose() { }
            }
        }
    }
}


text:
'use strict';

angular.module('core').controller('ContactController', ['$scope', 'Authentication',
	function($scope, Authentication) {
		// This provides Authentication context.
		$scope.authentication = Authentication;
	}
]);